refactor(text): share unpaired surrogate checks (#15770)

This commit is contained in:
Vincent Koc authored and GitHub committed 2026-12-02 03:59:29 +00:00
1 parent c19f474453
commit 8f8a8539fc
6 files changed
+16 -52

No files matched your search

+1 -4
View File
@@ -1,3 +1,4 @@
import { hasUnpairedSurrogate } from "../kernel/hasUnpairedSurrogate.js";
/*
* The TOON, JSON, YAML and JSON Lines encodings and the Markdown layout are
* adapted from Incur's Formatter.
@@ -41,10 +42,6 @@ export interface CliDelimitedOutputOptions {
type DelimitedScalar = string | number | boolean | null | undefined;
/** UTF-8 cannot encode a lone UTF-16 surrogate without replacing it. */
export const hasUnpairedSurrogate = (value: string): boolean =>
/[\ud800-\udfff]/u.test(value);
/** Check selected output, including keys, before using a non-JSON text format. */
export const containsUnpairedSurrogate = (value: unknown): boolean => {
return containsText(value, hasUnpairedSurrogate);
+1 -1
View File
@@ -1,3 +1,4 @@
import { hasUnpairedSurrogate } from "../kernel/hasUnpairedSurrogate.js";
import { constants } from "node:buffer";
import type { Writable } from "node:stream";
@@ -30,7 +31,6 @@ import {
delimitedOutputInputError,
containsUnpairedSurrogate,
containsUnrepresentableMarkdown,
hasUnpairedSurrogate,
} from "./cliOutputFormatter.js";
import {
cliEvidencePublicationReceipt,
+2 -5
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { hasUnpairedSurrogate } from "../kernel/hasUnpairedSurrogate.js";
import { declaredByPatterns } from "./schemaConstraints.js";
@@ -26,10 +27,6 @@ export const INVALID_BASE64_PADDING_PATTERN = /(?:=[^=]|===)/;
export const INVALID_CANONICAL_BASE64_PAD_BITS_PATTERN =
/(?:[^AQgw]==$|[BCDFGHJKLNOPRSTVWXZabdefhijlmnpqrtuvxyz1235679+\x2f]=$)/;
// In `u` mode a well-formed surrogate pair is one code point outside this
// range, so the class matches only unpaired surrogates.
const UNPAIRED_SURROGATE_PATTERN = /[\uD800-\uDFFF]/u;
/**
* Reject unpaired UTF-16 surrogates without advertising a pattern.
*
@@ -45,7 +42,7 @@ export const rejectUnpairedSurrogates = <Schema extends z.ZodString>(
message: string,
): Schema =>
schema.superRefine((value, context) => {
if (UNPAIRED_SURROGATE_PATTERN.test(value))
if (hasUnpairedSurrogate(value))
context.addIssue({
code: "invalid_format",
format: "regex",
+3
View File
@@ -0,0 +1,3 @@
/** A Unicode-mode match treats a valid surrogate pair as one code point. */
export const hasUnpairedSurrogate = (value: string): boolean =>
/[\uD800-\uDFFF]/u.test(value);
+3 -15
View File
@@ -1,3 +1,4 @@
import { hasUnpairedSurrogate } from "../kernel/hasUnpairedSurrogate.js";
import { BinaryReader } from "../domain/binaryContainer.js";
import { decodeStrictUtf8 } from "../domain/strictUtf8.js";
import { parseJsonStringLiteral } from "../domain/jsonDuplicateMember.js";
@@ -67,21 +68,8 @@ class HeaderJson {
return rejectModel("Invalid JSON string");
// `text` was decoded via strict UTF-8, so only `\u` escapes can
// introduce unpaired UTF-16 surrogates.
if (raw.includes("\\u")) {
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code >= 0xd800 && code <= 0xdbff) {
const next = value.charCodeAt(i + 1);
if (next >= 0xdc00 && next <= 0xdfff) i++;
else
rejectModel(
"Safetensors JSON contains an unpaired surrogate",
);
} else if (code >= 0xdc00 && code <= 0xdfff) {
rejectModel("Safetensors JSON contains an unpaired surrogate");
}
}
}
if (raw.includes("\\u") && hasUnpairedSurrogate(value))
rejectModel("Safetensors JSON contains an unpaired surrogate");
return value;
} catch (cause) {
if (cause instanceof SyntaxError)
+6 -27
View File
@@ -1,3 +1,4 @@
import { hasUnpairedSurrogate } from "../../kernel/hasUnpairedSurrogate.js";
import { parseJsonStringLiteral } from "../../domain/jsonDuplicateMember.js";
/** JSON container type a projection declined to materialize. */
@@ -280,33 +281,11 @@ class Parser {
: this.text.slice(start + 1, this.position - 1);
if (typeof decoded !== "string")
throw new LosslessJsonFailure("Expected a JSON string");
return this.requirePairedSurrogates(decoded);
}
/**
* JSON admits \uXXXX escapes for unpaired surrogates, but the decoded text is
* not valid Unicode. Evidence carrying one would report malformed text as
* complete, so the parser refuses the string like any other malformed input.
* A high surrogate followed by its low surrogate escape stays valid text.
*/
private requirePairedSurrogates(value: string): string {
for (let index = 0; index < value.length; index += 1) {
const unit = value.charCodeAt(index);
if (unit >= 0xd800 && unit <= 0xdbff) {
const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0;
if (next < 0xdc00 || next > 0xdfff)
throw new LosslessJsonFailure(
"JSON string contains an unpaired surrogate",
);
index += 1;
continue;
}
if (unit >= 0xdc00 && unit <= 0xdfff)
throw new LosslessJsonFailure(
"JSON string contains an unpaired surrogate",
);
}
return value;
if (hasUnpairedSurrogate(decoded))
throw new LosslessJsonFailure(
"JSON string contains an unpaired surrogate",
);
return decoded;
}
private skipString(): boolean {