@mastra/core
Version:
254 lines (253 loc) • 10.9 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_run_registry = require("../run-registry-BrKoxzT0.cjs");
const require_manager = require("../manager-BnTcBPUx.cjs");
let zod_v4 = require("zod/v4");
let crypto = require("crypto");
// src/datasets/snapshot.ts
const DATASET_SNAPSHOT_DEFAULT_MAX_BYTES = 4194304;
const DATASET_SNAPSHOT_MAX_DEPTH = 100;
const snapshotOptionsSchema = zod_v4.z.object({ maxBytes: zod_v4.z.number().int().positive().default(DATASET_SNAPSHOT_DEFAULT_MAX_BYTES) });
function snapshotSizeSchema(options) {
const { maxBytes } = snapshotOptionsSchema.parse(options);
return zod_v4.z.string().refine((text) => Buffer.byteLength(text, "utf8") <= maxBytes, { message: `Dataset snapshot exceeds the ${maxBytes} byte limit` });
}
function hasLoneSurrogate(value) {
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code >= 55296 && code <= 56319) {
const next = value.charCodeAt(++i);
if (!(next >= 56320 && next <= 57343)) return true;
} else if (code >= 56320 && code <= 57343) return true;
}
return false;
}
function isJsonValue(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
if (depth > 100) return false;
if (value === null || typeof value === "boolean") return true;
if (typeof value === "string") return !hasLoneSurrogate(value);
if (typeof value === "number") return Number.isFinite(value);
if (typeof value !== "object" || ancestors.has(value)) return false;
const array = Array.isArray(value);
const prototype = Object.getPrototypeOf(value);
if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) return false;
ancestors.add(value);
try {
const keys = Reflect.ownKeys(value);
if (array && keys.length !== value.length + 1) return false;
return keys.every((key) => {
if (array && key === "length") return true;
if (typeof key !== "string" || hasLoneSurrogate(key)) return false;
if (array && (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= value.length)) return false;
const descriptor = Object.getOwnPropertyDescriptor(value, key);
return descriptor.enumerable && "value" in descriptor && isJsonValue(descriptor.value, ancestors, depth + 1);
});
} finally {
ancestors.delete(value);
}
}
const jsonValueSchema = zod_v4.z.custom((value) => isJsonValue(value), { message: `Expected lossless JSON with valid Unicode and at most 100 levels of nesting` });
const jsonObjectSchema = zod_v4.z.custom((value) => value !== null && typeof value === "object" && !Array.isArray(value) && isJsonValue(value), { message: "Expected a lossless JSON object" });
const identitySchema = zod_v4.z.uuid().refine((value) => value === value.toLowerCase(), "Portable identities must be lowercase");
const referenceSchema = zod_v4.z.string().min(1);
const configurationSchema = zod_v4.z.strictObject({
name: zod_v4.z.string(),
description: zod_v4.z.string().nullable().optional(),
metadata: jsonObjectSchema.optional(),
inputSchema: jsonObjectSchema.nullable().optional(),
groundTruthSchema: jsonObjectSchema.nullable().optional(),
requestContextSchema: jsonObjectSchema.nullable().optional(),
tags: zod_v4.z.array(zod_v4.z.string()).nullable().optional(),
targetType: zod_v4.z.enum([
"agent",
"workflow",
"scorer",
"processor"
]).nullable().optional(),
targetIds: zod_v4.z.array(referenceSchema).nullable().optional(),
scorerIds: zod_v4.z.array(referenceSchema).nullable().optional()
});
const payloadSchema = zod_v4.z.strictObject({
externalId: referenceSchema.nullable().optional(),
input: jsonValueSchema,
groundTruth: jsonValueSchema.optional(),
expectedTrajectory: jsonValueSchema.optional(),
toolMocks: zod_v4.z.array(zod_v4.z.strictObject({
toolName: zod_v4.z.string(),
args: jsonObjectSchema,
output: jsonValueSchema,
matchArgs: zod_v4.z.enum(["strict", "ignore"]).optional()
})).nullable().optional(),
unmockedToolPolicy: zod_v4.z.enum(["allow", "deny"]).nullable().optional(),
scorerIds: zod_v4.z.array(referenceSchema).nullable().optional(),
requestContext: jsonObjectSchema.nullable().optional(),
metadata: jsonObjectSchema.nullable().optional(),
source: zod_v4.z.strictObject({
type: zod_v4.z.enum([
"csv",
"json",
"trace",
"llm",
"experiment-result",
"candidate-screener"
]),
referenceId: zod_v4.z.string().optional()
}).nullable().optional()
});
const contentSchema = zod_v4.z.strictObject({
formatVersion: zod_v4.z.literal(1),
datasetIdentity: identitySchema,
configuration: configurationSchema,
items: zod_v4.z.array(zod_v4.z.strictObject({
itemIdentity: identitySchema,
createdAt: zod_v4.z.iso.datetime({ precision: 3 }),
updatedAt: zod_v4.z.iso.datetime({ precision: 3 }),
payload: payloadSchema
})),
provenance: zod_v4.z.strictObject({
exportedAt: zod_v4.z.iso.datetime({ offset: true }),
sourceDatasetId: referenceSchema,
itemVersion: zod_v4.z.number().int().nonnegative(),
configurationBasis: zod_v4.z.literal("export-time")
})
});
function validateIdentities(snapshot, ctx) {
const identities = /* @__PURE__ */ new Set();
const externalIds = /* @__PURE__ */ new Set();
snapshot.items.forEach((item, index) => {
if (identities.has(item.itemIdentity)) ctx.addIssue({
code: "custom",
path: [
"items",
index,
"itemIdentity"
],
message: "Duplicate portable item identity"
});
identities.add(item.itemIdentity);
const externalId = item.payload.externalId;
if (externalId != null) {
if (externalIds.has(externalId)) ctx.addIssue({
code: "custom",
path: [
"items",
index,
"payload",
"externalId"
],
message: "Duplicate externalId"
});
externalIds.add(externalId);
}
});
}
function canonicalize(value) {
if (value === null || typeof value !== "object") return JSON.stringify(value);
if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`;
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalize(value[key])}`).join(",")}}`;
}
function computeDigest(content) {
const items = [...content.items].sort((a, b) => a.itemIdentity < b.itemIdentity ? -1 : a.itemIdentity > b.itemIdentity ? 1 : 0);
const value = JSON.parse(JSON.stringify({
...content,
items
}));
return (0, crypto.createHash)("sha256").update(canonicalize(value)).digest("hex");
}
/** Validates unsigned artifact content, including portable identity uniqueness. */
const datasetSnapshotContentSchema = jsonValueSchema.pipe(contentSchema.superRefine(validateIdentities));
/** Validates the complete v1 artifact and SHA-256 digest, independently of deployment size limits. */
const datasetSnapshotSchema = jsonValueSchema.pipe(contentSchema.extend({ digest: zod_v4.z.string().regex(/^[0-9a-f]{64}$/) }).superRefine((snapshot, ctx) => {
validateIdentities(snapshot, ctx);
const { digest, ...content } = snapshot;
if (digest !== computeDigest(content)) ctx.addIssue({
code: "custom",
path: ["digest"],
message: "Dataset snapshot digest mismatch"
});
}));
/**
* Seals authored content and limits its compact JSON byte size. Does not read or write storage.
* The size check follows validation, cloning, and hashing; it does not bound CPU time or peak memory.
*/
function createDatasetSnapshot(content, options = {}) {
const sizeSchema = snapshotSizeSchema(options);
const captured = structuredClone(datasetSnapshotContentSchema.parse(content));
const snapshot = {
...captured,
digest: computeDigest(captured)
};
sizeSchema.parse(JSON.stringify(snapshot));
return snapshot;
}
const snapshotTextSchema = zod_v4.z.string().transform((text, ctx) => {
let parsed;
try {
parsed = JSON.parse(text);
} catch {
ctx.addIssue({
code: "custom",
message: "Invalid dataset snapshot JSON"
});
return zod_v4.z.NEVER;
}
const stack = [];
for (const [token] of text.matchAll(/"(?:\\[\s\S]|[^"\\])*"|[{}[\],]/g)) {
const object = stack.at(-1);
if (token === "{") stack.push({
keys: /* @__PURE__ */ new Set(),
expectingKey: true
});
else if (token === "[") stack.push(null);
else if (token === "}" || token === "]") stack.pop();
else if (token === "," && object) object.expectingKey = true;
else if (token.startsWith("\"") && object?.expectingKey) {
const key = JSON.parse(token);
if (object.keys.has(key)) {
ctx.addIssue({
code: "custom",
message: "Duplicate JSON property in dataset snapshot"
});
return zod_v4.z.NEVER;
}
object.keys.add(key);
object.expectingKey = false;
}
}
return parsed;
}).pipe(datasetSnapshotSchema);
/** Limits raw UTF-8 bytes before parsing untrusted JSON. Destination checks belong to import preflight. */
function parseDatasetSnapshot(text, options = {}) {
return snapshotSizeSchema(options).pipe(snapshotTextSchema).parse(text);
}
exports.DATASET_SNAPSHOT_DEFAULT_MAX_BYTES = DATASET_SNAPSHOT_DEFAULT_MAX_BYTES;
exports.DATASET_SNAPSHOT_MAX_DEPTH = DATASET_SNAPSHOT_MAX_DEPTH;
exports.Dataset = require_manager.Dataset;
exports.DatasetsManager = require_manager.DatasetsManager;
exports.EXPERIMENT_ITEM_BEFORE_EACH_FAILED = require_manager.EXPERIMENT_ITEM_BEFORE_EACH_FAILED;
exports.EXPERIMENT_ITEM_SCORER_NOT_FOUND = require_manager.EXPERIMENT_ITEM_SCORER_NOT_FOUND;
exports.SchemaUpdateValidationError = require_run_registry.SchemaUpdateValidationError;
exports.SchemaValidationError = require_run_registry.SchemaValidationError;
exports.SchemaValidator = require_run_registry.SchemaValidator;
exports.TOOL_MOCK_EXHAUSTED = require_manager.TOOL_MOCK_EXHAUSTED;
exports.TOOL_MOCK_MISMATCH = require_manager.TOOL_MOCK_MISMATCH;
exports.TOOL_MOCK_NOT_DECLARED = require_manager.TOOL_MOCK_NOT_DECLARED;
exports.ToolMockMatcher = require_manager.ToolMockMatcher;
exports.UnsupportedSchemaPatternError = require_run_registry.UnsupportedSchemaPatternError;
exports.assertSupportedPatterns = require_run_registry.assertSupportedPatterns;
exports.compareExperiments = require_manager.compareExperiments;
exports.computeMean = require_manager.computeMean;
exports.computeScorerStats = require_manager.computeScorerStats;
exports.createDatasetSnapshot = createDatasetSnapshot;
exports.createValidator = require_run_registry.createValidator;
exports.datasetSnapshotContentSchema = datasetSnapshotContentSchema;
exports.datasetSnapshotSchema = datasetSnapshotSchema;
exports.executeExperimentItem = require_manager.executeExperimentItem;
exports.executeTarget = require_manager.executeTarget;
exports.getSchemaValidator = require_run_registry.getSchemaValidator;
exports.isRegression = require_manager.isRegression;
exports.parseDatasetSnapshot = parseDatasetSnapshot;
exports.resolveScorers = require_manager.resolveScorers;
exports.resolveTarget = require_manager.resolveTarget;
exports.runExperiment = require_manager.runExperiment;
exports.runScorersForItem = require_manager.runScorersForItem;
//# sourceMappingURL=index.cjs.map