Simplify Custom JSX v2 authoring
This commit is contained in:
177 files changed
+4775
-43426
No files matched your search
@@ -6,22 +6,13 @@ export interface CustomJsxTemplateDiagnostic {
|
||||
column: number;
|
||||
}
|
||||
|
||||
export function createCustomJsxParseDiagnostic(template: string, error: unknown): CustomJsxTemplateDiagnostic {
|
||||
export function createCustomJsxParseDiagnostic(_template: string, error: unknown): CustomJsxTemplateDiagnostic {
|
||||
const parseError = error as Error & { pos?: number; loc?: { line?: number; column?: number } };
|
||||
const parseIndex = Math.max(0, (parseError.pos ?? 2) - 2);
|
||||
const missingInitializer = [...template.matchAll(/(?:\bconst|,)\s+([A-Za-z_$][\w$]*)\s*;/gu)].find((match) => {
|
||||
const semicolon = (match.index ?? 0) + match[0].length - 1;
|
||||
return Math.abs(semicolon - parseIndex) <= 1;
|
||||
});
|
||||
const duplicateBinding = /Identifier '([^']+)' has already been declared/iu.exec(parseError.message);
|
||||
const duplicateArgument = /Argument name clash/iu.test(parseError.message);
|
||||
const message = missingInitializer
|
||||
? `LOCAL_BINDING_REQUIRES_INITIALIZER: '${missingInitializer[1]}' requires an initializer`
|
||||
: duplicateBinding
|
||||
? `DUPLICATE_LOCAL_BINDING: '${duplicateBinding[1]}' is already declared`
|
||||
: duplicateArgument
|
||||
? "DUPLICATE_LOCAL_BINDING: Callback parameter names must be unique"
|
||||
: parseError.message;
|
||||
const message = duplicateArgument
|
||||
? "DUPLICATE_LOCAL_BINDING: Callback parameter names must be unique"
|
||||
: parseError.message;
|
||||
|
||||
return {
|
||||
severity: "error",
|
||||
|
||||
@@ -2,15 +2,11 @@ import {
|
||||
customJsxBindableComponentNames,
|
||||
customJsxComponentByName,
|
||||
customJsxSupportedPropsByName,
|
||||
resolveCustomJsxComponentName,
|
||||
} from "../core/component-registry";
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { containsEscapingCallback, nodeOf, nodesOf } from "./analyzer-ast";
|
||||
import {
|
||||
closestCustomJsxComponentName,
|
||||
customJsxTagName,
|
||||
isRestrictedRecursiveListPath,
|
||||
isSafeLiteralCustomJsxUrl,
|
||||
} from "./analyzer-language";
|
||||
import { closestCustomJsxComponentName, customJsxTagName, isSafeLiteralCustomJsxUrl } from "./analyzer-language";
|
||||
import { CUSTOM_JSX_URL_PROPS, isBlockedCustomJsxProp } from "./policy";
|
||||
import { getInvalidCustomJsxPropValueReason } from "./runtime-component-policy";
|
||||
|
||||
@@ -33,7 +29,8 @@ export function analyzeCustomJsxElement(
|
||||
}
|
||||
const nameNode = nodeOf(opening.name);
|
||||
const name = nameNode ? customJsxTagName(nameNode) : null;
|
||||
const descriptor = name ? customJsxComponentByName.get(name) : undefined;
|
||||
const resolvedName = name ? resolveCustomJsxComponentName(name) : null;
|
||||
const descriptor = resolvedName ? customJsxComponentByName.get(resolvedName) : undefined;
|
||||
if (descriptor?.safety === "denied") {
|
||||
context.add(
|
||||
opening,
|
||||
@@ -49,11 +46,8 @@ export function analyzeCustomJsxElement(
|
||||
);
|
||||
}
|
||||
|
||||
const attributeNames = new Set<string>();
|
||||
let hasAttributeSpread = false;
|
||||
for (const attribute of nodesOf(opening.attributes)) {
|
||||
if (attribute.type === "JSXSpreadAttribute") {
|
||||
hasAttributeSpread = true;
|
||||
const argument = nodeOf(attribute.argument);
|
||||
if (argument) context.visit(argument, depth + 1, bindings);
|
||||
continue;
|
||||
@@ -64,7 +58,6 @@ export function analyzeCustomJsxElement(
|
||||
}
|
||||
const attributeNameNode = nodeOf(attribute.name);
|
||||
const attributeName = attributeNameNode?.type === "JSXIdentifier" ? String(attributeNameNode.name) : "";
|
||||
attributeNames.add(attributeName);
|
||||
const componentBlockedProp = descriptor?.blockedProps.find(({ name: propName }) => propName === attributeName);
|
||||
if (componentBlockedProp) {
|
||||
context.add(
|
||||
@@ -73,22 +66,23 @@ export function analyzeCustomJsxElement(
|
||||
);
|
||||
} else if (isBlockedCustomJsxProp(attributeName)) {
|
||||
context.add(attribute, `BLOCKED_CAPABILITY: Prop '${attributeName}' is not allowed`);
|
||||
} else if (name && attributeName !== "bind" && !customJsxSupportedPropsByName.get(name)?.has(attributeName)) {
|
||||
} else if (
|
||||
resolvedName &&
|
||||
attributeName !== "bind" &&
|
||||
!customJsxSupportedPropsByName.get(resolvedName)?.has(attributeName)
|
||||
) {
|
||||
context.add(attribute, `UNKNOWN_MANTINE_PROP: '${attributeName}' on ${name} will be passed through`, "warning");
|
||||
} else if (name && attributeName === "bind" && !customJsxBindableComponentNames.has(name)) {
|
||||
} else if (resolvedName && attributeName === "bind" && !customJsxBindableComponentNames.has(resolvedName)) {
|
||||
context.add(attribute, `BINDING_UNAVAILABLE: '${name}' does not have a declarative binding adapter`, "warning");
|
||||
}
|
||||
analyzeAttributeValue(name, attributeName, attribute, depth, bindings, context);
|
||||
analyzeAttributeValue(resolvedName, attributeName, attribute, depth, bindings, context);
|
||||
}
|
||||
|
||||
if (name === "RecursiveList") analyzeRecursiveList(node, opening, attributeNames, hasAttributeSpread, context);
|
||||
nodesOf(node.children).forEach((child) => {
|
||||
if (name === "RecursiveList" && child.type === "JSXExpressionContainer") {
|
||||
const expression = nodeOf(child.expression);
|
||||
if (expression?.type === "ArrowFunctionExpression") {
|
||||
context.visitArrow(expression, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
const expression = child.type === "JSXExpressionContainer" ? nodeOf(child.expression) : null;
|
||||
if (resolvedName === "SubFetch" && expression?.type === "ArrowFunctionExpression") {
|
||||
context.visitArrow(expression, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
context.visit(child, depth + 1, bindings);
|
||||
});
|
||||
@@ -109,32 +103,6 @@ function analyzeAttributeValue(
|
||||
: value?.type === "JSXExpressionContainer" && nodeOf(value.expression)?.type === "Literal"
|
||||
? nodeOf(value.expression)
|
||||
: null;
|
||||
if (componentName === "RecursiveList" && literalValue?.type === "Literal") {
|
||||
if (
|
||||
["childrenPath", "keyPath"].includes(attributeName) &&
|
||||
(typeof literalValue.value !== "string" || !isRestrictedRecursiveListPath(literalValue.value))
|
||||
) {
|
||||
context.add(attribute, `INVALID_PROP_VALUE: '${attributeName}' must be a safe dotted property path`);
|
||||
}
|
||||
if (
|
||||
attributeName === "maxDepth" &&
|
||||
(typeof literalValue.value !== "number" ||
|
||||
!Number.isInteger(literalValue.value) ||
|
||||
literalValue.value < 1 ||
|
||||
literalValue.value > 32)
|
||||
) {
|
||||
context.add(attribute, "INVALID_PROP_VALUE: 'maxDepth' must be between 1 and 32");
|
||||
}
|
||||
if (
|
||||
attributeName === "maxNodes" &&
|
||||
(typeof literalValue.value !== "number" ||
|
||||
!Number.isInteger(literalValue.value) ||
|
||||
literalValue.value < 1 ||
|
||||
literalValue.value > 2_000)
|
||||
) {
|
||||
context.add(attribute, "INVALID_PROP_VALUE: 'maxNodes' must be between 1 and 2000");
|
||||
}
|
||||
}
|
||||
if (componentName && literalValue?.type === "Literal") {
|
||||
const reason = getInvalidCustomJsxPropValueReason(componentName, attributeName, literalValue.value);
|
||||
if (reason) context.add(attribute, `INVALID_PROP_VALUE: ${reason}`);
|
||||
@@ -155,35 +123,3 @@ function analyzeAttributeValue(
|
||||
context.visit(expression, depth + 1, bindings);
|
||||
}
|
||||
}
|
||||
|
||||
function analyzeRecursiveList(
|
||||
node: AstNode,
|
||||
opening: AstNode,
|
||||
attributeNames: ReadonlySet<string>,
|
||||
hasAttributeSpread: boolean,
|
||||
context: AnalyzerJsxContext,
|
||||
): void {
|
||||
for (const requiredProp of ["data", "childrenPath", "keyPath"]) {
|
||||
if (!hasAttributeSpread && !attributeNames.has(requiredProp)) {
|
||||
context.add(opening, `INVALID_PROP_VALUE: RecursiveList requires '${requiredProp}'`);
|
||||
}
|
||||
}
|
||||
const meaningfulChildren = nodesOf(node.children).filter(
|
||||
(child) => child.type !== "JSXText" || String(child.value ?? "").trim().length > 0,
|
||||
);
|
||||
const templateExpression =
|
||||
meaningfulChildren.length === 1 && meaningfulChildren[0]?.type === "JSXExpressionContainer"
|
||||
? nodeOf(meaningfulChildren[0].expression)
|
||||
: null;
|
||||
if (templateExpression?.type !== "ArrowFunctionExpression") {
|
||||
context.add(node, "RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList requires exactly one inline arrow child");
|
||||
return;
|
||||
}
|
||||
const parameters = nodesOf(templateExpression.params);
|
||||
if (parameters.length === 0 || parameters.length > 2) {
|
||||
context.add(
|
||||
templateExpression,
|
||||
"RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList child accepts node and optional metadata parameters",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { enabledCustomJsxComponents } from "../core/component-registry";
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { nodeOf, staticPropertyName } from "./analyzer-ast";
|
||||
import { CUSTOM_JSX_BLOCKED_PROPERTIES, normalizeCustomJsxProperty } from "./policy";
|
||||
|
||||
export const ROOT_BINDINGS = new Set([
|
||||
"Array",
|
||||
@@ -87,11 +86,6 @@ export function isSafeLiteralCustomJsxUrl(value: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRestrictedRecursiveListPath(value: string): boolean {
|
||||
if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u.test(value)) return false;
|
||||
return value.split(".").every((segment) => !CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(segment)));
|
||||
}
|
||||
|
||||
export function isStaticallyCallableBinding(node: AstNode): boolean {
|
||||
if (node.type === "Identifier") return callableRootBindings.has(String(node.name));
|
||||
if (node.type !== "MemberExpression") return false;
|
||||
|
||||
@@ -115,83 +115,13 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
}
|
||||
const body = nodeOf(node.body);
|
||||
if (!body) return;
|
||||
if (body.type === "BlockStatement") visitSafeBlock(body, depth + 1, callbackBindings);
|
||||
if (body.type === "BlockStatement")
|
||||
add(body, "UNSUPPORTED_BLOCK_STATEMENT: Use one expression in authored callbacks");
|
||||
else if (canStaticallyProduceCallable(body)) {
|
||||
add(body, "CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
|
||||
} else visit(body, depth + 1, callbackBindings);
|
||||
};
|
||||
|
||||
const visitSafeBlock = (block: AstNode, depth: number, bindings: ReadonlySet<string>) => {
|
||||
if (!checkBudget(block, depth)) return;
|
||||
const statements = nodesOf(block.body);
|
||||
const finalStatement = statements.at(-1);
|
||||
if (statements.length === 0 || finalStatement?.type !== "ReturnStatement" || !nodeOf(finalStatement.argument)) {
|
||||
add(block, "BLOCK_REQUIRES_FINAL_RETURN: A safe block must end with exactly one value-returning return");
|
||||
}
|
||||
if (statements.length < 2) {
|
||||
add(block, "INVALID_LOCAL_DECLARATION: A safe block requires at least one const before its final return");
|
||||
}
|
||||
|
||||
let scopedBindings = new Set(bindings);
|
||||
const localNames = new Set<string>();
|
||||
statements.forEach((statement, statementIndex) => {
|
||||
if (!checkBudget(statement, depth + 1)) return;
|
||||
const isFinal = statementIndex === statements.length - 1;
|
||||
if (statement.type === "ReturnStatement") {
|
||||
if (!isFinal) {
|
||||
add(statement, "BLOCK_REQUIRES_FINAL_RETURN: Return is only allowed as the final statement");
|
||||
return;
|
||||
}
|
||||
const argument = nodeOf(statement.argument);
|
||||
if (argument && canStaticallyProduceCallable(argument)) {
|
||||
add(argument, "CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
|
||||
} else if (argument) visit(argument, depth + 1, scopedBindings);
|
||||
return;
|
||||
}
|
||||
if (statement.type !== "VariableDeclaration") {
|
||||
add(statement, `UNSUPPORTED_BLOCK_STATEMENT: '${statement.type}' is not allowed in a safe block`);
|
||||
return;
|
||||
}
|
||||
if (statement.kind !== "const") {
|
||||
add(statement, "INVALID_LOCAL_DECLARATION: Only immutable const declarations are allowed");
|
||||
return;
|
||||
}
|
||||
for (const declaration of nodesOf(statement.declarations)) {
|
||||
if (!checkBudget(declaration, depth + 2)) continue;
|
||||
const identifier = nodeOf(declaration.id);
|
||||
if (declaration.type !== "VariableDeclarator" || identifier?.type !== "Identifier") {
|
||||
add(declaration, "INVALID_LOCAL_DECLARATION: Local declarations require a simple identifier");
|
||||
continue;
|
||||
}
|
||||
const name = String(identifier.name);
|
||||
if (isBlockedCustomJsxLexicalBinding(name)) {
|
||||
add(identifier, `INVALID_LOCAL_DECLARATION: '${name}' is not a safe local binding name`);
|
||||
continue;
|
||||
}
|
||||
if (RESERVED_LOCAL_BINDINGS.has(name)) {
|
||||
add(identifier, `RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
|
||||
continue;
|
||||
}
|
||||
if (localNames.has(name)) {
|
||||
add(identifier, `DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
continue;
|
||||
}
|
||||
const initializer = nodeOf(declaration.init);
|
||||
if (!initializer) {
|
||||
add(declaration, `LOCAL_BINDING_REQUIRES_INITIALIZER: '${name}' requires an initializer`);
|
||||
continue;
|
||||
}
|
||||
if (canStaticallyProduceCallable(initializer)) {
|
||||
add(initializer, "CALLBACK_VALUE_NOT_ALLOWED: Functions cannot be stored in local bindings");
|
||||
continue;
|
||||
}
|
||||
visit(initializer, depth + 1, scopedBindings);
|
||||
localNames.add(name);
|
||||
scopedBindings = new Set(scopedBindings).add(name);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
|
||||
if (!checkBudget(node, depth)) return;
|
||||
|
||||
@@ -221,9 +151,9 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
return;
|
||||
}
|
||||
case "Literal":
|
||||
if (node.regex !== undefined || typeof node.value === "bigint") {
|
||||
add(node, "Regular expressions and bigint literals are not supported");
|
||||
}
|
||||
if (typeof node.value === "bigint") add(node, "BIGINT_NOT_SUPPORTED: Use Number for widget values");
|
||||
if (node.regex !== undefined && !isSafeRegexLiteral(node.regex))
|
||||
add(node, "UNSAFE_REGEX: Use a bounded regex without lookbehind, backreferences, or nested quantifiers");
|
||||
return;
|
||||
case "Identifier": {
|
||||
const name = String(node.name ?? "");
|
||||
@@ -307,17 +237,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
add(node, "CALL_TARGET_NOT_ALLOWED: Optional calls are not supported");
|
||||
}
|
||||
if (callee?.type === "ArrowFunctionExpression") {
|
||||
if (nodesOf(callee.params).length > 0) {
|
||||
add(callee, "CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions cannot declare parameters");
|
||||
}
|
||||
if (arguments_.length > 0) {
|
||||
add(node, "CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions must be called without arguments");
|
||||
}
|
||||
if (nodeOf(callee.body)?.type !== "BlockStatement") {
|
||||
add(callee, "BLOCK_REQUIRES_FINAL_RETURN: Inline derived-value functions require a safe const block");
|
||||
}
|
||||
visitArrow(callee, depth + 1, bindings);
|
||||
arguments_.forEach((argument) => visit(argument, depth + 1, bindings));
|
||||
add(callee, "CALL_TARGET_NOT_ALLOWED: Inline IIFEs are not supported");
|
||||
return;
|
||||
}
|
||||
if (callee) visit(callee, depth + 1, bindings);
|
||||
@@ -363,7 +283,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
return;
|
||||
}
|
||||
case "BlockStatement":
|
||||
add(node, "UNSUPPORTED_BLOCK_STATEMENT: Blocks are only allowed as safe callback or IIFE bodies");
|
||||
add(node, "UNSUPPORTED_BLOCK_STATEMENT: Authored callbacks must use one expression");
|
||||
return;
|
||||
case "AssignmentExpression":
|
||||
case "UpdateExpression":
|
||||
@@ -398,3 +318,11 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
function isSafeRegexLiteral(regex: unknown): boolean {
|
||||
if (!regex || typeof regex !== "object") return false;
|
||||
const { pattern, flags } = regex as { pattern?: unknown; flags?: unknown };
|
||||
if (typeof pattern !== "string" || pattern.length > 128 || typeof flags !== "string" || /[^gimsu]/u.test(flags))
|
||||
return false;
|
||||
return !/\\[1-9]|\(\?<[=!]|(?:\+|\*|\{\d+(?:,\d*)?\})\)?(?:\+|\*|\{)/u.test(pattern);
|
||||
}
|
||||
@@ -1,28 +1,28 @@
|
||||
import { isSafeCallable } from "./safe-bindings";
|
||||
import { isInterpreterCallback, normalizedSliceIndex, numericArgument, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
|
||||
interface CollectionMethodContext {
|
||||
budget: Budget;
|
||||
runCallback(callback: InterpreterCallback, args: unknown[], depth: number): unknown;
|
||||
}
|
||||
import type { InterpreterCallback } from "./interpreter-foundation";
|
||||
import type { InterpreterMethodContext } from "./interpreter-method-context";
|
||||
import { callStringMethod } from "./string-methods";
|
||||
|
||||
export function callCollectionMethod(
|
||||
receiver: unknown,
|
||||
method: string,
|
||||
args: unknown[],
|
||||
depth: number,
|
||||
context: CollectionMethodContext,
|
||||
context: InterpreterMethodContext,
|
||||
): { handled: boolean; value?: unknown } {
|
||||
if (Array.isArray(receiver)) {
|
||||
if (method === "map" || method === "filter") {
|
||||
if (method === "map" || method === "filter" || method === "flatMap") {
|
||||
const callback = args[0];
|
||||
if (isSafeCallable(callback)) {
|
||||
const result: unknown[] = [];
|
||||
for (let index = 0; index < receiver.length; index += 1) {
|
||||
context.budget.collection();
|
||||
const callbackResult = callback(receiver[index] as never);
|
||||
if (method === "map") result.push(callbackResult);
|
||||
if (method === "flatMap" && Array.isArray(callbackResult)) {
|
||||
context.budget.collection(callbackResult.length);
|
||||
result.push(...callbackResult);
|
||||
} else if (method === "map" || method === "flatMap") result.push(callbackResult);
|
||||
else if (callbackResult) result.push(receiver[index]);
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
@@ -32,7 +32,25 @@ export function callCollectionMethod(
|
||||
for (let index = 0; index < receiver.length; index += 1) {
|
||||
context.budget.collection();
|
||||
const callbackResult = context.runCallback(callback, [receiver[index], index, receiver], depth + 1);
|
||||
if (method === "map" || callbackResult) result.push(method === "map" ? callbackResult : receiver[index]);
|
||||
if (method === "flatMap" && Array.isArray(callbackResult)) {
|
||||
context.budget.collection(callbackResult.length);
|
||||
result.push(...callbackResult);
|
||||
} else if (method === "map" || method === "flatMap" || callbackResult) {
|
||||
result.push(method === "map" || method === "flatMap" ? callbackResult : receiver[index]);
|
||||
}
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
if (method === "concat") {
|
||||
const result = [...receiver];
|
||||
for (const value of args) {
|
||||
if (Array.isArray(value)) {
|
||||
context.budget.collection(value.length);
|
||||
result.push(...value);
|
||||
} else {
|
||||
context.budget.collection();
|
||||
result.push(value);
|
||||
}
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
@@ -155,98 +173,11 @@ export function callCollectionMethod(
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof receiver === "string") {
|
||||
switch (method) {
|
||||
case "toUpperCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toUpperCase()) };
|
||||
case "toLowerCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toLowerCase()) };
|
||||
case "trim":
|
||||
return { handled: true, value: context.budget.string(receiver.trim()) };
|
||||
case "trimStart":
|
||||
return { handled: true, value: context.budget.string(receiver.trimStart()) };
|
||||
case "trimEnd":
|
||||
return { handled: true, value: context.budget.string(receiver.trimEnd()) };
|
||||
case "replace": {
|
||||
const search = String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
const matchIndex = receiver.indexOf(search);
|
||||
if (matchIndex === -1) return { handled: true, value: context.budget.string(receiver) };
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.slice(0, matchIndex) + replacement + receiver.slice(matchIndex + search.length),
|
||||
),
|
||||
};
|
||||
}
|
||||
case "replaceAll": {
|
||||
const search = String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search.length === 0) return { handled: true, value: context.budget.string(receiver) };
|
||||
let result = "";
|
||||
let cursor = 0;
|
||||
while (cursor < receiver.length) {
|
||||
const matchIndex = receiver.indexOf(search, cursor);
|
||||
if (matchIndex === -1) {
|
||||
result += receiver.slice(cursor);
|
||||
break;
|
||||
}
|
||||
result += receiver.slice(cursor, matchIndex) + replacement;
|
||||
cursor = matchIndex + search.length;
|
||||
}
|
||||
return { handled: true, value: context.budget.string(result) };
|
||||
}
|
||||
case "indexOf":
|
||||
return { handled: true, value: receiver.indexOf(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "lastIndexOf": {
|
||||
const fromIndex = args[1] !== undefined ? numericArgument(args[1], receiver.length) : undefined;
|
||||
return { handled: true, value: receiver.lastIndexOf(String(args[0] ?? ""), fromIndex) };
|
||||
}
|
||||
case "repeat": {
|
||||
let maxCount = 0;
|
||||
if (receiver.length > 0) maxCount = Math.floor(200_001 / receiver.length);
|
||||
const count = Math.max(0, Math.min(numericArgument(args[0], 0), maxCount));
|
||||
return { handled: true, value: context.budget.string(receiver.repeat(count).slice(0, 200_001)) };
|
||||
}
|
||||
case "slice":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.slice(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "substring":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.substring(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "includes":
|
||||
return { handled: true, value: receiver.includes(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "startsWith":
|
||||
return { handled: true, value: receiver.startsWith(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "endsWith":
|
||||
return { handled: true, value: receiver.endsWith(String(args[0] ?? ""), args[1] as number | undefined) };
|
||||
case "padStart":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padStart(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "padEnd":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padEnd(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "charAt":
|
||||
return { handled: true, value: receiver.charAt(numericArgument(args[0], 0)) };
|
||||
case "split": {
|
||||
const limit = Math.max(0, Math.min(2_000, numericArgument(args[1], 2_000)));
|
||||
const split = args[0] === undefined ? [receiver] : receiver.split(String(args[0]), limit);
|
||||
context.budget.collection(split.length);
|
||||
return { handled: true, value: split };
|
||||
}
|
||||
}
|
||||
if (typeof receiver === "string") return callStringMethod(receiver, method, args, context);
|
||||
|
||||
if (receiver instanceof RegExp && method === "test") {
|
||||
const value = String(args[0] ?? "");
|
||||
return { handled: true, value: receiver.test(value) };
|
||||
}
|
||||
|
||||
if (typeof receiver === "number") {
|
||||
@@ -258,6 +189,9 @@ export function callCollectionMethod(
|
||||
const precision = Math.max(1, Math.min(21, numericArgument(args[0], 1)));
|
||||
return { handled: true, value: receiver.toPrecision(precision) };
|
||||
}
|
||||
if (method === "toLocaleString") {
|
||||
return { handled: true, value: context.budget.string(receiver.toLocaleString()) };
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
@@ -4,6 +4,5 @@ export * from "./policy";
|
||||
export * from "./safe-bindings";
|
||||
export * from "./bindings";
|
||||
export * from "./runtime-components";
|
||||
export * from "./recursive-list";
|
||||
export * from "./interactive-components";
|
||||
export { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
asNode,
|
||||
asNodeArray,
|
||||
Environment,
|
||||
INTERPRETER_CALLBACK,
|
||||
isInterpreterCallback,
|
||||
SafeJsxError,
|
||||
} from "./interpreter-foundation";
|
||||
import { asNode, asNodeArray, Environment, INTERPRETER_CALLBACK, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
import { RESERVED_LOCAL_BINDINGS } from "./analyzer-language";
|
||||
import { isBlockedCustomJsxLexicalBinding } from "./policy";
|
||||
@@ -16,33 +9,23 @@ interface InterpreterCallbackContext {
|
||||
}
|
||||
|
||||
export function createInterpreterCallback(node: AstNode, environment: Environment): InterpreterCallback {
|
||||
if (node.async || node.generator) {
|
||||
if (node.async || node.generator)
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Async and generator callbacks are not supported");
|
||||
}
|
||||
const parameterNames = new Set<string>();
|
||||
const params = asNodeArray(node.params, "callback parameters").map((param) => {
|
||||
if (param.type !== "Identifier") {
|
||||
if (param.type !== "Identifier")
|
||||
throw new SafeJsxError("INVALID_LOCAL_DECLARATION: Callback parameters must be identifiers");
|
||||
}
|
||||
const name = String(param.name);
|
||||
if (isBlockedCustomJsxLexicalBinding(name)) {
|
||||
if (isBlockedCustomJsxLexicalBinding(name) || RESERVED_LOCAL_BINDINGS.has(name))
|
||||
throw new SafeJsxError(`INVALID_LOCAL_DECLARATION: '${name}' is not a safe callback parameter name`);
|
||||
}
|
||||
if (RESERVED_LOCAL_BINDINGS.has(name)) {
|
||||
throw new SafeJsxError(`RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
|
||||
}
|
||||
if (parameterNames.has(name)) {
|
||||
throw new SafeJsxError(`DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
}
|
||||
if (parameterNames.has(name)) throw new SafeJsxError(`DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
parameterNames.add(name);
|
||||
return name;
|
||||
});
|
||||
return {
|
||||
kind: INTERPRETER_CALLBACK,
|
||||
params,
|
||||
body: asNode(node.body, "callback body"),
|
||||
environment,
|
||||
};
|
||||
const body = asNode(node.body, "callback body");
|
||||
if (body.type === "BlockStatement")
|
||||
throw new SafeJsxError("UNSUPPORTED_BLOCK_STATEMENT: Use one expression in authored callbacks");
|
||||
return { kind: INTERPRETER_CALLBACK, params, body, environment };
|
||||
}
|
||||
|
||||
export function runInterpreterCallback(
|
||||
@@ -51,93 +34,17 @@ export function runInterpreterCallback(
|
||||
depth: number,
|
||||
context: InterpreterCallbackContext,
|
||||
): unknown {
|
||||
context.budget.operation(depth);
|
||||
const values: Record<string, unknown> = Object.create(null);
|
||||
callback.params.forEach((name, index) => {
|
||||
values[name] = args[index];
|
||||
});
|
||||
const environment = new Environment(values, callback.environment);
|
||||
const result =
|
||||
callback.body.type === "BlockStatement"
|
||||
? executeSafeBlock(callback.body, environment, depth + 1, context)
|
||||
: context.evaluate(callback.body, environment, depth + 1);
|
||||
return ensureNonCallableResult(result);
|
||||
}
|
||||
|
||||
function executeSafeBlock(
|
||||
block: AstNode,
|
||||
environment: Environment,
|
||||
depth: number,
|
||||
context: InterpreterCallbackContext,
|
||||
): unknown {
|
||||
context.budget.operation(depth);
|
||||
const statements = asNodeArray(block.body, "safe block statements");
|
||||
const finalStatement = statements.at(-1);
|
||||
if (statements.length === 0 || finalStatement?.type !== "ReturnStatement" || !finalStatement.argument) {
|
||||
throw new SafeJsxError(
|
||||
"BLOCK_REQUIRES_FINAL_RETURN: A safe block must end with exactly one value-returning return",
|
||||
);
|
||||
}
|
||||
if (statements.length < 2) {
|
||||
throw new SafeJsxError(
|
||||
"INVALID_LOCAL_DECLARATION: A safe block requires at least one const before its final return",
|
||||
);
|
||||
}
|
||||
|
||||
let scopedEnvironment = environment;
|
||||
const localNames = new Set<string>();
|
||||
for (let statementIndex = 0; statementIndex < statements.length; statementIndex += 1) {
|
||||
const statement = statements[statementIndex];
|
||||
if (!statement) continue;
|
||||
context.budget.operation(depth + 1);
|
||||
const isFinal = statementIndex === statements.length - 1;
|
||||
if (statement.type === "ReturnStatement") {
|
||||
if (!isFinal) {
|
||||
throw new SafeJsxError("BLOCK_REQUIRES_FINAL_RETURN: Return is only allowed as the final statement");
|
||||
}
|
||||
return ensureNonCallableResult(
|
||||
context.evaluate(asNode(statement.argument, "safe block return value"), scopedEnvironment, depth + 1),
|
||||
);
|
||||
}
|
||||
if (statement.type !== "VariableDeclaration") {
|
||||
throw new SafeJsxError(`UNSUPPORTED_BLOCK_STATEMENT: '${statement.type}' is not allowed in a safe block`);
|
||||
}
|
||||
if (statement.kind !== "const") {
|
||||
throw new SafeJsxError("INVALID_LOCAL_DECLARATION: Only immutable const declarations are allowed");
|
||||
}
|
||||
for (const declaration of asNodeArray(statement.declarations, "local declarations")) {
|
||||
context.budget.operation(depth + 2);
|
||||
const identifier = asNode(declaration.id, "local identifier");
|
||||
if (declaration.type !== "VariableDeclarator" || identifier.type !== "Identifier") {
|
||||
throw new SafeJsxError("INVALID_LOCAL_DECLARATION: Local declarations require a simple identifier");
|
||||
}
|
||||
const name = String(identifier.name);
|
||||
if (isBlockedCustomJsxLexicalBinding(name)) {
|
||||
throw new SafeJsxError(`INVALID_LOCAL_DECLARATION: '${name}' is not a safe local binding name`);
|
||||
}
|
||||
if (RESERVED_LOCAL_BINDINGS.has(name)) {
|
||||
throw new SafeJsxError(`RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
|
||||
}
|
||||
if (localNames.has(name)) {
|
||||
throw new SafeJsxError(`DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
}
|
||||
const initializer = asNode(declaration.init, `initializer for '${name}'`);
|
||||
if (initializer.type === "ArrowFunctionExpression" || initializer.type === "FunctionExpression") {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Functions cannot be stored in local bindings");
|
||||
}
|
||||
const value = context.evaluate(initializer, scopedEnvironment, depth + 1);
|
||||
if (typeof value === "function" || isInterpreterCallback(value)) {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Functions cannot be stored in local bindings");
|
||||
}
|
||||
localNames.add(name);
|
||||
scopedEnvironment = new Environment({ [name]: value }, scopedEnvironment);
|
||||
}
|
||||
}
|
||||
throw new SafeJsxError("BLOCK_REQUIRES_FINAL_RETURN: Safe block did not return a value");
|
||||
}
|
||||
|
||||
function ensureNonCallableResult(value: unknown): unknown {
|
||||
if (typeof value === "function" || isInterpreterCallback(value)) {
|
||||
const result = context.evaluate(callback.body, new Environment(values, callback.environment), depth + 1);
|
||||
if (
|
||||
typeof result === "function" ||
|
||||
(result !== null && typeof result === "object" && "kind" in result && result.kind === INTERPRETER_CALLBACK)
|
||||
) {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
|
||||
}
|
||||
return value;
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
|
||||
export interface InterpreterMethodContext {
|
||||
budget: Budget;
|
||||
runCallback(callback: InterpreterCallback, args: unknown[], depth: number): unknown;
|
||||
}
|
||||
@@ -49,6 +49,21 @@ class Interpreter {
|
||||
|
||||
switch (node.type) {
|
||||
case "Literal":
|
||||
if (node.regex !== undefined) {
|
||||
const regex = node.regex as { pattern?: unknown; flags?: unknown };
|
||||
if (
|
||||
typeof regex.pattern !== "string" ||
|
||||
regex.pattern.length > 128 ||
|
||||
typeof regex.flags !== "string" ||
|
||||
/[^gimsu]/u.test(regex.flags) ||
|
||||
/\\[1-9]|\(\?<[=!]|(?:\+|\*|\{\d+(?:,\d*)?\})\)?(?:\+|\*|\{)/u.test(regex.pattern)
|
||||
) {
|
||||
throw new SafeJsxError("UNSAFE_REGEX: Invalid regular expression literal");
|
||||
}
|
||||
return new RegExp(regex.pattern, regex.flags);
|
||||
}
|
||||
if (typeof node.value === "bigint")
|
||||
throw new SafeJsxError("BIGINT_NOT_SUPPORTED: Use Number for widget values");
|
||||
return node.value;
|
||||
case "Identifier":
|
||||
return environment.get(String(node.name));
|
||||
@@ -263,22 +278,8 @@ class Interpreter {
|
||||
if (node.optional) throw new SafeJsxError("Optional calls are not supported");
|
||||
const callee = asNode(node.callee, "call target");
|
||||
const argumentNodes = asNodeArray(node.arguments, "call arguments");
|
||||
if (callee.type === "ArrowFunctionExpression") {
|
||||
if (callee.body && asNode(callee.body, "inline derived-value body").type !== "BlockStatement") {
|
||||
throw new SafeJsxError(
|
||||
"BLOCK_REQUIRES_FINAL_RETURN: Inline derived-value functions require a safe const block",
|
||||
);
|
||||
}
|
||||
if (asNodeArray(callee.params, "inline derived-value parameters").length > 0) {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions cannot declare parameters");
|
||||
}
|
||||
if (argumentNodes.length > 0) {
|
||||
throw new SafeJsxError(
|
||||
"CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions must be called without arguments",
|
||||
);
|
||||
}
|
||||
return this.runCallback(this.createCallback(callee, environment), [], depth + 1);
|
||||
}
|
||||
if (callee.type === "ArrowFunctionExpression")
|
||||
throw new SafeJsxError("CALL_TARGET_NOT_ALLOWED: Inline IIFEs are not supported");
|
||||
const callbackMethod =
|
||||
callee.type === "MemberExpression"
|
||||
? callee.computed
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createElement, Fragment } from "react";
|
||||
import { asNode, asNodeArray, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Environment } from "./interpreter-foundation";
|
||||
import type { JsxEmitterContext } from "./emitter-context";
|
||||
import { emitRecursiveList } from "./recursive-list-emitter";
|
||||
import { resolveCustomJsxComponentName } from "../core/component-registry";
|
||||
import { diagnoseCustomJsxProps, normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
import { CUSTOM_JSX_BLOCKED_TAGS } from "./policy";
|
||||
|
||||
@@ -29,16 +29,16 @@ export function emitJsxElement(
|
||||
): ReactNode {
|
||||
const opening = asNode(node.openingElement, "JSX opening element");
|
||||
const tag = jsxTagName(asNode(opening.name, "JSX tag"));
|
||||
const resolvedTag = resolveCustomJsxComponentName(tag);
|
||||
if (CUSTOM_JSX_BLOCKED_TAGS.has(tag.toLowerCase())) {
|
||||
context.warnings.add(`Blocked element: ${tag}`);
|
||||
return null;
|
||||
}
|
||||
const component = context.components[tag];
|
||||
const component = context.components[resolvedTag];
|
||||
if (!component) {
|
||||
context.warnings.add(`Unknown or unavailable component: ${tag}`);
|
||||
return null;
|
||||
}
|
||||
if (tag === "RecursiveList") return emitRecursiveList(node, environment, depth, component, context);
|
||||
const rawProps: Record<string, unknown> = {};
|
||||
for (const attribute of asNodeArray(opening.attributes, "JSX attributes")) {
|
||||
if (attribute.type === "JSXSpreadAttribute") {
|
||||
@@ -58,11 +58,17 @@ export function emitJsxElement(
|
||||
rawProps[name] = value.type === "Literal" ? value.value : context.evaluate(value, environment, depth + 1);
|
||||
}
|
||||
}
|
||||
const children = asNodeArray(node.children, "JSX children").map((child) =>
|
||||
context.evaluate(child, environment, depth + 1),
|
||||
);
|
||||
diagnoseCustomJsxProps(rawProps, tag).forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const props = sanitizeCustomJsxProps(rawProps, tag);
|
||||
const children = asNodeArray(node.children, "JSX children").map((child) => {
|
||||
const expression =
|
||||
child.type === "JSXExpressionContainer" ? asNode(child.expression, "JSX child expression") : null;
|
||||
if (resolvedTag === "SubFetch" && expression?.type === "ArrowFunctionExpression") {
|
||||
const callback = context.createCallback(expression, environment);
|
||||
return (value: unknown) => context.renderCallback(callback, [value], depth + 1);
|
||||
}
|
||||
return context.evaluate(child, environment, depth + 1);
|
||||
});
|
||||
diagnoseCustomJsxProps(rawProps, resolvedTag).forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const props = sanitizeCustomJsxProps(rawProps, resolvedTag);
|
||||
context.budget.rendered();
|
||||
return createElement(component, props as never, ...(children as ReactNode[]));
|
||||
}
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Text } from "@mantine/core";
|
||||
import type { TreeNodeData } from "@mantine/core";
|
||||
|
||||
import { SafeJsxBudgetError } from "./interpreter-foundation";
|
||||
import {
|
||||
clampWithWarning,
|
||||
DEFAULT_MAX_DEPTH,
|
||||
DEFAULT_MAX_NODES,
|
||||
exceedsRecursiveListNodeLimit,
|
||||
formatPath,
|
||||
HARD_MAX_DEPTH,
|
||||
HARD_MAX_NODES,
|
||||
isObject,
|
||||
parseRestrictedPath,
|
||||
primitiveKey,
|
||||
readRestrictedPath,
|
||||
} from "./recursive-list-helpers";
|
||||
import type { RecursiveListBuildOptions, RecursiveListMetadata } from "./recursive-list-types";
|
||||
|
||||
const OMITTED_LABEL = "Additional levels omitted";
|
||||
|
||||
export function buildTrustedRecursiveList(options: RecursiveListBuildOptions): TreeNodeData[] {
|
||||
const maxDepth = clampWithWarning(
|
||||
options.maxDepth,
|
||||
DEFAULT_MAX_DEPTH,
|
||||
1,
|
||||
HARD_MAX_DEPTH,
|
||||
"maxDepth",
|
||||
options.warnings,
|
||||
);
|
||||
const maxNodes = clampWithWarning(
|
||||
options.maxNodes,
|
||||
DEFAULT_MAX_NODES,
|
||||
1,
|
||||
HARD_MAX_NODES,
|
||||
"maxNodes",
|
||||
options.warnings,
|
||||
);
|
||||
let childrenPath: string[];
|
||||
let keyPath: string[];
|
||||
try {
|
||||
childrenPath = parseRestrictedPath(options.childrenPath, "childrenPath");
|
||||
keyPath = parseRestrictedPath(options.keyPath, "keyPath");
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
options.warnings.add(message);
|
||||
options.budget.operation(1);
|
||||
options.budget.collection();
|
||||
options.budget.rendered();
|
||||
return [diagnosticNode("diagnostic:path", message)];
|
||||
}
|
||||
const roots = Array.isArray(options.data) ? options.data : isObject(options.data) ? [options.data] : null;
|
||||
if (!roots) {
|
||||
options.warnings.add("RECURSIVE_LIST_INVALID_DATA: data must be an object or an array of objects");
|
||||
options.budget.operation(1);
|
||||
options.budget.collection();
|
||||
options.budget.rendered();
|
||||
return [diagnosticNode("diagnostic:root-data", "RecursiveList data must be an object or an array")];
|
||||
}
|
||||
|
||||
const willExceedNodeLimit = exceedsRecursiveListNodeLimit(roots, childrenPath, maxDepth, maxNodes, options.budget);
|
||||
let renderedRowCount = 0;
|
||||
let diagnosticCount = 0;
|
||||
let limitSentinelRendered = false;
|
||||
const usedKeys = new Set<string>();
|
||||
const chargeRow = (depth: number) => {
|
||||
options.budget.operation(depth + 1);
|
||||
options.budget.collection();
|
||||
options.budget.rendered();
|
||||
renderedRowCount += 1;
|
||||
};
|
||||
const makeLimitDiagnostic = (path: readonly number[], depth: number): TreeNodeData | null => {
|
||||
if (limitSentinelRendered || renderedRowCount >= maxNodes) return null;
|
||||
options.warnings.add(`RECURSIVE_LIST_NODE_LIMIT: Rendering stopped after ${maxNodes} nodes`);
|
||||
chargeRow(depth);
|
||||
diagnosticCount += 1;
|
||||
limitSentinelRendered = true;
|
||||
return diagnosticNode(`diagnostic:${path.join(".")}:${diagnosticCount}`, OMITTED_LABEL);
|
||||
};
|
||||
const makeDiagnostic = (path: readonly number[], message: string, depth: number): TreeNodeData | null => {
|
||||
if (renderedRowCount >= maxNodes) return null;
|
||||
if (willExceedNodeLimit && renderedRowCount === maxNodes - 1) return makeLimitDiagnostic(path, depth);
|
||||
chargeRow(depth);
|
||||
diagnosticCount += 1;
|
||||
return diagnosticNode(`diagnostic:${path.join(".")}:${diagnosticCount}`, message);
|
||||
};
|
||||
|
||||
const visitSiblings = (
|
||||
values: readonly unknown[],
|
||||
depth: number,
|
||||
parentPath: readonly number[],
|
||||
ancestors: ReadonlySet<object>,
|
||||
): TreeNodeData[] => {
|
||||
const result: TreeNodeData[] = [];
|
||||
for (let index = 0; index < values.length; index += 1) {
|
||||
if (renderedRowCount >= maxNodes) break;
|
||||
if (willExceedNodeLimit && renderedRowCount === maxNodes - 1) {
|
||||
const omitted = makeLimitDiagnostic(parentPath, depth);
|
||||
if (omitted) result.push(omitted);
|
||||
break;
|
||||
}
|
||||
const value = values[index];
|
||||
const path = [...parentPath, index];
|
||||
if (!isObject(value)) {
|
||||
options.warnings.add(`RECURSIVE_LIST_INVALID_NODE: Node at ${formatPath(path)} is not an object`);
|
||||
const invalid = makeDiagnostic(path, "Invalid tree node omitted", depth);
|
||||
if (invalid) result.push(invalid);
|
||||
continue;
|
||||
}
|
||||
if (ancestors.has(value)) {
|
||||
options.warnings.add(`RECURSIVE_LIST_CYCLE: Cycle detected at ${formatPath(path)}`);
|
||||
const cycle = makeDiagnostic(path, OMITTED_LABEL, depth);
|
||||
if (cycle) result.push(cycle);
|
||||
continue;
|
||||
}
|
||||
|
||||
chargeRow(depth);
|
||||
const rawKey = readRestrictedPath(value, keyPath);
|
||||
const preferredKey = primitiveKey(rawKey);
|
||||
const namespacedPreferredKey = preferredKey === null ? null : `key:${typeof rawKey}:${preferredKey}`;
|
||||
let key = namespacedPreferredKey ?? `path:${path.join(".")}`;
|
||||
if (namespacedPreferredKey === null) {
|
||||
options.warnings.add(`RECURSIVE_LIST_MISSING_KEY: Node at ${formatPath(path)} uses a stable path key`);
|
||||
} else if (usedKeys.has(namespacedPreferredKey)) {
|
||||
key = `path:${path.join(".")}`;
|
||||
options.warnings.add(`RECURSIVE_LIST_DUPLICATE_KEY: '${preferredKey}' uses a stable path key`);
|
||||
}
|
||||
usedKeys.add(key);
|
||||
|
||||
const rawChildren = readRestrictedPath(value, childrenPath);
|
||||
const childValues = rawChildren === undefined || rawChildren === null ? [] : rawChildren;
|
||||
const validChildren = Array.isArray(childValues);
|
||||
const childCount = validChildren ? childValues.length : 0;
|
||||
const metadata: RecursiveListMetadata = Object.freeze({
|
||||
depth,
|
||||
index,
|
||||
path: Object.freeze(path) as unknown as number[],
|
||||
key,
|
||||
hasChildren: childCount > 0,
|
||||
childCount,
|
||||
isLast: index === values.length - 1,
|
||||
});
|
||||
const nextAncestors = new Set(ancestors).add(value);
|
||||
const children: TreeNodeData[] = [];
|
||||
if (!validChildren) {
|
||||
options.warnings.add(
|
||||
`RECURSIVE_LIST_INVALID_CHILDREN: ${options.childrenPath} at ${formatPath(path)} must be an array`,
|
||||
);
|
||||
const invalidChildren = makeDiagnostic(path, `Expected ${options.childrenPath} to be an array`, depth + 1);
|
||||
if (invalidChildren) children.push(invalidChildren);
|
||||
} else if (childCount > 0 && depth + 1 >= maxDepth) {
|
||||
options.warnings.add(`RECURSIVE_LIST_DEPTH_LIMIT: Rendering stopped at depth ${maxDepth}`);
|
||||
const omitted = makeDiagnostic(path, OMITTED_LABEL, depth + 1);
|
||||
if (omitted) children.push(omitted);
|
||||
} else if (childCount > 0) {
|
||||
children.push(...visitSiblings(childValues, depth + 1, path, nextAncestors));
|
||||
}
|
||||
|
||||
let label: ReactNode;
|
||||
try {
|
||||
label = options.render(value, metadata, depth + 1);
|
||||
} catch (error) {
|
||||
if (error instanceof SafeJsxBudgetError) throw error;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
options.warnings.add(`RECURSIVE_LIST_BRANCH_ERROR: ${formatPath(path)}: ${message}`);
|
||||
label = (
|
||||
<Text size="xs" c="red">
|
||||
Unable to render this branch: {message}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
result.push({
|
||||
value: key,
|
||||
label,
|
||||
...(children.length > 0 ? { children } : {}),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
return visitSiblings(roots, 0, [], new Set());
|
||||
}
|
||||
|
||||
function diagnosticNode(value: string, message: string): TreeNodeData {
|
||||
return {
|
||||
value,
|
||||
label: (
|
||||
<Text size="xs" c="dimmed" fs="italic">
|
||||
{message}
|
||||
</Text>
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createElement } from "react";
|
||||
|
||||
import { buildTrustedRecursiveList } from "./recursive-list";
|
||||
import { asNode, asNodeArray, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Environment, InterpreterCallback } from "./interpreter-foundation";
|
||||
import type { JsxEmitterContext } from "./emitter-context";
|
||||
import { diagnoseCustomJsxProps, normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
|
||||
const supportedProps = new Set([
|
||||
"data",
|
||||
"childrenPath",
|
||||
"keyPath",
|
||||
"maxDepth",
|
||||
"maxNodes",
|
||||
"defaultExpandedDepth",
|
||||
"indent",
|
||||
"gap",
|
||||
"showLines",
|
||||
"bind",
|
||||
]);
|
||||
|
||||
export function emitRecursiveList(
|
||||
node: AstNode,
|
||||
environment: Environment,
|
||||
depth: number,
|
||||
component: ComponentType<never>,
|
||||
context: JsxEmitterContext,
|
||||
): ReactNode {
|
||||
const opening = asNode(node.openingElement, "RecursiveList opening element");
|
||||
const props: Record<string, unknown> = Object.create(null);
|
||||
for (const attribute of asNodeArray(opening.attributes, "RecursiveList attributes")) {
|
||||
if (attribute.type === "JSXSpreadAttribute") {
|
||||
const spread = context.evaluate(
|
||||
asNode(attribute.argument, "RecursiveList spread attribute"),
|
||||
environment,
|
||||
depth + 1,
|
||||
);
|
||||
if (spread && typeof spread === "object" && !Array.isArray(spread)) {
|
||||
for (const [name, value] of Object.entries(spread)) {
|
||||
props[name] = value;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (attribute.type !== "JSXAttribute") throw new SafeJsxError(`Unsupported JSX attribute: ${attribute.type}`);
|
||||
const nameNode = asNode(attribute.name, "RecursiveList attribute name");
|
||||
if (nameNode.type !== "JSXIdentifier") throw new SafeJsxError("Namespaced JSX attributes are not supported");
|
||||
const rawName = String(nameNode.name);
|
||||
const name = rawName === "bind" ? rawName : normalizedProperty(rawName);
|
||||
if (attribute.value == null) props[name] = true;
|
||||
else {
|
||||
const value = asNode(attribute.value, `RecursiveList ${name} value`);
|
||||
props[name] = value.type === "Literal" ? value.value : context.evaluate(value, environment, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const callback = recursiveListCallback(node, environment, context);
|
||||
const data = props.data;
|
||||
const childrenPath = typeof props.childrenPath === "string" ? props.childrenPath : "";
|
||||
const keyPath = typeof props.keyPath === "string" ? props.keyPath : "";
|
||||
const nodes = buildTrustedRecursiveList({
|
||||
data,
|
||||
childrenPath,
|
||||
keyPath,
|
||||
maxDepth: props.maxDepth,
|
||||
maxNodes: props.maxNodes,
|
||||
budget: context.budget,
|
||||
warnings: context.warnings,
|
||||
render: (value, metadata, callbackDepth) =>
|
||||
context.renderCallback(callback, [value, metadata], depth + callbackDepth + 1),
|
||||
});
|
||||
if (Object.hasOwn(props, "bind")) {
|
||||
context.warnings.add("BINDING_UNAVAILABLE: 'RecursiveList' does not have a declarative binding adapter");
|
||||
}
|
||||
diagnoseCustomJsxProps(props, "RecursiveList").forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const rootProps = sanitizeCustomJsxProps(
|
||||
Object.fromEntries(Object.entries(props).filter(([name]) => !supportedProps.has(name))),
|
||||
"RecursiveList",
|
||||
);
|
||||
const trustedProps = {
|
||||
nodes,
|
||||
defaultExpandedDepth: finiteNumber(props.defaultExpandedDepth),
|
||||
indent: spacing(props.indent),
|
||||
gap: spacing(props.gap),
|
||||
showLines: props.showLines === true,
|
||||
rootProps,
|
||||
};
|
||||
context.budget.rendered();
|
||||
return createElement(component, trustedProps as never);
|
||||
}
|
||||
|
||||
function recursiveListCallback(
|
||||
node: AstNode,
|
||||
environment: Environment,
|
||||
context: JsxEmitterContext,
|
||||
): InterpreterCallback {
|
||||
const meaningfulChildren = asNodeArray(node.children, "RecursiveList children").filter(
|
||||
(child) => child.type !== "JSXText" || String(child.value ?? "").trim().length > 0,
|
||||
);
|
||||
if (meaningfulChildren.length !== 1 || meaningfulChildren[0]?.type !== "JSXExpressionContainer") {
|
||||
throw new SafeJsxError("RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList requires exactly one inline arrow child");
|
||||
}
|
||||
const expression = asNode(meaningfulChildren[0].expression, "RecursiveList template child");
|
||||
if (expression.type !== "ArrowFunctionExpression") {
|
||||
throw new SafeJsxError("RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList child must be an inline arrow");
|
||||
}
|
||||
const params = asNodeArray(expression.params, "RecursiveList template parameters");
|
||||
if (params.length === 0 || params.length > 2) {
|
||||
throw new SafeJsxError(
|
||||
"RECURSIVE_LIST_TEMPLATE_REQUIRED: RecursiveList child accepts node and optional metadata parameters",
|
||||
);
|
||||
}
|
||||
return context.createCallback(expression, environment);
|
||||
}
|
||||
|
||||
function spacing(value: unknown): string | number | undefined {
|
||||
return typeof value === "string" || typeof value === "number" ? value : undefined;
|
||||
}
|
||||
|
||||
function finiteNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import { SafeJsxError } from "./interpreter-foundation";
|
||||
import type { Budget } from "./interpreter-foundation";
|
||||
import { CUSTOM_JSX_BLOCKED_PROPERTIES, normalizeCustomJsxProperty } from "./policy";
|
||||
import { ownProperty } from "./safe-properties";
|
||||
|
||||
export const DEFAULT_MAX_DEPTH = 16;
|
||||
export const HARD_MAX_DEPTH = 32;
|
||||
export const DEFAULT_MAX_NODES = 500;
|
||||
export const HARD_MAX_NODES = 2_000;
|
||||
|
||||
export function exceedsRecursiveListNodeLimit(
|
||||
roots: readonly unknown[],
|
||||
childrenPath: readonly string[],
|
||||
maxDepth: number,
|
||||
maxNodes: number,
|
||||
budget: Budget,
|
||||
) {
|
||||
let rows = 0;
|
||||
const charge = (depth: number) => {
|
||||
budget.operation(depth + 1);
|
||||
rows += 1;
|
||||
return rows > maxNodes;
|
||||
};
|
||||
const visit = (values: readonly unknown[], depth: number, ancestors: ReadonlySet<object>): boolean => {
|
||||
for (const value of values) {
|
||||
if (charge(depth)) return true;
|
||||
if (!isObject(value) || ancestors.has(value)) continue;
|
||||
|
||||
const rawChildren = readRestrictedPath(value, childrenPath);
|
||||
if (rawChildren !== undefined && rawChildren !== null && !Array.isArray(rawChildren)) {
|
||||
if (charge(depth + 1)) return true;
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(rawChildren) || rawChildren.length === 0) continue;
|
||||
if (depth + 1 >= maxDepth) {
|
||||
if (charge(depth + 1)) return true;
|
||||
continue;
|
||||
}
|
||||
if (visit(rawChildren, depth + 1, new Set(ancestors).add(value))) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return visit(roots, 0, new Set());
|
||||
}
|
||||
|
||||
export function parseRestrictedPath(value: string, name: string): string[] {
|
||||
if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u.test(value)) {
|
||||
throw new SafeJsxError(`RECURSIVE_LIST_INVALID_PATH: ${name} must be a dotted property path`);
|
||||
}
|
||||
const segments = value.split(".");
|
||||
for (const segment of segments) {
|
||||
if (CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(segment))) {
|
||||
throw new SafeJsxError(`RECURSIVE_LIST_INVALID_PATH: ${name} contains blocked segment '${segment}'`);
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
export function readRestrictedPath(value: unknown, path: readonly string[]): unknown {
|
||||
let current = value;
|
||||
for (const segment of path) current = ownProperty(current, segment);
|
||||
return current;
|
||||
}
|
||||
|
||||
export function primitiveKey(value: unknown): string | null {
|
||||
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : null;
|
||||
}
|
||||
|
||||
export function clampWithWarning(
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
minimum: number,
|
||||
maximum: number,
|
||||
name: string,
|
||||
warnings: Set<string>,
|
||||
) {
|
||||
const validNumber = typeof value === "number" && Number.isFinite(value);
|
||||
const number = validNumber ? Math.trunc(value) : fallback;
|
||||
const clamped = Math.min(maximum, Math.max(minimum, number));
|
||||
if (value !== undefined && (!validNumber || value !== number || number !== clamped)) {
|
||||
warnings.add(`RECURSIVE_LIST_LIMIT_CLAMPED: ${name} was clamped to ${clamped}`);
|
||||
}
|
||||
return clamped;
|
||||
}
|
||||
|
||||
export function isObject(value: unknown): value is object {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function formatPath(path: readonly number[]) {
|
||||
return path.length === 0 ? "root" : path.join(".");
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { MantineSpacing, TreeNodeData } from "@mantine/core";
|
||||
|
||||
import type { Budget } from "./interpreter-foundation";
|
||||
|
||||
export interface RecursiveListMetadata {
|
||||
depth: number;
|
||||
index: number;
|
||||
path: number[];
|
||||
key: string;
|
||||
hasChildren: boolean;
|
||||
childCount: number;
|
||||
isLast: boolean;
|
||||
}
|
||||
|
||||
export interface RecursiveListBuildOptions {
|
||||
data: unknown;
|
||||
childrenPath: string;
|
||||
keyPath: string;
|
||||
maxDepth?: unknown;
|
||||
maxNodes?: unknown;
|
||||
budget: Budget;
|
||||
warnings: Set<string>;
|
||||
render(node: unknown, metadata: RecursiveListMetadata, depth: number): ReactNode;
|
||||
}
|
||||
|
||||
export interface TrustedRecursiveListProps {
|
||||
nodes: TreeNodeData[];
|
||||
defaultExpandedDepth?: number;
|
||||
indent?: MantineSpacing;
|
||||
gap?: MantineSpacing;
|
||||
showLines?: boolean;
|
||||
rootProps?: Record<string, unknown>;
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import type { ErrorInfo, ReactNode } from "react";
|
||||
import { Component, useMemo } from "react";
|
||||
import { Box, Group, Text, Tree, useTree } from "@mantine/core";
|
||||
import type { MantineSpacing, RenderTreeNodePayload, TreeNodeData } from "@mantine/core";
|
||||
import { IconChevronRight } from "@tabler/icons-react";
|
||||
|
||||
import { buildTrustedRecursiveList } from "./recursive-list-builder";
|
||||
import type { TrustedRecursiveListProps } from "./recursive-list-types";
|
||||
|
||||
const HARD_MAX_DEPTH = 32;
|
||||
|
||||
export { buildTrustedRecursiveList };
|
||||
export type {
|
||||
RecursiveListBuildOptions,
|
||||
RecursiveListMetadata,
|
||||
TrustedRecursiveListProps,
|
||||
} from "./recursive-list-types";
|
||||
|
||||
export function TrustedRecursiveList({ ...props }: TrustedRecursiveListProps) {
|
||||
return (
|
||||
<RecursiveListErrorBoundary resetKey={props.nodes} code="RECURSIVE_LIST_RENDER_ERROR">
|
||||
<TrustedRecursiveListInner {...props} />
|
||||
</RecursiveListErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
function TrustedRecursiveListInner({
|
||||
nodes,
|
||||
defaultExpandedDepth = 4,
|
||||
indent = "lg",
|
||||
gap = "xs",
|
||||
showLines = false,
|
||||
rootProps = {},
|
||||
}: TrustedRecursiveListProps) {
|
||||
const initialExpandedState = useMemo(
|
||||
() => collectInitialExpandedState(nodes, clampInteger(defaultExpandedDepth, 0, HARD_MAX_DEPTH, 4)),
|
||||
[defaultExpandedDepth, nodes],
|
||||
);
|
||||
const tree = useTree({ initialExpandedState });
|
||||
|
||||
return (
|
||||
<Tree
|
||||
{...rootProps}
|
||||
data={nodes}
|
||||
tree={tree}
|
||||
levelOffset={indent}
|
||||
withLines={showLines}
|
||||
renderNode={(payload) => <TrustedRecursiveListNode {...payload} gap={gap} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
class RecursiveListErrorBoundary extends Component<
|
||||
{ children: ReactNode; resetKey: unknown; code: string },
|
||||
{ error: Error | null; resetKey: unknown }
|
||||
> {
|
||||
public state = { error: null, resetKey: this.props.resetKey } as { error: Error | null; resetKey: unknown };
|
||||
public static getDerivedStateFromProps(
|
||||
props: Readonly<{ children: ReactNode; resetKey: unknown; code: string }>,
|
||||
state: Readonly<{ error: Error | null; resetKey: unknown }>,
|
||||
) {
|
||||
if (props.resetKey === state.resetKey) return null;
|
||||
return { error: null, resetKey: props.resetKey };
|
||||
}
|
||||
public static getDerivedStateFromError(error: Error) {
|
||||
return { error };
|
||||
}
|
||||
public componentDidCatch(_error: Error, _info: ErrorInfo) {}
|
||||
public render() {
|
||||
return this.state.error ? (
|
||||
<Text size="xs" c="red">
|
||||
{this.props.code}: {this.state.error.message}
|
||||
</Text>
|
||||
) : (
|
||||
this.props.children
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function TrustedRecursiveListNode({
|
||||
node,
|
||||
expanded,
|
||||
hasChildren,
|
||||
elementProps,
|
||||
gap,
|
||||
}: RenderTreeNodePayload & { gap: MantineSpacing }) {
|
||||
return (
|
||||
<Group {...elementProps} aria-expanded={hasChildren ? expanded : undefined} gap={gap} wrap="nowrap" py={2}>
|
||||
<Box w={16} h={16} style={{ flex: "0 0 16px" }} aria-hidden>
|
||||
{hasChildren && (
|
||||
<IconChevronRight
|
||||
size={15}
|
||||
style={{ transform: expanded ? "rotate(90deg)" : undefined, transition: "transform 120ms ease" }}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box style={{ minWidth: 0, flex: 1 }}>
|
||||
<RecursiveListErrorBoundary resetKey={node.label} code="RECURSIVE_LIST_BRANCH_RENDER_ERROR">
|
||||
{node.label}
|
||||
</RecursiveListErrorBoundary>
|
||||
</Box>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
function collectInitialExpandedState(nodes: readonly TreeNodeData[], depthLimit: number) {
|
||||
const expanded: Record<string, boolean> = {};
|
||||
const visit = (values: readonly TreeNodeData[], depth: number) => {
|
||||
for (const node of values) {
|
||||
if (!node.children?.length || depth >= depthLimit) continue;
|
||||
expanded[node.value] = true;
|
||||
visit(node.children, depth + 1);
|
||||
}
|
||||
};
|
||||
visit(nodes, 0);
|
||||
return expanded;
|
||||
}
|
||||
|
||||
function clampInteger(value: number, minimum: number, maximum: number, fallback: number) {
|
||||
if (!Number.isFinite(value)) return fallback;
|
||||
return Math.min(maximum, Math.max(minimum, Math.trunc(value)));
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import { SubData } from "../runtime/data";
|
||||
import { RefreshButton } from "../runtime/refresh-button";
|
||||
import { SubFetch } from "../runtime/sub-fetch";
|
||||
import { Collapsible, PaginatedList, StatBar, TabPanel, TabsContainer, TypeBadge } from "./interactive-components";
|
||||
import { TrustedRecursiveList } from "./recursive-list";
|
||||
import { getScopedCustomJsxControlName, isSafeCustomJsxUrl } from "./runtime-component-policy";
|
||||
import { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
|
||||
@@ -278,7 +277,6 @@ export function createCustomJsxComponents(adapters: CustomJsxComponentAdapters):
|
||||
ActionButton,
|
||||
ToggleSwitch,
|
||||
RefreshButton,
|
||||
RecursiveList: TrustedRecursiveList,
|
||||
});
|
||||
return components;
|
||||
}
|
||||
@@ -20,6 +20,7 @@ export const CUSTOM_JSX_CALLBACK_METHODS: ReadonlySet<string> = new Set([
|
||||
"filter",
|
||||
"find",
|
||||
"findIndex",
|
||||
"flatMap",
|
||||
"map",
|
||||
"reduce",
|
||||
"some",
|
||||
@@ -30,12 +31,16 @@ export const CUSTOM_JSX_SAFE_VALUE_METHODS: ReadonlySet<string> = new Set([
|
||||
...CUSTOM_JSX_CALLBACK_METHODS,
|
||||
"at",
|
||||
"charAt",
|
||||
"concat",
|
||||
"endsWith",
|
||||
"flat",
|
||||
"flatMap",
|
||||
"includes",
|
||||
"indexOf",
|
||||
"join",
|
||||
"lastIndexOf",
|
||||
"localeCompare",
|
||||
"match",
|
||||
"padEnd",
|
||||
"padStart",
|
||||
"pop",
|
||||
@@ -44,10 +49,12 @@ export const CUSTOM_JSX_SAFE_VALUE_METHODS: ReadonlySet<string> = new Set([
|
||||
"replaceAll",
|
||||
"reverse",
|
||||
"slice",
|
||||
"search",
|
||||
"split",
|
||||
"startsWith",
|
||||
"substring",
|
||||
"toFixed",
|
||||
"toLocaleString",
|
||||
"toLowerCase",
|
||||
"toPrecision",
|
||||
"toString",
|
||||
@@ -55,4 +62,5 @@ export const CUSTOM_JSX_SAFE_VALUE_METHODS: ReadonlySet<string> = new Set([
|
||||
"trim",
|
||||
"trimEnd",
|
||||
"trimStart",
|
||||
"test",
|
||||
]);
|
||||
@@ -0,0 +1,119 @@
|
||||
import { numericArgument, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { InterpreterMethodContext } from "./interpreter-method-context";
|
||||
|
||||
export function callStringMethod(
|
||||
receiver: string,
|
||||
method: string,
|
||||
args: unknown[],
|
||||
context: InterpreterMethodContext,
|
||||
): { handled: boolean; value?: unknown } {
|
||||
switch (method) {
|
||||
case "toUpperCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toUpperCase()) };
|
||||
case "toLowerCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toLowerCase()) };
|
||||
case "trim":
|
||||
return { handled: true, value: context.budget.string(receiver.trim()) };
|
||||
case "trimStart":
|
||||
return { handled: true, value: context.budget.string(receiver.trimStart()) };
|
||||
case "trimEnd":
|
||||
return { handled: true, value: context.budget.string(receiver.trimEnd()) };
|
||||
case "replace": {
|
||||
const search = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search instanceof RegExp)
|
||||
return { handled: true, value: context.budget.string(receiver.replace(search, replacement)) };
|
||||
const matchIndex = receiver.indexOf(search);
|
||||
if (matchIndex === -1) return { handled: true, value: context.budget.string(receiver) };
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.slice(0, matchIndex) + replacement + receiver.slice(matchIndex + search.length),
|
||||
),
|
||||
};
|
||||
}
|
||||
case "replaceAll": {
|
||||
const search = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search instanceof RegExp) {
|
||||
if (!search.global) throw new SafeJsxError("replaceAll() requires a global regular expression");
|
||||
return { handled: true, value: context.budget.string(receiver.replaceAll(search, replacement)) };
|
||||
}
|
||||
if (search.length === 0) return { handled: true, value: context.budget.string(receiver) };
|
||||
let result = "";
|
||||
let cursor = 0;
|
||||
while (cursor < receiver.length) {
|
||||
const matchIndex = receiver.indexOf(search, cursor);
|
||||
if (matchIndex === -1) {
|
||||
result += receiver.slice(cursor);
|
||||
break;
|
||||
}
|
||||
result += receiver.slice(cursor, matchIndex) + replacement;
|
||||
cursor = matchIndex + search.length;
|
||||
}
|
||||
return { handled: true, value: context.budget.string(result) };
|
||||
}
|
||||
case "indexOf":
|
||||
return { handled: true, value: receiver.indexOf(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "lastIndexOf": {
|
||||
const fromIndex = args[1] !== undefined ? numericArgument(args[1], receiver.length) : undefined;
|
||||
return { handled: true, value: receiver.lastIndexOf(String(args[0] ?? ""), fromIndex) };
|
||||
}
|
||||
case "repeat": {
|
||||
const maxCount = receiver.length > 0 ? Math.floor(200_001 / receiver.length) : 0;
|
||||
const count = Math.max(0, Math.min(numericArgument(args[0], 0), maxCount));
|
||||
return { handled: true, value: context.budget.string(receiver.repeat(count).slice(0, 200_001)) };
|
||||
}
|
||||
case "slice":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.slice(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "substring":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.substring(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "includes":
|
||||
return { handled: true, value: receiver.includes(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "startsWith":
|
||||
return { handled: true, value: receiver.startsWith(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "endsWith":
|
||||
return { handled: true, value: receiver.endsWith(String(args[0] ?? ""), args[1] as number | undefined) };
|
||||
case "padStart":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padStart(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "padEnd":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padEnd(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "charAt":
|
||||
return { handled: true, value: receiver.charAt(numericArgument(args[0], 0)) };
|
||||
case "localeCompare":
|
||||
return { handled: true, value: receiver.localeCompare(String(args[0] ?? "")) };
|
||||
case "split": {
|
||||
const limit = Math.max(0, Math.min(2_000, numericArgument(args[1], 2_000)));
|
||||
const separator = args[0] instanceof RegExp ? args[0] : args[0] === undefined ? undefined : String(args[0]);
|
||||
const split = separator === undefined ? [receiver] : receiver.split(separator, limit);
|
||||
context.budget.collection(split.length);
|
||||
return { handled: true, value: split };
|
||||
}
|
||||
case "match": {
|
||||
const pattern = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const matches = receiver.match(pattern);
|
||||
if (matches) context.budget.collection(matches.length);
|
||||
return { handled: true, value: matches ? [...matches] : null };
|
||||
}
|
||||
case "search":
|
||||
return { handled: true, value: receiver.search(args[0] instanceof RegExp ? args[0] : String(args[0] ?? "")) };
|
||||
default:
|
||||
return { handled: false };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user