Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | 2x 35x 35x 1x 1x 4x 4x 34x 2x 33x 95646x 95620x 75568x 20020x 32x 36x 36x 36x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 201x 35x 34x 1x 1x 1x 35x 95683x 95683x 95683x 57x 57x 57x 95626x 95626x 95626x 95626x 95626x 95626x 95626x 95626x 6x 95626x 95619x 95619x 95626x 18555x 2x 2x 2x 18553x 95624x 32x 32x 27x 5x 95592x 95624x 166x 166x 166x 1x 1x 165x 35x 35x 66x 95626x 95626x 33x 55x 95625x | /**
* Chunked, cancelable search over the whole value (SPEC.md ยง4.4).
*
* Three properties that together are the point of this module:
*
* 1. **It searches the whole document**, not the visible rows โ a match
* inside a collapsed subtree is exactly the one you were looking for.
* 2. **It never holds the main thread.** Work is done in slices of
* `budgetMs`, with a real yield between them.
* 3. **It uses an explicit stack.** A 4.5 M-node document would overflow the
* call stack, and a recursive walk cannot be suspended and resumed across
* slices anyway.
*/
import {
childAccessor,
classify,
isContainerKind,
type ChildAccessor,
} from "../model/value";
import { now, scheduleYield } from "./scheduler";
import type {
JsonKind,
JsonPath,
JsonSearchOptions,
JsonSearchProgress,
JsonSearchResult,
PathSegment,
} from "../types";
/** How often the elapsed-time check runs. Checking every node costs more than it saves. */
const CLOCK_INTERVAL = 512;
interface Frame {
value: unknown;
kind: JsonKind;
accessor: ChildAccessor;
/** Next child to visit. */
cursor: number;
/** True when this container's child labels are content (object keys, Map keys). */
labelsAreKeys: boolean;
}
/** Build the predicate once; a regex compiled per node would dominate the scan. */
function buildMatcher(options: JsonSearchOptions): (text: string) => boolean {
const { query, caseSensitive = false, regex = false } = options;
if (regex) {
const compiled = new RegExp(query, caseSensitive ? "" : "i");
return (text) => {
compiled.lastIndex = 0;
return compiled.test(text);
};
}
if (caseSensitive) {
return (text) => text.includes(query);
}
const needle = query.toLowerCase();
return (text) => text.toLowerCase().includes(needle);
}
/**
* The searchable text of a leaf.
*
* Containers return `null`: their preview (`{ 3 keys }`) is our rendering, not
* the user's data, and matching it would produce hits nobody typed.
*/
function contentOf(value: unknown, kind: JsonKind): string | null {
switch (kind) {
case "string":
return value as string;
case "number":
case "boolean":
case "bigint":
return String(value);
case "null":
return "null";
case "undefined":
return "undefined";
case "date": {
const time = (value as Date).getTime();
return Number.isNaN(time) ? "Invalid Date" : (value as Date).toISOString();
}
default:
return null;
}
}
/**
* Search `data`, yielding to the browser between slices.
*
* @example
* ```ts
* const controller = new AbortController();
* const { paths, capped } = await searchJson(
* data,
* { query: "error", signal: controller.signal },
* (p) => setProgress(p),
* );
* ```
*/
export async function searchJson(
data: unknown,
options: JsonSearchOptions,
onProgress?: (progress: JsonSearchProgress) => void,
): Promise<JsonSearchResult> {
const {
matchKeys = true,
matchValues = true,
maxResults = 10_000,
budgetMs = 8,
signal,
} = options;
const paths: JsonPath[] = [];
if (options.query === "") {
onProgress?.({ scanned: 0, matches: 0, done: true, capped: false });
return { paths, capped: false, aborted: false };
}
const matches = buildMatcher(options);
const rootKind = classify(data);
// The frame stack and the path stack move together: pushing a frame always
// follows pushing that child's segment, so the current path is simply the
// path stack โ no per-node path allocation anywhere in the hot loop.
const frames: Frame[] = [];
const pathStack: PathSegment[] = [];
let scanned = 0;
let capped = false;
let aborted = false;
let sliceStart = now();
const report = (done: boolean) =>
onProgress?.({ scanned, matches: paths.length, done, capped });
if (isContainerKind(rootKind)) {
frames.push(makeFrame(data, rootKind));
} else {
scanned = 1;
const content = contentOf(data, rootKind);
Eif (matchValues && content !== null && matches(content)) paths.push([]);
}
while (frames.length > 0) {
Iif (signal?.aborted) {
aborted = true;
break;
}
const frame = frames[frames.length - 1]!;
if (frame.cursor >= frame.accessor.count) {
frames.pop();
if (frames.length > 0) pathStack.pop();
continue;
}
const index = frame.cursor++;
const segment = frame.accessor.keyAt(index);
const childValue = frame.accessor.valueAt(index);
const childKind = kindOf(childValue, frames);
scanned++;
pathStack.push(segment);
let hit = false;
if (matchKeys && frame.labelsAreKeys && matches(frame.accessor.labelAt(index))) {
hit = true;
}
if (!hit && matchValues) {
const content = contentOf(childValue, childKind);
if (content !== null && matches(content)) hit = true;
}
if (hit) {
if (paths.length >= maxResults) {
// Only now is the answer genuinely incomplete. Setting `capped` on the
// match that *reaches* the limit would report "first 10 000 only" for a
// document that has exactly 10 000 matches and no more.
capped = true;
pathStack.pop();
break;
}
paths.push(pathStack.slice());
}
if (childKind !== "circular" && isContainerKind(childKind)) {
const child = makeFrame(childValue, childKind);
if (child.accessor.count > 0) {
frames.push(child);
} else {
pathStack.pop();
}
} else {
pathStack.pop();
}
if (scanned % CLOCK_INTERVAL === 0 && now() - sliceStart >= budgetMs) {
report(false);
await scheduleYield();
if (signal?.aborted) {
aborted = true;
break;
}
sliceStart = now();
}
}
report(true);
return { paths, capped, aborted };
}
function makeFrame(value: unknown, kind: JsonKind): Frame {
return {
value,
kind,
accessor: childAccessor(value, kind),
cursor: 0,
// Array indices and Set positions are our addressing, not the user's
// content โ matching them would make every search for "1" return the
// entire document.
labelsAreKeys: kind === "object" || kind === "map",
};
}
/** Classify, reporting a cycle so the walk terminates on self-referential data. */
function kindOf(value: unknown, frames: readonly Frame[]): JsonKind {
const kind = classify(value);
if (value !== null && typeof value === "object") {
for (let i = frames.length - 1; i >= 0; i--) {
if (frames[i]!.value === value) return "circular";
}
}
return kind;
}
|