@midscene/test 1.12.10-beta-20260920031616.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/{1~891.mjs → 1~214.mjs} +6 -6
- package/dist/es/{1~891.mjs.map → 1~214.mjs.map} +1 -1
- package/dist/es/cli/index.mjs +534 -1700
- package/dist/es/cli/index.mjs.map +1 -1
- package/dist/es/index.mjs +57 -1525
- package/dist/es/index.mjs.map +1 -1
- package/dist/es/midscene/index.mjs +93 -168
- package/dist/es/midscene/index.mjs.map +1 -1
- package/dist/es/runtime/index.mjs +317 -0
- package/dist/es/runtime/index.mjs.map +1 -0
- package/dist/es/test-cli.mjs +666 -1780
- package/dist/es/test-cli.mjs.map +1 -1
- package/dist/lib/{0~458.js → 0~160.js} +5 -5
- package/dist/lib/{0~458.js.map → 0~160.js.map} +1 -1
- package/dist/lib/cli/index.js +545 -1711
- package/dist/lib/cli/index.js.map +1 -1
- package/dist/lib/index.js +92 -1557
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/midscene/index.js +130 -172
- package/dist/lib/midscene/index.js.map +1 -1
- package/dist/lib/runtime/index.js +372 -0
- package/dist/lib/runtime/index.js.map +1 -0
- package/dist/lib/test-cli.js +670 -1784
- package/dist/lib/test-cli.js.map +1 -1
- package/dist/types/cli/index.d.ts +62 -233
- package/dist/types/index.d.ts +186 -492
- package/dist/types/midscene/index.d.ts +82 -96
- package/dist/types/runtime/index.d.ts +52 -0
- package/package.json +51 -8
package/dist/es/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../src/errors.ts","../../src/parser/normalize.ts","../../src/node/define-node.ts","../../src/engine/registry.ts","../../src/engine/execute-step.ts","../../src/engine/scope-teardown.ts","../../src/engine/run-collected-case.ts","../../src/engine/case-runner.ts","../../src/engine/document-runtime.ts","../../src/engine/run-workflow-document.ts","../../src/engine/project-runtime.ts","../../src/parser/variables.ts","../../src/parser/collect.ts","../../src/report/sanitize.ts","../../src/report/test-run-report.ts"],"sourcesContent":["import type { z } from 'zod/v4';\n\nexport interface WorkflowErrorOptions {\n code?: string;\n details?: unknown;\n cause?: unknown;\n}\n\nexport class WorkflowError extends Error {\n readonly code: string;\n readonly details?: unknown;\n\n constructor(message: string, options: WorkflowErrorOptions = {}) {\n super(message, { cause: options.cause });\n this.name = new.target.name;\n this.code = options.code ?? 'WORKFLOW_ERROR';\n this.details = options.details;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n ...(this.details === undefined ? {} : { details: this.details }),\n };\n }\n}\n\nexport class WorkflowParseError extends WorkflowError {\n constructor(message: string, details?: unknown, cause?: unknown) {\n super(message, { code: 'WORKFLOW_PARSE_ERROR', details, cause });\n }\n}\n\nexport class NodeDefinitionError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'NODE_DEFINITION_ERROR', details });\n }\n}\n\nexport class DuplicateNodeError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string) {\n super(`Node \"${node}\" is already registered.`, {\n code: 'DUPLICATE_NODE',\n details: { node },\n });\n this.node = node;\n }\n}\n\nexport class NodeNotFoundError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string) {\n super(`Node \"${node}\" is not registered.`, {\n code: 'NODE_NOT_FOUND',\n details: { node },\n });\n this.node = node;\n }\n}\n\nexport class NodeInputValidationError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'NODE_INPUT_VALIDATION_ERROR', details });\n }\n\n static fromZod(node: string, error: z.ZodError): NodeInputValidationError {\n const issues = error.issues.map((issue) => ({\n code: issue.code,\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n const firstIssue = issues[0];\n const path = firstIssue?.path || '<root>';\n const message = firstIssue?.message ?? 'invalid input';\n return new NodeInputValidationError(\n `Node \"${node}\" input validation failed at \"${path}\": ${message}`,\n { node, issues },\n );\n }\n}\n\nexport class StepTimeoutError extends WorkflowError {\n readonly timeoutMs: number;\n readonly node?: string;\n\n constructor(timeoutMs: number, node?: string) {\n super(\n node\n ? `Node \"${node}\" timed out after ${timeoutMs}ms.`\n : `Step timed out after ${timeoutMs}ms.`,\n {\n code: 'STEP_TIMEOUT',\n details: { timeoutMs, ...(node === undefined ? {} : { node }) },\n },\n );\n this.timeoutMs = timeoutMs;\n this.node = node;\n }\n}\n\nexport class NodeExecutionError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string, cause: unknown) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Node \"${node}\" failed: ${causeMessage}`, {\n code: 'NODE_EXECUTION_ERROR',\n details: { node },\n cause,\n });\n this.node = node;\n }\n}\n\nexport class WorkflowLifecycleError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'WORKFLOW_LIFECYCLE_ERROR', details });\n }\n}\n\nexport class ProjectSetupError extends WorkflowError {\n constructor(cause: unknown, details: { projectName: string }) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Project \"${details.projectName}\" setup failed: ${causeMessage}`, {\n code: 'PROJECT_SETUP_ERROR',\n details,\n cause,\n });\n }\n}\n\nexport class ProjectTeardownError extends WorkflowError {\n constructor(\n cause: unknown,\n details: { projectName: string; registrationIndex: number },\n ) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Project \"${details.projectName}\" teardown failed: ${causeMessage}`, {\n code: 'PROJECT_TEARDOWN_ERROR',\n details,\n cause,\n });\n }\n}\n\nexport class NodeScopeTeardownError extends WorkflowError {\n constructor(\n cause: unknown,\n details: {\n scope: 'case' | 'document';\n scopeId: string;\n node: string;\n registrationIndex: number;\n },\n ) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(\n `${details.scope === 'case' ? 'Case attempt' : 'Workflow document'} node teardown failed for \"${details.node}\": ${causeMessage}`,\n { code: 'NODE_SCOPE_TEARDOWN_ERROR', details, cause },\n );\n }\n}\n\nexport class FatalDeviceError extends WorkflowError {\n constructor(message: string, cause?: unknown) {\n super(message, { code: 'FATAL_DEVICE_ERROR', cause });\n }\n}\n\nexport const isFatalDeviceError = (error: unknown): boolean => {\n if (error instanceof FatalDeviceError) return true;\n if (error instanceof WorkflowError && error.code === 'FATAL_DEVICE_ERROR') {\n return true;\n }\n if (\n error instanceof Error &&\n /device offline|device not found|(?:adb|bdc|device) connection (?:was )?closed/i.test(\n error.message,\n )\n ) {\n return true;\n }\n return error instanceof Error && error.cause !== undefined\n ? isFatalDeviceError(error.cause)\n : false;\n};\n\nexport class CaseExecutionError extends WorkflowError {\n readonly result: import('./engine/types').CaseRunResult;\n\n constructor(result: import('./engine/types').CaseRunResult) {\n super(`Case \"${result.name}\" failed.`, {\n code: 'CASE_EXECUTION_FAILED',\n details: { caseId: result.caseId, runId: result.runId },\n });\n this.result = result;\n }\n}\n\nexport class WorkflowDocumentExecutionError extends WorkflowError {\n readonly result: import('./engine/types').WorkflowDocumentRunResult;\n\n constructor(result: import('./engine/types').WorkflowDocumentRunResult) {\n super(`Workflow document \"${result.sourcePath}\" failed.`, {\n code: 'WORKFLOW_DOCUMENT_EXECUTION_FAILED',\n details: {\n documentId: result.documentId,\n documentRunId: result.documentRunId,\n },\n });\n this.result = result;\n }\n}\n\nexport function normalizeNodeExecutionError(\n error: unknown,\n node: string,\n): WorkflowError {\n return error instanceof WorkflowError\n ? error\n : new NodeExecutionError(node, error);\n}\n","import { WorkflowParseError } from '../errors';\nimport type { NormalizedStep, NormalizedStepMeta } from './types';\n\ninterface StringInputNodeDefinition {\n stringInputKey?: string | false;\n}\n\nexport type ResolveNodeForNormalization = (\n name: string,\n) => StringInputNodeDefinition | undefined;\n\nconst supportedMetaKeys = new Set(['timeout', 'continue-on-error']);\n\nfunction isMapping(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype ||\n Object.getPrototypeOf(value) === null)\n );\n}\n\nfunction formatStep(index: number): string {\n return `step ${index + 1}`;\n}\n\nfunction normalizeMeta(value: unknown, index: number): NormalizedStepMeta {\n if (value === undefined) {\n return { continueOnError: false };\n }\n\n if (!isMapping(value)) {\n throw new WorkflowParseError(\n `${formatStep(index)} \"$\" must be a mapping.`,\n { index },\n );\n }\n\n for (const key of Object.keys(value)) {\n if (!supportedMetaKeys.has(key)) {\n throw new WorkflowParseError(\n `${formatStep(index)} has unsupported engine metadata \"${key}\".`,\n { index, key },\n );\n }\n }\n\n const timeout = value.timeout;\n if (\n timeout !== undefined &&\n (typeof timeout !== 'number' || !Number.isFinite(timeout) || timeout <= 0)\n ) {\n throw new WorkflowParseError(\n `${formatStep(index)} \"$.timeout\" must be a positive number of milliseconds.`,\n { index, timeout },\n );\n }\n\n const continueOnError = value['continue-on-error'];\n if (continueOnError !== undefined && typeof continueOnError !== 'boolean') {\n throw new WorkflowParseError(\n `${formatStep(index)} \"$.continue-on-error\" must be a boolean.`,\n { index, continueOnError },\n );\n }\n\n return {\n ...(timeout === undefined ? {} : { timeoutMs: timeout }),\n continueOnError: continueOnError ?? false,\n };\n}\n\nexport function normalizeStep(\n value: unknown,\n index = 0,\n resolveNode?: ResolveNodeForNormalization,\n): NormalizedStep {\n if (!isMapping(value)) {\n throw new WorkflowParseError(`${formatStep(index)} must be a mapping.`, {\n index,\n });\n }\n\n const entries = Object.entries(value);\n if (entries.length !== 1) {\n throw new WorkflowParseError(\n `${formatStep(index)} must contain exactly one node.`,\n { index, nodes: Object.keys(value) },\n );\n }\n\n const [node, rawValue] = entries[0];\n if (node.trim().length === 0) {\n throw new WorkflowParseError(\n `${formatStep(index)} node name must not be empty.`,\n { index },\n );\n }\n\n if (typeof rawValue === 'string') {\n const resolvedNode = resolveNode?.(node);\n const stringInputKey = resolvedNode\n ? resolvedNode.stringInputKey\n : 'prompt';\n if (stringInputKey === false || stringInputKey === undefined) {\n throw new WorkflowParseError(\n `${formatStep(index)} node \"${node}\" does not accept string shorthand.`,\n { index, node },\n );\n }\n return {\n node,\n input: { [stringInputKey]: rawValue },\n meta: { continueOnError: false },\n };\n }\n\n if (!isMapping(rawValue)) {\n throw new WorkflowParseError(\n `${formatStep(index)} value must be a string shorthand or a mapping.`,\n { index, node },\n );\n }\n\n const { $: rawMeta, ...input } = rawValue;\n\n return {\n node,\n input,\n meta: normalizeMeta(rawMeta, index),\n };\n}\n\nexport function normalizeSteps(\n steps: unknown,\n resolveNode?: ResolveNodeForNormalization,\n): NormalizedStep[] {\n if (!Array.isArray(steps)) {\n throw new WorkflowParseError('Steps must be an array.');\n }\n return steps.map((step, index) => normalizeStep(step, index, resolveNode));\n}\n","import { z } from 'zod/v4';\nimport { NodeDefinitionError } from '../errors';\nimport type {\n DefineNodeOptions,\n DefineNodeWithSchemaOptions,\n NodeDefinition,\n NodeDefinitionWithSchema,\n NodeInputSchema,\n} from './types';\n\nconst validateOptionalText = (\n value: unknown,\n field: 'title' | 'description',\n node: string,\n): void => {\n if (\n value !== undefined &&\n (typeof value !== 'string' || value.trim().length === 0)\n ) {\n throw new NodeDefinitionError(\n `Node \"${node}\" ${field} must be a non-empty string.`,\n { node, field },\n );\n }\n};\n\nconst validateInputSchema = (schema: unknown, node: string): void => {\n if (schema === undefined) return;\n if (!(schema instanceof z.ZodObject)) {\n throw new NodeDefinitionError(\n `Node \"${node}\" inputSchema must be a Zod object schema.`,\n { node, field: 'inputSchema' },\n );\n }\n if ('$' in schema.shape) {\n throw new NodeDefinitionError(\n `Node \"${node}\" inputSchema must not declare \"$\" as an input property.`,\n { node, field: 'inputSchema.$' },\n );\n }\n};\n\nconst validateDefinition = (options: {\n name: string;\n title?: unknown;\n description?: unknown;\n stringInputKey?: unknown;\n inputSchema?: unknown;\n execute: unknown;\n}): void => {\n if (!options || typeof options !== 'object') {\n throw new NodeDefinitionError('Node definition must be an object.');\n }\n\n if (typeof options.name !== 'string' || options.name.trim().length === 0) {\n throw new NodeDefinitionError('Node name must be a non-empty string.');\n }\n\n validateOptionalText(options.title, 'title', options.name);\n validateOptionalText(options.description, 'description', options.name);\n if (\n options.stringInputKey !== undefined &&\n options.stringInputKey !== false &&\n (typeof options.stringInputKey !== 'string' ||\n options.stringInputKey.trim().length === 0)\n ) {\n throw new NodeDefinitionError(\n `Node \"${options.name}\" stringInputKey must be a non-empty string or false.`,\n { node: options.name, field: 'stringInputKey' },\n );\n }\n validateInputSchema(options.inputSchema, options.name);\n\n if (\n typeof options.stringInputKey === 'string' &&\n options.inputSchema instanceof z.ZodObject &&\n !(options.stringInputKey in options.inputSchema.shape)\n ) {\n throw new NodeDefinitionError(\n `Node \"${options.name}\" stringInputKey must reference a field in inputSchema.`,\n { node: options.name, field: 'stringInputKey' },\n );\n }\n\n if (typeof options.execute !== 'function') {\n throw new NodeDefinitionError(\n `Node \"${options.name}\" must provide an execute function.`,\n { node: options.name },\n );\n }\n};\n\nexport function defineNode<\n TSchema extends NodeInputSchema,\n TData = unknown,\n TContext = unknown,\n>(\n options: DefineNodeWithSchemaOptions<TSchema, TData, TContext>,\n): NodeDefinitionWithSchema<TSchema, TData, TContext>;\n\nexport function defineNode<\n TInput = unknown,\n TData = unknown,\n TContext = unknown,\n>(\n options: DefineNodeOptions<TInput, TData, TContext>,\n): NodeDefinition<TInput, TData, TContext>;\n\nexport function defineNode(\n options: DefineNodeOptions<any, any, any>,\n): NodeDefinition<any, any, any> {\n validateDefinition(options);\n return options;\n}\n","import { DuplicateNodeError, NodeNotFoundError } from '../errors';\nimport { defineNode } from '../node/define-node';\nimport type { NodeDefinition } from '../node/types';\n\nexport class NodeRegistry {\n readonly #nodes = new Map<string, NodeDefinition<any, any, any>>();\n\n constructor(nodes: readonly NodeDefinition<any, any>[] = []) {\n for (const node of nodes) {\n this.register(node);\n }\n }\n\n register<TInput, TData>(node: NodeDefinition<TInput, TData>): this {\n defineNode(node);\n\n if (this.#nodes.has(node.name)) {\n throw new DuplicateNodeError(node.name);\n }\n\n this.#nodes.set(node.name, node);\n return this;\n }\n\n get(name: string): NodeDefinition<any, any> | undefined {\n return this.#nodes.get(name);\n }\n\n require(name: string): NodeDefinition<any, any> {\n const node = this.get(name);\n if (!node) {\n throw new NodeNotFoundError(name);\n }\n return node;\n }\n\n has(name: string): boolean {\n return this.#nodes.has(name);\n }\n\n names(): string[] {\n return [...this.#nodes.keys()];\n }\n\n definitions(): readonly NodeDefinition<any, any, any>[] {\n return [...this.#nodes.values()];\n }\n}\n","import {\n NodeExecutionError,\n NodeInputValidationError,\n StepTimeoutError,\n normalizeNodeExecutionError,\n} from '../errors';\nimport type {\n NodeDefinition,\n NodeReportCollector,\n NodeReportTrace,\n NodeResult,\n} from '../node/types';\nimport type { NormalizedStep } from '../parser/types';\nimport type {\n NodeCaseContext,\n NodeDocumentContext,\n NodeExecutionPhase,\n NodeScopeTeardown,\n StepRunResult,\n} from './types';\n\nconst assertJsonSerializable = (\n value: unknown,\n label: string,\n node: string,\n): void => {\n const visit = (\n candidate: unknown,\n path: string,\n seen: Set<unknown>,\n ): void => {\n if (\n candidate === null ||\n typeof candidate === 'string' ||\n typeof candidate === 'boolean'\n ) {\n return;\n }\n if (typeof candidate === 'number') {\n if (Number.isFinite(candidate)) return;\n throw new TypeError(`${path} contains a non-finite number.`);\n }\n if (candidate === undefined) {\n throw new TypeError(`${path} contains undefined.`);\n }\n if (typeof candidate !== 'object') {\n throw new TypeError(`${path} is not JSON-serializable.`);\n }\n if (\n !Array.isArray(candidate) &&\n Object.getPrototypeOf(candidate) !== Object.prototype &&\n Object.getPrototypeOf(candidate) !== null\n ) {\n throw new TypeError(`${path} must contain only plain objects.`);\n }\n if (seen.has(candidate)) throw new TypeError(`${path} contains a cycle.`);\n seen.add(candidate);\n if (Array.isArray(candidate)) {\n candidate.forEach((child, index) =>\n visit(child, `${path}[${index}]`, seen),\n );\n } else {\n for (const [key, child] of Object.entries(candidate)) {\n visit(child, `${path}.${key}`, seen);\n }\n }\n seen.delete(candidate);\n };\n\n try {\n visit(value, label, new Set());\n } catch (error) {\n throw new NodeExecutionError(node, error);\n }\n};\n\nfunction validateNodeOutput<TData>(\n output: unknown,\n node: string,\n): NodeResult<TData> | undefined {\n if (output === undefined) {\n return undefined;\n }\n\n if (typeof output !== 'object' || output === null || Array.isArray(output)) {\n throw new NodeExecutionError(\n node,\n new TypeError('Node output must be an object or undefined.'),\n );\n }\n\n if (\n 'summary' in output &&\n output.summary !== undefined &&\n typeof output.summary !== 'string'\n ) {\n throw new NodeExecutionError(\n node,\n new TypeError('Node output summary must be a string.'),\n );\n }\n\n if ('data' in output && output.data !== undefined) {\n assertJsonSerializable(output.data, 'output.data', node);\n }\n\n return output as NodeResult<TData>;\n}\n\nfunction createStepResultBase(\n step: NormalizedStep,\n startedAt: Date,\n phase: NodeExecutionPhase,\n stepIndex: number,\n) {\n const endedAt = new Date();\n return {\n node: step.node,\n phase,\n stepIndex,\n input: step.input,\n meta: step.meta,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n };\n}\n\nasync function executeNode<TOutputData>(\n step: NormalizedStep,\n execute: (signal: AbortSignal) => unknown,\n phase: NodeExecutionPhase,\n stepIndex: number,\n options: { parentSignal?: AbortSignal; defaultTimeoutMs?: number },\n): Promise<StepRunResult<TOutputData>> {\n const startedAt = new Date();\n const abortController = new AbortController();\n const parentSignal = options.parentSignal;\n const abortFromParent = () => abortController.abort(parentSignal?.reason);\n if (parentSignal?.aborted) abortFromParent();\n else parentSignal?.addEventListener('abort', abortFromParent, { once: true });\n const timeoutMs = step.meta.timeoutMs ?? options.defaultTimeoutMs;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let abortGraceTimeout: ReturnType<typeof setTimeout> | undefined;\n const execution = Promise.resolve().then(() => {\n abortController.signal.throwIfAborted();\n return execute(abortController.signal);\n });\n let settleOnAbort: (() => void) | undefined;\n const abortedExecution = new Promise<never>((_, reject) => {\n settleOnAbort = () => {\n // Abort listeners run synchronously. Wait one task before rejecting so a\n // cooperative node can settle in response to the forwarded abort first.\n abortGraceTimeout = setTimeout(() => {\n reject(abortController.signal.reason);\n }, 0);\n };\n if (abortController.signal.aborted) settleOnAbort();\n else\n abortController.signal.addEventListener('abort', settleOnAbort, {\n once: true,\n });\n });\n const timeoutExecution =\n timeoutMs === undefined\n ? undefined\n : new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n if (abortController.signal.aborted) {\n reject(abortController.signal.reason);\n return;\n }\n const timeoutError = new StepTimeoutError(timeoutMs, step.node);\n abortController.abort(timeoutError);\n reject(timeoutError);\n }, timeoutMs);\n });\n const settledExecution = Promise.race([\n execution,\n abortedExecution,\n ...(timeoutExecution === undefined ? [] : [timeoutExecution]),\n ]);\n\n try {\n const output = validateNodeOutput<TOutputData>(\n await settledExecution,\n step.node,\n );\n return {\n ...createStepResultBase(step, startedAt, phase, stepIndex),\n status: 'success',\n continuedAfterError: false,\n ...(output === undefined ? {} : { output }),\n };\n } catch (error) {\n return {\n ...createStepResultBase(step, startedAt, phase, stepIndex),\n status: 'failed',\n continuedAfterError: step.meta.continueOnError,\n error: normalizeNodeExecutionError(error, step.node),\n };\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n if (abortGraceTimeout !== undefined) clearTimeout(abortGraceTimeout);\n if (settleOnAbort !== undefined) {\n abortController.signal.removeEventListener('abort', settleOnAbort);\n }\n parentSignal?.removeEventListener('abort', abortFromParent);\n }\n}\n\ntype StepExecutionTarget =\n | { scope: 'case'; case: NodeCaseContext }\n | { scope: 'document'; document: NodeDocumentContext };\n\nfunction createNodeReportCollector(node: string): {\n collector: NodeReportCollector;\n close(): readonly NodeReportTrace[];\n} {\n const traces = new Map<string, NodeReportTrace>();\n let accepting = true;\n\n return {\n collector: Object.freeze({\n addTrace(trace: NodeReportTrace): void {\n if (!accepting) {\n throw new NodeExecutionError(\n node,\n new Error(\n 'Report traces can only be added while the current Step is running.',\n ),\n );\n }\n if (\n !trace ||\n typeof trace !== 'object' ||\n (trace as { type?: unknown }).type !== 'midscene-execution'\n ) {\n throw new NodeExecutionError(\n node,\n new TypeError('Report trace type must be \"midscene-execution\".'),\n );\n }\n if (\n typeof trace.executionId !== 'string' ||\n trace.executionId.trim().length === 0\n ) {\n throw new NodeExecutionError(\n node,\n new TypeError('Report trace executionId must be non-empty.'),\n );\n }\n const normalized = Object.freeze({\n type: 'midscene-execution' as const,\n executionId: trace.executionId,\n });\n traces.set(`${normalized.type}:${normalized.executionId}`, normalized);\n },\n }),\n close(): readonly NodeReportTrace[] {\n accepting = false;\n return Object.freeze([...traces.values()]);\n },\n };\n}\n\nasync function parseNodeInput<TInput, TData, TContext>(\n node: NodeDefinition<TInput, TData, TContext>,\n input: Record<string, unknown>,\n): Promise<TInput> {\n if (!node.inputSchema) {\n return input as TInput;\n }\n\n const parsed = await node.inputSchema.safeParseAsync(input);\n if (!parsed.success) {\n throw NodeInputValidationError.fromZod(node.name, parsed.error);\n }\n return parsed.data as TInput;\n}\n\nexport async function executeStep<\n TInput = unknown,\n TOutputData = unknown,\n TContext = unknown,\n>(\n step: NormalizedStep,\n node: NodeDefinition<TInput, TOutputData, TContext>,\n target: StepExecutionTarget,\n context: TContext,\n execution: {\n signal?: AbortSignal;\n defaultTimeoutMs?: number;\n onTeardown?(node: string, teardown: NodeScopeTeardown): void;\n } = {},\n): Promise<StepRunResult<TOutputData>> {\n const phase =\n target.scope === 'case' ? target.case.phase : target.document.phase;\n const stepIndex =\n target.scope === 'case' ? target.case.stepIndex : target.document.stepIndex;\n\n const reportCollector = createNodeReportCollector(step.node);\n let result: StepRunResult<TOutputData> | undefined;\n\n try {\n result = await executeNode<TOutputData>(\n step,\n async (signal) => {\n const input = await parseNodeInput(node, step.input);\n signal.throwIfAborted();\n const common = {\n input,\n $: step.meta,\n signal,\n context,\n report: reportCollector.collector,\n onTeardown: (teardown: NodeScopeTeardown) => {\n if (!execution.onTeardown) {\n throw new NodeExecutionError(\n step.node,\n new Error(\n 'The current execution scope cannot register teardown.',\n ),\n );\n }\n execution.onTeardown(step.node, teardown);\n },\n };\n return target.scope === 'case'\n ? node.execute({ ...common, scope: 'case', case: target.case })\n : node.execute({\n ...common,\n scope: 'document',\n document: target.document,\n });\n },\n phase,\n stepIndex,\n {\n parentSignal: execution.signal,\n defaultTimeoutMs: execution.defaultTimeoutMs,\n },\n );\n } finally {\n const traces = reportCollector.close();\n if (traces.length > 0 && result) {\n result = { ...result, report: { traces } };\n }\n }\n\n if (!result) {\n throw new NodeExecutionError(\n step.node,\n new Error('Step execution completed without a result.'),\n );\n }\n return result;\n}\n","import { isAbsolute } from 'node:path';\nimport type { NodeScopeTeardownResult } from './types';\n\nexport const reportPathsFromTeardown = (\n // biome-ignore lint/suspicious/noConfusingVoidType: this consumes the intentional void teardown return.\n result: NodeScopeTeardownResult | void,\n): readonly string[] => {\n if (result === undefined) return [];\n if (typeof result !== 'object' || result === null || Array.isArray(result)) {\n throw new TypeError('Node teardown result must be an object or undefined.');\n }\n const paths = result.reportPaths;\n if (paths === undefined) return [];\n if (!Array.isArray(paths)) {\n throw new TypeError('Node teardown reportPaths must be an array.');\n }\n return paths.map((path, index) => {\n if (typeof path !== 'string' || path.trim().length === 0) {\n throw new TypeError(\n `Node teardown reportPaths[${index}] must be a non-empty string.`,\n );\n }\n if (!isAbsolute(path)) {\n throw new TypeError(\n `Node teardown reportPaths[${index}] must be an absolute path.`,\n );\n }\n return path;\n });\n};\n","import { randomUUID } from 'node:crypto';\nimport { NodeScopeTeardownError, WorkflowLifecycleError } from '../errors';\nimport type { CollectedCase, NormalizedStep } from '../parser/types';\nimport { executeStep } from './execute-step';\nimport { reportPathsFromTeardown } from './scope-teardown';\nimport type {\n CaseNodePhase,\n CaseRunResult,\n NodeCaseContext,\n NodeScopeTeardown,\n RunCollectedCaseOptions,\n StepRunResult,\n} from './types';\n\nexport async function runCollectedCase<TContext = undefined>(\n collectedCase: CollectedCase,\n options: RunCollectedCaseOptions<TContext>,\n): Promise<CaseRunResult> {\n const phases: Record<CaseNodePhase, readonly NormalizedStep[]> = {\n beforeEach: options.beforeEach ?? [],\n steps: collectedCase.definition.steps,\n afterEach: options.afterEach ?? [],\n };\n const nodes = {\n beforeEach: phases.beforeEach.map((step) => options.resolveNode(step.node)),\n steps: phases.steps.map((step) => options.resolveNode(step.node)),\n afterEach: phases.afterEach.map((step) => options.resolveNode(step.node)),\n };\n const runId = options.createRunId?.() ?? randomUUID();\n const startedAt = new Date();\n const beforeEach: StepRunResult[] = [];\n const steps: StepRunResult[] = [];\n const afterEach: StepRunResult[] = [];\n const teardownStack: Array<{\n registrationIndex: number;\n node: string;\n teardown: NodeScopeTeardown;\n }> = [];\n let acceptingTeardowns = true;\n\n const onTeardown = (node: string, teardown: NodeScopeTeardown): void => {\n if (!acceptingTeardowns) {\n throw new WorkflowLifecycleError(\n 'Node teardown can only be registered while a case attempt is running.',\n { runId, node },\n );\n }\n if (typeof teardown !== 'function') {\n throw new WorkflowLifecycleError(\n 'Node onTeardown() requires a teardown function.',\n { runId, node },\n );\n }\n teardownStack.push({\n registrationIndex: teardownStack.length,\n node,\n teardown,\n });\n };\n\n const runPhase = async (\n phase: CaseNodePhase,\n results: StepRunResult[],\n signal = options.signal,\n ): Promise<void> => {\n for (const [stepIndex, step] of phases[phase].entries()) {\n const caseContext: NodeCaseContext = {\n caseId: collectedCase.caseId,\n runId,\n projectName: options.projectName ?? collectedCase.projectId,\n attemptIndex: options.attemptIndex ?? 0,\n name: collectedCase.definition.name,\n sourcePath: collectedCase.sourcePath,\n caseIndex: collectedCase.caseIndex,\n phase,\n stepIndex,\n };\n const stepInfo = {\n scope: 'case' as const,\n node: step.node,\n stepCount: phases[phase].length,\n case: caseContext,\n };\n await options.onStepStart?.(stepInfo);\n const result = await executeStep(\n step,\n nodes[phase][stepIndex],\n { scope: 'case', case: caseContext },\n options.context as TContext,\n {\n signal,\n defaultTimeoutMs: options.defaultTimeoutMs,\n onTeardown,\n },\n );\n await options.onStepResult?.(stepInfo, result);\n results.push(result);\n if (result.status === 'failed' && !result.continuedAfterError) break;\n }\n };\n\n let executionError: unknown;\n try {\n await runPhase('beforeEach', beforeEach);\n if (!beforeEach.some((step) => step.status === 'failed')) {\n await runPhase('steps', steps);\n }\n } catch (error) {\n executionError = error;\n }\n try {\n const cleanupSignal = options.signal?.aborted\n ? new AbortController().signal\n : options.signal;\n await runPhase('afterEach', afterEach, cleanupSignal);\n } catch (error) {\n executionError ??= error;\n }\n\n acceptingTeardowns = false;\n const teardownErrors: NodeScopeTeardownError[] = [];\n const reportPaths = new Set<string>();\n for (const { registrationIndex, node, teardown } of teardownStack.reverse()) {\n try {\n for (const path of reportPathsFromTeardown(await teardown())) {\n reportPaths.add(path);\n }\n } catch (error) {\n teardownErrors.push(\n new NodeScopeTeardownError(error, {\n scope: 'case',\n scopeId: runId,\n node,\n registrationIndex,\n }),\n );\n }\n }\n if (executionError) throw executionError;\n\n const endedAt = new Date();\n const result: CaseRunResult = {\n caseId: collectedCase.caseId,\n runId,\n projectName: options.projectName ?? collectedCase.projectId,\n attemptIndex: options.attemptIndex ?? 0,\n name: collectedCase.definition.name,\n sourcePath: collectedCase.sourcePath,\n caseIndex: collectedCase.caseIndex,\n status:\n beforeEach.some((step) => step.status === 'failed') ||\n steps.some((step) => step.status === 'failed') ||\n afterEach.some((step) => step.status === 'failed') ||\n teardownErrors.length > 0\n ? 'failed'\n : 'success',\n beforeEach,\n steps,\n afterEach,\n ...(teardownErrors.length > 0 ? { teardownErrors } : {}),\n ...(reportPaths.size > 0 ? { reportPaths: [...reportPaths] } : {}),\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n };\n\n await options.onResult?.(result);\n return result;\n}\n","import type { NodeDefinition } from '../node/types';\nimport { normalizeSteps } from '../parser/normalize';\nimport type { CaseInput, CollectedCase } from '../parser/types';\nimport { NodeRegistry } from './registry';\nimport { runCollectedCase } from './run-collected-case';\nimport type { CaseRunResult, CaseRunnerOptions } from './types';\n\nexport class CaseRunner<TContext = undefined> {\n readonly registry: NodeRegistry;\n readonly context: TContext;\n\n constructor(options: CaseRunnerOptions<TContext> = {}) {\n this.registry = new NodeRegistry(options.nodes);\n this.context = options.context as TContext;\n }\n\n register<TInput, TData>(node: NodeDefinition<TInput, TData, TContext>): this {\n this.registry.register(node);\n return this;\n }\n\n async run(input: CaseInput): Promise<CaseRunResult> {\n const collectedCase: CollectedCase = {\n caseId: 'standalone-case',\n projectId: 'standalone-project',\n sourcePath: '',\n caseIndex: 0,\n definition: {\n name: input.name ?? 'case',\n tags: input.tags ?? [],\n steps: normalizeSteps(input.steps, (name) => this.registry.get(name)),\n },\n };\n const result = await runCollectedCase(collectedCase, {\n resolveNode: (name) =>\n this.registry.require(name) as NodeDefinition<any, any, TContext>,\n context: this.context,\n createRunId: () => 'standalone-case',\n });\n\n const fatalStepError = result.steps.find(\n (step) => step.status === 'failed' && !step.continuedAfterError,\n )?.error;\n if (fatalStepError) throw fatalStepError;\n return result;\n }\n}\n\nexport function createCaseRunner<TContext = undefined>(\n options: CaseRunnerOptions<TContext> = {},\n): CaseRunner<TContext> {\n return new CaseRunner(options);\n}\n","import { randomUUID } from 'node:crypto';\nimport {\n NodeScopeTeardownError,\n type WorkflowError,\n WorkflowLifecycleError,\n} from '../errors';\nimport type { CollectedWorkflowDocument } from '../parser/types';\nimport { executeStep } from './execute-step';\nimport { reportPathsFromTeardown } from './scope-teardown';\nimport type {\n CreateDocumentRuntimeOptions,\n DocumentNodePhase,\n NodeDocumentContext,\n NodeScopeTeardown,\n StepRunResult,\n WorkflowDocumentRunResult,\n WorkflowDocumentRuntime,\n} from './types';\n\nexport function createDocumentRuntime<TContext = undefined>(\n document: CollectedWorkflowDocument,\n options: CreateDocumentRuntimeOptions<TContext>,\n): WorkflowDocumentRuntime<TContext> {\n const documentRunId = options.createDocumentRunId?.() ?? randomUUID();\n const startedAt = new Date();\n const beforeAll: StepRunResult[] = [];\n const afterAll: StepRunResult[] = [];\n const nodes = {\n beforeAll: document.lifecycle.beforeAll.map((step) =>\n options.resolveNode(step.node),\n ),\n afterAll: document.lifecycle.afterAll.map((step) =>\n options.resolveNode(step.node),\n ),\n };\n const project =\n options.project ??\n Object.freeze({\n projectId: document.projectId,\n name: document.projectId,\n tags: Object.freeze({ include: [], exclude: [] }),\n retry: 0,\n variables: Object.freeze({}),\n });\n const context = options.projectContext as TContext;\n const signal = options.signal ?? new AbortController().signal;\n const nodeTeardownStack: Array<{\n registrationIndex: number;\n node: string;\n teardown: NodeScopeTeardown;\n }> = [];\n let acceptingNodeTeardowns = true;\n let started = false;\n let finishedResult: WorkflowDocumentRunResult | undefined;\n const reportPaths = new Set<string>();\n\n const createResult = (\n teardownErrors: WorkflowError[] = [],\n ): WorkflowDocumentRunResult => {\n const endedAt = new Date();\n return {\n documentId: document.documentId,\n documentRunId,\n projectId: document.projectId,\n projectName: project.name,\n sourcePath: document.sourcePath,\n status:\n beforeAll.some((step) => step.status === 'failed') ||\n afterAll.some((step) => step.status === 'failed') ||\n teardownErrors.length > 0\n ? 'failed'\n : 'success',\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n beforeAll: [...beforeAll],\n afterAll: [...afterAll],\n ...(teardownErrors.length > 0 ? { teardownErrors } : {}),\n ...(reportPaths.size > 0 ? { reportPaths: [...reportPaths] } : {}),\n };\n };\n\n const runPhase = async (\n phase: DocumentNodePhase,\n results: StepRunResult[],\n executionSignal = signal,\n ): Promise<void> => {\n for (const [stepIndex, step] of document.lifecycle[phase].entries()) {\n const documentContext: NodeDocumentContext = {\n documentId: document.documentId,\n documentRunId,\n projectId: document.projectId,\n projectName: project.name,\n sourcePath: document.sourcePath,\n phase,\n stepIndex,\n };\n const stepInfo = {\n scope: 'document' as const,\n node: step.node,\n stepCount: document.lifecycle[phase].length,\n document: documentContext,\n };\n await options.onStepStart?.(stepInfo);\n const result = await executeStep(\n step,\n nodes[phase][stepIndex],\n { scope: 'document', document: documentContext },\n context,\n {\n signal: executionSignal,\n defaultTimeoutMs: options.defaultTimeoutMs,\n onTeardown(node, teardown) {\n if (!acceptingNodeTeardowns) {\n throw new WorkflowLifecycleError(\n 'Node teardown can only be registered while a workflow document is running.',\n { documentId: document.documentId, documentRunId, node },\n );\n }\n if (typeof teardown !== 'function') {\n throw new WorkflowLifecycleError(\n 'Node onTeardown() requires a teardown function.',\n { documentId: document.documentId, documentRunId, node },\n );\n }\n nodeTeardownStack.push({\n registrationIndex: nodeTeardownStack.length,\n node,\n teardown,\n });\n },\n },\n );\n await options.onStepResult?.(stepInfo, result);\n results.push(result);\n if (result.status === 'failed' && !result.continuedAfterError) break;\n }\n };\n\n return {\n get context() {\n return context;\n },\n get canRunCases() {\n return (\n started &&\n !signal.aborted &&\n !beforeAll.some((step) => step.status === 'failed')\n );\n },\n async start() {\n if (started) {\n throw new WorkflowLifecycleError(\n 'Workflow document runtime has already started.',\n { documentId: document.documentId, documentRunId },\n );\n }\n started = true;\n if (!signal.aborted) await runPhase('beforeAll', beforeAll);\n return createResult();\n },\n async finish() {\n if (finishedResult) return finishedResult;\n if (!started) {\n throw new WorkflowLifecycleError(\n 'Workflow document runtime must start before it can finish.',\n { documentId: document.documentId, documentRunId },\n );\n }\n let finishError: unknown;\n try {\n await runPhase(\n 'afterAll',\n afterAll,\n signal.aborted ? new AbortController().signal : signal,\n );\n } catch (error) {\n finishError = error;\n }\n\n acceptingNodeTeardowns = false;\n const teardownErrors: WorkflowError[] = [];\n for (const {\n registrationIndex,\n node,\n teardown,\n } of nodeTeardownStack.reverse()) {\n try {\n for (const path of reportPathsFromTeardown(await teardown())) {\n reportPaths.add(path);\n }\n } catch (error) {\n teardownErrors.push(\n new NodeScopeTeardownError(error, {\n scope: 'document',\n scopeId: documentRunId,\n node,\n registrationIndex,\n }),\n );\n }\n }\n finishedResult = createResult(teardownErrors);\n if (finishError) throw finishError;\n await options.onResult?.(finishedResult);\n return finishedResult;\n },\n };\n}\n","import type { CollectedCase, CollectedWorkflowDocument } from '../parser/types';\nimport { createDocumentRuntime } from './document-runtime';\nimport { runCollectedCase } from './run-collected-case';\nimport type {\n CaseRunOutcome,\n RunWorkflowDocumentOptions,\n WorkflowDocumentExecutionResult,\n WorkflowDocumentRunResult,\n} from './types';\n\nconst asNotRun = (\n collectedCase: CollectedCase,\n projectName: string,\n reason: NonNullable<CaseRunOutcome['notRunReason']>,\n): CaseRunOutcome => ({\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\nexport async function runWorkflowDocument<TContext = undefined>(\n document: CollectedWorkflowDocument,\n options: RunWorkflowDocumentOptions<TContext>,\n): Promise<WorkflowDocumentExecutionResult> {\n const createDocumentRunId = options.createDocumentRunId;\n const createCaseRunId = options.createCaseRunId;\n const projectName = options.project?.name ?? document.projectId;\n const retry = options.retry ?? options.project?.retry ?? 0;\n if (!Number.isInteger(retry) || retry < 0) {\n throw new TypeError(\n 'Workflow document retry must be a non-negative integer.',\n );\n }\n const runtime = createDocumentRuntime(document, {\n resolveNode: options.resolveNode,\n project: options.project,\n projectContext: options.projectContext,\n signal: options.signal,\n defaultTimeoutMs: options.defaultTimeoutMs,\n onStepStart: options.onStepStart,\n onStepResult: options.onStepResult,\n onResult: options.onDocumentResult,\n createDocumentRunId: createDocumentRunId\n ? () => createDocumentRunId(document)\n : undefined,\n });\n const cases: CaseRunOutcome[] = [];\n let runtimeStarted = false;\n let documentResult: WorkflowDocumentRunResult | undefined;\n let executionError: unknown;\n let fatalError = false;\n\n try {\n runtimeStarted = true;\n await runtime.start();\n\n if (!runtime.canRunCases) {\n const reason = options.signal?.aborted\n ? (options.stopReason?.() ?? 'interrupted')\n : 'document-start-failed';\n cases.push(\n ...document.cases.map((collectedCase) =>\n asNotRun(collectedCase, projectName, reason),\n ),\n );\n } else {\n for (const collectedCase of document.cases) {\n if (fatalError || options.shouldStop?.()) {\n const outcome = asNotRun(\n collectedCase,\n projectName,\n fatalError\n ? 'fatal-error'\n : (options.stopReason?.() ?? 'interrupted'),\n );\n cases.push(outcome);\n await options.onCaseOutcome?.(outcome);\n continue;\n }\n\n await options.onCaseStart?.(collectedCase);\n const attempts = [];\n for (let attemptIndex = 0; attemptIndex <= retry; attemptIndex += 1) {\n const run = await runCollectedCase(collectedCase, {\n resolveNode: options.resolveNode,\n beforeEach: document.lifecycle.beforeEach,\n afterEach: document.lifecycle.afterEach,\n context: runtime.context,\n projectName,\n attemptIndex,\n signal: options.signal,\n defaultTimeoutMs: options.defaultTimeoutMs,\n onStepStart: options.onStepStart,\n onStepResult: options.onStepResult,\n onResult: options.onCaseResult,\n createRunId: createCaseRunId\n ? () => createCaseRunId(collectedCase, attemptIndex)\n : undefined,\n });\n attempts.push(run);\n fatalError = options.isFatalError?.(run) ?? false;\n if (run.status === 'success' || fatalError) break;\n }\n const run = attempts.at(-1)!;\n const outcome: CaseRunOutcome = {\n caseId: collectedCase.caseId,\n projectName,\n name: collectedCase.definition.name,\n sourcePath: collectedCase.sourcePath,\n caseIndex: collectedCase.caseIndex,\n status: run.status,\n run,\n attempts,\n };\n cases.push(outcome);\n await options.onCaseOutcome?.(outcome);\n }\n }\n } catch (error) {\n executionError = error;\n } finally {\n if (runtimeStarted) {\n try {\n documentResult = await runtime.finish();\n } catch (error) {\n executionError ??= error;\n }\n }\n }\n\n if (executionError) throw executionError;\n if (!documentResult) {\n throw new Error(\n `Workflow document \"${document.sourcePath}\" did not produce a result.`,\n );\n }\n return { document: documentResult, cases };\n}\n","import {\n ProjectSetupError,\n ProjectTeardownError,\n WorkflowLifecycleError,\n} from '../errors';\nimport type {\n ProjectRuntime,\n ProjectRuntimeOptions,\n ProjectRuntimeResult,\n} from './types';\n\nexport const createProjectRuntime = <TProjectContext = unknown>(\n options: ProjectRuntimeOptions<TProjectContext>,\n): ProjectRuntime<TProjectContext> => {\n const startedAt = new Date();\n const controller = new AbortController();\n const parentSignal = options.signal;\n const abortFromParent = () => controller.abort(parentSignal?.reason);\n if (parentSignal?.aborted) abortFromParent();\n else parentSignal?.addEventListener('abort', abortFromParent, { once: true });\n\n const teardownStack: Array<{\n registrationIndex: number;\n teardown: Parameters<\n Parameters<NonNullable<typeof options.setup>['setup']>[0]['onTeardown']\n >[0];\n }> = [];\n let context: TProjectContext | undefined;\n let setupError: ProjectSetupError | undefined;\n let started = false;\n let acceptingTeardowns = options.setup !== undefined;\n let finishedResult: ProjectRuntimeResult<TProjectContext> | undefined;\n\n const createResult = (\n requestedStatus: 'success' | 'failed',\n teardownErrors: readonly ProjectTeardownError[] = [],\n ): ProjectRuntimeResult<TProjectContext> => {\n const endedAt = new Date();\n return {\n projectName: options.project.name,\n status:\n requestedStatus === 'failed' || setupError || teardownErrors.length > 0\n ? 'failed'\n : 'success',\n ...(setupError ? { setupError } : {}),\n ...(teardownErrors.length > 0 ? { teardownErrors } : {}),\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n };\n };\n\n const onTeardown = (\n teardown: (typeof teardownStack)[number]['teardown'],\n ): void => {\n if (!acceptingTeardowns) {\n throw new WorkflowLifecycleError(\n 'onTeardown() can only be called while Project setup is running.',\n { projectName: options.project.name },\n );\n }\n if (typeof teardown !== 'function') {\n throw new WorkflowLifecycleError(\n 'Project onTeardown() requires a teardown function.',\n { projectName: options.project.name },\n );\n }\n teardownStack.push({\n registrationIndex: teardownStack.length,\n teardown,\n });\n };\n\n return {\n get context() {\n return context;\n },\n get signal() {\n return controller.signal;\n },\n get canRun() {\n return started && !setupError && !controller.signal.aborted;\n },\n async start() {\n if (started) {\n throw new WorkflowLifecycleError(\n 'Project runtime has already started.',\n {\n projectName: options.project.name,\n },\n );\n }\n started = true;\n if (controller.signal.aborted) {\n acceptingTeardowns = false;\n return createResult('failed');\n }\n if (options.setup) {\n try {\n context = await options.setup.setup({\n project: options.project,\n env: Object.freeze({ ...process.env }),\n signal: controller.signal,\n onTeardown,\n });\n } catch (error) {\n setupError = new ProjectSetupError(error, {\n projectName: options.project.name,\n });\n } finally {\n acceptingTeardowns = false;\n }\n }\n return createResult(setupError ? 'failed' : 'success');\n },\n async finish(requestedStatus = 'success') {\n if (finishedResult) return finishedResult;\n if (!started) {\n throw new WorkflowLifecycleError(\n 'Project runtime must start before it can finish.',\n { projectName: options.project.name },\n );\n }\n const statusBeforeTeardown = createResult(requestedStatus).status;\n const teardownErrors: ProjectTeardownError[] = [];\n for (const { registrationIndex, teardown } of teardownStack.reverse()) {\n try {\n await teardown({\n project: options.project,\n context,\n status: statusBeforeTeardown,\n ...(setupError ? { setupError } : {}),\n });\n } catch (error) {\n teardownErrors.push(\n new ProjectTeardownError(error, {\n projectName: options.project.name,\n registrationIndex,\n }),\n );\n }\n }\n parentSignal?.removeEventListener('abort', abortFromParent);\n finishedResult = createResult(requestedStatus, teardownErrors);\n return finishedResult;\n },\n abort(reason) {\n controller.abort(reason);\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 { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { sep } from 'node:path';\nimport { JSON_SCHEMA, load as loadYaml } from 'js-yaml';\nimport type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\nimport type { NodeDefinition } from '../node/types';\nimport { normalizeSteps } from './normalize';\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\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 =>\n createHash('sha256')\n .update(JSON.stringify([projectId, sourcePath, caseIndex]))\n .digest('hex');\n\nexport const createWorkflowDocumentId = (\n projectId: string,\n sourcePath: string,\n): string =>\n createHash('sha256')\n .update(JSON.stringify([projectId, sourcePath]))\n .digest('hex');\n\nexport function collectWorkflowDocument(\n source: WorkflowDocumentSource,\n options: CollectWorkflowDocumentOptions,\n): CollectedWorkflowDocument {\n let parsed: unknown;\n try {\n parsed = loadYaml(readFileSync(source.absolutePath, 'utf8'), {\n schema: JSON_SCHEMA,\n });\n } catch (error) {\n throw new WorkflowParseError(\n `Failed to parse workflow document \"${source.sourcePath}\".`,\n { sourcePath: source.sourcePath },\n error,\n );\n }\n\n if (!isMapping(parsed)) {\n throw new WorkflowParseError('Workflow document must be a mapping.');\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 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 lifecycle,\n cases,\n } satisfies CollectedWorkflowDocument;\n}\n","import type { TestRunReportError, TestRunReportValue } from '@midscene/core';\n\nconst MAX_DEPTH = 6;\nconst MAX_STRING_LENGTH = 2_000;\nconst MAX_ARRAY_ITEMS = 50;\nconst MAX_OBJECT_KEYS = 50;\nconst MAX_SERIALIZED_BYTES = 64 * 1024;\nconst TRUNCATED_VALUE = '[Truncated: display value exceeded 64 KiB]';\n\nconst normalizedSecretKeys = [\n 'password',\n 'passwd',\n 'secret',\n 'token',\n 'authorization',\n 'cookie',\n 'apikey',\n];\n\nconst normalizedKey = (key: string): string =>\n key.toLowerCase().replace(/[^a-z0-9]/g, '');\n\nconst isSecretKey = (key: string): boolean => {\n const normalized = normalizedKey(key);\n return normalizedSecretKeys.some((secret) => normalized.includes(secret));\n};\n\nconst objectPath = (parent: string, key: string): string =>\n /^[A-Za-z_$][\\w$]*$/.test(key)\n ? `${parent}.${key}`\n : `${parent}[${JSON.stringify(key)}]`;\n\nconst stringByteLength = (value: string): number =>\n Buffer.byteLength(value, 'utf8');\n\nexport function sanitizeReportText(\n value: string,\n maximumLength = MAX_STRING_LENGTH,\n): string {\n return value.length <= maximumLength\n ? value\n : `${value.slice(0, maximumLength)}… [truncated]`;\n}\n\n/** Convert arbitrary Node input/output to a bounded, JSON-safe display value. */\nexport function sanitizeReportValue(value: unknown): TestRunReportValue {\n const truncatedPaths = new Set<string>();\n const redactedPaths = new Set<string>();\n const ancestors = new WeakSet<object>();\n let remainingBytes = MAX_SERIALIZED_BYTES;\n\n const consume = (path: string, text: string): boolean => {\n remainingBytes -= stringByteLength(text);\n if (remainingBytes >= 0) return true;\n truncatedPaths.add(path);\n return false;\n };\n\n const visit = (current: unknown, path: string, depth: number): unknown => {\n if (remainingBytes <= 0) {\n truncatedPaths.add(path);\n return '[Truncated: size limit]';\n }\n if (current === null || typeof current === 'boolean') {\n consume(path, String(current));\n return current;\n }\n if (typeof current === 'string') {\n if (current.length > MAX_STRING_LENGTH) {\n truncatedPaths.add(path);\n const shortened = `${current.slice(0, MAX_STRING_LENGTH)}… [truncated]`;\n consume(path, shortened);\n return shortened;\n }\n consume(path, current);\n return current;\n }\n if (typeof current === 'number') {\n if (Number.isFinite(current)) {\n consume(path, String(current));\n return current;\n }\n truncatedPaths.add(path);\n return `[Unsupported number: ${String(current)}]`;\n }\n if (typeof current === 'bigint') {\n truncatedPaths.add(path);\n return `[Unsupported bigint: ${String(current)}]`;\n }\n if (\n current === undefined ||\n typeof current === 'function' ||\n typeof current === 'symbol'\n ) {\n truncatedPaths.add(path);\n return `[Unsupported ${typeof current}]`;\n }\n if (depth >= MAX_DEPTH) {\n truncatedPaths.add(path);\n return '[Truncated: maximum depth]';\n }\n\n if (current instanceof Date) {\n const date = Number.isNaN(current.getTime())\n ? '[Invalid Date]'\n : current.toISOString();\n consume(path, date);\n return date;\n }\n if (ancestors.has(current)) {\n truncatedPaths.add(path);\n return '[Unsupported circular value]';\n }\n\n if (Array.isArray(current)) {\n ancestors.add(current);\n const output: unknown[] = [];\n const itemCount = Math.min(current.length, MAX_ARRAY_ITEMS);\n for (let index = 0; index < itemCount; index += 1) {\n if (remainingBytes <= 0) break;\n output.push(visit(current[index], `${path}[${index}]`, depth + 1));\n }\n if (current.length > output.length) truncatedPaths.add(path);\n ancestors.delete(current);\n return output;\n }\n\n const prototype = Object.getPrototypeOf(current);\n if (prototype !== Object.prototype && prototype !== null) {\n truncatedPaths.add(path);\n const constructorName =\n (current as { constructor?: { name?: string } }).constructor?.name ??\n 'object';\n return `[Unsupported object: ${constructorName}]`;\n }\n\n ancestors.add(current);\n const output: Record<string, unknown> = {};\n const keys = Object.keys(current as Record<string, unknown>);\n for (const key of keys.slice(0, MAX_OBJECT_KEYS)) {\n const childPath = objectPath(path, key);\n if (!consume(childPath, key)) break;\n if (isSecretKey(key)) {\n output[key] = '[REDACTED]';\n redactedPaths.add(childPath);\n } else {\n output[key] = visit(\n (current as Record<string, unknown>)[key],\n childPath,\n depth + 1,\n );\n }\n if (remainingBytes <= 0) break;\n }\n if (keys.length > Object.keys(output).length) truncatedPaths.add(path);\n ancestors.delete(current);\n return output;\n };\n\n const sanitized = visit(value, '$', 0);\n const serialized = JSON.stringify(sanitized);\n if (\n serialized === undefined ||\n stringByteLength(serialized) > MAX_SERIALIZED_BYTES\n ) {\n return { value: TRUNCATED_VALUE, truncatedPaths: ['$'] };\n }\n\n return {\n value: sanitized,\n ...(truncatedPaths.size > 0 ? { truncatedPaths: [...truncatedPaths] } : {}),\n ...(redactedPaths.size > 0 ? { redactedPaths: [...redactedPaths] } : {}),\n };\n}\n\nexport function sanitizeReportError(error: unknown): TestRunReportError {\n if (error instanceof Error) {\n const workflowLike = error as Error & {\n code?: unknown;\n details?: unknown;\n };\n return {\n name: sanitizeReportText(error.name || 'Error', 200),\n message: sanitizeReportText(error.message || String(error)),\n ...(typeof workflowLike.code === 'string'\n ? { code: sanitizeReportText(workflowLike.code, 200) }\n : {}),\n ...(workflowLike.details === undefined\n ? {}\n : { details: sanitizeReportValue(workflowLike.details) }),\n };\n }\n\n return {\n name: 'Error',\n message: sanitizeReportText(String(error)),\n };\n}\n","import type {\n IndexedTestRunReportSource,\n TestRunReportAgentDetail,\n TestRunReportAttempt,\n TestRunReportCase,\n TestRunReportDiagnostic,\n TestRunReportDocument,\n TestRunReportDump,\n TestRunReportProject,\n TestRunReportSource,\n TestRunReportSourceIndex,\n TestRunReportStep,\n} from '@midscene/core';\nimport { getDebug } from '@midscene/shared/logger';\nimport type {\n TestProjectCaseRunResult,\n TestProjectRunResult,\n} from '../cli/types';\nimport type {\n CaseRunResult,\n StepRunResult,\n WorkflowDocumentRunResult,\n} from '../engine/types';\nimport {\n sanitizeReportError,\n sanitizeReportText,\n sanitizeReportValue,\n} from './sanitize';\n\nconst warnReport = getDebug('test-runner:report-assembler', {\n console: true,\n});\n\nconst exactMidsceneDetailNodes = new Set([\n 'aiAct',\n 'aiAssert',\n 'recordToReport',\n]);\n\ninterface ManifestBuildContext {\n diagnostics: TestRunReportDiagnostic[];\n sourcesByScope: Map<string, IndexedTestRunReportSource[]>;\n detailsByScopeAndExecution: Map<string, TestRunReportAgentDetail>;\n tracedScopeByExecution: Map<string, string>;\n warnedDiagnostics: Set<string>;\n}\n\nconst scopedExecutionKey = (scopeId: string, executionId: string): string =>\n `${scopeId}\\u0000${executionId}`;\n\nconst reportSourcesForScope = (\n context: ManifestBuildContext,\n scopeId: string,\n): IndexedTestRunReportSource[] => context.sourcesByScope.get(scopeId) ?? [];\n\nconst addDiagnostic = (\n context: ManifestBuildContext,\n diagnostic: TestRunReportDiagnostic,\n): void => {\n context.diagnostics.push(diagnostic);\n const key = JSON.stringify([\n diagnostic.code,\n diagnostic.scopeId,\n diagnostic.executionId,\n ]);\n if (!context.warnedDiagnostics.has(key)) {\n context.warnedDiagnostics.add(key);\n warnReport(diagnostic.message);\n }\n};\n\nconst buildStep = (\n step: StepRunResult,\n scopeId: string,\n context: ManifestBuildContext,\n): TestRunReportStep => {\n const details: TestRunReportAgentDetail[] = [];\n const unresolvedExecutionIds: string[] = [];\n for (const trace of step.report?.traces ?? []) {\n const previousScope = context.tracedScopeByExecution.get(trace.executionId);\n if (previousScope && previousScope !== scopeId) {\n throw new Error(\n `Agent execution ${trace.executionId} was traced by multiple test scopes (${previousScope}, ${scopeId}).`,\n );\n }\n context.tracedScopeByExecution.set(trace.executionId, scopeId);\n const detail = context.detailsByScopeAndExecution.get(\n scopedExecutionKey(scopeId, trace.executionId),\n );\n if (detail) details.push(detail);\n else unresolvedExecutionIds.push(trace.executionId);\n }\n\n let agentDetailDiagnostic: string | undefined;\n if (unresolvedExecutionIds.length > 0) {\n agentDetailDiagnostic = `Agent detail could not be resolved for ${unresolvedExecutionIds.join(', ')}.`;\n const sources = reportSourcesForScope(context, scopeId);\n for (const executionId of unresolvedExecutionIds) {\n addDiagnostic(context, {\n level: 'warning',\n code: 'agent-detail-unresolved',\n message: `Agent detail could not be resolved for execution ${executionId} in test scope ${scopeId}.`,\n scopeId,\n executionId,\n ...(sources.length > 0\n ? { sourcePaths: sources.map((source) => source.sourcePath) }\n : {}),\n });\n }\n } else if (details.length === 0 && exactMidsceneDetailNodes.has(step.node)) {\n agentDetailDiagnostic =\n 'This Agent did not expose a stable execution reference for the Step.';\n addDiagnostic(context, {\n level: 'warning',\n code: 'agent-detail-unavailable',\n message: `No stable Agent execution reference was captured for ${step.node} in test scope ${scopeId}.`,\n scopeId,\n ...(reportSourcesForScope(context, scopeId).length > 0\n ? {\n sourcePaths: reportSourcesForScope(context, scopeId).map(\n (source) => source.sourcePath,\n ),\n }\n : {}),\n });\n }\n\n const prompt =\n typeof (step.input as { prompt?: unknown } | undefined)?.prompt === 'string'\n ? (step.input as { prompt: string }).prompt\n : undefined;\n return {\n id: `${scopeId}:${step.phase}:${step.stepIndex}`,\n phase: step.phase,\n stepIndex: step.stepIndex,\n node: step.node,\n ...(prompt ? { title: sanitizeReportText(prompt, 240) } : {}),\n status: step.status,\n continuedAfterError: step.continuedAfterError,\n startedAt: step.startedAt,\n endedAt: step.endedAt,\n durationMs: step.durationMs,\n input: sanitizeReportValue(step.input),\n ...(step.output\n ? {\n output: {\n ...(step.output.summary === undefined\n ? {}\n : { summary: sanitizeReportText(step.output.summary) }),\n ...(step.output.data === undefined\n ? {}\n : { data: sanitizeReportValue(step.output.data) }),\n },\n }\n : {}),\n ...(step.error ? { error: sanitizeReportError(step.error) } : {}),\n ...(details.length > 0 ? { agentDetails: details } : {}),\n ...(agentDetailDiagnostic ? { agentDetailDiagnostic } : {}),\n };\n};\n\nconst buildAttempt = (\n attempt: CaseRunResult,\n context: ManifestBuildContext,\n): TestRunReportAttempt => ({\n attemptId: attempt.runId,\n attemptIndex: attempt.attemptIndex,\n status: attempt.status,\n startedAt: attempt.startedAt,\n endedAt: attempt.endedAt,\n durationMs: attempt.durationMs,\n beforeEach: attempt.beforeEach.map((step) =>\n buildStep(step, attempt.runId, context),\n ),\n steps: attempt.steps.map((step) => buildStep(step, attempt.runId, context)),\n afterEach: attempt.afterEach.map((step) =>\n buildStep(step, attempt.runId, context),\n ),\n ...(attempt.teardownErrors?.length\n ? { teardownErrors: attempt.teardownErrors.map(sanitizeReportError) }\n : {}),\n ...(reportSourcesForScope(context, attempt.runId).length > 0\n ? {\n scopeReportIds: reportSourcesForScope(context, attempt.runId).map(\n (source) => source.reportId,\n ),\n }\n : {}),\n});\n\nconst buildCase = (\n outcome: TestProjectCaseRunResult,\n context: ManifestBuildContext,\n): TestRunReportCase => ({\n caseId: outcome.caseId,\n name: outcome.name,\n caseIndex: outcome.caseIndex,\n status: outcome.status,\n ...(outcome.notRunReason ? { notRunReason: outcome.notRunReason } : {}),\n attempts: (outcome.attempts ?? (outcome.run ? [outcome.run] : [])).map(\n (attempt) => buildAttempt(attempt, context),\n ),\n});\n\nconst buildDocument = (\n documentId: string,\n document: WorkflowDocumentRunResult | undefined,\n cases: readonly TestProjectCaseRunResult[],\n context: ManifestBuildContext,\n): TestRunReportDocument => {\n const sourcePath =\n document?.sourcePath ?? cases[0]?.sourcePath ?? '<unknown>';\n const status =\n document?.status ??\n (cases.some((item) => item.status !== 'success') ? 'failed' : 'success');\n return {\n documentId,\n sourcePath,\n status,\n ...(document\n ? {\n startedAt: document.startedAt,\n endedAt: document.endedAt,\n durationMs: document.durationMs,\n }\n : {}),\n beforeAll: (document?.beforeAll ?? []).map((step) =>\n buildStep(step, document!.documentRunId, context),\n ),\n cases: cases.map((outcome) => buildCase(outcome, context)),\n afterAll: (document?.afterAll ?? []).map((step) =>\n buildStep(step, document!.documentRunId, context),\n ),\n ...(document?.teardownErrors?.length\n ? { teardownErrors: document.teardownErrors.map(sanitizeReportError) }\n : {}),\n ...(document &&\n reportSourcesForScope(context, document.documentRunId).length > 0\n ? {\n scopeReportIds: reportSourcesForScope(\n context,\n document.documentRunId,\n ).map((source) => source.reportId),\n }\n : {}),\n };\n};\n\nconst buildProject = (\n project: TestProjectRunResult['projects'][number],\n context: ManifestBuildContext,\n): TestRunReportProject => {\n const documentById = new Map(\n project.documents.map((document) => [document.documentId, document]),\n );\n const casesByDocumentId = new Map<string, TestProjectCaseRunResult[]>();\n for (const outcome of project.cases) {\n const current = casesByDocumentId.get(outcome.documentId) ?? [];\n current.push(outcome);\n casesByDocumentId.set(outcome.documentId, current);\n }\n const documentIds = new Set([\n ...project.documents.map((document) => document.documentId),\n ...project.cases.map((outcome) => outcome.documentId),\n ]);\n\n return {\n projectId: project.projectId,\n name: project.name,\n status: project.status,\n retry: project.retry,\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.setupError\n ? {\n setupError: sanitizeReportError(project.lifecycle.setupError),\n }\n : {}),\n ...(project.lifecycle.teardownErrors?.length\n ? {\n teardownErrors:\n project.lifecycle.teardownErrors.map(sanitizeReportError),\n }\n : {}),\n },\n }\n : {}),\n documents: [...documentIds].map((documentId) =>\n buildDocument(\n documentId,\n documentById.get(documentId),\n casesByDocumentId.get(documentId) ?? [],\n context,\n ),\n ),\n collectionErrors: project.collectionErrors.map((collectionError) => ({\n sourcePath: collectionError.sourcePath,\n error: sanitizeReportError(collectionError.error),\n })),\n };\n};\n\nexport function collectTestRunReportSources(\n result: TestProjectRunResult,\n): TestRunReportSource[] {\n const sources: TestRunReportSource[] = [];\n for (const project of result.projects) {\n for (const document of project.documents) {\n for (const sourcePath of document.reportPaths ?? []) {\n sources.push({\n scopeId: document.documentRunId,\n sourcePath,\n });\n }\n }\n for (const outcome of project.cases) {\n for (const attempt of outcome.attempts ??\n (outcome.run ? [outcome.run] : [])) {\n for (const sourcePath of attempt.reportPaths ?? []) {\n sources.push({ scopeId: attempt.runId, sourcePath });\n }\n }\n }\n }\n return sources;\n}\n\nexport function buildTestRunReportDump(\n result: TestProjectRunResult,\n index: TestRunReportSourceIndex,\n): TestRunReportDump {\n const sourcesByScope = new Map<string, IndexedTestRunReportSource[]>();\n const detailsByScopeAndExecution = new Map<\n string,\n TestRunReportAgentDetail\n >();\n for (const source of index.sources) {\n const scopeSources = sourcesByScope.get(source.scopeId) ?? [];\n scopeSources.push(source);\n sourcesByScope.set(source.scopeId, scopeSources);\n for (const executionId of source.executionIds) {\n detailsByScopeAndExecution.set(\n scopedExecutionKey(source.scopeId, executionId),\n { reportId: source.reportId, executionId },\n );\n }\n }\n const context: ManifestBuildContext = {\n diagnostics: [],\n sourcesByScope,\n detailsByScopeAndExecution,\n tracedScopeByExecution: new Map(),\n warnedDiagnostics: new Set(),\n };\n for (const source of index.sources) {\n if (source.executionIds.length === 0) {\n addDiagnostic(context, {\n level: 'warning',\n code: 'source-without-executions',\n message: `Agent report contains no executions: ${source.sourcePath}`,\n scopeId: source.scopeId,\n sourcePaths: [source.sourcePath],\n });\n }\n }\n\n const projects = result.projects.map((project) =>\n buildProject(project, context),\n );\n return {\n schemaVersion: 1,\n kind: 'test-runner',\n runId: result.runId,\n status: result.status,\n startedAt: result.startedAt,\n endedAt: result.endedAt,\n durationMs: result.durationMs,\n summary: { ...result.summary },\n metrics: index.metrics,\n projects,\n ...(context.diagnostics.length > 0\n ? { diagnostics: context.diagnostics }\n : {}),\n };\n}\n"],"names":["WorkflowError","Error","undefined","message","options","WorkflowParseError","details","cause","NodeDefinitionError","DuplicateNodeError","node","NodeNotFoundError","NodeInputValidationError","error","issues","issue","String","firstIssue","path","StepTimeoutError","timeoutMs","NodeExecutionError","causeMessage","WorkflowLifecycleError","ProjectSetupError","ProjectTeardownError","NodeScopeTeardownError","FatalDeviceError","isFatalDeviceError","CaseExecutionError","result","WorkflowDocumentExecutionError","normalizeNodeExecutionError","supportedMetaKeys","Set","isMapping","value","Array","Object","formatStep","index","normalizeMeta","key","timeout","Number","continueOnError","normalizeStep","resolveNode","entries","rawValue","resolvedNode","stringInputKey","rawMeta","input","normalizeSteps","steps","step","validateOptionalText","field","validateInputSchema","schema","z","validateDefinition","defineNode","_nodes","NodeRegistry","name","nodes","Map","assertJsonSerializable","label","visit","candidate","seen","TypeError","child","validateNodeOutput","output","createStepResultBase","startedAt","phase","stepIndex","endedAt","Date","Math","executeNode","execute","abortController","AbortController","parentSignal","abortFromParent","abortGraceTimeout","execution","Promise","settleOnAbort","abortedExecution","_","reject","setTimeout","timeoutExecution","timeoutError","settledExecution","clearTimeout","createNodeReportCollector","traces","accepting","trace","normalized","parseNodeInput","parsed","executeStep","target","context","reportCollector","signal","common","teardown","reportPathsFromTeardown","paths","isAbsolute","runCollectedCase","collectedCase","phases","runId","randomUUID","beforeEach","afterEach","teardownStack","acceptingTeardowns","onTeardown","runPhase","results","caseContext","stepInfo","executionError","cleanupSignal","teardownErrors","reportPaths","registrationIndex","CaseRunner","fatalStepError","createCaseRunner","createDocumentRuntime","document","documentRunId","beforeAll","afterAll","project","nodeTeardownStack","acceptingNodeTeardowns","started","finishedResult","createResult","executionSignal","documentContext","finishError","asNotRun","projectName","reason","runWorkflowDocument","createDocumentRunId","createCaseRunId","retry","runtime","cases","runtimeStarted","documentResult","fatalError","outcome","attempts","attemptIndex","run","createProjectRuntime","controller","setupError","requestedStatus","process","statusBeforeTeardown","interpolationExpression","exactEnvExpression","exactProjectExpression","missingVariable","kind","projectVariable","environmentVariable","interpolationValue","resolveString","exactEnv","exactProject","_match","environmentName","resolveWorkflowVariables","rejectUnknownKeys","allowed","allowedSet","unknown","createCaseId","projectId","sourcePath","caseIndex","createHash","JSON","createWorkflowDocumentId","collectWorkflowDocument","source","loadYaml","readFileSync","JSON_SCHEMA","sep","resolveStepVariables","normalizeLifecycle","resolved","lifecycle","ids","definition","tags","tag","caseId","MAX_DEPTH","MAX_STRING_LENGTH","MAX_ARRAY_ITEMS","MAX_OBJECT_KEYS","MAX_SERIALIZED_BYTES","TRUNCATED_VALUE","normalizedSecretKeys","normalizedKey","isSecretKey","secret","objectPath","parent","stringByteLength","Buffer","sanitizeReportText","maximumLength","sanitizeReportValue","truncatedPaths","redactedPaths","ancestors","WeakSet","remainingBytes","consume","text","current","depth","shortened","date","itemCount","prototype","constructorName","keys","childPath","sanitized","serialized","sanitizeReportError","workflowLike","warnReport","getDebug","exactMidsceneDetailNodes","scopedExecutionKey","scopeId","executionId","reportSourcesForScope","addDiagnostic","diagnostic","buildStep","unresolvedExecutionIds","previousScope","detail","agentDetailDiagnostic","sources","prompt","buildAttempt","attempt","buildCase","buildDocument","documentId","status","item","buildProject","documentById","casesByDocumentId","documentIds","collectionError","collectTestRunReportSources","buildTestRunReportDump","sourcesByScope","detailsByScopeAndExecution","scopeSources","projects"],"mappings":";;;;;;;;;;;;;;;;AAQO,MAAMA,s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AAU;QAC7B,SAAS;YAAE,GAAGA,OAAO,OAAO;QAAC;QAC7B,SAASU,MAAM,OAAO;QACtBwP;QACA,GAAIhL,QAAQ,WAAW,CAAC,MAAM,GAAG,IAC7B;YAAE,aAAaA,QAAQ,WAAW;QAAC,IACnC,CAAC,CAAC;IACR;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../src/engine/case-runner.ts","../../src/engine/document-runtime.ts","../../src/engine/registry.ts","../../src/engine/run-workflow-document.ts","../../src/node/define-node.ts","../../src/parser/identifiers.ts","../../src/parser/normalize.ts","../../src/parser/variables.ts","../../src/parser/collect.ts"],"sourcesContent":["import {\n CaseRunner as CoreCaseRunner,\n createCaseRunner as coreCreateCaseRunner,\n} from '@midscene/core/internal/test-runner';\nimport type { NodeDefinition } from '../node/types';\nimport type { CaseInput } from '../parser/types';\nimport type { NodeRegistry } from './registry';\nimport type { CaseRunResult, CaseRunnerOptions } from './types';\n\nexport type CaseRunner<TContext = undefined> = Omit<\n CoreCaseRunner<TContext>,\n 'run' | 'register' | 'registry'\n> & {\n readonly registry: NodeRegistry;\n register<TInput, TData>(\n node: NodeDefinition<TInput, TData, TContext>,\n ): CaseRunner<TContext>;\n run(input: CaseInput): Promise<CaseRunResult>;\n};\nexport const CaseRunner: {\n new <TContext = undefined>(\n options?: CaseRunnerOptions<TContext>,\n ): CaseRunner<TContext>;\n} = CoreCaseRunner;\nexport const createCaseRunner: <TContext = undefined>(\n options?: CaseRunnerOptions<TContext>,\n) => CaseRunner<TContext> = coreCreateCaseRunner;\n","import { createDocumentRuntime as coreCreateDocumentRuntime } from '@midscene/core/internal/test-runner';\nimport type { CollectedWorkflowDocument } from '../parser/types';\nimport type {\n CreateDocumentRuntimeOptions,\n WorkflowDocumentRuntime,\n} from './types';\n\nexport const createDocumentRuntime: <TContext = undefined>(\n document: CollectedWorkflowDocument,\n options: CreateDocumentRuntimeOptions<TContext>,\n) => WorkflowDocumentRuntime<TContext> = coreCreateDocumentRuntime;\n","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 { runWorkflowDocument as coreRunWorkflowDocument } from '@midscene/core/internal/test-runner';\nimport type { CollectedWorkflowDocument } from '../parser/types';\nimport type {\n RunWorkflowDocumentOptions,\n WorkflowDocumentExecutionResult,\n} from './types';\n\nexport const runWorkflowDocument: <TContext = undefined>(\n document: CollectedWorkflowDocument,\n options: RunWorkflowDocumentOptions<TContext>,\n) => Promise<WorkflowDocumentExecutionResult> = coreRunWorkflowDocument;\n","import { defineNode as coreDefineNode } from '@midscene/core/internal/test-runner';\nimport type {\n DefineNodeOptions,\n DefineNodeWithSchemaOptions,\n NodeDefinition,\n NodeDefinitionWithSchema,\n NodeInputSchema,\n} from './types';\n\n// A type-only facade: validation and execution still belong to the shared kernel.\ninterface DefineNativeNode {\n <TSchema extends NodeInputSchema, TData = unknown, TContext = unknown>(\n options: DefineNodeWithSchemaOptions<TSchema, TData, TContext>,\n ): NodeDefinitionWithSchema<TSchema, TData, TContext>;\n <TInput = unknown, TData = unknown, TContext = unknown>(\n options: DefineNodeOptions<TInput, TData, TContext>,\n ): NodeDefinition<TInput, TData, TContext>;\n}\nexport const defineNode: DefineNativeNode = coreDefineNode;\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 { 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 { JSON_SCHEMA, load as loadYaml } from 'js-yaml';\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 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 parsed: unknown;\n try {\n parsed = loadYaml(readFileSync(source.absolutePath, 'utf8'), {\n schema: JSON_SCHEMA,\n });\n } catch (error) {\n throw new WorkflowParseError(\n `Failed to parse workflow document \"${source.sourcePath}\".`,\n { sourcePath: source.sourcePath },\n error,\n );\n }\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 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 lifecycle,\n cases,\n } satisfies CollectedWorkflowDocument;\n}\n"],"names":["CaseRunner","CoreCaseRunner","createCaseRunner","coreCreateCaseRunner","createDocumentRuntime","coreCreateDocumentRuntime","NodeRegistry","CoreNodeRegistry","runWorkflowDocument","coreRunWorkflowDocument","defineNode","coreDefineNode","createCaseInvocationId","projectId","sourcePath","caseIndex","invocationIndex","createHash","JSON","createDocumentInvocationId","normalizeStep","coreNormalizeStep","normalizeSteps","coreNormalizeSteps","interpolationExpression","exactEnvExpression","exactProjectExpression","missingVariable","kind","name","options","WorkflowParseError","projectVariable","Object","environmentVariable","value","undefined","interpolationValue","String","resolveString","exactEnv","exactProject","_match","environmentName","projectName","resolveWorkflowVariables","Array","child","key","isMapping","NativeWorkflowFormatError","actualFormat","rejectUnknownKeys","allowed","label","allowedSet","Set","unknown","createCaseId","createWorkflowDocumentId","collectWorkflowDocument","source","parsed","loadYaml","readFileSync","JSON_SCHEMA","error","format","classifyWorkflowDocumentFormat","sep","resolveStepVariables","step","phase","stepIndex","process","normalizeLifecycle","normalized","resolved","lifecycle","ids","cases","definition","tags","tag","steps","caseId"],"mappings":";;;;;;AAmBO,MAAMA,yBAITC;AACG,MAAMC,+BAEeC;ACnBrB,MAAMC,yCAG4BC;ACElC,MAAMC,wBAETC;ACPG,MAAMC,4CAGmCC;ACQzC,MAAMC,yBAA+BC;ACfrC,MAAMC,yBAAyB,CACpCC,WACAC,YACAC,WACAC,kBAAkB,CAAC,GAEnBC,WAAW,UACR,MAAM,CACLC,KAAK,SAAS,CAAC;QACbL;QACAC;QACAC;WACIC,kBAAkB;YAACA;SAAgB,GAAG,EAAE;KAC7C,GAEF,MAAM,CAAC;AAEL,MAAMG,6BAA6B,CACxCN,WACAC,YACAE,kBAAkB,CAAC,GAEnBC,WAAW,UACR,MAAM,CACLC,KAAK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