@polymorphism-tech/morph-spec 10.12.0 → 11.0.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/CLAUDE.md +27 -57
- package/README.md +51 -340
- package/bin/morph-spec.js +22 -373
- package/docs/CHEATSHEET.md +37 -166
- package/docs/QUICKSTART.md +14 -74
- package/framework/CLAUDE.md +15 -26
- package/framework/MORPH.md +34 -101
- package/framework/agents.json +8 -8
- package/framework/commands/morph-apply.md +5 -5
- package/framework/commands/morph-infra.md +1 -1
- package/framework/docs/CLI.md +74 -886
- package/framework/evals/review-checklist.md +14 -14
- package/framework/hooks/README.md +21 -189
- package/framework/hooks/claude-code/core/README.md +2 -5
- package/framework/hooks/claude-code/core/conventional-commit.js +2 -2
- package/framework/hooks/claude-code/core/denylist.json +3 -3
- package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
- package/framework/hooks/claude-code/core/masked-exit.js +6 -6
- package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
- package/framework/hooks/claude-code/core/protect-spec-files.js +17 -61
- package/framework/hooks/claude-code/core/stack-changed.js +35 -0
- package/framework/hooks/claude-code/core/validate-completion.js +31 -86
- package/framework/hooks/shared/{heavy-command.js → command-kind.js} +6 -79
- package/framework/hooks/shared/command-tokens.js +0 -139
- package/framework/hooks/shared/contract.js +14 -0
- package/framework/hooks/shared/feature-slug.js +21 -0
- package/framework/hooks/shared/frontend-locations.js +0 -1
- package/framework/hooks/shared/git-paths.js +0 -15
- package/framework/hooks/shared/graph-freshness.js +0 -19
- package/framework/hooks/shared/hook-response.js +0 -7
- package/framework/hooks/shared/morph-cli.js +2 -81
- package/framework/hooks/shared/owner-words.js +2 -120
- package/framework/hooks/shared/payload-utils.js +0 -39
- package/framework/hooks/shared/report-progress.js +7 -101
- package/framework/hooks/statusline.js +16 -60
- package/framework/mcp/registry.json +2 -2
- package/framework/rules/ai-agents-standards.md +1 -1
- package/framework/rules/asaas-standards.md +1 -1
- package/framework/rules/ef-standards.md +1 -1
- package/framework/rules/gsap-standards.md +1 -1
- package/framework/rules/hangfire-standards.md +1 -1
- package/framework/rules/implement-report.md +3 -3
- package/framework/rules/neon-auth-standards.md +1 -1
- package/framework/rules/nextjs-standards.md +1 -1
- package/framework/rules/plan-grammar.md +13 -11
- package/framework/rules/resend-standards.md +1 -1
- package/framework/rules/ui-design.md +4 -0
- package/framework/schemas/config.schema.json +95 -310
- package/framework/skills/README.md +12 -32
- package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
- package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
- package/framework/skills/core/morph-apply/SKILL.md +21 -46
- package/framework/skills/core/morph-plan/SKILL.md +28 -63
- package/framework/skills/core/morph-uiux/SKILL.md +23 -25
- package/framework/{templates/docs/ui-mockups.md → skills/core/morph-uiux/references/mockups.md} +4 -4
- package/framework/standards/STANDARDS.json +10 -11
- package/framework/standards/STANDARDS.meta.json +1 -1
- package/framework/standards/ai-agents/evals-with-cache.md +18 -32
- package/framework/standards/ai-agents/observability-patterns.md +2 -2
- package/framework/standards/architecture/code-comments.md +2 -5
- package/framework/standards/architecture/engineering-lens.md +1 -1
- package/framework/standards/backend/dotnet/testing.md +4 -4
- package/framework/standards/frontend/nextjs/lint.md +24 -10
- package/framework/standards/frontend/nextjs/testing.md +2 -2
- package/framework/standards/infrastructure/docker/local-compose-isolation.md +14 -30
- package/framework/templates/CLAUDE.md.core.guide.md +2 -2
- package/framework/templates/README.md +1 -1
- package/framework/templates/REGISTRY.json +3 -33
- package/framework/templates/docs/plan.md +3 -2
- package/framework/templates/dotnet/ai-kit/README.md +2 -4
- package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalCacheMissException.cs +1 -1
- package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalFixture.cs +1 -1
- package/package.json +1 -2
- package/src/commands/graph/explain.js +2 -1
- package/src/commands/graph/status.js +2 -1
- package/src/commands/mcp/mcp-setup.js +1 -2
- package/src/commands/project/doctor.js +5 -341
- package/src/commands/project/env.js +21 -52
- package/src/commands/project/init-contract.js +47 -0
- package/src/commands/project/init.js +36 -66
- package/src/commands/project/stack-scan.js +1 -1
- package/src/commands/project/update.js +15 -50
- package/src/commands/validation/check.js +128 -0
- package/src/commands/validation/plan-check.js +41 -64
- package/src/commands/validation/prove-red.js +1 -1
- package/src/core/paths/output-schema.js +0 -22
- package/src/core/templates/template-renderer.js +0 -14
- package/src/lib/ai/ai-project-scan.js +1 -6
- package/src/lib/check/attempts.js +38 -0
- package/src/lib/check/signals.js +145 -0
- package/src/lib/config/project-config.js +13 -0
- package/src/lib/contract/apply.js +62 -0
- package/src/lib/contract/defaults.js +96 -0
- package/src/lib/contract/merge.js +79 -0
- package/src/lib/contract/ports.js +43 -0
- package/src/lib/contract/scan.js +102 -0
- package/src/lib/detectors/claude-config-detector.js +7 -0
- package/src/lib/{procs → detectors}/mcp-config.js +1 -37
- package/src/lib/diff/diff-lines.js +64 -0
- package/src/lib/generators/architecture-scanner.js +1 -1
- package/src/lib/generators/scaffold-generator.js +0 -7
- package/src/lib/git/default-branch.js +0 -122
- package/src/lib/graph/diff-tree.js +2 -1
- package/src/lib/graph/god-nodes.js +2 -1
- package/src/lib/graph/graphify-runtime.js +0 -1
- package/src/lib/graph/graphifyignore.js +1 -1
- package/src/lib/graph/sanitize.js +2 -8
- package/src/lib/installers/memory-installer.js +15 -30
- package/src/lib/installers/stack-sync.js +16 -9
- package/src/lib/plan/checks.js +20 -64
- package/src/lib/plan/media.js +1 -1
- package/src/lib/plan/plan-parser.js +5 -5
- package/src/lib/review-reports.js +3 -77
- package/src/lib/scan/worktree-dirs.js +3 -0
- package/src/lib/specs/adr-index.js +2 -2
- package/src/lib/stack/dotnet-build-ignores.js +10 -2
- package/src/lib/stack/stack-scan.js +2 -2
- package/src/lib/stack-filter.js +3 -2
- package/src/lib/tests-audit/audit.js +1 -1
- package/src/scripts/setup-infra.js +6 -59
- package/src/utils/agents-installer.js +1 -34
- package/src/utils/atomic-json.js +27 -0
- package/src/utils/file-copier.js +4 -12
- package/src/utils/hooks-installer.js +9 -107
- package/claude-plugin.json +0 -14
- package/framework/commands/morph-archive.md +0 -46
- package/framework/commands/morph-hotfix.md +0 -17
- package/framework/commands/morph-preflight.md +0 -180
- package/framework/commands/morph-review.md +0 -15
- package/framework/commands/morph-status.md +0 -37
- package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +0 -80
- package/framework/hooks/claude-code/core/block-raw-worktree-add.js +0 -72
- package/framework/hooks/claude-code/core/enforce-phase-writes.js +0 -100
- package/framework/hooks/claude-code/core/gate-guard.js +0 -148
- package/framework/hooks/claude-code/core/heavy-gate.js +0 -78
- package/framework/hooks/claude-code/core/heavy-release.js +0 -23
- package/framework/hooks/claude-code/core/loop-detect.js +0 -79
- package/framework/hooks/claude-code/core/state-sync.js +0 -214
- package/framework/hooks/claude-code/core/telemetry-log.js +0 -259
- package/framework/hooks/claude-code/core/test-budget.js +0 -29
- package/framework/hooks/claude-code/core/worktree-context.js +0 -249
- package/framework/hooks/claude-code/core/worktree-create.js +0 -119
- package/framework/hooks/claude-code/core/worktree-env-inject.js +0 -68
- package/framework/hooks/claude-code/core/worktree-remove.js +0 -55
- package/framework/hooks/shared/build-check.js +0 -120
- package/framework/hooks/shared/claim-registry.js +0 -125
- package/framework/hooks/shared/e2e-check.js +0 -1022
- package/framework/hooks/shared/feature-locator.js +0 -82
- package/framework/hooks/shared/gate-event.js +0 -18
- package/framework/hooks/shared/gate-question.js +0 -20
- package/framework/hooks/shared/heavy-config.js +0 -113
- package/framework/hooks/shared/heavy-holders.js +0 -85
- package/framework/hooks/shared/heavy-slots.js +0 -280
- package/framework/hooks/shared/host-services.js +0 -440
- package/framework/hooks/shared/next-step.js +0 -181
- package/framework/hooks/shared/redact-secrets.js +0 -44
- package/framework/hooks/shared/reparse-scan.js +0 -40
- package/framework/hooks/shared/state-reader.js +0 -220
- package/framework/hooks/shared/state-writer.js +0 -112
- package/framework/hooks/shared/telemetry-logger.js +0 -101
- package/framework/hooks/shared/transcript-usage.js +0 -58
- package/framework/hooks/shared/worktree-root.js +0 -71
- package/framework/phases.json +0 -92
- package/framework/schemas/feature.schema.json +0 -242
- package/framework/skills/core/morph-apply/references/hotfix.md +0 -46
- package/framework/skills/core/morph-apply/references/machine.md +0 -30
- package/framework/skills/core/morph-apply/references/review.md +0 -77
- package/framework/skills/core/morph-plan/references/critique.md +0 -51
- package/framework/skills/core/morph-plan/references/interview.md +0 -37
- package/framework/templates/state.template.json +0 -17
- package/src/commands/dashboard/dashboard.js +0 -74
- package/src/commands/e2e/e2e.js +0 -400
- package/src/commands/observability/cost.js +0 -283
- package/src/commands/project/branch.js +0 -129
- package/src/commands/project/claim.js +0 -132
- package/src/commands/project/doctor-procs.js +0 -162
- package/src/commands/project/fleet.js +0 -66
- package/src/commands/project/heavy.js +0 -81
- package/src/commands/project/install-plugin-cmd.js +0 -27
- package/src/commands/project/status.js +0 -61
- package/src/commands/project/worktree.js +0 -1234
- package/src/commands/state/advance.js +0 -248
- package/src/commands/state/approve.js +0 -303
- package/src/commands/state/archive.js +0 -231
- package/src/commands/state/auto-approval.js +0 -67
- package/src/commands/state/create.js +0 -274
- package/src/commands/state/delete.js +0 -192
- package/src/commands/state/finish.js +0 -1247
- package/src/commands/state/gate-check.js +0 -244
- package/src/commands/state/gate-decision.js +0 -122
- package/src/commands/state/list.js +0 -244
- package/src/commands/state/next.js +0 -24
- package/src/commands/state/recap.js +0 -80
- package/src/commands/state/report-check.js +0 -244
- package/src/commands/state/retype.js +0 -110
- package/src/commands/validation/verify.js +0 -421
- package/src/core/state/feature-identity.js +0 -10
- package/src/core/state/gate-order.js +0 -23
- package/src/core/state/lifecycle-audit.js +0 -171
- package/src/core/state/state-manager.js +0 -523
- package/src/core/templates/template-seed.js +0 -21
- package/src/core/work-types.js +0 -44
- package/src/dashboard/app/App.jsx +0 -84
- package/src/dashboard/app/components/ActivityFeed.jsx +0 -166
- package/src/dashboard/app/components/CommandPalette.jsx +0 -144
- package/src/dashboard/app/components/DetailPanel.jsx +0 -43
- package/src/dashboard/app/components/EntityLink.jsx +0 -42
- package/src/dashboard/app/components/ErrorBoundary.jsx +0 -47
- package/src/dashboard/app/components/FlowGraph.jsx +0 -19
- package/src/dashboard/app/components/GatePauses.jsx +0 -116
- package/src/dashboard/app/components/KnowledgeMarkdown.jsx +0 -42
- package/src/dashboard/app/components/Markdown.jsx +0 -38
- package/src/dashboard/app/components/PhaseRail.jsx +0 -100
- package/src/dashboard/app/components/SearchFilter.jsx +0 -36
- package/src/dashboard/app/components/SessionMap.jsx +0 -77
- package/src/dashboard/app/components/Sidebar.jsx +0 -147
- package/src/dashboard/app/hooks/useMorphQuery.js +0 -44
- package/src/dashboard/app/hooks/usePref.js +0 -34
- package/src/dashboard/app/lib/format.js +0 -69
- package/src/dashboard/app/lib/phases.js +0 -75
- package/src/dashboard/app/lib/project.js +0 -38
- package/src/dashboard/app/main.jsx +0 -13
- package/src/dashboard/app/pages/Activity.jsx +0 -28
- package/src/dashboard/app/pages/AgentMap.jsx +0 -363
- package/src/dashboard/app/pages/FeatureDetail.jsx +0 -579
- package/src/dashboard/app/pages/Features.jsx +0 -393
- package/src/dashboard/app/pages/Guide.jsx +0 -145
- package/src/dashboard/app/pages/HookInspector.jsx +0 -444
- package/src/dashboard/app/pages/PhasePipeline.jsx +0 -273
- package/src/dashboard/app/pages/Portfolio.jsx +0 -190
- package/src/dashboard/app/pages/RulesMap.jsx +0 -285
- package/src/dashboard/app/pages/SkillsLibrary.jsx +0 -468
- package/src/dashboard/app/pages/Standards.jsx +0 -392
- package/src/dashboard/app/styles/index.css +0 -187
- package/src/dashboard/index.html +0 -14
- package/src/dashboard/package.json +0 -32
- package/src/dashboard/scanner/activity-scanner.js +0 -321
- package/src/dashboard/scanner/agents-scanner.js +0 -67
- package/src/dashboard/scanner/docs-scanner.js +0 -34
- package/src/dashboard/scanner/feature-status.js +0 -7
- package/src/dashboard/scanner/features-scanner.js +0 -397
- package/src/dashboard/scanner/hooks-scanner.js +0 -96
- package/src/dashboard/scanner/index.js +0 -21
- package/src/dashboard/scanner/phases-scanner.js +0 -14
- package/src/dashboard/scanner/portfolio.js +0 -129
- package/src/dashboard/scanner/project-api.js +0 -160
- package/src/dashboard/scanner/rules-scanner.js +0 -46
- package/src/dashboard/scanner/skills-scanner.js +0 -104
- package/src/dashboard/scanner/standards-scanner.js +0 -38
- package/src/dashboard/vite-plugin-morph-data.js +0 -120
- package/src/dashboard/vite.config.js +0 -26
- package/src/lib/ci/ci-verify.js +0 -30
- package/src/lib/ci/github-ci.js +0 -52
- package/src/lib/ci/pr-checks.js +0 -76
- package/src/lib/e2e/applicability.js +0 -39
- package/src/lib/e2e/compose-env.js +0 -80
- package/src/lib/e2e/stack-teardown.js +0 -96
- package/src/lib/git/branch-classifier.js +0 -104
- package/src/lib/git/evidence-staleness.js +0 -40
- package/src/lib/git/gh.js +0 -15
- package/src/lib/git/pending-prs.js +0 -58
- package/src/lib/git/pr-files.js +0 -31
- package/src/lib/git/pr-index.js +0 -39
- package/src/lib/git/tree-fingerprint.js +0 -58
- package/src/lib/git/tree-state.js +0 -125
- package/src/lib/heavy/cleanup.js +0 -72
- package/src/lib/heavy/gate.js +0 -168
- package/src/lib/heavy/live-stacks.js +0 -64
- package/src/lib/heavy/reclaim.js +0 -107
- package/src/lib/heavy/watchdog.js +0 -46
- package/src/lib/next-step.js +0 -12
- package/src/lib/plan/critique.js +0 -67
- package/src/lib/plan/plan-template.js +0 -18
- package/src/lib/procs/classify.js +0 -91
- package/src/lib/procs/list.js +0 -124
- package/src/lib/procs/prune.js +0 -47
- package/src/lib/procs/wslconfig.js +0 -70
- package/src/lib/projects/registry.js +0 -121
- package/src/lib/recap/piper.js +0 -36
- package/src/lib/recap/recap.js +0 -259
- package/src/lib/review-confirmation.js +0 -66
- package/src/lib/risk/diff-risk.js +0 -137
- package/src/lib/risk-detector.js +0 -638
- package/src/lib/specs/design-seed.js +0 -18
- package/src/lib/specs/screen-checklist.js +0 -315
- package/src/lib/stack/stack-profile.js +0 -69
- package/src/lib/tasks/eval-node.js +0 -293
- package/src/lib/tasks/linux-runner.js +0 -200
- package/src/lib/tasks/test-nodes.js +0 -414
- package/src/lib/tasks/test-runner.js +0 -569
- package/src/lib/telemetry/metrics.js +0 -384
- package/src/lib/telemetry/telemetry-reader.js +0 -276
- package/src/lib/telemetry/verify-event.js +0 -57
- package/src/lib/validators/code-budget/code-budget-validator.js +0 -170
- package/src/lib/validators/contracts/contract-compliance-validator.js +0 -219
- package/src/lib/validators/nextjs/next-component-validator.js +0 -142
- package/src/lib/validators/packages/package-validator.js +0 -310
- package/src/lib/validators/reuse/reuse-validator.js +0 -202
- package/src/lib/validators/reuse/symbol-scanner.js +0 -64
- package/src/lib/validators/validation-runner.js +0 -188
- package/src/lib/validators/verify-cache.js +0 -63
- package/src/lib/validators/verify-runner.js +0 -971
- package/src/lib/verify/affected.js +0 -143
- package/src/lib/verify/detached.js +0 -159
- package/src/lib/view/feature-html.js +0 -480
- package/src/lib/view/feature-page.client.js +0 -109
- package/src/lib/view/feature-page.css +0 -278
- package/src/lib/view/feature-view.js +0 -113
- package/src/lib/view/flow-layers.js +0 -79
- package/src/lib/view/flow-svg.js +0 -63
- package/src/lib/view/tokens.css +0 -18
- package/src/lib/work-type-detector.js +0 -81
- package/src/lib/worktree/dirs.js +0 -3
- package/src/lib/worktree/docker-audit.js +0 -175
- package/src/lib/worktree/env-allocator.js +0 -177
- package/src/lib/worktree/feature-truth.js +0 -145
- package/src/lib/worktree/finish-backup.js +0 -529
- package/src/lib/worktree/fleet-scanner.js +0 -223
- package/src/lib/worktree/ignored-triage.js +0 -136
- package/src/lib/worktree/vscode-settings.js +0 -112
- package/src/lib/worktree/worktree-audit.js +0 -323
- package/src/lib/worktree/worktree-include.js +0 -44
- package/src/scripts/install-plugin.js +0 -114
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
import { existsSync } from 'fs';
|
|
2
|
-
import { join } from 'path';
|
|
3
|
-
import { appendTelemetryEvent, readTelemetryEvents } from '../../../framework/hooks/shared/telemetry-logger.js';
|
|
4
|
-
|
|
5
|
-
const NODE_NAMES = ['build', 'tests', 'validators', 'e2e'];
|
|
6
|
-
|
|
7
|
-
export function buildVerifyEvent(result, { sha, tree, persisted, reason, fingerprint = null, source = 'local' }) {
|
|
8
|
-
const nodes = {};
|
|
9
|
-
for (const name of NODE_NAMES) {
|
|
10
|
-
const node = result.nodes?.[name];
|
|
11
|
-
if (!node) continue;
|
|
12
|
-
nodes[name] = { status: node.status, durationMs: Number.isFinite(node.durationMs) ? node.durationMs : null };
|
|
13
|
-
}
|
|
14
|
-
if (nodes.tests && Array.isArray(result.nodes.tests.runs)) {
|
|
15
|
-
nodes.tests.runs = result.nodes.tests.runs.map(({ id, status, durationMs }) => ({
|
|
16
|
-
id, status: status ?? null, durationMs: Number.isFinite(durationMs) ? durationMs : null,
|
|
17
|
-
}));
|
|
18
|
-
}
|
|
19
|
-
if (nodes.validators) {
|
|
20
|
-
nodes.validators.ran = [...(result.nodes.validators.ran || [])];
|
|
21
|
-
nodes.validators.skipped = (result.nodes.validators.skipped || [])
|
|
22
|
-
.map(({ validator, reason: why, unavailable }) => ({ validator, reason: why, unavailable: unavailable === true }));
|
|
23
|
-
}
|
|
24
|
-
return {
|
|
25
|
-
event: 'Verify',
|
|
26
|
-
feature: result.feature,
|
|
27
|
-
status: result.status,
|
|
28
|
-
sha,
|
|
29
|
-
fingerprint,
|
|
30
|
-
tree,
|
|
31
|
-
persisted,
|
|
32
|
-
reason: persisted ? null : (reason ?? null),
|
|
33
|
-
source,
|
|
34
|
-
reused: result.reused ?? [],
|
|
35
|
-
flaky: result.flaky ?? [],
|
|
36
|
-
nodes,
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** A partial run (`--filter`, `--skip-*`, `--no-persist`) is not the proof a complete one replaces. */
|
|
41
|
-
export function findRepeatedVerify(projectPath, { feature, fingerprint }) {
|
|
42
|
-
if (!fingerprint) return null;
|
|
43
|
-
const events = readTelemetryEvents(projectPath);
|
|
44
|
-
for (let i = events.length - 1; i >= 0; i--) {
|
|
45
|
-
const e = events[i];
|
|
46
|
-
if (e.event !== 'Verify' || e.feature !== feature) continue;
|
|
47
|
-
if (e.persisted === false) continue;
|
|
48
|
-
return e.fingerprint === fingerprint ? { ts: e.ts, status: e.status, sha: e.sha ?? null } : null;
|
|
49
|
-
}
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// Appends only where a morph project exists: this command must never be the one that creates `.morph/`.
|
|
54
|
-
export function recordVerifyEvent(projectPath, event) {
|
|
55
|
-
if (!existsSync(join(projectPath, '.morph'))) return;
|
|
56
|
-
appendTelemetryEvent(event, projectPath);
|
|
57
|
-
}
|
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
// Sempre `warning`: é medida de volume, e o excesso pode estar justificado no plano.
|
|
2
|
-
|
|
3
|
-
import { readFileSync } from 'fs';
|
|
4
|
-
import { join } from 'path';
|
|
5
|
-
|
|
6
|
-
import { addedLinesAgainst, detectDefaultBranch } from '../../git/default-branch.js';
|
|
7
|
-
import { resolveBaseRef } from '../../git/branch-classifier.js';
|
|
8
|
-
import { isTestFile } from '../reuse/symbol-scanner.js';
|
|
9
|
-
import { readPlanChecks } from '../../plan/checks.js';
|
|
10
|
-
import { isGenerated, isProjectSource } from '../../../../framework/hooks/shared/source-files.js';
|
|
11
|
-
import { citesProcess, commentLines } from '../../../../framework/hooks/shared/comment-scanner.js';
|
|
12
|
-
|
|
13
|
-
export const MAX_TEST_RATIO = 1;
|
|
14
|
-
|
|
15
|
-
/** Abaixo disto a razão não é julgada: a regressão de um bug de 2 linhas cabe aqui. */
|
|
16
|
-
export const MIN_TEST_LINES = 40;
|
|
17
|
-
|
|
18
|
-
/** Linhas de teste que cada cenário com `prova: teste` (sempre com `risco:`) pode pedir além da razão. */
|
|
19
|
-
export const REQUIRED_TEST_ALLOWANCE = 40;
|
|
20
|
-
|
|
21
|
-
export const MAX_COMMENT_RATIO = 0.1;
|
|
22
|
-
|
|
23
|
-
/** Abaixo disto a densidade não é julgada: um comentário legítimo num arquivo pequeno já passaria da razão. */
|
|
24
|
-
export const MIN_CODE_LINES = 40;
|
|
25
|
-
|
|
26
|
-
const MAX_CITED = 4;
|
|
27
|
-
|
|
28
|
-
const decimal = (n) => n.toFixed(1).replace('.', ',');
|
|
29
|
-
|
|
30
|
-
/** `added` são as linhas adicionadas de cada arquivo; `null` é o arquivo inteiro (novo). */
|
|
31
|
-
export function measureCodeBudget(files) {
|
|
32
|
-
const measured = { commentLines: 0, processLines: [], testLines: 0, productionLines: 0, commentsByFile: {} };
|
|
33
|
-
|
|
34
|
-
for (const { path, content, added } of files) {
|
|
35
|
-
if (!isProjectSource(path) || isGenerated(path)) continue;
|
|
36
|
-
const addedSet = added ? new Set(added) : null;
|
|
37
|
-
const isAdded = (n) => addedSet === null || addedSet.has(n);
|
|
38
|
-
|
|
39
|
-
const nonBlank = String(content).split('\n')
|
|
40
|
-
.filter((row, i) => isAdded(i + 1) && row.trim()).length;
|
|
41
|
-
if (isTestFile(path)) measured.testLines += nonBlank;
|
|
42
|
-
else measured.productionLines += nonBlank;
|
|
43
|
-
|
|
44
|
-
for (const [line, text] of commentLines(content, path)) {
|
|
45
|
-
if (!isAdded(line)) continue;
|
|
46
|
-
measured.commentLines++;
|
|
47
|
-
measured.commentsByFile[path] = (measured.commentsByFile[path] ?? 0) + 1;
|
|
48
|
-
if (citesProcess(text)) measured.processLines.push({ file: path, line, text });
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
return measured;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export function budgetIssues(measured, { requiredTests = 0 } = {}) {
|
|
56
|
-
const issues = [];
|
|
57
|
-
const { commentLines: comments, processLines, testLines, productionLines, commentsByFile = {} } = measured;
|
|
58
|
-
|
|
59
|
-
if (processLines.length > 0) {
|
|
60
|
-
const shown = processLines.slice(0, MAX_CITED).map((p) => `${p.file}:${p.line}`);
|
|
61
|
-
const more = processLines.length - shown.length;
|
|
62
|
-
issues.push({
|
|
63
|
-
level: 'warning',
|
|
64
|
-
message:
|
|
65
|
-
`${processLines.length} de ${comments} linhas de comentário adicionadas citam processo ` +
|
|
66
|
-
`(UC, ADR, FR, C{n}, F{n}, Gate, plan.md, checks.json, mockup): ${shown.join(', ')}${more > 0 ? ` (+${more})` : ''}`,
|
|
67
|
-
file: processLines[0].file,
|
|
68
|
-
line: processLines[0].line,
|
|
69
|
-
solution:
|
|
70
|
-
'A história vai na mensagem de commit e no plan.md; no código fica só o porquê que ' +
|
|
71
|
-
'ele não mostra (standard architecture-code-comments).',
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const allowance = REQUIRED_TEST_ALLOWANCE * requiredTests;
|
|
76
|
-
if (testLines > MIN_TEST_LINES && testLines > MAX_TEST_RATIO * productionLines + allowance) {
|
|
77
|
-
const ratio = productionLines > 0 ? ` (${decimal(testLines / productionLines)}×)` : '';
|
|
78
|
-
const required = requiredTests > 0 ? `, já descontadas ${allowance} de ${requiredTests} cenário(s) com prova: teste` : '';
|
|
79
|
-
issues.push({
|
|
80
|
-
level: 'warning',
|
|
81
|
-
message:
|
|
82
|
-
`linhas de teste adicionadas passam de ${decimal(MAX_TEST_RATIO)}× as de produção: ` +
|
|
83
|
-
`${testLines} de teste para ${productionLines} de produção${ratio}${required}`,
|
|
84
|
-
solution:
|
|
85
|
-
'Orçamento por task: um teste por pós-condição + um de regressão por bug, cenários do mesmo ' +
|
|
86
|
-
'comportamento numa tabela, nenhum teste que só fixa texto. Excesso justificado fica escrito na task.',
|
|
87
|
-
});
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
const codeLines = testLines + productionLines - comments;
|
|
91
|
-
if (codeLines >= MIN_CODE_LINES && comments > MAX_COMMENT_RATIO * codeLines) {
|
|
92
|
-
const ranked = Object.entries(commentsByFile).sort(([, a], [, b]) => b - a);
|
|
93
|
-
const shown = ranked.slice(0, MAX_CITED).map(([file, n]) => `${file} (${n})`);
|
|
94
|
-
const more = ranked.length - shown.length;
|
|
95
|
-
issues.push({
|
|
96
|
-
level: 'warning',
|
|
97
|
-
message:
|
|
98
|
-
`${comments} linhas de comentário para ${codeLines} de código adicionadas ` +
|
|
99
|
-
`(${decimal((comments / codeLines) * 10)} a cada 10, o teto é ${decimal(MAX_COMMENT_RATIO * 10)}): ` +
|
|
100
|
-
`${shown.join(', ')}${more > 0 ? ` (+${more})` : ''}`,
|
|
101
|
-
file: ranked[0]?.[0],
|
|
102
|
-
solution:
|
|
103
|
-
'O padrão é nenhum comentário: renomeie, extraia função ou constante, expresse no tipo ou ' +
|
|
104
|
-
'escreva um teste. Fica só o porquê que o código não mostra, sem doc-comment que repete a ' +
|
|
105
|
-
'assinatura (standard architecture-code-comments).',
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
return issues;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function requiredTestCount(projectPath, featureName) {
|
|
113
|
-
if (!featureName) return 0;
|
|
114
|
-
const checks = readPlanChecks(projectPath, featureName).checks?.checks ?? [];
|
|
115
|
-
return checks.filter((c) => c.proof === 'teste').length;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
export async function validateCodeBudget(projectPath, featureName = null, options = {}) {
|
|
119
|
-
const result = { errors: 0, warnings: 0, issues: [] };
|
|
120
|
-
|
|
121
|
-
try {
|
|
122
|
-
const added = options.addedLines
|
|
123
|
-
?? addedLinesAgainst(resolveBaseRef(detectDefaultBranch(projectPath), projectPath), projectPath);
|
|
124
|
-
if (!added) {
|
|
125
|
-
result._skipReason = 'sem base git para medir o que a feature adicionou';
|
|
126
|
-
result._skipUnavailable = true;
|
|
127
|
-
return result;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
const files = [];
|
|
131
|
-
// Todo path do diff existe no disco; um que não se lê é medida faltando, e isso se diz.
|
|
132
|
-
const unreadable = [];
|
|
133
|
-
for (const [path, lines] of added) {
|
|
134
|
-
if (!isProjectSource(path)) continue;
|
|
135
|
-
try {
|
|
136
|
-
files.push({ path, content: readFileSync(join(projectPath, path), 'utf8'), added: lines });
|
|
137
|
-
} catch {
|
|
138
|
-
unreadable.push(path);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
const named = unreadable.slice(0, MAX_CITED).join(', ') +
|
|
142
|
-
(unreadable.length > MAX_CITED ? ` (+${unreadable.length - MAX_CITED})` : '');
|
|
143
|
-
|
|
144
|
-
const measured = measureCodeBudget(files);
|
|
145
|
-
if (measured.testLines + measured.productionLines === 0) {
|
|
146
|
-
result._skipReason = unreadable.length > 0
|
|
147
|
-
? `nenhum arquivo adicionado pôde ser lido (${named})`
|
|
148
|
-
: 'nenhuma linha de código adicionada nesta árvore';
|
|
149
|
-
if (unreadable.length > 0) result._skipUnavailable = true;
|
|
150
|
-
return result;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
result.issues = budgetIssues(measured, { requiredTests: requiredTestCount(projectPath, featureName) });
|
|
154
|
-
if (unreadable.length > 0) {
|
|
155
|
-
result.issues.push({
|
|
156
|
-
level: 'warning',
|
|
157
|
-
message: `${unreadable.length} arquivo(s) adicionado(s) não puderam ser lidos, a medida é parcial: ${named}`,
|
|
158
|
-
solution: 'Confira se o verify roda na raiz do projeto e se os arquivos têm permissão de leitura.',
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
result.warnings = result.issues.length;
|
|
162
|
-
} catch (err) {
|
|
163
|
-
result.issues = [];
|
|
164
|
-
result.warnings = 0;
|
|
165
|
-
result._skipReason = `medição indisponível: ${err.message}`;
|
|
166
|
-
result._skipUnavailable = true;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
return result;
|
|
170
|
-
}
|
|
@@ -1,219 +0,0 @@
|
|
|
1
|
-
import { readFileSync, existsSync } from 'fs';
|
|
2
|
-
import { join } from 'path';
|
|
3
|
-
import { glob } from 'glob';
|
|
4
|
-
import chalk from 'chalk';
|
|
5
|
-
import { getAbsoluteOutputPath, resolveContractsOutputType } from '../../../core/paths/output-schema.js';
|
|
6
|
-
|
|
7
|
-
export async function validateContracts(projectPath, featureName, options = {}) {
|
|
8
|
-
const contractsPath = getAbsoluteOutputPath(projectPath, featureName, resolveContractsOutputType());
|
|
9
|
-
|
|
10
|
-
const skipped = (message) => ({ status: 'ok', errors: 0, warnings: 0, issues: [], coverage: null, message });
|
|
11
|
-
|
|
12
|
-
if (!existsSync(contractsPath)) return skipped('No plan.md found — skipping');
|
|
13
|
-
|
|
14
|
-
const contractsContent = readFileSync(contractsPath, 'utf-8');
|
|
15
|
-
const contracts = parseContracts(contractsContent);
|
|
16
|
-
|
|
17
|
-
if (contracts.interfaces.length === 0 && contracts.records.length === 0 && contracts.enums.length === 0) {
|
|
18
|
-
return skipped('plan.md declares no interfaces/records/enums — skipping');
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
const csFiles = await glob('**/*.cs', {
|
|
22
|
-
cwd: projectPath,
|
|
23
|
-
ignore: ['.morph/**', '**/bin/**', '**/obj/**', '**/node_modules/**']
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
const projectCode = {};
|
|
27
|
-
for (const file of csFiles) {
|
|
28
|
-
const fullPath = join(projectPath, file);
|
|
29
|
-
try {
|
|
30
|
-
projectCode[file] = readFileSync(fullPath, 'utf-8');
|
|
31
|
-
} catch {
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const issues = [];
|
|
36
|
-
let implemented = 0;
|
|
37
|
-
let total = 0;
|
|
38
|
-
const interfaceResults = [];
|
|
39
|
-
|
|
40
|
-
for (const iface of contracts.interfaces) {
|
|
41
|
-
total++;
|
|
42
|
-
const result = validateInterface(iface, projectCode, options);
|
|
43
|
-
interfaceResults.push(result);
|
|
44
|
-
|
|
45
|
-
if (result.implemented) {
|
|
46
|
-
implemented++;
|
|
47
|
-
if (options.verbose) {
|
|
48
|
-
console.log(chalk.green(` ✓ ${iface.name} → ${result.implementingClass} (${result.implementedMethods}/${result.totalMethods} methods)`));
|
|
49
|
-
}
|
|
50
|
-
} else {
|
|
51
|
-
issues.push({
|
|
52
|
-
level: 'error',
|
|
53
|
-
message: `Interface ${iface.name} not implemented in project code`,
|
|
54
|
-
solution: `Create a class that implements ${iface.name} with all ${iface.methods.length} method(s)`
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
for (const method of result.missingMethods || []) {
|
|
59
|
-
issues.push({
|
|
60
|
-
level: 'error',
|
|
61
|
-
message: `Method ${method} missing from ${result.implementingClass || iface.name} implementation`,
|
|
62
|
-
file: result.implementingFile,
|
|
63
|
-
solution: `Add method ${method} to the class implementing ${iface.name}`
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
for (const record of contracts.records) {
|
|
69
|
-
total++;
|
|
70
|
-
const found = Object.entries(projectCode).some(([, content]) =>
|
|
71
|
-
new RegExp(`(class|record|struct)\\s+${escapeRegex(record.name)}`, 'g').test(content)
|
|
72
|
-
);
|
|
73
|
-
|
|
74
|
-
if (found) {
|
|
75
|
-
implemented++;
|
|
76
|
-
if (options.verbose) {
|
|
77
|
-
console.log(chalk.green(` ✓ ${record.name} (${record.type})`));
|
|
78
|
-
}
|
|
79
|
-
} else {
|
|
80
|
-
issues.push({
|
|
81
|
-
level: 'warning',
|
|
82
|
-
message: `${record.type} ${record.name} defined in contracts but not found in project code`,
|
|
83
|
-
solution: `Create ${record.type} ${record.name} matching the contract definition`
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
for (const enumDef of contracts.enums) {
|
|
89
|
-
total++;
|
|
90
|
-
const found = Object.entries(projectCode).some(([, content]) =>
|
|
91
|
-
new RegExp(`enum\\s+${escapeRegex(enumDef.name)}`, 'g').test(content)
|
|
92
|
-
);
|
|
93
|
-
|
|
94
|
-
if (found) {
|
|
95
|
-
implemented++;
|
|
96
|
-
if (options.verbose) {
|
|
97
|
-
console.log(chalk.green(` ✓ ${enumDef.name} (enum)`));
|
|
98
|
-
}
|
|
99
|
-
} else {
|
|
100
|
-
issues.push({
|
|
101
|
-
level: 'warning',
|
|
102
|
-
message: `Enum ${enumDef.name} defined in contracts but not found in project code`,
|
|
103
|
-
solution: `Create enum ${enumDef.name} matching the contract definition`
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
const coveragePercent = total > 0 ? Math.round((implemented / total) * 100) : 100;
|
|
109
|
-
const errors = issues.filter(i => i.level === 'error').length;
|
|
110
|
-
const warnings = issues.filter(i => i.level === 'warning').length;
|
|
111
|
-
|
|
112
|
-
if (options.verbose) {
|
|
113
|
-
console.log(chalk.cyan(`\n Contract coverage: ${coveragePercent}% (${implemented}/${total})`));
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
return {
|
|
117
|
-
status: errors > 0 ? 'error' : 'ok',
|
|
118
|
-
errors,
|
|
119
|
-
warnings,
|
|
120
|
-
issues,
|
|
121
|
-
coverage: {
|
|
122
|
-
percentage: coveragePercent,
|
|
123
|
-
implemented,
|
|
124
|
-
total,
|
|
125
|
-
interfaces: interfaceResults
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
function parseContracts(content) {
|
|
131
|
-
const interfaces = [];
|
|
132
|
-
const records = [];
|
|
133
|
-
const enums = [];
|
|
134
|
-
|
|
135
|
-
const interfaceRegex = /public\s+interface\s+(I\w+)(?:\s*:\s*[\w<>,\s]+)?\s*\{([^}]*)\}/gs;
|
|
136
|
-
let match;
|
|
137
|
-
|
|
138
|
-
while ((match = interfaceRegex.exec(content)) !== null) {
|
|
139
|
-
const name = match[1];
|
|
140
|
-
const body = match[2];
|
|
141
|
-
const methods = extractMethods(body);
|
|
142
|
-
|
|
143
|
-
interfaces.push({ name, methods });
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
const recordRegex = /public\s+(record|class|struct)\s+(\w+)/g;
|
|
147
|
-
while ((match = recordRegex.exec(content)) !== null) {
|
|
148
|
-
const type = match[1];
|
|
149
|
-
const name = match[2];
|
|
150
|
-
if (!name.startsWith('I') || !interfaces.some(i => i.name === name)) {
|
|
151
|
-
records.push({ type, name });
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
const enumRegex = /public\s+enum\s+(\w+)/g;
|
|
156
|
-
while ((match = enumRegex.exec(content)) !== null) {
|
|
157
|
-
enums.push({ name: match[1] });
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
return { interfaces, records, enums };
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
function extractMethods(body) {
|
|
164
|
-
const methods = [];
|
|
165
|
-
|
|
166
|
-
// Match method signatures like: Task<Result> DoSomethingAsync(params);
|
|
167
|
-
const methodRegex = /(?:Task<[^>]+>|Task|void|string|int|bool|decimal|[\w<>[\],\s?]+)\s+(\w+)\s*\(/g;
|
|
168
|
-
let match;
|
|
169
|
-
|
|
170
|
-
while ((match = methodRegex.exec(body)) !== null) {
|
|
171
|
-
const methodName = match[1];
|
|
172
|
-
if (!['get', 'set', 'init'].includes(methodName)) {
|
|
173
|
-
methods.push(methodName);
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
return methods;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
function validateInterface(iface, projectCode, options) {
|
|
181
|
-
const result = {
|
|
182
|
-
name: iface.name,
|
|
183
|
-
implemented: false,
|
|
184
|
-
implementingClass: null,
|
|
185
|
-
implementingFile: null,
|
|
186
|
-
totalMethods: iface.methods.length,
|
|
187
|
-
implementedMethods: 0,
|
|
188
|
-
missingMethods: []
|
|
189
|
-
};
|
|
190
|
-
|
|
191
|
-
const implRegex = new RegExp(`class\\s+(\\w+)\\s*(?:<[^>]*>)?\\s*:\\s*[^{]*${escapeRegex(iface.name)}`, 'g');
|
|
192
|
-
|
|
193
|
-
for (const [file, content] of Object.entries(projectCode)) {
|
|
194
|
-
const match = implRegex.exec(content);
|
|
195
|
-
if (match) {
|
|
196
|
-
result.implemented = true;
|
|
197
|
-
result.implementingClass = match[1];
|
|
198
|
-
result.implementingFile = file;
|
|
199
|
-
|
|
200
|
-
for (const method of iface.methods) {
|
|
201
|
-
const methodExists = new RegExp(`(public|protected|private|internal)?\\s*(async\\s+)?\\S+\\s+${escapeRegex(method)}\\s*\\(`, 'g').test(content);
|
|
202
|
-
if (methodExists) {
|
|
203
|
-
result.implementedMethods++;
|
|
204
|
-
} else {
|
|
205
|
-
result.missingMethods.push(method);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
break;
|
|
210
|
-
}
|
|
211
|
-
implRegex.lastIndex = 0;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
return result;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
function escapeRegex(str) {
|
|
218
|
-
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
219
|
-
}
|
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
import { glob } from 'glob';
|
|
2
|
-
import { readFileSync } from 'node:fs';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
|
|
5
|
-
const CLIENT_HOOKS = ['useState', 'useEffect', 'useRef', 'useReducer', 'useCallback', 'useMemo', 'useContext'];
|
|
6
|
-
|
|
7
|
-
const EVENT_HANDLER_PATTERNS = [
|
|
8
|
-
/\bonClick\b/,
|
|
9
|
-
/\bonChange\b/,
|
|
10
|
-
/\bonSubmit\b/,
|
|
11
|
-
/\bonFocus\b/,
|
|
12
|
-
/\bonBlur\b/,
|
|
13
|
-
/\bonKeyDown\b/,
|
|
14
|
-
/\bon[A-Z]\w*\s*=\s*\{/,
|
|
15
|
-
];
|
|
16
|
-
|
|
17
|
-
// `[<(]` faz hook com argumento de tipo (`useState<Record<string, string>>(`) contar.
|
|
18
|
-
const HOOK_CALL_PATTERN = /\buse[A-Z]\w*\s*[<(]/;
|
|
19
|
-
|
|
20
|
-
// Lançam em Server Component: o módulo precisa da diretiva mesmo sem hook nem handler.
|
|
21
|
-
const CLIENT_ONLY_APIS = [/\bforwardRef\b/, /\bcreateContext\b/];
|
|
22
|
-
|
|
23
|
-
const BROWSER_GLOBALS = /\b(window|document|localStorage|sessionStorage|navigator)\s*[.[]/;
|
|
24
|
-
|
|
25
|
-
// Wrapper shadcn/Radix só reexporta primitivas client-only, sem hook nem handler no arquivo.
|
|
26
|
-
const CLIENT_ONLY_IMPORTS = /from\s+['"](@radix-ui\/|sonner|@react-pdf\/|file-saver|framer-motion|motion\/|recharts|next\/navigation|react-hook-form|@tanstack\/react-query|embla-carousel|cmdk|vaul|react-day-picker|input-otp|@dnd-kit\/)/;
|
|
27
|
-
|
|
28
|
-
const NEXTJS_SPECIAL_FILES = ['page.tsx', 'layout.tsx', 'loading.tsx', 'error.tsx', 'not-found.tsx', 'route.ts', 'middleware.ts'];
|
|
29
|
-
|
|
30
|
-
export function validateNextComponent(content, filePath) {
|
|
31
|
-
const issues = [];
|
|
32
|
-
|
|
33
|
-
if (!filePath.endsWith('.tsx') && !filePath.endsWith('.ts')) {
|
|
34
|
-
return issues;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const hasJsx = /(?<![a-zA-Z0-9])<[A-Z][a-zA-Z]*[\s/>]|(?<![a-zA-Z0-9])<[a-z][a-z]+[\s>/]/.test(content);
|
|
38
|
-
const hasHooks = CLIENT_HOOKS.some(hook => content.includes(hook));
|
|
39
|
-
|
|
40
|
-
if (!hasJsx && !hasHooks) {
|
|
41
|
-
return issues;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const hasUseClient = /^'use client';?|^"use client";?/.test(content.trimStart());
|
|
45
|
-
|
|
46
|
-
if (hasUseClient) {
|
|
47
|
-
const hasEventHandlers = EVENT_HANDLER_PATTERNS.some(pattern => pattern.test(content));
|
|
48
|
-
const hasClientHooks = CLIENT_HOOKS.some(hook => new RegExp(`\\b${hook}\\b`).test(content));
|
|
49
|
-
// Falso-positivo pediria remover uma diretiva que o build precisa: erra para o lado calado.
|
|
50
|
-
const needsClient =
|
|
51
|
-
hasEventHandlers ||
|
|
52
|
-
hasClientHooks ||
|
|
53
|
-
HOOK_CALL_PATTERN.test(content) ||
|
|
54
|
-
CLIENT_ONLY_APIS.some(pattern => pattern.test(content)) ||
|
|
55
|
-
BROWSER_GLOBALS.test(content) ||
|
|
56
|
-
CLIENT_ONLY_IMPORTS.test(content);
|
|
57
|
-
if (!needsClient) {
|
|
58
|
-
issues.push({
|
|
59
|
-
type: 'warning',
|
|
60
|
-
message: "'use client' directive present but no interactivity detected (no hooks, no event handlers)",
|
|
61
|
-
suggestion: "Remove 'use client' to make this a Server Component, or add interactive behavior",
|
|
62
|
-
file: filePath,
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// .ts files (custom hooks, utilities) never render JSX — skip this check
|
|
68
|
-
if (!hasUseClient) {
|
|
69
|
-
if (!filePath.endsWith('.tsx')) return issues;
|
|
70
|
-
const usedHooks = CLIENT_HOOKS.filter(hook => new RegExp(`\\b${hook}\\b`).test(content));
|
|
71
|
-
if (usedHooks.length > 0) {
|
|
72
|
-
issues.push({
|
|
73
|
-
type: 'error',
|
|
74
|
-
message: `React hook(s) used (${usedHooks.join(', ')}) without 'use client' directive`,
|
|
75
|
-
suggestion: "Add 'use client' as the first line of the file",
|
|
76
|
-
file: filePath,
|
|
77
|
-
line: 1,
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
const fileName = filePath.split('/').pop() ?? '';
|
|
83
|
-
const isSpecialFile = NEXTJS_SPECIAL_FILES.includes(fileName);
|
|
84
|
-
|
|
85
|
-
if (!isSpecialFile && fileName.endsWith('.tsx')) {
|
|
86
|
-
const baseName = fileName.replace('.tsx', '');
|
|
87
|
-
const hasUpperCase = /[A-Z]/.test(baseName);
|
|
88
|
-
if (hasUpperCase) {
|
|
89
|
-
issues.push({
|
|
90
|
-
type: 'warning',
|
|
91
|
-
message: `Component file '${fileName}' should use kebab-case naming`,
|
|
92
|
-
suggestion: `Rename to '${toKebabCase(baseName)}.tsx'`,
|
|
93
|
-
file: filePath,
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
return issues;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
function toKebabCase(str) {
|
|
102
|
-
return str
|
|
103
|
-
.replace(/([A-Z])/g, '-$1')
|
|
104
|
-
.toLowerCase()
|
|
105
|
-
.replace(/^-/, '');
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
export async function validateNextComponentFiles(projectPath, _options = {}) {
|
|
109
|
-
const result = { errors: 0, warnings: 0, issues: [] };
|
|
110
|
-
|
|
111
|
-
const srcDir = join(projectPath, 'src');
|
|
112
|
-
const normalizedSrc = srcDir.replace(/\\/g, '/');
|
|
113
|
-
const pattern = normalizedSrc + '/**/*.{tsx,ts}';
|
|
114
|
-
const files = await glob(pattern, { ignore: ['**/node_modules/**', '**/.next/**'] });
|
|
115
|
-
|
|
116
|
-
for (const filePath of files) {
|
|
117
|
-
let content;
|
|
118
|
-
try {
|
|
119
|
-
content = readFileSync(filePath, 'utf8');
|
|
120
|
-
} catch {
|
|
121
|
-
continue;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const normFilePath = filePath.replace(/\\/g, '/');
|
|
125
|
-
const relPath = normFilePath.replace(projectPath.replace(/\\/g, '/') + '/', '');
|
|
126
|
-
const fileIssues = validateNextComponent(content, relPath);
|
|
127
|
-
|
|
128
|
-
for (const issue of fileIssues) {
|
|
129
|
-
result.issues.push({
|
|
130
|
-
level: issue.type,
|
|
131
|
-
message: issue.message,
|
|
132
|
-
file: issue.file,
|
|
133
|
-
line: issue.line,
|
|
134
|
-
solution: issue.suggestion,
|
|
135
|
-
});
|
|
136
|
-
if (issue.type === 'error') result.errors++;
|
|
137
|
-
else if (issue.type === 'warning') result.warnings++;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
return result;
|
|
142
|
-
}
|