@capybara-hq/plugin-sdk 0.1.0-rc.3 → 0.1.0-rc.31

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.
Files changed (127) hide show
  1. package/agent-docs/agent-templates.md +15 -3
  2. package/agent-docs/concepts.md +5 -0
  3. package/agent-docs/connector-templates.md +2 -1
  4. package/agent-docs/extension-points/channel.md +1 -1
  5. package/agent-docs/extension-points/config-source.md +1 -1
  6. package/agent-docs/extension-points/connector.md +1 -1
  7. package/agent-docs/extension-points/context.md +15 -0
  8. package/agent-docs/extension-points/counter.md +1 -1
  9. package/agent-docs/extension-points/directory.md +1 -1
  10. package/agent-docs/extension-points/file-preview.md +1 -1
  11. package/agent-docs/extension-points/identity-source.md +1 -1
  12. package/agent-docs/extension-points/model-provider.md +4 -2
  13. package/agent-docs/extension-points/object-store.md +3 -1
  14. package/agent-docs/extension-points/sandbox.md +3 -3
  15. package/agent-docs/extension-points/secret-store.md +1 -1
  16. package/agent-docs/extension-points/web-fetch.md +1 -1
  17. package/agent-docs/extension-points/web-search.md +1 -1
  18. package/agent-docs/extensions.md +29 -4
  19. package/agent-docs/plugin-format.md +43 -3
  20. package/agent-docs/setup.md +46 -0
  21. package/agent-docs/skills.md +1 -1
  22. package/agent-docs/tool-naming.md +1 -1
  23. package/dist/agent-template.d.ts +15 -6
  24. package/dist/agent-template.js +32 -13
  25. package/dist/bootstrap.d.ts +15 -1
  26. package/dist/bootstrap.js +17 -1
  27. package/dist/cards.d.ts +56 -13
  28. package/dist/cards.js +90 -20
  29. package/dist/channel.d.ts +111 -48
  30. package/dist/channel.js +10 -5
  31. package/dist/client-css.d.ts +36 -0
  32. package/dist/client-css.js +326 -0
  33. package/dist/client-section.d.ts +35 -0
  34. package/dist/client-section.js +133 -0
  35. package/dist/config-ui.d.ts +22 -0
  36. package/dist/config-ui.js +64 -4
  37. package/dist/connector-auth.d.ts +7 -2
  38. package/dist/connector-auth.js +29 -8
  39. package/dist/connector.d.ts +74 -32
  40. package/dist/context.d.ts +40 -0
  41. package/dist/context.js +2 -0
  42. package/dist/ctx.d.ts +135 -26
  43. package/dist/define-extension.d.ts +26 -12
  44. package/dist/define-extension.js +11 -4
  45. package/dist/device-protocol-v3.d.ts +117 -0
  46. package/dist/device-protocol-v3.js +409 -0
  47. package/dist/device-protocol.d.ts +330 -0
  48. package/dist/device-protocol.js +567 -0
  49. package/dist/extension-point.d.ts +2 -0
  50. package/dist/extension-point.js +5 -2
  51. package/dist/file-preview.d.ts +1 -1
  52. package/dist/git-hosts.d.ts +44 -0
  53. package/dist/git-hosts.js +81 -0
  54. package/dist/hooks.d.ts +111 -21
  55. package/dist/hooks.js +5 -0
  56. package/dist/http-access.d.ts +52 -0
  57. package/dist/http-access.js +12 -0
  58. package/dist/identity.d.ts +22 -9
  59. package/dist/index.d.ts +23 -1
  60. package/dist/index.js +24 -1
  61. package/dist/marketplace.d.ts +26 -0
  62. package/dist/marketplace.js +43 -1
  63. package/dist/model-params.d.ts +41 -22
  64. package/dist/model-params.js +28 -15
  65. package/dist/model.d.ts +180 -71
  66. package/dist/model.js +71 -19
  67. package/dist/net.d.ts +52 -0
  68. package/dist/net.js +34 -0
  69. package/dist/permissions.d.ts +42 -20
  70. package/dist/permissions.js +97 -40
  71. package/dist/plugin-manifest.d.ts +45 -5
  72. package/dist/plugin-manifest.js +169 -6
  73. package/dist/plugin-package.d.ts +82 -38
  74. package/dist/plugin-package.js +61 -29
  75. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  76. package/dist/sandbox-linux-runtime-source.js +1886 -0
  77. package/dist/sandbox-native-runtime-source.d.ts +8 -0
  78. package/dist/sandbox-native-runtime-source.js +325 -0
  79. package/dist/sandbox-operation.d.ts +248 -0
  80. package/dist/sandbox-operation.js +245 -0
  81. package/dist/sandbox-runtime-source.d.ts +19 -0
  82. package/dist/sandbox-runtime-source.js +28 -0
  83. package/dist/sandbox-write-denies.d.ts +60 -0
  84. package/dist/sandbox-write-denies.js +630 -0
  85. package/dist/sandbox.d.ts +201 -16
  86. package/dist/sandbox.js +89 -14
  87. package/dist/secret.d.ts +4 -1
  88. package/dist/secret.js +4 -1
  89. package/dist/setup-check.d.ts +115 -0
  90. package/dist/setup-check.js +142 -0
  91. package/dist/setup-guide-parse.d.ts +121 -0
  92. package/dist/setup-guide-parse.js +350 -0
  93. package/dist/setup-guide-render.d.ts +45 -0
  94. package/dist/setup-guide-render.js +351 -0
  95. package/dist/setup-guide.d.ts +94 -0
  96. package/dist/setup-guide.js +336 -0
  97. package/dist/skill-invocation.d.ts +4 -3
  98. package/dist/skill-invocation.js +5 -4
  99. package/dist/skill.d.ts +34 -21
  100. package/dist/skill.js +48 -31
  101. package/dist/storage.d.ts +52 -25
  102. package/dist/theme-assets.d.ts +39 -0
  103. package/dist/theme-assets.js +449 -0
  104. package/dist/theme-readability.d.ts +37 -0
  105. package/dist/theme-readability.js +145 -0
  106. package/dist/theme-tokens.generated.d.ts +279 -0
  107. package/dist/theme-tokens.generated.js +174 -0
  108. package/dist/theme.d.ts +152 -0
  109. package/dist/theme.js +392 -0
  110. package/dist/tool.d.ts +69 -26
  111. package/dist/tool.js +29 -9
  112. package/dist/ui-parts.d.ts +23 -0
  113. package/dist/ui-parts.js +337 -0
  114. package/dist/ui-resolve.d.ts +35 -0
  115. package/dist/ui-resolve.js +42 -0
  116. package/dist/ui-slots.d.ts +53 -0
  117. package/dist/ui-slots.js +238 -0
  118. package/dist/ui.d.ts +191 -79
  119. package/dist/ui.js +101 -27
  120. package/dist/url.d.ts +4 -1
  121. package/dist/url.js +4 -1
  122. package/package.json +7 -1
  123. package/schemas/bootstrap.v1.schema.json +6 -0
  124. package/schemas/connector-template.v1.schema.json +35 -0
  125. package/schemas/marketplace.v1.schema.json +14 -0
  126. package/schemas/plugin.v1.schema.json +115 -3
  127. package/schemas/theme.v1.schema.json +225 -0
package/dist/storage.d.ts CHANGED
@@ -7,27 +7,34 @@
7
7
  */
8
8
  /** Object storage extension point ref. */
9
9
  export declare const OBJECT_STORE_EXTENSION_POINT = "object-store@1";
10
- /** 对象的元数据。 */
10
+ /** Metadata of an object. */
11
11
  export interface ObjectHead {
12
12
  key: string;
13
- /** 字节数。 */
13
+ /** Size in bytes. */
14
14
  size: number;
15
15
  contentType: string;
16
16
  etag?: string;
17
- /** ISO 8601 时间。 */
17
+ /** ISO 8601 time. */
18
18
  lastModified?: string;
19
19
  }
20
- /** `object-store@1` 的实现(由对象存储插件提供,如 S3 兼容存储)。 */
20
+ /**
21
+ * The `object-store@1` implementation (provided by an object-store plugin, e.g. S3-compatible
22
+ * storage).
23
+ */
21
24
  export interface ObjectStore {
22
- /** 写入(覆盖同名键);`body` 是流时最好给出 `size`。 */
25
+ /**
26
+ * Writes (overwriting a key of the same name); give `size` when `body` is a stream if possible.
27
+ */
23
28
  put(key: string, body: Uint8Array | ReadableStream<Uint8Array>, opts: {
24
29
  contentType: string;
25
30
  size?: number;
26
31
  signal?: AbortSignal;
27
32
  }): Promise<ObjectHead>;
28
33
  /**
29
- * 读取;不存在返回 null。`range` 为闭区间字节范围,缺省 `end` 表示读到末尾。
30
- * 带 `range` 时 `head.size` 仍是整个对象的大小;存储忽略 Range 时 body 可能是整个对象。
34
+ * Reads; returns null when missing. `range` is a closed byte range; an omitted `end` means read
35
+ * to the end.
36
+ * With `range`, `head.size` is still the size of the whole object; when the store ignores Range,
37
+ * body may be the whole object.
31
38
  */
32
39
  get(key: string, opts?: {
33
40
  signal?: AbortSignal;
@@ -39,15 +46,18 @@ export interface ObjectStore {
39
46
  head: ObjectHead;
40
47
  body: ReadableStream<Uint8Array>;
41
48
  } | null>;
42
- /** 不存在返回 null。 */
49
+ /** Returns null when missing. */
43
50
  head(key: string): Promise<ObjectHead | null>;
44
- /** 删除;不存在也算成功。 */
51
+ /** Deletes; a missing key also counts as success. */
45
52
  delete(key: string): Promise<void>;
46
- /** 删除前缀下的全部对象,返回删除数(用于组织数据删除)。 */
53
+ /**
54
+ * Deletes all objects under a prefix and returns the number deleted (used for org data deletion).
55
+ */
47
56
  deletePrefix(prefix: string): Promise<number>;
48
57
  /**
49
- * 分页列举前缀下的对象;返回的 `cursor` 缺省表示没有下一页。列举结果不带类型时 `contentType` 为空串
50
- * (需要时用 `head` 取)。
58
+ * Lists objects under a prefix with pagination; an omitted `cursor` in the result means there is
59
+ * no next page. When the listing carries no type, `contentType` is an empty string
60
+ * (use `head` to get it when needed).
51
61
  */
52
62
  list(prefix: string, opts?: {
53
63
  cursor?: string;
@@ -56,41 +66,58 @@ export interface ObjectStore {
56
66
  items: ObjectHead[];
57
67
  cursor?: string;
58
68
  }>;
59
- /** 预签名下载 URL(选项见 {@link PresignGetOptions})。 */
69
+ /** Presigned download URL (options in {@link PresignGetOptions}). */
60
70
  presignGet(key: string, opts: PresignGetOptions): Promise<string>;
61
71
  /**
62
- * 预签名上传:浏览器按返回的 {@link PresignedUpload} 直传存储。超过 `maxSize` 的上传必须由**存储端**拒绝
63
- * (预签名 PUT 无法限制大小,所以 S3 兼容实现用带 `content-length-range` 条件的 POST 策略)。
72
+ * Presigned upload: the browser uploads straight to storage following the returned {@link
73
+ * PresignedUpload}. An upload over `maxSize` must be rejected by the **store side**
74
+ * (a presigned PUT cannot limit the size, so S3-compatible implementations use a POST policy with
75
+ * a `content-length-range` condition).
64
76
  */
65
77
  presignPut(key: string, opts: {
66
78
  contentType: string;
67
79
  maxSize: number;
68
80
  ttlSeconds: number;
69
81
  }): Promise<PresignedUpload>;
82
+ /**
83
+ * The canonical URI of a key in this store: unsigned, stable, no credentials
84
+ * (`s3://bucket/key`). This is an identifier, never a presigned URL: it may be recorded in an
85
+ * event log and shown to a model, so it must stay valid and carry no secret. Optional: a store
86
+ * with no notion of URIs leaves it out and the kernel falls back to its own reference.
87
+ */
88
+ uri?(key: string): string;
70
89
  }
71
- /** 预签名下载的选项。 */
90
+ /** Options of a presigned download. */
72
91
  export interface PresignGetOptions {
73
92
  ttlSeconds: number;
74
- /** 下载文件名,进 `Content-Disposition`(RFC 6266,非 ASCII 用 `filename*=UTF-8''…`)。 */
93
+ /**
94
+ * Download file name, goes into `Content-Disposition` (RFC 6266; non-ASCII uses
95
+ * `filename*=UTF-8''…`).
96
+ */
75
97
  downloadName?: string;
76
98
  /**
77
- * 浏览器打开方式:`attachment`(缺省,下载)或 `inline`(在页面里显示)。用户上传的内容只应对
78
- * 不会执行脚本的类型(图片、PDF)用 `inline`。
99
+ * How the browser opens it: `attachment` (default, download) or `inline` (display in the page).
100
+ * User-uploaded content should use `inline` only for types
101
+ * that do not execute scripts (images, PDF).
79
102
  */
80
103
  disposition?: "attachment" | "inline";
81
- /** 覆盖响应的 `Content-Type`(如按核对过的类型返回,而不是存储里记的类型)。 */
104
+ /**
105
+ * Overrides the response `Content-Type` (e.g. return the verified type rather than the type
106
+ * recorded in storage).
107
+ */
82
108
  responseContentType?: string;
83
109
  }
84
110
  /**
85
- * 预签名上传的请求方式:
86
- * - `PUT`:请求体就是文件字节,请求头带上 `headers`;
87
- * - `POST`:`multipart/form-data` 表单,先按原样放入 `fields` 的每一项,**最后**放文件字段 `file`;
88
- * 请求头带上 `headers`(通常为空)。
111
+ * The request method of a presigned upload:
112
+ * - `PUT`: the request body is the file bytes, and the request carries `headers`;
113
+ * - `POST`: a `multipart/form-data` form; first put every item of `fields` in as is, and put the
114
+ * file field `file` **last**;
115
+ * the request carries `headers` (usually empty).
89
116
  */
90
117
  export interface PresignedUpload {
91
118
  method: "PUT" | "POST";
92
119
  url: string;
93
120
  headers: Record<string, string>;
94
- /** `POST` 时必有:表单字段(含策略与签名)。 */
121
+ /** Always present for `POST`: the form fields (including policy and signature). */
95
122
  fields?: Record<string, string>;
96
123
  }
@@ -0,0 +1,39 @@
1
+ import { type ParsedTheme } from "./theme.js";
2
+ /**
3
+ * Parses a logo SVG (UTF-8, ≤ {@link THEME_LIMITS}`.svgBytes`) with a strict, namespace-aware
4
+ * XML parser and re-serializes it. The root must be an `svg` element in the SVG namespace with a
5
+ * numeric `viewBox`; its `width`, `height` and `class` are dropped. Rejected: a DOCTYPE (and so
6
+ * any entity declaration), processing instructions, a non-UTF-8 encoding, elements outside the
7
+ * SVG allowlist (`script`, `foreignObject`, `style`, …) or in the XHTML namespace, `style` and
8
+ * `on*` attributes, `href` / `xlink:href` not starting with `#`, `javascript:` / `vbscript:` in
9
+ * any value, quotes or a backslash in attribute values, any function other than `url(#id)`, colors
10
+ * (`rgb`, `rgba`, `hsl`, `hsla`) and transforms (`translate`, `rotate`, `scale`, `matrix`,
11
+ * `skewX`, `skewY`), a viewBox longer than 128 characters, and animation of `href`, `style` or event
12
+ * handlers. Comments, the XML declaration and elements / attributes in other namespaces (editor
13
+ * metadata) are dropped; CDATA becomes escaped text. Never throws.
14
+ */
15
+ export declare function sanitizeThemeSvg(bytes: Uint8Array): {
16
+ svg: string;
17
+ } | {
18
+ error: string;
19
+ };
20
+ /** A woff2 font: the `wOF2` signature and at most {@link THEME_LIMITS}`.fontBytes`. */
21
+ export declare function checkWoff2(bytes: Uint8Array): string | undefined;
22
+ /**
23
+ * A PNG logo: the PNG signature, an `IHDR` first chunk with a height of at least
24
+ * {@link THEME_LIMITS}`.pngMinHeight` pixels, and at most {@link THEME_LIMITS}`.pngBytes`.
25
+ */
26
+ export declare function checkPng(bytes: Uint8Array): string | undefined;
27
+ /**
28
+ * Resolves and checks the asset files of a parsed theme: each `fonts[].file` ({@link checkWoff2})
29
+ * and `logo.mark` / `logo.favicon` (`.svg` through {@link sanitizeThemeSvg}, `.png` through
30
+ * {@link checkPng}); the favicon must be square (SVG viewBox or PNG width = height). `files` holds the plugin's files keyed by their path without a leading
31
+ * `./`; the returned `assets` (the sanitized SVG bytes, the other files unchanged) use the same
32
+ * keys. Errors are `<field>: <reason>`, English; the total input size of the theme's distinct
33
+ * assets must stay within {@link THEME_LIMITS}`.assetsBytes`. That limit is per plugin, so a
34
+ * caller reading several themes also checks the sum over all of them (distinct paths).
35
+ */
36
+ export declare function validateThemeAssets(theme: ParsedTheme, files: Map<string, Uint8Array>): {
37
+ assets: Map<string, Uint8Array>;
38
+ errors: string[];
39
+ };
@@ -0,0 +1,449 @@
1
+ import { SaxesParser } from "saxes";
2
+ import { isSafePackagePath } from "./plugin-package.js";
3
+ import { THEME_LIMITS } from "./theme.js";
4
+ /**
5
+ * Checks of a theme's asset files (themes spec §4.2-§4.4): woff2 fonts, PNG logos and the SVG
6
+ * sanitizer. The sanitized SVG is served to every browser, so {@link sanitizeThemeSvg} is a trust
7
+ * boundary: the output is re-serialized from the parsed tree (never the input bytes), elements are
8
+ * allowlisted, every attribute value and text node is escaped on output.
9
+ */
10
+ const SVG_NS = "http://www.w3.org/2000/svg";
11
+ const XLINK_NS = "http://www.w3.org/1999/xlink";
12
+ const XML_NS = "http://www.w3.org/XML/1998/namespace";
13
+ const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
14
+ const XHTML_NS = "http://www.w3.org/1999/xhtml";
15
+ /** SVG elements a logo may use: shapes, structure, paint servers, filters and animation. */
16
+ const SVG_ELEMENTS = new Set([
17
+ "svg",
18
+ "g",
19
+ "defs",
20
+ "symbol",
21
+ "use",
22
+ "title",
23
+ "desc",
24
+ "metadata",
25
+ "a",
26
+ "switch",
27
+ "view",
28
+ "path",
29
+ "rect",
30
+ "circle",
31
+ "ellipse",
32
+ "line",
33
+ "polyline",
34
+ "polygon",
35
+ "text",
36
+ "tspan",
37
+ "textPath",
38
+ "image",
39
+ "marker",
40
+ "linearGradient",
41
+ "radialGradient",
42
+ "stop",
43
+ "pattern",
44
+ "clipPath",
45
+ "mask",
46
+ "filter",
47
+ "feBlend",
48
+ "feColorMatrix",
49
+ "feComponentTransfer",
50
+ "feComposite",
51
+ "feConvolveMatrix",
52
+ "feDiffuseLighting",
53
+ "feDisplacementMap",
54
+ "feDistantLight",
55
+ "feDropShadow",
56
+ "feFlood",
57
+ "feFuncA",
58
+ "feFuncB",
59
+ "feFuncG",
60
+ "feFuncR",
61
+ "feGaussianBlur",
62
+ "feImage",
63
+ "feMerge",
64
+ "feMergeNode",
65
+ "feMorphology",
66
+ "feOffset",
67
+ "fePointLight",
68
+ "feSpecularLighting",
69
+ "feSpotLight",
70
+ "feTile",
71
+ "feTurbulence",
72
+ "animate",
73
+ "animateMotion",
74
+ "animateTransform",
75
+ "set",
76
+ "mpath",
77
+ ]);
78
+ /** `xml:` attributes kept; `xml:base` and the rest are dropped. */
79
+ const XML_ATTRS = new Set(["space", "lang"]);
80
+ /** Root attributes dropped: the design system sizes the logo to its slot. */
81
+ const ROOT_DROPPED = new Set(["width", "height", "class"]);
82
+ /** Characters of a viewBox value; longer values are refused before they are split. */
83
+ const VIEWBOX_MAX_CHARS = 128;
84
+ /** Characters a viewBox number may use (checked per character class, no backtracking). */
85
+ const VIEWBOX_NUMBER_RE = /^[-+.0-9eE]+$/;
86
+ /**
87
+ * The only functions an attribute value may call: colors and transforms. `url` is allowed only as
88
+ * `url(#id)` (checked separately); everything else (`image-set`, `cross-fade`, `element`,
89
+ * `src`, `var`, ...) is refused, since some of them load resources from quoted strings.
90
+ */
91
+ const ALLOWED_FUNCTIONS = new Set([
92
+ "url",
93
+ "rgb",
94
+ "rgba",
95
+ "hsl",
96
+ "hsla",
97
+ "translate",
98
+ "rotate",
99
+ "scale",
100
+ "matrix",
101
+ "skewx",
102
+ "skewy",
103
+ ]);
104
+ const isIdentChar = (c) => /[A-Za-z0-9_-]/.test(c);
105
+ const isSpace = (c) => c === " " || c === "\t" || c === "\n" || c === "\r" || c === "\f";
106
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: whitespace and control characters are stripped before matching schemes
107
+ const IGNORED_IN_SCHEME_RE = /[\u0000- \u007f]/g;
108
+ class SvgRejected extends Error {
109
+ }
110
+ const reject = (message) => {
111
+ throw new SvgRejected(message);
112
+ };
113
+ const escapeText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
114
+ const escapeAttr = (s) => escapeText(s)
115
+ .replace(/"/g, "&quot;")
116
+ .replace(/\t/g, "&#9;")
117
+ .replace(/\n/g, "&#10;")
118
+ .replace(/\r/g, "&#13;");
119
+ /** Rejects an attribute value that could run script or load a resource outside the document. */
120
+ function checkValue(el, attr, value) {
121
+ const squeezed = value.replace(IGNORED_IN_SCHEME_RE, "").toLowerCase();
122
+ if (squeezed.includes("javascript:") || squeezed.includes("vbscript:")) {
123
+ reject(`attribute ${attr} on <${el}> must not contain javascript: or vbscript: URLs`);
124
+ }
125
+ // CSS escapes could spell a function name; quoted strings are how CSS functions take URLs.
126
+ if (value.includes("\\"))
127
+ reject(`attribute ${attr} on <${el}> must not contain "\\"`);
128
+ if (value.includes("'") || value.includes('"')) {
129
+ reject(`attribute ${attr} on <${el}> must not contain quotes`);
130
+ }
131
+ // Linear scan: at every "(", walk back over spaces and the function name.
132
+ for (let i = value.indexOf("("); i !== -1; i = value.indexOf("(", i + 1)) {
133
+ let end = i;
134
+ while (end > 0 && isSpace(value.charAt(end - 1)))
135
+ end -= 1;
136
+ let start = end;
137
+ while (start > 0 && isIdentChar(value.charAt(start - 1)))
138
+ start -= 1;
139
+ const fn = value.slice(start, end).toLowerCase();
140
+ if (!ALLOWED_FUNCTIONS.has(fn)) {
141
+ reject(`attribute ${attr} on <${el}> must not call ${fn === "" ? "a bare (" : `${fn}()`}; only url(#id), colors and transforms are allowed`);
142
+ }
143
+ if (fn === "url") {
144
+ let j = i + 1;
145
+ while (j < value.length && isSpace(value.charAt(j)))
146
+ j += 1;
147
+ if (value.charAt(j) !== "#") {
148
+ reject(`attribute ${attr} on <${el}> may only reference url(#id) inside the document`);
149
+ }
150
+ }
151
+ }
152
+ }
153
+ /** `min-x min-y width height`, width and height > 0; undefined when malformed. */
154
+ function parseViewBox(v) {
155
+ if (v.length > VIEWBOX_MAX_CHARS)
156
+ return undefined;
157
+ const parts = v
158
+ .trim()
159
+ .split(/[\s,]+/)
160
+ .filter((p) => p !== "");
161
+ if (parts.length !== 4 || !parts.every((p) => VIEWBOX_NUMBER_RE.test(p)))
162
+ return undefined;
163
+ const n = parts.map(Number);
164
+ if (!n.every(Number.isFinite) || n[2] <= 0 || n[3] <= 0)
165
+ return undefined;
166
+ return n;
167
+ }
168
+ /** The serialized attributes of an allowed SVG element; rejects the forbidden ones. */
169
+ function attributesOf(tag, isRoot, usesXlink) {
170
+ const el = tag.local;
171
+ let out = "";
172
+ for (const a of Object.values(tag.attributes)) {
173
+ const lower = a.local.toLowerCase();
174
+ if (a.uri === XMLNS_NS || a.name === "xmlns")
175
+ continue;
176
+ let name;
177
+ if (a.uri === "") {
178
+ if (lower === "style")
179
+ reject(`attribute style on <${el}> is not allowed`);
180
+ if (lower.startsWith("on"))
181
+ reject(`event handler attribute ${a.name} on <${el}> is not allowed`);
182
+ if (isRoot && ROOT_DROPPED.has(a.local))
183
+ continue;
184
+ name = a.local;
185
+ }
186
+ else if (a.uri === XLINK_NS) {
187
+ usesXlink.value = true;
188
+ name = `xlink:${a.local}`;
189
+ }
190
+ else if (a.uri === XML_NS) {
191
+ if (!XML_ATTRS.has(a.local))
192
+ continue;
193
+ name = `xml:${a.local}`;
194
+ }
195
+ else {
196
+ // Editor metadata (inkscape:*, sodipodi:*, …) in foreign namespaces is dropped.
197
+ continue;
198
+ }
199
+ if (lower === "href" && !a.value.startsWith("#")) {
200
+ reject(`attribute ${name} on <${el}> must reference an element of the document (#id)`);
201
+ }
202
+ if (lower === "attributename") {
203
+ const target = (a.value.split(":").pop() ?? "").trim().toLowerCase();
204
+ if (target === "href" || target === "style" || target.startsWith("on")) {
205
+ reject(`<${el}> must not animate ${a.value}`);
206
+ }
207
+ }
208
+ checkValue(el, name, a.value);
209
+ out += ` ${name}="${escapeAttr(a.value)}"`;
210
+ }
211
+ return out;
212
+ }
213
+ /**
214
+ * Parses a logo SVG (UTF-8, ≤ {@link THEME_LIMITS}`.svgBytes`) with a strict, namespace-aware
215
+ * XML parser and re-serializes it. The root must be an `svg` element in the SVG namespace with a
216
+ * numeric `viewBox`; its `width`, `height` and `class` are dropped. Rejected: a DOCTYPE (and so
217
+ * any entity declaration), processing instructions, a non-UTF-8 encoding, elements outside the
218
+ * SVG allowlist (`script`, `foreignObject`, `style`, …) or in the XHTML namespace, `style` and
219
+ * `on*` attributes, `href` / `xlink:href` not starting with `#`, `javascript:` / `vbscript:` in
220
+ * any value, quotes or a backslash in attribute values, any function other than `url(#id)`, colors
221
+ * (`rgb`, `rgba`, `hsl`, `hsla`) and transforms (`translate`, `rotate`, `scale`, `matrix`,
222
+ * `skewX`, `skewY`), a viewBox longer than 128 characters, and animation of `href`, `style` or event
223
+ * handlers. Comments, the XML declaration and elements / attributes in other namespaces (editor
224
+ * metadata) are dropped; CDATA becomes escaped text. Never throws.
225
+ */
226
+ export function sanitizeThemeSvg(bytes) {
227
+ const r = sanitize(bytes);
228
+ return "error" in r ? r : { svg: r.svg };
229
+ }
230
+ /** {@link sanitizeThemeSvg} plus the root viewBox (for the favicon's squareness). */
231
+ function sanitize(bytes) {
232
+ if (bytes.length > THEME_LIMITS.svgBytes) {
233
+ return { error: `SVG is larger than ${THEME_LIMITS.svgBytes} bytes` };
234
+ }
235
+ let source;
236
+ try {
237
+ source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
238
+ }
239
+ catch {
240
+ return { error: "SVG is not valid UTF-8" };
241
+ }
242
+ const parts = [];
243
+ const usesXlink = { value: false };
244
+ let xlinkAt = -1;
245
+ let depth = 0;
246
+ /** Depth at which a dropped foreign element started; 0 when not inside one. */
247
+ let skipFrom = 0;
248
+ /** The last emitted start tag still lacks its `>`. */
249
+ let openPending = false;
250
+ let sawRoot = false;
251
+ let rootBox = [0, 0, 0, 0];
252
+ const closePending = () => {
253
+ if (openPending)
254
+ parts.push(">");
255
+ openPending = false;
256
+ };
257
+ const parser = new SaxesParser({ xmlns: true, position: true });
258
+ parser.on("error", (e) => reject(`SVG is not valid XML: ${e.message}`));
259
+ parser.on("doctype", () => reject("SVG must not contain a DOCTYPE or entity declarations"));
260
+ parser.on("processinginstruction", () => reject("SVG must not contain processing instructions"));
261
+ parser.on("xmldecl", (d) => {
262
+ if (d.encoding !== undefined && !/^utf-?8$/i.test(d.encoding)) {
263
+ reject(`SVG must be encoded as UTF-8, not ${d.encoding}`);
264
+ }
265
+ });
266
+ parser.on("opentag", (tag) => {
267
+ depth += 1;
268
+ if (skipFrom > 0)
269
+ return;
270
+ const isRoot = !sawRoot;
271
+ sawRoot = true;
272
+ if (tag.uri === XHTML_NS)
273
+ reject(`XHTML element <${tag.name}> is not allowed`);
274
+ if (isRoot) {
275
+ if (tag.local !== "svg")
276
+ reject("the root element must be <svg>");
277
+ if (tag.uri !== SVG_NS)
278
+ reject(`the root <svg> must be in the SVG namespace (${SVG_NS})`);
279
+ const viewBox = Object.values(tag.attributes).find((a) => a.uri === "" && a.local === "viewBox");
280
+ if (viewBox === undefined)
281
+ reject("the root <svg> must have a viewBox");
282
+ else {
283
+ const box = parseViewBox(viewBox.value);
284
+ if (box === undefined) {
285
+ reject("the root <svg> viewBox must be four numbers with a positive width and height");
286
+ }
287
+ else
288
+ rootBox = box;
289
+ }
290
+ }
291
+ if (tag.uri !== SVG_NS) {
292
+ skipFrom = depth;
293
+ return;
294
+ }
295
+ if (!SVG_ELEMENTS.has(tag.local))
296
+ reject(`element <${tag.local}> is not allowed`);
297
+ closePending();
298
+ parts.push(`<${tag.local}`);
299
+ if (isRoot) {
300
+ parts.push(` xmlns="${SVG_NS}"`);
301
+ xlinkAt = parts.length;
302
+ parts.push("");
303
+ }
304
+ parts.push(attributesOf(tag, isRoot, usesXlink));
305
+ openPending = true;
306
+ });
307
+ parser.on("closetag", (tag) => {
308
+ depth -= 1;
309
+ if (skipFrom > 0) {
310
+ if (depth < skipFrom)
311
+ skipFrom = 0;
312
+ return;
313
+ }
314
+ if (openPending) {
315
+ parts.push("/>");
316
+ openPending = false;
317
+ }
318
+ else {
319
+ parts.push(`</${tag.local}>`);
320
+ }
321
+ });
322
+ const onText = (t) => {
323
+ if (depth === 0 || skipFrom > 0 || t === "")
324
+ return;
325
+ closePending();
326
+ parts.push(escapeText(t));
327
+ };
328
+ parser.on("text", onText);
329
+ parser.on("cdata", onText);
330
+ try {
331
+ parser.write(source).close();
332
+ }
333
+ catch (e) {
334
+ if (e instanceof SvgRejected)
335
+ return { error: e.message };
336
+ return { error: `SVG is not valid XML: ${e instanceof Error ? e.message : String(e)}` };
337
+ }
338
+ if (!sawRoot)
339
+ return { error: "the root element must be <svg>" };
340
+ if (usesXlink.value)
341
+ parts[xlinkAt] = ` xmlns:xlink="${XLINK_NS}"`;
342
+ return { svg: parts.join(""), viewBox: rootBox };
343
+ }
344
+ const startsWith = (bytes, sig) => bytes.length >= sig.length && sig.every((b, i) => bytes[i] === b);
345
+ const WOFF2_SIG = [0x77, 0x4f, 0x46, 0x32]; // "wOF2"
346
+ const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
347
+ const IHDR = [0x49, 0x48, 0x44, 0x52];
348
+ /** A woff2 font: the `wOF2` signature and at most {@link THEME_LIMITS}`.fontBytes`. */
349
+ export function checkWoff2(bytes) {
350
+ if (bytes.length > THEME_LIMITS.fontBytes) {
351
+ return `font is larger than ${THEME_LIMITS.fontBytes} bytes`;
352
+ }
353
+ if (!startsWith(bytes, WOFF2_SIG))
354
+ return "font is not a woff2 file (no wOF2 signature)";
355
+ return undefined;
356
+ }
357
+ /**
358
+ * A PNG logo: the PNG signature, an `IHDR` first chunk with a height of at least
359
+ * {@link THEME_LIMITS}`.pngMinHeight` pixels, and at most {@link THEME_LIMITS}`.pngBytes`.
360
+ */
361
+ export function checkPng(bytes) {
362
+ const r = readPng(bytes);
363
+ return typeof r === "string" ? r : undefined;
364
+ }
365
+ /** {@link checkPng}, returning the IHDR size when the PNG passes. */
366
+ function readPng(bytes) {
367
+ if (bytes.length > THEME_LIMITS.pngBytes) {
368
+ return `PNG is larger than ${THEME_LIMITS.pngBytes} bytes`;
369
+ }
370
+ if (!startsWith(bytes, PNG_SIG))
371
+ return "image is not a PNG file (no PNG signature)";
372
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
373
+ if (bytes.length < 24 || view.getUint32(8) !== 13 || !IHDR.every((b, i) => bytes[12 + i] === b)) {
374
+ return "PNG has no valid IHDR header";
375
+ }
376
+ const width = view.getUint32(16);
377
+ const height = view.getUint32(20);
378
+ if (width === 0)
379
+ return "PNG has a width of 0";
380
+ if (height < THEME_LIMITS.pngMinHeight) {
381
+ return `PNG must be at least ${THEME_LIMITS.pngMinHeight} px high, not ${height}`;
382
+ }
383
+ return { width, height };
384
+ }
385
+ /**
386
+ * Resolves and checks the asset files of a parsed theme: each `fonts[].file` ({@link checkWoff2})
387
+ * and `logo.mark` / `logo.favicon` (`.svg` through {@link sanitizeThemeSvg}, `.png` through
388
+ * {@link checkPng}); the favicon must be square (SVG viewBox or PNG width = height). `files` holds the plugin's files keyed by their path without a leading
389
+ * `./`; the returned `assets` (the sanitized SVG bytes, the other files unchanged) use the same
390
+ * keys. Errors are `<field>: <reason>`, English; the total input size of the theme's distinct
391
+ * assets must stay within {@link THEME_LIMITS}`.assetsBytes`. That limit is per plugin, so a
392
+ * caller reading several themes also checks the sum over all of them (distinct paths).
393
+ */
394
+ export function validateThemeAssets(theme, files) {
395
+ const assets = new Map();
396
+ const errors = [];
397
+ const sizes = new Map();
398
+ const resolve = (field, ref, check) => {
399
+ const path = ref.replace(/^\.\//, "");
400
+ if (!isSafePackagePath(path)) {
401
+ errors.push(`${field}: ${ref} must be a relative path inside the plugin`);
402
+ return;
403
+ }
404
+ const bytes = files.get(path);
405
+ if (bytes === undefined) {
406
+ errors.push(`${field}: ${ref} not found in the plugin`);
407
+ return;
408
+ }
409
+ const r = check(bytes);
410
+ if (typeof r === "string") {
411
+ errors.push(`${field}: ${ref}: ${r}`);
412
+ return;
413
+ }
414
+ sizes.set(path, bytes.length);
415
+ assets.set(path, r);
416
+ };
417
+ const font = (b) => checkWoff2(b) ?? b;
418
+ const image = (ref, square) => (b) => {
419
+ const notSquare = (w, h) => `favicon must be square, not ${w} x ${h}`;
420
+ if (/\.png$/i.test(ref)) {
421
+ const r = readPng(b);
422
+ if (typeof r === "string")
423
+ return r;
424
+ return square && r.width !== r.height ? notSquare(r.width, r.height) : b;
425
+ }
426
+ if (!/\.svg$/i.test(ref))
427
+ return "must be a .svg or .png file";
428
+ const r = sanitize(b);
429
+ if ("error" in r)
430
+ return r.error;
431
+ const [, , w, h] = r.viewBox;
432
+ return square && w !== h ? notSquare(w, h) : new TextEncoder().encode(r.svg);
433
+ };
434
+ theme.fonts?.forEach((f, i) => {
435
+ resolve(`fonts.${i}.file`, f.file, font);
436
+ });
437
+ for (const key of ["mark", "favicon"]) {
438
+ const ref = theme.logo?.[key];
439
+ if (ref !== undefined)
440
+ resolve(`logo.${key}`, ref, image(ref, key === "favicon"));
441
+ }
442
+ let total = 0;
443
+ for (const n of sizes.values())
444
+ total += n;
445
+ if (total > THEME_LIMITS.assetsBytes) {
446
+ errors.push(`theme assets are larger than ${THEME_LIMITS.assetsBytes} bytes in total (${total})`);
447
+ }
448
+ return { assets, errors };
449
+ }
@@ -0,0 +1,37 @@
1
+ export type ThemeScheme = "dark" | "light";
2
+ /** A theme scheme after merging its overrides onto the built-in values. */
3
+ export type MergedScheme = {
4
+ color: Record<string, string>;
5
+ shadow: Record<string, string>;
6
+ radius: Record<string, number>;
7
+ };
8
+ export type ReadabilityIssue = {
9
+ kind: "contrast" | "separation" | "separation-order" | "unevaluable";
10
+ /** `<fg> on <bg>` (with ` over <surface>` for a surface pair) or `<ground> on <surface>`. */
11
+ pair: string;
12
+ /** The measured value: contrast ratio, or OKLab lightness difference x100. */
13
+ ratio: number;
14
+ /** The floor it had to reach (for `separation-order`: the hover difference selected must beat). */
15
+ floor: number;
16
+ /** The composited colors compared, or for `unevaluable` the offending value. */
17
+ detail?: string;
18
+ };
19
+ /** WCAG 2 contrast ratio of two #RRGGBB colors. */
20
+ export declare function contrastRatio(fg: string, bg: string): number;
21
+ /** OKLab lightness (x100) of a #RRGGBB color. */
22
+ export declare function oklabL(hex: string): number;
23
+ /**
24
+ * The opaque #RRGGBB of `color` drawn over the opaque `ground`: a hex color passes through, an
25
+ * rgba(...) color is alpha-blended (per channel, rounded), anything else (color-mix) is undefined.
26
+ */
27
+ export declare function compositeOver(color: string, ground: string): string | undefined;
28
+ /**
29
+ * Evaluates the readability rules (every contrast pair and separation entry of the design tokens)
30
+ * on one merged scheme. An rgba(...) value is composited over the scheme's `bg` first, or over a
31
+ * pair's surface token; pairs with a color-mix value are skipped. `selected` must stand further
32
+ * from a surface than `hover` on the same surface. `rules` defaults to the built-in lists.
33
+ */
34
+ export declare function checkThemeReadability(_scheme: ThemeScheme, merged: MergedScheme, rules?: {
35
+ contrast: readonly (readonly [string, string, number, string?])[];
36
+ separation: readonly (readonly [string, string, number])[];
37
+ }): ReadabilityIssue[];