@caelo-cms/shared 0.10.24 → 0.10.27

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 (115) hide show
  1. package/dist/ai-tools.d.ts +23 -14
  2. package/dist/ai-tools.d.ts.map +1 -1
  3. package/dist/ai-tools.js +18 -16
  4. package/dist/ai-tools.js.map +1 -1
  5. package/dist/build-page.d.ts +0 -2
  6. package/dist/build-page.d.ts.map +1 -1
  7. package/dist/build-page.js +2 -3
  8. package/dist/build-page.js.map +1 -1
  9. package/dist/content.d.ts +0 -3
  10. package/dist/content.d.ts.map +1 -1
  11. package/dist/content.js +91 -7
  12. package/dist/content.js.map +1 -1
  13. package/dist/context.d.ts +6 -0
  14. package/dist/context.d.ts.map +1 -1
  15. package/dist/font-assets.d.ts +89 -0
  16. package/dist/font-assets.d.ts.map +1 -0
  17. package/dist/font-assets.js +61 -0
  18. package/dist/font-assets.js.map +1 -0
  19. package/dist/google-models.d.ts +19 -0
  20. package/dist/google-models.d.ts.map +1 -0
  21. package/dist/google-models.js +13 -0
  22. package/dist/google-models.js.map +1 -0
  23. package/dist/image-capabilities.d.ts +55 -0
  24. package/dist/image-capabilities.d.ts.map +1 -0
  25. package/dist/image-capabilities.js +39 -0
  26. package/dist/image-capabilities.js.map +1 -0
  27. package/dist/index.d.ts +5 -2
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +5 -2
  30. package/dist/index.js.map +1 -1
  31. package/dist/media.d.ts +29 -3
  32. package/dist/media.d.ts.map +1 -1
  33. package/dist/media.js +19 -5
  34. package/dist/media.js.map +1 -1
  35. package/dist/plugin-preview.d.ts +44 -0
  36. package/dist/plugin-preview.d.ts.map +1 -0
  37. package/dist/plugin-preview.js +69 -0
  38. package/dist/plugin-preview.js.map +1 -0
  39. package/dist/preview-compose.d.ts +26 -0
  40. package/dist/preview-compose.d.ts.map +1 -1
  41. package/dist/preview-compose.js +92 -46
  42. package/dist/preview-compose.js.map +1 -1
  43. package/dist/responsive-images.d.ts +6 -5
  44. package/dist/responsive-images.d.ts.map +1 -1
  45. package/dist/responsive-images.js +6 -5
  46. package/dist/responsive-images.js.map +1 -1
  47. package/dist/seo.d.ts +10 -14
  48. package/dist/seo.d.ts.map +1 -1
  49. package/dist/seo.js +11 -12
  50. package/dist/seo.js.map +1 -1
  51. package/dist/template-engine.d.ts +18 -0
  52. package/dist/template-engine.d.ts.map +1 -1
  53. package/dist/template-engine.js +39 -2
  54. package/dist/template-engine.js.map +1 -1
  55. package/dist/theme-importers/loose.js +1 -1
  56. package/dist/theme-importers/loose.js.map +1 -1
  57. package/dist/theme-normalize.d.ts +9 -0
  58. package/dist/theme-normalize.d.ts.map +1 -1
  59. package/dist/theme-normalize.js +65 -6
  60. package/dist/theme-normalize.js.map +1 -1
  61. package/dist/theme-render.d.ts +15 -0
  62. package/dist/theme-render.d.ts.map +1 -1
  63. package/dist/theme-render.js +39 -0
  64. package/dist/theme-render.js.map +1 -1
  65. package/dist/themes.d.ts +15 -1
  66. package/dist/themes.d.ts.map +1 -1
  67. package/dist/themes.js +48 -1
  68. package/dist/themes.js.map +1 -1
  69. package/dist/url.d.ts +45 -0
  70. package/dist/url.d.ts.map +1 -0
  71. package/dist/url.js +64 -0
  72. package/dist/url.js.map +1 -0
  73. package/dist/version.d.ts +2 -2
  74. package/dist/version.js +1 -1
  75. package/package.json +2 -2
  76. package/src/__tests__/redos-hardening.test.ts +1 -1
  77. package/src/ai-tools.ts +19 -16
  78. package/src/build-page.ts +3 -5
  79. package/src/content.test.ts +99 -17
  80. package/src/content.ts +95 -8
  81. package/src/context.ts +6 -0
  82. package/src/font-assets.ts +63 -0
  83. package/src/google-models.ts +13 -0
  84. package/src/image-capabilities.ts +91 -0
  85. package/src/index.ts +5 -2
  86. package/src/media.ts +23 -6
  87. package/src/plugin-preview.test.ts +79 -0
  88. package/src/plugin-preview.ts +81 -0
  89. package/src/preview-compose-deferrals.test.ts +144 -0
  90. package/src/preview-compose.test.ts +16 -0
  91. package/src/preview-compose.ts +125 -37
  92. package/src/responsive-images.ts +6 -5
  93. package/src/seo.test.ts +8 -8
  94. package/src/seo.ts +15 -23
  95. package/src/template-engine-data-lists.test.ts +90 -0
  96. package/src/template-engine.ts +72 -1
  97. package/src/theme-importers/loose.ts +1 -1
  98. package/src/theme-normalize.ts +70 -8
  99. package/src/theme-render.ts +36 -0
  100. package/src/theme-token-roles.test.ts +182 -0
  101. package/src/themes.ts +53 -0
  102. package/src/url.test.ts +40 -0
  103. package/src/url.ts +69 -0
  104. package/src/version.ts +1 -1
  105. package/dist/design-manifest.d.ts +0 -36
  106. package/dist/design-manifest.d.ts.map +0 -1
  107. package/dist/design-manifest.js +0 -90
  108. package/dist/design-manifest.js.map +0 -1
  109. package/dist/i18n.d.ts +0 -42
  110. package/dist/i18n.d.ts.map +0 -1
  111. package/dist/i18n.js +0 -85
  112. package/dist/i18n.js.map +0 -1
  113. package/src/design-manifest.ts +0 -93
  114. package/src/i18n.test.ts +0 -58
  115. package/src/i18n.ts +0 -91
@@ -2,9 +2,9 @@
2
2
 
3
3
  import { describe, expect, it } from "bun:test";
4
4
  import {
5
- localeSchema,
6
5
  MODULE_HTML_MAX,
7
6
  moduleCreateSchema,
7
+ moduleUpdateSchema,
8
8
  pageCreateSchema,
9
9
  pageSetModulesSchema,
10
10
  pageUpdateSchema,
@@ -29,21 +29,6 @@ describe("slugSchema", () => {
29
29
  });
30
30
  });
31
31
 
32
- describe("localeSchema", () => {
33
- it("accepts language and language-region", () => {
34
- expect(localeSchema.safeParse("en").success).toBe(true);
35
- expect(localeSchema.safeParse("de").success).toBe(true);
36
- expect(localeSchema.safeParse("de-AT").success).toBe(true);
37
- });
38
-
39
- it("rejects malformed locales", () => {
40
- expect(localeSchema.safeParse("EN").success).toBe(false);
41
- expect(localeSchema.safeParse("en-us").success).toBe(false);
42
- expect(localeSchema.safeParse("eng").success).toBe(false);
43
- expect(localeSchema.safeParse("").success).toBe(false);
44
- });
45
- });
46
-
47
32
  describe("moduleCreateSchema", () => {
48
33
  it("accepts a minimal module", () => {
49
34
  const r = moduleCreateSchema.safeParse({
@@ -73,6 +58,104 @@ describe("moduleCreateSchema", () => {
73
58
  });
74
59
  expect(r.success).toBe(false);
75
60
  });
61
+
62
+ // issue #432 — CDATA wrappers stored verbatim broke rendering and sent the
63
+ // AI into a ~20-loop visual repair spiral; the write boundary now rejects
64
+ // them with an actionable message.
65
+ it("rejects XML CDATA wrappers in css and js, with an actionable message", () => {
66
+ const base = { slug: "site-header", displayName: "Site header", html: "<header></header>" };
67
+ const css = moduleCreateSchema.safeParse({
68
+ ...base,
69
+ css: "/*<![CDATA[*/ .x { color: red } /*]]>*/",
70
+ });
71
+ expect(css.success).toBe(false);
72
+ if (!css.success) {
73
+ expect(css.error.issues.map((i) => i.message).join(" ")).toContain("CDATA");
74
+ }
75
+ const js = moduleCreateSchema.safeParse({
76
+ ...base,
77
+ js: "//<![CDATA[\nconsole.log('hi');\n//]]>",
78
+ });
79
+ expect(js.success).toBe(false);
80
+ });
81
+
82
+ it("accepts plain css/js (and js merely mentioning ']]>' in a string)", () => {
83
+ const base = { slug: "site-header", displayName: "Site header", html: "<header></header>" };
84
+ expect(
85
+ moduleCreateSchema.safeParse({ ...base, css: ".x { color: red }", js: "console.log(1);" })
86
+ .success,
87
+ ).toBe(true);
88
+ // Only the OPENING marker is the corruption signature; a bare "]]>"
89
+ // inside a string literal is legitimate (e.g. code emitting XML).
90
+ expect(moduleCreateSchema.safeParse({ ...base, js: 'xml += "]]>";' }).success).toBe(true);
91
+ });
92
+
93
+ it("rejects CDATA on the update path too (edit_module / edit_content funnel)", () => {
94
+ const r = moduleUpdateSchema.safeParse({
95
+ moduleId: "8c2f2f2a-0000-4000-8000-000000000432",
96
+ css: "/*<![CDATA[*/ .x{} /*]]>*/",
97
+ });
98
+ expect(r.success).toBe(false);
99
+ });
100
+ });
101
+
102
+ // CLAUDE.md §1A / issue #417 — repeating content is a list field, never
103
+ // numbered scalars. Threshold is 3: a pair (col1/col2) is a legitimate
104
+ // layout split; three-or-more numbered siblings is a list.
105
+ describe("moduleFields numbered-scalar fanout guard (§1A)", () => {
106
+ const mod = (fields: unknown) =>
107
+ moduleCreateSchema.safeParse({
108
+ slug: "cards",
109
+ displayName: "Cards",
110
+ html: "<div></div>",
111
+ fields,
112
+ });
113
+ const text = (name: string) => ({ name, kind: "text", label: name });
114
+
115
+ it("rejects a bare base + numbered siblings (label, label2, label3)", () => {
116
+ const r = mod([text("label"), text("label2"), text("label3")]);
117
+ expect(r.success).toBe(false);
118
+ if (!r.success) {
119
+ const msg = r.error.issues[0]?.message ?? "";
120
+ expect(msg).toContain("numbered-scalar fanout");
121
+ expect(msg).toContain('"label", "label2", "label3"');
122
+ // AI-actionable: the error names every list-kind fix.
123
+ expect(msg).toContain("text-list");
124
+ expect(msg).toContain("link-list");
125
+ expect(msg).toContain("module-list");
126
+ expect(msg).toContain("§1A");
127
+ }
128
+ });
129
+
130
+ it("rejects underscore-separated runs (quote_1..quote_3) and mixed separators", () => {
131
+ expect(mod([text("quote_1"), text("quote_2"), text("quote_3")]).success).toBe(false);
132
+ expect(mod([text("logo1"), text("logo_2"), text("logo_3")]).success).toBe(false);
133
+ });
134
+
135
+ it("rejects fanout on moduleUpdateSchema too (same shared fields array)", () => {
136
+ const r = moduleUpdateSchema.safeParse({
137
+ moduleId: "6f9619ff-8b86-4d01-b42d-00cf4fc964ff",
138
+ fields: [text("card1"), text("card2"), text("card3")],
139
+ });
140
+ expect(r.success).toBe(false);
141
+ });
142
+
143
+ it("allows a two-field split (col1/col2) — threshold is 3", () => {
144
+ expect(mod([text("col1"), text("col2")]).success).toBe(true);
145
+ expect(mod([text("label"), text("label2")]).success).toBe(true);
146
+ expect(mod([text("address_line1"), text("address_line2")]).success).toBe(true);
147
+ });
148
+
149
+ it("allows unrelated numbered fields that never form a run of 3", () => {
150
+ expect(mod([text("hero_title"), text("cta_2024"), text("step_1")]).success).toBe(true);
151
+ // Same suffix, different bases — no shared run.
152
+ expect(mod([text("left_col1"), text("right_col1"), text("mid_col1")]).success).toBe(true);
153
+ });
154
+
155
+ it("scopes to scalar kinds — numbered list fields are a modelling question, not fanout", () => {
156
+ const linkList = (name: string) => ({ name, kind: "link-list", label: name });
157
+ expect(mod([linkList("links1"), linkList("links2"), linkList("links3")]).success).toBe(true);
158
+ });
76
159
  });
77
160
 
78
161
  describe("pageCreateSchema (no raw HTML invariant)", () => {
@@ -84,7 +167,6 @@ describe("pageCreateSchema (no raw HTML invariant)", () => {
84
167
  });
85
168
  expect(r.success).toBe(true);
86
169
  if (!r.success) return;
87
- expect(r.data.locale).toBe("en");
88
170
  // status is intentionally OPTIONAL (no schema default): pages.create
89
171
  // resolves it at write time — published on a bootstrap site, else draft.
90
172
  // Omitting it here leaves it undefined for the handler to resolve.
package/src/content.ts CHANGED
@@ -84,11 +84,6 @@ export function slugifyModuleSection(
84
84
  return `${deriveModuleType(displayName)}-${idx}-${suffix}`;
85
85
  }
86
86
 
87
- /** BCP-47 shape: 2-letter language with optional 2-letter region. P9 widens this. */
88
- export const localeSchema = z
89
- .string()
90
- .regex(/^[a-z]{2}(-[A-Z]{2})?$/, "locale must be 'xx' or 'xx-YY' (BCP-47 shape)");
91
-
92
87
  const displayNameSchema = z.string().min(1).max(128);
93
88
 
94
89
  /** Caps are arbitrary but cheap — paste-of-binary mistakes get caught. */
@@ -99,8 +94,39 @@ export const TEMPLATE_HTML_MAX = 512 * 1024;
99
94
  export const TEMPLATE_CSS_MAX = 128 * 1024;
100
95
 
101
96
  const moduleHtml = z.string().max(MODULE_HTML_MAX, `html exceeds ${MODULE_HTML_MAX} bytes`);
102
- const moduleCss = z.string().max(MODULE_CSS_MAX, `css exceeds ${MODULE_CSS_MAX} bytes`);
103
- const moduleJs = z.string().max(MODULE_JS_MAX, `js exceeds ${MODULE_JS_MAX} bytes`);
97
+
98
+ /**
99
+ * issue #432 root-cause guard — reject XML CDATA wrappers in module css/js.
100
+ *
101
+ * Module css/js is stored and served VERBATIM, so a `<![CDATA[ … ]]>`
102
+ * wrapper (an XHTML-era idiom the AI occasionally reaches for when
103
+ * "protecting" inline code) reaches the browser unparsed: the stylesheet
104
+ * fails to apply and the script throws `SyntaxError: Unexpected token '<'`.
105
+ * On e2e runs 31000584991 / 31000699422 (2026-08-05) exactly this landed
106
+ * silently, the page rendered broken, and the model burned ~15–20 extra
107
+ * loops (~+1.2M input tokens) discovering and repairing it via
108
+ * screenshot/inspect/edit cycles. Rejecting at the write boundary with an
109
+ * actionable message turns that repair spiral into a single corrected call
110
+ * (CLAUDE.md §11 — failure surfaces are AI-actionable; §2 — fail loudly).
111
+ *
112
+ * css/js only: CDATA is never valid CSS or JS, while an html body may
113
+ * legitimately carry CDATA inside inline `<svg>`/`<math>` foreign content.
114
+ */
115
+ const CDATA_OPEN = "<![CDATA[";
116
+ const noCdata = (value: string): boolean => !value.includes(CDATA_OPEN);
117
+ const cdataMessage = (field: "css" | "js"): string =>
118
+ `${field} contains an XML CDATA marker (${CDATA_OPEN}) — module ${field} is stored and served ` +
119
+ `verbatim, so CDATA wrappers reach the browser unparsed and break rendering. ` +
120
+ `Remove the wrapper and resend plain ${field === "css" ? "CSS" : "JavaScript"}.`;
121
+
122
+ const moduleCss = z
123
+ .string()
124
+ .max(MODULE_CSS_MAX, `css exceeds ${MODULE_CSS_MAX} bytes`)
125
+ .refine(noCdata, cdataMessage("css"));
126
+ const moduleJs = z
127
+ .string()
128
+ .max(MODULE_JS_MAX, `js exceeds ${MODULE_JS_MAX} bytes`)
129
+ .refine(noCdata, cdataMessage("js"));
104
130
 
105
131
  /**
106
132
  * v0.4.0 — module field schema. Each field declares one substitution slot in
@@ -283,6 +309,54 @@ export const moduleRefSchema = z
283
309
  .strict();
284
310
  export type ModuleRef = z.infer<typeof moduleRefSchema>;
285
311
 
312
+ /**
313
+ * CLAUDE.md §1A — "repeating content is a list field, never numbered
314
+ * scalars". This guard rejects the mechanically detectable half of that
315
+ * rule: a RUN of 3+ sibling scalar fields sharing a base name plus a
316
+ * numeric suffix (`label`, `label2`, `label3` / `quote_1`…`quote_3`).
317
+ *
318
+ * Threshold is 3 (issue #417): a two-field split (`col1`/`col2` for a
319
+ * two-column layout) is routinely a genuine layout role, so a pair stays
320
+ * legal; three-or-more numbered siblings is repeating content that must
321
+ * be ONE list field. The bare base name counts as an implicit member of
322
+ * its run — `label` next to `label2`/`label3` is item 1 in disguise.
323
+ *
324
+ * Deliberately out of scope (guidance-only, per the issue): content-
325
+ * derived names (`quote_justamazing`) and mid-name numbering
326
+ * (`step1_title`) — neither is detectable without false positives.
327
+ * Nested/list kinds are excluded too: a numbered run of lists is
328
+ * already a modelling question, not scalar fanout. The server-side
329
+ * extractor fallback (`extract-module-structure.ts`) is also
330
+ * unguarded on purpose: it numbers repeated tags in messy HUMAN-
331
+ * authored HTML, runs only when the caller declared no fields, and its
332
+ * output never re-enters this schema — the guard polices the boundary
333
+ * where the AI (or a human) AUTHORS `fields[]` explicitly.
334
+ */
335
+ const NUMBERED_SCALAR_FANOUT_THRESHOLD = 3;
336
+ const numberedFieldName = /^([a-z][a-z0-9_]*?)_?\d+$/;
337
+
338
+ function findNumberedScalarFanoutRuns(
339
+ fields: readonly { name: string; kind: string }[],
340
+ ): string[][] {
341
+ const scalarKinds = new Set<string>(MODULE_FIELD_PRIMITIVE_KINDS);
342
+ const scalarNames = fields.filter((f) => scalarKinds.has(f.kind)).map((f) => f.name);
343
+ const byBase = new Map<string, string[]>();
344
+ for (const name of scalarNames) {
345
+ const m = numberedFieldName.exec(name);
346
+ const base = m?.[1];
347
+ if (base === undefined) continue;
348
+ const members = byBase.get(base);
349
+ if (members) members.push(name);
350
+ else byBase.set(base, [name]);
351
+ }
352
+ const runs: string[][] = [];
353
+ for (const [base, members] of byBase) {
354
+ const run = scalarNames.includes(base) ? [base, ...members] : members;
355
+ if (run.length >= NUMBERED_SCALAR_FANOUT_THRESHOLD) runs.push(run);
356
+ }
357
+ return runs;
358
+ }
359
+
286
360
  const moduleFieldsArray = z
287
361
  .array(moduleFieldSchema)
288
362
  .max(64, "modules may declare at most 64 fields")
@@ -295,6 +369,20 @@ const moduleFieldsArray = z
295
369
  }
296
370
  seen.add(f.name);
297
371
  }
372
+ for (const run of findNumberedScalarFanoutRuns(arr)) {
373
+ ctx.addIssue({
374
+ code: z.ZodIssueCode.custom,
375
+ message:
376
+ `numbered-scalar fanout: ${run.map((n) => `"${n}"`).join(", ")} repeat one role as ` +
377
+ "numbered scalar fields — repeating content is ONE list field, never numbered scalars " +
378
+ '(CLAUDE.md §1A). Replace the run with a single field: kind "text-list" (list of ' +
379
+ 'strings, inner template iterates {{.}}), "link-list" (list of {label, href}), or ' +
380
+ '"module-list" (rich per-item structure: mint a card sub-module and reference it per ' +
381
+ "item — in build_page, author the card detached with `ref` and pass " +
382
+ '[{"$ref": "<ref>"}, …] as the field value). A two-field split like col1/col2 is fine; ' +
383
+ `${NUMBERED_SCALAR_FANOUT_THRESHOLD}+ numbered siblings is a list.`,
384
+ });
385
+ }
298
386
  });
299
387
 
300
388
  /**
@@ -457,7 +545,6 @@ export const pageStatusSchema = z.enum(["draft", "published"]);
457
545
  export const pageCreateSchema = z
458
546
  .object({
459
547
  slug: slugSchema,
460
- locale: localeSchema.default("en"),
461
548
  /** P6.7.5 — internal editor label. Defaults to title if omitted. */
462
549
  name: z.string().min(1).max(256).optional(),
463
550
  title: z.string().min(1).max(256),
package/src/context.ts CHANGED
@@ -31,6 +31,12 @@ export interface ExecutionContext {
31
31
  * fold consecutive AI actions into one entry.
32
32
  */
33
33
  readonly chatTaskId?: string;
34
+ /**
35
+ * For a plugin installed as an external artifact: the digest of the
36
+ * artifact this call runs. Private storage operations accept the call
37
+ * only while exactly this artifact is the active, granted one.
38
+ */
39
+ readonly pluginArtifactDigest?: string;
34
40
  /**
35
41
  * P10.5: parent attribution for subagent invocations. When the
36
42
  * `spawn_subagent` tool calls runChatTurn for the child, it carries
@@ -0,0 +1,63 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ import { z } from "zod";
3
+
4
+ export const fontRef = z
5
+ .object({ id: z.string().uuid(), sha256: z.string().regex(/^[a-f0-9]{64}$/) })
6
+ .strict();
7
+ export const fontLicense = z
8
+ .object({
9
+ name: z.string().min(1).max(200),
10
+ text: z.string().min(1).max(100_000),
11
+ webEmbedding: z.boolean(),
12
+ documentEmbedding: z.boolean(),
13
+ })
14
+ .strict();
15
+ export const fontMetadata = fontRef.extend({
16
+ family: z.string(),
17
+ subfamily: z.string(),
18
+ postscriptName: z.string(),
19
+ cssFamily: z.string(),
20
+ format: z.enum(["ttf", "otf", "woff", "woff2"]),
21
+ weight: z.number(),
22
+ style: z.enum(["normal", "italic"]),
23
+ axes: z.record(z.string(), z.object({ min: z.number(), max: z.number(), default: z.number() })),
24
+ sizeBytes: z.number(),
25
+ glyphCount: z.number(),
26
+ embedding: z.object({
27
+ web: z.boolean(),
28
+ document: z.boolean(),
29
+ subset: z.boolean(),
30
+ restriction: z.string().nullable(),
31
+ }),
32
+ license: fontLicense,
33
+ source: z.string(),
34
+ createdAt: z.string(),
35
+ });
36
+ export type FontRef = z.infer<typeof fontRef>;
37
+ export type FontMetadata = z.infer<typeof fontMetadata>;
38
+ export const fontImportInput = z
39
+ .object({
40
+ dataBase64: z.string().min(1).max(11_184_812),
41
+ license: fontLicense,
42
+ source: z.string().min(1).max(1000),
43
+ })
44
+ .strict();
45
+ export const fontResolveInput = fontRef
46
+ .extend({
47
+ use: z.enum(["web", "document"]),
48
+ text: z.string().max(200_000).default(""),
49
+ formats: z
50
+ .array(z.enum(["ttf", "otf", "woff", "woff2"]))
51
+ .min(1)
52
+ .max(4),
53
+ })
54
+ .strict();
55
+ export const fontReadInput = fontRef
56
+ .extend({ offset: z.number().int().min(0), length: z.number().int().min(1).max(262144) })
57
+ .strict();
58
+ export const fontFindInput = z
59
+ .object({
60
+ query: z.string().max(200).default(""),
61
+ limit: z.number().int().min(1).max(100).default(50),
62
+ })
63
+ .strict();
@@ -0,0 +1,13 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /** Google image models, curated against https://ai.google.dev/gemini-api/docs/models
4
+ * on 2026-09-11. Chat models live in admin-core's model-catalog.json; image-only
5
+ * models stay out of it because they cannot call tools. Exact IDs are
6
+ * intentional; automatic latest aliases could change behaviour.
7
+ */
8
+ export const GOOGLE_IMAGE_MODELS = [
9
+ { id: "gemini-3.1-flash-image", label: "Nano Banana 2 (Gemini 3.1 Flash Image)" },
10
+ { id: "gemini-3.1-flash-lite-image", label: "Nano Banana 2 Lite" },
11
+ { id: "gemini-3-pro-image", label: "Nano Banana Pro (Gemini 3 Pro Image)" },
12
+ { id: "gemini-2.5-flash-image", label: "Nano Banana (Gemini 2.5 Flash Image)" },
13
+ ] as const;
@@ -0,0 +1,91 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * Image model capabilities (#529) and the one check every caller runs
5
+ * before a paid image request — the chat's generate_image/edit_image
6
+ * (admin-core) and the plugin `ctx.images` broker (plugin-host) alike.
7
+ * Profiles per model live in admin-core/src/ai/image-models.ts.
8
+ */
9
+
10
+ /** What callers may ask of a model. Reported verbatim to the AI and plugins. */
11
+ export interface ImageCapabilities {
12
+ readonly provider: "openai" | "google";
13
+ readonly model: string;
14
+ /** `edit` = change a source image (optionally under a mask). */
15
+ readonly operations: readonly ("generate" | "edit")[];
16
+ readonly references: {
17
+ readonly max: number;
18
+ readonly maxBytesEach: number;
19
+ readonly maxBytesTotal: number;
20
+ readonly mediaTypes: readonly ("image/png" | "image/jpeg" | "image/webp")[];
21
+ };
22
+ /** True when an edit can be limited to a masked region. */
23
+ readonly mask: boolean;
24
+ /** Output shapes accepted as `size`. */
25
+ readonly sizes: readonly ("1024x1024" | "1792x1024" | "1024x1792")[];
26
+ /** Native resolutions accepted as `imageSize` (empty: not selectable). */
27
+ readonly imageSizes: readonly ("1K" | "2K" | "4K")[];
28
+ }
29
+
30
+ /** The fields the check reads — satisfied by ImageCapabilities and by the
31
+ * plugin SDK's structurally identical PluginImageCapabilities. */
32
+ export interface ImageCapabilityLimits {
33
+ readonly model: string;
34
+ readonly operations: readonly string[];
35
+ readonly references: {
36
+ readonly max: number;
37
+ readonly maxBytesEach: number;
38
+ readonly maxBytesTotal: number;
39
+ readonly mediaTypes: readonly string[];
40
+ };
41
+ readonly mask: boolean;
42
+ readonly sizes: readonly string[];
43
+ readonly imageSizes: readonly string[];
44
+ }
45
+
46
+ /**
47
+ * Check a request against a model's capabilities. Returns an AI-actionable
48
+ * reason, or null when the request fits. Run before any reservation.
49
+ */
50
+ export function capabilityRefusal(
51
+ caps: ImageCapabilityLimits,
52
+ request: {
53
+ operation: "generate" | "edit";
54
+ references: readonly { bytes: number; mediaType: string }[];
55
+ mask: boolean;
56
+ size?: string;
57
+ imageSize?: string;
58
+ },
59
+ ): string | null {
60
+ if (!caps.operations.includes(request.operation)) {
61
+ return `${caps.model} cannot ${request.operation} images. Supported: ${caps.operations.join(", ")}.`;
62
+ }
63
+ if (request.mask && !caps.mask) {
64
+ return `${caps.model} cannot limit an edit to a mask. Describe the region in the prompt instead, or configure a model that supports masks.`;
65
+ }
66
+ if (request.references.length > caps.references.max) {
67
+ return `${caps.model} accepts at most ${caps.references.max} reference image(s); ${request.references.length} given.`;
68
+ }
69
+ let total = 0;
70
+ for (const ref of request.references) {
71
+ if (!caps.references.mediaTypes.includes(ref.mediaType)) {
72
+ return `${caps.model} accepts reference images as ${caps.references.mediaTypes.join(", ")}; got ${ref.mediaType}.`;
73
+ }
74
+ if (ref.bytes > caps.references.maxBytesEach) {
75
+ return `A reference image is larger than ${caps.references.maxBytesEach} bytes, the limit for ${caps.model}.`;
76
+ }
77
+ total += ref.bytes;
78
+ }
79
+ if (total > caps.references.maxBytesTotal) {
80
+ return `Reference images total ${total} bytes; ${caps.model} accepts ${caps.references.maxBytesTotal}.`;
81
+ }
82
+ if (request.size && !caps.sizes.includes(request.size)) {
83
+ return `${caps.model} does not produce ${request.size}. Sizes: ${caps.sizes.join(", ")}.`;
84
+ }
85
+ if (request.imageSize && !caps.imageSizes.includes(request.imageSize)) {
86
+ return caps.imageSizes.length === 0
87
+ ? `${caps.model} has no selectable resolution; omit imageSize.`
88
+ : `${caps.model} resolutions: ${caps.imageSizes.join(", ")}.`;
89
+ }
90
+ return null;
91
+ }
package/src/index.ts CHANGED
@@ -12,11 +12,12 @@ export * from "./context.js";
12
12
  export * from "./css-gradient-scan.js";
13
13
  export * from "./css-var-scan.js";
14
14
  export * from "./design-draft-shell.js";
15
- export * from "./design-manifest.js";
15
+ export * from "./font-assets.js";
16
16
  export * from "./fonts.js";
17
17
  export * from "./genesis.js";
18
18
  export * from "./genesis-inventory.js";
19
- export * from "./i18n.js";
19
+ export * from "./google-models.js";
20
+ export * from "./image-capabilities.js";
20
21
  export * from "./interactions.js";
21
22
  export {
22
23
  type LogContext,
@@ -31,6 +32,7 @@ export {
31
32
  } from "./logger.js";
32
33
  export * from "./media.js";
33
34
  export * from "./page-log.js";
35
+ export * from "./plugin-preview.js";
34
36
  export * from "./preview-compose.js";
35
37
  export * from "./preview-scanner.js";
36
38
  export * from "./proposal-status.js";
@@ -56,4 +58,5 @@ export * from "./theme-ramp.js";
56
58
  export * from "./theme-render.js";
57
59
  export * from "./themes.js";
58
60
  export * from "./themes-errors.js";
61
+ export * from "./url.js";
59
62
  export { CAELO_VERSION, CALEO_VERSION, type CaeloVersion, parseVersion } from "./version.js";
package/src/media.ts CHANGED
@@ -184,6 +184,14 @@ export function extractMediaRefs(html: string): MediaRef[] {
184
184
 
185
185
  const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/, "must be hex sha256");
186
186
 
187
+ /**
188
+ * #531 — `library` assets are listed and placeable on pages; `reference`
189
+ * assets exist only to guide image generation/editing: hidden from the
190
+ * default listing and refused by the static generator on a page.
191
+ */
192
+ export const mediaVisibilitySchema = z.enum(["library", "reference"]);
193
+ export type MediaVisibility = z.infer<typeof mediaVisibilitySchema>;
194
+
187
195
  export const mediaUploadInputSchema = z
188
196
  .object({
189
197
  sha256: sha256Schema,
@@ -213,6 +221,10 @@ export const mediaUploadInputSchema = z
213
221
  sourceKind: z.enum(["upload", "ai_generated", "imported", "external"]).optional(),
214
222
  sourceDetail: z.string().max(2048).optional(),
215
223
  license: z.string().max(200).optional(),
224
+ /** Defaults to `library`; a re-upload of existing content keeps its visibility. */
225
+ visibility: mediaVisibilitySchema.optional(),
226
+ /** #528/#532 — the asset this one was made from (an edit). */
227
+ derivedFromId: z.string().uuid().optional(),
216
228
  variants: z
217
229
  .array(
218
230
  z.object({
@@ -234,6 +246,8 @@ export const mediaListInputSchema = z
234
246
  query: z.string().max(256).optional(),
235
247
  mime: z.enum(MEDIA_ALLOWED_MIMES).optional(),
236
248
  sort: z.enum(["recent", "most_used"]).default("recent"),
249
+ /** `library` (default) hides reference images; `all` lists both. */
250
+ visibility: z.enum(["library", "reference", "all"]).default("library"),
237
251
  limit: z.number().int().positive().max(200).default(60),
238
252
  offset: z.number().int().nonnegative().default(0),
239
253
  })
@@ -264,6 +278,15 @@ export const mediaSetSourceInputSchema = z
264
278
  .strict();
265
279
  export type MediaSetSourceInput = z.infer<typeof mediaSetSourceInputSchema>;
266
280
 
281
+ /** media.set_visibility (#531) — move an asset between library and reference. */
282
+ export const mediaSetVisibilityInputSchema = z
283
+ .object({
284
+ assetId: z.string().uuid(),
285
+ visibility: mediaVisibilitySchema,
286
+ })
287
+ .strict();
288
+ export type MediaSetVisibilityInput = z.infer<typeof mediaSetVisibilityInputSchema>;
289
+
267
290
  export const mediaDeleteInputSchema = z
268
291
  .object({
269
292
  assetId: z.string().uuid(),
@@ -279,12 +302,6 @@ export const mediaRecordUsageInputSchema = z
279
302
  .strict();
280
303
  export type MediaRecordUsageInput = z.infer<typeof mediaRecordUsageInputSchema>;
281
304
 
282
- export const mediaRecentForAiInputSchema = z
283
- .object({
284
- limit: z.number().int().positive().max(60).default(30),
285
- })
286
- .strict();
287
-
288
305
  export const mediaSetCdnInputSchema = z
289
306
  .object({
290
307
  enabled: z.boolean(),
@@ -0,0 +1,79 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ import { expect, test } from "bun:test";
3
+ import { chatSendMessageInput } from "./ai-tools.js";
4
+ import {
5
+ PLUGIN_PREVIEW_REFERENCE_MARKER,
6
+ pluginPreviewDocumentSchema,
7
+ pluginPreviewSelectionSchema,
8
+ readPluginPreviewReference,
9
+ } from "./plugin-preview.js";
10
+
11
+ test("bounded plugin selections retain exact revision and target identity through chat input", () => {
12
+ const selection = {
13
+ pluginSlug: "example",
14
+ id: "page-one-text",
15
+ label: "Page 1 · Text",
16
+ reference: {
17
+ documentId: crypto.randomUUID(),
18
+ revisionId: crypto.randomUUID(),
19
+ pageId: crypto.randomUUID(),
20
+ part: "text",
21
+ },
22
+ };
23
+ const parsed = chatSendMessageInput.parse({
24
+ chatSessionId: crypto.randomUUID(),
25
+ content: "Make this shorter",
26
+ previewSelection: selection,
27
+ });
28
+ expect(parsed.previewSelection).toEqual(selection);
29
+ expect(
30
+ pluginPreviewSelectionSchema.safeParse({ ...selection, reference: { html: "x".repeat(257) } })
31
+ .success,
32
+ ).toBe(false);
33
+ expect(
34
+ pluginPreviewSelectionSchema.safeParse({ ...selection, pluginSlug: "../admin" }).success,
35
+ ).toBe(false);
36
+ const target = { id: "one", label: "One", reference: { id: "one" } };
37
+ expect(
38
+ pluginPreviewDocumentSchema.safeParse({ html: "<p>One</p>", targets: [target, target] })
39
+ .success,
40
+ ).toBe(false);
41
+ });
42
+
43
+ test("transcripts show a reference label without exposing opaque IDs or losing ordinary text", () => {
44
+ const selection = {
45
+ id: "text",
46
+ label: "Page 1 · Text",
47
+ pluginSlug: "example",
48
+ reference: { revisionId: "private-revision", part: "text" },
49
+ };
50
+ expect(
51
+ readPluginPreviewReference(
52
+ "Shorten this" + PLUGIN_PREVIEW_REFERENCE_MARKER + JSON.stringify(selection),
53
+ ),
54
+ ).toEqual({ text: "Shorten this", selection });
55
+ const literal = "Unrelated message" + PLUGIN_PREVIEW_REFERENCE_MARKER + "not JSON";
56
+ expect(readPluginPreviewReference(literal)).toEqual({ text: literal });
57
+ });
58
+
59
+ test("viewport context must reference declared targets and document choices have unique identities", () => {
60
+ const target = { id: "page", label: "Page", reference: { revisionId: "one" } };
61
+ expect(
62
+ pluginPreviewDocumentSchema.safeParse({
63
+ html: "",
64
+ targets: [target],
65
+ contextTargetIds: ["missing"],
66
+ }).success,
67
+ ).toBe(false);
68
+ expect(
69
+ pluginPreviewDocumentSchema.safeParse({
70
+ html: "",
71
+ targets: [target],
72
+ contextTargetIds: ["page"],
73
+ }).success,
74
+ ).toBe(true);
75
+ const doc = { id: "document", label: "Document", url: "/plugins/example/preview?args=%7B%7D" };
76
+ expect(pluginPreviewDocumentSchema.safeParse({ html: "", documents: [doc, doc] }).success).toBe(
77
+ false,
78
+ );
79
+ });