refactor(environment): share response status checks and write plan fixtures (#14336)

* refactor(environment): share HTTP response status classification

* test(environment): share capture parents and write plan lookups

* refactor(environment): mark write-check imports as type-only
This commit is contained in:
Vincent Koc authored and GitHub committed 2026-11-24 10:12:02 +00:00
1 parent 30fe9d9f42
commit e17033450e
31 files changed
+132 -256

No files matched your search

@@ -1,3 +1,4 @@
import { isSuccessfulHttpStatus } from "../../domain/httpResponseStatus.js";
import { boundedList } from "../../domain/boundedList.js";
import {
ownMember,
@@ -139,9 +140,6 @@ const emptyNormalised = (): Normalised => ({
unobserved_bodies: 0,
});
const isSuccess = (status: number | null): boolean =>
status !== null && status >= 200 && status < 300;
/** Where a call's answer holds its own entities, and the collection they belong to: a read view's entity or list pointer, a write's response pointer, else the root. A write that answers with only the new id learns that scalar. */
const entityOf = (
run: ProbeRun,
@@ -406,7 +404,11 @@ const compareStep = (
for (const key of NORMALISED_KEYS)
run.normalised[key] += compared.normalised[key];
const differences = [...compared.differences];
if (unknownPath && isSuccess(live.status) && !isSuccess(env.status))
if (
unknownPath &&
isSuccessfulHttpStatus(live.status) &&
!isSuccessfulHttpStatus(env.status)
)
differences.unshift({ category: "unmapped-id", pointer: "" });
return ok(stepOf(base, call, { env_status: env.status, differences }));
};
@@ -1,3 +1,4 @@
import { isSuccessfulHttpStatus } from "../../domain/httpResponseStatus.js";
import { hasRepeatedQueryArgument } from "./environmentTools.js";
import { stateBodyJson } from "../../domain/analysisView/EnvironmentStateAccumulator.js";
import {
@@ -346,9 +347,7 @@ export const missingAnswer = (
exchange !== undefined &&
(isAbsence(exchange.status) ||
(nullAbsence &&
exchange.status !== null &&
exchange.status >= 200 &&
exchange.status < 300 &&
isSuccessfulHttpStatus(exchange.status) &&
recordedJson(exchange) === null)),
)
.at(-1);
@@ -1,3 +1,4 @@
import { isSuccessfulHttpStatus } from "../../domain/httpResponseStatus.js";
import { advertiseToolInput } from "../../contracts/advertisedTool.js";
import { formattedEllipsisExcerpt } from "../../domain/excerpt.js";
import { jsonPointerTokens } from "../../domain/jsonPointer.js";
@@ -206,9 +207,6 @@ const describeJson = (value: JsonValue): string => {
return `a JSON ${value === null ? "null" : typeof value}`;
};
const isSuccess = (status: number | null): boolean =>
status !== null && status >= 200 && status < 300;
/** The first cited record replay answers as JSON, preferring a 2xx one; each body is parsed at most once. */
const firstJson = (
tool: EnvironmentManifestTool,
@@ -219,7 +217,10 @@ const firstJson = (
for (const success of [true, false])
for (const ordinal of tool.record_ordinals) {
const exchange = exchanges.get(ordinal);
if (exchange === undefined || isSuccess(exchange.status) !== success)
if (
exchange === undefined ||
isSuccessfulHttpStatus(exchange.status) !== success
)
continue;
const body = replayedBody(exchange);
if (body.kind === "json")
@@ -239,7 +240,7 @@ const describeResponses = (
: `recorded statuses ${describeList(tool.statuses, tool.statuses.length)}`;
const found = firstJson(tool, exchanges);
if (found === undefined) return recorded;
const returns = isSuccess(found.status)
const returns = isSuccessfulHttpStatus(found.status)
? "returns"
: found.status === null
? "a record without a status returns"
@@ -1,3 +1,4 @@
import { isSuccessfulHttpStatus } from "../httpResponseStatus.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { jsonValueType, parseJsonObject } from "../jsonShape.js";
import { ok, type Result } from "../result.js";
@@ -108,8 +109,7 @@ const manifestResponseIsEmpty = (record: WebNetworkCaptureRecord): boolean => {
};
/** A write group every response of which had no body, at least one of them a success. */
const answeredEmpty = (group: GroupState): boolean =>
group.bodiless &&
[...group.statuses].some((status) => status >= 200 && status < 300);
group.bodiless && [...group.statuses].some(isSuccessfulHttpStatus);
const ASSET_ESSENCES = new Set([
"text/html",
"application/xhtml+xml",
@@ -7,6 +7,7 @@ import {
environmentEntityKey,
} from "./environmentStateIdentity.js";
import {
succeeded,
ownMember,
apiBaseLengths,
at,
@@ -409,9 +410,7 @@ export class EnvironmentStateExtraction {
.filter(
(record): record is StateRecordFacts =>
record !== undefined &&
record.status !== null &&
record.status >= 200 &&
record.status < 300 &&
succeeded(record) &&
this.#beforeInitLimit(record, limit),
)
.sort(
@@ -477,13 +476,7 @@ export class EnvironmentStateExtraction {
if (limit === undefined) return { laterFields: names };
for (const ordinal of tool.record_ordinals) {
const record = this.#byOrdinal.get(ordinal);
if (
record === undefined ||
record.status === null ||
record.status < 200 ||
record.status >= 300
)
continue;
if (record === undefined || !succeeded(record)) continue;
// Any read may show the soft-delete flag; only plain later reads add fields.
const later =
(record.query ?? "") === "" && !this.#beforeInitLimit(record, limit);
@@ -526,9 +519,7 @@ export class EnvironmentStateExtraction {
const record = this.#byOrdinal.get(ordinal);
if (
record === undefined ||
record.status === null ||
record.status < 200 ||
record.status >= 300 ||
!succeeded(record) ||
this.#beforeInitLimit(record, limit)
)
continue;
@@ -18,6 +18,7 @@ import {
environmentStateViewOf,
renamedBook,
type Book,
planOf as gated,
} from "../../../tests/fixtures/environmentStateWrites.js";
import type { JsonValue } from "../jsonValue.js";
import { ok } from "../result.js";
@@ -34,14 +35,6 @@ import {
} from "./environmentStateWriteObserve.js";
import { updatedFields } from "./environmentStateWriteApply.js";
/** The plan the gate gives `tool` over a capture of `rows`. */
const gated = (rows: readonly TimedCaptureRow[], tool: string) => {
const { writes } = environmentStateViewOf(timedCaptureEvidence(rows));
const plan = writes.find((candidate) => candidate.tool === tool);
if (plan === undefined) throw new Error(`The gate planned no ${tool}`);
return plan;
};
const RENAMED = renamedBook(FIRST_BOOK, "Renamed Book", 3);
it.each([
@@ -2,6 +2,7 @@ import { ENTRY_BYTES } from "./webNetworkRouteTemplates.js";
import { CapturedWriteCompletion } from "./environmentStateWriteCompletion.js";
import type { JsonValue } from "../jsonValue.js";
import {
succeeded,
at,
changesState,
isObject,
@@ -47,7 +48,6 @@ import {
entityTarget,
isAbsence,
itemTarget,
succeeded,
withBodies,
showsPlacement,
SimulatedState,
@@ -1,15 +1,13 @@
import { expect, it } from "vitest";
import {
analysisViewCaptureEvidence,
environmentStateCaptureFixture,
timedCaptureEvidence,
captureParent,
} from "../../../tests/fixtures/analysisView.js";
import {
SCENARIO_EXCHANGES,
scenarioCaptureEvidence,
scenarioCaptureFixture,
} from "../../../tests/fixtures/browserScenarioCapture.js";
import type { Evidence } from "../evidence.js";
import { projectAnalysisView } from "./analysisView.js";
import type { AnalysisViewParent } from "./analysisViewParent.js";
import type { AnalysisViewResult } from "./analysisViewResult.js";
@@ -28,23 +26,9 @@ const RULES = [
"sibling-variance",
] as const;
const parentOf = (
evidence: Evidence = analysisViewCaptureEvidence(
environmentStateCaptureFixture(),
),
): AnalysisViewParent => ({
predicateType: evidence.predicate_type,
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: evidence.normalized_result,
subject: evidence.subject,
limitations: [],
parameters: evidence.parameters,
});
const project = (
kind: "environment-state" | "environment-coverage",
parent: AnalysisViewParent = parentOf(),
parent: AnalysisViewParent = captureParent(),
): AnalysisViewResult => {
const projected = projectAnalysisView(
parent,
@@ -173,7 +157,7 @@ it("does not claim reads are missing when a literal delete has no modelled targe
["GET", "/api/folders/f1", { message: "not found" }, 404],
["GET", "/api/folders", []],
]);
const parent = parentOf(evidence);
const parent = captureParent(evidence);
const state = project("environment-state", parent);
const coverage = project("environment-coverage", parent);
if (
@@ -199,7 +183,7 @@ it("does not claim reads are missing when a literal delete has no modelled targe
it("says an untimed capture learns no clock, and only for an untimed capture", () => {
const untimed = /learns no clock/u;
const scenarioParent = parentOf(
const scenarioParent = captureParent(
scenarioCaptureEvidence(
scenarioCaptureFixture(SCENARIO_EXCHANGES, {
request_body: true,
@@ -209,7 +193,7 @@ it("says an untimed capture learns no clock, and only for an untimed capture", (
),
);
for (const [parent, needsClockAdvice] of [
[parentOf(), false],
[captureParent(), false],
[scenarioParent, true],
] as const) {
const coverage = project("environment-coverage", parent);
@@ -230,7 +214,7 @@ it("refuses a browser scenario without selected response bodies", () => {
}),
);
expect(
projectAnalysisView(parentOf(evidence), {
projectAnalysisView(captureParent(evidence), {
kind: "environment-coverage",
template_rules: [],
}),
@@ -1,26 +1,18 @@
import { describe, expect, it } from "vitest";
import {
timedCaptureEvidence,
type TimedCaptureRow,
} from "../../../tests/fixtures/analysisView.js";
import type { TimedCaptureRow } from "../../../tests/fixtures/analysisView.js";
import {
HELD_FIXED_TAG_ROWS,
misshelvedRows,
referencedCreateRows,
shelvedRows,
} from "../../../tests/fixtures/environmentStateDerivedValues.js";
import { environmentStateViewOf } from "../../../tests/fixtures/environmentStateWrites.js";
import { planOf } from "../../../tests/fixtures/environmentStateWrites.js";
import { mergedCreatePlan } from "./environmentStateWriteCreateCalls.js";
import type { FieldRule } from "./environmentStateWriteRules.js";
const createPlan = (rows: readonly TimedCaptureRow[], tool = "post_books") => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error("No create plan");
return plan;
};
const createPlan = (rows: readonly TimedCaptureRow[], tool = "post_books") =>
planOf(rows, tool);
const OPTIONAL_SHELF = {
served: true,
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import {
timedCaptureEvidence,
type TimedCaptureRow,
} from "../../../tests/fixtures/analysisView.js";
import type { TimedCaptureRow } from "../../../tests/fixtures/analysisView.js";
import {
BOOKMARK_ROWS,
FIXED_HELD_TAG_ROWS,
@@ -21,20 +18,12 @@ import {
} from "../../../tests/fixtures/environmentStateDerivedValues.js";
import {
bookClock,
environmentStateViewOf,
numberedUuid,
planOf,
} from "../../../tests/fixtures/environmentStateWrites.js";
import type { JsonValue } from "../jsonValue.js";
import { isObject, type JsonObject } from "./environmentStateRules.js";
const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error(`No plan for ${tool}`);
return plan;
};
const TRIMMED = {
kind: "iso",
separator: "T",
@@ -1,9 +1,5 @@
import { describe, expect, it } from "vitest";
import {
timedCaptureEvidence,
type TimedCaptureRow,
} from "../../../tests/fixtures/analysisView.js";
import {
BULK_EMPTY_TAG_ROWS,
CREATION_ORDER_ROWS,
@@ -21,19 +17,11 @@ import {
CONFIRMED_RENAME_ROWS,
UNPLACED_CREATE_ROWS,
} from "../../../tests/fixtures/environmentStateFormWrites.js";
import { environmentStateViewOf } from "../../../tests/fixtures/environmentStateWrites.js";
import { planOf } from "../../../tests/fixtures/environmentStateWrites.js";
import { mergedCreatePlan } from "./environmentStateWriteCreateCalls.js";
import { resortedMembers } from "./environmentStateWriteExplain.js";
import type { WriteBody } from "./environmentStateWriteRules.js";
const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error(`No plan for ${tool}`);
return plan;
};
const BY_NAME = {
rule: "sorted",
field: "name",
@@ -1,9 +1,5 @@
import { describe, expect, it } from "vitest";
import {
timedCaptureEvidence,
type TimedCaptureRow,
} from "../../../tests/fixtures/analysisView.js";
import {
BOOKMARK_TOGGLE_ROWS,
CREATES_BY_TITLE_ROWS,
@@ -12,15 +8,7 @@ import {
REFUTED_TITLE_SORT_ROWS,
feedEntry,
} from "../../../tests/fixtures/environmentStateItemWrites.js";
import { environmentStateViewOf } from "../../../tests/fixtures/environmentStateWrites.js";
const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error(`No plan for ${tool}`);
return plan;
};
import { planOf } from "../../../tests/fixtures/environmentStateWrites.js";
describe("item writes", () => {
it("learns a create's sort from a later list its full order follows, after one create was placed last", () => {
@@ -12,18 +12,15 @@ import {
SOFT_DELETED_QUERY_ROWS,
SOFT_DELETED_ROWS,
} from "../../../tests/fixtures/environmentStateLaterReads.js";
import { environmentStateViewOf } from "../../../tests/fixtures/environmentStateWrites.js";
import {
environmentStateViewOf,
planOf,
} from "../../../tests/fixtures/environmentStateWrites.js";
import { markedDeleted } from "./environmentStateRules.js";
const viewOf = (rows: readonly TimedCaptureRow[]) =>
environmentStateViewOf(timedCaptureEvidence(rows));
const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = viewOf(rows).writes.find((candidate) => candidate.tool === tool);
if (plan === undefined) throw new Error(`No plan for ${tool}`);
return plan;
};
describe("deletes the application answers for afterwards", () => {
it("confirms a delete by an item read that shows the entity marked deleted", () => {
expect(planOf(SOFT_DELETED_ROWS, "delete_contacts_by_id")).toMatchObject({
@@ -3,6 +3,7 @@ import { digestCanonicalValue } from "../canonicalDigest.js";
import { identifierWords } from "./environmentStateWords.js";
import type { JsonValue } from "../jsonValue.js";
import {
succeeded,
changesState,
isObject,
isParam,
@@ -114,9 +115,6 @@ const responseDigests = (
};
};
const succeeded = (record: StateRecordFacts): boolean =>
record.status !== null && record.status >= 200 && record.status < 300;
/** A call that may have changed state without a 2xx answer saying what it did: redirected or unanswered. */
const unresolved = (record: StateRecordFacts): boolean =>
isStateWrite(record) && !succeeded(record);
@@ -3,6 +3,7 @@ import { canonicalJson } from "../comparisonSemantics.js";
import type { JsonValue } from "../jsonValue.js";
import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js";
import {
succeeded,
isObject,
normalizedPath,
replaceAt,
@@ -18,9 +19,6 @@ const MINIMUM_REPEATS = 2;
/** The paths whose repeated reads showed each member minted anew, so only views of those paths leave it out. */
export type MintedMembers = ReadonlyMap<string, ReadonlySet<string>>;
const succeeded = (record: StateRecordFacts): boolean =>
record.status !== null && record.status >= 200 && record.status < 300;
/** A body's top-level members whose value looks minted: a UUID or a clock reading. */
const mintedValues = (
body: JsonValue | undefined,
@@ -1,3 +1,4 @@
import { isSuccessfulHttpStatus } from "../httpResponseStatus.js";
import { isRecord } from "../../kernel/isRecord.js";
import { escapeJsonPointerToken, jsonPointerTokens } from "../jsonPointer.js";
import {
@@ -440,6 +441,10 @@ export const isQueryPost = (method: string, path: string): boolean =>
export const changesState = (method: string, path: string): boolean =>
WRITE_METHODS.has(method) && !isQueryPost(method, path);
/** A 2xx record: the only status whose response shows what a request did. */
export const succeeded = (record: Pick<StateRecordFacts, "status">): boolean =>
isSuccessfulHttpStatus(record.status);
/** Whether a record may change state: a successful or unanswered request that `changesState` names. */
export const isStateWrite = (
record: Pick<StateRecordFacts, "method" | "path" | "status">,
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import {
timedCaptureEvidence,
type TimedCaptureRow,
} from "../../../tests/fixtures/analysisView.js";
import type { TimedCaptureRow } from "../../../tests/fixtures/analysisView.js";
import {
CLEARED_THEN_OMITTED_KEPT_ROWS,
DEFAULT_THEN_NUMBERED_ROWS,
@@ -24,15 +21,7 @@ import {
CLEARED_THEN_KEPT_ROWS,
PUT_CLEARS_ROWS,
} from "../../../tests/fixtures/environmentStateVariedCalls.js";
import { environmentStateViewOf } from "../../../tests/fixtures/environmentStateWrites.js";
const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error(`No plan for ${tool}`);
return plan;
};
import { planOf } from "../../../tests/fixtures/environmentStateWrites.js";
describe("writes whose calls send different members", () => {
it("serves an update a later call sends fewer members to, requiring only those every call sent", () => {
@@ -2,16 +2,15 @@ import { expect, it } from "vitest";
import {
analysisViewCaptureEvidence,
environmentManifestCaptureFixture,
environmentStateCaptureFixture,
timedCaptureEvidence,
type TimedCaptureRow,
captureParent,
} from "../../../tests/fixtures/analysisView.js";
import {
SCENARIO_EXCHANGES,
scenarioCaptureEvidence,
scenarioCaptureFixture,
} from "../../../tests/fixtures/browserScenarioCapture.js";
import type { Evidence } from "../evidence.js";
import { ownedJsonObjectSchema, type JsonValue } from "../jsonValue.js";
import { webNetworkCaptureSchema } from "../webNetworkCapture.js";
import { projectAnalysisView } from "./analysisView.js";
@@ -52,21 +51,7 @@ const ALL_RULES = [
"sibling-variance",
] as const;
const parentOf = (
evidence: Evidence = analysisViewCaptureEvidence(
environmentStateCaptureFixture(),
),
): AnalysisViewParent => ({
predicateType: evidence.predicate_type,
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: evidence.normalized_result,
subject: evidence.subject,
limitations: [],
parameters: evidence.parameters,
});
const stateOf = (parent: AnalysisViewParent = parentOf()): State => {
const stateOf = (parent: AnalysisViewParent = captureParent()): State => {
const result = projectAnalysisView(parent, {
kind: "environment-state",
template_rules: [...ALL_RULES],
@@ -77,7 +62,7 @@ const stateOf = (parent: AnalysisViewParent = parentOf()): State => {
};
const captureOf = (rows: readonly TimedCaptureRow[]): AnalysisViewParent =>
parentOf(timedCaptureEvidence(rows));
captureParent(timedCaptureEvidence(rows));
const viewOf = (state: State, tool: string) =>
state.views.find((view) => view.tool === tool);
@@ -266,7 +251,7 @@ it("leaves out of a type's state a read made while the write its value changed a
},
});
const state = stateOf(
parentOf(
captureParent(
analysisViewCaptureEvidence(
environmentManifestCaptureFixture([
exchange([
@@ -753,7 +738,7 @@ it("holds a deleted path's initial non-entity read as a document", () => {
});
it("orders a scenario capture by request order and needs its response bodies", () => {
const state = stateOf(parentOf(scenarioCaptureEvidence()));
const state = stateOf(captureParent(scenarioCaptureEvidence()));
expect(state.timeline).toBe("record-order");
expect(state.types).toEqual([
{
@@ -776,7 +761,7 @@ it("orders a scenario capture by request order and needs its response bodies", (
}),
);
expect(
projectAnalysisView(parentOf(headersOnly), {
projectAnalysisView(captureParent(headersOnly), {
kind: "environment-state",
template_rules: [],
}),
@@ -792,7 +777,7 @@ it("orders a scenario capture by request order and needs its response bodies", (
it("refuses when extraction would exceed the projection budget", () => {
expect(
projectAnalysisView(
parentOf(),
captureParent(),
{ kind: "environment-state", template_rules: [...ALL_RULES] },
{ state: new EnvironmentStateAccumulator(160 * 1024, [...ALL_RULES]) },
),
@@ -1426,7 +1411,7 @@ it.each<{
environmentManifestCaptureFixture(entries),
);
expect(capture.records.map((record) => record.reported)).toEqual(entries);
const state = stateOf(parentOf(analysisViewCaptureEvidence(capture)));
const state = stateOf(captureParent(analysisViewCaptureEvidence(capture)));
expect(state.documents).toEqual([
{
tool: "get_settings",
@@ -1485,7 +1470,7 @@ it.each([
environmentManifestCaptureFixture(entries),
);
const before = structuredClone(capture);
const state = stateOf(parentOf(analysisViewCaptureEvidence(capture)));
const state = stateOf(captureParent(analysisViewCaptureEvidence(capture)));
expect(state.timeline).toBe("recorded-start-time");
expect(state.limitations).toContainEqual(
expect.stringMatching(/request duration.*completion.*overlap.*unknown/iu),
@@ -2007,7 +1992,7 @@ it.each([
environmentManifestCaptureFixture(entries),
);
const original = structuredClone(capture.records);
const state = stateOf(parentOf(analysisViewCaptureEvidence(capture)));
const state = stateOf(captureParent(analysisViewCaptureEvidence(capture)));
expect(state.timeline).toBe("recorded-start-time");
expect(state.documents).toEqual([
{
@@ -2039,7 +2024,7 @@ it.each(["not a URL", "", 42, undefined])(
if (url === undefined) delete request.url;
else request.url = url;
const before = structuredClone(capture);
const state = stateOf(parentOf(analysisViewCaptureEvidence(capture)));
const state = stateOf(captureParent(analysisViewCaptureEvidence(capture)));
expect(state.types).toMatchObject([
{ init_before_ordinal: 1, volatile_fields: [] },
]);
@@ -2121,7 +2106,7 @@ it.each([
reported.startedDateTime = `2026-10-20T09:00:01.${"1230".repeat(2000)}Z`;
// The budget admits the original capture, but not a separate timing expansion.
const result = projectAnalysisView(
parentOf(analysisViewCaptureEvidence(capture)),
captureParent(analysisViewCaptureEvidence(capture)),
{ kind: "environment-state", template_rules: [...ALL_RULES] },
{ state: new EnvironmentStateAccumulator(256 * 1024, [...ALL_RULES]) },
);
@@ -2152,7 +2137,7 @@ it.each([{}, { status: "unknown" }, { status: null }])(
const reported = ownedJsonObjectSchema.parse(capture.records[1]!.reported);
ownedJsonObjectSchema.parse(reported.request).url = "not a URL";
reported.response = ownedJsonObjectSchema.parse(response);
const state = stateOf(parentOf(analysisViewCaptureEvidence(capture)));
const state = stateOf(captureParent(analysisViewCaptureEvidence(capture)));
expect(state.types).toMatchObject([
{ init_before_ordinal: 1, volatile_fields: [] },
]);
@@ -14,16 +14,9 @@ import {
environmentStateViewOf,
renamedBook,
type Book,
planOf,
} from "../../../tests/fixtures/environmentStateWrites.js";
const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error(`No write plan for ${tool}`);
return plan;
};
const RENAMED_AT_3 = renamedBook(FIRST_BOOK, "Renamed Book", 3);
/** A book with an `archived` flag, which an item action sets. */
@@ -1,5 +1,6 @@
import type { JsonValue } from "../jsonValue.js";
import {
succeeded,
ownMember,
at,
requestJson,
@@ -14,7 +15,7 @@ import {
type StateToolFacts,
type StateView,
} from "./environmentStateRules.js";
import { entityTarget, succeeded } from "./environmentStateWriteChecks.js";
import { entityTarget } from "./environmentStateWriteChecks.js";
import type { WriteIo } from "./environmentStateWriteEffects.js";
import {
pathValuesOf,
@@ -1,5 +1,6 @@
import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js";
import {
succeeded,
ownMember,
at,
isObject,
@@ -14,7 +15,6 @@ import {
collectionTarget,
entityTarget,
itemTarget,
succeeded,
type SimulatedState,
} from "./environmentStateWriteChecks.js";
import type { WriteIo } from "./environmentStateWriteEffects.js";
@@ -1,26 +1,15 @@
import { describe, expect, it } from "vitest";
import {
timedCaptureEvidence,
type TimedCaptureRow,
} from "../../../tests/fixtures/analysisView.js";
import type { TimedCaptureRow } from "../../../tests/fixtures/analysisView.js";
import {
FIRST_BOOK,
SECOND_BOOK,
THIRD_BOOK,
environmentStateViewOf,
renamedBook,
type Book,
planOf,
} from "../../../tests/fixtures/environmentStateWrites.js";
const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error(`No write plan for ${tool}`);
return plan;
};
/** A book as its item reads show it, with the shelves its write responses leave out. */
const shelved = (entry: Book): Book => ({
...entry,
@@ -6,6 +6,7 @@ import {
environmentEntityKey,
} from "./environmentStateIdentity.js";
import {
succeeded,
ownMember,
at,
decodedSegment,
@@ -333,10 +334,6 @@ export class SimulatedState {
export const isAbsence = (status: number | null): boolean =>
status === 400 || status === 404 || status === 410;
/** A 2xx record: the only status whose response shows what a request did. */
export const succeeded = (record: StateRecordFacts): boolean =>
record.status !== null && record.status >= 200 && record.status < 300;
/** Hand a base recording's body and a read's body to `use` together, parsing a recording once when both are the same. */
export const withBodies = <T>(
withBody: <U>(ordinal: number, use: (body: JsonValue | undefined) => U) => U,
@@ -1,6 +1,7 @@
import type { StateRecordChronology } from "./StateRecordChronology.js";
import type { JsonValue } from "../jsonValue.js";
import {
succeeded,
ownMember,
collectionPathOf,
IDENTITY_NAMES,
@@ -34,9 +35,6 @@ const MIN_ID_LENGTH = 4;
/** Identity names that describe an entity rather than number it, so its own suffix-named id may sit beside them. */
const DESCRIPTIVE_NAMES: ReadonlySet<string> = new Set(["key", "slug", "name"]);
const succeeded = (record: StateRecordFacts): boolean =>
record.status !== null && record.status >= 200 && record.status < 300;
/** An object's identity-named scalar members. */
const identityValues = (object: JsonValue | undefined): string[] =>
isObject(object)
@@ -1,6 +1,7 @@
import type { JsonValue } from "../jsonValue.js";
import type { StateRecordChronology } from "./StateRecordChronology.js";
import {
succeeded,
ownMember,
at,
collectionPathOf,
@@ -221,9 +222,6 @@ export const projectedRead = (
});
};
const succeeded = (record: StateRecordFacts): boolean =>
record.status !== null && record.status >= 200 && record.status < 300;
/**
* The first later read, before the next write, that shows a written entity: an item read of
* `id` when given, else an item read of an unheld id or a collection read listing exactly one.
@@ -1,4 +1,5 @@
import {
succeeded,
ownMember,
at,
isObject,
@@ -11,11 +12,10 @@ import {
type StateRecordFacts,
type StateView,
} from "./environmentStateRules.js";
import {
succeeded,
type CheckOutcome,
type ReadBodies,
type SimulatedState,
import type {
CheckOutcome,
ReadBodies,
SimulatedState,
} from "./environmentStateWriteChecks.js";
/**
@@ -1,10 +1,7 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import {
timedCaptureEvidence,
type TimedCaptureRow,
} from "../../../tests/fixtures/analysisView.js";
import type { TimedCaptureRow } from "../../../tests/fixtures/analysisView.js";
import {
LISTED_LABEL_ROWS,
READ_BACK_TAG_ROWS,
@@ -14,15 +11,7 @@ import {
slugSaveRows,
slugOnlySaveRows,
} from "../../../tests/fixtures/environmentStateWriteViews.js";
import { environmentStateViewOf } from "../../../tests/fixtures/environmentStateWrites.js";
const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error(`No plan for ${tool}`);
return plan;
};
import { planOf } from "../../../tests/fixtures/environmentStateWrites.js";
describe("creates whose answer shows the entity otherwise than reads do", () => {
it.each(["123456", "123457"])(
@@ -537,10 +537,11 @@ describe("values the application assigns", () => {
});
});
const itemView = (rows: readonly TimedCaptureRow[]) =>
stateOf(rows).views.find((view) => view.tool === "get_books_by_id");
describe("write coverage limits", () => {
const WHOLE_BOOK = ["slug", "created_at", "updated_at"];
const itemView = (rows: readonly TimedCaptureRow[]) =>
stateOf(rows).views.find((view) => view.tool === "get_books_by_id");
it("notes no omission from a read that asked for some fields, nor from one of a book the state no longer holds", () => {
const projected: TimedCaptureRow[] = [
@@ -699,8 +700,6 @@ describe("omissions shown by reads the gate ignores", () => {
const requiresDetail = {
required_fields: expect.arrayContaining(["detail"]),
};
const itemView = (rows: readonly TimedCaptureRow[]) =>
stateOf(rows).views.find((view) => view.tool === "get_books_by_id");
expect([running, outgrown].map(itemView)).toMatchObject([
requiresDetail,
requiresDetail,
@@ -1321,6 +1320,11 @@ describe("list reads with query values no line recorded", () => {
});
});
const bookOnShelf = (id: number, name: string, shelf: string, at: number) => ({
...book(id, name, bookClock(at)),
shelf,
});
describe("list reads on a line they did not name", () => {
const first = { ...FIRST_BOOK, shelf: "a" };
const second = { ...SECOND_BOOK, shelf: "b" };
@@ -1358,14 +1362,10 @@ describe("list reads on a line they did not name", () => {
});
it("lets a sorted read whose values tie fix a create's position, as its order shows where the create put it", () => {
const shelved = (id: number, name: string, shelf: string, at: number) => ({
...book(id, name, bookClock(at)),
shelf,
});
const beta = shelved(1, "Beta", "a", 0);
const mike = shelved(2, "Mike", "b", 1);
const zulu = shelved(3, "Zulu", "a", 2);
const alpha = shelved(4, "Alpha", "a", 6);
const beta = bookOnShelf(1, "Beta", "a", 0);
const mike = bookOnShelf(2, "Mike", "b", 1);
const zulu = bookOnShelf(3, "Zulu", "a", 2);
const alpha = bookOnShelf(4, "Alpha", "a", 6);
const rows: TimedCaptureRow[] = [
["GET", "/api/books", [beta, mike, zulu]],
["GET", "/api/books?shelf=a", [beta, zulu]],
@@ -1421,14 +1421,10 @@ describe("list reads on a line they did not name", () => {
});
it("leaves a create's position open after a sorted read, for a later whole list to settle", () => {
const shelved = (id: number, name: string, shelf: string, at: number) => ({
...book(id, name, bookClock(at)),
shelf,
});
const beta = shelved(1, "Beta", "a", 0);
const mike = shelved(2, "Mike", "b", 1);
const zulu = shelved(3, "Zulu", "a", 2);
const alpha = shelved(4, "Alpha", "a", 6);
const beta = bookOnShelf(1, "Beta", "a", 0);
const mike = bookOnShelf(2, "Mike", "b", 1);
const zulu = bookOnShelf(3, "Zulu", "a", 2);
const alpha = bookOnShelf(4, "Alpha", "a", 6);
const rows: TimedCaptureRow[] = [
["GET", "/api/books", [beta, mike, zulu]],
["GET", "/api/books?shelf=a", [beta, zulu]],
@@ -1450,13 +1446,9 @@ describe("list reads on a line they did not name", () => {
});
describe("what a list query read shows of writes", () => {
const shelved = (id: number, name: string, shelf: string, at: number) => ({
...book(id, name, bookClock(at)),
shelf,
});
const beta = shelved(1, "Beta", "a", 0);
const mike = shelved(2, "Mike", "b", 1);
const zulu = shelved(3, "Zulu", "a", 2);
const beta = bookOnShelf(1, "Beta", "a", 0);
const mike = bookOnShelf(2, "Mike", "b", 1);
const zulu = bookOnShelf(3, "Zulu", "a", 2);
const INIT: TimedCaptureRow[] = [
["GET", "/api/books", [beta, mike, zulu]],
["GET", "/api/books?shelf=a", [beta, zulu]],
@@ -1488,7 +1480,7 @@ describe("what a list query read shows of writes", () => {
});
it("leaves a create's position open after a filter that lists only its book, for a later whole list to settle", () => {
const alpha = shelved(4, "Alpha", "c", 5);
const alpha = bookOnShelf(4, "Alpha", "c", 5);
const rows: TimedCaptureRow[] = [
...INIT,
["POST", "/api/books", alpha, 201, { name: "Alpha", shelf: "c" }],
@@ -1838,8 +1830,6 @@ describe("item lines first recorded after a write, against the lines left", () =
["GET", "/api/books/3", created],
late,
];
const itemView = (rows: TimedCaptureRow[]) =>
stateOf(rows).views.find((view) => view.tool === "get_books_by_id");
it("compares a later line with the lines left after variants are dropped, not the dropped ones", () => {
// The early `expand` line is dropped as a variant, so `include` shows a shelf the lines left never show.
+3
View File
@@ -0,0 +1,3 @@
/** Whether a reported HTTP status is in the successful (2xx) class. */
export const isSuccessfulHttpStatus = (status: number | null): boolean =>
status !== null && status >= 200 && status < 300;
+16
View File
@@ -1,3 +1,4 @@
import type { AnalysisViewParent } from "../../src/domain/analysisView/analysisViewParent.js";
import { unknownTarget } from "../../src/domain/targetIdentity.js";
import type { JsonValue } from "../../src/domain/jsonValue.js";
import {
@@ -317,6 +318,21 @@ export const environmentManifestCaptureFixture = (
export const environmentStateCaptureFixture = () =>
environmentManifestCaptureFixture(environmentStateHar().log.entries);
/** Parent facts passed to a view of captured traffic. */
export const captureParent = (
evidence: Evidence = analysisViewCaptureEvidence(
environmentStateCaptureFixture(),
),
): AnalysisViewParent => ({
predicateType: evidence.predicate_type,
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: evidence.normalized_result,
subject: evidence.subject,
limitations: [],
parameters: evidence.parameters,
});
/** One synthetic exchange. A string response body is recorded as written. */
export type TimedCaptureRow = readonly [
method: string,
+15 -12
View File
@@ -6,6 +6,8 @@ import type { JsonValue } from "../../src/domain/jsonValue.js";
import {
analysisViewCaptureEvidence,
environmentManifestCaptureFixture,
captureParent,
timedCaptureEvidence,
type TimedCaptureRow,
} from "./analysisView.js";
@@ -451,19 +453,20 @@ export const environmentStateViewOf = (
capture: Evidence,
templateRules: readonly TemplateRule[] = [],
): EnvironmentStateView => {
const result = projectAnalysisView(
{
predicateType: capture.predicate_type,
evidenceId: capture.evidence_id,
operation: capture.operation,
normalizedResult: capture.normalized_result,
subject: capture.subject,
limitations: [],
parameters: capture.parameters,
},
{ kind: "environment-state", template_rules: [...templateRules] },
);
const result = projectAnalysisView(captureParent(capture), {
kind: "environment-state",
template_rules: [...templateRules],
});
if (!result.ok || result.value.kind !== "environment-state")
throw new Error("Expected an environment state");
return result.value;
};
/** The write plan inferred for one tool from a timed capture. */
export const planOf = (rows: readonly TimedCaptureRow[], tool: string) => {
const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find(
(candidate) => candidate.tool === tool,
);
if (plan === undefined) throw new Error(`No write plan for ${tool}`);
return plan;
};