@littlepress/renderer-web 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +20 -0
- package/README.md +229 -2
- package/dist/answer/answerComponents.d.ts +107 -0
- package/dist/answer/answerComponents.js +637 -0
- package/dist/answer/download.d.ts +63 -0
- package/dist/answer/download.js +109 -0
- package/dist/answer/downloadExport.d.ts +44 -0
- package/dist/answer/downloadExport.js +266 -0
- package/dist/answer/hostValues.d.ts +28 -0
- package/dist/answer/hostValues.js +379 -0
- package/dist/answer/mapComponent.d.ts +6 -0
- package/dist/answer/mapComponent.js +213 -0
- package/dist/answer/math.d.ts +57 -0
- package/dist/answer/math.js +168 -0
- package/dist/answer/surfaceStream.d.ts +51 -0
- package/dist/answer/surfaceStream.js +260 -0
- package/dist/answer/tableLayout.d.ts +42 -0
- package/dist/answer/tableLayout.js +89 -0
- package/dist/controls/ActionFeedback.d.ts +5 -0
- package/dist/controls/ActionFeedback.js +43 -0
- package/dist/controls/actionDispatch.d.ts +51 -0
- package/dist/controls/actionDispatch.js +211 -0
- package/dist/controls/actionOutcome.generated.d.ts +64 -0
- package/dist/controls/actionOutcome.generated.js +64 -0
- package/dist/controls/calculationPublisher.d.ts +14 -0
- package/dist/controls/calculationPublisher.js +6 -0
- package/dist/controls/calculations.d.ts +20 -0
- package/dist/controls/calculations.generated.d.ts +73 -0
- package/dist/controls/calculations.generated.js +85 -0
- package/dist/controls/calculations.js +208 -0
- package/dist/controls/controlState.d.ts +84 -0
- package/dist/controls/controlState.js +256 -0
- package/dist/controls/fieldMessages.d.ts +41 -0
- package/dist/controls/fieldMessages.js +81 -0
- package/dist/controls/fieldValidation.d.ts +19 -0
- package/dist/controls/fieldValidation.js +98 -0
- package/dist/controls/formComponents.d.ts +23 -0
- package/dist/controls/formComponents.js +738 -0
- package/dist/controls/formProgress.d.ts +63 -0
- package/dist/controls/formProgress.js +122 -0
- package/dist/controls/inputDrafts.d.ts +55 -0
- package/dist/controls/inputDrafts.js +183 -0
- package/dist/controls/inputValidation.d.ts +33 -0
- package/dist/controls/inputValidation.js +119 -0
- package/dist/controls/localWrites.d.ts +9 -0
- package/dist/controls/localWrites.js +29 -0
- package/dist/core/A2uiSurface.d.ts +13 -0
- package/dist/core/A2uiSurface.js +15 -0
- package/dist/core/AtlasIcon.d.ts +18 -0
- package/dist/core/AtlasIcon.js +22 -0
- package/dist/core/AtlasMedia.d.ts +22 -0
- package/dist/core/AtlasMedia.js +45 -0
- package/dist/core/Carousel.d.ts +61 -0
- package/dist/core/Carousel.js +183 -0
- package/dist/core/CoreMedia.d.ts +19 -0
- package/dist/core/CoreMedia.js +25 -0
- package/dist/core/FoundationA2uiSurface.d.ts +86 -0
- package/dist/core/FoundationA2uiSurface.js +440 -0
- package/dist/core/ImagePreview.d.ts +42 -0
- package/dist/core/ImagePreview.js +73 -0
- package/dist/core/LucideIcon.d.ts +19 -0
- package/dist/core/LucideIcon.js +42 -0
- package/dist/core/SurfaceLink.d.ts +35 -0
- package/dist/core/SurfaceLink.js +60 -0
- package/dist/core/appearance/aegis.d.ts +49 -0
- package/dist/core/appearance/aegis.js +34 -0
- package/dist/core/appearance/colour.d.ts +24 -0
- package/dist/core/appearance/colour.js +103 -0
- package/dist/core/appearance/css.d.ts +17 -0
- package/dist/core/appearance/css.js +153 -0
- package/dist/core/appearance/presets.generated.d.ts +4 -0
- package/dist/core/appearance/presets.generated.js +1184 -0
- package/dist/core/appearance/react.d.ts +29 -0
- package/dist/core/appearance/react.js +110 -0
- package/dist/core/appearance/resolve.d.ts +76 -0
- package/dist/core/appearance/resolve.js +127 -0
- package/dist/core/appearance/textScale.d.ts +11 -0
- package/dist/core/appearance/textScale.js +51 -0
- package/dist/core/appearance/theme.d.ts +138 -0
- package/dist/core/appearance/theme.js +274 -0
- package/dist/core/baseComponents.d.ts +53 -0
- package/dist/core/baseComponents.js +480 -0
- package/dist/core/binding.d.ts +46 -0
- package/dist/core/binding.js +118 -0
- package/dist/core/bundle.d.ts +23 -0
- package/dist/core/bundle.js +75 -0
- package/dist/core/catalog/catalog-index.generated.d.ts +44 -0
- package/dist/core/catalog/catalog-index.generated.js +79 -0
- package/dist/core/catalog/icons.generated.d.ts +6 -0
- package/dist/core/catalog/icons.generated.js +1788 -0
- package/dist/core/catalog.d.ts +6 -0
- package/dist/core/catalog.generated.d.ts +50 -0
- package/dist/core/catalog.generated.js +2174 -0
- package/dist/core/catalog.js +8 -0
- package/dist/core/chartRows.d.ts +7 -0
- package/dist/core/chartRows.js +38 -0
- package/dist/core/component-support.d.ts +39 -0
- package/dist/core/component-support.js +127 -0
- package/dist/core/components/actions.d.ts +4 -0
- package/dist/core/components/actions.js +21 -0
- package/dist/core/components/cards.d.ts +9 -0
- package/dist/core/components/cards.js +227 -0
- package/dist/core/components/charts.d.ts +18 -0
- package/dist/core/components/charts.js +412 -0
- package/dist/core/components/comparisonTable.d.ts +50 -0
- package/dist/core/components/comparisonTable.js +89 -0
- package/dist/core/components/content.d.ts +13 -0
- package/dist/core/components/content.js +108 -0
- package/dist/core/components/seriesCharts.d.ts +531 -0
- package/dist/core/components/seriesCharts.js +1053 -0
- package/dist/core/components/stepFlow.d.ts +7 -0
- package/dist/core/components/stepFlow.js +13 -0
- package/dist/core/components.full.d.ts +10 -0
- package/dist/core/components.full.js +41 -0
- package/dist/core/context.d.ts +207 -0
- package/dist/core/context.js +172 -0
- package/dist/core/coverage.d.ts +30 -0
- package/dist/core/coverage.js +93 -0
- package/dist/core/foundation.d.ts +21 -0
- package/dist/core/foundation.js +22 -0
- package/dist/core/fullTheme.d.ts +5 -0
- package/dist/core/fullTheme.js +9 -0
- package/dist/core/iconNodes.generated.d.ts +7 -0
- package/dist/core/iconNodes.generated.js +5 -0
- package/dist/core/lucideIcons.d.ts +5 -0
- package/dist/core/lucideIcons.js +7 -0
- package/dist/core/messages.d.ts +111 -0
- package/dist/core/messages.js +134 -0
- package/dist/core/pointer.d.ts +17 -0
- package/dist/core/pointer.js +104 -0
- package/dist/core/registry.d.ts +12 -0
- package/dist/core/registry.js +114 -0
- package/dist/core/runtime.d.ts +8 -0
- package/dist/core/runtime.js +6 -0
- package/dist/core/state.d.ts +73 -0
- package/dist/core/state.js +274 -0
- package/dist/core/surfaceMotion.d.ts +5 -0
- package/dist/core/surfaceMotion.js +46 -0
- package/dist/core/theme.d.ts +5 -0
- package/dist/core/theme.js +7 -0
- package/dist/core/useSurfaceImage.d.ts +20 -0
- package/dist/core/useSurfaceImage.js +65 -0
- package/dist/graph/RelationshipGraph.d.ts +14 -0
- package/dist/graph/RelationshipGraph.js +206 -0
- package/dist/graph/model.d.ts +20 -0
- package/dist/graph/model.js +36 -0
- package/dist/graph/program/assets.d.ts +3 -0
- package/dist/graph/program/assets.js +3 -0
- package/dist/graph/program/bridge.d.ts +6 -0
- package/dist/graph/program/bridge.generated.d.ts +136 -0
- package/dist/graph/program/bridge.generated.js +1 -0
- package/dist/graph/program/bridge.js +24 -0
- package/dist/graph/program/bridge.schema.json +717 -0
- package/dist/graph/program/bridgeValidator.cjs +2 -0
- package/dist/graph/program/bridgeValidator.d.cts +4 -0
- package/dist/graph/program/runner.d.ts +1 -0
- package/dist/graph/program/runner.html +2193 -0
- package/dist/graph/program/runner.js +157 -0
- package/dist/graph/program/runtime-manifest.json +1 -0
- package/dist/graph/program/view.d.ts +11 -0
- package/dist/graph/program/view.js +210 -0
- package/dist/graph/program/worker.d.ts +1 -0
- package/dist/graph/program/worker.js +2186 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +45 -0
- package/dist/internal/dsh.d.ts +4 -0
- package/dist/internal/dsh.js +3 -0
- package/dist/internal/relationship-graph.d.ts +4 -0
- package/dist/internal/relationship-graph.js +7202 -0
- package/dist/page/layoutComponents.d.ts +6 -0
- package/dist/page/layoutComponents.js +123 -0
- package/dist/page/layoutGeometry.d.ts +68 -0
- package/dist/page/layoutGeometry.js +174 -0
- package/dist/page/pageFormat.d.ts +34 -0
- package/dist/page/pageFormat.js +119 -0
- package/dist/page/printFit.d.ts +81 -0
- package/dist/page/printFit.js +338 -0
- package/dist/react/index.d.ts +5 -0
- package/dist/react/index.js +2 -0
- package/dist/report/locate.d.ts +42 -0
- package/dist/report/locate.js +34 -0
- package/dist/styles/renderer.css +4580 -0
- package/licenses/LUCIDE-LICENSE.txt +43 -0
- package/licenses/QUICKJS-EMSCRIPTEN-LICENSE.txt +21 -0
- package/licenses/QUICKJS-VARIANT-LICENSE.txt +47 -0
- package/package.json +68 -3
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { A2uiComponent } from "../core/messages.ts";
|
|
2
|
+
import type { ComponentRenderer, SaveFileHandler } from "../core/context.ts";
|
|
3
|
+
import { type DownloadError, type DownloadFormat } from "./downloadExport.ts";
|
|
4
|
+
type Status = {
|
|
5
|
+
kind: "idle";
|
|
6
|
+
} | {
|
|
7
|
+
kind: "saving";
|
|
8
|
+
} | {
|
|
9
|
+
kind: "saved";
|
|
10
|
+
name: string;
|
|
11
|
+
} | {
|
|
12
|
+
kind: "error";
|
|
13
|
+
reason: DownloadError | "save_failed";
|
|
14
|
+
};
|
|
15
|
+
declare const copy: {
|
|
16
|
+
en: {
|
|
17
|
+
saved: (name: string) => string;
|
|
18
|
+
too_large: string;
|
|
19
|
+
invalid_data: string;
|
|
20
|
+
save_failed: string;
|
|
21
|
+
};
|
|
22
|
+
zh: {
|
|
23
|
+
saved: (name: string) => string;
|
|
24
|
+
too_large: string;
|
|
25
|
+
invalid_data: string;
|
|
26
|
+
save_failed: string;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* The browser's own download: a Blob URL clicked through a temporary `<a download>`, revoked
|
|
31
|
+
* once the click has been handled. The browser decides where the file goes, so this reports saved.
|
|
32
|
+
*/
|
|
33
|
+
export declare const saveWithBlobUrl: SaveFileHandler;
|
|
34
|
+
type Copy = (typeof copy)["en"];
|
|
35
|
+
/**
|
|
36
|
+
* One button's saves: writes the file, hands it to `save`, and reports each step to
|
|
37
|
+
* `onStatus`. A tap while a save is still open does nothing.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createDownloadSession(onStatus: (status: Status) => void): {
|
|
40
|
+
readonly busy: boolean;
|
|
41
|
+
tap(value: unknown, format: DownloadFormat, columns: readonly string[] | null, name: string, save: SaveFileHandler): Promise<void>;
|
|
42
|
+
};
|
|
43
|
+
export type DownloadSession = ReturnType<typeof createDownloadSession>;
|
|
44
|
+
export type DownloadStatus = Status;
|
|
45
|
+
export declare function downloadCopy(chinese: boolean): Copy;
|
|
46
|
+
/** The button and its messages for one state; `onTap` is left off while the answer streams. */
|
|
47
|
+
export declare function DownloadView({ label, format, status, streaming, text, onTap }: {
|
|
48
|
+
label: string;
|
|
49
|
+
format: DownloadFormat;
|
|
50
|
+
status: Status;
|
|
51
|
+
streaming: boolean;
|
|
52
|
+
text: Copy;
|
|
53
|
+
onTap: () => void;
|
|
54
|
+
}): import("react/jsx-runtime").JSX.Element;
|
|
55
|
+
/** What a download component asks for, read from its props. */
|
|
56
|
+
export declare function downloadProps(component: A2uiComponent): {
|
|
57
|
+
format: DownloadFormat;
|
|
58
|
+
label: string;
|
|
59
|
+
columns: string[] | null;
|
|
60
|
+
name: string;
|
|
61
|
+
};
|
|
62
|
+
export declare const renderDownload: ComponentRenderer;
|
|
63
|
+
export {};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useRef, useState } from "react";
|
|
3
|
+
import { resolveValue } from "../core/binding.js";
|
|
4
|
+
import { isChineseLanguage, surfaceLanguage } from "../controls/fieldMessages.js";
|
|
5
|
+
import { surfaceIsStreaming } from "../controls/actionDispatch.js";
|
|
6
|
+
import { LucideIcon } from "../core/LucideIcon.js";
|
|
7
|
+
import { downloadFile, safeDownloadFilename } from "./downloadExport.js";
|
|
8
|
+
const copy = {
|
|
9
|
+
en: {
|
|
10
|
+
saved: (name) => `Saved ${name}`,
|
|
11
|
+
too_large: "This file is larger than 1 MB, so it can't be saved.",
|
|
12
|
+
invalid_data: "This data can't be saved as a file.",
|
|
13
|
+
save_failed: "The file couldn't be saved. Try again.",
|
|
14
|
+
},
|
|
15
|
+
zh: {
|
|
16
|
+
saved: (name) => `已保存 ${name}`,
|
|
17
|
+
too_large: "文件超过 1 MB,无法保存。",
|
|
18
|
+
invalid_data: "这份数据无法保存为文件。",
|
|
19
|
+
save_failed: "文件没有保存成功,请重试。",
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The browser's own download: a Blob URL clicked through a temporary `<a download>`, revoked
|
|
24
|
+
* once the click has been handled. The browser decides where the file goes, so this reports saved.
|
|
25
|
+
*/
|
|
26
|
+
export const saveWithBlobUrl = (name, mime, bytes) => {
|
|
27
|
+
const blob = new Blob([bytes], { type: mime });
|
|
28
|
+
const url = URL.createObjectURL(blob);
|
|
29
|
+
try {
|
|
30
|
+
const link = document.createElement("a");
|
|
31
|
+
link.href = url;
|
|
32
|
+
link.download = name;
|
|
33
|
+
link.rel = "noopener";
|
|
34
|
+
link.style.display = "none";
|
|
35
|
+
document.body.appendChild(link);
|
|
36
|
+
link.click();
|
|
37
|
+
link.remove();
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
// Revoke after the click has been dispatched, so the download keeps its bytes.
|
|
41
|
+
setTimeout(() => URL.revokeObjectURL(url), 0);
|
|
42
|
+
}
|
|
43
|
+
return "saved";
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* One button's saves: writes the file, hands it to `save`, and reports each step to
|
|
47
|
+
* `onStatus`. A tap while a save is still open does nothing.
|
|
48
|
+
*/
|
|
49
|
+
export function createDownloadSession(onStatus) {
|
|
50
|
+
let busy = false;
|
|
51
|
+
return {
|
|
52
|
+
get busy() { return busy; },
|
|
53
|
+
async tap(value, format, columns, name, save) {
|
|
54
|
+
if (busy)
|
|
55
|
+
return;
|
|
56
|
+
const file = downloadFile(value, format, columns);
|
|
57
|
+
if (!file.ok) {
|
|
58
|
+
onStatus({ kind: "error", reason: file.error });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
busy = true;
|
|
62
|
+
onStatus({ kind: "saving" });
|
|
63
|
+
try {
|
|
64
|
+
const result = await save(name, file.mime, file.bytes);
|
|
65
|
+
onStatus(result === "cancelled" ? { kind: "idle" } : { kind: "saved", name });
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
onStatus({ kind: "error", reason: "save_failed" });
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
busy = false;
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
export function downloadCopy(chinese) {
|
|
77
|
+
return chinese ? copy.zh : copy.en;
|
|
78
|
+
}
|
|
79
|
+
/** The button and its messages for one state; `onTap` is left off while the answer streams. */
|
|
80
|
+
export function DownloadView({ label, format, status, streaming, text, onTap }) {
|
|
81
|
+
const saving = status.kind === "saving";
|
|
82
|
+
const message = status.kind === "error" ? text[status.reason] : null;
|
|
83
|
+
const announcement = status.kind === "saved" ? text.saved(status.name) : message ?? "";
|
|
84
|
+
return (_jsxs("div", { className: "lp-download", "data-download-state": status.kind, children: [_jsxs("button", { type: "button", className: "lp-btn", "data-format": format, disabled: streaming, "aria-disabled": streaming || saving || undefined, "aria-busy": saving || undefined, onClick: streaming ? undefined : onTap, children: [_jsx(LucideIcon, { name: "download", size: "sm", decorative: true }), _jsx("span", { children: label })] }), message ? _jsx("p", { className: "lp-field-error", "aria-hidden": "true", children: message }) : null, _jsx("p", { className: "lp-visually-hidden", role: "status", "aria-live": "polite", "aria-atomic": "true", children: announcement })] }));
|
|
85
|
+
}
|
|
86
|
+
/** What a download component asks for, read from its props. */
|
|
87
|
+
export function downloadProps(component) {
|
|
88
|
+
const format = component.format === "json" ? "json" : "csv";
|
|
89
|
+
const label = typeof component.label === "string" && component.label
|
|
90
|
+
? component.label : (format === "json" ? "Download JSON" : "Download CSV");
|
|
91
|
+
const columns = Array.isArray(component.columns)
|
|
92
|
+
? component.columns.filter((entry) => typeof entry === "string") : null;
|
|
93
|
+
return { format, label, columns, name: safeDownloadFilename(component.filename, format) };
|
|
94
|
+
}
|
|
95
|
+
function DownloadButton({ component, context }) {
|
|
96
|
+
const [status, setStatus] = useState({ kind: "idle" });
|
|
97
|
+
const session = useRef(null);
|
|
98
|
+
session.current ??= createDownloadSession(setStatus);
|
|
99
|
+
const { format, label, columns, name } = downloadProps(component);
|
|
100
|
+
const streaming = surfaceIsStreaming(context.state);
|
|
101
|
+
const onTap = () => {
|
|
102
|
+
if (streaming)
|
|
103
|
+
return;
|
|
104
|
+
const value = resolveValue(component.data, context.binding, context.valueFunctions);
|
|
105
|
+
void session.current.tap(value, format, columns, name, context.saveFile ?? saveWithBlobUrl);
|
|
106
|
+
};
|
|
107
|
+
return (_jsx(DownloadView, { label: label, format: format, status: status, streaming: streaming, text: downloadCopy(isChineseLanguage(surfaceLanguage(context.state?.rendererHints))), onTap: onTap }));
|
|
108
|
+
}
|
|
109
|
+
export const renderDownload = (component, context) => _jsx(DownloadButton, { component: component, context: context });
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export type DownloadFormat = "csv" | "json";
|
|
2
|
+
export type DownloadError = "too_large" | "invalid_data";
|
|
3
|
+
export type DownloadFile = {
|
|
4
|
+
ok: true;
|
|
5
|
+
bytes: Uint8Array;
|
|
6
|
+
mime: string;
|
|
7
|
+
} | {
|
|
8
|
+
ok: false;
|
|
9
|
+
error: DownloadError;
|
|
10
|
+
};
|
|
11
|
+
/** The most bytes a file may have; one more and nothing is saved. */
|
|
12
|
+
export declare const MAX_DOWNLOAD_BYTES: number;
|
|
13
|
+
export declare const DEFAULT_DOWNLOAD_NAME = "download";
|
|
14
|
+
export declare function downloadMime(format: DownloadFormat): string;
|
|
15
|
+
type Shape = "objects" | "rows";
|
|
16
|
+
/** `rows` for a 2-D list (and an empty list), `objects` for a list of flat objects, else null. */
|
|
17
|
+
export declare function downloadShape(value: unknown): Shape | null;
|
|
18
|
+
/**
|
|
19
|
+
* Whether two names are one text in two Unicode forms (equal in NFC, different code points):
|
|
20
|
+
* two `columns`, two keys of one row, or a key and the column that names it. Swift compares
|
|
21
|
+
* strings by canonical equivalence and Web and Kotlin by code points, so such a file would differ
|
|
22
|
+
* between platforms (a value dropped, another cell filled); it is refused instead.
|
|
23
|
+
*/
|
|
24
|
+
export declare function unicodeClash(rows: readonly Record<string, unknown>[], columns: readonly string[]): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Whether a column, a key or a text cell starts with U+FEFF. Swift's JSON decoding drops that
|
|
27
|
+
* character at the start of a string, so the file would differ between platforms; it is refused.
|
|
28
|
+
* Inside a string every platform keeps it.
|
|
29
|
+
*/
|
|
30
|
+
export declare function leadingBom(rows: readonly unknown[], columns: readonly string[]): boolean;
|
|
31
|
+
/** ECMAScript number text: what `String(n)` writes, which the native renderers reproduce. */
|
|
32
|
+
export declare function numberText(value: number): string;
|
|
33
|
+
/**
|
|
34
|
+
* The file for `value`: a list of flat objects (written in `columns` order, which it then
|
|
35
|
+
* needs) or a 2-D list whose first row is the header. `invalid_data` for anything else and
|
|
36
|
+
* `too_large` past 1 MiB, never a cut-off file.
|
|
37
|
+
*/
|
|
38
|
+
export declare function downloadFile(value: unknown, format: DownloadFormat, columns?: readonly string[] | null): DownloadFile;
|
|
39
|
+
/**
|
|
40
|
+
* The name a file is saved under: only letters, digits, spaces, `. _ - ( )` and printable
|
|
41
|
+
* non-ASCII characters, no leading dot, at most 80 code points, and the extension of `format`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function safeDownloadFilename(name: unknown, format: DownloadFormat): string;
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* What `LPDownload_Default` saves: the value at its `/data/` path written as a CSV or JSON file
|
|
3
|
+
* on the device. Compose and SwiftUI write the same bytes for every case of
|
|
4
|
+
* `contracts/fixtures/renderer/download-export.json`; nothing here depends on how an object's
|
|
5
|
+
* keys happen to be ordered.
|
|
6
|
+
*/
|
|
7
|
+
/** The most bytes a file may have; one more and nothing is saved. */
|
|
8
|
+
export const MAX_DOWNLOAD_BYTES = 1024 * 1024;
|
|
9
|
+
export const DEFAULT_DOWNLOAD_NAME = "download";
|
|
10
|
+
const MAX_NAME_BASE = 80;
|
|
11
|
+
const BOM = "";
|
|
12
|
+
export function downloadMime(format) {
|
|
13
|
+
return format === "csv" ? "text/csv;charset=utf-8" : "application/json";
|
|
14
|
+
}
|
|
15
|
+
function isCell(value) {
|
|
16
|
+
return value === null || typeof value === "string" || typeof value === "boolean"
|
|
17
|
+
|| (typeof value === "number" && Number.isFinite(value));
|
|
18
|
+
}
|
|
19
|
+
function isObject(value) {
|
|
20
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
21
|
+
}
|
|
22
|
+
/** `rows` for a 2-D list (and an empty list), `objects` for a list of flat objects, else null. */
|
|
23
|
+
export function downloadShape(value) {
|
|
24
|
+
if (!Array.isArray(value))
|
|
25
|
+
return null;
|
|
26
|
+
if (value.every((row) => Array.isArray(row) && row.every(isCell)))
|
|
27
|
+
return "rows";
|
|
28
|
+
if (value.every((row) => isObject(row) && Object.values(row).every(isCell)))
|
|
29
|
+
return "objects";
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Whether two names are one text in two Unicode forms (equal in NFC, different code points):
|
|
34
|
+
* two `columns`, two keys of one row, or a key and the column that names it. Swift compares
|
|
35
|
+
* strings by canonical equivalence and Web and Kotlin by code points, so such a file would differ
|
|
36
|
+
* between platforms (a value dropped, another cell filled); it is refused instead.
|
|
37
|
+
*/
|
|
38
|
+
export function unicodeClash(rows, columns) {
|
|
39
|
+
const named = new Map();
|
|
40
|
+
for (const column of columns) {
|
|
41
|
+
const form = column.normalize("NFC");
|
|
42
|
+
if ((named.get(form) ?? column) !== column)
|
|
43
|
+
return true;
|
|
44
|
+
named.set(form, column);
|
|
45
|
+
}
|
|
46
|
+
for (const row of rows) {
|
|
47
|
+
const seen = new Set();
|
|
48
|
+
for (const key of Object.keys(row)) {
|
|
49
|
+
const form = key.normalize("NFC");
|
|
50
|
+
if (seen.has(form) || (named.get(form) ?? key) !== key)
|
|
51
|
+
return true;
|
|
52
|
+
seen.add(form);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Whether a column, a key or a text cell starts with U+FEFF. Swift's JSON decoding drops that
|
|
59
|
+
* character at the start of a string, so the file would differ between platforms; it is refused.
|
|
60
|
+
* Inside a string every platform keeps it.
|
|
61
|
+
*/
|
|
62
|
+
export function leadingBom(rows, columns) {
|
|
63
|
+
const starts = (text) => typeof text === "string" && text.startsWith("\ufeff");
|
|
64
|
+
if (columns.some(starts))
|
|
65
|
+
return true;
|
|
66
|
+
return rows.some((row) => Array.isArray(row)
|
|
67
|
+
? row.some(starts)
|
|
68
|
+
: isObject(row) && Object.entries(row).some(([key, cell]) => starts(key) || starts(cell)));
|
|
69
|
+
}
|
|
70
|
+
/** ECMAScript number text: what `String(n)` writes, which the native renderers reproduce. */
|
|
71
|
+
export function numberText(value) {
|
|
72
|
+
return String(value);
|
|
73
|
+
}
|
|
74
|
+
const leadingSpace = /^[ \t\n\r\u000b\u000c]*/;
|
|
75
|
+
function csvCell(value) {
|
|
76
|
+
if (value === null || value === undefined)
|
|
77
|
+
return "";
|
|
78
|
+
if (typeof value === "boolean")
|
|
79
|
+
return value ? "true" : "false";
|
|
80
|
+
if (typeof value === "number")
|
|
81
|
+
return numberText(value);
|
|
82
|
+
let text = value;
|
|
83
|
+
// A spreadsheet runs a cell that starts like a formula; only text can, never a number.
|
|
84
|
+
const first = text.replace(leadingSpace, "").charAt(0);
|
|
85
|
+
if (text.startsWith("\t") || text.startsWith("\r") || first === "=" || first === "+" || first === "-" || first === "@") {
|
|
86
|
+
text = `'${text}`;
|
|
87
|
+
}
|
|
88
|
+
return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
|
89
|
+
}
|
|
90
|
+
function jsonString(value) {
|
|
91
|
+
let out = '"';
|
|
92
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
93
|
+
const code = value.charCodeAt(index);
|
|
94
|
+
const character = value[index];
|
|
95
|
+
if (character === '"')
|
|
96
|
+
out += '\\"';
|
|
97
|
+
else if (character === "\\")
|
|
98
|
+
out += "\\\\";
|
|
99
|
+
else if (character === "\b")
|
|
100
|
+
out += "\\b";
|
|
101
|
+
else if (character === "\f")
|
|
102
|
+
out += "\\f";
|
|
103
|
+
else if (character === "\n")
|
|
104
|
+
out += "\\n";
|
|
105
|
+
else if (character === "\r")
|
|
106
|
+
out += "\\r";
|
|
107
|
+
else if (character === "\t")
|
|
108
|
+
out += "\\t";
|
|
109
|
+
else if (code < 0x20)
|
|
110
|
+
out += `\\u${code.toString(16).padStart(4, "0")}`;
|
|
111
|
+
else
|
|
112
|
+
out += character;
|
|
113
|
+
}
|
|
114
|
+
return `${out}"`;
|
|
115
|
+
}
|
|
116
|
+
function jsonScalar(value) {
|
|
117
|
+
if (value === null)
|
|
118
|
+
return "null";
|
|
119
|
+
if (typeof value === "boolean")
|
|
120
|
+
return value ? "true" : "false";
|
|
121
|
+
if (typeof value === "number")
|
|
122
|
+
return numberText(value);
|
|
123
|
+
return jsonString(value);
|
|
124
|
+
}
|
|
125
|
+
/** Code-unit order, the same in every language: `<` on strings compares UTF-16 code units. */
|
|
126
|
+
function byCodeUnits(a, b) {
|
|
127
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
128
|
+
}
|
|
129
|
+
class TooLarge extends Error {
|
|
130
|
+
}
|
|
131
|
+
/** Collects UTF-8 bytes and stops as soon as there are more than the limit. */
|
|
132
|
+
class Writer {
|
|
133
|
+
encoder = new TextEncoder();
|
|
134
|
+
chunks = [];
|
|
135
|
+
size = 0;
|
|
136
|
+
write(text) {
|
|
137
|
+
const chunk = this.encoder.encode(text);
|
|
138
|
+
this.size += chunk.length;
|
|
139
|
+
if (this.size > MAX_DOWNLOAD_BYTES)
|
|
140
|
+
throw new TooLarge();
|
|
141
|
+
this.chunks.push(chunk);
|
|
142
|
+
}
|
|
143
|
+
bytes() {
|
|
144
|
+
const out = new Uint8Array(this.size);
|
|
145
|
+
let at = 0;
|
|
146
|
+
for (const chunk of this.chunks) {
|
|
147
|
+
out.set(chunk, at);
|
|
148
|
+
at += chunk.length;
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function writeCsv(writer, rows) {
|
|
154
|
+
writer.write(BOM);
|
|
155
|
+
const width = rows.reduce((widest, row) => Math.max(widest, row.length), 0);
|
|
156
|
+
for (const row of rows) {
|
|
157
|
+
const cells = Array.from({ length: width }, (_, index) => csvCell(row[index]));
|
|
158
|
+
writer.write(`${cells.join(",")}\r\n`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function writeJson(writer, value, shape, columns) {
|
|
162
|
+
if (value.length === 0) {
|
|
163
|
+
writer.write("[]\n");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
writer.write("[\n");
|
|
167
|
+
value.forEach((row, index) => {
|
|
168
|
+
const separator = index < value.length - 1 ? ",\n" : "\n";
|
|
169
|
+
let entries;
|
|
170
|
+
let open;
|
|
171
|
+
let close;
|
|
172
|
+
if (shape === "objects") {
|
|
173
|
+
const record = row;
|
|
174
|
+
const keys = Object.keys(record);
|
|
175
|
+
const listed = columns.filter((column) => Object.hasOwn(record, column));
|
|
176
|
+
const rest = keys.filter((key) => !columns.includes(key)).sort(byCodeUnits);
|
|
177
|
+
entries = [...listed, ...rest].map((key) => `${jsonString(key)}: ${jsonScalar(record[key])}`);
|
|
178
|
+
[open, close] = ["{", "}"];
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
entries = row.map(jsonScalar);
|
|
182
|
+
[open, close] = ["[", "]"];
|
|
183
|
+
}
|
|
184
|
+
if (entries.length === 0) {
|
|
185
|
+
writer.write(` ${open}${close}${separator}`);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
writer.write(` ${open}\n`);
|
|
189
|
+
entries.forEach((entry, at) => writer.write(` ${entry}${at < entries.length - 1 ? ",\n" : "\n"}`));
|
|
190
|
+
writer.write(` ${close}${separator}`);
|
|
191
|
+
});
|
|
192
|
+
writer.write("]\n");
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The file for `value`: a list of flat objects (written in `columns` order, which it then
|
|
196
|
+
* needs) or a 2-D list whose first row is the header. `invalid_data` for anything else and
|
|
197
|
+
* `too_large` past 1 MiB, never a cut-off file.
|
|
198
|
+
*/
|
|
199
|
+
export function downloadFile(value, format, columns) {
|
|
200
|
+
const shape = downloadShape(value);
|
|
201
|
+
const named = Array.isArray(columns) ? columns.filter((column) => typeof column === "string") : [];
|
|
202
|
+
if (shape === null || (shape === "objects" && value.length > 0 && named.length === 0)) {
|
|
203
|
+
return { ok: false, error: "invalid_data" };
|
|
204
|
+
}
|
|
205
|
+
const list = value;
|
|
206
|
+
// An empty list with `columns` is written as objects too, so its columns are checked alike.
|
|
207
|
+
if (leadingBom(list, named) || ((shape === "objects" || list.length === 0)
|
|
208
|
+
&& unicodeClash(shape === "objects" ? list : [], named))) {
|
|
209
|
+
return { ok: false, error: "invalid_data" };
|
|
210
|
+
}
|
|
211
|
+
// An empty list has no rows to tell its kind: with `columns` it is objects, so the header stays.
|
|
212
|
+
const kind = list.length === 0 && named.length > 0 ? "objects" : shape;
|
|
213
|
+
const writer = new Writer();
|
|
214
|
+
try {
|
|
215
|
+
if (format === "json") {
|
|
216
|
+
writeJson(writer, list, kind, named);
|
|
217
|
+
}
|
|
218
|
+
else if (kind === "objects") {
|
|
219
|
+
writeCsv(writer, [named, ...list.map((row) => named.map((column) => row[column]))]);
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
writeCsv(writer, list);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
if (error instanceof TooLarge)
|
|
227
|
+
return { ok: false, error: "too_large" };
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
return { ok: true, bytes: writer.bytes(), mime: downloadMime(format) };
|
|
231
|
+
}
|
|
232
|
+
const safeAscii = /^[A-Za-z0-9 ._\-()]$/;
|
|
233
|
+
function keptCodePoint(character) {
|
|
234
|
+
if (safeAscii.test(character))
|
|
235
|
+
return true;
|
|
236
|
+
const point = character.codePointAt(0);
|
|
237
|
+
if (point < 0xa0 || (point >= 0xd800 && point <= 0xdfff))
|
|
238
|
+
return false;
|
|
239
|
+
return !(point === 0x2028 || point === 0x2029 || point === 0xfeff || (point >= 0x200b && point <= 0x200f)
|
|
240
|
+
|| (point >= 0x202a && point <= 0x202e) || (point >= 0x2066 && point <= 0x2069));
|
|
241
|
+
}
|
|
242
|
+
function trimNameEdges(name, leading) {
|
|
243
|
+
let start = 0;
|
|
244
|
+
let end = name.length;
|
|
245
|
+
while (leading && start < end && (name[start] === " " || name[start] === "."))
|
|
246
|
+
start += 1;
|
|
247
|
+
while (end > start && (name[end - 1] === " " || name[end - 1] === "."))
|
|
248
|
+
end -= 1;
|
|
249
|
+
return name.slice(start, end);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* The name a file is saved under: only letters, digits, spaces, `. _ - ( )` and printable
|
|
253
|
+
* non-ASCII characters, no leading dot, at most 80 code points, and the extension of `format`.
|
|
254
|
+
*/
|
|
255
|
+
export function safeDownloadFilename(name, format) {
|
|
256
|
+
const extension = format === "json" ? ".json" : ".csv";
|
|
257
|
+
let base = [...(typeof name === "string" ? name : "")].filter(keptCodePoint).join("");
|
|
258
|
+
for (const known of [".csv", ".json"]) {
|
|
259
|
+
if (base.slice(-known.length).replace(/[A-Z]/g, (letter) => letter.toLowerCase()) === known) {
|
|
260
|
+
base = base.slice(0, -known.length);
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
base = trimNameEdges([...trimNameEdges(base, true)].slice(0, MAX_NAME_BASE).join(""), false);
|
|
265
|
+
return `${base || DEFAULT_DOWNLOAD_NAME}${extension}`;
|
|
266
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Defensive Host-value validation helpers shared by Web answer renderers.
|
|
3
|
+
*
|
|
4
|
+
* Renderer layer: enforces ASCII-only hostnames (domain labels, IPv4, or bracketed IPv6; Unicode
|
|
5
|
+
* hostnames are normalized to ASCII punycode by the compiler) while allowing Unicode scalars in
|
|
6
|
+
* path, query, and fragment. Matches `ascii_https_url` in Python and the Compose/SwiftUI helpers,
|
|
7
|
+
* verified against `ui-foundation/surface/contracts/fixtures/renderer/host-values.json`.
|
|
8
|
+
*/
|
|
9
|
+
export declare const MAX_HTTPS_URL_LENGTH = 2048;
|
|
10
|
+
export declare const MAX_STABLE_ID_LENGTH = 120;
|
|
11
|
+
export declare function isExecutableUrl(value: unknown): boolean;
|
|
12
|
+
export declare function validImageUrl(value: unknown, maxLen?: number): string | null;
|
|
13
|
+
/** Validates a Host-resolved `<img src>` value (e.g. from `images` or `imageLoader`). */
|
|
14
|
+
export declare function validResolvedImageSrc(value: unknown): string | null;
|
|
15
|
+
/**
|
|
16
|
+
* Validates any link URL that may be handed to the Host `actionHandler` or default opener.
|
|
17
|
+
* Execution-layer safety: rejects `javascript:`, `vbscript:`, and non-raster `data:` (including
|
|
18
|
+
* `data:text/html` and `data:image/svg+xml`) unconditionally. Safe raster `data:image/*` links
|
|
19
|
+
* are allowed through to the Host `actionHandler` (never opened by the built-in default opener).
|
|
20
|
+
*/
|
|
21
|
+
export declare function validLinkUrl(value: unknown, maxLen?: number): string | null;
|
|
22
|
+
/** Whether the renderer's built-in default opener may open this URL when the Host declines. */
|
|
23
|
+
export declare function isDefaultOpenableLinkUrl(value: unknown, maxLen?: number): boolean;
|
|
24
|
+
export declare function validHttpsUrl(value: unknown, maxLen?: number): string | null;
|
|
25
|
+
export declare function validDisplayText(value: unknown, maxLen: number): string | null;
|
|
26
|
+
export declare function validStableId(value: unknown, maxLen?: number): string | null;
|
|
27
|
+
export declare function nfcKey(value: string): string;
|
|
28
|
+
export declare function hasDuplicateNfcIds(ids: Iterable<string>): boolean;
|