insite-config 2.3.3 → 2.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 Eugene Nesvetaev
3
+ Copyright (c) 2026 Eugene Nesvetaev
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,13 +1,103 @@
1
- # inSite config
1
+ # insite-config
2
+
3
+ Runtime configuration storage backed by MongoDB. Define a schema with defaults, read and update values in memory, persist to a `config` collection. Changes sync automatically via MongoDB change streams.
4
+
5
+ Part of [inSite](../../README.md) — requires [insite-db](../db/README.md). MongoDB must support change streams (replica set or sharded cluster).
2
6
 
3
7
  ## Installation
4
8
 
5
9
  ```sh
6
- $ npm install insite-config
10
+ npm install insite-config
7
11
  ```
8
12
 
9
- Or
13
+ Or:
10
14
 
11
15
  ```sh
12
- $ bun add insite-config
16
+ bun add insite-config
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```ts
22
+ import { connect } from "insite-db";
23
+ import { init as initConfig } from "insite-config";
24
+
25
+ const schema = {
26
+ theme: { dark: false },
27
+ api: { rateLimit: 100 }
28
+ };
29
+
30
+ const { collections } = await connect({ url: "...", name: "myapp" });
31
+ const config = await initConfig(collections, schema);
32
+
33
+ console.log(config.theme.dark); // false
34
+ await config.update("theme", { dark: true });
13
35
  ```
36
+
37
+ ## API Reference
38
+
39
+ ### Exports
40
+
41
+ | Export | Type | Description |
42
+ |--------|------|-------------|
43
+ | `init` | function | Initializes config instance |
44
+ | `UnknownConfigItemError` | class | Thrown when config item ID not in schema |
45
+ | `Schema` | type | `Record<string, Record<string, boolean \| number \| string \| null>>` |
46
+ | `Config<S>` | type | Config object returned by `init()` |
47
+ | `Listener<CI>` | type | `(this: CI, updatedFields, prevFields) => void \| Promise<void>` |
48
+ | `ConfigItemID<S>` | type | String union of config item IDs |
49
+ | `Updates<CI>` | type | `Partial<Omit<CI, "_u">>` |
50
+ | `CollectionOptions` | type | Extends insite-db CollectionOptions; `fullDocument` and `watch` fixed |
51
+
52
+ ### init(collections, schema, collectionOptions?)
53
+
54
+ **Parameters:**
55
+
56
+ | Name | Type | Description |
57
+ |------|------|-------------|
58
+ | `collections` | `Collections` | From [insite-db](../db/README.md) `connect()` |
59
+ | `schema` | `Schema` | Object mapping config item IDs to default field values |
60
+ | `collectionOptions` | `CollectionOptions` | Optional. Passed to `collections.ensure()` for `config` |
61
+
62
+ **Returns:** `Promise<Config<S>>`. Singleton — subsequent calls return same instance.
63
+
64
+ ### UnknownConfigItemError
65
+
66
+ Extends `Error`. `name`: `"UnknownConfigItemError"`
67
+
68
+ ### Config&lt;S&gt;
69
+
70
+ **Indexed access:** `config[id]` — readonly config item (includes internal `_u` field)
71
+
72
+ **Methods:**
73
+
74
+ | Method | Signature | Description |
75
+ |--------|------------|-------------|
76
+ | `addListener` / `on` | `(id, listener, immediately?) => void` | Subscribe to updates. `immediately: true` calls listener once with current state |
77
+ | `removeListener` / `off` | `(id, listener) => void` | Unsubscribe |
78
+ | `update` | `(id, updates) => Promise<ConfigItem>` | Apply partial updates |
79
+
80
+ ## Usage Examples
81
+
82
+ ```ts
83
+ const theme = config.theme;
84
+ const isDark = theme.dark;
85
+
86
+ await config.update("api", { rateLimit: 200 });
87
+
88
+ config.addListener("theme", (updated, prev) => {
89
+ console.log("theme changed:", updated, prev);
90
+ }, true);
91
+ config.removeListener("theme", listener);
92
+ ```
93
+
94
+ **Notes:** Singleton; schema changes — removed items deleted from DB, new items created with defaults; conflict resolution via `updatedAt`.
95
+
96
+ ## Related
97
+
98
+ - [insite-db](../db/README.md) — provides Collections
99
+ - [insite-server](../server/README.md) — uses config
100
+
101
+ ## License
102
+
103
+ MIT
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- function y(){}var O=new WeakMap,b=class o extends Promise{constructor(n,t){let i,c;if(super((s,a)=>{i=s,c=a}),O.set(this,{resolve:i,reject:c}),t?.signal)if(t.signal.aborted)this.reject(new DOMException("Aborted","AbortError"));else{let s=()=>this.reject(new DOMException("Aborted","AbortError"));t.signal.addEventListener("abort",s),this.finally(()=>t.signal?.removeEventListener("abort",s))}if(typeof t?.timeout=="number"&&Number.isFinite(t.timeout)){let s=setTimeout(()=>this.reject(new DOMException("Timeout exceeded","TimeoutError")),t.timeout);this.finally(()=>clearTimeout(s))}n?.(this.resolve,this.reject)}isPending=!0;isFulfilled=!1;isRejected=!1;state="pending";result;resolve=n=>{if(this.isPending){this.isPending=!1,this.isFulfilled=!0,this.state="fulfilled",this.result=n;let t=O.get(this);t&&(t.resolve.call(this,n),O.delete(this))}};reject=n=>{if(this.isPending){this.isPending=!1,this.isRejected=!0,this.state="rejected",this.result=n;let t=O.get(this);t&&(t.reject.call(this,n),O.delete(this))}};static resolved(n){return new o(t=>t(n))}static rejected(n){return new o((t,i)=>i(n))}};function A(o,n=0,t={}){let{leading:i=!1,trailing:c=!0}=t,{maxWait:s=1/0}=t,a,d,j,e,l,f,r,u,p=async()=>{let h=Date.now();h>=j?(a=void 0,j=void 0,clearTimeout(d),d=void 0,typeof r=="function"&&await r(),m.resolve(u),f=i):(clearTimeout(a),a=setTimeout(p,j-h))},x=Number.isFinite(s)?()=>{r===w&&(r=!1),w(),d=setTimeout(x,s)}:null;async function w(){try{return u=await o.apply(e,l),u}catch(h){throw m.reject(h),h}}i&&typeof i=="boolean"&&(i=w),f=i,c&&typeof c=="boolean"&&(c=w),r=c;let m=Object.assign(function(...h){return l=h,e=this,j=Date.now()+n,r=c,m.promise.isPending||(m.promise=new b((T,D)=>{m.resolve=T,m.reject=D,typeof f=="function"&&(f(),f=!1,r===w&&(r=!1)),a||(a=setTimeout(p,n),x&&(d=setTimeout(x,s)))})),m.promise},{callback:o,promise:b.resolved(void 0),resolve:y,reject:y,run:w,clear:async h=>{clearTimeout(a),a=void 0,clearTimeout(d),d=void 0,m.resolve(h?await w():u)}});return m}A.noop=Object.assign(()=>{},{callback:y,promise:b.resolved(void 0),resolve:y,reject:y,run:y,clear:y});function E(o){for(let n in o)return!1;return!0}function k(o,n,t,i,c=!0){return Array.isArray(o)&&(o=o.length),typeof i!="string"&&(c=i??!0,i=t),(c?`${o}\xA0`:"")+k.raw(o,n,t,i)}k.raw=(o,n,t,i=t)=>{o=Math.abs(o);let c=o%10,s=o%100;return c===1&&s!==11?n:c>=2&&c<=4&&!(s>=12&&s<=15)?t:i};function v(o,n){let t={};for(let i of n)i in o&&(t[i]=o[i]);return t}function C(o){return Object.entries(o)}function M(o){return Object.fromEntries(o)}var g="_u",I=Symbol("updatedAt");var S=class extends Error{constructor(n){super(`Unknown Config item "${n}"`)}name="UnknownConfigItemError"},$;async function vr(o,n,t){if(!$){let i=new Map,c=await o.ensure("config",t),s={addListener(e,l,f){let r=this[e];if(r)f&&l.call(r,r,{...r}),i.get(r)?.add(l)??i.set(r,new Set([l]));else throw new S(e)},removeListener(e,l){let f=this[e];if(f)i.get(f)?.delete(l);else throw new S(e)},async update(e,{[I]:l,...f}){let r=this[e];if(g in f&&delete f[g],r){if(!E(f)&&(!l||r[g]<l)){let u={};for(let[p,x]of Object.entries(f))p in r&&r[p]!==x&&(u[p]=x);if(!E(u)){l||(Object.assign(u,{[g]:Date.now()}),c.updateOne({_id:e},{$set:u}));let p=v(r,Object.keys(u));Object.assign(r,u);for(let x of i.get(r)??[])await x.call(r,u,p)}}return r}throw new S(e)}};s.on=s.addListener,s.off=s.removeListener,$=s;let a=new Map((await c.find().toArray()).map(({_id:e,...l})=>[e,l])),d=new Map,j=Date.now();for(let[e,l]of Object.entries(n)){let f=a.get(e),r={...M(C(l).map(([u,p])=>[u,f?.[u]??p])),[g]:f?.[g]??j};s[e]=r,d.set(e,r)}await c.bulkWrite([...[...d].map(([e,l])=>({replaceOne:{filter:{_id:e},replacement:{_id:e,...l},upsert:!0}})),...[...a.keys()].filter(e=>!n[e]).map(e=>({deleteOne:{filter:{_id:e}}}))]),c.onChange(e=>{switch(e.operationType){case"update":case"replace":{let{_id:l,[g]:f=Date.now(),...r}=e.operationType==="replace"?e.fullDocument:e.updateDescription.updatedFields;s.update(e.documentKey._id,{...r,[I]:f})}}})}return $}export{S as UnknownConfigItemError,vr as init};
1
+ import{isEmpty as g,pick as D,typeSafeObjectEntries as b,typeSafeObjectFromEntries as O}from"@nesvet/n";var m=Symbol("updatedAt");var c=class extends Error{constructor(p){super(`Unknown Config item "${p}"`)}name="UnknownConfigItemError"},C;async function j(I,p,w){if(!C){let f=new Map,l=await I.ensure("config",w),s={addListener(e,o,n){let t=this[e];if(t)n&&o.call(t,t,{...t}),f.get(t)?.add(o)??f.set(t,new Set([o]));else throw new c(e)},removeListener(e,o){let n=this[e];if(n)f.get(n)?.delete(o);else throw new c(e)},async update(e,{[m]:o,...n}){let t=this[e];if("_u"in n&&delete n["_u"],t){if(!g(n)&&(!o||t["_u"]<o)){let i={};for(let[a,d]of Object.entries(n))a in t&&t[a]!==d&&(i[a]=d);if(!g(i)){o||(Object.assign(i,{_u:Date.now()}),l.updateOne({_id:e},{$set:i}));let a=D(t,Object.keys(i));Object.assign(t,i);for(let d of f.get(t)??[])await d.call(t,i,a)}}return t}throw new c(e)}};s.on=s.addListener,s.off=s.removeListener,C=s;let y=new Map((await l.find().toArray()).map(({_id:e,...o})=>[e,o])),u=new Map,S=Date.now();for(let[e,o]of Object.entries(p)){let n=y.get(e),t={...O(b(o).map(([i,a])=>[i,n?.[i]??a])),_u:n?.["_u"]??S};s[e]=t,u.set(e,t)}await l.bulkWrite([...[...u].map(([e,o])=>({replaceOne:{filter:{_id:e},replacement:{_id:e,...o},upsert:!0}})),...[...y.keys()].filter(e=>!p[e]).map(e=>({deleteOne:{filter:{_id:e}}}))]),l.onChange(e=>{switch(e.operationType){case"update":case"replace":{let{_id:o,["_u"]:n=Date.now(),...t}=e.operationType==="replace"?e.fullDocument:e.updateDescription.updatedFields;s.update(e.documentKey._id,{...t,[m]:n})}}})}return C}export{c as UnknownConfigItemError,j as init};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../@nesvet/npm/n/src/noop.ts", "../../../../@nesvet/npm/n/src/StatefulPromise.ts", "../../../../@nesvet/npm/n/src/debounce.ts", "../../../../@nesvet/npm/n/src/isEmpty.ts", "../../../../@nesvet/npm/n/src/howmuch.ts", "../../../../@nesvet/npm/n/src/pick.ts", "../../../../@nesvet/npm/n/src/typeSafeObjectEntries.ts", "../../../../@nesvet/npm/n/src/typeSafeObjectFromEntries.ts", "../src/symbols.ts", "../src/init.ts"],
4
- "sourcesContent": ["export function noop() { /**/ }\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype Value<T> = PromiseLike<T> | T;\ntype Resolve<T> = (value: Value<T>) => void;\ntype Reject = (reason?: any) => void;\n\ntype Options = {\n\tsignal?: AbortSignal;\n\ttimeout?: number;\n};\n\nconst nativesMap = new WeakMap<StatefulPromise<any>, { resolve: Resolve<any>; reject: Reject }>();\n\n\nexport class StatefulPromise<T> extends Promise<T> {\n\tconstructor(\n\t\texecutor?: (resolve: Resolve<T>, reject: Reject) => void,\n\t\toptions?: Options\n\t) {\n\t\tlet nativeResolve: Resolve<T>;\n\t\tlet nativeReject: Reject;\n\t\t\n\t\tsuper((resolve, reject) => {\n\t\t\tnativeResolve = resolve;\n\t\t\tnativeReject = reject;\n\t\t\t\n\t\t});\n\t\t\n\t\tnativesMap.set(this, { resolve: nativeResolve!, reject: nativeReject! });\n\t\t\n\t\tif (options?.signal)\n\t\t\tif (options.signal.aborted)\n\t\t\t\tthis.reject(new DOMException(\"Aborted\", \"AbortError\"));\n\t\t\telse {\n\t\t\t\tconst abortListener = () => this.reject(new DOMException(\"Aborted\", \"AbortError\"));\n\t\t\t\t\n\t\t\t\toptions.signal.addEventListener(\"abort\", abortListener);\n\t\t\t\t\n\t\t\t\tthis.finally(() => options.signal?.removeEventListener(\"abort\", abortListener));\n\t\t\t}\n\t\t\n\t\tif (typeof options?.timeout === \"number\" && Number.isFinite(options.timeout)) {\n\t\t\tconst timeout = setTimeout(() => this.reject(new DOMException(\"Timeout exceeded\", \"TimeoutError\")), options.timeout);\n\t\t\t\n\t\t\tthis.finally(() => clearTimeout(timeout));\n\t\t}\n\t\t\n\t\texecutor?.(this.resolve, this.reject);\n\t\t\n\t}\n\t\n\tisPending = true;\n\tisFulfilled = false;\n\tisRejected = false;\n\t\n\tstate: \"fulfilled\" | \"pending\" | \"rejected\" = \"pending\";\n\t\n\tresult?: T | unknown;\n\t\n\treadonly resolve = (value: Value<T>) => {\n\t\t\n\t\tif (this.isPending) {\n\t\t\tthis.isPending = false;\n\t\t\tthis.isFulfilled = true;\n\t\t\tthis.state = \"fulfilled\";\n\t\t\tthis.result = value;\n\t\t\t\n\t\t\tconst native = nativesMap.get(this);\n\t\t\t\n\t\t\tif (native) {\n\t\t\t\tnative.resolve.call(this, value);\n\t\t\t\tnativesMap.delete(this);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\treadonly reject = (reason?: any) => {\n\t\t\n\t\tif (this.isPending) {\n\t\t\tthis.isPending = false;\n\t\t\tthis.isRejected = true;\n\t\t\tthis.state = \"rejected\";\n\t\t\tthis.result = reason;\n\t\t\t\n\t\t\tconst native = nativesMap.get(this);\n\t\t\t\n\t\t\tif (native) {\n\t\t\t\tnative.reject.call(this, reason);\n\t\t\t\tnativesMap.delete(this);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\t\n\tstatic resolved<U>(value: U): StatefulPromise<U> {\n\t\treturn new StatefulPromise<U>(resolve => resolve(value));\n\t}\n\t\n\tstatic rejected(reason: unknown): StatefulPromise<never> {\n\t\treturn new StatefulPromise((_, reject) => reject(reason));\n\t}\n\t\n}\n", "import { noop } from \"./noop.js\";\nimport { StatefulPromise } from \"./StatefulPromise.js\";\n\n\ntype Callback = (...args: any[]) => unknown;// eslint-disable-line @typescript-eslint/no-explicit-any\ntype FunctionOrBoolean = (() => unknown) | boolean;\ntype Options = { leading?: FunctionOrBoolean; maxWait?: number; trailing?: FunctionOrBoolean };\n\ntype DebouncedFunction<C extends Callback> = {\n\t(this: ThisParameterType<C>, ...args: Parameters<C>): Promise<Awaited<ReturnType<C>>>;\n};\n\nexport type Debounced<C extends Callback, R extends ReturnType<C>> = DebouncedFunction<C> & {\n\tcallback: C;\n\tpromise: StatefulPromise<R>;\n\tresolve: (value: R) => void;\n\treject: (reason?: unknown) => void;\n\trun(): Promise<R>;\n\tclear(shouldRun?: boolean): Promise<void>;\n};\n\n\nexport function debounce<C extends Callback, R extends ReturnType<C>>(callback: C, limit = 0, options: Options = {}) {\n\tlet { leading = false, trailing = true } = options;\n\tconst { maxWait = Infinity } = options;\n\t\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\tlet maxWaitTimeout: ReturnType<typeof setTimeout> | undefined;\n\tlet end: number | undefined;\n\tlet context: ThisParameterType<C>;\n\tlet args: unknown[];\n\tlet initial: FunctionOrBoolean;\n\tlet final: FunctionOrBoolean;\n\tlet result: R;\n\t\n\tconst expired = async () => {\n\t\t\n\t\tconst n = Date.now();\n\t\t\n\t\tif (n >= end!) {\n\t\t\ttimeout = undefined;\n\t\t\tend = undefined;\n\t\t\t\n\t\t\tclearTimeout(maxWaitTimeout);\n\t\t\tmaxWaitTimeout = undefined;\n\t\t\t\n\t\t\tif (typeof final == \"function\")\n\t\t\t\tawait final();\n\t\t\t\n\t\t\tdebounced.resolve(result);\n\t\t\t\n\t\t\tinitial = leading;\n\t\t} else {\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = setTimeout(expired, end! - n);\n\t\t}\n\t\t\n\t};\n\t\n\tconst maxWaitExpired = Number.isFinite(maxWait) ? () => {\n\t\t\n\t\tif (final === run)\n\t\t\tfinal = false;\n\t\t\n\t\trun();\n\t\t\n\t\tmaxWaitTimeout = setTimeout(maxWaitExpired as TimerHandler, maxWait);\n\t\t\n\t} : null;\n\t\n\tasync function run() {\n\t\ttry {\n\t\t\tresult = await callback.apply(context, args) as R;\n\t\t\t\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tdebounced.reject(error);\n\t\t\t\n\t\t\tthrow error;\n\t\t}\n\t}\n\t\n\tif (leading && typeof leading == \"boolean\")\n\t\tleading = run;\n\tinitial = leading;\n\t\n\tif (trailing && typeof trailing == \"boolean\")\n\t\ttrailing = run;\n\tfinal = trailing;\n\t\n\tconst debounced: Debounced<C, R> = Object.assign(function (..._args) {\n\t\targs = _args;\n\t\tcontext = this;// eslint-disable-line no-invalid-this\n\t\t\n\t\tend = Date.now() + limit;\n\t\tfinal = trailing;\n\t\t\n\t\tif (!debounced.promise.isPending)\n\t\t\tdebounced.promise = new StatefulPromise<R>((resolve, reject) => {\n\t\t\t\tdebounced.resolve = resolve;\n\t\t\t\tdebounced.reject = reject;\n\t\t\t\t\n\t\t\t\tif (typeof initial == \"function\") {\n\t\t\t\t\tinitial();\n\t\t\t\t\t\n\t\t\t\t\tinitial = false;\n\t\t\t\t\t\n\t\t\t\t\tif (final === run)\n\t\t\t\t\t\tfinal = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!timeout) {\n\t\t\t\t\ttimeout = setTimeout(expired, limit);\n\t\t\t\t\t\n\t\t\t\t\tif (maxWaitExpired)\n\t\t\t\t\t\tmaxWaitTimeout = setTimeout(maxWaitExpired, maxWait);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t\n\t\treturn debounced.promise;\n\t} as DebouncedFunction<C>, {\n\t\tcallback,\n\t\tpromise: StatefulPromise.resolved(undefined as unknown as R),\n\t\tresolve: noop,\n\t\treject: noop,\n\t\trun,\n\t\tclear: async (shouldRun?: boolean) => {\n\t\t\t\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = undefined;\n\t\t\t\n\t\t\tclearTimeout(maxWaitTimeout);\n\t\t\tmaxWaitTimeout = undefined;\n\t\t\t\n\t\t\tdebounced.resolve(shouldRun ? await run() : result);\n\t\t\t\n\t\t}\n\t});\n\t\n\treturn debounced;\n}\n\n\ndebounce.noop = Object.assign(() => { /**/ }, {\n\tcallback: noop,\n\tpromise: StatefulPromise.resolved(undefined), // eslint-disable-line unicorn/no-useless-undefined\n\tresolve: noop,\n\treject: noop,\n\trun: noop,\n\tclear: noop\n}) as Debounced<() => void, void>;\n\n\nexport function throttle(callback: Callback, limit?: number, options?: Options) {\n\treturn debounce(callback, limit, {\n\t\tmaxWait: limit,\n\t\tleading: true,\n\t\ttrailing: true,\n\t\t...options\n\t});\n}\n", "export function isEmpty(object: object) {\n\tfor (const _ in object)// eslint-disable-line guard-for-in, no-unreachable-loop\n\t\treturn false;\n\t\n\treturn true;\n}\n", "export function howmuch(number: [] | number, one: string, two: string, five: boolean | string, shouldPrintNumber = true) {\n\tif (Array.isArray(number))\n\t\tnumber = number.length;\n\t\n\tif (typeof five != \"string\") {\n\t\tshouldPrintNumber = five ?? true;\n\t\tfive = two;\n\t}\n\t\n\t\n\treturn (shouldPrintNumber ? `${number}\u00A0` : \"\") + howmuch.raw(number, one, two, five);\n}\n\nhowmuch.raw = (number: number, one: string, two: string, five = two) => {\n\tnumber = Math.abs(number);\n\tconst u = number % 10;\n\tconst d = number % 100;\n\t\n\treturn (\n\t\t(u === 1 && d !== 11) ?\n\t\t\tone :\n\t\t\t((u >= 2 && u <= 4) && !(d >= 12 && d <= 15)) ?\n\t\t\t\ttwo :\n\t\t\t\tfive\n\t);\n};\n", "export function pick<O extends object, K extends keyof O>(object: O, keys: K[]) {\n\t\n\tconst picked: Partial<Pick<O, K>> = {};\n\t\n\tfor (const key of keys)\n\t\tif (key in object)\n\t\t\tpicked[key] = object[key];\n\t\n\treturn picked as Pick<O, K>;\n}\n", "export function typeSafeObjectEntries<T extends Record<PropertyKey, unknown>>(obj: T) {\n\treturn Object.entries(obj) as { [K in keyof T]: [K, T[K]] }[keyof T][];\n}\n", "export function typeSafeObjectFromEntries<const T extends ReadonlyArray<readonly [PropertyKey, unknown]>>(entries: T) {\n\treturn Object.fromEntries(entries) as { [K in T[number] as K[0]]: K[1] };\n}\n", "export const updatedAtKey = \"_u\";\nexport const updatedAtSymbol = Symbol(\"updatedAt\");\n", "import {\n\tisEmpty,\n\tpick,\n\ttypeSafeObjectEntries,\n\ttypeSafeObjectFromEntries\n} from \"@nesvet/n\";\nimport type { Collections } from \"insite-db\";\nimport { updatedAtKey, updatedAtSymbol } from \"./symbols\";\nimport type {\n\tCollectionOptions,\n\tConfig,\n\tConfigItemID,\n\tListener,\n\tSchema,\n\tUpdates\n} from \"./types\";\n\n\nexport class UnknownConfigItemError extends Error {\n\tconstructor(_id: string) {\n\t\tsuper(`Unknown Config item \"${_id}\"`);\n\t\t\n\t}\n\t\n\tname = \"UnknownConfigItemError\";\n\t\n}\n\n\nlet initedConfig: Config<Schema>;\n\nexport async function init<S extends Schema>(collections: Collections, schema: S, collectionOptions?: CollectionOptions) {\n\t\n\tif (!initedConfig) {\n\t\ttype ID = ConfigItemID<S>;\n\t\ttype CI = Config<S>[ID];\n\t\t\n\t\tconst updateListeners = new Map<CI, Set<Listener<CI>>>();\n\t\t\n\t\ttype CIDoc = CI & { _id: ID };\n\t\tconst collection = await collections.ensure<CIDoc>(\"config\", collectionOptions);\n\t\t\n\t\tconst config: Config<S> = {\n\t\t\t\n\t\t\taddListener(_id, listener: Listener<CI>, immediately) {\n\t\t\t\tconst item = this[_id];\n\t\t\t\t\n\t\t\t\tif (item) {\n\t\t\t\t\tif (immediately)\n\t\t\t\t\t\tvoid listener.call(item, item, { ...item });\n\t\t\t\t\t\n\t\t\t\t\tupdateListeners.get(item)?.add(listener) ??\n\t\t\t\t\tupdateListeners.set(item, new Set([ listener ]));\n\t\t\t\t} else\n\t\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t},\n\t\t\t\n\t\t\tremoveListener(_id, listener: Listener<CI>) {\n\t\t\t\tconst item = this[_id];\n\t\t\t\t\n\t\t\t\tif (item)\n\t\t\t\t\tupdateListeners.get(item)?.delete(listener);\n\t\t\t\telse\n\t\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t},\n\t\t\t\n\t\t\tasync update(_id, { [updatedAtSymbol]: updatedAt, ...updates }) {\n\t\t\t\tconst item = this[_id] as CI;\n\t\t\t\t\n\t\t\t\tif (updatedAtKey in updates)\n\t\t\t\t\tdelete updates[updatedAtKey];\n\t\t\t\t\n\t\t\t\tif (item) {\n\t\t\t\t\tif (!isEmpty(updates) && (!updatedAt || item[updatedAtKey] < updatedAt)) {\n\t\t\t\t\t\tconst updatedFields: Partial<CI> = {};\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (const [ key, value ] of Object.entries(updates) as [ keyof CI, CI[keyof CI] ][])\n\t\t\t\t\t\t\tif (key in item && item[key] !== value)\n\t\t\t\t\t\t\t\tupdatedFields[key] = value;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!isEmpty(updatedFields)) {\n\t\t\t\t\t\t\tif (!updatedAt) {\n\t\t\t\t\t\t\t\tObject.assign(updatedFields, { [updatedAtKey]: Date.now() });\n\t\t\t\t\t\t\t\tvoid collection.updateOne({ _id }, { $set: updatedFields as Partial<CIDoc> });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tconst prevFields = pick(item, Object.keys(updatedFields)) as Partial<CI>;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tObject.assign(item, updatedFields);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (const listener of updateListeners.get(item) ?? [])\n\t\t\t\t\t\t\t\tawait listener.call(item, updatedFields, prevFields);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\treturn item;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t}\n\t\t\t\n\t\t} as Config<S>;\n\t\t\n\t\tconfig.on = config.addListener;\n\t\tconfig.off = config.removeListener;\n\t\t\n\t\tinitedConfig = config;// eslint-disable-line require-atomic-updates\n\t\t\n\t\t\n\t\tconst collectionMap = new Map((await collection.find().toArray()).map(({ _id, ...props }) => [ _id as ID, props as CI ]));\n\t\t\n\t\tconst itemsMap = new Map<ID, CI>();\n\t\t\n\t\tconst initialUpdatedAt = Date.now();\n\t\t\n\t\tfor (const [ _id, props ] of Object.entries(schema) as [ID, S[keyof S]][]) {\n\t\t\tconst collectionItem = collectionMap.get(_id);\n\t\t\t\n\t\t\tconst item = {\n\t\t\t\t...typeSafeObjectFromEntries(\n\t\t\t\t\ttypeSafeObjectEntries(props).map(([ key, value ]) =>\n\t\t\t\t\t\t[ key, collectionItem?.[key] ?? value ]\n\t\t\t\t\t)\n\t\t\t\t),\n\t\t\t\t[updatedAtKey]: collectionItem?.[updatedAtKey] ?? initialUpdatedAt\n\t\t\t} as CI;\n\t\t\t\n\t\t\tconfig[_id] = item;\n\t\t\t\n\t\t\titemsMap.set(_id, item);\n\t\t}\n\t\t\n\t\t\n\t\tawait collection.bulkWrite([\n\t\t\t...[ ...itemsMap ].map(([ _id, item ]) => ({ replaceOne: { filter: { _id }, replacement: { _id, ...item }, upsert: true } })),\n\t\t\t...[ ...collectionMap.keys() ].filter(_id => !schema[_id]).map(_id => ({ deleteOne: { filter: { _id } } }))\n\t\t]);\n\t\t\n\t\tcollection.onChange(next => {\n\t\t\tswitch (next.operationType) {\n\t\t\t\tcase \"update\":\n\t\t\t\tcase \"replace\": {\n\t\t\t\t\tconst {\n\t\t\t\t\t\t_id: _,\n\t\t\t\t\t\t[updatedAtKey]: updatedAt = Date.now(),\n\t\t\t\t\t\t...restProps\n\t\t\t\t\t} = next.operationType === \"replace\" ? next.fullDocument : next.updateDescription.updatedFields!;\n\t\t\t\t\t\n\t\t\t\t\tvoid config.update(next.documentKey._id as unknown as ID, {\n\t\t\t\t\t\t...restProps,\n\t\t\t\t\t\t[updatedAtSymbol]: updatedAt\n\t\t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esMap", "StatefulPromise", "_StatefulPromise", "executor", "options", "nativeResolve", "nativeReject", "resolve", "reject", "abortListener", "timeout", "value", "native", "reason", "_", "debounce", "callback", "limit", "options", "leading", "trailing", "maxWait", "timeout", "maxWaitTimeout", "end", "context", "args", "initial", "final", "result", "expired", "n", "debounced", "maxWaitExpired", "run", "error", "_args", "StatefulPromise", "resolve", "reject", "noop", "shouldRun", "isEmpty", "object", "_", "howmuch", "number", "one", "two", "five", "shouldPrintNumber", "u", "d", "pick", "object", "keys", "picked", "key", "typeSafeObjectEntries", "obj", "typeSafeObjectFromEntries", "entries", "updatedAtKey", "updatedAtSymbol", "UnknownConfigItemError", "_id", "initedConfig", "init", "collections", "schema", "collectionOptions", "updateListeners", "collection", "config", "listener", "immediately", "item", "updatedAtSymbol", "updatedAt", "updates", "updatedAtKey", "isEmpty", "updatedFields", "key", "value", "prevFields", "pick", "collectionMap", "props", "itemsMap", "initialUpdatedAt", "collectionItem", "typeSafeObjectFromEntries", "typeSafeObjectEntries", "next", "_", "restProps"]
3
+ "sources": ["../src/init.ts", "../src/symbols.ts"],
4
+ "sourcesContent": ["import {\n\tisEmpty,\n\tpick,\n\ttypeSafeObjectEntries,\n\ttypeSafeObjectFromEntries\n} from \"@nesvet/n\";\nimport type { Collections } from \"insite-db\";\nimport { updatedAtKey, updatedAtSymbol } from \"./symbols\";\nimport type {\n\tCollectionOptions,\n\tConfig,\n\tConfigItemID,\n\tListener,\n\tSchema,\n\tUpdates\n} from \"./types\";\n\n\nexport class UnknownConfigItemError extends Error {\n\tconstructor(_id: string) {\n\t\tsuper(`Unknown Config item \"${_id}\"`);\n\t\t\n\t}\n\t\n\tname = \"UnknownConfigItemError\";\n\t\n}\n\n\nlet initedConfig: Config<Schema>;\n\nexport async function init<S extends Schema>(collections: Collections, schema: S, collectionOptions?: CollectionOptions) {\n\t\n\tif (!initedConfig) {\n\t\ttype ID = ConfigItemID<S>;\n\t\ttype CI = Config<S>[ID];\n\t\t\n\t\tconst updateListeners = new Map<CI, Set<Listener<CI>>>();\n\t\t\n\t\ttype CIDoc = CI & { _id: ID };\n\t\tconst collection = await collections.ensure<CIDoc>(\"config\", collectionOptions);\n\t\t\n\t\tconst config: Config<S> = {\n\t\t\t\n\t\t\taddListener(_id, listener: Listener<CI>, immediately) {\n\t\t\t\tconst item = this[_id];\n\t\t\t\t\n\t\t\t\tif (item) {\n\t\t\t\t\tif (immediately)\n\t\t\t\t\t\tvoid listener.call(item, item, { ...item });\n\t\t\t\t\t\n\t\t\t\t\tupdateListeners.get(item)?.add(listener) ??\n\t\t\t\t\tupdateListeners.set(item, new Set([ listener ]));\n\t\t\t\t} else\n\t\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t},\n\t\t\t\n\t\t\tremoveListener(_id, listener: Listener<CI>) {\n\t\t\t\tconst item = this[_id];\n\t\t\t\t\n\t\t\t\tif (item)\n\t\t\t\t\tupdateListeners.get(item)?.delete(listener);\n\t\t\t\telse\n\t\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t},\n\t\t\t\n\t\t\tasync update(_id, { [updatedAtSymbol]: updatedAt, ...updates }) {\n\t\t\t\tconst item = this[_id] as CI;\n\t\t\t\t\n\t\t\t\tif (updatedAtKey in updates)\n\t\t\t\t\tdelete updates[updatedAtKey];\n\t\t\t\t\n\t\t\t\tif (item) {\n\t\t\t\t\tif (!isEmpty(updates) && (!updatedAt || item[updatedAtKey] < updatedAt)) {\n\t\t\t\t\t\tconst updatedFields: Partial<CI> = {};\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (const [ key, value ] of Object.entries(updates) as [ keyof CI, CI[keyof CI] ][])\n\t\t\t\t\t\t\tif (key in item && item[key] !== value)\n\t\t\t\t\t\t\t\tupdatedFields[key] = value;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!isEmpty(updatedFields)) {\n\t\t\t\t\t\t\tif (!updatedAt) {\n\t\t\t\t\t\t\t\tObject.assign(updatedFields, { [updatedAtKey]: Date.now() });\n\t\t\t\t\t\t\t\tvoid collection.updateOne({ _id }, { $set: updatedFields as Partial<CIDoc> });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tconst prevFields = pick(item, Object.keys(updatedFields)) as Partial<CI>;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tObject.assign(item, updatedFields);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (const listener of updateListeners.get(item) ?? [])\n\t\t\t\t\t\t\t\tawait listener.call(item, updatedFields, prevFields);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\treturn item;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t}\n\t\t\t\n\t\t} as Config<S>;\n\t\t\n\t\tconfig.on = config.addListener;\n\t\tconfig.off = config.removeListener;\n\t\t\n\t\tinitedConfig = config;// eslint-disable-line require-atomic-updates\n\t\t\n\t\t\n\t\tconst collectionMap = new Map((await collection.find().toArray()).map(({ _id, ...props }) => [ _id as ID, props as CI ]));\n\t\t\n\t\tconst itemsMap = new Map<ID, CI>();\n\t\t\n\t\tconst initialUpdatedAt = Date.now();\n\t\t\n\t\tfor (const [ _id, props ] of Object.entries(schema) as [ID, S[keyof S]][]) {\n\t\t\tconst collectionItem = collectionMap.get(_id);\n\t\t\t\n\t\t\tconst item = {\n\t\t\t\t...typeSafeObjectFromEntries(\n\t\t\t\t\ttypeSafeObjectEntries(props).map(([ key, value ]) =>\n\t\t\t\t\t\t[ key, collectionItem?.[key] ?? value ]\n\t\t\t\t\t)\n\t\t\t\t),\n\t\t\t\t[updatedAtKey]: collectionItem?.[updatedAtKey] ?? initialUpdatedAt\n\t\t\t} as CI;\n\t\t\t\n\t\t\tconfig[_id] = item;\n\t\t\t\n\t\t\titemsMap.set(_id, item);\n\t\t}\n\t\t\n\t\t\n\t\tawait collection.bulkWrite([\n\t\t\t...[ ...itemsMap ].map(([ _id, item ]) => ({ replaceOne: { filter: { _id }, replacement: { _id, ...item }, upsert: true } })),\n\t\t\t...[ ...collectionMap.keys() ].filter(_id => !schema[_id]).map(_id => ({ deleteOne: { filter: { _id } } }))\n\t\t]);\n\t\t\n\t\tcollection.onChange(next => {\n\t\t\tswitch (next.operationType) {\n\t\t\t\tcase \"update\":\n\t\t\t\tcase \"replace\": {\n\t\t\t\t\tconst {\n\t\t\t\t\t\t_id: _,\n\t\t\t\t\t\t[updatedAtKey]: updatedAt = Date.now(),\n\t\t\t\t\t\t...restProps\n\t\t\t\t\t} = next.operationType === \"replace\" ? next.fullDocument : next.updateDescription.updatedFields!;\n\t\t\t\t\t\n\t\t\t\t\tvoid config.update(next.documentKey._id as unknown as ID, {\n\t\t\t\t\t\t...restProps,\n\t\t\t\t\t\t[updatedAtSymbol]: updatedAt\n\t\t\t\t\t} as Updates<CI>);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t});\n\t\t\n\t}\n\t\n\treturn initedConfig as Config<S>;\n}\n", "export const updatedAtKey = \"_u\";\nexport const updatedAtSymbol = Symbol(\"updatedAt\");\n"],
5
+ "mappings": "AAAA,OACC,WAAAA,EACA,QAAAC,EACA,yBAAAC,EACA,6BAAAC,MACM,YCJA,IAAMC,EAAkB,OAAO,WAAW,EDiB1C,IAAMC,EAAN,cAAqC,KAAM,CACjD,YAAYC,EAAa,CACxB,MAAM,wBAAwBA,CAAG,GAAG,CAErC,CAEA,KAAO,wBAER,EAGIC,EAEJ,eAAsBC,EAAuBC,EAA0BC,EAAWC,EAAuC,CAExH,GAAI,CAACJ,EAAc,CAIlB,IAAMK,EAAkB,IAAI,IAGtBC,EAAa,MAAMJ,EAAY,OAAc,SAAUE,CAAiB,EAExEG,EAAoB,CAEzB,YAAYR,EAAKS,EAAwBC,EAAa,CACrD,IAAMC,EAAO,KAAKX,CAAG,EAErB,GAAIW,EACCD,GACED,EAAS,KAAKE,EAAMA,EAAM,CAAE,GAAGA,CAAK,CAAC,EAE3CL,EAA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AK,YAAY,IAAsB,CACzD,GAAGE,EACH,CAAClB,CAAe,EAAGC,CACpB,CAAgB,CACjB,CACD,CAED,CAAC,CAEF,CAEA,OAAOZ,CACR",
6
+ "names": ["isEmpty", "pick", "typeSafeObjectEntries", "typeSafeObjectFromEntries", "updatedAtSymbol", "UnknownConfigItemError", "_id", "initedConfig", "init", "collections", "schema", "collectionOptions", "updateListeners", "collection", "config", "listener", "immediately", "item", "updatedAtSymbol", "updatedAt", "updates", "isEmpty", "updatedFields", "key", "value", "prevFields", "pick", "collectionMap", "props", "itemsMap", "initialUpdatedAt", "collectionItem", "typeSafeObjectFromEntries", "typeSafeObjectEntries", "next", "_", "restProps"]
7
7
  }
package/package.json CHANGED
@@ -1,34 +1,48 @@
1
1
  {
2
- "name": "insite-config",
3
- "version": "2.3.3",
4
- "description": "inSite config",
5
- "type": "module",
6
- "main": "./dist/index.js",
7
- "module": "./dist/index.js",
8
- "packageManager": "bun@1.2.18",
9
- "scripts": {
10
- "test": "echo \"Error: no test specified\" && exit 1",
11
- "build": "bun .conveyer.js",
12
- "postbuild": "tsc -p ."
13
- },
14
- "repository": {
15
- "type": "git",
16
- "url": "git+https://github.com/nesvet/insite-config.git"
17
- },
18
- "keywords": [
19
- "insite",
20
- "config"
21
- ],
22
- "author": "Eugene Nesvetaev <dev@nesvet.dev> (https://nesvet.dev/)",
23
- "license": "MIT",
24
- "dependencies": {
25
- "@nesvet/n": "^1.2.1",
26
- "insite-db": "^2.3.3"
27
- },
28
- "devDependencies": {
29
- "@nesvet/conveyer": "^2.6.1",
30
- "@nesvet/eslint-config": "^2.1.2",
31
- "@types/node": "^24.0.13",
32
- "typescript": "^5.8.3"
33
- }
2
+ "name": "insite-config",
3
+ "version": "2.4.0",
4
+ "description": "Configuration loader for inSite server",
5
+ "keywords": [
6
+ "insite",
7
+ "config",
8
+ "server"
9
+ ],
10
+ "homepage": "https://github.com/nesvet/insite#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/nesvet/insite/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/nesvet/insite.git",
17
+ "directory": "packages/config"
18
+ },
19
+ "funding": {
20
+ "type": "patreon",
21
+ "url": "https://www.patreon.com/nesvet"
22
+ },
23
+ "license": "MIT",
24
+ "author": "Eugene Nesvetaev <dev@nesvet.dev> (https://nesvet.dev/)",
25
+ "type": "module",
26
+ "main": "./dist/index.js",
27
+ "module": "./dist/index.js",
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "scripts": {
34
+ "build": "bun .conveyer.js",
35
+ "postbuild": "tsc -p .",
36
+ "clean": "rm -rf dist",
37
+ "test": "echo \"Error: no test specified\" && exit 1",
38
+ "typecheck": "tsc --noEmit"
39
+ },
40
+ "dependencies": {
41
+ "@nesvet/n": "^1.2.1",
42
+ "insite-db": "^2.4.0"
43
+ },
44
+ "packageManager": "bun@1.3.9",
45
+ "engines": {
46
+ "node": ">=20.0.0"
47
+ }
34
48
  }