@murumets-ee/settings 0.3.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/LICENSE ADDED
@@ -0,0 +1,94 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject
14
+ to the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set
20
+ of the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other
27
+ notices of the licensor in the software. Any use of the licensor's trademarks
28
+ is subject to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license
39
+ for the software granted under these terms ends immediately. If your company
40
+ makes such a claim, your patent license ends immediately for work on behalf
41
+ of your company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from
46
+ you also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license
61
+ no later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your
64
+ licenses to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising
70
+ out of these terms or the use or nature of the software, under any kind of
71
+ legal claim.
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is
76
+ the software the licensor makes available under these terms, including any
77
+ portion of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that organization.
84
+ **control** means ownership of substantially all the assets of an entity, or
85
+ the power to direct the management and policies of an entity (for example, by
86
+ voting right, contract, or otherwise). Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your
92
+ licenses.
93
+
94
+ **trademark** means trademarks, service marks, and similar rights.
@@ -1 +1 @@
1
- {"version":3,"file":"admin.d.mts","names":[],"sources":["../src/types.ts","../src/admin/resources.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;EAEV;EAAA,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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iBAAA;EACR,IAAA;EACA,OAAA,EAAS,CAAA;EACT,OAAA,GAAU,CAAA;AAAA;AAAA,UAGK,iBAAA,sBAAuC,iBAAA;EACtD,IAAA;EACA,OAAA,GAAU,CAAA;EAZH;EAcP,MAAA,GAAS,OAAA,CAAQ,CAAA;AAAA;AAAA,UAGF,kBAAA,SAA2B,iBAAA;EAC1C,IAAA;EACA,OAAA;EACA,MAAA;AAAA;AAAA,KAGU,aAAA,GACR,iBAAA,GACA,mBAAA,GACA,oBAAA,GACA,mBAAA,GACA,iBAAA,GACA,kBAAA;AAAA,KAgDQ,YAAA;AAAA,UAYK,kBAAA,WACL,MAAA,SAAe,aAAA,IAAiB,MAAA,SAAe,aAAA;EA/EzD;EAkFA,SAAA;EAjFU;EAmFV,KAAA,EAAO,YAAA;EAjFE;EAmFT,MAAA,EAAQ,CAAA;EAnFU;EAqFlB,KAAA;AAAA;;;iBC1Hc,iBAAA,CACd,WAAA,EAAa,kBAAA,KACZ,KAAA;EAAQ,QAAA;EAAkB,OAAA;AAAA;;;;;;;;;;iBCuEb,cAAA,CAAe,UAAA,EAAY,kBAAA,GAAqB,UAAA;AAAA,iBAChD,cAAA,CAAe,WAAA,EAAa,kBAAA,KAAuB,UAAA"}
package/dist/admin.mjs CHANGED
@@ -1,2 +1,2 @@
1
- function e(e){return e.map(e=>({resource:`settings:${e.namespace}`,actions:[`view`,`update`]}))}const t=/^[a-z]{2}(-[A-Z]{2})?$/;function n(e){if(e&&t.test(e))return e}function r(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function i(e,t){return r({error:e},t)}function a(e){return{definition:e,clientPromise:null}}async function o(e,t){if(e.definition.scope===`user`){let{getApp:n}=await import(`@murumets-ee/core`),{createSettingsClient:r}=await import(`./client-factory-f4nNDWaD.mjs`);return r(e.definition,{app:n(),scopeId:t})}return e.clientPromise||=(async()=>{let{getApp:t}=await import(`@murumets-ee/core`),{createSettingsClient:n}=await import(`./client-factory-f4nNDWaD.mjs`);return n(e.definition,{app:t()})})(),e.clientPromise}function s(e){let t=Array.isArray(e)?e:[e],s=new Map;for(let e of t)s.set(e.namespace,a(e));async function c(e,t){let a=t.segments[0];if(!a)return i(`Missing settings namespace`,400);let c=s.get(a);if(!c)return i(`Unknown settings namespace: ${a}`,404);if(!t.checkPermission(`settings:${a}`,`view`))return i(`Forbidden: cannot view settings:${a}`,403);let l=new URL(e.url),u;if(c.definition.scope===`user`&&(u=l.searchParams.get(`scopeId`)??t.user.id,u!==t.user.id))return i(`Forbidden: cannot read other users' preferences`,403);let d=await o(c,u),f=n(l.searchParams.get(`locale`));return r(await d.getAll(f?{locale:f}:void 0))}async function l(e,t){let a=t.segments[0];if(!a)return i(`Missing settings namespace`,400);let c=s.get(a);if(!c)return i(`Unknown settings namespace: ${a}`,404);if(!t.checkPermission(`settings:${a}`,`update`))return i(`Forbidden: cannot update settings:${a}`,403);let{values:l,locale:u,scopeId:d}=await e.json(),f=n(u);if(!l||typeof l!=`object`)return i(`Body must contain "values" object`,400);let p;return c.definition.scope===`user`&&(p=d??t.user.id,p!==t.user.id)?i(`Forbidden: cannot update other users' preferences`,403):(await(await o(c,p)).setMany(l,f?{locale:f}:void 0),t.audit?.({action:`settings.update`,entityType:`settings`,userId:t.user.id,userName:t.user.name,changes:{fields:l},metadata:{namespace:a,...f?{locale:f}:{},...p?{scopeId:p}:{}}}),r({success:!0}))}return{prefix:`settings`,actions:[`view`,`update`],handlers:{GET:c,PATCH:l}}}export{e as settingsResources,s as settingsRoutes};
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/resources.ts","../src/admin/routes.ts"],"sourcesContent":["/**\n * Derive permission resource entries from settings definitions.\n *\n * Each definition produces one resource (`settings:<namespace>`) with\n * `['view', 'update']` actions. Spread the result into your\n * `pluginResources` array so the permission catalog includes them.\n *\n * @example\n * ```typescript\n * import { settingsResources } from '@murumets-ee/settings/admin'\n * import { siteSettings } from '@/settings/site'\n * import { ticketingSettings } from '@murumets-ee/ticketing'\n *\n * export const pluginResources = [\n * ...settingsResources([siteSettings, ticketingSettings]),\n * { resource: 'storage', actions: ['view', 'create', 'update', 'delete'] },\n * ]\n * ```\n */\n\nimport type { SettingsDefinition } from '../types.js'\n\nexport function settingsResources(\n definitions: SettingsDefinition[],\n): Array<{ resource: string; actions: readonly string[] }> {\n return definitions.map((def) => ({\n resource: `settings:${def.namespace}`,\n actions: ['view', 'update'] as const,\n }))\n}\n","/**\n * Settings admin routes for the centralized admin API handler.\n *\n * Provides get/update operations for typed settings, with per-namespace\n * permission checks. Accepts a single definition (backward-compat) or\n * an array of definitions for multi-namespace support.\n *\n * URL scheme:\n * - `GET /api/admin/settings/:namespace` — Get all settings (query: `?locale=`)\n * - `PATCH /api/admin/settings/:namespace` — Update settings (JSON body: `{ values, locale?, scopeId? }`)\n *\n * Each namespace is independently gated by `checkPermission('settings:<ns>', action)`.\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { settingsRoutes } from '@murumets-ee/settings/admin'\n * import { siteSettings } from '@/settings/site'\n * import { ticketingSettings, agentPreferences } from '@murumets-ee/ticketing'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [Article],\n * routes: [settingsRoutes([siteSettings, ticketingSettings, agentPreferences])],\n * })\n * ```\n */\n\nimport type { AdminRoute, AuditLogFn, AuthUser } from '@murumets-ee/core'\nimport type { SettingsClient } from '../client.js'\nimport type { SettingConfig, SettingsDefinition } from '../types.js'\n\n// ---------------------------------------------------------------------------\n// Locale validation (same BCP47 pattern as the framework-level check)\n// ---------------------------------------------------------------------------\n\nconst LOCALE_RE = /^[a-z]{2}(-[A-Z]{2})?$/\n\nfunction validateLocale(raw: string | null | undefined): string | undefined {\n if (!raw) return undefined\n if (!LOCALE_RE.test(raw)) return undefined\n return raw\n}\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction json(data: unknown, status = 200) {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction errorJson(message: string, status: number) {\n return json({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Per-namespace entry: definition + lazy client\n// ---------------------------------------------------------------------------\n\ninterface NamespaceEntry<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {\n definition: SettingsDefinition<S>\n clientPromise: Promise<SettingsClient<S>> | null\n}\n\nfunction createEntry<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n): NamespaceEntry<S> {\n return { definition, clientPromise: null }\n}\n\nasync function getClient<S extends Record<string, SettingConfig>>(\n entry: NamespaceEntry<S>,\n scopeId?: string,\n): Promise<SettingsClient<S>> {\n // User-scoped settings need a fresh client per scopeId — no caching\n if (entry.definition.scope === 'user') {\n const { getApp } = await import('@murumets-ee/core')\n const { createSettingsClient } = await import('../client-factory.js')\n return createSettingsClient(entry.definition, { app: getApp(), scopeId })\n }\n\n if (!entry.clientPromise) {\n entry.clientPromise = (async () => {\n const { getApp } = await import('@murumets-ee/core')\n const { createSettingsClient } = await import('../client-factory.js')\n return createSettingsClient(entry.definition, { app: getApp() })\n })()\n }\n return entry.clientPromise\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create admin API routes for settings management.\n *\n * Accepts a single definition (backward-compatible) or an array for\n * multi-namespace support. Each namespace gets its own permission\n * resource (`settings:<namespace>`).\n */\nexport function settingsRoutes(definition: SettingsDefinition): AdminRoute\nexport function settingsRoutes(definitions: SettingsDefinition[]): AdminRoute\nexport function settingsRoutes(\n input: SettingsDefinition | SettingsDefinition[],\n): AdminRoute {\n const definitions = Array.isArray(input) ? input : [input]\n\n // Build lookup map: namespace → entry\n const nsMap = new Map<string, NamespaceEntry>()\n for (const def of definitions) {\n nsMap.set(def.namespace, createEntry(def))\n }\n\n // ---------- GET /api/admin/settings/:namespace ----------\n async function handleGet(\n req: Request,\n ctx: {\n segments: string[]\n user: AuthUser\n audit?: AuditLogFn\n checkPermission: (resource: string, action: string) => boolean\n },\n ): Promise<Response> {\n const namespace = ctx.segments[0]\n if (!namespace) return errorJson('Missing settings namespace', 400)\n\n const entry = nsMap.get(namespace)\n if (!entry) return errorJson(`Unknown settings namespace: ${namespace}`, 404)\n\n // Per-namespace permission check\n if (!ctx.checkPermission(`settings:${namespace}`, 'view')) {\n return errorJson(`Forbidden: cannot view settings:${namespace}`, 403)\n }\n\n // User-scoped: only allow reading own preferences\n const url = new URL(req.url)\n let scopeId: string | undefined\n if (entry.definition.scope === 'user') {\n scopeId = url.searchParams.get('scopeId') ?? ctx.user.id\n if (scopeId !== ctx.user.id) {\n return errorJson('Forbidden: cannot read other users\\' preferences', 403)\n }\n }\n\n const client = await getClient(entry, scopeId)\n const locale = validateLocale(url.searchParams.get('locale'))\n const values = await client.getAll(locale ? { locale } : undefined)\n return json(values)\n }\n\n // ---------- PATCH /api/admin/settings/:namespace ----------\n async function handlePatch(\n req: Request,\n ctx: {\n segments: string[]\n user: AuthUser\n audit?: AuditLogFn\n checkPermission: (resource: string, action: string) => boolean\n },\n ): Promise<Response> {\n const namespace = ctx.segments[0]\n if (!namespace) return errorJson('Missing settings namespace', 400)\n\n const entry = nsMap.get(namespace)\n if (!entry) return errorJson(`Unknown settings namespace: ${namespace}`, 404)\n\n // Per-namespace permission check\n if (!ctx.checkPermission(`settings:${namespace}`, 'update')) {\n return errorJson(`Forbidden: cannot update settings:${namespace}`, 403)\n }\n\n const body = await req.json()\n const { values, locale: rawLocale, scopeId } = body as {\n values: Record<string, unknown>\n locale?: string\n scopeId?: string\n }\n const locale = validateLocale(rawLocale)\n\n if (!values || typeof values !== 'object') {\n return errorJson('Body must contain \"values\" object', 400)\n }\n\n // User-scoped: enforce user isolation\n let resolvedScopeId: string | undefined\n if (entry.definition.scope === 'user') {\n resolvedScopeId = scopeId ?? ctx.user.id\n if (resolvedScopeId !== ctx.user.id) {\n return errorJson('Forbidden: cannot update other users\\' preferences', 403)\n }\n }\n\n const client = await getClient(entry, resolvedScopeId)\n await client.setMany(\n values as Parameters<typeof client.setMany>[0],\n locale ? { locale } : undefined,\n )\n\n ctx.audit?.({\n action: 'settings.update',\n entityType: 'settings',\n userId: ctx.user.id,\n userName: ctx.user.name,\n changes: { fields: values },\n metadata: {\n namespace,\n ...(locale ? { locale } : {}),\n ...(resolvedScopeId ? { scopeId: resolvedScopeId } : {}),\n },\n })\n\n return json({ success: true })\n }\n\n return {\n prefix: 'settings',\n // No `resource` — permission checks happen per-namespace inside handlers\n actions: ['view', 'update'],\n handlers: {\n GET: handleGet,\n PATCH: handlePatch,\n },\n }\n}\n"],"mappings":"AAsBA,SAAgB,EACd,EACyD,CACzD,OAAO,EAAY,IAAK,IAAS,CAC/B,SAAU,YAAY,EAAI,YAC1B,QAAS,CAAC,OAAQ,SAAS,CAC5B,EAAE,CCQL,MAAM,EAAY,yBAElB,SAAS,EAAe,EAAoD,CACrE,MACA,EAAU,KAAK,EAAI,CACxB,OAAO,EAOT,SAAS,EAAK,EAAe,EAAS,IAAK,CACzC,OAAO,IAAI,SAAS,KAAK,UAAU,EAAK,CAAE,CACxC,SACA,QAAS,CAAE,eAAgB,mBAAoB,CAChD,CAAC,CAGJ,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,EAAM,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C,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"}
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,EAAM,WAAY,CAAE,IAAK,GAAQ,CAAE,UAAS,CAAC,CAU3E,MAPA,CACE,EAAM,iBAAiB,SAAY,CACjC,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,wBAAyB,MAAM,OAAO,iCAC9C,OAAO,EAAqB,EAAM,WAAY,CAAE,IAAK,GAAQ,CAAE,CAAC,IAC9D,CAEC,EAAM,cAgBf,SAAgB,EACd,EACY,CACZ,IAAM,EAAc,MAAM,QAAQ,EAAM,CAAG,EAAQ,CAAC,EAAM,CAGpD,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAO,EAChB,EAAM,IAAI,EAAI,UAAW,EAAY,EAAI,CAAC,CAI5C,eAAe,EACb,EACA,EAMmB,CACnB,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AAU,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,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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
@@ -133,7 +133,7 @@ interface LocaleOption {
133
133
  }
134
134
  declare class SettingsClient<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {
135
135
  private definition;
136
- private db;
136
+ private table;
137
137
  private logger?;
138
138
  private scope;
139
139
  private scopeId;
@@ -184,12 +184,14 @@ declare class SettingsClient<S extends Record<string, SettingConfig> = Record<st
184
184
  * Translatable settings use the requested locale or DEFAULT_LOCALE.
185
185
  */
186
186
  private resolveLocale;
187
- /** Base where conditions: namespace + scope + scopeId */
187
+ /** Base where conditions: namespace + scope + scopeId. */
188
188
  private baseWhere;
189
- /** Full where clause for a specific key + locale */
190
- private whereClause;
191
- /** Upsert a single setting row */
192
- 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;
193
195
  }
194
196
  //#endregion
195
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;EAAV;EAEA,SAAA;AAAA;AAAA,UAGe,mBAAA,SAA4B,iBAAA;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,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 /** Render as textarea instead of single-line input. */\n multiline?: boolean\n}\n\nexport interface NumberSettingConfig extends BaseSettingConfig {\n type: 'number'\n default?: number\n min?: number\n max?: number\n integer?: boolean\n}\n\nexport interface BooleanSettingConfig extends BaseSettingConfig {\n type: 'boolean'\n default?: boolean\n}\n\nexport interface SelectSettingConfig<O extends readonly string[] = readonly string[]>\n extends BaseSettingConfig {\n type: 'select'\n options: O\n default?: O[number]\n}\n\nexport interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {\n type: 'json'\n default?: T\n /** Optional Zod schema for validation. If provided, values are validated on set. */\n schema?: ZodType<T>\n}\n\nexport interface MediaSettingConfig extends BaseSettingConfig {\n type: 'media'\n default?: string\n accept?: string[]\n}\n\nexport type SettingConfig =\n | TextSettingConfig\n | NumberSettingConfig\n | BooleanSettingConfig\n | SelectSettingConfig\n | JsonSettingConfig\n | MediaSettingConfig\n\n// ---------------------------------------------------------------\n// 2. Setting-to-TypeScript mapping (single setting)\n// ---------------------------------------------------------------\n\n/**\n * Maps a single SettingConfig to its TypeScript output type.\n * Each branch is a shallow comparison — no recursion.\n */\nexport type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig\n ? string\n : S extends NumberSettingConfig\n ? number\n : S extends BooleanSettingConfig\n ? boolean\n : S extends SelectSettingConfig<infer O>\n ? O[number]\n : S extends JsonSettingConfig<infer T>\n ? T\n : S extends MediaSettingConfig\n ? string\n : never\n\n// ---------------------------------------------------------------\n// 3. Null awareness: settings with defaults always return value\n// ---------------------------------------------------------------\n\n/**\n * If a setting has a `default`, get() never returns null.\n * Without a default, it returns T | null.\n */\nexport type InferSettingValue<S extends SettingConfig> = S extends { default: unknown }\n ? SettingToTS<S>\n : SettingToTS<S> | null\n\n// ---------------------------------------------------------------\n// 4. Full settings map type (what getAll() returns)\n// ---------------------------------------------------------------\n\nexport type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {\n [K in keyof Schema]: InferSettingValue<Schema[K]>\n}\n\n// ---------------------------------------------------------------\n// 5. Scope types\n// ---------------------------------------------------------------\n\nexport type SettingScope = 'global' | 'team' | 'user'\n\n/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */\nexport const GLOBAL_SCOPE_ID = '__global__'\n\n/** Sentinel value for locale column when no locale is specified (base/default value) */\nexport const DEFAULT_LOCALE = '_default'\n\n// ---------------------------------------------------------------\n// 6. Settings definition (returned by defineSettings)\n// ---------------------------------------------------------------\n\nexport interface SettingsDefinition<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n /** Unique namespace for this settings group */\n namespace: string\n /** Default scope for these settings */\n scope: SettingScope\n /** Setting schema (the shape) */\n schema: S\n /** Human-readable label for admin UI */\n label?: string\n}\n","/**\n * Generate Zod validation schemas from setting config definitions.\n * Validates values before writing to the database.\n */\n\nimport { z } from 'zod'\nimport type { SettingConfig, SettingsDefinition } from './types.js'\n\n/**\n * Convert a single setting config to a Zod schema.\n */\nexport function settingToZod(config: SettingConfig): z.ZodType {\n switch (config.type) {\n case 'text': {\n let schema: z.ZodString = z.string()\n if (config.maxLength) schema = schema.max(config.maxLength)\n if (config.minLength) schema = schema.min(config.minLength)\n if (config.pattern) schema = schema.regex(config.pattern)\n return schema\n }\n\n case 'number': {\n let schema: z.ZodNumber = z.number()\n if (config.integer) schema = schema.int()\n if (config.min !== undefined) schema = schema.min(config.min)\n if (config.max !== undefined) schema = schema.max(config.max)\n return schema\n }\n\n case 'boolean':\n return z.boolean()\n\n case 'select':\n return z.enum(config.options as [string, ...string[]])\n\n case 'json':\n return config.schema ?? z.unknown()\n\n case 'media':\n return z.string().uuid()\n\n default:\n return z.unknown()\n }\n}\n\n/**\n * Generate a validation map for all settings in a definition.\n * Returns a Record<key, ZodType> for validating individual set() calls.\n *\n * Settings without a default are nullable (matching InferSettingValue),\n * so their validators accept null.\n */\nexport function generateSettingValidators(\n definition: SettingsDefinition,\n): Record<string, z.ZodType> {\n const validators: Record<string, z.ZodType> = {}\n for (const [key, config] of Object.entries(definition.schema)) {\n let schema = settingToZod(config)\n const hasDefault = 'default' in config && config.default !== undefined\n if (!hasDefault) {\n schema = schema.nullable()\n }\n validators[key] = schema\n }\n return validators\n}\n","/**\n * SettingsClient — typed CRUD for key-value settings.\n *\n * Server-only. Uses read-write DB connection.\n * Validates values against the setting schema on set().\n *\n * Supports per-locale values for settings marked `translatable: true`.\n * Non-translatable settings always use the `__default__` locale.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n *\n * // Default locale\n * const name = await settings.get('siteName') // string (has default)\n *\n * // Locale-specific (only for translatable settings)\n * const nameEt = await settings.get('siteName', { locale: 'et' })\n *\n * await settings.set('siteName', 'Mänguväljak', { locale: 'et' })\n * ```\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { and, eq, or } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettings } from './schema.js'\nimport type {\n InferSettingsMap,\n InferSettingValue,\n SettingConfig,\n SettingScope,\n SettingsDefinition,\n} from './types.js'\nimport { DEFAULT_LOCALE, GLOBAL_SCOPE_ID } from './types.js'\nimport { generateSettingValidators } from './validation.js'\n\nexport interface SettingsClientConfig {\n /** Database client (read-write) */\n db: PostgresJsDatabase\n /** Logger instance */\n logger?: Logger\n /** Override scope (defaults to definition's scope) */\n scope?: SettingScope\n /** Scope ID (required for team/user scope, defaults to '__global__' for global) */\n scopeId?: string\n}\n\nexport interface LocaleOption {\n /** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */\n locale?: string\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private db: PostgresJsDatabase\n private logger?: Logger\n private scope: SettingScope\n private scopeId: string\n private validators: Record<string, ZodType>\n\n constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig) {\n if (typeof window !== 'undefined') {\n throw new Error('SettingsClient cannot be used in browser code.')\n }\n\n this.definition = definition\n this.db = config.db\n this.logger = config.logger\n this.scope = config.scope ?? definition.scope\n this.scopeId = config.scopeId ?? GLOBAL_SCOPE_ID\n\n if ((this.scope === 'team' || this.scope === 'user') && !config.scopeId) {\n throw new Error(\n `scopeId is required for ${this.scope}-scoped settings (namespace: ${definition.namespace})`,\n )\n }\n\n this.validators = generateSettingValidators(definition)\n }\n\n /**\n * Get a single setting value.\n *\n * For translatable settings with a locale, tries locale-specific value first,\n * then falls back to the default value, then the schema default, then null.\n */\n async get<K extends string & keyof S>(\n key: K,\n options?: LocaleOption,\n ): Promise<InferSettingValue<S[K]>> {\n const config = this.definition.schema[key]\n const locale = config?.translatable && options?.locale ? options.locale : null\n\n this.logger?.debug({ namespace: this.definition.namespace, key, locale }, 'Getting setting')\n\n if (locale) {\n // Fetch both locale-specific and default in one query\n const rows = await this.db\n .select({ locale: toolkitSettings.locale, value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n or(eq(toolkitSettings.locale, locale), eq(toolkitSettings.locale, DEFAULT_LOCALE)),\n ),\n )\n\n // Prefer locale-specific, fall back to default\n const localeRow = rows.find((r) => r.locale === locale)\n const defaultRow = rows.find((r) => r.locale === DEFAULT_LOCALE)\n const row = localeRow ?? defaultRow\n\n if (row && row.value !== undefined && row.value !== null) {\n return row.value as InferSettingValue<S[K]>\n }\n } else {\n const rows = await this.db\n .select({ value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(this.whereClause(key))\n .limit(1)\n\n if (rows.length > 0 && rows[0].value !== undefined && rows[0].value !== null) {\n return rows[0].value as InferSettingValue<S[K]>\n }\n }\n\n if (config && 'default' in config && config.default !== undefined) {\n return config.default as InferSettingValue<S[K]>\n }\n\n return null as InferSettingValue<S[K]>\n }\n\n /**\n * Get all settings for this namespace/scope as a typed object.\n * Missing values are filled from schema defaults.\n *\n * When locale is specified, translatable settings prefer the locale-specific\n * value over the default value.\n */\n async getAll(options?: LocaleOption): Promise<InferSettingsMap<S>> {\n const locale = options?.locale ?? null\n\n this.logger?.debug({ namespace: this.definition.namespace, locale }, 'Getting all settings')\n\n let rows: { key: string; locale: string; value: unknown }[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n or(eq(toolkitSettings.locale, DEFAULT_LOCALE), eq(toolkitSettings.locale, locale)),\n ),\n )\n } else {\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(and(...this.baseWhere(), eq(toolkitSettings.locale, DEFAULT_LOCALE)))\n }\n\n // Build lookup: key → { default: value, locale: value }\n const stored = new Map<string, { default?: unknown; locale?: unknown }>()\n for (const row of rows) {\n const entry = stored.get(row.key) ?? {}\n if (row.locale === DEFAULT_LOCALE) {\n entry.default = row.value\n } else {\n entry.locale = row.value\n }\n stored.set(row.key, entry)\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, config] of Object.entries(this.definition.schema)) {\n const entry = stored.get(key)\n\n // For translatable settings with locale, prefer locale-specific value\n let value: unknown\n if (config.translatable && locale && entry?.locale !== undefined && entry?.locale !== null) {\n value = entry.locale\n } else if (entry?.default !== undefined && entry?.default !== null) {\n value = entry.default\n }\n\n if (value !== undefined) {\n result[key] = value\n } else if ('default' in config && config.default !== undefined) {\n result[key] = config.default\n } else {\n result[key] = null\n }\n }\n\n return result as InferSettingsMap<S>\n }\n\n /**\n * Set a single setting value.\n * Validates against the schema before writing.\n *\n * Pass `{ locale }` to write a locale-specific value (only for translatable settings).\n */\n async set<K extends string & keyof S>(\n key: K,\n value: InferSettingValue<S[K]>,\n options?: LocaleOption,\n ): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Setting value')\n\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n\n const validator = this.validators[key]\n if (validator) {\n validator.parse(value)\n }\n\n await this.upsert(key, value as unknown, locale)\n }\n\n /**\n * Set multiple settings at once (validated individually).\n * Writes in a transaction — all or nothing.\n *\n * Pass `{ locale }` to write locale-specific values for translatable settings.\n * Non-translatable settings in the values will always write to the default locale.\n */\n async setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void> {\n this.logger?.info(\n { namespace: this.definition.namespace, keys: Object.keys(values), locale: options?.locale },\n 'Setting multiple values',\n )\n\n // Validate all first (fail fast)\n for (const [key, value] of Object.entries(values)) {\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n const validator = this.validators[key]\n if (validator && value !== undefined) {\n validator.parse(value)\n }\n }\n\n await this.db.transaction(async (tx) => {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n const locale = this.resolveLocale(key, options)\n await tx\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value: value as unknown,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value: value as unknown,\n updatedAt: new Date(),\n },\n })\n }\n })\n }\n\n /**\n * Delete a setting (resets to default on next get).\n * Pass `{ locale }` to delete only the locale-specific value.\n */\n async delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Deleting setting')\n\n await this.db.delete(toolkitSettings).where(this.whereClause(key, locale))\n }\n\n /**\n * Check if a setting has a stored value (not relying on default).\n */\n async has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean> {\n const locale = this.resolveLocale(key, options)\n\n const rows = await this.db\n .select({ key: toolkitSettings.key })\n .from(toolkitSettings)\n .where(this.whereClause(key, locale))\n .limit(1)\n\n return rows.length > 0\n }\n\n // ---------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------\n\n /**\n * Resolve which locale to use for a given key.\n * Non-translatable settings always use DEFAULT_LOCALE.\n * Translatable settings use the requested locale or DEFAULT_LOCALE.\n */\n private resolveLocale(key: string, options?: LocaleOption): string {\n const config = this.definition.schema[key as keyof S] as SettingConfig | undefined\n if (config?.translatable && options?.locale) {\n return options.locale\n }\n return DEFAULT_LOCALE\n }\n\n /** Base where conditions: namespace + scope + scopeId */\n private baseWhere() {\n return [\n eq(toolkitSettings.namespace, this.definition.namespace),\n eq(toolkitSettings.scope, this.scope),\n eq(toolkitSettings.scopeId, this.scopeId),\n ] as const\n }\n\n /** Full where clause for a specific key + locale */\n private whereClause(key: string, locale: string = DEFAULT_LOCALE) {\n return and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n eq(toolkitSettings.locale, locale),\n )!\n }\n\n /** Upsert a single setting row */\n private async upsert(key: string, value: unknown, locale: string) {\n await this.db\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value,\n updatedAt: new Date(),\n },\n })\n }\n}\n","/**\n * Factory function for creating typed SettingsClient instances.\n *\n * Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { SettingsClient } from './client.js'\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport interface CreateSettingsClientOptions {\n /** Override the toolkit app (defaults to getApp()) */\n app?: ToolkitApp\n /** Override scope from definition */\n scope?: SettingScope\n /** Scope ID for team/user scoped settings */\n scopeId?: string\n}\n\n/**\n * Create a typed SettingsClient.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n * const name = await settings.get('siteName') // string\n * ```\n */\nexport function createSettingsClient<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n options?: CreateSettingsClientOptions,\n): SettingsClient<S> {\n const app = options?.app ?? getApp()\n\n return new SettingsClient(definition, {\n db: app.db.readWrite,\n logger: app.logger.child({ settings: definition.namespace }),\n scope: options?.scope,\n scopeId: options?.scopeId,\n })\n}\n","/**\n * Define a typed settings group.\n *\n * @example\n * ```typescript\n * import { defineSettings, setting } from '@murumets-ee/settings'\n *\n * export const siteSettings = defineSettings({\n * namespace: 'site',\n * scope: 'global',\n * schema: {\n * siteName: setting.text({ default: 'My Site' }),\n * logo: setting.media(),\n * maintenance: setting.boolean({ default: false }),\n * },\n * })\n * ```\n */\n\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport function defineSettings<const S extends Record<string, SettingConfig>>(definition: {\n namespace: string\n scope: SettingScope\n schema: S\n label?: string\n}): SettingsDefinition<S> {\n if (!definition.namespace) {\n throw new Error('Settings namespace is required')\n }\n if (!definition.schema || Object.keys(definition.schema).length === 0) {\n throw new Error('Settings schema must have at least one setting')\n }\n return definition\n}\n"],"mappings":"wLAmBA,MAAa,EAAU,CAKrB,KACE,IAC2B,CAAE,KAAM,OAAQ,GAAG,EAAQ,EAMxD,OACE,IAC6B,CAAE,KAAM,SAAU,GAAG,EAAQ,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,CC8CY,EAAkB,aAGlB,EAAiB,WCrH9B,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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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,KACE,IAC8B,CAAE,KAAM,OAAQ,GAAG,EAAQ,EAM3D,MACE,IAC4B,CAAE,KAAM,QAAS,GAAG,EAAQ,EAC3D,CC8CY,EAAkB,aAGlB,EAAiB,WCrH9B,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,EAWx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.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
@@ -10,6 +13,11 @@ import * as _$drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
10
13
  *
11
14
  * These tables are registered for migration discovery via the `settings()`
12
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.
13
21
  */
14
22
  /**
15
23
  * Typed settings table.
@@ -20,127 +28,89 @@ import * as _$drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
20
28
  * scopeId uses '__global__' sentinel for global scope to avoid
21
29
  * PostgreSQL's NULL != NULL behavior in unique constraints.
22
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. */
23
105
  declare const toolkitSettings: _$drizzle_orm_pg_core0.PgTableWithColumns<{
24
- name: "toolkit_settings";
106
+ name: string;
25
107
  schema: undefined;
26
108
  columns: {
27
- id: _$drizzle_orm_pg_core0.PgColumn<{
28
- name: "id";
29
- tableName: "toolkit_settings";
30
- dataType: "string";
31
- columnType: "PgUUID";
32
- data: string;
33
- driverParam: string;
34
- notNull: true;
35
- hasDefault: true;
36
- isPrimaryKey: true;
37
- isAutoincrement: false;
38
- hasRuntimeDefault: false;
39
- enumValues: undefined;
40
- baseColumn: never;
41
- identity: undefined;
42
- generated: undefined;
43
- }, {}, {}>;
44
- namespace: _$drizzle_orm_pg_core0.PgColumn<{
45
- name: "namespace";
46
- tableName: "toolkit_settings";
47
- dataType: "string";
48
- columnType: "PgVarchar";
49
- data: string;
50
- driverParam: string;
51
- notNull: true;
52
- hasDefault: false;
53
- isPrimaryKey: false;
54
- isAutoincrement: false;
55
- hasRuntimeDefault: false;
56
- enumValues: [string, ...string[]];
57
- baseColumn: never;
58
- identity: undefined;
59
- generated: undefined;
60
- }, {}, {
61
- length: 100;
62
- }>;
63
- scope: _$drizzle_orm_pg_core0.PgColumn<{
64
- name: "scope";
65
- tableName: "toolkit_settings";
66
- dataType: "string";
67
- columnType: "PgVarchar";
68
- data: string;
69
- driverParam: string;
70
- notNull: true;
71
- hasDefault: true;
72
- isPrimaryKey: false;
73
- isAutoincrement: false;
74
- hasRuntimeDefault: false;
75
- enumValues: [string, ...string[]];
76
- baseColumn: never;
77
- identity: undefined;
78
- generated: undefined;
79
- }, {}, {
80
- length: 20;
81
- }>;
82
- scopeId: _$drizzle_orm_pg_core0.PgColumn<{
83
- name: "scope_id";
84
- tableName: "toolkit_settings";
85
- dataType: "string";
86
- columnType: "PgVarchar";
87
- data: string;
88
- driverParam: string;
89
- notNull: true;
90
- hasDefault: true;
91
- isPrimaryKey: false;
92
- isAutoincrement: false;
93
- hasRuntimeDefault: false;
94
- enumValues: [string, ...string[]];
95
- baseColumn: never;
96
- identity: undefined;
97
- generated: undefined;
98
- }, {}, {
99
- length: 100;
100
- }>;
101
- key: _$drizzle_orm_pg_core0.PgColumn<{
102
- name: "key";
103
- tableName: "toolkit_settings";
104
- dataType: "string";
105
- columnType: "PgVarchar";
106
- data: string;
107
- driverParam: string;
108
- notNull: true;
109
- hasDefault: false;
110
- isPrimaryKey: false;
111
- isAutoincrement: false;
112
- hasRuntimeDefault: false;
113
- enumValues: [string, ...string[]];
114
- baseColumn: never;
115
- identity: undefined;
116
- generated: undefined;
117
- }, {}, {
118
- length: 255;
119
- }>;
120
- locale: _$drizzle_orm_pg_core0.PgColumn<{
121
- name: "locale";
122
- tableName: "toolkit_settings";
123
- dataType: "string";
124
- columnType: "PgVarchar";
125
- data: string;
126
- driverParam: string;
127
- notNull: true;
128
- hasDefault: true;
129
- isPrimaryKey: false;
130
- isAutoincrement: false;
131
- hasRuntimeDefault: false;
132
- enumValues: [string, ...string[]];
133
- baseColumn: never;
134
- identity: undefined;
135
- generated: undefined;
136
- }, {}, {
137
- length: 10;
138
- }>;
139
- value: _$drizzle_orm_pg_core0.PgColumn<{
140
- name: "value";
141
- tableName: "toolkit_settings";
142
- dataType: "json";
143
- columnType: "PgJsonb";
109
+ [x: string]: _$drizzle_orm_pg_core0.PgColumn<{
110
+ name: string;
111
+ tableName: string;
112
+ dataType: _$drizzle_orm0.ColumnDataType;
113
+ columnType: string;
144
114
  data: unknown;
145
115
  driverParam: unknown;
146
116
  notNull: false;
@@ -148,41 +118,7 @@ declare const toolkitSettings: _$drizzle_orm_pg_core0.PgTableWithColumns<{
148
118
  isPrimaryKey: false;
149
119
  isAutoincrement: false;
150
120
  hasRuntimeDefault: false;
151
- enumValues: undefined;
152
- baseColumn: never;
153
- identity: undefined;
154
- generated: undefined;
155
- }, {}, {}>;
156
- updatedAt: _$drizzle_orm_pg_core0.PgColumn<{
157
- name: "updated_at";
158
- tableName: "toolkit_settings";
159
- dataType: "date";
160
- columnType: "PgTimestamp";
161
- data: Date;
162
- driverParam: string;
163
- notNull: true;
164
- hasDefault: true;
165
- isPrimaryKey: false;
166
- isAutoincrement: false;
167
- hasRuntimeDefault: false;
168
- enumValues: undefined;
169
- baseColumn: never;
170
- identity: undefined;
171
- generated: undefined;
172
- }, {}, {}>;
173
- updatedBy: _$drizzle_orm_pg_core0.PgColumn<{
174
- name: "updated_by";
175
- tableName: "toolkit_settings";
176
- dataType: "string";
177
- columnType: "PgUUID";
178
- data: string;
179
- driverParam: string;
180
- notNull: false;
181
- hasDefault: false;
182
- isPrimaryKey: false;
183
- isAutoincrement: false;
184
- hasRuntimeDefault: false;
185
- enumValues: undefined;
121
+ enumValues: string[] | undefined;
186
122
  baseColumn: never;
187
123
  identity: undefined;
188
124
  generated: undefined;
@@ -196,110 +132,91 @@ declare const toolkitSettings: _$drizzle_orm_pg_core0.PgTableWithColumns<{
196
132
  * Stores schemaless user-scoped JSON blobs for persisting
197
133
  * UI state (table filters, column order, etc.) with optional TTL.
198
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. */
199
203
  declare const toolkitViewState: _$drizzle_orm_pg_core0.PgTableWithColumns<{
200
- name: "toolkit_view_state";
204
+ name: string;
201
205
  schema: undefined;
202
206
  columns: {
203
- id: _$drizzle_orm_pg_core0.PgColumn<{
204
- name: "id";
205
- tableName: "toolkit_view_state";
206
- dataType: "string";
207
- columnType: "PgUUID";
208
- data: string;
209
- driverParam: string;
210
- notNull: true;
211
- hasDefault: true;
212
- isPrimaryKey: true;
213
- isAutoincrement: false;
214
- hasRuntimeDefault: false;
215
- enumValues: undefined;
216
- baseColumn: never;
217
- identity: undefined;
218
- generated: undefined;
219
- }, {}, {}>;
220
- userId: _$drizzle_orm_pg_core0.PgColumn<{
221
- name: "user_id";
222
- tableName: "toolkit_view_state";
223
- dataType: "string";
224
- columnType: "PgUUID";
225
- data: string;
226
- driverParam: string;
227
- notNull: true;
228
- hasDefault: false;
229
- isPrimaryKey: false;
230
- isAutoincrement: false;
231
- hasRuntimeDefault: false;
232
- enumValues: undefined;
233
- baseColumn: never;
234
- identity: undefined;
235
- generated: undefined;
236
- }, {}, {}>;
237
- viewKey: _$drizzle_orm_pg_core0.PgColumn<{
238
- name: "view_key";
239
- tableName: "toolkit_view_state";
240
- dataType: "string";
241
- columnType: "PgVarchar";
242
- data: string;
243
- driverParam: string;
244
- notNull: true;
245
- hasDefault: false;
246
- isPrimaryKey: false;
247
- isAutoincrement: false;
248
- hasRuntimeDefault: false;
249
- enumValues: [string, ...string[]];
250
- baseColumn: never;
251
- identity: undefined;
252
- generated: undefined;
253
- }, {}, {
254
- length: 255;
255
- }>;
256
- state: _$drizzle_orm_pg_core0.PgColumn<{
257
- name: "state";
258
- tableName: "toolkit_view_state";
259
- dataType: "json";
260
- columnType: "PgJsonb";
207
+ [x: string]: _$drizzle_orm_pg_core0.PgColumn<{
208
+ name: string;
209
+ tableName: string;
210
+ dataType: _$drizzle_orm0.ColumnDataType;
211
+ columnType: string;
261
212
  data: unknown;
262
213
  driverParam: unknown;
263
- notNull: true;
264
- hasDefault: false;
265
- isPrimaryKey: false;
266
- isAutoincrement: false;
267
- hasRuntimeDefault: false;
268
- enumValues: undefined;
269
- baseColumn: never;
270
- identity: undefined;
271
- generated: undefined;
272
- }, {}, {}>;
273
- expiresAt: _$drizzle_orm_pg_core0.PgColumn<{
274
- name: "expires_at";
275
- tableName: "toolkit_view_state";
276
- dataType: "date";
277
- columnType: "PgTimestamp";
278
- data: Date;
279
- driverParam: string;
280
214
  notNull: false;
281
215
  hasDefault: false;
282
216
  isPrimaryKey: false;
283
217
  isAutoincrement: false;
284
218
  hasRuntimeDefault: false;
285
- enumValues: undefined;
286
- baseColumn: never;
287
- identity: undefined;
288
- generated: undefined;
289
- }, {}, {}>;
290
- updatedAt: _$drizzle_orm_pg_core0.PgColumn<{
291
- name: "updated_at";
292
- tableName: "toolkit_view_state";
293
- dataType: "date";
294
- columnType: "PgTimestamp";
295
- data: Date;
296
- driverParam: string;
297
- notNull: true;
298
- hasDefault: true;
299
- isPrimaryKey: false;
300
- isAutoincrement: false;
301
- hasRuntimeDefault: false;
302
- enumValues: undefined;
219
+ enumValues: string[] | undefined;
303
220
  baseColumn: never;
304
221
  identity: undefined;
305
222
  generated: undefined;
@@ -308,5 +225,5 @@ declare const toolkitViewState: _$drizzle_orm_pg_core0.PgTableWithColumns<{
308
225
  dialect: "pg";
309
226
  }>;
310
227
  //#endregion
311
- export { toolkitSettings, toolkitViewState };
228
+ export { toolkitSettings, toolkitSettingsTable, toolkitViewState, toolkitViewStateTable };
312
229
  //# sourceMappingURL=schema.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.mts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;;AAsBA;;;;;;;;;;;;;;;;cAAa,eAAA,yBAAe,kBAAA;;;;QAsB3B,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAQY,gBAAA,yBAAgB,kBAAA;;;;QAa5B,sBAAA,CAAA,QAAA"}
1
+ {"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 * These tables are registered for migration discovery via the `settings()`\n * plugin's `tables` field. `lumi migrate` picks them up automatically.\n */\n\nimport { jsonb, pgTable, timestamp, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\n/**\n * Typed settings table.\n *\n * Stores key-value pairs grouped by namespace and scoped\n * to global, team, or user contexts.\n *\n * scopeId uses '__global__' sentinel for global scope to avoid\n * PostgreSQL's NULL != NULL behavior in unique constraints.\n */\nexport const toolkitSettings = pgTable(\n 'toolkit_settings',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n namespace: varchar('namespace', { length: 100 }).notNull(),\n scope: varchar('scope', { length: 20 }).notNull().default('global'),\n scopeId: varchar('scope_id', { length: 100 }).notNull().default('__global__'),\n key: varchar('key', { length: 255 }).notNull(),\n locale: varchar('locale', { length: 10 }).notNull().default('_default'),\n value: jsonb('value'),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n updatedBy: uuid('updated_by'),\n },\n (table) => ({\n uniqueSetting: unique().on(\n table.namespace,\n table.scope,\n table.scopeId,\n table.key,\n table.locale,\n ),\n }),\n)\n\n/**\n * View state table.\n *\n * Stores schemaless user-scoped JSON blobs for persisting\n * UI state (table filters, column order, etc.) with optional TTL.\n */\nexport const toolkitViewState = pgTable(\n 'toolkit_view_state',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n userId: uuid('user_id').notNull(),\n viewKey: varchar('view_key', { length: 255 }).notNull(),\n state: jsonb('state').notNull(),\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => ({\n uniqueUserView: unique().on(table.userId, table.viewKey),\n }),\n)\n"],"mappings":"2GAsBA,MAAa,EAAkB,EAC7B,mBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,UAAW,EAAQ,YAAa,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC1D,MAAO,EAAQ,QAAS,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,SAAS,CACnE,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAAC,QAAQ,aAAa,CAC7E,IAAK,EAAQ,MAAO,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC9C,OAAQ,EAAQ,SAAU,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,WAAW,CACvE,MAAO,EAAM,QAAQ,CACrB,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAAC,SAAS,CAAC,YAAY,CACjF,UAAW,EAAK,aAAa,CAC9B,CACA,IAAW,CACV,cAAe,GAAQ,CAAC,GACtB,EAAM,UACN,EAAM,MACN,EAAM,QACN,EAAM,IACN,EAAM,OACP,CACF,EACF,CAQY,EAAmB,EAC9B,qBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,OAAQ,EAAK,UAAU,CAAC,SAAS,CACjC,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CACvD,MAAO,EAAM,QAAQ,CAAC,SAAS,CAC/B,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAC1D,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAAC,SAAS,CAAC,YAAY,CAClF,CACA,IAAW,CACV,eAAgB,GAAQ,CAAC,GAAG,EAAM,OAAQ,EAAM,QAAQ,CACzD,EACF"}
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 pgTable still work. */\nexport const toolkitViewState = toolkitViewStateTable.table\n"],"mappings":"0DA2BA,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,CAGW,EAAkB,EAAqB,MAQvC,EAAwB,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,CAAE,aAAc,GAAM,OAAQ,aAAc,CAAC,CACzE,UAAW,EAAO,UAAU,CAC1B,QAAS,GACT,WAAY,GACZ,aAAc,GACd,OAAQ,aACT,CAAC,CACH,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.3.0",
3
+ "version": "0.4.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,24 +28,24 @@
28
28
  "files": [
29
29
  "dist"
30
30
  ],
31
- "scripts": {
32
- "build": "tsdown",
33
- "dev": "tsdown --watch",
34
- "test": "vitest",
35
- "test:integration": "vitest run --config vitest.integration.config.ts"
36
- },
37
31
  "dependencies": {
38
- "@murumets-ee/core": "workspace:*",
39
- "@murumets-ee/db": "workspace:*",
40
- "@murumets-ee/logging": "workspace:*",
41
32
  "drizzle-orm": "^0.45.1",
42
33
  "zod": "^3.24.1",
43
- "server-only": "^0.0.1"
34
+ "server-only": "^0.0.1",
35
+ "@murumets-ee/core": "0.4.0",
36
+ "@murumets-ee/db": "0.4.0",
37
+ "@murumets-ee/logging": "0.4.0"
44
38
  },
45
39
  "devDependencies": {
46
40
  "@types/node": "^22.10.5",
47
41
  "tsdown": "^0.21.7",
48
42
  "typescript": "^5.7.3",
49
43
  "vitest": "^2.1.8"
44
+ },
45
+ "scripts": {
46
+ "build": "tsdown",
47
+ "dev": "tsdown --watch",
48
+ "test": "vitest",
49
+ "test:integration": "vitest run --config vitest.integration.config.ts"
50
50
  }
51
- }
51
+ }
@@ -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 * These tables are registered for migration discovery via the `settings()`\n * plugin's `tables` field. `lumi migrate` picks them up automatically.\n */\n\nimport { jsonb, pgTable, timestamp, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\n/**\n * Typed settings table.\n *\n * Stores key-value pairs grouped by namespace and scoped\n * to global, team, or user contexts.\n *\n * scopeId uses '__global__' sentinel for global scope to avoid\n * PostgreSQL's NULL != NULL behavior in unique constraints.\n */\nexport const toolkitSettings = pgTable(\n 'toolkit_settings',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n namespace: varchar('namespace', { length: 100 }).notNull(),\n scope: varchar('scope', { length: 20 }).notNull().default('global'),\n scopeId: varchar('scope_id', { length: 100 }).notNull().default('__global__'),\n key: varchar('key', { length: 255 }).notNull(),\n locale: varchar('locale', { length: 10 }).notNull().default('_default'),\n value: jsonb('value'),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n updatedBy: uuid('updated_by'),\n },\n (table) => ({\n uniqueSetting: unique().on(\n table.namespace,\n table.scope,\n table.scopeId,\n table.key,\n table.locale,\n ),\n }),\n)\n\n/**\n * View state table.\n *\n * Stores schemaless user-scoped JSON blobs for persisting\n * UI state (table filters, column order, etc.) with optional TTL.\n */\nexport const toolkitViewState = pgTable(\n 'toolkit_view_state',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n userId: uuid('user_id').notNull(),\n viewKey: varchar('view_key', { length: 255 }).notNull(),\n state: jsonb('state').notNull(),\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => ({\n uniqueUserView: unique().on(table.userId, table.viewKey),\n }),\n)\n","/**\n * Setting configuration types and compile-time type inference.\n *\n * Design mirrors the entity field system:\n * - Config interfaces define what each setting type accepts\n * - SettingToTS maps a single config to its TypeScript type\n * - InferSettingValue adds null awareness based on `default` presence\n * - InferSettingsMap maps an entire schema to a typed record\n */\n\nimport type { ZodType } from 'zod'\n\n// ---------------------------------------------------------------\n// 1. Setting config interfaces\n// ---------------------------------------------------------------\n\nexport interface BaseSettingConfig {\n /** Human-readable label for admin UI */\n label?: string\n /** Description / help text */\n description?: string\n /** If true, this setting can have per-locale values (mirrors entity translatable pattern) */\n translatable?: boolean\n}\n\nexport interface TextSettingConfig extends BaseSettingConfig {\n type: 'text'\n default?: string\n maxLength?: number\n minLength?: number\n pattern?: RegExp\n /** Render as textarea instead of single-line input. */\n multiline?: boolean\n}\n\nexport interface NumberSettingConfig extends BaseSettingConfig {\n type: 'number'\n default?: number\n min?: number\n max?: number\n integer?: boolean\n}\n\nexport interface BooleanSettingConfig extends BaseSettingConfig {\n type: 'boolean'\n default?: boolean\n}\n\nexport interface SelectSettingConfig<O extends readonly string[] = readonly string[]>\n extends BaseSettingConfig {\n type: 'select'\n options: O\n default?: O[number]\n}\n\nexport interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {\n type: 'json'\n default?: T\n /** Optional Zod schema for validation. If provided, values are validated on set. */\n schema?: ZodType<T>\n}\n\nexport interface MediaSettingConfig extends BaseSettingConfig {\n type: 'media'\n default?: string\n accept?: string[]\n}\n\nexport type SettingConfig =\n | TextSettingConfig\n | NumberSettingConfig\n | BooleanSettingConfig\n | SelectSettingConfig\n | JsonSettingConfig\n | MediaSettingConfig\n\n// ---------------------------------------------------------------\n// 2. Setting-to-TypeScript mapping (single setting)\n// ---------------------------------------------------------------\n\n/**\n * Maps a single SettingConfig to its TypeScript output type.\n * Each branch is a shallow comparison — no recursion.\n */\nexport type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig\n ? string\n : S extends NumberSettingConfig\n ? number\n : S extends BooleanSettingConfig\n ? boolean\n : S extends SelectSettingConfig<infer O>\n ? O[number]\n : S extends JsonSettingConfig<infer T>\n ? T\n : S extends MediaSettingConfig\n ? string\n : never\n\n// ---------------------------------------------------------------\n// 3. Null awareness: settings with defaults always return value\n// ---------------------------------------------------------------\n\n/**\n * If a setting has a `default`, get() never returns null.\n * Without a default, it returns T | null.\n */\nexport type InferSettingValue<S extends SettingConfig> = S extends { default: unknown }\n ? SettingToTS<S>\n : SettingToTS<S> | null\n\n// ---------------------------------------------------------------\n// 4. Full settings map type (what getAll() returns)\n// ---------------------------------------------------------------\n\nexport type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {\n [K in keyof Schema]: InferSettingValue<Schema[K]>\n}\n\n// ---------------------------------------------------------------\n// 5. Scope types\n// ---------------------------------------------------------------\n\nexport type SettingScope = 'global' | 'team' | 'user'\n\n/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */\nexport const GLOBAL_SCOPE_ID = '__global__'\n\n/** Sentinel value for locale column when no locale is specified (base/default value) */\nexport const DEFAULT_LOCALE = '_default'\n\n// ---------------------------------------------------------------\n// 6. Settings definition (returned by defineSettings)\n// ---------------------------------------------------------------\n\nexport interface SettingsDefinition<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n /** Unique namespace for this settings group */\n namespace: string\n /** Default scope for these settings */\n scope: SettingScope\n /** Setting schema (the shape) */\n schema: S\n /** Human-readable label for admin UI */\n label?: string\n}\n","/**\n * Generate Zod validation schemas from setting config definitions.\n * Validates values before writing to the database.\n */\n\nimport { z } from 'zod'\nimport type { SettingConfig, SettingsDefinition } from './types.js'\n\n/**\n * Convert a single setting config to a Zod schema.\n */\nexport function settingToZod(config: SettingConfig): z.ZodType {\n switch (config.type) {\n case 'text': {\n let schema: z.ZodString = z.string()\n if (config.maxLength) schema = schema.max(config.maxLength)\n if (config.minLength) schema = schema.min(config.minLength)\n if (config.pattern) schema = schema.regex(config.pattern)\n return schema\n }\n\n case 'number': {\n let schema: z.ZodNumber = z.number()\n if (config.integer) schema = schema.int()\n if (config.min !== undefined) schema = schema.min(config.min)\n if (config.max !== undefined) schema = schema.max(config.max)\n return schema\n }\n\n case 'boolean':\n return z.boolean()\n\n case 'select':\n return z.enum(config.options as [string, ...string[]])\n\n case 'json':\n return config.schema ?? z.unknown()\n\n case 'media':\n return z.string().uuid()\n\n default:\n return z.unknown()\n }\n}\n\n/**\n * Generate a validation map for all settings in a definition.\n * Returns a Record<key, ZodType> for validating individual set() calls.\n *\n * Settings without a default are nullable (matching InferSettingValue),\n * so their validators accept null.\n */\nexport function generateSettingValidators(\n definition: SettingsDefinition,\n): Record<string, z.ZodType> {\n const validators: Record<string, z.ZodType> = {}\n for (const [key, config] of Object.entries(definition.schema)) {\n let schema = settingToZod(config)\n const hasDefault = 'default' in config && config.default !== undefined\n if (!hasDefault) {\n schema = schema.nullable()\n }\n validators[key] = schema\n }\n return validators\n}\n","/**\n * SettingsClient — typed CRUD for key-value settings.\n *\n * Server-only. Uses read-write DB connection.\n * Validates values against the setting schema on set().\n *\n * Supports per-locale values for settings marked `translatable: true`.\n * Non-translatable settings always use the `__default__` locale.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n *\n * // Default locale\n * const name = await settings.get('siteName') // string (has default)\n *\n * // Locale-specific (only for translatable settings)\n * const nameEt = await settings.get('siteName', { locale: 'et' })\n *\n * await settings.set('siteName', 'Mänguväljak', { locale: 'et' })\n * ```\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { and, eq, or } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettings } from './schema.js'\nimport type {\n InferSettingsMap,\n InferSettingValue,\n SettingConfig,\n SettingScope,\n SettingsDefinition,\n} from './types.js'\nimport { DEFAULT_LOCALE, GLOBAL_SCOPE_ID } from './types.js'\nimport { generateSettingValidators } from './validation.js'\n\nexport interface SettingsClientConfig {\n /** Database client (read-write) */\n db: PostgresJsDatabase\n /** Logger instance */\n logger?: Logger\n /** Override scope (defaults to definition's scope) */\n scope?: SettingScope\n /** Scope ID (required for team/user scope, defaults to '__global__' for global) */\n scopeId?: string\n}\n\nexport interface LocaleOption {\n /** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */\n locale?: string\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private db: PostgresJsDatabase\n private logger?: Logger\n private scope: SettingScope\n private scopeId: string\n private validators: Record<string, ZodType>\n\n constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig) {\n if (typeof window !== 'undefined') {\n throw new Error('SettingsClient cannot be used in browser code.')\n }\n\n this.definition = definition\n this.db = config.db\n this.logger = config.logger\n this.scope = config.scope ?? definition.scope\n this.scopeId = config.scopeId ?? GLOBAL_SCOPE_ID\n\n if ((this.scope === 'team' || this.scope === 'user') && !config.scopeId) {\n throw new Error(\n `scopeId is required for ${this.scope}-scoped settings (namespace: ${definition.namespace})`,\n )\n }\n\n this.validators = generateSettingValidators(definition)\n }\n\n /**\n * Get a single setting value.\n *\n * For translatable settings with a locale, tries locale-specific value first,\n * then falls back to the default value, then the schema default, then null.\n */\n async get<K extends string & keyof S>(\n key: K,\n options?: LocaleOption,\n ): Promise<InferSettingValue<S[K]>> {\n const config = this.definition.schema[key]\n const locale = config?.translatable && options?.locale ? options.locale : null\n\n this.logger?.debug({ namespace: this.definition.namespace, key, locale }, 'Getting setting')\n\n if (locale) {\n // Fetch both locale-specific and default in one query\n const rows = await this.db\n .select({ locale: toolkitSettings.locale, value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n or(eq(toolkitSettings.locale, locale), eq(toolkitSettings.locale, DEFAULT_LOCALE)),\n ),\n )\n\n // Prefer locale-specific, fall back to default\n const localeRow = rows.find((r) => r.locale === locale)\n const defaultRow = rows.find((r) => r.locale === DEFAULT_LOCALE)\n const row = localeRow ?? defaultRow\n\n if (row && row.value !== undefined && row.value !== null) {\n return row.value as InferSettingValue<S[K]>\n }\n } else {\n const rows = await this.db\n .select({ value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(this.whereClause(key))\n .limit(1)\n\n if (rows.length > 0 && rows[0].value !== undefined && rows[0].value !== null) {\n return rows[0].value as InferSettingValue<S[K]>\n }\n }\n\n if (config && 'default' in config && config.default !== undefined) {\n return config.default as InferSettingValue<S[K]>\n }\n\n return null as InferSettingValue<S[K]>\n }\n\n /**\n * Get all settings for this namespace/scope as a typed object.\n * Missing values are filled from schema defaults.\n *\n * When locale is specified, translatable settings prefer the locale-specific\n * value over the default value.\n */\n async getAll(options?: LocaleOption): Promise<InferSettingsMap<S>> {\n const locale = options?.locale ?? null\n\n this.logger?.debug({ namespace: this.definition.namespace, locale }, 'Getting all settings')\n\n let rows: { key: string; locale: string; value: unknown }[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n or(eq(toolkitSettings.locale, DEFAULT_LOCALE), eq(toolkitSettings.locale, locale)),\n ),\n )\n } else {\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(and(...this.baseWhere(), eq(toolkitSettings.locale, DEFAULT_LOCALE)))\n }\n\n // Build lookup: key → { default: value, locale: value }\n const stored = new Map<string, { default?: unknown; locale?: unknown }>()\n for (const row of rows) {\n const entry = stored.get(row.key) ?? {}\n if (row.locale === DEFAULT_LOCALE) {\n entry.default = row.value\n } else {\n entry.locale = row.value\n }\n stored.set(row.key, entry)\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, config] of Object.entries(this.definition.schema)) {\n const entry = stored.get(key)\n\n // For translatable settings with locale, prefer locale-specific value\n let value: unknown\n if (config.translatable && locale && entry?.locale !== undefined && entry?.locale !== null) {\n value = entry.locale\n } else if (entry?.default !== undefined && entry?.default !== null) {\n value = entry.default\n }\n\n if (value !== undefined) {\n result[key] = value\n } else if ('default' in config && config.default !== undefined) {\n result[key] = config.default\n } else {\n result[key] = null\n }\n }\n\n return result as InferSettingsMap<S>\n }\n\n /**\n * Set a single setting value.\n * Validates against the schema before writing.\n *\n * Pass `{ locale }` to write a locale-specific value (only for translatable settings).\n */\n async set<K extends string & keyof S>(\n key: K,\n value: InferSettingValue<S[K]>,\n options?: LocaleOption,\n ): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Setting value')\n\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n\n const validator = this.validators[key]\n if (validator) {\n validator.parse(value)\n }\n\n await this.upsert(key, value as unknown, locale)\n }\n\n /**\n * Set multiple settings at once (validated individually).\n * Writes in a transaction — all or nothing.\n *\n * Pass `{ locale }` to write locale-specific values for translatable settings.\n * Non-translatable settings in the values will always write to the default locale.\n */\n async setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void> {\n this.logger?.info(\n { namespace: this.definition.namespace, keys: Object.keys(values), locale: options?.locale },\n 'Setting multiple values',\n )\n\n // Validate all first (fail fast)\n for (const [key, value] of Object.entries(values)) {\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n const validator = this.validators[key]\n if (validator && value !== undefined) {\n validator.parse(value)\n }\n }\n\n await this.db.transaction(async (tx) => {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n const locale = this.resolveLocale(key, options)\n await tx\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value: value as unknown,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value: value as unknown,\n updatedAt: new Date(),\n },\n })\n }\n })\n }\n\n /**\n * Delete a setting (resets to default on next get).\n * Pass `{ locale }` to delete only the locale-specific value.\n */\n async delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Deleting setting')\n\n await this.db.delete(toolkitSettings).where(this.whereClause(key, locale))\n }\n\n /**\n * Check if a setting has a stored value (not relying on default).\n */\n async has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean> {\n const locale = this.resolveLocale(key, options)\n\n const rows = await this.db\n .select({ key: toolkitSettings.key })\n .from(toolkitSettings)\n .where(this.whereClause(key, locale))\n .limit(1)\n\n return rows.length > 0\n }\n\n // ---------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------\n\n /**\n * Resolve which locale to use for a given key.\n * Non-translatable settings always use DEFAULT_LOCALE.\n * Translatable settings use the requested locale or DEFAULT_LOCALE.\n */\n private resolveLocale(key: string, options?: LocaleOption): string {\n const config = this.definition.schema[key as keyof S] as SettingConfig | undefined\n if (config?.translatable && options?.locale) {\n return options.locale\n }\n return DEFAULT_LOCALE\n }\n\n /** Base where conditions: namespace + scope + scopeId */\n private baseWhere() {\n return [\n eq(toolkitSettings.namespace, this.definition.namespace),\n eq(toolkitSettings.scope, this.scope),\n eq(toolkitSettings.scopeId, this.scopeId),\n ] as const\n }\n\n /** Full where clause for a specific key + locale */\n private whereClause(key: string, locale: string = DEFAULT_LOCALE) {\n return and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n eq(toolkitSettings.locale, locale),\n )!\n }\n\n /** Upsert a single setting row */\n private async upsert(key: string, value: unknown, locale: string) {\n await this.db\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value,\n updatedAt: new Date(),\n },\n })\n }\n}\n","/**\n * Factory function for creating typed SettingsClient instances.\n *\n * Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { SettingsClient } from './client.js'\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport interface CreateSettingsClientOptions {\n /** Override the toolkit app (defaults to getApp()) */\n app?: ToolkitApp\n /** Override scope from definition */\n scope?: SettingScope\n /** Scope ID for team/user scoped settings */\n scopeId?: string\n}\n\n/**\n * Create a typed SettingsClient.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n * const name = await settings.get('siteName') // string\n * ```\n */\nexport function createSettingsClient<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n options?: CreateSettingsClientOptions,\n): SettingsClient<S> {\n const app = options?.app ?? getApp()\n\n return new SettingsClient(definition, {\n db: app.db.readWrite,\n logger: app.logger.child({ settings: definition.namespace }),\n scope: options?.scope,\n scopeId: options?.scopeId,\n })\n}\n"],"mappings":"gOAsBA,MAAa,EAAkB,EAC7B,mBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,UAAW,EAAQ,YAAa,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC1D,MAAO,EAAQ,QAAS,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,SAAS,CACnE,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAAC,QAAQ,aAAa,CAC7E,IAAK,EAAQ,MAAO,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC9C,OAAQ,EAAQ,SAAU,CAAE,OAAQ,GAAI,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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