@murumets-ee/settings 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/admin.d.mts CHANGED
@@ -16,6 +16,8 @@ interface TextSettingConfig extends BaseSettingConfig {
16
16
  maxLength?: number;
17
17
  minLength?: number;
18
18
  pattern?: RegExp;
19
+ /** Render as textarea instead of single-line input. */
20
+ multiline?: boolean;
19
21
  }
20
22
  interface NumberSettingConfig extends BaseSettingConfig {
21
23
  type: 'number';
@@ -41,6 +43,7 @@ interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {
41
43
  }
42
44
  interface MediaSettingConfig extends BaseSettingConfig {
43
45
  type: 'media';
46
+ default?: string;
44
47
  accept?: string[];
45
48
  }
46
49
  type SettingConfig = TextSettingConfig | NumberSettingConfig | BooleanSettingConfig | SelectSettingConfig | JsonSettingConfig | MediaSettingConfig;
@@ -56,17 +59,22 @@ interface SettingsDefinition<S extends Record<string, SettingConfig> = Record<st
56
59
  label?: string;
57
60
  }
58
61
  //#endregion
62
+ //#region src/admin/resources.d.ts
63
+ declare function settingsResources(definitions: SettingsDefinition[]): Array<{
64
+ resource: string;
65
+ actions: readonly string[];
66
+ }>;
67
+ //#endregion
59
68
  //#region src/admin/routes.d.ts
60
69
  /**
61
70
  * Create admin API routes for settings management.
62
71
  *
63
- * Routes:
64
- * - `GET /api/admin/settings` — Get all settings (query: `?locale=`)
65
- * - `PATCH /api/admin/settings` — Update settings (JSON body: `{ values, locale? }`)
66
- *
67
- * @param definition - The settings definition (created by defineSettings)
72
+ * Accepts a single definition (backward-compatible) or an array for
73
+ * multi-namespace support. Each namespace gets its own permission
74
+ * resource (`settings:<namespace>`).
68
75
  */
69
- declare function settingsRoutes<S extends Record<string, SettingConfig>>(definition: SettingsDefinition<S>): AdminRoute;
76
+ declare function settingsRoutes(definition: SettingsDefinition): AdminRoute;
77
+ declare function settingsRoutes(definitions: SettingsDefinition[]): AdminRoute;
70
78
  //#endregion
71
- export { settingsRoutes };
79
+ export { settingsResources, settingsRoutes };
72
80
  //# sourceMappingURL=admin.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"admin.d.mts","names":[],"sources":["../src/types.ts","../src/admin/routes.ts"],"mappings":";;;;UAgBiB,iBAAA;EAMH;EAJZ,KAAA;EAOe;EALf,WAAA;;EAEA,YAAA;AAAA;AAAA,UAGe,iBAAA,SAA0B,iBAAA;EACzC,IAAA;EACA,OAAA;EACA,SAAA;EACA,SAAA;EACA,OAAA,GAAU,MAAA;AAAA;AAAA,UAGK,mBAAA,SAA4B,iBAAA;EAC3C,IAAA;EACA,OAAA;EACA,GAAA;EACA,GAAA;EACA,OAAA;AAAA;AAAA,UAGe,oBAAA,SAA6B,iBAAA;EAC5C,IAAA;EACA,OAAA;AAAA;AAAA,UAGe,mBAAA,0DACP,iBAAA;EACR,IAAA;EACA,OAAA,EAAS,CAAA;EACT,OAAA,GAAU,CAAA;AAAA;AAAA,UAGK,iBAAA,sBAAuC,iBAAA;EACtD,IAAA;EACA,OAAA,GAAU,CAAA;EAZV;EAcA,MAAA,GAAS,OAAA,CAAQ,CAAA;AAAA;AAAA,UAGF,kBAAA,SAA2B,iBAAA;EAC1C,IAAA;EACA,MAAA;AAAA;AAAA,KAGU,aAAA,GACR,iBAAA,GACA,mBAAA,GACA,oBAAA,GACA,mBAAA,GACA,iBAAA,GACA,kBAAA;AAAA,KAgDQ,YAAA;AAAA,UAYK,kBAAA,WACL,MAAA,SAAe,aAAA,IAAiB,MAAA,SAAe,aAAA;EA/ExB;EAkFjC,SAAA;EAjFA;EAmFA,KAAA,EAAO,YAAA;EAlFG;EAoFV,MAAA,EAAQ,CAAA;EAlFC;EAoFT,KAAA;AAAA;;;;;;;AA5GF;;;;;iBCoBgB,cAAA,WAAyB,MAAA,SAAe,aAAA,EAAA,CACtD,UAAA,EAAY,kBAAA,CAAmB,CAAA,IAC9B,UAAA"}
1
+ {"version":3,"file":"admin.d.mts","names":[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-1,2 +1,2 @@
1
- function e(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function t(t,n){return e({error:t},n)}function n(n){let r=null;function i(){return r||=(async()=>{let{getApp:e}=await import(`@murumets-ee/core`),{createSettingsClient:t}=await import(`./client-factory-f4nNDWaD.mjs`);return t(n,{app:e()})})(),r}async function a(t,n){let r=await i(),a=new URL(t.url).searchParams.get(`locale`)??void 0;return e(await r.getAll(a?{locale:a}:void 0))}async function o(r,{user:a,audit:o}){let s=await i(),{values:c,locale:l}=await r.json();return!c||typeof c!=`object`?t(`Body must contain "values" object`,400):(await s.setMany(c,l?{locale:l}:void 0),o?.({action:`settings.update`,entityType:`settings`,userId:a.id,userName:a.name,changes:{fields:c},metadata:{namespace:n.namespace,...l?{locale:l}:{}}}),e({success:!0}))}return{prefix:`settings`,resource:`settings`,actions:[`view`,`update`],handlers:{GET:a,PATCH:o}}}export{n as settingsRoutes};
1
+ function e(e){return e.map(e=>({resource:`settings:${e.namespace}`,actions:[`view`,`update`]}))}const t=/^[a-z]{2}(-[A-Z]{2})?$/;function n(e){if(e&&t.test(e))return e}function r(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function i(e,t){return r({error:e},t)}function a(e){return{definition:e,clientPromise:null}}async function o(e,t){if(e.definition.scope===`user`){let{getApp:n}=await import(`@murumets-ee/core`),{createSettingsClient:r}=await import(`./client-factory-f4nNDWaD.mjs`);return r(e.definition,{app:n(),scopeId:t})}return e.clientPromise||=(async()=>{let{getApp:t}=await import(`@murumets-ee/core`),{createSettingsClient:n}=await import(`./client-factory-f4nNDWaD.mjs`);return n(e.definition,{app:t()})})(),e.clientPromise}function s(e){let t=Array.isArray(e)?e:[e],s=new Map;for(let e of t)s.set(e.namespace,a(e));async function c(e,t){let a=t.segments[0];if(!a)return i(`Missing settings namespace`,400);let c=s.get(a);if(!c)return i(`Unknown settings namespace: ${a}`,404);if(!t.checkPermission(`settings:${a}`,`view`))return i(`Forbidden: cannot view settings:${a}`,403);let l=new URL(e.url),u;if(c.definition.scope===`user`&&(u=l.searchParams.get(`scopeId`)??t.user.id,u!==t.user.id))return i(`Forbidden: cannot read other users' preferences`,403);let d=await o(c,u),f=n(l.searchParams.get(`locale`));return r(await d.getAll(f?{locale:f}:void 0))}async function l(e,t){let a=t.segments[0];if(!a)return i(`Missing settings namespace`,400);let c=s.get(a);if(!c)return i(`Unknown settings namespace: ${a}`,404);if(!t.checkPermission(`settings:${a}`,`update`))return i(`Forbidden: cannot update settings:${a}`,403);let{values:l,locale:u,scopeId:d}=await e.json(),f=n(u);if(!l||typeof l!=`object`)return i(`Body must contain "values" object`,400);let p;return c.definition.scope===`user`&&(p=d??t.user.id,p!==t.user.id)?i(`Forbidden: cannot update other users' preferences`,403):(await(await o(c,p)).setMany(l,f?{locale:f}:void 0),t.audit?.({action:`settings.update`,entityType:`settings`,userId:t.user.id,userName:t.user.name,changes:{fields:l},metadata:{namespace:a,...f?{locale:f}:{},...p?{scopeId:p}:{}}}),r({success:!0}))}return{prefix:`settings`,actions:[`view`,`update`],handlers:{GET:c,PATCH:l}}}export{e as settingsResources,s as settingsRoutes};
2
2
  //# sourceMappingURL=admin.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"admin.mjs","names":[],"sources":["../src/admin/routes.ts"],"sourcesContent":["/**\n * Settings admin routes for the centralized admin API handler.\n *\n * Provides get/update operations for typed settings.\n * All auth, CSRF, and role checks are handled by the parent handler.\n * Settings mutations require admin role (not editor).\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { settingsRoutes } from '@murumets-ee/settings/admin'\n * import { siteSettings } from '@/settings/site'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [Article],\n * routes: [settingsRoutes(siteSettings)],\n * })\n * ```\n */\n\nimport type { AdminRoute, AuditLogFn, AuthUser } from '@murumets-ee/core'\nimport type { SettingsClient } from '../client.js'\nimport type { SettingConfig, SettingsDefinition } from '../types.js'\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction json(data: unknown, status = 200) {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction errorJson(message: string, status: number) {\n return json({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create admin API routes for settings management.\n *\n * Routes:\n * - `GET /api/admin/settings` — Get all settings (query: `?locale=`)\n * - `PATCH /api/admin/settings` — Update settings (JSON body: `{ values, locale? }`)\n *\n * @param definition - The settings definition (created by defineSettings)\n */\nexport function settingsRoutes<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n): AdminRoute {\n let clientPromise: Promise<SettingsClient<S>> | null = null\n\n function getClient(): Promise<SettingsClient<S>> {\n if (!clientPromise) {\n clientPromise = (async () => {\n const { getApp } = await import('@murumets-ee/core')\n const { createSettingsClient } = await import('../client-factory.js')\n\n const app = getApp()\n return createSettingsClient(definition, { app })\n })()\n }\n return clientPromise\n }\n\n async function handleGet(\n req: Request,\n _ctx: { segments: string[]; user: AuthUser; audit?: AuditLogFn },\n ): Promise<Response> {\n const client = await getClient()\n const url = new URL(req.url)\n const locale = url.searchParams.get('locale') ?? undefined\n const values = await client.getAll(locale ? { locale } : undefined)\n return json(values)\n }\n\n async function handlePatch(\n req: Request,\n { user, audit }: { segments: string[]; user: AuthUser; audit?: AuditLogFn },\n ): Promise<Response> {\n const client = await getClient()\n const body = await req.json()\n\n const { values, locale } = body as { values: Record<string, unknown>; locale?: string }\n if (!values || typeof values !== 'object') {\n return errorJson('Body must contain \"values\" object', 400)\n }\n\n await client.setMany(\n values as Parameters<typeof client.setMany>[0],\n locale ? { locale } : undefined,\n )\n\n audit?.({\n action: 'settings.update',\n entityType: 'settings',\n userId: user.id,\n userName: user.name,\n changes: { fields: values },\n metadata: {\n namespace: definition.namespace,\n ...(locale ? { locale } : {}),\n },\n })\n\n return json({ success: true })\n }\n\n return {\n prefix: 'settings',\n resource: 'settings',\n actions: ['view', 'update'],\n handlers: {\n GET: handleGet,\n PATCH: handlePatch,\n },\n }\n}\n"],"mappings":"AA6BA,SAAS,EAAK,EAAe,EAAS,IAAK,CACzC,OAAO,IAAI,SAAS,KAAK,UAAU,EAAK,CAAE,CACxC,SACA,QAAS,CAAE,eAAgB,mBAAoB,CAChD,CAAC,CAGJ,SAAS,EAAU,EAAiB,EAAgB,CAClD,OAAO,EAAK,CAAE,MAAO,EAAS,CAAE,EAAO,CAgBzC,SAAgB,EACd,EACY,CACZ,IAAI,EAAmD,KAEvD,SAAS,GAAwC,CAU/C,MATA,CACE,KAAiB,SAAY,CAC3B,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,wBAAyB,MAAM,OAAO,iCAG9C,OAAO,EAAqB,EAAY,CAAE,IAD9B,GAAQ,CAC2B,CAAC,IAC9C,CAEC,EAGT,eAAe,EACb,EACA,EACmB,CACnB,IAAM,EAAS,MAAM,GAAW,CAE1B,EADM,IAAI,IAAI,EAAI,IAAI,CACT,aAAa,IAAI,SAAS,EAAI,IAAA,GAEjD,OAAO,EADQ,MAAM,EAAO,OAAO,EAAS,CAAE,SAAQ,CAAG,IAAA,GAAU,CAChD,CAGrB,eAAe,EACb,EACA,CAAE,OAAM,SACW,CACnB,IAAM,EAAS,MAAM,GAAW,CAG1B,CAAE,SAAQ,UAFH,MAAM,EAAI,MAAM,CAwB7B,MArBI,CAAC,GAAU,OAAO,GAAW,SACxB,EAAU,oCAAqC,IAAI,EAG5D,MAAM,EAAO,QACX,EACA,EAAS,CAAE,SAAQ,CAAG,IAAA,GACvB,CAED,IAAQ,CACN,OAAQ,kBACR,WAAY,WACZ,OAAQ,EAAK,GACb,SAAU,EAAK,KACf,QAAS,CAAE,OAAQ,EAAQ,CAC3B,SAAU,CACR,UAAW,EAAW,UACtB,GAAI,EAAS,CAAE,SAAQ,CAAG,EAAE,CAC7B,CACF,CAAC,CAEK,EAAK,CAAE,QAAS,GAAM,CAAC,EAGhC,MAAO,CACL,OAAQ,WACR,SAAU,WACV,QAAS,CAAC,OAAQ,SAAS,CAC3B,SAAU,CACR,IAAK,EACL,MAAO,EACR,CACF"}
1
+ {"version":3,"file":"admin.mjs","names":[],"sources":["../src/admin/resources.ts","../src/admin/routes.ts"],"sourcesContent":["/**\n * Derive permission resource entries from settings definitions.\n *\n * Each definition produces one resource (`settings:<namespace>`) with\n * `['view', 'update']` actions. Spread the result into your\n * `pluginResources` array so the permission catalog includes them.\n *\n * @example\n * ```typescript\n * import { settingsResources } from '@murumets-ee/settings/admin'\n * import { siteSettings } from '@/settings/site'\n * import { ticketingSettings } from '@murumets-ee/ticketing'\n *\n * export const pluginResources = [\n * ...settingsResources([siteSettings, ticketingSettings]),\n * { resource: 'storage', actions: ['view', 'create', 'update', 'delete'] },\n * ]\n * ```\n */\n\nimport type { SettingsDefinition } from '../types.js'\n\nexport function settingsResources(\n definitions: SettingsDefinition[],\n): Array<{ resource: string; actions: readonly string[] }> {\n return definitions.map((def) => ({\n resource: `settings:${def.namespace}`,\n actions: ['view', 'update'] as const,\n }))\n}\n","/**\n * Settings admin routes for the centralized admin API handler.\n *\n * Provides get/update operations for typed settings, with per-namespace\n * permission checks. Accepts a single definition (backward-compat) or\n * an array of definitions for multi-namespace support.\n *\n * URL scheme:\n * - `GET /api/admin/settings/:namespace` — Get all settings (query: `?locale=`)\n * - `PATCH /api/admin/settings/:namespace` — Update settings (JSON body: `{ values, locale?, scopeId? }`)\n *\n * Each namespace is independently gated by `checkPermission('settings:<ns>', action)`.\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { settingsRoutes } from '@murumets-ee/settings/admin'\n * import { siteSettings } from '@/settings/site'\n * import { ticketingSettings, agentPreferences } from '@murumets-ee/ticketing'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [Article],\n * routes: [settingsRoutes([siteSettings, ticketingSettings, agentPreferences])],\n * })\n * ```\n */\n\nimport type { AdminRoute, AuditLogFn, AuthUser } from '@murumets-ee/core'\nimport type { SettingsClient } from '../client.js'\nimport type { SettingConfig, SettingsDefinition } from '../types.js'\n\n// ---------------------------------------------------------------------------\n// Locale validation (same BCP47 pattern as the framework-level check)\n// ---------------------------------------------------------------------------\n\nconst LOCALE_RE = /^[a-z]{2}(-[A-Z]{2})?$/\n\nfunction validateLocale(raw: string | null | undefined): string | undefined {\n if (!raw) return undefined\n if (!LOCALE_RE.test(raw)) return undefined\n return raw\n}\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction json(data: unknown, status = 200) {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction errorJson(message: string, status: number) {\n return json({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Per-namespace entry: definition + lazy client\n// ---------------------------------------------------------------------------\n\ninterface NamespaceEntry<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {\n definition: SettingsDefinition<S>\n clientPromise: Promise<SettingsClient<S>> | null\n}\n\nfunction createEntry<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n): NamespaceEntry<S> {\n return { definition, clientPromise: null }\n}\n\nasync function getClient<S extends Record<string, SettingConfig>>(\n entry: NamespaceEntry<S>,\n scopeId?: string,\n): Promise<SettingsClient<S>> {\n // User-scoped settings need a fresh client per scopeId — no caching\n if (entry.definition.scope === 'user') {\n const { getApp } = await import('@murumets-ee/core')\n const { createSettingsClient } = await import('../client-factory.js')\n return createSettingsClient(entry.definition, { app: getApp(), scopeId })\n }\n\n if (!entry.clientPromise) {\n entry.clientPromise = (async () => {\n const { getApp } = await import('@murumets-ee/core')\n const { createSettingsClient } = await import('../client-factory.js')\n return createSettingsClient(entry.definition, { app: getApp() })\n })()\n }\n return entry.clientPromise\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create admin API routes for settings management.\n *\n * Accepts a single definition (backward-compatible) or an array for\n * multi-namespace support. Each namespace gets its own permission\n * resource (`settings:<namespace>`).\n */\nexport function settingsRoutes(definition: SettingsDefinition): AdminRoute\nexport function settingsRoutes(definitions: SettingsDefinition[]): AdminRoute\nexport function settingsRoutes(\n input: SettingsDefinition | SettingsDefinition[],\n): AdminRoute {\n const definitions = Array.isArray(input) ? input : [input]\n\n // Build lookup map: namespace → entry\n const nsMap = new Map<string, NamespaceEntry>()\n for (const def of definitions) {\n nsMap.set(def.namespace, createEntry(def))\n }\n\n // ---------- GET /api/admin/settings/:namespace ----------\n async function handleGet(\n req: Request,\n ctx: {\n segments: string[]\n user: AuthUser\n audit?: AuditLogFn\n checkPermission: (resource: string, action: string) => boolean\n },\n ): Promise<Response> {\n const namespace = ctx.segments[0]\n if (!namespace) return errorJson('Missing settings namespace', 400)\n\n const entry = nsMap.get(namespace)\n if (!entry) return errorJson(`Unknown settings namespace: ${namespace}`, 404)\n\n // Per-namespace permission check\n if (!ctx.checkPermission(`settings:${namespace}`, 'view')) {\n return errorJson(`Forbidden: cannot view settings:${namespace}`, 403)\n }\n\n // User-scoped: only allow reading own preferences\n const url = new URL(req.url)\n let scopeId: string | undefined\n if (entry.definition.scope === 'user') {\n scopeId = url.searchParams.get('scopeId') ?? ctx.user.id\n if (scopeId !== ctx.user.id) {\n return errorJson('Forbidden: cannot read other users\\' preferences', 403)\n }\n }\n\n const client = await getClient(entry, scopeId)\n const locale = validateLocale(url.searchParams.get('locale'))\n const values = await client.getAll(locale ? { locale } : undefined)\n return json(values)\n }\n\n // ---------- PATCH /api/admin/settings/:namespace ----------\n async function handlePatch(\n req: Request,\n ctx: {\n segments: string[]\n user: AuthUser\n audit?: AuditLogFn\n checkPermission: (resource: string, action: string) => boolean\n },\n ): Promise<Response> {\n const namespace = ctx.segments[0]\n if (!namespace) return errorJson('Missing settings namespace', 400)\n\n const entry = nsMap.get(namespace)\n if (!entry) return errorJson(`Unknown settings namespace: ${namespace}`, 404)\n\n // Per-namespace permission check\n if (!ctx.checkPermission(`settings:${namespace}`, 'update')) {\n return errorJson(`Forbidden: cannot update settings:${namespace}`, 403)\n }\n\n const body = await req.json()\n const { values, locale: rawLocale, scopeId } = body as {\n values: Record<string, unknown>\n locale?: string\n scopeId?: string\n }\n const locale = validateLocale(rawLocale)\n\n if (!values || typeof values !== 'object') {\n return errorJson('Body must contain \"values\" object', 400)\n }\n\n // User-scoped: enforce user isolation\n let resolvedScopeId: string | undefined\n if (entry.definition.scope === 'user') {\n resolvedScopeId = scopeId ?? ctx.user.id\n if (resolvedScopeId !== ctx.user.id) {\n return errorJson('Forbidden: cannot update other users\\' preferences', 403)\n }\n }\n\n const client = await getClient(entry, resolvedScopeId)\n await client.setMany(\n values as Parameters<typeof client.setMany>[0],\n locale ? { locale } : undefined,\n )\n\n ctx.audit?.({\n action: 'settings.update',\n entityType: 'settings',\n userId: ctx.user.id,\n userName: ctx.user.name,\n changes: { fields: values },\n metadata: {\n namespace,\n ...(locale ? { locale } : {}),\n ...(resolvedScopeId ? { scopeId: resolvedScopeId } : {}),\n },\n })\n\n return json({ success: true })\n }\n\n return {\n prefix: 'settings',\n // No `resource` — permission checks happen per-namespace inside handlers\n actions: ['view', 'update'],\n handlers: {\n GET: handleGet,\n PATCH: handlePatch,\n },\n }\n}\n"],"mappings":"AAsBA,SAAgB,EACd,EACyD,CACzD,OAAO,EAAY,IAAK,IAAS,CAC/B,SAAU,YAAY,EAAI,YAC1B,QAAS,CAAC,OAAQ,SAAS,CAC5B,EAAE,CCQL,MAAM,EAAY,yBAElB,SAAS,EAAe,EAAoD,CACrE,MACA,EAAU,KAAK,EAAI,CACxB,OAAO,EAOT,SAAS,EAAK,EAAe,EAAS,IAAK,CACzC,OAAO,IAAI,SAAS,KAAK,UAAU,EAAK,CAAE,CACxC,SACA,QAAS,CAAE,eAAgB,mBAAoB,CAChD,CAAC,CAGJ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1
- {"version":3,"file":"client-factory-f4nNDWaD.mjs","names":[],"sources":["../src/schema.ts","../src/types.ts","../src/validation.ts","../src/client.ts","../src/client-factory.ts"],"sourcesContent":["/**\n * Drizzle schema for settings tables.\n *\n * Two tables:\n * - toolkit_settings: typed key-value settings grouped by namespace and scope\n * - toolkit_view_state: schemaless user-scoped JSON blobs with optional TTL\n *\n * Usage in drizzle.config.ts:\n * ```typescript\n * import type { Config } from 'drizzle-kit'\n * export default {\n * schema: ['./generated/schema.ts', '@murumets-ee/settings/schema'],\n * // ...\n * } satisfies Config\n * ```\n */\n\nimport { jsonb, pgTable, timestamp, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\n/**\n * Typed settings table.\n *\n * Stores key-value pairs grouped by namespace and scoped\n * to global, team, or user contexts.\n *\n * scopeId uses '__global__' sentinel for global scope to avoid\n * PostgreSQL's NULL != NULL behavior in unique constraints.\n */\nexport const toolkitSettings = pgTable(\n 'toolkit_settings',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n namespace: varchar('namespace', { length: 100 }).notNull(),\n scope: varchar('scope', { length: 20 }).notNull().default('global'),\n scopeId: varchar('scope_id', { length: 100 }).notNull().default('__global__'),\n key: varchar('key', { length: 255 }).notNull(),\n locale: varchar('locale', { length: 10 }).notNull().default('_default'),\n value: jsonb('value'),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n updatedBy: uuid('updated_by'),\n },\n (table) => ({\n uniqueSetting: unique().on(\n table.namespace,\n table.scope,\n table.scopeId,\n table.key,\n table.locale,\n ),\n }),\n)\n\n/**\n * View state table.\n *\n * Stores schemaless user-scoped JSON blobs for persisting\n * UI state (table filters, column order, etc.) with optional TTL.\n */\nexport const toolkitViewState = pgTable(\n 'toolkit_view_state',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n userId: uuid('user_id').notNull(),\n viewKey: varchar('view_key', { length: 255 }).notNull(),\n state: jsonb('state').notNull(),\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => ({\n uniqueUserView: unique().on(table.userId, table.viewKey),\n }),\n)\n","/**\n * Setting configuration types and compile-time type inference.\n *\n * Design mirrors the entity field system:\n * - Config interfaces define what each setting type accepts\n * - SettingToTS maps a single config to its TypeScript type\n * - InferSettingValue adds null awareness based on `default` presence\n * - InferSettingsMap maps an entire schema to a typed record\n */\n\nimport type { ZodType } from 'zod'\n\n// ---------------------------------------------------------------\n// 1. Setting config interfaces\n// ---------------------------------------------------------------\n\nexport interface BaseSettingConfig {\n /** Human-readable label for admin UI */\n label?: string\n /** Description / help text */\n description?: string\n /** If true, this setting can have per-locale values (mirrors entity translatable pattern) */\n translatable?: boolean\n}\n\nexport interface TextSettingConfig extends BaseSettingConfig {\n type: 'text'\n default?: string\n maxLength?: number\n minLength?: number\n pattern?: RegExp\n}\n\nexport interface NumberSettingConfig extends BaseSettingConfig {\n type: 'number'\n default?: number\n min?: number\n max?: number\n integer?: boolean\n}\n\nexport interface BooleanSettingConfig extends BaseSettingConfig {\n type: 'boolean'\n default?: boolean\n}\n\nexport interface SelectSettingConfig<O extends readonly string[] = readonly string[]>\n extends BaseSettingConfig {\n type: 'select'\n options: O\n default?: O[number]\n}\n\nexport interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {\n type: 'json'\n default?: T\n /** Optional Zod schema for validation. If provided, values are validated on set. */\n schema?: ZodType<T>\n}\n\nexport interface MediaSettingConfig extends BaseSettingConfig {\n type: 'media'\n accept?: string[]\n}\n\nexport type SettingConfig =\n | TextSettingConfig\n | NumberSettingConfig\n | BooleanSettingConfig\n | SelectSettingConfig\n | JsonSettingConfig\n | MediaSettingConfig\n\n// ---------------------------------------------------------------\n// 2. Setting-to-TypeScript mapping (single setting)\n// ---------------------------------------------------------------\n\n/**\n * Maps a single SettingConfig to its TypeScript output type.\n * Each branch is a shallow comparison — no recursion.\n */\nexport type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig\n ? string\n : S extends NumberSettingConfig\n ? number\n : S extends BooleanSettingConfig\n ? boolean\n : S extends SelectSettingConfig<infer O>\n ? O[number]\n : S extends JsonSettingConfig<infer T>\n ? T\n : S extends MediaSettingConfig\n ? string\n : never\n\n// ---------------------------------------------------------------\n// 3. Null awareness: settings with defaults always return value\n// ---------------------------------------------------------------\n\n/**\n * If a setting has a `default`, get() never returns null.\n * Without a default, it returns T | null.\n */\nexport type InferSettingValue<S extends SettingConfig> = S extends { default: unknown }\n ? SettingToTS<S>\n : SettingToTS<S> | null\n\n// ---------------------------------------------------------------\n// 4. Full settings map type (what getAll() returns)\n// ---------------------------------------------------------------\n\nexport type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {\n [K in keyof Schema]: InferSettingValue<Schema[K]>\n}\n\n// ---------------------------------------------------------------\n// 5. Scope types\n// ---------------------------------------------------------------\n\nexport type SettingScope = 'global' | 'team' | 'user'\n\n/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */\nexport const GLOBAL_SCOPE_ID = '__global__'\n\n/** Sentinel value for locale column when no locale is specified (base/default value) */\nexport const DEFAULT_LOCALE = '_default'\n\n// ---------------------------------------------------------------\n// 6. Settings definition (returned by defineSettings)\n// ---------------------------------------------------------------\n\nexport interface SettingsDefinition<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n /** Unique namespace for this settings group */\n namespace: string\n /** Default scope for these settings */\n scope: SettingScope\n /** Setting schema (the shape) */\n schema: S\n /** Human-readable label for admin UI */\n label?: string\n}\n","/**\n * Generate Zod validation schemas from setting config definitions.\n * Validates values before writing to the database.\n */\n\nimport { z } from 'zod'\nimport type { SettingConfig, SettingsDefinition } from './types.js'\n\n/**\n * Convert a single setting config to a Zod schema.\n */\nexport function settingToZod(config: SettingConfig): z.ZodType {\n switch (config.type) {\n case 'text': {\n let schema: z.ZodString = z.string()\n if (config.maxLength) schema = schema.max(config.maxLength)\n if (config.minLength) schema = schema.min(config.minLength)\n if (config.pattern) schema = schema.regex(config.pattern)\n return schema\n }\n\n case 'number': {\n let schema: z.ZodNumber = z.number()\n if (config.integer) schema = schema.int()\n if (config.min !== undefined) schema = schema.min(config.min)\n if (config.max !== undefined) schema = schema.max(config.max)\n return schema\n }\n\n case 'boolean':\n return z.boolean()\n\n case 'select':\n return z.enum(config.options as [string, ...string[]])\n\n case 'json':\n return config.schema ?? z.unknown()\n\n case 'media':\n return z.string().uuid()\n\n default:\n return z.unknown()\n }\n}\n\n/**\n * Generate a validation map for all settings in a definition.\n * Returns a Record<key, ZodType> for validating individual set() calls.\n *\n * Settings without a default are nullable (matching InferSettingValue),\n * so their validators accept null.\n */\nexport function generateSettingValidators(\n definition: SettingsDefinition,\n): Record<string, z.ZodType> {\n const validators: Record<string, z.ZodType> = {}\n for (const [key, config] of Object.entries(definition.schema)) {\n let schema = settingToZod(config)\n const hasDefault = 'default' in config && config.default !== undefined\n if (!hasDefault) {\n schema = schema.nullable()\n }\n validators[key] = schema\n }\n return validators\n}\n","/**\n * SettingsClient — typed CRUD for key-value settings.\n *\n * Server-only. Uses read-write DB connection.\n * Validates values against the setting schema on set().\n *\n * Supports per-locale values for settings marked `translatable: true`.\n * Non-translatable settings always use the `__default__` locale.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n *\n * // Default locale\n * const name = await settings.get('siteName') // string (has default)\n *\n * // Locale-specific (only for translatable settings)\n * const nameEt = await settings.get('siteName', { locale: 'et' })\n *\n * await settings.set('siteName', 'Mänguväljak', { locale: 'et' })\n * ```\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { and, eq, or } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettings } from './schema.js'\nimport type {\n InferSettingsMap,\n InferSettingValue,\n SettingConfig,\n SettingScope,\n SettingsDefinition,\n} from './types.js'\nimport { DEFAULT_LOCALE, GLOBAL_SCOPE_ID } from './types.js'\nimport { generateSettingValidators } from './validation.js'\n\nexport interface SettingsClientConfig {\n /** Database client (read-write) */\n db: PostgresJsDatabase\n /** Logger instance */\n logger?: Logger\n /** Override scope (defaults to definition's scope) */\n scope?: SettingScope\n /** Scope ID (required for team/user scope, defaults to '__global__' for global) */\n scopeId?: string\n}\n\nexport interface LocaleOption {\n /** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */\n locale?: string\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private db: PostgresJsDatabase\n private logger?: Logger\n private scope: SettingScope\n private scopeId: string\n private validators: Record<string, ZodType>\n\n constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig) {\n if (typeof window !== 'undefined') {\n throw new Error('SettingsClient cannot be used in browser code.')\n }\n\n this.definition = definition\n this.db = config.db\n this.logger = config.logger\n this.scope = config.scope ?? definition.scope\n this.scopeId = config.scopeId ?? GLOBAL_SCOPE_ID\n\n if ((this.scope === 'team' || this.scope === 'user') && !config.scopeId) {\n throw new Error(\n `scopeId is required for ${this.scope}-scoped settings (namespace: ${definition.namespace})`,\n )\n }\n\n this.validators = generateSettingValidators(definition)\n }\n\n /**\n * Get a single setting value.\n *\n * For translatable settings with a locale, tries locale-specific value first,\n * then falls back to the default value, then the schema default, then null.\n */\n async get<K extends string & keyof S>(\n key: K,\n options?: LocaleOption,\n ): Promise<InferSettingValue<S[K]>> {\n const config = this.definition.schema[key]\n const locale = config?.translatable && options?.locale ? options.locale : null\n\n this.logger?.debug({ namespace: this.definition.namespace, key, locale }, 'Getting setting')\n\n if (locale) {\n // Fetch both locale-specific and default in one query\n const rows = await this.db\n .select({ locale: toolkitSettings.locale, value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n or(eq(toolkitSettings.locale, locale), eq(toolkitSettings.locale, DEFAULT_LOCALE)),\n ),\n )\n\n // Prefer locale-specific, fall back to default\n const localeRow = rows.find((r) => r.locale === locale)\n const defaultRow = rows.find((r) => r.locale === DEFAULT_LOCALE)\n const row = localeRow ?? defaultRow\n\n if (row && row.value !== undefined && row.value !== null) {\n return row.value as InferSettingValue<S[K]>\n }\n } else {\n const rows = await this.db\n .select({ value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(this.whereClause(key))\n .limit(1)\n\n if (rows.length > 0 && rows[0].value !== undefined && rows[0].value !== null) {\n return rows[0].value as InferSettingValue<S[K]>\n }\n }\n\n if (config && 'default' in config && config.default !== undefined) {\n return config.default as InferSettingValue<S[K]>\n }\n\n return null as InferSettingValue<S[K]>\n }\n\n /**\n * Get all settings for this namespace/scope as a typed object.\n * Missing values are filled from schema defaults.\n *\n * When locale is specified, translatable settings prefer the locale-specific\n * value over the default value.\n */\n async getAll(options?: LocaleOption): Promise<InferSettingsMap<S>> {\n const locale = options?.locale ?? null\n\n this.logger?.debug({ namespace: this.definition.namespace, locale }, 'Getting all settings')\n\n let rows: { key: string; locale: string; value: unknown }[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n or(eq(toolkitSettings.locale, DEFAULT_LOCALE), eq(toolkitSettings.locale, locale)),\n ),\n )\n } else {\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(and(...this.baseWhere(), eq(toolkitSettings.locale, DEFAULT_LOCALE)))\n }\n\n // Build lookup: key → { default: value, locale: value }\n const stored = new Map<string, { default?: unknown; locale?: unknown }>()\n for (const row of rows) {\n const entry = stored.get(row.key) ?? {}\n if (row.locale === DEFAULT_LOCALE) {\n entry.default = row.value\n } else {\n entry.locale = row.value\n }\n stored.set(row.key, entry)\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, config] of Object.entries(this.definition.schema)) {\n const entry = stored.get(key)\n\n // For translatable settings with locale, prefer locale-specific value\n let value: unknown\n if (config.translatable && locale && entry?.locale !== undefined && entry?.locale !== null) {\n value = entry.locale\n } else if (entry?.default !== undefined && entry?.default !== null) {\n value = entry.default\n }\n\n if (value !== undefined) {\n result[key] = value\n } else if ('default' in config && config.default !== undefined) {\n result[key] = config.default\n } else {\n result[key] = null\n }\n }\n\n return result as InferSettingsMap<S>\n }\n\n /**\n * Set a single setting value.\n * Validates against the schema before writing.\n *\n * Pass `{ locale }` to write a locale-specific value (only for translatable settings).\n */\n async set<K extends string & keyof S>(\n key: K,\n value: InferSettingValue<S[K]>,\n options?: LocaleOption,\n ): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Setting value')\n\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n\n const validator = this.validators[key]\n if (validator) {\n validator.parse(value)\n }\n\n await this.upsert(key, value as unknown, locale)\n }\n\n /**\n * Set multiple settings at once (validated individually).\n * Writes in a transaction — all or nothing.\n *\n * Pass `{ locale }` to write locale-specific values for translatable settings.\n * Non-translatable settings in the values will always write to the default locale.\n */\n async setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void> {\n this.logger?.info(\n { namespace: this.definition.namespace, keys: Object.keys(values), locale: options?.locale },\n 'Setting multiple values',\n )\n\n // Validate all first (fail fast)\n for (const [key, value] of Object.entries(values)) {\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n const validator = this.validators[key]\n if (validator && value !== undefined) {\n validator.parse(value)\n }\n }\n\n await this.db.transaction(async (tx) => {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n const locale = this.resolveLocale(key, options)\n await tx\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value: value as unknown,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value: value as unknown,\n updatedAt: new Date(),\n },\n })\n }\n })\n }\n\n /**\n * Delete a setting (resets to default on next get).\n * Pass `{ locale }` to delete only the locale-specific value.\n */\n async delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Deleting setting')\n\n await this.db.delete(toolkitSettings).where(this.whereClause(key, locale))\n }\n\n /**\n * Check if a setting has a stored value (not relying on default).\n */\n async has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean> {\n const locale = this.resolveLocale(key, options)\n\n const rows = await this.db\n .select({ key: toolkitSettings.key })\n .from(toolkitSettings)\n .where(this.whereClause(key, locale))\n .limit(1)\n\n return rows.length > 0\n }\n\n // ---------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------\n\n /**\n * Resolve which locale to use for a given key.\n * Non-translatable settings always use DEFAULT_LOCALE.\n * Translatable settings use the requested locale or DEFAULT_LOCALE.\n */\n private resolveLocale(key: string, options?: LocaleOption): string {\n const config = this.definition.schema[key as keyof S] as SettingConfig | undefined\n if (config?.translatable && options?.locale) {\n return options.locale\n }\n return DEFAULT_LOCALE\n }\n\n /** Base where conditions: namespace + scope + scopeId */\n private baseWhere() {\n return [\n eq(toolkitSettings.namespace, this.definition.namespace),\n eq(toolkitSettings.scope, this.scope),\n eq(toolkitSettings.scopeId, this.scopeId),\n ] as const\n }\n\n /** Full where clause for a specific key + locale */\n private whereClause(key: string, locale: string = DEFAULT_LOCALE) {\n return and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n eq(toolkitSettings.locale, locale),\n )!\n }\n\n /** Upsert a single setting row */\n private async upsert(key: string, value: unknown, locale: string) {\n await this.db\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value,\n updatedAt: new Date(),\n },\n })\n }\n}\n","/**\n * Factory function for creating typed SettingsClient instances.\n *\n * Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { SettingsClient } from './client.js'\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport interface CreateSettingsClientOptions {\n /** Override the toolkit app (defaults to getApp()) */\n app?: ToolkitApp\n /** Override scope from definition */\n scope?: SettingScope\n /** Scope ID for team/user scoped settings */\n scopeId?: string\n}\n\n/**\n * Create a typed SettingsClient.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n * const name = await settings.get('siteName') // string\n * ```\n */\nexport function createSettingsClient<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n options?: CreateSettingsClientOptions,\n): SettingsClient<S> {\n const app = options?.app ?? getApp()\n\n return new SettingsClient(definition, {\n db: app.db.readWrite,\n logger: app.logger.child({ settings: definition.namespace }),\n scope: options?.scope,\n scopeId: options?.scopeId,\n })\n}\n"],"mappings":"gOA4BA,MAAa,EAAkB,EAC7B,mBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,UAAW,EAAQ,YAAa,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC1D,MAAO,EAAQ,QAAS,CAAE,OAAQ,GAAI,CAAC,CAAC,S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B,CACrB,MAAM,KAAK,YAAY,EAAK,EAAO,CAAC,CACpC,MAAM,EAAE,EAEC,OAAS,EAYvB,cAAsB,EAAa,EAAgC,CAKjE,OAJe,KAAK,WAAW,OAAO,IAC1B,cAAgB,GAAS,OAC5B,EAAQ,OAEV,EAIT,WAAoB,CAClB,MAAO,CACL,EAAG,EAAgB,UAAW,KAAK,WAAW,UAAU,CACxD,EAAG,EAAgB,MAAO,KAAK,MAAM,CACrC,EAAG,EAAgB,QAAS,KAAK,QAAQ,CAC1C,CAIH,YAAoB,EAAa,EAAiB,EAAgB,CAChE,OAAO,EACL,GAAG,KAAK,WAAW,CACnB,EAAG,EAAgB,IAAK,EAAI,CAC5B,EAAG,EAAgB,OAAQ,EAAO,CACnC,CAIH,MAAc,OAAO,EAAa,EAAgB,EAAgB,CAChE,MAAM,KAAK,GACR,OAAO,EAAgB,CACvB,OAAO,CACN,UAAW,KAAK,WAAW,UAC3B,MAAO,KAAK,MACZ,QAAS,KAAK,QACd,MACA,SACA,QACA,UAAW,IAAI,KAChB,CAAC,CACD,mBAAmB,CAClB,OAAQ,CACN,EAAgB,UAChB,EAAgB,MAChB,EAAgB,QAChB,EAAgB,IAChB,EAAgB,OACjB,CACD,IAAK,CACH,QACA,UAAW,IAAI,KAChB,CACF,CAAC,GCpWR,SAAgB,EACd,EACA,EACmB,CACnB,IAAM,EAAM,GAAS,KAAO,GAAQ,CAEpC,OAAO,IAAI,EAAe,EAAY,CACpC,GAAI,EAAI,GAAG,UACX,OAAQ,EAAI,OAAO,MAAM,CAAE,SAAU,EAAW,UAAW,CAAC,CAC5D,MAAO,GAAS,MAChB,QAAS,GAAS,QACnB,CAAC"}
1
+ {"version":3,"file":"client-factory-f4nNDWaD.mjs","names":[],"sources":["../src/schema.ts","../src/types.ts","../src/validation.ts","../src/client.ts","../src/client-factory.ts"],"sourcesContent":["/**\n * Drizzle schema for settings tables.\n *\n * Two tables:\n * - toolkit_settings: typed key-value settings grouped by namespace and scope\n * - toolkit_view_state: schemaless user-scoped JSON blobs with optional TTL\n *\n * These tables are registered for migration discovery via the `settings()`\n * plugin's `tables` field. `lumi migrate` picks them up automatically.\n */\n\nimport { jsonb, pgTable, timestamp, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\n/**\n * Typed settings table.\n *\n * Stores key-value pairs grouped by namespace and scoped\n * to global, team, or user contexts.\n *\n * scopeId uses '__global__' sentinel for global scope to avoid\n * PostgreSQL's NULL != NULL behavior in unique constraints.\n */\nexport const toolkitSettings = pgTable(\n 'toolkit_settings',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n namespace: varchar('namespace', { length: 100 }).notNull(),\n scope: varchar('scope', { length: 20 }).notNull().default('global'),\n scopeId: varchar('scope_id', { length: 100 }).notNull().default('__global__'),\n key: varchar('key', { length: 255 }).notNull(),\n locale: varchar('locale', { length: 10 }).notNull().default('_default'),\n value: jsonb('value'),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n updatedBy: uuid('updated_by'),\n },\n (table) => ({\n uniqueSetting: unique().on(\n table.namespace,\n table.scope,\n table.scopeId,\n table.key,\n table.locale,\n ),\n }),\n)\n\n/**\n * View state table.\n *\n * Stores schemaless user-scoped JSON blobs for persisting\n * UI state (table filters, column order, etc.) with optional TTL.\n */\nexport const toolkitViewState = pgTable(\n 'toolkit_view_state',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n userId: uuid('user_id').notNull(),\n viewKey: varchar('view_key', { length: 255 }).notNull(),\n state: jsonb('state').notNull(),\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => ({\n uniqueUserView: unique().on(table.userId, table.viewKey),\n }),\n)\n","/**\n * Setting configuration types and compile-time type inference.\n *\n * Design mirrors the entity field system:\n * - Config interfaces define what each setting type accepts\n * - SettingToTS maps a single config to its TypeScript type\n * - InferSettingValue adds null awareness based on `default` presence\n * - InferSettingsMap maps an entire schema to a typed record\n */\n\nimport type { ZodType } from 'zod'\n\n// ---------------------------------------------------------------\n// 1. Setting config interfaces\n// ---------------------------------------------------------------\n\nexport interface BaseSettingConfig {\n /** Human-readable label for admin UI */\n label?: string\n /** Description / help text */\n description?: string\n /** If true, this setting can have per-locale values (mirrors entity translatable pattern) */\n translatable?: boolean\n}\n\nexport interface TextSettingConfig extends BaseSettingConfig {\n type: 'text'\n default?: string\n maxLength?: number\n minLength?: number\n pattern?: RegExp\n /** Render as textarea instead of single-line input. */\n multiline?: boolean\n}\n\nexport interface NumberSettingConfig extends BaseSettingConfig {\n type: 'number'\n default?: number\n min?: number\n max?: number\n integer?: boolean\n}\n\nexport interface BooleanSettingConfig extends BaseSettingConfig {\n type: 'boolean'\n default?: boolean\n}\n\nexport interface SelectSettingConfig<O extends readonly string[] = readonly string[]>\n extends BaseSettingConfig {\n type: 'select'\n options: O\n default?: O[number]\n}\n\nexport interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {\n type: 'json'\n default?: T\n /** Optional Zod schema for validation. If provided, values are validated on set. */\n schema?: ZodType<T>\n}\n\nexport interface MediaSettingConfig extends BaseSettingConfig {\n type: 'media'\n default?: string\n accept?: string[]\n}\n\nexport type SettingConfig =\n | TextSettingConfig\n | NumberSettingConfig\n | BooleanSettingConfig\n | SelectSettingConfig\n | JsonSettingConfig\n | MediaSettingConfig\n\n// ---------------------------------------------------------------\n// 2. Setting-to-TypeScript mapping (single setting)\n// ---------------------------------------------------------------\n\n/**\n * Maps a single SettingConfig to its TypeScript output type.\n * Each branch is a shallow comparison — no recursion.\n */\nexport type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig\n ? string\n : S extends NumberSettingConfig\n ? number\n : S extends BooleanSettingConfig\n ? boolean\n : S extends SelectSettingConfig<infer O>\n ? O[number]\n : S extends JsonSettingConfig<infer T>\n ? T\n : S extends MediaSettingConfig\n ? string\n : never\n\n// ---------------------------------------------------------------\n// 3. Null awareness: settings with defaults always return value\n// ---------------------------------------------------------------\n\n/**\n * If a setting has a `default`, get() never returns null.\n * Without a default, it returns T | null.\n */\nexport type InferSettingValue<S extends SettingConfig> = S extends { default: unknown }\n ? SettingToTS<S>\n : SettingToTS<S> | null\n\n// ---------------------------------------------------------------\n// 4. Full settings map type (what getAll() returns)\n// ---------------------------------------------------------------\n\nexport type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {\n [K in keyof Schema]: InferSettingValue<Schema[K]>\n}\n\n// ---------------------------------------------------------------\n// 5. Scope types\n// ---------------------------------------------------------------\n\nexport type SettingScope = 'global' | 'team' | 'user'\n\n/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */\nexport const GLOBAL_SCOPE_ID = '__global__'\n\n/** Sentinel value for locale column when no locale is specified (base/default value) */\nexport const DEFAULT_LOCALE = '_default'\n\n// ---------------------------------------------------------------\n// 6. Settings definition (returned by defineSettings)\n// ---------------------------------------------------------------\n\nexport interface SettingsDefinition<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n /** Unique namespace for this settings group */\n namespace: string\n /** Default scope for these settings */\n scope: SettingScope\n /** Setting schema (the shape) */\n schema: S\n /** Human-readable label for admin UI */\n label?: string\n}\n","/**\n * Generate Zod validation schemas from setting config definitions.\n * Validates values before writing to the database.\n */\n\nimport { z } from 'zod'\nimport type { SettingConfig, SettingsDefinition } from './types.js'\n\n/**\n * Convert a single setting config to a Zod schema.\n */\nexport function settingToZod(config: SettingConfig): z.ZodType {\n switch (config.type) {\n case 'text': {\n let schema: z.ZodString = z.string()\n if (config.maxLength) schema = schema.max(config.maxLength)\n if (config.minLength) schema = schema.min(config.minLength)\n if (config.pattern) schema = schema.regex(config.pattern)\n return schema\n }\n\n case 'number': {\n let schema: z.ZodNumber = z.number()\n if (config.integer) schema = schema.int()\n if (config.min !== undefined) schema = schema.min(config.min)\n if (config.max !== undefined) schema = schema.max(config.max)\n return schema\n }\n\n case 'boolean':\n return z.boolean()\n\n case 'select':\n return z.enum(config.options as [string, ...string[]])\n\n case 'json':\n return config.schema ?? z.unknown()\n\n case 'media':\n return z.string().uuid()\n\n default:\n return z.unknown()\n }\n}\n\n/**\n * Generate a validation map for all settings in a definition.\n * Returns a Record<key, ZodType> for validating individual set() calls.\n *\n * Settings without a default are nullable (matching InferSettingValue),\n * so their validators accept null.\n */\nexport function generateSettingValidators(\n definition: SettingsDefinition,\n): Record<string, z.ZodType> {\n const validators: Record<string, z.ZodType> = {}\n for (const [key, config] of Object.entries(definition.schema)) {\n let schema = settingToZod(config)\n const hasDefault = 'default' in config && config.default !== undefined\n if (!hasDefault) {\n schema = schema.nullable()\n }\n validators[key] = schema\n }\n return validators\n}\n","/**\n * SettingsClient — typed CRUD for key-value settings.\n *\n * Server-only. Uses read-write DB connection.\n * Validates values against the setting schema on set().\n *\n * Supports per-locale values for settings marked `translatable: true`.\n * Non-translatable settings always use the `__default__` locale.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n *\n * // Default locale\n * const name = await settings.get('siteName') // string (has default)\n *\n * // Locale-specific (only for translatable settings)\n * const nameEt = await settings.get('siteName', { locale: 'et' })\n *\n * await settings.set('siteName', 'Mänguväljak', { locale: 'et' })\n * ```\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { and, eq, or } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettings } from './schema.js'\nimport type {\n InferSettingsMap,\n InferSettingValue,\n SettingConfig,\n SettingScope,\n SettingsDefinition,\n} from './types.js'\nimport { DEFAULT_LOCALE, GLOBAL_SCOPE_ID } from './types.js'\nimport { generateSettingValidators } from './validation.js'\n\nexport interface SettingsClientConfig {\n /** Database client (read-write) */\n db: PostgresJsDatabase\n /** Logger instance */\n logger?: Logger\n /** Override scope (defaults to definition's scope) */\n scope?: SettingScope\n /** Scope ID (required for team/user scope, defaults to '__global__' for global) */\n scopeId?: string\n}\n\nexport interface LocaleOption {\n /** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */\n locale?: string\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private db: PostgresJsDatabase\n private logger?: Logger\n private scope: SettingScope\n private scopeId: string\n private validators: Record<string, ZodType>\n\n constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig) {\n if (typeof window !== 'undefined') {\n throw new Error('SettingsClient cannot be used in browser code.')\n }\n\n this.definition = definition\n this.db = config.db\n this.logger = config.logger\n this.scope = config.scope ?? definition.scope\n this.scopeId = config.scopeId ?? GLOBAL_SCOPE_ID\n\n if ((this.scope === 'team' || this.scope === 'user') && !config.scopeId) {\n throw new Error(\n `scopeId is required for ${this.scope}-scoped settings (namespace: ${definition.namespace})`,\n )\n }\n\n this.validators = generateSettingValidators(definition)\n }\n\n /**\n * Get a single setting value.\n *\n * For translatable settings with a locale, tries locale-specific value first,\n * then falls back to the default value, then the schema default, then null.\n */\n async get<K extends string & keyof S>(\n key: K,\n options?: LocaleOption,\n ): Promise<InferSettingValue<S[K]>> {\n const config = this.definition.schema[key]\n const locale = config?.translatable && options?.locale ? options.locale : null\n\n this.logger?.debug({ namespace: this.definition.namespace, key, locale }, 'Getting setting')\n\n if (locale) {\n // Fetch both locale-specific and default in one query\n const rows = await this.db\n .select({ locale: toolkitSettings.locale, value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n or(eq(toolkitSettings.locale, locale), eq(toolkitSettings.locale, DEFAULT_LOCALE)),\n ),\n )\n\n // Prefer locale-specific, fall back to default\n const localeRow = rows.find((r) => r.locale === locale)\n const defaultRow = rows.find((r) => r.locale === DEFAULT_LOCALE)\n const row = localeRow ?? defaultRow\n\n if (row && row.value !== undefined && row.value !== null) {\n return row.value as InferSettingValue<S[K]>\n }\n } else {\n const rows = await this.db\n .select({ value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(this.whereClause(key))\n .limit(1)\n\n if (rows.length > 0 && rows[0].value !== undefined && rows[0].value !== null) {\n return rows[0].value as InferSettingValue<S[K]>\n }\n }\n\n if (config && 'default' in config && config.default !== undefined) {\n return config.default as InferSettingValue<S[K]>\n }\n\n return null as InferSettingValue<S[K]>\n }\n\n /**\n * Get all settings for this namespace/scope as a typed object.\n * Missing values are filled from schema defaults.\n *\n * When locale is specified, translatable settings prefer the locale-specific\n * value over the default value.\n */\n async getAll(options?: LocaleOption): Promise<InferSettingsMap<S>> {\n const locale = options?.locale ?? null\n\n this.logger?.debug({ namespace: this.definition.namespace, locale }, 'Getting all settings')\n\n let rows: { key: string; locale: string; value: unknown }[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n or(eq(toolkitSettings.locale, DEFAULT_LOCALE), eq(toolkitSettings.locale, locale)),\n ),\n )\n } else {\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(and(...this.baseWhere(), eq(toolkitSettings.locale, DEFAULT_LOCALE)))\n }\n\n // Build lookup: key → { default: value, locale: value }\n const stored = new Map<string, { default?: unknown; locale?: unknown }>()\n for (const row of rows) {\n const entry = stored.get(row.key) ?? {}\n if (row.locale === DEFAULT_LOCALE) {\n entry.default = row.value\n } else {\n entry.locale = row.value\n }\n stored.set(row.key, entry)\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, config] of Object.entries(this.definition.schema)) {\n const entry = stored.get(key)\n\n // For translatable settings with locale, prefer locale-specific value\n let value: unknown\n if (config.translatable && locale && entry?.locale !== undefined && entry?.locale !== null) {\n value = entry.locale\n } else if (entry?.default !== undefined && entry?.default !== null) {\n value = entry.default\n }\n\n if (value !== undefined) {\n result[key] = value\n } else if ('default' in config && config.default !== undefined) {\n result[key] = config.default\n } else {\n result[key] = null\n }\n }\n\n return result as InferSettingsMap<S>\n }\n\n /**\n * Set a single setting value.\n * Validates against the schema before writing.\n *\n * Pass `{ locale }` to write a locale-specific value (only for translatable settings).\n */\n async set<K extends string & keyof S>(\n key: K,\n value: InferSettingValue<S[K]>,\n options?: LocaleOption,\n ): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Setting value')\n\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n\n const validator = this.validators[key]\n if (validator) {\n validator.parse(value)\n }\n\n await this.upsert(key, value as unknown, locale)\n }\n\n /**\n * Set multiple settings at once (validated individually).\n * Writes in a transaction — all or nothing.\n *\n * Pass `{ locale }` to write locale-specific values for translatable settings.\n * Non-translatable settings in the values will always write to the default locale.\n */\n async setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void> {\n this.logger?.info(\n { namespace: this.definition.namespace, keys: Object.keys(values), locale: options?.locale },\n 'Setting multiple values',\n )\n\n // Validate all first (fail fast)\n for (const [key, value] of Object.entries(values)) {\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n const validator = this.validators[key]\n if (validator && value !== undefined) {\n validator.parse(value)\n }\n }\n\n await this.db.transaction(async (tx) => {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n const locale = this.resolveLocale(key, options)\n await tx\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value: value as unknown,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value: value as unknown,\n updatedAt: new Date(),\n },\n })\n }\n })\n }\n\n /**\n * Delete a setting (resets to default on next get).\n * Pass `{ locale }` to delete only the locale-specific value.\n */\n async delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Deleting setting')\n\n await this.db.delete(toolkitSettings).where(this.whereClause(key, locale))\n }\n\n /**\n * Check if a setting has a stored value (not relying on default).\n */\n async has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean> {\n const locale = this.resolveLocale(key, options)\n\n const rows = await this.db\n .select({ key: toolkitSettings.key })\n .from(toolkitSettings)\n .where(this.whereClause(key, locale))\n .limit(1)\n\n return rows.length > 0\n }\n\n // ---------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------\n\n /**\n * Resolve which locale to use for a given key.\n * Non-translatable settings always use DEFAULT_LOCALE.\n * Translatable settings use the requested locale or DEFAULT_LOCALE.\n */\n private resolveLocale(key: string, options?: LocaleOption): string {\n const config = this.definition.schema[key as keyof S] as SettingConfig | undefined\n if (config?.translatable && options?.locale) {\n return options.locale\n }\n return DEFAULT_LOCALE\n }\n\n /** Base where conditions: namespace + scope + scopeId */\n private baseWhere() {\n return [\n eq(toolkitSettings.namespace, this.definition.namespace),\n eq(toolkitSettings.scope, this.scope),\n eq(toolkitSettings.scopeId, this.scopeId),\n ] as const\n }\n\n /** Full where clause for a specific key + locale */\n private whereClause(key: string, locale: string = DEFAULT_LOCALE) {\n return and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n eq(toolkitSettings.locale, locale),\n )!\n }\n\n /** Upsert a single setting row */\n private async upsert(key: string, value: unknown, locale: string) {\n await this.db\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value,\n updatedAt: new Date(),\n },\n })\n }\n}\n","/**\n * Factory function for creating typed SettingsClient instances.\n *\n * Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { SettingsClient } from './client.js'\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport interface CreateSettingsClientOptions {\n /** Override the toolkit app (defaults to getApp()) */\n app?: ToolkitApp\n /** Override scope from definition */\n scope?: SettingScope\n /** Scope ID for team/user scoped settings */\n scopeId?: string\n}\n\n/**\n * Create a typed SettingsClient.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n * const name = await settings.get('siteName') // string\n * ```\n */\nexport function createSettingsClient<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n options?: CreateSettingsClientOptions,\n): SettingsClient<S> {\n const app = options?.app ?? getApp()\n\n return new SettingsClient(definition, {\n db: app.db.readWrite,\n logger: app.logger.child({ settings: definition.namespace }),\n scope: options?.scope,\n scopeId: options?.scopeId,\n })\n}\n"],"mappings":"gOAsBA,MAAa,EAAkB,EAC7B,mBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,UAAW,EAAQ,YAAa,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC1D,MAAO,EAAQ,QAAS,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,SAAS,CACnE,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAAC,QAAQ,aAAa,CAC7E,IAAK,EAAQ,MAAO,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC9C,OAAQ,EAAQ,SAAU,CAAE,OAAQ,GAAI,CA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UAAW,KAAK,WAAW,UAAU,CACxD,EAAG,EAAgB,MAAO,KAAK,MAAM,CACrC,EAAG,EAAgB,QAAS,KAAK,QAAQ,CAC1C,CAIH,YAAoB,EAAa,EAAiB,EAAgB,CAChE,OAAO,EACL,GAAG,KAAK,WAAW,CACnB,EAAG,EAAgB,IAAK,EAAI,CAC5B,EAAG,EAAgB,OAAQ,EAAO,CACnC,CAIH,MAAc,OAAO,EAAa,EAAgB,EAAgB,CAChE,MAAM,KAAK,GACR,OAAO,EAAgB,CACvB,OAAO,CACN,UAAW,KAAK,WAAW,UAC3B,MAAO,KAAK,MACZ,QAAS,KAAK,QACd,MACA,SACA,QACA,UAAW,IAAI,KAChB,CAAC,CACD,mBAAmB,CAClB,OAAQ,CACN,EAAgB,UAChB,EAAgB,MAChB,EAAgB,QAChB,EAAgB,IAChB,EAAgB,OACjB,CACD,IAAK,CACH,QACA,UAAW,IAAI,KAChB,CACF,CAAC,GCpWR,SAAgB,EACd,EACA,EACmB,CACnB,IAAM,EAAM,GAAS,KAAO,GAAQ,CAEpC,OAAO,IAAI,EAAe,EAAY,CACpC,GAAI,EAAI,GAAG,UACX,OAAQ,EAAI,OAAO,MAAM,CAAE,SAAU,EAAW,UAAW,CAAC,CAC5D,MAAO,GAAS,MAChB,QAAS,GAAS,QACnB,CAAC"}
package/dist/index.d.mts CHANGED
@@ -17,6 +17,8 @@ interface TextSettingConfig extends BaseSettingConfig {
17
17
  maxLength?: number;
18
18
  minLength?: number;
19
19
  pattern?: RegExp;
20
+ /** Render as textarea instead of single-line input. */
21
+ multiline?: boolean;
20
22
  }
21
23
  interface NumberSettingConfig extends BaseSettingConfig {
22
24
  type: 'number';
@@ -42,6 +44,7 @@ interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {
42
44
  }
43
45
  interface MediaSettingConfig extends BaseSettingConfig {
44
46
  type: 'media';
47
+ default?: string;
45
48
  accept?: string[];
46
49
  }
47
50
  type SettingConfig = TextSettingConfig | NumberSettingConfig | BooleanSettingConfig | SelectSettingConfig | JsonSettingConfig | MediaSettingConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/builders.ts","../src/client.ts","../src/client-factory.ts","../src/define-settings.ts"],"mappings":";;;;;UAgBiB,iBAAA;EAIf;EAFA,KAAA;EAIY;EAFZ,WAAA;EAKe;EAHf,YAAA;AAAA;AAAA,UAGe,iBAAA,SAA0B,iBAAA;EACzC,IAAA;EACA,OAAA;EACA,SAAA;EACA,SAAA;EACA,OAAA,GAAU,MAAA;AAAA;AAAA,UAGK,mBAAA,SAA4B,iBAAA;EAC3C,IAAA;EACA,OAAA;EACA,GAAA;EACA,GAAA;EACA,OAAA;AAAA;AAAA,UAGe,oBAAA,SAA6B,iBAAA;EAC5C,IAAA;EACA,OAAA;AAAA;AAAA,UAGe,mBAAA,0DACP,iBAAA;EACR,IAAA;EACA,OAAA,EAAS,CAAA;EACT,OAAA,GAAU,CAAA;AAAA;AAAA,UAGK,iBAAA,sBAAuC,iBAAA;EACtD,IAAA;EACA,OAAA,GAAU,CAAA;EAdkC;EAgB5C,MAAA,GAAS,OAAA,CAAQ,CAAA;AAAA;AAAA,UAGF,kBAAA,SAA2B,iBAAA;EAC1C,IAAA;EACA,MAAA;AAAA;AAAA,KAGU,aAAA,GACR,iBAAA,GACA,mBAAA,GACA,oBAAA,GACA,mBAAA,GACA,iBAAA,GACA,kBAAA;;;;;KAUQ,WAAA,WAAsB,aAAA,IAAiB,CAAA,SAAU,iBAAA,YAEzD,CAAA,SAAU,mBAAA,YAER,CAAA,SAAU,oBAAA,aAER,CAAA,SAAU,mBAAA,YACR,CAAA,WACA,CAAA,SAAU,iBAAA,YACR,CAAA,GACA,CAAA,SAAU,kBAAA;;;;;KAYV,iBAAA,WAA4B,aAAA,IAAiB,CAAA;EAAY,OAAA;AAAA,IACjE,WAAA,CAAY,CAAA,IACZ,WAAA,CAAY,CAAA;AAAA,KAMJ,gBAAA,gBAAgC,MAAA,SAA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AA,CAAmB,CAAA,GAC/B,OAAA,GAAU,2BAAA,GACT,cAAA,CAAe,CAAA;;;iBCdF,cAAA,iBAA+B,MAAA,SAAe,aAAA,EAAA,CAAgB,UAAA;EAC5E,SAAA;EACA,KAAA,EAAO,YAAA;EACP,MAAA,EAAQ,CAAA;EACR,KAAA;AAAA,IACE,kBAAA,CAAmB,CAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/builders.ts","../src/client.ts","../src/client-factory.ts","../src/define-settings.ts"],"mappings":";;;;;UAgBiB,iBAAA;EAIf;EAFA,KAAA;EAIY;EAFZ,WAAA;EAKe;EAHf,YAAA;AAAA;AAAA,UAGe,iBAAA,SAA0B,iBAAA;EACzC,IAAA;EACA,OAAA;EACA,SAAA;EACA,SAAA;EACA,OAAA,GAAU,MAAA;EAAV;EAEA,SAAA;AAAA;AAAA,UAGe,mBAAA,SAA4B,iBAAA;EAC3C,IAAA;EACA,OAAA;EACA,GAAA;EACA,GAAA;EACA,OAAA;AAAA;AAAA,UAGe,oBAAA,SAA6B,iBAAA;EAC5C,IAAA;EACA,OAAA;AAAA;AAAA,UAGe,mBAAA,0DACP,iBAAA;EACR,IAAA;EACA,OAAA,EAAS,CAAA;EACT,OAAA,GAAU,CAAA;AAAA;AAAA,UAGK,iBAAA,sBAAuC,iBAAA;EACtD,IAAA;EACA,OAAA,GAAU,CAAA;EAbV;EAeA,MAAA,GAAS,OAAA,CAAQ,CAAA;AAAA;AAAA,UAGF,kBAAA,SAA2B,iBAAA;EAC1C,IAAA;EACA,OAAA;EACA,MAAA;AAAA;AAAA,KAGU,aAAA,GACR,iBAAA,GACA,mBAAA,GACA,oBAAA,GACA,mBAAA,GACA,iBAAA,GACA,kBAAA;;;;;KAUQ,WAAA,WAAsB,aAAA,IAAiB,CAAA,SAAU,iBAAA,YAEzD,CAAA,SAAU,mBAAA,YAER,CAAA,SAAU,oBAAA,aAER,CAAA,SAAU,mBAAA,YACR,CAAA,WACA,CAAA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MAAA;AAAA;;;UCjWC,2BAAA;EHKiB;EGHhC,GAAA,GAAM,UAAA;EHON;EGLA,KAAA,GAAQ,YAAA;EHOI;EGLZ,OAAA;AAAA;;;;;;;;;;;;;iBAec,oBAAA,WAA+B,MAAA,SAAe,aAAA,EAAA,CAC5D,UAAA,EAAY,kBAAA,CAAmB,CAAA,GAC/B,OAAA,GAAU,2BAAA,GACT,cAAA,CAAe,CAAA;;;iBCdF,cAAA,iBAA+B,MAAA,SAAe,aAAA,EAAA,CAAgB,UAAA;EAC5E,SAAA;EACA,KAAA,EAAO,YAAA;EACP,MAAA,EAAQ,CAAA;EACR,KAAA;AAAA,IACE,kBAAA,CAAmB,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/builders.ts","../src/types.ts","../src/validation.ts","../src/client.ts","../src/client-factory.ts","../src/define-settings.ts"],"sourcesContent":["/**\n * Fluent API for building setting definitions.\n *\n * Each builder uses a `const` generic parameter on the config to preserve\n * literal types (e.g., `default: 'My Site'` stays literal, not `string`).\n * This enables compile-time type inference in the settings system.\n *\n * Pattern matches packages/entity/src/fields/builders.ts exactly.\n */\n\nimport type {\n BooleanSettingConfig,\n JsonSettingConfig,\n MediaSettingConfig,\n NumberSettingConfig,\n SelectSettingConfig,\n TextSettingConfig,\n} from './types.js'\n\nexport const setting = {\n /**\n * Text setting (string value)\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n text: <const C extends Partial<Omit<TextSettingConfig, 'type'>> = {}>(\n config?: C,\n ): TextSettingConfig & C => ({ type: 'text', ...config }) as TextSettingConfig & C,\n\n /**\n * Number setting\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n number: <const C extends Partial<Omit<NumberSettingConfig, 'type'>> = {}>(\n config?: C,\n ): NumberSettingConfig & C => ({ type: 'number', ...config }) as NumberSettingConfig & C,\n\n /**\n * Boolean setting\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n boolean: <const C extends Partial<Omit<BooleanSettingConfig, 'type'>> = {}>(\n config?: C,\n ): BooleanSettingConfig & C => ({ type: 'boolean', ...config }) as BooleanSettingConfig & C,\n\n /**\n * Select setting (enum from options tuple)\n * Preserves literal option types for type inference.\n *\n * @example\n * setting.select({ options: ['light', 'dark', 'system'] as const, default: 'system' })\n * // inferred type: 'light' | 'dark' | 'system'\n */\n select: <\n const O extends readonly string[],\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n const C extends Partial<Omit<SelectSettingConfig, 'type' | 'options'>> = {},\n >(\n config: { options: O } & C,\n ): SelectSettingConfig<O> & C => ({ type: 'select', ...config }) as SelectSettingConfig<O> & C,\n\n /**\n * JSON setting (arbitrary typed JSON)\n *\n * @example\n * setting.json<{ twitter?: string; github?: string }>()\n * setting.json<string[]>({ default: [] })\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n json: <T = unknown, const C extends Partial<Omit<JsonSettingConfig<T>, 'type'>> = {}>(\n config?: C,\n ): JsonSettingConfig<T> & C => ({ type: 'json', ...config }) as JsonSettingConfig<T> & C,\n\n /**\n * Media setting (stores media ID as string UUID)\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n media: <const C extends Partial<Omit<MediaSettingConfig, 'type'>> = {}>(\n config?: C,\n ): MediaSettingConfig & C => ({ type: 'media', ...config }) as MediaSettingConfig & C,\n}\n","/**\n * Setting configuration types and compile-time type inference.\n *\n * Design mirrors the entity field system:\n * - Config interfaces define what each setting type accepts\n * - SettingToTS maps a single config to its TypeScript type\n * - InferSettingValue adds null awareness based on `default` presence\n * - InferSettingsMap maps an entire schema to a typed record\n */\n\nimport type { ZodType } from 'zod'\n\n// ---------------------------------------------------------------\n// 1. Setting config interfaces\n// ---------------------------------------------------------------\n\nexport interface BaseSettingConfig {\n /** Human-readable label for admin UI */\n label?: string\n /** Description / help text */\n description?: string\n /** If true, this setting can have per-locale values (mirrors entity translatable pattern) */\n translatable?: boolean\n}\n\nexport interface TextSettingConfig extends BaseSettingConfig {\n type: 'text'\n default?: string\n maxLength?: number\n minLength?: number\n pattern?: RegExp\n}\n\nexport interface NumberSettingConfig extends BaseSettingConfig {\n type: 'number'\n default?: number\n min?: number\n max?: number\n integer?: boolean\n}\n\nexport interface BooleanSettingConfig extends BaseSettingConfig {\n type: 'boolean'\n default?: boolean\n}\n\nexport interface SelectSettingConfig<O extends readonly string[] = readonly string[]>\n extends BaseSettingConfig {\n type: 'select'\n options: O\n default?: O[number]\n}\n\nexport interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {\n type: 'json'\n default?: T\n /** Optional Zod schema for validation. If provided, values are validated on set. */\n schema?: ZodType<T>\n}\n\nexport interface MediaSettingConfig extends BaseSettingConfig {\n type: 'media'\n accept?: string[]\n}\n\nexport type SettingConfig =\n | TextSettingConfig\n | NumberSettingConfig\n | BooleanSettingConfig\n | SelectSettingConfig\n | JsonSettingConfig\n | MediaSettingConfig\n\n// ---------------------------------------------------------------\n// 2. Setting-to-TypeScript mapping (single setting)\n// ---------------------------------------------------------------\n\n/**\n * Maps a single SettingConfig to its TypeScript output type.\n * Each branch is a shallow comparison — no recursion.\n */\nexport type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig\n ? string\n : S extends NumberSettingConfig\n ? number\n : S extends BooleanSettingConfig\n ? boolean\n : S extends SelectSettingConfig<infer O>\n ? O[number]\n : S extends JsonSettingConfig<infer T>\n ? T\n : S extends MediaSettingConfig\n ? string\n : never\n\n// ---------------------------------------------------------------\n// 3. Null awareness: settings with defaults always return value\n// ---------------------------------------------------------------\n\n/**\n * If a setting has a `default`, get() never returns null.\n * Without a default, it returns T | null.\n */\nexport type InferSettingValue<S extends SettingConfig> = S extends { default: unknown }\n ? SettingToTS<S>\n : SettingToTS<S> | null\n\n// ---------------------------------------------------------------\n// 4. Full settings map type (what getAll() returns)\n// ---------------------------------------------------------------\n\nexport type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {\n [K in keyof Schema]: InferSettingValue<Schema[K]>\n}\n\n// ---------------------------------------------------------------\n// 5. Scope types\n// ---------------------------------------------------------------\n\nexport type SettingScope = 'global' | 'team' | 'user'\n\n/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */\nexport const GLOBAL_SCOPE_ID = '__global__'\n\n/** Sentinel value for locale column when no locale is specified (base/default value) */\nexport const DEFAULT_LOCALE = '_default'\n\n// ---------------------------------------------------------------\n// 6. Settings definition (returned by defineSettings)\n// ---------------------------------------------------------------\n\nexport interface SettingsDefinition<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n /** Unique namespace for this settings group */\n namespace: string\n /** Default scope for these settings */\n scope: SettingScope\n /** Setting schema (the shape) */\n schema: S\n /** Human-readable label for admin UI */\n label?: string\n}\n","/**\n * Generate Zod validation schemas from setting config definitions.\n * Validates values before writing to the database.\n */\n\nimport { z } from 'zod'\nimport type { SettingConfig, SettingsDefinition } from './types.js'\n\n/**\n * Convert a single setting config to a Zod schema.\n */\nexport function settingToZod(config: SettingConfig): z.ZodType {\n switch (config.type) {\n case 'text': {\n let schema: z.ZodString = z.string()\n if (config.maxLength) schema = schema.max(config.maxLength)\n if (config.minLength) schema = schema.min(config.minLength)\n if (config.pattern) schema = schema.regex(config.pattern)\n return schema\n }\n\n case 'number': {\n let schema: z.ZodNumber = z.number()\n if (config.integer) schema = schema.int()\n if (config.min !== undefined) schema = schema.min(config.min)\n if (config.max !== undefined) schema = schema.max(config.max)\n return schema\n }\n\n case 'boolean':\n return z.boolean()\n\n case 'select':\n return z.enum(config.options as [string, ...string[]])\n\n case 'json':\n return config.schema ?? z.unknown()\n\n case 'media':\n return z.string().uuid()\n\n default:\n return z.unknown()\n }\n}\n\n/**\n * Generate a validation map for all settings in a definition.\n * Returns a Record<key, ZodType> for validating individual set() calls.\n *\n * Settings without a default are nullable (matching InferSettingValue),\n * so their validators accept null.\n */\nexport function generateSettingValidators(\n definition: SettingsDefinition,\n): Record<string, z.ZodType> {\n const validators: Record<string, z.ZodType> = {}\n for (const [key, config] of Object.entries(definition.schema)) {\n let schema = settingToZod(config)\n const hasDefault = 'default' in config && config.default !== undefined\n if (!hasDefault) {\n schema = schema.nullable()\n }\n validators[key] = schema\n }\n return validators\n}\n","/**\n * SettingsClient — typed CRUD for key-value settings.\n *\n * Server-only. Uses read-write DB connection.\n * Validates values against the setting schema on set().\n *\n * Supports per-locale values for settings marked `translatable: true`.\n * Non-translatable settings always use the `__default__` locale.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n *\n * // Default locale\n * const name = await settings.get('siteName') // string (has default)\n *\n * // Locale-specific (only for translatable settings)\n * const nameEt = await settings.get('siteName', { locale: 'et' })\n *\n * await settings.set('siteName', 'Mänguväljak', { locale: 'et' })\n * ```\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { and, eq, or } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettings } from './schema.js'\nimport type {\n InferSettingsMap,\n InferSettingValue,\n SettingConfig,\n SettingScope,\n SettingsDefinition,\n} from './types.js'\nimport { DEFAULT_LOCALE, GLOBAL_SCOPE_ID } from './types.js'\nimport { generateSettingValidators } from './validation.js'\n\nexport interface SettingsClientConfig {\n /** Database client (read-write) */\n db: PostgresJsDatabase\n /** Logger instance */\n logger?: Logger\n /** Override scope (defaults to definition's scope) */\n scope?: SettingScope\n /** Scope ID (required for team/user scope, defaults to '__global__' for global) */\n scopeId?: string\n}\n\nexport interface LocaleOption {\n /** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */\n locale?: string\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private db: PostgresJsDatabase\n private logger?: Logger\n private scope: SettingScope\n private scopeId: string\n private validators: Record<string, ZodType>\n\n constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig) {\n if (typeof window !== 'undefined') {\n throw new Error('SettingsClient cannot be used in browser code.')\n }\n\n this.definition = definition\n this.db = config.db\n this.logger = config.logger\n this.scope = config.scope ?? definition.scope\n this.scopeId = config.scopeId ?? GLOBAL_SCOPE_ID\n\n if ((this.scope === 'team' || this.scope === 'user') && !config.scopeId) {\n throw new Error(\n `scopeId is required for ${this.scope}-scoped settings (namespace: ${definition.namespace})`,\n )\n }\n\n this.validators = generateSettingValidators(definition)\n }\n\n /**\n * Get a single setting value.\n *\n * For translatable settings with a locale, tries locale-specific value first,\n * then falls back to the default value, then the schema default, then null.\n */\n async get<K extends string & keyof S>(\n key: K,\n options?: LocaleOption,\n ): Promise<InferSettingValue<S[K]>> {\n const config = this.definition.schema[key]\n const locale = config?.translatable && options?.locale ? options.locale : null\n\n this.logger?.debug({ namespace: this.definition.namespace, key, locale }, 'Getting setting')\n\n if (locale) {\n // Fetch both locale-specific and default in one query\n const rows = await this.db\n .select({ locale: toolkitSettings.locale, value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n or(eq(toolkitSettings.locale, locale), eq(toolkitSettings.locale, DEFAULT_LOCALE)),\n ),\n )\n\n // Prefer locale-specific, fall back to default\n const localeRow = rows.find((r) => r.locale === locale)\n const defaultRow = rows.find((r) => r.locale === DEFAULT_LOCALE)\n const row = localeRow ?? defaultRow\n\n if (row && row.value !== undefined && row.value !== null) {\n return row.value as InferSettingValue<S[K]>\n }\n } else {\n const rows = await this.db\n .select({ value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(this.whereClause(key))\n .limit(1)\n\n if (rows.length > 0 && rows[0].value !== undefined && rows[0].value !== null) {\n return rows[0].value as InferSettingValue<S[K]>\n }\n }\n\n if (config && 'default' in config && config.default !== undefined) {\n return config.default as InferSettingValue<S[K]>\n }\n\n return null as InferSettingValue<S[K]>\n }\n\n /**\n * Get all settings for this namespace/scope as a typed object.\n * Missing values are filled from schema defaults.\n *\n * When locale is specified, translatable settings prefer the locale-specific\n * value over the default value.\n */\n async getAll(options?: LocaleOption): Promise<InferSettingsMap<S>> {\n const locale = options?.locale ?? null\n\n this.logger?.debug({ namespace: this.definition.namespace, locale }, 'Getting all settings')\n\n let rows: { key: string; locale: string; value: unknown }[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n or(eq(toolkitSettings.locale, DEFAULT_LOCALE), eq(toolkitSettings.locale, locale)),\n ),\n )\n } else {\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(and(...this.baseWhere(), eq(toolkitSettings.locale, DEFAULT_LOCALE)))\n }\n\n // Build lookup: key → { default: value, locale: value }\n const stored = new Map<string, { default?: unknown; locale?: unknown }>()\n for (const row of rows) {\n const entry = stored.get(row.key) ?? {}\n if (row.locale === DEFAULT_LOCALE) {\n entry.default = row.value\n } else {\n entry.locale = row.value\n }\n stored.set(row.key, entry)\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, config] of Object.entries(this.definition.schema)) {\n const entry = stored.get(key)\n\n // For translatable settings with locale, prefer locale-specific value\n let value: unknown\n if (config.translatable && locale && entry?.locale !== undefined && entry?.locale !== null) {\n value = entry.locale\n } else if (entry?.default !== undefined && entry?.default !== null) {\n value = entry.default\n }\n\n if (value !== undefined) {\n result[key] = value\n } else if ('default' in config && config.default !== undefined) {\n result[key] = config.default\n } else {\n result[key] = null\n }\n }\n\n return result as InferSettingsMap<S>\n }\n\n /**\n * Set a single setting value.\n * Validates against the schema before writing.\n *\n * Pass `{ locale }` to write a locale-specific value (only for translatable settings).\n */\n async set<K extends string & keyof S>(\n key: K,\n value: InferSettingValue<S[K]>,\n options?: LocaleOption,\n ): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Setting value')\n\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n\n const validator = this.validators[key]\n if (validator) {\n validator.parse(value)\n }\n\n await this.upsert(key, value as unknown, locale)\n }\n\n /**\n * Set multiple settings at once (validated individually).\n * Writes in a transaction — all or nothing.\n *\n * Pass `{ locale }` to write locale-specific values for translatable settings.\n * Non-translatable settings in the values will always write to the default locale.\n */\n async setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void> {\n this.logger?.info(\n { namespace: this.definition.namespace, keys: Object.keys(values), locale: options?.locale },\n 'Setting multiple values',\n )\n\n // Validate all first (fail fast)\n for (const [key, value] of Object.entries(values)) {\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n const validator = this.validators[key]\n if (validator && value !== undefined) {\n validator.parse(value)\n }\n }\n\n await this.db.transaction(async (tx) => {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n const locale = this.resolveLocale(key, options)\n await tx\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value: value as unknown,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value: value as unknown,\n updatedAt: new Date(),\n },\n })\n }\n })\n }\n\n /**\n * Delete a setting (resets to default on next get).\n * Pass `{ locale }` to delete only the locale-specific value.\n */\n async delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Deleting setting')\n\n await this.db.delete(toolkitSettings).where(this.whereClause(key, locale))\n }\n\n /**\n * Check if a setting has a stored value (not relying on default).\n */\n async has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean> {\n const locale = this.resolveLocale(key, options)\n\n const rows = await this.db\n .select({ key: toolkitSettings.key })\n .from(toolkitSettings)\n .where(this.whereClause(key, locale))\n .limit(1)\n\n return rows.length > 0\n }\n\n // ---------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------\n\n /**\n * Resolve which locale to use for a given key.\n * Non-translatable settings always use DEFAULT_LOCALE.\n * Translatable settings use the requested locale or DEFAULT_LOCALE.\n */\n private resolveLocale(key: string, options?: LocaleOption): string {\n const config = this.definition.schema[key as keyof S] as SettingConfig | undefined\n if (config?.translatable && options?.locale) {\n return options.locale\n }\n return DEFAULT_LOCALE\n }\n\n /** Base where conditions: namespace + scope + scopeId */\n private baseWhere() {\n return [\n eq(toolkitSettings.namespace, this.definition.namespace),\n eq(toolkitSettings.scope, this.scope),\n eq(toolkitSettings.scopeId, this.scopeId),\n ] as const\n }\n\n /** Full where clause for a specific key + locale */\n private whereClause(key: string, locale: string = DEFAULT_LOCALE) {\n return and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n eq(toolkitSettings.locale, locale),\n )!\n }\n\n /** Upsert a single setting row */\n private async upsert(key: string, value: unknown, locale: string) {\n await this.db\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value,\n updatedAt: new Date(),\n },\n })\n }\n}\n","/**\n * Factory function for creating typed SettingsClient instances.\n *\n * Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { SettingsClient } from './client.js'\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport interface CreateSettingsClientOptions {\n /** Override the toolkit app (defaults to getApp()) */\n app?: ToolkitApp\n /** Override scope from definition */\n scope?: SettingScope\n /** Scope ID for team/user scoped settings */\n scopeId?: string\n}\n\n/**\n * Create a typed SettingsClient.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n * const name = await settings.get('siteName') // string\n * ```\n */\nexport function createSettingsClient<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n options?: CreateSettingsClientOptions,\n): SettingsClient<S> {\n const app = options?.app ?? getApp()\n\n return new SettingsClient(definition, {\n db: app.db.readWrite,\n logger: app.logger.child({ settings: definition.namespace }),\n scope: options?.scope,\n scopeId: options?.scopeId,\n })\n}\n","/**\n * Define a typed settings group.\n *\n * @example\n * ```typescript\n * import { defineSettings, setting } from '@murumets-ee/settings'\n *\n * export const siteSettings = defineSettings({\n * namespace: 'site',\n * scope: 'global',\n * schema: {\n * siteName: setting.text({ default: 'My Site' }),\n * logo: setting.media(),\n * maintenance: setting.boolean({ default: false }),\n * },\n * })\n * ```\n */\n\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport function defineSettings<const S extends Record<string, SettingConfig>>(definition: {\n namespace: string\n scope: SettingScope\n schema: S\n label?: string\n}): SettingsDefinition<S> {\n if (!definition.namespace) {\n throw new Error('Settings namespace is required')\n }\n if (!definition.schema || Object.keys(definition.schema).length === 0) {\n throw new Error('Settings schema must have at least one setting')\n }\n return definition\n}\n"],"mappings":"wLAmBA,MAAa,EAAU,CAKrB,KACE,IAC2B,CAAE,KAAM,OAAQ,GAAG,EAAQ,EAMxD,OACE,IAC6B,CAAE,KAAM,SAAU,GAAG,EAAQ,EAM5D,QACE,IAC8B,CAAE,KAAM,UAAW,GAAG,EAAQ,EAU9D,OAKE,IACg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,CACD,IAAK,CACH,QACA,UAAW,IAAI,KAChB,CACF,CAAC,GCpWR,SAAgB,EACd,EACA,EACmB,CACnB,IAAM,EAAM,GAAS,KAAO,GAAQ,CAEpC,OAAO,IAAI,EAAe,EAAY,CACpC,GAAI,EAAI,GAAG,UACX,OAAQ,EAAI,OAAO,MAAM,CAAE,SAAU,EAAW,UAAW,CAAC,CAC5D,MAAO,GAAS,MAChB,QAAS,GAAS,QACnB,CAAC,CCtBJ,SAAgB,EAA8D,EAKpD,CACxB,GAAI,CAAC,EAAW,UACd,MAAU,MAAM,iCAAiC,CAEnD,GAAI,CAAC,EAAW,QAAU,OAAO,KAAK,EAAW,OAAO,CAAC,SAAW,EAClE,MAAU,MAAM,iDAAiD,CAEnE,OAAO"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/builders.ts","../src/types.ts","../src/validation.ts","../src/client.ts","../src/client-factory.ts","../src/define-settings.ts"],"sourcesContent":["/**\n * Fluent API for building setting definitions.\n *\n * Each builder uses a `const` generic parameter on the config to preserve\n * literal types (e.g., `default: 'My Site'` stays literal, not `string`).\n * This enables compile-time type inference in the settings system.\n *\n * Pattern matches packages/entity/src/fields/builders.ts exactly.\n */\n\nimport type {\n BooleanSettingConfig,\n JsonSettingConfig,\n MediaSettingConfig,\n NumberSettingConfig,\n SelectSettingConfig,\n TextSettingConfig,\n} from './types.js'\n\nexport const setting = {\n /**\n * Text setting (string value)\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n text: <const C extends Partial<Omit<TextSettingConfig, 'type'>> = {}>(\n config?: C,\n ): TextSettingConfig & C => ({ type: 'text', ...config }) as TextSettingConfig & C,\n\n /**\n * Number setting\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n number: <const C extends Partial<Omit<NumberSettingConfig, 'type'>> = {}>(\n config?: C,\n ): NumberSettingConfig & C => ({ type: 'number', ...config }) as NumberSettingConfig & C,\n\n /**\n * Boolean setting\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n boolean: <const C extends Partial<Omit<BooleanSettingConfig, 'type'>> = {}>(\n config?: C,\n ): BooleanSettingConfig & C => ({ type: 'boolean', ...config }) as BooleanSettingConfig & C,\n\n /**\n * Select setting (enum from options tuple)\n * Preserves literal option types for type inference.\n *\n * @example\n * setting.select({ options: ['light', 'dark', 'system'] as const, default: 'system' })\n * // inferred type: 'light' | 'dark' | 'system'\n */\n select: <\n const O extends readonly string[],\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n const C extends Partial<Omit<SelectSettingConfig, 'type' | 'options'>> = {},\n >(\n config: { options: O } & C,\n ): SelectSettingConfig<O> & C => ({ type: 'select', ...config }) as SelectSettingConfig<O> & C,\n\n /**\n * JSON setting (arbitrary typed JSON)\n *\n * @example\n * setting.json<{ twitter?: string; github?: string }>()\n * setting.json<string[]>({ default: [] })\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n json: <T = unknown, const C extends Partial<Omit<JsonSettingConfig<T>, 'type'>> = {}>(\n config?: C,\n ): JsonSettingConfig<T> & C => ({ type: 'json', ...config }) as JsonSettingConfig<T> & C,\n\n /**\n * Media setting (stores media ID as string UUID)\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n media: <const C extends Partial<Omit<MediaSettingConfig, 'type'>> = {}>(\n config?: C,\n ): MediaSettingConfig & C => ({ type: 'media', ...config }) as MediaSettingConfig & C,\n}\n","/**\n * Setting configuration types and compile-time type inference.\n *\n * Design mirrors the entity field system:\n * - Config interfaces define what each setting type accepts\n * - SettingToTS maps a single config to its TypeScript type\n * - InferSettingValue adds null awareness based on `default` presence\n * - InferSettingsMap maps an entire schema to a typed record\n */\n\nimport type { ZodType } from 'zod'\n\n// ---------------------------------------------------------------\n// 1. Setting config interfaces\n// ---------------------------------------------------------------\n\nexport interface BaseSettingConfig {\n /** Human-readable label for admin UI */\n label?: string\n /** Description / help text */\n description?: string\n /** If true, this setting can have per-locale values (mirrors entity translatable pattern) */\n translatable?: boolean\n}\n\nexport interface TextSettingConfig extends BaseSettingConfig {\n type: 'text'\n default?: string\n maxLength?: number\n minLength?: number\n pattern?: RegExp\n /** Render as textarea instead of single-line input. */\n multiline?: boolean\n}\n\nexport interface NumberSettingConfig extends BaseSettingConfig {\n type: 'number'\n default?: number\n min?: number\n max?: number\n integer?: boolean\n}\n\nexport interface BooleanSettingConfig extends BaseSettingConfig {\n type: 'boolean'\n default?: boolean\n}\n\nexport interface SelectSettingConfig<O extends readonly string[] = readonly string[]>\n extends BaseSettingConfig {\n type: 'select'\n options: O\n default?: O[number]\n}\n\nexport interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {\n type: 'json'\n default?: T\n /** Optional Zod schema for validation. If provided, values are validated on set. */\n schema?: ZodType<T>\n}\n\nexport interface MediaSettingConfig extends BaseSettingConfig {\n type: 'media'\n default?: string\n accept?: string[]\n}\n\nexport type SettingConfig =\n | TextSettingConfig\n | NumberSettingConfig\n | BooleanSettingConfig\n | SelectSettingConfig\n | JsonSettingConfig\n | MediaSettingConfig\n\n// ---------------------------------------------------------------\n// 2. Setting-to-TypeScript mapping (single setting)\n// ---------------------------------------------------------------\n\n/**\n * Maps a single SettingConfig to its TypeScript output type.\n * Each branch is a shallow comparison — no recursion.\n */\nexport type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig\n ? string\n : S extends NumberSettingConfig\n ? number\n : S extends BooleanSettingConfig\n ? boolean\n : S extends SelectSettingConfig<infer O>\n ? O[number]\n : S extends JsonSettingConfig<infer T>\n ? T\n : S extends MediaSettingConfig\n ? string\n : never\n\n// ---------------------------------------------------------------\n// 3. Null awareness: settings with defaults always return value\n// ---------------------------------------------------------------\n\n/**\n * If a setting has a `default`, get() never returns null.\n * Without a default, it returns T | null.\n */\nexport type InferSettingValue<S extends SettingConfig> = S extends { default: unknown }\n ? SettingToTS<S>\n : SettingToTS<S> | null\n\n// ---------------------------------------------------------------\n// 4. Full settings map type (what getAll() returns)\n// ---------------------------------------------------------------\n\nexport type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {\n [K in keyof Schema]: InferSettingValue<Schema[K]>\n}\n\n// ---------------------------------------------------------------\n// 5. Scope types\n// ---------------------------------------------------------------\n\nexport type SettingScope = 'global' | 'team' | 'user'\n\n/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */\nexport const GLOBAL_SCOPE_ID = '__global__'\n\n/** Sentinel value for locale column when no locale is specified (base/default value) */\nexport const DEFAULT_LOCALE = '_default'\n\n// ---------------------------------------------------------------\n// 6. Settings definition (returned by defineSettings)\n// ---------------------------------------------------------------\n\nexport interface SettingsDefinition<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n /** Unique namespace for this settings group */\n namespace: string\n /** Default scope for these settings */\n scope: SettingScope\n /** Setting schema (the shape) */\n schema: S\n /** Human-readable label for admin UI */\n label?: string\n}\n","/**\n * Generate Zod validation schemas from setting config definitions.\n * Validates values before writing to the database.\n */\n\nimport { z } from 'zod'\nimport type { SettingConfig, SettingsDefinition } from './types.js'\n\n/**\n * Convert a single setting config to a Zod schema.\n */\nexport function settingToZod(config: SettingConfig): z.ZodType {\n switch (config.type) {\n case 'text': {\n let schema: z.ZodString = z.string()\n if (config.maxLength) schema = schema.max(config.maxLength)\n if (config.minLength) schema = schema.min(config.minLength)\n if (config.pattern) schema = schema.regex(config.pattern)\n return schema\n }\n\n case 'number': {\n let schema: z.ZodNumber = z.number()\n if (config.integer) schema = schema.int()\n if (config.min !== undefined) schema = schema.min(config.min)\n if (config.max !== undefined) schema = schema.max(config.max)\n return schema\n }\n\n case 'boolean':\n return z.boolean()\n\n case 'select':\n return z.enum(config.options as [string, ...string[]])\n\n case 'json':\n return config.schema ?? z.unknown()\n\n case 'media':\n return z.string().uuid()\n\n default:\n return z.unknown()\n }\n}\n\n/**\n * Generate a validation map for all settings in a definition.\n * Returns a Record<key, ZodType> for validating individual set() calls.\n *\n * Settings without a default are nullable (matching InferSettingValue),\n * so their validators accept null.\n */\nexport function generateSettingValidators(\n definition: SettingsDefinition,\n): Record<string, z.ZodType> {\n const validators: Record<string, z.ZodType> = {}\n for (const [key, config] of Object.entries(definition.schema)) {\n let schema = settingToZod(config)\n const hasDefault = 'default' in config && config.default !== undefined\n if (!hasDefault) {\n schema = schema.nullable()\n }\n validators[key] = schema\n }\n return validators\n}\n","/**\n * SettingsClient — typed CRUD for key-value settings.\n *\n * Server-only. Uses read-write DB connection.\n * Validates values against the setting schema on set().\n *\n * Supports per-locale values for settings marked `translatable: true`.\n * Non-translatable settings always use the `__default__` locale.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n *\n * // Default locale\n * const name = await settings.get('siteName') // string (has default)\n *\n * // Locale-specific (only for translatable settings)\n * const nameEt = await settings.get('siteName', { locale: 'et' })\n *\n * await settings.set('siteName', 'Mänguväljak', { locale: 'et' })\n * ```\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { and, eq, or } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettings } from './schema.js'\nimport type {\n InferSettingsMap,\n InferSettingValue,\n SettingConfig,\n SettingScope,\n SettingsDefinition,\n} from './types.js'\nimport { DEFAULT_LOCALE, GLOBAL_SCOPE_ID } from './types.js'\nimport { generateSettingValidators } from './validation.js'\n\nexport interface SettingsClientConfig {\n /** Database client (read-write) */\n db: PostgresJsDatabase\n /** Logger instance */\n logger?: Logger\n /** Override scope (defaults to definition's scope) */\n scope?: SettingScope\n /** Scope ID (required for team/user scope, defaults to '__global__' for global) */\n scopeId?: string\n}\n\nexport interface LocaleOption {\n /** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */\n locale?: string\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private db: PostgresJsDatabase\n private logger?: Logger\n private scope: SettingScope\n private scopeId: string\n private validators: Record<string, ZodType>\n\n constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig) {\n if (typeof window !== 'undefined') {\n throw new Error('SettingsClient cannot be used in browser code.')\n }\n\n this.definition = definition\n this.db = config.db\n this.logger = config.logger\n this.scope = config.scope ?? definition.scope\n this.scopeId = config.scopeId ?? GLOBAL_SCOPE_ID\n\n if ((this.scope === 'team' || this.scope === 'user') && !config.scopeId) {\n throw new Error(\n `scopeId is required for ${this.scope}-scoped settings (namespace: ${definition.namespace})`,\n )\n }\n\n this.validators = generateSettingValidators(definition)\n }\n\n /**\n * Get a single setting value.\n *\n * For translatable settings with a locale, tries locale-specific value first,\n * then falls back to the default value, then the schema default, then null.\n */\n async get<K extends string & keyof S>(\n key: K,\n options?: LocaleOption,\n ): Promise<InferSettingValue<S[K]>> {\n const config = this.definition.schema[key]\n const locale = config?.translatable && options?.locale ? options.locale : null\n\n this.logger?.debug({ namespace: this.definition.namespace, key, locale }, 'Getting setting')\n\n if (locale) {\n // Fetch both locale-specific and default in one query\n const rows = await this.db\n .select({ locale: toolkitSettings.locale, value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n or(eq(toolkitSettings.locale, locale), eq(toolkitSettings.locale, DEFAULT_LOCALE)),\n ),\n )\n\n // Prefer locale-specific, fall back to default\n const localeRow = rows.find((r) => r.locale === locale)\n const defaultRow = rows.find((r) => r.locale === DEFAULT_LOCALE)\n const row = localeRow ?? defaultRow\n\n if (row && row.value !== undefined && row.value !== null) {\n return row.value as InferSettingValue<S[K]>\n }\n } else {\n const rows = await this.db\n .select({ value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(this.whereClause(key))\n .limit(1)\n\n if (rows.length > 0 && rows[0].value !== undefined && rows[0].value !== null) {\n return rows[0].value as InferSettingValue<S[K]>\n }\n }\n\n if (config && 'default' in config && config.default !== undefined) {\n return config.default as InferSettingValue<S[K]>\n }\n\n return null as InferSettingValue<S[K]>\n }\n\n /**\n * Get all settings for this namespace/scope as a typed object.\n * Missing values are filled from schema defaults.\n *\n * When locale is specified, translatable settings prefer the locale-specific\n * value over the default value.\n */\n async getAll(options?: LocaleOption): Promise<InferSettingsMap<S>> {\n const locale = options?.locale ?? null\n\n this.logger?.debug({ namespace: this.definition.namespace, locale }, 'Getting all settings')\n\n let rows: { key: string; locale: string; value: unknown }[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n or(eq(toolkitSettings.locale, DEFAULT_LOCALE), eq(toolkitSettings.locale, locale)),\n ),\n )\n } else {\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(and(...this.baseWhere(), eq(toolkitSettings.locale, DEFAULT_LOCALE)))\n }\n\n // Build lookup: key → { default: value, locale: value }\n const stored = new Map<string, { default?: unknown; locale?: unknown }>()\n for (const row of rows) {\n const entry = stored.get(row.key) ?? {}\n if (row.locale === DEFAULT_LOCALE) {\n entry.default = row.value\n } else {\n entry.locale = row.value\n }\n stored.set(row.key, entry)\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, config] of Object.entries(this.definition.schema)) {\n const entry = stored.get(key)\n\n // For translatable settings with locale, prefer locale-specific value\n let value: unknown\n if (config.translatable && locale && entry?.locale !== undefined && entry?.locale !== null) {\n value = entry.locale\n } else if (entry?.default !== undefined && entry?.default !== null) {\n value = entry.default\n }\n\n if (value !== undefined) {\n result[key] = value\n } else if ('default' in config && config.default !== undefined) {\n result[key] = config.default\n } else {\n result[key] = null\n }\n }\n\n return result as InferSettingsMap<S>\n }\n\n /**\n * Set a single setting value.\n * Validates against the schema before writing.\n *\n * Pass `{ locale }` to write a locale-specific value (only for translatable settings).\n */\n async set<K extends string & keyof S>(\n key: K,\n value: InferSettingValue<S[K]>,\n options?: LocaleOption,\n ): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Setting value')\n\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n\n const validator = this.validators[key]\n if (validator) {\n validator.parse(value)\n }\n\n await this.upsert(key, value as unknown, locale)\n }\n\n /**\n * Set multiple settings at once (validated individually).\n * Writes in a transaction — all or nothing.\n *\n * Pass `{ locale }` to write locale-specific values for translatable settings.\n * Non-translatable settings in the values will always write to the default locale.\n */\n async setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void> {\n this.logger?.info(\n { namespace: this.definition.namespace, keys: Object.keys(values), locale: options?.locale },\n 'Setting multiple values',\n )\n\n // Validate all first (fail fast)\n for (const [key, value] of Object.entries(values)) {\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n const validator = this.validators[key]\n if (validator && value !== undefined) {\n validator.parse(value)\n }\n }\n\n await this.db.transaction(async (tx) => {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n const locale = this.resolveLocale(key, options)\n await tx\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value: value as unknown,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value: value as unknown,\n updatedAt: new Date(),\n },\n })\n }\n })\n }\n\n /**\n * Delete a setting (resets to default on next get).\n * Pass `{ locale }` to delete only the locale-specific value.\n */\n async delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Deleting setting')\n\n await this.db.delete(toolkitSettings).where(this.whereClause(key, locale))\n }\n\n /**\n * Check if a setting has a stored value (not relying on default).\n */\n async has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean> {\n const locale = this.resolveLocale(key, options)\n\n const rows = await this.db\n .select({ key: toolkitSettings.key })\n .from(toolkitSettings)\n .where(this.whereClause(key, locale))\n .limit(1)\n\n return rows.length > 0\n }\n\n // ---------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------\n\n /**\n * Resolve which locale to use for a given key.\n * Non-translatable settings always use DEFAULT_LOCALE.\n * Translatable settings use the requested locale or DEFAULT_LOCALE.\n */\n private resolveLocale(key: string, options?: LocaleOption): string {\n const config = this.definition.schema[key as keyof S] as SettingConfig | undefined\n if (config?.translatable && options?.locale) {\n return options.locale\n }\n return DEFAULT_LOCALE\n }\n\n /** Base where conditions: namespace + scope + scopeId */\n private baseWhere() {\n return [\n eq(toolkitSettings.namespace, this.definition.namespace),\n eq(toolkitSettings.scope, this.scope),\n eq(toolkitSettings.scopeId, this.scopeId),\n ] as const\n }\n\n /** Full where clause for a specific key + locale */\n private whereClause(key: string, locale: string = DEFAULT_LOCALE) {\n return and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n eq(toolkitSettings.locale, locale),\n )!\n }\n\n /** Upsert a single setting row */\n private async upsert(key: string, value: unknown, locale: string) {\n await this.db\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value,\n updatedAt: new Date(),\n },\n })\n }\n}\n","/**\n * Factory function for creating typed SettingsClient instances.\n *\n * Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { SettingsClient } from './client.js'\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport interface CreateSettingsClientOptions {\n /** Override the toolkit app (defaults to getApp()) */\n app?: ToolkitApp\n /** Override scope from definition */\n scope?: SettingScope\n /** Scope ID for team/user scoped settings */\n scopeId?: string\n}\n\n/**\n * Create a typed SettingsClient.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n * const name = await settings.get('siteName') // string\n * ```\n */\nexport function createSettingsClient<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n options?: CreateSettingsClientOptions,\n): SettingsClient<S> {\n const app = options?.app ?? getApp()\n\n return new SettingsClient(definition, {\n db: app.db.readWrite,\n logger: app.logger.child({ settings: definition.namespace }),\n scope: options?.scope,\n scopeId: options?.scopeId,\n })\n}\n","/**\n * Define a typed settings group.\n *\n * @example\n * ```typescript\n * import { defineSettings, setting } from '@murumets-ee/settings'\n *\n * export const siteSettings = defineSettings({\n * namespace: 'site',\n * scope: 'global',\n * schema: {\n * siteName: setting.text({ default: 'My Site' }),\n * logo: setting.media(),\n * maintenance: setting.boolean({ default: false }),\n * },\n * })\n * ```\n */\n\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport function defineSettings<const S extends Record<string, SettingConfig>>(definition: {\n namespace: string\n scope: SettingScope\n schema: S\n label?: string\n}): SettingsDefinition<S> {\n if (!definition.namespace) {\n throw new Error('Settings namespace is required')\n }\n if (!definition.schema || Object.keys(definition.schema).length === 0) {\n throw new Error('Settings schema must have at least one setting')\n }\n return definition\n}\n"],"mappings":"wLAmBA,MAAa,EAAU,CAKrB,KACE,IAC2B,CAAE,KAAM,OAAQ,GAAG,EAAQ,EAMxD,OACE,IAC6B,CAAE,KAAM,SAAU,GAAG,EAAQ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,CACN,EAAgB,UAChB,EAAgB,MAChB,EAAgB,QAChB,EAAgB,IAChB,EAAgB,OACjB,CACD,IAAK,CACH,QACA,UAAW,IAAI,KAChB,CACF,CAAC,GCpWR,SAAgB,EACd,EACA,EACmB,CACnB,IAAM,EAAM,GAAS,KAAO,GAAQ,CAEpC,OAAO,IAAI,EAAe,EAAY,CACpC,GAAI,EAAI,GAAG,UACX,OAAQ,EAAI,OAAO,MAAM,CAAE,SAAU,EAAW,UAAW,CAAC,CAC5D,MAAO,GAAS,MAChB,QAAS,GAAS,QACnB,CAAC,CCtBJ,SAAgB,EAA8D,EAKpD,CACxB,GAAI,CAAC,EAAW,UACd,MAAU,MAAM,iCAAiC,CAEnD,GAAI,CAAC,EAAW,QAAU,OAAO,KAAK,EAAW,OAAO,CAAC,SAAW,EAClE,MAAU,MAAM,iDAAiD,CAEnE,OAAO"}
package/dist/schema.d.mts CHANGED
@@ -8,14 +8,8 @@ import * as _$drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
8
8
  * - toolkit_settings: typed key-value settings grouped by namespace and scope
9
9
  * - toolkit_view_state: schemaless user-scoped JSON blobs with optional TTL
10
10
  *
11
- * Usage in drizzle.config.ts:
12
- * ```typescript
13
- * import type { Config } from 'drizzle-kit'
14
- * export default {
15
- * schema: ['./generated/schema.ts', '@murumets-ee/settings/schema'],
16
- * // ...
17
- * } satisfies Config
18
- * ```
11
+ * These tables are registered for migration discovery via the `settings()`
12
+ * plugin's `tables` field. `lumi migrate` picks them up automatically.
19
13
  */
20
14
  /**
21
15
  * Typed settings table.
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.mts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;;AA4BA;;;;;;;;;;;;;;;;;;;;;;cAAa,eAAA,yBAAe,kBAAA;;;;QAsB3B,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAQY,gBAAA,yBAAgB,kBAAA;;;;QAa5B,sBAAA,CAAA,QAAA"}
1
+ {"version":3,"file":"schema.d.mts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;;AAsBA;;;;;;;;;;;;;;;;cAAa,eAAA,yBAAe,kBAAA;;;;QAsB3B,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAQY,gBAAA,yBAAgB,kBAAA;;;;QAa5B,sBAAA,CAAA,QAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"schema.mjs","names":[],"sources":["../src/schema.ts"],"sourcesContent":["/**\n * Drizzle schema for settings tables.\n *\n * Two tables:\n * - toolkit_settings: typed key-value settings grouped by namespace and scope\n * - toolkit_view_state: schemaless user-scoped JSON blobs with optional TTL\n *\n * Usage in drizzle.config.ts:\n * ```typescript\n * import type { Config } from 'drizzle-kit'\n * export default {\n * schema: ['./generated/schema.ts', '@murumets-ee/settings/schema'],\n * // ...\n * } satisfies Config\n * ```\n */\n\nimport { jsonb, pgTable, timestamp, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\n/**\n * Typed settings table.\n *\n * Stores key-value pairs grouped by namespace and scoped\n * to global, team, or user contexts.\n *\n * scopeId uses '__global__' sentinel for global scope to avoid\n * PostgreSQL's NULL != NULL behavior in unique constraints.\n */\nexport const toolkitSettings = pgTable(\n 'toolkit_settings',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n namespace: varchar('namespace', { length: 100 }).notNull(),\n scope: varchar('scope', { length: 20 }).notNull().default('global'),\n scopeId: varchar('scope_id', { length: 100 }).notNull().default('__global__'),\n key: varchar('key', { length: 255 }).notNull(),\n locale: varchar('locale', { length: 10 }).notNull().default('_default'),\n value: jsonb('value'),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n updatedBy: uuid('updated_by'),\n },\n (table) => ({\n uniqueSetting: unique().on(\n table.namespace,\n table.scope,\n table.scopeId,\n table.key,\n table.locale,\n ),\n }),\n)\n\n/**\n * View state table.\n *\n * Stores schemaless user-scoped JSON blobs for persisting\n * UI state (table filters, column order, etc.) with optional TTL.\n */\nexport const toolkitViewState = pgTable(\n 'toolkit_view_state',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n userId: uuid('user_id').notNull(),\n viewKey: varchar('view_key', { length: 255 }).notNull(),\n state: jsonb('state').notNull(),\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => ({\n uniqueUserView: unique().on(table.userId, table.viewKey),\n }),\n)\n"],"mappings":"2GA4BA,MAAa,EAAkB,EAC7B,mBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,UAAW,EAAQ,YAAa,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC1D,MAAO,EAAQ,QAAS,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,SAAS,CACnE,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAAC,QAAQ,aAAa,CAC7E,IAAK,EAAQ,MAAO,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC9C,OAAQ,EAAQ,SAAU,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,WAAW,CACvE,MAAO,EAAM,QAAQ,CACrB,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAAC,SAAS,CAAC,YAAY,CACjF,UAAW,EAAK,aAAa,CAC9B,CACA,IAAW,CACV,cAAe,GAAQ,CAAC,GACtB,EAAM,UACN,EAAM,MACN,EAAM,QACN,EAAM,IACN,EAAM,OACP,CACF,EACF,CAQY,EAAmB,EAC9B,qBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,OAAQ,EAAK,UAAU,CAAC,SAAS,CACjC,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CACvD,MAAO,EAAM,QAAQ,CAAC,SAAS,CAC/B,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAC1D,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAAC,SAAS,CAAC,YAAY,CAClF,CACA,IAAW,CACV,eAAgB,GAAQ,CAAC,GAAG,EAAM,OAAQ,EAAM,QAAQ,CACzD,EACF"}
1
+ {"version":3,"file":"schema.mjs","names":[],"sources":["../src/schema.ts"],"sourcesContent":["/**\n * Drizzle schema for settings tables.\n *\n * Two tables:\n * - toolkit_settings: typed key-value settings grouped by namespace and scope\n * - toolkit_view_state: schemaless user-scoped JSON blobs with optional TTL\n *\n * These tables are registered for migration discovery via the `settings()`\n * plugin's `tables` field. `lumi migrate` picks them up automatically.\n */\n\nimport { jsonb, pgTable, timestamp, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\n/**\n * Typed settings table.\n *\n * Stores key-value pairs grouped by namespace and scoped\n * to global, team, or user contexts.\n *\n * scopeId uses '__global__' sentinel for global scope to avoid\n * PostgreSQL's NULL != NULL behavior in unique constraints.\n */\nexport const toolkitSettings = pgTable(\n 'toolkit_settings',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n namespace: varchar('namespace', { length: 100 }).notNull(),\n scope: varchar('scope', { length: 20 }).notNull().default('global'),\n scopeId: varchar('scope_id', { length: 100 }).notNull().default('__global__'),\n key: varchar('key', { length: 255 }).notNull(),\n locale: varchar('locale', { length: 10 }).notNull().default('_default'),\n value: jsonb('value'),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n updatedBy: uuid('updated_by'),\n },\n (table) => ({\n uniqueSetting: unique().on(\n table.namespace,\n table.scope,\n table.scopeId,\n table.key,\n table.locale,\n ),\n }),\n)\n\n/**\n * View state table.\n *\n * Stores schemaless user-scoped JSON blobs for persisting\n * UI state (table filters, column order, etc.) with optional TTL.\n */\nexport const toolkitViewState = pgTable(\n 'toolkit_view_state',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n userId: uuid('user_id').notNull(),\n viewKey: varchar('view_key', { length: 255 }).notNull(),\n state: jsonb('state').notNull(),\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => ({\n uniqueUserView: unique().on(table.userId, table.viewKey),\n }),\n)\n"],"mappings":"2GAsBA,MAAa,EAAkB,EAC7B,mBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,UAAW,EAAQ,YAAa,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC1D,MAAO,EAAQ,QAAS,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,SAAS,CACnE,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAAC,QAAQ,aAAa,CAC7E,IAAK,EAAQ,MAAO,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC9C,OAAQ,EAAQ,SAAU,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,WAAW,CACvE,MAAO,EAAM,QAAQ,CACrB,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAAC,SAAS,CAAC,YAAY,CACjF,UAAW,EAAK,aAAa,CAC9B,CACA,IAAW,CACV,cAAe,GAAQ,CAAC,GACtB,EAAM,UACN,EAAM,MACN,EAAM,QACN,EAAM,IACN,EAAM,OACP,CACF,EACF,CAQY,EAAmB,EAC9B,qBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,OAAQ,EAAK,UAAU,CAAC,SAAS,CACjC,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CACvD,MAAO,EAAM,QAAQ,CAAC,SAAS,CAC/B,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAC1D,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAAC,SAAS,CAAC,YAAY,CAClF,CACA,IAAW,CACV,eAAgB,GAAQ,CAAC,GAAG,EAAM,OAAQ,EAAM,QAAQ,CACzD,EACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murumets-ee/settings",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,24 +28,24 @@
28
28
  "files": [
29
29
  "dist"
30
30
  ],
31
+ "scripts": {
32
+ "build": "tsdown",
33
+ "dev": "tsdown --watch",
34
+ "test": "vitest",
35
+ "test:integration": "vitest run --config vitest.integration.config.ts"
36
+ },
31
37
  "dependencies": {
38
+ "@murumets-ee/core": "workspace:*",
39
+ "@murumets-ee/db": "workspace:*",
40
+ "@murumets-ee/logging": "workspace:*",
32
41
  "drizzle-orm": "^0.45.1",
33
42
  "zod": "^3.24.1",
34
- "server-only": "^0.0.1",
35
- "@murumets-ee/core": "0.2.0",
36
- "@murumets-ee/db": "0.2.0",
37
- "@murumets-ee/logging": "0.2.0"
43
+ "server-only": "^0.0.1"
38
44
  },
39
45
  "devDependencies": {
40
46
  "@types/node": "^22.10.5",
41
47
  "tsdown": "^0.21.7",
42
48
  "typescript": "^5.7.3",
43
49
  "vitest": "^2.1.8"
44
- },
45
- "scripts": {
46
- "build": "tsdown",
47
- "dev": "tsdown --watch",
48
- "test": "vitest",
49
- "test:integration": "vitest run --config vitest.integration.config.ts"
50
50
  }
51
- }
51
+ }
package/LICENSE DELETED
@@ -1,94 +0,0 @@
1
- Elastic License 2.0 (ELv2)
2
-
3
- URL: https://www.elastic.co/licensing/elastic-license
4
-
5
- ## Acceptance
6
-
7
- By using the software, you agree to all of the terms and conditions below.
8
-
9
- ## Copyright License
10
-
11
- The licensor grants you a non-exclusive, royalty-free, worldwide,
12
- non-sublicensable, non-transferable license to use, copy, distribute, make
13
- available, and prepare derivative works of the software, in each case subject
14
- to the limitations and conditions below.
15
-
16
- ## Limitations
17
-
18
- You may not provide the software to third parties as a hosted or managed
19
- service, where the service provides users with access to any substantial set
20
- of the features or functionality of the software.
21
-
22
- You may not move, change, disable, or circumvent the license key functionality
23
- in the software, and you may not remove or obscure any functionality in the
24
- software that is protected by the license key.
25
-
26
- You may not alter, remove, or obscure any licensing, copyright, or other
27
- notices of the licensor in the software. Any use of the licensor's trademarks
28
- is subject to applicable law.
29
-
30
- ## Patents
31
-
32
- The licensor grants you a license, under any patent claims the licensor can
33
- license, or becomes able to license, to make, have made, use, sell, offer for
34
- sale, import and have imported the software, in each case subject to the
35
- limitations and conditions in this license. This license does not cover any
36
- patent claims that you cause to be infringed by modifications or additions to
37
- the software. If you or your company make any written claim that the software
38
- infringes or contributes to infringement of any patent, your patent license
39
- for the software granted under these terms ends immediately. If your company
40
- makes such a claim, your patent license ends immediately for work on behalf
41
- of your company.
42
-
43
- ## Notices
44
-
45
- You must ensure that anyone who gets a copy of any part of the software from
46
- you also gets a copy of these terms.
47
-
48
- If you modify the software, you must include in any modified copies of the
49
- software prominent notices stating that you have modified the software.
50
-
51
- ## No Other Rights
52
-
53
- These terms do not imply any licenses other than those expressly granted in
54
- these terms.
55
-
56
- ## Termination
57
-
58
- If you use the software in violation of these terms, such use is not licensed,
59
- and your licenses will automatically terminate. If the licensor provides you
60
- with a notice of your violation, and you cease all violation of this license
61
- no later than 30 days after you receive that notice, your licenses will be
62
- reinstated retroactively. However, if you violate these terms after such
63
- reinstatement, any additional violation of these terms will cause your
64
- licenses to terminate automatically and permanently.
65
-
66
- ## No Liability
67
-
68
- As far as the law allows, the software comes as is, without any warranty or
69
- condition, and the licensor will not be liable to you for any damages arising
70
- out of these terms or the use or nature of the software, under any kind of
71
- legal claim.
72
-
73
- ## Definitions
74
-
75
- The **licensor** is the entity offering these terms, and the **software** is
76
- the software the licensor makes available under these terms, including any
77
- portion of it.
78
-
79
- **you** refers to the individual or entity agreeing to these terms.
80
-
81
- **your company** is any legal entity, sole proprietorship, or other kind of
82
- organization that you work for, plus all organizations that have control over,
83
- are under the control of, or are under common control with that organization.
84
- **control** means ownership of substantially all the assets of an entity, or
85
- the power to direct the management and policies of an entity (for example, by
86
- voting right, contract, or otherwise). Control can be direct or indirect.
87
-
88
- **your licenses** are all the licenses granted to you for the software under
89
- these terms.
90
-
91
- **use** means anything you do with the software requiring one of your
92
- licenses.
93
-
94
- **trademark** means trademarks, service marks, and similar rights.