@tinyshed/tinystore 0.1.0-rc.3 → 0.1.0-rc.5

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/src/config.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  // An application's settings, as Go's kv.Config makes them: the defaults, then
2
- // a file's values, then the environment, then what update kept, which the
3
- // server keeps field by field in kv.db and sends to every store watching the
4
- // config. `value` is read from memory and is new after each change.
2
+ // each layer in the order given, then what update kept, which the server
3
+ // keeps field by field in kv.db and sends to every store watching the config.
4
+ // `value` is read from memory and is new after each change.
5
+
6
+ import { readFile } from 'node:fs/promises'
5
7
 
6
8
  import type { Link } from './connection.ts'
7
9
  import { ClosedError, InvalidError } from './errors.ts'
8
10
  import { checkName, handleOn } from './handles.ts'
9
- import { check, type StandardSchemaV1 } from './schema.ts'
11
+ import { check, isSchema, type StandardSchemaV1 } from './schema.ts'
10
12
  import type { Stream } from './session.ts'
11
13
  import { KvBucket, KvCall, KvConfigure, KvKept, methods } from './wire/messages.ts'
12
14
 
@@ -19,19 +21,102 @@ export type DeepPartial<T> = {
19
21
  : T[K]
20
22
  }
21
23
 
22
- export interface ConfigOptions<T> {
23
- /** a file's values over the defaults, as Bun reads YAML, JSON or TOML: `import file from './config.yaml'` */
24
- file?: DeepPartial<T>
25
- /** the variables' prefix: 'APP' reads APP_PORT; none when absent */
26
- prefix?: string
27
- /** a field's own variable, by its path: `{ dbUrl: 'DATABASE_URL' }`; false reads none */
28
- env?: Record<string, string> | false
29
- /** paths set by the defaults, the file or the environment alone: never kept, shown as *** */
30
- secret?: readonly string[]
31
- /** checks the config each time it is made: zod's, valibot's or another Standard Schema */
32
- schema?: StandardSchemaV1<unknown, T>
24
+ type Kind = 'string' | 'number' | 'boolean'
25
+
26
+ /** A field of a config's defaults made by `secret` or `required`, in place of its value. */
27
+ export class Setting<V> {
28
+ readonly kind: Kind
29
+ /** absent for a field a layer has to give */
30
+ readonly fallback: V | undefined
31
+ readonly secret: boolean
32
+ /** its own variable, read in place of the prefix and its path */
33
+ readonly variable: string | undefined
34
+
35
+ constructor(kind: Kind, fallback: V | undefined, secret: boolean, variable: string | undefined) {
36
+ this.kind = kind
37
+ this.fallback = fallback
38
+ this.secret = secret
39
+ this.variable = variable
40
+ }
41
+ }
42
+
43
+ /**
44
+ * A secret: never kept by update, and shown as *** by sources(). It reads
45
+ * its own variable when given one, and is required without a default.
46
+ *
47
+ * ```ts
48
+ * db: { url: secret('DATABASE_URL'), pool: 10 }
49
+ * ```
50
+ */
51
+ export function secret(variable?: string, fallback?: string): Setting<string> {
52
+ return new Setting('string', fallback, true, variable)
53
+ }
54
+
55
+ /** A field a layer has to give, or the config does not open: a string unless kind says. */
56
+ export function required(): Setting<string>
57
+ export function required(kind: StringConstructor): Setting<string>
58
+ export function required(kind: NumberConstructor): Setting<number>
59
+ export function required(kind: BooleanConstructor): Setting<boolean>
60
+ export function required(
61
+ kind: StringConstructor | NumberConstructor | BooleanConstructor = String,
62
+ ): Setting<string | number | boolean> {
63
+ return new Setting<string | number | boolean>(
64
+ kind === Number ? 'number' : kind === Boolean ? 'boolean' : 'string',
65
+ undefined,
66
+ false,
67
+ undefined,
68
+ )
69
+ }
70
+
71
+ /** The environment as a layer of a config, which `fromEnv` makes. */
72
+ export class FromEnv {
73
+ readonly prefix: string
74
+ readonly files: readonly string[]
75
+
76
+ constructor(prefix: string, files: readonly string[]) {
77
+ this.prefix = prefix
78
+ this.files = files
79
+ }
80
+ }
81
+
82
+ /**
83
+ * The environment as a config's layer: `fromEnv('APP')` reads db.pool from
84
+ * APP_DB_POOL, and `fromEnv()` from DB_POOL. The .env files given are read
85
+ * first, the process's own variables over them, a missing file skipped.
86
+ */
87
+ export function fromEnv(prefix = '', ...files: string[]): FromEnv {
88
+ return new FromEnv(prefix, files)
33
89
  }
34
90
 
91
+ /** A config's check, which `validate` makes. */
92
+ export class Validate {
93
+ readonly schema: StandardSchemaV1
94
+
95
+ constructor(schema: StandardSchemaV1) {
96
+ this.schema = schema
97
+ }
98
+ }
99
+
100
+ /** Checks a config each time it is made, with zod's, valibot's or another Standard Schema. */
101
+ export function validate(schema: StandardSchemaV1): Validate {
102
+ return new Validate(schema)
103
+ }
104
+
105
+ /** A config's value, as its defaults make it: each Setting its value's type. */
106
+ export type ConfigValue<D extends object> = { [K in keyof D]: FieldValue<D[K]> }
107
+
108
+ type FieldValue<F> =
109
+ F extends Setting<infer V>
110
+ ? V
111
+ : F extends readonly unknown[] | Date
112
+ ? F
113
+ : F extends object
114
+ ? ConfigValue<F>
115
+ : F
116
+
117
+ /** What a config takes after its defaults, each over the one before. */
118
+ export type ConfigLayer<V> = DeepPartial<V> | FromEnv | Validate
119
+
35
120
  /** Where a field's value came from. */
36
121
  export interface Source {
37
122
  path: string
@@ -43,6 +128,14 @@ export interface Source {
43
128
  ignored?: string
44
129
  }
45
130
 
131
+ interface Field {
132
+ /** its default, or '', 0 or false for one without */
133
+ sample: unknown
134
+ secret: boolean
135
+ required: boolean
136
+ variable: string | undefined
137
+ }
138
+
46
139
  /**
47
140
  * A field's variable: the prefix and its path in upper snake case, as Go's and
48
141
  * Python's configs name it.
@@ -74,38 +167,110 @@ const isUpper = (c: string) => c !== c.toLowerCase() && c === c.toUpperCase()
74
167
  const isLower = (c: string) => c !== c.toUpperCase() && c === c.toLowerCase()
75
168
  const isDigit = (c: string) => c >= '0' && c <= '9'
76
169
 
77
- /** A config: open it with `store.kv.config(name, defaults, options)`. */
170
+ /**
171
+ * The variables of a .env file, as Go's and Python's configs read one: NAME=value
172
+ * lines, export before a name, # comments, a comment after a space, double
173
+ * quotes reading \n \r \t \" and \\, single quotes reading nothing, a quoted
174
+ * value over lines; a later name wins.
175
+ */
176
+ export function parseDotenv(text: string): Record<string, string> {
177
+ const values: Record<string, string> = {}
178
+ let line = 1
179
+ let rest = text
180
+ while (rest !== '') {
181
+ const [name, value, after] = dotenvAssignment(rest, line)
182
+ line += rest.slice(0, rest.length - after.length).split('\n').length - 1
183
+ if (name !== '') {
184
+ values[name] = value
185
+ }
186
+ rest = after
187
+ }
188
+ return values
189
+ }
190
+
191
+ function dotenvAssignment(text: string, number: number): [string, string, string] {
192
+ const end = text.indexOf('\n')
193
+ const line = end < 0 ? text : text.slice(0, end)
194
+ const rest = end < 0 ? '' : text.slice(end + 1)
195
+ const trimmed = line.trim()
196
+ if (trimmed === '' || trimmed.startsWith('#')) {
197
+ return ['', '', rest]
198
+ }
199
+ const equals = line.indexOf('=')
200
+ if (equals < 0) {
201
+ throw new InvalidError(`line ${number}: ${JSON.stringify(line)} is no NAME=value`)
202
+ }
203
+ let name = line.slice(0, equals).trim()
204
+ if (name.startsWith('export ')) {
205
+ name = name.slice('export '.length).trim()
206
+ }
207
+ if (!/^[\p{L}_][\p{L}\p{Nd}_]*$/u.test(name)) {
208
+ throw new InvalidError(`line ${number}: ${JSON.stringify(name)} is no variable's name`)
209
+ }
210
+ let start = equals + 1
211
+ while (line[start] === ' ' || line[start] === '\t') {
212
+ start++
213
+ }
214
+ if (line[start] === '"' || line[start] === "'") {
215
+ return [name, ...dotenvQuoted(text.slice(start), number)]
216
+ }
217
+ let value = line.slice(start)
218
+ const comment = value.indexOf(' #')
219
+ if (comment >= 0) {
220
+ value = value.slice(0, comment)
221
+ }
222
+ return [name, value.replace(/[ \t\r]+$/, ''), rest]
223
+ }
224
+
225
+ function dotenvQuoted(text: string, number: number): [string, string] {
226
+ const quote = text[0]
227
+ let out = ''
228
+ for (let i = 1; i < text.length; i++) {
229
+ const c = text[i] as string
230
+ if (c === quote) {
231
+ const end = text.indexOf('\n', i + 1)
232
+ return [out, end < 0 ? '' : text.slice(end + 1)]
233
+ }
234
+ if (c === '\\' && quote === '"' && i + 1 < text.length) {
235
+ i++
236
+ const escaped = text[i] as string
237
+ out += escaped === 'n' ? '\n' : escaped === 'r' ? '\r' : escaped === 't' ? '\t' : escaped
238
+ } else {
239
+ out += c
240
+ }
241
+ }
242
+ throw new InvalidError(`line ${number}: a value opened with ${quote} is never closed`)
243
+ }
244
+
245
+ /** A config: open it with `store.kv.config(name, defaults, ...layers)`. */
78
246
  export class Config<T extends object> {
79
247
  readonly name: string
80
248
  readonly #link: Link
81
249
  readonly #open: Uint8Array
82
- readonly #leaves: Map<string, unknown>
250
+ readonly #fields: Map<string, Field>
83
251
  readonly #base: Record<string, unknown>
84
252
  readonly #from: Map<string, string>
85
- readonly #secret: Set<string>
86
- readonly #schema: StandardSchemaV1<unknown, T> | undefined
253
+ readonly #schemas: StandardSchemaV1[] = []
87
254
  readonly #listeners = new Set<(value: T) => void>()
255
+ /** the last fromEnv's prefix, for a missing field's variable */
256
+ #prefix: string | undefined
88
257
  #kept = new Map<string, string>()
89
258
  #ignored = new Map<string, string>()
90
- #value: T
259
+ #value = {} as T
91
260
  #stream: Stream | undefined
92
261
  #closed = false
93
262
 
94
- /** Configs come from `store.kv.config`, which waits for the first state. */
95
- constructor(link: Link, name: string, defaults: T, options: ConfigOptions<T>) {
263
+ /** Configs come from `store.kv.config`, which lays their layers and waits for the first state. */
264
+ constructor(link: Link, name: string, defaults: object) {
96
265
  checkName(name, 'config')
97
266
  this.#link = link
98
267
  this.name = name
99
268
  this.#open = KvBucket.encode({ name, config: true })
100
- this.#leaves = new Map(leavesOf(defaults))
101
- this.#schema = options.schema
102
- this.#secret = new Set(options.secret ?? [])
103
- for (const path of this.#secret) {
104
- this.#leaf(path)
105
- }
106
- this.#from = new Map([...this.#leaves.keys()].map(path => [path, 'default']))
107
- this.#base = layered(this.#leaves, defaults, options, this.#from)
108
- this.#value = deepFreeze(structuredClone(this.#base)) as T
269
+ this.#fields = new Map(leavesOf(defaults).map(([path, leaf]) => [path, fieldOf(leaf)]))
270
+ this.#base = valuesOf(defaults as Record<string, unknown>)
271
+ this.#from = new Map(
272
+ [...this.#fields].filter(([, field]) => !field.required).map(([path]) => [path, 'default']),
273
+ )
109
274
  }
110
275
 
111
276
  /** The config now, frozen: update changes it. */
@@ -113,24 +278,55 @@ export class Config<T extends object> {
113
278
  return this.#value
114
279
  }
115
280
 
281
+ /** Lays each layer over the defaults, the one before it under it, and checks what is required. */
282
+ async lay(layers: readonly unknown[]): Promise<void> {
283
+ for (const layer of layers) {
284
+ if (layer instanceof FromEnv) {
285
+ await this.#layEnvironment(layer)
286
+ } else if (layer instanceof Validate) {
287
+ this.#schemas.push(layer.schema)
288
+ } else if (isSchema(layer)) {
289
+ throw new InvalidError(
290
+ `config ${this.name}: a schema checks the config as validate(schema)`,
291
+ )
292
+ } else if (plain(layer)) {
293
+ this.#layFile(layer)
294
+ } else {
295
+ throw new InvalidError(
296
+ `config ${this.name}: a layer is a file's values, fromEnv() or validate(), not ${String(layer)}`,
297
+ )
298
+ }
299
+ }
300
+ for (const [path, field] of this.#fields) {
301
+ if (field.required && missing(pathIn(this.#base, path))) {
302
+ throw new InvalidError(`config ${this.name}: ${this.#requiredText(path, field)}`)
303
+ }
304
+ }
305
+ this.#value = deepFreeze(structuredClone(this.#base)) as T
306
+ }
307
+
116
308
  /**
117
309
  * Changes the fields change names, at any depth; each one that changed is
118
310
  * checked, kept, and seen by every store watching the config. A change the
119
- * schema refuses, or one of a secret, is InvalidError and keeps nothing.
311
+ * schema refuses, one of a secret, or one leaving a required field empty, is
312
+ * InvalidError and keeps nothing.
120
313
  */
121
314
  async update(change: DeepPartial<T>): Promise<void> {
122
315
  const next = merged(structuredClone(this.#value) as Record<string, unknown>, change)
123
316
  const set: string[] = []
124
- for (const path of this.#leaves.keys()) {
317
+ for (const [path, field] of this.#fields) {
125
318
  const now = JSON.stringify(pathIn(next, path))
126
319
  if (now === JSON.stringify(pathIn(this.#value, path))) {
127
320
  continue
128
321
  }
129
- if (this.#secret.has(path)) {
322
+ if (field.secret) {
130
323
  throw new InvalidError(
131
- `config ${this.name}: ${path} is a secret, set by the defaults, the file or the environment alone`,
324
+ `config ${this.name}: ${path} is a secret, set by the defaults, a file or the environment alone`,
132
325
  )
133
326
  }
327
+ if (field.required && missing(pathIn(next, path))) {
328
+ throw new InvalidError(`config ${this.name}: ${path} is required`)
329
+ }
134
330
  set.push(path, now)
135
331
  }
136
332
  if (set.length === 0) {
@@ -143,7 +339,7 @@ export class Config<T extends object> {
143
339
  /** Forgets what update kept for paths, each a field or a group of them; all of it without paths. */
144
340
  async reset(...paths: string[]): Promise<void> {
145
341
  for (const path of paths) {
146
- if (![...this.#leaves.keys()].some(leaf => under(leaf, path))) {
342
+ if (![...this.#fields.keys()].some(leaf => under(leaf, path))) {
147
343
  throw new InvalidError(`config ${this.name} has no field ${path}`)
148
344
  }
149
345
  }
@@ -164,13 +360,11 @@ export class Config<T extends object> {
164
360
 
165
361
  /** Where each field's value came from, and why a kept value is left out. */
166
362
  sources(): Source[] {
167
- return [...this.#leaves.keys()].map(path => {
363
+ return [...this.#fields].map(([path, field]) => {
168
364
  const kept = this.#kept.has(path) && !this.#ignored.has(path)
169
365
  const source: Source = {
170
366
  path,
171
- value: this.#secret.has(path)
172
- ? '***'
173
- : (JSON.stringify(pathIn(this.#value, path)) ?? 'null'),
367
+ value: field.secret ? '***' : (JSON.stringify(pathIn(this.#value, path)) ?? 'null'),
174
368
  from: kept ? 'kept' : (this.#from.get(path) ?? 'default'),
175
369
  }
176
370
  const ignored = this.#ignored.get(path)
@@ -191,6 +385,46 @@ export class Config<T extends object> {
191
385
  this.#stream?.cancel()
192
386
  }
193
387
 
388
+ #layFile(values: Record<string, unknown>): void {
389
+ for (const [path, value] of leavesOf(values)) {
390
+ const field = this.#fields.get(path)
391
+ if (field === undefined) {
392
+ continue
393
+ }
394
+ if (!fits(value, field.sample)) {
395
+ throw new InvalidError(
396
+ `the file's ${path}: ${JSON.stringify(value)} is no ${kindOf(field.sample)}`,
397
+ )
398
+ }
399
+ setPath(this.#base, path, value)
400
+ this.#from.set(path, 'file')
401
+ }
402
+ }
403
+
404
+ async #layEnvironment(layer: FromEnv): Promise<void> {
405
+ const variables: Record<string, string | undefined> = {}
406
+ for (const file of layer.files) {
407
+ Object.assign(variables, await readDotenv(file))
408
+ }
409
+ Object.assign(variables, process.env)
410
+ for (const [path, field] of this.#fields) {
411
+ const name = field.variable ?? envName(layer.prefix, path)
412
+ const text = variables[name]
413
+ if (text !== undefined) {
414
+ setPath(this.#base, path, readVariable(text, field.sample, name))
415
+ this.#from.set(path, `env ${name}`)
416
+ }
417
+ }
418
+ this.#prefix = layer.prefix
419
+ }
420
+
421
+ #requiredText(path: string, field: Field): string {
422
+ if (this.#prefix === undefined) {
423
+ return `${path} is required`
424
+ }
425
+ return `${path} is required: set ${field.variable ?? envName(this.#prefix, path)}`
426
+ }
427
+
194
428
  async #follow(ready: () => void, failed: (err: unknown) => void): Promise<void> {
195
429
  let first = true
196
430
  for (let pause = 100; !this.#closed; pause = Math.min(pause * 2, 5000)) {
@@ -264,7 +498,7 @@ export class Config<T extends object> {
264
498
  /** Makes the config from its base and what is kept, leaving out what no longer fits, and tells the watchers. */
265
499
  async #build(kept: Map<string, string>): Promise<void> {
266
500
  const ignored = new Map<string, string>()
267
- let next = withKept(this.#base, this.#leaves, kept, ignored)
501
+ let next = withKept(this.#base, this.#fields, kept, ignored)
268
502
  let issues = await this.#issues(next)
269
503
  if (issues !== undefined && kept.size > ignored.size) {
270
504
  for (const path of kept.keys()) {
@@ -295,71 +529,83 @@ export class Config<T extends object> {
295
529
  }
296
530
 
297
531
  async #issues(value: Record<string, unknown>): Promise<string | undefined> {
298
- if (this.#schema === undefined) {
299
- return undefined
532
+ for (const schema of this.#schemas) {
533
+ const checked = await check(schema, value)
534
+ if ('issues' in checked) {
535
+ return checked.issues
536
+ }
300
537
  }
301
- const checked = await check(this.#schema, value)
302
- return 'issues' in checked ? checked.issues : undefined
538
+ return undefined
303
539
  }
540
+ }
304
541
 
305
- #leaf(path: string): unknown {
306
- if (!this.#leaves.has(path)) {
307
- throw new InvalidError(`config ${this.name} has no field ${path}`)
308
- }
309
- return this.#leaves.get(path)
542
+ function fieldOf(leaf: unknown): Field {
543
+ if (!(leaf instanceof Setting)) {
544
+ return { sample: leaf, secret: false, required: false, variable: undefined }
545
+ }
546
+ return {
547
+ sample: leaf.fallback ?? { string: '', number: 0, boolean: false }[leaf.kind],
548
+ secret: leaf.secret,
549
+ required: leaf.fallback === undefined,
550
+ variable: leaf.variable,
310
551
  }
311
552
  }
312
553
 
313
- /** The defaults, the file and the environment, each over the one before. */
314
- function layered<T>(
315
- leaves: Map<string, unknown>,
316
- defaults: T,
317
- options: ConfigOptions<T>,
318
- from: Map<string, string>,
319
- ): Record<string, unknown> {
320
- const base = structuredClone(defaults) as Record<string, unknown>
321
- if (options.file !== undefined) {
322
- for (const [path, value] of leavesOf(options.file)) {
323
- const wanted = leaves.get(path)
324
- if (!leaves.has(path)) {
325
- continue
326
- }
327
- if (!fits(value, wanted)) {
328
- throw new InvalidError(
329
- `the file's ${path}: ${JSON.stringify(value)} is no ${kindOf(wanted)}`,
330
- )
554
+ /** The defaults' values: a Setting's default, and nothing for one without. */
555
+ function valuesOf(tree: Record<string, unknown>): Record<string, unknown> {
556
+ const values: Record<string, unknown> = {}
557
+ for (const [key, inner] of Object.entries(tree)) {
558
+ if (inner instanceof Setting) {
559
+ if (inner.fallback !== undefined) {
560
+ values[key] = inner.fallback
331
561
  }
332
- setPath(base, path, value)
333
- from.set(path, 'file')
562
+ } else {
563
+ values[key] = plain(inner) ? valuesOf(inner) : structuredClone(inner)
334
564
  }
335
565
  }
336
- if (options.env === false) {
337
- return base
338
- }
339
- for (const [path, wanted] of leaves) {
340
- const name = options.env?.[path] ?? envName(options.prefix ?? '', path)
341
- const text = process.env[name]
342
- if (text !== undefined) {
343
- setPath(base, path, fromEnv(text, wanted, name))
344
- from.set(path, `env ${name}`)
566
+ return values
567
+ }
568
+
569
+ /** A required field's value no layer gave, or gave empty. */
570
+ function missing(value: unknown): boolean {
571
+ return value === undefined || value === ''
572
+ }
573
+
574
+ async function readDotenv(path: string): Promise<Record<string, string>> {
575
+ let text: string
576
+ try {
577
+ text = await readFile(path, 'utf8')
578
+ } catch (err) {
579
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
580
+ return {}
345
581
  }
582
+ throw err
583
+ }
584
+ try {
585
+ return parseDotenv(text)
586
+ } catch (err) {
587
+ throw new InvalidError(`${path}: ${(err as Error).message}`)
346
588
  }
347
- return base
348
589
  }
349
590
 
350
- /** The base with each kept value that fits its field over it. */
591
+ /** The base with each kept value that fits its field over it; a secret is never taken from what was kept. */
351
592
  function withKept(
352
593
  base: Record<string, unknown>,
353
- leaves: Map<string, unknown>,
594
+ fields: Map<string, Field>,
354
595
  kept: Map<string, string>,
355
596
  ignored: Map<string, string>,
356
597
  ): Record<string, unknown> {
357
598
  const next = structuredClone(base)
358
599
  for (const [path, spelled] of kept) {
359
- if (!leaves.has(path)) {
600
+ const field = fields.get(path)
601
+ if (field === undefined) {
360
602
  ignored.set(path, 'the config has no such field')
361
603
  continue
362
604
  }
605
+ if (field.secret) {
606
+ ignored.set(path, 'the field is a secret')
607
+ continue
608
+ }
363
609
  let value: unknown
364
610
  try {
365
611
  value = JSON.parse(spelled)
@@ -367,8 +613,12 @@ function withKept(
367
613
  ignored.set(path, `${spelled} is no JSON`)
368
614
  continue
369
615
  }
370
- if (!fits(value, leaves.get(path))) {
371
- ignored.set(path, `${spelled} is no ${kindOf(leaves.get(path))}`)
616
+ if (!fits(value, field.sample)) {
617
+ ignored.set(path, `${spelled} is no ${kindOf(field.sample)}`)
618
+ continue
619
+ }
620
+ if (field.required && missing(value)) {
621
+ ignored.set(path, 'the field is required')
372
622
  continue
373
623
  }
374
624
  setPath(next, path, value)
@@ -382,7 +632,7 @@ function withKept(
382
632
  *
383
633
  * 8080 ← '3000' → 3000, ['x'] ← 'a.com, b.com' → ['a.com', 'b.com']
384
634
  */
385
- function fromEnv(text: string, wanted: unknown, name: string): unknown {
635
+ function readVariable(text: string, wanted: unknown, name: string): unknown {
386
636
  const trimmed = text.trim()
387
637
  if (typeof wanted === 'string') {
388
638
  return text
@@ -405,7 +655,9 @@ function fromEnv(text: string, wanted: unknown, name: string): unknown {
405
655
  }
406
656
  if (Array.isArray(wanted) && !trimmed.startsWith('[')) {
407
657
  const item = wanted[0] ?? ''
408
- return trimmed === '' ? [] : trimmed.split(',').map(part => fromEnv(part.trim(), item, name))
658
+ return trimmed === ''
659
+ ? []
660
+ : trimmed.split(',').map(part => readVariable(part.trim(), item, name))
409
661
  }
410
662
  try {
411
663
  const value: unknown = JSON.parse(trimmed)
@@ -434,7 +686,13 @@ function leavesOf(value: unknown, parent = ''): [string, unknown][] {
434
686
 
435
687
  function plain(value: unknown): value is Record<string, unknown> {
436
688
  return (
437
- typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
689
+ typeof value === 'object' &&
690
+ value !== null &&
691
+ !Array.isArray(value) &&
692
+ !(value instanceof Date) &&
693
+ !(value instanceof Setting) &&
694
+ !(value instanceof FromEnv) &&
695
+ !(value instanceof Validate)
438
696
  )
439
697
  }
440
698
 
package/src/console.ts CHANGED
@@ -8,6 +8,17 @@
8
8
  /** How a logger writes its lines as they are logged; without one, pretty on a terminal and JSON otherwise. */
9
9
  export type ConsoleFormat = 'pretty' | 'json' | 'off'
10
10
 
11
+ /** How a pretty line shows its time: `11:02:11.123`, `2026-10-02 11:02:11.123 +03:00` or none. */
12
+ export type ConsoleTime = 'clock' | 'full' | 'off'
13
+
14
+ export interface Look {
15
+ color: boolean
16
+ /** a test's, whose lines do not depend on the machine's zone */
17
+ utc?: boolean
18
+ time?: ConsoleTime | undefined
19
+ hideStream?: boolean | undefined
20
+ }
21
+
11
22
  /** A line as a console writes it and the store keeps it: its fields already JSON. */
12
23
  export interface ConsoleLine {
13
24
  at: Date
@@ -74,16 +85,22 @@ const cyan = '\x1b[36m'
74
85
  * traceback, follows the line, indented. A key or a string shows without its
75
86
  * quotes when it is one word with no '=', quote or backslash.
76
87
  */
77
- export function prettyLine(line: ConsoleLine, color: boolean, utc = false): string {
78
- const paint = (hue: string, text: string) => (color ? hue + text + reset : text)
88
+ export function prettyLine(line: ConsoleLine, look: Look): string {
89
+ const paint = (hue: string, text: string) => (look.color ? hue + text + reset : text)
79
90
  const [label, hue] = prettyLevel(line.level)
80
- let out = `${paint(dim, clock(line.at, utc))} ${paint(hue, label)}${' '.repeat(Math.max(0, 5 - label.length))}`
81
- out += ` ${paint(cyan, line.stream)}`
91
+ let out = look.time === 'off' ? '' : `${paint(dim, stamp(line.at, look))} `
92
+ out += paint(hue, label)
93
+ // the level is padded to five; the columns after it are two spaces apart
94
+ let separator = `${' '.repeat(Math.max(0, 5 - label.length))} `
95
+ if (look.hideStream !== true) {
96
+ out += `${separator}${paint(cyan, line.stream)}`
97
+ separator = ' '
98
+ }
82
99
  const message = prettyMessage(line)
83
100
  if (message !== '') {
84
- out += ` ${message}`
101
+ out += `${separator}${message}`
102
+ separator = ' '
85
103
  }
86
- let separator = ' '
87
104
  const field = (key: string, text: string) => {
88
105
  out += `${separator}${paint(dim, `${bare(key) ? key : JSON.stringify(key)}=`)}${text}`
89
106
  separator = ' '
@@ -174,12 +191,36 @@ function bare(text: string): boolean {
174
191
  return true
175
192
  }
176
193
 
177
- function clock(at: Date, utc: boolean): string {
178
- const parts = utc
179
- ? [at.getUTCHours(), at.getUTCMinutes(), at.getUTCSeconds()]
180
- : [at.getHours(), at.getMinutes(), at.getSeconds()]
181
- const millis = utc ? at.getUTCMilliseconds() : at.getMilliseconds()
182
- return `${parts.map(n => String(n).padStart(2, '0')).join(':')}.${String(millis).padStart(3, '0')}`
194
+ /** The time of day, or with the date and zone in full: 2026-10-02 11:02:11.123 +03:00. */
195
+ function stamp(at: Date, look: Look): string {
196
+ const utc = look.utc === true
197
+ const [year, month, day, hours, minutes, seconds, millis] = utc
198
+ ? [
199
+ at.getUTCFullYear(),
200
+ at.getUTCMonth() + 1,
201
+ at.getUTCDate(),
202
+ at.getUTCHours(),
203
+ at.getUTCMinutes(),
204
+ at.getUTCSeconds(),
205
+ at.getUTCMilliseconds(),
206
+ ]
207
+ : [
208
+ at.getFullYear(),
209
+ at.getMonth() + 1,
210
+ at.getDate(),
211
+ at.getHours(),
212
+ at.getMinutes(),
213
+ at.getSeconds(),
214
+ at.getMilliseconds(),
215
+ ]
216
+ const two = (n: number) => String(n).padStart(2, '0')
217
+ const clock = `${two(hours)}:${two(minutes)}:${two(seconds)}.${String(millis).padStart(3, '0')}`
218
+ if (look.time !== 'full') {
219
+ return clock
220
+ }
221
+ const offset = utc ? 0 : -at.getTimezoneOffset()
222
+ const zone = `${offset < 0 ? '-' : '+'}${two(Math.trunc(Math.abs(offset) / 60))}:${two(Math.abs(offset) % 60)}`
223
+ return `${String(year).padStart(4, '0')}-${two(month)}-${two(day)} ${clock} ${zone}`
183
224
  }
184
225
 
185
226
  /**