mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 14:59:05 +00:00
* feat(managed): decode .NET resource set headers and values Parse the ResourceManager and RuntimeResourceSet headers of a .resources stream, its name table and each entry's type code and payload range, as System.Resources.ResourceReader lays them out. Fixed-size primitives get a decoded value; strings, byte arrays and streams are payload ranges; serialized user types are named from the type table and never decoded. The test fixture writes resource sets the way ResourceWriter does, and its output is byte-identical to .NET Framework 4.8 ResourceWriter for the same values. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * feat(artifacts): bound .NET resource set admission Add the dotnet_resources reader limit group: the resource count follows the session member count, and the type count and header bytes bound what a reader holds before it reaches the data section. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * feat(artifacts): read .NET resource sets as members Serve each named resource of a .resources stream as a member whose bytes are one range of the set: a string's UTF-8 bytes, a byte array's or stream's payload, or a primitive's stored bytes with its decoded value in the entry metadata. Serialized objects are listed by type name. Names that are not safe paths, malformed values, hash table damage and version 1 sets are reported as limitations. Entry heads are read through windows of the data section in offset order, so a large set costs few reads. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * feat(artifacts): recognize .NET resource sets for inventory and extraction Claim a .resources stream by its 0xBEEFCACE magic and a usable ResourceManager header, open it as an archive target, and register the extractable dotnet-resources container so inspect_artifact, extract_artifact and inventory views reach its members. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * test(artifacts): cover .NET resource sets through the artifact provider Open a resource set as a target, inventory its members with value facts, extract payloads, and recover from a resource count limit. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * docs(managed): document .NET resource set inventory Describe how resource sets are recognized, what each member's bytes and metadata hold, which values stay unknown, extraction, and reader admission. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * docs(reference): list .NET resource set limits and compared metadata Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * docs(skill): route .NET resource sets to artifact inventory Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * refactor(managed): read resource set fields through BinaryReader Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * docs(skill): sync the Cursor plugin skill Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * test(artifacts): select the .NET resource count among explicit member counts Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * test(artifacts): resolve .NET resource limits from the member count setting Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * fix(managed): reject negative type codes and show Local dates as UTC instants A version 2 type code decoded as a negative Int32 is malformed, so the entry is omitted instead of failing the metadata schema. DateTime.ToBinary stores a Local value's UTC instant, so it is shown with a Z suffix like a Utc value. Name records are read without decoding, so callers can bound decoded names. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * feat(artifacts): bound retained .NET resource names Count every decoded name, including names several table entries share, against dotnet_resources.retained_name_bytes. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * fix(artifacts): bound shared resource names and keep neighbors' data ranges Entry data ranges now come from every record with a data offset, so an entry whose name does not decode no longer extends its neighbor. Decoded names are charged against retained_name_bytes; a set that exceeds it keeps the members read before the limit. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * fix(artifacts): inventory .NET resource names that collide as paths Resource names are flat keys, so a and a/b are distinct resources. Inventory lists both, as for PyInstaller, Bun and Deno members, and extraction still refuses to write colliding destinations together. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * docs(managed): describe resource name limits, flat keys and DateTime instants Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * refactor(managed): report resource set header failures through ParseFailureError The header parser now throws the shared parse failure with the format, offset and field: truncated with the available and required bytes, unsupported for a set version ResourceReader does not read, limit naming the exceeded artifact_limits.dotnet_resources field, and malformed otherwise. Name and value decoders take the caller's BinaryReader instead of allocating one per record, and the metadata schemas live in formatMetadata. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * fix(artifacts): report the full retained name requirement in bytes The retained name refusal now names every reference's bytes, which are known before decoding, so retrying with that value succeeds, and both byte allowances report the bytes unit. The reader maps shared parse failures, grows its header read on truncation inside the set, and holds one reader per name section and data window. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * ci: select the Apple artifact lane for .NET resource set changes Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * docs(cli): show .NET resource set inventory and extraction Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * docs(skill): describe .NET resource set members for agents Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> --------- Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
745 lines
26 KiB
TypeScript
745 lines
26 KiB
TypeScript
import type { FixedAllowance } from "../domain/fixedAllowanceRemediation.js";
|
|
import type { ArtifactReaderLimitFact } from "../domain/artifactReaderLimits.js";
|
|
import type {
|
|
ArtifactAdmissionLimit,
|
|
ArtifactIntegrityCheck,
|
|
ArtifactLimitBoundary,
|
|
ArtifactOperationError,
|
|
} from "../domain/artifactOperationError.js";
|
|
import type {
|
|
ArtifactContainerIntegrityPair,
|
|
ArtifactIntegrityClaim,
|
|
ArtifactIntegrityDetails,
|
|
} from "../domain/artifactIntegrity.js";
|
|
import type { ArtifactFormatMetadata } from "../domain/artifactFormatMetadata.js";
|
|
import type { AnalysisCleanupLease } from "./AnalysisCleanupLease.js";
|
|
import type { Readable } from "node:stream";
|
|
import type {
|
|
ArtifactCommand,
|
|
ArtifactInventoryCoverage,
|
|
ArtifactLinkTarget,
|
|
ArtifactTraversalOmissionKind,
|
|
} from "../domain/artifactGraph.js";
|
|
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
|
|
import {
|
|
AnalysisError,
|
|
appendCleanupObservation,
|
|
type AnalysisCleanupObservation,
|
|
type AnalysisPartialObservation,
|
|
} from "../domain/analysisErrorBase.js";
|
|
import { errorMessage } from "../kernel/errorMessage.js";
|
|
import type { LimitRef } from "../domain/parseFailure.js";
|
|
import {
|
|
isFormatTargetFailureKind,
|
|
type FormatTargetFailure,
|
|
type FormatTargetFailureKind,
|
|
type TargetFailureOf,
|
|
} from "../domain/targetFailure.js";
|
|
import { ParseFailureError } from "../domain/parseFailure.js";
|
|
|
|
/** One rejected close, with facts and optional authority from its owner. */
|
|
export interface ArtifactCleanupRejection {
|
|
readonly cause: unknown;
|
|
readonly cleanup: AnalysisCleanupObservation;
|
|
readonly cleanupLeases?: readonly AnalysisCleanupLease[] | undefined;
|
|
}
|
|
|
|
export interface ArtifactReaderFailureOptions extends ErrorOptions {
|
|
/** Recovery guidance established by the producing adapter, separate from diagnostics. */
|
|
readonly userMessage?: string | undefined;
|
|
/** Regular-file path observed behind a rejected selected symlink; retry still revalidates it. */
|
|
readonly resolvedPath?: string | undefined;
|
|
readonly cancellation?: { readonly reason: unknown } | undefined;
|
|
readonly cleanup?: AnalysisCleanupObservation | undefined;
|
|
/** Exact authority for all reported cleanup; undefined leaves ownership unknown. */
|
|
readonly cleanupLeases?: readonly AnalysisCleanupLease[] | undefined;
|
|
/** Independently rejected closes; retain their typed facts and ownership. */
|
|
readonly cleanupRejections?: readonly ArtifactCleanupRejection[] | undefined;
|
|
readonly partialObservation?: AnalysisPartialObservation | undefined;
|
|
readonly secondaryFailures?: readonly ArtifactReaderFailure[];
|
|
/** The constrained resource bound for a limit failure. */
|
|
readonly boundary?: ArtifactLimitBoundary;
|
|
/** For a `file-size` limit, the observed size the refused read needs. */
|
|
readonly observedBytes?: bigint | undefined;
|
|
/** Named admission whose recovery must not be inferred from other limit text. */
|
|
readonly admission?: ArtifactAdmissionLimit;
|
|
readonly readerLimit?: ArtifactReaderLimitFact;
|
|
readonly parserLimit?: LimitRef;
|
|
/** For a `limit` failure, the release-fixed allowance that refused the input. */
|
|
readonly fixedAllowance?: ArtifactFixedLimit;
|
|
/** For an `integrity` failure, the check that failed, when the reader names it. */
|
|
readonly integrityCheck?: ArtifactIntegrityCheck | undefined;
|
|
/**
|
|
* For a `malformed`, `truncated` or `unsupported` failure, the format
|
|
* owner's facts. Set by {@link artifactFormatFailure}.
|
|
*/
|
|
readonly parseFailure?: FormatTargetFailure | undefined;
|
|
}
|
|
|
|
/** Archive-neutral entry metadata. Reader adapters never choose output paths. */
|
|
export interface ArtifactEntry {
|
|
readonly path: string;
|
|
/** Exact reader-source path or opaque key before logical path mapping. */
|
|
readonly sourcePath?: string;
|
|
readonly kind: "file" | "directory" | "symlink" | "slice" | "metadata";
|
|
readonly declaredSize: number | null;
|
|
readonly compressedSize: number | null;
|
|
/** null means the source did not provide readable permission bits. */
|
|
readonly executable: boolean | null;
|
|
readonly encrypted: boolean;
|
|
readonly byteOffset: number | null;
|
|
/** Stored source extent; expanded size may differ for compressed members. */
|
|
readonly byteLength?: number;
|
|
readonly declaredIntegrity: ArtifactIntegrityClaim | null;
|
|
readonly formatMetadata?: ArtifactFormatMetadata;
|
|
readonly unpacked: boolean;
|
|
readonly limitations: readonly string[];
|
|
readonly adapterKey: string;
|
|
/** A symlink's stored target, when the adapter read it; never followed. */
|
|
readonly linkTarget?: ArtifactLinkTarget;
|
|
/** Filesystem identity captured during traversal, when supplied by an adapter. */
|
|
readonly sourceIdentity?: {
|
|
readonly device: bigint;
|
|
readonly inode: bigint;
|
|
readonly size: bigint;
|
|
readonly mode: bigint;
|
|
readonly mtimeNs: bigint;
|
|
readonly ctimeNs: bigint;
|
|
};
|
|
}
|
|
|
|
/** Compare captured filesystem identity and mutable metadata at a read boundary. */
|
|
export const sameArtifactSourceIdentity = (
|
|
expected: ArtifactEntry["sourceIdentity"],
|
|
observed: {
|
|
readonly dev: bigint;
|
|
readonly ino: bigint;
|
|
readonly size: bigint;
|
|
readonly mode: bigint;
|
|
readonly mtimeNs: bigint;
|
|
readonly ctimeNs: bigint;
|
|
},
|
|
): boolean =>
|
|
expected !== undefined &&
|
|
observed.dev === expected.device &&
|
|
observed.ino === expected.inode &&
|
|
observed.size === expected.size &&
|
|
observed.mode === expected.mode &&
|
|
observed.mtimeNs === expected.mtimeNs &&
|
|
observed.ctimeNs === expected.ctimeNs;
|
|
|
|
/** Snapshot mutable entry metadata before the producer later validates open(). */
|
|
export const copyArtifactEntry = (entry: ArtifactEntry): ArtifactEntry => ({
|
|
...entry,
|
|
limitations: [...entry.limitations],
|
|
declaredIntegrity:
|
|
entry.declaredIntegrity === null ? null : { ...entry.declaredIntegrity },
|
|
...(entry.formatMetadata === undefined
|
|
? {}
|
|
: { formatMetadata: structuredClone(entry.formatMetadata) }),
|
|
...(entry.sourceIdentity === undefined
|
|
? {}
|
|
: { sourceIdentity: { ...entry.sourceIdentity } }),
|
|
...(entry.linkTarget === undefined
|
|
? {}
|
|
: { linkTarget: { ...entry.linkTarget } }),
|
|
});
|
|
|
|
/**
|
|
* Require that an opened entry is one this reader produced, unchanged. Throws
|
|
* the `integrity` failure naming `foreign-entry` when the reader has no such
|
|
* entry, or `entry-metadata` when the supplied facts differ from it.
|
|
*/
|
|
export function assertProducedEntry<Produced extends ArtifactEntry>(
|
|
entry: ArtifactEntry,
|
|
produced: Produced | undefined,
|
|
message: string,
|
|
): asserts produced is Produced {
|
|
if (produced !== undefined && sameArtifactEntry(entry, produced)) return;
|
|
throw new ArtifactReaderFailure("integrity", message, {
|
|
integrityCheck: produced === undefined ? "foreign-entry" : "entry-metadata",
|
|
});
|
|
}
|
|
|
|
/** Compare every portable and adapter-owned fact supplied with an entry. */
|
|
export const sameArtifactEntry = (
|
|
entry: ArtifactEntry,
|
|
produced: ArtifactEntry,
|
|
): boolean =>
|
|
entry.path === produced.path &&
|
|
entry.sourcePath === produced.sourcePath &&
|
|
entry.kind === produced.kind &&
|
|
entry.declaredSize === produced.declaredSize &&
|
|
entry.compressedSize === produced.compressedSize &&
|
|
entry.executable === produced.executable &&
|
|
entry.encrypted === produced.encrypted &&
|
|
entry.byteOffset === produced.byteOffset &&
|
|
entry.byteLength === produced.byteLength &&
|
|
sameDeclaredIntegrity(entry.declaredIntegrity, produced.declaredIntegrity) &&
|
|
sameFormatMetadata(entry.formatMetadata, produced.formatMetadata) &&
|
|
entry.unpacked === produced.unpacked &&
|
|
entry.adapterKey === produced.adapterKey &&
|
|
entry.limitations.length === produced.limitations.length &&
|
|
entry.limitations.every(
|
|
(limitation, index) => limitation === produced.limitations[index],
|
|
) &&
|
|
entry.sourceIdentity?.device === produced.sourceIdentity?.device &&
|
|
entry.sourceIdentity?.inode === produced.sourceIdentity?.inode &&
|
|
entry.sourceIdentity?.size === produced.sourceIdentity?.size &&
|
|
entry.sourceIdentity?.mode === produced.sourceIdentity?.mode &&
|
|
entry.sourceIdentity?.mtimeNs === produced.sourceIdentity?.mtimeNs &&
|
|
entry.sourceIdentity?.ctimeNs === produced.sourceIdentity?.ctimeNs;
|
|
|
|
const sameDeclaredIntegrity = (
|
|
left: ArtifactEntry["declaredIntegrity"],
|
|
right: ArtifactEntry["declaredIntegrity"],
|
|
): boolean =>
|
|
left === right ||
|
|
(left !== null &&
|
|
left !== undefined &&
|
|
right !== null &&
|
|
right !== undefined &&
|
|
left.algorithm === right.algorithm &&
|
|
left.digest === right.digest);
|
|
|
|
/** Compare cloned JSON facts structurally while retaining the primitive fast path. */
|
|
const sameFormatMetadata = (left: unknown, right: unknown): boolean => {
|
|
if (left === right) return true;
|
|
if (Array.isArray(left) || Array.isArray(right))
|
|
return (
|
|
Array.isArray(left) &&
|
|
Array.isArray(right) &&
|
|
left.length === right.length &&
|
|
left.every((value, index) => sameFormatMetadata(value, right[index]))
|
|
);
|
|
if (
|
|
left === null ||
|
|
right === null ||
|
|
typeof left !== "object" ||
|
|
typeof right !== "object"
|
|
)
|
|
return false;
|
|
return (
|
|
Object.keys(left).length === Object.keys(right).length &&
|
|
Object.entries(left).every(
|
|
([key, value]) =>
|
|
Object.hasOwn(right, key) &&
|
|
sameFormatMetadata(value, Reflect.get(right, key)),
|
|
)
|
|
);
|
|
};
|
|
|
|
/** One entry or subtree deliberately excluded from a traversal. */
|
|
export interface ArtifactTraversalOmission {
|
|
readonly path: string;
|
|
readonly kind: ArtifactTraversalOmissionKind;
|
|
}
|
|
|
|
/** Facts from an exhausted traversal, separate from entry content certainty. */
|
|
export interface ArtifactReaderTraversal {
|
|
readonly status: ArtifactInventoryCoverage["status"];
|
|
readonly limitations: readonly string[];
|
|
/** Number of directory entries examined, including names omitted before decoding. */
|
|
readonly examinedEntries?: number;
|
|
}
|
|
|
|
/**
|
|
* Per-iterator observation sink; adapters report intentional omissions without shared state.
|
|
* A reader declares its coverage through `onCoverage` before its iterator ends,
|
|
* including complete coverage; consumers that need a completeness claim
|
|
* iterate through `declaredArtifactEntries`, which treats silence as unknown.
|
|
*/
|
|
export interface ArtifactTraversalOptions {
|
|
readonly onOmission?: (omission: ArtifactTraversalOmission) => void;
|
|
readonly onCoverage?: (coverage: ArtifactReaderTraversal) => void;
|
|
}
|
|
|
|
/** The sink of a traversal whose coverage feeds a completeness claim. */
|
|
export type ArtifactTraversalSink = Required<ArtifactTraversalOptions>;
|
|
|
|
/** Read-only adapter over one directory, archive, or virtual container. */
|
|
export interface ArtifactReader {
|
|
readonly format:
|
|
| "directory"
|
|
| ZipPackageFormat
|
|
| "asar"
|
|
| "ines"
|
|
| "game-boy-rom"
|
|
| "gba-rom"
|
|
| "nds"
|
|
| "mega-drive-rom"
|
|
| "n64-rom"
|
|
| "psx-exe"
|
|
| "godot-pck"
|
|
| "unityfs"
|
|
| "wxapkg"
|
|
| "tar"
|
|
| "ar"
|
|
| "dotnet-resources"
|
|
| "dds"
|
|
| "glb"
|
|
| "ktx"
|
|
| "ktx2"
|
|
| "ogg-opus"
|
|
| "riff-xma2"
|
|
| "bink2"
|
|
| "vulkan-pipeline-cache"
|
|
| "uimage"
|
|
| "nso"
|
|
| "nro"
|
|
| "android-boot-image"
|
|
| "android-dtbo"
|
|
| "android-ota-payload"
|
|
| "android-vbmeta"
|
|
| "android-sparse-image"
|
|
| "android-super-image"
|
|
| "ubi-image"
|
|
| "iso9660"
|
|
| "uefi"
|
|
| "pyinstaller"
|
|
| "dotnet-bundle"
|
|
| "bun-standalone"
|
|
| "deno-standalone"
|
|
| "node-sea"
|
|
| "intel-hex"
|
|
| "srec"
|
|
| "esp-image"
|
|
| "uf2"
|
|
| "dfuse"
|
|
| "bflt"
|
|
| "esp-flash-image"
|
|
| "fit"
|
|
| "swf"
|
|
| "mcuboot"
|
|
| "qualcomm-mbn"
|
|
| "apple-img4"
|
|
| "mql-program"
|
|
| "esp8266-image"
|
|
| "ntfs-mft"
|
|
| "systemd-journal"
|
|
| "auditd-log"
|
|
| "kubernetes-audit-log"
|
|
| "pkg"
|
|
| "file";
|
|
entries(
|
|
signal?: AbortSignal,
|
|
options?: ArtifactTraversalOptions,
|
|
): AsyncIterable<ArtifactEntry>;
|
|
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable>;
|
|
provenance(): readonly ArtifactCommand[];
|
|
formatMetadata?(): ArtifactFormatMetadata | undefined;
|
|
/** A checksum the container declares over its own bytes, with the observed value. */
|
|
containerIntegrity?(): ArtifactContainerIntegrityPair | undefined;
|
|
/** Bind materialization to the exact inventoried carrier before creating outputs. */
|
|
prepareContainer?(
|
|
expectedSha256: string,
|
|
signal?: AbortSignal,
|
|
): Promise<void>;
|
|
close(): Promise<void>;
|
|
}
|
|
|
|
/** Typed adapter failure translated at provider boundary. */
|
|
/** A selected-file read whose own cleanup failed. */
|
|
export type CleanupFailedRead = ArtifactReaderFailure & {
|
|
readonly cleanup: AnalysisCleanupObservation;
|
|
};
|
|
|
|
/** Why an artifact reader failed. */
|
|
export type ArtifactReaderFailureReason =
|
|
| ArtifactOperationError["reason"]
|
|
| FormatTargetFailure["kind"];
|
|
|
|
export class ArtifactReaderFailure extends Error {
|
|
readonly userMessage: string | undefined;
|
|
readonly resolvedPath: string | undefined;
|
|
readonly cancellation: { readonly reason: unknown } | undefined;
|
|
readonly cleanup: AnalysisCleanupObservation | undefined;
|
|
readonly cleanupLeases: readonly AnalysisCleanupLease[] | undefined;
|
|
readonly cleanupRejections: readonly ArtifactCleanupRejection[] | undefined;
|
|
partialObservation: AnalysisPartialObservation | undefined;
|
|
secondaryFailures: readonly ArtifactReaderFailure[] | undefined;
|
|
/** The constrained bound for a `limit` reason, when the reader knows it. */
|
|
readonly boundary: ArtifactLimitBoundary | undefined;
|
|
readonly observedBytes: bigint | undefined;
|
|
/** Named admission for a limit whose public recovery is owned by the producer. */
|
|
readonly admission: ArtifactAdmissionLimit | undefined;
|
|
readonly readerLimit: ArtifactReaderLimitFact | undefined;
|
|
readonly parserLimit: LimitRef | undefined;
|
|
readonly fixedAllowance: ArtifactFixedLimit | undefined;
|
|
readonly integrityCheck: ArtifactIntegrityCheck | undefined;
|
|
readonly parseFailure: FormatTargetFailure | undefined;
|
|
|
|
/** An `integrity` failure names the check that failed. */
|
|
constructor(
|
|
reason: "integrity",
|
|
message: string,
|
|
options: ArtifactReaderFailureOptions & {
|
|
readonly integrityCheck: ArtifactIntegrityCheck;
|
|
},
|
|
details?: ArtifactIntegrityDetails,
|
|
);
|
|
/** A format owner's refusal carries the owner's facts. */
|
|
constructor(
|
|
reason: FormatTargetFailure["kind"],
|
|
message: string,
|
|
options: ArtifactReaderFailureOptions & {
|
|
readonly parseFailure: FormatTargetFailure;
|
|
},
|
|
details?: ArtifactIntegrityDetails,
|
|
);
|
|
constructor(
|
|
reason: Exclude<
|
|
ArtifactReaderFailureReason,
|
|
"integrity" | FormatTargetFailure["kind"]
|
|
>,
|
|
message: string,
|
|
options?: ArtifactReaderFailureOptions,
|
|
details?: ArtifactIntegrityDetails,
|
|
);
|
|
/**
|
|
* A rebuild whose reason is not a literal carries the check explicitly, as
|
|
* {@link primaryFacts} does, so a rewrapped integrity failure keeps it.
|
|
*/
|
|
constructor(
|
|
reason: ArtifactReaderFailureReason,
|
|
message: string,
|
|
options: ArtifactReaderFailureOptions & {
|
|
readonly integrityCheck: ArtifactIntegrityCheck | undefined;
|
|
},
|
|
details?: ArtifactIntegrityDetails,
|
|
);
|
|
constructor(
|
|
readonly reason: ArtifactReaderFailureReason,
|
|
message: string,
|
|
options?: ArtifactReaderFailureOptions,
|
|
readonly details?: ArtifactIntegrityDetails,
|
|
) {
|
|
super(message, options);
|
|
this.name = "ArtifactReaderFailure";
|
|
this.userMessage = options?.userMessage;
|
|
this.resolvedPath = options?.resolvedPath;
|
|
this.cancellation =
|
|
reason === "cancelled"
|
|
? (options?.cancellation ?? { reason: options?.cause })
|
|
: undefined;
|
|
this.cleanup = options?.cleanup;
|
|
this.cleanupLeases =
|
|
options?.cleanupLeases ?? (this.cleanup === undefined ? [] : undefined);
|
|
this.cleanupRejections = options?.cleanupRejections;
|
|
this.partialObservation = options?.partialObservation;
|
|
this.secondaryFailures = options?.secondaryFailures;
|
|
this.boundary = options?.boundary;
|
|
this.observedBytes = options?.observedBytes;
|
|
this.admission = options?.admission;
|
|
this.readerLimit = options?.readerLimit;
|
|
this.parserLimit = options?.parserLimit;
|
|
this.fixedAllowance = options?.fixedAllowance;
|
|
this.integrityCheck = options?.integrityCheck;
|
|
this.parseFailure = isFormatTargetFailureKind(reason)
|
|
? options?.parseFailure
|
|
: undefined;
|
|
}
|
|
|
|
/**
|
|
* Reader-owned facts a rebuilt failure must keep. Each rebuild chooses its
|
|
* own cause, cleanup, cancellation and partial observation.
|
|
*/
|
|
primaryFacts(): Pick<
|
|
ArtifactReaderFailureOptions,
|
|
| "userMessage"
|
|
| "resolvedPath"
|
|
| "boundary"
|
|
| "observedBytes"
|
|
| "admission"
|
|
| "readerLimit"
|
|
| "parserLimit"
|
|
| "fixedAllowance"
|
|
| "parseFailure"
|
|
| "secondaryFailures"
|
|
> & { readonly integrityCheck: ArtifactIntegrityCheck | undefined } {
|
|
return {
|
|
...(this.userMessage === undefined
|
|
? {}
|
|
: { userMessage: this.userMessage }),
|
|
...(this.resolvedPath === undefined
|
|
? {}
|
|
: { resolvedPath: this.resolvedPath }),
|
|
...(this.boundary === undefined ? {} : { boundary: this.boundary }),
|
|
...(this.observedBytes === undefined
|
|
? {}
|
|
: { observedBytes: this.observedBytes }),
|
|
...(this.admission === undefined ? {} : { admission: this.admission }),
|
|
...(this.readerLimit === undefined
|
|
? {}
|
|
: { readerLimit: this.readerLimit }),
|
|
...(this.parserLimit === undefined
|
|
? {}
|
|
: { parserLimit: this.parserLimit }),
|
|
...(this.fixedAllowance === undefined
|
|
? {}
|
|
: { fixedAllowance: this.fixedAllowance }),
|
|
...(this.parseFailure === undefined
|
|
? {}
|
|
: { parseFailure: this.parseFailure }),
|
|
...(this.secondaryFailures === undefined
|
|
? {}
|
|
: { secondaryFailures: this.secondaryFailures }),
|
|
integrityCheck: this.integrityCheck,
|
|
};
|
|
}
|
|
|
|
/** Retain completed facts when a later artifact step fails. */
|
|
retainPartialObservation(observation: AnalysisPartialObservation): this {
|
|
this.partialObservation ??= observation;
|
|
return this;
|
|
}
|
|
|
|
retainSecondaryFailure(failure: ArtifactReaderFailure): this {
|
|
this.secondaryFailures = [...(this.secondaryFailures ?? []), failure];
|
|
return this;
|
|
}
|
|
|
|
/** Preserve the primary failure and observation. Supplied leases must cover all merged cleanup. */
|
|
static withCleanup(
|
|
cause: unknown,
|
|
cleanup: AnalysisCleanupObservation,
|
|
partialObservation?: AnalysisPartialObservation,
|
|
cleanupLeases?: readonly AnalysisCleanupLease[],
|
|
addedRejections?: readonly ArtifactCleanupRejection[],
|
|
): ArtifactReaderFailure {
|
|
const primary =
|
|
cause instanceof ArtifactReaderFailure
|
|
? cause
|
|
: new ArtifactReaderFailure("io", errorMessage(cause), {
|
|
cause,
|
|
...(cause instanceof AnalysisError
|
|
? {
|
|
partialObservation: cause.partialObservation,
|
|
...(cause.cleanupIncomplete
|
|
? {
|
|
cleanup: ArtifactReaderFailure.cleanupObservation(
|
|
cause,
|
|
[],
|
|
),
|
|
}
|
|
: {}),
|
|
}
|
|
: {}),
|
|
});
|
|
const previousCleanup = primary.cleanup;
|
|
const sameCleanup = previousCleanup === cleanup;
|
|
const mergedObservation = partialObservation ?? primary.partialObservation;
|
|
return new ArtifactReaderFailure(
|
|
primary.reason,
|
|
primary.message,
|
|
{
|
|
cause: primary,
|
|
// The constrained bound survives cleanup wrapping, or a file-size
|
|
// refusal would be reported as a memory constraint once a close fails.
|
|
...primary.primaryFacts(),
|
|
cancellation: primary.cancellation,
|
|
cleanup: sameCleanup
|
|
? cleanup
|
|
: appendCleanupObservation(previousCleanup, cleanup),
|
|
cleanupLeases:
|
|
cleanupLeases ?? (sameCleanup ? primary.cleanupLeases : undefined),
|
|
...(primary.cleanupRejections === undefined
|
|
? {}
|
|
: {
|
|
cleanupRejections: sameCleanup
|
|
? primary.cleanupRejections
|
|
: [
|
|
...primary.cleanupRejections,
|
|
...(addedRejections ?? [
|
|
{ cause: undefined, cleanup, cleanupLeases },
|
|
]),
|
|
],
|
|
}),
|
|
...(mergedObservation === undefined
|
|
? {}
|
|
: { partialObservation: mergedObservation }),
|
|
},
|
|
primary.details,
|
|
);
|
|
}
|
|
|
|
/** Give otherwise opaque cleanup failures a concrete owned resource. */
|
|
static cleanupObservation(
|
|
cause: unknown,
|
|
resource: string | readonly string[],
|
|
): AnalysisCleanupObservation {
|
|
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
|
|
return cause.cleanup;
|
|
if (cause instanceof AnalysisError && cause.cleanupIncomplete)
|
|
return {
|
|
reason: cause.cleanup?.reason ?? cause.message,
|
|
resources: [...cause.cleanupResources],
|
|
};
|
|
return {
|
|
reason: errorMessage(cause),
|
|
resources: typeof resource === "string" ? [resource] : [...resource],
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* A release-fixed reader ceiling. The reader states its value, so a consumer
|
|
* that carries the ceiling to another process or projection keeps it.
|
|
*/
|
|
export type ArtifactFixedLimit = FixedAllowance & {
|
|
readonly limit: number;
|
|
readonly unit: string;
|
|
};
|
|
|
|
/**
|
|
* Refuse input above a release-fixed reader ceiling. `outcome` states what
|
|
* exceeded it; CLI and MCP derive the recovery from the typed allowance.
|
|
*/
|
|
export const artifactFixedLimitFailure = (
|
|
allowance: ArtifactFixedLimit,
|
|
outcome: string,
|
|
boundary: ArtifactLimitBoundary = "capacity",
|
|
options?: ErrorOptions,
|
|
): ArtifactReaderFailure =>
|
|
new ArtifactReaderFailure("limit", outcome, {
|
|
...options,
|
|
boundary,
|
|
userMessage: outcome,
|
|
fixedAllowance: allowance,
|
|
});
|
|
|
|
/** Where in the format a structure failed, when the reader knows it. */
|
|
export interface ArtifactFormatSite extends Omit<
|
|
ArtifactReaderFailureOptions,
|
|
"parseFailure"
|
|
> {
|
|
readonly offset?: number;
|
|
readonly field?: string;
|
|
}
|
|
|
|
/** A truncated structure's measured extents, when the reader measured them. */
|
|
export interface ArtifactTruncationSite extends ArtifactFormatSite {
|
|
readonly availableBytes?: number;
|
|
readonly requiredBytes?: number;
|
|
}
|
|
|
|
/**
|
|
* A container reader's byte-structure failure, raised once by the reader that
|
|
* owns `format`. The reason is the failure's own kind, so no consumer has to
|
|
* reinterpret the message.
|
|
*/
|
|
export const artifactFormatFailure = (
|
|
failure: FormatTargetFailure,
|
|
options: Omit<ArtifactReaderFailureOptions, "parseFailure"> = {},
|
|
): ArtifactReaderFailure =>
|
|
new ArtifactReaderFailure(failure.kind, failure.detail, {
|
|
...options,
|
|
parseFailure: failure,
|
|
});
|
|
|
|
const located = (offset: number | undefined, field: string | undefined) => ({
|
|
...(offset === undefined ? {} : { offset }),
|
|
...(field === undefined ? {} : { field }),
|
|
});
|
|
|
|
/** The bytes break `format`'s own rules. */
|
|
export const malformedArtifact = (
|
|
format: string,
|
|
detail: string,
|
|
{ offset, field, ...options }: ArtifactFormatSite = {},
|
|
): ArtifactReaderFailure =>
|
|
artifactFormatFailure(
|
|
{ kind: "malformed", format, detail, ...located(offset, field) },
|
|
options,
|
|
);
|
|
|
|
/**
|
|
* The throwable for a failure a reader established. Bytes that came up short
|
|
* after the file's size was measured mean the file changed during the read,
|
|
* a read-coverage integrity failure; any other kind is the owner's parse
|
|
* failure, which a stable-file owner re-verifies before reporting.
|
|
*/
|
|
export const readFailureError = (
|
|
failure: FormatTargetFailure | TargetFailureOf<"changed">,
|
|
): ArtifactReaderFailure | ParseFailureError<FormatTargetFailureKind> =>
|
|
failure.kind === "changed"
|
|
? new ArtifactReaderFailure("integrity", failure.detail, {
|
|
integrityCheck: "read-coverage",
|
|
})
|
|
: new ParseFailureError(failure);
|
|
|
|
/**
|
|
* The bytes use a form outside what this reader of `format` decodes.
|
|
* `undecodedContent` says the input holds the content in that form.
|
|
*/
|
|
export const unsupportedArtifact = (
|
|
format: string,
|
|
detail: string,
|
|
{
|
|
offset,
|
|
field,
|
|
undecodedContent = false,
|
|
...options
|
|
}: ArtifactFormatSite & { readonly undecodedContent?: boolean } = {},
|
|
): ArtifactReaderFailure =>
|
|
artifactFormatFailure(
|
|
{
|
|
kind: "unsupported",
|
|
format,
|
|
detail,
|
|
undecodedContent,
|
|
...located(offset, field),
|
|
},
|
|
options,
|
|
);
|
|
|
|
/** The bytes end before a structure `format` declares. */
|
|
export const truncatedArtifact = (
|
|
format: string,
|
|
detail: string,
|
|
{
|
|
offset,
|
|
field,
|
|
availableBytes,
|
|
requiredBytes,
|
|
...options
|
|
}: ArtifactTruncationSite = {},
|
|
): ArtifactReaderFailure =>
|
|
artifactFormatFailure(
|
|
{
|
|
kind: "truncated",
|
|
format,
|
|
detail,
|
|
...located(offset, field),
|
|
// The model carries the measured end only as a complete pair.
|
|
...(availableBytes === undefined || requiredBytes === undefined
|
|
? {}
|
|
: { extent: { availableBytes, requiredBytes } }),
|
|
},
|
|
options,
|
|
);
|
|
|
|
/** Read explicit source authority; unrelated domain cleanup remains unresolved. */
|
|
export const artifactPrimaryCleanupLeases = (
|
|
cause: unknown,
|
|
): readonly AnalysisCleanupLease[] | undefined =>
|
|
cause instanceof ArtifactReaderFailure
|
|
? cause.cleanupLeases
|
|
: cause instanceof AnalysisError && cause.cleanupIncomplete
|
|
? undefined
|
|
: [];
|
|
|
|
/** Known member identities whose content cannot be read; never a reader shutdown. */
|
|
export class ArtifactEntryContentUnavailable extends ArtifactReaderFailure {
|
|
readonly traversal: ArtifactReaderTraversal | undefined;
|
|
constructor(
|
|
message: string,
|
|
readonly limitation: string,
|
|
options?: ErrorOptions & { readonly traversal?: ArtifactReaderTraversal },
|
|
details?: ArtifactIntegrityDetails,
|
|
) {
|
|
super("unavailable", message, options, details);
|
|
this.traversal = options?.traversal;
|
|
}
|
|
}
|