@midscene/shared 1.17.5 → 1.17.7

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,31 +1,34 @@
1
1
  import { existsSync, mkdirSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
2
  import node_path from "node:path";
3
+ import { createConsoleContext } from "#console-context";
4
4
  import { getBasicEnvValue } from "./env/basic.mjs";
5
5
  import { MIDSCENE_RUN_DIR } from "./env/types.mjs";
6
6
  import { ifInNode } from "./utils.mjs";
7
7
  const defaultRunDirName = 'midscene_run';
8
8
  let configuredRunDir;
9
+ const contextKey = Symbol.for('@midscene/shared/run-directory');
10
+ const host = globalThis;
11
+ host[contextKey] ??= createConsoleContext();
12
+ const runDirectoryContext = host[contextKey];
13
+ const validateRunDir = (value)=>{
14
+ if ('string' != typeof value || !value.trim()) throw new TypeError('Midscene run directory must be a non-empty path.');
15
+ return value;
16
+ };
9
17
  const setMidsceneRunDir = (runDir)=>{
10
- configuredRunDir = runDir;
18
+ configuredRunDir = void 0 === runDir ? void 0 : validateRunDir(runDir);
11
19
  };
12
20
  const getMidsceneRunDir = ()=>{
13
21
  if (!ifInNode) return '';
14
- return configuredRunDir ?? getBasicEnvValue(MIDSCENE_RUN_DIR) ?? defaultRunDirName;
22
+ return validateRunDir(runDirectoryContext.getStore() ?? configuredRunDir ?? getBasicEnvValue(MIDSCENE_RUN_DIR) ?? defaultRunDirName);
15
23
  };
24
+ const resolveMidsceneRunDir = (baseDir)=>node_path.resolve(baseDir, validateRunDir(getMidsceneRunDir()));
25
+ const runWithMidsceneRunDir = (runDir, run)=>runDirectoryContext.run(node_path.resolve(validateRunDir(runDir)), run);
16
26
  const getMidsceneRunBaseDir = ()=>{
17
27
  if (!ifInNode) return '';
18
- let basePath = node_path.resolve(process.cwd(), getMidsceneRunDir());
19
- if (!existsSync(basePath)) try {
20
- mkdirSync(basePath, {
21
- recursive: true
22
- });
23
- } catch (error) {
24
- basePath = node_path.join(tmpdir(), defaultRunDirName);
25
- mkdirSync(basePath, {
26
- recursive: true
27
- });
28
- }
28
+ const basePath = node_path.resolve(process.cwd(), getMidsceneRunDir());
29
+ mkdirSync(basePath, {
30
+ recursive: true
31
+ });
29
32
  return basePath;
30
33
  };
31
34
  const getMidsceneRunSubDir = (subdir)=>{
@@ -38,4 +41,4 @@ const getMidsceneRunSubDir = (subdir)=>{
38
41
  return logPath;
39
42
  };
40
43
  const ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = 'NOT_IMPLEMENTED_AS_DESIGNED';
41
- export { ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED, defaultRunDirName, getMidsceneRunBaseDir, getMidsceneRunDir, getMidsceneRunSubDir, setMidsceneRunDir };
44
+ export { ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED, defaultRunDirName, getMidsceneRunBaseDir, getMidsceneRunDir, getMidsceneRunSubDir, resolveMidsceneRunDir, runWithMidsceneRunDir, setMidsceneRunDir };
@@ -5,7 +5,7 @@ import { assert } from "../utils.mjs";
5
5
  import { maskConfig, parseJson } from "./helper.mjs";
6
6
  import { initDebugConfig } from "./init-debug.mjs";
7
7
  const MODEL_CONFIG_DOC_URL = 'https://midscenejs.com/model-api-setup.html';
8
- const getCurrentVersion = ()=>"1.17.5";
8
+ const getCurrentVersion = ()=>"1.17.7";
9
9
  const getInvalidModelFamilyMessage = (modelFamily)=>`Invalid MIDSCENE_MODEL_FAMILY value: ${modelFamily}. Current version v${getCurrentVersion()} accepts the following model families: ${MODEL_FAMILY_VALUES.join(', ')}. You can also visit ${MODEL_CONFIG_DOC_URL} for the latest configuration information.`;
10
10
  const KEYS_MAP = {
11
11
  locate: LOCATE_MODEL_CONFIG_KEYS,
@@ -34,7 +34,7 @@ function logReport(message) {
34
34
  const logStreams = new Map();
35
35
  const logStreamPaths = new Map();
36
36
  let logDirectoryResolver;
37
- const backpressuredLogStreams = new Set();
37
+ const backpressuredLogStreams = new Map();
38
38
  const unavailableLogStreams = new Set();
39
39
  const debugInstances = new Map();
40
40
  function setLogDirectoryResolver(resolver) {
@@ -49,13 +49,16 @@ function setLogDirectoryResolver(resolver) {
49
49
  function getLogDirectory() {
50
50
  return logDirectoryResolver?.() ?? getMidsceneRunSubDir('log');
51
51
  }
52
- function getLogStream(topic) {
53
- const topicFileName = topic.replace(/:/g, '-');
54
- if (unavailableLogStreams.has(topicFileName)) return null;
55
- const logFile = node_path.join(getLogDirectory(), `${topicFileName}.log`);
56
- const existingStream = logStreams.get(topicFileName);
57
- if (existingStream && logStreamPaths.get(topicFileName) !== logFile) {
58
- existingStream.end();
52
+ function getLogStream(logFile) {
53
+ if (unavailableLogStreams.has(logFile)) return null;
54
+ const topicFileName = node_path.basename(logFile);
55
+ const existing = logStreams.get(topicFileName);
56
+ const previousPath = logStreamPaths.get(topicFileName);
57
+ if (existing && previousPath !== logFile) {
58
+ if (previousPath && backpressuredLogStreams.get(previousPath) === existing) existing.once('finish', ()=>{
59
+ if (backpressuredLogStreams.get(previousPath) === existing) backpressuredLogStreams.delete(previousPath);
60
+ });
61
+ existing.end();
59
62
  logStreams.delete(topicFileName);
60
63
  logStreamPaths.delete(topicFileName);
61
64
  }
@@ -64,8 +67,8 @@ function getLogStream(topic) {
64
67
  flags: 'a'
65
68
  });
66
69
  stream.on('error', ()=>{
67
- unavailableLogStreams.add(topicFileName);
68
- backpressuredLogStreams.delete(topicFileName);
70
+ unavailableLogStreams.add(logFile);
71
+ if (backpressuredLogStreams.get(logFile) === stream) backpressuredLogStreams.delete(logFile);
69
72
  if (logStreams.get(topicFileName) === stream) {
70
73
  logStreams.delete(topicFileName);
71
74
  logStreamPaths.delete(topicFileName);
@@ -79,8 +82,9 @@ function getLogStream(topic) {
79
82
  function writeLogToFile(topic, message) {
80
83
  if (!ifInNode) return;
81
84
  const topicFileName = topic.replace(/:/g, '-');
82
- if (backpressuredLogStreams.has(topicFileName)) return;
83
- const stream = getLogStream(topic);
85
+ const logFile = node_path.join(getLogDirectory(), `${topicFileName}.log`);
86
+ if (backpressuredLogStreams.has(logFile)) return;
87
+ const stream = getLogStream(logFile);
84
88
  if (!stream) return;
85
89
  const now = new Date();
86
90
  const isoDate = now.toLocaleDateString('sv-SE');
@@ -94,14 +98,14 @@ function writeLogToFile(topic, message) {
94
98
  const localISOTime = `${isoDate}T${isoTime}.${milliseconds}${timezoneString}`;
95
99
  try {
96
100
  if (!stream.write(`[${localISOTime}] ${message}\n`)) {
97
- backpressuredLogStreams.add(topicFileName);
101
+ backpressuredLogStreams.set(logFile, stream);
98
102
  stream.once('drain', ()=>{
99
- backpressuredLogStreams.delete(topicFileName);
103
+ if (backpressuredLogStreams.get(logFile) === stream) backpressuredLogStreams.delete(logFile);
100
104
  });
101
105
  }
102
106
  } catch {
103
- unavailableLogStreams.add(topicFileName);
104
- backpressuredLogStreams.delete(topicFileName);
107
+ unavailableLogStreams.add(logFile);
108
+ if (backpressuredLogStreams.get(logFile) === stream) backpressuredLogStreams.delete(logFile);
105
109
  }
106
110
  }
107
111
  function printConsoleWarning(topic, args, warning) {
@@ -33,42 +33,47 @@ var __webpack_require__ = {};
33
33
  var __webpack_exports__ = {};
34
34
  __webpack_require__.r(__webpack_exports__);
35
35
  __webpack_require__.d(__webpack_exports__, {
36
+ runWithMidsceneRunDir: ()=>runWithMidsceneRunDir,
36
37
  ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED: ()=>ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED,
37
- setMidsceneRunDir: ()=>setMidsceneRunDir,
38
+ resolveMidsceneRunDir: ()=>resolveMidsceneRunDir,
38
39
  getMidsceneRunBaseDir: ()=>getMidsceneRunBaseDir,
39
40
  getMidsceneRunDir: ()=>getMidsceneRunDir,
40
- getMidsceneRunSubDir: ()=>getMidsceneRunSubDir,
41
- defaultRunDirName: ()=>defaultRunDirName
41
+ defaultRunDirName: ()=>defaultRunDirName,
42
+ setMidsceneRunDir: ()=>setMidsceneRunDir,
43
+ getMidsceneRunSubDir: ()=>getMidsceneRunSubDir
42
44
  });
43
45
  const external_node_fs_namespaceObject = require("node:fs");
44
- const external_node_os_namespaceObject = require("node:os");
45
46
  const external_node_path_namespaceObject = require("node:path");
46
47
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
48
+ const external_console_context_namespaceObject = require("#console-context");
47
49
  const basic_js_namespaceObject = require("./env/basic.js");
48
50
  const types_js_namespaceObject = require("./env/types.js");
49
51
  const external_utils_js_namespaceObject = require("./utils.js");
50
52
  const defaultRunDirName = 'midscene_run';
51
53
  let configuredRunDir;
54
+ const contextKey = Symbol.for('@midscene/shared/run-directory');
55
+ const host = globalThis;
56
+ host[contextKey] ??= (0, external_console_context_namespaceObject.createConsoleContext)();
57
+ const runDirectoryContext = host[contextKey];
58
+ const validateRunDir = (value)=>{
59
+ if ('string' != typeof value || !value.trim()) throw new TypeError('Midscene run directory must be a non-empty path.');
60
+ return value;
61
+ };
52
62
  const setMidsceneRunDir = (runDir)=>{
53
- configuredRunDir = runDir;
63
+ configuredRunDir = void 0 === runDir ? void 0 : validateRunDir(runDir);
54
64
  };
55
65
  const getMidsceneRunDir = ()=>{
56
66
  if (!external_utils_js_namespaceObject.ifInNode) return '';
57
- return configuredRunDir ?? (0, basic_js_namespaceObject.getBasicEnvValue)(types_js_namespaceObject.MIDSCENE_RUN_DIR) ?? defaultRunDirName;
67
+ return validateRunDir(runDirectoryContext.getStore() ?? configuredRunDir ?? (0, basic_js_namespaceObject.getBasicEnvValue)(types_js_namespaceObject.MIDSCENE_RUN_DIR) ?? defaultRunDirName);
58
68
  };
69
+ const resolveMidsceneRunDir = (baseDir)=>external_node_path_default().resolve(baseDir, validateRunDir(getMidsceneRunDir()));
70
+ const runWithMidsceneRunDir = (runDir, run)=>runDirectoryContext.run(external_node_path_default().resolve(validateRunDir(runDir)), run);
59
71
  const getMidsceneRunBaseDir = ()=>{
60
72
  if (!external_utils_js_namespaceObject.ifInNode) return '';
61
- let basePath = external_node_path_default().resolve(process.cwd(), getMidsceneRunDir());
62
- if (!(0, external_node_fs_namespaceObject.existsSync)(basePath)) try {
63
- (0, external_node_fs_namespaceObject.mkdirSync)(basePath, {
64
- recursive: true
65
- });
66
- } catch (error) {
67
- basePath = external_node_path_default().join((0, external_node_os_namespaceObject.tmpdir)(), defaultRunDirName);
68
- (0, external_node_fs_namespaceObject.mkdirSync)(basePath, {
69
- recursive: true
70
- });
71
- }
73
+ const basePath = external_node_path_default().resolve(process.cwd(), getMidsceneRunDir());
74
+ (0, external_node_fs_namespaceObject.mkdirSync)(basePath, {
75
+ recursive: true
76
+ });
72
77
  return basePath;
73
78
  };
74
79
  const getMidsceneRunSubDir = (subdir)=>{
@@ -86,6 +91,8 @@ exports.defaultRunDirName = __webpack_exports__.defaultRunDirName;
86
91
  exports.getMidsceneRunBaseDir = __webpack_exports__.getMidsceneRunBaseDir;
87
92
  exports.getMidsceneRunDir = __webpack_exports__.getMidsceneRunDir;
88
93
  exports.getMidsceneRunSubDir = __webpack_exports__.getMidsceneRunSubDir;
94
+ exports.resolveMidsceneRunDir = __webpack_exports__.resolveMidsceneRunDir;
95
+ exports.runWithMidsceneRunDir = __webpack_exports__.runWithMidsceneRunDir;
89
96
  exports.setMidsceneRunDir = __webpack_exports__.setMidsceneRunDir;
90
97
  for(var __rspack_i in __webpack_exports__)if (-1 === [
91
98
  "ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED",
@@ -93,6 +100,8 @@ for(var __rspack_i in __webpack_exports__)if (-1 === [
93
100
  "getMidsceneRunBaseDir",
94
101
  "getMidsceneRunDir",
95
102
  "getMidsceneRunSubDir",
103
+ "resolveMidsceneRunDir",
104
+ "runWithMidsceneRunDir",
96
105
  "setMidsceneRunDir"
97
106
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
98
107
  Object.defineProperty(exports, '__esModule', {
@@ -37,7 +37,7 @@ const external_utils_js_namespaceObject = require("../utils.js");
37
37
  const external_helper_js_namespaceObject = require("./helper.js");
38
38
  const external_init_debug_js_namespaceObject = require("./init-debug.js");
39
39
  const MODEL_CONFIG_DOC_URL = 'https://midscenejs.com/model-api-setup.html';
40
- const getCurrentVersion = ()=>"1.17.5";
40
+ const getCurrentVersion = ()=>"1.17.7";
41
41
  const getInvalidModelFamilyMessage = (modelFamily)=>`Invalid MIDSCENE_MODEL_FAMILY value: ${modelFamily}. Current version v${getCurrentVersion()} accepts the following model families: ${external_types_js_namespaceObject.MODEL_FAMILY_VALUES.join(', ')}. You can also visit ${MODEL_CONFIG_DOC_URL} for the latest configuration information.`;
42
42
  const KEYS_MAP = {
43
43
  locate: external_constants_js_namespaceObject.LOCATE_MODEL_CONFIG_KEYS,
@@ -80,7 +80,7 @@ function logReport(message) {
80
80
  const logStreams = new Map();
81
81
  const logStreamPaths = new Map();
82
82
  let logDirectoryResolver;
83
- const backpressuredLogStreams = new Set();
83
+ const backpressuredLogStreams = new Map();
84
84
  const unavailableLogStreams = new Set();
85
85
  const debugInstances = new Map();
86
86
  function setLogDirectoryResolver(resolver) {
@@ -95,13 +95,16 @@ function setLogDirectoryResolver(resolver) {
95
95
  function getLogDirectory() {
96
96
  return logDirectoryResolver?.() ?? (0, external_common_js_namespaceObject.getMidsceneRunSubDir)('log');
97
97
  }
98
- function getLogStream(topic) {
99
- const topicFileName = topic.replace(/:/g, '-');
100
- if (unavailableLogStreams.has(topicFileName)) return null;
101
- const logFile = external_node_path_default().join(getLogDirectory(), `${topicFileName}.log`);
102
- const existingStream = logStreams.get(topicFileName);
103
- if (existingStream && logStreamPaths.get(topicFileName) !== logFile) {
104
- existingStream.end();
98
+ function getLogStream(logFile) {
99
+ if (unavailableLogStreams.has(logFile)) return null;
100
+ const topicFileName = external_node_path_default().basename(logFile);
101
+ const existing = logStreams.get(topicFileName);
102
+ const previousPath = logStreamPaths.get(topicFileName);
103
+ if (existing && previousPath !== logFile) {
104
+ if (previousPath && backpressuredLogStreams.get(previousPath) === existing) existing.once('finish', ()=>{
105
+ if (backpressuredLogStreams.get(previousPath) === existing) backpressuredLogStreams.delete(previousPath);
106
+ });
107
+ existing.end();
105
108
  logStreams.delete(topicFileName);
106
109
  logStreamPaths.delete(topicFileName);
107
110
  }
@@ -110,8 +113,8 @@ function getLogStream(topic) {
110
113
  flags: 'a'
111
114
  });
112
115
  stream.on('error', ()=>{
113
- unavailableLogStreams.add(topicFileName);
114
- backpressuredLogStreams.delete(topicFileName);
116
+ unavailableLogStreams.add(logFile);
117
+ if (backpressuredLogStreams.get(logFile) === stream) backpressuredLogStreams.delete(logFile);
115
118
  if (logStreams.get(topicFileName) === stream) {
116
119
  logStreams.delete(topicFileName);
117
120
  logStreamPaths.delete(topicFileName);
@@ -125,8 +128,9 @@ function getLogStream(topic) {
125
128
  function writeLogToFile(topic, message) {
126
129
  if (!external_utils_js_namespaceObject.ifInNode) return;
127
130
  const topicFileName = topic.replace(/:/g, '-');
128
- if (backpressuredLogStreams.has(topicFileName)) return;
129
- const stream = getLogStream(topic);
131
+ const logFile = external_node_path_default().join(getLogDirectory(), `${topicFileName}.log`);
132
+ if (backpressuredLogStreams.has(logFile)) return;
133
+ const stream = getLogStream(logFile);
130
134
  if (!stream) return;
131
135
  const now = new Date();
132
136
  const isoDate = now.toLocaleDateString('sv-SE');
@@ -140,14 +144,14 @@ function writeLogToFile(topic, message) {
140
144
  const localISOTime = `${isoDate}T${isoTime}.${milliseconds}${timezoneString}`;
141
145
  try {
142
146
  if (!stream.write(`[${localISOTime}] ${message}\n`)) {
143
- backpressuredLogStreams.add(topicFileName);
147
+ backpressuredLogStreams.set(logFile, stream);
144
148
  stream.once('drain', ()=>{
145
- backpressuredLogStreams.delete(topicFileName);
149
+ if (backpressuredLogStreams.get(logFile) === stream) backpressuredLogStreams.delete(logFile);
146
150
  });
147
151
  }
148
152
  } catch {
149
- unavailableLogStreams.add(topicFileName);
150
- backpressuredLogStreams.delete(topicFileName);
153
+ unavailableLogStreams.add(logFile);
154
+ if (backpressuredLogStreams.get(logFile) === stream) backpressuredLogStreams.delete(logFile);
151
155
  }
152
156
  }
153
157
  function printConsoleWarning(topic, args, warning) {
@@ -6,6 +6,10 @@ export declare const defaultRunDirName = "midscene_run";
6
6
  */
7
7
  export declare const setMidsceneRunDir: (runDir: string | undefined) => void;
8
8
  export declare const getMidsceneRunDir: () => string;
9
+ /** Resolve Test paths against its project; standalone callers use their cwd. */
10
+ export declare const resolveMidsceneRunDir: (baseDir: string) => string;
11
+ /** Isolate concurrent Test runs without changing process.env or the app root. */
12
+ export declare const runWithMidsceneRunDir: <T>(runDir: string, run: () => T) => T;
9
13
  export declare const getMidsceneRunBaseDir: () => string;
10
14
  /**
11
15
  * Get the path to the midscene_run directory or a subdirectory within it.
@@ -14,6 +18,6 @@ export declare const getMidsceneRunBaseDir: () => string;
14
18
  * @param subdir - Optional subdirectory name (e.g., 'log', 'report')
15
19
  * @returns The absolute path to the requested directory
16
20
  */
17
- export declare const getMidsceneRunSubDir: (subdir: "dump" | "cache" | "report" | "tmp" | "log" | "output") => string;
21
+ export declare const getMidsceneRunSubDir: (subdir: "dump" | "cache" | "report" | "tmp" | "log" | "output" | "test-results") => string;
18
22
  export declare const ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = "NOT_IMPLEMENTED_AS_DESIGNED";
19
23
  //# sourceMappingURL=common.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAIhD;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,GAAI,QAAQ,MAAM,GAAG,SAAS,KAAG,IAE9D,CAAC;AAEF,eAAO,MAAM,iBAAiB,cAQ7B,CAAC;AAEF,eAAO,MAAM,qBAAqB,cAmBjC,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,KAAK,GAAG,KAAK,GAAG,QAAQ,KAC7D,MAaF,CAAC;AAEF,eAAO,MAAM,sCAAsC,gCACpB,CAAC"}
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAgBhD;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,GAAI,QAAQ,MAAM,GAAG,SAAS,KAAG,IAE9D,CAAC;AAEF,eAAO,MAAM,iBAAiB,cAW7B,CAAC;AAEF,gFAAgF;AAChF,eAAO,MAAM,qBAAqB,GAAI,SAAS,MAAM,KAAG,MACI,CAAC;AAE7D,iFAAiF;AACjF,eAAO,MAAM,qBAAqB,GAAI,CAAC,EAAE,QAAQ,MAAM,EAAE,KAAK,MAAM,CAAC,KAAG,CACJ,CAAC;AAErE,eAAO,MAAM,qBAAqB,cAUjC,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,GAC/B,QACI,MAAM,GACN,OAAO,GACP,QAAQ,GACR,KAAK,GACL,KAAK,GACL,QAAQ,GACR,cAAc,KACjB,MAaF,CAAC;AAEF,eAAO,MAAM,sCAAsC,gCACpB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAUA,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,qBAAqB,GAC7B;IAAE,IAAI,EAAE,sBAAsB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,KAAK,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,EACtC,OAAO,eAAe,EACtB,KAAK,MAAM,CAAC,KACX,CAOF,CAAC;AAEF,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAI/C;AAcD;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,CAAC,MAAM,MAAM,CAAC,GAAG,SAAS,GACnC,IAAI,CAWN;AA8FD,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;AA0BzD,wBAAgB,QAAQ,CACtB,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,qBAAqB,CAAA;CAAE,GAC/D,aAAa,CAwCf;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAM/C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midscene/shared",
3
- "version": "1.17.5",
3
+ "version": "1.17.7",
4
4
  "repository": "https://github.com/web-infra-dev/midscene",
5
5
  "homepage": "https://midscenejs.com/",
6
6
  "types": "./dist/types/index.d.ts",
package/src/common.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { existsSync, mkdirSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
2
  import path from 'node:path';
3
+ import { createConsoleContext } from '#console-context';
4
4
  // do not import getBasicEnvValue and MIDSCENE_RUN_DIR directly from ./env,
5
5
  // because it will cause circular dependency
6
6
  import { getBasicEnvValue } from './env/basic';
@@ -9,7 +9,19 @@ import { ifInNode } from './utils';
9
9
 
10
10
  export const defaultRunDirName = 'midscene_run';
11
11
  let configuredRunDir: string | undefined;
12
- // Define locally for now to avoid import issues
12
+ const contextKey = Symbol.for('@midscene/shared/run-directory');
13
+ const host = globalThis as typeof globalThis & {
14
+ [contextKey]?: ReturnType<typeof createConsoleContext<string>>;
15
+ };
16
+ // Configs may load ESM SDKs while the CLI uses CJS. Share their async scope.
17
+ host[contextKey] ??= createConsoleContext<string>();
18
+ const runDirectoryContext = host[contextKey];
19
+
20
+ const validateRunDir = (value: string): string => {
21
+ if (typeof value !== 'string' || !value.trim())
22
+ throw new TypeError('Midscene run directory must be a non-empty path.');
23
+ return value;
24
+ };
13
25
 
14
26
  /**
15
27
  * Sets the run directory for the current process without changing the
@@ -17,7 +29,7 @@ let configuredRunDir: string | undefined;
17
29
  * behavior.
18
30
  */
19
31
  export const setMidsceneRunDir = (runDir: string | undefined): void => {
20
- configuredRunDir = runDir;
32
+ configuredRunDir = runDir === undefined ? undefined : validateRunDir(runDir);
21
33
  };
22
34
 
23
35
  export const getMidsceneRunDir = () => {
@@ -25,28 +37,30 @@ export const getMidsceneRunDir = () => {
25
37
  return '';
26
38
  }
27
39
 
28
- return (
29
- configuredRunDir ?? getBasicEnvValue(MIDSCENE_RUN_DIR) ?? defaultRunDirName
40
+ return validateRunDir(
41
+ runDirectoryContext.getStore() ??
42
+ configuredRunDir ??
43
+ getBasicEnvValue(MIDSCENE_RUN_DIR) ??
44
+ defaultRunDirName,
30
45
  );
31
46
  };
32
47
 
48
+ /** Resolve Test paths against its project; standalone callers use their cwd. */
49
+ export const resolveMidsceneRunDir = (baseDir: string): string =>
50
+ path.resolve(baseDir, validateRunDir(getMidsceneRunDir()));
51
+
52
+ /** Isolate concurrent Test runs without changing process.env or the app root. */
53
+ export const runWithMidsceneRunDir = <T>(runDir: string, run: () => T): T =>
54
+ runDirectoryContext.run(path.resolve(validateRunDir(runDir)), run);
55
+
33
56
  export const getMidsceneRunBaseDir = () => {
34
57
  if (!ifInNode) {
35
58
  return '';
36
59
  }
37
60
 
38
- let basePath = path.resolve(process.cwd(), getMidsceneRunDir());
39
-
40
- // Create a base directory
41
- if (!existsSync(basePath)) {
42
- try {
43
- mkdirSync(basePath, { recursive: true });
44
- } catch (error) {
45
- // console.error(`Failed to create ${runDirName} directory: ${error}`);
46
- basePath = path.join(tmpdir(), defaultRunDirName);
47
- mkdirSync(basePath, { recursive: true });
48
- }
49
- }
61
+ const basePath = path.resolve(process.cwd(), getMidsceneRunDir());
62
+ // A configured root is authoritative: report filesystem errors to its caller.
63
+ mkdirSync(basePath, { recursive: true });
50
64
 
51
65
  return basePath;
52
66
  };
@@ -59,7 +73,14 @@ export const getMidsceneRunBaseDir = () => {
59
73
  * @returns The absolute path to the requested directory
60
74
  */
61
75
  export const getMidsceneRunSubDir = (
62
- subdir: 'dump' | 'cache' | 'report' | 'tmp' | 'log' | 'output',
76
+ subdir:
77
+ | 'dump'
78
+ | 'cache'
79
+ | 'report'
80
+ | 'tmp'
81
+ | 'log'
82
+ | 'output'
83
+ | 'test-results',
63
84
  ): string => {
64
85
  if (!ifInNode) {
65
86
  return '';
package/src/logger.ts CHANGED
@@ -83,7 +83,7 @@ let logDirectoryResolver: (() => string) | undefined;
83
83
  // main process can keep running while macOS has deprioritized a backgrounded
84
84
  // app, so retaining diagnostic logs here can otherwise grow without bound.
85
85
  // Drop best-effort logs until the stream drains instead.
86
- const backpressuredLogStreams = new Set<string>();
86
+ const backpressuredLogStreams = new Map<string, fs.WriteStream>();
87
87
  const unavailableLogStreams = new Set<string>();
88
88
  // Map to store debug instances
89
89
  const debugInstances = new Map<string, DebugFunction>();
@@ -115,15 +115,26 @@ function getLogDirectory(): string {
115
115
  }
116
116
 
117
117
  // Function to get or create a log stream
118
- function getLogStream(topic: string): fs.WriteStream | null {
119
- const topicFileName = topic.replace(/:/g, '-');
120
- if (unavailableLogStreams.has(topicFileName)) {
118
+ function getLogStream(logFile: string): fs.WriteStream | null {
119
+ if (unavailableLogStreams.has(logFile)) {
121
120
  return null;
122
121
  }
123
- const logFile = path.join(getLogDirectory(), `${topicFileName}.log`);
124
- const existingStream = logStreams.get(topicFileName);
125
- if (existingStream && logStreamPaths.get(topicFileName) !== logFile) {
126
- existingStream.end();
122
+ const topicFileName = path.basename(logFile);
123
+ const existing = logStreams.get(topicFileName);
124
+ const previousPath = logStreamPaths.get(topicFileName);
125
+ if (existing && previousPath !== logFile) {
126
+ // An ended stream emits finish rather than drain. Keep dropping logs
127
+ // until its queued bytes are flushed, then allow this run to resume.
128
+ if (
129
+ previousPath &&
130
+ backpressuredLogStreams.get(previousPath) === existing
131
+ ) {
132
+ existing.once('finish', () => {
133
+ if (backpressuredLogStreams.get(previousPath) === existing)
134
+ backpressuredLogStreams.delete(previousPath);
135
+ });
136
+ }
137
+ existing.end();
127
138
  logStreams.delete(topicFileName);
128
139
  logStreamPaths.delete(topicFileName);
129
140
  }
@@ -133,8 +144,9 @@ function getLogStream(topic: string): fs.WriteStream | null {
133
144
  // Logging must remain best-effort, so disable this topic after a file error
134
145
  // rather than repeatedly queuing writes to a broken stream.
135
146
  stream.on('error', () => {
136
- unavailableLogStreams.add(topicFileName);
137
- backpressuredLogStreams.delete(topicFileName);
147
+ unavailableLogStreams.add(logFile);
148
+ if (backpressuredLogStreams.get(logFile) === stream)
149
+ backpressuredLogStreams.delete(logFile);
138
150
  if (logStreams.get(topicFileName) === stream) {
139
151
  logStreams.delete(topicFileName);
140
152
  logStreamPaths.delete(topicFileName);
@@ -151,11 +163,12 @@ function writeLogToFile(topic: string, message: string): void {
151
163
  if (!ifInNode) return;
152
164
 
153
165
  const topicFileName = topic.replace(/:/g, '-');
154
- if (backpressuredLogStreams.has(topicFileName)) {
166
+ const logFile = path.join(getLogDirectory(), `${topicFileName}.log`);
167
+ if (backpressuredLogStreams.has(logFile)) {
155
168
  return;
156
169
  }
157
170
 
158
- const stream = getLogStream(topic);
171
+ const stream = getLogStream(logFile);
159
172
  if (!stream) return;
160
173
  // Generate ISO format timestamp with local timezone
161
174
  const now = new Date();
@@ -176,14 +189,16 @@ function writeLogToFile(topic: string, message: string): void {
176
189
  const localISOTime = `${isoDate}T${isoTime}.${milliseconds}${timezoneString}`;
177
190
  try {
178
191
  if (!stream.write(`[${localISOTime}] ${message}\n`)) {
179
- backpressuredLogStreams.add(topicFileName);
192
+ backpressuredLogStreams.set(logFile, stream);
180
193
  stream.once('drain', () => {
181
- backpressuredLogStreams.delete(topicFileName);
194
+ if (backpressuredLogStreams.get(logFile) === stream)
195
+ backpressuredLogStreams.delete(logFile);
182
196
  });
183
197
  }
184
198
  } catch {
185
- unavailableLogStreams.add(topicFileName);
186
- backpressuredLogStreams.delete(topicFileName);
199
+ unavailableLogStreams.add(logFile);
200
+ if (backpressuredLogStreams.get(logFile) === stream)
201
+ backpressuredLogStreams.delete(logFile);
187
202
  }
188
203
  }
189
204