@midscene/web 0.7.2 → 0.7.3-beta-20241104100519.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,1697 +1,1895 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
- var __spreadValues = (a, b) => {
14
- for (var prop in b || (b = {}))
15
- if (__hasOwnProp.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- if (__getOwnPropSymbols)
18
- for (var prop of __getOwnPropSymbols(b)) {
19
- if (__propIsEnum.call(b, prop))
20
- __defNormalProp(a, prop, b[prop]);
21
- }
22
- return a;
23
- };
24
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
- var __commonJS = (cb, mod) => function __require() {
26
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
27
- };
28
- var __copyProps = (to, from, except, desc) => {
29
- if (from && typeof from === "object" || typeof from === "function") {
30
- for (let key of __getOwnPropNames(from))
31
- if (!__hasOwnProp.call(to, key) && key !== except)
32
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
- }
34
- return to;
35
- };
36
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
37
- // If the importer is in node compatibility mode or this is not an ESM
38
- // file that has been converted to a CommonJS file using a Babel-
39
- // compatible transform (i.e. "__esModule" has not been set), then set
40
- // "default" to the CommonJS "module.exports" for node compatibility.
41
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
42
- mod
43
- ));
44
-
45
- // ../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js
46
- var require_dayjs_min = __commonJS({
47
- "../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js"(exports, module2) {
1
+ (function(global, factory) {
2
+ if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("assert"), require("crypto"), require("fs"), require("path"), require("@midscene/shared/constants"), require("@midscene/shared/fs"), require("@midscene/shared/img"), require("@midscene/shared/utils"), require("@midscene/core/utils"), require("cors"), require("express"), require("@midscene/core"));
3
+ else if (typeof define === "function" && define.amd) define([
4
+ "exports",
5
+ "assert",
6
+ "crypto",
7
+ "fs",
8
+ "path",
9
+ "@midscene/shared/constants",
10
+ "@midscene/shared/fs",
11
+ "@midscene/shared/img",
12
+ "@midscene/shared/utils",
13
+ "@midscene/core/utils",
14
+ "cors",
15
+ "express",
16
+ "@midscene/core"
17
+ ], factory);
18
+ else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.midscenePlayground = {}, global.assert, global.crypto, global.fs, global.path, global.constants, global.fs, global.img, global.utils, global.utils, global.cors, global.express, global.core);
19
+ })(this, function(exports, _assert, _crypto, _fs, _path, _constants, _fs1, _img, _utils, _utils1, _cors, _express, _core) {
48
20
  "use strict";
49
- !function(t, e) {
50
- "object" == typeof exports && "undefined" != typeof module2 ? module2.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
51
- }(exports, function() {
52
- "use strict";
53
- var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t2) {
54
- var e2 = ["th", "st", "nd", "rd"], n2 = t2 % 100;
55
- return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
56
- } }, m = function(t2, e2, n2) {
57
- var r2 = String(t2);
58
- return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
59
- }, v = { s: m, z: function(t2) {
60
- var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
61
- return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
62
- }, m: function t2(e2, n2) {
63
- if (e2.date() < n2.date())
64
- return -t2(n2, e2);
65
- var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i2 = e2.clone().add(r2, c), s2 = n2 - i2 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c);
66
- return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
67
- }, a: function(t2) {
68
- return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
69
- }, p: function(t2) {
70
- return { M: c, y: h, w: o, d: a, D: d, h: u, m: s, s: i, ms: r, Q: f }[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
71
- }, u: function(t2) {
72
- return void 0 === t2;
73
- } }, g = "en", D = {};
74
- D[g] = M;
75
- var p = "$isDayjsObject", S = function(t2) {
76
- return t2 instanceof _ || !(!t2 || !t2[p]);
77
- }, w = function t2(e2, n2, r2) {
78
- var i2;
79
- if (!e2)
80
- return g;
81
- if ("string" == typeof e2) {
82
- var s2 = e2.toLowerCase();
83
- D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
84
- var u2 = e2.split("-");
85
- if (!i2 && u2.length > 1)
86
- return t2(u2[0]);
87
- } else {
88
- var a2 = e2.name;
89
- D[a2] = e2, i2 = a2;
21
+ Object.defineProperty(exports, "__esModule", {
22
+ value: true
23
+ });
24
+ _assert = /*#__PURE__*/ _interop_require_default(_assert);
25
+ _path = /*#__PURE__*/ _interop_require_wildcard(_path);
26
+ _cors = /*#__PURE__*/ _interop_require_default(_cors);
27
+ _express = /*#__PURE__*/ _interop_require_default(_express);
28
+ function _interop_require_default(obj) {
29
+ return obj && obj.__esModule ? obj : {
30
+ default: obj
31
+ };
32
+ }
33
+ function _getRequireWildcardCache(nodeInterop) {
34
+ if (typeof WeakMap !== "function") return null;
35
+ var cacheBabelInterop = new WeakMap();
36
+ var cacheNodeInterop = new WeakMap();
37
+ return (_getRequireWildcardCache = function(nodeInterop) {
38
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
39
+ })(nodeInterop);
40
+ }
41
+ function _interop_require_wildcard(obj, nodeInterop) {
42
+ if (!nodeInterop && obj && obj.__esModule) {
43
+ return obj;
90
44
  }
91
- return !r2 && i2 && (g = i2), i2 || !r2 && g;
92
- }, O = function(t2, e2) {
93
- if (S(t2))
94
- return t2.clone();
95
- var n2 = "object" == typeof e2 ? e2 : {};
96
- return n2.date = t2, n2.args = arguments, new _(n2);
97
- }, b = v;
98
- b.l = w, b.i = S, b.w = function(t2, e2) {
99
- return O(t2, { locale: e2.$L, utc: e2.$u, x: e2.$x, $offset: e2.$offset });
100
- };
101
- var _ = function() {
102
- function M2(t2) {
103
- this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
45
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
46
+ return {
47
+ default: obj
48
+ };
104
49
  }
105
- var m2 = M2.prototype;
106
- return m2.parse = function(t2) {
107
- this.$d = function(t3) {
108
- var e2 = t3.date, n2 = t3.utc;
109
- if (null === e2)
110
- return /* @__PURE__ */ new Date(NaN);
111
- if (b.u(e2))
112
- return /* @__PURE__ */ new Date();
113
- if (e2 instanceof Date)
114
- return new Date(e2);
115
- if ("string" == typeof e2 && !/Z$/i.test(e2)) {
116
- var r2 = e2.match($);
117
- if (r2) {
118
- var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
119
- return n2 ? new Date(Date.UTC(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2);
120
- }
121
- }
122
- return new Date(e2);
123
- }(t2), this.init();
124
- }, m2.init = function() {
125
- var t2 = this.$d;
126
- this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
127
- }, m2.$utils = function() {
128
- return b;
129
- }, m2.isValid = function() {
130
- return !(this.$d.toString() === l);
131
- }, m2.isSame = function(t2, e2) {
132
- var n2 = O(t2);
133
- return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
134
- }, m2.isAfter = function(t2, e2) {
135
- return O(t2) < this.startOf(e2);
136
- }, m2.isBefore = function(t2, e2) {
137
- return this.endOf(e2) < O(t2);
138
- }, m2.$g = function(t2, e2, n2) {
139
- return b.u(t2) ? this[e2] : this.set(n2, t2);
140
- }, m2.unix = function() {
141
- return Math.floor(this.valueOf() / 1e3);
142
- }, m2.valueOf = function() {
143
- return this.$d.getTime();
144
- }, m2.startOf = function(t2, e2) {
145
- var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
146
- var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
147
- return r2 ? i2 : i2.endOf(a);
148
- }, $2 = function(t3, e3) {
149
- return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e3)), n2);
150
- }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
151
- switch (f2) {
152
- case h:
153
- return r2 ? l2(1, 0) : l2(31, 11);
154
- case c:
155
- return r2 ? l2(1, M3) : l2(0, M3 + 1);
156
- case o:
157
- var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
158
- return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
159
- case a:
160
- case d:
161
- return $2(v2 + "Hours", 0);
162
- case u:
163
- return $2(v2 + "Minutes", 1);
164
- case s:
165
- return $2(v2 + "Seconds", 2);
166
- case i:
167
- return $2(v2 + "Milliseconds", 3);
168
- default:
169
- return this.clone();
170
- }
171
- }, m2.endOf = function(t2) {
172
- return this.startOf(t2, false);
173
- }, m2.$set = function(t2, e2) {
174
- var n2, o2 = b.p(t2), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2;
175
- if (o2 === c || o2 === h) {
176
- var y2 = this.clone().set(d, 1);
177
- y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
178
- } else
179
- l2 && this.$d[l2]($2);
180
- return this.init(), this;
181
- }, m2.set = function(t2, e2) {
182
- return this.clone().$set(t2, e2);
183
- }, m2.get = function(t2) {
184
- return this[b.p(t2)]();
185
- }, m2.add = function(r2, f2) {
186
- var d2, l2 = this;
187
- r2 = Number(r2);
188
- var $2 = b.p(f2), y2 = function(t2) {
189
- var e2 = O(l2);
190
- return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
191
- };
192
- if ($2 === c)
193
- return this.set(c, this.$M + r2);
194
- if ($2 === h)
195
- return this.set(h, this.$y + r2);
196
- if ($2 === a)
197
- return y2(1);
198
- if ($2 === o)
199
- return y2(7);
200
- var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
201
- return b.w(m3, this);
202
- }, m2.subtract = function(t2, e2) {
203
- return this.add(-1 * t2, e2);
204
- }, m2.format = function(t2) {
205
- var e2 = this, n2 = this.$locale();
206
- if (!this.isValid())
207
- return n2.invalidDate || l;
208
- var r2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", i2 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t3, n3, i3, s3) {
209
- return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
210
- }, d2 = function(t3) {
211
- return b.s(s2 % 12 || 12, t3, "0");
212
- }, $2 = f2 || function(t3, e3, n3) {
213
- var r3 = t3 < 12 ? "AM" : "PM";
214
- return n3 ? r3.toLowerCase() : r3;
215
- };
216
- return r2.replace(y, function(t3, r3) {
217
- return r3 || function(t4) {
218
- switch (t4) {
219
- case "YY":
220
- return String(e2.$y).slice(-2);
221
- case "YYYY":
222
- return b.s(e2.$y, 4, "0");
223
- case "M":
224
- return a2 + 1;
225
- case "MM":
226
- return b.s(a2 + 1, 2, "0");
227
- case "MMM":
228
- return h2(n2.monthsShort, a2, c2, 3);
229
- case "MMMM":
230
- return h2(c2, a2);
231
- case "D":
232
- return e2.$D;
233
- case "DD":
234
- return b.s(e2.$D, 2, "0");
235
- case "d":
236
- return String(e2.$W);
237
- case "dd":
238
- return h2(n2.weekdaysMin, e2.$W, o2, 2);
239
- case "ddd":
240
- return h2(n2.weekdaysShort, e2.$W, o2, 3);
241
- case "dddd":
242
- return o2[e2.$W];
243
- case "H":
244
- return String(s2);
245
- case "HH":
246
- return b.s(s2, 2, "0");
247
- case "h":
248
- return d2(1);
249
- case "hh":
250
- return d2(2);
251
- case "a":
252
- return $2(s2, u2, true);
253
- case "A":
254
- return $2(s2, u2, false);
255
- case "m":
256
- return String(u2);
257
- case "mm":
258
- return b.s(u2, 2, "0");
259
- case "s":
260
- return String(e2.$s);
261
- case "ss":
262
- return b.s(e2.$s, 2, "0");
263
- case "SSS":
264
- return b.s(e2.$ms, 3, "0");
265
- case "Z":
266
- return i2;
267
- }
268
- return null;
269
- }(t3) || i2.replace(":", "");
270
- });
271
- }, m2.utcOffset = function() {
272
- return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
273
- }, m2.diff = function(r2, d2, l2) {
274
- var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
275
- return b.m(y2, m3);
276
- };
277
- switch (M3) {
278
- case h:
279
- $2 = D2() / 12;
280
- break;
281
- case c:
282
- $2 = D2();
283
- break;
284
- case f:
285
- $2 = D2() / 3;
286
- break;
287
- case o:
288
- $2 = (g2 - v2) / 6048e5;
289
- break;
290
- case a:
291
- $2 = (g2 - v2) / 864e5;
292
- break;
293
- case u:
294
- $2 = g2 / n;
295
- break;
296
- case s:
297
- $2 = g2 / e;
298
- break;
299
- case i:
300
- $2 = g2 / t;
301
- break;
302
- default:
303
- $2 = g2;
304
- }
305
- return l2 ? $2 : b.a($2);
306
- }, m2.daysInMonth = function() {
307
- return this.endOf(c).$D;
308
- }, m2.$locale = function() {
309
- return D[this.$L];
310
- }, m2.locale = function(t2, e2) {
311
- if (!t2)
312
- return this.$L;
313
- var n2 = this.clone(), r2 = w(t2, e2, true);
314
- return r2 && (n2.$L = r2), n2;
315
- }, m2.clone = function() {
316
- return b.w(this.$d, this);
317
- }, m2.toDate = function() {
318
- return new Date(this.valueOf());
319
- }, m2.toJSON = function() {
320
- return this.isValid() ? this.toISOString() : null;
321
- }, m2.toISOString = function() {
322
- return this.$d.toISOString();
323
- }, m2.toString = function() {
324
- return this.$d.toUTCString();
325
- }, M2;
326
- }(), k = _.prototype;
327
- return O.prototype = k, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach(function(t2) {
328
- k[t2[1]] = function(e2) {
329
- return this.$g(e2, t2[0], t2[1]);
50
+ var cache = _getRequireWildcardCache(nodeInterop);
51
+ if (cache && cache.has(obj)) {
52
+ return cache.get(obj);
53
+ }
54
+ var newObj = {
55
+ __proto__: null
330
56
  };
331
- }), O.extend = function(t2, e2) {
332
- return t2.$i || (t2(e2, _, O), t2.$i = true), O;
333
- }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
334
- return O(1e3 * t2);
335
- }, O.en = D[g], O.Ls = D, O.p = {}, O;
57
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
58
+ for(var key in obj){
59
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
60
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
61
+ if (desc && (desc.get || desc.set)) {
62
+ Object.defineProperty(newObj, key, desc);
63
+ } else {
64
+ newObj[key] = obj[key];
65
+ }
66
+ }
67
+ }
68
+ newObj.default = obj;
69
+ if (cache) {
70
+ cache.set(obj, newObj);
71
+ }
72
+ return newObj;
73
+ }
74
+ var __create = Object.create;
75
+ var __defProp = Object.defineProperty;
76
+ var __defProps = Object.defineProperties;
77
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
78
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
79
+ var __getOwnPropNames = Object.getOwnPropertyNames;
80
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
81
+ var __getProtoOf = Object.getPrototypeOf;
82
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
83
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
84
+ var __defNormalProp = (obj, key, value)=>key in obj ? __defProp(obj, key, {
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true,
88
+ value
89
+ }) : obj[key] = value;
90
+ var __spreadValues = (a, b)=>{
91
+ for(var prop in b || (b = {}))if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]);
92
+ if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)){
93
+ if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]);
94
+ }
95
+ return a;
96
+ };
97
+ var __spreadProps = (a, b)=>__defProps(a, __getOwnPropDescs(b));
98
+ var __require = /* @__PURE__ */ ((x)=>typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
99
+ get: (a, b)=>(typeof require !== "undefined" ? require : a)[b]
100
+ }) : x)(function(x) {
101
+ if (typeof require !== "undefined") return require.apply(this, arguments);
102
+ throw Error('Dynamic require of "' + x + '" is not supported');
336
103
  });
337
- }
338
- });
339
-
340
- // ../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json
341
- var require_package = __commonJS({
342
- "../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json"(exports, module2) {
343
- module2.exports = {
344
- name: "dotenv",
345
- version: "16.4.5",
346
- description: "Loads environment variables from .env file",
347
- main: "lib/main.js",
348
- types: "lib/main.d.ts",
349
- exports: {
350
- ".": {
351
- types: "./lib/main.d.ts",
352
- require: "./lib/main.js",
353
- default: "./lib/main.js"
354
- },
355
- "./config": "./config.js",
356
- "./config.js": "./config.js",
357
- "./lib/env-options": "./lib/env-options.js",
358
- "./lib/env-options.js": "./lib/env-options.js",
359
- "./lib/cli-options": "./lib/cli-options.js",
360
- "./lib/cli-options.js": "./lib/cli-options.js",
361
- "./package.json": "./package.json"
362
- },
363
- scripts: {
364
- "dts-check": "tsc --project tests/types/tsconfig.json",
365
- lint: "standard",
366
- "lint-readme": "standard-markdown",
367
- pretest: "npm run lint && npm run dts-check",
368
- test: "tap tests/*.js --100 -Rspec",
369
- "test:coverage": "tap --coverage-report=lcov",
370
- prerelease: "npm test",
371
- release: "standard-version"
372
- },
373
- repository: {
374
- type: "git",
375
- url: "git://github.com/motdotla/dotenv.git"
376
- },
377
- funding: "https://dotenvx.com",
378
- keywords: [
379
- "dotenv",
380
- "env",
381
- ".env",
382
- "environment",
383
- "variables",
384
- "config",
385
- "settings"
386
- ],
387
- readmeFilename: "README.md",
388
- license: "BSD-2-Clause",
389
- devDependencies: {
390
- "@definitelytyped/dtslint": "^0.0.133",
391
- "@types/node": "^18.11.3",
392
- decache: "^4.6.1",
393
- sinon: "^14.0.1",
394
- standard: "^17.0.0",
395
- "standard-markdown": "^7.1.0",
396
- "standard-version": "^9.5.0",
397
- tap: "^16.3.0",
398
- tar: "^6.1.11",
399
- typescript: "^4.8.4"
400
- },
401
- engines: {
402
- node: ">=12"
403
- },
404
- browser: {
405
- fs: false
406
- }
104
+ var __commonJS = (cb, mod)=>function __require2() {
105
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = {
106
+ exports: {}
107
+ }).exports, mod), mod.exports;
108
+ };
109
+ var __copyProps = (to, from, except, desc)=>{
110
+ if (from && typeof from === "object" || typeof from === "function") {
111
+ for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
112
+ get: ()=>from[key],
113
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
114
+ });
115
+ }
116
+ return to;
407
117
  };
408
- }
409
- });
410
-
411
- // ../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js
412
- var require_main = __commonJS({
413
- "../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js"(exports, module2) {
414
- "use strict";
415
- var fs = require("fs");
416
- var path2 = require("path");
417
- var os = require("os");
418
- var crypto = require("crypto");
419
- var packageJson = require_package();
420
- var version = packageJson.version;
421
- var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
422
- function parse(src) {
423
- const obj = {};
424
- let lines = src.toString();
425
- lines = lines.replace(/\r\n?/mg, "\n");
426
- let match;
427
- while ((match = LINE.exec(lines)) != null) {
428
- const key = match[1];
429
- let value = match[2] || "";
430
- value = value.trim();
431
- const maybeQuote = value[0];
432
- value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
433
- if (maybeQuote === '"') {
434
- value = value.replace(/\\n/g, "\n");
435
- value = value.replace(/\\r/g, "\r");
118
+ var __toESM = (mod, isNodeMode, target)=>(target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
119
+ // file that has been converted to a CommonJS file using a Babel-
120
+ // compatible transform (i.e. "__esModule" has not been set), then set
121
+ // "default" to the CommonJS "module.exports" for node compatibility.
122
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
123
+ value: mod,
124
+ enumerable: true
125
+ }) : target, mod));
126
+ var __async = (__this, __arguments, generator)=>{
127
+ return new Promise((resolve, reject)=>{
128
+ var fulfilled = (value)=>{
129
+ try {
130
+ step(generator.next(value));
131
+ } catch (e) {
132
+ reject(e);
133
+ }
134
+ };
135
+ var rejected = (value)=>{
136
+ try {
137
+ step(generator.throw(value));
138
+ } catch (e) {
139
+ reject(e);
140
+ }
141
+ };
142
+ var step = (x)=>x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
143
+ step((generator = generator.apply(__this, __arguments)).next());
144
+ });
145
+ };
146
+ // ../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js
147
+ var require_dayjs_min = __commonJS({
148
+ "../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js" (exports, module1) {
149
+ "use strict";
150
+ !function(t, e) {
151
+ "object" == typeof exports && "undefined" != typeof module1 ? module1.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
152
+ }(exports, function() {
153
+ "use strict";
154
+ var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = {
155
+ name: "en",
156
+ weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
157
+ months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
158
+ ordinal: function(t2) {
159
+ var e2 = [
160
+ "th",
161
+ "st",
162
+ "nd",
163
+ "rd"
164
+ ], n2 = t2 % 100;
165
+ return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
166
+ }
167
+ }, m = function(t2, e2, n2) {
168
+ var r2 = String(t2);
169
+ return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
170
+ }, v = {
171
+ s: m,
172
+ z: function(t2) {
173
+ var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
174
+ return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
175
+ },
176
+ m: function t2(e2, n2) {
177
+ if (e2.date() < n2.date()) return -t2(n2, e2);
178
+ var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i2 = e2.clone().add(r2, c), s2 = n2 - i2 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c);
179
+ return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
180
+ },
181
+ a: function(t2) {
182
+ return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
183
+ },
184
+ p: function(t2) {
185
+ return ({
186
+ M: c,
187
+ y: h,
188
+ w: o,
189
+ d: a,
190
+ D: d,
191
+ h: u,
192
+ m: s,
193
+ s: i,
194
+ ms: r,
195
+ Q: f
196
+ })[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
197
+ },
198
+ u: function(t2) {
199
+ return void 0 === t2;
200
+ }
201
+ }, g = "en", D = {};
202
+ D[g] = M;
203
+ var p = "$isDayjsObject", S = function(t2) {
204
+ return t2 instanceof _ || !(!t2 || !t2[p]);
205
+ }, w = function t2(e2, n2, r2) {
206
+ var i2;
207
+ if (!e2) return g;
208
+ if ("string" == typeof e2) {
209
+ var s2 = e2.toLowerCase();
210
+ D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
211
+ var u2 = e2.split("-");
212
+ if (!i2 && u2.length > 1) return t2(u2[0]);
213
+ } else {
214
+ var a2 = e2.name;
215
+ D[a2] = e2, i2 = a2;
216
+ }
217
+ return !r2 && i2 && (g = i2), i2 || !r2 && g;
218
+ }, O = function(t2, e2) {
219
+ if (S(t2)) return t2.clone();
220
+ var n2 = "object" == typeof e2 ? e2 : {};
221
+ return n2.date = t2, n2.args = arguments, new _(n2);
222
+ }, b = v;
223
+ b.l = w, b.i = S, b.w = function(t2, e2) {
224
+ return O(t2, {
225
+ locale: e2.$L,
226
+ utc: e2.$u,
227
+ x: e2.$x,
228
+ $offset: e2.$offset
229
+ });
230
+ };
231
+ var _ = function() {
232
+ function M2(t2) {
233
+ this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
234
+ }
235
+ var m2 = M2.prototype;
236
+ return m2.parse = function(t2) {
237
+ this.$d = function(t3) {
238
+ var e2 = t3.date, n2 = t3.utc;
239
+ if (null === e2) return /* @__PURE__ */ new Date(NaN);
240
+ if (b.u(e2)) return /* @__PURE__ */ new Date();
241
+ if (e2 instanceof Date) return new Date(e2);
242
+ if ("string" == typeof e2 && !/Z$/i.test(e2)) {
243
+ var r2 = e2.match($);
244
+ if (r2) {
245
+ var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
246
+ return n2 ? new Date(Date.UTC(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2);
247
+ }
248
+ }
249
+ return new Date(e2);
250
+ }(t2), this.init();
251
+ }, m2.init = function() {
252
+ var t2 = this.$d;
253
+ this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
254
+ }, m2.$utils = function() {
255
+ return b;
256
+ }, m2.isValid = function() {
257
+ return !(this.$d.toString() === l);
258
+ }, m2.isSame = function(t2, e2) {
259
+ var n2 = O(t2);
260
+ return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
261
+ }, m2.isAfter = function(t2, e2) {
262
+ return O(t2) < this.startOf(e2);
263
+ }, m2.isBefore = function(t2, e2) {
264
+ return this.endOf(e2) < O(t2);
265
+ }, m2.$g = function(t2, e2, n2) {
266
+ return b.u(t2) ? this[e2] : this.set(n2, t2);
267
+ }, m2.unix = function() {
268
+ return Math.floor(this.valueOf() / 1e3);
269
+ }, m2.valueOf = function() {
270
+ return this.$d.getTime();
271
+ }, m2.startOf = function(t2, e2) {
272
+ var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
273
+ var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
274
+ return r2 ? i2 : i2.endOf(a);
275
+ }, $2 = function(t3, e3) {
276
+ return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [
277
+ 0,
278
+ 0,
279
+ 0,
280
+ 0
281
+ ] : [
282
+ 23,
283
+ 59,
284
+ 59,
285
+ 999
286
+ ]).slice(e3)), n2);
287
+ }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
288
+ switch(f2){
289
+ case h:
290
+ return r2 ? l2(1, 0) : l2(31, 11);
291
+ case c:
292
+ return r2 ? l2(1, M3) : l2(0, M3 + 1);
293
+ case o:
294
+ var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
295
+ return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
296
+ case a:
297
+ case d:
298
+ return $2(v2 + "Hours", 0);
299
+ case u:
300
+ return $2(v2 + "Minutes", 1);
301
+ case s:
302
+ return $2(v2 + "Seconds", 2);
303
+ case i:
304
+ return $2(v2 + "Milliseconds", 3);
305
+ default:
306
+ return this.clone();
307
+ }
308
+ }, m2.endOf = function(t2) {
309
+ return this.startOf(t2, false);
310
+ }, m2.$set = function(t2, e2) {
311
+ var n2, o2 = b.p(t2), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2;
312
+ if (o2 === c || o2 === h) {
313
+ var y2 = this.clone().set(d, 1);
314
+ y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
315
+ } else l2 && this.$d[l2]($2);
316
+ return this.init(), this;
317
+ }, m2.set = function(t2, e2) {
318
+ return this.clone().$set(t2, e2);
319
+ }, m2.get = function(t2) {
320
+ return this[b.p(t2)]();
321
+ }, m2.add = function(r2, f2) {
322
+ var d2, l2 = this;
323
+ r2 = Number(r2);
324
+ var $2 = b.p(f2), y2 = function(t2) {
325
+ var e2 = O(l2);
326
+ return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
327
+ };
328
+ if ($2 === c) return this.set(c, this.$M + r2);
329
+ if ($2 === h) return this.set(h, this.$y + r2);
330
+ if ($2 === a) return y2(1);
331
+ if ($2 === o) return y2(7);
332
+ var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
333
+ return b.w(m3, this);
334
+ }, m2.subtract = function(t2, e2) {
335
+ return this.add(-1 * t2, e2);
336
+ }, m2.format = function(t2) {
337
+ var e2 = this, n2 = this.$locale();
338
+ if (!this.isValid()) return n2.invalidDate || l;
339
+ var r2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", i2 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t3, n3, i3, s3) {
340
+ return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
341
+ }, d2 = function(t3) {
342
+ return b.s(s2 % 12 || 12, t3, "0");
343
+ }, $2 = f2 || function(t3, e3, n3) {
344
+ var r3 = t3 < 12 ? "AM" : "PM";
345
+ return n3 ? r3.toLowerCase() : r3;
346
+ };
347
+ return r2.replace(y, function(t3, r3) {
348
+ return r3 || function(t4) {
349
+ switch(t4){
350
+ case "YY":
351
+ return String(e2.$y).slice(-2);
352
+ case "YYYY":
353
+ return b.s(e2.$y, 4, "0");
354
+ case "M":
355
+ return a2 + 1;
356
+ case "MM":
357
+ return b.s(a2 + 1, 2, "0");
358
+ case "MMM":
359
+ return h2(n2.monthsShort, a2, c2, 3);
360
+ case "MMMM":
361
+ return h2(c2, a2);
362
+ case "D":
363
+ return e2.$D;
364
+ case "DD":
365
+ return b.s(e2.$D, 2, "0");
366
+ case "d":
367
+ return String(e2.$W);
368
+ case "dd":
369
+ return h2(n2.weekdaysMin, e2.$W, o2, 2);
370
+ case "ddd":
371
+ return h2(n2.weekdaysShort, e2.$W, o2, 3);
372
+ case "dddd":
373
+ return o2[e2.$W];
374
+ case "H":
375
+ return String(s2);
376
+ case "HH":
377
+ return b.s(s2, 2, "0");
378
+ case "h":
379
+ return d2(1);
380
+ case "hh":
381
+ return d2(2);
382
+ case "a":
383
+ return $2(s2, u2, true);
384
+ case "A":
385
+ return $2(s2, u2, false);
386
+ case "m":
387
+ return String(u2);
388
+ case "mm":
389
+ return b.s(u2, 2, "0");
390
+ case "s":
391
+ return String(e2.$s);
392
+ case "ss":
393
+ return b.s(e2.$s, 2, "0");
394
+ case "SSS":
395
+ return b.s(e2.$ms, 3, "0");
396
+ case "Z":
397
+ return i2;
398
+ }
399
+ return null;
400
+ }(t3) || i2.replace(":", "");
401
+ });
402
+ }, m2.utcOffset = function() {
403
+ return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
404
+ }, m2.diff = function(r2, d2, l2) {
405
+ var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
406
+ return b.m(y2, m3);
407
+ };
408
+ switch(M3){
409
+ case h:
410
+ $2 = D2() / 12;
411
+ break;
412
+ case c:
413
+ $2 = D2();
414
+ break;
415
+ case f:
416
+ $2 = D2() / 3;
417
+ break;
418
+ case o:
419
+ $2 = (g2 - v2) / 6048e5;
420
+ break;
421
+ case a:
422
+ $2 = (g2 - v2) / 864e5;
423
+ break;
424
+ case u:
425
+ $2 = g2 / n;
426
+ break;
427
+ case s:
428
+ $2 = g2 / e;
429
+ break;
430
+ case i:
431
+ $2 = g2 / t;
432
+ break;
433
+ default:
434
+ $2 = g2;
435
+ }
436
+ return l2 ? $2 : b.a($2);
437
+ }, m2.daysInMonth = function() {
438
+ return this.endOf(c).$D;
439
+ }, m2.$locale = function() {
440
+ return D[this.$L];
441
+ }, m2.locale = function(t2, e2) {
442
+ if (!t2) return this.$L;
443
+ var n2 = this.clone(), r2 = w(t2, e2, true);
444
+ return r2 && (n2.$L = r2), n2;
445
+ }, m2.clone = function() {
446
+ return b.w(this.$d, this);
447
+ }, m2.toDate = function() {
448
+ return new Date(this.valueOf());
449
+ }, m2.toJSON = function() {
450
+ return this.isValid() ? this.toISOString() : null;
451
+ }, m2.toISOString = function() {
452
+ return this.$d.toISOString();
453
+ }, m2.toString = function() {
454
+ return this.$d.toUTCString();
455
+ }, M2;
456
+ }(), k = _.prototype;
457
+ return O.prototype = k, [
458
+ [
459
+ "$ms",
460
+ r
461
+ ],
462
+ [
463
+ "$s",
464
+ i
465
+ ],
466
+ [
467
+ "$m",
468
+ s
469
+ ],
470
+ [
471
+ "$H",
472
+ u
473
+ ],
474
+ [
475
+ "$W",
476
+ a
477
+ ],
478
+ [
479
+ "$M",
480
+ c
481
+ ],
482
+ [
483
+ "$y",
484
+ h
485
+ ],
486
+ [
487
+ "$D",
488
+ d
489
+ ]
490
+ ].forEach(function(t2) {
491
+ k[t2[1]] = function(e2) {
492
+ return this.$g(e2, t2[0], t2[1]);
493
+ };
494
+ }), O.extend = function(t2, e2) {
495
+ return t2.$i || (t2(e2, _, O), t2.$i = true), O;
496
+ }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
497
+ return O(1e3 * t2);
498
+ }, O.en = D[g], O.Ls = D, O.p = {}, O;
499
+ });
436
500
  }
437
- obj[key] = value;
438
- }
439
- return obj;
440
- }
441
- function _parseVault(options) {
442
- const vaultPath = _vaultPath(options);
443
- const result = DotenvModule.configDotenv({ path: vaultPath });
444
- if (!result.parsed) {
445
- const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
446
- err.code = "MISSING_DATA";
447
- throw err;
448
- }
449
- const keys = _dotenvKey(options).split(",");
450
- const length = keys.length;
451
- let decrypted;
452
- for (let i = 0; i < length; i++) {
453
- try {
454
- const key = keys[i].trim();
455
- const attrs = _instructions(result, key);
456
- decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
457
- break;
458
- } catch (error) {
459
- if (i + 1 >= length) {
460
- throw error;
461
- }
501
+ });
502
+ // ../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json
503
+ var require_package = __commonJS({
504
+ "../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json" (exports, module1) {
505
+ module1.exports = {
506
+ name: "dotenv",
507
+ version: "16.4.5",
508
+ description: "Loads environment variables from .env file",
509
+ main: "lib/main.js",
510
+ types: "lib/main.d.ts",
511
+ exports: {
512
+ ".": {
513
+ types: "./lib/main.d.ts",
514
+ require: "./lib/main.js",
515
+ default: "./lib/main.js"
516
+ },
517
+ "./config": "./config.js",
518
+ "./config.js": "./config.js",
519
+ "./lib/env-options": "./lib/env-options.js",
520
+ "./lib/env-options.js": "./lib/env-options.js",
521
+ "./lib/cli-options": "./lib/cli-options.js",
522
+ "./lib/cli-options.js": "./lib/cli-options.js",
523
+ "./package.json": "./package.json"
524
+ },
525
+ scripts: {
526
+ "dts-check": "tsc --project tests/types/tsconfig.json",
527
+ lint: "standard",
528
+ "lint-readme": "standard-markdown",
529
+ pretest: "npm run lint && npm run dts-check",
530
+ test: "tap tests/*.js --100 -Rspec",
531
+ "test:coverage": "tap --coverage-report=lcov",
532
+ prerelease: "npm test",
533
+ release: "standard-version"
534
+ },
535
+ repository: {
536
+ type: "git",
537
+ url: "git://github.com/motdotla/dotenv.git"
538
+ },
539
+ funding: "https://dotenvx.com",
540
+ keywords: [
541
+ "dotenv",
542
+ "env",
543
+ ".env",
544
+ "environment",
545
+ "variables",
546
+ "config",
547
+ "settings"
548
+ ],
549
+ readmeFilename: "README.md",
550
+ license: "BSD-2-Clause",
551
+ devDependencies: {
552
+ "@definitelytyped/dtslint": "^0.0.133",
553
+ "@types/node": "^18.11.3",
554
+ decache: "^4.6.1",
555
+ sinon: "^14.0.1",
556
+ standard: "^17.0.0",
557
+ "standard-markdown": "^7.1.0",
558
+ "standard-version": "^9.5.0",
559
+ tap: "^16.3.0",
560
+ tar: "^6.1.11",
561
+ typescript: "^4.8.4"
562
+ },
563
+ engines: {
564
+ node: ">=12"
565
+ },
566
+ browser: {
567
+ fs: false
568
+ }
569
+ };
462
570
  }
463
- }
464
- return DotenvModule.parse(decrypted);
465
- }
466
- function _log(message) {
467
- console.log(`[dotenv@${version}][INFO] ${message}`);
468
- }
469
- function _warn(message) {
470
- console.log(`[dotenv@${version}][WARN] ${message}`);
471
- }
472
- function _debug(message) {
473
- console.log(`[dotenv@${version}][DEBUG] ${message}`);
474
- }
475
- function _dotenvKey(options) {
476
- if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
477
- return options.DOTENV_KEY;
478
- }
479
- if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
480
- return process.env.DOTENV_KEY;
481
- }
482
- return "";
483
- }
484
- function _instructions(result, dotenvKey) {
485
- let uri;
486
- try {
487
- uri = new URL(dotenvKey);
488
- } catch (error) {
489
- if (error.code === "ERR_INVALID_URL") {
490
- const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
491
- err.code = "INVALID_DOTENV_KEY";
492
- throw err;
571
+ });
572
+ // ../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js
573
+ var require_main = __commonJS({
574
+ "../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js" (exports, module1) {
575
+ "use strict";
576
+ var fs = __require("fs");
577
+ var path2 = __require("path");
578
+ var os = __require("os");
579
+ var crypto = __require("crypto");
580
+ var packageJson = require_package();
581
+ var version = packageJson.version;
582
+ var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
583
+ function parse(src) {
584
+ const obj = {};
585
+ let lines = src.toString();
586
+ lines = lines.replace(/\r\n?/mg, "\n");
587
+ let match;
588
+ while((match = LINE.exec(lines)) != null){
589
+ const key = match[1];
590
+ let value = match[2] || "";
591
+ value = value.trim();
592
+ const maybeQuote = value[0];
593
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
594
+ if (maybeQuote === '"') {
595
+ value = value.replace(/\\n/g, "\n");
596
+ value = value.replace(/\\r/g, "\r");
597
+ }
598
+ obj[key] = value;
599
+ }
600
+ return obj;
601
+ }
602
+ function _parseVault(options) {
603
+ const vaultPath = _vaultPath(options);
604
+ const result = DotenvModule.configDotenv({
605
+ path: vaultPath
606
+ });
607
+ if (!result.parsed) {
608
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
609
+ err.code = "MISSING_DATA";
610
+ throw err;
611
+ }
612
+ const keys = _dotenvKey(options).split(",");
613
+ const length = keys.length;
614
+ let decrypted;
615
+ for(let i = 0; i < length; i++){
616
+ try {
617
+ const key = keys[i].trim();
618
+ const attrs = _instructions(result, key);
619
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
620
+ break;
621
+ } catch (error) {
622
+ if (i + 1 >= length) {
623
+ throw error;
624
+ }
625
+ }
626
+ }
627
+ return DotenvModule.parse(decrypted);
628
+ }
629
+ function _log(message) {
630
+ console.log(`[dotenv@${version}][INFO] ${message}`);
631
+ }
632
+ function _warn(message) {
633
+ console.log(`[dotenv@${version}][WARN] ${message}`);
634
+ }
635
+ function _debug(message) {
636
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
637
+ }
638
+ function _dotenvKey(options) {
639
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
640
+ return options.DOTENV_KEY;
641
+ }
642
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
643
+ return process.env.DOTENV_KEY;
644
+ }
645
+ return "";
646
+ }
647
+ function _instructions(result, dotenvKey) {
648
+ let uri;
649
+ try {
650
+ uri = new URL(dotenvKey);
651
+ } catch (error) {
652
+ if (error.code === "ERR_INVALID_URL") {
653
+ const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
654
+ err.code = "INVALID_DOTENV_KEY";
655
+ throw err;
656
+ }
657
+ throw error;
658
+ }
659
+ const key = uri.password;
660
+ if (!key) {
661
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
662
+ err.code = "INVALID_DOTENV_KEY";
663
+ throw err;
664
+ }
665
+ const environment = uri.searchParams.get("environment");
666
+ if (!environment) {
667
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
668
+ err.code = "INVALID_DOTENV_KEY";
669
+ throw err;
670
+ }
671
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
672
+ const ciphertext = result.parsed[environmentKey];
673
+ if (!ciphertext) {
674
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
675
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
676
+ throw err;
677
+ }
678
+ return {
679
+ ciphertext,
680
+ key
681
+ };
682
+ }
683
+ function _vaultPath(options) {
684
+ let possibleVaultPath = null;
685
+ if (options && options.path && options.path.length > 0) {
686
+ if (Array.isArray(options.path)) {
687
+ for (const filepath of options.path){
688
+ if (fs.existsSync(filepath)) {
689
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
690
+ }
691
+ }
692
+ } else {
693
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
694
+ }
695
+ } else {
696
+ possibleVaultPath = path2.resolve(process.cwd(), ".env.vault");
697
+ }
698
+ if (fs.existsSync(possibleVaultPath)) {
699
+ return possibleVaultPath;
700
+ }
701
+ return null;
702
+ }
703
+ function _resolveHome(envPath) {
704
+ return envPath[0] === "~" ? path2.join(os.homedir(), envPath.slice(1)) : envPath;
705
+ }
706
+ function _configVault(options) {
707
+ _log("Loading env from encrypted .env.vault");
708
+ const parsed = DotenvModule._parseVault(options);
709
+ let processEnv = process.env;
710
+ if (options && options.processEnv != null) {
711
+ processEnv = options.processEnv;
712
+ }
713
+ DotenvModule.populate(processEnv, parsed, options);
714
+ return {
715
+ parsed
716
+ };
717
+ }
718
+ function configDotenv(options) {
719
+ const dotenvPath = path2.resolve(process.cwd(), ".env");
720
+ let encoding = "utf8";
721
+ const debug = Boolean(options && options.debug);
722
+ if (options && options.encoding) {
723
+ encoding = options.encoding;
724
+ } else {
725
+ if (debug) {
726
+ _debug("No encoding is specified. UTF-8 is used by default");
727
+ }
728
+ }
729
+ let optionPaths = [
730
+ dotenvPath
731
+ ];
732
+ if (options && options.path) {
733
+ if (!Array.isArray(options.path)) {
734
+ optionPaths = [
735
+ _resolveHome(options.path)
736
+ ];
737
+ } else {
738
+ optionPaths = [];
739
+ for (const filepath of options.path){
740
+ optionPaths.push(_resolveHome(filepath));
741
+ }
742
+ }
743
+ }
744
+ let lastError;
745
+ const parsedAll = {};
746
+ for (const path3 of optionPaths){
747
+ try {
748
+ const parsed = DotenvModule.parse(fs.readFileSync(path3, {
749
+ encoding
750
+ }));
751
+ DotenvModule.populate(parsedAll, parsed, options);
752
+ } catch (e) {
753
+ if (debug) {
754
+ _debug(`Failed to load ${path3} ${e.message}`);
755
+ }
756
+ lastError = e;
757
+ }
758
+ }
759
+ let processEnv = process.env;
760
+ if (options && options.processEnv != null) {
761
+ processEnv = options.processEnv;
762
+ }
763
+ DotenvModule.populate(processEnv, parsedAll, options);
764
+ if (lastError) {
765
+ return {
766
+ parsed: parsedAll,
767
+ error: lastError
768
+ };
769
+ } else {
770
+ return {
771
+ parsed: parsedAll
772
+ };
773
+ }
774
+ }
775
+ function config(options) {
776
+ if (_dotenvKey(options).length === 0) {
777
+ return DotenvModule.configDotenv(options);
778
+ }
779
+ const vaultPath = _vaultPath(options);
780
+ if (!vaultPath) {
781
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
782
+ return DotenvModule.configDotenv(options);
783
+ }
784
+ return DotenvModule._configVault(options);
785
+ }
786
+ function decrypt(encrypted, keyStr) {
787
+ const key = Buffer.from(keyStr.slice(-64), "hex");
788
+ let ciphertext = Buffer.from(encrypted, "base64");
789
+ const nonce = ciphertext.subarray(0, 12);
790
+ const authTag = ciphertext.subarray(-16);
791
+ ciphertext = ciphertext.subarray(12, -16);
792
+ try {
793
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
794
+ aesgcm.setAuthTag(authTag);
795
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
796
+ } catch (error) {
797
+ const isRange = error instanceof RangeError;
798
+ const invalidKeyLength = error.message === "Invalid key length";
799
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
800
+ if (isRange || invalidKeyLength) {
801
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
802
+ err.code = "INVALID_DOTENV_KEY";
803
+ throw err;
804
+ } else if (decryptionFailed) {
805
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
806
+ err.code = "DECRYPTION_FAILED";
807
+ throw err;
808
+ } else {
809
+ throw error;
810
+ }
811
+ }
812
+ }
813
+ function populate(processEnv, parsed, options = {}) {
814
+ const debug = Boolean(options && options.debug);
815
+ const override = Boolean(options && options.override);
816
+ if (typeof parsed !== "object") {
817
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
818
+ err.code = "OBJECT_REQUIRED";
819
+ throw err;
820
+ }
821
+ for (const key of Object.keys(parsed)){
822
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
823
+ if (override === true) {
824
+ processEnv[key] = parsed[key];
825
+ }
826
+ if (debug) {
827
+ if (override === true) {
828
+ _debug(`"${key}" is already defined and WAS overwritten`);
829
+ } else {
830
+ _debug(`"${key}" is already defined and was NOT overwritten`);
831
+ }
832
+ }
833
+ } else {
834
+ processEnv[key] = parsed[key];
835
+ }
836
+ }
837
+ }
838
+ var DotenvModule = {
839
+ configDotenv,
840
+ _configVault,
841
+ _parseVault,
842
+ config,
843
+ decrypt,
844
+ parse,
845
+ populate
846
+ };
847
+ module1.exports.configDotenv = DotenvModule.configDotenv;
848
+ module1.exports._configVault = DotenvModule._configVault;
849
+ module1.exports._parseVault = DotenvModule._parseVault;
850
+ module1.exports.config = DotenvModule.config;
851
+ module1.exports.decrypt = DotenvModule.decrypt;
852
+ module1.exports.parse = DotenvModule.parse;
853
+ module1.exports.populate = DotenvModule.populate;
854
+ module1.exports = DotenvModule;
855
+ }
856
+ });
857
+ // src/common/utils.ts
858
+ var import_dayjs = __toESM(require_dayjs_min());
859
+ // src/web-element.ts
860
+ var WebElementInfo = class {
861
+ constructor({ content, rect, page, locator, id, attributes, indexId }){
862
+ this.content = content;
863
+ this.rect = rect;
864
+ this.center = [
865
+ Math.floor(rect.left + rect.width / 2),
866
+ Math.floor(rect.top + rect.height / 2)
867
+ ];
868
+ this.page = page;
869
+ this.locator = locator;
870
+ this.id = id;
871
+ this.attributes = attributes;
872
+ this.indexId = indexId;
493
873
  }
494
- throw error;
495
- }
496
- const key = uri.password;
497
- if (!key) {
498
- const err = new Error("INVALID_DOTENV_KEY: Missing key part");
499
- err.code = "INVALID_DOTENV_KEY";
500
- throw err;
501
- }
502
- const environment = uri.searchParams.get("environment");
503
- if (!environment) {
504
- const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
505
- err.code = "INVALID_DOTENV_KEY";
506
- throw err;
507
- }
508
- const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
509
- const ciphertext = result.parsed[environmentKey];
510
- if (!ciphertext) {
511
- const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
512
- err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
513
- throw err;
514
- }
515
- return { ciphertext, key };
874
+ };
875
+ // src/common/utils.ts
876
+ function parseContextFromWebPage(page, _opt) {
877
+ return __async(this, null, function*() {
878
+ (0, _assert.default)(page, "page is required");
879
+ if (page._forceUsePageContext) {
880
+ return yield page._forceUsePageContext();
881
+ }
882
+ const url = yield page.url();
883
+ let screenshotBase64;
884
+ let elementsInfo;
885
+ yield Promise.all([
886
+ page.screenshotBase64().then((base64)=>{
887
+ screenshotBase64 = base64;
888
+ }),
889
+ page.getElementInfos().then((snapshot)=>__async(this, null, function*() {
890
+ elementsInfo = yield alignElements(snapshot, page);
891
+ }))
892
+ ]);
893
+ (0, _assert.default)(screenshotBase64, "screenshotBase64 is required");
894
+ const elementsPositionInfoWithoutText = elementsInfo.filter((elementInfo)=>{
895
+ if (elementInfo.attributes.nodeType === _constants.NodeType.TEXT) {
896
+ return false;
897
+ }
898
+ return true;
899
+ });
900
+ const size = yield page.size();
901
+ const width = size.width;
902
+ const height = size.height;
903
+ const screenshotBase64WithElementMarker = (_opt == null ? void 0 : _opt.ignoreMarker) ? void 0 : yield (0, _img.compositeElementInfoImg)({
904
+ inputImgBase64: screenshotBase64,
905
+ elementsPositionInfo: elementsPositionInfoWithoutText,
906
+ size: {
907
+ width,
908
+ height
909
+ }
910
+ });
911
+ return {
912
+ content: elementsInfo,
913
+ size: {
914
+ width,
915
+ height
916
+ },
917
+ screenshotBase64,
918
+ screenshotBase64WithElementMarker,
919
+ url
920
+ };
921
+ });
516
922
  }
517
- function _vaultPath(options) {
518
- let possibleVaultPath = null;
519
- if (options && options.path && options.path.length > 0) {
520
- if (Array.isArray(options.path)) {
521
- for (const filepath of options.path) {
522
- if (fs.existsSync(filepath)) {
523
- possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
923
+ var sizeThreshold = 3;
924
+ function alignElements(elements, page) {
925
+ return __async(this, null, function*() {
926
+ const validElements = elements.filter((item)=>{
927
+ return item.rect.height >= sizeThreshold && item.rect.width >= sizeThreshold;
928
+ });
929
+ const textsAligned = [];
930
+ for (const item of validElements){
931
+ const { rect, id, content, attributes, locator, indexId } = item;
932
+ textsAligned.push(new WebElementInfo({
933
+ rect,
934
+ locator,
935
+ id,
936
+ content,
937
+ attributes,
938
+ page,
939
+ indexId
940
+ }));
524
941
  }
525
- }
526
- } else {
527
- possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
528
- }
529
- } else {
530
- possibleVaultPath = path2.resolve(process.cwd(), ".env.vault");
531
- }
532
- if (fs.existsSync(possibleVaultPath)) {
533
- return possibleVaultPath;
534
- }
535
- return null;
942
+ return textsAligned;
943
+ });
536
944
  }
537
- function _resolveHome(envPath) {
538
- return envPath[0] === "~" ? path2.join(os.homedir(), envPath.slice(1)) : envPath;
945
+ function reportFileName(tag = "web") {
946
+ const dateTimeInFileName = (0, import_dayjs.default)().format("YYYY-MM-DD_HH-mm-ss-SSS");
947
+ return `${tag}-${dateTimeInFileName}`;
539
948
  }
540
- function _configVault(options) {
541
- _log("Loading env from encrypted .env.vault");
542
- const parsed = DotenvModule._parseVault(options);
543
- let processEnv = process.env;
544
- if (options && options.processEnv != null) {
545
- processEnv = options.processEnv;
546
- }
547
- DotenvModule.populate(processEnv, parsed, options);
548
- return { parsed };
949
+ function printReportMsg(filepath) {
950
+ console.log("Midscene - report file updated:", filepath);
549
951
  }
550
- function configDotenv(options) {
551
- const dotenvPath = path2.resolve(process.cwd(), ".env");
552
- let encoding = "utf8";
553
- const debug = Boolean(options && options.debug);
554
- if (options && options.encoding) {
555
- encoding = options.encoding;
556
- } else {
557
- if (debug) {
558
- _debug("No encoding is specified. UTF-8 is used by default");
559
- }
560
- }
561
- let optionPaths = [dotenvPath];
562
- if (options && options.path) {
563
- if (!Array.isArray(options.path)) {
564
- optionPaths = [_resolveHome(options.path)];
565
- } else {
566
- optionPaths = [];
567
- for (const filepath of options.path) {
568
- optionPaths.push(_resolveHome(filepath));
569
- }
570
- }
571
- }
572
- let lastError;
573
- const parsedAll = {};
574
- for (const path3 of optionPaths) {
575
- try {
576
- const parsed = DotenvModule.parse(fs.readFileSync(path3, { encoding }));
577
- DotenvModule.populate(parsedAll, parsed, options);
578
- } catch (e) {
579
- if (debug) {
580
- _debug(`Failed to load ${path3} ${e.message}`);
581
- }
582
- lastError = e;
952
+ function getCurrentExecutionFile(trace) {
953
+ const error = new Error();
954
+ const stackTrace = trace || error.stack;
955
+ const pkgDir = process.cwd() || "";
956
+ if (stackTrace) {
957
+ const stackLines = stackTrace.split("\n");
958
+ for (const line of stackLines){
959
+ if (line.includes(".spec.") || line.includes(".test.") || line.includes(".ts") || line.includes(".js")) {
960
+ const match = line.match(/(?:at\s+)?(.*?\.(?:spec|test)\.[jt]s)/);
961
+ if (match == null ? void 0 : match[1]) {
962
+ const targetFileName = match[1].replace(pkgDir, "").trim().replace("at ", "");
963
+ return targetFileName;
964
+ }
965
+ }
966
+ }
583
967
  }
584
- }
585
- let processEnv = process.env;
586
- if (options && options.processEnv != null) {
587
- processEnv = options.processEnv;
588
- }
589
- DotenvModule.populate(processEnv, parsedAll, options);
590
- if (lastError) {
591
- return { parsed: parsedAll, error: lastError };
592
- } else {
593
- return { parsed: parsedAll };
594
- }
595
- }
596
- function config(options) {
597
- if (_dotenvKey(options).length === 0) {
598
- return DotenvModule.configDotenv(options);
599
- }
600
- const vaultPath = _vaultPath(options);
601
- if (!vaultPath) {
602
- _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
603
- return DotenvModule.configDotenv(options);
604
- }
605
- return DotenvModule._configVault(options);
968
+ return false;
606
969
  }
607
- function decrypt(encrypted, keyStr) {
608
- const key = Buffer.from(keyStr.slice(-64), "hex");
609
- let ciphertext = Buffer.from(encrypted, "base64");
610
- const nonce = ciphertext.subarray(0, 12);
611
- const authTag = ciphertext.subarray(-16);
612
- ciphertext = ciphertext.subarray(12, -16);
613
- try {
614
- const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
615
- aesgcm.setAuthTag(authTag);
616
- return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
617
- } catch (error) {
618
- const isRange = error instanceof RangeError;
619
- const invalidKeyLength = error.message === "Invalid key length";
620
- const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
621
- if (isRange || invalidKeyLength) {
622
- const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
623
- err.code = "INVALID_DOTENV_KEY";
624
- throw err;
625
- } else if (decryptionFailed) {
626
- const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
627
- err.code = "DECRYPTION_FAILED";
628
- throw err;
629
- } else {
630
- throw error;
970
+ var testFileIndex = /* @__PURE__ */ new Map();
971
+ function generateCacheId(fileName) {
972
+ let taskFile = fileName || getCurrentExecutionFile();
973
+ if (!taskFile) {
974
+ taskFile = (0, _utils.uuid)();
975
+ console.warn("Midscene - using random UUID for cache id. Cache may be invalid.");
631
976
  }
632
- }
633
- }
634
- function populate(processEnv, parsed, options = {}) {
635
- const debug = Boolean(options && options.debug);
636
- const override = Boolean(options && options.override);
637
- if (typeof parsed !== "object") {
638
- const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
639
- err.code = "OBJECT_REQUIRED";
640
- throw err;
641
- }
642
- for (const key of Object.keys(parsed)) {
643
- if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
644
- if (override === true) {
645
- processEnv[key] = parsed[key];
646
- }
647
- if (debug) {
648
- if (override === true) {
649
- _debug(`"${key}" is already defined and WAS overwritten`);
650
- } else {
651
- _debug(`"${key}" is already defined and was NOT overwritten`);
977
+ if (testFileIndex.has(taskFile)) {
978
+ const currentIndex = testFileIndex.get(taskFile);
979
+ if (currentIndex !== void 0) {
980
+ testFileIndex.set(taskFile, currentIndex + 1);
652
981
  }
653
- }
654
982
  } else {
655
- processEnv[key] = parsed[key];
656
- }
657
- }
658
- }
659
- var DotenvModule = {
660
- configDotenv,
661
- _configVault,
662
- _parseVault,
663
- config,
664
- decrypt,
665
- parse,
666
- populate
667
- };
668
- module2.exports.configDotenv = DotenvModule.configDotenv;
669
- module2.exports._configVault = DotenvModule._configVault;
670
- module2.exports._parseVault = DotenvModule._parseVault;
671
- module2.exports.config = DotenvModule.config;
672
- module2.exports.decrypt = DotenvModule.decrypt;
673
- module2.exports.parse = DotenvModule.parse;
674
- module2.exports.populate = DotenvModule.populate;
675
- module2.exports = DotenvModule;
676
- }
677
- });
678
-
679
- // src/playground/server.ts
680
- var import_node_assert3 = __toESM(require("assert"));
681
- var import_node_crypto2 = require("crypto");
682
- var import_node_fs3 = require("fs");
683
- var import_node_path3 = require("path");
684
-
685
- // src/common/utils.ts
686
- var import_node_assert = __toESM(require("assert"));
687
- var import_node_crypto = require("crypto");
688
- var import_node_fs = require("fs");
689
- var import_node_path = __toESM(require("path"));
690
- var import_constants = require("@midscene/shared/constants");
691
- var import_fs = require("@midscene/shared/fs");
692
- var import_img = require("@midscene/shared/img");
693
- var import_img2 = require("@midscene/shared/img");
694
- var import_dayjs = __toESM(require_dayjs_min());
695
-
696
- // src/web-element.ts
697
- var WebElementInfo = class {
698
- constructor({
699
- content,
700
- rect,
701
- page,
702
- locator,
703
- id,
704
- attributes,
705
- indexId
706
- }) {
707
- this.content = content;
708
- this.rect = rect;
709
- this.center = [
710
- Math.floor(rect.left + rect.width / 2),
711
- Math.floor(rect.top + rect.height / 2)
712
- ];
713
- this.page = page;
714
- this.locator = locator;
715
- this.id = id;
716
- this.attributes = attributes;
717
- this.indexId = indexId;
718
- }
719
- };
720
-
721
- // src/common/utils.ts
722
- async function parseContextFromWebPage(page, _opt) {
723
- (0, import_node_assert.default)(page, "page is required");
724
- if (page._forceUsePageContext) {
725
- return await page._forceUsePageContext();
726
- }
727
- const url = page.url();
728
- const file = await page.screenshot();
729
- const screenshotBase64 = (0, import_img.base64Encoded)(file);
730
- const captureElementSnapshot = await page.getElementInfos();
731
- const elementsInfo = await alignElements(captureElementSnapshot, page);
732
- const elementsPositionInfoWithoutText = elementsInfo.filter((elementInfo) => {
733
- if (elementInfo.attributes.nodeType === import_constants.NodeType.TEXT) {
734
- return false;
735
- }
736
- return true;
737
- });
738
- const size = await (0, import_img.imageInfoOfBase64)(screenshotBase64);
739
- const screenshotBase64WithElementMarker = await (0, import_img2.compositeElementInfoImg)({
740
- inputImgBase64: screenshotBase64.split(";base64,").pop(),
741
- elementsPositionInfo: elementsPositionInfoWithoutText
742
- });
743
- return {
744
- content: elementsInfo,
745
- size,
746
- screenshotBase64,
747
- screenshotBase64WithElementMarker: `data:image/png;base64,${screenshotBase64WithElementMarker}`,
748
- url
749
- };
750
- }
751
- var sizeThreshold = 3;
752
- async function alignElements(elements, page) {
753
- const validElements = elements.filter((item) => {
754
- return item.rect.height >= sizeThreshold && item.rect.width >= sizeThreshold;
755
- });
756
- const textsAligned = [];
757
- for (const item of validElements) {
758
- const { rect, id, content, attributes, locator, indexId } = item;
759
- textsAligned.push(
760
- new WebElementInfo({
761
- rect,
762
- locator,
763
- id,
764
- content,
765
- attributes,
766
- page,
767
- indexId
768
- })
769
- );
770
- }
771
- return textsAligned;
772
- }
773
- function reportFileName(tag = "web") {
774
- const dateTimeInFileName = (0, import_dayjs.default)().format("YYYY-MM-DD_HH-mm-ss-SSS");
775
- return `${tag}-${dateTimeInFileName}`;
776
- }
777
- function printReportMsg(filepath) {
778
- console.log("Midscene - report file updated:", filepath);
779
- }
780
- function getCurrentExecutionFile(trace) {
781
- const error = new Error();
782
- const stackTrace = trace || error.stack;
783
- const pkgDir = process.cwd() || "";
784
- if (stackTrace) {
785
- const stackLines = stackTrace.split("\n");
786
- for (const line of stackLines) {
787
- if (line.includes(".spec.") || line.includes(".test.") || line.includes(".ts") || line.includes(".js")) {
788
- const match = line.match(/(?:at\s+)?(.*?\.(?:spec|test)\.[jt]s)/);
789
- if (match == null ? void 0 : match[1]) {
790
- const targetFileName = match[1].replace(pkgDir, "").trim().replace("at ", "");
791
- return targetFileName;
983
+ testFileIndex.set(taskFile, 1);
792
984
  }
793
- }
794
- }
795
- }
796
- return false;
797
- }
798
- var testFileIndex = /* @__PURE__ */ new Map();
799
- function generateCacheId(fileName) {
800
- let taskFile = fileName || getCurrentExecutionFile();
801
- if (!taskFile) {
802
- taskFile = (0, import_node_crypto.randomUUID)();
803
- console.warn(
804
- "Midscene - using random UUID for cache id. Cache may be invalid."
805
- );
806
- }
807
- if (testFileIndex.has(taskFile)) {
808
- const currentIndex = testFileIndex.get(taskFile);
809
- if (currentIndex !== void 0) {
810
- testFileIndex.set(taskFile, currentIndex + 1);
985
+ return `${taskFile}-${testFileIndex.get(taskFile)}`;
811
986
  }
812
- } else {
813
- testFileIndex.set(taskFile, 1);
814
- }
815
- return `${taskFile}-${testFileIndex.get(taskFile)}`;
816
- }
817
- var ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = "NOT_IMPLEMENTED_AS_DESIGNED";
818
-
819
- // src/playground/server.ts
820
- var import_utils10 = require("@midscene/core/utils");
821
- var import_cors = __toESM(require("cors"));
822
- var import_dotenv = __toESM(require_main());
823
- var import_express = __toESM(require("express"));
824
-
825
- // src/common/agent.ts
826
- var import_utils5 = require("@midscene/core/utils");
827
-
828
- // src/common/tasks.ts
829
- var import_node_assert2 = __toESM(require("assert"));
830
- var import_core = require("@midscene/core");
831
- var import_utils3 = require("@midscene/core/utils");
832
- var import_img3 = require("@midscene/shared/img");
833
-
834
- // src/common/task-cache.ts
835
- var import_node_fs2 = require("fs");
836
- var import_node_path2 = require("path");
837
- var import_utils = require("@midscene/core/utils");
838
- var import_fs2 = require("@midscene/shared/fs");
839
- var TaskCache = class {
840
- constructor(opts) {
841
- this.midscenePkgInfo = (0, import_fs2.getMidscenePkgInfo)(__dirname);
842
- this.cacheId = generateCacheId(opts == null ? void 0 : opts.fileName);
843
- this.cache = this.readCacheFromFile() || {
844
- aiTasks: []
845
- };
846
- this.newCache = {
847
- aiTasks: []
848
- };
849
- }
850
- getCacheGroupByPrompt(aiActionPrompt) {
851
- const { aiTasks = [] } = this.cache || { aiTasks: [] };
852
- const index = aiTasks.findIndex((item) => item.prompt === aiActionPrompt);
853
- const newCacheGroup = [];
854
- this.newCache.aiTasks.push({
855
- prompt: aiActionPrompt,
856
- tasks: newCacheGroup
857
- });
858
- return {
859
- readCache: (pageContext, type, actionPrompt) => {
860
- if (index === -1) {
861
- return false;
987
+ var ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = "NOT_IMPLEMENTED_AS_DESIGNED";
988
+ var TaskCache = class {
989
+ getCacheGroupByPrompt(aiActionPrompt) {
990
+ const { aiTasks = [] } = this.cache || {
991
+ aiTasks: []
992
+ };
993
+ const index = aiTasks.findIndex((item)=>item.prompt === aiActionPrompt);
994
+ const newCacheGroup = [];
995
+ this.newCache.aiTasks.push({
996
+ prompt: aiActionPrompt,
997
+ tasks: newCacheGroup
998
+ });
999
+ return {
1000
+ readCache: (pageContext, type, actionPrompt)=>{
1001
+ if (index === -1) {
1002
+ return false;
1003
+ }
1004
+ if (type === "plan") {
1005
+ return this.readCache(pageContext, type, actionPrompt, aiTasks[index].tasks);
1006
+ }
1007
+ return this.readCache(pageContext, type, actionPrompt, aiTasks[index].tasks);
1008
+ },
1009
+ saveCache: (cache)=>{
1010
+ newCacheGroup.push(cache);
1011
+ this.writeCacheToFile();
1012
+ }
1013
+ };
862
1014
  }
863
- if (type === "plan") {
864
- return this.readCache(
865
- pageContext,
866
- type,
867
- actionPrompt,
868
- aiTasks[index].tasks
869
- );
1015
+ readCache(pageContext, type, userPrompt, cacheGroup) {
1016
+ var _a;
1017
+ if (cacheGroup.length > 0) {
1018
+ const index = cacheGroup.findIndex((item)=>item.prompt === userPrompt);
1019
+ if (index === -1) {
1020
+ return false;
1021
+ }
1022
+ const taskRes = cacheGroup.splice(index, 1)[0];
1023
+ if ((taskRes == null ? void 0 : taskRes.type) === "locate" && !((_a = taskRes.response) == null ? void 0 : _a.elements.every((element)=>{
1024
+ const findIndex = pageContext.content.findIndex((contentElement)=>contentElement.id === element.id);
1025
+ if (findIndex === -1) {
1026
+ return false;
1027
+ }
1028
+ return true;
1029
+ }))) {
1030
+ return false;
1031
+ }
1032
+ if (taskRes && taskRes.type === type && taskRes.prompt === userPrompt && this.pageContextEqual(taskRes.pageContext, pageContext)) {
1033
+ return taskRes.response;
1034
+ }
1035
+ }
1036
+ return false;
870
1037
  }
871
- return this.readCache(
872
- pageContext,
873
- type,
874
- actionPrompt,
875
- aiTasks[index].tasks
876
- );
877
- },
878
- saveCache: (cache) => {
879
- newCacheGroup.push(cache);
880
- this.writeCacheToFile();
881
- }
882
- };
883
- }
884
- readCache(pageContext, type, userPrompt, cacheGroup) {
885
- var _a;
886
- if (cacheGroup.length > 0) {
887
- const index = cacheGroup.findIndex((item) => item.prompt === userPrompt);
888
- if (index === -1) {
889
- return false;
890
- }
891
- const taskRes = cacheGroup.splice(index, 1)[0];
892
- if ((taskRes == null ? void 0 : taskRes.type) === "locate" && !((_a = taskRes.response) == null ? void 0 : _a.elements.every((element) => {
893
- const findIndex = pageContext.content.findIndex(
894
- (contentElement) => contentElement.id === element.id
895
- );
896
- if (findIndex === -1) {
897
- return false;
1038
+ pageContextEqual(taskPageContext, pageContext) {
1039
+ return taskPageContext.size.width === pageContext.size.width && taskPageContext.size.height === pageContext.size.height;
898
1040
  }
899
- return true;
900
- }))) {
901
- return false;
902
- }
903
- if (taskRes && taskRes.type === type && taskRes.prompt === userPrompt && this.pageContextEqual(taskRes.pageContext, pageContext)) {
904
- return taskRes.response;
905
- }
906
- }
907
- return false;
908
- }
909
- pageContextEqual(taskPageContext, pageContext) {
910
- return taskPageContext.size.width === pageContext.size.width && taskPageContext.size.height === pageContext.size.height;
911
- }
912
- /**
1041
+ /**
913
1042
  * Generate task cache data.
914
1043
  * This method is mainly used to create or obtain some cached data for tasks, and it returns a new cache object.
915
1044
  * In the cache object, it may contain task-related information, states, or other necessary data.
916
1045
  * It is assumed that the `newCache` property already exists in the current class or object and is a data structure used to store task cache.
917
1046
  * @returns {Object} Returns a new cache object, which may include task cache data.
918
- */
919
- generateTaskCache() {
920
- return this.newCache;
921
- }
922
- readCacheFromFile() {
923
- const cacheFile = (0, import_node_path2.join)((0, import_utils.getLogDirByType)("cache"), `${this.cacheId}.json`);
924
- if (process.env.MIDSCENE_CACHE === "true" && (0, import_node_fs2.existsSync)(cacheFile)) {
925
- try {
926
- const data = (0, import_node_fs2.readFileSync)(cacheFile, "utf8");
927
- const jsonData = JSON.parse(data);
928
- if (jsonData.pkgName !== this.midscenePkgInfo.name || jsonData.pkgVersion !== this.midscenePkgInfo.version) {
929
- return void 0;
930
- }
931
- return jsonData;
932
- } catch (err) {
933
- return void 0;
934
- }
935
- }
936
- return void 0;
937
- }
938
- writeCacheToFile() {
939
- const midscenePkgInfo = (0, import_fs2.getMidscenePkgInfo)(__dirname);
940
- (0, import_utils.writeLogFile)({
941
- fileName: `${this.cacheId}`,
942
- fileExt: "json",
943
- fileContent: (0, import_utils.stringifyDumpData)(
944
- __spreadValues({
945
- pkgName: midscenePkgInfo.name,
946
- pkgVersion: midscenePkgInfo.version,
947
- cacheId: this.cacheId
948
- }, this.newCache),
949
- 2
950
- ),
951
- type: "cache"
952
- });
953
- }
954
- };
955
-
956
- // src/common/tasks.ts
957
- var PageTaskExecutor = class {
958
- constructor(page, opts) {
959
- this.page = page;
960
- this.insight = new import_core.Insight(async () => {
961
- return await parseContextFromWebPage(page);
962
- });
963
- this.taskCache = new TaskCache({
964
- fileName: opts == null ? void 0 : opts.cacheId
965
- });
966
- }
967
- async recordScreenshot(timing) {
968
- const file = await this.page.screenshot();
969
- const item = {
970
- type: "screenshot",
971
- ts: Date.now(),
972
- screenshot: (0, import_img3.base64Encoded)(file),
973
- timing
974
- };
975
- return item;
976
- }
977
- wrapExecutorWithScreenshot(taskApply) {
978
- const taskWithScreenshot = __spreadProps(__spreadValues({}, taskApply), {
979
- executor: async (param, context, ...args) => {
980
- const recorder = [];
981
- const { task } = context;
982
- task.recorder = recorder;
983
- const shot = await this.recordScreenshot(`before ${task.type}`);
984
- recorder.push(shot);
985
- const result = await taskApply.executor(param, context, ...args);
986
- if (taskApply.type === "Action") {
987
- await (0, import_utils3.sleep)(1e3);
988
- const shot2 = await this.recordScreenshot("after Action");
989
- recorder.push(shot2);
1047
+ */ generateTaskCache() {
1048
+ return this.newCache;
990
1049
  }
991
- return result;
992
- }
993
- });
994
- return taskWithScreenshot;
995
- }
996
- async convertPlanToExecutable(plans, cacheGroup) {
997
- const tasks = plans.map((plan2) => {
998
- if (plan2.type === "Locate") {
999
- const taskFind = {
1000
- type: "Insight",
1001
- subType: "Locate",
1002
- param: plan2.param,
1003
- executor: async (param, taskContext) => {
1004
- const { task } = taskContext;
1005
- let insightDump;
1006
- const dumpCollector = (dump) => {
1007
- insightDump = dump;
1008
- };
1009
- this.insight.onceDumpUpdatedFn = dumpCollector;
1010
- const pageContext = await this.insight.contextRetrieverFn();
1011
- const locateCache = cacheGroup == null ? void 0 : cacheGroup.readCache(
1012
- pageContext,
1013
- "locate",
1014
- param.prompt
1015
- );
1016
- let locateResult;
1017
- const callAI = this.insight.aiVendorFn;
1018
- const element = await this.insight.locate(param.prompt, {
1019
- quickAnswer: plan2.quickAnswer,
1020
- callAI: async (...message) => {
1021
- if (locateCache) {
1022
- locateResult = locateCache;
1023
- return Promise.resolve(locateCache);
1024
- }
1025
- locateResult = await callAI(...message);
1026
- (0, import_node_assert2.default)(locateResult);
1027
- return locateResult;
1028
- }
1029
- });
1030
- if (locateResult) {
1031
- cacheGroup == null ? void 0 : cacheGroup.saveCache({
1032
- type: "locate",
1033
- pageContext: {
1034
- url: pageContext.url,
1035
- size: pageContext.size
1036
- },
1037
- prompt: param.prompt,
1038
- response: locateResult
1039
- });
1050
+ readCacheFromFile() {
1051
+ if (_utils.ifInBrowser) {
1052
+ return void 0;
1040
1053
  }
1041
- if (!element) {
1042
- task.log = {
1043
- dump: insightDump
1044
- };
1045
- throw new Error(`Element not found: ${param.prompt}`);
1046
- }
1047
- return {
1048
- output: {
1049
- element
1050
- },
1051
- log: {
1052
- dump: insightDump
1053
- },
1054
- cache: {
1055
- hit: Boolean(locateCache)
1056
- }
1057
- };
1058
- }
1059
- };
1060
- return taskFind;
1061
- }
1062
- if (plan2.type === "Assert" || plan2.type === "AssertWithoutThrow") {
1063
- const assertPlan = plan2;
1064
- const taskAssert = {
1065
- type: "Insight",
1066
- subType: "Assert",
1067
- param: assertPlan.param,
1068
- executor: async (param, taskContext) => {
1069
- const { task } = taskContext;
1070
- let insightDump;
1071
- const dumpCollector = (dump) => {
1072
- insightDump = dump;
1073
- };
1074
- this.insight.onceDumpUpdatedFn = dumpCollector;
1075
- const assertion = await this.insight.assert(
1076
- assertPlan.param.assertion
1077
- );
1078
- if (!assertion.pass) {
1079
- if (plan2.type === "Assert") {
1080
- task.output = assertion;
1081
- task.log = {
1082
- dump: insightDump
1083
- };
1084
- throw new Error(
1085
- assertion.thought || "Assertion failed without reason"
1086
- );
1087
- }
1088
- task.error = assertion.thought;
1054
+ const cacheFile = (0, _path.join)((0, _utils1.getLogDirByType)("cache"), `${this.cacheId}.json`);
1055
+ if (process.env.MIDSCENE_CACHE === "true" && (0, _fs.existsSync)(cacheFile)) {
1056
+ try {
1057
+ const data = (0, _fs.readFileSync)(cacheFile, "utf8");
1058
+ const jsonData = JSON.parse(data);
1059
+ if (!this.midscenePkgInfo) {
1060
+ return void 0;
1061
+ }
1062
+ if (jsonData.pkgName !== this.midscenePkgInfo.name || jsonData.pkgVersion !== this.midscenePkgInfo.version) {
1063
+ return void 0;
1064
+ }
1065
+ return jsonData;
1066
+ } catch (err) {
1067
+ return void 0;
1068
+ }
1089
1069
  }
1090
- return {
1091
- output: assertion,
1092
- log: {
1093
- dump: insightDump
1094
- }
1095
- };
1096
- }
1097
- };
1098
- return taskAssert;
1099
- }
1100
- if (plan2.type === "Input") {
1101
- const taskActionInput = {
1102
- type: "Action",
1103
- subType: "Input",
1104
- param: plan2.param,
1105
- executor: async (taskParam, { element }) => {
1106
- if (element) {
1107
- await this.page.clearInput(element);
1108
- if (taskParam.value === "") {
1070
+ return void 0;
1071
+ }
1072
+ writeCacheToFile() {
1073
+ const midscenePkgInfo = (0, _fs1.getRunningPkgInfo)();
1074
+ if (!midscenePkgInfo) {
1109
1075
  return;
1110
- }
1111
- await this.page.keyboard.type(taskParam.value);
1112
1076
  }
1113
- }
1114
- };
1115
- return taskActionInput;
1116
- }
1117
- if (plan2.type === "KeyboardPress") {
1118
- const taskActionKeyboardPress = {
1119
- type: "Action",
1120
- subType: "KeyboardPress",
1121
- param: plan2.param,
1122
- executor: async (taskParam) => {
1123
- (0, import_node_assert2.default)(taskParam.value, "No key to press");
1124
- await this.page.keyboard.press(taskParam.value);
1125
- }
1126
- };
1127
- return taskActionKeyboardPress;
1128
- }
1129
- if (plan2.type === "Tap") {
1130
- const taskActionTap = {
1131
- type: "Action",
1132
- subType: "Tap",
1133
- executor: async (param, { element }) => {
1134
- (0, import_node_assert2.default)(element, "Element not found, cannot tap");
1135
- await this.page.mouse.click(
1136
- element.center[0],
1137
- element.center[1]
1138
- );
1139
- }
1140
- };
1141
- return taskActionTap;
1142
- }
1143
- if (plan2.type === "Hover") {
1144
- const taskActionHover = {
1145
- type: "Action",
1146
- subType: "Hover",
1147
- executor: async (param, { element }) => {
1148
- (0, import_node_assert2.default)(element, "Element not found, cannot hover");
1149
- await this.page.mouse.move(
1150
- element.center[0],
1151
- element.center[1]
1152
- );
1153
- }
1154
- };
1155
- return taskActionHover;
1156
- }
1157
- if (plan2.type === "Scroll") {
1158
- const taskActionScroll = {
1159
- type: "Action",
1160
- subType: "Scroll",
1161
- param: plan2.param,
1162
- executor: async (taskParam) => {
1163
- const scrollToEventName = taskParam.scrollType;
1164
- switch (scrollToEventName) {
1165
- case "scrollUntilTop":
1166
- await this.page.scrollUntilTop();
1167
- break;
1168
- case "scrollUntilBottom":
1169
- await this.page.scrollUntilBottom();
1170
- break;
1171
- case "scrollUpOneScreen":
1172
- await this.page.scrollUpOneScreen();
1173
- break;
1174
- case "scrollDownOneScreen":
1175
- await this.page.scrollDownOneScreen();
1176
- break;
1177
- default:
1178
- console.error(
1179
- "Unknown scroll event type:",
1180
- scrollToEventName
1181
- );
1077
+ if (!_utils.ifInBrowser) {
1078
+ (0, _utils1.writeLogFile)({
1079
+ fileName: `${this.cacheId}`,
1080
+ fileExt: "json",
1081
+ fileContent: (0, _utils1.stringifyDumpData)(__spreadValues({
1082
+ pkgName: midscenePkgInfo.name,
1083
+ pkgVersion: midscenePkgInfo.version,
1084
+ cacheId: this.cacheId
1085
+ }, this.newCache), 2),
1086
+ type: "cache"
1087
+ });
1182
1088
  }
1183
- }
1184
- };
1185
- return taskActionScroll;
1186
- }
1187
- if (plan2.type === "Sleep") {
1188
- const taskActionSleep = {
1189
- type: "Action",
1190
- subType: "Sleep",
1191
- param: plan2.param,
1192
- executor: async (taskParam) => {
1193
- await (0, import_utils3.sleep)(taskParam.timeMs || 3e3);
1194
- }
1195
- };
1196
- return taskActionSleep;
1197
- }
1198
- if (plan2.type === "Error") {
1199
- const taskActionError = {
1200
- type: "Action",
1201
- subType: "Error",
1202
- param: plan2.param,
1203
- executor: async (taskParam) => {
1204
- (0, import_node_assert2.default)(
1205
- taskParam.thought,
1206
- "An error occurred, but no thought provided"
1207
- );
1208
- throw new Error(taskParam.thought);
1209
- }
1210
- };
1211
- return taskActionError;
1212
- }
1213
- throw new Error(`Unknown or Unsupported task type: ${plan2.type}`);
1214
- }).map((task) => {
1215
- return this.wrapExecutorWithScreenshot(task);
1216
- });
1217
- return tasks;
1218
- }
1219
- async action(userPrompt) {
1220
- const taskExecutor = new import_core.Executor(userPrompt);
1221
- const cacheGroup = this.taskCache.getCacheGroupByPrompt(userPrompt);
1222
- let plans = [];
1223
- const planningTask = {
1224
- type: "Planning",
1225
- param: {
1226
- userPrompt
1227
- },
1228
- executor: async (param) => {
1229
- const pageContext = await this.insight.contextRetrieverFn();
1230
- let planResult;
1231
- const planCache = cacheGroup.readCache(pageContext, "plan", userPrompt);
1232
- if (planCache) {
1233
- planResult = planCache;
1234
- } else {
1235
- planResult = await (0, import_core.plan)(param.userPrompt, {
1236
- context: pageContext
1237
- });
1238
1089
  }
1239
- (0, import_node_assert2.default)(planResult.plans.length > 0, "No plans found");
1240
- plans = planResult.plans;
1241
- cacheGroup.saveCache({
1242
- type: "plan",
1243
- pageContext: {
1244
- url: pageContext.url,
1245
- size: pageContext.size
1246
- },
1247
- prompt: userPrompt,
1248
- response: planResult
1249
- });
1250
- return {
1251
- output: planResult,
1252
- cache: {
1253
- hit: Boolean(planCache)
1254
- }
1255
- };
1256
- }
1257
- };
1258
- await taskExecutor.append(this.wrapExecutorWithScreenshot(planningTask));
1259
- let output = await taskExecutor.flush();
1260
- if (taskExecutor.isInErrorState()) {
1261
- return {
1262
- output,
1263
- executor: taskExecutor
1264
- };
1265
- }
1266
- const executables = await this.convertPlanToExecutable(plans, cacheGroup);
1267
- await taskExecutor.append(executables);
1268
- output = await taskExecutor.flush();
1269
- return {
1270
- output,
1271
- executor: taskExecutor
1272
- };
1273
- }
1274
- async query(demand) {
1275
- const description = typeof demand === "string" ? demand : JSON.stringify(demand);
1276
- const taskExecutor = new import_core.Executor(description);
1277
- const queryTask = {
1278
- type: "Insight",
1279
- subType: "Query",
1280
- param: {
1281
- dataDemand: demand
1282
- },
1283
- executor: async (param) => {
1284
- let insightDump;
1285
- const dumpCollector = (dump) => {
1286
- insightDump = dump;
1287
- };
1288
- this.insight.onceDumpUpdatedFn = dumpCollector;
1289
- const data = await this.insight.extract(param.dataDemand);
1290
- return {
1291
- output: data,
1292
- log: { dump: insightDump }
1293
- };
1294
- }
1295
- };
1296
- await taskExecutor.append(this.wrapExecutorWithScreenshot(queryTask));
1297
- const output = await taskExecutor.flush();
1298
- return {
1299
- output,
1300
- executor: taskExecutor
1301
- };
1302
- }
1303
- async assert(assertion) {
1304
- const description = `assert: ${assertion}`;
1305
- const taskExecutor = new import_core.Executor(description);
1306
- const assertionPlan = {
1307
- type: "Assert",
1308
- param: {
1309
- assertion
1310
- }
1311
- };
1312
- const assertTask = await this.convertPlanToExecutable([assertionPlan]);
1313
- await taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1314
- const output = await taskExecutor.flush();
1315
- return {
1316
- output,
1317
- executor: taskExecutor
1318
- };
1319
- }
1320
- async waitFor(assertion, opt) {
1321
- const description = `waitFor: ${assertion}`;
1322
- const taskExecutor = new import_core.Executor(description);
1323
- const { timeoutMs, checkIntervalMs } = opt;
1324
- (0, import_node_assert2.default)(assertion, "No assertion for waitFor");
1325
- (0, import_node_assert2.default)(timeoutMs, "No timeoutMs for waitFor");
1326
- (0, import_node_assert2.default)(checkIntervalMs, "No checkIntervalMs for waitFor");
1327
- const overallStartTime = Date.now();
1328
- let startTime = Date.now();
1329
- let errorThought = "";
1330
- while (Date.now() - overallStartTime < timeoutMs) {
1331
- startTime = Date.now();
1332
- const assertPlan = {
1333
- type: "AssertWithoutThrow",
1334
- param: {
1335
- assertion
1090
+ constructor(opts){
1091
+ this.midscenePkgInfo = (0, _fs1.getRunningPkgInfo)();
1092
+ this.cacheId = generateCacheId(opts == null ? void 0 : opts.fileName);
1093
+ this.cache = this.readCacheFromFile() || {
1094
+ aiTasks: []
1095
+ };
1096
+ this.newCache = {
1097
+ aiTasks: []
1098
+ };
1336
1099
  }
1337
- };
1338
- const assertTask = await this.convertPlanToExecutable([assertPlan]);
1339
- await taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1340
- const output = await taskExecutor.flush();
1341
- if (output == null ? void 0 : output.pass) {
1342
- return {
1343
- output: void 0,
1344
- executor: taskExecutor
1345
- };
1346
- }
1347
- errorThought = (output == null ? void 0 : output.thought) || "unknown error";
1348
- const now = Date.now();
1349
- if (now - startTime < checkIntervalMs) {
1350
- const timeRemaining = checkIntervalMs - (now - startTime);
1351
- const sleepPlan = {
1352
- type: "Sleep",
1353
- param: {
1354
- timeMs: timeRemaining
1355
- }
1356
- };
1357
- const sleepTask = await this.convertPlanToExecutable([sleepPlan]);
1358
- await taskExecutor.append(
1359
- this.wrapExecutorWithScreenshot(sleepTask[0])
1360
- );
1361
- await taskExecutor.flush();
1362
- }
1363
- }
1364
- const errorPlan = {
1365
- type: "Error",
1366
- param: {
1367
- thought: `waitFor timeout: ${errorThought}`
1368
- }
1369
- };
1370
- const errorTask = await this.convertPlanToExecutable([errorPlan]);
1371
- await taskExecutor.append(errorTask[0]);
1372
- await taskExecutor.flush();
1373
- return {
1374
- output: void 0,
1375
- executor: taskExecutor
1376
1100
  };
1377
- }
1378
- };
1379
-
1380
- // src/common/agent.ts
1381
- var PageAgent = class {
1382
- constructor(page, opts) {
1383
- this.page = page;
1384
- this.opts = Object.assign(
1385
- {
1386
- generateReport: true,
1387
- autoPrintReportMsg: true,
1388
- groupName: "Midscene Report",
1389
- groupDescription: ""
1390
- },
1391
- opts || {}
1392
- );
1393
- this.dump = {
1394
- groupName: this.opts.groupName,
1395
- groupDescription: this.opts.groupDescription,
1396
- executions: []
1101
+ // src/common/tasks.ts
1102
+ var PageTaskExecutor = class {
1103
+ recordScreenshot(timing) {
1104
+ return __async(this, null, function*() {
1105
+ const base64 = yield this.page.screenshotBase64();
1106
+ const item = {
1107
+ type: "screenshot",
1108
+ ts: Date.now(),
1109
+ screenshot: base64,
1110
+ timing
1111
+ };
1112
+ return item;
1113
+ });
1114
+ }
1115
+ wrapExecutorWithScreenshot(taskApply) {
1116
+ const taskWithScreenshot = __spreadProps(__spreadValues({}, taskApply), {
1117
+ executor: (param, context, ...args)=>__async(this, null, function*() {
1118
+ const recorder = [];
1119
+ const { task } = context;
1120
+ task.recorder = recorder;
1121
+ const shot = yield this.recordScreenshot(`before ${task.type}`);
1122
+ recorder.push(shot);
1123
+ const result = yield taskApply.executor(param, context, ...args);
1124
+ if (taskApply.type === "Action") {
1125
+ yield (0, _utils1.sleep)(1e3);
1126
+ const shot2 = yield this.recordScreenshot("after Action");
1127
+ recorder.push(shot2);
1128
+ }
1129
+ return result;
1130
+ })
1131
+ });
1132
+ return taskWithScreenshot;
1133
+ }
1134
+ convertPlanToExecutable(plans, cacheGroup) {
1135
+ return __async(this, null, function*() {
1136
+ const tasks = plans.map((plan2)=>{
1137
+ if (plan2.type === "Locate") {
1138
+ const taskFind = {
1139
+ type: "Insight",
1140
+ subType: "Locate",
1141
+ param: plan2.param,
1142
+ quickAnswer: plan2.quickAnswer,
1143
+ executor: (param, taskContext)=>__async(this, null, function*() {
1144
+ const { task } = taskContext;
1145
+ let insightDump;
1146
+ const dumpCollector = (dump)=>{
1147
+ insightDump = dump;
1148
+ };
1149
+ this.insight.onceDumpUpdatedFn = dumpCollector;
1150
+ const pageContext = yield this.insight.contextRetrieverFn();
1151
+ const locateCache = cacheGroup == null ? void 0 : cacheGroup.readCache(pageContext, "locate", param.prompt);
1152
+ let locateResult;
1153
+ const callAI = this.insight.aiVendorFn;
1154
+ const element = yield this.insight.locate(param.prompt, {
1155
+ quickAnswer: task.quickAnswer,
1156
+ callAI: (...message)=>__async(this, null, function*() {
1157
+ if (locateCache) {
1158
+ locateResult = locateCache;
1159
+ return Promise.resolve(locateCache);
1160
+ }
1161
+ const aiResult = yield callAI(...message);
1162
+ locateResult = (0, _core.transformElementPositionToId)(aiResult, pageContext.content);
1163
+ (0, _assert.default)(locateResult);
1164
+ return locateResult;
1165
+ })
1166
+ });
1167
+ if (locateResult) {
1168
+ cacheGroup == null ? void 0 : cacheGroup.saveCache({
1169
+ type: "locate",
1170
+ pageContext: {
1171
+ url: pageContext.url,
1172
+ size: pageContext.size
1173
+ },
1174
+ prompt: param.prompt,
1175
+ response: locateResult
1176
+ });
1177
+ }
1178
+ if (!element) {
1179
+ task.log = {
1180
+ dump: insightDump
1181
+ };
1182
+ throw new Error(`Element not found: ${param.prompt}`);
1183
+ }
1184
+ return {
1185
+ output: {
1186
+ element
1187
+ },
1188
+ log: {
1189
+ dump: insightDump
1190
+ },
1191
+ cache: {
1192
+ hit: Boolean(locateCache)
1193
+ }
1194
+ };
1195
+ })
1196
+ };
1197
+ return taskFind;
1198
+ }
1199
+ if (plan2.type === "Assert" || plan2.type === "AssertWithoutThrow") {
1200
+ const assertPlan = plan2;
1201
+ const taskAssert = {
1202
+ type: "Insight",
1203
+ subType: "Assert",
1204
+ param: assertPlan.param,
1205
+ executor: (param, taskContext)=>__async(this, null, function*() {
1206
+ const { task } = taskContext;
1207
+ let insightDump;
1208
+ const dumpCollector = (dump)=>{
1209
+ insightDump = dump;
1210
+ };
1211
+ this.insight.onceDumpUpdatedFn = dumpCollector;
1212
+ const assertion = yield this.insight.assert(assertPlan.param.assertion);
1213
+ if (!assertion.pass) {
1214
+ if (plan2.type === "Assert") {
1215
+ task.output = assertion;
1216
+ task.log = {
1217
+ dump: insightDump
1218
+ };
1219
+ throw new Error(assertion.thought || "Assertion failed without reason");
1220
+ }
1221
+ task.error = assertion.thought;
1222
+ }
1223
+ return {
1224
+ output: assertion,
1225
+ log: {
1226
+ dump: insightDump
1227
+ }
1228
+ };
1229
+ })
1230
+ };
1231
+ return taskAssert;
1232
+ }
1233
+ if (plan2.type === "Input") {
1234
+ const taskActionInput = {
1235
+ type: "Action",
1236
+ subType: "Input",
1237
+ param: plan2.param,
1238
+ executor: (_0, _1)=>__async(this, [
1239
+ _0,
1240
+ _1
1241
+ ], function*(taskParam, { element }) {
1242
+ if (element) {
1243
+ yield this.page.clearInput(element);
1244
+ if (taskParam.value === "") {
1245
+ return;
1246
+ }
1247
+ yield this.page.keyboard.type(taskParam.value);
1248
+ }
1249
+ })
1250
+ };
1251
+ return taskActionInput;
1252
+ }
1253
+ if (plan2.type === "KeyboardPress") {
1254
+ const taskActionKeyboardPress = {
1255
+ type: "Action",
1256
+ subType: "KeyboardPress",
1257
+ param: plan2.param,
1258
+ executor: (taskParam)=>__async(this, null, function*() {
1259
+ (0, _assert.default)(taskParam.value, "No key to press");
1260
+ yield this.page.keyboard.press(taskParam.value);
1261
+ })
1262
+ };
1263
+ return taskActionKeyboardPress;
1264
+ }
1265
+ if (plan2.type === "Tap") {
1266
+ const taskActionTap = {
1267
+ type: "Action",
1268
+ subType: "Tap",
1269
+ executor: (_0, _1)=>__async(this, [
1270
+ _0,
1271
+ _1
1272
+ ], function*(param, { element }) {
1273
+ (0, _assert.default)(element, "Element not found, cannot tap");
1274
+ yield this.page.mouse.click(element.center[0], element.center[1]);
1275
+ })
1276
+ };
1277
+ return taskActionTap;
1278
+ }
1279
+ if (plan2.type === "Hover") {
1280
+ const taskActionHover = {
1281
+ type: "Action",
1282
+ subType: "Hover",
1283
+ executor: (_0, _1)=>__async(this, [
1284
+ _0,
1285
+ _1
1286
+ ], function*(param, { element }) {
1287
+ (0, _assert.default)(element, "Element not found, cannot hover");
1288
+ yield this.page.mouse.move(element.center[0], element.center[1]);
1289
+ })
1290
+ };
1291
+ return taskActionHover;
1292
+ }
1293
+ if (plan2.type === "Scroll") {
1294
+ const taskActionScroll = {
1295
+ type: "Action",
1296
+ subType: "Scroll",
1297
+ param: plan2.param,
1298
+ executor: (taskParam)=>__async(this, null, function*() {
1299
+ const scrollToEventName = taskParam.scrollType;
1300
+ switch(scrollToEventName){
1301
+ case "scrollUntilTop":
1302
+ yield this.page.scrollUntilTop();
1303
+ break;
1304
+ case "scrollUntilBottom":
1305
+ yield this.page.scrollUntilBottom();
1306
+ break;
1307
+ case "scrollUpOneScreen":
1308
+ yield this.page.scrollUpOneScreen();
1309
+ break;
1310
+ case "scrollDownOneScreen":
1311
+ yield this.page.scrollDownOneScreen();
1312
+ break;
1313
+ default:
1314
+ console.error("Unknown scroll event type:", scrollToEventName);
1315
+ }
1316
+ })
1317
+ };
1318
+ return taskActionScroll;
1319
+ }
1320
+ if (plan2.type === "Sleep") {
1321
+ const taskActionSleep = {
1322
+ type: "Action",
1323
+ subType: "Sleep",
1324
+ param: plan2.param,
1325
+ executor: (taskParam)=>__async(this, null, function*() {
1326
+ yield (0, _utils1.sleep)(taskParam.timeMs || 3e3);
1327
+ })
1328
+ };
1329
+ return taskActionSleep;
1330
+ }
1331
+ if (plan2.type === "Error") {
1332
+ const taskActionError = {
1333
+ type: "Action",
1334
+ subType: "Error",
1335
+ param: plan2.param,
1336
+ executor: (taskParam)=>__async(this, null, function*() {
1337
+ (0, _assert.default)(taskParam.thought, "An error occurred, but no thought provided");
1338
+ throw new Error(taskParam.thought);
1339
+ })
1340
+ };
1341
+ return taskActionError;
1342
+ }
1343
+ throw new Error(`Unknown or Unsupported task type: ${plan2.type}`);
1344
+ }).map((task)=>{
1345
+ return this.wrapExecutorWithScreenshot(task);
1346
+ });
1347
+ return tasks;
1348
+ });
1349
+ }
1350
+ action(userPrompt) {
1351
+ return __async(this, null, function*() {
1352
+ const taskExecutor = new _core.Executor(userPrompt);
1353
+ const cacheGroup = this.taskCache.getCacheGroupByPrompt(userPrompt);
1354
+ let plans = [];
1355
+ const planningTask = {
1356
+ type: "Planning",
1357
+ param: {
1358
+ userPrompt
1359
+ },
1360
+ executor: (param)=>__async(this, null, function*() {
1361
+ const pageContext = yield this.insight.contextRetrieverFn();
1362
+ let planResult;
1363
+ const planCache = cacheGroup.readCache(pageContext, "plan", userPrompt);
1364
+ if (planCache) {
1365
+ planResult = planCache;
1366
+ } else {
1367
+ planResult = yield (0, _core.plan)(param.userPrompt, {
1368
+ context: pageContext
1369
+ });
1370
+ }
1371
+ (0, _assert.default)(planResult.plans.length > 0, "No plans found");
1372
+ plans = planResult.plans;
1373
+ cacheGroup.saveCache({
1374
+ type: "plan",
1375
+ pageContext: {
1376
+ url: pageContext.url,
1377
+ size: pageContext.size
1378
+ },
1379
+ prompt: userPrompt,
1380
+ response: planResult
1381
+ });
1382
+ return {
1383
+ output: planResult,
1384
+ pageContext,
1385
+ cache: {
1386
+ hit: Boolean(planCache)
1387
+ }
1388
+ };
1389
+ })
1390
+ };
1391
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(planningTask));
1392
+ let output = yield taskExecutor.flush();
1393
+ if (taskExecutor.isInErrorState()) {
1394
+ return {
1395
+ output,
1396
+ executor: taskExecutor
1397
+ };
1398
+ }
1399
+ const executables = yield this.convertPlanToExecutable(plans, cacheGroup);
1400
+ yield taskExecutor.append(executables);
1401
+ output = yield taskExecutor.flush();
1402
+ return {
1403
+ output,
1404
+ executor: taskExecutor
1405
+ };
1406
+ });
1407
+ }
1408
+ query(demand) {
1409
+ return __async(this, null, function*() {
1410
+ const description = typeof demand === "string" ? demand : JSON.stringify(demand);
1411
+ const taskExecutor = new _core.Executor(description);
1412
+ const queryTask = {
1413
+ type: "Insight",
1414
+ subType: "Query",
1415
+ param: {
1416
+ dataDemand: demand
1417
+ },
1418
+ executor: (param)=>__async(this, null, function*() {
1419
+ let insightDump;
1420
+ const dumpCollector = (dump)=>{
1421
+ insightDump = dump;
1422
+ };
1423
+ this.insight.onceDumpUpdatedFn = dumpCollector;
1424
+ const data = yield this.insight.extract(param.dataDemand);
1425
+ return {
1426
+ output: data,
1427
+ log: {
1428
+ dump: insightDump
1429
+ }
1430
+ };
1431
+ })
1432
+ };
1433
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(queryTask));
1434
+ const output = yield taskExecutor.flush();
1435
+ return {
1436
+ output,
1437
+ executor: taskExecutor
1438
+ };
1439
+ });
1440
+ }
1441
+ assert(assertion) {
1442
+ return __async(this, null, function*() {
1443
+ const description = `assert: ${assertion}`;
1444
+ const taskExecutor = new _core.Executor(description);
1445
+ const assertionPlan = {
1446
+ type: "Assert",
1447
+ param: {
1448
+ assertion
1449
+ }
1450
+ };
1451
+ const assertTask = yield this.convertPlanToExecutable([
1452
+ assertionPlan
1453
+ ]);
1454
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1455
+ const output = yield taskExecutor.flush();
1456
+ return {
1457
+ output,
1458
+ executor: taskExecutor
1459
+ };
1460
+ });
1461
+ }
1462
+ waitFor(assertion, opt) {
1463
+ return __async(this, null, function*() {
1464
+ const description = `waitFor: ${assertion}`;
1465
+ const taskExecutor = new _core.Executor(description);
1466
+ const { timeoutMs, checkIntervalMs } = opt;
1467
+ (0, _assert.default)(assertion, "No assertion for waitFor");
1468
+ (0, _assert.default)(timeoutMs, "No timeoutMs for waitFor");
1469
+ (0, _assert.default)(checkIntervalMs, "No checkIntervalMs for waitFor");
1470
+ const overallStartTime = Date.now();
1471
+ let startTime = Date.now();
1472
+ let errorThought = "";
1473
+ while(Date.now() - overallStartTime < timeoutMs){
1474
+ startTime = Date.now();
1475
+ const assertPlan = {
1476
+ type: "AssertWithoutThrow",
1477
+ param: {
1478
+ assertion
1479
+ }
1480
+ };
1481
+ const assertTask = yield this.convertPlanToExecutable([
1482
+ assertPlan
1483
+ ]);
1484
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1485
+ const output = yield taskExecutor.flush();
1486
+ if (output == null ? void 0 : output.pass) {
1487
+ return {
1488
+ output: void 0,
1489
+ executor: taskExecutor
1490
+ };
1491
+ }
1492
+ errorThought = (output == null ? void 0 : output.thought) || "unknown error";
1493
+ const now = Date.now();
1494
+ if (now - startTime < checkIntervalMs) {
1495
+ const timeRemaining = checkIntervalMs - (now - startTime);
1496
+ const sleepPlan = {
1497
+ type: "Sleep",
1498
+ param: {
1499
+ timeMs: timeRemaining
1500
+ }
1501
+ };
1502
+ const sleepTask = yield this.convertPlanToExecutable([
1503
+ sleepPlan
1504
+ ]);
1505
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(sleepTask[0]));
1506
+ yield taskExecutor.flush();
1507
+ }
1508
+ }
1509
+ const errorPlan = {
1510
+ type: "Error",
1511
+ param: {
1512
+ thought: `waitFor timeout: ${errorThought}`
1513
+ }
1514
+ };
1515
+ const errorTask = yield this.convertPlanToExecutable([
1516
+ errorPlan
1517
+ ]);
1518
+ yield taskExecutor.append(errorTask[0]);
1519
+ yield taskExecutor.flush();
1520
+ return {
1521
+ output: void 0,
1522
+ executor: taskExecutor
1523
+ };
1524
+ });
1525
+ }
1526
+ constructor(page, insight, opts){
1527
+ this.page = page;
1528
+ this.insight = insight;
1529
+ this.taskCache = new TaskCache({
1530
+ fileName: opts == null ? void 0 : opts.cacheId
1531
+ });
1532
+ }
1397
1533
  };
1398
- this.taskExecutor = new PageTaskExecutor(this.page, {
1399
- cacheId: opts == null ? void 0 : opts.cacheId
1400
- });
1401
- this.reportFileName = reportFileName((opts == null ? void 0 : opts.testId) || "web");
1402
- }
1403
- appendExecutionDump(execution) {
1404
- const currentDump = this.dump;
1405
- currentDump.executions.push(execution);
1406
- }
1407
- dumpDataString() {
1408
- this.dump.groupName = this.opts.groupName;
1409
- this.dump.groupDescription = this.opts.groupDescription;
1410
- return (0, import_utils5.stringifyDumpData)(this.dump);
1411
- }
1412
- writeOutActionDumps() {
1413
- const { generateReport, autoPrintReportMsg } = this.opts;
1414
- this.reportFile = (0, import_utils5.writeLogFile)({
1415
- fileName: this.reportFileName,
1416
- fileExt: import_utils5.groupedActionDumpFileExt,
1417
- fileContent: this.dumpDataString(),
1418
- type: "dump",
1419
- generateReport
1420
- });
1421
- if (generateReport && autoPrintReportMsg) {
1422
- printReportMsg(this.reportFile);
1423
- }
1424
- }
1425
- async aiAction(taskPrompt) {
1426
- const { executor } = await this.taskExecutor.action(taskPrompt);
1427
- this.appendExecutionDump(executor.dump());
1428
- this.writeOutActionDumps();
1429
- if (executor.isInErrorState()) {
1430
- const errorTask = executor.latestErrorTask();
1431
- throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1534
+ // src/common/agent.ts
1535
+ var PageAgent = class {
1536
+ getUIContext() {
1537
+ return __async(this, null, function*() {
1538
+ return yield parseContextFromWebPage(this.page);
1539
+ });
1540
+ }
1541
+ resetDump() {
1542
+ this.dump = {
1543
+ groupName: this.opts.groupName,
1544
+ groupDescription: this.opts.groupDescription,
1545
+ executions: []
1546
+ };
1547
+ return this.dump;
1548
+ }
1549
+ appendExecutionDump(execution) {
1550
+ const currentDump = this.dump;
1551
+ currentDump.executions.push(execution);
1552
+ }
1553
+ dumpDataString() {
1554
+ this.dump.groupName = this.opts.groupName;
1555
+ this.dump.groupDescription = this.opts.groupDescription;
1556
+ return (0, _utils1.stringifyDumpData)(this.dump);
1557
+ }
1558
+ reportHTMLString() {
1559
+ return (0, _utils1.reportHTMLContent)(this.dumpDataString());
1560
+ }
1561
+ writeOutActionDumps() {
1562
+ const { generateReport, autoPrintReportMsg } = this.opts;
1563
+ this.reportFile = (0, _utils1.writeLogFile)({
1564
+ fileName: this.reportFileName,
1565
+ fileExt: _utils1.groupedActionDumpFileExt,
1566
+ fileContent: this.dumpDataString(),
1567
+ type: "dump",
1568
+ generateReport
1569
+ });
1570
+ if (generateReport && autoPrintReportMsg && this.reportFile) {
1571
+ printReportMsg(this.reportFile);
1572
+ }
1573
+ }
1574
+ aiAction(taskPrompt) {
1575
+ return __async(this, null, function*() {
1576
+ const { executor } = yield this.taskExecutor.action(taskPrompt);
1577
+ this.appendExecutionDump(executor.dump());
1578
+ this.writeOutActionDumps();
1579
+ if (executor.isInErrorState()) {
1580
+ const errorTask = executor.latestErrorTask();
1581
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1432
1582
  ${errorTask == null ? void 0 : errorTask.errorStack}`);
1433
- }
1434
- }
1435
- async aiQuery(demand) {
1436
- const { output, executor } = await this.taskExecutor.query(demand);
1437
- this.appendExecutionDump(executor.dump());
1438
- this.writeOutActionDumps();
1439
- if (executor.isInErrorState()) {
1440
- const errorTask = executor.latestErrorTask();
1441
- throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1583
+ }
1584
+ });
1585
+ }
1586
+ aiQuery(demand) {
1587
+ return __async(this, null, function*() {
1588
+ const { output, executor } = yield this.taskExecutor.query(demand);
1589
+ this.appendExecutionDump(executor.dump());
1590
+ this.writeOutActionDumps();
1591
+ if (executor.isInErrorState()) {
1592
+ const errorTask = executor.latestErrorTask();
1593
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1442
1594
  ${errorTask == null ? void 0 : errorTask.errorStack}`);
1443
- }
1444
- return output;
1445
- }
1446
- async aiAssert(assertion, msg, opt) {
1447
- const { output, executor } = await this.taskExecutor.assert(assertion);
1448
- this.appendExecutionDump(executor.dump());
1449
- this.writeOutActionDumps();
1450
- if (opt == null ? void 0 : opt.keepRawResponse) {
1451
- return output;
1452
- }
1453
- if (!(output == null ? void 0 : output.pass)) {
1454
- const errMsg = msg || `Assertion failed: ${assertion}`;
1455
- const reasonMsg = `Reason: ${(output == null ? void 0 : output.thought) || "(no_reason)"}`;
1456
- throw new Error(`${errMsg}
1595
+ }
1596
+ return output;
1597
+ });
1598
+ }
1599
+ aiAssert(assertion, msg, opt) {
1600
+ return __async(this, null, function*() {
1601
+ var _a;
1602
+ const { output, executor } = yield this.taskExecutor.assert(assertion);
1603
+ this.appendExecutionDump(executor.dump());
1604
+ this.writeOutActionDumps();
1605
+ if (output && (opt == null ? void 0 : opt.keepRawResponse)) {
1606
+ return output;
1607
+ }
1608
+ if (!(output == null ? void 0 : output.pass)) {
1609
+ const errMsg = msg || `Assertion failed: ${assertion}`;
1610
+ const reasonMsg = `Reason: ${(output == null ? void 0 : output.thought) || ((_a = executor.latestErrorTask()) == null ? void 0 : _a.error) || "(no_reason)"}`;
1611
+ throw new Error(`${errMsg}
1457
1612
  ${reasonMsg}`);
1458
- }
1459
- }
1460
- async aiWaitFor(assertion, opt) {
1461
- const { executor } = await this.taskExecutor.waitFor(assertion, {
1462
- timeoutMs: (opt == null ? void 0 : opt.timeoutMs) || 15 * 1e3,
1463
- checkIntervalMs: (opt == null ? void 0 : opt.checkIntervalMs) || 3 * 1e3,
1464
- assertion
1465
- });
1466
- this.appendExecutionDump(executor.dump());
1467
- this.writeOutActionDumps();
1468
- if (executor.isInErrorState()) {
1469
- const errorTask = executor.latestErrorTask();
1470
- throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1613
+ }
1614
+ });
1615
+ }
1616
+ aiWaitFor(assertion, opt) {
1617
+ return __async(this, null, function*() {
1618
+ const { executor } = yield this.taskExecutor.waitFor(assertion, {
1619
+ timeoutMs: (opt == null ? void 0 : opt.timeoutMs) || 15 * 1e3,
1620
+ checkIntervalMs: (opt == null ? void 0 : opt.checkIntervalMs) || 3 * 1e3,
1621
+ assertion
1622
+ });
1623
+ this.appendExecutionDump(executor.dump());
1624
+ this.writeOutActionDumps();
1625
+ if (executor.isInErrorState()) {
1626
+ const errorTask = executor.latestErrorTask();
1627
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1471
1628
  ${errorTask == null ? void 0 : errorTask.errorStack}`);
1472
- }
1473
- }
1474
- async ai(taskPrompt, type = "action") {
1475
- if (type === "action") {
1476
- return this.aiAction(taskPrompt);
1477
- }
1478
- if (type === "query") {
1479
- return this.aiQuery(taskPrompt);
1480
- }
1481
- if (type === "assert") {
1482
- return this.aiAssert(taskPrompt);
1483
- }
1484
- throw new Error(
1485
- `Unknown type: ${type}, only support 'action', 'query', 'assert'`
1486
- );
1487
- }
1488
- };
1489
-
1490
- // src/playground/agent.ts
1491
- var StaticPageAgent = class extends PageAgent {
1492
- constructor(page) {
1493
- super(page, {});
1494
- }
1495
- };
1496
-
1497
- // src/playground/static-page.ts
1498
- var import_utils8 = require("@midscene/core/utils");
1499
- var import_img4 = require("@midscene/shared/img");
1500
- var ThrowNotImplemented = (methodName) => {
1501
- throw new Error(
1502
- `The method "${methodName}" is not implemented as designed since this is a static UI context. (${ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED})`
1503
- );
1504
- };
1505
- var StaticPage = class {
1506
- constructor(uiContext) {
1507
- this.pageType = "static";
1508
- this.mouse = {
1509
- click: ThrowNotImplemented.bind(null, "mouse.click"),
1510
- wheel: ThrowNotImplemented.bind(null, "mouse.wheel"),
1511
- move: ThrowNotImplemented.bind(null, "mouse.move")
1629
+ }
1630
+ });
1631
+ }
1632
+ ai(taskPrompt, type = "action") {
1633
+ return __async(this, null, function*() {
1634
+ if (type === "action") {
1635
+ return this.aiAction(taskPrompt);
1636
+ }
1637
+ if (type === "query") {
1638
+ return this.aiQuery(taskPrompt);
1639
+ }
1640
+ if (type === "assert") {
1641
+ return this.aiAssert(taskPrompt);
1642
+ }
1643
+ throw new Error(`Unknown type: ${type}, only support 'action', 'query', 'assert'`);
1644
+ });
1645
+ }
1646
+ destroy() {
1647
+ return __async(this, null, function*() {
1648
+ yield this.page.destroy();
1649
+ });
1650
+ }
1651
+ constructor(page, opts){
1652
+ /**
1653
+ * If true, the agent will not perform any actions
1654
+ */ this.dryMode = false;
1655
+ this.page = page;
1656
+ this.opts = Object.assign({
1657
+ generateReport: true,
1658
+ autoPrintReportMsg: true,
1659
+ groupName: "Midscene Report",
1660
+ groupDescription: ""
1661
+ }, opts || {});
1662
+ this.insight = new _core.Insight(()=>__async(this, null, function*() {
1663
+ return this.getUIContext();
1664
+ }), {
1665
+ generateElement: ({ content, rect })=>new WebElementInfo({
1666
+ content: content || "",
1667
+ rect,
1668
+ page,
1669
+ id: "",
1670
+ attributes: {
1671
+ nodeType: _constants.NodeType.CONTAINER
1672
+ },
1673
+ indexId: 0
1674
+ })
1675
+ });
1676
+ this.taskExecutor = new PageTaskExecutor(this.page, this.insight, {
1677
+ cacheId: opts == null ? void 0 : opts.cacheId
1678
+ });
1679
+ this.dump = this.resetDump();
1680
+ this.reportFileName = reportFileName((opts == null ? void 0 : opts.testId) || "web");
1681
+ }
1512
1682
  };
1513
- this.keyboard = {
1514
- type: ThrowNotImplemented.bind(null, "keyboard.type"),
1515
- press: ThrowNotImplemented.bind(null, "keyboard.press")
1683
+ // src/playground/agent.ts
1684
+ var StaticPageAgent = class extends PageAgent {
1685
+ constructor(page){
1686
+ super(page, {});
1687
+ this.dryMode = true;
1688
+ }
1516
1689
  };
1517
- this.uiContext = uiContext;
1518
- }
1519
- async getElementInfos() {
1520
- return ThrowNotImplemented("getElementInfos");
1521
- }
1522
- async screenshot() {
1523
- const base64 = this.uiContext.screenshotBase64;
1524
- if (!base64) {
1525
- throw new Error("screenshot base64 is empty");
1526
- }
1527
- const tmpFilePath = (0, import_utils8.getTmpFile)("png");
1528
- await (0, import_img4.saveBase64Image)({ base64Data: base64, outputPath: tmpFilePath });
1529
- return tmpFilePath;
1530
- }
1531
- url() {
1532
- return this.uiContext.url;
1533
- }
1534
- async scrollUntilTop() {
1535
- return ThrowNotImplemented("scrollUntilTop");
1536
- }
1537
- async scrollUntilBottom() {
1538
- return ThrowNotImplemented("scrollUntilBottom");
1539
- }
1540
- async scrollUpOneScreen() {
1541
- return ThrowNotImplemented("scrollUpOneScreen");
1542
- }
1543
- async scrollDownOneScreen() {
1544
- return ThrowNotImplemented("scrollDownOneScreen");
1545
- }
1546
- async clearInput() {
1547
- return ThrowNotImplemented("clearInput");
1548
- }
1549
- async _forceUsePageContext() {
1550
- return this.uiContext;
1551
- }
1552
- };
1553
-
1554
- // src/playground/server.ts
1555
- var defaultPort = 5800;
1556
- var staticPath = (0, import_node_path3.join)(__dirname, "../../static");
1557
- var agentRequestCount = 1;
1558
- var errorHandler = (err, req, res, next) => {
1559
- console.error(err);
1560
- res.status(500).json({
1561
- error: err.message
1562
- });
1563
- };
1564
- var setup = () => {
1565
- import_dotenv.default.config();
1566
- };
1567
- var PlaygroundServer = class {
1568
- constructor() {
1569
- this.app = (0, import_express.default)();
1570
- this.tmpDir = (0, import_utils10.getTmpDir)();
1571
- setup();
1572
- }
1573
- filePathForUuid(uuid) {
1574
- return (0, import_node_path3.join)(this.tmpDir, `${uuid}.json`);
1575
- }
1576
- saveContextFile(uuid, context) {
1577
- const tmpFile = this.filePathForUuid(uuid);
1578
- console.log(`save context file: ${tmpFile}`);
1579
- (0, import_node_fs3.writeFileSync)(tmpFile, context);
1580
- return tmpFile;
1581
- }
1582
- async launch() {
1583
- this.app.use(errorHandler);
1584
- this.app.use(
1585
- (0, import_cors.default)({
1586
- origin: "*",
1587
- credentials: true
1588
- })
1589
- );
1590
- this.app.get("/status", (0, import_cors.default)(), async (req, res) => {
1591
- res.send({
1592
- status: "ok"
1593
- });
1594
- });
1595
- this.app.get("/", (req, res) => {
1596
- res.sendFile((0, import_node_path3.join)(staticPath, "index.html"));
1597
- });
1598
- this.app.get("/playground/:uuid", async (req, res) => {
1599
- res.sendFile((0, import_node_path3.join)(staticPath, "index.html"));
1600
- });
1601
- this.app.get("/context/:uuid", async (req, res) => {
1602
- const { uuid } = req.params;
1603
- const contextFile = this.filePathForUuid(uuid);
1604
- (0, import_node_assert3.default)((0, import_node_fs3.existsSync)(contextFile), "Context not found");
1605
- const context = (0, import_node_fs3.readFileSync)(contextFile, "utf8");
1606
- res.json({
1607
- context
1608
- });
1609
- });
1610
- this.app.post(
1611
- "/playground-with-context",
1612
- import_express.default.json({ limit: "50mb" }),
1613
- async (req, res) => {
1614
- const context = req.body.context;
1615
- (0, import_node_assert3.default)(context, "context is required");
1616
- const uuid = (0, import_node_crypto2.randomUUID)();
1617
- this.saveContextFile(uuid, context);
1618
- return res.json({
1619
- location: `/playground/${uuid}`,
1620
- uuid
1690
+ // src/playground/static-page.ts
1691
+ var ThrowNotImplemented = (methodName)=>{
1692
+ throw new Error(`The method "${methodName}" is not implemented as designed since this is a static UI context. (${ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED})`);
1693
+ };
1694
+ var StaticPage = class {
1695
+ getElementInfos() {
1696
+ return __async(this, null, function*() {
1697
+ return ThrowNotImplemented("getElementInfos");
1698
+ });
1699
+ }
1700
+ size() {
1701
+ return __async(this, null, function*() {
1702
+ return this.uiContext.size;
1703
+ });
1704
+ }
1705
+ screenshotBase64() {
1706
+ return __async(this, null, function*() {
1707
+ const base64 = this.uiContext.screenshotBase64;
1708
+ if (!base64) {
1709
+ throw new Error("screenshot base64 is empty");
1710
+ }
1711
+ return base64;
1712
+ });
1713
+ }
1714
+ url() {
1715
+ return __async(this, null, function*() {
1716
+ return this.uiContext.url;
1717
+ });
1718
+ }
1719
+ scrollUntilTop() {
1720
+ return __async(this, null, function*() {
1721
+ return ThrowNotImplemented("scrollUntilTop");
1722
+ });
1723
+ }
1724
+ scrollUntilBottom() {
1725
+ return __async(this, null, function*() {
1726
+ return ThrowNotImplemented("scrollUntilBottom");
1727
+ });
1728
+ }
1729
+ scrollUpOneScreen() {
1730
+ return __async(this, null, function*() {
1731
+ return ThrowNotImplemented("scrollUpOneScreen");
1732
+ });
1733
+ }
1734
+ scrollDownOneScreen() {
1735
+ return __async(this, null, function*() {
1736
+ return ThrowNotImplemented("scrollDownOneScreen");
1737
+ });
1738
+ }
1739
+ clearInput() {
1740
+ return __async(this, null, function*() {
1741
+ return ThrowNotImplemented("clearInput");
1742
+ });
1743
+ }
1744
+ _forceUsePageContext() {
1745
+ return __async(this, null, function*() {
1746
+ return this.uiContext;
1747
+ });
1748
+ }
1749
+ destroy() {
1750
+ return __async(this, null, function*() {});
1751
+ }
1752
+ constructor(uiContext){
1753
+ this.pageType = "static";
1754
+ this.mouse = {
1755
+ click: ThrowNotImplemented.bind(null, "mouse.click"),
1756
+ wheel: ThrowNotImplemented.bind(null, "mouse.wheel"),
1757
+ move: ThrowNotImplemented.bind(null, "mouse.move")
1758
+ };
1759
+ this.keyboard = {
1760
+ type: ThrowNotImplemented.bind(null, "keyboard.type"),
1761
+ press: ThrowNotImplemented.bind(null, "keyboard.press")
1762
+ };
1763
+ this.uiContext = uiContext;
1764
+ }
1765
+ };
1766
+ // src/playground/server.ts
1767
+ var defaultPort = 5800;
1768
+ var agentRequestCount = 1;
1769
+ var errorHandler = (err, req, res, next)=>{
1770
+ console.error(err);
1771
+ res.status(500).json({
1772
+ error: err.message
1621
1773
  });
1622
- }
1623
- );
1624
- this.app.post(
1625
- "/execute",
1626
- import_express.default.json({ limit: "30mb" }),
1627
- async (req, res) => {
1628
- const { context, type, prompt } = req.body;
1629
- (0, import_node_assert3.default)(context, "context is required");
1630
- (0, import_node_assert3.default)(type, "type is required");
1631
- (0, import_node_assert3.default)(prompt, "prompt is required");
1632
- const requestId = agentRequestCount++;
1633
- console.log(`handle request: #${requestId}, ${type}, ${prompt}`);
1634
- const page = new StaticPage(context);
1635
- const agent = new StaticPageAgent(page);
1636
- const response = {
1637
- result: null,
1638
- dump: null,
1639
- error: null
1640
- };
1641
- try {
1642
- if (type === "aiQuery") {
1643
- response.result = await agent.aiQuery(prompt);
1644
- } else if (type === "aiAction") {
1645
- response.result = await agent.aiAction(prompt);
1646
- } else if (type === "aiAssert") {
1647
- response.result = await agent.aiAssert(prompt, void 0, {
1648
- keepRawResponse: true
1774
+ };
1775
+ var setup = ()=>__async(void 0, null, function*() {
1776
+ if (!_utils.ifInBrowser) {
1777
+ const dotenv = yield Promise.resolve().then(()=>__toESM(require_main()));
1778
+ dotenv.config();
1779
+ }
1780
+ });
1781
+ var PlaygroundServer = class {
1782
+ filePathForUuid(uuid2) {
1783
+ return (0, _path.join)(this.tmpDir, `${uuid2}.json`);
1784
+ }
1785
+ saveContextFile(uuid2, context) {
1786
+ const tmpFile = this.filePathForUuid(uuid2);
1787
+ console.log(`save context file: ${tmpFile}`);
1788
+ (0, _fs.writeFileSync)(tmpFile, context);
1789
+ return tmpFile;
1790
+ }
1791
+ launch() {
1792
+ return __async(this, null, function*() {
1793
+ this.app.use(errorHandler);
1794
+ this.app.use((0, _cors.default)({
1795
+ origin: "*",
1796
+ credentials: true
1797
+ }));
1798
+ this.app.get("/status", (0, _cors.default)(), (req, res)=>__async(this, null, function*() {
1799
+ res.send({
1800
+ status: "ok"
1801
+ });
1802
+ }));
1803
+ this.app.get("/context/:uuid", (req, res)=>__async(this, null, function*() {
1804
+ const { uuid: uuid2 } = req.params;
1805
+ const contextFile = this.filePathForUuid(uuid2);
1806
+ (0, _assert.default)((0, _fs.existsSync)(contextFile), "Context not found");
1807
+ const context = (0, _fs.readFileSync)(contextFile, "utf8");
1808
+ res.json({
1809
+ context
1810
+ });
1811
+ }));
1812
+ this.app.post("/playground-with-context", _express.default.json({
1813
+ limit: "50mb"
1814
+ }), (req, res)=>__async(this, null, function*() {
1815
+ const context = req.body.context;
1816
+ (0, _assert.default)(context, "context is required");
1817
+ const uuid2 = (0, _crypto.randomUUID)();
1818
+ this.saveContextFile(uuid2, context);
1819
+ return res.json({
1820
+ location: `/playground/${uuid2}`,
1821
+ uuid: uuid2
1822
+ });
1823
+ }));
1824
+ this.app.post("/execute", _express.default.json({
1825
+ limit: "30mb"
1826
+ }), (req, res)=>__async(this, null, function*() {
1827
+ const { context, type, prompt } = req.body;
1828
+ (0, _assert.default)(context, "context is required");
1829
+ (0, _assert.default)(type, "type is required");
1830
+ (0, _assert.default)(prompt, "prompt is required");
1831
+ const requestId = agentRequestCount++;
1832
+ console.log(`handle request: #${requestId}, ${type}, ${prompt}`);
1833
+ const page = new StaticPage(context);
1834
+ const agent = new StaticPageAgent(page);
1835
+ const response = {
1836
+ result: null,
1837
+ dump: null,
1838
+ error: null
1839
+ };
1840
+ try {
1841
+ if (type === "aiQuery") {
1842
+ response.result = yield agent.aiQuery(prompt);
1843
+ } else if (type === "aiAction") {
1844
+ response.result = yield agent.aiAction(prompt);
1845
+ } else if (type === "aiAssert") {
1846
+ response.result = yield agent.aiAssert(prompt, void 0, {
1847
+ keepRawResponse: true
1848
+ });
1849
+ } else {
1850
+ response.error = `Unknown type: ${type}`;
1851
+ }
1852
+ } catch (error) {
1853
+ if (!error.message.includes(ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED)) {
1854
+ response.error = error.message;
1855
+ }
1856
+ }
1857
+ try {
1858
+ response.dump = JSON.parse(agent.dumpDataString());
1859
+ agent.writeOutActionDumps();
1860
+ } catch (error) {
1861
+ console.error(`write out dump failed: #${requestId}, ${error.message}`);
1862
+ }
1863
+ res.send(response);
1864
+ if (response.error) {
1865
+ console.error(`handle request failed: #${requestId}, ${response.error}`);
1866
+ } else {
1867
+ console.log(`handle request done: #${requestId}`);
1868
+ }
1869
+ }));
1870
+ return new Promise((resolve, reject)=>{
1871
+ const port = this.port || defaultPort;
1872
+ this.server = this.app.listen(port, ()=>{
1873
+ this.port = port;
1874
+ resolve(this);
1875
+ });
1876
+ });
1649
1877
  });
1650
- } else {
1651
- response.error = `Unknown type: ${type}`;
1652
- }
1653
- } catch (error) {
1654
- if (!error.message.includes(ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED)) {
1655
- response.error = error.message;
1656
- }
1657
1878
  }
1658
- try {
1659
- response.dump = JSON.parse(agent.dumpDataString());
1660
- agent.writeOutActionDumps();
1661
- } catch (error) {
1662
- console.error(
1663
- `write out dump failed: #${requestId}, ${error.message}`
1664
- );
1879
+ close() {
1880
+ if (this.server) {
1881
+ return this.server.close();
1882
+ }
1665
1883
  }
1666
- res.send(response);
1667
- if (response.error) {
1668
- console.error(
1669
- `handle request failed: #${requestId}, ${response.error}`
1670
- );
1671
- } else {
1672
- console.log(`handle request done: #${requestId}`);
1884
+ constructor(){
1885
+ this.app = (0, _express.default)();
1886
+ this.tmpDir = (0, _utils1.getTmpDir)();
1887
+ setup();
1673
1888
  }
1674
- }
1675
- );
1676
- return new Promise((resolve, reject) => {
1677
- const port = this.port || defaultPort;
1678
- this.server = this.app.listen(port, () => {
1679
- this.port = port;
1680
- resolve(this);
1681
- });
1889
+ };
1890
+ // src/playground/bin.ts
1891
+ var server = new PlaygroundServer();
1892
+ Promise.resolve().then(()=>server.launch()).then(()=>{
1893
+ console.log(`Midscene playground server is running on http://localhost:${server.port}`);
1682
1894
  });
1683
- }
1684
- close() {
1685
- if (this.server) {
1686
- return this.server.close();
1687
- }
1688
- }
1689
- };
1690
-
1691
- // src/playground/bin.ts
1692
- var server = new PlaygroundServer();
1693
- Promise.resolve().then(() => server.launch()).then(() => {
1694
- console.log(
1695
- `Midscene playground server is running on http://localhost:${server.port}`
1696
- );
1697
1895
  });