@midscene/test 1.16.0 → 1.16.1

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 +1 @@
1
- {"version":3,"file":"cli/index.mjs","sources":["../../../src/engine/registry.ts","../../../src/cli/test-project.ts","../../../src/parser/identifiers.ts","../../../src/parser/normalize.ts","../../../src/parser/source.ts","../../../src/parser/variables.ts","../../../src/parser/collect.ts","../../../src/cli/result-store.ts","../../../src/cli/project-preparation.ts","../../../src/cli/prepare-test-run.ts","../../../src/report/result-markdown.ts","../../../src/cli/document-invocation.ts","../../../src/cli/operation-journal.ts","../../../src/cli/run-prepared-project.ts","../../../src/cli/test-project-runner.ts"],"sourcesContent":["import { NodeRegistry as CoreNodeRegistry } from '@midscene/core/internal/test-runner';\nimport type { NodeDefinition } from '../node/types';\n\nexport type NodeRegistry = Omit<\n CoreNodeRegistry,\n 'get' | 'require' | 'register' | 'definitions'\n> & {\n get(name: string): NodeDefinition<any, any> | undefined;\n require(name: string): NodeDefinition<any, any>;\n register<TInput, TData>(node: NodeDefinition<TInput, TData>): NodeRegistry;\n definitions(): readonly NodeDefinition<any, any, any>[];\n};\nexport const NodeRegistry: {\n new (nodes?: readonly NodeDefinition<any, any>[]): NodeRegistry;\n} = CoreNodeRegistry;\n","import { dirname, isAbsolute, resolve, sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { require as tsxRequire } from 'tsx/cjs/api';\nimport { NodeRegistry } from '../engine/registry';\nimport type { NodeDefinition } from '../node/types';\n\nimport type {\n JsonValue,\n ProjectSetupDefinition,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nexport type {\n JsonPrimitive,\n JsonValue,\n ProjectSetupContext,\n ProjectSetupDefinition,\n ProjectTeardown,\n ProjectTeardownContext,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nimport type { ExecutionProjectDefinition as CoreExecutionProjectDefinition } from '@midscene/core/internal/test-runner';\n\nexport type ExecutionProjectDefinition<TContext = unknown> = Omit<\n CoreExecutionProjectDefinition<TContext>,\n 'nodes'\n> & {\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n};\n\nexport interface TestOptions {\n maxConcurrency?: number;\n bail?: number;\n testTimeout?: number;\n}\n\nexport interface ResolvedTestOptions {\n maxConcurrency: number;\n bail: number;\n testTimeout: number;\n}\n\nexport interface TestOutputDefinition {\n reportDir?: string;\n}\n\nexport interface ResolvedTestOutputDefinition {\n reportDir: string;\n}\n\nconst projectIdFromIndex = (index: number): string => `project-${index}`;\n\nexport interface TestProjectDefinition<TContext = undefined> {\n setup?: ProjectSetupDefinition<TContext>;\n projects?: readonly ExecutionProjectDefinition<TContext>[];\n test?: TestOptions;\n output?: TestOutputDefinition;\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n}\n\nexport interface LoadedExecutionProject<TProjectContext = unknown>\n extends ResolvedExecutionProject<TProjectContext> {\n /** Effective Nodes: globals plus project-local overrides. */\n readonly nodes: NodeRegistry;\n}\n\nexport interface LoadedTestProject<TContext = undefined> {\n projects: readonly LoadedExecutionProject<TContext>[];\n hasExplicitProjects: boolean;\n test: ResolvedTestOptions;\n output: ResolvedTestOutputDefinition;\n nodes: NodeRegistry;\n resolveNode(name: string): NodeDefinition<any, any, TContext> | undefined;\n}\n\nexport const defineTestProject = <TContext = undefined>(\n definition: TestProjectDefinition<TContext>,\n): TestProjectDefinition<TContext> => definition;\n\nexport const defineProjectSetup = <TProjectContext>(\n definition: ProjectSetupDefinition<TProjectContext>,\n): ProjectSetupDefinition<TProjectContext> => definition;\n\nconst getDefaultExport = (loaded: unknown, absolutePath: string): unknown => {\n if (typeof loaded === 'object' && loaded !== null && 'default' in loaded) {\n const defaultExport = (loaded as { default: unknown }).default;\n if (\n typeof defaultExport === 'object' &&\n defaultExport !== null &&\n '__esModule' in defaultExport\n ) {\n if ('default' in defaultExport) {\n return (defaultExport as { default: unknown }).default;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n }\n return defaultExport;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowedKeys: readonly string[],\n label: string,\n): void => {\n const allowed = new Set(allowedKeys);\n const unknown = Object.keys(value).find((key) => !allowed.has(key));\n if (unknown) {\n throw new TypeError(\n `Midscene config ${label}.${unknown} is not supported.`,\n );\n }\n};\n\nconst isAbsolutePattern = (pattern: string): boolean =>\n isAbsolute(pattern) ||\n /^[A-Za-z]:[\\\\/]/.test(pattern) ||\n pattern.startsWith('\\\\\\\\');\n\nconst validatePatterns = (\n value: unknown,\n field: 'include' | 'exclude',\n label = 'files',\n allowEmptyInclude = false,\n): readonly string[] => {\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n if (field === 'include' && value.length === 0 && !allowEmptyInclude) {\n throw new TypeError(\n `Midscene config ${label}.include must be a non-empty array.`,\n );\n }\n\n return value.map((pattern, index) => {\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n if (isAbsolutePattern(pattern)) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be relative to the project root.`,\n );\n }\n if (pattern.split(/[\\\\/]/).includes('..')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must not contain a \"..\" path segment.`,\n );\n }\n if (pattern.includes('\\\\')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must use POSIX path separators (/).`,\n );\n }\n if (pattern.startsWith('!')) {\n if (field === 'include') {\n throw new TypeError(\n `Midscene config ${label}.include[${index}] must not be a negated pattern. Use files.exclude instead.`,\n );\n }\n throw new TypeError(\n `Midscene config ${label}.exclude[${index}] must not be a negated pattern.`,\n );\n }\n return pattern;\n });\n};\n\nexport const validateTestFileSelection = (\n value: unknown,\n label = 'files',\n): TestFileSelection | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['include', 'exclude'], label);\n const include = validatePatterns(value.include, 'include', label);\n const exclude =\n value.exclude === undefined\n ? undefined\n : validatePatterns(value.exclude, 'exclude', label);\n return Object.freeze({\n include: Object.freeze(include),\n ...(exclude ? { exclude: Object.freeze(exclude) } : {}),\n });\n};\n\nconst validateTagList = (\n value: unknown,\n field: 'include' | 'exclude',\n label: string,\n): readonly string[] => {\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n return value.map((tag, index) => {\n if (typeof tag !== 'string' || tag.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n return tag;\n });\n};\n\nconst validateTagSelection = (\n value: unknown,\n label: string,\n): Readonly<Required<TestTagSelection>> => {\n if (value === undefined) return Object.freeze({ include: [], exclude: [] });\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n return Object.freeze({\n include: Object.freeze(validateTagList(value.include, 'include', label)),\n exclude: Object.freeze(validateTagList(value.exclude, 'exclude', label)),\n });\n};\n\nfunction assertJsonValue(\n value: unknown,\n path: string,\n seen: Set<unknown>,\n): asserts value is JsonValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean'\n ) {\n return;\n }\n if (typeof value === 'number') {\n if (Number.isFinite(value)) return;\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (typeof value !== 'object' || value === undefined) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n ) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (seen.has(value)) {\n throw new TypeError(`Midscene config ${path} must not contain cycles.`);\n }\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertJsonValue(item, `${path}[${index}]`, seen),\n );\n } else {\n for (const [key, child] of Object.entries(value)) {\n assertJsonValue(child, `${path}.${key}`, seen);\n }\n }\n seen.delete(value);\n}\n\nconst deepFreezeJson = <T extends JsonValue>(value: T): T => {\n if (typeof value === 'object' && value !== null) {\n for (const child of Object.values(value)) deepFreezeJson(child);\n Object.freeze(value);\n }\n return value;\n};\n\nconst validateVariables = (\n value: unknown,\n label: string,\n): Readonly<Record<string, JsonValue>> => {\n if (value === undefined) return Object.freeze({});\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n assertJsonValue(value, label, new Set());\n return deepFreezeJson(value as Record<string, JsonValue>);\n};\n\nconst validateSetup = <TSetup>(\n value: unknown,\n label: string,\n): TSetup | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['name', 'setup'], label);\n if (typeof value.name !== 'string' || value.name.trim().length === 0) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (typeof value.setup !== 'function') {\n throw new TypeError(`Midscene config ${label}.setup must be a function.`);\n }\n return value as unknown as TSetup;\n};\n\nconst validatePositiveInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) <= 0) {\n throw new TypeError(`Midscene config ${label} must be a positive integer.`);\n }\n return value as number;\n};\n\nconst validateNonNegativeInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) < 0) {\n throw new TypeError(\n `Midscene config ${label} must be a non-negative integer.`,\n );\n }\n return value as number;\n};\n\nconst validateExecutionProjects = <TProjectContext>(\n value: unknown,\n defaultSetup: unknown,\n globalNodes: NodeRegistry,\n): {\n projects: readonly LoadedExecutionProject<TProjectContext>[];\n hasExplicitProjects: boolean;\n} => {\n if (value === undefined) {\n const setup = validateSetup<ProjectSetupDefinition<TProjectContext>>(\n defaultSetup,\n 'setup',\n );\n return {\n hasExplicitProjects: false,\n projects: Object.freeze([\n Object.freeze({\n projectId: projectIdFromIndex(0),\n name: 'default',\n ...(setup ? { setup } : {}),\n tags: Object.freeze({ include: [], exclude: [] }),\n retry: 0,\n variables: Object.freeze({}),\n nodes: new NodeRegistry(globalNodes.definitions()),\n }),\n ]),\n };\n }\n if (defaultSetup !== undefined) {\n throw new TypeError(\n 'Midscene config setup cannot be used together with projects. Move setup to projects[].setup.',\n );\n }\n if (!Array.isArray(value) || value.length === 0) {\n throw new TypeError(\n 'Midscene config projects must be a non-empty array when declared.',\n );\n }\n const names = new Set<string>();\n const projects = value.map((candidate, index) => {\n const label = `projects[${index}]`;\n if (!isRecord(candidate)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(\n candidate,\n ['name', 'setup', 'nodes', 'files', 'tags', 'retry', 'variables'],\n label,\n );\n if (\n typeof candidate.name !== 'string' ||\n candidate.name.trim().length === 0\n ) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (names.has(candidate.name)) {\n throw new TypeError(\n `Midscene config project name \"${candidate.name}\" must be unique.`,\n );\n }\n names.add(candidate.name);\n const files = validateTestFileSelection(candidate.files, `${label}.files`);\n if (candidate.nodes !== undefined && !Array.isArray(candidate.nodes)) {\n throw new TypeError(`Midscene config ${label}.nodes must be an array.`);\n }\n const localNodes = new NodeRegistry(\n candidate.nodes as NodeDefinition[] | undefined,\n );\n const nodes = new NodeRegistry([\n ...globalNodes.definitions().filter((node) => !localNodes.has(node.name)),\n ...localNodes.definitions(),\n ]);\n return Object.freeze({\n projectId: projectIdFromIndex(index),\n name: candidate.name,\n nodes,\n ...(files ? { files } : {}),\n tags: validateTagSelection(candidate.tags, `${label}.tags`),\n retry: validateNonNegativeInteger(candidate.retry, 0, `${label}.retry`),\n variables: validateVariables(candidate.variables, `${label}.variables`),\n ...(candidate.setup === undefined\n ? {}\n : {\n setup: validateSetup<ProjectSetupDefinition<TProjectContext>>(\n candidate.setup,\n `${label}.setup`,\n )!,\n }),\n });\n });\n return { projects: Object.freeze(projects), hasExplicitProjects: true };\n};\n\nconst validateTestOptions = (value: unknown): ResolvedTestOptions => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config test must be an object.');\n }\n const candidate = value ?? {};\n return Object.freeze({\n maxConcurrency: validatePositiveInteger(\n (candidate as Record<string, unknown>).maxConcurrency,\n 1,\n 'test.maxConcurrency',\n ),\n bail: validateNonNegativeInteger(\n (candidate as Record<string, unknown>).bail,\n 0,\n 'test.bail',\n ),\n testTimeout: validatePositiveInteger(\n (candidate as Record<string, unknown>).testTimeout,\n 120_000,\n 'test.testTimeout',\n ),\n });\n};\n\nconst validateOutputPath = (\n value: unknown,\n fallback: string,\n label: string,\n): string => {\n if (value === undefined) return fallback;\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new TypeError(`Midscene config ${label} must be non-empty.`);\n }\n return value;\n};\n\nconst validateOutput = (value: unknown): ResolvedTestOutputDefinition => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config output must be an object.');\n }\n const candidate = (value ?? {}) as Record<string, unknown>;\n rejectUnknownKeys(candidate, ['reportDir'], 'output');\n return Object.freeze({\n reportDir: validateOutputPath(\n candidate.reportDir,\n './midscene_run/report',\n 'output.reportDir',\n ),\n });\n};\n\nconst validateTestProjectDefinition = <TContext>(\n definition: unknown,\n): LoadedTestProject<TContext> => {\n if (!isRecord(definition)) {\n throw new TypeError('Midscene config must default export an object.');\n }\n if (definition.nodes !== undefined && !Array.isArray(definition.nodes)) {\n throw new TypeError('Midscene config nodes must be an array.');\n }\n if ('setupWorkflow' in definition) {\n throw new TypeError(\n 'Midscene config setupWorkflow is no longer supported. Use setup or projects[].setup instead.',\n );\n }\n if ('setupDocument' in definition) {\n throw new TypeError(\n 'Midscene config setupDocument is not supported. Use setup or projects[].setup for resources, and beforeAll/afterAll for document lifecycle steps.',\n );\n }\n if ('root' in definition) {\n throw new TypeError(\n 'Midscene config root is not supported. Pass the Test Project directory to midscene-test instead.',\n );\n }\n if ('files' in definition) {\n throw new TypeError(\n 'Midscene config files is not supported at the root. Move it to projects[].files.',\n );\n }\n if ('testRunner' in definition) {\n throw new TypeError(\n 'Midscene config testRunner is not supported. Rename it to test.',\n );\n }\n rejectUnknownKeys(\n definition,\n ['setup', 'projects', 'test', 'output', 'nodes'],\n 'root',\n );\n const nodes = new NodeRegistry(\n definition.nodes as NodeDefinition[] | undefined,\n );\n const resolvedProjects = validateExecutionProjects<TContext>(\n definition.projects,\n definition.setup,\n nodes,\n );\n return {\n ...resolvedProjects,\n test: validateTestOptions(definition.test),\n output: validateOutput(definition.output),\n nodes,\n resolveNode: (name) =>\n nodes.get(name) as NodeDefinition<any, any, TContext> | undefined,\n };\n};\n\nconst assertSupportedConfig = (absolutePath: string): '.ts' | '.mjs' => {\n if (!absolutePath.endsWith('.ts') && !absolutePath.endsWith('.mjs')) {\n const extension = absolutePath.match(/(\\.[^./\\\\]+)$/)?.[1] ?? '(none)';\n throw new TypeError(\n `Unsupported Midscene config extension: ${extension}. Supported extensions: .ts, .mjs.`,\n );\n }\n return absolutePath.endsWith('.mjs') ? '.mjs' : '.ts';\n};\n\nconst canRetryWithCjsLoader = (error: unknown): error is Error => {\n if (!(error instanceof Error)) return false;\n const errorCode = (error as Error & { code?: string }).code;\n return (\n (error instanceof SyntaxError &&\n /^Unexpected (?:identifier|reserved word|token)/.test(error.message)) ||\n errorCode === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' ||\n (errorCode === 'ERR_UNKNOWN_FILE_EXTENSION' &&\n /^Unknown file extension\\b/.test(error.message))\n );\n};\n\nexport async function loadTestProject<TContext = undefined>(\n configPath?: string,\n): Promise<LoadedTestProject<TContext>> {\n if (!configPath) {\n return validateTestProjectDefinition<TContext>({\n nodes: [],\n });\n }\n\n const absolutePath = resolve(configPath);\n const extension = assertSupportedConfig(absolutePath);\n let loaded: unknown;\n try {\n if (extension === '.mjs') {\n loaded = await import(pathToFileURL(absolutePath).href);\n } else {\n // Select tsx's ESM entry even when this loader is built as CommonJS.\n // Its CommonJS entry can resolve the async loader relative to the wrong directory.\n const { tsImport } = await import('tsx/esm/api');\n loaded = await tsImport(pathToFileURL(absolutePath).href, {\n parentURL: pathToFileURL(`${dirname(absolutePath)}${sep}`).href,\n tsconfig: false,\n });\n }\n } catch (error) {\n try {\n if (extension === '.mjs' || !canRetryWithCjsLoader(error)) throw error;\n loaded = tsxRequire(absolutePath, pathToFileURL(absolutePath));\n } catch (fallbackError) {\n const message =\n fallbackError instanceof Error ? `: ${fallbackError.message}` : '';\n throw new Error(\n `Failed to load Midscene config \"${absolutePath}\"${message}`,\n { cause: fallbackError },\n );\n }\n }\n\n return validateTestProjectDefinition<TContext>(\n getDefaultExport(loaded, absolutePath),\n );\n}\n","import { createHash } from 'node:crypto';\n\n/** Internal invocation identity keeps repeated legacy files distinct. */\nexport const createCaseInvocationId = (\n projectId: string,\n sourcePath: string,\n caseIndex: number,\n invocationIndex = 0,\n): string =>\n createHash('sha256')\n .update(\n JSON.stringify([\n projectId,\n sourcePath,\n caseIndex,\n ...(invocationIndex ? [invocationIndex] : []),\n ]),\n )\n .digest('hex');\n\nexport const createDocumentInvocationId = (\n projectId: string,\n sourcePath: string,\n invocationIndex = 0,\n): string =>\n createHash('sha256')\n .update(\n JSON.stringify([\n projectId,\n sourcePath,\n ...(invocationIndex ? [invocationIndex] : []),\n ]),\n )\n .digest('hex');\n","import {\n type ResolveNodeForNormalization,\n normalizeStep as coreNormalizeStep,\n normalizeSteps as coreNormalizeSteps,\n} from '@midscene/core/internal/test-runner';\nimport type { NormalizedStep } from './types';\nexport type { ResolveNodeForNormalization } from '@midscene/core/internal/test-runner';\n\nexport const normalizeStep: (\n value: unknown,\n index?: number,\n resolveNode?: ResolveNodeForNormalization,\n) => NormalizedStep = coreNormalizeStep;\nexport const normalizeSteps: (\n values: unknown,\n resolveNode?: ResolveNodeForNormalization,\n) => NormalizedStep[] = coreNormalizeSteps;\n","import type { TestRunReportValue } from '@midscene/core';\nimport {\n isReportSecretKey,\n sanitizeReportText,\n} from '@midscene/core/internal/test-runner';\nimport { JSON_SCHEMA, load } from 'js-yaml';\n\ninterface SourceNode {\n start: number;\n end: number;\n value: unknown;\n children: SourceNode[];\n}\n\n/** Keep author formatting while redacting values by parsed YAML keys, including aliases. */\nexport function parseWorkflowSource(source: string): {\n parsed: unknown;\n sourceYaml: TestRunReportValue;\n} {\n const stack: SourceNode[] = [];\n const nodes: SourceNode[] = [];\n const sensitiveNodes = new Set<SourceNode>();\n const sensitiveValues = new Set<unknown>();\n const redactedPaths = new Set<string>();\n // js-yaml removes the BOM before reporting source positions.\n const sourceOffset = source.charCodeAt(0) === 0xfeff ? 1 : 0;\n const parsed = load(source, {\n schema: JSON_SCHEMA,\n listener(event, state) {\n if (event === 'open') {\n stack.push({\n start: state.position + sourceOffset,\n end: 0,\n value: null,\n children: [],\n });\n return;\n }\n const node = stack.pop()!;\n node.end = state.position + sourceOffset;\n node.value = state.result;\n stack.at(-1)?.children.push(node);\n nodes.push(node);\n if (state.kind !== 'mapping') return;\n for (let index = 0; index < node.children.length; index += 2) {\n const key = node.children[index].value;\n const value = node.children[index + 1];\n if (typeof key !== 'string' || !isReportSecretKey(key) || !value)\n continue;\n sensitiveNodes.add(value);\n if (value.value !== null) sensitiveValues.add(value.value);\n redactedPaths.add(`$..[${JSON.stringify(key)}]`);\n }\n },\n });\n // Redact the definition as well when a secret value refers to a YAML anchor.\n const ranges = nodes\n .filter(\n (node) => sensitiveNodes.has(node) || sensitiveValues.has(node.value),\n )\n .sort((left, right) => left.start - right.start || right.end - left.end);\n let offset = 0;\n let redacted = '';\n for (const range of ranges) {\n if (range.start < offset) continue;\n const text = source.slice(range.start, range.end);\n const leading = text.match(/^\\s*/)?.[0] ?? '';\n const trailing = text.slice(leading.length).match(/\\s*$/)?.[0] ?? '';\n redacted += `${source.slice(offset, range.start)}${leading}\"[REDACTED]\"${trailing}`;\n offset = range.end;\n }\n redacted += source.slice(offset);\n const value = sanitizeReportText(redacted, 64 * 1024);\n return {\n parsed,\n sourceYaml: {\n value,\n ...(redactedPaths.size ? { redactedPaths: [...redactedPaths] } : {}),\n ...(value !== redacted ? { truncatedPaths: ['$'] } : {}),\n },\n };\n}\n","import type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\n\nexport interface VariableResolutionLocation {\n projectName: string;\n sourcePath: string;\n phase: 'beforeAll' | 'beforeEach' | 'steps' | 'afterEach' | 'afterAll';\n stepIndex: number;\n caseIndex?: number;\n}\n\nexport interface ResolveWorkflowVariablesOptions {\n variables?: Readonly<Record<string, JsonValue>>;\n env?: Readonly<NodeJS.ProcessEnv>;\n location: VariableResolutionLocation;\n}\n\nconst interpolationExpression =\n /\\$\\{\\{([A-Za-z_][A-Za-z0-9_]*)\\}\\}|\\$\\{([^{}]+)\\}/g;\nconst exactEnvExpression = /^\\$\\{\\{([A-Za-z_][A-Za-z0-9_]*)\\}\\}$/;\nconst exactProjectExpression = /^\\$\\{([^{}]+)\\}$/;\n\nconst missingVariable = (\n kind: 'environment' | 'project',\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): never => {\n throw new WorkflowParseError(\n `Undefined ${kind} variable \"${name}\" in ${options.location.sourcePath}.`,\n { ...options.location, variable: name, variableKind: kind },\n );\n};\n\nconst projectVariable = (\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): JsonValue => {\n if (!Object.hasOwn(options.variables ?? {}, name)) {\n return missingVariable('project', name, options);\n }\n return options.variables![name];\n};\n\nconst environmentVariable = (\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): string => {\n const value = options.env?.[name];\n if (value === undefined) return missingVariable('environment', name, options);\n return value;\n};\n\nconst interpolationValue = (\n name: string,\n value: JsonValue,\n options: ResolveWorkflowVariablesOptions,\n): string => {\n if (typeof value === 'object' && value !== null) {\n throw new WorkflowParseError(\n `Project variable \"${name}\" must be a primitive when embedded in a string.`,\n {\n ...options.location,\n variable: name,\n variableKind: 'project',\n },\n );\n }\n return String(value);\n};\n\nconst resolveString = (\n value: string,\n options: ResolveWorkflowVariablesOptions,\n): JsonValue => {\n const exactEnv = exactEnvExpression.exec(value);\n if (exactEnv) return environmentVariable(exactEnv[1], options);\n const exactProject = exactProjectExpression.exec(value);\n if (exactProject) return projectVariable(exactProject[1], options);\n\n return value.replace(\n interpolationExpression,\n (_match, environmentName: string | undefined, projectName: string) =>\n environmentName\n ? environmentVariable(environmentName, options)\n : interpolationValue(\n projectName,\n projectVariable(projectName, options),\n options,\n ),\n );\n};\n\nexport const resolveWorkflowVariables = (\n value: unknown,\n options: ResolveWorkflowVariablesOptions,\n): unknown => {\n if (typeof value === 'string') return resolveString(value, options);\n if (Array.isArray(value)) {\n return value.map((child) => resolveWorkflowVariables(child, options));\n }\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n key,\n resolveWorkflowVariables(child, options),\n ]),\n );\n }\n return value;\n};\n","import { readFileSync } from 'node:fs';\nimport { sep } from 'node:path';\nimport { classifyWorkflowDocumentFormat } from '@midscene/core/internal/test-runner';\nimport type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\nimport type { NodeDefinition } from '../node/types';\nimport {\n createCaseInvocationId,\n createDocumentInvocationId,\n} from './identifiers';\nimport { normalizeSteps } from './normalize';\nimport { parseWorkflowSource } from './source';\nimport type {\n CollectedCase,\n CollectedWorkflowDocument,\n WorkflowDocumentSource,\n} from './types';\nimport { resolveWorkflowVariables } from './variables';\n\nexport interface CollectWorkflowDocumentOptions {\n resolveNode(name: string): NodeDefinition<any, any> | undefined;\n variables?: Readonly<Record<string, JsonValue>>;\n env?: Readonly<NodeJS.ProcessEnv>;\n}\n\nconst isMapping = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nexport class NativeWorkflowFormatError extends WorkflowParseError {\n readonly actualFormat: 'legacy' | 'legacy-batch' | 'mixed';\n\n constructor(\n actualFormat: 'legacy' | 'legacy-batch' | 'mixed',\n sourcePath: string,\n ) {\n super(\n actualFormat === 'legacy'\n ? `Legacy tasks/flow YAML is not supported by midscene-test: ${sourcePath}. Run it with \\`midscene ${sourcePath}\\`, or migrate the file to cases/steps.`\n : actualFormat === 'legacy-batch'\n ? `Legacy YAML batch configuration is not a midscene-test workflow document: ${sourcePath}. Run it with \\`midscene --config ${sourcePath}\\`, or migrate it to a native project config.`\n : `A workflow file cannot mix legacy tasks/flow with native cases/steps or lifecycle hooks: ${sourcePath}. Keep the formats in separate files and run each file with its matching command.`,\n { sourcePath, actualFormat, expectedFormat: 'native' },\n );\n this.actualFormat = actualFormat;\n }\n}\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowed: readonly string[],\n label: string,\n) => {\n const allowedSet = new Set(allowed);\n const unknown = Object.keys(value).filter((key) => !allowedSet.has(key));\n if (unknown.length) {\n throw new WorkflowParseError(\n `${label} has unsupported field \"${unknown[0]}\".`,\n { field: unknown[0] },\n );\n }\n};\n\nexport const createCaseId = (\n projectId: string,\n sourcePath: string,\n caseIndex: number,\n): string => createCaseInvocationId(projectId, sourcePath, caseIndex);\n\nexport const createWorkflowDocumentId = (\n projectId: string,\n sourcePath: string,\n): string => createDocumentInvocationId(projectId, sourcePath);\n\nexport function collectWorkflowDocument(\n source: WorkflowDocumentSource,\n options: CollectWorkflowDocumentOptions,\n): CollectedWorkflowDocument {\n let snapshot: ReturnType<typeof parseWorkflowSource>;\n try {\n snapshot = parseWorkflowSource(readFileSync(source.absolutePath, 'utf8'));\n } catch (error) {\n throw new WorkflowParseError(\n `Failed to parse workflow document \"${source.sourcePath}\".`,\n { sourcePath: source.sourcePath },\n error,\n );\n }\n const { parsed, sourceYaml } = snapshot;\n\n if (!isMapping(parsed)) {\n throw new WorkflowParseError('Workflow document must be a mapping.');\n }\n const format = classifyWorkflowDocumentFormat(parsed);\n if (format === 'legacy' || format === 'legacy-batch' || format === 'mixed') {\n throw new NativeWorkflowFormatError(format, source.sourcePath);\n }\n rejectUnknownKeys(\n parsed,\n ['beforeAll', 'beforeEach', 'cases', 'afterEach', 'afterAll'],\n 'Workflow document',\n );\n if (!Array.isArray(parsed.cases) || parsed.cases.length === 0) {\n throw new WorkflowParseError(\n 'Workflow document must contain a non-empty cases array.',\n );\n }\n\n const sourcePath = source.sourcePath.split(sep).join('/');\n const resolveStepVariables = (\n step: ReturnType<typeof normalizeSteps>[number],\n phase: 'beforeAll' | 'beforeEach' | 'steps' | 'afterEach' | 'afterAll',\n stepIndex: number,\n caseIndex?: number,\n ) => ({\n ...step,\n templateInput: step.input,\n input: resolveWorkflowVariables(step.input, {\n variables: options.variables,\n env: options.env ?? process.env,\n location: {\n projectName: source.projectName ?? source.projectId,\n sourcePath,\n phase,\n stepIndex,\n ...(caseIndex === undefined ? {} : { caseIndex }),\n },\n }) as typeof step.input,\n });\n const normalizeLifecycle = (\n phase: 'beforeAll' | 'beforeEach' | 'afterEach' | 'afterAll',\n ) => {\n const value = parsed[phase];\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new WorkflowParseError(\n `Workflow document ${phase} must be an array.`,\n { phase },\n );\n }\n return normalizeSteps(value, options.resolveNode).map(\n (normalized, stepIndex) => {\n const resolved = options.resolveNode(normalized.node);\n if (!resolved) {\n throw new WorkflowParseError(\n `Workflow document ${phase} step ${stepIndex + 1} references unknown node \"${normalized.node}\".`,\n { phase, stepIndex, node: normalized.node },\n );\n }\n return resolveStepVariables(normalized, phase, stepIndex);\n },\n );\n };\n const lifecycle = {\n beforeAll: normalizeLifecycle('beforeAll'),\n beforeEach: normalizeLifecycle('beforeEach'),\n afterEach: normalizeLifecycle('afterEach'),\n afterAll: normalizeLifecycle('afterAll'),\n };\n const ids = new Set<string>();\n const cases: CollectedCase[] = parsed.cases.map((definition, caseIndex) => {\n if (!isMapping(definition)) {\n throw new WorkflowParseError(`Case ${caseIndex + 1} must be a mapping.`, {\n caseIndex,\n });\n }\n rejectUnknownKeys(\n definition,\n ['name', 'tags', 'steps'],\n `Case ${caseIndex + 1}`,\n );\n if (\n typeof definition.name !== 'string' ||\n definition.name.trim().length === 0\n ) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} name must be a non-empty string.`,\n { caseIndex },\n );\n }\n if (!Array.isArray(definition.steps) || definition.steps.length === 0) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} steps must be a non-empty array.`,\n { caseIndex },\n );\n }\n const tags = definition.tags ?? [];\n if (\n !Array.isArray(tags) ||\n tags.some((tag) => typeof tag !== 'string' || tag.trim().length === 0)\n ) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} tags must be an array of non-empty strings.`,\n { caseIndex },\n );\n }\n\n const steps = normalizeSteps(definition.steps, options.resolveNode).map(\n (normalized, stepIndex) => {\n if (!options.resolveNode(normalized.node)) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} step ${stepIndex + 1} references unknown node \"${normalized.node}\".`,\n { caseIndex, stepIndex, node: normalized.node },\n );\n }\n return resolveStepVariables(normalized, 'steps', stepIndex, caseIndex);\n },\n );\n const caseId = createCaseId(source.projectId, sourcePath, caseIndex);\n if (ids.has(caseId)) {\n throw new WorkflowParseError(`Case id collision: ${caseId}.`, {\n caseId,\n });\n }\n ids.add(caseId);\n\n return {\n caseId,\n projectId: source.projectId,\n sourcePath,\n caseIndex,\n definition: {\n name: definition.name,\n tags: tags as string[],\n steps,\n },\n };\n });\n\n return {\n documentId: createWorkflowDocumentId(source.projectId, sourcePath),\n projectId: source.projectId,\n sourcePath,\n sourceYaml,\n lifecycle,\n cases,\n } satisfies CollectedWorkflowDocument;\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport {\n WorkflowPublicationError,\n sanitizeReportError,\n} from '@midscene/core/internal/test-runner';\nimport type { CaseRunResult, WorkflowDocumentRunResult } from '../engine/types';\nimport type { PreparedExecutionProject } from './execution-plan';\nimport type { TestProjectCollectionError, TestProjectRunResult } from './types';\n\nconst writeJson = async (path: string, value: unknown) => {\n try {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, JSON.stringify(value, null, 2));\n } catch (error) {\n throw new WorkflowPublicationError('write-result', path, error);\n }\n};\n\nexport const writeTestRunPlan = (\n runDir: string,\n projects: readonly PreparedExecutionProject[],\n) =>\n writeJson(join(runDir, 'plan.json'), {\n schemaVersion: 1,\n createdAt: new Date().toISOString(),\n projects: projects.map((item) => ({\n projectId: item.project.projectId,\n name: item.project.name,\n documents: item.plans ?? [],\n })),\n });\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nexport const caseAttemptResultPath = (\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n): string =>\n toPosix(\n join(\n projectId,\n 'documents',\n documentId,\n 'cases',\n result.caseId,\n `${result.runId}.json`,\n ),\n );\n\nexport const workflowDocumentResultPath = (\n result: WorkflowDocumentRunResult,\n): string =>\n toPosix(\n join(\n result.projectId,\n 'documents',\n result.documentId,\n result.attemptIndex === undefined\n ? 'document.json'\n : `${result.documentRunId}.json`,\n ),\n );\n\nexport const collectionErrorPath = (\n projectId: string,\n sourcePath: string,\n): string => {\n const id = createHash('sha256')\n .update(JSON.stringify([projectId, sourcePath]))\n .digest('hex');\n return toPosix(join(projectId, 'collection-errors', `${id}.json`));\n};\n\nexport const writeWorkflowDocumentResult = (\n runDir: string,\n result: WorkflowDocumentRunResult,\n) => {\n const { documentRunId: _documentRunId, ...persistedResult } = result;\n return writeJson(\n join(runDir, workflowDocumentResultPath(result)),\n persistedResult,\n );\n};\n\nexport const writeCaseAttemptResult = (\n runDir: string,\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n) => {\n const { runId: attemptId, ...persistedResult } = result;\n return writeJson(\n join(runDir, caseAttemptResultPath(projectId, documentId, result)),\n {\n ...persistedResult,\n attemptId,\n },\n );\n};\n\nexport const writeCollectionError = (\n runDir: string,\n collectionError: TestProjectCollectionError,\n) => {\n return writeJson(\n join(\n runDir,\n collectionErrorPath(\n collectionError.projectId,\n collectionError.sourcePath,\n ),\n ),\n { kind: 'collection-error', ...collectionError },\n );\n};\n\nconst relativeToSummary = (summaryPath: string, target: string): string => {\n const value = relative(dirname(summaryPath), target);\n return toPosix(value || '.');\n};\n\nconst errorJson = sanitizeReportError;\n\nexport interface TestProjectResultFileOptions {\n projectRoot: string;\n configPath?: string;\n result: TestProjectRunResult;\n}\n\nexport const writeTestProjectRunResult = (\n options: TestProjectResultFileOptions,\n) => {\n const { result } = options;\n const fact = (path: string) => toPosix(path);\n\n return writeJson(result.summaryPath, {\n schemaVersion: result.schemaVersion,\n runId: result.runId,\n startedAt: result.startedAt,\n endedAt: result.endedAt,\n durationMs: result.durationMs,\n status: result.status,\n exitCode: result.exitCode,\n ...(result.errors?.length ? { errors: result.errors.map(errorJson) } : {}),\n projectRoot: options.projectRoot,\n ...(options.configPath ? { configPath: options.configPath } : {}),\n factsRoot: '.',\n plan: 'plan.json',\n ...(result.operationLog\n ? {\n operationLog: {\n ...result.operationLog,\n path: relativeToSummary(\n result.summaryPath,\n result.operationLog.path,\n ),\n },\n }\n : {}),\n reportDir: relativeToSummary(result.summaryPath, result.reportDir),\n ...(result.reportPath\n ? { report: relativeToSummary(result.summaryPath, result.reportPath) }\n : {}),\n ...(result.markdownPath\n ? { markdown: relativeToSummary(result.summaryPath, result.markdownPath) }\n : {}),\n summary: result.summary,\n projects: result.projects.map((project) => ({\n projectId: project.projectId,\n name: project.name,\n status: project.status,\n retry: project.retry,\n fileSelection: project.fileSelection,\n tagSelection: project.tagSelection,\n sourceCount: project.sourceCount,\n selectedCaseCount: project.selectedCaseCount,\n filteredCaseCount: project.filteredCaseCount,\n ...(project.lifecycle\n ? {\n lifecycle: {\n status: project.lifecycle.status,\n startedAt: project.lifecycle.startedAt,\n endedAt: project.lifecycle.endedAt,\n durationMs: project.lifecycle.durationMs,\n ...(project.lifecycle.cleanup\n ? { cleanup: project.lifecycle.cleanup }\n : {}),\n ...(project.lifecycle.pendingOperations\n ? { pendingOperations: project.lifecycle.pendingOperations }\n : {}),\n ...(project.lifecycle.setupError\n ? { setupError: errorJson(project.lifecycle.setupError) }\n : {}),\n ...(project.lifecycle.teardownErrors\n ? {\n teardownErrors:\n project.lifecycle.teardownErrors.map(errorJson),\n }\n : {}),\n },\n }\n : {}),\n cases: project.cases.map((outcome) => ({\n ...(outcome.documentRunId\n ? { documentRunId: outcome.documentRunId }\n : {}),\n documentId: outcome.documentId,\n caseId: outcome.caseId,\n sourcePath: outcome.sourcePath,\n caseIndex: outcome.caseIndex,\n name: outcome.name,\n status: outcome.status,\n ...(outcome.notRunReason ? { notRunReason: outcome.notRunReason } : {}),\n ...(outcome.attempts\n ? {\n attempts: outcome.attempts.map((attempt) => ({\n attemptId: attempt.runId,\n attemptIndex: attempt.attemptIndex,\n status: attempt.status,\n ...(attempt.cleanup ? { cleanup: attempt.cleanup } : {}),\n ...(attempt.pendingOperations\n ? { pendingOperations: attempt.pendingOperations }\n : {}),\n ...(attempt.executionStatus\n ? { executionStatus: attempt.executionStatus }\n : {}),\n ...(attempt.retryDecision\n ? { retryDecision: attempt.retryDecision }\n : {}),\n resultFile: fact(\n caseAttemptResultPath(\n project.projectId,\n outcome.documentId,\n attempt,\n ),\n ),\n ...(attempt.reportPaths?.length\n ? {\n reports: attempt.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n }\n : {}),\n })),\n documents: project.documents.map((document) => ({\n documentId: document.documentId,\n ...(document.attemptIndex === undefined\n ? {}\n : {\n attemptIndex: document.attemptIndex,\n documentRunId: document.documentRunId,\n }),\n sourcePath: document.sourcePath,\n status: document.status,\n ...(document.cleanup ? { cleanup: document.cleanup } : {}),\n ...(document.pendingOperations\n ? { pendingOperations: document.pendingOperations }\n : {}),\n ...(document.executionStatus\n ? { executionStatus: document.executionStatus }\n : {}),\n ...(document.retryDecision\n ? { retryDecision: document.retryDecision }\n : {}),\n resultFile: fact(workflowDocumentResultPath(document)),\n ...(document.reportPaths?.length\n ? {\n reports: document.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n collectionErrors: project.collectionErrors.map((error) => ({\n sourcePath: error.sourcePath,\n errorFile: fact(collectionErrorPath(error.projectId, error.sourcePath)),\n })),\n })),\n });\n};\n","import { readdirSync } from 'node:fs';\nimport { join, relative, resolve, sep } from 'node:path';\nimport type { CollectedWorkflowDocument } from '@midscene/core/internal/test-runner';\nimport { buildTestRunReportPlan } from '@midscene/core/internal/test-runner';\nimport { globSync } from 'tinyglobby';\nimport { WorkflowError, WorkflowParseError } from '../errors';\nimport { collectWorkflowDocument } from '../parser/collect';\nimport type {\n PreparedDocumentInvocation,\n PreparedExecutionProject,\n ProjectPreparationOptions,\n} from './execution-plan';\nimport { writeCollectionError } from './result-store';\nimport type { LoadedExecutionProject, TestFileSelection } from './test-project';\nimport { validateTestFileSelection } from './test-project';\nimport type { TestProjectCollectionError } from './types';\n\nexport const CONFIG_NAMES = [\n 'midscene.config.ts',\n 'midscene.config.mjs',\n] as const;\nconst CONFIG_PREFIX = 'midscene.config.';\nconst ALWAYS_IGNORED_PATTERNS = [\n '.git/**',\n '.midscene/**',\n 'midscene_run/**',\n 'node_modules/**',\n '**/.git/**',\n '**/.midscene/**',\n '**/midscene_run/**',\n '**/node_modules/**',\n];\n\nexport const DEFAULT_TEST_FILE_SELECTION: TestFileSelection = {\n include: ['**/*.{yaml,yml}'],\n};\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nconst discoverResolvedTestFiles = (\n projectRoot: string,\n selection: TestFileSelection,\n): string[] => {\n const root = resolve(projectRoot);\n const match = (patterns: readonly string[]) =>\n globSync(patterns, {\n absolute: true,\n caseSensitiveMatch: false,\n cwd: root,\n dot: true,\n expandDirectories: false,\n followSymbolicLinks: false,\n ignore: [...ALWAYS_IGNORED_PATTERNS, ...(selection.exclude ?? [])],\n onlyFiles: true,\n }).filter((file) => /\\.ya?ml$/i.test(file));\n const files = match(selection.include);\n\n return [...new Set(files.map((file) => resolve(file)))].sort((a, b) => {\n const relativeA = toPosix(relative(root, a));\n const relativeB = toPosix(relative(root, b));\n return relativeA < relativeB ? -1 : relativeA > relativeB ? 1 : 0;\n });\n};\n\nexport const discoverTestFiles = (\n projectRoot: string,\n selection: TestFileSelection = DEFAULT_TEST_FILE_SELECTION,\n): string[] => {\n const normalized = validateTestFileSelection(selection);\n if (!normalized) throw new TypeError('Test file selection is required.');\n return discoverResolvedTestFiles(projectRoot, normalized);\n};\n\nexport const discoverTestConfig = (projectRoot: string): string | undefined => {\n const root = resolve(projectRoot);\n const candidates = readdirSync(root)\n .filter((name) => name.startsWith(CONFIG_PREFIX))\n .sort();\n const supported = candidates.filter((name) =>\n CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n const unsupported = candidates.filter(\n (name) => !CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n if (unsupported.length > 0) {\n throw new Error(\n [\n `Unsupported or conflicting Midscene configs found in ${root}:`,\n ...candidates.map((name) => `- ${name}`),\n `Only ${CONFIG_NAMES.join(' and ')} are supported.`,\n ].join('\\n'),\n );\n }\n if (supported.length > 1) {\n throw new Error(\n [\n `Multiple Midscene configs found in ${root}:`,\n ...supported.map((name) => `- ${name}`),\n 'Pass --config <path> to select one explicitly.',\n ].join('\\n'),\n );\n }\n return supported[0] ? join(root, supported[0]) : undefined;\n};\n\nconst asCollectionError = (\n projectId: string,\n projectName: string,\n sourcePath: string,\n error: unknown,\n): TestProjectCollectionError => ({\n projectId,\n projectName,\n sourcePath,\n error:\n error instanceof WorkflowError\n ? error\n : new WorkflowParseError(\n `Failed to collect workflow document \"${sourcePath}\": ${\n error instanceof Error ? error.message : String(error)\n }`,\n { projectName, sourcePath },\n error,\n ),\n});\n\nexport const matchesTags = (\n tags: readonly string[],\n selection: LoadedExecutionProject['tags'],\n): boolean => {\n if (selection.exclude.some((tag) => tags.includes(tag))) return false;\n return (\n selection.include.length === 0 ||\n selection.include.some((tag) => tags.includes(tag))\n );\n};\n\nconst filterDocumentCases = (\n document: CollectedWorkflowDocument,\n project: LoadedExecutionProject,\n): { document?: CollectedWorkflowDocument; filtered: number } => {\n const cases = document.cases.filter((item) =>\n matchesTags(item.definition.tags ?? [], project.tags),\n );\n const filtered = document.cases.length - cases.length;\n return cases.length === 0\n ? { filtered }\n : { document: { ...document, cases }, filtered };\n};\n\nexport const selectProjects = <TProjectContext>(\n projects: readonly LoadedExecutionProject<TProjectContext>[],\n names: readonly string[] | undefined,\n): readonly LoadedExecutionProject<TProjectContext>[] => {\n if (!names || names.length === 0) return projects;\n const requested = new Set(names);\n if (requested.size !== names.length) {\n throw new Error('Each --project name may only be specified once.');\n }\n const known = new Set(projects.map((project) => project.name));\n const unknown = names.find((name) => !known.has(name));\n if (unknown) throw new Error(`Unknown Midscene project: ${unknown}`);\n return projects.filter((project) => requested.has(project.name));\n};\n\n/** Prepare and validate every document before any Project resource is acquired. */\nexport async function prepareProject(\n project: LoadedExecutionProject,\n projectRoot: string,\n runDir: string,\n defaultTimeoutMs: number,\n options: ProjectPreparationOptions = {},\n): Promise<PreparedExecutionProject> {\n const platform = options.platform?.trim();\n const fileSelection = project.files ?? DEFAULT_TEST_FILE_SELECTION;\n const prerequisiteFile = options.prerequisiteFile\n ? resolve(options.prerequisiteFile)\n : undefined;\n const mainFiles =\n options.files ?? discoverResolvedTestFiles(projectRoot, fileSelection);\n const files = [\n ...(prerequisiteFile ? [prerequisiteFile] : []),\n ...mainFiles.filter((file) => file !== prerequisiteFile),\n ];\n const occurrences = new Map<string, number>();\n const sources = files.map((absolutePath) => {\n const invocationIndex = occurrences.get(absolutePath) ?? 0;\n occurrences.set(absolutePath, invocationIndex + 1);\n return {\n projectId: project.projectId,\n projectName: project.name,\n sourcePath: toPosix(relative(projectRoot, absolutePath)),\n absolutePath,\n invocationIndex,\n };\n });\n const collectionErrors: TestProjectCollectionError[] = [];\n const invocations: PreparedDocumentInvocation[] = [];\n const plans: import('@midscene/core').TestRunReportDocumentPlan[] = [];\n let filteredCaseCount = 0;\n\n if (sources.length === 0) {\n const error = asCollectionError(\n project.projectId,\n project.name,\n '<project>',\n new WorkflowParseError(\n `No workflow YAML files found for project \"${project.name}\" in ${projectRoot}.`,\n { projectName: project.name, projectRoot },\n ),\n );\n collectionErrors.push(error);\n await writeCollectionError(runDir, error);\n }\n\n for (const source of sources) {\n try {\n const collected = await options.collectDocument?.(source, project);\n if (collected) {\n filteredCaseCount += collected.filteredCaseCount;\n if (collected.invocation) {\n const plan = buildTestRunReportPlan(collected.invocation.document, {\n defaultTimeoutMs: collected.invocation.defaultTimeoutMs,\n retry: collected.invocation.retry,\n });\n invocations.push({ ...collected.invocation, plan });\n plans.push(plan);\n }\n continue;\n }\n const document = collectWorkflowDocument(source, {\n resolveNode: project.nodes.get.bind(project.nodes),\n variables: project.variables,\n env: process.env,\n });\n const filtered =\n source.absolutePath === prerequisiteFile\n ? { document, filtered: 0 }\n : filterDocumentCases(document, project);\n const plan = buildTestRunReportPlan(document, {\n selectedCaseIds:\n filtered.document?.cases.map((item) => item.caseId) ?? [],\n defaultTimeoutMs,\n retry: { scope: 'case', count: project.retry },\n });\n plans.push(plan);\n filteredCaseCount += filtered.filtered;\n if (filtered.document)\n invocations.push({\n plan,\n document: filtered.document,\n retry: { scope: 'case', count: project.retry },\n defaultTimeoutMs,\n reportEnabled: true,\n bindings: { resolveNode: project.nodes.require.bind(project.nodes) },\n });\n } catch (error) {\n const collectionError = asCollectionError(\n project.projectId,\n project.name,\n source.sourcePath,\n error,\n );\n collectionErrors.push(collectionError);\n await writeCollectionError(runDir, collectionError);\n }\n }\n\n const documents = invocations.map((invocation) => invocation.document);\n const prerequisiteSource = sources.find(\n (source) => source.absolutePath === prerequisiteFile,\n );\n const prerequisiteDocument = documents.find(\n (document) => document.sourcePath === prerequisiteSource?.sourcePath,\n );\n return {\n project,\n ...(platform ? { platform } : {}),\n documentConcurrency: options.documentConcurrency ?? 1,\n ...(prerequisiteDocument\n ? { prerequisiteDocumentId: prerequisiteDocument.documentId }\n : {}),\n fileSelection,\n sources,\n documents,\n invocations,\n plans,\n collectionErrors,\n selectedCaseCount: documents.reduce(\n (total, document) => total + document.cases.length,\n 0,\n ),\n filteredCaseCount,\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, statSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { NativeWorkflowFormatError } from '../parser/collect';\nimport type {\n PreparedExecutionProject,\n PreparedTestRunPlan,\n TestProjectRunOptions,\n TestRunInput,\n} from './execution-plan';\nimport {\n discoverTestConfig,\n prepareProject,\n selectProjects,\n} from './project-preparation';\nimport { loadTestProject } from './test-project';\n\nconst padDatePart = (value: number): string => String(value).padStart(2, '0');\n\nexport const createTestRunId = (\n date = new Date(),\n uuid = randomUUID(),\n): string => {\n const timestamp = [\n date.getFullYear(),\n padDatePart(date.getMonth() + 1),\n padDatePart(date.getDate()),\n padDatePart(date.getHours()),\n padDatePart(date.getMinutes()),\n padDatePart(date.getSeconds()),\n ].join('');\n return `${timestamp}-${uuid.slice(0, 8)}`;\n};\n\nconst assertDirectory = (path: string, label: string): void => {\n if (!existsSync(path) || !statSync(path).isDirectory()) {\n throw new Error(`${label} does not exist or is not a directory: ${path}`);\n }\n};\n\nconst resolveRunInput = (options: TestProjectRunOptions): TestRunInput => {\n const cwd = resolve(options.cwd ?? process.cwd());\n assertDirectory(cwd, 'Test working directory');\n const inputPath = options.projectRoot\n ? resolve(cwd, options.projectRoot)\n : undefined;\n const singleFile =\n inputPath && existsSync(inputPath) && statSync(inputPath).isFile()\n ? inputPath\n : undefined;\n if (singleFile && !/\\.ya?ml$/i.test(singleFile))\n throw new Error(\n `Test input must be a YAML file or project directory: ${singleFile}`,\n );\n const cliProjectRoot = singleFile ? dirname(singleFile) : inputPath;\n if (cliProjectRoot) assertDirectory(cliProjectRoot, 'Test project directory');\n const projectRoot = cliProjectRoot ?? cwd;\n return {\n cwd,\n projectRoot,\n configSearchRoot: projectRoot,\n ...(singleFile ? { singleFile } : {}),\n };\n};\n\n/** Composition boundary only: execution receives no raw input syntax or host options. */\nexport async function prepareTestRun(\n options: TestProjectRunOptions,\n): Promise<PreparedTestRunPlan> {\n const startedAt = new Date();\n const runId = createTestRunId(startedAt);\n const input = resolveRunInput(options);\n const configPath = options.configPath\n ? resolve(input.configSearchRoot, options.configPath)\n : discoverTestConfig(input.configSearchRoot);\n if (options.configPath && /\\.ya?ml$/i.test(configPath!)) {\n throw new Error(\n `midscene-test --config only accepts a native TypeScript or JavaScript project config: ${configPath}. Run legacy batch YAML with \\`midscene --config ${options.configPath}\\`.`,\n );\n }\n if (options.configPath && !existsSync(configPath!))\n throw new Error(`Midscene config does not exist: ${configPath}`);\n const definition = await loadTestProject<unknown>(configPath);\n const resultDir = options.resultDir\n ? resolve(input.cwd, options.resultDir)\n : join(input.projectRoot, '.midscene', 'test-results');\n const runDir = join(resultDir, runId);\n const summaryPath = join(runDir, 'summary.json');\n const reportDir = resolve(input.projectRoot, definition.output.reportDir);\n mkdirSync(resultDir, { recursive: true });\n mkdirSync(runDir);\n const projects: PreparedExecutionProject[] = [];\n for (const project of selectProjects(\n definition.projects,\n options.projectNames,\n ))\n projects.push(\n await prepareProject(\n project,\n input.projectRoot,\n runDir,\n definition.test.testTimeout,\n input.singleFile ? { files: [input.singleFile] } : undefined,\n ),\n );\n const hasFormatMismatch = projects.some((project) =>\n project.collectionErrors.some(\n ({ error }) => error instanceof NativeWorkflowFormatError,\n ),\n );\n return {\n startedAt,\n runId,\n projectRoot: input.projectRoot,\n ...(configPath ? { configPath } : {}),\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects,\n // A wrong-format file invalidates the complete command invocation. Other\n // native collection failures retain the existing per-Project isolation.\n preflightScope: hasFormatMismatch ? 'run' : 'project',\n reportEnabled: true,\n publications: [],\n onProgress: options.onProgress ?? (() => {}),\n };\n}\n","import { writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport type {\n TestRunReportDump,\n TestRunReportSourceIndex,\n TestRunReportStep,\n} from '@midscene/core';\nimport type { TestProjectRunResult } from '../cli/types';\nimport { buildTestRunReportDump } from './test-run-report';\n\nconst text = (value: string): string =>\n value\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll('|', '&#124;')\n .replaceAll('[', '&#91;')\n .replaceAll(']', '&#93;')\n .replaceAll('*', '&#42;')\n .replaceAll('_', '&#95;')\n .replaceAll('`', '&#96;')\n .replaceAll('\\\\', '&#92;')\n .replace(/[\\r\\n]+/g, ' ');\n\nconst duration = (ms: number): string => {\n const seconds = Math.round(ms / 1000);\n return seconds < 60\n ? `${seconds}s`\n : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;\n};\nconst href = (from: string, target: string): string =>\n relative(dirname(from), target).split(sep).map(encodeURIComponent).join('/');\n\nexport interface TestResultMarkdownOptions {\n /** Relative or hosted URL of the HTML report. */\n reportHref?: string;\n}\n\n/** Render the same sanitized execution facts used by the HTML report. */\nexport function renderTestResultMarkdown(\n dump: TestRunReportDump,\n options: TestResultMarkdownOptions = {},\n): string {\n const { summary } = dump;\n const outcome =\n dump.status === 'success'\n ? `✅ **${summary.passed}/${summary.total} passed**`\n : `❌ **${summary.failed} failed** · ${summary.passed} passed · ${summary.notRun} not run`;\n const lines = [\n '## Midscene Test',\n '',\n `${outcome} · ${duration(dump.durationMs)}`,\n '',\n ];\n if (summary.filtered) lines.push(`**Filtered:** ${summary.filtered}`, '');\n const infrastructure = [\n summary.collectionErrors\n ? `${summary.collectionErrors} collection errors`\n : '',\n summary.documentFailures\n ? `${summary.documentFailures} document failures`\n : '',\n summary.projectFailures\n ? `${summary.projectFailures} project failures`\n : '',\n ].filter(Boolean);\n if (infrastructure.length)\n lines.push(`**Infrastructure:** ${infrastructure.join(' · ')}`, '');\n const groups: { name: string; rows: string[] }[] = [];\n const errors: string[] = [];\n const recordSteps = (label: string, steps: readonly TestRunReportStep[]) => {\n for (const step of steps) {\n if (step.status === 'failed')\n errors.push(\n `${label} / ${step.node}: ${step.error?.message ?? 'Step failed'}`,\n );\n }\n };\n for (const project of dump.projects) {\n if (project.lifecycle?.setupError)\n errors.push(`${project.name}: ${project.lifecycle.setupError.message}`);\n for (const error of project.lifecycle?.teardownErrors ?? [])\n errors.push(`${project.name}: ${error.message}`);\n for (const error of project.collectionErrors)\n errors.push(\n `${project.name} / ${error.sourcePath}: ${error.error.message}`,\n );\n for (const document of project.documents) {\n const name = document.sourcePath\n .replace(/\\\\/g, '/')\n .replace(/\\.(?:yaml|yml)$/, '');\n const group = {\n name: dump.projects.length > 1 ? `${project.name} / ${name}` : name,\n rows: [] as string[],\n };\n groups.push(group);\n recordSteps(`${project.name} / ${document.sourcePath}`, [\n ...document.beforeAll,\n ...document.afterAll,\n ]);\n for (const error of document.teardownErrors ?? [])\n errors.push(`${document.sourcePath}: ${error.message}`);\n for (const failure of document.hostErrors ?? [])\n errors.push(\n `${document.sourcePath} / ${failure.phase}: ${failure.error.message}`,\n );\n for (const testCase of document.cases) {\n group.rows.push(\n ` - ${testCase.status === 'success' ? '✅' : testCase.status === 'not-run' ? '⏭️' : '❌'} ${text(testCase.name)}`,\n );\n }\n }\n }\n for (const diagnostic of dump.diagnostics ?? []) {\n if (diagnostic.level === 'error') errors.push(diagnostic.message);\n }\n if (errors.length)\n lines.push(\n '### Execution errors',\n '',\n ...errors.map((error) => `- ${text(error)}`),\n '',\n );\n for (const group of groups) {\n if (group.rows.length) lines.push(`- ${text(group.name)}`, ...group.rows);\n }\n if (!groups.some((group) => group.rows.length))\n lines.push('No cases were reported.');\n if (options.reportHref)\n lines.push(\n '',\n `[Open the Midscene Test report ↗](<${options.reportHref}>)`,\n );\n return `${lines.join('\\n')}\\n`;\n}\n\nconst emptyIndex = (): TestRunReportSourceIndex => ({\n sources: [],\n metrics: {\n modelCallCount: 0,\n modelTimeMs: 0,\n promptTokens: 0,\n cachedInputTokens: 0,\n completionTokens: 0,\n totalTokens: 0,\n },\n});\n\n/** Write a per-run Markdown artifact even when HTML publication fails or is disabled. */\nexport async function writeTestResultMarkdown(\n result: TestProjectRunResult,\n index: TestRunReportSourceIndex = emptyIndex(),\n): Promise<string> {\n const output = join(dirname(result.summaryPath), 'result.md');\n const dump = buildTestRunReportDump(result, index);\n await writeFile(\n output,\n renderTestResultMarkdown(dump, {\n ...(result.reportPath\n ? { reportHref: href(output, result.reportPath) }\n : {}),\n }),\n );\n return output;\n}\n","import {\n WorkflowExecutionFailure,\n decideRetry,\n isResourceRecoveryError,\n runDocumentAttempts,\n runWorkflowDocument,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CaseRunOutcome,\n StepExecutionInfo,\n StepRunResult,\n WorkflowDocumentExecutionResult,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport { isFatalDeviceError } from '../errors';\nimport type { PreparedDocumentInvocation } from './execution-plan';\nimport {\n writeCaseAttemptResult,\n writeWorkflowDocumentResult,\n} from './result-store';\nimport type { LoadedExecutionProject } from './test-project';\nimport type { TestProjectCaseRunResult } from './types';\n\ninterface DocumentInvocationSinks {\n cases: TestProjectCaseRunResult[];\n documents: WorkflowDocumentRunResult[];\n}\n\ninterface ExecuteDocumentInvocationOptions {\n invocation: PreparedDocumentInvocation;\n project: LoadedExecutionProject<unknown>;\n projectContext: unknown;\n runDir: string;\n signal: AbortSignal;\n rootSignal: AbortSignal;\n shouldBail(): boolean;\n isProjectFatal(): boolean;\n markProjectFatal(): void;\n addFailedCases(count: number): void;\n onProgress(message: string): void;\n onDocumentResult?(result: WorkflowDocumentRunResult): Promise<void>;\n sinks: DocumentInvocationSinks;\n}\n\nconst stepPosition = (info: StepExecutionInfo) =>\n info.scope === 'case' ? info.case : info.document;\n\nconst formatStep = (info: StepExecutionInfo): string => {\n const position = stepPosition(info);\n const phase = position.phase === 'steps' ? 'step' : position.phase;\n return `${phase} ${position.stepIndex + 1}/${info.stepCount}: ${info.node}`;\n};\n\nconst formatStepResult = (\n info: StepExecutionInfo,\n result: StepRunResult,\n): string => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n if (result.status === 'not-run')\n return `${indent}– ${formatStep(info)} (not run: ${result.notRunReason})`;\n const symbol = result.status === 'success' ? '✓' : '✗';\n const error = result.error ? ` — ${result.error.message}` : '';\n const continuation = result.continuedAfterError ? '; continuing' : '';\n return `${indent}${symbol} ${formatStep(info)} (${result.durationMs} ms)${error}${continuation}`;\n};\n\nconst caseHasFatalError = (outcome: CaseRunOutcome): boolean =>\n (outcome.attempts ?? []).some(\n (attempt) =>\n [...attempt.beforeEach, ...attempt.steps, ...attempt.afterEach].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (attempt.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!attempt.executionErrors?.some(isResourceRecoveryError),\n );\n\nconst documentHasFatalError = (result: WorkflowDocumentRunResult): boolean =>\n [...result.beforeAll, ...result.afterAll].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (result.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!result.executionErrors?.some(isResourceRecoveryError);\n\n/** Execute prepared document policies through the shared retry boundary. */\nexport async function executeDocumentInvocation(\n options: ExecuteDocumentInvocationOptions,\n): Promise<void> {\n const { invocation, project, sinks } = options;\n const { document } = invocation;\n const documentRetry = invocation.retry.scope === 'document';\n const attempts: WorkflowDocumentExecutionResult[] = [];\n\n await runDocumentAttempts(\n {\n retry: documentRetry ? invocation.retry.count : 0,\n signal: options.signal,\n shouldStop: () => options.shouldBail() || options.isProjectFatal(),\n },\n async (documentAttemptIndex) => {\n if (documentRetry)\n options.onProgress(\n ` file attempt ${documentAttemptIndex + 1}/${invocation.retry.count + 1}: ${document.sourcePath}`,\n );\n const execution = await runWorkflowDocument(document, {\n plan: invocation.plan,\n documentAttemptIndex: documentRetry ? documentAttemptIndex : undefined,\n ...invocation.bindings,\n project,\n projectContext: options.projectContext,\n retry: documentRetry ? 0 : invocation.retry.count,\n signal: options.signal,\n defaultTimeoutMs: invocation.defaultTimeoutMs,\n shouldStop: () =>\n options.rootSignal.aborted ||\n options.shouldBail() ||\n options.isProjectFatal(),\n stopReason: () =>\n options.rootSignal.aborted\n ? 'interrupted'\n : options.isProjectFatal()\n ? 'fatal-error'\n : 'bail',\n isFatalError: (run) =>\n [...run.beforeEach, ...run.steps, ...run.afterEach].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) || (run.teardownErrors ?? []).some(isFatalDeviceError),\n onCaseStart: (collectedCase) => {\n options.onProgress(\n ` [case ${collectedCase.caseIndex + 1}/${document.cases.length}] ${collectedCase.definition.name}`,\n );\n },\n onStepStart: (info) => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n options.onProgress(`${indent}→ ${formatStep(info)}`);\n },\n onStepResult: async (info, result) => {\n await invocation.bindings.onStepResult?.(info, result);\n options.onProgress(formatStepResult(info, result));\n },\n onCaseResult: async (attempt) => {\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n options.onProgress(\n ` ${attempt.status === 'success' ? '✓' : '✗'} attempt ${attempt.attemptIndex + 1}/${documentRetry ? 1 : invocation.retry.count + 1}: ${attempt.name} (${attempt.durationMs} ms)`,\n );\n },\n onCaseOutcome: (outcome) => {\n if (caseHasFatalError(outcome)) options.markProjectFatal();\n if (!documentRetry && outcome.status === 'failed')\n options.addFailedCases(1);\n },\n onDocumentResult: options.onDocumentResult,\n }).catch(async (error: unknown) => {\n if (error instanceof WorkflowExecutionFailure) {\n const partial = error.result as WorkflowDocumentExecutionResult;\n const resourceOnly =\n error.errors.length > 0 &&\n error.errors.every(\n (failure) =>\n isResourceRecoveryError(failure) ||\n partial.document.hostErrors?.some(\n (host) =>\n host.phase === 'cleanup' &&\n (host.error === failure ||\n (host.error instanceof Error &&\n host.error.cause === failure)),\n ),\n );\n // Recovery and disposal failures stop this Project, not independent\n // Projects. Publication and other infrastructure failures still throw.\n if (resourceOnly) {\n if (error.errors.some(isResourceRecoveryError))\n options.markProjectFatal();\n return partial;\n }\n if (documentRetry)\n partial.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n attempts.push(partial);\n sinks.documents.push(partial.document);\n sinks.cases.push(\n ...partial.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: partial.document.documentRunId,\n })),\n );\n try {\n for (const outcome of partial.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, partial.document);\n } catch (publicationError) {\n throw new WorkflowExecutionFailure(partial, [\n ...error.errors,\n publicationError,\n ]);\n }\n }\n throw error;\n });\n\n if (documentHasFatalError(execution.document)) options.markProjectFatal();\n const owners = [\n execution.document,\n ...execution.cases.flatMap((outcome) => outcome.attempts ?? []),\n ];\n const cleanupPending = owners.some(\n (owner) => owner.cleanup?.status === 'pending',\n );\n const operationPending = owners.some(\n (owner) => !!owner.pendingOperations?.length,\n );\n const cleanupFailed = owners.some(\n (owner) =>\n owner.cleanup?.status === 'failed' ||\n !!owner.teardownErrors?.length ||\n ('hostErrors' in owner &&\n owner.hostErrors?.some(({ phase }) => phase === 'cleanup')),\n );\n // Files share the Project context; stop reusing it without cancelling\n // independent Projects. Publication and execution errors still throw.\n if (cleanupPending || cleanupFailed || operationPending)\n options.markProjectFatal();\n const failed =\n execution.document.status === 'failed' ||\n execution.cases.some((item) => item.status !== 'success');\n const decision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: failed ? 'failed' : 'success',\n cleanupPending,\n cleanupFailed,\n operationPending,\n fatalError: options.isProjectFatal(),\n interrupted: options.signal.aborted || options.rootSignal.aborted,\n shouldStop: options.shouldBail(),\n });\n if (documentRetry) execution.document.retryDecision = decision;\n attempts.push(execution);\n sinks.cases.push(\n ...execution.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: execution.document.documentRunId,\n })),\n );\n sinks.documents.push(execution.document);\n // Per-attempt callbacks publish incremental facts; seal the final retry\n // decision after callback-driven interruption/bail has been observed.\n try {\n for (const outcome of execution.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, execution.document);\n } catch (error) {\n execution.document.status = 'failed';\n execution.document.hostErrors = [\n ...(execution.document.hostErrors ?? []),\n { phase: 'publication', error },\n ];\n if (documentRetry)\n execution.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n throw new WorkflowExecutionFailure(execution, [error]);\n }\n return decision.decision === 'retry' ? 'failed' : undefined;\n },\n );\n\n const final = attempts.at(-1);\n if (!final) return;\n const failedCases = final.cases.filter(\n (item) => item.status === 'failed',\n ).length;\n if (documentRetry && failedCases) options.addFailedCases(failedCases);\n else if (final.document.status === 'failed' && failedCases === 0)\n options.addFailedCases(Math.max(1, failedCases));\n}\n","import { appendFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { TestRunReportOperationEvent } from '@midscene/core';\n\n/** Registered operations keep this sink after the report has been sealed.\n * Each small, bounded event is written before returning to the operation. No\n * open file descriptor or mutable report object is retained by the journal.\n */\nexport function createOperationJournal(runDir: string) {\n const path = join(runDir, 'operations.jsonl');\n writeFileSync(path, '', { flag: 'wx' });\n return {\n path,\n append(event: Readonly<TestRunReportOperationEvent>) {\n appendFileSync(path, `${JSON.stringify(event)}\\n`);\n },\n };\n}\n","import { setMaxListeners } from 'node:events';\nimport { dirname, join } from 'node:path';\nimport type { TestRunReportSourceIndex } from '@midscene/core';\nimport {\n WorkflowExecutionFailure,\n WorkflowPublicationError,\n asExecutionError,\n observeResourceOperations,\n runConcurrentJobs,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CollectedCase,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport {\n TestRunReportAssembler,\n calculateTestRunHealth,\n} from '@midscene/core/report';\nimport { getDebug } from '@midscene/shared/logger';\nimport { createProjectRuntime } from '../engine/project-runtime';\nimport { writeTestResultMarkdown } from '../report/result-markdown';\nimport {\n buildTestRunReportDump,\n collectTestRunReportSources,\n} from '../report/test-run-report';\nimport { executeDocumentInvocation } from './document-invocation';\nimport type {\n PreparedDocumentInvocation,\n PreparedExecutionProject,\n PreparedTestRunPlan,\n} from './execution-plan';\nimport { createOperationJournal } from './operation-journal';\nimport { writeTestProjectRunResult, writeTestRunPlan } from './result-store';\nimport type {\n TestExecutionProjectRunResult,\n TestProjectCaseRunResult,\n TestProjectRunResult,\n TestProjectRunSummary,\n} from './types';\n\nconst asNotRun = (\n documentId: string,\n collectedCase: CollectedCase,\n projectName: string,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult => ({\n documentId,\n caseId: collectedCase.caseId,\n projectName,\n name: collectedCase.definition.name,\n sourcePath: collectedCase.sourcePath,\n caseIndex: collectedCase.caseIndex,\n status: 'not-run',\n notRunReason: reason,\n});\n\nconst summarize = (\n projects: readonly TestExecutionProjectRunResult[],\n): TestProjectRunSummary => {\n const healthCases = projects.flatMap((project) => {\n const documentAttemptByRunId = new Map(\n project.documents.map((document) => [\n document.documentRunId,\n document.attemptIndex ?? 0,\n ]),\n );\n return latestById(project.cases, (item) => item.caseId).map((item) => {\n return {\n status: item.status,\n ...(item.run ? { run: item.run } : {}),\n ...(item.attempts ? { attempts: item.attempts } : {}),\n retryCount: item.documentRunId\n ? (documentAttemptByRunId.get(item.documentRunId) ?? 0)\n : 0,\n };\n });\n });\n const documents = projects.flatMap((project) =>\n latestById(project.documents, (item) => item.documentId),\n );\n const health = calculateTestRunHealth(healthCases);\n return {\n total: health.total,\n passed: health.passed,\n failed: health.failed,\n notRun: health.notRun,\n passedAfterRetry: health.passedAfterRetry,\n finalPassRate: health.finalPassRate,\n firstPassRate: health.firstPassRate,\n filtered: projects.reduce(\n (total, project) => total + project.filteredCaseCount,\n 0,\n ),\n collectionErrors: projects.reduce(\n (total, project) => total + project.collectionErrors.length,\n 0,\n ),\n documentFailures: documents.filter(\n (document) => document.status === 'failed',\n ).length,\n projectFailures: projects.filter((project) => project.status === 'failed')\n .length,\n };\n};\n\nconst latestById = <T>(items: readonly T[], id: (item: T) => string): T[] => [\n ...new Map(items.map((item) => [id(item), item])).values(),\n];\n\nconst notRunSuite = (\n prepared: PreparedExecutionProject,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult[] =>\n prepared.documents.flatMap((document) =>\n document.cases.map((item) =>\n asNotRun(document.documentId, item, prepared.project.name, reason),\n ),\n );\n\n/** The executor sees prepared policies and bindings, never source-language rules. */\nexport async function runPreparedTestProject(\n plan: PreparedTestRunPlan,\n): Promise<TestProjectRunResult> {\n const {\n startedAt,\n runId,\n projectRoot,\n configPath,\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects: preparedProjects,\n } = plan;\n const progress = plan.onProgress;\n const totalDocuments = preparedProjects.reduce(\n (total, prepared) => total + prepared.documents.length,\n 0,\n );\n const totalCases = preparedProjects.reduce(\n (total, prepared) => total + prepared.selectedCaseCount,\n 0,\n );\n const totalErrors = preparedProjects.reduce(\n (total, prepared) => total + prepared.collectionErrors.length,\n 0,\n );\n progress(\n `midscene-test: preflighted ${preparedProjects.length} projects, ${totalDocuments} documents, ${totalCases} cases, ${totalErrors} collection errors`,\n );\n\n const effectiveConcurrency = Math.min(\n definition.test.maxConcurrency,\n preparedProjects.length,\n );\n await writeTestRunPlan(runDir, preparedProjects);\n const journal = createOperationJournal(runDir);\n const rootController = new AbortController();\n setMaxListeners(\n Math.max(10, effectiveConcurrency + 1),\n rootController.signal,\n );\n const handleSignal = (signal: NodeJS.Signals) => {\n rootController.abort(new Error(`Workflow interrupted by ${signal}.`));\n };\n const sigint = () => handleSignal('SIGINT');\n const sigterm = () => handleSignal('SIGTERM');\n process.on('SIGINT', sigint);\n process.on('SIGTERM', sigterm);\n\n let failedCaseCount = 0;\n const bailReached = () =>\n definition.test.bail > 0 && failedCaseCount >= definition.test.bail;\n let hasInfrastructureError = false;\n const infrastructureErrors: unknown[] = [];\n const recordInfrastructureError = (error: unknown) => {\n const errors =\n error instanceof WorkflowExecutionFailure ? error.errors : [error];\n for (const item of errors)\n if (!infrastructureErrors.includes(item)) infrastructureErrors.push(item);\n hasInfrastructureError = true;\n rootController.abort(error);\n };\n const runInfrastructureCallback = <T>(callback: () => T): T => {\n try {\n return callback();\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n };\n const stopObservingOperations = observeResourceOperations(\n rootController.signal,\n (event) => {\n try {\n journal.append(event);\n } catch (error) {\n recordInfrastructureError(\n new WorkflowPublicationError('write-result', journal.path, error),\n );\n getDebug('test-runner:operations', { console: true })(\n `Could not persist operation event: ${String(error)}`,\n );\n }\n },\n );\n type PreparedProject = (typeof preparedProjects)[number];\n const announceProject = (prepared: PreparedProject, projectIndex: number) => {\n const { project } = prepared;\n runInfrastructureCallback(() =>\n progress(\n `[project ${projectIndex + 1}/${preparedProjects.length}] ${project.name}`,\n ),\n );\n };\n const buildProjectResult = (\n prepared: PreparedProject,\n cases: readonly TestProjectCaseRunResult[],\n documents: readonly WorkflowDocumentRunResult[],\n lifecycle?: TestExecutionProjectRunResult['lifecycle'],\n ): TestExecutionProjectRunResult => {\n const { project } = prepared;\n const projectFailed =\n prepared.collectionErrors.length > 0 ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n ) ||\n latestById(documents, (item) => item.documentId).some(\n (item) => item.status === 'failed',\n ) ||\n lifecycle?.status === 'failed';\n return {\n projectId: project.projectId,\n name: project.name,\n ...(prepared.platform ? { platform: prepared.platform } : {}),\n status: projectFailed ? 'failed' : 'success',\n retry: project.retry,\n fileSelection: prepared.fileSelection,\n tagSelection: project.tags,\n sourceCount: prepared.sources.length,\n selectedCaseCount: prepared.selectedCaseCount,\n filteredCaseCount: prepared.filteredCaseCount,\n ...(lifecycle ? { lifecycle } : {}),\n cases,\n plans: prepared.plans,\n documents,\n collectionErrors: prepared.collectionErrors,\n };\n };\n const buildSkippedProjectResult = (\n prepared: PreparedProject,\n projectIndex: number,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n ): TestExecutionProjectRunResult => {\n announceProject(prepared, projectIndex);\n return buildProjectResult(prepared, notRunSuite(prepared, reason), []);\n };\n const runPreparedProject = async (\n prepared: PreparedProject,\n projectIndex: number,\n ): Promise<TestExecutionProjectRunResult> => {\n const { project } = prepared;\n announceProject(prepared, projectIndex);\n const projectProgress = (message: string) =>\n runInfrastructureCallback(() =>\n progress(\n effectiveConcurrency > 1 ? `[${project.name}]${message}` : message,\n ),\n );\n const cases: TestProjectCaseRunResult[] = [];\n const documents: WorkflowDocumentRunResult[] = [];\n let lifecycle: TestExecutionProjectRunResult['lifecycle'];\n let projectFatal = false;\n\n if (\n prepared.collectionErrors.length > 0 ||\n (plan.preflightScope === 'run' && totalErrors > 0)\n ) {\n cases.push(...notRunSuite(prepared, 'project-preflight-failed'));\n } else if (rootController.signal.aborted) {\n cases.push(...notRunSuite(prepared, 'interrupted'));\n } else if (bailReached()) {\n cases.push(...notRunSuite(prepared, 'bail'));\n } else {\n const runtime = createProjectRuntime({\n project,\n setup: project.setup,\n signal: rootController.signal,\n });\n let hasProjectExecutionError = false;\n try {\n await runtime.start();\n if (!runtime.canRun) {\n cases.push(\n ...notRunSuite(\n prepared,\n rootController.signal.aborted\n ? 'interrupted'\n : 'project-setup-failed',\n ),\n );\n } else {\n const runDocument = async (\n invocation: PreparedDocumentInvocation,\n documentIndex: number,\n ) => {\n const { document } = invocation;\n if (\n rootController.signal.aborted ||\n bailReached() ||\n projectFatal\n ) {\n const reason = rootController.signal.aborted\n ? 'interrupted'\n : projectFatal\n ? 'fatal-error'\n : 'bail';\n cases.push(\n ...document.cases.map((item) =>\n asNotRun(document.documentId, item, project.name, reason),\n ),\n );\n return;\n }\n projectProgress(\n ` [document ${documentIndex + 1}/${prepared.documents.length}] ${document.sourcePath}`,\n );\n await executeDocumentInvocation({\n invocation,\n project,\n projectContext: runtime.context,\n runDir,\n signal: runtime.signal,\n rootSignal: rootController.signal,\n shouldBail: bailReached,\n isProjectFatal: () => projectFatal,\n markProjectFatal: () => {\n projectFatal = true;\n },\n addFailedCases: (count) => {\n failedCaseCount += count;\n },\n onProgress: projectProgress,\n sinks: {\n cases,\n documents,\n },\n });\n };\n let prerequisiteFailed = false;\n const prerequisite = prepared.invocations.find(\n (invocation) =>\n invocation.document.documentId ===\n prepared.prerequisiteDocumentId,\n );\n const prerequisiteCount = prerequisite ? 1 : 0;\n if (prerequisite) {\n await runDocument(prerequisite, 0);\n prerequisiteFailed =\n documents.at(-1)?.status === 'failed' ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n );\n }\n if (!prerequisiteFailed) {\n await runConcurrentJobs(\n prepared.invocations.filter(\n (invocation) => invocation !== prerequisite,\n ),\n {\n concurrency: prepared.documentConcurrency,\n shouldStop: () =>\n rootController.signal.aborted ||\n bailReached() ||\n projectFatal,\n },\n async (invocation, index) => {\n try {\n await runDocument(invocation, index + prerequisiteCount);\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n },\n );\n }\n const completed = new Set(cases.map((item) => item.caseId));\n const reason = prerequisiteFailed\n ? 'project-setup-failed'\n : rootController.signal.aborted\n ? 'interrupted'\n : projectFatal\n ? 'fatal-error'\n : 'bail';\n cases.push(\n ...notRunSuite(prepared, reason).filter(\n (item) => !completed.has(item.caseId),\n ),\n );\n }\n } catch (error) {\n hasProjectExecutionError = true;\n recordInfrastructureError(error);\n } finally {\n const hasFailure =\n hasProjectExecutionError ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n ) ||\n latestById(documents, (item) => item.documentId).some(\n (item) => item.status === 'failed',\n ) ||\n projectFatal ||\n rootController.signal.aborted;\n lifecycle = await runtime.finish(hasFailure ? 'failed' : 'success');\n }\n if (hasProjectExecutionError) {\n const completed = new Set(cases.map((item) => item.caseId));\n cases.push(\n ...notRunSuite(prepared, 'interrupted').filter(\n (item) => !completed.has(item.caseId),\n ),\n );\n }\n }\n\n const order = new Map(\n prepared.documents.map((document, index) => [document.documentId, index]),\n );\n const documentOrder = (id: string) =>\n order.get(id) ?? Number.MAX_SAFE_INTEGER;\n cases.sort(\n (a, b) =>\n documentOrder(a.documentId) - documentOrder(b.documentId) ||\n a.caseIndex - b.caseIndex,\n );\n documents.sort(\n (a, b) =>\n documentOrder(a.documentId) - documentOrder(b.documentId) ||\n (a.attemptIndex ?? 0) - (b.attemptIndex ?? 0),\n );\n return buildProjectResult(prepared, cases, documents, lifecycle);\n };\n\n const projectResults: Array<TestExecutionProjectRunResult | undefined> =\n new Array(preparedProjects.length);\n\n try {\n await runConcurrentJobs(\n preparedProjects,\n {\n concurrency: effectiveConcurrency,\n shouldStop: () =>\n hasInfrastructureError ||\n rootController.signal.aborted ||\n bailReached(),\n },\n async (prepared, index) => {\n try {\n projectResults[index] = await runPreparedProject(prepared, index);\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n },\n );\n } catch (error) {\n recordInfrastructureError(error);\n } finally {\n stopObservingOperations();\n process.off('SIGINT', sigint);\n process.off('SIGTERM', sigterm);\n }\n\n const completedProjectResults = preparedProjects.map(\n (prepared, projectIndex) => {\n const result = projectResults[projectIndex];\n if (result) return result;\n const reason = prepared.collectionErrors.length\n ? 'project-preflight-failed'\n : rootController.signal.aborted\n ? 'interrupted'\n : bailReached()\n ? 'bail'\n : undefined;\n if (!reason) {\n throw new Error(\n `Project scheduler did not produce a result for \"${prepared.project.name}\".`,\n );\n }\n return buildSkippedProjectResult(prepared, projectIndex, reason);\n },\n );\n\n const summary = summarize(completedProjectResults);\n const failed =\n hasInfrastructureError ||\n rootController.signal.aborted ||\n summary.failed > 0 ||\n summary.notRun > 0 ||\n summary.collectionErrors > 0 ||\n summary.documentFailures > 0 ||\n summary.projectFailures > 0;\n const endedAt = new Date();\n const result: TestProjectRunResult = {\n schemaVersion: 3,\n operationLog: { path: journal.path, snapshotAt: endedAt.toISOString() },\n runId,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n status: failed ? 'failed' : 'success',\n exitCode: failed ? 1 : 0,\n resultDir,\n summaryPath,\n reportDir,\n summary,\n projects: completedProjectResults,\n cases: completedProjectResults.flatMap((project) => project.cases),\n documents: completedProjectResults.flatMap((project) => project.documents),\n collectionErrors: completedProjectResults.flatMap(\n (project) => project.collectionErrors,\n ),\n ...(hasInfrastructureError\n ? { errors: infrastructureErrors.map(asExecutionError) }\n : {}),\n };\n let completedResult = result;\n let reportIndex: TestRunReportSourceIndex | undefined;\n const publish = async (\n operation: 'write-result' | 'write-report',\n path: string,\n callback: () => unknown | Promise<unknown>,\n ): Promise<boolean> => {\n try {\n await callback();\n return true;\n } catch (error) {\n recordInfrastructureError(\n error instanceof WorkflowPublicationError ||\n error instanceof WorkflowExecutionFailure\n ? error\n : new WorkflowPublicationError(operation, path, error),\n );\n completedResult = {\n ...completedResult,\n status: 'failed',\n exitCode: 1,\n errors: infrastructureErrors.map(asExecutionError),\n };\n return false;\n }\n };\n const writeSummary = () =>\n publish('write-result', summaryPath, () =>\n writeTestProjectRunResult({\n projectRoot,\n ...(configPath ? { configPath } : {}),\n result: completedResult,\n }),\n );\n const writeReport = () =>\n publish('write-report', reportDir, async () => {\n if (!plan.reportEnabled) return;\n const reportPath = await new TestRunReportAssembler().assembleAsync({\n outputDir: reportDir,\n reportFileName: `midscene-e2e-${runId}`,\n overwrite: false,\n sources: collectTestRunReportSources(completedResult),\n buildRunnerDump: (index) => {\n reportIndex = index;\n const dump = buildTestRunReportDump(completedResult, index);\n const warn = getDebug('test-runner:report-assembler', {\n console: true,\n });\n for (const diagnostic of dump.diagnostics ?? [])\n warn(diagnostic.message);\n return dump;\n },\n });\n completedResult = { ...completedResult, reportPath };\n });\n // Publish each artifact once. The summary includes the report path or its\n // failure. If the summary itself fails, the thrown result remains authoritative;\n // do not rebuild an already-published execution report to backfill that error.\n await writeReport();\n for (const publication of plan.publications)\n await publish(publication.operation, publication.path, async () => {\n await publication.publish(completedResult);\n });\n await publish(\n 'write-result',\n join(dirname(summaryPath), 'result.md'),\n async () => {\n const markdownPath = await writeTestResultMarkdown(\n completedResult,\n reportIndex,\n );\n completedResult = { ...completedResult, markdownPath };\n },\n );\n await writeSummary();\n if (hasInfrastructureError)\n throw new WorkflowExecutionFailure(completedResult, infrastructureErrors);\n return completedResult;\n}\n","import type { TestProjectRunOptions } from './execution-plan';\nimport { prepareTestRun } from './prepare-test-run';\nimport { runPreparedTestProject } from './run-prepared-project';\nimport type { TestProjectRunResult } from './types';\n\nexport type { TestProjectRunOptions } from './execution-plan';\nexport { createTestRunId } from './prepare-test-run';\nexport {\n DEFAULT_TEST_FILE_SELECTION,\n discoverTestConfig,\n discoverTestFiles,\n} from './project-preparation';\n\n/** Native Test entry for cases/steps workflow documents. */\nexport async function runTestProject(\n options: TestProjectRunOptions = {},\n): Promise<TestProjectRunResult> {\n return runPreparedTestProject(await prepareTestRun(options));\n}\n"],"names":["NodeRegistry","CoreNodeRegistry","projectIdFromIndex","index","defineTestProject","definition","defineProjectSetup","getDefaultExport","loaded","absolutePath","defaultExport","TypeError","isRecord","value","Array","rejectUnknownKeys","allowedKeys","label","allowed","Set","unknown","Object","key","isAbsolutePattern","pattern","isAbsolute","validatePatterns","field","allowEmptyInclude","validateTestFileSelection","undefined","include","exclude","validateTagList","tag","validateTagSelection","assertJsonValue","path","seen","Number","item","child","deepFreezeJson","validateVariables","validateSetup","validatePositiveInteger","fallback","validateNonNegativeInteger","validateExecutionProjects","defaultSetup","globalNodes","setup","names","projects","candidate","files","localNodes","nodes","node","validateTestOptions","validateOutputPath","validateOutput","validateTestProjectDefinition","resolvedProjects","name","assertSupportedConfig","extension","canRetryWithCjsLoader","error","Error","errorCode","SyntaxError","loadTestProject","configPath","resolve","pathToFileURL","tsImport","dirname","sep","tsxRequire","fallbackError","message","createCaseInvocationId","projectId","sourcePath","caseIndex","invocationIndex","createHash","JSON","createDocumentInvocationId","normalizeSteps","coreNormalizeSteps","parseWorkflowSource","source","stack","sensitiveNodes","sensitiveValues","redactedPaths","sourceOffset","parsed","load","JSON_SCHEMA","event","state","isReportSecretKey","ranges","left","right","offset","redacted","range","text","leading","trailing","sanitizeReportText","interpolationExpression","exactEnvExpression","exactProjectExpression","missingVariable","kind","options","WorkflowParseError","projectVariable","environmentVariable","interpolationValue","String","resolveString","exactEnv","exactProject","_match","environmentName","projectName","resolveWorkflowVariables","isMapping","NativeWorkflowFormatError","actualFormat","allowedSet","createCaseId","createWorkflowDocumentId","collectWorkflowDocument","snapshot","readFileSync","sourceYaml","format","classifyWorkflowDocumentFormat","resolveStepVariables","step","phase","stepIndex","process","normalizeLifecycle","normalized","resolved","lifecycle","ids","cases","tags","steps","caseId","writeJson","mkdir","writeFile","WorkflowPublicationError","writeTestRunPlan","runDir","join","Date","toPosix","caseAttemptResultPath","documentId","result","workflowDocumentResultPath","collectionErrorPath","id","writeWorkflowDocumentResult","_documentRunId","persistedResult","writeCaseAttemptResult","attemptId","writeCollectionError","collectionError","relativeToSummary","summaryPath","target","relative","errorJson","sanitizeReportError","writeTestProjectRunResult","fact","project","outcome","attempt","document","CONFIG_NAMES","CONFIG_PREFIX","ALWAYS_IGNORED_PATTERNS","DEFAULT_TEST_FILE_SELECTION","discoverResolvedTestFiles","projectRoot","selection","root","match","patterns","globSync","file","a","b","relativeA","relativeB","discoverTestFiles","discoverTestConfig","candidates","readdirSync","supported","unsupported","asCollectionError","WorkflowError","matchesTags","filterDocumentCases","filtered","selectProjects","requested","known","prepareProject","defaultTimeoutMs","platform","fileSelection","prerequisiteFile","mainFiles","occurrences","Map","sources","collectionErrors","invocations","plans","filteredCaseCount","collected","plan","buildTestRunReportPlan","documents","invocation","prerequisiteSource","prerequisiteDocument","total","padDatePart","createTestRunId","date","uuid","randomUUID","timestamp","assertDirectory","existsSync","statSync","resolveRunInput","cwd","inputPath","singleFile","cliProjectRoot","prepareTestRun","startedAt","runId","input","resultDir","reportDir","mkdirSync","hasFormatMismatch","duration","ms","seconds","Math","href","from","encodeURIComponent","renderTestResultMarkdown","dump","summary","lines","infrastructure","Boolean","groups","errors","recordSteps","group","failure","testCase","diagnostic","emptyIndex","writeTestResultMarkdown","output","buildTestRunReportDump","stepPosition","info","formatStep","position","formatStepResult","indent","symbol","continuation","caseHasFatalError","isFatalDeviceError","isResourceRecoveryError","documentHasFatalError","executeDocumentInvocation","sinks","documentRetry","attempts","runDocumentAttempts","documentAttemptIndex","execution","runWorkflowDocument","run","collectedCase","WorkflowExecutionFailure","partial","resourceOnly","host","decideRetry","publicationError","owners","cleanupPending","owner","operationPending","cleanupFailed","failed","decision","final","failedCases","createOperationJournal","writeFileSync","appendFileSync","asNotRun","reason","summarize","healthCases","documentAttemptByRunId","latestById","health","calculateTestRunHealth","items","notRunSuite","prepared","runPreparedTestProject","preparedProjects","progress","totalDocuments","totalCases","totalErrors","effectiveConcurrency","journal","rootController","AbortController","setMaxListeners","handleSignal","signal","sigint","sigterm","failedCaseCount","bailReached","hasInfrastructureError","infrastructureErrors","recordInfrastructureError","runInfrastructureCallback","callback","stopObservingOperations","observeResourceOperations","getDebug","announceProject","projectIndex","buildProjectResult","projectFailed","buildSkippedProjectResult","runPreparedProject","projectProgress","projectFatal","runtime","createProjectRuntime","hasProjectExecutionError","runDocument","documentIndex","count","prerequisiteFailed","prerequisite","prerequisiteCount","runConcurrentJobs","completed","hasFailure","order","documentOrder","projectResults","completedProjectResults","endedAt","asExecutionError","completedResult","reportIndex","publish","operation","writeSummary","writeReport","reportPath","TestRunReportAssembler","collectTestRunReportSources","warn","publication","markdownPath","runTestProject"],"mappings":";;;;;;;;;;;;AAYO,MAAMA,wBAETC;ACuCJ,MAAMC,qBAAqB,CAACC,QAA0B,CAAC,QAAQ,EAAEA,OAAO;AAyBjE,MAAMC,oBAAoB,CAC/BC,aACoCA;AAE/B,MAAMC,qBAAqB,CAChCD,aAC4CA;AAE9C,MAAME,mBAAmB,CAACC,QAAiBC;IACzC,IAAI,AAAkB,YAAlB,OAAOD,UAAuBA,AAAW,SAAXA,UAAmB,aAAaA,QAAQ;QACxE,MAAME,gBAAiBF,OAAgC,OAAO;QAC9D,IACE,AAAyB,YAAzB,OAAOE,iBACPA,AAAkB,SAAlBA,iBACA,gBAAgBA,eAChB;YACA,IAAI,aAAaA,eACf,OAAQA,cAAuC,OAAO;YAExD,MAAM,IAAIC,UACR,CAAC,iBAAiB,EAAEF,aAAa,6BAA6B,CAAC;QAEnE;QACA,OAAOC;IACT;IACA,MAAM,IAAIC,UACR,CAAC,iBAAiB,EAAEF,aAAa,6BAA6B,CAAC;AAEnE;AAEA,MAAMG,WAAW,CAACC,QAChB,AAAiB,YAAjB,OAAOA,SAAsBA,AAAU,SAAVA,SAAkB,CAACC,MAAM,OAAO,CAACD;AAEhE,MAAME,oBAAoB,CACxBF,OACAG,aACAC;IAEA,MAAMC,UAAU,IAAIC,IAAIH;IACxB,MAAMI,UAAUC,OAAO,IAAI,CAACR,OAAO,IAAI,CAAC,CAACS,MAAQ,CAACJ,QAAQ,GAAG,CAACI;IAC9D,IAAIF,SACF,MAAM,IAAIT,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AW,IAAI,CAAC,CAAC;gBACpC,QAAQ+T;YACV;IAEJ,MAAMK,cAAc,IAClBH,QAAQ,gBAAgBnI,WAAW;YACjC,IAAI,CAAC1B,KAAK,aAAa,EAAE;YACzB,MAAMiK,aAAa,MAAM,IAAIC,yBAAyB,aAAa,CAAC;gBAClE,WAAWxI;gBACX,gBAAgB,CAAC,aAAa,EAAEH,OAAO;gBACvC,WAAW;gBACX,SAAS4I,4BAA4BR;gBACrC,iBAAiB,CAACrY;oBAChBsY,cAActY;oBACd,MAAM+Q,OAAOe,uBAAuBuG,iBAAiBrY;oBACrD,MAAM8Y,OAAOpC,SAAS,gCAAgC;wBACpD,SAAS;oBACX;oBACA,KAAK,MAAMhF,cAAcX,KAAK,WAAW,IAAI,EAAE,CAC7C+H,KAAKpH,WAAW,OAAO;oBACzB,OAAOX;gBACT;YACF;YACAsH,kBAAkB;gBAAE,GAAGA,eAAe;gBAAEM;YAAW;QACrD;IAIF,MAAMD;IACN,KAAK,MAAMK,eAAerK,KAAK,YAAY,CACzC,MAAM6J,QAAQQ,YAAY,SAAS,EAAEA,YAAY,IAAI,EAAE;QACrD,MAAMA,YAAY,OAAO,CAACV;IAC5B;IACF,MAAME,QACJ,gBACArO,KAAKxF,QAAQyG,cAAc,cAC3B;QACE,MAAM6N,eAAe,MAAMpH,wBACzByG,iBACAC;QAEFD,kBAAkB;YAAE,GAAGA,eAAe;YAAEW;QAAa;IACvD;IAEF,MAAMP;IACN,IAAItC,wBACF,MAAM,IAAI9C,yBAAyBgF,iBAAiBjC;IACtD,OAAOiC;AACT;AChlBO,eAAeY,eACpB5R,UAAiC,CAAC,CAAC;IAEnC,OAAO6N,uBAAuB,MAAMnF,eAAe1I;AACrD"}
1
+ {"version":3,"file":"cli/index.mjs","sources":["../../../src/engine/registry.ts","../../../src/cli/test-project.ts","../../../src/parser/identifiers.ts","../../../src/parser/normalize.ts","../../../src/parser/source.ts","../../../src/parser/variables.ts","../../../src/parser/collect.ts","../../../src/cli/result-store.ts","../../../src/cli/project-preparation.ts","../../../src/cli/prepare-test-run.ts","../../../src/report/result-markdown.ts","../../../src/cli/document-invocation.ts","../../../src/cli/file-scheduler.ts","../../../src/cli/operation-journal.ts","../../../src/cli/run-prepared-project.ts","../../../src/cli/test-project-runner.ts"],"sourcesContent":["import { NodeRegistry as CoreNodeRegistry } from '@midscene/core/internal/test-runner';\nimport type { NodeDefinition } from '../node/types';\n\nexport type NodeRegistry = Omit<\n CoreNodeRegistry,\n 'get' | 'require' | 'register' | 'definitions'\n> & {\n get(name: string): NodeDefinition<any, any> | undefined;\n require(name: string): NodeDefinition<any, any>;\n register<TInput, TData>(node: NodeDefinition<TInput, TData>): NodeRegistry;\n definitions(): readonly NodeDefinition<any, any, any>[];\n};\nexport const NodeRegistry: {\n new (nodes?: readonly NodeDefinition<any, any>[]): NodeRegistry;\n} = CoreNodeRegistry;\n","import { dirname, isAbsolute, resolve, sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { require as tsxRequire } from 'tsx/cjs/api';\nimport { NodeRegistry } from '../engine/registry';\nimport type { NodeDefinition } from '../node/types';\n\nimport type {\n FileSetupDefinition,\n JsonValue,\n ProjectSetupDefinition,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nexport type {\n FileSetupContext,\n FileSetupDefinition,\n JsonPrimitive,\n JsonValue,\n ProjectSetupContext,\n ProjectSetupDefinition,\n ProjectTeardown,\n ProjectTeardownContext,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nimport type { ExecutionProjectDefinition as CoreExecutionProjectDefinition } from '@midscene/core/internal/test-runner';\n\nexport type ExecutionProjectDefinition<\n TContext = unknown,\n TProjectContext = TContext,\n> = Omit<\n CoreExecutionProjectDefinition<TProjectContext>,\n 'nodes' | 'fileSetup'\n> & {\n fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n};\n\nexport interface TestOptions {\n /** Global active files, including preparation and cleanup. Default 1; null is unlimited. */\n maxConcurrentFiles?: number | null;\n /** Projects from setup through completed cleanup. Default 1; null is unlimited. */\n maxConcurrentProjects?: number | null;\n /** Milliseconds for each Project setup/fileSetup, including device waits. */\n setupTimeout?: number;\n /** Milliseconds per cleanup scope; shared deadline during abnormal shutdown. */\n teardownTimeout?: number;\n bail?: number;\n testTimeout?: number;\n}\n\nexport interface ResolvedTestOptions {\n maxConcurrentFiles: number | null;\n maxConcurrentProjects: number | null;\n setupTimeout: number;\n teardownTimeout: number;\n bail: number;\n testTimeout: number;\n}\n\nexport interface TestOutputDefinition {\n reportDir?: string;\n}\n\nexport interface ResolvedTestOutputDefinition {\n reportDir: string;\n}\n\nconst projectIdFromIndex = (index: number): string => `project-${index}`;\n\nexport interface TestProjectDefinition<\n TContext = undefined,\n TProjectContext = TContext,\n> {\n setup?: ProjectSetupDefinition<TProjectContext>;\n fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n projects?: readonly ExecutionProjectDefinition<TContext, TProjectContext>[];\n test?: TestOptions;\n output?: TestOutputDefinition;\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n}\n\nexport interface LoadedExecutionProject<\n TContext = unknown,\n TProjectContext = TContext,\n> extends ResolvedExecutionProject<TProjectContext> {\n readonly fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n /** Effective Nodes: globals plus project-local overrides. */\n readonly nodes: NodeRegistry;\n}\n\nexport interface LoadedTestProject<\n TContext = undefined,\n TProjectContext = TContext,\n> {\n projects: readonly LoadedExecutionProject<TContext, TProjectContext>[];\n hasExplicitProjects: boolean;\n test: ResolvedTestOptions;\n output: ResolvedTestOutputDefinition;\n nodes: NodeRegistry;\n resolveNode(name: string): NodeDefinition<any, any, TContext> | undefined;\n}\n\nexport const defineTestProject = <\n TContext = undefined,\n TProjectContext = TContext,\n>(\n definition: TestProjectDefinition<TContext, TProjectContext>,\n): TestProjectDefinition<TContext, TProjectContext> => definition;\n\nexport const defineProjectSetup = <TProjectContext>(\n definition: ProjectSetupDefinition<TProjectContext>,\n): ProjectSetupDefinition<TProjectContext> => definition;\n\nexport const defineFileSetup = <TContext, TProjectContext = unknown>(\n definition: FileSetupDefinition<TContext, TProjectContext>,\n): FileSetupDefinition<TContext, TProjectContext> => definition;\n\nconst getDefaultExport = (loaded: unknown, absolutePath: string): unknown => {\n if (typeof loaded === 'object' && loaded !== null && 'default' in loaded) {\n const defaultExport = (loaded as { default: unknown }).default;\n if (\n typeof defaultExport === 'object' &&\n defaultExport !== null &&\n '__esModule' in defaultExport\n ) {\n if ('default' in defaultExport) {\n return (defaultExport as { default: unknown }).default;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n }\n return defaultExport;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowedKeys: readonly string[],\n label: string,\n): void => {\n const allowed = new Set(allowedKeys);\n const unknown = Object.keys(value).find((key) => !allowed.has(key));\n if (unknown) {\n throw new TypeError(\n `Midscene config ${label}.${unknown} is not supported.`,\n );\n }\n};\n\nconst isAbsolutePattern = (pattern: string): boolean =>\n isAbsolute(pattern) ||\n /^[A-Za-z]:[\\\\/]/.test(pattern) ||\n pattern.startsWith('\\\\\\\\');\n\nconst validatePatterns = (\n value: unknown,\n field: 'include' | 'exclude',\n label = 'files',\n allowEmptyInclude = false,\n): readonly string[] => {\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n if (field === 'include' && value.length === 0 && !allowEmptyInclude) {\n throw new TypeError(\n `Midscene config ${label}.include must be a non-empty array.`,\n );\n }\n\n return value.map((pattern, index) => {\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n if (isAbsolutePattern(pattern)) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be relative to the project root.`,\n );\n }\n if (pattern.split(/[\\\\/]/).includes('..')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must not contain a \"..\" path segment.`,\n );\n }\n if (pattern.includes('\\\\')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must use POSIX path separators (/).`,\n );\n }\n if (pattern.startsWith('!')) {\n if (field === 'include') {\n throw new TypeError(\n `Midscene config ${label}.include[${index}] must not be a negated pattern. Use files.exclude instead.`,\n );\n }\n throw new TypeError(\n `Midscene config ${label}.exclude[${index}] must not be a negated pattern.`,\n );\n }\n return pattern;\n });\n};\n\nexport const validateTestFileSelection = (\n value: unknown,\n label = 'files',\n): TestFileSelection | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['include', 'exclude'], label);\n const include = validatePatterns(value.include, 'include', label);\n const exclude =\n value.exclude === undefined\n ? undefined\n : validatePatterns(value.exclude, 'exclude', label);\n return Object.freeze({\n include: Object.freeze(include),\n ...(exclude ? { exclude: Object.freeze(exclude) } : {}),\n });\n};\n\nconst validateTagList = (\n value: unknown,\n field: 'include' | 'exclude',\n label: string,\n): readonly string[] => {\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n return value.map((tag, index) => {\n if (typeof tag !== 'string' || tag.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n return tag;\n });\n};\n\nconst validateTagSelection = (\n value: unknown,\n label: string,\n): Readonly<Required<TestTagSelection>> => {\n if (value === undefined) return Object.freeze({ include: [], exclude: [] });\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n return Object.freeze({\n include: Object.freeze(validateTagList(value.include, 'include', label)),\n exclude: Object.freeze(validateTagList(value.exclude, 'exclude', label)),\n });\n};\n\nfunction assertJsonValue(\n value: unknown,\n path: string,\n seen: Set<unknown>,\n): asserts value is JsonValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean'\n ) {\n return;\n }\n if (typeof value === 'number') {\n if (Number.isFinite(value)) return;\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (typeof value !== 'object' || value === undefined) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n ) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (seen.has(value)) {\n throw new TypeError(`Midscene config ${path} must not contain cycles.`);\n }\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertJsonValue(item, `${path}[${index}]`, seen),\n );\n } else {\n for (const [key, child] of Object.entries(value)) {\n assertJsonValue(child, `${path}.${key}`, seen);\n }\n }\n seen.delete(value);\n}\n\nconst deepFreezeJson = <T extends JsonValue>(value: T): T => {\n if (typeof value === 'object' && value !== null) {\n for (const child of Object.values(value)) deepFreezeJson(child);\n Object.freeze(value);\n }\n return value;\n};\n\nconst validateVariables = (\n value: unknown,\n label: string,\n): Readonly<Record<string, JsonValue>> => {\n if (value === undefined) return Object.freeze({});\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n assertJsonValue(value, label, new Set());\n return deepFreezeJson(value as Record<string, JsonValue>);\n};\n\nconst validateSetup = <TSetup>(\n value: unknown,\n label: string,\n): TSetup | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['name', 'setup'], label);\n if (typeof value.name !== 'string' || value.name.trim().length === 0) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (typeof value.setup !== 'function') {\n throw new TypeError(`Midscene config ${label}.setup must be a function.`);\n }\n return value as unknown as TSetup;\n};\n\nconst validatePositiveInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) <= 0) {\n throw new TypeError(`Midscene config ${label} must be a positive integer.`);\n }\n return value as number;\n};\n\nconst validateNonNegativeInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) < 0) {\n throw new TypeError(\n `Midscene config ${label} must be a non-negative integer.`,\n );\n }\n return value as number;\n};\n\nconst validateConcurrency = (value: unknown, label: string): number | null => {\n if (value === null) return null;\n return validatePositiveInteger(value, 1, label);\n};\n\nconst validateFileConcurrency = (\n maxConcurrentFiles: number,\n fileSetup: unknown,\n label: string,\n): void => {\n if (maxConcurrentFiles > 1 && !fileSetup) {\n throw new TypeError(\n `Midscene config ${label}.fileSetup is required when the effective maxConcurrentFiles is greater than 1.`,\n );\n }\n};\n\nconst validateExecutionProjects = <TContext, TProjectContext>(\n value: unknown,\n defaultSetup: unknown,\n defaultFileSetup: unknown,\n globalNodes: NodeRegistry,\n test: ResolvedTestOptions,\n): {\n projects: readonly LoadedExecutionProject<TContext, TProjectContext>[];\n hasExplicitProjects: boolean;\n} => {\n if (value === undefined) {\n const setup = validateSetup<ProjectSetupDefinition<TProjectContext>>(\n defaultSetup,\n 'setup',\n );\n const fileSetup = validateSetup<\n FileSetupDefinition<TContext, TProjectContext>\n >(defaultFileSetup, 'fileSetup');\n const maxConcurrentFiles =\n test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY;\n validateFileConcurrency(maxConcurrentFiles, fileSetup, 'default');\n return {\n hasExplicitProjects: false,\n projects: Object.freeze([\n Object.freeze({\n projectId: projectIdFromIndex(0),\n name: 'default',\n ...(setup ? { setup } : {}),\n ...(fileSetup ? { fileSetup } : {}),\n maxConcurrentFiles,\n tags: Object.freeze({ include: [], exclude: [] }),\n retry: 0,\n variables: Object.freeze({}),\n nodes: new NodeRegistry(globalNodes.definitions()),\n }),\n ]),\n };\n }\n if (defaultSetup !== undefined) {\n throw new TypeError(\n 'Midscene config setup cannot be used together with projects. Move setup to projects[].setup.',\n );\n }\n if (defaultFileSetup !== undefined) {\n throw new TypeError(\n 'Midscene config fileSetup cannot be used together with projects. Move fileSetup to projects[].fileSetup.',\n );\n }\n if (!Array.isArray(value) || value.length === 0) {\n throw new TypeError(\n 'Midscene config projects must be a non-empty array when declared.',\n );\n }\n const names = new Set<string>();\n const projects = value.map((candidate, index) => {\n const label = `projects[${index}]`;\n if (!isRecord(candidate)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(\n candidate,\n [\n 'name',\n 'setup',\n 'fileSetup',\n 'maxConcurrentFiles',\n 'nodes',\n 'files',\n 'tags',\n 'retry',\n 'variables',\n ],\n label,\n );\n if (\n typeof candidate.name !== 'string' ||\n candidate.name.trim().length === 0\n ) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (names.has(candidate.name)) {\n throw new TypeError(\n `Midscene config project name \"${candidate.name}\" must be unique.`,\n );\n }\n names.add(candidate.name);\n const files = validateTestFileSelection(candidate.files, `${label}.files`);\n if (candidate.nodes !== undefined && !Array.isArray(candidate.nodes)) {\n throw new TypeError(`Midscene config ${label}.nodes must be an array.`);\n }\n const localNodes = new NodeRegistry(\n candidate.nodes as NodeDefinition[] | undefined,\n );\n const nodes = new NodeRegistry([\n ...globalNodes.definitions().filter((node) => !localNodes.has(node.name)),\n ...localNodes.definitions(),\n ]);\n const fileSetup = validateSetup<\n FileSetupDefinition<TContext, TProjectContext>\n >(candidate.fileSetup, `${label}.fileSetup`);\n const globalFileLimit = test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY;\n const maxConcurrentFiles = Math.min(\n globalFileLimit,\n validatePositiveInteger(\n candidate.maxConcurrentFiles,\n globalFileLimit,\n `${label}.maxConcurrentFiles`,\n ),\n );\n validateFileConcurrency(maxConcurrentFiles, fileSetup, label);\n return Object.freeze({\n projectId: projectIdFromIndex(index),\n name: candidate.name,\n nodes,\n ...(fileSetup ? { fileSetup } : {}),\n maxConcurrentFiles,\n ...(files ? { files } : {}),\n tags: validateTagSelection(candidate.tags, `${label}.tags`),\n retry: validateNonNegativeInteger(candidate.retry, 0, `${label}.retry`),\n variables: validateVariables(candidate.variables, `${label}.variables`),\n ...(candidate.setup === undefined\n ? {}\n : {\n setup: validateSetup<ProjectSetupDefinition<TProjectContext>>(\n candidate.setup,\n `${label}.setup`,\n )!,\n }),\n });\n });\n return { projects: Object.freeze(projects), hasExplicitProjects: true };\n};\n\nconst validateTestOptions = (\n value: unknown,\n hasExplicitProjects: boolean,\n): ResolvedTestOptions => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config test must be an object.');\n }\n const candidate = (value ?? {}) as Record<string, unknown>;\n if (candidate.maxConcurrency !== undefined) {\n const limit =\n typeof candidate.maxConcurrency === 'number' &&\n Number.isInteger(candidate.maxConcurrency) &&\n candidate.maxConcurrency > 0\n ? candidate.maxConcurrency\n : 1;\n throw new TypeError(\n [\n 'Midscene config test.maxConcurrency is no longer supported.',\n 'It controlled project concurrency, not file concurrency. Remove it and use:',\n ` test: { maxConcurrentProjects: ${limit}, maxConcurrentFiles: ${hasExplicitProjects ? limit : 1} }`,\n hasExplicitProjects\n ? ' Set projects[].maxConcurrentFiles to 1 to keep files sequential within each project.'\n : ' The implicit default project keeps running files sequentially.',\n hasExplicitProjects\n ? 'For parallel files, configure fileSetup and raise both test.maxConcurrentFiles and projects[].maxConcurrentFiles.'\n : 'For parallel files, configure fileSetup and raise test.maxConcurrentFiles.',\n 'Migration guide: https://midscenejs.com/midscene-test/configuration.html#existing-configurations',\n ].join('\\n'),\n );\n }\n return Object.freeze({\n maxConcurrentFiles: validateConcurrency(\n candidate.maxConcurrentFiles,\n 'test.maxConcurrentFiles',\n ),\n maxConcurrentProjects: validateConcurrency(\n candidate.maxConcurrentProjects,\n 'test.maxConcurrentProjects',\n ),\n setupTimeout: validatePositiveInteger(\n candidate.setupTimeout,\n 120_000,\n 'test.setupTimeout',\n ),\n teardownTimeout: validatePositiveInteger(\n candidate.teardownTimeout,\n 30_000,\n 'test.teardownTimeout',\n ),\n bail: validateNonNegativeInteger(\n (candidate as Record<string, unknown>).bail,\n 0,\n 'test.bail',\n ),\n testTimeout: validatePositiveInteger(\n (candidate as Record<string, unknown>).testTimeout,\n 120_000,\n 'test.testTimeout',\n ),\n });\n};\n\nconst validateOutputPath = (\n value: unknown,\n fallback: string,\n label: string,\n): string => {\n if (value === undefined) return fallback;\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new TypeError(`Midscene config ${label} must be non-empty.`);\n }\n return value;\n};\n\nconst validateOutput = (value: unknown): ResolvedTestOutputDefinition => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config output must be an object.');\n }\n const candidate = (value ?? {}) as Record<string, unknown>;\n rejectUnknownKeys(candidate, ['reportDir'], 'output');\n return Object.freeze({\n reportDir: validateOutputPath(\n candidate.reportDir,\n './midscene_run/report',\n 'output.reportDir',\n ),\n });\n};\n\nconst validateTestProjectDefinition = <TContext, TProjectContext = TContext>(\n definition: unknown,\n): LoadedTestProject<TContext, TProjectContext> => {\n if (!isRecord(definition)) {\n throw new TypeError('Midscene config must default export an object.');\n }\n if (definition.nodes !== undefined && !Array.isArray(definition.nodes)) {\n throw new TypeError('Midscene config nodes must be an array.');\n }\n if ('setupWorkflow' in definition) {\n throw new TypeError(\n 'Midscene config setupWorkflow is no longer supported. Use setup or projects[].setup instead.',\n );\n }\n if ('setupDocument' in definition) {\n throw new TypeError(\n 'Midscene config setupDocument is not supported. Use setup or projects[].setup for resources, and beforeAll/afterAll for document lifecycle steps.',\n );\n }\n if ('root' in definition) {\n throw new TypeError(\n 'Midscene config root is not supported. Pass the Test Project directory to midscene-test instead.',\n );\n }\n if ('files' in definition) {\n throw new TypeError(\n 'Midscene config files is not supported at the root. Move it to projects[].files.',\n );\n }\n if ('testRunner' in definition) {\n throw new TypeError(\n 'Midscene config testRunner is not supported. Rename it to test.',\n );\n }\n rejectUnknownKeys(\n definition,\n ['setup', 'fileSetup', 'projects', 'test', 'output', 'nodes'],\n 'root',\n );\n const nodes = new NodeRegistry(\n definition.nodes as NodeDefinition[] | undefined,\n );\n const test = validateTestOptions(\n definition.test,\n definition.projects !== undefined,\n );\n const resolvedProjects = validateExecutionProjects<TContext, TProjectContext>(\n definition.projects,\n definition.setup,\n definition.fileSetup,\n nodes,\n test,\n );\n return {\n ...resolvedProjects,\n test,\n output: validateOutput(definition.output),\n nodes,\n resolveNode: (name) =>\n nodes.get(name) as NodeDefinition<any, any, TContext> | undefined,\n };\n};\n\nconst assertSupportedConfig = (absolutePath: string): '.ts' | '.mjs' => {\n if (!absolutePath.endsWith('.ts') && !absolutePath.endsWith('.mjs')) {\n const extension = absolutePath.match(/(\\.[^./\\\\]+)$/)?.[1] ?? '(none)';\n throw new TypeError(\n `Unsupported Midscene config extension: ${extension}. Supported extensions: .ts, .mjs.`,\n );\n }\n return absolutePath.endsWith('.mjs') ? '.mjs' : '.ts';\n};\n\nconst canRetryWithCjsLoader = (error: unknown): error is Error => {\n if (!(error instanceof Error)) return false;\n const errorCode = (error as Error & { code?: string }).code;\n return (\n (error instanceof SyntaxError &&\n /^Unexpected (?:identifier|reserved word|token)/.test(error.message)) ||\n errorCode === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' ||\n (errorCode === 'ERR_UNKNOWN_FILE_EXTENSION' &&\n /^Unknown file extension\\b/.test(error.message))\n );\n};\n\nexport async function loadTestProject<\n TContext = undefined,\n TProjectContext = TContext,\n>(configPath?: string): Promise<LoadedTestProject<TContext, TProjectContext>> {\n if (!configPath) {\n return validateTestProjectDefinition<TContext, TProjectContext>({\n nodes: [],\n });\n }\n\n const absolutePath = resolve(configPath);\n const extension = assertSupportedConfig(absolutePath);\n let loaded: unknown;\n try {\n if (extension === '.mjs') {\n loaded = await import(pathToFileURL(absolutePath).href);\n } else {\n // Select tsx's ESM entry even when this loader is built as CommonJS.\n // Its CommonJS entry can resolve the async loader relative to the wrong directory.\n const { tsImport } = await import('tsx/esm/api');\n loaded = await tsImport(pathToFileURL(absolutePath).href, {\n parentURL: pathToFileURL(`${dirname(absolutePath)}${sep}`).href,\n tsconfig: false,\n });\n }\n } catch (error) {\n try {\n if (extension === '.mjs' || !canRetryWithCjsLoader(error)) throw error;\n loaded = tsxRequire(absolutePath, pathToFileURL(absolutePath));\n } catch (fallbackError) {\n const message =\n fallbackError instanceof Error ? `: ${fallbackError.message}` : '';\n throw new Error(\n `Failed to load Midscene config \"${absolutePath}\"${message}`,\n { cause: fallbackError },\n );\n }\n }\n\n return validateTestProjectDefinition<TContext, TProjectContext>(\n getDefaultExport(loaded, absolutePath),\n );\n}\n","import { createHash } from 'node:crypto';\n\n/** Internal invocation identity keeps repeated legacy files distinct. */\nexport const createCaseInvocationId = (\n projectId: string,\n sourcePath: string,\n caseIndex: number,\n invocationIndex = 0,\n): string =>\n createHash('sha256')\n .update(\n JSON.stringify([\n projectId,\n sourcePath,\n caseIndex,\n ...(invocationIndex ? [invocationIndex] : []),\n ]),\n )\n .digest('hex');\n\nexport const createDocumentInvocationId = (\n projectId: string,\n sourcePath: string,\n invocationIndex = 0,\n): string =>\n createHash('sha256')\n .update(\n JSON.stringify([\n projectId,\n sourcePath,\n ...(invocationIndex ? [invocationIndex] : []),\n ]),\n )\n .digest('hex');\n","import {\n type ResolveNodeForNormalization,\n normalizeStep as coreNormalizeStep,\n normalizeSteps as coreNormalizeSteps,\n} from '@midscene/core/internal/test-runner';\nimport type { NormalizedStep } from './types';\nexport type { ResolveNodeForNormalization } from '@midscene/core/internal/test-runner';\n\nexport const normalizeStep: (\n value: unknown,\n index?: number,\n resolveNode?: ResolveNodeForNormalization,\n) => NormalizedStep = coreNormalizeStep;\nexport const normalizeSteps: (\n values: unknown,\n resolveNode?: ResolveNodeForNormalization,\n) => NormalizedStep[] = coreNormalizeSteps;\n","import type { TestRunReportValue } from '@midscene/core';\nimport {\n isReportSecretKey,\n sanitizeReportText,\n} from '@midscene/core/internal/test-runner';\nimport { JSON_SCHEMA, load } from 'js-yaml';\n\ninterface SourceNode {\n start: number;\n end: number;\n value: unknown;\n children: SourceNode[];\n}\n\n/** Keep author formatting while redacting values by parsed YAML keys, including aliases. */\nexport function parseWorkflowSource(source: string): {\n parsed: unknown;\n sourceYaml: TestRunReportValue;\n} {\n const stack: SourceNode[] = [];\n const nodes: SourceNode[] = [];\n const sensitiveNodes = new Set<SourceNode>();\n const sensitiveValues = new Set<unknown>();\n const redactedPaths = new Set<string>();\n // js-yaml removes the BOM before reporting source positions.\n const sourceOffset = source.charCodeAt(0) === 0xfeff ? 1 : 0;\n const parsed = load(source, {\n schema: JSON_SCHEMA,\n listener(event, state) {\n if (event === 'open') {\n stack.push({\n start: state.position + sourceOffset,\n end: 0,\n value: null,\n children: [],\n });\n return;\n }\n const node = stack.pop()!;\n node.end = state.position + sourceOffset;\n node.value = state.result;\n stack.at(-1)?.children.push(node);\n nodes.push(node);\n if (state.kind !== 'mapping') return;\n for (let index = 0; index < node.children.length; index += 2) {\n const key = node.children[index].value;\n const value = node.children[index + 1];\n if (typeof key !== 'string' || !isReportSecretKey(key) || !value)\n continue;\n sensitiveNodes.add(value);\n if (value.value !== null) sensitiveValues.add(value.value);\n redactedPaths.add(`$..[${JSON.stringify(key)}]`);\n }\n },\n });\n // Redact the definition as well when a secret value refers to a YAML anchor.\n const ranges = nodes\n .filter(\n (node) => sensitiveNodes.has(node) || sensitiveValues.has(node.value),\n )\n .sort((left, right) => left.start - right.start || right.end - left.end);\n let offset = 0;\n let redacted = '';\n for (const range of ranges) {\n if (range.start < offset) continue;\n const text = source.slice(range.start, range.end);\n const leading = text.match(/^\\s*/)?.[0] ?? '';\n const trailing = text.slice(leading.length).match(/\\s*$/)?.[0] ?? '';\n redacted += `${source.slice(offset, range.start)}${leading}\"[REDACTED]\"${trailing}`;\n offset = range.end;\n }\n redacted += source.slice(offset);\n const value = sanitizeReportText(redacted, 64 * 1024);\n return {\n parsed,\n sourceYaml: {\n value,\n ...(redactedPaths.size ? { redactedPaths: [...redactedPaths] } : {}),\n ...(value !== redacted ? { truncatedPaths: ['$'] } : {}),\n },\n };\n}\n","import type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\n\nexport interface VariableResolutionLocation {\n projectName: string;\n sourcePath: string;\n phase: 'beforeAll' | 'beforeEach' | 'steps' | 'afterEach' | 'afterAll';\n stepIndex: number;\n caseIndex?: number;\n}\n\nexport interface ResolveWorkflowVariablesOptions {\n variables?: Readonly<Record<string, JsonValue>>;\n env?: Readonly<NodeJS.ProcessEnv>;\n location: VariableResolutionLocation;\n}\n\nconst interpolationExpression =\n /\\$\\{\\{([A-Za-z_][A-Za-z0-9_]*)\\}\\}|\\$\\{([^{}]+)\\}/g;\nconst exactEnvExpression = /^\\$\\{\\{([A-Za-z_][A-Za-z0-9_]*)\\}\\}$/;\nconst exactProjectExpression = /^\\$\\{([^{}]+)\\}$/;\n\nconst missingVariable = (\n kind: 'environment' | 'project',\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): never => {\n throw new WorkflowParseError(\n `Undefined ${kind} variable \"${name}\" in ${options.location.sourcePath}.`,\n { ...options.location, variable: name, variableKind: kind },\n );\n};\n\nconst projectVariable = (\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): JsonValue => {\n if (!Object.hasOwn(options.variables ?? {}, name)) {\n return missingVariable('project', name, options);\n }\n return options.variables![name];\n};\n\nconst environmentVariable = (\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): string => {\n const value = options.env?.[name];\n if (value === undefined) return missingVariable('environment', name, options);\n return value;\n};\n\nconst interpolationValue = (\n name: string,\n value: JsonValue,\n options: ResolveWorkflowVariablesOptions,\n): string => {\n if (typeof value === 'object' && value !== null) {\n throw new WorkflowParseError(\n `Project variable \"${name}\" must be a primitive when embedded in a string.`,\n {\n ...options.location,\n variable: name,\n variableKind: 'project',\n },\n );\n }\n return String(value);\n};\n\nconst resolveString = (\n value: string,\n options: ResolveWorkflowVariablesOptions,\n): JsonValue => {\n const exactEnv = exactEnvExpression.exec(value);\n if (exactEnv) return environmentVariable(exactEnv[1], options);\n const exactProject = exactProjectExpression.exec(value);\n if (exactProject) return projectVariable(exactProject[1], options);\n\n return value.replace(\n interpolationExpression,\n (_match, environmentName: string | undefined, projectName: string) =>\n environmentName\n ? environmentVariable(environmentName, options)\n : interpolationValue(\n projectName,\n projectVariable(projectName, options),\n options,\n ),\n );\n};\n\nexport const resolveWorkflowVariables = (\n value: unknown,\n options: ResolveWorkflowVariablesOptions,\n): unknown => {\n if (typeof value === 'string') return resolveString(value, options);\n if (Array.isArray(value)) {\n return value.map((child) => resolveWorkflowVariables(child, options));\n }\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n key,\n resolveWorkflowVariables(child, options),\n ]),\n );\n }\n return value;\n};\n","import { readFileSync } from 'node:fs';\nimport { sep } from 'node:path';\nimport { classifyWorkflowDocumentFormat } from '@midscene/core/internal/test-runner';\nimport type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\nimport type { NodeDefinition } from '../node/types';\nimport {\n createCaseInvocationId,\n createDocumentInvocationId,\n} from './identifiers';\nimport { normalizeSteps } from './normalize';\nimport { parseWorkflowSource } from './source';\nimport type {\n CollectedCase,\n CollectedWorkflowDocument,\n WorkflowDocumentSource,\n} from './types';\nimport { resolveWorkflowVariables } from './variables';\n\nexport interface CollectWorkflowDocumentOptions {\n resolveNode(name: string): NodeDefinition<any, any> | undefined;\n variables?: Readonly<Record<string, JsonValue>>;\n env?: Readonly<NodeJS.ProcessEnv>;\n}\n\nconst isMapping = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nexport class NativeWorkflowFormatError extends WorkflowParseError {\n readonly actualFormat: 'legacy' | 'legacy-batch' | 'mixed';\n\n constructor(\n actualFormat: 'legacy' | 'legacy-batch' | 'mixed',\n sourcePath: string,\n ) {\n super(\n actualFormat === 'legacy'\n ? `Legacy tasks/flow YAML is not supported by midscene-test: ${sourcePath}. Run it with \\`midscene ${sourcePath}\\`, or migrate the file to cases/steps.`\n : actualFormat === 'legacy-batch'\n ? `Legacy YAML batch configuration is not a midscene-test workflow document: ${sourcePath}. Run it with \\`midscene --config ${sourcePath}\\`, or migrate it to a native project config.`\n : `A workflow file cannot mix legacy tasks/flow with native cases/steps or lifecycle hooks: ${sourcePath}. Keep the formats in separate files and run each file with its matching command.`,\n { sourcePath, actualFormat, expectedFormat: 'native' },\n );\n this.actualFormat = actualFormat;\n }\n}\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowed: readonly string[],\n label: string,\n) => {\n const allowedSet = new Set(allowed);\n const unknown = Object.keys(value).filter((key) => !allowedSet.has(key));\n if (unknown.length) {\n throw new WorkflowParseError(\n `${label} has unsupported field \"${unknown[0]}\".`,\n { field: unknown[0] },\n );\n }\n};\n\nexport const createCaseId = (\n projectId: string,\n sourcePath: string,\n caseIndex: number,\n): string => createCaseInvocationId(projectId, sourcePath, caseIndex);\n\nexport const createWorkflowDocumentId = (\n projectId: string,\n sourcePath: string,\n): string => createDocumentInvocationId(projectId, sourcePath);\n\nexport function collectWorkflowDocument(\n source: WorkflowDocumentSource,\n options: CollectWorkflowDocumentOptions,\n): CollectedWorkflowDocument {\n let snapshot: ReturnType<typeof parseWorkflowSource>;\n try {\n snapshot = parseWorkflowSource(readFileSync(source.absolutePath, 'utf8'));\n } catch (error) {\n throw new WorkflowParseError(\n `Failed to parse workflow document \"${source.sourcePath}\".`,\n { sourcePath: source.sourcePath },\n error,\n );\n }\n const { parsed, sourceYaml } = snapshot;\n\n if (!isMapping(parsed)) {\n throw new WorkflowParseError('Workflow document must be a mapping.');\n }\n const format = classifyWorkflowDocumentFormat(parsed);\n if (format === 'legacy' || format === 'legacy-batch' || format === 'mixed') {\n throw new NativeWorkflowFormatError(format, source.sourcePath);\n }\n rejectUnknownKeys(\n parsed,\n ['beforeAll', 'beforeEach', 'cases', 'afterEach', 'afterAll'],\n 'Workflow document',\n );\n if (!Array.isArray(parsed.cases) || parsed.cases.length === 0) {\n throw new WorkflowParseError(\n 'Workflow document must contain a non-empty cases array.',\n );\n }\n\n const sourcePath = source.sourcePath.split(sep).join('/');\n const resolveStepVariables = (\n step: ReturnType<typeof normalizeSteps>[number],\n phase: 'beforeAll' | 'beforeEach' | 'steps' | 'afterEach' | 'afterAll',\n stepIndex: number,\n caseIndex?: number,\n ) => ({\n ...step,\n templateInput: step.input,\n input: resolveWorkflowVariables(step.input, {\n variables: options.variables,\n env: options.env ?? process.env,\n location: {\n projectName: source.projectName ?? source.projectId,\n sourcePath,\n phase,\n stepIndex,\n ...(caseIndex === undefined ? {} : { caseIndex }),\n },\n }) as typeof step.input,\n });\n const normalizeLifecycle = (\n phase: 'beforeAll' | 'beforeEach' | 'afterEach' | 'afterAll',\n ) => {\n const value = parsed[phase];\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new WorkflowParseError(\n `Workflow document ${phase} must be an array.`,\n { phase },\n );\n }\n return normalizeSteps(value, options.resolveNode).map(\n (normalized, stepIndex) => {\n const resolved = options.resolveNode(normalized.node);\n if (!resolved) {\n throw new WorkflowParseError(\n `Workflow document ${phase} step ${stepIndex + 1} references unknown node \"${normalized.node}\".`,\n { phase, stepIndex, node: normalized.node },\n );\n }\n return resolveStepVariables(normalized, phase, stepIndex);\n },\n );\n };\n const lifecycle = {\n beforeAll: normalizeLifecycle('beforeAll'),\n beforeEach: normalizeLifecycle('beforeEach'),\n afterEach: normalizeLifecycle('afterEach'),\n afterAll: normalizeLifecycle('afterAll'),\n };\n const ids = new Set<string>();\n const cases: CollectedCase[] = parsed.cases.map((definition, caseIndex) => {\n if (!isMapping(definition)) {\n throw new WorkflowParseError(`Case ${caseIndex + 1} must be a mapping.`, {\n caseIndex,\n });\n }\n rejectUnknownKeys(\n definition,\n ['name', 'tags', 'steps'],\n `Case ${caseIndex + 1}`,\n );\n if (\n typeof definition.name !== 'string' ||\n definition.name.trim().length === 0\n ) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} name must be a non-empty string.`,\n { caseIndex },\n );\n }\n if (!Array.isArray(definition.steps) || definition.steps.length === 0) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} steps must be a non-empty array.`,\n { caseIndex },\n );\n }\n const tags = definition.tags ?? [];\n if (\n !Array.isArray(tags) ||\n tags.some((tag) => typeof tag !== 'string' || tag.trim().length === 0)\n ) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} tags must be an array of non-empty strings.`,\n { caseIndex },\n );\n }\n\n const steps = normalizeSteps(definition.steps, options.resolveNode).map(\n (normalized, stepIndex) => {\n if (!options.resolveNode(normalized.node)) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} step ${stepIndex + 1} references unknown node \"${normalized.node}\".`,\n { caseIndex, stepIndex, node: normalized.node },\n );\n }\n return resolveStepVariables(normalized, 'steps', stepIndex, caseIndex);\n },\n );\n const caseId = createCaseId(source.projectId, sourcePath, caseIndex);\n if (ids.has(caseId)) {\n throw new WorkflowParseError(`Case id collision: ${caseId}.`, {\n caseId,\n });\n }\n ids.add(caseId);\n\n return {\n caseId,\n projectId: source.projectId,\n sourcePath,\n caseIndex,\n definition: {\n name: definition.name,\n tags: tags as string[],\n steps,\n },\n };\n });\n\n return {\n documentId: createWorkflowDocumentId(source.projectId, sourcePath),\n projectId: source.projectId,\n sourcePath,\n sourceYaml,\n lifecycle,\n cases,\n } satisfies CollectedWorkflowDocument;\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport {\n WorkflowPublicationError,\n sanitizeReportError,\n} from '@midscene/core/internal/test-runner';\nimport type { CaseRunResult, WorkflowDocumentRunResult } from '../engine/types';\nimport type { PreparedExecutionProject } from './execution-plan';\nimport type { TestProjectCollectionError, TestProjectRunResult } from './types';\n\nconst writeJson = async (path: string, value: unknown) => {\n try {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, JSON.stringify(value, null, 2));\n } catch (error) {\n throw new WorkflowPublicationError('write-result', path, error);\n }\n};\n\nexport const writeTestRunPlan = (\n runDir: string,\n projects: readonly PreparedExecutionProject[],\n) =>\n writeJson(join(runDir, 'plan.json'), {\n schemaVersion: 1,\n createdAt: new Date().toISOString(),\n projects: projects.map((item) => ({\n projectId: item.project.projectId,\n name: item.project.name,\n documents: item.plans ?? [],\n })),\n });\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nexport const caseAttemptResultPath = (\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n): string =>\n toPosix(\n join(\n projectId,\n 'documents',\n documentId,\n 'cases',\n result.caseId,\n `${result.runId}.json`,\n ),\n );\n\nexport const workflowDocumentResultPath = (\n result: WorkflowDocumentRunResult,\n): string =>\n toPosix(\n join(\n result.projectId,\n 'documents',\n result.documentId,\n result.attemptIndex === undefined\n ? 'document.json'\n : `${result.documentRunId}.json`,\n ),\n );\n\nexport const collectionErrorPath = (\n projectId: string,\n sourcePath: string,\n): string => {\n const id = createHash('sha256')\n .update(JSON.stringify([projectId, sourcePath]))\n .digest('hex');\n return toPosix(join(projectId, 'collection-errors', `${id}.json`));\n};\n\nexport const writeWorkflowDocumentResult = (\n runDir: string,\n result: WorkflowDocumentRunResult,\n) => {\n const { documentRunId: _documentRunId, ...persistedResult } = result;\n return writeJson(\n join(runDir, workflowDocumentResultPath(result)),\n persistedResult,\n );\n};\n\nexport const writeCaseAttemptResult = (\n runDir: string,\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n) => {\n const { runId: attemptId, ...persistedResult } = result;\n return writeJson(\n join(runDir, caseAttemptResultPath(projectId, documentId, result)),\n {\n ...persistedResult,\n attemptId,\n },\n );\n};\n\nexport const writeCollectionError = (\n runDir: string,\n collectionError: TestProjectCollectionError,\n) => {\n return writeJson(\n join(\n runDir,\n collectionErrorPath(\n collectionError.projectId,\n collectionError.sourcePath,\n ),\n ),\n { kind: 'collection-error', ...collectionError },\n );\n};\n\nconst relativeToSummary = (summaryPath: string, target: string): string => {\n const value = relative(dirname(summaryPath), target);\n return toPosix(value || '.');\n};\n\nconst errorJson = sanitizeReportError;\n\nexport interface TestProjectResultFileOptions {\n projectRoot: string;\n configPath?: string;\n result: TestProjectRunResult;\n}\n\nexport const writeTestProjectRunResult = (\n options: TestProjectResultFileOptions,\n) => {\n const { result } = options;\n const fact = (path: string) => toPosix(path);\n\n return writeJson(result.summaryPath, {\n schemaVersion: result.schemaVersion,\n runId: result.runId,\n startedAt: result.startedAt,\n endedAt: result.endedAt,\n durationMs: result.durationMs,\n status: result.status,\n exitCode: result.exitCode,\n ...(result.errors?.length ? { errors: result.errors.map(errorJson) } : {}),\n projectRoot: options.projectRoot,\n ...(options.configPath ? { configPath: options.configPath } : {}),\n factsRoot: '.',\n plan: 'plan.json',\n ...(result.operationLog\n ? {\n operationLog: {\n ...result.operationLog,\n path: relativeToSummary(\n result.summaryPath,\n result.operationLog.path,\n ),\n },\n }\n : {}),\n reportDir: relativeToSummary(result.summaryPath, result.reportDir),\n ...(result.reportPath\n ? { report: relativeToSummary(result.summaryPath, result.reportPath) }\n : {}),\n ...(result.markdownPath\n ? { markdown: relativeToSummary(result.summaryPath, result.markdownPath) }\n : {}),\n summary: result.summary,\n projects: result.projects.map((project) => ({\n projectId: project.projectId,\n name: project.name,\n status: project.status,\n retry: project.retry,\n fileSelection: project.fileSelection,\n tagSelection: project.tagSelection,\n sourceCount: project.sourceCount,\n selectedCaseCount: project.selectedCaseCount,\n filteredCaseCount: project.filteredCaseCount,\n ...(project.lifecycle\n ? {\n lifecycle: {\n status: project.lifecycle.status,\n startedAt: project.lifecycle.startedAt,\n endedAt: project.lifecycle.endedAt,\n durationMs: project.lifecycle.durationMs,\n ...(project.lifecycle.cleanup\n ? { cleanup: project.lifecycle.cleanup }\n : {}),\n ...(project.lifecycle.pendingOperations\n ? { pendingOperations: project.lifecycle.pendingOperations }\n : {}),\n ...(project.lifecycle.setupError\n ? { setupError: errorJson(project.lifecycle.setupError) }\n : {}),\n ...(project.lifecycle.teardownErrors\n ? {\n teardownErrors:\n project.lifecycle.teardownErrors.map(errorJson),\n }\n : {}),\n },\n }\n : {}),\n cases: project.cases.map((outcome) => ({\n ...(outcome.documentRunId\n ? { documentRunId: outcome.documentRunId }\n : {}),\n documentId: outcome.documentId,\n caseId: outcome.caseId,\n sourcePath: outcome.sourcePath,\n caseIndex: outcome.caseIndex,\n name: outcome.name,\n status: outcome.status,\n ...(outcome.notRunReason ? { notRunReason: outcome.notRunReason } : {}),\n ...(outcome.attempts\n ? {\n attempts: outcome.attempts.map((attempt) => ({\n attemptId: attempt.runId,\n attemptIndex: attempt.attemptIndex,\n status: attempt.status,\n ...(attempt.cleanup ? { cleanup: attempt.cleanup } : {}),\n ...(attempt.pendingOperations\n ? { pendingOperations: attempt.pendingOperations }\n : {}),\n ...(attempt.executionStatus\n ? { executionStatus: attempt.executionStatus }\n : {}),\n ...(attempt.retryDecision\n ? { retryDecision: attempt.retryDecision }\n : {}),\n resultFile: fact(\n caseAttemptResultPath(\n project.projectId,\n outcome.documentId,\n attempt,\n ),\n ),\n ...(attempt.reportPaths?.length\n ? {\n reports: attempt.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n }\n : {}),\n })),\n documents: project.documents.map((document) => ({\n documentId: document.documentId,\n ...(document.attemptIndex === undefined\n ? {}\n : {\n attemptIndex: document.attemptIndex,\n documentRunId: document.documentRunId,\n }),\n sourcePath: document.sourcePath,\n status: document.status,\n ...(document.cleanup ? { cleanup: document.cleanup } : {}),\n ...(document.pendingOperations\n ? { pendingOperations: document.pendingOperations }\n : {}),\n ...(document.executionStatus\n ? { executionStatus: document.executionStatus }\n : {}),\n ...(document.retryDecision\n ? { retryDecision: document.retryDecision }\n : {}),\n resultFile: fact(workflowDocumentResultPath(document)),\n ...(document.reportPaths?.length\n ? {\n reports: document.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n collectionErrors: project.collectionErrors.map((error) => ({\n sourcePath: error.sourcePath,\n errorFile: fact(collectionErrorPath(error.projectId, error.sourcePath)),\n })),\n })),\n });\n};\n","import { readdirSync } from 'node:fs';\nimport { join, relative, resolve, sep } from 'node:path';\nimport type { CollectedWorkflowDocument } from '@midscene/core/internal/test-runner';\nimport { buildTestRunReportPlan } from '@midscene/core/internal/test-runner';\nimport { globSync } from 'tinyglobby';\nimport { WorkflowError, WorkflowParseError } from '../errors';\nimport { collectWorkflowDocument } from '../parser/collect';\nimport type {\n PreparedDocumentInvocation,\n PreparedExecutionProject,\n ProjectPreparationOptions,\n} from './execution-plan';\nimport { writeCollectionError } from './result-store';\nimport type { LoadedExecutionProject, TestFileSelection } from './test-project';\nimport { validateTestFileSelection } from './test-project';\nimport type { TestProjectCollectionError } from './types';\n\nexport const CONFIG_NAMES = [\n 'midscene.config.ts',\n 'midscene.config.mjs',\n] as const;\nconst CONFIG_PREFIX = 'midscene.config.';\nconst ALWAYS_IGNORED_PATTERNS = [\n '.git/**',\n '.midscene/**',\n 'midscene_run/**',\n 'node_modules/**',\n '**/.git/**',\n '**/.midscene/**',\n '**/midscene_run/**',\n '**/node_modules/**',\n];\n\nexport const DEFAULT_TEST_FILE_SELECTION: TestFileSelection = {\n include: ['**/*.{yaml,yml}'],\n};\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nconst discoverResolvedTestFiles = (\n projectRoot: string,\n selection: TestFileSelection,\n): string[] => {\n const root = resolve(projectRoot);\n const match = (patterns: readonly string[]) =>\n globSync(patterns, {\n absolute: true,\n caseSensitiveMatch: false,\n cwd: root,\n dot: true,\n expandDirectories: false,\n followSymbolicLinks: false,\n ignore: [...ALWAYS_IGNORED_PATTERNS, ...(selection.exclude ?? [])],\n onlyFiles: true,\n }).filter((file) => /\\.ya?ml$/i.test(file));\n const files = match(selection.include);\n\n return [...new Set(files.map((file) => resolve(file)))].sort((a, b) => {\n const relativeA = toPosix(relative(root, a));\n const relativeB = toPosix(relative(root, b));\n return relativeA < relativeB ? -1 : relativeA > relativeB ? 1 : 0;\n });\n};\n\nexport const discoverTestFiles = (\n projectRoot: string,\n selection: TestFileSelection = DEFAULT_TEST_FILE_SELECTION,\n): string[] => {\n const normalized = validateTestFileSelection(selection);\n if (!normalized) throw new TypeError('Test file selection is required.');\n return discoverResolvedTestFiles(projectRoot, normalized);\n};\n\nexport const discoverTestConfig = (projectRoot: string): string | undefined => {\n const root = resolve(projectRoot);\n const candidates = readdirSync(root)\n .filter((name) => name.startsWith(CONFIG_PREFIX))\n .sort();\n const supported = candidates.filter((name) =>\n CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n const unsupported = candidates.filter(\n (name) => !CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n if (unsupported.length > 0) {\n throw new Error(\n [\n `Unsupported or conflicting Midscene configs found in ${root}:`,\n ...candidates.map((name) => `- ${name}`),\n `Only ${CONFIG_NAMES.join(' and ')} are supported.`,\n ].join('\\n'),\n );\n }\n if (supported.length > 1) {\n throw new Error(\n [\n `Multiple Midscene configs found in ${root}:`,\n ...supported.map((name) => `- ${name}`),\n 'Pass --config <path> to select one explicitly.',\n ].join('\\n'),\n );\n }\n return supported[0] ? join(root, supported[0]) : undefined;\n};\n\nconst asCollectionError = (\n projectId: string,\n projectName: string,\n sourcePath: string,\n error: unknown,\n): TestProjectCollectionError => ({\n projectId,\n projectName,\n sourcePath,\n error:\n error instanceof WorkflowError\n ? error\n : new WorkflowParseError(\n `Failed to collect workflow document \"${sourcePath}\": ${\n error instanceof Error ? error.message : String(error)\n }`,\n { projectName, sourcePath },\n error,\n ),\n});\n\nexport const matchesTags = (\n tags: readonly string[],\n selection: LoadedExecutionProject['tags'],\n): boolean => {\n if (selection.exclude.some((tag) => tags.includes(tag))) return false;\n return (\n selection.include.length === 0 ||\n selection.include.some((tag) => tags.includes(tag))\n );\n};\n\nconst filterDocumentCases = (\n document: CollectedWorkflowDocument,\n project: LoadedExecutionProject,\n): { document?: CollectedWorkflowDocument; filtered: number } => {\n const cases = document.cases.filter((item) =>\n matchesTags(item.definition.tags ?? [], project.tags),\n );\n const filtered = document.cases.length - cases.length;\n return cases.length === 0\n ? { filtered }\n : { document: { ...document, cases }, filtered };\n};\n\nexport const selectProjects = <TProjectContext>(\n projects: readonly LoadedExecutionProject<TProjectContext>[],\n names: readonly string[] | undefined,\n): readonly LoadedExecutionProject<TProjectContext>[] => {\n if (!names || names.length === 0) return projects;\n const requested = new Set(names);\n if (requested.size !== names.length) {\n throw new Error('Each --project name may only be specified once.');\n }\n const known = new Set(projects.map((project) => project.name));\n const unknown = names.find((name) => !known.has(name));\n if (unknown) throw new Error(`Unknown Midscene project: ${unknown}`);\n return projects.filter((project) => requested.has(project.name));\n};\n\n/** Prepare and validate every document before any Project resource is acquired. */\nexport async function prepareProject(\n project: LoadedExecutionProject,\n projectRoot: string,\n runDir: string,\n defaultTimeoutMs: number,\n options: ProjectPreparationOptions = {},\n): Promise<PreparedExecutionProject> {\n const platform = options.platform?.trim();\n const fileSelection = project.files ?? DEFAULT_TEST_FILE_SELECTION;\n const prerequisiteFile = options.prerequisiteFile\n ? resolve(options.prerequisiteFile)\n : undefined;\n const mainFiles =\n options.files ?? discoverResolvedTestFiles(projectRoot, fileSelection);\n const files = [\n ...(prerequisiteFile ? [prerequisiteFile] : []),\n ...mainFiles.filter((file) => file !== prerequisiteFile),\n ];\n const occurrences = new Map<string, number>();\n const sources = files.map((absolutePath) => {\n const invocationIndex = occurrences.get(absolutePath) ?? 0;\n occurrences.set(absolutePath, invocationIndex + 1);\n return {\n projectId: project.projectId,\n projectName: project.name,\n sourcePath: toPosix(relative(projectRoot, absolutePath)),\n absolutePath,\n invocationIndex,\n };\n });\n const collectionErrors: TestProjectCollectionError[] = [];\n const invocations: PreparedDocumentInvocation[] = [];\n const plans: import('@midscene/core').TestRunReportDocumentPlan[] = [];\n let filteredCaseCount = 0;\n\n if (sources.length === 0) {\n const error = asCollectionError(\n project.projectId,\n project.name,\n '<project>',\n new WorkflowParseError(\n `No workflow YAML files found for project \"${project.name}\" in ${projectRoot}.`,\n { projectName: project.name, projectRoot },\n ),\n );\n collectionErrors.push(error);\n await writeCollectionError(runDir, error);\n }\n\n for (const source of sources) {\n try {\n const collected = await options.collectDocument?.(source, project);\n if (collected) {\n filteredCaseCount += collected.filteredCaseCount;\n if (collected.invocation) {\n const plan = buildTestRunReportPlan(collected.invocation.document, {\n defaultTimeoutMs: collected.invocation.defaultTimeoutMs,\n retry: collected.invocation.retry,\n });\n invocations.push({ ...collected.invocation, plan });\n plans.push(plan);\n }\n continue;\n }\n const document = collectWorkflowDocument(source, {\n resolveNode: project.nodes.get.bind(project.nodes),\n variables: project.variables,\n env: process.env,\n });\n const filtered =\n source.absolutePath === prerequisiteFile\n ? { document, filtered: 0 }\n : filterDocumentCases(document, project);\n const plan = buildTestRunReportPlan(document, {\n selectedCaseIds:\n filtered.document?.cases.map((item) => item.caseId) ?? [],\n defaultTimeoutMs,\n retry: { scope: 'case', count: project.retry },\n });\n plans.push(plan);\n filteredCaseCount += filtered.filtered;\n if (filtered.document)\n invocations.push({\n plan,\n document: filtered.document,\n retry: { scope: 'case', count: project.retry },\n defaultTimeoutMs,\n reportEnabled: true,\n bindings: {\n resolveNode: project.nodes.require.bind(project.nodes),\n ...(project.fileSetup\n ? {\n documentSetup: {\n name: project.fileSetup.name,\n setup({ projectContext, document, signal, onTeardown }) {\n return project.fileSetup!.setup({\n project,\n projectContext,\n file: document,\n env: Object.freeze({ ...process.env }),\n signal,\n onTeardown,\n });\n },\n },\n }\n : {}),\n },\n });\n } catch (error) {\n const collectionError = asCollectionError(\n project.projectId,\n project.name,\n source.sourcePath,\n error,\n );\n collectionErrors.push(collectionError);\n await writeCollectionError(runDir, collectionError);\n }\n }\n\n const documents = invocations.map((invocation) => invocation.document);\n const prerequisiteSource = sources.find(\n (source) => source.absolutePath === prerequisiteFile,\n );\n const prerequisiteDocument = documents.find(\n (document) => document.sourcePath === prerequisiteSource?.sourcePath,\n );\n return {\n project,\n ...(platform ? { platform } : {}),\n documentConcurrency: options.documentConcurrency ?? 1,\n ...(prerequisiteDocument\n ? { prerequisiteDocumentId: prerequisiteDocument.documentId }\n : {}),\n fileSelection,\n sources,\n documents,\n invocations,\n plans,\n collectionErrors,\n selectedCaseCount: documents.reduce(\n (total, document) => total + document.cases.length,\n 0,\n ),\n filteredCaseCount,\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, statSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { NativeWorkflowFormatError } from '../parser/collect';\nimport type {\n PreparedExecutionProject,\n PreparedTestRunPlan,\n TestProjectRunOptions,\n TestRunInput,\n} from './execution-plan';\nimport {\n discoverTestConfig,\n prepareProject,\n selectProjects,\n} from './project-preparation';\nimport { loadTestProject } from './test-project';\n\nconst padDatePart = (value: number): string => String(value).padStart(2, '0');\n\nexport const createTestRunId = (\n date = new Date(),\n uuid = randomUUID(),\n): string => {\n const timestamp = [\n date.getFullYear(),\n padDatePart(date.getMonth() + 1),\n padDatePart(date.getDate()),\n padDatePart(date.getHours()),\n padDatePart(date.getMinutes()),\n padDatePart(date.getSeconds()),\n ].join('');\n return `${timestamp}-${uuid.slice(0, 8)}`;\n};\n\nconst assertDirectory = (path: string, label: string): void => {\n if (!existsSync(path) || !statSync(path).isDirectory()) {\n throw new Error(`${label} does not exist or is not a directory: ${path}`);\n }\n};\n\nconst resolveRunInput = (options: TestProjectRunOptions): TestRunInput => {\n const cwd = resolve(options.cwd ?? process.cwd());\n assertDirectory(cwd, 'Test working directory');\n const inputPath = options.projectRoot\n ? resolve(cwd, options.projectRoot)\n : undefined;\n const singleFile =\n inputPath && existsSync(inputPath) && statSync(inputPath).isFile()\n ? inputPath\n : undefined;\n if (singleFile && !/\\.ya?ml$/i.test(singleFile))\n throw new Error(\n `Test input must be a YAML file or project directory: ${singleFile}`,\n );\n const cliProjectRoot = singleFile ? dirname(singleFile) : inputPath;\n if (cliProjectRoot) assertDirectory(cliProjectRoot, 'Test project directory');\n const projectRoot = cliProjectRoot ?? cwd;\n return {\n cwd,\n projectRoot,\n configSearchRoot: projectRoot,\n ...(singleFile ? { singleFile } : {}),\n };\n};\n\n/** Composition boundary only: execution receives no raw input syntax or host options. */\nexport async function prepareTestRun(\n options: TestProjectRunOptions,\n): Promise<PreparedTestRunPlan> {\n const startedAt = new Date();\n const runId = createTestRunId(startedAt);\n const input = resolveRunInput(options);\n const configPath = options.configPath\n ? resolve(input.configSearchRoot, options.configPath)\n : discoverTestConfig(input.configSearchRoot);\n if (options.configPath && /\\.ya?ml$/i.test(configPath!)) {\n throw new Error(\n `midscene-test --config only accepts a native TypeScript or JavaScript project config: ${configPath}. Run legacy batch YAML with \\`midscene --config ${options.configPath}\\`.`,\n );\n }\n if (options.configPath && !existsSync(configPath!))\n throw new Error(`Midscene config does not exist: ${configPath}`);\n const definition = await loadTestProject<unknown>(configPath);\n const resultDir = options.resultDir\n ? resolve(input.cwd, options.resultDir)\n : join(input.projectRoot, '.midscene', 'test-results');\n const runDir = join(resultDir, runId);\n const summaryPath = join(runDir, 'summary.json');\n const reportDir = resolve(input.projectRoot, definition.output.reportDir);\n mkdirSync(resultDir, { recursive: true });\n mkdirSync(runDir);\n const projects: PreparedExecutionProject[] = [];\n for (const project of selectProjects(\n definition.projects,\n options.projectNames,\n ))\n projects.push(\n await prepareProject(\n project,\n input.projectRoot,\n runDir,\n definition.test.testTimeout,\n input.singleFile ? { files: [input.singleFile] } : undefined,\n ),\n );\n const hasFormatMismatch = projects.some((project) =>\n project.collectionErrors.some(\n ({ error }) => error instanceof NativeWorkflowFormatError,\n ),\n );\n return {\n startedAt,\n runId,\n projectRoot: input.projectRoot,\n ...(configPath ? { configPath } : {}),\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects,\n // A wrong-format file invalidates the complete command invocation. Other\n // native collection failures retain the existing per-Project isolation.\n preflightScope: hasFormatMismatch ? 'run' : 'project',\n reportEnabled: true,\n publications: [],\n onProgress: options.onProgress ?? (() => {}),\n };\n}\n","import { writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport type {\n TestRunReportDump,\n TestRunReportSourceIndex,\n TestRunReportStep,\n} from '@midscene/core';\nimport type { TestProjectRunResult } from '../cli/types';\nimport { buildTestRunReportDump } from './test-run-report';\n\nconst text = (value: string): string =>\n value\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll('|', '&#124;')\n .replaceAll('[', '&#91;')\n .replaceAll(']', '&#93;')\n .replaceAll('*', '&#42;')\n .replaceAll('_', '&#95;')\n .replaceAll('`', '&#96;')\n .replaceAll('\\\\', '&#92;')\n .replace(/[\\r\\n]+/g, ' ');\n\nconst duration = (ms: number): string => {\n const seconds = Math.round(ms / 1000);\n return seconds < 60\n ? `${seconds}s`\n : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;\n};\nconst href = (from: string, target: string): string =>\n relative(dirname(from), target).split(sep).map(encodeURIComponent).join('/');\n\nexport interface TestResultMarkdownOptions {\n /** Relative or hosted URL of the HTML report. */\n reportHref?: string;\n}\n\n/** Render the same sanitized execution facts used by the HTML report. */\nexport function renderTestResultMarkdown(\n dump: TestRunReportDump,\n options: TestResultMarkdownOptions = {},\n): string {\n const { summary } = dump;\n const outcome =\n dump.status === 'success'\n ? `✅ **${summary.passed}/${summary.total} passed**`\n : `❌ **${summary.failed} failed** · ${summary.passed} passed · ${summary.notRun} not run`;\n const lines = [\n '## Midscene Test',\n '',\n `${outcome} · ${duration(dump.durationMs)}`,\n '',\n ];\n if (summary.filtered) lines.push(`**Filtered:** ${summary.filtered}`, '');\n const infrastructure = [\n summary.collectionErrors\n ? `${summary.collectionErrors} collection errors`\n : '',\n summary.documentFailures\n ? `${summary.documentFailures} document failures`\n : '',\n summary.projectFailures\n ? `${summary.projectFailures} project failures`\n : '',\n ].filter(Boolean);\n if (infrastructure.length)\n lines.push(`**Infrastructure:** ${infrastructure.join(' · ')}`, '');\n const groups: { name: string; rows: string[] }[] = [];\n const errors: string[] = [];\n const recordSteps = (label: string, steps: readonly TestRunReportStep[]) => {\n for (const step of steps) {\n if (step.status === 'failed')\n errors.push(\n `${label} / ${step.node}: ${step.error?.message ?? 'Step failed'}`,\n );\n }\n };\n for (const project of dump.projects) {\n if (project.lifecycle?.setupError)\n errors.push(`${project.name}: ${project.lifecycle.setupError.message}`);\n for (const error of project.lifecycle?.teardownErrors ?? [])\n errors.push(`${project.name}: ${error.message}`);\n for (const error of project.collectionErrors)\n errors.push(\n `${project.name} / ${error.sourcePath}: ${error.error.message}`,\n );\n for (const document of project.documents) {\n const name = document.sourcePath\n .replace(/\\\\/g, '/')\n .replace(/\\.(?:yaml|yml)$/, '');\n const group = {\n name: dump.projects.length > 1 ? `${project.name} / ${name}` : name,\n rows: [] as string[],\n };\n groups.push(group);\n recordSteps(`${project.name} / ${document.sourcePath}`, [\n ...document.beforeAll,\n ...document.afterAll,\n ]);\n for (const error of document.teardownErrors ?? [])\n errors.push(`${document.sourcePath}: ${error.message}`);\n for (const failure of document.hostErrors ?? [])\n errors.push(\n `${document.sourcePath} / ${failure.phase}: ${failure.error.message}`,\n );\n for (const testCase of document.cases) {\n group.rows.push(\n ` - ${testCase.status === 'success' ? '✅' : testCase.status === 'not-run' ? '⏭️' : '❌'} ${text(testCase.name)}`,\n );\n }\n }\n }\n for (const diagnostic of dump.diagnostics ?? []) {\n if (diagnostic.level === 'error') errors.push(diagnostic.message);\n }\n if (errors.length)\n lines.push(\n '### Execution errors',\n '',\n ...errors.map((error) => `- ${text(error)}`),\n '',\n );\n for (const group of groups) {\n if (group.rows.length) lines.push(`- ${text(group.name)}`, ...group.rows);\n }\n if (!groups.some((group) => group.rows.length))\n lines.push('No cases were reported.');\n if (options.reportHref)\n lines.push(\n '',\n `[Open the Midscene Test report ↗](<${options.reportHref}>)`,\n );\n return `${lines.join('\\n')}\\n`;\n}\n\nconst emptyIndex = (): TestRunReportSourceIndex => ({\n sources: [],\n metrics: {\n modelCallCount: 0,\n modelTimeMs: 0,\n promptTokens: 0,\n cachedInputTokens: 0,\n completionTokens: 0,\n totalTokens: 0,\n },\n});\n\n/** Write a per-run Markdown artifact even when HTML publication fails or is disabled. */\nexport async function writeTestResultMarkdown(\n result: TestProjectRunResult,\n index: TestRunReportSourceIndex = emptyIndex(),\n): Promise<string> {\n const output = join(dirname(result.summaryPath), 'result.md');\n const dump = buildTestRunReportDump(result, index);\n await writeFile(\n output,\n renderTestResultMarkdown(dump, {\n ...(result.reportPath\n ? { reportHref: href(output, result.reportPath) }\n : {}),\n }),\n );\n return output;\n}\n","import {\n WorkflowExecutionFailure,\n decideRetry,\n isResourceRecoveryError,\n runDocumentAttempts,\n runWorkflowDocument,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CaseRunOutcome,\n StepExecutionInfo,\n StepRunResult,\n WorkflowDocumentExecutionResult,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport { isFatalDeviceError } from '../errors';\nimport type { PreparedDocumentInvocation } from './execution-plan';\nimport {\n writeCaseAttemptResult,\n writeWorkflowDocumentResult,\n} from './result-store';\nimport type { LoadedExecutionProject } from './test-project';\nimport type { TestProjectCaseRunResult } from './types';\n\ninterface DocumentInvocationSinks {\n cases: TestProjectCaseRunResult[];\n documents: WorkflowDocumentRunResult[];\n}\n\ninterface ExecuteDocumentInvocationOptions {\n isolatedContext?: boolean;\n setupTimeoutMs?: number;\n teardownTimeoutMs?: () => number;\n onUnresolvedResources?(): void;\n /** Classify failures by resource ownership, independently of notifications. */\n isProjectResourceFailure?(error: unknown): boolean;\n invocation: PreparedDocumentInvocation;\n project: LoadedExecutionProject<unknown>;\n projectContext: unknown;\n runDir: string;\n signal: AbortSignal;\n rootSignal: AbortSignal;\n shouldBail(): boolean;\n isProjectFatal(): boolean;\n markProjectFatal(): void;\n addFailedCases(count: number): void;\n onProgress(message: string): void;\n onDocumentResult?(result: WorkflowDocumentRunResult): Promise<void>;\n sinks: DocumentInvocationSinks;\n}\n\nconst stepPosition = (info: StepExecutionInfo) =>\n info.scope === 'case' ? info.case : info.document;\n\nconst formatStep = (info: StepExecutionInfo): string => {\n const position = stepPosition(info);\n const phase = position.phase === 'steps' ? 'step' : position.phase;\n return `${phase} ${position.stepIndex + 1}/${info.stepCount}: ${info.node}`;\n};\n\nconst formatStepResult = (\n info: StepExecutionInfo,\n result: StepRunResult,\n): string => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n if (result.status === 'not-run')\n return `${indent}– ${formatStep(info)} (not run: ${result.notRunReason})`;\n const symbol = result.status === 'success' ? '✓' : '✗';\n const error = result.error ? ` — ${result.error.message}` : '';\n const continuation = result.continuedAfterError ? '; continuing' : '';\n return `${indent}${symbol} ${formatStep(info)} (${result.durationMs} ms)${error}${continuation}`;\n};\n\nconst caseHasFatalError = (outcome: CaseRunOutcome): boolean =>\n (outcome.attempts ?? []).some(\n (attempt) =>\n [...attempt.beforeEach, ...attempt.steps, ...attempt.afterEach].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (attempt.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!attempt.executionErrors?.some(isResourceRecoveryError),\n );\n\nconst documentHasFatalError = (result: WorkflowDocumentRunResult): boolean =>\n [...result.beforeAll, ...result.afterAll].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (result.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!result.executionErrors?.some(isResourceRecoveryError);\n\n// Only an explicit ownership signal can establish a Project-wide failure.\nexport const isSharedResourceFailure = (error: unknown): boolean => {\n const seen = new Set<object>();\n const pending: unknown[] = [error];\n while (pending.length && seen.size < 50) {\n const item = pending.pop();\n if (typeof item !== 'object' || item === null || seen.has(item)) continue;\n seen.add(item);\n const failure = item as {\n code?: string;\n cause?: unknown;\n errors?: unknown[];\n };\n if (failure.code === 'PROJECT_RESOURCE_ERROR') return true;\n if (failure.cause) pending.push(failure.cause);\n if (Array.isArray(failure.errors))\n pending.push(...failure.errors.slice(0, 50));\n }\n return false;\n};\n\n/** Execute prepared document policies through the shared retry boundary. */\nexport async function executeDocumentInvocation(\n options: ExecuteDocumentInvocationOptions,\n): Promise<void> {\n const { invocation, project, sinks } = options;\n const isProjectResourceFailure =\n options.isProjectResourceFailure ?? (() => false);\n const { document } = invocation;\n const documentRetry = invocation.retry.scope === 'document';\n const attempts: WorkflowDocumentExecutionResult[] = [];\n const fileSetup = invocation.bindings.documentSetup;\n const documentSetup =\n options.isProjectResourceFailure && fileSetup\n ? {\n ...fileSetup,\n async setup(ctx: Parameters<typeof fileSetup.setup>[0]) {\n try {\n return await fileSetup.setup(ctx);\n } catch (error) {\n if (isProjectResourceFailure(error)) options.markProjectFatal();\n throw error;\n }\n },\n }\n : fileSetup;\n\n await runDocumentAttempts(\n {\n retry: documentRetry ? invocation.retry.count : 0,\n signal: options.signal,\n shouldStop: () => options.shouldBail() || options.isProjectFatal(),\n },\n async (documentAttemptIndex) => {\n if (documentRetry)\n options.onProgress(\n ` file attempt ${documentAttemptIndex + 1}/${invocation.retry.count + 1}: ${document.sourcePath}`,\n );\n const execution = await runWorkflowDocument(document, {\n plan: invocation.plan,\n documentAttemptIndex: documentRetry ? documentAttemptIndex : undefined,\n ...invocation.bindings,\n documentSetup,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n project,\n projectContext: options.projectContext,\n retry: documentRetry ? 0 : invocation.retry.count,\n signal: options.signal,\n defaultTimeoutMs: invocation.defaultTimeoutMs,\n shouldStop: () =>\n options.rootSignal.aborted ||\n options.shouldBail() ||\n options.isProjectFatal(),\n stopReason: () =>\n options.rootSignal.aborted\n ? 'interrupted'\n : options.isProjectFatal()\n ? 'fatal-error'\n : 'bail',\n isFatalError: (run) =>\n [...run.beforeEach, ...run.steps, ...run.afterEach].some(\n (step) =>\n step.error &&\n (isFatalDeviceError(step.error) ||\n isProjectResourceFailure(step.error)),\n ) ||\n (run.teardownErrors ?? []).some(\n (error) =>\n isFatalDeviceError(error) || isProjectResourceFailure(error),\n ),\n onCaseStart: (collectedCase) => {\n options.onProgress(\n ` [case ${collectedCase.caseIndex + 1}/${document.cases.length}] ${collectedCase.definition.name}`,\n );\n },\n onStepStart: (info) => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n options.onProgress(`${indent}→ ${formatStep(info)}`);\n },\n onStepResult: async (info, result) => {\n if (isProjectResourceFailure(result.error))\n options.markProjectFatal();\n await invocation.bindings.onStepResult?.(info, result);\n options.onProgress(formatStepResult(info, result));\n },\n onCaseResult: async (attempt) => {\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n options.onProgress(\n ` ${attempt.status === 'success' ? '✓' : '✗'} attempt ${attempt.attemptIndex + 1}/${documentRetry ? 1 : invocation.retry.count + 1}: ${attempt.name} (${attempt.durationMs} ms)`,\n );\n },\n onCaseOutcome: (outcome) => {\n if (\n outcome.attempts?.some(\n (attempt) =>\n [\n ...attempt.beforeEach,\n ...attempt.steps,\n ...attempt.afterEach,\n ].some((step) => isProjectResourceFailure(step.error)) ||\n attempt.teardownErrors?.some(isProjectResourceFailure),\n )\n )\n options.markProjectFatal();\n if (!options.isolatedContext && caseHasFatalError(outcome))\n options.markProjectFatal();\n if (!documentRetry && outcome.status === 'failed')\n options.addFailedCases(1);\n },\n onDocumentResult: options.onDocumentResult,\n }).catch(async (error: unknown) => {\n if (error instanceof WorkflowExecutionFailure) {\n const partial = error.result as WorkflowDocumentExecutionResult;\n const resourceOnly =\n error.errors.length > 0 &&\n error.errors.every(\n (failure) =>\n isResourceRecoveryError(failure) ||\n partial.document.hostErrors?.some(\n (host) =>\n host.phase === 'cleanup' &&\n (host.error === failure ||\n (host.error instanceof Error &&\n host.error.cause === failure)),\n ),\n );\n // Legacy recovery failures stop context reuse. Isolated file failures\n // are checked for unresolved resources below; publication still throws.\n if (resourceOnly) {\n if (\n !options.isolatedContext &&\n error.errors.some(isResourceRecoveryError)\n )\n options.markProjectFatal();\n return partial;\n }\n if (documentRetry)\n partial.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n attempts.push(partial);\n sinks.documents.push(partial.document);\n sinks.cases.push(\n ...partial.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: partial.document.documentRunId,\n })),\n );\n try {\n for (const outcome of partial.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, partial.document);\n } catch (publicationError) {\n throw new WorkflowExecutionFailure(partial, [\n ...error.errors,\n publicationError,\n ]);\n }\n }\n throw error;\n });\n\n if (!options.isolatedContext && documentHasFatalError(execution.document))\n options.markProjectFatal();\n if (\n [\n ...execution.document.beforeAll,\n ...execution.document.afterAll,\n ...(execution.document.hostErrors ?? []).map(({ error }) => ({\n error,\n })),\n ...(execution.document.teardownErrors ?? []).map((error) => ({\n error,\n })),\n ].some(({ error }) => isProjectResourceFailure(error))\n )\n options.markProjectFatal();\n const owners = [\n execution.document,\n ...execution.cases.flatMap((outcome) => outcome.attempts ?? []),\n ];\n const cleanupPending = owners.some(\n (owner) => owner.cleanup?.status === 'pending',\n );\n const operationPending = owners.some(\n (owner) => !!owner.pendingOperations?.length,\n );\n const cleanupFailed = owners.some(\n (owner) =>\n owner.cleanup?.status === 'failed' ||\n !!owner.teardownErrors?.length ||\n ('hostErrors' in owner &&\n owner.hostErrors?.some(({ phase }) => phase === 'cleanup')),\n );\n // Legacy files reuse their Project context. Isolated files may continue\n // after settled local cleanup failure; unresolved ownership stops dispatch.\n if (cleanupPending || operationPending) {\n options.markProjectFatal();\n options.onUnresolvedResources?.();\n } else if (cleanupFailed && !options.isolatedContext)\n options.markProjectFatal();\n const failed =\n execution.document.status === 'failed' ||\n execution.cases.some((item) => item.status !== 'success');\n const decision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: failed ? 'failed' : 'success',\n cleanupPending,\n cleanupFailed,\n operationPending,\n fatalError: options.isProjectFatal(),\n interrupted: options.signal.aborted || options.rootSignal.aborted,\n shouldStop: options.shouldBail(),\n });\n if (documentRetry) execution.document.retryDecision = decision;\n attempts.push(execution);\n sinks.cases.push(\n ...execution.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: execution.document.documentRunId,\n })),\n );\n sinks.documents.push(execution.document);\n // Per-attempt callbacks publish incremental facts; seal the final retry\n // decision after callback-driven interruption/bail has been observed.\n try {\n for (const outcome of execution.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, execution.document);\n } catch (error) {\n execution.document.status = 'failed';\n execution.document.hostErrors = [\n ...(execution.document.hostErrors ?? []),\n { phase: 'publication', error },\n ];\n if (documentRetry)\n execution.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n throw new WorkflowExecutionFailure(execution, [error]);\n }\n return decision.decision === 'retry' ? 'failed' : undefined;\n },\n );\n\n const final = attempts.at(-1);\n if (!final) return;\n const failedCases = final.cases.filter(\n (item) => item.status === 'failed',\n ).length;\n if (documentRetry && failedCases) options.addFailedCases(failedCases);\n else if (final.document.status === 'failed' && failedCases === 0)\n options.addFailedCases(Math.max(1, failedCases));\n}\n","import type {\n ProjectRuntime,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport {\n WorkflowError,\n getPendingScopeOperations,\n getResourceCleanupCompletion,\n trackResourceOperation,\n waitForScopeOperations,\n} from '@midscene/core/internal/test-runner';\nimport { createProjectRuntime } from '../engine/project-runtime';\nimport {\n executeDocumentInvocation,\n isSharedResourceFailure,\n} from './document-invocation';\nimport type { PreparedExecutionProject } from './execution-plan';\nimport type {\n TestExecutionProjectRunResult,\n TestProjectCaseRunResult,\n} from './types';\n\ninterface FileProjectState {\n prepared: PreparedExecutionProject;\n cases: TestProjectCaseRunResult[];\n documents: WorkflowDocumentRunResult[];\n runtime?: ProjectRuntime;\n lifecycle?: TestExecutionProjectRunResult['lifecycle'];\n cursor: number;\n active: number;\n initializing: boolean;\n finished: boolean;\n fatal: boolean;\n setupFailed: boolean;\n}\n\ninterface FileSchedulerOptions {\n projects: readonly PreparedExecutionProject[];\n maxConcurrentFiles: number;\n maxConcurrentProjects: number;\n setupTimeoutMs: number;\n teardownTimeoutMs(): number;\n signal: AbortSignal;\n runDir: string;\n preflightFailed: boolean;\n shouldBail(): boolean;\n addFailedCases(count: number): void;\n announceProject(project: PreparedExecutionProject, index: number): void;\n onProgress(project: PreparedExecutionProject, message: string): void;\n onInfrastructureError(error: unknown): void;\n}\n\n/** Round-robin files within global file and live Project limits. */\nexport async function runPreparedFiles(\n options: FileSchedulerOptions,\n): Promise<FileProjectState[]> {\n const states: FileProjectState[] = options.projects.map((prepared) => ({\n prepared,\n cases: [],\n documents: [],\n cursor: 0,\n active: 0,\n initializing: false,\n finished: false,\n fatal: false,\n setupFailed: false,\n }));\n let nextProject = 0;\n let resourcesUnresolved = false;\n let occupied = 0;\n let occupiedProjects = 0;\n const cleanupQueue: Array<() => void> = [];\n const release = () => {\n occupied--;\n while (occupied < options.maxConcurrentFiles && cleanupQueue.length) {\n occupied++;\n cleanupQueue.shift()!();\n }\n wake?.();\n };\n let wake: (() => void) | undefined;\n const running = new Set<Promise<void>>();\n const stopped = (state: FileProjectState) =>\n options.signal.aborted || options.shouldBail() || state.fatal;\n const invalid = (state: FileProjectState) =>\n options.preflightFailed || state.prepared.collectionErrors.length > 0;\n const unresolved = () => {\n if (resourcesUnresolved) return;\n resourcesUnresolved = true;\n options.onInfrastructureError(\n new WorkflowError(\n 'Resources are still running or cleanup is pending. No new test files will start.',\n { code: 'UNRESOLVED_FILE_RESOURCES' },\n ),\n );\n };\n const finishProject = async (state: FileProjectState) => {\n if (!state.runtime || state.finished) return;\n state.finished = true;\n const failed =\n state.fatal ||\n options.signal.aborted ||\n state.cases.some((item) => item.status !== 'success') ||\n state.documents.some((item) => item.status !== 'success');\n state.lifecycle = await state.runtime.finish(failed ? 'failed' : 'success');\n const releaseProject = () => {\n occupiedProjects--;\n wake?.();\n };\n if (\n state.lifecycle.cleanup?.status === 'pending' ||\n state.lifecycle.pendingOperations?.length\n ) {\n unresolved();\n // A result snapshot can precede actual resource release.\n void Promise.all([\n waitForScopeOperations(state.runtime.signal),\n getResourceCleanupCompletion(state.runtime.signal),\n ]).then(releaseProject, (error) => {\n options.onInfrastructureError(error);\n releaseProject();\n });\n } else releaseProject();\n };\n\n const admit = () => {\n for (let offset = 0; offset < states.length; offset++) {\n const index = (nextProject + offset) % states.length;\n const state = states[index];\n if (invalid(state) || state.finished || state.initializing) continue;\n if (!state.runtime && occupiedProjects >= options.maxConcurrentProjects)\n continue;\n const cleanupOnly =\n !!state.runtime &&\n state.active === 0 &&\n (stopped(state) || state.cursor === state.prepared.invocations.length);\n if (\n !cleanupOnly &&\n (stopped(state) ||\n state.cursor >= state.prepared.invocations.length ||\n state.active >=\n (state.prepared.project.maxConcurrentFiles ??\n options.maxConcurrentFiles))\n )\n continue;\n nextProject = (index + 1) % states.length;\n occupied++;\n state.active++;\n if (!state.runtime && !cleanupOnly) {\n // Claim both budgets before setup so idle Projects are not pre-created.\n occupiedProjects++;\n state.initializing = true;\n }\n const invocationIndex = cleanupOnly ? -1 : state.cursor++;\n return { state, index, invocationIndex };\n }\n };\n\n const run = async ({\n state,\n index,\n invocationIndex,\n }: NonNullable<ReturnType<typeof admit>>) => {\n const { prepared } = state;\n const { project } = prepared;\n let fileResourcesPending = false;\n try {\n if (invocationIndex < 0) {\n await finishProject(state);\n return;\n }\n if (!state.runtime) {\n state.runtime = createProjectRuntime({\n project,\n setup: project.setup,\n signal: options.signal,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n });\n setMaxListeners(\n Math.max(\n 10,\n Math.min(\n prepared.invocations.length,\n project.maxConcurrentFiles ?? options.maxConcurrentFiles,\n ) + 1,\n ),\n state.runtime.signal,\n );\n options.announceProject(prepared, index);\n await state.runtime.start();\n state.initializing = false;\n if (!state.runtime.canRun) {\n state.fatal = true;\n state.setupFailed = true;\n }\n wake?.();\n }\n if (stopped(state)) return;\n const invocation = prepared.invocations[invocationIndex];\n options.onProgress(\n prepared,\n ` [document ${invocationIndex + 1}/${prepared.invocations.length}] ${invocation.document.sourcePath}`,\n );\n await executeDocumentInvocation({\n invocation,\n project,\n projectContext: state.runtime.context,\n runDir: options.runDir,\n signal: state.runtime.signal,\n rootSignal: options.signal,\n shouldBail: options.shouldBail,\n isProjectFatal: () => state.fatal,\n markProjectFatal: () => {\n if (state.fatal) return;\n state.fatal = true;\n state.runtime?.abort(\n new WorkflowError(\n `Project \"${project.name}\" shared execution environment is unavailable.`,\n { code: 'PROJECT_RESOURCE_ERROR' },\n ),\n );\n },\n addFailedCases: options.addFailedCases,\n onProgress: (message) => options.onProgress(prepared, message),\n sinks: state,\n isolatedContext: project.fileSetup !== undefined,\n isProjectResourceFailure: isSharedResourceFailure,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n onUnresolvedResources: () => {\n fileResourcesPending = true;\n unresolved();\n },\n });\n } catch (error) {\n state.fatal = true;\n fileResourcesPending =\n !!state.runtime &&\n getPendingScopeOperations(state.runtime.signal).length > 0;\n options.onInfrastructureError(error);\n } finally {\n state.initializing = false;\n try {\n // The last file retains its global/local admission through shared cleanup.\n if (\n state.active === 1 &&\n (stopped(state) || state.cursor === prepared.invocations.length)\n )\n await finishProject(state);\n } catch (error) {\n options.onInfrastructureError(error);\n }\n state.active--;\n if (\n state.runtime &&\n (fileResourcesPending || state.lifecycle?.cleanup?.status === 'pending')\n ) {\n // A returned pending snapshot does not release the actual admission.\n // At shutdown this may conservatively wait for siblings in the Project.\n void waitForScopeOperations(state.runtime.signal).then(\n release,\n (error) => {\n options.onInfrastructureError(error);\n release();\n },\n );\n } else release();\n wake?.();\n }\n };\n\n while (true) {\n const changed = new Promise<void>((resolve) => {\n wake = resolve;\n });\n while (occupied < options.maxConcurrentFiles) {\n const job = admit();\n if (!job) break;\n const task = run(job);\n running.add(task);\n const settled = () => {\n running.delete(task);\n wake?.();\n };\n void task.then(settled, (error) => {\n options.onInfrastructureError(error);\n settled();\n });\n }\n if (!running.size) break;\n await changed;\n }\n wake = undefined;\n\n // Pending acquisitions/disposers retain their admissions after the result\n // deadline. Idle initialized Projects queue actual cleanup behind those\n // admissions; their snapshots still return within the shared shutdown limit.\n await Promise.all(\n states.map(async (state) => {\n if (!state.runtime || state.finished) return;\n const admission = new Promise<void>((resolve) => {\n cleanupQueue.push(resolve);\n });\n trackResourceOperation({}, admission, state.runtime.signal);\n while (occupied < options.maxConcurrentFiles && cleanupQueue.length) {\n occupied++;\n cleanupQueue.shift()!();\n }\n try {\n await finishProject(state);\n } catch (error) {\n options.onInfrastructureError(error);\n } finally {\n void Promise.all([\n admission,\n getResourceCleanupCompletion(state.runtime.signal),\n ]).then(release, (error) => {\n options.onInfrastructureError(error);\n release();\n });\n }\n }),\n );\n\n for (const state of states) {\n const { prepared } = state;\n if (!state.runtime)\n options.announceProject(prepared, states.indexOf(state));\n const completed = new Set(state.cases.map((item) => item.caseId));\n const reason = invalid(state)\n ? 'project-preflight-failed'\n : state.setupFailed\n ? 'project-setup-failed'\n : options.signal.aborted\n ? 'interrupted'\n : state.fatal\n ? 'fatal-error'\n : 'bail';\n for (const document of prepared.documents) {\n for (const item of document.cases) {\n if (completed.has(item.caseId)) continue;\n state.cases.push({\n documentId: document.documentId,\n caseId: item.caseId,\n projectName: prepared.project.name,\n name: item.definition.name,\n sourcePath: item.sourcePath,\n caseIndex: item.caseIndex,\n status: 'not-run',\n notRunReason: reason,\n });\n }\n }\n const order = new Map(\n prepared.documents.map((document, i) => [document.documentId, i]),\n );\n const position = (id: string) => order.get(id) ?? Number.MAX_SAFE_INTEGER;\n state.cases.sort(\n (a, b) =>\n position(a.documentId) - position(b.documentId) ||\n a.caseIndex - b.caseIndex,\n );\n state.documents.sort(\n (a, b) => position(a.documentId) - position(b.documentId),\n );\n }\n return states;\n}\nimport { setMaxListeners } from 'node:events';\n","import { appendFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { TestRunReportOperationEvent } from '@midscene/core';\n\n/** Registered operations keep this sink after the report has been sealed.\n * Each small, bounded event is written before returning to the operation. No\n * open file descriptor or mutable report object is retained by the journal.\n */\nexport function createOperationJournal(runDir: string) {\n const path = join(runDir, 'operations.jsonl');\n writeFileSync(path, '', { flag: 'wx' });\n return {\n path,\n append(event: Readonly<TestRunReportOperationEvent>) {\n appendFileSync(path, `${JSON.stringify(event)}\\n`);\n },\n };\n}\n","import { setMaxListeners } from 'node:events';\nimport { dirname, join } from 'node:path';\nimport type { TestRunReportSourceIndex } from '@midscene/core';\nimport {\n WorkflowExecutionFailure,\n WorkflowPublicationError,\n asExecutionError,\n observeResourceOperations,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CollectedCase,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport {\n TestRunReportAssembler,\n calculateTestRunHealth,\n} from '@midscene/core/report';\nimport { getDebug } from '@midscene/shared/logger';\nimport { writeTestResultMarkdown } from '../report/result-markdown';\nimport {\n buildTestRunReportDump,\n collectTestRunReportSources,\n} from '../report/test-run-report';\nimport type {\n PreparedExecutionProject,\n PreparedTestRunPlan,\n} from './execution-plan';\nimport { runPreparedFiles } from './file-scheduler';\nimport { createOperationJournal } from './operation-journal';\nimport { writeTestProjectRunResult, writeTestRunPlan } from './result-store';\nimport type {\n TestExecutionProjectRunResult,\n TestProjectCaseRunResult,\n TestProjectRunResult,\n TestProjectRunSummary,\n} from './types';\n\nconst asNotRun = (\n documentId: string,\n collectedCase: CollectedCase,\n projectName: string,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult => ({\n documentId,\n caseId: collectedCase.caseId,\n projectName,\n name: collectedCase.definition.name,\n sourcePath: collectedCase.sourcePath,\n caseIndex: collectedCase.caseIndex,\n status: 'not-run',\n notRunReason: reason,\n});\n\nconst summarize = (\n projects: readonly TestExecutionProjectRunResult[],\n): TestProjectRunSummary => {\n const healthCases = projects.flatMap((project) => {\n const documentAttemptByRunId = new Map(\n project.documents.map((document) => [\n document.documentRunId,\n document.attemptIndex ?? 0,\n ]),\n );\n return latestById(project.cases, (item) => item.caseId).map((item) => {\n return {\n status: item.status,\n ...(item.run ? { run: item.run } : {}),\n ...(item.attempts ? { attempts: item.attempts } : {}),\n retryCount: item.documentRunId\n ? (documentAttemptByRunId.get(item.documentRunId) ?? 0)\n : 0,\n };\n });\n });\n const documents = projects.flatMap((project) =>\n latestById(project.documents, (item) => item.documentId),\n );\n const health = calculateTestRunHealth(healthCases);\n return {\n total: health.total,\n passed: health.passed,\n failed: health.failed,\n notRun: health.notRun,\n passedAfterRetry: health.passedAfterRetry,\n finalPassRate: health.finalPassRate,\n firstPassRate: health.firstPassRate,\n filtered: projects.reduce(\n (total, project) => total + project.filteredCaseCount,\n 0,\n ),\n collectionErrors: projects.reduce(\n (total, project) => total + project.collectionErrors.length,\n 0,\n ),\n documentFailures: documents.filter(\n (document) => document.status === 'failed',\n ).length,\n projectFailures: projects.filter((project) => project.status === 'failed')\n .length,\n };\n};\n\nconst latestById = <T>(items: readonly T[], id: (item: T) => string): T[] => [\n ...new Map(items.map((item) => [id(item), item])).values(),\n];\n\nconst notRunSuite = (\n prepared: PreparedExecutionProject,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult[] =>\n prepared.documents.flatMap((document) =>\n document.cases.map((item) =>\n asNotRun(document.documentId, item, prepared.project.name, reason),\n ),\n );\n\n/** The executor sees prepared policies and bindings, never source-language rules. */\nexport async function runPreparedTestProject(\n plan: PreparedTestRunPlan,\n): Promise<TestProjectRunResult> {\n const {\n startedAt,\n runId,\n projectRoot,\n configPath,\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects: preparedProjects,\n } = plan;\n const progress = plan.onProgress;\n const totalDocuments = preparedProjects.reduce(\n (total, prepared) => total + prepared.documents.length,\n 0,\n );\n const totalCases = preparedProjects.reduce(\n (total, prepared) => total + prepared.selectedCaseCount,\n 0,\n );\n const totalErrors = preparedProjects.reduce(\n (total, prepared) => total + prepared.collectionErrors.length,\n 0,\n );\n progress(\n `midscene-test: preflighted ${preparedProjects.length} projects, ${totalDocuments} documents, ${totalCases} cases, ${totalErrors} collection errors`,\n );\n\n const effectiveConcurrency = Math.min(\n definition.test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY,\n Math.max(1, totalDocuments),\n );\n await writeTestRunPlan(runDir, preparedProjects);\n const journal = createOperationJournal(runDir);\n const rootController = new AbortController();\n setMaxListeners(\n Math.max(10, effectiveConcurrency + 1),\n rootController.signal,\n );\n const handleSignal = (signal: NodeJS.Signals) => {\n rootController.abort(new Error(`Workflow interrupted by ${signal}.`));\n };\n const sigint = () => handleSignal('SIGINT');\n const sigterm = () => handleSignal('SIGTERM');\n process.on('SIGINT', sigint);\n process.on('SIGTERM', sigterm);\n\n let failedCaseCount = 0;\n const bailReached = () =>\n definition.test.bail > 0 && failedCaseCount >= definition.test.bail;\n let shutdownDeadline: number | undefined;\n const beginShutdown = () => {\n shutdownDeadline ??= Date.now() + definition.test.teardownTimeout;\n };\n rootController.signal.addEventListener('abort', beginShutdown, {\n once: true,\n });\n const addFailedCases = (count: number) => {\n failedCaseCount += count;\n if (bailReached()) beginShutdown();\n };\n const teardownTimeoutMs = () =>\n Math.max(\n 0,\n Math.min(\n definition.test.teardownTimeout,\n shutdownDeadline === undefined\n ? Number.POSITIVE_INFINITY\n : shutdownDeadline - Date.now(),\n ),\n );\n let hasInfrastructureError = false;\n const infrastructureErrors: unknown[] = [];\n const recordInfrastructureError = (error: unknown) => {\n const errors =\n error instanceof WorkflowExecutionFailure ? error.errors : [error];\n for (const item of errors)\n if (!infrastructureErrors.includes(item)) infrastructureErrors.push(item);\n hasInfrastructureError = true;\n rootController.abort(error);\n };\n const runInfrastructureCallback = <T>(callback: () => T): T => {\n try {\n return callback();\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n };\n const stopObservingOperations = observeResourceOperations(\n rootController.signal,\n (event) => {\n try {\n journal.append(event);\n } catch (error) {\n recordInfrastructureError(\n new WorkflowPublicationError('write-result', journal.path, error),\n );\n getDebug('test-runner:operations', { console: true })(\n `Could not persist operation event: ${String(error)}`,\n );\n }\n },\n );\n type PreparedProject = (typeof preparedProjects)[number];\n const announceProject = (prepared: PreparedProject, projectIndex: number) => {\n const { project } = prepared;\n runInfrastructureCallback(() =>\n progress(\n `[project ${projectIndex + 1}/${preparedProjects.length}] ${project.name}`,\n ),\n );\n };\n const buildProjectResult = (\n prepared: PreparedProject,\n cases: readonly TestProjectCaseRunResult[],\n documents: readonly WorkflowDocumentRunResult[],\n lifecycle?: TestExecutionProjectRunResult['lifecycle'],\n ): TestExecutionProjectRunResult => {\n const { project } = prepared;\n const projectFailed =\n prepared.collectionErrors.length > 0 ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n ) ||\n latestById(documents, (item) => item.documentId).some(\n (item) => item.status === 'failed',\n ) ||\n lifecycle?.status === 'failed';\n return {\n projectId: project.projectId,\n name: project.name,\n ...(prepared.platform ? { platform: prepared.platform } : {}),\n status: projectFailed ? 'failed' : 'success',\n retry: project.retry,\n fileSelection: prepared.fileSelection,\n tagSelection: project.tags,\n sourceCount: prepared.sources.length,\n selectedCaseCount: prepared.selectedCaseCount,\n filteredCaseCount: prepared.filteredCaseCount,\n ...(lifecycle ? { lifecycle } : {}),\n cases,\n plans: prepared.plans,\n documents,\n collectionErrors: prepared.collectionErrors,\n };\n };\n const buildSkippedProjectResult = (\n prepared: PreparedProject,\n projectIndex: number,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n ): TestExecutionProjectRunResult => {\n announceProject(prepared, projectIndex);\n return buildProjectResult(prepared, notRunSuite(prepared, reason), []);\n };\n const projectResults: Array<TestExecutionProjectRunResult | undefined> =\n new Array(preparedProjects.length);\n\n try {\n const states = await runPreparedFiles({\n projects: preparedProjects,\n maxConcurrentFiles: effectiveConcurrency,\n maxConcurrentProjects:\n definition.test.maxConcurrentProjects ?? Number.POSITIVE_INFINITY,\n setupTimeoutMs: definition.test.setupTimeout,\n teardownTimeoutMs,\n signal: rootController.signal,\n runDir,\n preflightFailed: plan.preflightScope === 'run' && totalErrors > 0,\n shouldBail: bailReached,\n addFailedCases,\n announceProject,\n onProgress: (prepared, message) =>\n runInfrastructureCallback(() =>\n progress(\n effectiveConcurrency > 1\n ? `[${prepared.project.name}]${message}`\n : message,\n ),\n ),\n onInfrastructureError: recordInfrastructureError,\n });\n states.forEach((state, index) => {\n projectResults[index] = buildProjectResult(\n state.prepared,\n state.cases,\n state.documents,\n state.lifecycle,\n );\n });\n } catch (error) {\n recordInfrastructureError(error);\n } finally {\n stopObservingOperations();\n process.off('SIGINT', sigint);\n process.off('SIGTERM', sigterm);\n }\n\n const completedProjectResults = preparedProjects.map(\n (prepared, projectIndex) => {\n const result = projectResults[projectIndex];\n if (result) return result;\n const reason = prepared.collectionErrors.length\n ? 'project-preflight-failed'\n : rootController.signal.aborted\n ? 'interrupted'\n : bailReached()\n ? 'bail'\n : undefined;\n if (!reason) {\n throw new Error(\n `Project scheduler did not produce a result for \"${prepared.project.name}\".`,\n );\n }\n return buildSkippedProjectResult(prepared, projectIndex, reason);\n },\n );\n\n const summary = summarize(completedProjectResults);\n const failed =\n hasInfrastructureError ||\n rootController.signal.aborted ||\n summary.failed > 0 ||\n summary.notRun > 0 ||\n summary.collectionErrors > 0 ||\n summary.documentFailures > 0 ||\n summary.projectFailures > 0;\n const endedAt = new Date();\n const result: TestProjectRunResult = {\n schemaVersion: 3,\n operationLog: { path: journal.path, snapshotAt: endedAt.toISOString() },\n runId,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n status: failed ? 'failed' : 'success',\n exitCode: failed ? 1 : 0,\n resultDir,\n summaryPath,\n reportDir,\n summary,\n projects: completedProjectResults,\n cases: completedProjectResults.flatMap((project) => project.cases),\n documents: completedProjectResults.flatMap((project) => project.documents),\n collectionErrors: completedProjectResults.flatMap(\n (project) => project.collectionErrors,\n ),\n ...(hasInfrastructureError\n ? { errors: infrastructureErrors.map(asExecutionError) }\n : {}),\n };\n let completedResult = result;\n let reportIndex: TestRunReportSourceIndex | undefined;\n const publish = async (\n operation: 'write-result' | 'write-report',\n path: string,\n callback: () => unknown | Promise<unknown>,\n ): Promise<boolean> => {\n try {\n await callback();\n return true;\n } catch (error) {\n recordInfrastructureError(\n error instanceof WorkflowPublicationError ||\n error instanceof WorkflowExecutionFailure\n ? error\n : new WorkflowPublicationError(operation, path, error),\n );\n completedResult = {\n ...completedResult,\n status: 'failed',\n exitCode: 1,\n errors: infrastructureErrors.map(asExecutionError),\n };\n return false;\n }\n };\n const writeSummary = () =>\n publish('write-result', summaryPath, () =>\n writeTestProjectRunResult({\n projectRoot,\n ...(configPath ? { configPath } : {}),\n result: completedResult,\n }),\n );\n const writeReport = () =>\n publish('write-report', reportDir, async () => {\n if (!plan.reportEnabled) return;\n const reportPath = await new TestRunReportAssembler().assembleAsync({\n outputDir: reportDir,\n reportFileName: `midscene-e2e-${runId}`,\n overwrite: false,\n sources: collectTestRunReportSources(completedResult),\n buildRunnerDump: (index) => {\n reportIndex = index;\n const dump = buildTestRunReportDump(completedResult, index);\n const warn = getDebug('test-runner:report-assembler', {\n console: true,\n });\n for (const diagnostic of dump.diagnostics ?? [])\n warn(diagnostic.message);\n return dump;\n },\n });\n completedResult = { ...completedResult, reportPath };\n });\n // Publish each artifact once. The summary includes the report path or its\n // failure. If the summary itself fails, the thrown result remains authoritative;\n // do not rebuild an already-published execution report to backfill that error.\n await writeReport();\n for (const publication of plan.publications)\n await publish(publication.operation, publication.path, async () => {\n await publication.publish(completedResult);\n });\n await publish(\n 'write-result',\n join(dirname(summaryPath), 'result.md'),\n async () => {\n const markdownPath = await writeTestResultMarkdown(\n completedResult,\n reportIndex,\n );\n completedResult = { ...completedResult, markdownPath };\n },\n );\n await writeSummary();\n if (hasInfrastructureError)\n throw new WorkflowExecutionFailure(completedResult, infrastructureErrors);\n return completedResult;\n}\n","import type { TestProjectRunOptions } from './execution-plan';\nimport { prepareTestRun } from './prepare-test-run';\nimport { runPreparedTestProject } from './run-prepared-project';\nimport type { TestProjectRunResult } from './types';\n\nexport type { TestProjectRunOptions } from './execution-plan';\nexport { createTestRunId } from './prepare-test-run';\nexport {\n DEFAULT_TEST_FILE_SELECTION,\n discoverTestConfig,\n discoverTestFiles,\n} from './project-preparation';\n\n/** Native Test entry for cases/steps workflow documents. */\nexport async function runTestProject(\n options: TestProjectRunOptions = {},\n): Promise<TestProjectRunResult> {\n return runPreparedTestProject(await prepareTestRun(options));\n}\n"],"names":["NodeRegistry","CoreNodeRegistry","projectIdFromIndex","index","defineTestProject","definition","defineProjectSetup","defineFileSetup","getDefaultExport","loaded","absolutePath","defaultExport","TypeError","isRecord","value","Array","rejectUnknownKeys","allowedKeys","label","allowed","Set","unknown","Object","key","isAbsolutePattern","pattern","isAbsolute","validatePatterns","field","allowEmptyInclude","validateTestFileSelection","undefined","include","exclude","validateTagList","tag","validateTagSelection","assertJsonValue","path","seen","Number","item","child","deepFreezeJson","validateVariables","validateSetup","validatePositiveInteger","fallback","validateNonNegativeInteger","validateConcurrency","validateFileConcurrency","maxConcurrentFiles","fileSetup","validateExecutionProjects","defaultSetup","defaultFileSetup","globalNodes","test","setup","names","projects","candidate","files","localNodes","nodes","node","globalFileLimit","Math","validateTestOptions","hasExplicitProjects","limit","validateOutputPath","validateOutput","validateTestProjectDefinition","resolvedProjects","name","assertSupportedConfig","extension","canRetryWithCjsLoader","error","Error","errorCode","SyntaxError","loadTestProject","configPath","resolve","pathToFileURL","tsImport","dirname","sep","tsxRequire","fallbackError","message","createCaseInvocationId","projectId","sourcePath","caseIndex","invocationIndex","createHash","JSON","createDocumentInvocationId","normalizeSteps","coreNormalizeSteps","parseWorkflowSource","source","stack","sensitiveNodes","sensitiveValues","redactedPaths","sourceOffset","parsed","load","JSON_SCHEMA","event","state","isReportSecretKey","ranges","left","right","offset","redacted","range","text","leading","trailing","sanitizeReportText","interpolationExpression","exactEnvExpression","exactProjectExpression","missingVariable","kind","options","WorkflowParseError","projectVariable","environmentVariable","interpolationValue","String","resolveString","exactEnv","exactProject","_match","environmentName","projectName","resolveWorkflowVariables","isMapping","NativeWorkflowFormatError","actualFormat","allowedSet","createCaseId","createWorkflowDocumentId","collectWorkflowDocument","snapshot","readFileSync","sourceYaml","format","classifyWorkflowDocumentFormat","resolveStepVariables","step","phase","stepIndex","process","normalizeLifecycle","normalized","resolved","lifecycle","ids","cases","tags","steps","caseId","writeJson","mkdir","writeFile","WorkflowPublicationError","writeTestRunPlan","runDir","join","Date","toPosix","caseAttemptResultPath","documentId","result","workflowDocumentResultPath","collectionErrorPath","id","writeWorkflowDocumentResult","_documentRunId","persistedResult","writeCaseAttemptResult","attemptId","writeCollectionError","collectionError","relativeToSummary","summaryPath","target","relative","errorJson","sanitizeReportError","writeTestProjectRunResult","fact","project","outcome","attempt","document","CONFIG_NAMES","CONFIG_PREFIX","ALWAYS_IGNORED_PATTERNS","DEFAULT_TEST_FILE_SELECTION","discoverResolvedTestFiles","projectRoot","selection","root","match","patterns","globSync","file","a","b","relativeA","relativeB","discoverTestFiles","discoverTestConfig","candidates","readdirSync","supported","unsupported","asCollectionError","WorkflowError","matchesTags","filterDocumentCases","filtered","selectProjects","requested","known","prepareProject","defaultTimeoutMs","platform","fileSelection","prerequisiteFile","mainFiles","occurrences","Map","sources","collectionErrors","invocations","plans","filteredCaseCount","collected","plan","buildTestRunReportPlan","projectContext","signal","onTeardown","documents","invocation","prerequisiteSource","prerequisiteDocument","total","padDatePart","createTestRunId","date","uuid","randomUUID","timestamp","assertDirectory","existsSync","statSync","resolveRunInput","cwd","inputPath","singleFile","cliProjectRoot","prepareTestRun","startedAt","runId","input","resultDir","reportDir","mkdirSync","hasFormatMismatch","duration","ms","seconds","href","from","encodeURIComponent","renderTestResultMarkdown","dump","summary","lines","infrastructure","Boolean","groups","errors","recordSteps","group","failure","testCase","diagnostic","emptyIndex","writeTestResultMarkdown","output","buildTestRunReportDump","stepPosition","info","formatStep","position","formatStepResult","indent","symbol","continuation","caseHasFatalError","isFatalDeviceError","isResourceRecoveryError","documentHasFatalError","isSharedResourceFailure","pending","executeDocumentInvocation","sinks","isProjectResourceFailure","documentRetry","attempts","documentSetup","ctx","runDocumentAttempts","documentAttemptIndex","execution","runWorkflowDocument","run","collectedCase","WorkflowExecutionFailure","partial","resourceOnly","host","decideRetry","publicationError","owners","cleanupPending","owner","operationPending","cleanupFailed","failed","decision","final","failedCases","runPreparedFiles","states","prepared","nextProject","resourcesUnresolved","occupied","occupiedProjects","cleanupQueue","release","wake","running","stopped","invalid","unresolved","finishProject","releaseProject","Promise","waitForScopeOperations","getResourceCleanupCompletion","admit","cleanupOnly","fileResourcesPending","createProjectRuntime","setMaxListeners","getPendingScopeOperations","changed","job","task","settled","admission","trackResourceOperation","completed","reason","order","i","createOperationJournal","writeFileSync","appendFileSync","asNotRun","summarize","healthCases","documentAttemptByRunId","latestById","health","calculateTestRunHealth","items","notRunSuite","runPreparedTestProject","preparedProjects","progress","totalDocuments","totalCases","totalErrors","effectiveConcurrency","journal","rootController","AbortController","handleSignal","sigint","sigterm","failedCaseCount","bailReached","shutdownDeadline","beginShutdown","addFailedCases","count","teardownTimeoutMs","hasInfrastructureError","infrastructureErrors","recordInfrastructureError","runInfrastructureCallback","callback","stopObservingOperations","observeResourceOperations","getDebug","announceProject","projectIndex","buildProjectResult","projectFailed","buildSkippedProjectResult","projectResults","completedProjectResults","endedAt","asExecutionError","completedResult","reportIndex","publish","operation","writeSummary","writeReport","reportPath","TestRunReportAssembler","collectTestRunReportSources","warn","publication","markdownPath","runTestProject"],"mappings":";;;;;;;;;;;;AAYO,MAAMA,wBAETC;ACwDJ,MAAMC,qBAAqB,CAACC,QAA0B,CAAC,QAAQ,EAAEA,OAAO;AAmCjE,MAAMC,oBAAoB,CAI/BC,aACqDA;AAEhD,MAAMC,qBAAqB,CAChCD,aAC4CA;AAEvC,MAAME,kBAAkB,CAC7BF,aACmDA;AAErD,MAAMG,mBAAmB,CAACC,QAAiBC;IACzC,IAAI,AAAkB,YAAlB,OAAOD,UAAuBA,AAAW,SAAXA,UAAmB,aAAaA,QAAQ;QACxE,MAAME,gBAAiBF,OAAgC,OAAO;QAC9D,IACE,AAAyB,YAAzB,OAAOE,iBACPA,AAAkB,SAAlBA,iBACA,gBAAgBA,eAChB;YACA,IAAI,aAAaA,eACf,OAAQA,cAAuC,OAAO;YAExD,MAAM,IAAIC,UACR,CAAC,iBAAiB,EAAEF,aAAa,6BAA6B,CAAC;QAEnE;QACA,OAAOC;IACT;IACA,MAAM,IAAIC,UACR,CAAC,iBAAiB,EAAEF,aAAa,6BAA6B,CAAC;AAEnE;AAEA,MAAMG,WAAW,CAACC,QAChB,AAAiB,YAAjB,OAAOA,SAAsBA,AAAU,SAAVA,SAAkB,CAACC,MAAM,OAAO,CAACD;AAEhE,MAAME,oBAAoB,CACxBF,OACAG,aACAC;IAEA,MAAMC,UAAU,IAAIC,IAAIH;IAC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