revert: keep only minimal review fixes

This commit is contained in:
ajnart committed 2026-08-22 09:00:57 +02:00
1 parent caf1f6621a
commit 396b78aa3e
39 files changed
+421 -958

No files matched your search

@@ -2,7 +2,6 @@ export * from "./bundled-widgets";
export * from "./examples";
export * from "./import";
export * from "./options";
export * from "./request-limits";
export * from "./schema";
export * from "./schema-references";
export * from "./secret-requirements";
@@ -1 +0,0 @@
export const CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT = 4;
@@ -24,10 +24,6 @@ export interface RenderSafeJsxOptions {
budgets?: SafeJsxBudgets;
}
export interface RenderCompiledSafeJsxOptions extends Omit<RenderSafeJsxOptions, "template"> {
root: AstNode;
}
export interface SafeJsxRenderResult {
node: ReactNode;
warnings: string[];
@@ -355,23 +351,11 @@ class Interpreter {
}
}
export function compileSafeJsx(template: string): AstNode {
return parseCustomJsxTemplate(template);
}
export function renderCompiledSafeJsx({
root,
components,
bindings,
budgets,
}: RenderCompiledSafeJsxOptions): SafeJsxRenderResult {
export function renderSafeJsx({ template, components, bindings, budgets }: RenderSafeJsxOptions): SafeJsxRenderResult {
const limits: EvaluationBudgets = { ...DEFAULT_BUDGETS, ...budgets };
for (const [name, value] of Object.entries(limits)) {
if (!Number.isSafeInteger(value) || value <= 0) throw new SafeJsxError(`Invalid interpreter budget: ${name}`);
}
const root = parseCustomJsxTemplate(template);
return new Interpreter(components, new Environment(bindings), limits).render(root);
}
export function renderSafeJsx({ template, ...options }: RenderSafeJsxOptions): SafeJsxRenderResult {
return renderCompiledSafeJsx({ ...options, root: compileSafeJsx(template) });
}
@@ -68,7 +68,7 @@ export function emitJsxElement(
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, metadata: unknown) => context.renderCallback(callback, [value, metadata], depth + 1);
return (value: unknown) => context.renderCallback(callback, [value], depth + 1);
}
return context.evaluate(child, environment, depth + 1);
});
@@ -3,14 +3,12 @@ import { Component, useCallback, useEffect, useId, useMemo, useState } from "rea
import { Alert, Box, Stack, Text } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { compileSafeJsx, renderCompiledSafeJsx } from "../jsx/interpreter";
import { renderSafeJsx } from "../jsx/interpreter";
import { CustomJsxInputsProvider } from "../jsx/runtime-components";
import type { WidgetInputType, WidgetInputValue } from "../jsx/runtime-components";
import type { CustomJsxRequestCapability } from "./types";
const EMPTY_RECORD: Record<string, never> = {};
const referenceIds = new WeakMap<object, number>();
let nextReferenceId = 1;
const methodColors: Readonly<Record<string, string>> = {
GET: "blue",
@@ -164,27 +162,12 @@ function CustomJsxRendererSession({
},
[inputTypes],
);
const compiled = useMemo(() => {
try {
return { root: compileSafeJsx(template), error: null };
} catch (error) {
return { root: null, error: error instanceof Error ? error : new Error(String(error)) };
}
}, [template]);
const rendered = useMemo(() => {
if (compiled.error || !compiled.root) {
return {
node: null,
warnings: [],
boundaryKey: `${template.length}:compile-error`,
error: compiled.error ?? new Error("Template compilation failed"),
};
}
try {
const bindings = { ...createBindings(data), status, options, inputs };
return {
...renderCompiledSafeJsx({ root: compiled.root, components, bindings }),
boundaryKey: createBoundaryKey(template, [data, status, options, inputs]),
...renderSafeJsx({ template, components, bindings }),
boundaryKey: createBoundaryKey(template, bindings),
error: null,
};
} catch (error) {
@@ -195,7 +178,7 @@ function CustomJsxRendererSession({
error: error instanceof Error ? error : new Error(String(error)),
};
}
}, [compiled, components, createBindings, data, inputs, options, status, template]);
}, [components, createBindings, data, inputs, options, status, template]);
useEffect(() => setParseErrors([]), [rendered.boundaryKey, template]);
const handleError = useCallback(
(error: Error) =>
@@ -245,20 +228,9 @@ function CustomJsxRendererSession({
);
}
function createBoundaryKey(template: string, values: readonly unknown[]) {
return `${template.length}:${values.map(referenceKey).join(":")}`;
}
function referenceKey(value: unknown): string {
if ((typeof value === "object" && value !== null) || typeof value === "function") {
const reference = value as object;
let id = referenceIds.get(reference);
if (!id) {
id = nextReferenceId;
nextReferenceId += 1;
referenceIds.set(reference, id);
}
return `r${id}`;
}
return `${typeof value}:${String(value)}`;
function createBoundaryKey(template: string, bindings: Readonly<Record<string, unknown>>) {
let hash = 0;
const value = `${template}\0${JSON.stringify(bindings)}`;
for (let index = 0; index < value.length; index += 1) hash = (hash * 31 + value.charCodeAt(index)) | 0;
return `${template.length}:${hash}`;
}
@@ -37,7 +37,7 @@ export function RefreshButton({ label, color = "gray", variant = "subtle", size
size={size as never}
onClick={() => void refresh()}
loading={loading}
disabled={!runtime.canRefresh || (!runtime.itemId && !runtime.previewSessionId) || runtime.isEditMode}
disabled={(!runtime.itemId && !runtime.previewSessionId) || runtime.isEditMode}
>
<IconRefresh size={16} />
</ActionIcon>
@@ -82,7 +82,6 @@ export interface CustomWidgetRuntimeValue {
previewSessionId?: string;
previewLiveActions?: boolean;
queriesDisabled?: boolean;
canRefresh?: boolean;
isEditMode: boolean;
requestCapabilities: readonly CustomJsxRequestCapability[];
port: CustomWidgetRuntimePort;
@@ -19,6 +19,7 @@ export type { CustomWidgetAuthConfig, CustomWidgetHttpRequest, CustomWidgetHttpR
export {
CUSTOM_WIDGET_DEFINITION_CONCURRENCY_LIMIT,
CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS,
CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT,
CustomWidgetRequestLimiter,
} from "./request-limits";
export type { RequestLimitInput, RequestLimiterOptions, RequestLimitStore } from "./request-limits";
@@ -13,8 +13,7 @@ import {
validateCustomWidgetUrl,
} from "./network-policy";
import { closeDispatcher } from "./request-dispatcher-lifecycle";
import { isCustomWidgetRequestTimeoutError } from "./request-timeout";
import { normalizeResponseHeaders, parseResponseBody } from "./response";
import { parseResponseBody } from "./response";
export {
assertSafeStaticHeaders,
@@ -29,14 +28,13 @@ export {
MAX_RESPONSE_JSON_DEPTH,
MAX_RESPONSE_JSON_NODES,
} from "./response";
export { isCustomWidgetRequestTimeoutError } from "./request-timeout";
export const MAX_REQUEST_BODY_BYTES = 10 * 1024;
const REQUEST_TIMEOUT_MS = 10_000;
const MAX_QUERY_REDIRECTS = 3;
const MAX_RESPONSE_CACHE_ENTRIES = 1_000;
const MAX_RESPONSE_CACHE_BYTES = 64 * 1024 * 1024;
export const MAX_REQUEST_DURATION_MS = 45_000;
const TIMEOUT_ERROR_CODES = new Set(["UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"]);
const RESPONSE_TOO_LARGE_ERROR_CODE = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
export interface CustomWidgetAuthConfig {
@@ -65,10 +63,9 @@ export interface CustomWidgetHttpResponse {
statusText: string;
data: unknown;
}
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse; size: number }>();
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse }>();
const inFlight = new Map<string, Promise<CustomWidgetHttpResponse>>();
let cacheEpoch = 0;
let cacheBytes = 0;
type RequestHopResult =
| { kind: "response"; response: CustomWidgetHttpResponse }
@@ -220,6 +217,23 @@ async function performRequestWithinDeadline(
}
}
export function isCustomWidgetRequestTimeoutError(error: unknown, ...signals: readonly AbortSignal[]): boolean {
if (signals.some((signal) => signal.aborted)) return true;
if (!(error instanceof Error)) return false;
if (error.name.includes("Timeout")) return true;
const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
return code !== undefined && TIMEOUT_ERROR_CODES.has(code);
}
function normalizeResponseHeaders(values: Record<string, string | string[] | undefined>) {
const headers = new Headers();
for (const [name, value] of Object.entries(values)) {
if (Array.isArray(value)) value.forEach((entry) => headers.append(name, entry));
else if (value !== undefined) headers.set(name, value);
}
return headers;
}
function assertRequest(input: CustomWidgetHttpRequest): void {
if (input.body !== undefined && Buffer.byteLength(input.body, "utf8") > MAX_REQUEST_BODY_BYTES)
throw new CustomWidgetDomainError({ code: "PAYLOAD_TOO_LARGE", message: "Request body exceeds the 10 KiB limit" });
@@ -242,12 +256,8 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
const key = input.kind === "query" ? input.cacheKey : undefined;
if (!key) return performRequest(input);
const cached = cache.get(key);
if (cached && cached.expiresAt > Date.now()) {
cache.delete(key);
cache.set(key, cached);
return cached.response;
}
if (cached) deleteCachedResponse(key);
if (cached && cached.expiresAt > Date.now()) return cached.response;
if (cached) cache.delete(key);
const pending = inFlight.get(key);
if (pending) return pending;
const requestEpoch = cacheEpoch;
@@ -255,12 +265,8 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
request = performRequest(input)
.then((response) => {
if (response.ok && (input.cacheTtlSeconds ?? 0) > 0 && requestEpoch === cacheEpoch) {
const size = Buffer.byteLength(JSON.stringify(response), "utf8");
if (size <= MAX_RESPONSE_CACHE_BYTES) {
pruneCache(size);
cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response, size });
cacheBytes += size;
}
pruneCache();
cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response });
}
return response;
})
@@ -274,22 +280,15 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
export function invalidateCustomWidgetResponseCache(prefixes: readonly string[]): void {
if (prefixes.length === 0) return;
cacheEpoch += 1;
for (const key of cache.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) deleteCachedResponse(key);
for (const key of cache.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) cache.delete(key);
for (const key of inFlight.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) inFlight.delete(key);
}
function pruneCache(incomingSize: number): void {
for (const [key, entry] of cache) if (entry.expiresAt <= Date.now()) deleteCachedResponse(key);
while (cache.size >= MAX_RESPONSE_CACHE_ENTRIES || cacheBytes + incomingSize > MAX_RESPONSE_CACHE_BYTES) {
function pruneCache(): void {
for (const [key, entry] of cache) if (entry.expiresAt <= Date.now()) cache.delete(key);
while (cache.size >= MAX_RESPONSE_CACHE_ENTRIES) {
const key = cache.keys().next().value as string | undefined;
if (!key) return;
deleteCachedResponse(key);
cache.delete(key);
}
}
function deleteCachedResponse(key: string): void {
const cached = cache.get(key);
if (!cached) return;
cache.delete(key);
cacheBytes = Math.max(0, cacheBytes - cached.size);
}
@@ -1,6 +1,5 @@
import { createHash, randomUUID } from "node:crypto";
import { CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT } from "../core/request-limits";
import { CustomWidgetDomainError } from "./errors";
const WINDOW_MS = 60_000;
@@ -8,6 +7,7 @@ const WINDOW_MS = 60_000;
// Keep the lease above that total and identify every acquisition so a late
// release can never remove capacity owned by a newer request.
export const CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS = 60_000;
export const CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT = 4;
export const CUSTOM_WIDGET_DEFINITION_CONCURRENCY_LIMIT = 8;
const CATEGORY_LIMITS = { query: 60, action: 10, delete: 3 } as const;
const DEFINITION_CATEGORY_LIMITS = { query: 240, action: 40, delete: 12 } as const;
@@ -1,9 +0,0 @@
const TIMEOUT_ERROR_CODES = new Set(["UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"]);
export function isCustomWidgetRequestTimeoutError(error: unknown, ...signals: readonly AbortSignal[]): boolean {
if (signals.some((signal) => signal.aborted)) return true;
if (!(error instanceof Error)) return false;
if (error.name.includes("Timeout")) return true;
const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
return code !== undefined && TIMEOUT_ERROR_CODES.has(code);
}
@@ -1,4 +1,3 @@
import { Headers } from "undici";
import type { Response } from "undici";
import { CustomWidgetDomainError } from "./errors";
@@ -6,15 +5,6 @@ export const MAX_RESPONSE_BODY_BYTES = 1024 * 1024;
export const MAX_RESPONSE_JSON_DEPTH = 32;
export const MAX_RESPONSE_JSON_NODES = 50_000;
export function normalizeResponseHeaders(values: Record<string, string | string[] | undefined>) {
const headers = new Headers();
for (const [name, value] of Object.entries(values)) {
if (Array.isArray(value)) value.forEach((entry) => headers.append(name, entry));
else if (value !== undefined) headers.set(name, value);
}
return headers;
}
export function assertJsonBudget(value: unknown): void {
let nodes = 0;
const visit = (current: unknown, depth: number): void => {