@strutvane/redis 0.0.0-stage → 0.2.0-next.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.
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The installer (`node strut install:redis`, today `node strut add redis`): sets Redis up in an
3
+ * app completely and idempotently (running it twice changes nothing the second time).
4
+ *
5
+ * 1. `config/redis.ts`: the non-secret connection settings, read from `.env`;
6
+ * 2. `config/index.ts`: registers that file (`config('redis.host')`);
7
+ * 3. `.env` and `.env.example`: the `REDIS_*` keys (empty secrets; never overwrites a value);
8
+ * 4. `bootstrap/providers.ts`: adds `RedisServiceProvider`;
9
+ * 5. `config/session.ts`: allows `SESSION_DRIVER=redis` (the skeleton only lists `file`).
10
+ *
11
+ * It does **not** switch `CACHE_STORE` or `SESSION_DRIVER`: the app keeps working exactly as
12
+ * before until you choose Redis in `.env` (a running app must never start depending on a server
13
+ * nobody set up yet).
14
+ *
15
+ * The app files are edited as text, only when they have the skeleton's shape; any other shape
16
+ * is left untouched and the step is printed for you to do by hand (never a half-edited file).
17
+ * Uninstall reverses each edit and keeps a `config/redis.ts` you changed.
18
+ *
19
+ * @module
20
+ */
21
+ import { Installer } from "@strutvane/framework/contracts";
22
+ /** The `config/redis.ts` the installer writes. */
23
+ export declare const CONFIG_FILE: string;
24
+ /** The `.env` keys the installer adds (and uninstall removes). */
25
+ export declare const ENV_KEYS: readonly string[];
26
+ /**
27
+ * Add the provider to `bootstrap/providers.ts` source; `undefined` when the file doesn't have the
28
+ * skeleton's shape (`const providers … = [ … ]`). Unchanged source when already present.
29
+ *
30
+ * @example
31
+ * addProvider("import x from 'y'\nconst providers: readonly AnyProvider[] = [AppServiceProvider]\n")
32
+ */
33
+ export declare function addProvider(source: string): string | undefined;
34
+ /**
35
+ * Remove what {@link addProvider} added.
36
+ *
37
+ * @example
38
+ * removeProvider(addProvider(source) ?? source) === source
39
+ */
40
+ export declare function removeProvider(source: string): string;
41
+ /**
42
+ * Register `config/redis.ts` in `config/index.ts` source; `undefined` when the file doesn't have the
43
+ * skeleton's shape (`export default { … }`).
44
+ *
45
+ * @example
46
+ * addConfigFile("import app from './app.ts'\nexport default { app } satisfies ConfigFiles\n")
47
+ */
48
+ export declare function addConfigFile(source: string): string | undefined;
49
+ /**
50
+ * Remove what {@link addConfigFile} added.
51
+ *
52
+ * @example
53
+ * removeConfigFile(source)
54
+ */
55
+ export declare function removeConfigFile(source: string): string;
56
+ /**
57
+ * Let `SESSION_DRIVER` be `redis` in `config/session.ts` source; `undefined` when the skeleton's
58
+ * line isn't there (already edited, or a different file).
59
+ *
60
+ * @example
61
+ * allowRedisSessions("driver: env.oneOf('SESSION_DRIVER', ['file'], 'file'),")
62
+ */
63
+ export declare function allowRedisSessions(source: string): string | undefined;
64
+ /**
65
+ * The Redis installer.
66
+ *
67
+ * @example
68
+ * // package.json: "strutvane": { "installer": "./dist/installer.mjs" }
69
+ * export { installer } from '@strutvane/redis/installer'
70
+ */
71
+ export declare const installer: Installer;
72
+ //# sourceMappingURL=installer.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installer.d.mts","names":[],"sources":["../src/installer.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;qBA6Ba;;qBA6BA;;;;;;;;wBAmBG,YAAY;;;;;;;wBA2BZ,eAAe;;;;;;;;wBAef,cAAc;;;;;;;wBAyBd,iBAAiB;;;;;;;;wBAkBjB,mBAAmB;;;;;;;;qBActB,WAAW"}
@@ -0,0 +1,228 @@
1
+ // src/installer.ts
2
+ const PROVIDER = "RedisServiceProvider";
3
+ const PROVIDER_IMPORT = `import { ${PROVIDER} } from '@strutvane/redis/provider'`;
4
+ const CONFIG_IMPORT = "import redis from './redis.ts'";
5
+ const SESSION_FILE_ONLY = "env.oneOf('SESSION_DRIVER', ['file'],";
6
+ const SESSION_WITH_REDIS = "env.oneOf('SESSION_DRIVER', ['file', 'redis'],";
7
+ /** The `config/redis.ts` the installer writes. */
8
+ const CONFIG_FILE = `// Redis / Valkey connection settings (@strutvane/redis), read from .env.
9
+ //
10
+ // REDIS_URL and REDIS_PASSWORD are deliberately not here: the config tree is cached and easy to
11
+ // dump, so the package reads secrets from the environment only when it connects. REDIS_URL, when
12
+ // set, wins over host, port, user, password and database (rediss:// means TLS).
13
+ import { defineConfig } from '@strutvane/framework'
14
+ import type { RedisConfig } from '@strutvane/redis'
15
+
16
+ export default defineConfig(
17
+ (env) =>
18
+ ({
19
+ /** The server. */
20
+ host: env.string('REDIS_HOST', '127.0.0.1'),
21
+ port: env.integer('REDIS_PORT', 6379),
22
+ /** An ACL user (Redis 6+); empty means the default user. */
23
+ username: env.string('REDIS_USERNAME', ''),
24
+ /** The database number (0-15 on a default server). */
25
+ database: env.integer('REDIS_DB', 0),
26
+ /** TLS: true or false; empty follows REDIS_URL (rediss:// = TLS). Always verified. */
27
+ tls: env.string('REDIS_TLS', ''),
28
+ /** A PEM CA file for a private CA. */
29
+ tls_ca: env.string('REDIS_TLS_CA', ''),
30
+ /** Prefix for every key, so apps can share one server. Empty: the app name. */
31
+ prefix: env.string('REDIS_PREFIX', ''),
32
+ }) satisfies RedisConfig,
33
+ )
34
+ `;
35
+ /** The `.env` keys the installer adds (and uninstall removes). */
36
+ const ENV_KEYS = [
37
+ "REDIS_URL",
38
+ "REDIS_HOST",
39
+ "REDIS_PORT",
40
+ "REDIS_USERNAME",
41
+ "REDIS_PASSWORD",
42
+ "REDIS_DB",
43
+ "REDIS_TLS",
44
+ "REDIS_TLS_CA",
45
+ "REDIS_PREFIX"
46
+ ];
47
+ /**
48
+ * Add the provider to `bootstrap/providers.ts` source; `undefined` when the file doesn't have the
49
+ * skeleton's shape (`const providers … = [ … ]`). Unchanged source when already present.
50
+ *
51
+ * @example
52
+ * addProvider("import x from 'y'\nconst providers: readonly AnyProvider[] = [AppServiceProvider]\n")
53
+ */
54
+ function addProvider(source) {
55
+ const array = /(const\s+providers\b[^=]*=\s*\[)([\s\S]*?)(\])/.exec(source);
56
+ if (array === null) return void 0;
57
+ if (new RegExp(`\\b${PROVIDER}\\b`).test(array[2] ?? "")) return source;
58
+ const items = array[2] ?? "";
59
+ const multiline = items.includes("\n");
60
+ let replaced;
61
+ if (multiline) {
62
+ const indent = /\n([ \t]+)\S/.exec(items)?.[1] ?? " ";
63
+ const trimmed = items.replace(/\s*$/, "");
64
+ replaced = `${trimmed}${trimmed === "" || trimmed.endsWith(",") ? "" : ","}\n${indent}${PROVIDER},\n`;
65
+ } else {
66
+ const trimmed = items.trim().replace(/,$/, "");
67
+ replaced = trimmed === "" ? PROVIDER : `${trimmed}, ${PROVIDER}`;
68
+ }
69
+ const start = array.index + (array[1] ?? "").length;
70
+ return addImport(source.slice(0, start) + replaced + source.slice(start + items.length), PROVIDER_IMPORT);
71
+ }
72
+ /**
73
+ * Remove what {@link addProvider} added.
74
+ *
75
+ * @example
76
+ * removeProvider(addProvider(source) ?? source) === source
77
+ */
78
+ function removeProvider(source) {
79
+ return removeImport(source, PROVIDER_IMPORT).replace(new RegExp(`,\\n[ \\t]*${PROVIDER},?(?=\\n)`), "").replace(new RegExp(`\\n[ \\t]*${PROVIDER},`), "").replace(new RegExp(`,\\s*${PROVIDER}\\b`), "").replace(new RegExp(`\\[\\s*${PROVIDER}\\s*\\]`), "[]");
80
+ }
81
+ /**
82
+ * Register `config/redis.ts` in `config/index.ts` source; `undefined` when the file doesn't have the
83
+ * skeleton's shape (`export default { … }`).
84
+ *
85
+ * @example
86
+ * addConfigFile("import app from './app.ts'\nexport default { app } satisfies ConfigFiles\n")
87
+ */
88
+ function addConfigFile(source) {
89
+ const object = /export\s+default\s+\{([^{}]*)\}/.exec(source);
90
+ if (object === null) return void 0;
91
+ const items = object[1] ?? "";
92
+ if (/\bredis\b/.test(items)) return source;
93
+ const names = items.split(",").map((name) => name.trim()).filter((name) => name !== "");
94
+ names.push("redis");
95
+ names.sort();
96
+ const start = object.index + object[0].indexOf("{") + 1;
97
+ const rebuilt = ` ${names.join(", ")} `;
98
+ return addImport(source.slice(0, start) + rebuilt + source.slice(start + items.length), CONFIG_IMPORT);
99
+ }
100
+ /**
101
+ * Remove what {@link addConfigFile} added.
102
+ *
103
+ * @example
104
+ * removeConfigFile(source)
105
+ */
106
+ function removeConfigFile(source) {
107
+ return removeImport(source, CONFIG_IMPORT).replace(/export\s+default\s+\{([^{}]*)\}/, (whole, items) => {
108
+ const names = items.split(",").map((name) => name.trim()).filter((name) => name !== "" && name !== "redis");
109
+ return whole.replace(`{${items}}`, `{ ${names.join(", ")} }`);
110
+ });
111
+ }
112
+ /**
113
+ * Let `SESSION_DRIVER` be `redis` in `config/session.ts` source; `undefined` when the skeleton's
114
+ * line isn't there (already edited, or a different file).
115
+ *
116
+ * @example
117
+ * allowRedisSessions("driver: env.oneOf('SESSION_DRIVER', ['file'], 'file'),")
118
+ */
119
+ function allowRedisSessions(source) {
120
+ if (source.includes(SESSION_WITH_REDIS)) return source;
121
+ return source.includes(SESSION_FILE_ONLY) ? source.replace(SESSION_FILE_ONLY, SESSION_WITH_REDIS) : void 0;
122
+ }
123
+ /**
124
+ * The Redis installer.
125
+ *
126
+ * @example
127
+ * // package.json: "strutvane": { "installer": "./dist/installer.mjs" }
128
+ * export { installer } from '@strutvane/redis/installer'
129
+ */
130
+ const installer = {
131
+ name: "redis",
132
+ description: "Redis / Valkey: cache store, locks, sessions, rate limits and an experimental queue driver.",
133
+ async install(context) {
134
+ const { fs, log } = context;
135
+ if (!await fs.exists("config/redis.ts")) await fs.write("config/redis.ts", CONFIG_FILE);
136
+ await edit(context, "config/index.ts", addConfigFile, "add `redis` (import redis from './redis.ts') to the object");
137
+ await edit(context, "bootstrap/providers.ts", addProvider, `add ${PROVIDER} (${PROVIDER_IMPORT}) to the providers`);
138
+ if (await fs.exists("config/session.ts")) {
139
+ const source = await fs.read("config/session.ts");
140
+ const changed = allowRedisSessions(source);
141
+ if (changed === void 0) log.warn("config/session.ts: allow 'redis' in the SESSION_DRIVER choices to use Redis sessions.");
142
+ else if (changed !== source) await fs.write("config/session.ts", changed, { overwrite: true });
143
+ }
144
+ await context.env.add("Redis (@strutvane/redis)", [
145
+ {
146
+ key: "REDIS_URL",
147
+ value: "",
148
+ comment: "A full URL instead of the keys below (holds the password: .env only). rediss:// = TLS."
149
+ },
150
+ {
151
+ key: "REDIS_HOST",
152
+ value: "127.0.0.1"
153
+ },
154
+ {
155
+ key: "REDIS_PORT",
156
+ value: "6379"
157
+ },
158
+ {
159
+ key: "REDIS_USERNAME",
160
+ value: "",
161
+ comment: "An ACL user (Redis 6+); empty = the default user."
162
+ },
163
+ {
164
+ key: "REDIS_PASSWORD",
165
+ value: ""
166
+ },
167
+ {
168
+ key: "REDIS_DB",
169
+ value: "0"
170
+ },
171
+ {
172
+ key: "REDIS_TLS",
173
+ value: "",
174
+ comment: "true for TLS; empty follows REDIS_URL."
175
+ },
176
+ {
177
+ key: "REDIS_TLS_CA",
178
+ value: "",
179
+ comment: "A PEM CA file for a private CA (TLS is always verified)."
180
+ },
181
+ {
182
+ key: "REDIS_PREFIX",
183
+ value: "",
184
+ comment: "Key prefix so apps can share one server; empty = the app name."
185
+ }
186
+ ]);
187
+ log.info("Redis is set up. Choose it in .env: CACHE_STORE=redis and/or SESSION_DRIVER=redis.");
188
+ },
189
+ async uninstall(context) {
190
+ const { fs, log } = context;
191
+ for (const [path, undo] of [["bootstrap/providers.ts", removeProvider], ["config/index.ts", removeConfigFile]]) {
192
+ if (!await fs.exists(path)) continue;
193
+ const source = await fs.read(path);
194
+ const changed = undo(source);
195
+ if (changed !== source) await fs.write(path, changed, { overwrite: true });
196
+ }
197
+ if (await fs.exists("config/redis.ts")) {
198
+ if ((await fs.read("config/redis.ts")).replace(/\r\n/g, "\n") === "// Redis / Valkey connection settings (@strutvane/redis), read from .env.\n//\n// REDIS_URL and REDIS_PASSWORD are deliberately not here: the config tree is cached and easy to\n// dump, so the package reads secrets from the environment only when it connects. REDIS_URL, when\n// set, wins over host, port, user, password and database (rediss:// means TLS).\nimport { defineConfig } from '@strutvane/framework'\nimport type { RedisConfig } from '@strutvane/redis'\n\nexport default defineConfig(\n (env) =>\n ({\n /** The server. */\n host: env.string('REDIS_HOST', '127.0.0.1'),\n port: env.integer('REDIS_PORT', 6379),\n /** An ACL user (Redis 6+); empty means the default user. */\n username: env.string('REDIS_USERNAME', ''),\n /** The database number (0-15 on a default server). */\n database: env.integer('REDIS_DB', 0),\n /** TLS: true or false; empty follows REDIS_URL (rediss:// = TLS). Always verified. */\n tls: env.string('REDIS_TLS', ''),\n /** A PEM CA file for a private CA. */\n tls_ca: env.string('REDIS_TLS_CA', ''),\n /** Prefix for every key, so apps can share one server. Empty: the app name. */\n prefix: env.string('REDIS_PREFIX', ''),\n }) satisfies RedisConfig,\n)\n") await fs.remove("config/redis.ts");
199
+ else log.warn("config/redis.ts was changed, so it was kept. Delete it if you no longer need it.");
200
+ }
201
+ await context.env.remove(ENV_KEYS);
202
+ log.info("Redis was removed. Set CACHE_STORE and SESSION_DRIVER back to file if they were redis.");
203
+ }
204
+ };
205
+ async function edit(context, path, change, manual) {
206
+ if (!await context.fs.exists(path)) {
207
+ context.log.warn(`${path} not found: ${manual} by hand.`);
208
+ return;
209
+ }
210
+ const source = await context.fs.read(path);
211
+ const changed = change(source);
212
+ if (changed === void 0) context.log.warn(`${path} has an unexpected shape: ${manual} by hand.`);
213
+ else if (changed !== source) await context.fs.write(path, changed, { overwrite: true });
214
+ }
215
+ /** Add an import line after the last import (or at the top). Idempotent. */
216
+ function addImport(source, line) {
217
+ if (source.includes(line)) return source;
218
+ const last = [...source.matchAll(/^import[^\n]*\n/gm)].at(-1);
219
+ if (last === void 0) return `${line}\n${source}`;
220
+ const at = last.index + last[0].length;
221
+ return `${source.slice(0, at)}${line}\n${source.slice(at)}`;
222
+ }
223
+ function removeImport(source, line) {
224
+ return source.replace(`${line}\n`, "");
225
+ }
226
+ export { CONFIG_FILE, ENV_KEYS, addConfigFile, addProvider, allowRedisSessions, installer, removeConfigFile, removeProvider };
227
+
228
+ //# sourceMappingURL=installer.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installer.mjs","names":[],"sources":["../src/installer.ts"],"sourcesContent":["/**\n * The installer (`node strut install:redis`, today `node strut add redis`): sets Redis up in an\n * app completely and idempotently (running it twice changes nothing the second time).\n *\n * 1. `config/redis.ts`: the non-secret connection settings, read from `.env`;\n * 2. `config/index.ts`: registers that file (`config('redis.host')`);\n * 3. `.env` and `.env.example`: the `REDIS_*` keys (empty secrets; never overwrites a value);\n * 4. `bootstrap/providers.ts`: adds `RedisServiceProvider`;\n * 5. `config/session.ts`: allows `SESSION_DRIVER=redis` (the skeleton only lists `file`).\n *\n * It does **not** switch `CACHE_STORE` or `SESSION_DRIVER`: the app keeps working exactly as\n * before until you choose Redis in `.env` (a running app must never start depending on a server\n * nobody set up yet).\n *\n * The app files are edited as text, only when they have the skeleton's shape; any other shape\n * is left untouched and the step is printed for you to do by hand (never a half-edited file).\n * Uninstall reverses each edit and keeps a `config/redis.ts` you changed.\n *\n * @module\n */\nimport type { InstallContext, Installer } from '@strutvane/framework/contracts'\n\nconst PROVIDER = 'RedisServiceProvider'\nconst PROVIDER_IMPORT = `import { ${PROVIDER} } from '@strutvane/redis/provider'`\nconst CONFIG_IMPORT = \"import redis from './redis.ts'\"\nconst SESSION_FILE_ONLY = \"env.oneOf('SESSION_DRIVER', ['file'],\"\nconst SESSION_WITH_REDIS = \"env.oneOf('SESSION_DRIVER', ['file', 'redis'],\"\n\n/** The `config/redis.ts` the installer writes. */\nexport const CONFIG_FILE: string = `// Redis / Valkey connection settings (@strutvane/redis), read from .env.\n//\n// REDIS_URL and REDIS_PASSWORD are deliberately not here: the config tree is cached and easy to\n// dump, so the package reads secrets from the environment only when it connects. REDIS_URL, when\n// set, wins over host, port, user, password and database (rediss:// means TLS).\nimport { defineConfig } from '@strutvane/framework'\nimport type { RedisConfig } from '@strutvane/redis'\n\nexport default defineConfig(\n (env) =>\n ({\n /** The server. */\n host: env.string('REDIS_HOST', '127.0.0.1'),\n port: env.integer('REDIS_PORT', 6379),\n /** An ACL user (Redis 6+); empty means the default user. */\n username: env.string('REDIS_USERNAME', ''),\n /** The database number (0-15 on a default server). */\n database: env.integer('REDIS_DB', 0),\n /** TLS: true or false; empty follows REDIS_URL (rediss:// = TLS). Always verified. */\n tls: env.string('REDIS_TLS', ''),\n /** A PEM CA file for a private CA. */\n tls_ca: env.string('REDIS_TLS_CA', ''),\n /** Prefix for every key, so apps can share one server. Empty: the app name. */\n prefix: env.string('REDIS_PREFIX', ''),\n }) satisfies RedisConfig,\n)\n`\n\n/** The `.env` keys the installer adds (and uninstall removes). */\nexport const ENV_KEYS: readonly string[] = [\n 'REDIS_URL',\n 'REDIS_HOST',\n 'REDIS_PORT',\n 'REDIS_USERNAME',\n 'REDIS_PASSWORD',\n 'REDIS_DB',\n 'REDIS_TLS',\n 'REDIS_TLS_CA',\n 'REDIS_PREFIX',\n]\n\n/**\n * Add the provider to `bootstrap/providers.ts` source; `undefined` when the file doesn't have the\n * skeleton's shape (`const providers … = [ … ]`). Unchanged source when already present.\n *\n * @example\n * addProvider(\"import x from 'y'\\nconst providers: readonly AnyProvider[] = [AppServiceProvider]\\n\")\n */\nexport function addProvider(source: string): string | undefined {\n const array = /(const\\s+providers\\b[^=]*=\\s*\\[)([\\s\\S]*?)(\\])/.exec(source)\n if (array === null) return undefined\n if (new RegExp(`\\\\b${PROVIDER}\\\\b`).test(array[2] ?? '')) return source\n const items = array[2] ?? ''\n const multiline = items.includes('\\n')\n let replaced: string\n if (multiline) {\n const indent = /\\n([ \\t]+)\\S/.exec(items)?.[1] ?? ' '\n const trimmed = items.replace(/\\s*$/, '')\n const comma = trimmed === '' || trimmed.endsWith(',') ? '' : ','\n replaced = `${trimmed}${comma}\\n${indent}${PROVIDER},\\n`\n } else {\n const trimmed = items.trim().replace(/,$/, '')\n replaced = trimmed === '' ? PROVIDER : `${trimmed}, ${PROVIDER}`\n }\n const start = array.index + (array[1] ?? '').length\n const withItem = source.slice(0, start) + replaced + source.slice(start + items.length)\n return addImport(withItem, PROVIDER_IMPORT)\n}\n\n/**\n * Remove what {@link addProvider} added.\n *\n * @example\n * removeProvider(addProvider(source) ?? source) === source\n */\nexport function removeProvider(source: string): string {\n return removeImport(source, PROVIDER_IMPORT)\n .replace(new RegExp(`,\\\\n[ \\\\t]*${PROVIDER},?(?=\\\\n)`), '')\n .replace(new RegExp(`\\\\n[ \\\\t]*${PROVIDER},`), '')\n .replace(new RegExp(`,\\\\s*${PROVIDER}\\\\b`), '')\n .replace(new RegExp(`\\\\[\\\\s*${PROVIDER}\\\\s*\\\\]`), '[]')\n}\n\n/**\n * Register `config/redis.ts` in `config/index.ts` source; `undefined` when the file doesn't have the\n * skeleton's shape (`export default { … }`).\n *\n * @example\n * addConfigFile(\"import app from './app.ts'\\nexport default { app } satisfies ConfigFiles\\n\")\n */\nexport function addConfigFile(source: string): string | undefined {\n const object = /export\\s+default\\s+\\{([^{}]*)\\}/.exec(source)\n if (object === null) return undefined\n const items = object[1] ?? ''\n if (/\\bredis\\b/.test(items)) return source\n const names = items\n .split(',')\n .map((name) => name.trim())\n .filter((name) => name !== '')\n names.push('redis')\n names.sort()\n const start = object.index + object[0].indexOf('{') + 1\n const rebuilt = ` ${names.join(', ')} `\n return addImport(\n source.slice(0, start) + rebuilt + source.slice(start + items.length),\n CONFIG_IMPORT,\n )\n}\n\n/**\n * Remove what {@link addConfigFile} added.\n *\n * @example\n * removeConfigFile(source)\n */\nexport function removeConfigFile(source: string): string {\n const withoutImport = removeImport(source, CONFIG_IMPORT)\n return withoutImport.replace(/export\\s+default\\s+\\{([^{}]*)\\}/, (whole, items: string) => {\n const names = items\n .split(',')\n .map((name) => name.trim())\n .filter((name) => name !== '' && name !== 'redis')\n return whole.replace(`{${items}}`, `{ ${names.join(', ')} }`)\n })\n}\n\n/**\n * Let `SESSION_DRIVER` be `redis` in `config/session.ts` source; `undefined` when the skeleton's\n * line isn't there (already edited, or a different file).\n *\n * @example\n * allowRedisSessions(\"driver: env.oneOf('SESSION_DRIVER', ['file'], 'file'),\")\n */\nexport function allowRedisSessions(source: string): string | undefined {\n if (source.includes(SESSION_WITH_REDIS)) return source\n return source.includes(SESSION_FILE_ONLY)\n ? source.replace(SESSION_FILE_ONLY, SESSION_WITH_REDIS)\n : undefined\n}\n\n/**\n * The Redis installer.\n *\n * @example\n * // package.json: \"strutvane\": { \"installer\": \"./dist/installer.mjs\" }\n * export { installer } from '@strutvane/redis/installer'\n */\nexport const installer: Installer = {\n name: 'redis',\n description:\n 'Redis / Valkey: cache store, locks, sessions, rate limits and an experimental queue driver.',\n async install(context: InstallContext): Promise<void> {\n const { fs, log } = context\n if (!(await fs.exists('config/redis.ts'))) await fs.write('config/redis.ts', CONFIG_FILE)\n\n await edit(\n context,\n 'config/index.ts',\n addConfigFile,\n \"add `redis` (import redis from './redis.ts') to the object\",\n )\n await edit(\n context,\n 'bootstrap/providers.ts',\n addProvider,\n `add ${PROVIDER} (${PROVIDER_IMPORT}) to the providers`,\n )\n if (await fs.exists('config/session.ts')) {\n const source = await fs.read('config/session.ts')\n const changed = allowRedisSessions(source)\n if (changed === undefined)\n log.warn(\n \"config/session.ts: allow 'redis' in the SESSION_DRIVER choices to use Redis sessions.\",\n )\n else if (changed !== source) await fs.write('config/session.ts', changed, { overwrite: true })\n }\n\n await context.env.add('Redis (@strutvane/redis)', [\n {\n key: 'REDIS_URL',\n value: '',\n comment:\n 'A full URL instead of the keys below (holds the password: .env only). rediss:// = TLS.',\n },\n { key: 'REDIS_HOST', value: '127.0.0.1' },\n { key: 'REDIS_PORT', value: '6379' },\n {\n key: 'REDIS_USERNAME',\n value: '',\n comment: 'An ACL user (Redis 6+); empty = the default user.',\n },\n { key: 'REDIS_PASSWORD', value: '' },\n { key: 'REDIS_DB', value: '0' },\n { key: 'REDIS_TLS', value: '', comment: 'true for TLS; empty follows REDIS_URL.' },\n {\n key: 'REDIS_TLS_CA',\n value: '',\n comment: 'A PEM CA file for a private CA (TLS is always verified).',\n },\n {\n key: 'REDIS_PREFIX',\n value: '',\n comment: 'Key prefix so apps can share one server; empty = the app name.',\n },\n ])\n log.info('Redis is set up. Choose it in .env: CACHE_STORE=redis and/or SESSION_DRIVER=redis.')\n },\n\n async uninstall(context: InstallContext): Promise<void> {\n const { fs, log } = context\n for (const [path, undo] of [\n ['bootstrap/providers.ts', removeProvider],\n ['config/index.ts', removeConfigFile],\n ] as const) {\n if (!(await fs.exists(path))) continue\n const source = await fs.read(path)\n const changed = undo(source)\n if (changed !== source) await fs.write(path, changed, { overwrite: true })\n }\n if (await fs.exists('config/redis.ts')) {\n if ((await fs.read('config/redis.ts')).replace(/\\r\\n/g, '\\n') === CONFIG_FILE)\n await fs.remove('config/redis.ts')\n else\n log.warn('config/redis.ts was changed, so it was kept. Delete it if you no longer need it.')\n }\n await context.env.remove(ENV_KEYS)\n log.info(\n 'Redis was removed. Set CACHE_STORE and SESSION_DRIVER back to file if they were redis.',\n )\n },\n}\n\nasync function edit(\n context: InstallContext,\n path: string,\n change: (source: string) => string | undefined,\n manual: string,\n): Promise<void> {\n if (!(await context.fs.exists(path))) {\n context.log.warn(`${path} not found: ${manual} by hand.`)\n return\n }\n const source = await context.fs.read(path)\n const changed = change(source)\n if (changed === undefined) context.log.warn(`${path} has an unexpected shape: ${manual} by hand.`)\n else if (changed !== source) await context.fs.write(path, changed, { overwrite: true })\n}\n\n/** Add an import line after the last import (or at the top). Idempotent. */\nfunction addImport(source: string, line: string): string {\n if (source.includes(line)) return source\n const imports = [...source.matchAll(/^import[^\\n]*\\n/gm)]\n const last = imports.at(-1)\n if (last === undefined) return `${line}\\n${source}`\n const at = last.index + last[0].length\n return `${source.slice(0, at)}${line}\\n${source.slice(at)}`\n}\n\nfunction removeImport(source: string, line: string): string {\n return source.replace(`${line}\\n`, '')\n}\n"],"mappings":";AAsBA,MAAM,WAAW;AACjB,MAAM,kBAAkB,YAAY,SAAS;AAC7C,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B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,iBAAiB,GAAG;GACtC,KAAK,MAAM,GAAG,KAAK,iBAAiB,EAAA,CAAG,QAAQ,SAAS,IAAI,MAAA,kvCAC1D,MAAM,GAAG,OAAO,iBAAiB;QAEjC,IAAI,KAAK,kFAAkF;EAC/F;EACA,MAAM,QAAQ,IAAI,OAAO,QAAQ;EACjC,IAAI,KACF,wFACF;CACF;AACF;AAEA,eAAe,KACb,SACA,MACA,QACA,QACe;CACf,IAAI,CAAE,MAAM,QAAQ,GAAG,OAAO,IAAI,GAAI;EACpC,QAAQ,IAAI,KAAK,GAAG,KAAK,cAAc,OAAO,UAAU;EACxD;CACF;CACA,MAAM,SAAS,MAAM,QAAQ,GAAG,KAAK,IAAI;CACzC,MAAM,UAAU,OAAO,MAAM;CAC7B,IAAI,YAAY,KAAA,GAAW,QAAQ,IAAI,KAAK,GAAG,KAAK,4BAA4B,OAAO,UAAU;MAC5F,IAAI,YAAY,QAAQ,MAAM,QAAQ,GAAG,MAAM,MAAM,SAAS,EAAE,WAAW,KAAK,CAAC;AACxF;;AAGA,SAAS,UAAU,QAAgB,MAAsB;CACvD,IAAI,OAAO,SAAS,IAAI,GAAG,OAAO;CAElC,MAAM,OAAO,CADI,GAAG,OAAO,SAAS,mBAAmB,CACpC,CAAC,CAAC,GAAG,EAAE;CAC1B,IAAI,SAAS,KAAA,GAAW,OAAO,GAAG,KAAK,IAAI;CAC3C,MAAM,KAAK,KAAK,QAAQ,KAAK,EAAE,CAAC;CAChC,OAAO,GAAG,OAAO,MAAM,GAAG,EAAE,IAAI,KAAK,IAAI,OAAO,MAAM,EAAE;AAC1D;AAEA,SAAS,aAAa,QAAgB,MAAsB;CAC1D,OAAO,OAAO,QAAQ,GAAG,KAAK,KAAK,EAAE;AACvC"}
@@ -0,0 +1,169 @@
1
+ /**
2
+ * A Lua script with its SHA-1, for `EVALSHA` (the script body is sent only once per server).
3
+ *
4
+ * @example
5
+ * const GET_DEL = defineLua("local v = redis.call('GET', KEYS[1]) redis.call('DEL', KEYS[1]) return v")
6
+ */
7
+ interface LuaScript {
8
+ readonly source: string;
9
+ readonly sha1: string;
10
+ }
11
+ /**
12
+ * Define a Lua script.
13
+ *
14
+ * @example
15
+ * const script = defineLua("return redis.call('GET', KEYS[1])")
16
+ */
17
+ declare function defineLua(source: string): LuaScript;
18
+ /**
19
+ * What the stores need from a Redis connection.
20
+ *
21
+ * @example
22
+ * const value = await driver.command(['GET', 'blog:cache:posts'])
23
+ */
24
+ interface RedisDriver {
25
+ /** Run one command. Errors are the 503 `redis_unavailable` problem when the server is unreachable. */
26
+ command(args: readonly string[]): Promise<unknown>;
27
+ /** Run a Lua script atomically (`EVALSHA`, loading it with `EVAL` on `NOSCRIPT`). */
28
+ script(script: LuaScript, keys: readonly string[], args: readonly string[]): Promise<unknown>;
29
+ /** Round-trip time of a `PING`, in milliseconds. */
30
+ ping(): Promise<number>;
31
+ /** Close the connection gracefully (pending replies are awaited, bounded by a timeout). */
32
+ close(): Promise<void>;
33
+ }
34
+ /**
35
+ * Narrow a reply to a string or `null` (bulk string or nil). Numbers become strings.
36
+ *
37
+ * @example
38
+ * asNullableString(await driver.command(['GET', key]))
39
+ */
40
+ declare function asNullableString(reply: unknown): string | null;
41
+ /**
42
+ * Narrow a reply to a safe integer (integer reply, or a numeric string from Lua).
43
+ *
44
+ * @example
45
+ * asInteger(await driver.command(['PTTL', key]))
46
+ */
47
+ declare function asInteger(reply: unknown): number;
48
+ /**
49
+ * Narrow a reply to an array.
50
+ *
51
+ * @example
52
+ * const [cursor, keys] = asArray(await driver.command(['SCAN', '0']))
53
+ */
54
+ declare function asArray(reply: unknown): readonly unknown[];
55
+ /**
56
+ * Delete every key matching a `SCAN` pattern, in batches (`UNLINK`, so large values are freed in
57
+ * the background). Never `FLUSHDB`: other apps may share the database. Returns how many keys were
58
+ * removed.
59
+ *
60
+ * @example
61
+ * await deleteMatching(driver, space.pattern())
62
+ */
63
+ declare function deleteMatching(driver: RedisDriver, pattern: string, batch?: number): Promise<number>;
64
+ /**
65
+ * Key spaces: every key this package writes is `<app prefix><area>:<key>`, optionally with a
66
+ * tenant segment, `<app prefix><area>:t:<tenant>:<key>`.
67
+ *
68
+ * **Why:** one Redis is often shared by several apps (and several environments of one app), and a
69
+ * multi-tenant app must never let tenant A read, overwrite or flush tenant B's entries. Prefixes
70
+ * are how Redis users isolate data; this module makes them impossible to get wrong:
71
+ *
72
+ * - **Tenant ids are validated, not escaped.** A tenant id may only contain letters, digits, `_`
73
+ * and `-` (UUIDs, ULIDs, slugs and numbers fit). A tenant called `a:t:b` could otherwise reach
74
+ * into another tenant's namespace, so anything else is refused (fail closed).
75
+ * - **The tenant marker can't be forged from a key.** The tenant segment is `t:<id>:`, and a
76
+ * global (non-tenant) key may not start with `t:`, so a global key can never alias a tenant key.
77
+ * - **Flushing matches the prefix literally.** `SCAN MATCH` takes a glob, so `*`, `?`, `[`, `]`
78
+ * and `\` in a prefix are escaped; an app prefixed `a*` can't flush app `ab`'s keys.
79
+ * - **Keys are bounded.** Empty keys and keys over 1 KiB are refused: long keys are almost always
80
+ * a bug (a whole payload used as a key) and cost memory on every lookup.
81
+ *
82
+ * Keys travel as RESP bulk strings (length-prefixed), so a key containing CR/LF or spaces cannot
83
+ * inject a command; such keys are stored literally.
84
+ *
85
+ * @module
86
+ */
87
+ /** The longest key (in UTF-8 bytes) this package accepts from callers. */
88
+ declare const MAX_KEY_BYTES = 1024;
89
+ /**
90
+ * Check an app prefix (`REDIS_PREFIX`): letters, digits and `_ . : -`, at most 128 characters.
91
+ * Returns an error message, or `undefined` when it is fine.
92
+ *
93
+ * @example
94
+ * prefixProblem('blog:') // undefined
95
+ * prefixProblem('a b') // 'may only contain …'
96
+ */
97
+ declare function prefixProblem(prefix: string): string | undefined;
98
+ /**
99
+ * Whether a tenant id can be used in a key (letters, digits, `_` and `-`; 1 to 128 characters).
100
+ *
101
+ * @example
102
+ * isValidTenantId('acme-1') // true
103
+ * isValidTenantId('a:t:b') // false
104
+ */
105
+ declare function isValidTenantId(id: string): boolean;
106
+ /**
107
+ * Escape a literal string for a Redis glob pattern (`SCAN MATCH`, `KEYS`).
108
+ *
109
+ * @example
110
+ * globEscape('app*[1]') // 'app\\*\\[1\\]'
111
+ */
112
+ declare function globEscape(literal: string): string;
113
+ /**
114
+ * A namespace of keys. Immutable: {@link KeySpace.area} and {@link KeySpace.tenant} return new
115
+ * spaces.
116
+ *
117
+ * @example
118
+ * const cache = KeySpace.root('blog:').area('cache')
119
+ * cache.key('posts') // 'blog:cache:posts'
120
+ * cache.tenant('acme').key('posts') // 'blog:cache:t:acme:posts'
121
+ */
122
+ declare class KeySpace {
123
+ #private;
124
+ /** The full prefix every key of this space starts with. */
125
+ readonly prefix: string;
126
+ /** The tenant this space is scoped to, if any. */
127
+ readonly tenantId: string | undefined;
128
+ private constructor();
129
+ /**
130
+ * The app-wide root (no area yet). Throws a `TypeError` for an invalid prefix.
131
+ *
132
+ * @example
133
+ * KeySpace.root('blog:')
134
+ */
135
+ static root(appPrefix: string): KeySpace;
136
+ /**
137
+ * A sub-area (`cache`, `lock`, `session`, …): lowercase, starting with a letter.
138
+ *
139
+ * @example
140
+ * KeySpace.root('blog:').area('lock').key('reports') // 'blog:lock:reports'
141
+ */
142
+ area(name: string): KeySpace;
143
+ /**
144
+ * The same area scoped to one tenant. Throws a `TypeError` for an id that could escape its
145
+ * namespace (see the module notes); re-scoping a tenant space is refused too.
146
+ *
147
+ * @example
148
+ * space.tenant('acme').key('stats') // '<prefix>t:acme:stats'
149
+ */
150
+ tenant(id: string): KeySpace;
151
+ /**
152
+ * The full key for `key`. Throws a `TypeError` for an empty or over-long key, or (in the global
153
+ * space) a key that starts with the tenant marker `t:`.
154
+ *
155
+ * @example
156
+ * KeySpace.root('blog:').area('cache').key('posts:1') // 'blog:cache:posts:1'
157
+ */
158
+ key(key: string): string;
159
+ /**
160
+ * The `SCAN MATCH` pattern for every key in this space (and, for a global space, every tenant's
161
+ * keys under it too: flushing an area clears it for all tenants).
162
+ *
163
+ * @example
164
+ * KeySpace.root('a*:').area('cache').pattern() // 'a\\*:cache:*'
165
+ */
166
+ pattern(): string;
167
+ }
168
+ export { prefixProblem as a, asArray as c, defineLua as d, deleteMatching as f, isValidTenantId as i, asInteger as l, MAX_KEY_BYTES as n, LuaScript as o, globEscape as r, RedisDriver as s, KeySpace as t, asNullableString as u };
169
+ //# sourceMappingURL=keys-BeX5p2wm.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys-BeX5p2wm.d.mts","names":[],"sources":["../src/driver.ts","../src/keys.ts"],"mappings":";;;;;;UAqBiB;WACN;WACA;;;;;;;;iBASK,UAAU,iBAAiB;;;;;;;UAU1B;;EAEf,QAAQ,0BAA0B;;EAElC,OAAO,QAAQ,WAAW,yBAAyB,0BAA0B;;EAE7E,QAAQ;;EAER,SAAS;;;;;;;;iBASK,iBAAiB;;;;;;;iBAcjB,UAAU;;;;;;;iBAaV,QAAQ;;;;;;;;;iBAkBF,eACpB,QAAQ,aACR,iBACA,iBACC;;;;;;;;;;;;;;;;;;;;;;;;;cCnFU;;;;;;;;;iBAeG,cAAc;;;;;;;;iBAad,gBAAgB;;;;;;;iBAUhB,WAAW;;;;;;;;;;cAad;;;WAEF;;WAEA;UAGD;;;;;;;SAYD,KAAK,oBAAoB;;;;;;;EAYhC,KAAK,eAAe;;;;;;;;EAiBpB,OAAO,aAAa;;;;;;;;EAiBpB,IAAI;;;;;;;;EAmBJ"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `RedisServiceProvider`: wires Redis into a Strutvane app. The installer adds it to
3
+ * `bootstrap/providers.ts`; nothing else is needed.
4
+ *
5
+ * **What it binds** (in `register()`, so it wins over the framework's defaults):
6
+ * - `RedisConnectionToken`: one lazily opened connection for the whole app (closed on shutdown);
7
+ * - `RedisKeySpaceToken`, `RedisLocksToken`, `RedisRateLimiterToken`;
8
+ * - `CacheManagerToken`: the framework's stores plus `redis` (and any `driver: 'redis'` store in
9
+ * `config/cache.ts`). With `CACHE_STORE=redis`, `Cache` and the `throttle` middleware count in
10
+ * Redis, so limits hold across every server;
11
+ * - `SessionStoreToken`: the Redis session store, when `SESSION_DRIVER=redis`;
12
+ * - `IdempotencyStoreToken`: the Redis idempotency store, when the default cache store is a Redis
13
+ * store (the app has declared Redis its shared state; a memory store would let a retry that
14
+ * reaches another server run twice).
15
+ *
16
+ * **Fails closed at boot:** a bad `REDIS_*` value stops the app (`invalid_redis_config`). It does
17
+ * not connect at boot: commands that never touch Redis keep working while it is down, and a
18
+ * request that needs it gets a 503 `redis_unavailable` (see `connection.ts`).
19
+ *
20
+ * In production it warns (once, in the log) about a plain-text connection to a non-local host
21
+ * and about a server without a password.
22
+ *
23
+ * @module
24
+ */
25
+ import { Application, ServiceProvider } from "@strutvane/framework";
26
+ /**
27
+ * Options for {@link redisProvider} (tests and unusual setups; apps normally list the plain
28
+ * {@link RedisServiceProvider}).
29
+ *
30
+ * @example
31
+ * redisProvider({ env: { REDIS_URL: 'redis://127.0.0.1:6380' } })
32
+ */
33
+ export interface RedisProviderOptions {
34
+ /** The environment to read `REDIS_*` from. Default: `<app>/.env` under `process.env`. */
35
+ readonly env?: Readonly<Record<string, string | undefined>>;
36
+ /** Passed to the connection: how long shutdown waits for pending replies. Default 2000 ms. */
37
+ readonly closeTimeoutMs?: number;
38
+ }
39
+ /**
40
+ * The Redis service provider.
41
+ *
42
+ * @example
43
+ * // bootstrap/providers.ts
44
+ * import { RedisServiceProvider } from '@strutvane/redis/provider'
45
+ * const providers: readonly AnyProvider[] = [AppServiceProvider, RedisServiceProvider]
46
+ */
47
+ export declare class RedisServiceProvider extends ServiceProvider {
48
+ #private;
49
+ constructor(options?: RedisProviderOptions);
50
+ override register(app: Application): void;
51
+ override boot(app: Application): void;
52
+ override shutdown(): Promise<void>;
53
+ }
54
+ /**
55
+ * A provider class with fixed options (for `bootstrap/providers.ts`, which lists classes).
56
+ *
57
+ * @example
58
+ * const providers = [AppServiceProvider, redisProvider({ closeTimeoutMs: 5000 })]
59
+ */
60
+ export declare function redisProvider(options: RedisProviderOptions): new () => RedisServiceProvider;
61
+ /** The package name, as `node strut doctor` shows it. */
62
+ export declare const name: string;
63
+ //# sourceMappingURL=provider.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.mts","names":[],"sources":["../src/provider.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0DiB;;WAEN,MAAM,SAAS;;WAEf;;;;;;;;;;qBAWE,6BAA6B;;EAKxC,YAAY,UAAS;WAKZ,SAAS,KAAK;WA6Dd,KAAK,KAAK;WAmBJ,YAAY;;;;;;;;wBAWb,cAAc,SAAS,iCAAiC;;qBAS3D"}