@murumets-ee/settings 0.2.0 → 0.4.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
+ import{validateLocale as e}from"@murumets-ee/core";function t(e){return e.map(e=>({resource:`settings:${e.namespace}`,actions:[`view`,`update`]}))}function n(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function r(e,t){return n({error:e},t)}function i(e){return{definition:e,clientPromise:null}}async function a(e,t){if(e.definition.scope===`user`){let{getApp:n}=await import(`@murumets-ee/core`),{createSettingsClient:r}=await import(`./client-factory-DBlcuyG0.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-DBlcuyG0.mjs`);return n(e.definition,{app:t()})})(),e.clientPromise}function o(t){let o=Array.isArray(t)?t:[t],s=new Map;for(let e of o)s.set(e.namespace,i(e));async function c(t,i){let o=i.segments[0];if(!o)return r(`Missing settings namespace`,400);let c=s.get(o);if(!c)return r(`Unknown settings namespace: ${o}`,404);if(!i.checkPermission(`settings:${o}`,`view`))return r(`Forbidden: cannot view settings:${o}`,403);let l=new URL(t.url),u;if(c.definition.scope===`user`&&(u=l.searchParams.get(`scopeId`)??i.user.id,u!==i.user.id))return r(`Forbidden: cannot read other users' preferences`,403);let d=await a(c,u),f=e(l.searchParams.get(`locale`));return n(await d.getAll(f?{locale:f}:void 0))}async function l(t,i){let o=i.segments[0];if(!o)return r(`Missing settings namespace`,400);let c=s.get(o);if(!c)return r(`Unknown settings namespace: ${o}`,404);if(!i.checkPermission(`settings:${o}`,`update`))return r(`Forbidden: cannot update settings:${o}`,403);let{values:l,locale:u,scopeId:d}=await t.json(),f=e(u);if(!l||typeof l!=`object`)return r(`Body must contain "values" object`,400);let p;return c.definition.scope===`user`&&(p=d??i.user.id,p!==i.user.id)?r(`Forbidden: cannot update other users' preferences`,403):(await(await a(c,p)).setMany(l,f?{locale:f}:void 0),i.audit?.({action:`settings.update`,entityType:`settings`,userId:i.user.id,userName:i.user.name,changes:{fields:l},metadata:{namespace:o,...f?{locale:f}:{},...p?{scopeId:p}:{}}}),n({success:!0}))}return{prefix:`settings`,actions:[`view`,`update`],handlers:{GET:c,PATCH:l}}}export{t as settingsResources,o 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 { validateLocale } 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// 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":"mDAsBA,SAAgB,EACd,EACyD,CACzD,OAAO,EAAY,IAAK,IAAS,CAC/B,SAAU,YAAY,EAAI,YAC1B,QAAS,CAAC,OAAQ,SAAS,CAC5B,EAAE,CCSL,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,CAYzC,SAAS,EACP,EACmB,CACnB,MAAO,CAAE,aAAY,cAAe,KAAM,CAG5C,eAAe,EACb,EACA,EAC4B,CAE5B,GAAI,EAAM,WAAW,QAAU,OAAQ,CACrC,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,wBAAyB,MAAM,OAAO,iCAC9C,OAAO,EAAqB,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U,CAClC,GAAI,CAAC,EAAO,OAAO,EAAU,+BAA+B,IAAa,IAAI,CAG7E,GAAI,CAAC,EAAI,gBAAgB,YAAY,IAAa,SAAS,CACzD,OAAO,EAAU,qCAAqC,IAAa,IAAI,CAIzE,GAAM,CAAE,SAAQ,OAAQ,EAAW,WADtB,MAAM,EAAI,MAAM,CAMvB,EAAS,EAAe,EAAU,CAExC,GAAI,CAAC,GAAU,OAAO,GAAW,SAC/B,OAAO,EAAU,oCAAqC,IAAI,CAI5D,IAAI,EA2BJ,OA1BI,EAAM,WAAW,QAAU,SAC7B,EAAkB,GAAW,EAAI,KAAK,GAClC,IAAoB,EAAI,KAAK,IACxB,EAAU,oDAAsD,IAAI,EAK/E,MADe,MAAM,EAAU,EAAO,EAAgB,EACzC,QACX,EACA,EAAS,CAAE,SAAQ,CAAG,IAAA,GACvB,CAED,EAAI,QAAQ,CACV,OAAQ,kBACR,WAAY,WACZ,OAAQ,EAAI,KAAK,GACjB,SAAU,EAAI,KAAK,KACnB,QAAS,CAAE,OAAQ,EAAQ,CAC3B,SAAU,CACR,YACA,GAAI,EAAS,CAAE,SAAQ,CAAG,EAAE,CAC5B,GAAI,EAAkB,CAAE,QAAS,EAAiB,CAAG,EAAE,CACxD,CACF,CAAC,CAEK,EAAK,CAAE,QAAS,GAAM,CAAC,EAGhC,MAAO,CACL,OAAQ,WAER,QAAS,CAAC,OAAQ,SAAS,CAC3B,SAAU,CACR,IAAK,EACL,MAAO,EACR,CACF"}
@@ -0,0 +1,2 @@
1
+ import{getApp as e}from"@murumets-ee/core";import{column as t,defineTable as n}from"@murumets-ee/db";import{z as r}from"zod";const i=n({name:`toolkit_settings`,columns:{id:t.uuid({primaryKey:!0,defaultRandom:!0}),namespace:t.varchar({length:100,notNull:!0}),scope:t.varchar({length:20,notNull:!0,default:`global`}),scopeId:t.varchar({length:100,notNull:!0,default:`__global__`,pgName:`scope_id`}),key:t.varchar({length:255,notNull:!0}),locale:t.varchar({length:10,notNull:!0,default:`_default`}),value:t.jsonb(),updatedAt:t.timestamp({notNull:!0,defaultNow:!0,withTimezone:!0,pgName:`updated_at`}),updatedBy:t.uuid({pgName:`updated_by`})},unique:[{on:[`namespace`,`scope`,`scopeId`,`key`,`locale`]}]});i.table,n({name:`toolkit_view_state`,columns:{id:t.uuid({primaryKey:!0,defaultRandom:!0}),userId:t.uuid({notNull:!0,pgName:`user_id`}),viewKey:t.varchar({length:255,notNull:!0,pgName:`view_key`}),state:t.jsonb({notNull:!0}),expiresAt:t.timestamp({withTimezone:!0,pgName:`expires_at`}),updatedAt:t.timestamp({notNull:!0,defaultNow:!0,withTimezone:!0,pgName:`updated_at`})},unique:[{on:[`userId`,`viewKey`]}]}).table;const a=`_default`;function o(e){switch(e.type){case`text`:{let t=r.string();return e.maxLength&&(t=t.max(e.maxLength)),e.minLength&&(t=t.min(e.minLength)),e.pattern&&(t=t.regex(e.pattern)),t}case`number`:{let t=r.number();return e.integer&&(t=t.int()),e.min!==void 0&&(t=t.min(e.min)),e.max!==void 0&&(t=t.max(e.max)),t}case`boolean`:return r.boolean();case`select`:return r.enum(e.options);case`json`:return e.schema??r.unknown();case`media`:return r.string().uuid();default:return r.unknown()}}function s(e){let t={};for(let[n,r]of Object.entries(e.schema)){let e=o(r);`default`in r&&r.default!==void 0||(e=e.nullable()),t[n]=e}return t}var c=class{definition;table;logger;scope;scopeId;validators;constructor(e,t){if(typeof window<`u`)throw Error(`SettingsClient cannot be used in browser code.`);if(this.definition=e,this.table=i.makeClient(t.db),this.logger=t.logger,this.scope=t.scope??e.scope,this.scopeId=t.scopeId??`__global__`,(this.scope===`team`||this.scope===`user`)&&!t.scopeId)throw Error(`scopeId is required for ${this.scope}-scoped settings (namespace: ${e.namespace})`);this.validators=s(e)}async get(e,t){let n=this.definition.schema[e],r=n?.translatable&&t?.locale?t.locale:null;if(this.logger?.debug({namespace:this.definition.namespace,key:e,locale:r},`Getting setting`),r){let t=await this.table.findMany({where:{...this.baseWhere(),key:e,$or:[{locale:r},{locale:a}]},limit:2}),n=t.find(e=>e.locale===r),i=t.find(e=>e.locale===a),o=n??i;if(o&&o.value!==void 0&&o.value!==null)return o.value}else{let t=await this.table.findMany({where:{...this.baseWhere(),key:e,locale:a},limit:1});if(t.length>0&&t[0].value!==void 0&&t[0].value!==null)return t[0].value}return n&&`default`in n&&n.default!==void 0?n.default:null}async getAll(e){let t=e?.locale??null;this.logger?.debug({namespace:this.definition.namespace,locale:t},`Getting all settings`);let n;n=t?await this.table.findMany({where:{...this.baseWhere(),$or:[{locale:a},{locale:t}]},limit:1e3}):await this.table.findMany({where:{...this.baseWhere(),locale:a},limit:1e3});let r=new Map;for(let e of n){let t=r.get(e.key)??{};e.locale===`_default`?t.default=e.value:t.locale=e.value,r.set(e.key,t)}let i={};for(let[e,n]of Object.entries(this.definition.schema)){let a=r.get(e),o;n.translatable&&t&&a?.locale!==void 0&&a?.locale!==null?o=a.locale:a?.default!==void 0&&a?.default!==null&&(o=a.default),o===void 0?`default`in n&&n.default!==void 0?i[e]=n.default:i[e]=null:i[e]=o}return i}async set(e,t,n){let r=this.resolveLocale(e,n);if(this.logger?.info({namespace:this.definition.namespace,key:e,locale:r},`Setting value`),!(e in this.definition.schema))throw Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let i=this.validators[e];i&&i.parse(t),await this.upsertRow(e,t,r,this.table)}async setMany(e,t){this.logger?.info({namespace:this.definition.namespace,keys:Object.keys(e),locale:t?.locale},`Setting multiple values`);for(let[t,n]of Object.entries(e)){if(!(t in this.definition.schema))throw Error(`Unknown setting key '${t}' in namespace '${this.definition.namespace}'`);let e=this.validators[t];e&&n!==void 0&&e.parse(n)}await this.table.transaction(async n=>{for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=this.resolveLocale(r,t);await this.upsertRow(r,i,e,n)}})}async delete(e,t){let n=this.resolveLocale(e,t);this.logger?.info({namespace:this.definition.namespace,key:e,locale:n},`Deleting setting`),await this.table.deleteMany({...this.baseWhere(),key:e,locale:n})}async has(e,t){let n=this.resolveLocale(e,t);return await this.table.exists({...this.baseWhere(),key:e,locale:n})}resolveLocale(e,t){return this.definition.schema[e]?.translatable&&t?.locale?t.locale:a}baseWhere(){return{namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId}}async upsertRow(e,t,n,r){await r.upsert({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:e,locale:n,value:t,updatedAt:new Date},{target:[`namespace`,`scope`,`scopeId`,`key`,`locale`],set:{value:t,updatedAt:new Date}})}};function l(t,n){let r=n?.app??e();return new c(t,{db:r.db.readWrite,logger:r.logger.child({settings:t.namespace}),scope:n?.scope,scopeId:n?.scopeId})}export{l as createSettingsClient};
2
+ //# sourceMappingURL=client-factory-DBlcuyG0.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-factory-DBlcuyG0.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 * Built on `@murumets-ee/db`'s `defineTable` — the raw `pgTable` is still\n * re-exported (via `.table`) for backwards compatibility with existing\n * imports and tests, but all query construction in SettingsClient /\n * ViewStateClient goes through the typed TableClient.\n */\n\nimport { column, defineTable } from '@murumets-ee/db'\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 toolkitSettingsTable = defineTable({\n name: 'toolkit_settings',\n columns: {\n id: column.uuid({ primaryKey: true, defaultRandom: true }),\n namespace: column.varchar({ length: 100, notNull: true }),\n scope: column.varchar({ length: 20, notNull: true, default: 'global' }),\n scopeId: column.varchar({\n length: 100,\n notNull: true,\n default: '__global__',\n pgName: 'scope_id',\n }),\n key: column.varchar({ length: 255, notNull: true }),\n locale: column.varchar({ length: 10, notNull: true, default: '_default' }),\n value: column.jsonb(),\n updatedAt: column.timestamp({\n notNull: true,\n defaultNow: true,\n withTimezone: true,\n pgName: 'updated_at',\n }),\n updatedBy: column.uuid({ pgName: 'updated_by' }),\n },\n unique: [\n { on: ['namespace', 'scope', 'scopeId', 'key', 'locale'] },\n ],\n})\n\n/** Backwards-compatible export — existing imports of the raw pgTable still work. */\nexport const toolkitSettings = toolkitSettingsTable.table\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 toolkitViewStateTable = defineTable({\n name: 'toolkit_view_state',\n columns: {\n id: column.uuid({ primaryKey: true, defaultRandom: true }),\n userId: column.uuid({ notNull: true, pgName: 'user_id' }),\n viewKey: column.varchar({ length: 255, notNull: true, pgName: 'view_key' }),\n state: column.jsonb({ notNull: true }),\n expiresAt: column.timestamp({ withTimezone: true, pgName: 'expires_at' }),\n updatedAt: column.timestamp({\n notNull: true,\n defaultNow: true,\n withTimezone: true,\n pgName: 'updated_at',\n }),\n },\n unique: [\n { on: ['userId', 'viewKey'] },\n ],\n})\n\n/** Backwards-compatible export — existing imports of the raw pgTable still work. */\nexport const toolkitViewState = toolkitViewStateTable.table\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 * All persistence goes through the `toolkit_settings` TableClient\n * (`defineTable`) — no direct Drizzle usage from this module.\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 type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettingsTable } 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\n/** Row shape returned by the settings table (for narrow typing of fetched rows). */\ninterface SettingsRow {\n key: string\n locale: string\n value: unknown\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private table: ReturnType<typeof toolkitSettingsTable.makeClient>\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.table = toolkitSettingsTable.makeClient(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.table.findMany({\n where: {\n ...this.baseWhere(),\n key,\n $or: [{ locale }, { locale: DEFAULT_LOCALE }],\n },\n limit: 2,\n })) as unknown as SettingsRow[]\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.table.findMany({\n where: { ...this.baseWhere(), key, locale: DEFAULT_LOCALE },\n limit: 1,\n })) as unknown as SettingsRow[]\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: SettingsRow[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = (await this.table.findMany({\n where: {\n ...this.baseWhere(),\n $or: [{ locale: DEFAULT_LOCALE }, { locale }],\n },\n limit: 1000,\n })) as unknown as SettingsRow[]\n } else {\n rows = (await this.table.findMany({\n where: { ...this.baseWhere(), locale: DEFAULT_LOCALE },\n limit: 1000,\n })) as unknown as SettingsRow[]\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.upsertRow(key, value as unknown, locale, this.table)\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.table.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 this.upsertRow(key, value as unknown, locale, tx)\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.table.deleteMany({\n ...this.baseWhere(),\n key,\n locale,\n })\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 return await this.table.exists({\n ...this.baseWhere(),\n key,\n locale,\n })\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 namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n }\n }\n\n /**\n * Upsert a single setting row via the TableClient.\n * Accepts either the top-level table client or a transactional one —\n * same shape, used inside `setMany`'s transaction.\n */\n private async upsertRow(\n key: string,\n value: unknown,\n locale: string,\n tableClient: ReturnType<typeof toolkitSettingsTable.makeClient>,\n ) {\n await tableClient.upsert(\n {\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 {\n target: ['namespace', 'scope', 'scopeId', 'key', 'locale'],\n set: {\n value,\n updatedAt: new Date(),\n },\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":"6HA2BA,MAAa,EAAuB,EAAY,CAC9C,KAAM,mBACN,QAAS,CACP,GAAI,EAAO,KAAK,CAAE,WAAY,GAAM,cAAe,GAAM,CAAC,CAC1D,UAAW,EAAO,QAAQ,CAAE,OAAQ,IAAK,QAAS,GAAM,CAAC,CACzD,MAAO,EAAO,QAAQ,CAAE,OAAQ,GAAI,QAAS,GAAM,QAAS,SAAU,CAAC,CACvE,QAAS,EAAO,QAAQ,CACtB,OAAQ,IACR,QAAS,GACT,QAAS,aACT,OAAQ,WACT,CAAC,CACF,IAAK,EAAO,QAAQ,CAAE,OAAQ,IAAK,QAAS,GAAM,CAAC,CACnD,OAAQ,EAAO,QAAQ,CAAE,OAAQ,GAAI,QAAS,GAAM,QAAS,WAAY,CAAC,CAC1E,MAAO,EAAO,OAAO,CACrB,UAAW,EAAO,UAAU,CAC1B,QAAS,GACT,WAAY,GACZ,aAAc,GACd,OAAQ,aACT,CAAC,CACF,UAAW,EAAO,KAAK,CAAE,OAAQ,aAAc,CAAC,CACjD,CACD,OAAQ,CACN,CAAE,GAAI,CAAC,YAAa,QAAS,UAAW,MAAO,SAAS,CAAE,CAC3D,CACF,CAAC,CAG6B,EAAqB,MAQf,EAAY,CAC/C,KAAM,qBACN,QAAS,CACP,GAAI,EAAO,KAAK,CAAE,WAAY,GAAM,cAAe,GAAM,CAAC,CAC1D,OAAQ,EAAO,KAAK,CAAE,QAAS,GAAM,OAAQ,UAAW,CAAC,CACzD,QAAS,EAAO,QAAQ,CAAE,OAAQ,IAAK,QAAS,GAAM,OAAQ,WAAY,CAAC,CAC3E,MAAO,EAAO,MAAM,CAAE,QAAS,GAAM,CAAC,CACtC,UAAW,EAAO,UAAU,CAA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GAAG,KAAK,WAAW,CACnB,MACA,SACD,CAAC,CAYJ,cAAsB,EAAa,EAAgC,CAKjE,OAJe,KAAK,WAAW,OAAO,IAC1B,cAAgB,GAAS,OAC5B,EAAQ,OAEV,EAIT,WAAoB,CAClB,MAAO,CACL,UAAW,KAAK,WAAW,UAC3B,MAAO,KAAK,MACZ,QAAS,KAAK,QACf,CAQH,MAAc,UACZ,EACA,EACA,EACA,EACA,CACA,MAAM,EAAY,OAChB,CACE,UAAW,KAAK,WAAW,UAC3B,MAAO,KAAK,MACZ,QAAS,KAAK,QACd,MACA,SACA,QACA,UAAW,IAAI,KAChB,CACD,CACE,OAAQ,CAAC,YAAa,QAAS,UAAW,MAAO,SAAS,CAC1D,IAAK,CACH,QACA,UAAW,IAAI,KAChB,CACF,CACF,GCrUL,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;
@@ -130,7 +133,7 @@ interface LocaleOption {
130
133
  }
131
134
  declare class SettingsClient<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {
132
135
  private definition;
133
- private db;
136
+ private table;
134
137
  private logger?;
135
138
  private scope;
136
139
  private scopeId;
@@ -181,12 +184,14 @@ declare class SettingsClient<S extends Record<string, SettingConfig> = Record<st
181
184
  * Translatable settings use the requested locale or DEFAULT_LOCALE.
182
185
  */
183
186
  private resolveLocale;
184
- /** Base where conditions: namespace + scope + scopeId */
187
+ /** Base where conditions: namespace + scope + scopeId. */
185
188
  private baseWhere;
186
- /** Full where clause for a specific key + locale */
187
- private whereClause;
188
- /** Upsert a single setting row */
189
- private upsert;
189
+ /**
190
+ * Upsert a single setting row via the TableClient.
191
+ * Accepts either the top-level table client or a transactional one
192
+ * same shape, used inside `setMany`'s transaction.
193
+ */
194
+ private upsertRow;
190
195
  }
191
196
  //#endregion
192
197
  //#region src/client-factory.d.ts
@@ -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,UA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AAA,0BAAgC,CAAA,CAAA,CAAG,GAAA,EAAK,CAAA,EAAG,OAAA,GAAU,YAAA,GAAe,OAAA;EFrP3D;;;EEgQT,GAAA,0BAA6B,CAAA,CAAA,CAAG,GAAA,EAAK,CAAA,EAAG,OAAA,GAAU,YAAA,GAAe,OAAA;EFhQ7B;;;;;EAAA,QEqRlC,aAAA;EFhRe;EAAA,QEyRf,SAAA;EFxRN;EAAA,QEiSM,WAAA;EF/RN;EAAA,QEwSY,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
+ {"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;EAC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AAA,CAAE,CAAA,IAC3B,OAAA,GAAU,YAAA,GACT,OAAA;EFzKoE;;;;;;;EEiMjE,OAAA,CAAQ,MAAA,EAAQ,OAAA,CAAQ,gBAAA,CAAiB,CAAA,IAAK,OAAA,GAAU,YAAA,GAAe,OAAA;EF7L5D;;;AAGnB;EEwNQ,MAAA,0BAAgC,CAAA,CAAA,CAAG,GAAA,EAAK,CAAA,EAAG,OAAA,GAAU,YAAA,GAAe,OAAA;;;;EAepE,GAAA,0BAA6B,CAAA,CAAA,CAAG,GAAA,EAAK,CAAA,EAAG,OAAA,GAAU,YAAA,GAAe,OAAA;EFrOvE;;;;AAIF;EAJE,QEwPQ,aAAA;;UASA,SAAA;EF3PN;;;;;EAAA,QEwQY,SAAA;AAAA;;;UCnUC,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"}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{toolkitSettings as e}from"./schema.mjs";import"server-only";import{and as t,eq as n,or as r}from"drizzle-orm";import{z as i}from"zod";import{getApp as a}from"@murumets-ee/core";const o={text:e=>({type:`text`,...e}),number:e=>({type:`number`,...e}),boolean:e=>({type:`boolean`,...e}),select:e=>({type:`select`,...e}),json:e=>({type:`json`,...e}),media:e=>({type:`media`,...e})},s=`__global__`,c=`_default`;function l(e){switch(e.type){case`text`:{let t=i.string();return e.maxLength&&(t=t.max(e.maxLength)),e.minLength&&(t=t.min(e.minLength)),e.pattern&&(t=t.regex(e.pattern)),t}case`number`:{let t=i.number();return e.integer&&(t=t.int()),e.min!==void 0&&(t=t.min(e.min)),e.max!==void 0&&(t=t.max(e.max)),t}case`boolean`:return i.boolean();case`select`:return i.enum(e.options);case`json`:return e.schema??i.unknown();case`media`:return i.string().uuid();default:return i.unknown()}}function u(e){let t={};for(let[n,r]of Object.entries(e.schema)){let e=l(r);`default`in r&&r.default!==void 0||(e=e.nullable()),t[n]=e}return t}var d=class{definition;db;logger;scope;scopeId;validators;constructor(e,t){if(typeof window<`u`)throw Error(`SettingsClient cannot be used in browser code.`);if(this.definition=e,this.db=t.db,this.logger=t.logger,this.scope=t.scope??e.scope,this.scopeId=t.scopeId??`__global__`,(this.scope===`team`||this.scope===`user`)&&!t.scopeId)throw Error(`scopeId is required for ${this.scope}-scoped settings (namespace: ${e.namespace})`);this.validators=u(e)}async get(i,a){let o=this.definition.schema[i],s=o?.translatable&&a?.locale?a.locale:null;if(this.logger?.debug({namespace:this.definition.namespace,key:i,locale:s},`Getting setting`),s){let a=await this.db.select({locale:e.locale,value:e.value}).from(e).where(t(...this.baseWhere(),n(e.key,i),r(n(e.locale,s),n(e.locale,c)))),o=a.find(e=>e.locale===s),l=a.find(e=>e.locale===c),u=o??l;if(u&&u.value!==void 0&&u.value!==null)return u.value}else{let t=await this.db.select({value:e.value}).from(e).where(this.whereClause(i)).limit(1);if(t.length>0&&t[0].value!==void 0&&t[0].value!==null)return t[0].value}return o&&`default`in o&&o.default!==void 0?o.default:null}async getAll(i){let a=i?.locale??null;this.logger?.debug({namespace:this.definition.namespace,locale:a},`Getting all settings`);let o;o=a?await this.db.select({key:e.key,locale:e.locale,value:e.value}).from(e).where(t(...this.baseWhere(),r(n(e.locale,c),n(e.locale,a)))):await this.db.select({key:e.key,locale:e.locale,value:e.value}).from(e).where(t(...this.baseWhere(),n(e.locale,c)));let s=new Map;for(let e of o){let t=s.get(e.key)??{};e.locale===`_default`?t.default=e.value:t.locale=e.value,s.set(e.key,t)}let l={};for(let[e,t]of Object.entries(this.definition.schema)){let n=s.get(e),r;t.translatable&&a&&n?.locale!==void 0&&n?.locale!==null?r=n.locale:n?.default!==void 0&&n?.default!==null&&(r=n.default),r===void 0?`default`in t&&t.default!==void 0?l[e]=t.default:l[e]=null:l[e]=r}return l}async set(e,t,n){let r=this.resolveLocale(e,n);if(this.logger?.info({namespace:this.definition.namespace,key:e,locale:r},`Setting value`),!(e in this.definition.schema))throw Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let i=this.validators[e];i&&i.parse(t),await this.upsert(e,t,r)}async setMany(t,n){this.logger?.info({namespace:this.definition.namespace,keys:Object.keys(t),locale:n?.locale},`Setting multiple values`);for(let[e,n]of Object.entries(t)){if(!(e in this.definition.schema))throw Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let t=this.validators[e];t&&n!==void 0&&t.parse(n)}await this.db.transaction(async r=>{for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let t=this.resolveLocale(i,n);await r.insert(e).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:i,locale:t,value:a,updatedAt:new Date}).onConflictDoUpdate({target:[e.namespace,e.scope,e.scopeId,e.key,e.locale],set:{value:a,updatedAt:new Date}})}})}async delete(t,n){let r=this.resolveLocale(t,n);this.logger?.info({namespace:this.definition.namespace,key:t,locale:r},`Deleting setting`),await this.db.delete(e).where(this.whereClause(t,r))}async has(t,n){let r=this.resolveLocale(t,n);return(await this.db.select({key:e.key}).from(e).where(this.whereClause(t,r)).limit(1)).length>0}resolveLocale(e,t){return this.definition.schema[e]?.translatable&&t?.locale?t.locale:c}baseWhere(){return[n(e.namespace,this.definition.namespace),n(e.scope,this.scope),n(e.scopeId,this.scopeId)]}whereClause(r,i=c){return t(...this.baseWhere(),n(e.key,r),n(e.locale,i))}async upsert(t,n,r){await this.db.insert(e).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:t,locale:r,value:n,updatedAt:new Date}).onConflictDoUpdate({target:[e.namespace,e.scope,e.scopeId,e.key,e.locale],set:{value:n,updatedAt:new Date}})}};function f(e,t){let n=t?.app??a();return new d(e,{db:n.db.readWrite,logger:n.logger.child({settings:e.namespace}),scope:t?.scope,scopeId:t?.scopeId})}function p(e){if(!e.namespace)throw Error(`Settings namespace is required`);if(!e.schema||Object.keys(e.schema).length===0)throw Error(`Settings schema must have at least one setting`);return e}export{c as DEFAULT_LOCALE,s as GLOBAL_SCOPE_ID,d as SettingsClient,f as createSettingsClient,p as defineSettings,o as setting};
1
+ import{toolkitSettingsTable as e}from"./schema.mjs";import"server-only";import{z as t}from"zod";import{getApp as n}from"@murumets-ee/core";const r={text:e=>({type:`text`,...e}),number:e=>({type:`number`,...e}),boolean:e=>({type:`boolean`,...e}),select:e=>({type:`select`,...e}),json:e=>({type:`json`,...e}),media:e=>({type:`media`,...e})},i=`__global__`,a=`_default`;function o(e){switch(e.type){case`text`:{let n=t.string();return e.maxLength&&(n=n.max(e.maxLength)),e.minLength&&(n=n.min(e.minLength)),e.pattern&&(n=n.regex(e.pattern)),n}case`number`:{let n=t.number();return e.integer&&(n=n.int()),e.min!==void 0&&(n=n.min(e.min)),e.max!==void 0&&(n=n.max(e.max)),n}case`boolean`:return t.boolean();case`select`:return t.enum(e.options);case`json`:return e.schema??t.unknown();case`media`:return t.string().uuid();default:return t.unknown()}}function s(e){let t={};for(let[n,r]of Object.entries(e.schema)){let e=o(r);`default`in r&&r.default!==void 0||(e=e.nullable()),t[n]=e}return t}var c=class{definition;table;logger;scope;scopeId;validators;constructor(t,n){if(typeof window<`u`)throw Error(`SettingsClient cannot be used in browser code.`);if(this.definition=t,this.table=e.makeClient(n.db),this.logger=n.logger,this.scope=n.scope??t.scope,this.scopeId=n.scopeId??`__global__`,(this.scope===`team`||this.scope===`user`)&&!n.scopeId)throw Error(`scopeId is required for ${this.scope}-scoped settings (namespace: ${t.namespace})`);this.validators=s(t)}async get(e,t){let n=this.definition.schema[e],r=n?.translatable&&t?.locale?t.locale:null;if(this.logger?.debug({namespace:this.definition.namespace,key:e,locale:r},`Getting setting`),r){let t=await this.table.findMany({where:{...this.baseWhere(),key:e,$or:[{locale:r},{locale:a}]},limit:2}),n=t.find(e=>e.locale===r),i=t.find(e=>e.locale===a),o=n??i;if(o&&o.value!==void 0&&o.value!==null)return o.value}else{let t=await this.table.findMany({where:{...this.baseWhere(),key:e,locale:a},limit:1});if(t.length>0&&t[0].value!==void 0&&t[0].value!==null)return t[0].value}return n&&`default`in n&&n.default!==void 0?n.default:null}async getAll(e){let t=e?.locale??null;this.logger?.debug({namespace:this.definition.namespace,locale:t},`Getting all settings`);let n;n=t?await this.table.findMany({where:{...this.baseWhere(),$or:[{locale:a},{locale:t}]},limit:1e3}):await this.table.findMany({where:{...this.baseWhere(),locale:a},limit:1e3});let r=new Map;for(let e of n){let t=r.get(e.key)??{};e.locale===`_default`?t.default=e.value:t.locale=e.value,r.set(e.key,t)}let i={};for(let[e,n]of Object.entries(this.definition.schema)){let a=r.get(e),o;n.translatable&&t&&a?.locale!==void 0&&a?.locale!==null?o=a.locale:a?.default!==void 0&&a?.default!==null&&(o=a.default),o===void 0?`default`in n&&n.default!==void 0?i[e]=n.default:i[e]=null:i[e]=o}return i}async set(e,t,n){let r=this.resolveLocale(e,n);if(this.logger?.info({namespace:this.definition.namespace,key:e,locale:r},`Setting value`),!(e in this.definition.schema))throw Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let i=this.validators[e];i&&i.parse(t),await this.upsertRow(e,t,r,this.table)}async setMany(e,t){this.logger?.info({namespace:this.definition.namespace,keys:Object.keys(e),locale:t?.locale},`Setting multiple values`);for(let[t,n]of Object.entries(e)){if(!(t in this.definition.schema))throw Error(`Unknown setting key '${t}' in namespace '${this.definition.namespace}'`);let e=this.validators[t];e&&n!==void 0&&e.parse(n)}await this.table.transaction(async n=>{for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=this.resolveLocale(r,t);await this.upsertRow(r,i,e,n)}})}async delete(e,t){let n=this.resolveLocale(e,t);this.logger?.info({namespace:this.definition.namespace,key:e,locale:n},`Deleting setting`),await this.table.deleteMany({...this.baseWhere(),key:e,locale:n})}async has(e,t){let n=this.resolveLocale(e,t);return await this.table.exists({...this.baseWhere(),key:e,locale:n})}resolveLocale(e,t){return this.definition.schema[e]?.translatable&&t?.locale?t.locale:a}baseWhere(){return{namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId}}async upsertRow(e,t,n,r){await r.upsert({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:e,locale:n,value:t,updatedAt:new Date},{target:[`namespace`,`scope`,`scopeId`,`key`,`locale`],set:{value:t,updatedAt:new Date}})}};function l(e,t){let r=t?.app??n();return new c(e,{db:r.db.readWrite,logger:r.logger.child({settings:e.namespace}),scope:t?.scope,scopeId:t?.scopeId})}function u(e){if(!e.namespace)throw Error(`Settings namespace is required`);if(!e.schema||Object.keys(e.schema).length===0)throw Error(`Settings schema must have at least one setting`);return e}export{a as DEFAULT_LOCALE,i as GLOBAL_SCOPE_ID,c as SettingsClient,l as createSettingsClient,u as defineSettings,r as setting};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -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,IACgC,CAAE,KAAM,SAAU,GAAG,EAAQ,EAU/D,KACE,IAC8B,CAAE,KAAM,OAAQ,GAAG,EAAQ,EAM3D,MACE,IAC4B,CAAE,KAAM,QAAS,GAAG,EAAQ,EAC3D,CC2CY,EAAkB,aAGlB,EAAiB,WClH9B,SAAgB,EAAa,EAAkC,CAC7D,OAAQ,EAAO,KAAf,CACE,IAAK,OAAQ,CACX,IAAI,EAAsB,EAAE,QAAQ,CAIpC,OAHI,EAAO,YAAW,EAAS,EAAO,IAAI,EAAO,UAAU,EACvD,EAAO,YAAW,EAAS,EAAO,IAAI,EAAO,UAAU,EACvD,EAAO,UAAS,EAAS,EAAO,MAAM,EAAO,QAAQ,EAClD,EAGT,IAAK,SAAU,CACb,IAAI,EAAsB,EAAE,QAAQ,CAIpC,OAHI,EAAO,UAAS,EAAS,EAAO,KAAK,EACrC,EAAO,MAAQ,IAAA,KAAW,EAAS,EAAO,IAAI,EAAO,IAAI,EACzD,EAAO,MAAQ,IAAA,KAAW,EAAS,EAAO,IAAI,EAAO,IAAI,EACtD,EAGT,IAAK,UACH,OAAO,EAAE,SAAS,CAEpB,IAAK,SACH,OAAO,EAAE,KAAK,EAAO,QAAiC,CAExD,IAAK,OACH,OAAO,EAAO,QAAU,EAAE,SAAS,CAErC,IAAK,QACH,OAAO,EAAE,QAAQ,CAAC,MAAM,CAE1B,QACE,OAAO,EAAE,SAAS,EAWxB,SAAgB,EACd,EAC2B,CAC3B,IAAM,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,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,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 * All persistence goes through the `toolkit_settings` TableClient\n * (`defineTable`) — no direct Drizzle usage from this module.\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 type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettingsTable } 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\n/** Row shape returned by the settings table (for narrow typing of fetched rows). */\ninterface SettingsRow {\n key: string\n locale: string\n value: unknown\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private table: ReturnType<typeof toolkitSettingsTable.makeClient>\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.table = toolkitSettingsTable.makeClient(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.table.findMany({\n where: {\n ...this.baseWhere(),\n key,\n $or: [{ locale }, { locale: DEFAULT_LOCALE }],\n },\n limit: 2,\n })) as unknown as SettingsRow[]\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.table.findMany({\n where: { ...this.baseWhere(), key, locale: DEFAULT_LOCALE },\n limit: 1,\n })) as unknown as SettingsRow[]\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: SettingsRow[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = (await this.table.findMany({\n where: {\n ...this.baseWhere(),\n $or: [{ locale: DEFAULT_LOCALE }, { locale }],\n },\n limit: 1000,\n })) as unknown as SettingsRow[]\n } else {\n rows = (await this.table.findMany({\n where: { ...this.baseWhere(), locale: DEFAULT_LOCALE },\n limit: 1000,\n })) as unknown as SettingsRow[]\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.upsertRow(key, value as unknown, locale, this.table)\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.table.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 this.upsertRow(key, value as unknown, locale, tx)\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.table.deleteMany({\n ...this.baseWhere(),\n key,\n locale,\n })\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 return await this.table.exists({\n ...this.baseWhere(),\n key,\n locale,\n })\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 namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n }\n }\n\n /**\n * Upsert a single setting row via the TableClient.\n * Accepts either the top-level table client or a transactional one —\n * same shape, used inside `setMany`'s transaction.\n */\n private async upsertRow(\n key: string,\n value: unknown,\n locale: string,\n tableClient: ReturnType<typeof toolkitSettingsTable.makeClient>,\n ) {\n await tableClient.upsert(\n {\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 {\n target: ['namespace', 'scope', 'scopeId', 'key', 'locale'],\n set: {\n value,\n updatedAt: new Date(),\n },\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":"2IAmBA,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,IACgC,CAAE,KAAM,SAAU,GAAG,EAAQ,EAU/D,K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,OAAO,IAC1B,cAAgB,GAAS,OAC5B,EAAQ,OAEV,EAIT,WAAoB,CAClB,MAAO,CACL,UAAW,KAAK,WAAW,UAC3B,MAAO,KAAK,MACZ,QAAS,KAAK,QACf,CAQH,MAAc,UACZ,EACA,EACA,EACA,EACA,CACA,MAAM,EAAY,OAChB,CACE,UAAW,KAAK,WAAW,UAC3B,MAAO,KAAK,MACZ,QAAS,KAAK,QACd,MACA,SACA,QACA,UAAW,IAAI,KAChB,CACD,CACE,OAAQ,CAAC,YAAa,QAAS,UAAW,MAAO,SAAS,CAC1D,IAAK,CACH,QACA,UAAW,IAAI,KAChB,CACF,CACF,GCrUL,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
@@ -1,3 +1,6 @@
1
+ import * as _$_murumets_ee_db0 from "@murumets-ee/db";
2
+ import * as _$drizzle_orm0 from "drizzle-orm";
3
+ import * as _$drizzle_orm_postgres_js0 from "drizzle-orm/postgres-js";
1
4
  import * as _$drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
2
5
 
3
6
  //#region src/schema.d.ts
@@ -8,14 +11,13 @@ import * as _$drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
8
11
  * - toolkit_settings: typed key-value settings grouped by namespace and scope
9
12
  * - toolkit_view_state: schemaless user-scoped JSON blobs with optional TTL
10
13
  *
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
- * ```
14
+ * These tables are registered for migration discovery via the `settings()`
15
+ * plugin's `tables` field. `lumi migrate` picks them up automatically.
16
+ *
17
+ * Built on `@murumets-ee/db`'s `defineTable` — the raw `pgTable` is still
18
+ * re-exported (via `.table`) for backwards compatibility with existing
19
+ * imports and tests, but all query construction in SettingsClient /
20
+ * ViewStateClient goes through the typed TableClient.
19
21
  */
20
22
  /**
21
23
  * Typed settings table.
@@ -26,127 +28,89 @@ import * as _$drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
26
28
  * scopeId uses '__global__' sentinel for global scope to avoid
27
29
  * PostgreSQL's NULL != NULL behavior in unique constraints.
28
30
  */
31
+ declare const toolkitSettingsTable: {
32
+ table: _$drizzle_orm_pg_core0.PgTableWithColumns<{
33
+ name: string;
34
+ schema: undefined;
35
+ columns: {
36
+ [x: string]: _$drizzle_orm_pg_core0.PgColumn<{
37
+ name: string;
38
+ tableName: string;
39
+ dataType: _$drizzle_orm0.ColumnDataType;
40
+ columnType: string;
41
+ data: unknown;
42
+ driverParam: unknown;
43
+ notNull: false;
44
+ hasDefault: false;
45
+ isPrimaryKey: false;
46
+ isAutoincrement: false;
47
+ hasRuntimeDefault: false;
48
+ enumValues: string[] | undefined;
49
+ baseColumn: never;
50
+ identity: undefined;
51
+ generated: undefined;
52
+ }, {}, {}>;
53
+ };
54
+ dialect: "pg";
55
+ }>;
56
+ schema: _$_murumets_ee_db0.TableDefinition<{
57
+ readonly id: _$_murumets_ee_db0.ColumnFactory<string, "uuid", true, true>;
58
+ readonly namespace: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, false>;
59
+ readonly scope: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, true>;
60
+ readonly scopeId: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, true>;
61
+ readonly key: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, false>;
62
+ readonly locale: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, true>;
63
+ readonly value: _$_murumets_ee_db0.ColumnFactory<unknown, "jsonb", false, false>;
64
+ readonly updatedAt: _$_murumets_ee_db0.ColumnFactory<Date, "timestamp", true, true>;
65
+ readonly updatedBy: _$_murumets_ee_db0.ColumnFactory<string, "uuid", false, false>;
66
+ }>;
67
+ columnKinds: Readonly<Record<string, _$_murumets_ee_db0.ColumnKind>>;
68
+ primaryKeyColumns: readonly string[];
69
+ makeClient: (db: _$drizzle_orm_postgres_js0.PostgresJsDatabase) => _$_murumets_ee_db0.TableClient<{
70
+ readonly id: _$_murumets_ee_db0.ColumnFactory<string, "uuid", true, true>;
71
+ readonly namespace: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, false>;
72
+ readonly scope: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, true>;
73
+ readonly scopeId: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, true>;
74
+ readonly key: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, false>;
75
+ readonly locale: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, true>;
76
+ readonly value: _$_murumets_ee_db0.ColumnFactory<unknown, "jsonb", false, false>;
77
+ readonly updatedAt: _$_murumets_ee_db0.ColumnFactory<Date, "timestamp", true, true>;
78
+ readonly updatedBy: _$_murumets_ee_db0.ColumnFactory<string, "uuid", false, false>;
79
+ }, _$drizzle_orm_pg_core0.PgTableWithColumns<{
80
+ name: string;
81
+ schema: undefined;
82
+ columns: {
83
+ [x: string]: _$drizzle_orm_pg_core0.PgColumn<{
84
+ name: string;
85
+ tableName: string;
86
+ dataType: _$drizzle_orm0.ColumnDataType;
87
+ columnType: string;
88
+ data: unknown;
89
+ driverParam: unknown;
90
+ notNull: false;
91
+ hasDefault: false;
92
+ isPrimaryKey: false;
93
+ isAutoincrement: false;
94
+ hasRuntimeDefault: false;
95
+ enumValues: string[] | undefined;
96
+ baseColumn: never;
97
+ identity: undefined;
98
+ generated: undefined;
99
+ }, {}, {}>;
100
+ };
101
+ dialect: "pg";
102
+ }>>;
103
+ };
104
+ /** Backwards-compatible export — existing imports of the raw pgTable still work. */
29
105
  declare const toolkitSettings: _$drizzle_orm_pg_core0.PgTableWithColumns<{
30
- name: "toolkit_settings";
106
+ name: string;
31
107
  schema: undefined;
32
108
  columns: {
33
- id: _$drizzle_orm_pg_core0.PgColumn<{
34
- name: "id";
35
- tableName: "toolkit_settings";
36
- dataType: "string";
37
- columnType: "PgUUID";
38
- data: string;
39
- driverParam: string;
40
- notNull: true;
41
- hasDefault: true;
42
- isPrimaryKey: true;
43
- isAutoincrement: false;
44
- hasRuntimeDefault: false;
45
- enumValues: undefined;
46
- baseColumn: never;
47
- identity: undefined;
48
- generated: undefined;
49
- }, {}, {}>;
50
- namespace: _$drizzle_orm_pg_core0.PgColumn<{
51
- name: "namespace";
52
- tableName: "toolkit_settings";
53
- dataType: "string";
54
- columnType: "PgVarchar";
55
- data: string;
56
- driverParam: string;
57
- notNull: true;
58
- hasDefault: false;
59
- isPrimaryKey: false;
60
- isAutoincrement: false;
61
- hasRuntimeDefault: false;
62
- enumValues: [string, ...string[]];
63
- baseColumn: never;
64
- identity: undefined;
65
- generated: undefined;
66
- }, {}, {
67
- length: 100;
68
- }>;
69
- scope: _$drizzle_orm_pg_core0.PgColumn<{
70
- name: "scope";
71
- tableName: "toolkit_settings";
72
- dataType: "string";
73
- columnType: "PgVarchar";
74
- data: string;
75
- driverParam: string;
76
- notNull: true;
77
- hasDefault: true;
78
- isPrimaryKey: false;
79
- isAutoincrement: false;
80
- hasRuntimeDefault: false;
81
- enumValues: [string, ...string[]];
82
- baseColumn: never;
83
- identity: undefined;
84
- generated: undefined;
85
- }, {}, {
86
- length: 20;
87
- }>;
88
- scopeId: _$drizzle_orm_pg_core0.PgColumn<{
89
- name: "scope_id";
90
- tableName: "toolkit_settings";
91
- dataType: "string";
92
- columnType: "PgVarchar";
93
- data: string;
94
- driverParam: string;
95
- notNull: true;
96
- hasDefault: true;
97
- isPrimaryKey: false;
98
- isAutoincrement: false;
99
- hasRuntimeDefault: false;
100
- enumValues: [string, ...string[]];
101
- baseColumn: never;
102
- identity: undefined;
103
- generated: undefined;
104
- }, {}, {
105
- length: 100;
106
- }>;
107
- key: _$drizzle_orm_pg_core0.PgColumn<{
108
- name: "key";
109
- tableName: "toolkit_settings";
110
- dataType: "string";
111
- columnType: "PgVarchar";
112
- data: string;
113
- driverParam: string;
114
- notNull: true;
115
- hasDefault: false;
116
- isPrimaryKey: false;
117
- isAutoincrement: false;
118
- hasRuntimeDefault: false;
119
- enumValues: [string, ...string[]];
120
- baseColumn: never;
121
- identity: undefined;
122
- generated: undefined;
123
- }, {}, {
124
- length: 255;
125
- }>;
126
- locale: _$drizzle_orm_pg_core0.PgColumn<{
127
- name: "locale";
128
- tableName: "toolkit_settings";
129
- dataType: "string";
130
- columnType: "PgVarchar";
131
- data: string;
132
- driverParam: string;
133
- notNull: true;
134
- hasDefault: true;
135
- isPrimaryKey: false;
136
- isAutoincrement: false;
137
- hasRuntimeDefault: false;
138
- enumValues: [string, ...string[]];
139
- baseColumn: never;
140
- identity: undefined;
141
- generated: undefined;
142
- }, {}, {
143
- length: 10;
144
- }>;
145
- value: _$drizzle_orm_pg_core0.PgColumn<{
146
- name: "value";
147
- tableName: "toolkit_settings";
148
- dataType: "json";
149
- columnType: "PgJsonb";
109
+ [x: string]: _$drizzle_orm_pg_core0.PgColumn<{
110
+ name: string;
111
+ tableName: string;
112
+ dataType: _$drizzle_orm0.ColumnDataType;
113
+ columnType: string;
150
114
  data: unknown;
151
115
  driverParam: unknown;
152
116
  notNull: false;
@@ -154,41 +118,7 @@ declare const toolkitSettings: _$drizzle_orm_pg_core0.PgTableWithColumns<{
154
118
  isPrimaryKey: false;
155
119
  isAutoincrement: false;
156
120
  hasRuntimeDefault: false;
157
- enumValues: undefined;
158
- baseColumn: never;
159
- identity: undefined;
160
- generated: undefined;
161
- }, {}, {}>;
162
- updatedAt: _$drizzle_orm_pg_core0.PgColumn<{
163
- name: "updated_at";
164
- tableName: "toolkit_settings";
165
- dataType: "date";
166
- columnType: "PgTimestamp";
167
- data: Date;
168
- driverParam: string;
169
- notNull: true;
170
- hasDefault: true;
171
- isPrimaryKey: false;
172
- isAutoincrement: false;
173
- hasRuntimeDefault: false;
174
- enumValues: undefined;
175
- baseColumn: never;
176
- identity: undefined;
177
- generated: undefined;
178
- }, {}, {}>;
179
- updatedBy: _$drizzle_orm_pg_core0.PgColumn<{
180
- name: "updated_by";
181
- tableName: "toolkit_settings";
182
- dataType: "string";
183
- columnType: "PgUUID";
184
- data: string;
185
- driverParam: string;
186
- notNull: false;
187
- hasDefault: false;
188
- isPrimaryKey: false;
189
- isAutoincrement: false;
190
- hasRuntimeDefault: false;
191
- enumValues: undefined;
121
+ enumValues: string[] | undefined;
192
122
  baseColumn: never;
193
123
  identity: undefined;
194
124
  generated: undefined;
@@ -202,110 +132,91 @@ declare const toolkitSettings: _$drizzle_orm_pg_core0.PgTableWithColumns<{
202
132
  * Stores schemaless user-scoped JSON blobs for persisting
203
133
  * UI state (table filters, column order, etc.) with optional TTL.
204
134
  */
135
+ declare const toolkitViewStateTable: {
136
+ table: _$drizzle_orm_pg_core0.PgTableWithColumns<{
137
+ name: string;
138
+ schema: undefined;
139
+ columns: {
140
+ [x: string]: _$drizzle_orm_pg_core0.PgColumn<{
141
+ name: string;
142
+ tableName: string;
143
+ dataType: _$drizzle_orm0.ColumnDataType;
144
+ columnType: string;
145
+ data: unknown;
146
+ driverParam: unknown;
147
+ notNull: false;
148
+ hasDefault: false;
149
+ isPrimaryKey: false;
150
+ isAutoincrement: false;
151
+ hasRuntimeDefault: false;
152
+ enumValues: string[] | undefined;
153
+ baseColumn: never;
154
+ identity: undefined;
155
+ generated: undefined;
156
+ }, {}, {}>;
157
+ };
158
+ dialect: "pg";
159
+ }>;
160
+ schema: _$_murumets_ee_db0.TableDefinition<{
161
+ readonly id: _$_murumets_ee_db0.ColumnFactory<string, "uuid", true, true>;
162
+ readonly userId: _$_murumets_ee_db0.ColumnFactory<string, "uuid", true, false>;
163
+ readonly viewKey: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, false>;
164
+ readonly state: _$_murumets_ee_db0.ColumnFactory<unknown, "jsonb", true, false>;
165
+ readonly expiresAt: _$_murumets_ee_db0.ColumnFactory<Date, "timestamp", false, false>;
166
+ readonly updatedAt: _$_murumets_ee_db0.ColumnFactory<Date, "timestamp", true, true>;
167
+ }>;
168
+ columnKinds: Readonly<Record<string, _$_murumets_ee_db0.ColumnKind>>;
169
+ primaryKeyColumns: readonly string[];
170
+ makeClient: (db: _$drizzle_orm_postgres_js0.PostgresJsDatabase) => _$_murumets_ee_db0.TableClient<{
171
+ readonly id: _$_murumets_ee_db0.ColumnFactory<string, "uuid", true, true>;
172
+ readonly userId: _$_murumets_ee_db0.ColumnFactory<string, "uuid", true, false>;
173
+ readonly viewKey: _$_murumets_ee_db0.ColumnFactory<string, "varchar", true, false>;
174
+ readonly state: _$_murumets_ee_db0.ColumnFactory<unknown, "jsonb", true, false>;
175
+ readonly expiresAt: _$_murumets_ee_db0.ColumnFactory<Date, "timestamp", false, false>;
176
+ readonly updatedAt: _$_murumets_ee_db0.ColumnFactory<Date, "timestamp", true, true>;
177
+ }, _$drizzle_orm_pg_core0.PgTableWithColumns<{
178
+ name: string;
179
+ schema: undefined;
180
+ columns: {
181
+ [x: string]: _$drizzle_orm_pg_core0.PgColumn<{
182
+ name: string;
183
+ tableName: string;
184
+ dataType: _$drizzle_orm0.ColumnDataType;
185
+ columnType: string;
186
+ data: unknown;
187
+ driverParam: unknown;
188
+ notNull: false;
189
+ hasDefault: false;
190
+ isPrimaryKey: false;
191
+ isAutoincrement: false;
192
+ hasRuntimeDefault: false;
193
+ enumValues: string[] | undefined;
194
+ baseColumn: never;
195
+ identity: undefined;
196
+ generated: undefined;
197
+ }, {}, {}>;
198
+ };
199
+ dialect: "pg";
200
+ }>>;
201
+ };
202
+ /** Backwards-compatible export — existing imports of the raw pgTable still work. */
205
203
  declare const toolkitViewState: _$drizzle_orm_pg_core0.PgTableWithColumns<{
206
- name: "toolkit_view_state";
204
+ name: string;
207
205
  schema: undefined;
208
206
  columns: {
209
- id: _$drizzle_orm_pg_core0.PgColumn<{
210
- name: "id";
211
- tableName: "toolkit_view_state";
212
- dataType: "string";
213
- columnType: "PgUUID";
214
- data: string;
215
- driverParam: string;
216
- notNull: true;
217
- hasDefault: true;
218
- isPrimaryKey: true;
219
- isAutoincrement: false;
220
- hasRuntimeDefault: false;
221
- enumValues: undefined;
222
- baseColumn: never;
223
- identity: undefined;
224
- generated: undefined;
225
- }, {}, {}>;
226
- userId: _$drizzle_orm_pg_core0.PgColumn<{
227
- name: "user_id";
228
- tableName: "toolkit_view_state";
229
- dataType: "string";
230
- columnType: "PgUUID";
231
- data: string;
232
- driverParam: string;
233
- notNull: true;
234
- hasDefault: false;
235
- isPrimaryKey: false;
236
- isAutoincrement: false;
237
- hasRuntimeDefault: false;
238
- enumValues: undefined;
239
- baseColumn: never;
240
- identity: undefined;
241
- generated: undefined;
242
- }, {}, {}>;
243
- viewKey: _$drizzle_orm_pg_core0.PgColumn<{
244
- name: "view_key";
245
- tableName: "toolkit_view_state";
246
- dataType: "string";
247
- columnType: "PgVarchar";
248
- data: string;
249
- driverParam: string;
250
- notNull: true;
251
- hasDefault: false;
252
- isPrimaryKey: false;
253
- isAutoincrement: false;
254
- hasRuntimeDefault: false;
255
- enumValues: [string, ...string[]];
256
- baseColumn: never;
257
- identity: undefined;
258
- generated: undefined;
259
- }, {}, {
260
- length: 255;
261
- }>;
262
- state: _$drizzle_orm_pg_core0.PgColumn<{
263
- name: "state";
264
- tableName: "toolkit_view_state";
265
- dataType: "json";
266
- columnType: "PgJsonb";
207
+ [x: string]: _$drizzle_orm_pg_core0.PgColumn<{
208
+ name: string;
209
+ tableName: string;
210
+ dataType: _$drizzle_orm0.ColumnDataType;
211
+ columnType: string;
267
212
  data: unknown;
268
213
  driverParam: unknown;
269
- notNull: true;
270
- hasDefault: false;
271
- isPrimaryKey: false;
272
- isAutoincrement: false;
273
- hasRuntimeDefault: false;
274
- enumValues: undefined;
275
- baseColumn: never;
276
- identity: undefined;
277
- generated: undefined;
278
- }, {}, {}>;
279
- expiresAt: _$drizzle_orm_pg_core0.PgColumn<{
280
- name: "expires_at";
281
- tableName: "toolkit_view_state";
282
- dataType: "date";
283
- columnType: "PgTimestamp";
284
- data: Date;
285
- driverParam: string;
286
214
  notNull: false;
287
215
  hasDefault: false;
288
216
  isPrimaryKey: false;
289
217
  isAutoincrement: false;
290
218
  hasRuntimeDefault: false;
291
- enumValues: undefined;
292
- baseColumn: never;
293
- identity: undefined;
294
- generated: undefined;
295
- }, {}, {}>;
296
- updatedAt: _$drizzle_orm_pg_core0.PgColumn<{
297
- name: "updated_at";
298
- tableName: "toolkit_view_state";
299
- dataType: "date";
300
- columnType: "PgTimestamp";
301
- data: Date;
302
- driverParam: string;
303
- notNull: true;
304
- hasDefault: true;
305
- isPrimaryKey: false;
306
- isAutoincrement: false;
307
- hasRuntimeDefault: false;
308
- enumValues: undefined;
219
+ enumValues: string[] | undefined;
309
220
  baseColumn: never;
310
221
  identity: undefined;
311
222
  generated: undefined;
@@ -314,5 +225,5 @@ declare const toolkitViewState: _$drizzle_orm_pg_core0.PgTableWithColumns<{
314
225
  dialect: "pg";
315
226
  }>;
316
227
  //#endregion
317
- export { toolkitSettings, toolkitViewState };
228
+ export { toolkitSettings, toolkitSettingsTable, toolkitViewState, toolkitViewStateTable };
318
229
  //# sourceMappingURL=schema.d.mts.map
@@ -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":";;;;;;;;;;;;AA2BA;;;;;;;;;;;;;;;;;;cAAa,oBAAA;;;;;;;;kBA0BX,cAAA,CAAA,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAGW,eAAA,yBAAe,kBAAA;;;;;;;gBAA6B,cAAA,CAAA,cAAA;;;;;;;;;;;;;;;;;;;;;;;cAQ5C,qBAAA;;;;;;;;kBAkBX,cAAA,CAAA,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAGW,gBAAA,yBAAgB,kBAAA;;;;;;;gBAA8B,cAAA,CAAA,cAAA"}
package/dist/schema.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{jsonb as e,pgTable as t,timestamp as n,unique as r,uuid as i,varchar as a}from"drizzle-orm/pg-core";const o=t(`toolkit_settings`,{id:i(`id`).primaryKey().defaultRandom(),namespace:a(`namespace`,{length:100}).notNull(),scope:a(`scope`,{length:20}).notNull().default(`global`),scopeId:a(`scope_id`,{length:100}).notNull().default(`__global__`),key:a(`key`,{length:255}).notNull(),locale:a(`locale`,{length:10}).notNull().default(`_default`),value:e(`value`),updatedAt:n(`updated_at`,{withTimezone:!0}).notNull().defaultNow(),updatedBy:i(`updated_by`)},e=>({uniqueSetting:r().on(e.namespace,e.scope,e.scopeId,e.key,e.locale)})),s=t(`toolkit_view_state`,{id:i(`id`).primaryKey().defaultRandom(),userId:i(`user_id`).notNull(),viewKey:a(`view_key`,{length:255}).notNull(),state:e(`state`).notNull(),expiresAt:n(`expires_at`,{withTimezone:!0}),updatedAt:n(`updated_at`,{withTimezone:!0}).notNull().defaultNow()},e=>({uniqueUserView:r().on(e.userId,e.viewKey)}));export{o as toolkitSettings,s as toolkitViewState};
1
+ import{column as e,defineTable as t}from"@murumets-ee/db";const n=t({name:`toolkit_settings`,columns:{id:e.uuid({primaryKey:!0,defaultRandom:!0}),namespace:e.varchar({length:100,notNull:!0}),scope:e.varchar({length:20,notNull:!0,default:`global`}),scopeId:e.varchar({length:100,notNull:!0,default:`__global__`,pgName:`scope_id`}),key:e.varchar({length:255,notNull:!0}),locale:e.varchar({length:10,notNull:!0,default:`_default`}),value:e.jsonb(),updatedAt:e.timestamp({notNull:!0,defaultNow:!0,withTimezone:!0,pgName:`updated_at`}),updatedBy:e.uuid({pgName:`updated_by`})},unique:[{on:[`namespace`,`scope`,`scopeId`,`key`,`locale`]}]}),r=n.table,i=t({name:`toolkit_view_state`,columns:{id:e.uuid({primaryKey:!0,defaultRandom:!0}),userId:e.uuid({notNull:!0,pgName:`user_id`}),viewKey:e.varchar({length:255,notNull:!0,pgName:`view_key`}),state:e.jsonb({notNull:!0}),expiresAt:e.timestamp({withTimezone:!0,pgName:`expires_at`}),updatedAt:e.timestamp({notNull:!0,defaultNow:!0,withTimezone:!0,pgName:`updated_at`})},unique:[{on:[`userId`,`viewKey`]}]}),a=i.table;export{r as toolkitSettings,n as toolkitSettingsTable,a as toolkitViewState,i as toolkitViewStateTable};
2
2
  //# sourceMappingURL=schema.mjs.map
@@ -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 * Built on `@murumets-ee/db`'s `defineTable` — the raw `pgTable` is still\n * re-exported (via `.table`) for backwards compatibility with existing\n * imports and tests, but all query construction in SettingsClient /\n * ViewStateClient goes through the typed TableClient.\n */\n\nimport { column, defineTable } from '@murumets-ee/db'\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 toolkitSettingsTable = defineTable({\n name: 'toolkit_settings',\n columns: {\n id: column.uuid({ primaryKey: true, defaultRandom: true }),\n namespace: column.varchar({ length: 100, notNull: true }),\n scope: column.varchar({ length: 20, notNull: true, default: 'global' }),\n scopeId: column.varchar({\n length: 100,\n notNull: true,\n default: '__global__',\n pgName: 'scope_id',\n }),\n key: column.varchar({ length: 255, notNull: true }),\n locale: column.varchar({ length: 10, notNull: true, default: '_default' }),\n value: column.jsonb(),\n updatedAt: column.timestamp({\n notNull: true,\n defaultNow: true,\n withTimezone: true,\n pgName: 'updated_at',\n }),\n updatedBy: column.uuid({ pgName: 'updated_by' }),\n },\n unique: [\n { on: ['namespace', 'scope', 'scopeId', 'key', 'locale'] },\n ],\n})\n\n/** Backwards-compatible export — existing imports of the raw pgTable still work. */\nexport const toolkitSettings = toolkitSettingsTable.table\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 toolkitViewStateTable = defineTable({\n name: 'toolkit_view_state',\n columns: {\n id: column.uuid({ primaryKey: true, defaultRandom: true }),\n userId: column.uuid({ notNull: true, pgName: 'user_id' }),\n viewKey: column.varchar({ length: 255, notNull: true, pgName: 'view_key' }),\n state: column.jsonb({ notNull: true }),\n expiresAt: column.timestamp({ withTimezone: true, pgName: 'expires_at' }),\n updatedAt: column.timestamp({\n notNull: true,\n defaultNow: true,\n withTimezone: true,\n pgName: 'updated_at',\n }),\n },\n unique: [\n { on: ['userId', 'viewKey'] },\n ],\n})\n\n/** Backwards-compatible export — existing imports of the raw pgT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,CACD,OAAQ,CACN,CAAE,GAAI,CAAC,SAAU,UAAU,CAAE,CAC9B,CACF,CAAC,CAGW,EAAmB,EAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murumets-ee/settings",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -32,9 +32,9 @@
32
32
  "drizzle-orm": "^0.45.1",
33
33
  "zod": "^3.24.1",
34
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"
35
+ "@murumets-ee/core": "0.4.0",
36
+ "@murumets-ee/db": "0.4.0",
37
+ "@murumets-ee/logging": "0.4.0"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/node": "^22.10.5",
@@ -1,2 +0,0 @@
1
- import{getApp as e}from"@murumets-ee/core";import{and as t,eq as n,or as r}from"drizzle-orm";import{jsonb as i,pgTable as a,timestamp as o,unique as s,uuid as c,varchar as l}from"drizzle-orm/pg-core";import{z as u}from"zod";const d=a(`toolkit_settings`,{id:c(`id`).primaryKey().defaultRandom(),namespace:l(`namespace`,{length:100}).notNull(),scope:l(`scope`,{length:20}).notNull().default(`global`),scopeId:l(`scope_id`,{length:100}).notNull().default(`__global__`),key:l(`key`,{length:255}).notNull(),locale:l(`locale`,{length:10}).notNull().default(`_default`),value:i(`value`),updatedAt:o(`updated_at`,{withTimezone:!0}).notNull().defaultNow(),updatedBy:c(`updated_by`)},e=>({uniqueSetting:s().on(e.namespace,e.scope,e.scopeId,e.key,e.locale)}));a(`toolkit_view_state`,{id:c(`id`).primaryKey().defaultRandom(),userId:c(`user_id`).notNull(),viewKey:l(`view_key`,{length:255}).notNull(),state:i(`state`).notNull(),expiresAt:o(`expires_at`,{withTimezone:!0}),updatedAt:o(`updated_at`,{withTimezone:!0}).notNull().defaultNow()},e=>({uniqueUserView:s().on(e.userId,e.viewKey)}));const f=`_default`;function p(e){switch(e.type){case`text`:{let t=u.string();return e.maxLength&&(t=t.max(e.maxLength)),e.minLength&&(t=t.min(e.minLength)),e.pattern&&(t=t.regex(e.pattern)),t}case`number`:{let t=u.number();return e.integer&&(t=t.int()),e.min!==void 0&&(t=t.min(e.min)),e.max!==void 0&&(t=t.max(e.max)),t}case`boolean`:return u.boolean();case`select`:return u.enum(e.options);case`json`:return e.schema??u.unknown();case`media`:return u.string().uuid();default:return u.unknown()}}function m(e){let t={};for(let[n,r]of Object.entries(e.schema)){let e=p(r);`default`in r&&r.default!==void 0||(e=e.nullable()),t[n]=e}return t}var h=class{definition;db;logger;scope;scopeId;validators;constructor(e,t){if(typeof window<`u`)throw Error(`SettingsClient cannot be used in browser code.`);if(this.definition=e,this.db=t.db,this.logger=t.logger,this.scope=t.scope??e.scope,this.scopeId=t.scopeId??`__global__`,(this.scope===`team`||this.scope===`user`)&&!t.scopeId)throw Error(`scopeId is required for ${this.scope}-scoped settings (namespace: ${e.namespace})`);this.validators=m(e)}async get(e,i){let a=this.definition.schema[e],o=a?.translatable&&i?.locale?i.locale:null;if(this.logger?.debug({namespace:this.definition.namespace,key:e,locale:o},`Getting setting`),o){let i=await this.db.select({locale:d.locale,value:d.value}).from(d).where(t(...this.baseWhere(),n(d.key,e),r(n(d.locale,o),n(d.locale,f)))),a=i.find(e=>e.locale===o),s=i.find(e=>e.locale===f),c=a??s;if(c&&c.value!==void 0&&c.value!==null)return c.value}else{let t=await this.db.select({value:d.value}).from(d).where(this.whereClause(e)).limit(1);if(t.length>0&&t[0].value!==void 0&&t[0].value!==null)return t[0].value}return a&&`default`in a&&a.default!==void 0?a.default:null}async getAll(e){let i=e?.locale??null;this.logger?.debug({namespace:this.definition.namespace,locale:i},`Getting all settings`);let a;a=i?await this.db.select({key:d.key,locale:d.locale,value:d.value}).from(d).where(t(...this.baseWhere(),r(n(d.locale,f),n(d.locale,i)))):await this.db.select({key:d.key,locale:d.locale,value:d.value}).from(d).where(t(...this.baseWhere(),n(d.locale,f)));let o=new Map;for(let e of a){let t=o.get(e.key)??{};e.locale===`_default`?t.default=e.value:t.locale=e.value,o.set(e.key,t)}let s={};for(let[e,t]of Object.entries(this.definition.schema)){let n=o.get(e),r;t.translatable&&i&&n?.locale!==void 0&&n?.locale!==null?r=n.locale:n?.default!==void 0&&n?.default!==null&&(r=n.default),r===void 0?`default`in t&&t.default!==void 0?s[e]=t.default:s[e]=null:s[e]=r}return s}async set(e,t,n){let r=this.resolveLocale(e,n);if(this.logger?.info({namespace:this.definition.namespace,key:e,locale:r},`Setting value`),!(e in this.definition.schema))throw Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let i=this.validators[e];i&&i.parse(t),await this.upsert(e,t,r)}async setMany(e,t){this.logger?.info({namespace:this.definition.namespace,keys:Object.keys(e),locale:t?.locale},`Setting multiple values`);for(let[t,n]of Object.entries(e)){if(!(t in this.definition.schema))throw Error(`Unknown setting key '${t}' in namespace '${this.definition.namespace}'`);let e=this.validators[t];e&&n!==void 0&&e.parse(n)}await this.db.transaction(async n=>{for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=this.resolveLocale(r,t);await n.insert(d).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:r,locale:e,value:i,updatedAt:new Date}).onConflictDoUpdate({target:[d.namespace,d.scope,d.scopeId,d.key,d.locale],set:{value:i,updatedAt:new Date}})}})}async delete(e,t){let n=this.resolveLocale(e,t);this.logger?.info({namespace:this.definition.namespace,key:e,locale:n},`Deleting setting`),await this.db.delete(d).where(this.whereClause(e,n))}async has(e,t){let n=this.resolveLocale(e,t);return(await this.db.select({key:d.key}).from(d).where(this.whereClause(e,n)).limit(1)).length>0}resolveLocale(e,t){return this.definition.schema[e]?.translatable&&t?.locale?t.locale:f}baseWhere(){return[n(d.namespace,this.definition.namespace),n(d.scope,this.scope),n(d.scopeId,this.scopeId)]}whereClause(e,r=f){return t(...this.baseWhere(),n(d.key,e),n(d.locale,r))}async upsert(e,t,n){await this.db.insert(d).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:e,locale:n,value:t,updatedAt:new Date}).onConflictDoUpdate({target:[d.namespace,d.scope,d.scopeId,d.key,d.locale],set:{value:t,updatedAt:new Date}})}};function g(t,n){let r=n?.app??e();return new h(t,{db:r.db.readWrite,logger:r.logger.child({settings:t.namespace}),scope:n?.scope,scopeId:n?.scopeId})}export{g as createSettingsClient};
2
- //# sourceMappingURL=client-factory-f4nNDWaD.mjs.map
@@ -1 +0,0 @@
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,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,CAQ+B,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,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