@juicesharp/rpiv-config 1.8.1
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/CHANGELOG.md +6 -0
- package/config.ts +171 -0
- package/index.ts +9 -0
- package/package.json +39 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
## [1.8.1] - 2026-05-17
|
|
2
|
+
|
|
3
|
+
### Added
|
|
4
|
+
- Shared config I/O library with `configPath`, `loadJsonConfig`, `saveJsonConfig`, `readEnvVar`, and `validateConfig` helpers, extracted from the rpiv sibling packages.
|
|
5
|
+
- `saveJsonConfig` returns a boolean indicating persist success; callers guard user-facing notifications on the result.
|
|
6
|
+
- `loadJsonConfig` emits a `console.warn` diagnostic on malformed JSON and rejects array-root values.
|
package/config.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rpiv-config — shared config I/O utilities for rpiv-mono sibling packages.
|
|
3
|
+
*
|
|
4
|
+
* Provides JSON config load/save with crash-resistant defaults, path resolution,
|
|
5
|
+
* guidance-field validation, env-var fallback, and TypeBox-driven schema validation.
|
|
6
|
+
* Stateless — no module-level singletons, no globalThis caches, no side effects.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { dirname, join } from "node:path";
|
|
12
|
+
import type { Static, TObject } from "typebox";
|
|
13
|
+
import { Value } from "typebox/value";
|
|
14
|
+
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
// Path resolution
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Resolve a config file path under `~/.config/<name>/`.
|
|
21
|
+
*
|
|
22
|
+
* @param name — package directory name (e.g. "rpiv-todo")
|
|
23
|
+
* @param file — config filename (defaults to "config.json")
|
|
24
|
+
* @returns absolute path to the config file
|
|
25
|
+
*/
|
|
26
|
+
export function configPath(name: string, file: string = "config.json"): string {
|
|
27
|
+
return join(homedir(), ".config", name, file);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
// JSON config load — Variant A (with typeof guard) universally
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Load and parse a JSON config file.
|
|
36
|
+
*
|
|
37
|
+
* Returns `{}` for missing files, malformed JSON, or non-plain-object values.
|
|
38
|
+
* The typeof guard fixes a latent bug where valid non-object JSON
|
|
39
|
+
* (e.g. `"hello"`, `42`, `null`) passes through the cast. Arrays are also
|
|
40
|
+
* rejected — `typeof [] === "object"` in JavaScript, but config files are
|
|
41
|
+
* always plain objects.
|
|
42
|
+
*/
|
|
43
|
+
export function loadJsonConfig<T>(path: string): T {
|
|
44
|
+
if (!existsSync(path)) return {} as T;
|
|
45
|
+
try {
|
|
46
|
+
const parsed = JSON.parse(readFileSync(path, "utf-8")) as unknown;
|
|
47
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {} as T;
|
|
48
|
+
return parsed as T;
|
|
49
|
+
} catch (err) {
|
|
50
|
+
// Diagnostic for malformed-JSON path. Silent save + silent load otherwise
|
|
51
|
+
// produce identical user-visible symptoms (state reverts on next start)
|
|
52
|
+
// with zero diagnostic surface — the user cannot tell "never saved" from
|
|
53
|
+
// "saved-but-unreadable." Warning is owner-only since the file lives in
|
|
54
|
+
// the user's HOME.
|
|
55
|
+
console.warn(`rpiv-config: invalid JSON at ${path}, using default ({}) — ${(err as Error).message}`);
|
|
56
|
+
return {} as T;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// JSON config save — best-effort void
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
/** File mode for config files (user read/write only). */
|
|
65
|
+
const CONFIG_FILE_MODE = 0o600;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Persist a config object as formatted JSON. Returns `true` on successful
|
|
69
|
+
* mkdir+write, `false` on filesystem failure (disk full, EACCES, EROFS, …).
|
|
70
|
+
*
|
|
71
|
+
* Every current rpiv-* save call site is user-initiated and shows a
|
|
72
|
+
* "Saved …" notification — callers MUST guard the success notification on
|
|
73
|
+
* the boolean return so a silent disk failure can't make the success message
|
|
74
|
+
* lie on disk-full / EACCES.
|
|
75
|
+
*
|
|
76
|
+
* The chmod step is best-effort and never affects the return value: some
|
|
77
|
+
* filesystems (tmpfs, network mounts, Windows-style perms) silently ignore
|
|
78
|
+
* chmod and there is no portable way to enforce 0600 perms across platforms.
|
|
79
|
+
* Callers that genuinely don't care about persistence outcome can discard
|
|
80
|
+
* the return — TypeScript does not warn on ignored `boolean`.
|
|
81
|
+
*/
|
|
82
|
+
export function saveJsonConfig(path: string, data: unknown): boolean {
|
|
83
|
+
try {
|
|
84
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
85
|
+
writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`, "utf-8");
|
|
86
|
+
} catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
chmodSync(path, CONFIG_FILE_MODE);
|
|
91
|
+
} catch {
|
|
92
|
+
// chmod may fail on some filesystems — best effort only, never gates success
|
|
93
|
+
}
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ---------------------------------------------------------------------------
|
|
98
|
+
// GuidanceFields — extracted from 4 byte-identical copies
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
export interface GuidanceFields {
|
|
102
|
+
promptSnippet?: string;
|
|
103
|
+
promptGuidelines?: string[];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Validate and extract guidance fields from an unknown value.
|
|
108
|
+
*
|
|
109
|
+
* Returns a clean `GuidanceFields` object with only valid entries.
|
|
110
|
+
* Byte-identical logic previously in rpiv-todo, rpiv-ask-user-question,
|
|
111
|
+
* rpiv-advisor, and rpiv-web-tools.
|
|
112
|
+
*/
|
|
113
|
+
export function validateGuidanceFields(fields: unknown): GuidanceFields {
|
|
114
|
+
if (!fields || typeof fields !== "object") return {};
|
|
115
|
+
const g = fields as Record<string, unknown>;
|
|
116
|
+
const result: GuidanceFields = {};
|
|
117
|
+
if (typeof g.promptSnippet === "string" && g.promptSnippet.length > 0) {
|
|
118
|
+
result.promptSnippet = g.promptSnippet;
|
|
119
|
+
}
|
|
120
|
+
if (
|
|
121
|
+
Array.isArray(g.promptGuidelines) &&
|
|
122
|
+
g.promptGuidelines.length > 0 &&
|
|
123
|
+
g.promptGuidelines.every((s) => typeof s === "string" && s.length > 0)
|
|
124
|
+
) {
|
|
125
|
+
result.promptGuidelines = g.promptGuidelines;
|
|
126
|
+
}
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ---------------------------------------------------------------------------
|
|
131
|
+
// Env-var fallback
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Read an environment variable with optional fallback.
|
|
136
|
+
*
|
|
137
|
+
* Trims whitespace from the env value. Returns `fallback` (or `undefined`)
|
|
138
|
+
* when the variable is unset or empty after trimming.
|
|
139
|
+
*/
|
|
140
|
+
export function readEnvVar(key: string, fallback?: string): string | undefined {
|
|
141
|
+
return process.env[key]?.trim() || fallback;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ---------------------------------------------------------------------------
|
|
145
|
+
// TypeBox-driven schema validation
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Validate and clean a config value against a TypeBox schema.
|
|
150
|
+
*
|
|
151
|
+
* 1. Guards against non-plain-object input (returns `{}` for primitives, arrays).
|
|
152
|
+
* 2. Clones the input (Value.Clean mutates).
|
|
153
|
+
* 3. Strips unknown properties via `Value.Clean`.
|
|
154
|
+
* 4. Applies schema defaults via `Value.Create` (spread merge: defaults
|
|
155
|
+
* provide base, cleaned value overrides).
|
|
156
|
+
* 5. Returns the validated, cleaned object typed as the schema's static type.
|
|
157
|
+
*
|
|
158
|
+
* Falls back to `{}` on any failure — same fail-soft contract as `loadJsonConfig`.
|
|
159
|
+
*/
|
|
160
|
+
export function validateConfig<T extends TObject>(schema: T, value: unknown): Static<T> {
|
|
161
|
+
try {
|
|
162
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return {} as Static<T>;
|
|
163
|
+
const cleaned = Value.Clean(schema, Value.Clone(value));
|
|
164
|
+
const defaults = Value.Create(schema);
|
|
165
|
+
// Merge: defaults as base, cleaned values override.
|
|
166
|
+
// Both are plain objects from TypeBox operations — safe spread via Record cast.
|
|
167
|
+
return { ...(defaults as Record<string, unknown>), ...(cleaned as Record<string, unknown>) } as Static<T>;
|
|
168
|
+
} catch {
|
|
169
|
+
return {} as Static<T>;
|
|
170
|
+
}
|
|
171
|
+
}
|
package/index.ts
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@juicesharp/rpiv-config",
|
|
3
|
+
"version": "1.8.1",
|
|
4
|
+
"description": "Shared config I/O utilities for rpiv-mono sibling packages",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"rpiv",
|
|
7
|
+
"config",
|
|
8
|
+
"shared-utility"
|
|
9
|
+
],
|
|
10
|
+
"type": "module",
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"author": "juicesharp",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/juicesharp/rpiv-mono.git",
|
|
16
|
+
"directory": "packages/rpiv-config"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-config#readme",
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/juicesharp/rpiv-mono/issues"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "vitest run"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"index.ts",
|
|
30
|
+
"config.ts",
|
|
31
|
+
"CHANGELOG.md"
|
|
32
|
+
],
|
|
33
|
+
"exports": {
|
|
34
|
+
".": "./index.ts"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"typebox": "*"
|
|
38
|
+
}
|
|
39
|
+
}
|