ampless 1.0.0-alpha.16 → 1.0.0-alpha.18

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/dist/index.d.ts CHANGED
@@ -69,7 +69,339 @@ declare function detectContentEvents(input: {
69
69
  newStatus?: 'draft' | 'published';
70
70
  }): ContentEventType[];
71
71
 
72
+ type ThemeFieldType = 'color' | 'text' | 'select' | 'image' | 'length' | 'fontFamily' | 'linkList';
73
+ /**
74
+ * Single entry in a `linkList` field. Stored as part of a JSON array
75
+ * under the field's storage key. `url` may be:
76
+ * - a relative path (`/about`)
77
+ * - an absolute URL (`https://example.com`)
78
+ * - a tag reference (`tag:guide`) — themes interpret this as
79
+ * "expand to a list of posts with this tag" rather than rendering
80
+ * a literal link.
81
+ */
82
+ interface LinkListItem {
83
+ label: string;
84
+ url: string;
85
+ }
86
+ /**
87
+ * A user-facing string in a manifest. Either a plain string (rendered
88
+ * as-is, regardless of locale) or a per-locale map (the renderer picks
89
+ * the active locale, falling back to `en`, then to any value).
90
+ *
91
+ * Themes that ship in a single language can keep these as plain
92
+ * strings. The default themes use the map form so the same manifest
93
+ * works for both built-in dictionaries.
94
+ */
95
+ type LocalizedString = string | Record<string, string>;
96
+ interface ThemeFieldBase {
97
+ /** Storage key. Persisted as `theme.{key}` in site settings. */
98
+ key: string;
99
+ label: LocalizedString;
100
+ description?: LocalizedString;
101
+ /** Optional UI grouping (e.g. 'Colors', 'Typography', 'Branding'). */
102
+ group?: LocalizedString;
103
+ /** Used when no override is set. Always a string for storage uniformity. */
104
+ default: string;
105
+ /**
106
+ * If set, the loader injects `${cssVar}: ${value}` into a `:root`
107
+ * style block on every public page, so CSS rules using
108
+ * `var(${cssVar})` pick up overrides at render time.
109
+ *
110
+ * Fields without `cssVar` (e.g. logo URL, header tagline) are exposed
111
+ * to template code via `loadThemeConfig()` instead.
112
+ */
113
+ cssVar?: string;
114
+ }
115
+ interface ThemeColorField extends ThemeFieldBase {
116
+ type: 'color';
117
+ }
118
+ interface ThemeTextField extends ThemeFieldBase {
119
+ type: 'text';
120
+ maxLength?: number;
121
+ }
122
+ interface ThemeSelectField extends ThemeFieldBase {
123
+ type: 'select';
124
+ options: ReadonlyArray<{
125
+ value: string;
126
+ label: LocalizedString;
127
+ }>;
128
+ }
129
+ interface ThemeImageField extends ThemeFieldBase {
130
+ type: 'image';
131
+ }
132
+ interface ThemeLengthField extends ThemeFieldBase {
133
+ type: 'length';
134
+ }
135
+ interface ThemeFontFamilyField extends ThemeFieldBase {
136
+ type: 'fontFamily';
137
+ options: ReadonlyArray<{
138
+ value: string;
139
+ label: LocalizedString;
140
+ }>;
141
+ }
142
+ /**
143
+ * A repeatable list of {label, url} entries — used for nav menus,
144
+ * footer link sets, sidebar groups, etc. Stored in KvStore as a JSON
145
+ * string so it fits the existing `string`-valued site-settings cache.
146
+ *
147
+ * `default` is declared as a plain array for ergonomics; the loader
148
+ * stringifies it on the fly so manifest authors don't have to call
149
+ * JSON.stringify by hand.
150
+ */
151
+ interface ThemeLinkListField extends Omit<ThemeFieldBase, 'default' | 'cssVar'> {
152
+ type: 'linkList';
153
+ default: ReadonlyArray<LinkListItem>;
154
+ /** Cap admin-supplied list length. Default 50. */
155
+ maxItems?: number;
156
+ }
157
+ type ThemeField = ThemeColorField | ThemeTextField | ThemeSelectField | ThemeImageField | ThemeLengthField | ThemeFontFamilyField | ThemeLinkListField;
158
+ interface ThemeManifest {
159
+ /** Theme directory name (`themes/<name>/`). */
160
+ name: string;
161
+ label: LocalizedString;
162
+ description?: LocalizedString;
163
+ fields: ReadonlyArray<ThemeField>;
164
+ }
165
+ declare function defineTheme(m: ThemeManifest): ThemeManifest;
166
+ /**
167
+ * Resolve a `LocalizedString` to a plain string for display.
168
+ * Strings pass through; maps pick `locale` → `fallback` → any value
169
+ * → empty. The empty fallback keeps the renderer from crashing on a
170
+ * malformed manifest while making the missing translation visible.
171
+ */
172
+ declare function resolveLocalized(value: LocalizedString | undefined, locale: string, fallback?: string): string;
173
+ interface ThemeRouteContext<P = Record<string, string>> {
174
+ params: Promise<P>;
175
+ }
176
+ interface ThemeModule {
177
+ /** Stable identifier — must match the directory name and the value
178
+ * stored as `theme.active`. */
179
+ name: string;
180
+ manifest: ThemeManifest;
181
+ /**
182
+ * Server components rendered by the dispatcher routes
183
+ * (`app/page.tsx`, `app/[slug]/page.tsx`, `app/tag/[tag]/page.tsx`).
184
+ * Each theme MUST provide Home; Post / Tag are recommended but
185
+ * optional (dispatcher 404s when missing).
186
+ */
187
+ components: {
188
+ Home: (ctx: ThemeRouteContext) => Promise<unknown> | unknown;
189
+ Post?: (ctx: ThemeRouteContext<{
190
+ slug: string;
191
+ }>) => Promise<unknown> | unknown;
192
+ Tag?: (ctx: ThemeRouteContext<{
193
+ tag: string;
194
+ }>) => Promise<unknown> | unknown;
195
+ };
196
+ /**
197
+ * Optional `generateMetadata` hooks called by the dispatcher. Same
198
+ * signature as the matching component's params.
199
+ */
200
+ metadata?: {
201
+ Home?: (ctx: ThemeRouteContext) => Promise<unknown> | unknown;
202
+ Post?: (ctx: ThemeRouteContext<{
203
+ slug: string;
204
+ }>) => Promise<unknown> | unknown;
205
+ Tag?: (ctx: ThemeRouteContext<{
206
+ tag: string;
207
+ }>) => Promise<unknown> | unknown;
208
+ };
209
+ /**
210
+ * Optional route handlers for /feed.xml and /sitemap.xml. The
211
+ * dispatcher returns 404 if a theme doesn't provide them.
212
+ */
213
+ routes?: {
214
+ feed?: (ctx: {
215
+ request: Request;
216
+ }) => Promise<Response>;
217
+ sitemap?: (ctx: {
218
+ request: Request;
219
+ }) => Promise<Response>;
220
+ };
221
+ }
222
+ declare function defineThemeModule(m: ThemeModule): ThemeModule;
223
+ /**
224
+ * Storage key used in KvStore. Prefix `theme.` keeps the namespace
225
+ * separate from `site.*` / `media.*` so unrelated tools can scan
226
+ * settings without colliding.
227
+ */
228
+ declare function themeSettingKey(fieldKey: string): string;
229
+ /**
230
+ * Reject malformed or potentially-injectable values before they reach
231
+ * the KvStore. Admin/editor are trusted but typos and copy-paste
232
+ * mistakes shouldn't be able to break a site's CSS or sneak `</style>`
233
+ * into the inline tag the loader emits.
234
+ *
235
+ * Returns the normalized value, or null if the input is rejected.
236
+ */
237
+ /**
238
+ * Split a stored color value into its light / dark components.
239
+ *
240
+ * Accepts two storage forms:
241
+ * - Single value: `oklch(...)` / `#abcdef` / etc. → `{ light: value, dark: null }`
242
+ * - Pair: `light-dark(L, D)` → `{ light: L, dark: D }`
243
+ *
244
+ * Splits on the top-level comma (depth-aware) so nested commas inside
245
+ * `rgb(...)` / `hsl(...)` don't trip the parser.
246
+ */
247
+ declare function parseColorPair(value: string): {
248
+ light: string;
249
+ dark: string | null;
250
+ };
251
+ /**
252
+ * Build the storage string for a color field. When `dark` is non-empty
253
+ * and differs from `light`, returns `light-dark(light, dark)`; otherwise
254
+ * returns the bare `light` value. The runtime emits the result verbatim
255
+ * into the inline `:root { --foo: <value> }` override; `light-dark()`
256
+ * is a Baseline-2024 CSS function so the browser picks per mode.
257
+ */
258
+ declare function formatColorPair(light: string, dark?: string | null): string;
259
+ declare function validateThemeValue(field: ThemeField, raw: unknown): string | null;
260
+ /** Parse a stored linkList JSON value into typed items. Tolerant: bad
261
+ * shapes resolve to []. Throwing here would cascade into rendering. */
262
+ declare function parseLinkList(raw: string | undefined | null): LinkListItem[];
263
+ declare function stringifyLinkList(items: ReadonlyArray<LinkListItem>): string;
264
+ /**
265
+ * Detect a `tag:<name>` URL form. Themes use this to render a list of
266
+ * posts under a heading instead of a literal link — useful for docs
267
+ * sidebars and category-style nav.
268
+ */
269
+ declare function isTagListUrl(url: string): {
270
+ tag: string;
271
+ } | null;
272
+ /**
273
+ * Resolve effective values for every manifest field, merging stored
274
+ * overrides on top of defaults. `stored` is the flat settings map keyed
275
+ * by `theme.{key}` — typically the output of `listSiteSettings()`
276
+ * filtered to theme entries.
277
+ */
278
+ declare function resolveThemeValues(manifest: ThemeManifest, stored: Record<string, unknown>): Record<string, string>;
279
+
72
280
  type TrustLevel = 'untrusted' | 'trusted' | 'privileged';
281
+ /**
282
+ * Plugin capability declarations. The runtime uses this list for
283
+ * declaration-vs-implementation reconciliation warnings and (in later
284
+ * phases) for `allowCapabilities` gating in `cms.config.ts`.
285
+ *
286
+ * Phase 1 active capabilities:
287
+ * - `publicHead` / `publicBody`: descriptor-based head/body injection.
288
+ * - `metadata` / `eventHooks`: name-only declaration for existing surfaces.
289
+ *
290
+ * Reserved capabilities are accepted by the type so that plugins can
291
+ * declare future intent, but the runtime does nothing with them yet —
292
+ * each has its own RFP under `docs/tmp/`. Declaring a reserved
293
+ * capability today is harmless, but the runtime won't expose any new
294
+ * surface for it until the matching phase ships.
295
+ */
296
+ type PluginCapability = 'publicHead' | 'publicBody' | 'metadata' | 'eventHooks' | 'adminSettings' | 'schema' | 'writePublicAsset' | 'contentFields' | 'adminPage' | 'serverRoute' | 'secretSettings' | 'network' | 'scheduler' | 'storageWrite' | 'privilegedSystem';
297
+ /**
298
+ * Loading strategy for `script` / `inlineScript` descriptors.
299
+ *
300
+ * - `afterInteractive` (default): load after hydration, non-blocking.
301
+ * The runtime adds `async` for external scripts when neither
302
+ * `async` nor `defer` is set explicitly. `inlineScript` is emitted
303
+ * inline as-is in Phase 1 (strategy is informational only for
304
+ * inline; see comments in `plugin-head.ts`).
305
+ * - `lazyOnload`: defer load further. Phase 1 maps this to `defer`
306
+ * for external scripts; full lazy-load (next/script's idle
307
+ * scheduling) is a future enhancement.
308
+ *
309
+ * `beforeInteractive` is intentionally excluded — App Router does not
310
+ * support emitting plain `<script>` elements that block hydration from
311
+ * the runtime layer, and the spec defers that case to the future
312
+ * developer extension surface.
313
+ */
314
+ type ScriptStrategy = 'afterInteractive' | 'lazyOnload';
315
+ /**
316
+ * Context passed to `publicHead` / `publicBodyEnd`. Phase 1 carries
317
+ * only the site-wide config block. Phase 2 adds the `setting()`
318
+ * accessor for admin-managed `settings.public` values; per-route /
319
+ * per-post context lands in Phase 4 (`plugin-per-post-rfp.md`).
320
+ */
321
+ interface PluginPublicRenderContext {
322
+ site: Config['site'];
323
+ /**
324
+ * Resolve a public setting value for the active plugin instance.
325
+ * Returns `stored ?? manifest.default ?? undefined`. Stored values
326
+ * are read at request time from the DDB → S3 site-settings cache
327
+ * pipeline. Bound by the runtime when the plugin declares
328
+ * `settings.public` — plugins without a manifest can still call
329
+ * this, in which case it always returns `undefined`.
330
+ *
331
+ * The generic type is a convenience cast: the runtime does not
332
+ * coerce values, so callers should pick `T` to match the field's
333
+ * declared type (`text` → `string`, `number` → `number`, etc.).
334
+ * Validation at admin save time guarantees stored values match the
335
+ * field's declared shape, so the cast is safe in practice.
336
+ */
337
+ setting<T = unknown>(key: string): T | undefined;
338
+ }
339
+ /**
340
+ * Descriptor returned by `publicHead()`. The runtime validates each
341
+ * entry (URL scheme denylist, `attrs` allowlist, id collision handling)
342
+ * and renders the surviving descriptors as React elements inside the
343
+ * root layout's `<head>`. Returning arbitrary `ReactNode` is
344
+ * intentionally not offered here — see
345
+ * `docs/architecture/08-plugin-architecture.md` §"Descriptor-based
346
+ * Head/Body Injection".
347
+ */
348
+ type PublicHeadDescriptor = {
349
+ type: 'script';
350
+ /** Element id; doubles as the duplicate-detection key. */
351
+ id?: string;
352
+ src: string;
353
+ strategy?: ScriptStrategy;
354
+ async?: boolean;
355
+ defer?: boolean;
356
+ /** Allow-listed attributes only (data-*, crossorigin, referrerpolicy, ...). */
357
+ attrs?: Record<string, string | boolean>;
358
+ } | {
359
+ type: 'inlineScript';
360
+ /** Required for duplicate detection and dev warnings. */
361
+ id: string;
362
+ body: string;
363
+ strategy?: ScriptStrategy;
364
+ /**
365
+ * Type-only reservation. CSP nonce resolution (including the
366
+ * planned `'auto'` mode) is deferred to a future RFP; Phase 1
367
+ * does not propagate this field to the rendered element.
368
+ */
369
+ nonce?: string;
370
+ } | {
371
+ type: 'meta';
372
+ name?: string;
373
+ property?: string;
374
+ content: string;
375
+ } | {
376
+ type: 'link';
377
+ rel: string;
378
+ href: string;
379
+ as?: string;
380
+ /** Mapped to React's `type` attribute. */
381
+ typeAttr?: string;
382
+ } | {
383
+ type: 'noscript';
384
+ id?: string;
385
+ /** Raw HTML emitted inside `<noscript>`. */
386
+ html: string;
387
+ };
388
+ /**
389
+ * Descriptor returned by `publicBodyEnd()`. Supports the same
390
+ * `script` / `inlineScript` / `noscript` variants as the head, plus
391
+ * the body-only `iframe` variant (used by Google Tag Manager's
392
+ * `<noscript>`-style fallback frame, chat widgets, etc.).
393
+ */
394
+ type PublicBodyDescriptor = Extract<PublicHeadDescriptor, {
395
+ type: 'script' | 'inlineScript' | 'noscript';
396
+ }> | {
397
+ type: 'iframe';
398
+ id?: string;
399
+ src: string;
400
+ title?: string;
401
+ width?: number;
402
+ height?: number;
403
+ attrs?: Record<string, string | boolean>;
404
+ };
73
405
  /**
74
406
  * Metadata-like object that maps cleanly onto Next.js `Metadata`. We keep
75
407
  * the shape framework-agnostic so the core type doesn't depend on Next.js.
@@ -156,11 +488,131 @@ interface OgImageConfig {
156
488
  */
157
489
  render(ctx: OgImageRenderContext): Promise<unknown> | unknown;
158
490
  }
491
+ /**
492
+ * Shared shape for every `PluginSettingField` variant. `T` is the
493
+ * decoded value type (string for text-like fields, number for number,
494
+ * boolean for boolean, etc.). All variants share `key` / `label` /
495
+ * `default` / `required`; type-specific constraints (e.g. `pattern`,
496
+ * `min`, `options`) live on the discriminated branches.
497
+ */
498
+ interface PluginFieldBase<T> {
499
+ /**
500
+ * Storage key. Stored as `plugins.<instanceId>.<key>`. Must match
501
+ * `PLUGIN_KEY_PATTERN` (`/^[a-zA-Z0-9_-]+$/`) so the `pk.sk` dotted
502
+ * separator survives. Violations are skipped + warned by the
503
+ * runtime/admin normalization pass.
504
+ */
505
+ key: string;
506
+ label: LocalizedString;
507
+ description?: LocalizedString;
508
+ /** Used by the runtime when no admin-stored value is present. */
509
+ default?: T;
510
+ /**
511
+ * When true, an empty / undefined value is rejected at save time
512
+ * and the resolver returns `undefined`. When false (default),
513
+ * string-like fields accept empty string as a valid "disabled"
514
+ * value while non-string fields still reject empty strings.
515
+ */
516
+ required?: boolean;
517
+ /** Optional UI grouping (mirrors `ThemeField.group`). */
518
+ group?: LocalizedString;
519
+ }
520
+ interface PluginTextField extends PluginFieldBase<string> {
521
+ type: 'text';
522
+ maxLength?: number;
523
+ /** RegExp source (e.g. `'^G-[A-Z0-9]+$'`). Validated against
524
+ * non-empty values; empty string skips the check. */
525
+ pattern?: string;
526
+ /** Placeholder for the admin input. */
527
+ placeholder?: string;
528
+ }
529
+ interface PluginTextareaField extends PluginFieldBase<string> {
530
+ type: 'textarea';
531
+ maxLength?: number;
532
+ placeholder?: string;
533
+ /** Rendered rows hint for the admin textarea. */
534
+ rows?: number;
535
+ }
536
+ interface PluginBooleanField extends PluginFieldBase<boolean> {
537
+ type: 'boolean';
538
+ }
539
+ interface PluginNumberField extends PluginFieldBase<number> {
540
+ type: 'number';
541
+ min?: number;
542
+ max?: number;
543
+ step?: number;
544
+ }
545
+ interface PluginSelectField extends PluginFieldBase<string> {
546
+ type: 'select';
547
+ options: ReadonlyArray<{
548
+ value: string;
549
+ label: LocalizedString;
550
+ }>;
551
+ }
552
+ interface PluginUrlField extends PluginFieldBase<string> {
553
+ type: 'url';
554
+ placeholder?: string;
555
+ /** When true, relative paths (`/foo`, `./foo`) pass validation; default true. */
556
+ allowRelative?: boolean;
557
+ }
558
+ interface PluginCodeField extends PluginFieldBase<string> {
559
+ type: 'code';
560
+ /** Display-only language label (e.g. `'js'`, `'css'`, `'html'`). */
561
+ language?: string;
562
+ maxLength?: number;
563
+ placeholder?: string;
564
+ rows?: number;
565
+ }
566
+ interface PluginJsonField extends PluginFieldBase<unknown> {
567
+ type: 'json';
568
+ placeholder?: string;
569
+ rows?: number;
570
+ }
571
+ type PluginSettingField = PluginTextField | PluginTextareaField | PluginBooleanField | PluginNumberField | PluginSelectField | PluginUrlField | PluginCodeField | PluginJsonField;
572
+ /**
573
+ * Per-plugin settings declaration. Phase 2 implements `public`;
574
+ * `secret` is reserved for Phase 6a (admin-only storage; never reaches
575
+ * the public runtime).
576
+ */
577
+ interface PluginSettingsManifest {
578
+ public?: readonly PluginSettingField[];
579
+ }
159
580
  interface AmplessPlugin {
160
581
  name: string;
161
582
  /** Plugin API version. Currently 1; future versions will be additive. */
162
583
  apiVersion: 1;
163
584
  trust_level: TrustLevel;
585
+ /**
586
+ * Stable per-install namespace. Defaults to `name` when omitted.
587
+ * Distinguishes multiple instances of the same plugin (e.g. two GTM
588
+ * containers, two GA4 measurement IDs). Multi-instance run-time
589
+ * validation lands in Phase 3; Phase 1 only adds the field so plugin
590
+ * authors can author against it now.
591
+ */
592
+ instanceId?: string;
593
+ /**
594
+ * Human-readable label for admin UI surfaces (Phase 2 onward).
595
+ * Plain string or per-locale map — see `LocalizedString`.
596
+ */
597
+ displayName?: LocalizedString;
598
+ /**
599
+ * Declared capability list. The runtime uses this for
600
+ * declaration-vs-implementation warnings (e.g. a plugin that
601
+ * declares `publicBody` but defines no `publicBodyEnd`); later
602
+ * phases will gate dangerous capabilities through `cms.config.ts`
603
+ * `allowCapabilities`. Existing plugins that omit this field
604
+ * continue to work unchanged.
605
+ */
606
+ capabilities?: readonly PluginCapability[];
607
+ /**
608
+ * Public, admin-editable settings (Phase 2). Each declared field is
609
+ * stored under `pk='siteconfig', sk='plugins.<instanceId>.<key>'`,
610
+ * mirrored to S3 via the trusted processor, and surfaced to
611
+ * `publicHead` / `publicBodyEnd` via `ctx.setting<T>(key)`. Plugins
612
+ * without an admin UI continue to work — they just don't have a
613
+ * `settings` block.
614
+ */
615
+ settings?: PluginSettingsManifest;
164
616
  /** Async event hooks. Run in trust_level-matched Lambda. */
165
617
  hooks?: {
166
618
  [K in EventType]?: PluginEventHandler<K>;
@@ -174,6 +626,20 @@ interface AmplessPlugin {
174
626
  * Site-level metadata (root layout). Returned per request.
175
627
  */
176
628
  siteMetadata?(site: Config['site']): PluginMetadata;
629
+ /**
630
+ * Declarative head injection. Returns a list of validated
631
+ * descriptors (script / inlineScript / meta / link / noscript). The
632
+ * runtime collects every plugin's contribution at render time, runs
633
+ * URL scheme + attrs validation, then emits React elements inside
634
+ * the root layout's `<head>`. See `PublicHeadDescriptor`.
635
+ */
636
+ publicHead?(ctx: PluginPublicRenderContext): readonly PublicHeadDescriptor[];
637
+ /**
638
+ * Same shape as `publicHead`, but the result is appended at the
639
+ * end of `<body>` and additionally supports the `iframe` variant
640
+ * (GTM no-script fallback frame, chat widgets, ...).
641
+ */
642
+ publicBodyEnd?(ctx: PluginPublicRenderContext): readonly PublicBodyDescriptor[];
177
643
  /**
178
644
  * Dynamic OG image renderer. The dispatcher route (e.g.
179
645
  * `app/og/[slug]/route.ts`) reads this and feeds the element into
@@ -560,6 +1026,53 @@ declare function decodeAwsJson(value: unknown): unknown;
560
1026
  */
561
1027
  declare function formatPublicAssetUrl(bucket: string, region: string, key: string): string;
562
1028
 
1029
+ declare const PLUGIN_KEY_PATTERN: RegExp;
1030
+ declare function isValidPluginKey(key: string): boolean;
1031
+ /**
1032
+ * Validate one raw value against a field definition. Returns the
1033
+ * (possibly-coerced) value on success, or `null` to signal rejection.
1034
+ *
1035
+ * Semantics:
1036
+ * - **string-like fields** (text / textarea / url / code) accept
1037
+ * `''` as valid when `required` is falsy. This is the "disable"
1038
+ * sentinel — e.g. `pattern: '^$|^G-...'` lets a GA4 plugin save
1039
+ * an empty measurementId to suppress the loader without dropping
1040
+ * the row.
1041
+ * - **non-string-like fields** (number / boolean / json / select)
1042
+ * always reject `''`. Allowing it would force callers to handle a
1043
+ * `string` reading where `number | undefined` is declared. To
1044
+ * "unset" these fields, delete the row (admin form's "Reset to
1045
+ * default" button).
1046
+ * - `undefined` is treated as "not set" by `resolvePluginSettings`
1047
+ * — `validatePluginSettingValue` itself returns `null` for it.
1048
+ * - Constraints (`pattern`, `min`, `max`, `maxLength`, `options`) run
1049
+ * only when the value is present and non-empty.
1050
+ *
1051
+ * The returned shape preserves the declared type — `text` stores a
1052
+ * sanitized string, `number` stores a `number`, `boolean` stores a
1053
+ * `boolean`, `json` stores the decoded value (object / array /
1054
+ * primitive — never the source string), etc.
1055
+ */
1056
+ declare function validatePluginSettingValue(field: PluginSettingField, raw: unknown): unknown | null;
1057
+ /**
1058
+ * Merge stored values on top of manifest defaults for one plugin
1059
+ * instance. Both sides are validated through `validatePluginSettingValue`
1060
+ * — stored values that fail validation (manual DDB tampering, schema
1061
+ * drift) fall back to the validated default; defaults that themselves
1062
+ * fail validation surface as `undefined`.
1063
+ *
1064
+ * `stored` is a flat key → value map keyed by the field's `key` (not
1065
+ * the full DDB SK). The runtime extracts it from the site-settings
1066
+ * snapshot using the `plugins.<instanceId>.` prefix.
1067
+ *
1068
+ * Validation runs on the default too because the default can come
1069
+ * from a plugin's constructor argument (e.g. GA4 takes a
1070
+ * `measurementId` option and passes it through as the field's
1071
+ * `default`). If the operator supplies a bogus value at install time
1072
+ * we'd rather surface `undefined` than render garbage.
1073
+ */
1074
+ declare function resolvePluginSettings(manifest: PluginSettingsManifest | undefined, stored: Record<string, unknown>): Record<string, unknown>;
1075
+
563
1076
  /**
564
1077
  * Extract the first image URL from a post body. Used by plugins (e.g.
565
1078
  * plugin-og-image) that want to derive an image from the post content
@@ -663,214 +1176,6 @@ declare function pickDefaultEntrypoint(files: readonly {
663
1176
  path: string;
664
1177
  }[]): string;
665
1178
 
666
- type ThemeFieldType = 'color' | 'text' | 'select' | 'image' | 'length' | 'fontFamily' | 'linkList';
667
- /**
668
- * Single entry in a `linkList` field. Stored as part of a JSON array
669
- * under the field's storage key. `url` may be:
670
- * - a relative path (`/about`)
671
- * - an absolute URL (`https://example.com`)
672
- * - a tag reference (`tag:guide`) — themes interpret this as
673
- * "expand to a list of posts with this tag" rather than rendering
674
- * a literal link.
675
- */
676
- interface LinkListItem {
677
- label: string;
678
- url: string;
679
- }
680
- /**
681
- * A user-facing string in a manifest. Either a plain string (rendered
682
- * as-is, regardless of locale) or a per-locale map (the renderer picks
683
- * the active locale, falling back to `en`, then to any value).
684
- *
685
- * Themes that ship in a single language can keep these as plain
686
- * strings. The default themes use the map form so the same manifest
687
- * works for both built-in dictionaries.
688
- */
689
- type LocalizedString = string | Record<string, string>;
690
- interface ThemeFieldBase {
691
- /** Storage key. Persisted as `theme.{key}` in site settings. */
692
- key: string;
693
- label: LocalizedString;
694
- description?: LocalizedString;
695
- /** Optional UI grouping (e.g. 'Colors', 'Typography', 'Branding'). */
696
- group?: LocalizedString;
697
- /** Used when no override is set. Always a string for storage uniformity. */
698
- default: string;
699
- /**
700
- * If set, the loader injects `${cssVar}: ${value}` into a `:root`
701
- * style block on every public page, so CSS rules using
702
- * `var(${cssVar})` pick up overrides at render time.
703
- *
704
- * Fields without `cssVar` (e.g. logo URL, header tagline) are exposed
705
- * to template code via `loadThemeConfig()` instead.
706
- */
707
- cssVar?: string;
708
- }
709
- interface ThemeColorField extends ThemeFieldBase {
710
- type: 'color';
711
- }
712
- interface ThemeTextField extends ThemeFieldBase {
713
- type: 'text';
714
- maxLength?: number;
715
- }
716
- interface ThemeSelectField extends ThemeFieldBase {
717
- type: 'select';
718
- options: ReadonlyArray<{
719
- value: string;
720
- label: LocalizedString;
721
- }>;
722
- }
723
- interface ThemeImageField extends ThemeFieldBase {
724
- type: 'image';
725
- }
726
- interface ThemeLengthField extends ThemeFieldBase {
727
- type: 'length';
728
- }
729
- interface ThemeFontFamilyField extends ThemeFieldBase {
730
- type: 'fontFamily';
731
- options: ReadonlyArray<{
732
- value: string;
733
- label: LocalizedString;
734
- }>;
735
- }
736
- /**
737
- * A repeatable list of {label, url} entries — used for nav menus,
738
- * footer link sets, sidebar groups, etc. Stored in KvStore as a JSON
739
- * string so it fits the existing `string`-valued site-settings cache.
740
- *
741
- * `default` is declared as a plain array for ergonomics; the loader
742
- * stringifies it on the fly so manifest authors don't have to call
743
- * JSON.stringify by hand.
744
- */
745
- interface ThemeLinkListField extends Omit<ThemeFieldBase, 'default' | 'cssVar'> {
746
- type: 'linkList';
747
- default: ReadonlyArray<LinkListItem>;
748
- /** Cap admin-supplied list length. Default 50. */
749
- maxItems?: number;
750
- }
751
- type ThemeField = ThemeColorField | ThemeTextField | ThemeSelectField | ThemeImageField | ThemeLengthField | ThemeFontFamilyField | ThemeLinkListField;
752
- interface ThemeManifest {
753
- /** Theme directory name (`themes/<name>/`). */
754
- name: string;
755
- label: LocalizedString;
756
- description?: LocalizedString;
757
- fields: ReadonlyArray<ThemeField>;
758
- }
759
- declare function defineTheme(m: ThemeManifest): ThemeManifest;
760
- /**
761
- * Resolve a `LocalizedString` to a plain string for display.
762
- * Strings pass through; maps pick `locale` → `fallback` → any value
763
- * → empty. The empty fallback keeps the renderer from crashing on a
764
- * malformed manifest while making the missing translation visible.
765
- */
766
- declare function resolveLocalized(value: LocalizedString | undefined, locale: string, fallback?: string): string;
767
- interface ThemeRouteContext<P = Record<string, string>> {
768
- params: Promise<P>;
769
- }
770
- interface ThemeModule {
771
- /** Stable identifier — must match the directory name and the value
772
- * stored as `theme.active`. */
773
- name: string;
774
- manifest: ThemeManifest;
775
- /**
776
- * Server components rendered by the dispatcher routes
777
- * (`app/page.tsx`, `app/[slug]/page.tsx`, `app/tag/[tag]/page.tsx`).
778
- * Each theme MUST provide Home; Post / Tag are recommended but
779
- * optional (dispatcher 404s when missing).
780
- */
781
- components: {
782
- Home: (ctx: ThemeRouteContext) => Promise<unknown> | unknown;
783
- Post?: (ctx: ThemeRouteContext<{
784
- slug: string;
785
- }>) => Promise<unknown> | unknown;
786
- Tag?: (ctx: ThemeRouteContext<{
787
- tag: string;
788
- }>) => Promise<unknown> | unknown;
789
- };
790
- /**
791
- * Optional `generateMetadata` hooks called by the dispatcher. Same
792
- * signature as the matching component's params.
793
- */
794
- metadata?: {
795
- Home?: (ctx: ThemeRouteContext) => Promise<unknown> | unknown;
796
- Post?: (ctx: ThemeRouteContext<{
797
- slug: string;
798
- }>) => Promise<unknown> | unknown;
799
- Tag?: (ctx: ThemeRouteContext<{
800
- tag: string;
801
- }>) => Promise<unknown> | unknown;
802
- };
803
- /**
804
- * Optional route handlers for /feed.xml and /sitemap.xml. The
805
- * dispatcher returns 404 if a theme doesn't provide them.
806
- */
807
- routes?: {
808
- feed?: (ctx: {
809
- request: Request;
810
- }) => Promise<Response>;
811
- sitemap?: (ctx: {
812
- request: Request;
813
- }) => Promise<Response>;
814
- };
815
- }
816
- declare function defineThemeModule(m: ThemeModule): ThemeModule;
817
- /**
818
- * Storage key used in KvStore. Prefix `theme.` keeps the namespace
819
- * separate from `site.*` / `media.*` so unrelated tools can scan
820
- * settings without colliding.
821
- */
822
- declare function themeSettingKey(fieldKey: string): string;
823
- /**
824
- * Reject malformed or potentially-injectable values before they reach
825
- * the KvStore. Admin/editor are trusted but typos and copy-paste
826
- * mistakes shouldn't be able to break a site's CSS or sneak `</style>`
827
- * into the inline tag the loader emits.
828
- *
829
- * Returns the normalized value, or null if the input is rejected.
830
- */
831
- /**
832
- * Split a stored color value into its light / dark components.
833
- *
834
- * Accepts two storage forms:
835
- * - Single value: `oklch(...)` / `#abcdef` / etc. → `{ light: value, dark: null }`
836
- * - Pair: `light-dark(L, D)` → `{ light: L, dark: D }`
837
- *
838
- * Splits on the top-level comma (depth-aware) so nested commas inside
839
- * `rgb(...)` / `hsl(...)` don't trip the parser.
840
- */
841
- declare function parseColorPair(value: string): {
842
- light: string;
843
- dark: string | null;
844
- };
845
- /**
846
- * Build the storage string for a color field. When `dark` is non-empty
847
- * and differs from `light`, returns `light-dark(light, dark)`; otherwise
848
- * returns the bare `light` value. The runtime emits the result verbatim
849
- * into the inline `:root { --foo: <value> }` override; `light-dark()`
850
- * is a Baseline-2024 CSS function so the browser picks per mode.
851
- */
852
- declare function formatColorPair(light: string, dark?: string | null): string;
853
- declare function validateThemeValue(field: ThemeField, raw: unknown): string | null;
854
- /** Parse a stored linkList JSON value into typed items. Tolerant: bad
855
- * shapes resolve to []. Throwing here would cascade into rendering. */
856
- declare function parseLinkList(raw: string | undefined | null): LinkListItem[];
857
- declare function stringifyLinkList(items: ReadonlyArray<LinkListItem>): string;
858
- /**
859
- * Detect a `tag:<name>` URL form. Themes use this to render a list of
860
- * posts under a heading instead of a literal link — useful for docs
861
- * sidebars and category-style nav.
862
- */
863
- declare function isTagListUrl(url: string): {
864
- tag: string;
865
- } | null;
866
- /**
867
- * Resolve effective values for every manifest field, merging stored
868
- * overrides on top of defaults. `stored` is the flat settings map keyed
869
- * by `theme.{key}` — typically the output of `listSiteSettings()`
870
- * filtered to theme entries.
871
- */
872
- declare function resolveThemeValues(manifest: ThemeManifest, stored: Record<string, unknown>): Record<string, string>;
873
-
874
1179
  declare const VERSION = "0.0.1";
875
1180
 
876
- export { type AmplessEvent, type AmplessPlugin, type AuthContext, type BundleExtractResult, type CacheConfig, type CacheStrategy, type Config, type ContentEventPayload, type ContentEventType, type ContentFormat, type ContentTypeDefinition, type CreatePostInput, DEFAULT_ENTRYPOINT, type DateFormat, type EventPayloadOf, type EventType, type ExtractedFile, type FieldDefinition, type FieldType, type ImageDisplay, type KvItem, type KvStore, type LinkListItem, type ListOptions, type LocalizedString, MAX_BUNDLE_BYTES, type Media, type MediaEventPayload, type MediaEventType, type MediaMetadata, type MediaProcessingDefaults, type OgImageConfig, type OgImageFont, type OgImageRenderContext, type Page, type PluginEventHandler, type PluginMetadata, type PluginRuntimeContext, type Post, type PostIndexEventPayload, type PostIndexEventType, type PostMetadata, type PostStatus, type PostsProvider, type Role, SITE_CONFIG_PK, type SiteSettingsEventPayload, type SiteSettingsEventType, type StaticPostBody, type StaticPostFileMeta, type StreamEventName, TEXT_EXTENSIONS, type ThemeColorField, type ThemeField, type ThemeFieldType, type ThemeFontFamilyField, type ThemeImageField, type ThemeLengthField, type ThemeLinkListField, type ThemeManifest, type ThemeModule, type ThemeRouteContext, type ThemeSelectField, type ThemeTextField, type TrustLevel, VERSION, type ValidationIssue, bundlePrefix, createPost, decodeAwsJson, defineConfig, definePlugin, defineSchema, defineTheme, defineThemeModule, deletePost, deleteSiteSetting, detectContentEvents, encodeAwsJson, escapeXml, extractFirstImageUrl, findAbsolutePathRefs, flattenSettings, formatColorPair, formatDate, formatPublicAssetUrl, getKvStore, getPost, getPostById, getSiteSetting, hasKvStore, hasPostsProvider, isTagListUrl, listPosts, listSiteSettings, mimeTypeFor, parseColorPair, parseLinkList, pickDefaultEntrypoint, resolveLocalized, resolveThemeValues, setKvStore, setPostsProvider, setSiteSetting, stringifyLinkList, stripCommonPrefix, themeSettingKey, unflattenSettings, updatePost, validateBundle, validateBundlePath, validateThemeValue };
1181
+ export { type AmplessEvent, type AmplessPlugin, type AuthContext, type BundleExtractResult, type CacheConfig, type CacheStrategy, type Config, type ContentEventPayload, type ContentEventType, type ContentFormat, type ContentTypeDefinition, type CreatePostInput, DEFAULT_ENTRYPOINT, type DateFormat, type EventPayloadOf, type EventType, type ExtractedFile, type FieldDefinition, type FieldType, type ImageDisplay, type KvItem, type KvStore, type LinkListItem, type ListOptions, type LocalizedString, MAX_BUNDLE_BYTES, type Media, type MediaEventPayload, type MediaEventType, type MediaMetadata, type MediaProcessingDefaults, type OgImageConfig, type OgImageFont, type OgImageRenderContext, PLUGIN_KEY_PATTERN, type Page, type PluginBooleanField, type PluginCapability, type PluginCodeField, type PluginEventHandler, type PluginJsonField, type PluginMetadata, type PluginNumberField, type PluginPublicRenderContext, type PluginRuntimeContext, type PluginSelectField, type PluginSettingField, type PluginSettingsManifest, type PluginTextField, type PluginTextareaField, type PluginUrlField, type Post, type PostIndexEventPayload, type PostIndexEventType, type PostMetadata, type PostStatus, type PostsProvider, type PublicBodyDescriptor, type PublicHeadDescriptor, type Role, SITE_CONFIG_PK, type ScriptStrategy, type SiteSettingsEventPayload, type SiteSettingsEventType, type StaticPostBody, type StaticPostFileMeta, type StreamEventName, TEXT_EXTENSIONS, type ThemeColorField, type ThemeField, type ThemeFieldType, type ThemeFontFamilyField, type ThemeImageField, type ThemeLengthField, type ThemeLinkListField, type ThemeManifest, type ThemeModule, type ThemeRouteContext, type ThemeSelectField, type ThemeTextField, type TrustLevel, VERSION, type ValidationIssue, bundlePrefix, createPost, decodeAwsJson, defineConfig, definePlugin, defineSchema, defineTheme, defineThemeModule, deletePost, deleteSiteSetting, detectContentEvents, encodeAwsJson, escapeXml, extractFirstImageUrl, findAbsolutePathRefs, flattenSettings, formatColorPair, formatDate, formatPublicAssetUrl, getKvStore, getPost, getPostById, getSiteSetting, hasKvStore, hasPostsProvider, isTagListUrl, isValidPluginKey, listPosts, listSiteSettings, mimeTypeFor, parseColorPair, parseLinkList, pickDefaultEntrypoint, resolveLocalized, resolvePluginSettings, resolveThemeValues, setKvStore, setPostsProvider, setSiteSetting, stringifyLinkList, stripCommonPrefix, themeSettingKey, unflattenSettings, updatePost, validateBundle, validateBundlePath, validatePluginSettingValue, validateThemeValue };