@mandujs/core 0.30.0 → 0.32.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,379 @@
1
+ /**
2
+ * Phase 18.ν — Convenience presets for consumer-defined Guard rules.
3
+ *
4
+ * Wraps {@link defineGuardRule} with the three most common project-local
5
+ * patterns observed in Mandu consumer projects:
6
+ *
7
+ * 1. `forbidImport()` — reject imports whose specifier matches a regex
8
+ * (or equals a literal string). Replaces the 90% case of
9
+ * `eslint-plugin-local` rules.
10
+ * 2. `requireNamedExport()` — require specific named exports in files
11
+ * whose paths match a glob/regex. Useful for enforcing file-based
12
+ * routing conventions (`route.ts` must export a `handler`, etc.).
13
+ * 3. `requirePrefixForExports()` — require exported functions to start
14
+ * with a given prefix (e.g. HTTP verb names for API route files).
15
+ *
16
+ * All helpers return a {@link GuardRule} so they can be pushed directly
17
+ * into `mandu.config.ts` `guard.rules: [...]`.
18
+ *
19
+ * @module guard/rule-presets
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * // mandu.config.ts
24
+ * import {
25
+ * forbidImport,
26
+ * requireNamedExport,
27
+ * requirePrefixForExports,
28
+ * } from "@mandujs/core/guard/define-rule";
29
+ *
30
+ * export default {
31
+ * guard: {
32
+ * rules: [
33
+ * forbidImport({ from: "axios", matches: /./ }),
34
+ * requireNamedExport({
35
+ * patterns: [/app\/api\/.*\/route\.ts$/],
36
+ * names: ["GET", "POST"],
37
+ * requireAny: true,
38
+ * }),
39
+ * requirePrefixForExports({
40
+ * patterns: [/app\/api\/.*\/route\.ts$/],
41
+ * prefix: /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/,
42
+ * }),
43
+ * ],
44
+ * },
45
+ * };
46
+ * ```
47
+ */
48
+
49
+ import {
50
+ defineGuardRule,
51
+ type GuardRule,
52
+ type GuardRuleContext,
53
+ type GuardRuleSeverity,
54
+ type GuardViolation,
55
+ } from "./define-rule";
56
+
57
+ // ═══════════════════════════════════════════════════════════════════════════
58
+ // Shared helpers
59
+ // ═══════════════════════════════════════════════════════════════════════════
60
+
61
+ /** Normalize a string | RegExp matcher into a `.test(value)`-capable object. */
62
+ function toRegex(matcher: string | RegExp): RegExp {
63
+ if (matcher instanceof RegExp) return matcher;
64
+ // Escape regex metacharacters for literal-string matches.
65
+ const escaped = matcher.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
66
+ return new RegExp(escaped);
67
+ }
68
+
69
+ /**
70
+ * Returns true when `filePath` matches at least one of the supplied
71
+ * patterns. Strings are treated as literal substrings; RegExps use
72
+ * `.test()`. Forward slashes are used throughout (the Guard runner
73
+ * already normalizes Windows backslashes upstream).
74
+ */
75
+ function matchesAny(filePath: string, patterns: ReadonlyArray<string | RegExp>): boolean {
76
+ for (const pattern of patterns) {
77
+ if (typeof pattern === "string") {
78
+ if (filePath.includes(pattern)) return true;
79
+ } else if (pattern.test(filePath)) {
80
+ return true;
81
+ }
82
+ }
83
+ return false;
84
+ }
85
+
86
+ // ═══════════════════════════════════════════════════════════════════════════
87
+ // forbidImport
88
+ // ═══════════════════════════════════════════════════════════════════════════
89
+
90
+ /**
91
+ * Options for {@link forbidImport}.
92
+ */
93
+ export interface ForbidImportOptions {
94
+ /**
95
+ * Package name / path that triggers the rule. Matched against
96
+ * {@link ImportInfo.path} via `===` (literal) or `.test()` (regex).
97
+ * Pass a regex like `/^(node:fs|fs|fs\/promises)$/` for a set match.
98
+ */
99
+ from: string | RegExp;
100
+ /**
101
+ * Only the imports whose import path also matches this regex are
102
+ * flagged. Defaults to `/./` (all imports). Useful for cases where
103
+ * you want to forbid a package except when imported for types only.
104
+ */
105
+ matches?: RegExp;
106
+ /** Rule severity. Defaults to `"error"`. */
107
+ severity?: GuardRuleSeverity;
108
+ /** Override rule `id`. Defaults to `forbid-import:<normalized-from>`. */
109
+ id?: string;
110
+ /**
111
+ * Override rule `description`. Defaults to a human-friendly sentence
112
+ * describing the forbidden source.
113
+ */
114
+ description?: string;
115
+ /**
116
+ * Remediation hint surfaced alongside each violation. Defaults to a
117
+ * generic "Use a project-approved alternative" string.
118
+ */
119
+ hint?: string;
120
+ /** Optional docs URL surfaced with each violation. */
121
+ docsUrl?: string;
122
+ /**
123
+ * Restrict the rule to files whose path matches one of these
124
+ * patterns. When omitted, every scanned file is considered.
125
+ */
126
+ includePaths?: ReadonlyArray<string | RegExp>;
127
+ /**
128
+ * Exclude files whose path matches one of these patterns. Applied
129
+ * after `includePaths`.
130
+ */
131
+ excludePaths?: ReadonlyArray<string | RegExp>;
132
+ }
133
+
134
+ function normalizeIdFragment(value: string | RegExp): string {
135
+ const raw = value instanceof RegExp ? value.source : value;
136
+ return raw.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "import";
137
+ }
138
+
139
+ /**
140
+ * Create a rule that rejects every `import ... from "<from>"` whose
141
+ * specifier matches `matches` (default: all). Works for static,
142
+ * dynamic, and CommonJS `require()` imports.
143
+ */
144
+ export function forbidImport(options: ForbidImportOptions): GuardRule {
145
+ const fromMatcher = toRegex(options.from);
146
+ const extraMatcher = options.matches ?? /./;
147
+ const id = options.id ?? `forbid-import:${normalizeIdFragment(options.from)}`;
148
+ const description =
149
+ options.description ??
150
+ `Imports from \`${options.from instanceof RegExp ? options.from.source : options.from}\` are forbidden.`;
151
+ const hint = options.hint ?? "Use a project-approved alternative.";
152
+ const severity = options.severity ?? "error";
153
+
154
+ return defineGuardRule({
155
+ id,
156
+ severity,
157
+ description,
158
+ check(ctx: GuardRuleContext): GuardViolation[] {
159
+ if (options.includePaths && !matchesAny(ctx.sourceFile, options.includePaths)) {
160
+ return [];
161
+ }
162
+ if (options.excludePaths && matchesAny(ctx.sourceFile, options.excludePaths)) {
163
+ return [];
164
+ }
165
+
166
+ const violations: GuardViolation[] = [];
167
+ for (const imp of ctx.imports) {
168
+ if (!fromMatcher.test(imp.path)) continue;
169
+ if (!extraMatcher.test(imp.path)) continue;
170
+
171
+ violations.push({
172
+ file: ctx.sourceFile,
173
+ line: imp.line,
174
+ column: imp.column,
175
+ message: `Forbidden import: \`${imp.path}\` (${description})`,
176
+ hint,
177
+ docsUrl: options.docsUrl,
178
+ });
179
+ }
180
+ return violations;
181
+ },
182
+ });
183
+ }
184
+
185
+ // ═══════════════════════════════════════════════════════════════════════════
186
+ // requireNamedExport
187
+ // ═══════════════════════════════════════════════════════════════════════════
188
+
189
+ /**
190
+ * Options for {@link requireNamedExport}.
191
+ */
192
+ export interface RequireNamedExportOptions {
193
+ /**
194
+ * Only files whose path matches one of these patterns are checked.
195
+ * Strings are substring matches; regexes use `.test()`.
196
+ */
197
+ patterns: ReadonlyArray<string | RegExp>;
198
+ /**
199
+ * Export names that must be present. By default (`requireAny === false`)
200
+ * *all* names in this array must be exported; pass `requireAny: true`
201
+ * to require at least one.
202
+ */
203
+ names: readonly string[];
204
+ /**
205
+ * If `true`, a file passes when at least one of `names` is exported.
206
+ * Defaults to `false` (all names required).
207
+ */
208
+ requireAny?: boolean;
209
+ /** Rule severity. Defaults to `"error"`. */
210
+ severity?: GuardRuleSeverity;
211
+ /** Override rule `id`. Defaults to `require-named-export:<names.join("|")>`. */
212
+ id?: string;
213
+ /** Override rule `description`. */
214
+ description?: string;
215
+ /** Remediation hint. */
216
+ hint?: string;
217
+ /** Optional docs URL. */
218
+ docsUrl?: string;
219
+ }
220
+
221
+ /**
222
+ * Create a rule that requires specific named exports to exist in
223
+ * matching files. Useful for enforcing file-based routing conventions
224
+ * (e.g. `app/api/**\/route.ts` must export a `GET` or `POST` handler).
225
+ */
226
+ export function requireNamedExport(options: RequireNamedExportOptions): GuardRule {
227
+ if (!Array.isArray(options.names) || options.names.length === 0) {
228
+ throw new TypeError("requireNamedExport: `names` must be a non-empty array of strings.");
229
+ }
230
+ if (!Array.isArray(options.patterns) || options.patterns.length === 0) {
231
+ throw new TypeError("requireNamedExport: `patterns` must be a non-empty array.");
232
+ }
233
+
234
+ const id = options.id ?? `require-named-export:${options.names.join("|")}`;
235
+ const description =
236
+ options.description ??
237
+ (options.requireAny
238
+ ? `Files matching the pattern must export at least one of: ${options.names.join(", ")}.`
239
+ : `Files matching the pattern must export all of: ${options.names.join(", ")}.`);
240
+ const hint = options.hint ?? `Add the missing \`export\` declarations.`;
241
+ const severity = options.severity ?? "error";
242
+
243
+ return defineGuardRule({
244
+ id,
245
+ severity,
246
+ description,
247
+ check(ctx: GuardRuleContext): GuardViolation[] {
248
+ if (!matchesAny(ctx.sourceFile, options.patterns)) return [];
249
+
250
+ const exportedNames = new Set<string>();
251
+ for (const exp of ctx.exports) {
252
+ if (exp.type === "named" || exp.type === "default") {
253
+ if (exp.name) exportedNames.add(exp.name);
254
+ }
255
+ }
256
+
257
+ const missing = options.names.filter((n) => !exportedNames.has(n));
258
+
259
+ if (options.requireAny) {
260
+ if (missing.length === options.names.length) {
261
+ return [
262
+ {
263
+ file: ctx.sourceFile,
264
+ message: `Missing required export: expected at least one of [${options.names.join(", ")}], found none.`,
265
+ hint,
266
+ docsUrl: options.docsUrl,
267
+ },
268
+ ];
269
+ }
270
+ return [];
271
+ }
272
+
273
+ if (missing.length === 0) return [];
274
+ return [
275
+ {
276
+ file: ctx.sourceFile,
277
+ message: `Missing required exports: ${missing.join(", ")}.`,
278
+ hint,
279
+ docsUrl: options.docsUrl,
280
+ },
281
+ ];
282
+ },
283
+ });
284
+ }
285
+
286
+ // ═══════════════════════════════════════════════════════════════════════════
287
+ // requirePrefixForExports
288
+ // ═══════════════════════════════════════════════════════════════════════════
289
+
290
+ /**
291
+ * Options for {@link requirePrefixForExports}.
292
+ */
293
+ export interface RequirePrefixForExportsOptions {
294
+ /**
295
+ * Only files whose path matches one of these patterns are checked.
296
+ */
297
+ patterns: ReadonlyArray<string | RegExp>;
298
+ /**
299
+ * Prefix that every named export must match. String is treated as a
300
+ * literal prefix (`startsWith`); RegExp is `.test()`-ed against the
301
+ * full export name.
302
+ */
303
+ prefix: string | RegExp;
304
+ /**
305
+ * Export names to exempt from the check (e.g. `"default"`, helper
306
+ * types). Literal strings only — kept simple because this is the
307
+ * common case.
308
+ */
309
+ allowList?: readonly string[];
310
+ /**
311
+ * When `true`, only check exports whose `type` is `"named"` (skip
312
+ * `default`, `all`, and `type` re-exports). Defaults to `true`.
313
+ */
314
+ onlyNamed?: boolean;
315
+ /** Rule severity. Defaults to `"error"`. */
316
+ severity?: GuardRuleSeverity;
317
+ /** Override rule `id`. Defaults to `require-prefix:<normalized-prefix>`. */
318
+ id?: string;
319
+ /** Override rule `description`. */
320
+ description?: string;
321
+ /** Remediation hint. */
322
+ hint?: string;
323
+ /** Optional docs URL. */
324
+ docsUrl?: string;
325
+ }
326
+
327
+ /**
328
+ * Create a rule that requires every named export in matching files to
329
+ * match `prefix`. Classic use case: enforce that `app/api/**\/route.ts`
330
+ * files only export HTTP verb names (`GET`, `POST`, ...).
331
+ */
332
+ export function requirePrefixForExports(options: RequirePrefixForExportsOptions): GuardRule {
333
+ if (!Array.isArray(options.patterns) || options.patterns.length === 0) {
334
+ throw new TypeError("requirePrefixForExports: `patterns` must be a non-empty array.");
335
+ }
336
+
337
+ const prefixRegex =
338
+ options.prefix instanceof RegExp
339
+ ? options.prefix
340
+ : new RegExp(`^${options.prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
341
+ const id = options.id ?? `require-prefix:${normalizeIdFragment(options.prefix)}`;
342
+ const description =
343
+ options.description ??
344
+ `Named exports in matching files must start with \`${options.prefix instanceof RegExp ? options.prefix.source : options.prefix}\`.`;
345
+ const hint =
346
+ options.hint ??
347
+ `Rename the export to match the required prefix, or move the helper to a different module.`;
348
+ const severity = options.severity ?? "error";
349
+ const allowSet = new Set(options.allowList ?? []);
350
+ const onlyNamed = options.onlyNamed ?? true;
351
+
352
+ return defineGuardRule({
353
+ id,
354
+ severity,
355
+ description,
356
+ check(ctx: GuardRuleContext): GuardViolation[] {
357
+ if (!matchesAny(ctx.sourceFile, options.patterns)) return [];
358
+
359
+ const violations: GuardViolation[] = [];
360
+ for (const exp of ctx.exports) {
361
+ if (onlyNamed && exp.type !== "named") continue;
362
+ if (!exp.name) continue;
363
+ if (allowSet.has(exp.name)) continue;
364
+ if (prefixRegex.test(exp.name)) continue;
365
+
366
+ violations.push({
367
+ file: ctx.sourceFile,
368
+ line: exp.line,
369
+ message: `Export \`${exp.name}\` does not match the required prefix ${
370
+ options.prefix instanceof RegExp ? options.prefix.source : `"${options.prefix}"`
371
+ }.`,
372
+ hint,
373
+ docsUrl: options.docsUrl,
374
+ });
375
+ }
376
+ return violations;
377
+ },
378
+ });
379
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Phase 18.μ — `defineI18n()` contract.
3
+ *
4
+ * Thin factory with strict validation so misconfiguration surfaces
5
+ * at boot time (not at first request). Returns a frozen object
6
+ * branded as {@link I18nDefinition} to discourage callers from
7
+ * mutating the config after handing it to the runtime.
8
+ */
9
+
10
+ import type { I18nConfig, I18nDefinition, I18nStrategy, LocaleCode } from "./types";
11
+
12
+ export const VALID_STRATEGIES: readonly I18nStrategy[] = [
13
+ "path-prefix",
14
+ "domain",
15
+ "header",
16
+ "cookie",
17
+ ] as const;
18
+
19
+ /** Default cookie name when none is specified. Matches Next.js `NEXT_LOCALE`. */
20
+ export const DEFAULT_I18N_COOKIE = "mandu_locale";
21
+
22
+ /**
23
+ * Validate + brand an i18n configuration.
24
+ *
25
+ * @throws Error when:
26
+ * - `locales` is empty
27
+ * - `defaultLocale` is not in `locales`
28
+ * - `fallback` is supplied but not in `locales`
29
+ * - `strategy` is unknown
30
+ * - `strategy === "domain"` without a non-empty `domains` map
31
+ * - any `domains[...]` value is not in `locales`
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * export const i18n = defineI18n({
36
+ * locales: ['en', 'ko', 'ja'],
37
+ * defaultLocale: 'en',
38
+ * strategy: 'path-prefix',
39
+ * });
40
+ * ```
41
+ */
42
+ export function defineI18n(config: I18nConfig): I18nDefinition {
43
+ if (!config || typeof config !== "object") {
44
+ throw new Error("[mandu/i18n] defineI18n() requires a config object");
45
+ }
46
+
47
+ const { locales, defaultLocale, fallback, strategy, cookieName, domains } = config;
48
+
49
+ if (!Array.isArray(locales) || locales.length === 0) {
50
+ throw new Error("[mandu/i18n] `locales` must be a non-empty array");
51
+ }
52
+
53
+ for (const l of locales) {
54
+ if (typeof l !== "string" || l.length === 0) {
55
+ throw new Error(
56
+ "[mandu/i18n] every entry in `locales` must be a non-empty string"
57
+ );
58
+ }
59
+ }
60
+
61
+ const dedup = new Set(locales);
62
+ if (dedup.size !== locales.length) {
63
+ throw new Error("[mandu/i18n] `locales` must not contain duplicates");
64
+ }
65
+
66
+ if (typeof defaultLocale !== "string" || !dedup.has(defaultLocale)) {
67
+ throw new Error(
68
+ `[mandu/i18n] defaultLocale "${defaultLocale}" must be one of locales [${locales.join(", ")}]`
69
+ );
70
+ }
71
+
72
+ if (fallback !== undefined) {
73
+ if (typeof fallback !== "string" || !dedup.has(fallback)) {
74
+ throw new Error(
75
+ `[mandu/i18n] fallback "${fallback}" must be one of locales [${locales.join(", ")}]`
76
+ );
77
+ }
78
+ }
79
+
80
+ if (!VALID_STRATEGIES.includes(strategy)) {
81
+ throw new Error(
82
+ `[mandu/i18n] strategy "${strategy}" is invalid. Expected one of: ${VALID_STRATEGIES.join(", ")}`
83
+ );
84
+ }
85
+
86
+ if (strategy === "domain") {
87
+ if (!domains || typeof domains !== "object" || Object.keys(domains).length === 0) {
88
+ throw new Error(
89
+ "[mandu/i18n] strategy 'domain' requires a non-empty `domains` map"
90
+ );
91
+ }
92
+ for (const [host, locale] of Object.entries(domains)) {
93
+ if (typeof host !== "string" || host.length === 0) {
94
+ throw new Error("[mandu/i18n] domain keys must be non-empty strings");
95
+ }
96
+ if (!dedup.has(locale)) {
97
+ throw new Error(
98
+ `[mandu/i18n] domains["${host}"] = "${locale}" is not in locales`
99
+ );
100
+ }
101
+ }
102
+ }
103
+
104
+ const frozen: I18nDefinition = Object.freeze({
105
+ locales: Object.freeze([...locales]) as readonly LocaleCode[],
106
+ defaultLocale,
107
+ fallback,
108
+ strategy,
109
+ cookieName: cookieName ?? DEFAULT_I18N_COOKIE,
110
+ domains: domains ? Object.freeze({ ...domains }) : undefined,
111
+ __manduI18n: true,
112
+ });
113
+ return frozen;
114
+ }
115
+
116
+ /**
117
+ * Type guard for {@link I18nDefinition}. Use in adapter/runtime code
118
+ * that receives `unknown` from user config.
119
+ */
120
+ export function isI18nDefinition(value: unknown): value is I18nDefinition {
121
+ return (
122
+ typeof value === "object" &&
123
+ value !== null &&
124
+ (value as { __manduI18n?: unknown }).__manduI18n === true
125
+ );
126
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Phase 18.μ — i18n barrel.
3
+ *
4
+ * Public surface for first-class internationalization in Mandu.
5
+ *
6
+ * ```ts
7
+ * import { defineI18n, defineMessages, resolveLocale, createTranslator } from "@mandujs/core/i18n";
8
+ *
9
+ * export const i18n = defineI18n({
10
+ * locales: ["en", "ko"],
11
+ * defaultLocale: "en",
12
+ * strategy: "path-prefix",
13
+ * });
14
+ *
15
+ * export const messages = defineMessages({
16
+ * en: { welcome: "Welcome, {{name}}" },
17
+ * ko: { welcome: "환영합니다, {{name}}님" },
18
+ * } as const);
19
+ * ```
20
+ */
21
+
22
+ export type {
23
+ LocaleCode,
24
+ MessageBundle,
25
+ I18nStrategy,
26
+ I18nConfig,
27
+ I18nDefinition,
28
+ ResolvedLocale,
29
+ Translator,
30
+ } from "./types";
31
+
32
+ export {
33
+ defineI18n,
34
+ isI18nDefinition,
35
+ VALID_STRATEGIES,
36
+ DEFAULT_I18N_COOKIE,
37
+ } from "./define";
38
+
39
+ export {
40
+ resolveLocale,
41
+ stripLocalePrefix,
42
+ parseAcceptLanguage,
43
+ readLocaleCookie,
44
+ } from "./locale-resolver";
45
+
46
+ export {
47
+ defineMessages,
48
+ createTranslator,
49
+ interpolate,
50
+ isMessageRegistry,
51
+ type MessageRegistry,
52
+ } from "./message-registry";