mirror of
https://github.com/openclaw/openclaw.git
synced 2026-06-28 12:33:34 +00:00
76 lines
2.3 KiB
TypeScript
76 lines
2.3 KiB
TypeScript
/** JSON Pointer token helpers for file-backed secret refs. */
|
|
import { isRecord as isJsonObject } from "@openclaw/normalization-core/record-coerce";
|
|
import { parseConfigPathArrayIndex } from "../shared/path-array-index.js";
|
|
|
|
function failOrUndefined(params: { onMissing: "throw" | "undefined"; message: string }): undefined {
|
|
if (params.onMissing === "throw") {
|
|
throw new Error(params.message);
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function decodeJsonPointerToken(token: string): string {
|
|
return token.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
}
|
|
|
|
/**
|
|
* Encodes one JSON Pointer path token using RFC 6901 escaping.
|
|
*/
|
|
export function encodeJsonPointerToken(token: string): string {
|
|
return token.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
}
|
|
|
|
/**
|
|
* Reads a value from a JSON-like document using an absolute JSON Pointer.
|
|
* Missing segments throw by default; `onMissing: "undefined"` is for optional probes.
|
|
*/
|
|
export function readJsonPointer(
|
|
root: unknown,
|
|
pointer: string,
|
|
options: { onMissing?: "throw" | "undefined" } = {},
|
|
): unknown {
|
|
const onMissing = options.onMissing ?? "throw";
|
|
if (!pointer.startsWith("/")) {
|
|
return failOrUndefined({
|
|
onMissing,
|
|
message:
|
|
'File-backed secret ids must be absolute JSON pointers (for example: "/providers/openai/apiKey").',
|
|
});
|
|
}
|
|
|
|
const tokens = pointer
|
|
.slice(1)
|
|
.split("/")
|
|
.map((token) => decodeJsonPointerToken(token));
|
|
|
|
let current: unknown = root;
|
|
for (const token of tokens) {
|
|
if (Array.isArray(current)) {
|
|
// Array segments must be canonical non-negative indexes, not partial parses like "1abc".
|
|
const index = parseConfigPathArrayIndex(token);
|
|
if (index === undefined || index >= current.length) {
|
|
return failOrUndefined({
|
|
onMissing,
|
|
message: `JSON pointer segment "${token}" is out of bounds.`,
|
|
});
|
|
}
|
|
current = current[index];
|
|
continue;
|
|
}
|
|
if (!isJsonObject(current)) {
|
|
return failOrUndefined({
|
|
onMissing,
|
|
message: `JSON pointer segment "${token}" does not exist.`,
|
|
});
|
|
}
|
|
if (!Object.hasOwn(current, token)) {
|
|
return failOrUndefined({
|
|
onMissing,
|
|
message: `JSON pointer segment "${token}" does not exist.`,
|
|
});
|
|
}
|
|
current = current[token];
|
|
}
|
|
return current;
|
|
}
|