@mandujs/core 0.31.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.
- package/package.json +4 -1
- package/src/config/mandu.ts +58 -1
- package/src/config/validate.ts +97 -1
- package/src/filling/context.ts +60 -0
- package/src/guard/check.ts +225 -1
- package/src/guard/define-rule.ts +243 -0
- package/src/guard/index.ts +26 -0
- package/src/guard/rule-presets.ts +379 -0
- package/src/i18n/define.ts +126 -0
- package/src/i18n/index.ts +52 -0
- package/src/i18n/locale-resolver.ts +214 -0
- package/src/i18n/message-registry.ts +173 -0
- package/src/i18n/types.ts +112 -0
- package/src/router/fs-scanner.ts +101 -0
- package/src/router/index.ts +7 -1
- package/src/runtime/server.ts +277 -9
- package/src/runtime/ssr.ts +9 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mandujs/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.0",
|
|
4
4
|
"description": "Mandu Framework Core - Spec, Generator, Guard, Runtime",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"./testing": "./src/testing/index.ts",
|
|
37
37
|
"./plugins": "./src/plugins/index.ts",
|
|
38
38
|
"./error": "./src/error/index.ts",
|
|
39
|
+
"./i18n": "./src/i18n/index.ts",
|
|
39
40
|
"./id": "./src/id/index.ts",
|
|
40
41
|
"./observability": "./src/observability/index.ts",
|
|
41
42
|
"./perf": "./src/perf/index.ts",
|
|
@@ -43,6 +44,8 @@
|
|
|
43
44
|
"./routes": "./src/routes/index.ts",
|
|
44
45
|
"./scheduler": "./src/scheduler/index.ts",
|
|
45
46
|
"./storage/s3": "./src/storage/s3/index.ts",
|
|
47
|
+
"./guard/define-rule": "./src/guard/define-rule.ts",
|
|
48
|
+
"./guard/rule-presets": "./src/guard/rule-presets.ts",
|
|
46
49
|
"./bundler/prerender": "./src/bundler/prerender.ts",
|
|
47
50
|
"./bundler/safe-build": "./src/bundler/safe-build.ts",
|
|
48
51
|
"./bundler/hmr-types": "./src/bundler/hmr-types.ts",
|
package/src/config/mandu.ts
CHANGED
|
@@ -5,6 +5,8 @@ import type { ManduPlugin, ManduHooks } from "../plugins/hooks";
|
|
|
5
5
|
import type { Middleware } from "../middleware/define";
|
|
6
6
|
import type { RpcDefinition, RpcProcedureRecord } from "../contract/rpc";
|
|
7
7
|
import type { CronDef } from "../scheduler";
|
|
8
|
+
import type { GuardRule as CustomGuardRule } from "../guard/define-rule";
|
|
9
|
+
import type { I18nStrategy, LocaleCode } from "../i18n/types";
|
|
8
10
|
|
|
9
11
|
export type GuardRuleSeverity = "error" | "warn" | "warning" | "off";
|
|
10
12
|
|
|
@@ -148,7 +150,20 @@ export interface ManduConfig {
|
|
|
148
150
|
srcDir?: string;
|
|
149
151
|
exclude?: string[];
|
|
150
152
|
realtime?: boolean;
|
|
151
|
-
|
|
153
|
+
/**
|
|
154
|
+
* Built-in rule severity overrides (map) OR consumer-defined
|
|
155
|
+
* custom rules (array). The Guard runner dispatches on shape:
|
|
156
|
+
*
|
|
157
|
+
* - `Record<string, GuardRuleSeverity>` → override severity of
|
|
158
|
+
* Mandu's built-in rules by id.
|
|
159
|
+
* - `GuardRule[]` (Phase 18.ν) → register consumer-defined rules
|
|
160
|
+
* alongside the built-in presets. See `@mandujs/core/guard/define-rule`.
|
|
161
|
+
*
|
|
162
|
+
* Passing both at once is not supported; pick one shape per config.
|
|
163
|
+
* Mixed input falls back to "custom rules only" and the built-in
|
|
164
|
+
* rule severity overrides become unreachable.
|
|
165
|
+
*/
|
|
166
|
+
rules?: Record<string, GuardRuleSeverity> | CustomGuardRule[];
|
|
152
167
|
contractRequired?: GuardRuleSeverity;
|
|
153
168
|
/**
|
|
154
169
|
* Issue #207 — hard-fail on direct `__generated__/` imports at the
|
|
@@ -422,6 +437,48 @@ export interface ManduConfig {
|
|
|
422
437
|
jobs?: CronDef[];
|
|
423
438
|
disabled?: boolean;
|
|
424
439
|
};
|
|
440
|
+
/**
|
|
441
|
+
* Phase 18.μ — first-class internationalization.
|
|
442
|
+
*
|
|
443
|
+
* Declaring this block opts the project into the framework's built-in
|
|
444
|
+
* locale resolution + route synthesis. The CLI (`mandu build` /
|
|
445
|
+
* `mandu dev`) materializes per-locale route variants when
|
|
446
|
+
* `strategy === "path-prefix"` so a single `app/docs/page.tsx`
|
|
447
|
+
* serves `/en/docs`, `/ko/docs`, etc. without file duplication.
|
|
448
|
+
*
|
|
449
|
+
* At runtime, the server dispatcher attaches `ctx.locale`
|
|
450
|
+
* ({@link ResolvedLocale}) + `ctx.t` (typed translator, when a
|
|
451
|
+
* message registry is wired) to every loader and stamps
|
|
452
|
+
* `Vary: Accept-Language` on responses so CDNs cache correctly.
|
|
453
|
+
*
|
|
454
|
+
* Coexists with the legacy `app/[lang]/...` manual pattern — users
|
|
455
|
+
* migrate only when ready. See `docs/architect/i18n.md`.
|
|
456
|
+
*
|
|
457
|
+
* @example
|
|
458
|
+
* ```ts
|
|
459
|
+
* export default {
|
|
460
|
+
* i18n: {
|
|
461
|
+
* locales: ['en', 'ko'],
|
|
462
|
+
* defaultLocale: 'en',
|
|
463
|
+
* strategy: 'path-prefix',
|
|
464
|
+
* },
|
|
465
|
+
* } satisfies ManduConfig;
|
|
466
|
+
* ```
|
|
467
|
+
*/
|
|
468
|
+
i18n?: {
|
|
469
|
+
/** Non-empty list of supported locale codes. */
|
|
470
|
+
locales: LocaleCode[];
|
|
471
|
+
/** Fallback when no signal matches. MUST be in `locales`. */
|
|
472
|
+
defaultLocale: LocaleCode;
|
|
473
|
+
/** Optional fallback chain between request locale and defaultLocale. */
|
|
474
|
+
fallback?: LocaleCode;
|
|
475
|
+
/** Locale detection strategy. See {@link I18nStrategy}. */
|
|
476
|
+
strategy: I18nStrategy;
|
|
477
|
+
/** Cookie name (default: "mandu_locale"). */
|
|
478
|
+
cookieName?: string;
|
|
479
|
+
/** Domain → locale map; required when strategy === "domain". */
|
|
480
|
+
domains?: Record<string, LocaleCode>;
|
|
481
|
+
};
|
|
425
482
|
}
|
|
426
483
|
|
|
427
484
|
export const CONFIG_FILES = [
|
package/src/config/validate.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type { ManduAdapter } from "../runtime/adapter";
|
|
|
7
7
|
import type { ManduPlugin, ManduHooks } from "../plugins/hooks";
|
|
8
8
|
import type { Middleware } from "../middleware/define";
|
|
9
9
|
import type { CronDef } from "../scheduler";
|
|
10
|
+
import { isGuardRuleLike, type GuardRule as CustomGuardRule } from "../guard/define-rule";
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* DNA-003: Strict mode schema helper
|
|
@@ -72,8 +73,30 @@ const ServerConfigSchema = z
|
|
|
72
73
|
})
|
|
73
74
|
.strict();
|
|
74
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Phase 18.ν — consumer-defined Guard rule (structural check).
|
|
78
|
+
*
|
|
79
|
+
* Rule objects carry closures (`check`) that Zod cannot introspect, so
|
|
80
|
+
* we validate structurally: must be a non-null object with a non-empty
|
|
81
|
+
* `id` string and a `check` function. Deeper validation (severity enum,
|
|
82
|
+
* description type) happens at `defineGuardRule()` time for the clearest
|
|
83
|
+
* DX error; the Guard runner catches any in-band violations.
|
|
84
|
+
*/
|
|
85
|
+
const CustomGuardRuleSchema = z.custom<CustomGuardRule>(
|
|
86
|
+
(v) => isGuardRuleLike(v),
|
|
87
|
+
{
|
|
88
|
+
message:
|
|
89
|
+
"Each custom guard rule must be an object with a non-empty `id` string and a `check` function. Use `defineGuardRule({...})` from `@mandujs/core/guard/define-rule` to construct.",
|
|
90
|
+
}
|
|
91
|
+
);
|
|
92
|
+
|
|
75
93
|
/**
|
|
76
94
|
* Guard 설정 스키마 (strict)
|
|
95
|
+
*
|
|
96
|
+
* `guard.rules` is a discriminated union of two shapes:
|
|
97
|
+
* - `Record<string, GuardRuleSeverity>` → built-in rule severity overrides.
|
|
98
|
+
* - `GuardRule[]` (Phase 18.ν) → consumer-defined custom rules.
|
|
99
|
+
* The runner dispatches on `Array.isArray()`.
|
|
77
100
|
*/
|
|
78
101
|
const GuardConfigSchema = z
|
|
79
102
|
.object({
|
|
@@ -81,7 +104,12 @@ const GuardConfigSchema = z
|
|
|
81
104
|
srcDir: z.string().default("src"),
|
|
82
105
|
exclude: z.array(z.string()).default([]),
|
|
83
106
|
realtime: z.boolean().default(true),
|
|
84
|
-
rules: z
|
|
107
|
+
rules: z
|
|
108
|
+
.union([
|
|
109
|
+
z.record(z.enum(["error", "warn", "warning", "off"])),
|
|
110
|
+
z.array(CustomGuardRuleSchema),
|
|
111
|
+
])
|
|
112
|
+
.optional(),
|
|
85
113
|
/**
|
|
86
114
|
* Issue #207 — bundler-level hard-fail on direct `__generated__/`
|
|
87
115
|
* imports. Default `true`. Set `false` to opt out of the
|
|
@@ -377,6 +405,69 @@ const SchedulerConfigSchema = z
|
|
|
377
405
|
})
|
|
378
406
|
.strict();
|
|
379
407
|
|
|
408
|
+
/**
|
|
409
|
+
* Phase 18.μ — i18n config schema (strict).
|
|
410
|
+
*
|
|
411
|
+
* Strictly validates shape + cross-field invariants that `defineI18n()`
|
|
412
|
+
* enforces at runtime (defaultLocale ∈ locales, fallback ∈ locales,
|
|
413
|
+
* domain map required when strategy === "domain"). Doing this at
|
|
414
|
+
* config load gives users a clean `mandu validate` error instead of
|
|
415
|
+
* a runtime boot failure.
|
|
416
|
+
*/
|
|
417
|
+
const I18nConfigSchema = z
|
|
418
|
+
.object({
|
|
419
|
+
locales: z.array(z.string().min(1)).min(1),
|
|
420
|
+
defaultLocale: z.string().min(1),
|
|
421
|
+
fallback: z.string().min(1).optional(),
|
|
422
|
+
strategy: z.enum(["path-prefix", "domain", "header", "cookie"]),
|
|
423
|
+
cookieName: z.string().min(1).optional(),
|
|
424
|
+
domains: z.record(z.string().min(1)).optional(),
|
|
425
|
+
})
|
|
426
|
+
.strict()
|
|
427
|
+
.superRefine((value, ctx) => {
|
|
428
|
+
const locales = new Set(value.locales);
|
|
429
|
+
if (locales.size !== value.locales.length) {
|
|
430
|
+
ctx.addIssue({
|
|
431
|
+
code: z.ZodIssueCode.custom,
|
|
432
|
+
path: ["locales"],
|
|
433
|
+
message: "locales must not contain duplicates",
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
if (!locales.has(value.defaultLocale)) {
|
|
437
|
+
ctx.addIssue({
|
|
438
|
+
code: z.ZodIssueCode.custom,
|
|
439
|
+
path: ["defaultLocale"],
|
|
440
|
+
message: `defaultLocale "${value.defaultLocale}" must be one of locales`,
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
if (value.fallback !== undefined && !locales.has(value.fallback)) {
|
|
444
|
+
ctx.addIssue({
|
|
445
|
+
code: z.ZodIssueCode.custom,
|
|
446
|
+
path: ["fallback"],
|
|
447
|
+
message: `fallback "${value.fallback}" must be one of locales`,
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
if (value.strategy === "domain") {
|
|
451
|
+
if (!value.domains || Object.keys(value.domains).length === 0) {
|
|
452
|
+
ctx.addIssue({
|
|
453
|
+
code: z.ZodIssueCode.custom,
|
|
454
|
+
path: ["domains"],
|
|
455
|
+
message: "strategy 'domain' requires a non-empty domains map",
|
|
456
|
+
});
|
|
457
|
+
} else {
|
|
458
|
+
for (const [host, locale] of Object.entries(value.domains)) {
|
|
459
|
+
if (!locales.has(locale)) {
|
|
460
|
+
ctx.addIssue({
|
|
461
|
+
code: z.ZodIssueCode.custom,
|
|
462
|
+
path: ["domains", host],
|
|
463
|
+
message: `domains["${host}"] = "${locale}" is not in locales`,
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
|
|
380
471
|
export const ManduConfigSchema = z
|
|
381
472
|
.object({
|
|
382
473
|
adapter: AdapterConfigSchema.optional(),
|
|
@@ -423,6 +514,11 @@ export const ManduConfigSchema = z
|
|
|
423
514
|
* passthrough).
|
|
424
515
|
*/
|
|
425
516
|
scheduler: SchedulerConfigSchema.optional(),
|
|
517
|
+
/**
|
|
518
|
+
* Phase 18.μ — first-class i18n config. See {@link I18nConfigSchema}.
|
|
519
|
+
* Optional; omission leaves i18n disabled with zero runtime overhead.
|
|
520
|
+
*/
|
|
521
|
+
i18n: I18nConfigSchema.optional(),
|
|
426
522
|
})
|
|
427
523
|
.strict();
|
|
428
524
|
|
package/src/filling/context.ts
CHANGED
|
@@ -20,6 +20,8 @@ import {
|
|
|
20
20
|
type SpanAttributes,
|
|
21
21
|
type SpanOptions,
|
|
22
22
|
} from "../observability/tracing";
|
|
23
|
+
// Phase 18.μ — i18n integration.
|
|
24
|
+
import type { ResolvedLocale, Translator } from "../i18n/types";
|
|
23
25
|
|
|
24
26
|
type ContractInput<
|
|
25
27
|
TContract extends ContractSchema,
|
|
@@ -332,6 +334,18 @@ export class ManduContext {
|
|
|
332
334
|
private _deps: FillingDeps;
|
|
333
335
|
private _cacheMeta: { tags: string[]; maxAge?: number; staleWhileRevalidate?: number } = { tags: [] };
|
|
334
336
|
private _cacheHelper: CacheHelper | null = null;
|
|
337
|
+
/**
|
|
338
|
+
* Phase 18.μ — resolved active locale. `undefined` when the server has
|
|
339
|
+
* no `ManduConfig.i18n` configured (zero-overhead — the runtime never
|
|
340
|
+
* attaches this field). Populated by `runtime/server.ts` μ dispatch.
|
|
341
|
+
*/
|
|
342
|
+
private _locale: ResolvedLocale | undefined = undefined;
|
|
343
|
+
/**
|
|
344
|
+
* Phase 18.μ — typed translator bound to the active locale. `undefined`
|
|
345
|
+
* until the runtime attaches one via `_setI18n()`. User code should
|
|
346
|
+
* null-check via `ctx.t?.(...)` OR require i18n via a type predicate.
|
|
347
|
+
*/
|
|
348
|
+
private _t: Translator | undefined = undefined;
|
|
335
349
|
|
|
336
350
|
constructor(
|
|
337
351
|
public readonly request: Request,
|
|
@@ -397,6 +411,52 @@ export class ManduContext {
|
|
|
397
411
|
};
|
|
398
412
|
}
|
|
399
413
|
|
|
414
|
+
/**
|
|
415
|
+
* Phase 18.μ — active resolved locale. `undefined` when i18n is
|
|
416
|
+
* disabled at server boot (`ManduConfig.i18n` omitted). Populated by
|
|
417
|
+
* the runtime dispatcher BEFORE loader + render so downstream code
|
|
418
|
+
* can branch on it without threading state manually.
|
|
419
|
+
*
|
|
420
|
+
* @example
|
|
421
|
+
* ```ts
|
|
422
|
+
* if (ctx.locale?.code === "ko") {
|
|
423
|
+
* return ctx.redirect("/ko/welcome");
|
|
424
|
+
* }
|
|
425
|
+
* ```
|
|
426
|
+
*/
|
|
427
|
+
get locale(): ResolvedLocale | undefined {
|
|
428
|
+
return this._locale;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Phase 18.μ — typed translator bound to `ctx.locale`. `undefined`
|
|
433
|
+
* when i18n is disabled OR no message registry was supplied to
|
|
434
|
+
* `startServer()`. Unlike `ctx.locale`, this is safe to call with an
|
|
435
|
+
* unknown key — misses fall through `fallbackLocale` → `defaultLocale`
|
|
436
|
+
* → raw key per {@link createTranslator}.
|
|
437
|
+
*
|
|
438
|
+
* @example
|
|
439
|
+
* ```ts
|
|
440
|
+
* return ctx.ok({ greeting: ctx.t?.("welcome", { name: "만두" }) });
|
|
441
|
+
* ```
|
|
442
|
+
*/
|
|
443
|
+
get t(): Translator | undefined {
|
|
444
|
+
return this._t;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Phase 18.μ — runtime-internal: attach resolved locale + translator.
|
|
449
|
+
* Exposed as a method (not a public setter) so user code can't mutate
|
|
450
|
+
* mid-request. Called exactly once by the server dispatcher before
|
|
451
|
+
* loader execution.
|
|
452
|
+
*
|
|
453
|
+
* @internal
|
|
454
|
+
*/
|
|
455
|
+
_setI18n(locale: ResolvedLocale, translator?: Translator): void {
|
|
456
|
+
this._locale = locale;
|
|
457
|
+
if (translator) this._t = translator;
|
|
458
|
+
}
|
|
459
|
+
|
|
400
460
|
/**
|
|
401
461
|
* DNA-002: 의존성 접근
|
|
402
462
|
*
|
package/src/guard/check.ts
CHANGED
|
@@ -4,6 +4,14 @@ import { validateSlotContent } from "../slot/validator";
|
|
|
4
4
|
import type { RoutesManifest } from "../spec/schema";
|
|
5
5
|
import type { GeneratedMap } from "../generator/generate";
|
|
6
6
|
import { loadManduConfig, type GuardRuleSeverity } from "../config";
|
|
7
|
+
import { extractImportsAST, extractExportsAST } from "./ast-analyzer";
|
|
8
|
+
import {
|
|
9
|
+
validateCustomRules,
|
|
10
|
+
type GuardRule as CustomGuardRule,
|
|
11
|
+
type GuardRuleContext as CustomGuardRuleContext,
|
|
12
|
+
type GuardViolation as CustomGuardViolation,
|
|
13
|
+
} from "./define-rule";
|
|
14
|
+
import type { ManduConfig } from "../config/mandu";
|
|
7
15
|
import path from "path";
|
|
8
16
|
import fs from "fs/promises";
|
|
9
17
|
|
|
@@ -445,7 +453,20 @@ export async function runGuardCheck(
|
|
|
445
453
|
violations.push(...slotContentViolations);
|
|
446
454
|
violations.push(...contractViolations);
|
|
447
455
|
|
|
448
|
-
|
|
456
|
+
// ============================================
|
|
457
|
+
// Phase 18.ν — Consumer-defined custom rules
|
|
458
|
+
// ============================================
|
|
459
|
+
const customRules = (config.guard?.rules as unknown);
|
|
460
|
+
if (Array.isArray(customRules) && customRules.length > 0) {
|
|
461
|
+
const customViolations = await runCustomRules(
|
|
462
|
+
customRules as CustomGuardRule[],
|
|
463
|
+
rootDir,
|
|
464
|
+
config
|
|
465
|
+
);
|
|
466
|
+
violations.push(...customViolations);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const resolvedViolations = applyRuleSeverity(violations, normalizeGuardConfigForSeverity(config.guard));
|
|
449
470
|
const passed = resolvedViolations.every((v) => v.severity !== "error");
|
|
450
471
|
|
|
451
472
|
return {
|
|
@@ -453,3 +474,206 @@ export async function runGuardCheck(
|
|
|
453
474
|
violations: resolvedViolations,
|
|
454
475
|
};
|
|
455
476
|
}
|
|
477
|
+
|
|
478
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
479
|
+
// Phase 18.ν — Consumer-defined Guard rules
|
|
480
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* The existing `config.guard.rules` field was a `Record<string,
|
|
484
|
+
* GuardRuleSeverity>` map for built-in rule overrides. Phase 18.ν
|
|
485
|
+
* allows consumers to also pass an array of `GuardRule` objects.
|
|
486
|
+
* `applyRuleSeverity` only understands the record shape, so we strip
|
|
487
|
+
* the array out before forwarding to it.
|
|
488
|
+
*/
|
|
489
|
+
function normalizeGuardConfigForSeverity(
|
|
490
|
+
guard: ManduConfig["guard"] | undefined
|
|
491
|
+
): { rules?: Record<string, GuardRuleSeverity>; contractRequired?: GuardRuleSeverity } {
|
|
492
|
+
if (!guard) return {};
|
|
493
|
+
const rulesField = guard.rules as unknown;
|
|
494
|
+
const rules =
|
|
495
|
+
rulesField && !Array.isArray(rulesField) && typeof rulesField === "object"
|
|
496
|
+
? (rulesField as Record<string, GuardRuleSeverity>)
|
|
497
|
+
: undefined;
|
|
498
|
+
return {
|
|
499
|
+
rules,
|
|
500
|
+
contractRequired: (guard as { contractRequired?: GuardRuleSeverity }).contractRequired,
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Parallel scan cap for `runCustomRules()`. Matches `safeBuild` default
|
|
506
|
+
* (`MANDU_BUN_BUILD_CONCURRENCY`) semantics — tunable via
|
|
507
|
+
* `MANDU_GUARD_CUSTOM_CONCURRENCY` positive integer env var.
|
|
508
|
+
*/
|
|
509
|
+
function customRuleConcurrency(): number {
|
|
510
|
+
const raw = process.env.MANDU_GUARD_CUSTOM_CONCURRENCY;
|
|
511
|
+
if (!raw) return 8;
|
|
512
|
+
const parsed = Number.parseInt(raw, 10);
|
|
513
|
+
if (!Number.isFinite(parsed) || parsed < 1) return 8;
|
|
514
|
+
return parsed;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Default source directories scanned for custom rules. */
|
|
518
|
+
const CUSTOM_RULE_SOURCE_DIRS = ["packages", "src", "app"];
|
|
519
|
+
|
|
520
|
+
async function collectCustomRuleSourceFiles(rootDir: string): Promise<string[]> {
|
|
521
|
+
const files = await Promise.all(
|
|
522
|
+
CUSTOM_RULE_SOURCE_DIRS.map((d) => scanTsFiles(path.join(rootDir, d)))
|
|
523
|
+
);
|
|
524
|
+
// Deduplicate paths (a file could in theory live under multiple roots
|
|
525
|
+
// if a consumer symlinks, which the walker doesn't follow but we
|
|
526
|
+
// guard anyway).
|
|
527
|
+
return Array.from(new Set(files.flat()));
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Convert a consumer-defined `GuardViolation` into the standard Guard
|
|
532
|
+
* report `GuardViolation` shape. Adds the `custom:<id>` ruleId prefix
|
|
533
|
+
* so the reporter can attribute each entry unambiguously.
|
|
534
|
+
*/
|
|
535
|
+
function toReportViolation(
|
|
536
|
+
rule: CustomGuardRule,
|
|
537
|
+
violation: CustomGuardViolation
|
|
538
|
+
): GuardViolation {
|
|
539
|
+
const severity: "error" | "warning" =
|
|
540
|
+
rule.severity === "error" ? "error" : "warning";
|
|
541
|
+
return {
|
|
542
|
+
ruleId: `custom:${rule.id}`,
|
|
543
|
+
file: violation.file,
|
|
544
|
+
message: violation.message,
|
|
545
|
+
suggestion: violation.hint ?? violation.docsUrl ?? "",
|
|
546
|
+
line: violation.line,
|
|
547
|
+
severity,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Execute every consumer-defined rule against every source file under
|
|
553
|
+
* `rootDir`. Rules are awaited per-file with a concurrency cap; a
|
|
554
|
+
* single rule throwing is caught and reported as a `custom:<id>`
|
|
555
|
+
* violation so the rest of the scan still completes.
|
|
556
|
+
*
|
|
557
|
+
* Exported for tests; not re-exported via `guard/index.ts` to keep the
|
|
558
|
+
* public surface small.
|
|
559
|
+
*/
|
|
560
|
+
export async function runCustomRules(
|
|
561
|
+
rules: readonly CustomGuardRule[],
|
|
562
|
+
rootDir: string,
|
|
563
|
+
config: ManduConfig
|
|
564
|
+
): Promise<GuardViolation[]> {
|
|
565
|
+
const { duplicates, malformed } = validateCustomRules(rules);
|
|
566
|
+
const results: GuardViolation[] = [];
|
|
567
|
+
|
|
568
|
+
if (malformed.length > 0) {
|
|
569
|
+
for (const idx of malformed) {
|
|
570
|
+
results.push({
|
|
571
|
+
ruleId: "custom:__invalid__",
|
|
572
|
+
file: "mandu.config",
|
|
573
|
+
message: `guard.rules[${idx}] is not a valid GuardRule (missing \`id\` or \`check()\`).`,
|
|
574
|
+
suggestion:
|
|
575
|
+
"Wrap the rule with defineGuardRule({...}) or import a preset from @mandujs/core/guard/define-rule.",
|
|
576
|
+
severity: "error",
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (duplicates.length > 0) {
|
|
582
|
+
for (const dup of duplicates) {
|
|
583
|
+
// Warning-level so duplicates don't gate CI but still surface in the
|
|
584
|
+
// report. Matches the "soft failure" convention used by config-guard.
|
|
585
|
+
results.push({
|
|
586
|
+
ruleId: `custom:${dup.id}`,
|
|
587
|
+
file: "mandu.config",
|
|
588
|
+
message: `Duplicate guard.rules id "${dup.id}" at indices [${dup.indices.join(", ")}] — only the first instance will be enforced.`,
|
|
589
|
+
suggestion: "Give each rule a unique \`id\`, or remove the duplicate.",
|
|
590
|
+
severity: "warning",
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// Deduplicate rules by id (keep first occurrence). Matches the
|
|
596
|
+
// warning emitted above.
|
|
597
|
+
const seen = new Set<string>();
|
|
598
|
+
const uniqueRules = rules.filter((r) => {
|
|
599
|
+
if (!r || typeof r !== "object" || typeof (r as CustomGuardRule).id !== "string") return false;
|
|
600
|
+
const id = (r as CustomGuardRule).id;
|
|
601
|
+
if (seen.has(id)) return false;
|
|
602
|
+
seen.add(id);
|
|
603
|
+
return true;
|
|
604
|
+
});
|
|
605
|
+
if (uniqueRules.length === 0) return results;
|
|
606
|
+
|
|
607
|
+
const files = await collectCustomRuleSourceFiles(rootDir);
|
|
608
|
+
if (files.length === 0) return results;
|
|
609
|
+
|
|
610
|
+
const cap = customRuleConcurrency();
|
|
611
|
+
let cursor = 0;
|
|
612
|
+
|
|
613
|
+
async function worker(): Promise<GuardViolation[]> {
|
|
614
|
+
const local: GuardViolation[] = [];
|
|
615
|
+
while (true) {
|
|
616
|
+
const index = cursor++;
|
|
617
|
+
if (index >= files.length) return local;
|
|
618
|
+
const filePath = files[index];
|
|
619
|
+
|
|
620
|
+
// Skip __generated__ and build output.
|
|
621
|
+
if (filePath.includes("__generated__") || filePath.includes(".mandu/")) continue;
|
|
622
|
+
|
|
623
|
+
let content: string;
|
|
624
|
+
try {
|
|
625
|
+
content = await Bun.file(filePath).text();
|
|
626
|
+
} catch {
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
let imports: ReturnType<typeof extractImportsAST>;
|
|
631
|
+
let exportsAst: ReturnType<typeof extractExportsAST>;
|
|
632
|
+
try {
|
|
633
|
+
imports = extractImportsAST(content);
|
|
634
|
+
exportsAst = extractExportsAST(content);
|
|
635
|
+
} catch {
|
|
636
|
+
// Tokenizer failure on an exotic file — skip rather than abort.
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const relFile = path.relative(rootDir, filePath) || filePath;
|
|
641
|
+
const ctx: CustomGuardRuleContext = {
|
|
642
|
+
sourceFile: relFile.replace(/\\/g, "/"),
|
|
643
|
+
content,
|
|
644
|
+
imports,
|
|
645
|
+
exports: exportsAst,
|
|
646
|
+
config,
|
|
647
|
+
projectRoot: rootDir,
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
for (const rule of uniqueRules) {
|
|
651
|
+
try {
|
|
652
|
+
const violations = await rule.check(ctx);
|
|
653
|
+
if (!Array.isArray(violations)) continue;
|
|
654
|
+
for (const v of violations) {
|
|
655
|
+
if (!v || typeof v !== "object") continue;
|
|
656
|
+
local.push(toReportViolation(rule, v));
|
|
657
|
+
}
|
|
658
|
+
} catch (err) {
|
|
659
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
660
|
+
local.push({
|
|
661
|
+
ruleId: `custom:${rule.id}`,
|
|
662
|
+
file: ctx.sourceFile,
|
|
663
|
+
message: `Rule "${rule.id}" threw: ${message}`,
|
|
664
|
+
suggestion: "Fix the rule's check() implementation or wrap it in a try/catch.",
|
|
665
|
+
severity: rule.severity === "error" ? "error" : "warning",
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
const workerCount = Math.min(cap, files.length);
|
|
673
|
+
const workers: Promise<GuardViolation[]>[] = [];
|
|
674
|
+
for (let i = 0; i < workerCount; i++) workers.push(worker());
|
|
675
|
+
const chunks = await Promise.all(workers);
|
|
676
|
+
for (const chunk of chunks) results.push(...chunk);
|
|
677
|
+
|
|
678
|
+
return results;
|
|
679
|
+
}
|