@murumets-ee/settings 0.1.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 +94 -0
- package/README.md +15 -0
- package/dist/admin.d.ts +100 -0
- package/dist/admin.js +1 -0
- package/dist/chunk-E3K4GXDC.js +1 -0
- package/dist/client-factory-OGWK5MKO.js +1 -0
- package/dist/index.d.ts +291 -0
- package/dist/index.js +1 -0
- package/dist/plugin.d.ts +22 -0
- package/dist/plugin.js +1 -0
- package/dist/schema.d.ts +316 -0
- package/dist/schema.js +1 -0
- package/dist/view-state.d.ts +68 -0
- package/dist/view-state.js +1 -0
- package/package.json +51 -0
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# @murumets-ee/settings
|
|
2
|
+
|
|
3
|
+
Key-value settings system — typed definitions, scoped storage, translatable values, and view state.
|
|
4
|
+
|
|
5
|
+
Part of [Lumi CMS](https://github.com/murumets-ee/lumi-cms) — a modular, type-safe CMS toolkit for Node.js.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @murumets-ee/settings
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## License
|
|
14
|
+
|
|
15
|
+
[Elastic License 2.0 (ELv2)](../../LICENSE)
|
package/dist/admin.d.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { AdminRoute } from '@murumets-ee/core';
|
|
2
|
+
import { ZodType } from 'zod';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Setting configuration types and compile-time type inference.
|
|
6
|
+
*
|
|
7
|
+
* Design mirrors the entity field system:
|
|
8
|
+
* - Config interfaces define what each setting type accepts
|
|
9
|
+
* - SettingToTS maps a single config to its TypeScript type
|
|
10
|
+
* - InferSettingValue adds null awareness based on `default` presence
|
|
11
|
+
* - InferSettingsMap maps an entire schema to a typed record
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
interface BaseSettingConfig {
|
|
15
|
+
/** Human-readable label for admin UI */
|
|
16
|
+
label?: string;
|
|
17
|
+
/** Description / help text */
|
|
18
|
+
description?: string;
|
|
19
|
+
/** If true, this setting can have per-locale values (mirrors entity translatable pattern) */
|
|
20
|
+
translatable?: boolean;
|
|
21
|
+
}
|
|
22
|
+
interface TextSettingConfig extends BaseSettingConfig {
|
|
23
|
+
type: 'text';
|
|
24
|
+
default?: string;
|
|
25
|
+
maxLength?: number;
|
|
26
|
+
minLength?: number;
|
|
27
|
+
pattern?: RegExp;
|
|
28
|
+
}
|
|
29
|
+
interface NumberSettingConfig extends BaseSettingConfig {
|
|
30
|
+
type: 'number';
|
|
31
|
+
default?: number;
|
|
32
|
+
min?: number;
|
|
33
|
+
max?: number;
|
|
34
|
+
integer?: boolean;
|
|
35
|
+
}
|
|
36
|
+
interface BooleanSettingConfig extends BaseSettingConfig {
|
|
37
|
+
type: 'boolean';
|
|
38
|
+
default?: boolean;
|
|
39
|
+
}
|
|
40
|
+
interface SelectSettingConfig<O extends readonly string[] = readonly string[]> extends BaseSettingConfig {
|
|
41
|
+
type: 'select';
|
|
42
|
+
options: O;
|
|
43
|
+
default?: O[number];
|
|
44
|
+
}
|
|
45
|
+
interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {
|
|
46
|
+
type: 'json';
|
|
47
|
+
default?: T;
|
|
48
|
+
/** Optional Zod schema for validation. If provided, values are validated on set. */
|
|
49
|
+
schema?: ZodType<T>;
|
|
50
|
+
}
|
|
51
|
+
interface MediaSettingConfig extends BaseSettingConfig {
|
|
52
|
+
type: 'media';
|
|
53
|
+
accept?: string[];
|
|
54
|
+
}
|
|
55
|
+
type SettingConfig = TextSettingConfig | NumberSettingConfig | BooleanSettingConfig | SelectSettingConfig | JsonSettingConfig | MediaSettingConfig;
|
|
56
|
+
type SettingScope = 'global' | 'team' | 'user';
|
|
57
|
+
interface SettingsDefinition<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {
|
|
58
|
+
/** Unique namespace for this settings group */
|
|
59
|
+
namespace: string;
|
|
60
|
+
/** Default scope for these settings */
|
|
61
|
+
scope: SettingScope;
|
|
62
|
+
/** Setting schema (the shape) */
|
|
63
|
+
schema: S;
|
|
64
|
+
/** Human-readable label for admin UI */
|
|
65
|
+
label?: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Settings admin routes for the centralized admin API handler.
|
|
70
|
+
*
|
|
71
|
+
* Provides get/update operations for typed settings.
|
|
72
|
+
* All auth, CSRF, and role checks are handled by the parent handler.
|
|
73
|
+
* Settings mutations require admin role (not editor).
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```typescript
|
|
77
|
+
* import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'
|
|
78
|
+
* import { settingsRoutes } from '@murumets-ee/settings/admin'
|
|
79
|
+
* import { siteSettings } from '@/settings/site'
|
|
80
|
+
*
|
|
81
|
+
* const handler = createAdminApiHandler({
|
|
82
|
+
* authenticate: async (req) => { ... },
|
|
83
|
+
* entities: [Article],
|
|
84
|
+
* routes: [settingsRoutes(siteSettings)],
|
|
85
|
+
* })
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Create admin API routes for settings management.
|
|
91
|
+
*
|
|
92
|
+
* Routes:
|
|
93
|
+
* - `GET /api/admin/settings` — Get all settings (query: `?locale=`)
|
|
94
|
+
* - `PATCH /api/admin/settings` — Update settings (JSON body: `{ values, locale? }`)
|
|
95
|
+
*
|
|
96
|
+
* @param definition - The settings definition (created by defineSettings)
|
|
97
|
+
*/
|
|
98
|
+
declare function settingsRoutes<S extends Record<string, SettingConfig>>(definition: SettingsDefinition<S>): AdminRoute;
|
|
99
|
+
|
|
100
|
+
export { settingsRoutes };
|
package/dist/admin.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function u(t,e=200){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":"application/json"}})}function p(t,e){return u({error:t},e)}function d(t){let e=null;function c(){return e||(e=(async()=>{let{getApp:s}=await import("@murumets-ee/core"),{createSettingsClient:i}=await import("./client-factory-OGWK5MKO.js"),o=s();return i(t,{app:o})})()),e}async function g(s,i){let o=await c(),r=new URL(s.url).searchParams.get("locale")??void 0,n=await o.getAll(r?{locale:r}:void 0);return u(n)}async function m(s,{user:i,audit:o}){let l=await c(),r=await s.json(),{values:n,locale:a}=r;return!n||typeof n!="object"?p('Body must contain "values" object',400):(await l.setMany(n,a?{locale:a}:void 0),o?.({action:"settings.update",entityType:"settings",userId:i.id,userName:i.name,changes:{fields:n},metadata:{namespace:t.namespace,...a?{locale:a}:{}}}),u({success:!0}))}return{prefix:"settings",resource:"settings",actions:["view","update"],handlers:{GET:g,PATCH:m}}}export{d as settingsRoutes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonb as u,pgTable as a,timestamp as o,unique as i,uuid as l,varchar as t}from"drizzle-orm/pg-core";var d=a("toolkit_settings",{id:l("id").primaryKey().defaultRandom(),namespace:t("namespace",{length:100}).notNull(),scope:t("scope",{length:20}).notNull().default("global"),scopeId:t("scope_id",{length:100}).notNull().default("__global__"),key:t("key",{length:255}).notNull(),locale:t("locale",{length:10}).notNull().default("_default"),value:u("value"),updatedAt:o("updated_at",{withTimezone:!0}).notNull().defaultNow(),updatedBy:l("updated_by")},e=>({uniqueSetting:i().on(e.namespace,e.scope,e.scopeId,e.key,e.locale)})),s=a("toolkit_view_state",{id:l("id").primaryKey().defaultRandom(),userId:l("user_id").notNull(),viewKey:t("view_key",{length:255}).notNull(),state:u("state").notNull(),expiresAt:o("expires_at",{withTimezone:!0}),updatedAt:o("updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>({uniqueUserView:i().on(e.userId,e.viewKey)}));export{d as a,s as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getApp as L}from"@murumets-ee/core";import{and as S,eq as c,or as k}from"drizzle-orm";import{jsonb as y,pgTable as x,timestamp as w,unique as b,uuid as m,varchar as u}from"drizzle-orm/pg-core";var t=x("toolkit_settings",{id:m("id").primaryKey().defaultRandom(),namespace:u("namespace",{length:100}).notNull(),scope:u("scope",{length:20}).notNull().default("global"),scopeId:u("scope_id",{length:100}).notNull().default("__global__"),key:u("key",{length:255}).notNull(),locale:u("locale",{length:10}).notNull().default("_default"),value:y("value"),updatedAt:w("updated_at",{withTimezone:!0}).notNull().defaultNow(),updatedBy:m("updated_by")},i=>({uniqueSetting:b().on(i.namespace,i.scope,i.scopeId,i.key,i.locale)})),O=x("toolkit_view_state",{id:m("id").primaryKey().defaultRandom(),userId:m("user_id").notNull(),viewKey:u("view_key",{length:255}).notNull(),state:y("state").notNull(),expiresAt:w("expires_at",{withTimezone:!0}),updatedAt:w("updated_at",{withTimezone:!0}).notNull().defaultNow()},i=>({uniqueUserView:b().on(i.userId,i.viewKey)}));var C="__global__",p="_default";import{z as f}from"zod";function I(i){switch(i.type){case"text":{let e=f.string();return i.maxLength&&(e=e.max(i.maxLength)),i.minLength&&(e=e.min(i.minLength)),i.pattern&&(e=e.regex(i.pattern)),e}case"number":{let e=f.number();return i.integer&&(e=e.int()),i.min!==void 0&&(e=e.min(i.min)),i.max!==void 0&&(e=e.max(i.max)),e}case"boolean":return f.boolean();case"select":return f.enum(i.options);case"json":return i.schema??f.unknown();case"media":return f.string().uuid();default:return f.unknown()}}function v(i){let e={};for(let[n,o]of Object.entries(i.schema)){let a=I(o);"default"in o&&o.default!==void 0||(a=a.nullable()),e[n]=a}return e}var h=class{definition;db;logger;scope;scopeId;validators;constructor(e,n){if(typeof window<"u")throw new Error("SettingsClient cannot be used in browser code.");if(this.definition=e,this.db=n.db,this.logger=n.logger,this.scope=n.scope??e.scope,this.scopeId=n.scopeId??C,(this.scope==="team"||this.scope==="user")&&!n.scopeId)throw new Error(`scopeId is required for ${this.scope}-scoped settings (namespace: ${e.namespace})`);this.validators=v(e)}async get(e,n){let o=this.definition.schema[e],a=o?.translatable&&n?.locale?n.locale:null;if(this.logger?.debug({namespace:this.definition.namespace,key:e,locale:a},"Getting setting"),a){let s=await this.db.select({locale:t.locale,value:t.value}).from(t).where(S(...this.baseWhere(),c(t.key,e),k(c(t.locale,a),c(t.locale,p)))),r=s.find(d=>d.locale===a),g=s.find(d=>d.locale===p),l=r??g;if(l&&l.value!==void 0&&l.value!==null)return l.value}else{let s=await this.db.select({value:t.value}).from(t).where(this.whereClause(e)).limit(1);if(s.length>0&&s[0].value!==void 0&&s[0].value!==null)return s[0].value}return o&&"default"in o&&o.default!==void 0?o.default:null}async getAll(e){let n=e?.locale??null;this.logger?.debug({namespace:this.definition.namespace,locale:n},"Getting all settings");let o;n?o=await this.db.select({key:t.key,locale:t.locale,value:t.value}).from(t).where(S(...this.baseWhere(),k(c(t.locale,p),c(t.locale,n)))):o=await this.db.select({key:t.key,locale:t.locale,value:t.value}).from(t).where(S(...this.baseWhere(),c(t.locale,p)));let a=new Map;for(let r of o){let g=a.get(r.key)??{};r.locale===p?g.default=r.value:g.locale=r.value,a.set(r.key,g)}let s={};for(let[r,g]of Object.entries(this.definition.schema)){let l=a.get(r),d;g.translatable&&n&&l?.locale!==void 0&&l?.locale!==null?d=l.locale:l?.default!==void 0&&l?.default!==null&&(d=l.default),d!==void 0?s[r]=d:"default"in g&&g.default!==void 0?s[r]=g.default:s[r]=null}return s}async set(e,n,o){let a=this.resolveLocale(e,o);if(this.logger?.info({namespace:this.definition.namespace,key:e,locale:a},"Setting value"),!(e in this.definition.schema))throw new Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let s=this.validators[e];s&&s.parse(n),await this.upsert(e,n,a)}async setMany(e,n){this.logger?.info({namespace:this.definition.namespace,keys:Object.keys(e),locale:n?.locale},"Setting multiple values");for(let[o,a]of Object.entries(e)){if(!(o in this.definition.schema))throw new Error(`Unknown setting key '${o}' in namespace '${this.definition.namespace}'`);let s=this.validators[o];s&&a!==void 0&&s.parse(a)}await this.db.transaction(async o=>{for(let[a,s]of Object.entries(e)){if(s===void 0)continue;let r=this.resolveLocale(a,n);await o.insert(t).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:a,locale:r,value:s,updatedAt:new Date}).onConflictDoUpdate({target:[t.namespace,t.scope,t.scopeId,t.key,t.locale],set:{value:s,updatedAt:new Date}})}})}async delete(e,n){let o=this.resolveLocale(e,n);this.logger?.info({namespace:this.definition.namespace,key:e,locale:o},"Deleting setting"),await this.db.delete(t).where(this.whereClause(e,o))}async has(e,n){let o=this.resolveLocale(e,n);return(await this.db.select({key:t.key}).from(t).where(this.whereClause(e,o)).limit(1)).length>0}resolveLocale(e,n){return this.definition.schema[e]?.translatable&&n?.locale?n.locale:p}baseWhere(){return[c(t.namespace,this.definition.namespace),c(t.scope,this.scope),c(t.scopeId,this.scopeId)]}whereClause(e,n=p){return S(...this.baseWhere(),c(t.key,e),c(t.locale,n))}async upsert(e,n,o){await this.db.insert(t).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:e,locale:o,value:n,updatedAt:new Date}).onConflictDoUpdate({target:[t.namespace,t.scope,t.scopeId,t.key,t.locale],set:{value:n,updatedAt:new Date}})}};function E(i,e){let n=e?.app??L();return new h(i,{db:n.db.readWrite,logger:n.logger.child({settings:i.namespace}),scope:e?.scope,scopeId:e?.scopeId})}export{E as createSettingsClient};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { ZodType } from 'zod';
|
|
2
|
+
import { Logger, ToolkitApp } from '@murumets-ee/core';
|
|
3
|
+
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Setting configuration types and compile-time type inference.
|
|
7
|
+
*
|
|
8
|
+
* Design mirrors the entity field system:
|
|
9
|
+
* - Config interfaces define what each setting type accepts
|
|
10
|
+
* - SettingToTS maps a single config to its TypeScript type
|
|
11
|
+
* - InferSettingValue adds null awareness based on `default` presence
|
|
12
|
+
* - InferSettingsMap maps an entire schema to a typed record
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
interface BaseSettingConfig {
|
|
16
|
+
/** Human-readable label for admin UI */
|
|
17
|
+
label?: string;
|
|
18
|
+
/** Description / help text */
|
|
19
|
+
description?: string;
|
|
20
|
+
/** If true, this setting can have per-locale values (mirrors entity translatable pattern) */
|
|
21
|
+
translatable?: boolean;
|
|
22
|
+
}
|
|
23
|
+
interface TextSettingConfig extends BaseSettingConfig {
|
|
24
|
+
type: 'text';
|
|
25
|
+
default?: string;
|
|
26
|
+
maxLength?: number;
|
|
27
|
+
minLength?: number;
|
|
28
|
+
pattern?: RegExp;
|
|
29
|
+
}
|
|
30
|
+
interface NumberSettingConfig extends BaseSettingConfig {
|
|
31
|
+
type: 'number';
|
|
32
|
+
default?: number;
|
|
33
|
+
min?: number;
|
|
34
|
+
max?: number;
|
|
35
|
+
integer?: boolean;
|
|
36
|
+
}
|
|
37
|
+
interface BooleanSettingConfig extends BaseSettingConfig {
|
|
38
|
+
type: 'boolean';
|
|
39
|
+
default?: boolean;
|
|
40
|
+
}
|
|
41
|
+
interface SelectSettingConfig<O extends readonly string[] = readonly string[]> extends BaseSettingConfig {
|
|
42
|
+
type: 'select';
|
|
43
|
+
options: O;
|
|
44
|
+
default?: O[number];
|
|
45
|
+
}
|
|
46
|
+
interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {
|
|
47
|
+
type: 'json';
|
|
48
|
+
default?: T;
|
|
49
|
+
/** Optional Zod schema for validation. If provided, values are validated on set. */
|
|
50
|
+
schema?: ZodType<T>;
|
|
51
|
+
}
|
|
52
|
+
interface MediaSettingConfig extends BaseSettingConfig {
|
|
53
|
+
type: 'media';
|
|
54
|
+
accept?: string[];
|
|
55
|
+
}
|
|
56
|
+
type SettingConfig = TextSettingConfig | NumberSettingConfig | BooleanSettingConfig | SelectSettingConfig | JsonSettingConfig | MediaSettingConfig;
|
|
57
|
+
/**
|
|
58
|
+
* Maps a single SettingConfig to its TypeScript output type.
|
|
59
|
+
* Each branch is a shallow comparison — no recursion.
|
|
60
|
+
*/
|
|
61
|
+
type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig ? string : S extends NumberSettingConfig ? number : S extends BooleanSettingConfig ? boolean : S extends SelectSettingConfig<infer O> ? O[number] : S extends JsonSettingConfig<infer T> ? T : S extends MediaSettingConfig ? string : never;
|
|
62
|
+
/**
|
|
63
|
+
* If a setting has a `default`, get() never returns null.
|
|
64
|
+
* Without a default, it returns T | null.
|
|
65
|
+
*/
|
|
66
|
+
type InferSettingValue<S extends SettingConfig> = S extends {
|
|
67
|
+
default: unknown;
|
|
68
|
+
} ? SettingToTS<S> : SettingToTS<S> | null;
|
|
69
|
+
type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {
|
|
70
|
+
[K in keyof Schema]: InferSettingValue<Schema[K]>;
|
|
71
|
+
};
|
|
72
|
+
type SettingScope = 'global' | 'team' | 'user';
|
|
73
|
+
/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */
|
|
74
|
+
declare const GLOBAL_SCOPE_ID = "__global__";
|
|
75
|
+
/** Sentinel value for locale column when no locale is specified (base/default value) */
|
|
76
|
+
declare const DEFAULT_LOCALE = "_default";
|
|
77
|
+
interface SettingsDefinition<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {
|
|
78
|
+
/** Unique namespace for this settings group */
|
|
79
|
+
namespace: string;
|
|
80
|
+
/** Default scope for these settings */
|
|
81
|
+
scope: SettingScope;
|
|
82
|
+
/** Setting schema (the shape) */
|
|
83
|
+
schema: S;
|
|
84
|
+
/** Human-readable label for admin UI */
|
|
85
|
+
label?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Fluent API for building setting definitions.
|
|
90
|
+
*
|
|
91
|
+
* Each builder uses a `const` generic parameter on the config to preserve
|
|
92
|
+
* literal types (e.g., `default: 'My Site'` stays literal, not `string`).
|
|
93
|
+
* This enables compile-time type inference in the settings system.
|
|
94
|
+
*
|
|
95
|
+
* Pattern matches packages/entity/src/fields/builders.ts exactly.
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
declare const setting: {
|
|
99
|
+
/**
|
|
100
|
+
* Text setting (string value)
|
|
101
|
+
*/
|
|
102
|
+
text: <const C extends Partial<Omit<TextSettingConfig, "type">> = {}>(config?: C) => TextSettingConfig & C;
|
|
103
|
+
/**
|
|
104
|
+
* Number setting
|
|
105
|
+
*/
|
|
106
|
+
number: <const C extends Partial<Omit<NumberSettingConfig, "type">> = {}>(config?: C) => NumberSettingConfig & C;
|
|
107
|
+
/**
|
|
108
|
+
* Boolean setting
|
|
109
|
+
*/
|
|
110
|
+
boolean: <const C extends Partial<Omit<BooleanSettingConfig, "type">> = {}>(config?: C) => BooleanSettingConfig & C;
|
|
111
|
+
/**
|
|
112
|
+
* Select setting (enum from options tuple)
|
|
113
|
+
* Preserves literal option types for type inference.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* setting.select({ options: ['light', 'dark', 'system'] as const, default: 'system' })
|
|
117
|
+
* // inferred type: 'light' | 'dark' | 'system'
|
|
118
|
+
*/
|
|
119
|
+
select: <const O extends readonly string[], const C extends Partial<Omit<SelectSettingConfig, "type" | "options">> = {}>(config: {
|
|
120
|
+
options: O;
|
|
121
|
+
} & C) => SelectSettingConfig<O> & C;
|
|
122
|
+
/**
|
|
123
|
+
* JSON setting (arbitrary typed JSON)
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* setting.json<{ twitter?: string; github?: string }>()
|
|
127
|
+
* setting.json<string[]>({ default: [] })
|
|
128
|
+
*/
|
|
129
|
+
json: <T = unknown, const C extends Partial<Omit<JsonSettingConfig<T>, "type">> = {}>(config?: C) => JsonSettingConfig<T> & C;
|
|
130
|
+
/**
|
|
131
|
+
* Media setting (stores media ID as string UUID)
|
|
132
|
+
*/
|
|
133
|
+
media: <const C extends Partial<Omit<MediaSettingConfig, "type">> = {}>(config?: C) => MediaSettingConfig & C;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* SettingsClient — typed CRUD for key-value settings.
|
|
138
|
+
*
|
|
139
|
+
* Server-only. Uses read-write DB connection.
|
|
140
|
+
* Validates values against the setting schema on set().
|
|
141
|
+
*
|
|
142
|
+
* Supports per-locale values for settings marked `translatable: true`.
|
|
143
|
+
* Non-translatable settings always use the `__default__` locale.
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* ```typescript
|
|
147
|
+
* import { createSettingsClient } from '@murumets-ee/settings'
|
|
148
|
+
* import { siteSettings } from './settings/site'
|
|
149
|
+
*
|
|
150
|
+
* const settings = createSettingsClient(siteSettings)
|
|
151
|
+
*
|
|
152
|
+
* // Default locale
|
|
153
|
+
* const name = await settings.get('siteName') // string (has default)
|
|
154
|
+
*
|
|
155
|
+
* // Locale-specific (only for translatable settings)
|
|
156
|
+
* const nameEt = await settings.get('siteName', { locale: 'et' })
|
|
157
|
+
*
|
|
158
|
+
* await settings.set('siteName', 'Mänguväljak', { locale: 'et' })
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
|
|
162
|
+
interface SettingsClientConfig {
|
|
163
|
+
/** Database client (read-write) */
|
|
164
|
+
db: PostgresJsDatabase;
|
|
165
|
+
/** Logger instance */
|
|
166
|
+
logger?: Logger;
|
|
167
|
+
/** Override scope (defaults to definition's scope) */
|
|
168
|
+
scope?: SettingScope;
|
|
169
|
+
/** Scope ID (required for team/user scope, defaults to '__global__' for global) */
|
|
170
|
+
scopeId?: string;
|
|
171
|
+
}
|
|
172
|
+
interface LocaleOption {
|
|
173
|
+
/** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */
|
|
174
|
+
locale?: string;
|
|
175
|
+
}
|
|
176
|
+
declare class SettingsClient<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {
|
|
177
|
+
private definition;
|
|
178
|
+
private db;
|
|
179
|
+
private logger?;
|
|
180
|
+
private scope;
|
|
181
|
+
private scopeId;
|
|
182
|
+
private validators;
|
|
183
|
+
constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig);
|
|
184
|
+
/**
|
|
185
|
+
* Get a single setting value.
|
|
186
|
+
*
|
|
187
|
+
* For translatable settings with a locale, tries locale-specific value first,
|
|
188
|
+
* then falls back to the default value, then the schema default, then null.
|
|
189
|
+
*/
|
|
190
|
+
get<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<InferSettingValue<S[K]>>;
|
|
191
|
+
/**
|
|
192
|
+
* Get all settings for this namespace/scope as a typed object.
|
|
193
|
+
* Missing values are filled from schema defaults.
|
|
194
|
+
*
|
|
195
|
+
* When locale is specified, translatable settings prefer the locale-specific
|
|
196
|
+
* value over the default value.
|
|
197
|
+
*/
|
|
198
|
+
getAll(options?: LocaleOption): Promise<InferSettingsMap<S>>;
|
|
199
|
+
/**
|
|
200
|
+
* Set a single setting value.
|
|
201
|
+
* Validates against the schema before writing.
|
|
202
|
+
*
|
|
203
|
+
* Pass `{ locale }` to write a locale-specific value (only for translatable settings).
|
|
204
|
+
*/
|
|
205
|
+
set<K extends string & keyof S>(key: K, value: InferSettingValue<S[K]>, options?: LocaleOption): Promise<void>;
|
|
206
|
+
/**
|
|
207
|
+
* Set multiple settings at once (validated individually).
|
|
208
|
+
* Writes in a transaction — all or nothing.
|
|
209
|
+
*
|
|
210
|
+
* Pass `{ locale }` to write locale-specific values for translatable settings.
|
|
211
|
+
* Non-translatable settings in the values will always write to the default locale.
|
|
212
|
+
*/
|
|
213
|
+
setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void>;
|
|
214
|
+
/**
|
|
215
|
+
* Delete a setting (resets to default on next get).
|
|
216
|
+
* Pass `{ locale }` to delete only the locale-specific value.
|
|
217
|
+
*/
|
|
218
|
+
delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void>;
|
|
219
|
+
/**
|
|
220
|
+
* Check if a setting has a stored value (not relying on default).
|
|
221
|
+
*/
|
|
222
|
+
has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean>;
|
|
223
|
+
/**
|
|
224
|
+
* Resolve which locale to use for a given key.
|
|
225
|
+
* Non-translatable settings always use DEFAULT_LOCALE.
|
|
226
|
+
* Translatable settings use the requested locale or DEFAULT_LOCALE.
|
|
227
|
+
*/
|
|
228
|
+
private resolveLocale;
|
|
229
|
+
/** Base where conditions: namespace + scope + scopeId */
|
|
230
|
+
private baseWhere;
|
|
231
|
+
/** Full where clause for a specific key + locale */
|
|
232
|
+
private whereClause;
|
|
233
|
+
/** Upsert a single setting row */
|
|
234
|
+
private upsert;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Factory function for creating typed SettingsClient instances.
|
|
239
|
+
*
|
|
240
|
+
* Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.
|
|
241
|
+
*/
|
|
242
|
+
|
|
243
|
+
interface CreateSettingsClientOptions {
|
|
244
|
+
/** Override the toolkit app (defaults to getApp()) */
|
|
245
|
+
app?: ToolkitApp;
|
|
246
|
+
/** Override scope from definition */
|
|
247
|
+
scope?: SettingScope;
|
|
248
|
+
/** Scope ID for team/user scoped settings */
|
|
249
|
+
scopeId?: string;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Create a typed SettingsClient.
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* ```typescript
|
|
256
|
+
* import { createSettingsClient } from '@murumets-ee/settings'
|
|
257
|
+
* import { siteSettings } from './settings/site'
|
|
258
|
+
*
|
|
259
|
+
* const settings = createSettingsClient(siteSettings)
|
|
260
|
+
* const name = await settings.get('siteName') // string
|
|
261
|
+
* ```
|
|
262
|
+
*/
|
|
263
|
+
declare function createSettingsClient<S extends Record<string, SettingConfig>>(definition: SettingsDefinition<S>, options?: CreateSettingsClientOptions): SettingsClient<S>;
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Define a typed settings group.
|
|
267
|
+
*
|
|
268
|
+
* @example
|
|
269
|
+
* ```typescript
|
|
270
|
+
* import { defineSettings, setting } from '@murumets-ee/settings'
|
|
271
|
+
*
|
|
272
|
+
* export const siteSettings = defineSettings({
|
|
273
|
+
* namespace: 'site',
|
|
274
|
+
* scope: 'global',
|
|
275
|
+
* schema: {
|
|
276
|
+
* siteName: setting.text({ default: 'My Site' }),
|
|
277
|
+
* logo: setting.media(),
|
|
278
|
+
* maintenance: setting.boolean({ default: false }),
|
|
279
|
+
* },
|
|
280
|
+
* })
|
|
281
|
+
* ```
|
|
282
|
+
*/
|
|
283
|
+
|
|
284
|
+
declare function defineSettings<const S extends Record<string, SettingConfig>>(definition: {
|
|
285
|
+
namespace: string;
|
|
286
|
+
scope: SettingScope;
|
|
287
|
+
schema: S;
|
|
288
|
+
label?: string;
|
|
289
|
+
}): SettingsDefinition<S>;
|
|
290
|
+
|
|
291
|
+
export { type BaseSettingConfig, type BooleanSettingConfig, type CreateSettingsClientOptions, DEFAULT_LOCALE, GLOBAL_SCOPE_ID, type InferSettingValue, type InferSettingsMap, type JsonSettingConfig, type LocaleOption, type MediaSettingConfig, type NumberSettingConfig, type SelectSettingConfig, type SettingConfig, type SettingScope, type SettingToTS, SettingsClient, type SettingsClientConfig, type SettingsDefinition, type TextSettingConfig, createSettingsClient, defineSettings, setting };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as t}from"./chunk-E3K4GXDC.js";import"server-only";var x={text:n=>({type:"text",...n}),number:n=>({type:"number",...n}),boolean:n=>({type:"boolean",...n}),select:n=>({type:"select",...n}),json:n=>({type:"json",...n}),media:n=>({type:"media",...n})};import{and as u,eq as l,or as h}from"drizzle-orm";var m="__global__",f="_default";import{z as d}from"zod";function y(n){switch(n.type){case"text":{let e=d.string();return n.maxLength&&(e=e.max(n.maxLength)),n.minLength&&(e=e.min(n.minLength)),n.pattern&&(e=e.regex(n.pattern)),e}case"number":{let e=d.number();return n.integer&&(e=e.int()),n.min!==void 0&&(e=e.min(n.min)),n.max!==void 0&&(e=e.max(n.max)),e}case"boolean":return d.boolean();case"select":return d.enum(n.options);case"json":return n.schema??d.unknown();case"media":return d.string().uuid();default:return d.unknown()}}function C(n){let e={};for(let[i,o]of Object.entries(n.schema)){let a=y(o);"default"in o&&o.default!==void 0||(a=a.nullable()),e[i]=a}return e}var S=class{definition;db;logger;scope;scopeId;validators;constructor(e,i){if(typeof window<"u")throw new Error("SettingsClient cannot be used in browser code.");if(this.definition=e,this.db=i.db,this.logger=i.logger,this.scope=i.scope??e.scope,this.scopeId=i.scopeId??m,(this.scope==="team"||this.scope==="user")&&!i.scopeId)throw new Error(`scopeId is required for ${this.scope}-scoped settings (namespace: ${e.namespace})`);this.validators=C(e)}async get(e,i){let o=this.definition.schema[e],a=o?.translatable&&i?.locale?i.locale:null;if(this.logger?.debug({namespace:this.definition.namespace,key:e,locale:a},"Getting setting"),a){let s=await this.db.select({locale:t.locale,value:t.value}).from(t).where(u(...this.baseWhere(),l(t.key,e),h(l(t.locale,a),l(t.locale,f)))),r=s.find(p=>p.locale===a),c=s.find(p=>p.locale===f),g=r??c;if(g&&g.value!==void 0&&g.value!==null)return g.value}else{let s=await this.db.select({value:t.value}).from(t).where(this.whereClause(e)).limit(1);if(s.length>0&&s[0].value!==void 0&&s[0].value!==null)return s[0].value}return o&&"default"in o&&o.default!==void 0?o.default:null}async getAll(e){let i=e?.locale??null;this.logger?.debug({namespace:this.definition.namespace,locale:i},"Getting all settings");let o;i?o=await this.db.select({key:t.key,locale:t.locale,value:t.value}).from(t).where(u(...this.baseWhere(),h(l(t.locale,f),l(t.locale,i)))):o=await this.db.select({key:t.key,locale:t.locale,value:t.value}).from(t).where(u(...this.baseWhere(),l(t.locale,f)));let a=new Map;for(let r of o){let c=a.get(r.key)??{};r.locale===f?c.default=r.value:c.locale=r.value,a.set(r.key,c)}let s={};for(let[r,c]of Object.entries(this.definition.schema)){let g=a.get(r),p;c.translatable&&i&&g?.locale!==void 0&&g?.locale!==null?p=g.locale:g?.default!==void 0&&g?.default!==null&&(p=g.default),p!==void 0?s[r]=p:"default"in c&&c.default!==void 0?s[r]=c.default:s[r]=null}return s}async set(e,i,o){let a=this.resolveLocale(e,o);if(this.logger?.info({namespace:this.definition.namespace,key:e,locale:a},"Setting value"),!(e in this.definition.schema))throw new Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let s=this.validators[e];s&&s.parse(i),await this.upsert(e,i,a)}async setMany(e,i){this.logger?.info({namespace:this.definition.namespace,keys:Object.keys(e),locale:i?.locale},"Setting multiple values");for(let[o,a]of Object.entries(e)){if(!(o in this.definition.schema))throw new Error(`Unknown setting key '${o}' in namespace '${this.definition.namespace}'`);let s=this.validators[o];s&&a!==void 0&&s.parse(a)}await this.db.transaction(async o=>{for(let[a,s]of Object.entries(e)){if(s===void 0)continue;let r=this.resolveLocale(a,i);await o.insert(t).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:a,locale:r,value:s,updatedAt:new Date}).onConflictDoUpdate({target:[t.namespace,t.scope,t.scopeId,t.key,t.locale],set:{value:s,updatedAt:new Date}})}})}async delete(e,i){let o=this.resolveLocale(e,i);this.logger?.info({namespace:this.definition.namespace,key:e,locale:o},"Deleting setting"),await this.db.delete(t).where(this.whereClause(e,o))}async has(e,i){let o=this.resolveLocale(e,i);return(await this.db.select({key:t.key}).from(t).where(this.whereClause(e,o)).limit(1)).length>0}resolveLocale(e,i){return this.definition.schema[e]?.translatable&&i?.locale?i.locale:f}baseWhere(){return[l(t.namespace,this.definition.namespace),l(t.scope,this.scope),l(t.scopeId,this.scopeId)]}whereClause(e,i=f){return u(...this.baseWhere(),l(t.key,e),l(t.locale,i))}async upsert(e,i,o){await this.db.insert(t).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:e,locale:o,value:i,updatedAt:new Date}).onConflictDoUpdate({target:[t.namespace,t.scope,t.scopeId,t.key,t.locale],set:{value:i,updatedAt:new Date}})}};import{getApp as b}from"@murumets-ee/core";function w(n,e){let i=e?.app??b();return new S(n,{db:i.db.readWrite,logger:i.logger.child({settings:n.namespace}),scope:e?.scope,scopeId:e?.scopeId})}function v(n){if(!n.namespace)throw new Error("Settings namespace is required");if(!n.schema||Object.keys(n.schema).length===0)throw new Error("Settings schema must have at least one setting");return n}export{f as DEFAULT_LOCALE,m as GLOBAL_SCOPE_ID,S as SettingsClient,w as createSettingsClient,v as defineSettings,x as setting};
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Plugin } from '@murumets-ee/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Settings plugin for @murumets-ee/core.
|
|
5
|
+
*
|
|
6
|
+
* Registers the settings Drizzle tables with the schema registry
|
|
7
|
+
* so they can be discovered for migrations and queries.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { defineConfig } from '@murumets-ee/core'
|
|
12
|
+
* import { settings } from '@murumets-ee/settings/plugin'
|
|
13
|
+
*
|
|
14
|
+
* export default defineConfig({
|
|
15
|
+
* plugins: [settings()],
|
|
16
|
+
* })
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
declare function settings(): Plugin;
|
|
21
|
+
|
|
22
|
+
export { settings };
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function s(){return{name:"@murumets-ee/settings",init:async i=>{let{schemaRegistry:t}=await import("@murumets-ee/db"),{toolkitSettings:e,toolkitViewState:o}=await import("./schema.js");t.has("toolkit_settings")||t.register("toolkit_settings",e),t.has("toolkit_view_state")||t.register("toolkit_view_state",o),i.logger.info("Settings plugin initialized")}}}export{s as settings};
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Drizzle schema for settings tables.
|
|
5
|
+
*
|
|
6
|
+
* Two tables:
|
|
7
|
+
* - toolkit_settings: typed key-value settings grouped by namespace and scope
|
|
8
|
+
* - toolkit_view_state: schemaless user-scoped JSON blobs with optional TTL
|
|
9
|
+
*
|
|
10
|
+
* Usage in drizzle.config.ts:
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import type { Config } from 'drizzle-kit'
|
|
13
|
+
* export default {
|
|
14
|
+
* schema: ['./generated/schema.ts', '@murumets-ee/settings/schema'],
|
|
15
|
+
* // ...
|
|
16
|
+
* } satisfies Config
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Typed settings table.
|
|
21
|
+
*
|
|
22
|
+
* Stores key-value pairs grouped by namespace and scoped
|
|
23
|
+
* to global, team, or user contexts.
|
|
24
|
+
*
|
|
25
|
+
* scopeId uses '__global__' sentinel for global scope to avoid
|
|
26
|
+
* PostgreSQL's NULL != NULL behavior in unique constraints.
|
|
27
|
+
*/
|
|
28
|
+
declare const toolkitSettings: drizzle_orm_pg_core.PgTableWithColumns<{
|
|
29
|
+
name: "toolkit_settings";
|
|
30
|
+
schema: undefined;
|
|
31
|
+
columns: {
|
|
32
|
+
id: drizzle_orm_pg_core.PgColumn<{
|
|
33
|
+
name: "id";
|
|
34
|
+
tableName: "toolkit_settings";
|
|
35
|
+
dataType: "string";
|
|
36
|
+
columnType: "PgUUID";
|
|
37
|
+
data: string;
|
|
38
|
+
driverParam: string;
|
|
39
|
+
notNull: true;
|
|
40
|
+
hasDefault: true;
|
|
41
|
+
isPrimaryKey: true;
|
|
42
|
+
isAutoincrement: false;
|
|
43
|
+
hasRuntimeDefault: false;
|
|
44
|
+
enumValues: undefined;
|
|
45
|
+
baseColumn: never;
|
|
46
|
+
identity: undefined;
|
|
47
|
+
generated: undefined;
|
|
48
|
+
}, {}, {}>;
|
|
49
|
+
namespace: drizzle_orm_pg_core.PgColumn<{
|
|
50
|
+
name: "namespace";
|
|
51
|
+
tableName: "toolkit_settings";
|
|
52
|
+
dataType: "string";
|
|
53
|
+
columnType: "PgVarchar";
|
|
54
|
+
data: string;
|
|
55
|
+
driverParam: string;
|
|
56
|
+
notNull: true;
|
|
57
|
+
hasDefault: false;
|
|
58
|
+
isPrimaryKey: false;
|
|
59
|
+
isAutoincrement: false;
|
|
60
|
+
hasRuntimeDefault: false;
|
|
61
|
+
enumValues: [string, ...string[]];
|
|
62
|
+
baseColumn: never;
|
|
63
|
+
identity: undefined;
|
|
64
|
+
generated: undefined;
|
|
65
|
+
}, {}, {
|
|
66
|
+
length: 100;
|
|
67
|
+
}>;
|
|
68
|
+
scope: drizzle_orm_pg_core.PgColumn<{
|
|
69
|
+
name: "scope";
|
|
70
|
+
tableName: "toolkit_settings";
|
|
71
|
+
dataType: "string";
|
|
72
|
+
columnType: "PgVarchar";
|
|
73
|
+
data: string;
|
|
74
|
+
driverParam: string;
|
|
75
|
+
notNull: true;
|
|
76
|
+
hasDefault: true;
|
|
77
|
+
isPrimaryKey: false;
|
|
78
|
+
isAutoincrement: false;
|
|
79
|
+
hasRuntimeDefault: false;
|
|
80
|
+
enumValues: [string, ...string[]];
|
|
81
|
+
baseColumn: never;
|
|
82
|
+
identity: undefined;
|
|
83
|
+
generated: undefined;
|
|
84
|
+
}, {}, {
|
|
85
|
+
length: 20;
|
|
86
|
+
}>;
|
|
87
|
+
scopeId: drizzle_orm_pg_core.PgColumn<{
|
|
88
|
+
name: "scope_id";
|
|
89
|
+
tableName: "toolkit_settings";
|
|
90
|
+
dataType: "string";
|
|
91
|
+
columnType: "PgVarchar";
|
|
92
|
+
data: string;
|
|
93
|
+
driverParam: string;
|
|
94
|
+
notNull: true;
|
|
95
|
+
hasDefault: true;
|
|
96
|
+
isPrimaryKey: false;
|
|
97
|
+
isAutoincrement: false;
|
|
98
|
+
hasRuntimeDefault: false;
|
|
99
|
+
enumValues: [string, ...string[]];
|
|
100
|
+
baseColumn: never;
|
|
101
|
+
identity: undefined;
|
|
102
|
+
generated: undefined;
|
|
103
|
+
}, {}, {
|
|
104
|
+
length: 100;
|
|
105
|
+
}>;
|
|
106
|
+
key: drizzle_orm_pg_core.PgColumn<{
|
|
107
|
+
name: "key";
|
|
108
|
+
tableName: "toolkit_settings";
|
|
109
|
+
dataType: "string";
|
|
110
|
+
columnType: "PgVarchar";
|
|
111
|
+
data: string;
|
|
112
|
+
driverParam: string;
|
|
113
|
+
notNull: true;
|
|
114
|
+
hasDefault: false;
|
|
115
|
+
isPrimaryKey: false;
|
|
116
|
+
isAutoincrement: false;
|
|
117
|
+
hasRuntimeDefault: false;
|
|
118
|
+
enumValues: [string, ...string[]];
|
|
119
|
+
baseColumn: never;
|
|
120
|
+
identity: undefined;
|
|
121
|
+
generated: undefined;
|
|
122
|
+
}, {}, {
|
|
123
|
+
length: 255;
|
|
124
|
+
}>;
|
|
125
|
+
locale: drizzle_orm_pg_core.PgColumn<{
|
|
126
|
+
name: "locale";
|
|
127
|
+
tableName: "toolkit_settings";
|
|
128
|
+
dataType: "string";
|
|
129
|
+
columnType: "PgVarchar";
|
|
130
|
+
data: string;
|
|
131
|
+
driverParam: string;
|
|
132
|
+
notNull: true;
|
|
133
|
+
hasDefault: true;
|
|
134
|
+
isPrimaryKey: false;
|
|
135
|
+
isAutoincrement: false;
|
|
136
|
+
hasRuntimeDefault: false;
|
|
137
|
+
enumValues: [string, ...string[]];
|
|
138
|
+
baseColumn: never;
|
|
139
|
+
identity: undefined;
|
|
140
|
+
generated: undefined;
|
|
141
|
+
}, {}, {
|
|
142
|
+
length: 10;
|
|
143
|
+
}>;
|
|
144
|
+
value: drizzle_orm_pg_core.PgColumn<{
|
|
145
|
+
name: "value";
|
|
146
|
+
tableName: "toolkit_settings";
|
|
147
|
+
dataType: "json";
|
|
148
|
+
columnType: "PgJsonb";
|
|
149
|
+
data: unknown;
|
|
150
|
+
driverParam: unknown;
|
|
151
|
+
notNull: false;
|
|
152
|
+
hasDefault: false;
|
|
153
|
+
isPrimaryKey: false;
|
|
154
|
+
isAutoincrement: false;
|
|
155
|
+
hasRuntimeDefault: false;
|
|
156
|
+
enumValues: undefined;
|
|
157
|
+
baseColumn: never;
|
|
158
|
+
identity: undefined;
|
|
159
|
+
generated: undefined;
|
|
160
|
+
}, {}, {}>;
|
|
161
|
+
updatedAt: drizzle_orm_pg_core.PgColumn<{
|
|
162
|
+
name: "updated_at";
|
|
163
|
+
tableName: "toolkit_settings";
|
|
164
|
+
dataType: "date";
|
|
165
|
+
columnType: "PgTimestamp";
|
|
166
|
+
data: Date;
|
|
167
|
+
driverParam: string;
|
|
168
|
+
notNull: true;
|
|
169
|
+
hasDefault: true;
|
|
170
|
+
isPrimaryKey: false;
|
|
171
|
+
isAutoincrement: false;
|
|
172
|
+
hasRuntimeDefault: false;
|
|
173
|
+
enumValues: undefined;
|
|
174
|
+
baseColumn: never;
|
|
175
|
+
identity: undefined;
|
|
176
|
+
generated: undefined;
|
|
177
|
+
}, {}, {}>;
|
|
178
|
+
updatedBy: drizzle_orm_pg_core.PgColumn<{
|
|
179
|
+
name: "updated_by";
|
|
180
|
+
tableName: "toolkit_settings";
|
|
181
|
+
dataType: "string";
|
|
182
|
+
columnType: "PgUUID";
|
|
183
|
+
data: string;
|
|
184
|
+
driverParam: string;
|
|
185
|
+
notNull: false;
|
|
186
|
+
hasDefault: false;
|
|
187
|
+
isPrimaryKey: false;
|
|
188
|
+
isAutoincrement: false;
|
|
189
|
+
hasRuntimeDefault: false;
|
|
190
|
+
enumValues: undefined;
|
|
191
|
+
baseColumn: never;
|
|
192
|
+
identity: undefined;
|
|
193
|
+
generated: undefined;
|
|
194
|
+
}, {}, {}>;
|
|
195
|
+
};
|
|
196
|
+
dialect: "pg";
|
|
197
|
+
}>;
|
|
198
|
+
/**
|
|
199
|
+
* View state table.
|
|
200
|
+
*
|
|
201
|
+
* Stores schemaless user-scoped JSON blobs for persisting
|
|
202
|
+
* UI state (table filters, column order, etc.) with optional TTL.
|
|
203
|
+
*/
|
|
204
|
+
declare const toolkitViewState: drizzle_orm_pg_core.PgTableWithColumns<{
|
|
205
|
+
name: "toolkit_view_state";
|
|
206
|
+
schema: undefined;
|
|
207
|
+
columns: {
|
|
208
|
+
id: drizzle_orm_pg_core.PgColumn<{
|
|
209
|
+
name: "id";
|
|
210
|
+
tableName: "toolkit_view_state";
|
|
211
|
+
dataType: "string";
|
|
212
|
+
columnType: "PgUUID";
|
|
213
|
+
data: string;
|
|
214
|
+
driverParam: string;
|
|
215
|
+
notNull: true;
|
|
216
|
+
hasDefault: true;
|
|
217
|
+
isPrimaryKey: true;
|
|
218
|
+
isAutoincrement: false;
|
|
219
|
+
hasRuntimeDefault: false;
|
|
220
|
+
enumValues: undefined;
|
|
221
|
+
baseColumn: never;
|
|
222
|
+
identity: undefined;
|
|
223
|
+
generated: undefined;
|
|
224
|
+
}, {}, {}>;
|
|
225
|
+
userId: drizzle_orm_pg_core.PgColumn<{
|
|
226
|
+
name: "user_id";
|
|
227
|
+
tableName: "toolkit_view_state";
|
|
228
|
+
dataType: "string";
|
|
229
|
+
columnType: "PgUUID";
|
|
230
|
+
data: string;
|
|
231
|
+
driverParam: string;
|
|
232
|
+
notNull: true;
|
|
233
|
+
hasDefault: false;
|
|
234
|
+
isPrimaryKey: false;
|
|
235
|
+
isAutoincrement: false;
|
|
236
|
+
hasRuntimeDefault: false;
|
|
237
|
+
enumValues: undefined;
|
|
238
|
+
baseColumn: never;
|
|
239
|
+
identity: undefined;
|
|
240
|
+
generated: undefined;
|
|
241
|
+
}, {}, {}>;
|
|
242
|
+
viewKey: drizzle_orm_pg_core.PgColumn<{
|
|
243
|
+
name: "view_key";
|
|
244
|
+
tableName: "toolkit_view_state";
|
|
245
|
+
dataType: "string";
|
|
246
|
+
columnType: "PgVarchar";
|
|
247
|
+
data: string;
|
|
248
|
+
driverParam: string;
|
|
249
|
+
notNull: true;
|
|
250
|
+
hasDefault: false;
|
|
251
|
+
isPrimaryKey: false;
|
|
252
|
+
isAutoincrement: false;
|
|
253
|
+
hasRuntimeDefault: false;
|
|
254
|
+
enumValues: [string, ...string[]];
|
|
255
|
+
baseColumn: never;
|
|
256
|
+
identity: undefined;
|
|
257
|
+
generated: undefined;
|
|
258
|
+
}, {}, {
|
|
259
|
+
length: 255;
|
|
260
|
+
}>;
|
|
261
|
+
state: drizzle_orm_pg_core.PgColumn<{
|
|
262
|
+
name: "state";
|
|
263
|
+
tableName: "toolkit_view_state";
|
|
264
|
+
dataType: "json";
|
|
265
|
+
columnType: "PgJsonb";
|
|
266
|
+
data: unknown;
|
|
267
|
+
driverParam: unknown;
|
|
268
|
+
notNull: true;
|
|
269
|
+
hasDefault: false;
|
|
270
|
+
isPrimaryKey: false;
|
|
271
|
+
isAutoincrement: false;
|
|
272
|
+
hasRuntimeDefault: false;
|
|
273
|
+
enumValues: undefined;
|
|
274
|
+
baseColumn: never;
|
|
275
|
+
identity: undefined;
|
|
276
|
+
generated: undefined;
|
|
277
|
+
}, {}, {}>;
|
|
278
|
+
expiresAt: drizzle_orm_pg_core.PgColumn<{
|
|
279
|
+
name: "expires_at";
|
|
280
|
+
tableName: "toolkit_view_state";
|
|
281
|
+
dataType: "date";
|
|
282
|
+
columnType: "PgTimestamp";
|
|
283
|
+
data: Date;
|
|
284
|
+
driverParam: string;
|
|
285
|
+
notNull: false;
|
|
286
|
+
hasDefault: false;
|
|
287
|
+
isPrimaryKey: false;
|
|
288
|
+
isAutoincrement: false;
|
|
289
|
+
hasRuntimeDefault: false;
|
|
290
|
+
enumValues: undefined;
|
|
291
|
+
baseColumn: never;
|
|
292
|
+
identity: undefined;
|
|
293
|
+
generated: undefined;
|
|
294
|
+
}, {}, {}>;
|
|
295
|
+
updatedAt: drizzle_orm_pg_core.PgColumn<{
|
|
296
|
+
name: "updated_at";
|
|
297
|
+
tableName: "toolkit_view_state";
|
|
298
|
+
dataType: "date";
|
|
299
|
+
columnType: "PgTimestamp";
|
|
300
|
+
data: Date;
|
|
301
|
+
driverParam: string;
|
|
302
|
+
notNull: true;
|
|
303
|
+
hasDefault: true;
|
|
304
|
+
isPrimaryKey: false;
|
|
305
|
+
isAutoincrement: false;
|
|
306
|
+
hasRuntimeDefault: false;
|
|
307
|
+
enumValues: undefined;
|
|
308
|
+
baseColumn: never;
|
|
309
|
+
identity: undefined;
|
|
310
|
+
generated: undefined;
|
|
311
|
+
}, {}, {}>;
|
|
312
|
+
};
|
|
313
|
+
dialect: "pg";
|
|
314
|
+
}>;
|
|
315
|
+
|
|
316
|
+
export { toolkitSettings, toolkitViewState };
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"./chunk-E3K4GXDC.js";export{a as toolkitSettings,b as toolkitViewState};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { Logger } from '@murumets-ee/core';
|
|
2
|
+
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ViewStateClient — schemaless user-scoped state persistence.
|
|
6
|
+
*
|
|
7
|
+
* Used by admin UI for table filters, column order, panel state, etc.
|
|
8
|
+
* Optional TTL for auto-cleanup of stale state.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import { createViewStateClient } from '@murumets-ee/settings/view-state'
|
|
13
|
+
*
|
|
14
|
+
* const viewState = createViewStateClient({ db, userId: currentUser.id })
|
|
15
|
+
*
|
|
16
|
+
* await viewState.save('articles-table', {
|
|
17
|
+
* filters: { status: 'published' },
|
|
18
|
+
* columnOrder: ['title', 'status', 'date'],
|
|
19
|
+
* sortBy: 'date',
|
|
20
|
+
* })
|
|
21
|
+
*
|
|
22
|
+
* const state = await viewState.load('articles-table')
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
interface ViewStateClientConfig {
|
|
27
|
+
/** Database client (read-write) */
|
|
28
|
+
db: PostgresJsDatabase;
|
|
29
|
+
/** User ID for scoping */
|
|
30
|
+
userId: string;
|
|
31
|
+
/** Logger instance */
|
|
32
|
+
logger?: Logger;
|
|
33
|
+
/** Default TTL in seconds for view state entries. Defaults to 30 days. */
|
|
34
|
+
defaultTtl?: number;
|
|
35
|
+
}
|
|
36
|
+
declare class ViewStateClient {
|
|
37
|
+
private db;
|
|
38
|
+
private userId;
|
|
39
|
+
private logger?;
|
|
40
|
+
private defaultTtl;
|
|
41
|
+
constructor(config: ViewStateClientConfig);
|
|
42
|
+
/**
|
|
43
|
+
* Save view state (upsert).
|
|
44
|
+
*/
|
|
45
|
+
save<T extends Record<string, unknown>>(viewKey: string, state: T, options?: {
|
|
46
|
+
ttl?: number;
|
|
47
|
+
}): Promise<void>;
|
|
48
|
+
/**
|
|
49
|
+
* Load view state. Returns null if not found or expired.
|
|
50
|
+
*/
|
|
51
|
+
load<T extends Record<string, unknown> = Record<string, unknown>>(viewKey: string): Promise<T | null>;
|
|
52
|
+
/**
|
|
53
|
+
* Clear a specific view state entry.
|
|
54
|
+
*/
|
|
55
|
+
clear(viewKey: string): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Clear all expired view state entries (maintenance task).
|
|
58
|
+
* Call periodically (e.g., from a cron job or queue task).
|
|
59
|
+
* Returns the number of entries removed.
|
|
60
|
+
*/
|
|
61
|
+
clearExpired(): Promise<number>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Factory function following toolkit conventions.
|
|
65
|
+
*/
|
|
66
|
+
declare function createViewStateClient(config: ViewStateClientConfig): ViewStateClient;
|
|
67
|
+
|
|
68
|
+
export { ViewStateClient, type ViewStateClientConfig, createViewStateClient };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as t}from"./chunk-E3K4GXDC.js";import{and as d,eq as i,lt as u}from"drizzle-orm";var g=720*60*60,n=class{db;userId;logger;defaultTtl;constructor(e){if(typeof window<"u")throw new Error("ViewStateClient cannot be used in browser code.");this.db=e.db,this.userId=e.userId,this.logger=e.logger,this.defaultTtl=e.defaultTtl??g}async save(e,r,s){this.logger?.debug({userId:this.userId,viewKey:e},"Saving view state");let l=s?.ttl??this.defaultTtl,a=new Date(Date.now()+l*1e3);await this.db.insert(t).values({userId:this.userId,viewKey:e,state:r,expiresAt:a,updatedAt:new Date}).onConflictDoUpdate({target:[t.userId,t.viewKey],set:{state:r,expiresAt:a,updatedAt:new Date}})}async load(e){this.logger?.debug({userId:this.userId,viewKey:e},"Loading view state");let r=await this.db.select({state:t.state,expiresAt:t.expiresAt}).from(t).where(d(i(t.userId,this.userId),i(t.viewKey,e))).limit(1);if(r.length===0)return null;let s=r[0];return s.expiresAt&&s.expiresAt<new Date?(await this.clear(e),null):s.state}async clear(e){this.logger?.debug({userId:this.userId,viewKey:e},"Clearing view state"),await this.db.delete(t).where(d(i(t.userId,this.userId),i(t.viewKey,e)))}async clearExpired(){this.logger?.info("Clearing expired view state entries");let r=(await this.db.delete(t).where(u(t.expiresAt,new Date)).returning({id:t.id})).length;return this.logger?.info({count:r},"Expired view state entries cleared"),r}};function h(o){return new n(o)}export{n as ViewStateClient,h as createViewStateClient};
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@murumets-ee/settings",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "Elastic-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"import": "./dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./schema": {
|
|
12
|
+
"types": "./dist/schema.d.ts",
|
|
13
|
+
"import": "./dist/schema.js"
|
|
14
|
+
},
|
|
15
|
+
"./view-state": {
|
|
16
|
+
"types": "./dist/view-state.d.ts",
|
|
17
|
+
"import": "./dist/view-state.js"
|
|
18
|
+
},
|
|
19
|
+
"./plugin": {
|
|
20
|
+
"types": "./dist/plugin.d.ts",
|
|
21
|
+
"import": "./dist/plugin.js"
|
|
22
|
+
},
|
|
23
|
+
"./admin": {
|
|
24
|
+
"types": "./dist/admin.d.ts",
|
|
25
|
+
"import": "./dist/admin.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist"
|
|
30
|
+
],
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"drizzle-orm": "^0.45.1",
|
|
33
|
+
"zod": "^3.24.1",
|
|
34
|
+
"server-only": "^0.0.1",
|
|
35
|
+
"@murumets-ee/logging": "0.1.0",
|
|
36
|
+
"@murumets-ee/core": "0.1.0",
|
|
37
|
+
"@murumets-ee/db": "0.1.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/node": "^22.10.5",
|
|
41
|
+
"tsup": "^8.3.5",
|
|
42
|
+
"typescript": "^5.7.3",
|
|
43
|
+
"vitest": "^2.1.8"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "rm -rf dist && tsup",
|
|
47
|
+
"dev": "tsup --watch",
|
|
48
|
+
"test": "vitest",
|
|
49
|
+
"test:integration": "vitest run --config vitest.integration.config.ts"
|
|
50
|
+
}
|
|
51
|
+
}
|