create-tigra 4.0.1 → 5.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/CHANGELOG.md +43 -0
- package/README.md +21 -3
- package/bin/create-tigra.js +131 -65
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +123 -0
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +145 -0
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +75 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +20 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +37 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +133 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +45 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +104 -0
- package/package.json +1 -1
- package/template/AGENTS.md +18 -10
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { installModule } from '../installer-transaction.js';
|
|
5
|
+
import { nextModuleMigration } from '../project-files.js';
|
|
6
|
+
|
|
7
|
+
const payload = fileURLToPath(new URL('../../modules/diagnostics/', import.meta.url));
|
|
8
|
+
const moduleDir = 'server/src/modules/diagnostics';
|
|
9
|
+
const schema = 'server/prisma/schema.prisma';
|
|
10
|
+
const migrations = 'server/prisma/migrations';
|
|
11
|
+
const marker = `${moduleDir}/installation.json`;
|
|
12
|
+
const heading = '## Error and warning diagnostics';
|
|
13
|
+
const guide = 'server/docs/diagnostics.md';
|
|
14
|
+
const instruction = `${heading}\n\nWhen diagnostics is installed, use the [diagnostics guide](${guide}) to investigate error history through the read-only MySQL skill or admin API. Report observed failures separately from inferred causes. Verify automatic capture for new requests and jobs, and record handled failures or actionable warnings with stable codes and safe messages.\n`;
|
|
15
|
+
|
|
16
|
+
const transforms = {
|
|
17
|
+
'server/src/app.ts': [
|
|
18
|
+
["import { registerErrorHandler } from '@libs/error-handler.js';", "import { registerErrorHandler } from '@libs/error-handler.js';\nimport { registerDiagnostics } from '@modules/diagnostics/diagnostics.service.js';"],
|
|
19
|
+
[' const { onRoute } = options;', ' const { onRoute } = options;\n registerDiagnostics(app);'],
|
|
20
|
+
],
|
|
21
|
+
'server/src/libs/error-handler.ts': [
|
|
22
|
+
["import { logger } from '@libs/logger.js';", "import { logger } from '@libs/logger.js';\nimport { captureRequestFailure } from '@modules/diagnostics/diagnostics.context.js';"],
|
|
23
|
+
[' if (isAppError(error)) {', ' if (isAppError(error)) {\n if (error.statusCode >= 500) captureRequestFailure(error);'],
|
|
24
|
+
[" const requestId = request.id || 'unknown';", " captureRequestFailure(error);\n const requestId = request.id || 'unknown';"],
|
|
25
|
+
],
|
|
26
|
+
'server/src/jobs/schedule.ts': [
|
|
27
|
+
["import { logger } from '@libs/logger.js';", "import { logger } from '@libs/logger.js';\nimport { captureJobFailure, withDiagnosticJob } from '@modules/diagnostics/diagnostics.context.js';"],
|
|
28
|
+
[' const tick = async (): Promise<void> => {', ' const tick = (): Promise<void> => withDiagnosticJob(app, job.name, async () => {'],
|
|
29
|
+
[' } catch (error) {', ' } catch (error) {\n captureJobFailure(error);'],
|
|
30
|
+
[' };\n\n const firstRun', ' });\n\n const firstRun'],
|
|
31
|
+
],
|
|
32
|
+
'server/src/modules/admin/admin.routes.ts': [
|
|
33
|
+
["import { RATE_LIMITS } from '@config/rate-limit.config.js';", "import { registerAdminDiagnosticsRoute } from '@modules/diagnostics/diagnostics.routes.js';", true],
|
|
34
|
+
// Keep retrofits compatible with apps that still use the original admin hooks.
|
|
35
|
+
[[" registerAdminAuthorization(fastify);", " fastify.addHook('preValidation', authorize('ADMIN'));"], ' registerAdminDiagnosticsRoute(fastify);', true],
|
|
36
|
+
],
|
|
37
|
+
'server/src/__tests__/routes.integration.test.ts': [
|
|
38
|
+
['const COVERED_ELSEWHERE: Record<string, string> = {', "const COVERED_ELSEWHERE: Record<string, string> = {\n 'GET /api/v1/admin/diagnostics': 'src/modules/diagnostics/__tests__/diagnostics.integration.test.ts',"],
|
|
39
|
+
],
|
|
40
|
+
'server/src/test/integration.global-setup.ts': [
|
|
41
|
+
[' const tables = await tx.$queryRaw<{ name: string }[]>', ' // The guarded test database reset must also remove the diagnostics view.\n await tx.$executeRaw`DROP VIEW IF EXISTS diagnostic_hourly_top`;\n const tables = await tx.$queryRaw<{ name: string }[]>'],
|
|
42
|
+
],
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function patch(file, content, edits) {
|
|
46
|
+
const newline = content.includes('\r\n') ? '\r\n' : '\n';
|
|
47
|
+
let patched = content.replaceAll('\r\n', '\n');
|
|
48
|
+
for (const [anchors, replacement, append] of edits) {
|
|
49
|
+
const matches = [anchors].flat().filter((anchor) => patched.includes(anchor));
|
|
50
|
+
const [anchor] = matches;
|
|
51
|
+
if (matches.length !== 1 || patched.indexOf(anchor, patched.indexOf(anchor) + anchor.length) !== -1) {
|
|
52
|
+
throw new Error(`Cannot install diagnostics: expected one integration point in ${file}.`);
|
|
53
|
+
}
|
|
54
|
+
patched = patched.replace(anchor, append ? `${anchor}\n${replacement}` : replacement);
|
|
55
|
+
}
|
|
56
|
+
return patched.replaceAll('\n', newline);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function applyDiagnosticsModule(root) {
|
|
60
|
+
return installModule(root, planDiagnostics);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function planDiagnostics({ read: readFile, exists, list }) {
|
|
64
|
+
const read = (file) => readFile(file, 'utf8');
|
|
65
|
+
const originalSchema = await read(schema);
|
|
66
|
+
const agents = await read('AGENTS.md');
|
|
67
|
+
const serverPayload = path.join(payload, 'server');
|
|
68
|
+
const sources = (await fs.readdir(serverPayload, { recursive: true, withFileTypes: true }))
|
|
69
|
+
.filter((entry) => entry.isFile())
|
|
70
|
+
.map((entry) => {
|
|
71
|
+
const source = path.join(entry.parentPath, entry.name);
|
|
72
|
+
return [source, path.join(moduleDir, path.relative(serverPayload, source))];
|
|
73
|
+
});
|
|
74
|
+
sources.push([path.join(payload, 'diagnostics.md'), guide]);
|
|
75
|
+
|
|
76
|
+
if (await exists(marker)) {
|
|
77
|
+
const { migration } = JSON.parse(await read(marker));
|
|
78
|
+
const expected = typeof migration === 'string' && /^\d{14}_diagnostics$/.test(migration);
|
|
79
|
+
const installedFiles = [...sources.map(([, file]) => file), `${migrations}/${migration}/migration.sql`];
|
|
80
|
+
const integrations = await Promise.all(Object.entries(transforms).map(async ([file, edits]) => {
|
|
81
|
+
const content = (await read(file)).replaceAll('\r\n', '\n');
|
|
82
|
+
// Another module can insert lines between ours and a shared anchor.
|
|
83
|
+
return edits.every(([, replacement]) => replacement.split('\n').every((line) => content.includes(line)));
|
|
84
|
+
}));
|
|
85
|
+
if (!expected || !originalSchema.includes('model DiagnosticBucket') || !agents.includes(heading) ||
|
|
86
|
+
!integrations.every(Boolean) || !(await Promise.all(installedFiles.map((file) => exists(file)))).every(Boolean)) {
|
|
87
|
+
throw new Error('The diagnostics installation is incomplete. Restore the missing integration or pre-install state.');
|
|
88
|
+
}
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const existing = (await list(migrations))
|
|
93
|
+
.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
94
|
+
if (!/provider\s*=\s*"mysql"/.test(originalSchema) || /DiagnosticBucket|diagnostic_buckets/.test(originalSchema) ||
|
|
95
|
+
agents.includes(heading) || await exists(moduleDir) || existing.some((name) => name.endsWith('_diagnostics'))) {
|
|
96
|
+
throw new Error('Diagnostics requires a compatible MySQL Tigra project with no partial diagnostics installation.');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const migration = nextModuleMigration(await list(migrations), 'diagnostics');
|
|
100
|
+
const migrationFile = `${migrations}/${migration}/migration.sql`;
|
|
101
|
+
sources.push([path.join(payload, 'prisma/migration.sql'), migrationFile]);
|
|
102
|
+
const writes = new Map();
|
|
103
|
+
for (const [source, file] of sources) {
|
|
104
|
+
if (await exists(file)) throw new Error(`Cannot install diagnostics: ${file} already exists.`);
|
|
105
|
+
writes.set(file, await fs.readFile(source));
|
|
106
|
+
}
|
|
107
|
+
// Keep the view SQL usable on its own for projects with an applied migration.
|
|
108
|
+
const view = await fs.readFile(path.join(payload, 'prisma/diagnostic-hourly-view.sql'));
|
|
109
|
+
writes.set(migrationFile, Buffer.concat([writes.get(migrationFile), Buffer.from('\n'), view]));
|
|
110
|
+
for (const [file, edits] of Object.entries(transforms)) {
|
|
111
|
+
const original = await read(file);
|
|
112
|
+
if (original.includes('@modules/diagnostics/') || original.includes('GET /api/v1/admin/diagnostics')) {
|
|
113
|
+
throw new Error(`Cannot install over partial diagnostics integration in ${file}.`);
|
|
114
|
+
}
|
|
115
|
+
writes.set(file, patch(file, original, edits));
|
|
116
|
+
}
|
|
117
|
+
const model = await fs.readFile(path.join(payload, 'prisma/diagnostic-bucket.prisma'), 'utf8');
|
|
118
|
+
writes.set(schema, `${originalSchema.trimEnd()}\n\n${model}`);
|
|
119
|
+
writes.set('AGENTS.md', `${agents.trimEnd()}\n\n${instruction}`);
|
|
120
|
+
writes.set(marker, `${JSON.stringify({ migration }, null, 2)}\n`);
|
|
121
|
+
|
|
122
|
+
return writes;
|
|
123
|
+
}
|
|
@@ -10,76 +10,89 @@ import { Project, SyntaxKind } from 'ts-morph';
|
|
|
10
10
|
import fs from 'fs-extra';
|
|
11
11
|
import path from 'path';
|
|
12
12
|
import { fileURLToPath } from 'url';
|
|
13
|
+
import { installModule } from '../installer-transaction.js';
|
|
13
14
|
|
|
14
15
|
const __filename = fileURLToPath(import.meta.url);
|
|
15
16
|
const __dirname = path.dirname(__filename);
|
|
16
17
|
const ROOT_DIR = path.join(__dirname, '..', '..');
|
|
17
18
|
const MODULES_DIR = path.join(ROOT_DIR, 'modules', 'email-verification');
|
|
18
19
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
20
|
+
const auth = 'server/src/modules/auth';
|
|
21
|
+
const frontend = 'client/src/features/auth';
|
|
22
|
+
const payload = new Map([
|
|
23
|
+
['server/verification.service.ts', `${auth}/verification.service.ts`],
|
|
24
|
+
['server/verification.controller.ts', `${auth}/verification.controller.ts`],
|
|
25
|
+
['server/__tests__/verification.integration.test.ts', `${auth}/__tests__/verification.integration.test.ts`],
|
|
26
|
+
['server/__tests__/verification.service.test.ts', `${auth}/__tests__/verification.service.test.ts`],
|
|
27
|
+
['client/services/verification.service.ts', `${frontend}/services/verification.service.ts`],
|
|
28
|
+
['client/hooks/useVerification.ts', `${frontend}/hooks/useVerification.ts`],
|
|
29
|
+
]);
|
|
30
|
+
const integration = new Map([
|
|
31
|
+
[`${auth}/auth.routes.ts`, ["'/auth/send-verification'", "'/auth/verify-account'", 'handler: verificationController.sendVerification', 'handler: verificationController.verifyAccount']],
|
|
32
|
+
[`${auth}/auth.schemas.ts`, ['sendVerificationSchema', 'verifyAccountSchema']],
|
|
33
|
+
[`${auth}/auth.service.ts`, ['sendVerification(input.email', 'sendVerification(user.email']],
|
|
34
|
+
['server/src/config/rate-limit.config.ts', ['AUTH_SEND_VERIFICATION', 'AUTH_VERIFY_ACCOUNT']],
|
|
35
|
+
['server/src/config/env.ts', ['REQUIRE_USER_VERIFICATION: envBoolean(true)']],
|
|
36
|
+
['server/src/jobs/index.ts', ['startEmailVerificationJob(app)']],
|
|
37
|
+
['client/src/lib/constants/api-endpoints.ts', ['SEND_VERIFICATION', 'VERIFY_ACCOUNT']],
|
|
38
|
+
['client/src/lib/utils/error.ts', ['ALREADY_VERIFIED', 'INVALID_VERIFICATION_TOKEN']],
|
|
39
|
+
[`${frontend}/hooks/useAuth.ts`, ['router.push(ROUTES.VERIFY_ACCOUNT)']],
|
|
40
|
+
]);
|
|
41
|
+
const legacyMarker = `${auth}/verification.service.ts`;
|
|
42
|
+
const patchFiles = [
|
|
43
|
+
...integration.keys(), ...payload.values(), 'server/.env', 'server/.env.example',
|
|
44
|
+
'server/.env.example.production', 'server/postman/collection.json',
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
export function applyEmailVerificationModule(root) {
|
|
48
|
+
return installModule(root, async ({ read, exists, stage }) => {
|
|
49
|
+
// A checkout built before the auth and browser-session changes needs a
|
|
50
|
+
// retrofit first. Keep that compatibility check inside the project lock.
|
|
51
|
+
for (const file of [
|
|
52
|
+
`${auth}/auth-mail-queue.ts`, `${auth}/auth-link-store.ts`,
|
|
53
|
+
'server/src/libs/account-mutation.ts', `${frontend}/hooks/useSessionTransition.ts`,
|
|
54
|
+
]) {
|
|
55
|
+
if (!await exists(file)) {
|
|
56
|
+
throw new Error('This project needs the current Tigra auth infrastructure before installing email verification. See the account verification upgrade guide.');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const present = await Promise.all([...payload.values()].map(exists));
|
|
60
|
+
const states = await Promise.all([...integration].map(async ([file, markers]) => {
|
|
61
|
+
const content = await read(file, 'utf8');
|
|
62
|
+
return markers.map((marker) => content.includes(marker));
|
|
63
|
+
}));
|
|
64
|
+
// A few client errors/endpoints may already exist with the module off.
|
|
65
|
+
const dedicatedIntegrations = states.slice(0, 6);
|
|
66
|
+
if (present.some(Boolean) || dedicatedIntegrations.flat().some(Boolean)) {
|
|
67
|
+
if (present.every(Boolean) && states.flat().every(Boolean)) return null;
|
|
68
|
+
throw new Error('The email verification installation is incomplete. Restore the missing integration or pre-install state.');
|
|
69
|
+
}
|
|
52
70
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
dest: path.join(targetDir, 'client', 'src', 'features', 'auth', 'services', 'verification.service.ts'),
|
|
72
|
-
},
|
|
73
|
-
{
|
|
74
|
-
src: path.join(MODULES_DIR, 'client', 'hooks', 'useVerification.ts'),
|
|
75
|
-
dest: path.join(targetDir, 'client', 'src', 'features', 'auth', 'hooks', 'useVerification.ts'),
|
|
76
|
-
},
|
|
77
|
-
];
|
|
71
|
+
const writes = await stage(patchFiles, async (targetDir) => {
|
|
72
|
+
for (const [source, relative] of payload) {
|
|
73
|
+
const dest = path.join(targetDir, relative);
|
|
74
|
+
await fs.ensureDir(path.dirname(dest));
|
|
75
|
+
await fs.copyFile(path.join(MODULES_DIR, source), dest);
|
|
76
|
+
}
|
|
77
|
+
const project = new Project({ useInMemoryFileSystem: false, skipAddingFilesFromTsConfig: true });
|
|
78
|
+
patchAuthRoutes(project, targetDir);
|
|
79
|
+
patchAuthSchemas(project, targetDir);
|
|
80
|
+
patchRateLimitConfig(project, targetDir);
|
|
81
|
+
patchAuthService(project, targetDir);
|
|
82
|
+
patchVerificationJob(project, targetDir);
|
|
83
|
+
patchVerificationDefault(targetDir);
|
|
84
|
+
patchApiEndpoints(project, targetDir);
|
|
85
|
+
patchErrorCodes(project, targetDir);
|
|
86
|
+
patchUseAuthHook(targetDir);
|
|
87
|
+
await patchPostmanCollection(targetDir);
|
|
88
|
+
});
|
|
78
89
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
90
|
+
// Older callers recognize this file as the email module's installation marker.
|
|
91
|
+
const service = writes.get(legacyMarker);
|
|
92
|
+
writes.delete(legacyMarker);
|
|
93
|
+
writes.set(legacyMarker, service);
|
|
94
|
+
return writes;
|
|
95
|
+
});
|
|
83
96
|
}
|
|
84
97
|
|
|
85
98
|
// ─── Server Patches ─────────────────────────────────────────────
|
|
@@ -417,38 +430,19 @@ function patchAuthService(project, targetDir) {
|
|
|
417
430
|
}
|
|
418
431
|
|
|
419
432
|
/**
|
|
420
|
-
* Patch 5:
|
|
421
|
-
* - Add markEmailVerified function at end of file
|
|
422
|
-
*
|
|
423
|
-
* It sets emailVerifiedAt only for an active, not-yet-verified, non-deleted
|
|
424
|
-
* account and never touches isActive (the admin ban switch). The conditional
|
|
425
|
-
* write means a ban that lands mid-verification still wins. Returns whether a
|
|
426
|
-
* row was updated.
|
|
433
|
+
* Patch 5: register the verification worker only in projects with the module.
|
|
427
434
|
*/
|
|
428
|
-
function
|
|
429
|
-
const filePath = path.join(targetDir, 'server', 'src', '
|
|
435
|
+
function patchVerificationJob(project, targetDir) {
|
|
436
|
+
const filePath = path.join(targetDir, 'server', 'src', 'jobs', 'index.ts');
|
|
430
437
|
const sourceFile = project.addSourceFileAtPath(filePath);
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
isAsync: true,
|
|
440
|
-
parameters: [
|
|
441
|
-
{ name: 'userId', type: 'string' },
|
|
442
|
-
{ name: 'verifiedAt', type: 'Date' },
|
|
443
|
-
],
|
|
444
|
-
returnType: 'Promise<boolean>',
|
|
445
|
-
statements: `const result = await prisma.user.updateMany({
|
|
446
|
-
where: { id: userId, isActive: true, emailVerifiedAt: null, deletedAt: null },
|
|
447
|
-
data: { emailVerifiedAt: verifiedAt },
|
|
448
|
-
});
|
|
449
|
-
return result.count === 1;`,
|
|
450
|
-
});
|
|
451
|
-
|
|
438
|
+
const registry = sourceFile.getFunctionOrThrow('registerJobs');
|
|
439
|
+
const worker = '@modules/auth/verification.service.js';
|
|
440
|
+
if (!sourceFile.getImportDeclaration(worker)) {
|
|
441
|
+
sourceFile.addImportDeclaration({ moduleSpecifier: worker, namedImports: ['startEmailVerificationJob'] });
|
|
442
|
+
}
|
|
443
|
+
if (!registry.getBodyOrThrow().getText().includes('startEmailVerificationJob(app)')) {
|
|
444
|
+
registry.addStatements('startEmailVerificationJob(app);');
|
|
445
|
+
}
|
|
452
446
|
sourceFile.saveSync();
|
|
453
447
|
}
|
|
454
448
|
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { installModule } from '../installer-transaction.js';
|
|
5
|
+
import { nextModuleMigration } from '../project-files.js';
|
|
6
|
+
|
|
7
|
+
const payload = fileURLToPath(new URL('../../modules/metrics/', import.meta.url));
|
|
8
|
+
const server = 'server/src/modules/metrics';
|
|
9
|
+
const client = 'client/src/features/metrics';
|
|
10
|
+
const schema = 'server/prisma/schema.prisma';
|
|
11
|
+
const marker = `${server}/installation.json`;
|
|
12
|
+
const migrations = 'server/prisma/migrations';
|
|
13
|
+
const coverage = 'src/modules/metrics/__tests__/metrics.integration.test.ts';
|
|
14
|
+
const instruction = [
|
|
15
|
+
'## Performance metrics',
|
|
16
|
+
'',
|
|
17
|
+
'When metrics are installed, maintain performance coverage with every feature change. Verify request and Web Vitals coverage for new routes and pages. Add named timings for meaningful dependency calls and jobs, update page groups where needed, and verify that the affected measurements reach storage and the admin API. Use stable labels free of user data.',
|
|
18
|
+
'',
|
|
19
|
+
'See the [performance guide](server/docs/performance.md) for the collection and read contracts.',
|
|
20
|
+
].join('\n');
|
|
21
|
+
|
|
22
|
+
const transforms = {
|
|
23
|
+
'server/src/app.ts': [
|
|
24
|
+
["import { env } from '@config/env.js';", `\nimport { registerMetrics } from '@modules/metrics/metrics.service.js';\nimport { webVitalsRoutes } from '@modules/metrics/metrics.routes.js';`],
|
|
25
|
+
[' const { onRoute } = options;', '\n const metrics = registerMetrics(app);'],
|
|
26
|
+
[" await app.register(adminRoutes, { prefix: '/api/v1' });", "\n await app.register(webVitalsRoutes, { prefix: '/api/v1', collector: metrics });"],
|
|
27
|
+
],
|
|
28
|
+
'server/src/modules/admin/admin.routes.ts': [
|
|
29
|
+
["import { RATE_LIMITS } from '@config/rate-limit.config.js';", "\nimport { registerAdminMetricsRoute } from '@modules/metrics/metrics.routes.js';"],
|
|
30
|
+
// Older generated apps still register the individual preValidation hooks.
|
|
31
|
+
[[" registerAdminAuthorization(fastify);", " fastify.addHook('preValidation', authorize('ADMIN'));"], '\n registerAdminMetricsRoute(fastify);'],
|
|
32
|
+
],
|
|
33
|
+
'server/src/config/env.ts': [
|
|
34
|
+
['const envSchema = z.object({', '\n METRICS_ENABLED: envBoolean(true),'],
|
|
35
|
+
],
|
|
36
|
+
'server/src/config/rate-limit.config.ts': [
|
|
37
|
+
[" ADMIN_DEFAULT: routeLimit('ADMIN_DEFAULT', 30, '1m'),", "\n METRICS_INGESTION: routeLimit('METRICS_INGESTION', 120, '1m'),"],
|
|
38
|
+
],
|
|
39
|
+
'server/src/config/__tests__/rate-limit.config.test.ts': [
|
|
40
|
+
[' ADMIN_DEFAULT: { max: 30, timeWindow: MIN },', '\n METRICS_INGESTION: { max: 120, timeWindow: MIN },'],
|
|
41
|
+
],
|
|
42
|
+
'server/src/__tests__/routes.integration.test.ts': [
|
|
43
|
+
['const COVERED_ELSEWHERE: Record<string, string> = {', `\n 'POST /api/v1/metrics/web-vitals': '${coverage}',\n 'GET /api/v1/admin/metrics': '${coverage}',`],
|
|
44
|
+
],
|
|
45
|
+
'client/src/app/providers.tsx': [
|
|
46
|
+
["import { Toaster } from 'sonner';", "\nimport { WebVitalsReporter } from '@/features/metrics/WebVitalsReporter';"],
|
|
47
|
+
[' <Toaster position="top-right" richColors />', '\n <WebVitalsReporter />'],
|
|
48
|
+
],
|
|
49
|
+
'client/src/lib/env.ts': [
|
|
50
|
+
['const envSchema = z.object({', "\n NEXT_PUBLIC_METRICS_SAMPLE_RATE: z.preprocess((value) => value === '' ? undefined : value, z.coerce.number().min(0).max(1).default(1)),"],
|
|
51
|
+
[' const result = envSchema.safeParse({', '\n NEXT_PUBLIC_METRICS_SAMPLE_RATE: process.env.NEXT_PUBLIC_METRICS_SAMPLE_RATE,'],
|
|
52
|
+
],
|
|
53
|
+
'client/Dockerfile': [
|
|
54
|
+
['ARG NEXT_PUBLIC_API_BASE_URL', '\nARG NEXT_PUBLIC_METRICS_SAMPLE_RATE=1'],
|
|
55
|
+
['ENV NEXT_PUBLIC_API_BASE_URL=$NEXT_PUBLIC_API_BASE_URL', '\nENV NEXT_PUBLIC_METRICS_SAMPLE_RATE=$NEXT_PUBLIC_METRICS_SAMPLE_RATE'],
|
|
56
|
+
],
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
async function payloadFiles(source, target) {
|
|
60
|
+
const entries = await fs.readdir(path.join(payload, source), { withFileTypes: true });
|
|
61
|
+
return (await Promise.all(entries.map((entry) => {
|
|
62
|
+
const nextSource = `${source}/${entry.name}`;
|
|
63
|
+
const nextTarget = `${target}/${entry.name}`;
|
|
64
|
+
return entry.isDirectory() ? payloadFiles(nextSource, nextTarget) : [[nextSource, nextTarget]];
|
|
65
|
+
}))).flat();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function patchAnchor(content, file, anchors, addition) {
|
|
69
|
+
const matches = [anchors].flat().filter((anchor) => content.includes(anchor));
|
|
70
|
+
const [anchor] = matches;
|
|
71
|
+
if (matches.length !== 1 || content.indexOf(anchor, content.indexOf(anchor) + anchor.length) !== -1) {
|
|
72
|
+
throw new Error(`Cannot install metrics: expected one integration anchor in ${file}. Review the module guide and integrate that customization manually.`);
|
|
73
|
+
}
|
|
74
|
+
const newline = content.includes('\r\n') ? '\r\n' : '\n';
|
|
75
|
+
return content.replace(anchor, anchor + addition.replaceAll('\n', newline));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function applyMetricsModule(root) {
|
|
79
|
+
return installModule(root, planMetrics);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function planMetrics({ read: readFile, exists, list }) {
|
|
83
|
+
const read = (file) => readFile(file, 'utf8');
|
|
84
|
+
const copies = [
|
|
85
|
+
...await payloadFiles('server', server),
|
|
86
|
+
...await payloadFiles('client', client),
|
|
87
|
+
['performance.md', 'server/docs/performance.md'],
|
|
88
|
+
];
|
|
89
|
+
const originalSchema = await read(schema);
|
|
90
|
+
const agents = await read('AGENTS.md');
|
|
91
|
+
if (await exists(marker)) {
|
|
92
|
+
const install = JSON.parse(await read(marker));
|
|
93
|
+
const migration = typeof install.migration === 'string' && /^\d{14}_metrics$/.test(install.migration)
|
|
94
|
+
? `${migrations}/${install.migration}/migration.sql` : null;
|
|
95
|
+
if (!migration || !await exists(migration) || !originalSchema.includes('model MetricBucket') ||
|
|
96
|
+
!agents.includes('## Performance metrics') ||
|
|
97
|
+
!(await Promise.all(copies.map(([, file]) => exists(file)))).every(Boolean)) {
|
|
98
|
+
throw new Error('The metrics installation is incomplete. Restore the missing module files or restore the pre-install state.');
|
|
99
|
+
}
|
|
100
|
+
for (const [file, anchors] of Object.entries(transforms)) {
|
|
101
|
+
const content = (await read(file)).replaceAll('\r\n', '\n');
|
|
102
|
+
if (anchors.some(([, addition]) => !content.includes(addition.trim()))) {
|
|
103
|
+
throw new Error(`The metrics installation is incomplete at ${file}. Restore its metrics integration before continuing.`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
if (!/provider\s*=\s*"mysql"/.test(originalSchema) || /\bMetricBucket\b|metric_buckets/.test(originalSchema) ||
|
|
109
|
+
agents.includes('## Performance metrics') || await exists(server) || await exists(client)) {
|
|
110
|
+
throw new Error('Metrics needs a compatible MySQL Tigra project with no partial metrics installation.');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Build the entire write set first. A missing/ambiguous anchor or migration
|
|
114
|
+
// collision must not leave a customized app half patched.
|
|
115
|
+
const migration = nextModuleMigration(await list(migrations), 'metrics');
|
|
116
|
+
copies.push(['prisma/migration.sql', `${migrations}/${migration}/migration.sql`]);
|
|
117
|
+
const writes = new Map();
|
|
118
|
+
for (const [source, target] of copies) {
|
|
119
|
+
if (await exists(target)) throw new Error(`Cannot install metrics: ${target} already exists.`);
|
|
120
|
+
writes.set(target, await fs.readFile(path.join(payload, source)));
|
|
121
|
+
}
|
|
122
|
+
for (const [file, anchors] of Object.entries(transforms)) {
|
|
123
|
+
let content = await read(file);
|
|
124
|
+
for (const [anchor, addition] of anchors) {
|
|
125
|
+
if (content.replaceAll('\r\n', '\n').includes(addition.trim())) {
|
|
126
|
+
throw new Error(`Cannot install metrics over an incomplete installation at ${file}.`);
|
|
127
|
+
}
|
|
128
|
+
content = patchAnchor(content, file, anchor, addition);
|
|
129
|
+
}
|
|
130
|
+
writes.set(file, content);
|
|
131
|
+
}
|
|
132
|
+
writes.set(schema, `${originalSchema.trimEnd()}\n\n${await fs.readFile(path.join(payload, 'prisma/metric-bucket.prisma'), 'utf8')}`);
|
|
133
|
+
writes.set('AGENTS.md', `${agents.trimEnd()}\n\n${instruction}\n`);
|
|
134
|
+
for (const side of ['server', 'client']) {
|
|
135
|
+
const setting = side === 'server' ? 'METRICS_ENABLED=true' : 'NEXT_PUBLIC_METRICS_SAMPLE_RATE=1';
|
|
136
|
+
for (const example of ['.env.example', '.env.example.production']) {
|
|
137
|
+
const file = `${side}/${example}`;
|
|
138
|
+
const content = await read(file);
|
|
139
|
+
if (content.includes(setting.split('=')[0])) throw new Error(`Metrics configuration already exists in ${file}.`);
|
|
140
|
+
writes.set(file, `${content.trimEnd()}\n\n# Optional performance metrics\n${setting}\n`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
writes.set(marker, JSON.stringify({ migration }, null, 2) + '\n');
|
|
144
|
+
return writes;
|
|
145
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { chmod, lstat, mkdir, readdir, realpath, rename, rmdir, rm } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
// Existing Tigra checkouts already ignore .env.*.local. Recovery can contain
|
|
6
|
+
// original dotenv bytes and must be private there before a scaffold upgrade.
|
|
7
|
+
export const INSTALL_PREFIX = '.env.create-tigra-install';
|
|
8
|
+
export const INSTALL_STATE = `${INSTALL_PREFIX}.local`;
|
|
9
|
+
|
|
10
|
+
export function privateInstallerPath(root, label) {
|
|
11
|
+
return path.join(root, `${INSTALL_PREFIX}-${label}-${randomUUID()}.local`);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function pathParts(relative) {
|
|
15
|
+
const parts = relative.split(/[\\/]/);
|
|
16
|
+
if (parts.some((part) => !part || part === '.' || part === '..' || /[:\0]/.test(part) ||
|
|
17
|
+
(process.platform === 'win32' && (/[. ]$/.test(part) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))))) {
|
|
18
|
+
throw new Error('Invalid project-relative path');
|
|
19
|
+
}
|
|
20
|
+
return parts;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function nextModuleMigration(entries, module, now = new Date()) {
|
|
24
|
+
const names = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
25
|
+
const suffix = `_${module}`;
|
|
26
|
+
const latest = names.at(-1);
|
|
27
|
+
if (names.some((name) => name.endsWith(suffix))) throw new Error(`A ${module} migration already exists.`);
|
|
28
|
+
const prefix = (date) => date.toISOString().slice(0, 19).replace(/\D/g, '');
|
|
29
|
+
let candidate = `${prefix(now)}${suffix}`;
|
|
30
|
+
const date = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_/.exec(latest ?? '');
|
|
31
|
+
if (date && date[0].slice(0, -1) >= prefix(now)) {
|
|
32
|
+
const [, year, month, day, hour, minute, second] = date;
|
|
33
|
+
const previous = Date.parse(`${year}-${month}-${day}T${hour}:${minute}:${second}Z`);
|
|
34
|
+
if (Number.isFinite(previous)) candidate = `${prefix(new Date(previous + 1000))}${suffix}`;
|
|
35
|
+
}
|
|
36
|
+
if (latest && latest >= candidate) throw new Error(`Cannot place the ${module} migration after the existing migrations.`);
|
|
37
|
+
return candidate;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Inspect every existing component, including the leaf, without following links. */
|
|
41
|
+
export async function projectPath(root, relative, kind) {
|
|
42
|
+
const parts = pathParts(relative);
|
|
43
|
+
let current = root;
|
|
44
|
+
for (const [index, part] of parts.entries()) {
|
|
45
|
+
current = path.join(current, part);
|
|
46
|
+
const leaf = index === parts.length - 1;
|
|
47
|
+
const stat = await lstat(current).catch((error) => {
|
|
48
|
+
if (error.code !== 'ENOENT') throw error;
|
|
49
|
+
return null;
|
|
50
|
+
});
|
|
51
|
+
if (!stat) return { file: path.join(root, ...parts), stat: null };
|
|
52
|
+
const valid = leaf && kind !== 'directory'
|
|
53
|
+
? (stat.isFile() && stat.nlink === 1) || (!kind && stat.isDirectory())
|
|
54
|
+
: stat.isDirectory();
|
|
55
|
+
if (stat.isSymbolicLink() || !valid) throw new Error(`Unsafe project path: ${relative}`);
|
|
56
|
+
if (leaf) return { file: current, stat };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function createParents(root, relative) {
|
|
61
|
+
const parts = pathParts(relative);
|
|
62
|
+
for (let length = 1; length < parts.length; length++) {
|
|
63
|
+
const dir = await projectPath(root, parts.slice(0, length).join('/'), 'directory');
|
|
64
|
+
if (!dir.stat) await mkdir(dir.file);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Keep failed generation private. A nonempty destination always wins a competing rename. */
|
|
69
|
+
export async function stageScaffold(parent, name, generate) {
|
|
70
|
+
const root = await realpath(parent);
|
|
71
|
+
const target = await projectPath(root, name, 'directory');
|
|
72
|
+
if (target.stat && (await readdir(target.file)).length) {
|
|
73
|
+
throw new Error(`Directory "${name}" already exists and is not empty.`);
|
|
74
|
+
}
|
|
75
|
+
const stage = privateInstallerPath(root, 'scaffold');
|
|
76
|
+
await mkdir(stage, { mode: 0o700 });
|
|
77
|
+
try {
|
|
78
|
+
await generate(stage);
|
|
79
|
+
const current = await projectPath(root, name, 'directory');
|
|
80
|
+
if (current.stat && (!target.stat || current.stat.dev !== target.stat.dev || current.stat.ino !== target.stat.ino)) {
|
|
81
|
+
throw new Error(`Directory "${name}" changed during generation.`);
|
|
82
|
+
}
|
|
83
|
+
// Keep the scratch tree private until publication and give the finished
|
|
84
|
+
// checkout the same directory permissions as an ordinary scaffold.
|
|
85
|
+
await chmod(stage, (current.stat?.mode ?? (0o777 & ~process.umask())) & 0o777);
|
|
86
|
+
if (current.stat) {
|
|
87
|
+
// rmdir refuses a directory another process has populated while we generated.
|
|
88
|
+
await rmdir(current.file);
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
await rename(stage, target.file);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (current.stat) await mkdir(target.file).catch(() => {});
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
} finally {
|
|
97
|
+
await rm(stage, { recursive: true, force: true });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Investigating server errors and warnings
|
|
2
|
+
|
|
3
|
+
Start with the most recent completed UTC hour unless the user gives a range.
|
|
4
|
+
Check errors first and repeat for warnings when relevant. Use the app checkout
|
|
5
|
+
and its configured instance. Read the diagnostics through either path below.
|
|
6
|
+
Report observed counts and samples separately from what the source suggests
|
|
7
|
+
caused them. Use the recorded release to locate the matching source revision.
|
|
8
|
+
|
|
9
|
+
## Read with the shared MySQL skill
|
|
10
|
+
|
|
11
|
+
Use `seed-mysql-control` with the application's existing read-only access.
|
|
12
|
+
The example uses PowerShell. Set the checkout, instance and UTC hour for the
|
|
13
|
+
project under investigation. The hour format is `YYYY-MM-DD HH:00:00`.
|
|
14
|
+
|
|
15
|
+
```powershell
|
|
16
|
+
$tool = 'C:/Users/seed/Documents/GitHub/seed-plugins/mysql/mysql_control.py'
|
|
17
|
+
$app = 'C:/path/to/generated-app'
|
|
18
|
+
$instance = 'kotiko'
|
|
19
|
+
$hour = (Get-Date).ToUniversalTime().AddHours(-1).ToString('yyyy-MM-dd HH:00:00')
|
|
20
|
+
uv run --script $tool select $instance --repo-root $app --table diagnostic_hourly_top --columns hour_start,severity,group_rank,group_id,occurrence_count,first_seen,last_seen,source,label,code,message,frames,release --where "hour_start=$hour" --where 'severity=error' --limit 10
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Sort returned rows by `group_rank`. Use `severity=warning` for warnings. The
|
|
24
|
+
view returns at most ten groups for each exact hour and severity. Use the
|
|
25
|
+
admin API for custom intervals and for groups outside the hourly top ten.
|
|
26
|
+
|
|
27
|
+
The shared toolkit's existing reader has schema-wide read access. For a
|
|
28
|
+
diagnostics-only SQL principal, grant `SELECT` on `diagnostic_hourly_top`
|
|
29
|
+
alone. Its fixed projection runs as the app's stable migration account. Use
|
|
30
|
+
the bundled `modules/diagnostics/prisma/diagnostic-hourly-view.sql` as a new
|
|
31
|
+
migration when retrofitting an installed diagnostics view. Keep the applied
|
|
32
|
+
migration and run the new one with a schema-scoped account that will retain
|
|
33
|
+
read access to `diagnostic_buckets`.
|
|
34
|
+
|
|
35
|
+
## Read with an existing admin session
|
|
36
|
+
|
|
37
|
+
Use the project's existing admin session cookie jar. Do not print or copy the
|
|
38
|
+
cookies into diagnostic evidence. Replace the server origin and times below.
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
curl -fsS --cookie "$ADMIN_COOKIE_JAR" --get "$API_ORIGIN/api/v1/admin/diagnostics" \
|
|
42
|
+
--data-urlencode 'from=2026-07-21T12:00:00Z' \
|
|
43
|
+
--data-urlencode 'to=2026-07-21T13:00:00Z' \
|
|
44
|
+
--data-urlencode 'severity=error' --data-urlencode 'limit=10'
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`data.groups` is ranked by count, then group ID. Use `groupId` for one group
|
|
48
|
+
and `nextCursor` for more results with the same filters. `from` is inclusive,
|
|
49
|
+
`to` is exclusive, and both must identify five-minute boundaries with an
|
|
50
|
+
explicit timezone. A range can span up to seven days. Counts can change if
|
|
51
|
+
more batches arrive between requests. A valid empty range returns no groups.
|
|
52
|
+
MySQL can cancel a read at 1.5 seconds. On `503 DIAGNOSTICS_QUERY_TIMEOUT`,
|
|
53
|
+
retry with a narrower interval or a specific `groupId`.
|
|
54
|
+
|
|
55
|
+
Read `label`, `code`, `message`, and the first entry in `frames`. Open that
|
|
56
|
+
application-relative source file and inspect the function and line when known.
|
|
57
|
+
A null line means the stack came from compiled code without source maps. A
|
|
58
|
+
null release means the server commit was unavailable. The displayed sample and
|
|
59
|
+
release belong to the latest occurrence in the requested group and range.
|
|
60
|
+
When the commit is available locally, `git show <release>:server/<frame.file>`
|
|
61
|
+
opens the source at that release without switching branches.
|
|
62
|
+
|
|
63
|
+
## Maintain coverage
|
|
64
|
+
|
|
65
|
+
Unexpected request failures and failed recurring jobs are captured where the
|
|
66
|
+
scaffold handles them. Use `recordDiagnostic` from the diagnostics context
|
|
67
|
+
inside a request or job for a handled failure or an actionable warning. Use
|
|
68
|
+
a static operation name and add application-owned reason text to
|
|
69
|
+
`diagnosticMessages` when needed. Pass the original Error if it may be
|
|
70
|
+
rethrown. Keep all customer data and variable text out of labels and messages.
|
|
71
|
+
|
|
72
|
+
Counts persist in five-minute contributions. Writes normally flush within 15
|
|
73
|
+
seconds. Outages and shutdown can delay or drop samples after the bounded
|
|
74
|
+
buffer fills. Missing data alone does not establish that no failures occurred.
|
|
75
|
+
Diagnostics has no automatic expiry.
|