@routr/common 2.25.3 → 2.26.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,2 @@
1
+ export { interpolateEnv } from "./interpolate_env";
2
+ export { resolveSecretRefs } from "./resolve_secret_refs";
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveSecretRefs = exports.interpolateEnv = void 0;
4
+ /*
5
+ * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
6
+ * http://github.com/fonoster/routr
7
+ *
8
+ * This file is part of Routr.
9
+ *
10
+ * Licensed under the MIT License (the "License");
11
+ * you may not use this file except in compliance with
12
+ * the License. You may obtain a copy of the License at
13
+ *
14
+ * https://opensource.org/licenses/MIT
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ var interpolate_env_1 = require("./interpolate_env");
23
+ Object.defineProperty(exports, "interpolateEnv", { enumerable: true, get: function () { return interpolate_env_1.interpolateEnv; } });
24
+ var resolve_secret_refs_1 = require("./resolve_secret_refs");
25
+ Object.defineProperty(exports, "resolveSecretRefs", { enumerable: true, get: function () { return resolve_secret_refs_1.resolveSecretRefs; } });
@@ -0,0 +1,19 @@
1
+ import { z } from "zod/v4";
2
+ export declare const interpolateEnvSchema: z.ZodObject<{
3
+ input: z.ZodUnknown;
4
+ env: z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>;
5
+ allowedPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
6
+ }, z.core.$strip>;
7
+ export type InterpolateEnvParams<T> = Omit<z.infer<typeof interpolateEnvSchema>, "input"> & {
8
+ input: T;
9
+ };
10
+ /**
11
+ * Returns a copy of a parsed config with `${VAR}` and `${VAR:-default}`
12
+ * references in its strings resolved from `env`. The input is not mutated.
13
+ * Errors name the key path where they happened.
14
+ *
15
+ * @param {InterpolateEnvParams} params - The config, env and allowed paths
16
+ * @return {T} A copy of the config with references resolved
17
+ * @throws {ValidationError} When the params are invalid
18
+ */
19
+ export declare function interpolateEnv<T>(params: InterpolateEnvParams<T>): T;
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.interpolateEnvSchema = void 0;
4
+ exports.interpolateEnv = interpolateEnv;
5
+ /*
6
+ * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
7
+ * http://github.com/fonoster/routr
8
+ *
9
+ * This file is part of Routr.
10
+ *
11
+ * Licensed under the MIT License (the "License");
12
+ * you may not use this file except in compliance with
13
+ * the License. You may obtain a copy of the License at
14
+ *
15
+ * https://opensource.org/licenses/MIT
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const v4_1 = require("zod/v4");
24
+ const validation_error_1 = require("../validation_error");
25
+ exports.interpolateEnvSchema = v4_1.z.object({
26
+ input: v4_1.z.unknown(),
27
+ env: v4_1.z.record(v4_1.z.string(), v4_1.z.string({ error: "env values must be strings" }).optional(), { error: "env must be an object of environment variables" }),
28
+ allowedPaths: v4_1.z
29
+ .array(v4_1.z.string(), { error: "allowedPaths must be an array of key paths" })
30
+ .optional()
31
+ });
32
+ /**
33
+ * Shell / docker-compose style variable interpolation for config files.
34
+ *
35
+ * Supported forms inside any string value:
36
+ * - `${VAR}` -> value of VAR; throws if VAR is unset or empty
37
+ * - `${VAR:-default}` -> value of VAR, or `default` when VAR is unset or empty
38
+ *
39
+ * Anything that is not a `${...}` reference is left untouched, so plain
40
+ * literals (`http://asterisk:8088`, `$5.00`, ...) pass through unchanged.
41
+ */
42
+ const VAR_PATTERN = /\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}/g;
43
+ const HAS_REFERENCE = /\$\{[^}]*\}/;
44
+ /**
45
+ * Replaces every `${...}` reference in one string.
46
+ *
47
+ * @param {string} value - The string to interpolate
48
+ * @param {Env} env - The environment to read variables from
49
+ * @return {string} The interpolated string
50
+ */
51
+ function interpolateString(value, env) {
52
+ return value.replace(VAR_PATTERN, (_match, name, hasDefault, fallback) => {
53
+ const current = env[name];
54
+ if (current !== undefined && current !== "") {
55
+ return current;
56
+ }
57
+ if (hasDefault !== undefined) {
58
+ return fallback;
59
+ }
60
+ throw new Error(`references undefined environment variable \${${name}} and no default was given`);
61
+ });
62
+ }
63
+ /**
64
+ * Tells whether `${...}` may appear at a key path. `db.*` matches `db` and
65
+ * everything below it; `*` alone matches every key.
66
+ *
67
+ * @param {string} path - The key path of the value
68
+ * @param {string[]} allowedPaths - The allowed key path patterns
69
+ * @return {boolean} true when the path is allowed
70
+ */
71
+ function isAllowed(path, allowedPaths) {
72
+ return allowedPaths.some((pattern) => {
73
+ if (pattern === "*")
74
+ return true;
75
+ if (!pattern.endsWith(".*"))
76
+ return path === pattern;
77
+ const prefix = pattern.slice(0, -2);
78
+ return path === prefix || path.startsWith(`${prefix}.`);
79
+ });
80
+ }
81
+ /**
82
+ * Interpolates a value and everything below it.
83
+ *
84
+ * @param {unknown} input - The value to walk
85
+ * @param {Env} env - The environment to read variables from
86
+ * @param {string[]} allowedPaths - The allowed key paths, if any
87
+ * @param {string} path - The key path of the value
88
+ * @return {unknown} A copy of the value with references resolved
89
+ */
90
+ function walk(input, env, allowedPaths, path) {
91
+ if (typeof input === "string") {
92
+ if (!HAS_REFERENCE.test(input)) {
93
+ return input;
94
+ }
95
+ const where = path || "(root)";
96
+ if (allowedPaths && !isAllowed(path, allowedPaths)) {
97
+ throw new Error(`${where}: \${...} is only allowed at ${allowedPaths.join(", ") || "no key path here"}`);
98
+ }
99
+ try {
100
+ return interpolateString(input, env);
101
+ }
102
+ catch (e) {
103
+ throw new Error(`${where}: ${e.message}`);
104
+ }
105
+ }
106
+ if (Array.isArray(input)) {
107
+ return input.map((item, index) => walk(item, env, allowedPaths, `${path}[${index}]`));
108
+ }
109
+ if (input !== null && typeof input === "object") {
110
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [
111
+ key,
112
+ walk(value, env, allowedPaths, path ? `${path}.${key}` : key)
113
+ ]));
114
+ }
115
+ return input;
116
+ }
117
+ /**
118
+ * Returns a copy of a parsed config with `${VAR}` and `${VAR:-default}`
119
+ * references in its strings resolved from `env`. The input is not mutated.
120
+ * Errors name the key path where they happened.
121
+ *
122
+ * @param {InterpolateEnvParams} params - The config, env and allowed paths
123
+ * @return {T} A copy of the config with references resolved
124
+ * @throws {ValidationError} When the params are invalid
125
+ */
126
+ function interpolateEnv(params) {
127
+ const parsed = exports.interpolateEnvSchema.safeParse(params);
128
+ if (!parsed.success) {
129
+ throw new validation_error_1.ValidationError(parsed.error);
130
+ }
131
+ const { env, allowedPaths } = parsed.data;
132
+ return walk(params.input, env, allowedPaths, "");
133
+ }
@@ -0,0 +1,22 @@
1
+ import { z } from "zod/v4";
2
+ type ReadFile = (path: string) => string;
3
+ export declare const resolveSecretRefsSchema: z.ZodObject<{
4
+ input: z.ZodUnknown;
5
+ env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>>;
6
+ secretsDir: z.ZodOptional<z.ZodString>;
7
+ readFile: z.ZodOptional<z.ZodCustom<ReadFile, ReadFile>>;
8
+ }, z.core.$strip>;
9
+ export type ResolveSecretRefsParams<T> = Omit<z.infer<typeof resolveSecretRefsSchema>, "input"> & {
10
+ input: T;
11
+ };
12
+ /**
13
+ * Returns a copy of a parsed config with every `secret://` value resolved.
14
+ * Errors name the key path and the reference
15
+ * (`db.url: secret://env/DB: environment variable DB is not set`).
16
+ *
17
+ * @param {ResolveSecretRefsParams} params - The config and resolve options
18
+ * @return {T} A copy of the config with references resolved
19
+ * @throws {ValidationError} When the params are invalid
20
+ */
21
+ export declare function resolveSecretRefs<T>(params: ResolveSecretRefsParams<T>): T;
22
+ export {};
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveSecretRefsSchema = void 0;
4
+ exports.resolveSecretRefs = resolveSecretRefs;
5
+ /*
6
+ * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
7
+ * http://github.com/fonoster/routr
8
+ *
9
+ * This file is part of Routr.
10
+ *
11
+ * Licensed under the MIT License (the "License");
12
+ * you may not use this file except in compliance with
13
+ * the License. You may obtain a copy of the License at
14
+ *
15
+ * https://opensource.org/licenses/MIT
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const fs_1 = require("fs");
24
+ const path_1 = require("path");
25
+ const v4_1 = require("zod/v4");
26
+ const validation_error_1 = require("../validation_error");
27
+ /**
28
+ * `secret://` references in config values. A string value that is exactly a
29
+ * reference is replaced by the secret it names, so YAML never holds the raw
30
+ * secret:
31
+ *
32
+ * secret://env/NAME the environment variable NAME
33
+ * secret://file/<absolute path> a file's contents
34
+ * secret://k8s/<secret>#<key> a Kubernetes Secret mounted as a volume,
35
+ * secret://k8s/<ns>/<secret>#<key> read from <secretsDir>/<secret>/<key>
36
+ * (default ROUTR_SECRETS_DIR or
37
+ * /var/run/routr/secrets). The namespace,
38
+ * when given, must be the pod's
39
+ * (POD_NAMESPACE) if that is known.
40
+ *
41
+ * File contents lose one trailing newline. Errors name the key path and the
42
+ * reference, never a value. Values that only contain `secret://` somewhere
43
+ * else are left alone.
44
+ */
45
+ const SECRET_PREFIX = "secret://";
46
+ const DEFAULT_SECRETS_DIR = "/var/run/routr/secrets";
47
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
48
+ const K8S_NAME = /^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$/;
49
+ const K8S_KEY = /^[-._a-zA-Z0-9]+$/;
50
+ exports.resolveSecretRefsSchema = v4_1.z.object({
51
+ input: v4_1.z.unknown(),
52
+ env: v4_1.z
53
+ .record(v4_1.z.string(), v4_1.z.string({ error: "env values must be strings" }).optional(), { error: "env must be an object of environment variables" })
54
+ .optional(),
55
+ secretsDir: v4_1.z
56
+ .string({ error: "secretsDir must be a directory path" })
57
+ .optional(),
58
+ readFile: v4_1.z
59
+ .custom((value) => typeof value === "function", {
60
+ error: "readFile must be a function"
61
+ })
62
+ .optional()
63
+ });
64
+ /**
65
+ * Tells whether a value is a `secret://` reference.
66
+ *
67
+ * @param {unknown} value - The value to check
68
+ * @return {boolean} true when the value is a reference
69
+ */
70
+ function isSecretRef(value) {
71
+ return typeof value === "string" && value.startsWith(SECRET_PREFIX);
72
+ }
73
+ /**
74
+ * Reads a secret file, dropping one trailing newline.
75
+ *
76
+ * @param {string} ref - The reference being resolved
77
+ * @param {string} path - The file to read
78
+ * @param {Options} options - The resolve options
79
+ * @return {string} The file's contents
80
+ */
81
+ function readSecretFile(ref, path, options) {
82
+ var _a;
83
+ const read = (_a = options.readFile) !== null && _a !== void 0 ? _a : ((p) => (0, fs_1.readFileSync)(p, { encoding: "utf8" }));
84
+ try {
85
+ return read(path).replace(/\r?\n$/, "");
86
+ }
87
+ catch (e) {
88
+ const code = e.code;
89
+ throw new Error(`${ref}: cannot read ${path}${code ? ` (${code})` : ""}`);
90
+ }
91
+ }
92
+ /**
93
+ * Resolves one `secret://` reference. Throws with a message that never
94
+ * contains the secret.
95
+ *
96
+ * @param {string} ref - The reference to resolve
97
+ * @param {Options} options - The resolve options
98
+ * @return {string} The secret
99
+ */
100
+ function resolveSecretRef(ref, options) {
101
+ var _a, _b;
102
+ const env = options.env;
103
+ const rest = ref.slice(SECRET_PREFIX.length);
104
+ const slash = rest.indexOf("/");
105
+ const kind = slash < 0 ? rest : rest.slice(0, slash);
106
+ const target = slash < 0 ? "" : rest.slice(slash + 1);
107
+ if (kind === "env") {
108
+ if (!NAME.test(target))
109
+ throw new Error(`invalid variable name in ${ref}`);
110
+ const value = env[target];
111
+ if (value === undefined || value === "")
112
+ throw new Error(`${ref}: environment variable ${target} is not set`);
113
+ return value;
114
+ }
115
+ if (kind === "file") {
116
+ if (!target)
117
+ throw new Error(`${ref}: missing file path`);
118
+ return readSecretFile(ref, (0, path_1.resolve)("/", target), options);
119
+ }
120
+ if (kind === "k8s") {
121
+ const hash = target.indexOf("#");
122
+ if (hash < 0)
123
+ throw new Error(`${ref}: missing #<key>`);
124
+ const parts = target.slice(0, hash).split("/");
125
+ const key = target.slice(hash + 1);
126
+ if (parts.length > 2 || !parts.every((p) => K8S_NAME.test(p)))
127
+ throw new Error(`${ref}: expected secret://k8s/[<namespace>/]<secret>#<key>`);
128
+ if (!K8S_KEY.test(key))
129
+ throw new Error(`${ref}: invalid key`);
130
+ const [namespace, name] = parts.length === 2 ? parts : [undefined, parts[0]];
131
+ const podNamespace = env.POD_NAMESPACE;
132
+ if (namespace && podNamespace && namespace !== podNamespace)
133
+ throw new Error(`${ref}: Secrets of namespace ${namespace} are not mounted here (${podNamespace})`);
134
+ const dir = (_b = (_a = options.secretsDir) !== null && _a !== void 0 ? _a : env.ROUTR_SECRETS_DIR) !== null && _b !== void 0 ? _b : DEFAULT_SECRETS_DIR;
135
+ const base = (0, path_1.isAbsolute)(dir) ? dir : (0, path_1.resolve)(dir);
136
+ return readSecretFile(ref, (0, path_1.join)(base, name, key), options);
137
+ }
138
+ throw new Error(`unsupported reference ${ref} (use secret://env/NAME, secret://file/<path> or secret://k8s/<secret>#<key>)`);
139
+ }
140
+ /**
141
+ * Resolves the references in a value and everything below it.
142
+ *
143
+ * @param {unknown} input - The value to walk
144
+ * @param {Options} options - The resolve options
145
+ * @param {string} path - The key path of the value
146
+ * @return {unknown} A copy of the value with references resolved
147
+ */
148
+ function walk(input, options, path) {
149
+ if (isSecretRef(input)) {
150
+ try {
151
+ return resolveSecretRef(input, options);
152
+ }
153
+ catch (e) {
154
+ throw new Error(`${path || "(root)"}: ${e.message}`);
155
+ }
156
+ }
157
+ if (Array.isArray(input)) {
158
+ return input.map((item, i) => walk(item, options, `${path}[${i}]`));
159
+ }
160
+ if (input !== null && typeof input === "object") {
161
+ return Object.fromEntries(Object.entries(input).map(([k, v]) => [
162
+ k,
163
+ walk(v, options, path ? `${path}.${k}` : k)
164
+ ]));
165
+ }
166
+ return input;
167
+ }
168
+ /**
169
+ * Returns a copy of a parsed config with every `secret://` value resolved.
170
+ * Errors name the key path and the reference
171
+ * (`db.url: secret://env/DB: environment variable DB is not set`).
172
+ *
173
+ * @param {ResolveSecretRefsParams} params - The config and resolve options
174
+ * @return {T} A copy of the config with references resolved
175
+ * @throws {ValidationError} When the params are invalid
176
+ */
177
+ function resolveSecretRefs(params) {
178
+ const parsed = exports.resolveSecretRefsSchema.safeParse(params);
179
+ if (!parsed.success) {
180
+ throw new validation_error_1.ValidationError(parsed.error);
181
+ }
182
+ const { env, secretsDir, readFile } = parsed.data;
183
+ return walk(params.input, { env: env !== null && env !== void 0 ? env : process.env, secretsDir, readFile }, "");
184
+ }
package/dist/errors.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { ValidationError } from "./validation_error";
1
2
  /**
2
3
  * Error thrown if the definition for a service is not found.
3
4
  */
package/dist/errors.js CHANGED
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.BadRequestError = exports.ResourceAlreadyExistsError = exports.ResourceNotFoundError = exports.UnimplementedError = exports.ClientConnectionError = exports.ServiceUnavailableError = exports.NoListeningPointError = exports.ServiceDefinitionNotFoundError = void 0;
36
+ exports.BadRequestError = exports.ResourceAlreadyExistsError = exports.ResourceNotFoundError = exports.UnimplementedError = exports.ClientConnectionError = exports.ServiceUnavailableError = exports.NoListeningPointError = exports.ServiceDefinitionNotFoundError = exports.ValidationError = void 0;
37
37
  /*
38
38
  * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
39
39
  * http://github.com/fonoster/routr
@@ -53,6 +53,8 @@ exports.BadRequestError = exports.ResourceAlreadyExistsError = exports.ResourceN
53
53
  * limitations under the License.
54
54
  */
55
55
  const grpc = __importStar(require("@grpc/grpc-js"));
56
+ var validation_error_1 = require("./validation_error");
57
+ Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.ValidationError; } });
56
58
  /**
57
59
  * Error thrown if the definition for a service is not found.
58
60
  */
package/dist/index.d.ts CHANGED
@@ -15,3 +15,4 @@ export * as CommonErrors from "./errors";
15
15
  export * as ConnectSchemas from "./connect/schemas";
16
16
  export * as Verifier from "./verifier";
17
17
  export * as Trace from "./trace";
18
+ export * as Config from "./config";
package/dist/index.js CHANGED
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.Trace = exports.Verifier = exports.ConnectSchemas = exports.CommonErrors = exports.CommonTypes = exports.CommonResponse = exports.CommonRequester = exports.CommonConnect = exports.Assertions = exports.Tracer = exports.IpUtils = exports.Helper = exports.Redis = exports.Auth = exports.statusMap = exports.GRPC_SERVING_STATUS = exports.LOCATION_OBJECT_PROTO = exports.PROCESSOR_OBJECT_PROTO = exports.Method = exports.Transport = exports.getObjectProto = exports.createService = void 0;
36
+ exports.Config = exports.Trace = exports.Verifier = exports.ConnectSchemas = exports.CommonErrors = exports.CommonTypes = exports.CommonResponse = exports.CommonRequester = exports.CommonConnect = exports.Assertions = exports.Tracer = exports.IpUtils = exports.Helper = exports.Redis = exports.Auth = exports.statusMap = exports.GRPC_SERVING_STATUS = exports.LOCATION_OBJECT_PROTO = exports.PROCESSOR_OBJECT_PROTO = exports.Method = exports.Transport = exports.getObjectProto = exports.createService = void 0;
37
37
  /*
38
38
  * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
39
39
  * http://github.com/fonoster/routr
@@ -76,3 +76,4 @@ exports.CommonErrors = __importStar(require("./errors"));
76
76
  exports.ConnectSchemas = __importStar(require("./connect/schemas"));
77
77
  exports.Verifier = __importStar(require("./verifier"));
78
78
  exports.Trace = __importStar(require("./trace"));
79
+ exports.Config = __importStar(require("./config"));
@@ -0,0 +1,35 @@
1
+ import type { z } from "zod/v4";
2
+ export interface FieldError {
3
+ field: string;
4
+ message: string;
5
+ code: string;
6
+ }
7
+ /**
8
+ * Custom error class that wraps Zod validation errors with structured details.
9
+ * Provides field-level errors suitable for API responses.
10
+ */
11
+ export declare class ValidationError extends Error {
12
+ readonly code = "VALIDATION_ERROR";
13
+ readonly fieldErrors: FieldError[];
14
+ readonly zodError: z.ZodError;
15
+ /**
16
+ * Constructs a new ValidationError.
17
+ *
18
+ * @param {z.ZodError} zodError - The error Zod returned
19
+ */
20
+ constructor(zodError: z.ZodError);
21
+ /**
22
+ * Extracts field-level errors from a ZodError for API responses.
23
+ *
24
+ * @param {z.ZodError} zodError - The error Zod returned
25
+ * @return {FieldError[]} One entry per failed field
26
+ */
27
+ private static extractFieldErrors;
28
+ /**
29
+ * Builds a single human-readable message from the field errors.
30
+ *
31
+ * @param {FieldError[]} fieldErrors - The failed fields
32
+ * @return {string} The message
33
+ */
34
+ private static formatMessage;
35
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ValidationError = void 0;
4
+ /**
5
+ * Custom error class that wraps Zod validation errors with structured details.
6
+ * Provides field-level errors suitable for API responses.
7
+ */
8
+ class ValidationError extends Error {
9
+ /**
10
+ * Constructs a new ValidationError.
11
+ *
12
+ * @param {z.ZodError} zodError - The error Zod returned
13
+ */
14
+ constructor(zodError) {
15
+ const fieldErrors = ValidationError.extractFieldErrors(zodError);
16
+ const message = ValidationError.formatMessage(fieldErrors);
17
+ super(message);
18
+ this.code = "VALIDATION_ERROR";
19
+ this.name = "ValidationError";
20
+ this.zodError = zodError;
21
+ this.fieldErrors = fieldErrors;
22
+ // Maintains proper stack trace for where error was thrown (V8 engines)
23
+ if (Error.captureStackTrace) {
24
+ Error.captureStackTrace(this, ValidationError);
25
+ }
26
+ }
27
+ /**
28
+ * Extracts field-level errors from a ZodError for API responses.
29
+ *
30
+ * @param {z.ZodError} zodError - The error Zod returned
31
+ * @return {FieldError[]} One entry per failed field
32
+ */
33
+ static extractFieldErrors(zodError) {
34
+ return zodError.issues.map((issue) => ({
35
+ field: issue.path.join("."),
36
+ message: issue.message,
37
+ code: issue.code
38
+ }));
39
+ }
40
+ /**
41
+ * Builds a single human-readable message from the field errors.
42
+ *
43
+ * @param {FieldError[]} fieldErrors - The failed fields
44
+ * @return {string} The message
45
+ */
46
+ static formatMessage(fieldErrors) {
47
+ if (fieldErrors.length === 0)
48
+ return "Validation failed";
49
+ return fieldErrors
50
+ .map((e) => (e.field ? `${e.field}: ${e.message}` : e.message))
51
+ .join("; ");
52
+ }
53
+ }
54
+ exports.ValidationError = ValidationError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@routr/common",
3
- "version": "2.25.3",
3
+ "version": "2.26.0",
4
4
  "description": "Common package",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/routr#readme",
@@ -38,7 +38,8 @@
38
38
  "js-yaml": "^4.1.1",
39
39
  "pb-util": "^1.0.3",
40
40
  "phone": "^3.1.68",
41
- "validator": "^13.15.26"
41
+ "validator": "^13.15.26",
42
+ "zod": "^3.25.76"
42
43
  },
43
44
  "directories": {
44
45
  "src": "src",
@@ -60,5 +61,5 @@
60
61
  "devDependencies": {
61
62
  "@types/js-yaml": "^4.0.5"
62
63
  },
63
- "gitHead": "3567b6d21385d735e3433199e37d03725476778d"
64
+ "gitHead": "c8278f328a3c763ff677001fbeb49690c0bc8cf3"
64
65
  }