@createcms/core 0.1.1

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 (83) hide show
  1. package/README.md +169 -0
  2. package/dist/ab-edge/index.cjs +214 -0
  3. package/dist/ab-edge/index.d.cts +121 -0
  4. package/dist/ab-edge/index.d.ts +121 -0
  5. package/dist/ab-edge/index.js +205 -0
  6. package/dist/bin/createcms.js +3082 -0
  7. package/dist/db.cjs +496 -0
  8. package/dist/db.d.cts +128 -0
  9. package/dist/db.d.ts +128 -0
  10. package/dist/db.js +488 -0
  11. package/dist/index.cjs +13789 -0
  12. package/dist/index.d.cts +10277 -0
  13. package/dist/index.d.ts +10277 -0
  14. package/dist/index.js +13737 -0
  15. package/dist/nanoid.cjs +50 -0
  16. package/dist/nanoid.d.cts +29 -0
  17. package/dist/nanoid.d.ts +29 -0
  18. package/dist/nanoid.js +47 -0
  19. package/dist/next/index.cjs +60 -0
  20. package/dist/next/index.d.cts +141 -0
  21. package/dist/next/index.d.ts +141 -0
  22. package/dist/next/index.js +58 -0
  23. package/dist/next/middleware.cjs +113 -0
  24. package/dist/next/middleware.d.cts +77 -0
  25. package/dist/next/middleware.d.ts +77 -0
  26. package/dist/next/middleware.js +111 -0
  27. package/dist/plugins/ab-test/analytics/upstash.cjs +345 -0
  28. package/dist/plugins/ab-test/analytics/upstash.d.cts +193 -0
  29. package/dist/plugins/ab-test/analytics/upstash.d.ts +193 -0
  30. package/dist/plugins/ab-test/analytics/upstash.js +343 -0
  31. package/dist/plugins/ab-test/client.cjs +686 -0
  32. package/dist/plugins/ab-test/client.d.cts +233 -0
  33. package/dist/plugins/ab-test/client.d.ts +233 -0
  34. package/dist/plugins/ab-test/client.js +684 -0
  35. package/dist/plugins/ab-test/index.cjs +3400 -0
  36. package/dist/plugins/ab-test/index.d.cts +1131 -0
  37. package/dist/plugins/ab-test/index.d.ts +1131 -0
  38. package/dist/plugins/ab-test/index.js +3367 -0
  39. package/dist/plugins/client.cjs +20 -0
  40. package/dist/plugins/client.d.cts +3 -0
  41. package/dist/plugins/client.d.ts +3 -0
  42. package/dist/plugins/client.js +3 -0
  43. package/dist/plugins/consent/client.cjs +315 -0
  44. package/dist/plugins/consent/client.d.cts +145 -0
  45. package/dist/plugins/consent/client.d.ts +145 -0
  46. package/dist/plugins/consent/client.js +313 -0
  47. package/dist/plugins/consent/index.cjs +267 -0
  48. package/dist/plugins/consent/index.d.cts +618 -0
  49. package/dist/plugins/consent/index.d.ts +618 -0
  50. package/dist/plugins/consent/index.js +258 -0
  51. package/dist/plugins/i18n/index.cjs +2177 -0
  52. package/dist/plugins/i18n/index.d.cts +562 -0
  53. package/dist/plugins/i18n/index.d.ts +562 -0
  54. package/dist/plugins/i18n/index.js +2150 -0
  55. package/dist/plugins/media-optimize/index.cjs +315 -0
  56. package/dist/plugins/media-optimize/index.d.cts +144 -0
  57. package/dist/plugins/media-optimize/index.d.ts +144 -0
  58. package/dist/plugins/media-optimize/index.js +311 -0
  59. package/dist/plugins/multi-tenant/index.cjs +210 -0
  60. package/dist/plugins/multi-tenant/index.d.cts +431 -0
  61. package/dist/plugins/multi-tenant/index.d.ts +431 -0
  62. package/dist/plugins/multi-tenant/index.js +207 -0
  63. package/dist/plugins/server.cjs +24 -0
  64. package/dist/plugins/server.d.cts +3 -0
  65. package/dist/plugins/server.d.ts +3 -0
  66. package/dist/plugins/server.js +3 -0
  67. package/dist/react/blocks.cjs +233 -0
  68. package/dist/react/blocks.d.cts +320 -0
  69. package/dist/react/blocks.d.ts +320 -0
  70. package/dist/react/blocks.js +226 -0
  71. package/dist/react/index.cjs +901 -0
  72. package/dist/react/index.d.cts +992 -0
  73. package/dist/react/index.d.ts +992 -0
  74. package/dist/react/index.js +872 -0
  75. package/dist/react/tracking.cjs +243 -0
  76. package/dist/react/tracking.d.cts +364 -0
  77. package/dist/react/tracking.d.ts +364 -0
  78. package/dist/react/tracking.js +216 -0
  79. package/dist/react/variant.cjs +59 -0
  80. package/dist/react/variant.d.cts +26 -0
  81. package/dist/react/variant.d.ts +26 -0
  82. package/dist/react/variant.js +57 -0
  83. package/package.json +303 -0
@@ -0,0 +1,562 @@
1
+ import * as better_call from 'better-call';
2
+ import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
3
+ import { AnyPgTable, PgDatabase } from 'drizzle-orm/pg-core';
4
+ import { AnyColumn, SQL } from 'drizzle-orm';
5
+
6
+ type ResolvedUserConfig = {
7
+ table: AnyPgTable;
8
+ tableName: string;
9
+ schemaName: string | null;
10
+ idColumn: AnyColumn;
11
+ /** The camelCase key used in the Drizzle table definition (e.g. "id"). */
12
+ idColumnKey: string;
13
+ /** The actual database column name (e.g. "id" or "user_id"). */
14
+ idColumnDbName: string;
15
+ allColumns: Record<string, AnyColumn>;
16
+ /** Allowlist (camelCase keys) of columns exposable via `withUser`. */
17
+ exposeColumns: string[];
18
+ sqlTableRef: string;
19
+ };
20
+
21
+ type DrizzleInstance = PgDatabase<any, Record<string, unknown>, any>;
22
+
23
+ declare const notificationTypeEnum: drizzle_orm_pg_core.PgEnum<["mention", "comment", "threadResolved", "approvalRequested", "approvalApproved", "approvalRejected", "mergeRequestOpened", "mergeRequestMerged", "mergeRequestClosed", "mergeRequestReopened", "published", "custom"]>;
24
+
25
+ type NotificationType = (typeof notificationTypeEnum.enumValues)[number];
26
+ type NotificationPayload = {
27
+ id: string;
28
+ recipientId: string;
29
+ actorId: string | null;
30
+ type: NotificationType;
31
+ title: string;
32
+ body: string | null;
33
+ resourceType: string | null;
34
+ resourceId: string | null;
35
+ collection: string | null;
36
+ meta: Record<string, unknown> | null;
37
+ createdAt: Date;
38
+ };
39
+ type OnNotificationHandler = (notification: NotificationPayload) => void | Promise<void>;
40
+ type NotificationInput = Omit<NotificationPayload, 'id' | 'createdAt'>;
41
+
42
+ type NotificationService = ReturnType<typeof createNotificationService>;
43
+ declare function createNotificationService(db: DrizzleInstance, handlers: OnNotificationHandler[]): {
44
+ notify(input: NotificationInput): Promise<NotificationPayload>;
45
+ notifyMany(inputs: NotificationInput[]): Promise<NotificationPayload[]>;
46
+ };
47
+
48
+ /**
49
+ * Per-request scope produced by a ScopeConditionFactory.
50
+ * `where` — appended to SELECT/UPDATE/DELETE queries.
51
+ * `insertColumns` — snake_case column name → value pairs merged directly
52
+ * into the raw SQL INSERT via `scopedInsert` / `scopedInsertBatch`.
53
+ */
54
+ type TableScope = {
55
+ where?: SQL;
56
+ insertColumns?: Record<string, unknown>;
57
+ };
58
+ /**
59
+ * `roots` scope additionally supports a per-NEW-ENTRY column contributor: a
60
+ * plugin can compute fresh insert columns once per newly-created logical entry
61
+ * (e.g. a freshly minted translation-group id), which the static `insertColumns`
62
+ * channel (same value on every row) can't express. Called once per
63
+ * createRoot / root-duplication. Generic — core names no column. (Seam D.)
64
+ */
65
+ type RootTableScope = TableScope & {
66
+ newEntryColumns?: () => Record<string, unknown>;
67
+ /**
68
+ * Scope columns to EXCLUDE from cross-scope read filtering — columns the
69
+ * plugin varies INDEPENDENTLY of a query so that cross-scope reads (a
70
+ * reference/host/usage that legitimately spans them) must not filter on them.
71
+ * The i18n plugin declares `['language']` (a host/reference in any sibling
72
+ * language still counts; the read path already resolved a specific sibling).
73
+ * Generic — core names no column; passed to `rootScopeConditions` as its
74
+ * `exclude`. Empty/absent → every scope column filters. (Seam D6.)
75
+ */
76
+ crossScopeExclude?: readonly string[];
77
+ };
78
+ /**
79
+ * A plugin-provided resolver for reference values (rootId / group-key strings),
80
+ * carried on the resolved scope and consumed by the read path and the A/B
81
+ * co-render walk. Core ships an IDENTITY default (`coreReferenceResolver`)
82
+ * reproducing the single-language, no-plugin behaviour byte-for-byte; the i18n
83
+ * plugin supplies a real one that understands translation groups + the fallback
84
+ * chain. Core never names any i18n concept — it knows only this interface.
85
+ *
86
+ * `db` AND `scopeColumns` are passed PER CALL (not closed over): `db` so a
87
+ * caller inside a transaction (e.g. the A/B →running guard under FOR UPDATE)
88
+ * resolves against its own tx handle; `scopeColumns` because the MERGED root
89
+ * scope columns (tenant + language) exist only AFTER every scope factory has
90
+ * run — the i18n factory that builds the resolver sees only its OWN column at
91
+ * build time. The resolver therefore closes over just its resolution POLICY
92
+ * (e.g. the i18n active language + fallback chain). `scopeColumns` is the
93
+ * scope predicate; the resolver excludes its own cross-scope columns.
94
+ * (Seam B.)
95
+ */
96
+ type ReferenceResolver = {
97
+ /**
98
+ * Read-time render pick: stored reference value → the ONE rootId it renders
99
+ * as (omit a key to leave it unresolved). Identity default: `value → value`.
100
+ */
101
+ resolveRenderTargets(db: DrizzleInstance, scopeColumns: Record<string, unknown> | undefined, collection: string, storedValues: string[]): Promise<Map<string, string>>;
102
+ /**
103
+ * Conflict superset: stored reference keys → ALL rootIds they could render as
104
+ * (a group key expands to its whole group). Used by the A/B co-render walk;
105
+ * collection-agnostic (a reference may target any collection). Identity
106
+ * default: the existing, non-archived roots among `storedKeys` (by id).
107
+ */
108
+ resolveConflictTargets(db: DrizzleInstance, scopeColumns: Record<string, unknown> | undefined, storedKeys: string[]): Promise<string[]>;
109
+ /** rootIds → all their group siblings. Identity default: the input rootIds. */
110
+ expandGroup(db: DrizzleInstance, scopeColumns: Record<string, unknown> | undefined, rootIds: string[]): Promise<string[]>;
111
+ /** rootIds → the group keys a host could embed them by. Default: `[]`. */
112
+ groupKeysFor(db: DrizzleInstance, scopeColumns: Record<string, unknown> | undefined, rootIds: string[]): Promise<string[]>;
113
+ };
114
+ /** One variant branch of a running A/B test on a referenced root. */
115
+ type RunningAbTestVariant = {
116
+ branchId: string;
117
+ isControl: boolean;
118
+ };
119
+ /** A running A/B test on one root: the test plus its variant branches. */
120
+ type RunningAbTest = {
121
+ testId: string;
122
+ trafficPercentage: number;
123
+ variants: RunningAbTestVariant[];
124
+ };
125
+ /**
126
+ * A plugin-provided resolver that reports which referenced roots currently have
127
+ * a RUNNING A/B test (with that test's variant branches). Carried on the
128
+ * resolved scope and consumed by the read path's reference loader to fan the one
129
+ * XOR-guaranteed varying block's branches out to the client (AB_FANOUT F2). Core
130
+ * ships NO default — when absent (no ab-test plugin) the read path assumes no
131
+ * running tests and every embed stays on its deterministic single pick (F0).
132
+ * Core never names any A/B concept beyond this interface. (Seam F.)
133
+ */
134
+ type AbTestResolver = {
135
+ /**
136
+ * The subset of `rootIds` that have a running test, each mapped to its test +
137
+ * variant branches. `db` AND `scopeColumns` are passed PER CALL (same
138
+ * rationale as {@link ReferenceResolver}). The caller passes already
139
+ * render-resolved (active-language) rootIds, so this needs no group expansion.
140
+ */
141
+ runningTests(db: DrizzleInstance, scopeColumns: Record<string, unknown> | undefined, rootIds: string[]): Promise<Map<string, RunningAbTest>>;
142
+ };
143
+ type ResolvedScope = {
144
+ roots?: RootTableScope;
145
+ assets?: TableScope;
146
+ assetFolders?: TableScope;
147
+ redirects?: TableScope;
148
+ /**
149
+ * Plugin-provided reference resolver (i18n translation-group resolution). When
150
+ * absent, callers use core's identity default. Generic — see `ReferenceResolver`.
151
+ */
152
+ referenceResolver?: ReferenceResolver;
153
+ /**
154
+ * Plugin-provided running-A/B-test resolver (AB_FANOUT F2 server fan-out).
155
+ * When absent, the read path assumes no running tests. Generic — see
156
+ * {@link AbTestResolver}.
157
+ */
158
+ abTestResolver?: AbTestResolver;
159
+ /**
160
+ * Opaque per-plugin context slots, keyed by plugin id. Core never reads it;
161
+ * each plugin stashes its own per-request context here from a scope factory
162
+ * and reads it back via its own exported accessor. Merged generically in
163
+ * computeScope (shallow, last-writer-wins per slot).
164
+ */
165
+ pluginContext?: Record<string, unknown>;
166
+ };
167
+ /**
168
+ * Factory registered by plugins during `init`.
169
+ * Called once per request with the middleware result to produce
170
+ * table-level WHERE conditions and extra INSERT values.
171
+ */
172
+ type ScopeConditionFactory = (mwResult: MiddlewareResult) => ResolvedScope;
173
+ type CMSOperation = 'read' | 'create' | 'update' | 'delete';
174
+ type BlockTypes = {
175
+ string: string;
176
+ number: number;
177
+ boolean: boolean;
178
+ date: string;
179
+ richText: string;
180
+ image: string;
181
+ select: string;
182
+ reference: string;
183
+ };
184
+ type BlockPropertyType = keyof BlockTypes;
185
+ type SelectOption = {
186
+ readonly label: string;
187
+ readonly value: string;
188
+ };
189
+ type BlockPropertySpec<T extends BlockPropertyType> = {
190
+ type: T;
191
+ required?: boolean;
192
+ defaultValue?: BlockTypes[T];
193
+ label: string;
194
+ description?: string;
195
+ placeholder?: string;
196
+ } & (T extends 'select' ? {
197
+ options: readonly SelectOption[];
198
+ } : {}) & (T extends 'reference' ? {
199
+ collection: string;
200
+ } : {});
201
+ /** Discriminated union over all concrete block-property specs. */
202
+ type BlockProperty = {
203
+ [K in BlockPropertyType]: BlockPropertySpec<K>;
204
+ }[BlockPropertyType];
205
+ /** Scalar property subset usable as an event parameter (no references/media). */
206
+ type ScalarBlockProperty = Extract<BlockProperty, {
207
+ type: 'string' | 'number' | 'boolean' | 'select' | 'date';
208
+ }>;
209
+ /**
210
+ * Declares a meaningful event a functional block can emit (e.g. a form's
211
+ * `submitSuccess`). Living on the block DEFINITION makes it the single source of
212
+ * truth for the typed `fire(...)` union, the test-creation goal picker, and the
213
+ * analytics wire name. `name` overrides the GA4/dataLayer wire name (defaults to
214
+ * `cms_<blockType>_<eventKey>`, computed by the measurement layer). Whether an
215
+ * event counts as a conversion is decided per test in the UI, not here.
216
+ */
217
+ type EventDeclaration = {
218
+ /** Analytics wire-name override (snake_case). Defaults to cms_<type>_<key>. */
219
+ name?: string;
220
+ /** Typed parameters carried with the event (scalar only). */
221
+ params?: Record<string, ScalarBlockProperty>;
222
+ /** Human label for the goal picker. */
223
+ label?: string;
224
+ };
225
+ type BlockDefinition<TProps extends Record<string, BlockProperty> = Record<string, BlockProperty>, TEvents extends Record<string, EventDeclaration> = Record<string, never>> = {
226
+ properties: TProps;
227
+ label: string;
228
+ description?: string;
229
+ previewImageUrl?: string;
230
+ /** Events this (functional) block can emit — see {@link EventDeclaration}. */
231
+ events?: TEvents;
232
+ } & ({
233
+ allowChildren?: false;
234
+ } | {
235
+ allowChildren: true;
236
+ allowedChildBlocks?: string[];
237
+ });
238
+ type AnyBlockDefinition = BlockDefinition<Record<string, BlockProperty>, Record<string, EventDeclaration>>;
239
+ type RootDefinition<TProps extends Record<string, BlockProperty> = Record<string, BlockProperty>> = {
240
+ properties: TProps;
241
+ };
242
+ type SlugConfig = {
243
+ enabled: false;
244
+ } | {
245
+ enabled: true;
246
+ root: string;
247
+ allowRoot?: boolean;
248
+ normalize?: boolean;
249
+ nested?: boolean;
250
+ };
251
+ type CollectionDefinition<TProps extends Record<string, BlockProperty> = Record<string, BlockProperty>, TBlocks extends Record<string, AnyBlockDefinition> = Record<string, AnyBlockDefinition>> = {
252
+ slug?: SlugConfig;
253
+ root: RootDefinition<TProps>;
254
+ blocks?: TBlocks;
255
+ label: string;
256
+ description?: string;
257
+ /**
258
+ * Marks this collection as one whose roots are meant to be EMBEDDED into other
259
+ * roots via a `reference` property (a "reusable block" library). Purely an
260
+ * ergonomic hint — it informs editor pickers and which endpoints to surface; it
261
+ * NEVER gates safety (the delete-in-use guard protects every referenced root
262
+ * regardless of this flag). Any collection can still be a reference target.
263
+ */
264
+ reusableBlock?: boolean;
265
+ };
266
+ type AnyCollectionDefinition = CollectionDefinition<Record<string, BlockProperty>, Record<string, AnyBlockDefinition>>;
267
+ type CollectionWithName = Omit<AnyCollectionDefinition, 'blocks'> & {
268
+ name: string;
269
+ blocks: Record<string, AnyBlockDefinition>;
270
+ };
271
+ type DataRetentionConfig = {
272
+ keepDays: number;
273
+ keepMinCommits: number;
274
+ /**
275
+ * Grace period (days) before a soft-archived root (`archivedAt`) is physically
276
+ * hard-deleted by pruning. Defaults to `keepDays` when omitted — a trash
277
+ * window after which the page and its whole history are reclaimed.
278
+ */
279
+ archiveKeepDays?: number;
280
+ };
281
+ /**
282
+ * Subset of the incoming request forwarded to the authMiddleware.
283
+ * Available for all call styles (HTTP router and direct server-side calls).
284
+ */
285
+ type CMSMiddlewareRequest = {
286
+ body?: Record<string, unknown>;
287
+ query?: Record<string, unknown>;
288
+ params?: Record<string, unknown>;
289
+ headers?: HeadersInit;
290
+ request?: Request;
291
+ };
292
+ /** Result that user middleware can return to extend context */
293
+ type MiddlewareResult = {
294
+ userId?: string;
295
+ [key: string]: unknown;
296
+ };
297
+ /** Base ctx injected by withCMSContext middleware. */
298
+ type CMSProcedureCtx = {
299
+ db: DrizzleInstance;
300
+ collections: Record<string, CollectionWithName>;
301
+ dataRetention?: DataRetentionConfig;
302
+ scopeConditions?: ScopeConditionFactory[];
303
+ notificationService?: NotificationService;
304
+ resolvedUser?: ResolvedUserConfig;
305
+ };
306
+
307
+ type SchemaNamespace = 'cms';
308
+ type ColumnScalarType = 'text' | 'boolean' | 'integer' | 'timestamp' | 'jsonb' | 'tsvector';
309
+ type ColumnType<EnumTarget extends string = string> = ColumnScalarType | {
310
+ enum: EnumTarget;
311
+ };
312
+ type DefaultValue = {
313
+ kind: 'literal';
314
+ value: boolean | number | string | string[] | Record<string, unknown>;
315
+ } | {
316
+ kind: 'sql';
317
+ value: string;
318
+ };
319
+ type ForeignKeyAction = 'cascade' | 'restrict' | 'no action' | 'set null' | 'set default';
320
+ type IndexUsing = 'btree' | 'gin';
321
+ type ColumnDefinition<ReferenceTarget extends string = string, EnumTarget extends string = string> = {
322
+ type: ColumnType<EnumTarget>;
323
+ columnName?: string;
324
+ notNull?: boolean;
325
+ primaryKey?: boolean;
326
+ unique?: boolean;
327
+ default?: DefaultValue;
328
+ defaultId?: boolean;
329
+ defaultIdPrefix?: string;
330
+ defaultNow?: boolean;
331
+ jsonType?: string;
332
+ references?: {
333
+ table: ReferenceTarget;
334
+ column: string;
335
+ onDelete?: ForeignKeyAction;
336
+ onUpdate?: ForeignKeyAction;
337
+ };
338
+ };
339
+ type TableColumns<ReferenceTarget extends string = string, EnumTarget extends string = string> = Record<string, ColumnDefinition<ReferenceTarget, EnumTarget>>;
340
+ type IndexDefinition<ColumnName extends string> = {
341
+ columns: readonly ColumnName[];
342
+ unique?: boolean;
343
+ using?: IndexUsing;
344
+ where?: string;
345
+ };
346
+ type CompositePrimaryKey<ColumnName extends string> = {
347
+ columns: readonly ColumnName[];
348
+ };
349
+ type TableLevelForeignKey<ColumnName extends string = string> = {
350
+ columns: readonly ColumnName[];
351
+ foreignTable: string;
352
+ foreignColumns: readonly string[];
353
+ name?: string;
354
+ onDelete?: ForeignKeyAction;
355
+ onUpdate?: ForeignKeyAction;
356
+ };
357
+ type TableDefinition<Columns extends TableColumns = TableColumns, ReferenceTarget extends string = string, EnumTarget extends string = string> = {
358
+ tableName?: string;
359
+ indexPrefix?: string;
360
+ columns: Columns;
361
+ indexes?: Record<string, IndexDefinition<Extract<keyof Columns, string>>>;
362
+ compositePrimaryKey?: CompositePrimaryKey<Extract<keyof Columns, string>>;
363
+ foreignKeys?: TableLevelForeignKey<Extract<keyof Columns, string>>[];
364
+ };
365
+ type EnumDefinition = {
366
+ values: readonly string[];
367
+ enumName?: string;
368
+ };
369
+ type EnumMap = Record<string, EnumDefinition>;
370
+ type TableMap = Record<string, TableDefinition>;
371
+ type SchemaModule<_Namespace extends SchemaNamespace = SchemaNamespace, Tables extends TableMap = {}, Enums extends EnumMap = {}, Extensions = {}> = {
372
+ enums?: Enums;
373
+ tables?: Tables;
374
+ extend?: Extensions;
375
+ };
376
+
377
+ type CMSPluginContext = CMSProcedureCtx & {
378
+ collections: Record<string, CollectionWithName>;
379
+ };
380
+
381
+ type CMSEndpointMeta = {
382
+ permissionResource?: string;
383
+ operation: CMSOperation;
384
+ scope: 'collection' | 'system';
385
+ collection?: string;
386
+ /**
387
+ * When `true`, this endpoint is intentionally exempt from the auth /
388
+ * permission / scope / hook chain — it handles its own access control
389
+ * (e.g. a public asset redirect). Every other endpoint must carry full
390
+ * `cms` metadata; `toCMSEndpoints` throws on a missing one (fail-closed).
391
+ */
392
+ public?: boolean;
393
+ };
394
+
395
+ /**
396
+ * Extends the core MiddlewareResult to require `language`. Use this to type your
397
+ * authMiddleware when the i18n plugin is active. `L` is the language union from
398
+ * the configured `languages` universe (e.g. 'en' | 'de').
399
+ *
400
+ * @example
401
+ * ```ts
402
+ * import { resolveLanguage } from '@createcms/core/plugins/i18n';
403
+ *
404
+ * authMiddleware: async (ctx): Promise<MultilingualMiddlewareResult<'en' | 'de'>> => {
405
+ * const session = await getSession(ctx);
406
+ * const language = resolveLanguage(ctx, session.locale) ?? 'en';
407
+ * return { userId: session.userId, language };
408
+ * }
409
+ * ```
410
+ */
411
+ type MultilingualMiddlewareResult<L extends string = string> = MiddlewareResult & {
412
+ language: L;
413
+ };
414
+ /**
415
+ * Resolves the active language from the incoming request context.
416
+ * Priority: body.language -> query.language -> fallback.
417
+ *
418
+ * The CMS is routing-agnostic: HOW you derive the language (URL prefix `/de`,
419
+ * domain, Accept-Language header, cookie) is the consumer's middleware concern.
420
+ * This helper only reads an explicit per-request override; pass the negotiated
421
+ * default as `fallback`.
422
+ */
423
+ declare function resolveLanguage(ctx: {
424
+ request?: CMSMiddlewareRequest;
425
+ }, fallback?: string): string | undefined;
426
+ type I18nContext = {
427
+ language: string;
428
+ fallback: readonly string[];
429
+ languages: readonly string[];
430
+ };
431
+ /**
432
+ * Read the resolved i18n context (active language + fallback chain + configured
433
+ * universe) from a ResolvedScope. The plugin's own accessor for the OPAQUE
434
+ * `pluginContext.i18n` slot it stashes per request (Seam C); core never names
435
+ * i18n. Undefined when the i18n plugin did not scope the request.
436
+ */
437
+ declare function getI18nContext(scope: ResolvedScope | undefined): I18nContext | undefined;
438
+ /**
439
+ * i18n plugin config. `languages` is the static UNIVERSE of supported languages
440
+ * (a const tuple → a typed language union); `defaultLanguage` is the seed +
441
+ * fallback head and must be a member of the universe. Per-tenant activation of a
442
+ * SUBSET is a runtime concern handled by the consumer's middleware (it returns
443
+ * the active `language`); this plugin validates that the active language is in
444
+ * the universe. See I18N_DESIGN.md §7.
445
+ */
446
+ type I18nConfig<L extends readonly string[]> = {
447
+ languages: L;
448
+ defaultLanguage: L[number];
449
+ /**
450
+ * Per-language fallback chains (ordered languages to try AFTER the active one
451
+ * when a translation is missing). `default` is the catch-all for languages not
452
+ * listed; absent → every language falls back to `defaultLanguage`. An explicit
453
+ * empty array opts a language OUT of any fallback (`{ de: [] }` → a missing `de`
454
+ * translation stays unresolved rather than falling back). Example:
455
+ * `{ default: ['en'], 'fr-CA': ['fr', 'en'] }`.
456
+ */
457
+ fallback?: Partial<Record<L[number] | 'default', readonly L[number][]>>;
458
+ };
459
+ declare function i18n<const L extends readonly string[]>(config: I18nConfig<L>): {
460
+ id: "i18n";
461
+ schema: SchemaModule<"cms", {}, {}, {}>;
462
+ $ERROR_CODES: {
463
+ readonly LANGUAGE_REQUIRED: {
464
+ readonly status: 400;
465
+ readonly message: "language is required -- authMiddleware must return { language } when the i18n plugin is active";
466
+ };
467
+ readonly LANGUAGE_NOT_ENABLED: {
468
+ readonly status: 400;
469
+ readonly message: "the resolved language is not one of the configured i18n languages";
470
+ };
471
+ readonly TRANSLATION_SOURCE_NOT_FOUND: {
472
+ readonly status: 404;
473
+ readonly message: "Translation source root not found in this collection / active language";
474
+ };
475
+ readonly TRANSLATION_EXISTS: {
476
+ readonly status: 409;
477
+ readonly message: "A translation in the target language already exists for this entry";
478
+ };
479
+ readonly TRANSLATION_PARENT_NOT_TRANSLATED: {
480
+ readonly status: 409;
481
+ readonly message: "The parent has no translation in the target language — translate the parent first";
482
+ };
483
+ readonly TRANSLATION_LANGUAGE_NOT_ENABLED: {
484
+ readonly status: 400;
485
+ readonly message: "targetLanguage is not one of the configured i18n languages";
486
+ };
487
+ };
488
+ collectionEndpoints: (def: CollectionWithName, ctx: CMSPluginContext) => {
489
+ /**
490
+ * Creates a sibling-language version of an existing entry, inheriting its translation key and seeding from the source's main tree (or blank).
491
+ * @param sourceRootId The root to translate from (must exist in the active language).
492
+ * @param targetLanguage The language for the new root (must be configured in the plugin).
493
+ * @param targetSlug Optional slug for the target root; defaults to the source slug if not provided.
494
+ * @param seed How to initialize the target root's draft: 'copy' (default) copies the source's main tree, 'blank' starts empty.
495
+ * @param message Optional commit message for the initial draft; defaults to 'Translation (language)'.
496
+ * @returns The new root id, draft branch id, initial commit id, target language, and inherited translation key.
497
+ * @throws TRANSLATION_LANGUAGE_NOT_ENABLED if targetLanguage is not in the configured language universe.
498
+ * @throws TRANSLATION_SOURCE_NOT_FOUND if sourceRootId does not exist in the active language/tenant.
499
+ * @throws TRANSLATION_EXISTS if a translation to targetLanguage already exists for this entry.
500
+ * @throws TRANSLATION_PARENT_NOT_TRANSLATED if the source has a parent that has no translation in the target language.
501
+ * @throws SLUG_EMPTY_NOT_ALLOWED if the target slug is empty and the collection disallows root slugs.
502
+ * @example await cmsClient.pages.createTranslation({ sourceRootId: 'root_abc', targetLanguage: 'de', seed: 'copy' })
503
+ */
504
+ createTranslation: better_call.Endpoint<`/${string}/createTranslation`, "POST", {
505
+ sourceRootId: string;
506
+ targetLanguage: string;
507
+ targetSlug?: string;
508
+ seed?: "copy" | "blank";
509
+ message?: string;
510
+ }, Record<string, any> | undefined, [], {
511
+ rootId: string;
512
+ branchId: string;
513
+ commitId: string;
514
+ language: string;
515
+ translationKey: string;
516
+ }, {
517
+ $Infer: {
518
+ body: {
519
+ sourceRootId: string;
520
+ targetLanguage: string;
521
+ targetSlug?: string;
522
+ seed?: "copy" | "blank";
523
+ message?: string;
524
+ };
525
+ };
526
+ cms: CMSEndpointMeta;
527
+ }, undefined>;
528
+ /**
529
+ * Retrieves all language variants (siblings) of a given entry, bypassing per-language read scope.
530
+ * @param rootId The root id (must exist in the active language and tenant).
531
+ * @returns The translation key (group id) and an array of all siblings with their language, root id, slug, and resolved path.
532
+ * @throws TRANSLATION_SOURCE_NOT_FOUND if rootId does not exist or has no translation key.
533
+ * @example await cmsClient.pages.listTranslations({ rootId: 'root_abc' })
534
+ */
535
+ listTranslations: better_call.Endpoint<`/${string}/listTranslations`, "GET", undefined, {
536
+ rootId: string;
537
+ }, [], {
538
+ translationKey: string;
539
+ translations: {
540
+ language: string;
541
+ rootId: string;
542
+ slug: string | null;
543
+ path: string | null;
544
+ }[];
545
+ }, {
546
+ $Infer: {
547
+ query: {
548
+ rootId: string;
549
+ };
550
+ };
551
+ cms: CMSEndpointMeta;
552
+ }, undefined>;
553
+ };
554
+ init(_ctx: CMSPluginContext): {
555
+ context: {
556
+ scopeConditions: ScopeConditionFactory[];
557
+ };
558
+ };
559
+ };
560
+
561
+ export { getI18nContext, i18n, resolveLanguage };
562
+ export type { I18nConfig, I18nContext, MultilingualMiddlewareResult };