refactor(apple): group artifact producers and verification (#952)
* refactor(apple): group artifact producers and verification * test(apple): run affected native plist CLI regressions
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { collectInterfaceBuilderResourceKeys } from "./AppleAssetCatalogAnalysis.js";
|
||||
|
||||
describe("Apple asset catalog application workflow", () => {
|
||||
it("joins only explicit resource-key fields with archive provenance", () => {
|
||||
expect(
|
||||
collectInterfaceBuilderResourceKeys([
|
||||
{
|
||||
id: "ib:Main.nib:object:2",
|
||||
kind: "resource",
|
||||
name: "Decorative image",
|
||||
attributes: {
|
||||
imageName: "Toolbar",
|
||||
title: "not-an-asset-key",
|
||||
image: 42,
|
||||
},
|
||||
evidence: [
|
||||
{
|
||||
artifact_path: "Contents/Resources/Main.nib",
|
||||
artifact_sha256: "d".repeat(64),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "ib:Main.nib:object:3",
|
||||
kind: "control",
|
||||
name: "Toolbar",
|
||||
attributes: { title: "not-an-asset-key" },
|
||||
evidence: [],
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
sourceNodeId: "ib:Main.nib:object:2",
|
||||
sourcePath: "Contents/Resources/Main.nib",
|
||||
sourceArchiveSha256: "d".repeat(64),
|
||||
field: "imageName",
|
||||
key: "Toolbar",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
|
||||
import {
|
||||
appleAssetCatalogInputSchema,
|
||||
parseAppleAssetCatalogRecords,
|
||||
projectAppleAssetCatalogPage,
|
||||
} from "../../domain/apple/appleAssetCatalog.js";
|
||||
import { execFileOutput } from "../../process/ExecFileOutput.js";
|
||||
|
||||
const ASSETUTIL = "/usr/bin/assetutil";
|
||||
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
|
||||
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
|
||||
const RESOURCE_KEY_FIELDS = new Set([
|
||||
"image",
|
||||
"imageName",
|
||||
"image_name",
|
||||
"resourceName",
|
||||
"resource_name",
|
||||
"assetName",
|
||||
"asset_name",
|
||||
"UIImageName",
|
||||
"NSImageName",
|
||||
]);
|
||||
|
||||
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
|
||||
export const analyzeAppleAssetCatalogs = async (input: {
|
||||
readonly bundlePath: string;
|
||||
readonly targetSha256: string;
|
||||
readonly page?: unknown;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly runAssetUtil?: (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<string>;
|
||||
}) => {
|
||||
if (process.platform !== "darwin" && input.runAssetUtil === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Apple asset catalog inspection requires macOS assetutil",
|
||||
);
|
||||
const page = appleAssetCatalogInputSchema.parse(input.page ?? {});
|
||||
const reader = new DirectoryArtifactReader(input.bundlePath);
|
||||
const catalogs: {
|
||||
path: string;
|
||||
sha256: string;
|
||||
records: ReturnType<typeof parseAppleAssetCatalogRecords>;
|
||||
}[] = [];
|
||||
let totalMetadataBytes = 0;
|
||||
try {
|
||||
for await (const entry of reader.entries(input.signal)) {
|
||||
if (entry.kind !== "file" || !entry.path.endsWith("Assets.car")) continue;
|
||||
const inspected = await inspectAssetCatalogEntry({
|
||||
reader,
|
||||
entry,
|
||||
runAssetUtil: input.runAssetUtil ?? runAssetUtil,
|
||||
...(input.signal === undefined ? {} : { signal: input.signal }),
|
||||
});
|
||||
totalMetadataBytes += inspected.metadataBytes;
|
||||
if (totalMetadataBytes > MAX_TOTAL_METADATA_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Combined asset catalog metadata exceeds ${MAX_TOTAL_METADATA_BYTES} bytes`,
|
||||
);
|
||||
catalogs.push(inspected.catalog);
|
||||
}
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
if (catalogs.length === 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"No compiled Assets.car catalogs were found in the app bundle",
|
||||
);
|
||||
const interfaceBuilder = await analyzeInterfaceBuilderBundle({
|
||||
bundlePath: input.bundlePath,
|
||||
targetSha256: input.targetSha256,
|
||||
...(input.signal === undefined ? {} : { signal: input.signal }),
|
||||
});
|
||||
const resourceReferences = collectInterfaceBuilderResourceKeys(
|
||||
interfaceBuilder.graph.nodes,
|
||||
);
|
||||
const result = projectAppleAssetCatalogPage({
|
||||
targetSha256: input.targetSha256,
|
||||
catalogs,
|
||||
offset: page.offset,
|
||||
limit: page.limit,
|
||||
resourceReferences,
|
||||
});
|
||||
return {
|
||||
...result,
|
||||
limitations: [
|
||||
...result.limitations,
|
||||
"Exact resource-key joins use only recognized image or asset key fields on decoded Interface Builder resource objects; other archive resource references are not inferred.",
|
||||
...(interfaceBuilder.graph.truncated
|
||||
? [
|
||||
"Interface Builder resource-key joins may be incomplete because the decoded UI graph was truncated.",
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const inspectAssetCatalogEntry = async (input: {
|
||||
readonly reader: DirectoryArtifactReader;
|
||||
readonly entry: import("../ArtifactReader.js").ArtifactEntry;
|
||||
readonly runAssetUtil: (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<string>;
|
||||
readonly signal?: AbortSignal;
|
||||
}) => {
|
||||
const { entry, reader, signal } = input;
|
||||
const sha256 = await digestBounded(reader, entry, signal);
|
||||
const before = await lstat(entry.adapterKey);
|
||||
if (
|
||||
entry.sourceIdentity === undefined ||
|
||||
before.dev !== entry.sourceIdentity.device ||
|
||||
before.ino !== entry.sourceIdentity.inode
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Asset catalog changed before inspection: ${entry.path}`,
|
||||
);
|
||||
const output = await input.runAssetUtil(entry.adapterKey, signal);
|
||||
const after = await lstat(entry.adapterKey);
|
||||
if (
|
||||
before.dev !== after.dev ||
|
||||
before.ino !== after.ino ||
|
||||
before.size !== after.size ||
|
||||
(await digestBounded(reader, entry, signal)) !== sha256
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Asset catalog changed during inspection: ${entry.path}`,
|
||||
);
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(output);
|
||||
} catch (cause: unknown) {
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`assetutil returned invalid JSON for ${entry.path}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
try {
|
||||
return {
|
||||
catalog: {
|
||||
path: entry.path,
|
||||
sha256,
|
||||
records: parseAppleAssetCatalogRecords(parsed),
|
||||
},
|
||||
metadataBytes: Buffer.byteLength(output, "utf8"),
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`assetutil returned an unsupported record for ${entry.path}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Return only explicit image or asset fields from decoded resource objects. */
|
||||
export const collectInterfaceBuilderResourceKeys = (
|
||||
nodes: readonly {
|
||||
readonly id: string;
|
||||
readonly kind: string;
|
||||
readonly name?: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
readonly evidence: readonly {
|
||||
readonly artifact_path: string | null;
|
||||
readonly artifact_sha256: string | null;
|
||||
}[];
|
||||
}[],
|
||||
) =>
|
||||
nodes.flatMap((node) => {
|
||||
const source = node.evidence.find(
|
||||
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
|
||||
);
|
||||
const sourcePath = source?.artifact_path;
|
||||
const sourceArchiveSha256 = source?.artifact_sha256;
|
||||
if (sourcePath == null || sourceArchiveSha256 == null) return [];
|
||||
return Object.entries(node.attributes).flatMap(([field, value]) =>
|
||||
RESOURCE_KEY_FIELDS.has(field) &&
|
||||
typeof value === "string" &&
|
||||
value.length > 0
|
||||
? [
|
||||
{
|
||||
sourceNodeId: node.id,
|
||||
sourcePath,
|
||||
sourceArchiveSha256,
|
||||
field,
|
||||
key: value,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
});
|
||||
|
||||
const runAssetUtil = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
return (
|
||||
await execFileOutput(ASSETUTIL, ["--info", path], {
|
||||
timeout: 60_000,
|
||||
maxBuffer: MAX_CATALOG_BYTES,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
})
|
||||
).stdout;
|
||||
} catch (cause: unknown) {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Asset catalog inspection cancelled",
|
||||
);
|
||||
const code =
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
throw new ArtifactReaderFailure(
|
||||
code === "ENOENT"
|
||||
? "unavailable"
|
||||
: code === "ETIMEDOUT" || code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
|
||||
? "limit"
|
||||
: "io",
|
||||
`assetutil failed${code === undefined ? "" : ` (${String(code)})`}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const digestBounded = async (
|
||||
reader: DirectoryArtifactReader,
|
||||
entry: import("../ArtifactReader.js").ArtifactEntry,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
if (entry.declaredSize === null || entry.declaredSize > MAX_CATALOG_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Asset catalog exceeds ${MAX_CATALOG_BYTES} bytes: ${entry.path}`,
|
||||
);
|
||||
const stream = await reader.open(entry, signal);
|
||||
const hash = createHash("sha256");
|
||||
let length = 0;
|
||||
for await (const chunk of stream) {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Asset catalog inspection cancelled",
|
||||
);
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
length += bytes.length;
|
||||
if (length > MAX_CATALOG_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Asset catalog exceeds byte limit: ${entry.path}`,
|
||||
);
|
||||
hash.update(bytes);
|
||||
}
|
||||
return hash.digest("hex");
|
||||
};
|
||||
@@ -0,0 +1,410 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { parseBinary } from "plist";
|
||||
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { projectPlistValue } from "../../domain/apple/plistValue.js";
|
||||
import {
|
||||
omittedPrototypeKeysLimitation,
|
||||
parseXmlPropertyList,
|
||||
} from "../../domain/propertyListKeys.js";
|
||||
import { decodeNibArchive, type NibArchiveDocument } from "./NibArchive.js";
|
||||
import type { ArtifactEntry } from "../ArtifactReader.js";
|
||||
import {
|
||||
buildInterfaceBuilderAnalysis,
|
||||
interfaceBuilderLimitsSchema,
|
||||
type InterfaceBuilderDocumentInput,
|
||||
} from "../../domain/apple/interfaceBuilderGraph.js";
|
||||
import {
|
||||
mergeNibHierarchies,
|
||||
projectNibViewHierarchy,
|
||||
type NibHierarchyNode,
|
||||
} from "./NibViewHierarchy.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../../domain/jsonValue.js";
|
||||
|
||||
const MAX_DOCUMENT_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/** Decode compiled Interface Builder archives from a local app bundle. */
|
||||
export const analyzeInterfaceBuilderBundle = async (input: {
|
||||
readonly bundlePath: string;
|
||||
readonly targetSha256: string;
|
||||
readonly limits?: unknown;
|
||||
readonly signal?: AbortSignal;
|
||||
}) => {
|
||||
const limits = interfaceBuilderLimitsSchema.parse(input.limits ?? {});
|
||||
const reader = new DirectoryArtifactReader(input.bundlePath);
|
||||
const documents: InterfaceBuilderDocumentInput[] = [];
|
||||
const invalid: string[] = [];
|
||||
const incompleteHierarchies = new Map<string, number>();
|
||||
const prototypeKeyOmissions = new Map<string, number>();
|
||||
let omitted = 0;
|
||||
let attempted = 0;
|
||||
try {
|
||||
for await (const entry of reader.entries(input.signal)) {
|
||||
if (entry.kind !== "file" || !isInterfaceBuilderArchive(entry.path))
|
||||
continue;
|
||||
if (attempted >= limits.max_documents) {
|
||||
omitted += 1;
|
||||
continue;
|
||||
}
|
||||
attempted += 1;
|
||||
try {
|
||||
const bytes = await readEntry(reader, entry, input.signal);
|
||||
const nib =
|
||||
bytes.subarray(0, 10).toString("ascii") === "NIBArchive"
|
||||
? projectNibArchive(decodeNibArchive(bytes))
|
||||
: null;
|
||||
const { value: raw, omittedPrototypeKeys } =
|
||||
nib === null
|
||||
? decodePlist(bytes)
|
||||
: { value: nib.raw, omittedPrototypeKeys: 0 };
|
||||
if (nib !== null && nib.omitted > 0)
|
||||
incompleteHierarchies.set(entry.path, nib.omitted);
|
||||
if (omittedPrototypeKeys > 0)
|
||||
prototypeKeyOmissions.set(entry.path, omittedPrototypeKeys);
|
||||
const documentHash = createHash("sha256").update(bytes).digest("hex");
|
||||
documents.push({
|
||||
relativePath: entry.path,
|
||||
archiveSha256: documentHash,
|
||||
documentKind: entry.path.includes(".storyboardc/")
|
||||
? "storyboard_scene"
|
||||
: "nib",
|
||||
raw,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
if (input.signal?.aborted === true) throw cause;
|
||||
invalid.push(
|
||||
`${entry.path}: ${cause instanceof Error ? cause.message : "archive decode failed"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
const result = buildInterfaceBuilderAnalysis({
|
||||
targetSha256: input.targetSha256,
|
||||
toolVersion: "rea-interface-builder/1",
|
||||
documents,
|
||||
limits,
|
||||
});
|
||||
return finalizeHierarchyCoverage(result, {
|
||||
incompleteHierarchies,
|
||||
prototypeKeyOmissions,
|
||||
invalid,
|
||||
attempted,
|
||||
omitted,
|
||||
});
|
||||
};
|
||||
|
||||
const finalizeHierarchyCoverage = (
|
||||
result: ReturnType<typeof buildInterfaceBuilderAnalysis>,
|
||||
counts: {
|
||||
incompleteHierarchies: ReadonlyMap<string, number>;
|
||||
prototypeKeyOmissions: ReadonlyMap<string, number>;
|
||||
invalid: readonly string[];
|
||||
attempted: number;
|
||||
omitted: number;
|
||||
},
|
||||
) => {
|
||||
const { incompleteHierarchies, prototypeKeyOmissions, invalid } = counts;
|
||||
const archiveDecodePartial =
|
||||
invalid.length > 0 || prototypeKeyOmissions.size > 0;
|
||||
return {
|
||||
...result,
|
||||
documents: result.documents.map((document) => ({
|
||||
...document,
|
||||
hierarchy_complete:
|
||||
document.hierarchy_complete &&
|
||||
!incompleteHierarchies.has(document.relative_path),
|
||||
})),
|
||||
graph: {
|
||||
...result.graph,
|
||||
coverage: [
|
||||
...result.graph.coverage.map((facet) => {
|
||||
const omitted = incompleteHierarchies.get(
|
||||
facet.facet.replace(/^hierarchy:/u, ""),
|
||||
);
|
||||
return facet.facet.startsWith("hierarchy:") && omitted !== undefined
|
||||
? {
|
||||
...facet,
|
||||
status: "partial" as const,
|
||||
reason: "serialized_view_hierarchy_incomplete",
|
||||
omitted: facet.omitted + omitted,
|
||||
}
|
||||
: facet;
|
||||
}),
|
||||
{
|
||||
facet: "archive_decode",
|
||||
status: archiveDecodePartial
|
||||
? ("partial" as const)
|
||||
: ("complete" as const),
|
||||
reason:
|
||||
invalid.length > 0
|
||||
? "one_or_more_archives_invalid"
|
||||
: prototypeKeyOmissions.size > 0
|
||||
? "dictionary_entries_omitted"
|
||||
: null,
|
||||
examined: counts.attempted,
|
||||
omitted: counts.omitted,
|
||||
},
|
||||
],
|
||||
truncated:
|
||||
result.graph.truncated ||
|
||||
counts.omitted > 0 ||
|
||||
archiveDecodePartial ||
|
||||
incompleteHierarchies.size > 0,
|
||||
},
|
||||
limitations: [
|
||||
...result.limitations,
|
||||
"Compiled Interface Builder archives are private serialized object graphs. The decoder reports only recognized keyed-archive objects and connections; unrecognized object classes and fields remain unknown.",
|
||||
...(incompleteHierarchies.size === 0
|
||||
? []
|
||||
: [
|
||||
"Some serialized hierarchy links could not be projected within the bounded hierarchy; their parentage remains unknown.",
|
||||
]),
|
||||
...(invalid.length === 0
|
||||
? []
|
||||
: [
|
||||
`Some Interface Builder archives could not be decoded: ${invalid.slice(0, 16).join("; ")}`,
|
||||
]),
|
||||
...[...prototypeKeyOmissions].map(
|
||||
([path, count]) => `${path}: ${omittedPrototypeKeysLimitation(count)}`,
|
||||
),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
/** Project decoded NIB records into the same bounded graph input as ibtool. */
|
||||
const projectNibArchive = (archive: NibArchiveDocument) => {
|
||||
const byId = new Map(archive.objects.map((object) => [object.id, object]));
|
||||
const dereference = (value: JsonValue | undefined): JsonValue | undefined => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return value;
|
||||
const ref = value.$nib_object_ref;
|
||||
if (typeof ref !== "number") return value;
|
||||
const target = byId.get(ref);
|
||||
if (target === undefined) return undefined;
|
||||
if (target.class_name.replace(/\0+$/u, "") === "NSString") {
|
||||
const data = target.values["NS.bytes"];
|
||||
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
|
||||
const encoded = data.$nib_data_base64;
|
||||
if (typeof encoded === "string")
|
||||
return Buffer.from(encoded, "base64").toString("utf8");
|
||||
}
|
||||
}
|
||||
return { objectID: String(ref) };
|
||||
};
|
||||
const referencedString = (value: JsonValue | undefined): string | null => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return null;
|
||||
const ref = value.$nib_object_ref;
|
||||
if (typeof ref !== "number") return null;
|
||||
const target = byId.get(ref);
|
||||
const data = target?.values["NS.bytes"];
|
||||
if (target?.class_name.replace(/\0+$/u, "") !== "NSString") return null;
|
||||
if (typeof data !== "object" || data === null || Array.isArray(data))
|
||||
return null;
|
||||
const encoded = data.$nib_data_base64;
|
||||
return typeof encoded === "string"
|
||||
? Buffer.from(encoded, "base64").toString("utf8")
|
||||
: null;
|
||||
};
|
||||
const runtimeClass = (objectId: number): string | null => {
|
||||
const object = byId.get(objectId);
|
||||
if (object === undefined) return null;
|
||||
const storedClass = object.class_name.replace(/\0+$/u, "");
|
||||
if (storedClass === "NSClassSwapper")
|
||||
return referencedString(object.values.NSClassName) ?? storedClass;
|
||||
return storedClass === "UIClassSwapper"
|
||||
? (referencedString(object.values.UIClassName) ?? storedClass)
|
||||
: storedClass;
|
||||
};
|
||||
const objects = Object.fromEntries(
|
||||
archive.objects
|
||||
.filter((object) => {
|
||||
const name = runtimeClass(object.id) ?? "";
|
||||
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector|UIRuntime\w*Connection)$/u.test(
|
||||
name,
|
||||
);
|
||||
})
|
||||
.map((object) => {
|
||||
const className =
|
||||
runtimeClass(object.id) ?? object.class_name.replace(/\0+$/u, "");
|
||||
const strings = Object.entries(object.values).flatMap(
|
||||
([key, value]) => {
|
||||
const resolved = dereference(value);
|
||||
return typeof resolved === "string" ? [[key, resolved]] : [];
|
||||
},
|
||||
);
|
||||
const name =
|
||||
strings.find(([key]) =>
|
||||
/(?:title|label|identifier|accessibility|name|contents)/iu.test(
|
||||
key ?? "",
|
||||
),
|
||||
)?.[1] ?? className;
|
||||
return [
|
||||
String(object.id),
|
||||
{
|
||||
customClass: className,
|
||||
label: name,
|
||||
objectID: String(object.id),
|
||||
nibValues: Object.fromEntries(
|
||||
Object.entries(object.values).map(([key, value]) => [
|
||||
key,
|
||||
dereference(value) ?? null,
|
||||
]),
|
||||
),
|
||||
},
|
||||
];
|
||||
}),
|
||||
);
|
||||
const connections: Record<string, JsonValue[]> = {};
|
||||
const hierarchy: NibHierarchyNode[] = [];
|
||||
const reference = (value: JsonValue | undefined): number | null => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return null;
|
||||
return typeof value.$nib_object_ref === "number"
|
||||
? value.$nib_object_ref
|
||||
: null;
|
||||
};
|
||||
for (const object of archive.objects) {
|
||||
const className = object.class_name.replace(/\0+$/u, "");
|
||||
// AppKit connectors use NS-prefixed keys; UIKit's runtime outlet and
|
||||
// event connections use UI-prefixed keys with the same roles.
|
||||
const uiKit = /^UIRuntime\w*Connection$/u.test(className);
|
||||
if (!uiKit && !className.includes("Connector")) continue;
|
||||
const values = object.values;
|
||||
const source = reference(uiKit ? values.UISource : values.NSSource);
|
||||
if (source === null) continue;
|
||||
const destination = reference(
|
||||
uiKit ? values.UIDestination : values.NSDestination,
|
||||
);
|
||||
const label = referencedString(uiKit ? values.UILabel : values.NSLabel);
|
||||
const type = className.includes("Outlet")
|
||||
? "outlet"
|
||||
: className.includes("Control") || className.includes("Event")
|
||||
? "action"
|
||||
: className;
|
||||
const eventMask = values.UIEventMask;
|
||||
// The source is the outlet owner or the sending control; the destination
|
||||
// is the outlet value or the action target, and a nil target is the
|
||||
// first responder.
|
||||
(connections[String(source)] ??= []).push({
|
||||
type,
|
||||
"destination-id": destination === null ? null : String(destination),
|
||||
label,
|
||||
source_id: String(source),
|
||||
archive_object_id: String(object.id),
|
||||
...(typeof eventMask === "number" ? { ui_event_mask: eventMask } : {}),
|
||||
});
|
||||
}
|
||||
let hierarchyOmitted = 0;
|
||||
const hierarchyFor = (
|
||||
objectId: number,
|
||||
seen: Set<number>,
|
||||
depth: number,
|
||||
): NibHierarchyNode | null => {
|
||||
if (depth > 32 || seen.has(objectId)) {
|
||||
hierarchyOmitted += 1;
|
||||
return null;
|
||||
}
|
||||
const object = byId.get(objectId);
|
||||
if (object === undefined) {
|
||||
hierarchyOmitted += 1;
|
||||
return null;
|
||||
}
|
||||
const nextSeen = new Set(seen).add(objectId);
|
||||
const children: NibHierarchyNode[] = [];
|
||||
for (const [key, value] of Object.entries(object.values)) {
|
||||
if (!/(?:subviews|contentview|childviewcontrollers|view)$/iu.test(key))
|
||||
continue;
|
||||
const direct = reference(value);
|
||||
if (direct === null) continue;
|
||||
const target = byId.get(direct);
|
||||
if (target === undefined) {
|
||||
hierarchyOmitted += 1;
|
||||
continue;
|
||||
}
|
||||
if (/array|set/iu.test(target.class_name)) {
|
||||
for (const candidate of Object.values(target.values)) {
|
||||
const child = reference(candidate);
|
||||
const nested =
|
||||
child === null ? null : hierarchyFor(child, nextSeen, depth + 1);
|
||||
if (nested !== null) children.push(nested);
|
||||
}
|
||||
} else {
|
||||
const nested = hierarchyFor(direct, nextSeen, depth + 1);
|
||||
if (nested !== null) children.push(nested);
|
||||
}
|
||||
}
|
||||
return { objectID: String(objectId), children };
|
||||
};
|
||||
const ibData = archive.objects.find(
|
||||
({ class_name }) => class_name.replace(/\0+$/u, "") === "NSIBObjectData",
|
||||
);
|
||||
const rootId = reference(ibData?.values.NSRoot);
|
||||
const hierarchyRoots = rootId === null ? [] : [rootId];
|
||||
for (const hierarchyRoot of hierarchyRoots) {
|
||||
const root = hierarchyFor(hierarchyRoot, new Set(), 0);
|
||||
if (root !== null) hierarchy.push(root);
|
||||
}
|
||||
const viewHierarchy = projectNibViewHierarchy(
|
||||
archive.objects,
|
||||
new Set(Object.keys(objects).map(Number)),
|
||||
);
|
||||
const merged = mergeNibHierarchies(hierarchy, viewHierarchy.hierarchy ?? []);
|
||||
return {
|
||||
omitted: viewHierarchy.omitted + hierarchyOmitted + merged.omitted,
|
||||
raw: jsonValueSchema.parse({
|
||||
"com.apple.ibtool.document.objects": objects,
|
||||
"com.apple.ibtool.document.connections": connections,
|
||||
"com.apple.ibtool.document.hierarchy": merged.hierarchy,
|
||||
"com.apple.ibtool.document.classes": Object.fromEntries(
|
||||
archive.classes.map((name) => [name.replace(/\0+$/u, ""), {}]),
|
||||
),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const isInterfaceBuilderArchive = (path: string): boolean => {
|
||||
const lower = path.toLowerCase();
|
||||
return lower.endsWith(".nib") || lower.endsWith("/objects.nib");
|
||||
};
|
||||
|
||||
const readEntry = async (
|
||||
reader: DirectoryArtifactReader,
|
||||
entry: ArtifactEntry,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Buffer> => {
|
||||
if (entry.declaredSize !== null && entry.declaredSize > MAX_DOCUMENT_BYTES)
|
||||
throw new RangeError(
|
||||
"archive exceeds the 64 MiB per-document decode limit",
|
||||
);
|
||||
const stream = await reader.open(entry, signal);
|
||||
const chunks: Buffer[] = [];
|
||||
let length = 0;
|
||||
for await (const chunk of stream) {
|
||||
const bytes = Buffer.isBuffer(chunk)
|
||||
? chunk
|
||||
: Buffer.from(chunk as Uint8Array);
|
||||
length += bytes.length;
|
||||
if (length > MAX_DOCUMENT_BYTES) {
|
||||
stream.destroy();
|
||||
throw new RangeError(
|
||||
"archive exceeded the 64 MiB per-document decode limit",
|
||||
);
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
return Buffer.concat(chunks, length);
|
||||
};
|
||||
|
||||
/** Project decoded plist data and dates while retaining omitted-key coverage. */
|
||||
const decodePlist = (
|
||||
bytes: Buffer,
|
||||
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
|
||||
const { value, omittedPrototypeKeys } =
|
||||
bytes.subarray(0, 8).toString("ascii") === "bplist00"
|
||||
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
|
||||
: parseXmlPropertyList(bytes.toString("utf8"));
|
||||
return { value: projectPlistValue(value).value, omittedPrototypeKeys };
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { build, buildBinary } from "plist";
|
||||
import { decodeKeyedArchiveBytes } from "./KeyedArchiveReader.js";
|
||||
|
||||
const archive = {
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$objects: [
|
||||
"$null",
|
||||
{
|
||||
$class: { UID: 4 },
|
||||
child: { UID: 2 },
|
||||
shared: { UID: 2 },
|
||||
self: { UID: 1 },
|
||||
conditional: { UID: 0 },
|
||||
broken: { UID: 90 },
|
||||
},
|
||||
{ "NS.objects": [{ UID: 1 }, { UID: 3 }] },
|
||||
"value",
|
||||
{ $classname: "UnknownModel", $classes: ["UnknownModel", "NSObject"] },
|
||||
],
|
||||
$top: { root: { UID: 1 }, other: { UID: 2 } },
|
||||
};
|
||||
describe("inert keyed archive decoding", () => {
|
||||
it("preserves CF$UID, malformed references and original pagination identities", () => {
|
||||
const bytes = Buffer.from(
|
||||
build({
|
||||
...archive,
|
||||
$objects: [
|
||||
"$null",
|
||||
{ bad: { CF$UID: -1 }, valid: { CF$UID: 2 }, broken: { CF$UID: 90 } },
|
||||
"value",
|
||||
],
|
||||
}),
|
||||
);
|
||||
const graph = decodeKeyedArchiveBytes(bytes, {
|
||||
root: "root",
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
});
|
||||
expect(graph.roots).toEqual({ root: { UID: 1 } });
|
||||
expect(graph.objects.map(({ id }) => id)).toEqual([1]);
|
||||
expect(graph.next_offset).toBe(2);
|
||||
expect(graph.references).toContainEqual(
|
||||
expect.objectContaining({ source: 1, target: 90, status: "unresolved" }),
|
||||
);
|
||||
expect(graph.references).toContainEqual(
|
||||
expect.objectContaining({ source: 1, target: null, status: "malformed" }),
|
||||
);
|
||||
expect(graph.references).toContainEqual(
|
||||
expect.objectContaining({ source: 1, target: 2, status: "resolved" }),
|
||||
);
|
||||
});
|
||||
it.each([
|
||||
["binary", { UID: 1 }],
|
||||
["XML", { CF$UID: 1 }],
|
||||
] as const)(
|
||||
"resolves a %s root encoded under a UID-named key",
|
||||
(format, reference) => {
|
||||
const named = {
|
||||
...archive,
|
||||
$objects: ["$null", "payload"],
|
||||
$top: { UID: reference, CF$UID: reference },
|
||||
};
|
||||
const graph = decodeKeyedArchiveBytes(
|
||||
Buffer.from(format === "binary" ? buildBinary(named) : build(named)),
|
||||
{ offset: 0, limit: 2 },
|
||||
);
|
||||
expect(
|
||||
graph.references.map(({ source, path, target, status }) => ({
|
||||
source,
|
||||
path,
|
||||
target,
|
||||
status,
|
||||
})),
|
||||
).toEqual([
|
||||
{ source: null, path: ["CF$UID"], target: 1, status: "resolved" },
|
||||
{ source: null, path: ["UID"], target: 1, status: "resolved" },
|
||||
]);
|
||||
const selected = decodeKeyedArchiveBytes(
|
||||
Buffer.from(format === "binary" ? buildBinary(named) : build(named)),
|
||||
{ root: "UID", offset: 0, limit: 2 },
|
||||
);
|
||||
expect(selected.references).toEqual([
|
||||
expect.objectContaining({ path: ["UID"], target: 1 }),
|
||||
]);
|
||||
},
|
||||
);
|
||||
it("reports an XML archive dictionary keyed __proto__ as omitted", () => {
|
||||
const xml = build({ ...archive, $objects: ["$null", "value"] }).replace(
|
||||
"<key>$top</key>",
|
||||
"<key>__proto__</key><string>x</string><key>$top</key>",
|
||||
);
|
||||
const graph = decodeKeyedArchiveBytes(Buffer.from(xml), {
|
||||
offset: 0,
|
||||
limit: 2,
|
||||
});
|
||||
expect(graph.objects.map(({ value }) => value)).toEqual(["$null", "value"]);
|
||||
expect(graph.limitations).toContain(
|
||||
"1 dictionary entry keyed __proto__ was omitted because REA results cannot represent that key.",
|
||||
);
|
||||
});
|
||||
it("rejects missing roots, malformed plist, and non-keyed archives", () => {
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(Buffer.from("bplist00bad"), {
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(Buffer.from(build({ ...archive, $top: {} })), {
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow("roots");
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(Buffer.from(build({ plain: true })), {
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow("NSKeyedArchiver");
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(Buffer.from(buildBinary(archive)), {
|
||||
root: "missing",
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow("does not exist");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { TextDecoder } from "node:util";
|
||||
import { parseBinary } from "plist";
|
||||
import { z } from "zod";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { projectPlistValue } from "../../domain/apple/plistValue.js";
|
||||
import {
|
||||
omittedPrototypeKeysLimitation,
|
||||
parseXmlPropertyList,
|
||||
} from "../../domain/propertyListKeys.js";
|
||||
import {
|
||||
keyedArchiveInputSchema,
|
||||
keyedArchiveResultSchema,
|
||||
projectKeyedArchive,
|
||||
} from "../../domain/apple/keyedArchive.js";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||
|
||||
const MAX_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/** Parse inert plist bytes, preserving data and dates with explicit typed values. */
|
||||
export const decodeKeyedArchiveBytes = (
|
||||
bytes: Buffer,
|
||||
selection: { root?: string | undefined; offset: number; limit: number },
|
||||
) => {
|
||||
if (bytes.length > MAX_BYTES)
|
||||
throw new RangeError("Keyed archive exceeds 64 MiB");
|
||||
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
|
||||
const parsed = binary
|
||||
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
|
||||
: parseXmlPropertyList(decodeXmlPlistText(bytes));
|
||||
const graph = projectKeyedArchive(normalizePlist(parsed.value), selection);
|
||||
return {
|
||||
archive_format: binary ? ("binary-plist" as const) : ("xml-plist" as const),
|
||||
...graph,
|
||||
limitations: [
|
||||
...graph.limitations,
|
||||
...(parsed.omittedPrototypeKeys === 0
|
||||
? []
|
||||
: [omittedPrototypeKeysLimitation(parsed.omittedPrototypeKeys)]),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const decodeXmlPlistText = (bytes: Buffer): string => {
|
||||
const encoding =
|
||||
bytes[0] === 0xff && bytes[1] === 0xfe
|
||||
? "utf-16le"
|
||||
: bytes[0] === 0xfe && bytes[1] === 0xff
|
||||
? "utf-16be"
|
||||
: "utf-8";
|
||||
const text = new TextDecoder(encoding, { fatal: true }).decode(bytes);
|
||||
const declared = /^<\?xml\s[^?]*\bencoding\s*=\s*["']([^"']+)["']/u
|
||||
.exec(text)?.[1]
|
||||
?.toLowerCase();
|
||||
if (
|
||||
declared !== undefined &&
|
||||
((encoding !== "utf-8" && declared !== encoding && declared !== "utf-16") ||
|
||||
(encoding === "utf-8" && declared.startsWith("utf-16")))
|
||||
)
|
||||
throw new TypeError("XML encoding declaration disagrees with its bytes");
|
||||
return text;
|
||||
};
|
||||
|
||||
const normalizePlist = (value: unknown): JsonValue => {
|
||||
const projected = projectPlistValue(value);
|
||||
if (projected.unknownRealCount > 0)
|
||||
throw new RangeError("Keyed archive contains a non-finite real");
|
||||
return projected.value;
|
||||
};
|
||||
|
||||
/** Read exactly one regular, contained bundle entry without following symlinks. */
|
||||
export const inspectBundleKeyedArchive = async (input: {
|
||||
bundlePath: string;
|
||||
targetSha256: string;
|
||||
parameters: unknown;
|
||||
signal?: AbortSignal;
|
||||
}) => {
|
||||
const selected = keyedArchiveInputSchema.parse(input.parameters);
|
||||
if (
|
||||
selected.path.startsWith("/") ||
|
||||
selected.path
|
||||
.split("/")
|
||||
.some((part) => part === ".." || part === "." || part.length === 0)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Archive path must be a canonical relative bundle path",
|
||||
);
|
||||
const reader = new DirectoryArtifactReader(input.bundlePath);
|
||||
try {
|
||||
for await (const entry of reader.entries(input.signal)) {
|
||||
if (entry.path !== selected.path) continue;
|
||||
if (entry.kind !== "file")
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Archive must be a regular file, not a symlink or directory",
|
||||
);
|
||||
if ((entry.declaredSize ?? 0) > MAX_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Keyed archive exceeds 64 MiB",
|
||||
);
|
||||
const stream = await reader.open(entry, input.signal);
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
for await (const chunk of stream) {
|
||||
if (input.signal?.aborted) {
|
||||
stream.destroy();
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Archive inspection cancelled",
|
||||
);
|
||||
}
|
||||
const bytes = z.instanceof(Buffer).parse(chunk);
|
||||
size += bytes.length;
|
||||
if (size > MAX_BYTES) {
|
||||
stream.destroy();
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Keyed archive exceeds 64 MiB",
|
||||
);
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
const bytes = Buffer.concat(chunks, size);
|
||||
try {
|
||||
return keyedArchiveResultSchema.parse({
|
||||
target_sha256: input.targetSha256,
|
||||
archive_path: entry.path,
|
||||
archive_sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
...decodeKeyedArchiveBytes(bytes, selected),
|
||||
});
|
||||
} catch (cause) {
|
||||
throw new ArtifactReaderFailure(
|
||||
cause instanceof RangeError ? "limit" : "format",
|
||||
"Cannot decode selected Foundation keyed archive",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Archive not found in bundle: ${selected.path}`,
|
||||
);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
/** Encode a minimal NIBArchive object table for decoder and projection tests. */
|
||||
export const encodeNibArchiveFixture = (input: {
|
||||
readonly classes: readonly string[];
|
||||
readonly objects: readonly {
|
||||
readonly classIndex: number;
|
||||
readonly values: Readonly<
|
||||
Record<string, number | string | boolean | null | { ref: number }>
|
||||
>;
|
||||
}[];
|
||||
}): Buffer => {
|
||||
const keys = [
|
||||
...new Set(input.objects.flatMap(({ values }) => Object.keys(values))),
|
||||
];
|
||||
const keyIndex = new Map(keys.map((key, index) => [key, index]));
|
||||
const valueRecords = input.objects.flatMap(({ values }) =>
|
||||
Object.entries(values).map(([key, value]) =>
|
||||
Buffer.concat([varint(keyIndex.get(key) ?? 0), encodeValue(value)]),
|
||||
),
|
||||
);
|
||||
let valueStart = 0;
|
||||
const records = input.objects.map(({ classIndex, values }) => {
|
||||
const count = Object.keys(values).length;
|
||||
const result = Buffer.concat([
|
||||
varint(classIndex),
|
||||
varint(valueStart),
|
||||
varint(count),
|
||||
]);
|
||||
valueStart += count;
|
||||
return result;
|
||||
});
|
||||
const objects = Buffer.concat(records);
|
||||
const encodedKeys = Buffer.concat(
|
||||
keys.map((key) =>
|
||||
Buffer.concat([varint(Buffer.byteLength(key)), Buffer.from(key)]),
|
||||
),
|
||||
);
|
||||
const values = Buffer.concat(valueRecords);
|
||||
const classes = Buffer.concat(
|
||||
input.classes.map((name) => {
|
||||
const bytes = Buffer.from(name);
|
||||
return Buffer.concat([varint(bytes.length), varint(0), bytes]);
|
||||
}),
|
||||
);
|
||||
const objectsOffset = 50;
|
||||
const keysOffset = objectsOffset + objects.length;
|
||||
const valuesOffset = keysOffset + encodedKeys.length;
|
||||
const classesOffset = valuesOffset + values.length;
|
||||
const header = Buffer.alloc(50);
|
||||
header.write("NIBArchive", 0, "ascii");
|
||||
header.writeUInt32LE(1, 10);
|
||||
header.writeUInt32LE(10, 14);
|
||||
header.writeUInt32LE(input.objects.length, 18);
|
||||
header.writeUInt32LE(objectsOffset, 22);
|
||||
header.writeUInt32LE(keys.length, 26);
|
||||
header.writeUInt32LE(keysOffset, 30);
|
||||
header.writeUInt32LE(valueStart, 34);
|
||||
header.writeUInt32LE(valuesOffset, 38);
|
||||
header.writeUInt32LE(input.classes.length, 42);
|
||||
header.writeUInt32LE(classesOffset, 46);
|
||||
return Buffer.concat([header, objects, encodedKeys, values, classes]);
|
||||
};
|
||||
|
||||
const varint = (value: number): Buffer => {
|
||||
const bytes: number[] = [];
|
||||
let remaining = value;
|
||||
do {
|
||||
let byte = remaining & 0x7f;
|
||||
remaining >>>= 7;
|
||||
if (remaining === 0) byte |= 0x80;
|
||||
bytes.push(byte);
|
||||
} while (remaining > 0);
|
||||
return Buffer.from(bytes);
|
||||
};
|
||||
|
||||
const encodeValue = (
|
||||
value: number | string | boolean | null | { ref: number },
|
||||
): Buffer => {
|
||||
if (typeof value === "boolean") return Buffer.from([value ? 4 : 5]);
|
||||
if (value === null) return Buffer.from([9]);
|
||||
if (typeof value === "number") {
|
||||
const bytes = Buffer.alloc(5);
|
||||
bytes[0] = 2;
|
||||
bytes.writeInt32LE(value, 1);
|
||||
return bytes;
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
const bytes = Buffer.alloc(5);
|
||||
bytes[0] = 10;
|
||||
bytes.writeUInt32LE(value.ref, 1);
|
||||
return bytes;
|
||||
}
|
||||
const data = Buffer.from(value);
|
||||
return Buffer.concat([Buffer.from([8]), varint(data.length), data]);
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decodeNibArchive } from "./NibArchive.js";
|
||||
import { encodeNibArchiveFixture as encodeArchive } from "./NibArchive.fixture.js";
|
||||
|
||||
describe("NIBArchive decoder", () => {
|
||||
it("decodes bounded object, key, class, and reference tables", () => {
|
||||
const archive = encodeArchive({
|
||||
classes: ["NSView\0", "NSString\0"],
|
||||
objects: [
|
||||
{ classIndex: 0, values: { child: { ref: 1 }, enabled: true } },
|
||||
{ classIndex: 1, values: { text: "Button" } },
|
||||
],
|
||||
});
|
||||
const decoded = decodeNibArchive(archive);
|
||||
|
||||
expect(decoded.objects).toEqual([
|
||||
{
|
||||
id: 0,
|
||||
class_name: "NSView",
|
||||
values: { child: { $nib_object_ref: 1 }, enabled: true },
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
class_name: "NSString",
|
||||
values: { text: { $nib_data_base64: "QnV0dG9u" } },
|
||||
},
|
||||
]);
|
||||
expect(decoded.coder_version).toBe(10);
|
||||
});
|
||||
|
||||
it("rejects malformed references and unsupported format versions", () => {
|
||||
const valid = encodeArchive({
|
||||
classes: ["NSObject"],
|
||||
objects: [{ classIndex: 0, values: {} }],
|
||||
});
|
||||
const invalidVersion = Buffer.from(valid);
|
||||
invalidVersion.writeUInt32LE(2, 10);
|
||||
expect(() => decodeNibArchive(invalidVersion)).toThrow(/Unsupported/u);
|
||||
const invalidReference = encodeArchive({
|
||||
classes: ["NSObject"],
|
||||
objects: [{ classIndex: 0, values: { child: { ref: 4 } } }],
|
||||
});
|
||||
expect(() => decodeNibArchive(invalidReference)).toThrow(
|
||||
/object reference/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,430 @@
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { TextDecoder } from "node:util";
|
||||
|
||||
const MAGIC = Buffer.from("NIBArchive", "ascii");
|
||||
const MAX_RECORDS = 1_000_000;
|
||||
|
||||
interface NibObjectRecord {
|
||||
readonly class_index: number;
|
||||
readonly value_start: number;
|
||||
readonly value_count: number;
|
||||
}
|
||||
|
||||
interface NibValueRecord {
|
||||
readonly key_index: number;
|
||||
readonly value: JsonValue;
|
||||
}
|
||||
|
||||
/** Parsed NIBArchive payload with the original object indices preserved. */
|
||||
export interface NibArchiveDocument {
|
||||
readonly format_version: number;
|
||||
readonly coder_version: number;
|
||||
readonly object_count: number;
|
||||
readonly connection_object_count: number;
|
||||
readonly objects: readonly {
|
||||
readonly id: number;
|
||||
readonly class_name: string;
|
||||
readonly values: Readonly<Record<string, JsonValue>>;
|
||||
}[];
|
||||
readonly classes: readonly string[];
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Decode Apple's length-prefixed NIBArchive representation without loading UI classes. */
|
||||
export const decodeNibArchive = (bytes: Buffer): NibArchiveDocument => {
|
||||
if (bytes.length < 50 || !bytes.subarray(0, MAGIC.length).equals(MAGIC))
|
||||
throw new TypeError("NIBArchive magic or header is invalid");
|
||||
|
||||
const formatVersion = readU32(bytes, 10);
|
||||
const coderVersion = readU32(bytes, 14);
|
||||
if (formatVersion !== 1)
|
||||
throw new TypeError(
|
||||
`Unsupported NIBArchive format version ${formatVersion}`,
|
||||
);
|
||||
|
||||
const objectCount = readCount(bytes, 18, "object");
|
||||
const objectsOffset = readOffset(bytes, 22, bytes.length, "object");
|
||||
const keyCount = readCount(bytes, 26, "key");
|
||||
const keysOffset = readOffset(bytes, 30, bytes.length, "key");
|
||||
const valueCount = readCount(bytes, 34, "value");
|
||||
const valuesOffset = readOffset(bytes, 38, bytes.length, "value");
|
||||
const classCount = readCount(bytes, 42, "class");
|
||||
const classesOffset = readOffset(bytes, 46, bytes.length, "class");
|
||||
|
||||
assertOrderedOffsets(bytes.length, [
|
||||
objectsOffset,
|
||||
keysOffset,
|
||||
valuesOffset,
|
||||
classesOffset,
|
||||
]);
|
||||
const objectRecords = parseObjects(
|
||||
bytes,
|
||||
objectsOffset,
|
||||
keysOffset,
|
||||
objectCount,
|
||||
valueCount,
|
||||
classCount,
|
||||
);
|
||||
const keys = parseStrings(bytes, keysOffset, valuesOffset, keyCount, "key");
|
||||
const classes = parseClasses(bytes, classesOffset, bytes.length, classCount);
|
||||
const neededValues = valueIndexes(objectRecords, valueCount);
|
||||
const values = parseValues(
|
||||
bytes,
|
||||
valuesOffset,
|
||||
classesOffset,
|
||||
valueCount,
|
||||
keyCount,
|
||||
neededValues,
|
||||
);
|
||||
for (const { value } of values.values()) {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
!Array.isArray(value) &&
|
||||
typeof value.$nib_object_ref === "number" &&
|
||||
value.$nib_object_ref >= objectCount
|
||||
)
|
||||
throw new TypeError(
|
||||
"NIBArchive object reference is outside the object table",
|
||||
);
|
||||
}
|
||||
const objects = objectRecords.flatMap((object, id) => {
|
||||
const className = classes[object.class_index];
|
||||
if (className === undefined) return [];
|
||||
const fields: Record<string, JsonValue> = {};
|
||||
for (
|
||||
let index = object.value_start;
|
||||
index < object.value_start + object.value_count;
|
||||
index += 1
|
||||
) {
|
||||
const value = values.get(index);
|
||||
if (value === undefined) continue;
|
||||
const key = keys[value.key_index];
|
||||
if (key !== undefined) fields[key] = value.value;
|
||||
}
|
||||
return [{ id, class_name: className, values: fields }];
|
||||
});
|
||||
let connectionObjectCount = 0;
|
||||
for (const object of objects)
|
||||
if (
|
||||
/(?:Outlet|Connection|Segue|ActionConnection)/iu.test(object.class_name)
|
||||
)
|
||||
connectionObjectCount += 1;
|
||||
|
||||
return {
|
||||
format_version: formatVersion,
|
||||
coder_version: coderVersion,
|
||||
object_count: objectCount,
|
||||
connection_object_count: connectionObjectCount,
|
||||
objects,
|
||||
classes,
|
||||
limitations: [
|
||||
"NIBArchive class extensions and unsupported value encodings are retained as unavailable fields.",
|
||||
"NIBArchive object relationships are decoded from serialized references; runtime object creation and execution are not performed.",
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const parseObjects = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
count: number,
|
||||
valueCount: number,
|
||||
classCount: number,
|
||||
): NibObjectRecord[] => {
|
||||
const cursor = { offset: start };
|
||||
const output: NibObjectRecord[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const classIndex = readVarint(bytes, cursor, end);
|
||||
const valueStart = readVarint(bytes, cursor, end);
|
||||
const countForObject = readVarint(bytes, cursor, end);
|
||||
if (
|
||||
classIndex >= classCount ||
|
||||
valueStart > valueCount ||
|
||||
countForObject > valueCount - valueStart
|
||||
)
|
||||
throw new TypeError(
|
||||
`NIBArchive object ${index} references an invalid table range`,
|
||||
);
|
||||
output.push({
|
||||
class_index: classIndex,
|
||||
value_start: valueStart,
|
||||
value_count: countForObject,
|
||||
});
|
||||
}
|
||||
if (cursor.offset > end)
|
||||
throw new TypeError("NIBArchive object table overlaps the next table");
|
||||
return output;
|
||||
};
|
||||
|
||||
const parseStrings = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
count: number,
|
||||
label: string,
|
||||
): string[] => {
|
||||
const cursor = { offset: start };
|
||||
const output: string[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const length = readVarint(bytes, cursor, end);
|
||||
const next = checkedEnd(cursor.offset, length, end, `${label} ${index}`);
|
||||
const value = decodeUtf8(bytes, cursor.offset, next, `${label} ${index}`);
|
||||
cursor.offset = next;
|
||||
output.push(value);
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
const parseClasses = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
count: number,
|
||||
): string[] => {
|
||||
const cursor = { offset: start };
|
||||
const output: string[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const length = readVarint(bytes, cursor, end);
|
||||
const extraCount = readVarint(bytes, cursor, end);
|
||||
if (extraCount > 16)
|
||||
throw new TypeError(
|
||||
`NIBArchive class ${index} has too many extension values`,
|
||||
);
|
||||
ensureRange(
|
||||
cursor.offset,
|
||||
extraCount * 4,
|
||||
end,
|
||||
`class ${index} extensions`,
|
||||
);
|
||||
cursor.offset += extraCount * 4;
|
||||
const next = checkedEnd(cursor.offset, length, end, `class ${index}`);
|
||||
const name = decodeUtf8(
|
||||
bytes,
|
||||
cursor.offset,
|
||||
next,
|
||||
`class ${index}`,
|
||||
).replace(/\0+$/u, "");
|
||||
cursor.offset = next;
|
||||
output.push(name);
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
const parseValues = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
count: number,
|
||||
keyCount: number,
|
||||
needed: ReadonlySet<number>,
|
||||
): Map<number, NibValueRecord> => {
|
||||
const cursor = { offset: start };
|
||||
const output = new Map<number, NibValueRecord>();
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const keyIndex = readVarint(bytes, cursor, end);
|
||||
if (keyIndex >= keyCount)
|
||||
throw new TypeError(
|
||||
`NIBArchive value ${index} references an invalid key`,
|
||||
);
|
||||
ensureRange(cursor.offset, 1, end, `value ${index} type`);
|
||||
const type = bytes[cursor.offset++] ?? -1;
|
||||
const value = readValue(bytes, cursor, end, type, index);
|
||||
if (needed.has(index)) output.set(index, { key_index: keyIndex, value });
|
||||
}
|
||||
if (cursor.offset > end)
|
||||
throw new TypeError("NIBArchive value table overlaps the next table");
|
||||
return output;
|
||||
};
|
||||
|
||||
const readValue = (
|
||||
bytes: Buffer,
|
||||
cursor: { offset: number },
|
||||
end: number,
|
||||
type: number,
|
||||
index: number,
|
||||
): JsonValue => {
|
||||
switch (type) {
|
||||
case 0:
|
||||
ensureRange(cursor.offset, 1, end, `value ${index}`);
|
||||
return bytes.readInt8(cursor.offset++);
|
||||
case 1:
|
||||
ensureRange(cursor.offset, 2, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readInt16LE(cursor.offset);
|
||||
cursor.offset += 2;
|
||||
return value;
|
||||
}
|
||||
case 2:
|
||||
ensureRange(cursor.offset, 4, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readInt32LE(cursor.offset);
|
||||
cursor.offset += 4;
|
||||
return value;
|
||||
}
|
||||
case 3:
|
||||
ensureRange(cursor.offset, 8, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readBigInt64LE(cursor.offset);
|
||||
cursor.offset += 8;
|
||||
return value <= BigInt(Number.MAX_SAFE_INTEGER) &&
|
||||
value >= BigInt(Number.MIN_SAFE_INTEGER)
|
||||
? Number(value)
|
||||
: value.toString();
|
||||
}
|
||||
case 4:
|
||||
return true;
|
||||
case 5:
|
||||
return false;
|
||||
case 6:
|
||||
ensureRange(cursor.offset, 4, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readFloatLE(cursor.offset);
|
||||
cursor.offset += 4;
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
case 7:
|
||||
ensureRange(cursor.offset, 8, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readDoubleLE(cursor.offset);
|
||||
cursor.offset += 8;
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
case 8: {
|
||||
const length = readVarint(bytes, cursor, end);
|
||||
const next = checkedEnd(
|
||||
cursor.offset,
|
||||
length,
|
||||
end,
|
||||
`value ${index} data`,
|
||||
);
|
||||
const encoded = bytes.subarray(cursor.offset, next).toString("base64");
|
||||
cursor.offset = next;
|
||||
return { $nib_data_base64: encoded };
|
||||
}
|
||||
case 9:
|
||||
return null;
|
||||
case 10:
|
||||
ensureRange(cursor.offset, 4, end, `value ${index} reference`);
|
||||
{
|
||||
const objectIndex = bytes.readUInt32LE(cursor.offset);
|
||||
cursor.offset += 4;
|
||||
return { $nib_object_ref: objectIndex };
|
||||
}
|
||||
default:
|
||||
throw new TypeError(
|
||||
`NIBArchive value ${index} has unsupported type ${type}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const valueIndexes = (
|
||||
objects: readonly NibObjectRecord[],
|
||||
total: number,
|
||||
): ReadonlySet<number> => {
|
||||
const indexes = new Set<number>();
|
||||
for (const object of objects)
|
||||
for (
|
||||
let index = object.value_start;
|
||||
index < object.value_start + object.value_count;
|
||||
index += 1
|
||||
)
|
||||
indexes.add(index);
|
||||
if (indexes.size > total)
|
||||
throw new TypeError(
|
||||
"NIBArchive object value ranges exceed the value table",
|
||||
);
|
||||
return indexes;
|
||||
};
|
||||
|
||||
const readCount = (bytes: Buffer, offset: number, label: string): number => {
|
||||
const count = readU32(bytes, offset);
|
||||
if (count > MAX_RECORDS)
|
||||
throw new TypeError(`NIBArchive ${label} count exceeds the decoder bound`);
|
||||
return count;
|
||||
};
|
||||
|
||||
const readOffset = (
|
||||
bytes: Buffer,
|
||||
offset: number,
|
||||
fileLength: number,
|
||||
label: string,
|
||||
): number => {
|
||||
const value = readU32(bytes, offset);
|
||||
if (value < 50 || value > fileLength)
|
||||
throw new TypeError(`NIBArchive ${label} table offset is invalid`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const readU32 = (bytes: Buffer, offset: number): number => {
|
||||
ensureRange(offset, 4, bytes.length, "header");
|
||||
return bytes.readUInt32LE(offset);
|
||||
};
|
||||
|
||||
const decodeUtf8 = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
label: string,
|
||||
): string => {
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(
|
||||
bytes.subarray(start, end),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
throw new TypeError(`NIBArchive ${label} is not valid UTF-8`, {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const readVarint = (
|
||||
bytes: Buffer,
|
||||
cursor: { offset: number },
|
||||
end: number,
|
||||
): number => {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
ensureRange(cursor.offset, 1, end, "variable integer");
|
||||
const byte = bytes[cursor.offset++] ?? 0;
|
||||
value += (byte & 0x7f) * 2 ** shift;
|
||||
if ((byte & 0x80) !== 0) {
|
||||
if (value > 0x7fff_ffff)
|
||||
throw new TypeError("NIBArchive variable integer is out of range");
|
||||
return value;
|
||||
}
|
||||
shift += 7;
|
||||
}
|
||||
throw new TypeError("NIBArchive variable integer is too long");
|
||||
};
|
||||
|
||||
const checkedEnd = (
|
||||
start: number,
|
||||
length: number,
|
||||
limit: number,
|
||||
label: string,
|
||||
): number => {
|
||||
if (!Number.isSafeInteger(length) || length < 0 || start + length > limit)
|
||||
throw new TypeError(`NIBArchive ${label} exceeds its table`);
|
||||
return start + length;
|
||||
};
|
||||
|
||||
const ensureRange = (
|
||||
start: number,
|
||||
length: number,
|
||||
limit: number,
|
||||
label: string,
|
||||
): void => {
|
||||
checkedEnd(start, length, limit, label);
|
||||
};
|
||||
|
||||
const assertOrderedOffsets = (length: number, offsets: readonly number[]) => {
|
||||
let previous = 50;
|
||||
for (const offset of offsets) {
|
||||
if (offset < previous || offset > length)
|
||||
throw new TypeError("NIBArchive table offsets are out of order");
|
||||
previous = offset;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
mergeNibHierarchies,
|
||||
projectNibViewHierarchy,
|
||||
} from "./NibViewHierarchy.js";
|
||||
|
||||
const object = (id: number, parent?: number) => ({
|
||||
id,
|
||||
class_name: "NSView",
|
||||
values:
|
||||
parent === undefined ? {} : { NSSuperview: { $nib_object_ref: parent } },
|
||||
});
|
||||
|
||||
describe("serialized NIB view hierarchy bounds", () => {
|
||||
it("leaves archives without superview links to the legacy projection", () => {
|
||||
expect(projectNibViewHierarchy([object(0)], new Set([0]))).toEqual({
|
||||
hierarchy: null,
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the serialized parent direction and retains all sibling links", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy(
|
||||
[object(0), object(1, 0), object(2, 0)],
|
||||
new Set([0, 1, 2]),
|
||||
),
|
||||
).toEqual({
|
||||
hierarchy: [
|
||||
{
|
||||
objectID: "0",
|
||||
children: [
|
||||
{ objectID: "1", children: [] },
|
||||
{ objectID: "2", children: [] },
|
||||
],
|
||||
},
|
||||
],
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports missing parents without inventing parentage", () => {
|
||||
expect(projectNibViewHierarchy([object(0, 99)], new Set([0]))).toEqual({
|
||||
hierarchy: [],
|
||||
omitted: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a missing encoded window content view as incomplete", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy(
|
||||
[
|
||||
{
|
||||
id: 0,
|
||||
class_name: "NSWindowTemplate",
|
||||
values: { NSWindowView: { $nib_object_ref: 99 } },
|
||||
},
|
||||
],
|
||||
new Set([0]),
|
||||
),
|
||||
).toEqual({ hierarchy: [{ objectID: "0", children: [] }], omitted: 1 });
|
||||
});
|
||||
|
||||
it("marks unsupported serialized parent values as incomplete", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy(
|
||||
[{ id: 0, class_name: "NSView", values: { NSSuperview: "unknown" } }],
|
||||
new Set([0]),
|
||||
),
|
||||
).toEqual({ hierarchy: null, omitted: 1 });
|
||||
});
|
||||
|
||||
it("reports cyclic and self-referential parentage as incomplete", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy(
|
||||
[object(0, 1), object(1, 0), object(2, 2)],
|
||||
new Set([0, 1, 2]),
|
||||
),
|
||||
).toEqual({
|
||||
hierarchy: [],
|
||||
omitted: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not project children whose parent was not retained", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy([object(0), object(1, 0)], new Set([1])),
|
||||
).toEqual({
|
||||
hierarchy: [],
|
||||
omitted: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports nodes beyond the depth bound instead of claiming complete coverage", () => {
|
||||
const objects = Array.from({ length: 132 }, (_, id) =>
|
||||
object(id, id === 0 ? undefined : id - 1),
|
||||
);
|
||||
expect(
|
||||
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
|
||||
.omitted,
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it("reports nodes beyond the record bound", () => {
|
||||
const objects = Array.from({ length: 20_002 }, (_, id) =>
|
||||
object(id, id === 0 ? undefined : 0),
|
||||
);
|
||||
expect(
|
||||
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
|
||||
.omitted,
|
||||
).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("legacy NIB hierarchy preservation", () => {
|
||||
it("keeps encoded window parents while merging shared views only once", () => {
|
||||
const legacy = [
|
||||
{
|
||||
objectID: "window",
|
||||
children: [
|
||||
{ objectID: "view", children: [{ objectID: "first", children: [] }] },
|
||||
],
|
||||
},
|
||||
];
|
||||
const recovered = [
|
||||
{
|
||||
objectID: "view",
|
||||
children: [
|
||||
{ objectID: "first", children: [] },
|
||||
{ objectID: "second", children: [] },
|
||||
],
|
||||
},
|
||||
];
|
||||
expect(mergeNibHierarchies(legacy, recovered).hierarchy).toEqual([
|
||||
{
|
||||
objectID: "window",
|
||||
children: [
|
||||
{
|
||||
objectID: "view",
|
||||
children: [
|
||||
{ objectID: "first", children: [] },
|
||||
{ objectID: "second", children: [] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
it("moves an existing root under its encoded parent without duplicate visits", () => {
|
||||
expect(
|
||||
mergeNibHierarchies(
|
||||
[{ objectID: "child", children: [] }],
|
||||
[
|
||||
{
|
||||
objectID: "parent",
|
||||
children: [{ objectID: "child", children: [] }],
|
||||
},
|
||||
],
|
||||
),
|
||||
).toEqual({
|
||||
hierarchy: [
|
||||
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
|
||||
],
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
it("reports conflicting encoded parents rather than dropping a link silently", () => {
|
||||
const legacy = [
|
||||
{ objectID: "first", children: [{ objectID: "child", children: [] }] },
|
||||
];
|
||||
const recovered = [
|
||||
{ objectID: "second", children: [{ objectID: "child", children: [] }] },
|
||||
];
|
||||
expect(mergeNibHierarchies(legacy, recovered).omitted).toBe(1);
|
||||
});
|
||||
it("does not introduce a cycle when moving an existing root", () => {
|
||||
const legacy = [
|
||||
{ objectID: "child", children: [{ objectID: "parent", children: [] }] },
|
||||
];
|
||||
const recovered = [
|
||||
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
|
||||
];
|
||||
expect(mergeNibHierarchies(legacy, recovered)).toEqual({
|
||||
hierarchy: legacy,
|
||||
omitted: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { NibArchiveDocument } from "./NibArchive.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
|
||||
export type NibHierarchyNode = {
|
||||
objectID: string;
|
||||
children: NibHierarchyNode[];
|
||||
};
|
||||
|
||||
/** Project encoded view parents; archive owners are not inferred view parents. */
|
||||
export const projectNibViewHierarchy = (
|
||||
objects: NibArchiveDocument["objects"],
|
||||
retainedIds: ReadonlySet<number>,
|
||||
) => {
|
||||
const { parents, involved, invalid } = collectNibParents(
|
||||
objects,
|
||||
retainedIds,
|
||||
);
|
||||
if (parents.size === 0) return { hierarchy: null, omitted: invalid };
|
||||
const children = new Map<number, number[]>();
|
||||
for (const [child, parent] of parents) {
|
||||
if (!retainedIds.has(parent) || !retainedIds.has(child)) continue;
|
||||
const siblings = children.get(parent) ?? [];
|
||||
siblings.push(child);
|
||||
children.set(parent, siblings);
|
||||
}
|
||||
const roots: NibHierarchyNode[] = [];
|
||||
const pending: { id: number; depth: number; output: NibHierarchyNode[] }[] =
|
||||
[];
|
||||
for (const id of involved)
|
||||
if (!parents.has(id)) pending.push({ id, depth: 0, output: roots });
|
||||
const visited = new Set<number>();
|
||||
while (pending.length > 0) {
|
||||
const item = pending.pop();
|
||||
if (item === undefined) break;
|
||||
if (visited.has(item.id) || item.depth > 128 || visited.size >= 20_000)
|
||||
continue;
|
||||
visited.add(item.id);
|
||||
const node: NibHierarchyNode = { objectID: String(item.id), children: [] };
|
||||
item.output.push(node);
|
||||
for (const child of [...(children.get(item.id) ?? [])].reverse())
|
||||
pending.push({ id: child, depth: item.depth + 1, output: node.children });
|
||||
}
|
||||
return {
|
||||
hierarchy: roots,
|
||||
omitted: involved.size - visited.size + invalid,
|
||||
};
|
||||
};
|
||||
|
||||
/** Add encoded parent links once; conflicting legacy parents remain unknown. */
|
||||
export const mergeNibHierarchies = (
|
||||
legacy: NibHierarchyNode[],
|
||||
recovered: NibHierarchyNode[],
|
||||
) => {
|
||||
const existing = new Map<string, NibHierarchyNode>();
|
||||
const owners = new Map<string, NibHierarchyNode[]>();
|
||||
const parents = new Map<string, string>();
|
||||
const pending = legacy.map((node) => ({
|
||||
node,
|
||||
output: legacy,
|
||||
parent: null as string | null,
|
||||
}));
|
||||
while (pending.length > 0) {
|
||||
const entry = pending.pop();
|
||||
if (entry === undefined || existing.has(entry.node.objectID)) continue;
|
||||
existing.set(entry.node.objectID, entry.node);
|
||||
owners.set(entry.node.objectID, entry.output);
|
||||
if (entry.parent !== null) parents.set(entry.node.objectID, entry.parent);
|
||||
pending.push(
|
||||
...entry.node.children.map((node) => ({
|
||||
node,
|
||||
output: entry.node.children,
|
||||
parent: entry.node.objectID,
|
||||
})),
|
||||
);
|
||||
}
|
||||
let omitted = 0;
|
||||
const additions = recovered.map((node) => ({
|
||||
node,
|
||||
output: legacy,
|
||||
parent: null as string | null,
|
||||
}));
|
||||
while (additions.length > 0) {
|
||||
const entry = additions.pop();
|
||||
if (entry === undefined) break;
|
||||
let target = existing.get(entry.node.objectID);
|
||||
if (target === undefined) {
|
||||
target = { objectID: entry.node.objectID, children: [] };
|
||||
existing.set(target.objectID, target);
|
||||
entry.output.push(target);
|
||||
owners.set(target.objectID, entry.output);
|
||||
if (entry.parent !== null) parents.set(target.objectID, entry.parent);
|
||||
} else if (
|
||||
entry.parent !== null &&
|
||||
owners.get(target.objectID) !== entry.output
|
||||
) {
|
||||
const owner = owners.get(target.objectID);
|
||||
if (
|
||||
owner !== legacy ||
|
||||
wouldCycle(target.objectID, entry.parent, parents)
|
||||
) {
|
||||
omitted += 1;
|
||||
} else {
|
||||
owner.splice(owner.indexOf(target), 1);
|
||||
entry.output.push(target);
|
||||
owners.set(target.objectID, entry.output);
|
||||
parents.set(target.objectID, entry.parent);
|
||||
}
|
||||
}
|
||||
for (const node of [...entry.node.children].reverse())
|
||||
additions.push({
|
||||
node,
|
||||
output: target.children,
|
||||
parent: target.objectID,
|
||||
});
|
||||
}
|
||||
return { hierarchy: legacy, omitted };
|
||||
};
|
||||
|
||||
const wouldCycle = (
|
||||
child: string,
|
||||
parent: string,
|
||||
parents: ReadonlyMap<string, string>,
|
||||
): boolean => {
|
||||
const seen = new Set<string>();
|
||||
let current: string | undefined = parent;
|
||||
while (current !== undefined && !seen.has(current)) {
|
||||
if (current === child) return true;
|
||||
seen.add(current);
|
||||
current = parents.get(current);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const reference = (value: JsonValue | undefined): number | null => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return null;
|
||||
return typeof value.$nib_object_ref === "number"
|
||||
? value.$nib_object_ref
|
||||
: null;
|
||||
};
|
||||
|
||||
const collectNibParents = (
|
||||
objects: NibArchiveDocument["objects"],
|
||||
retainedIds: ReadonlySet<number>,
|
||||
) => {
|
||||
const parents = new Map<number, number>();
|
||||
const involved = new Set<number>();
|
||||
let invalid = 0;
|
||||
for (const object of objects) {
|
||||
if (!retainedIds.has(object.id)) continue;
|
||||
const child = reference(object.values.NSWindowView);
|
||||
if (
|
||||
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
|
||||
invalidReference(object.values.NSWindowView)
|
||||
)
|
||||
invalid += 1;
|
||||
if (
|
||||
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
|
||||
child !== null
|
||||
) {
|
||||
parents.set(child, object.id);
|
||||
involved.add(object.id);
|
||||
involved.add(child);
|
||||
}
|
||||
const parent = reference(object.values.NSSuperview);
|
||||
if (invalidReference(object.values.NSSuperview)) invalid += 1;
|
||||
if (parent === null) continue;
|
||||
parents.set(object.id, parent);
|
||||
involved.add(object.id);
|
||||
if (retainedIds.has(parent)) involved.add(parent);
|
||||
}
|
||||
return { parents, involved, invalid };
|
||||
};
|
||||
|
||||
const invalidReference = (value: JsonValue | undefined): boolean =>
|
||||
value !== undefined && value !== null && reference(value) === null;
|
||||
Reference in New Issue
Block a user