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
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,49 @@
|
|
|
3
3
|
A generated project never changes after it is created: these notes say what new projects get. To bring an older
|
|
4
4
|
project along, port the changes you need; the guides in [docs/](docs/) cover the ones that need care.
|
|
5
5
|
|
|
6
|
+
## 5.0.0 (2026-11-17)
|
|
7
|
+
|
|
8
|
+
### Compatibility
|
|
9
|
+
|
|
10
|
+
- The email-verification installer requires the new account transaction, mail queue, and client session code. Follow the [upgrade guide](docs/account-ban-vs-email-verification.md) before adding it to a 4.x project.
|
|
11
|
+
- The [server deployment guide](template/server/docs/deployment.md) describes the forward migrations and coordinated rollout for existing projects adopting session rotation, avatar cleanup, and account purge changes.
|
|
12
|
+
- Generated list endpoints cap page numbers at 1,000 and page sizes at 100. The admin and auth endpoints also enforce current account and session state during writes.
|
|
13
|
+
|
|
14
|
+
### Changes
|
|
15
|
+
|
|
16
|
+
- Queue password recovery and verification email in Redis. Make link issuance and redemption consistent across replicas, and commit credential revocation with account changes.
|
|
17
|
+
- Protect the last eligible admin, keep ordinary rate limits in place, and exempt authorized admin routes from quota counters and strikes.
|
|
18
|
+
- Keep browser sessions in sync across tabs and account switches. Prevent caching of authenticated responses and make avatar replacement and deletion visible on subsequent requests.
|
|
19
|
+
- Make scaffolding and optional module installation recoverable and keep local environment and build files out of the npm package. Test all eight combinations of email verification, metrics, and diagnostics in scaffold CI.
|
|
20
|
+
- Tighten outbound HTTP safeguards, health probes, and log redaction. Bound diagnostics queries and keep referrer and cookie data out of Web Vitals submissions.
|
|
21
|
+
|
|
22
|
+
## 4.1.0 (2026-11-10)
|
|
23
|
+
|
|
24
|
+
- Add optional performance metrics for Fastify requests, Node runtime health, named operations, and Next.js Web Vitals. The module stores five-minute aggregates in MySQL and provides a read-only admin API.
|
|
25
|
+
- Add optional error and warning tracking with sanitized diagnostic samples, an hourly MySQL view, and a read-only admin API for agent investigations.
|
|
26
|
+
- Choose either module independently in the wizard or install it later with `npx create-tigra add metrics` or `npx create-tigra add diagnostics`. Each module adds its own migration and maintenance guidance.
|
|
27
|
+
- Expand generated agent guidance on architecture and reuse. Search the relevant client or server code for the closest behavior and follow imports and callers before adding a new implementation.
|
|
28
|
+
|
|
29
|
+
- Focus rings show only for keyboard users. Radix menus and selects cancel the mouse press on their trigger and then
|
|
30
|
+
move focus by script, so Chrome treated mouse use as keyboard use and drew focus rings (for example on a menu item
|
|
31
|
+
under the pointer) until the first ordinary click. The client now keeps `<html data-input="pointer" | "keyboard">`
|
|
32
|
+
(`lib/input-modality.ts`, mounted by `components/common/InputModalityTracker.tsx` in the root layout), Tailwind's
|
|
33
|
+
`focus-visible:` variant stays off in pointer mode, and a global rule drops plain-CSS focus outlines in pointer
|
|
34
|
+
mode. Text fields still show focus for mouse users too.
|
|
35
|
+
- Keyboard focus has one quiet style everywhere: a 1px accent line on the element's own edge and a faint accent tint
|
|
36
|
+
inside, with nothing drawn outside the element (it replaces the 3px half-transparent rings). Accent-filled controls
|
|
37
|
+
(primary and destructive buttons, hand-styled `bg-primary` / `bg-destructive` links) get the edge plus a 1px
|
|
38
|
+
page-coloured line inside it, since their fill is the accent; menu items and select options keep their highlight
|
|
39
|
+
only.
|
|
40
|
+
- Text fields lose the 3px glow too: focus turns the field's own border accent, an invalid field's border is red, and a
|
|
41
|
+
focused invalid field also gets a faint red tint inside, so focus stays visible on a field with an error.
|
|
42
|
+
- To port into an older project: copy those two files, add `data-input="pointer"` to `<html>` and mount the tracker
|
|
43
|
+
in `app/layout.tsx`, copy the `@custom-variant focus-visible` line and the four focus rules at the end of
|
|
44
|
+
`app/globals.css` ("Focus rings", "Keyboard focus", "Filled controls", "Text fields"), and change any `focus:ring`
|
|
45
|
+
(for example a dialog's close button) to `focus-visible:ring`. In `components/ui/input.tsx` (and a textarea, if
|
|
46
|
+
you have one) keep only `focus-visible:border-ring` and `aria-invalid:border-destructive` from the focus and
|
|
47
|
+
invalid classes. Remove any own `:focus-visible { outline }` a menu item or option has.
|
|
48
|
+
|
|
6
49
|
## 4.0.1 (2026-10-20)
|
|
7
50
|
|
|
8
51
|
Documentation only, no code changes.
|
package/README.md
CHANGED
|
@@ -251,17 +251,35 @@ server replica each runs them too, which is safe.
|
|
|
251
251
|
|
|
252
252
|
## Adding a module later
|
|
253
253
|
|
|
254
|
-
Modules add a feature to an existing project.
|
|
254
|
+
Modules add a feature to an existing project. The creation wizard asks about
|
|
255
|
+
email verification, performance metrics, and error and warning tracking independently:
|
|
255
256
|
|
|
256
257
|
```bash
|
|
257
258
|
cd my-app # the folder that holds server/ and client/
|
|
258
259
|
npx create-tigra add email-verification
|
|
260
|
+
npx create-tigra add metrics
|
|
261
|
+
npx create-tigra add diagnostics
|
|
259
262
|
```
|
|
260
263
|
|
|
261
|
-
|
|
264
|
+
Run one module installer at a time per checkout. If it is interrupted, rerun the command after the prior process exits so the installer can recover before applying changes. If recovery reports an intervening edit, save that edit elsewhere and restore the named file to its pre-install or installer-written version before retrying.
|
|
265
|
+
|
|
266
|
+
The email verification module adds the routes (`POST /auth/send-verification`, `POST /auth/verify-account`), their integration
|
|
262
267
|
tests, the client's `useVerifyAccount` / `useSendVerification` hooks and service, and sets `REQUIRE_USER_VERIFICATION=true` in `server/.env`.
|
|
263
268
|
Then set `RESEND_API_KEY` in `server/.env` and restart the server. Answering "yes" to the email question when you
|
|
264
|
-
create a project does the same.
|
|
269
|
+
create a project does the same. The installer uses Tigra’s shared account transaction and Redis mail queue.
|
|
270
|
+
See the [email verification upgrade guide](docs/account-ban-vs-email-verification.md) for earlier projects.
|
|
271
|
+
|
|
272
|
+
The metrics module collects request and operation timings, Node runtime
|
|
273
|
+
measurements, and browser Web Vitals into five-minute MySQL buckets. Apply the
|
|
274
|
+
added Prisma migration and regenerate the Prisma client before starting the
|
|
275
|
+
server. The generated `server/docs/performance.md` explains the admin API,
|
|
276
|
+
sampling, and how to extend coverage when adding features.
|
|
277
|
+
|
|
278
|
+
The diagnostics module groups unexpected server errors and actionable warnings
|
|
279
|
+
with safe messages and source frames. Apply the additive Prisma migration and
|
|
280
|
+
regenerate the client before starting the server. The generated
|
|
281
|
+
`server/docs/diagnostics.md` gives agents copyable commands for the read-only
|
|
282
|
+
MySQL view and the admin API. Diagnostic history has no automatic expiry.
|
|
265
283
|
|
|
266
284
|
## Documentation
|
|
267
285
|
|
package/bin/create-tigra.js
CHANGED
|
@@ -8,6 +8,7 @@ import fs from 'fs-extra';
|
|
|
8
8
|
import path from 'path';
|
|
9
9
|
import { fileURLToPath } from 'url';
|
|
10
10
|
import crypto from 'crypto';
|
|
11
|
+
import { projectPath, stageScaffold } from '../lib/project-files.js';
|
|
11
12
|
|
|
12
13
|
const __filename = fileURLToPath(import.meta.url);
|
|
13
14
|
const __dirname = path.dirname(__filename);
|
|
@@ -45,9 +46,7 @@ const SKIP_PATTERNS = [
|
|
|
45
46
|
'.next',
|
|
46
47
|
'dist',
|
|
47
48
|
'out',
|
|
48
|
-
'.
|
|
49
|
-
'.env.local',
|
|
50
|
-
'.env.*.local',
|
|
49
|
+
'.npmignore',
|
|
51
50
|
// package-lock.json is NOT skipped: new projects get the template's tested
|
|
52
51
|
// lockfiles, written with the npm in the Dockerfiles' image, so the first
|
|
53
52
|
// `npm ci` (locally and in Docker) installs exactly the versions we tested.
|
|
@@ -122,15 +121,11 @@ function appRuntimeWarnings() {
|
|
|
122
121
|
|
|
123
122
|
function shouldSkip(filePath) {
|
|
124
123
|
const parts = filePath.split(path.sep);
|
|
125
|
-
return parts.some((part) =>
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
}
|
|
131
|
-
return part === pattern;
|
|
132
|
-
})
|
|
133
|
-
);
|
|
124
|
+
return parts.some((part) => {
|
|
125
|
+
const name = part.toLowerCase();
|
|
126
|
+
return SKIP_PATTERNS.includes(name) ||
|
|
127
|
+
(/^\.env(?:\.|$)/.test(name) && !['.env.example', '.env.example.production'].includes(part));
|
|
128
|
+
});
|
|
134
129
|
}
|
|
135
130
|
|
|
136
131
|
async function copyTemplate(templateDir, targetDir) {
|
|
@@ -152,10 +147,14 @@ async function copyTemplate(templateDir, targetDir) {
|
|
|
152
147
|
const destPath = path.join(targetDir, destName);
|
|
153
148
|
|
|
154
149
|
if (entry.isDirectory()) {
|
|
155
|
-
await
|
|
150
|
+
await projectPath(targetDir, destName, 'directory');
|
|
151
|
+
await fs.mkdir(destPath);
|
|
156
152
|
await copyTemplate(srcPath, destPath);
|
|
153
|
+
} else if (entry.isFile()) {
|
|
154
|
+
await projectPath(targetDir, destName, 'file');
|
|
155
|
+
await fs.copyFile(srcPath, destPath, fs.constants.COPYFILE_EXCL);
|
|
157
156
|
} else {
|
|
158
|
-
|
|
157
|
+
throw new Error(`Unsupported scaffold template entry: ${relativePath}`);
|
|
159
158
|
}
|
|
160
159
|
}
|
|
161
160
|
}
|
|
@@ -214,11 +213,11 @@ function registerAddCommand(program) {
|
|
|
214
213
|
console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`) + chalk.dim(' — add module'));
|
|
215
214
|
console.log();
|
|
216
215
|
|
|
217
|
-
const projectDir = process.cwd();
|
|
216
|
+
const projectDir = await fs.realpath(process.cwd());
|
|
218
217
|
|
|
219
218
|
// Detect if we're inside a Tigra project
|
|
220
|
-
const hasServer = await
|
|
221
|
-
const hasClient = await
|
|
219
|
+
const { stat: hasServer } = await projectPath(projectDir, 'server/src/modules/auth', 'directory');
|
|
220
|
+
const { stat: hasClient } = await projectPath(projectDir, 'client/src/features/auth', 'directory');
|
|
222
221
|
|
|
223
222
|
if (!hasServer || !hasClient) {
|
|
224
223
|
console.error(chalk.red(' This does not appear to be a Tigra project.'));
|
|
@@ -227,7 +226,7 @@ function registerAddCommand(program) {
|
|
|
227
226
|
process.exit(1);
|
|
228
227
|
}
|
|
229
228
|
|
|
230
|
-
const availableModules = ['email-verification'];
|
|
229
|
+
const availableModules = ['email-verification', 'metrics', 'diagnostics'];
|
|
231
230
|
|
|
232
231
|
if (!availableModules.includes(moduleName)) {
|
|
233
232
|
console.error(chalk.red(` Unknown module: "${moduleName}"`));
|
|
@@ -240,17 +239,40 @@ function registerAddCommand(program) {
|
|
|
240
239
|
process.exit(1);
|
|
241
240
|
}
|
|
242
241
|
|
|
243
|
-
if (moduleName === '
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
242
|
+
if (moduleName === 'metrics') {
|
|
243
|
+
const spinner = ora('Adding performance metrics module...').start();
|
|
244
|
+
try {
|
|
245
|
+
const { applyMetricsModule } = await import('../lib/patchers/metrics.patcher.js');
|
|
246
|
+
const installed = await applyMetricsModule(projectDir);
|
|
247
|
+
spinner.succeed(installed ? 'Performance metrics module added!' : 'Performance metrics is already installed.');
|
|
248
|
+
if (installed) {
|
|
249
|
+
console.log(' Apply the Prisma migration and regenerate the client from server/.');
|
|
250
|
+
console.log(' See server/docs/performance.md for settings and the admin API.');
|
|
251
|
+
}
|
|
252
|
+
} catch (error) {
|
|
253
|
+
spinner.fail('Failed to add performance metrics');
|
|
254
|
+
console.error(chalk.red(`\n ${error.message}\n`));
|
|
255
|
+
process.exit(1);
|
|
252
256
|
}
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
253
259
|
|
|
260
|
+
if (moduleName === 'diagnostics') {
|
|
261
|
+
const spinner = ora('Adding error and warning diagnostics...').start();
|
|
262
|
+
try {
|
|
263
|
+
const { applyDiagnosticsModule } = await import('../lib/patchers/diagnostics.patcher.js');
|
|
264
|
+
const installed = await applyDiagnosticsModule(projectDir);
|
|
265
|
+
spinner.succeed(installed ? 'Diagnostics module added!' : 'Diagnostics is already installed.');
|
|
266
|
+
if (installed) console.log(' Apply the Prisma migration and regenerate the client from server/. See server/docs/diagnostics.md.');
|
|
267
|
+
} catch (error) {
|
|
268
|
+
spinner.fail('Failed to add diagnostics');
|
|
269
|
+
console.error(chalk.red(`\n ${error.message}\n`));
|
|
270
|
+
process.exit(1);
|
|
271
|
+
}
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (moduleName === 'email-verification') {
|
|
254
276
|
const spinner = ora('Adding email verification module...').start();
|
|
255
277
|
|
|
256
278
|
try {
|
|
@@ -259,7 +281,11 @@ function registerAddCommand(program) {
|
|
|
259
281
|
);
|
|
260
282
|
// Also switches REQUIRE_USER_VERIFICATION on (env.ts default + every
|
|
261
283
|
// server env file), exactly as at scaffold time.
|
|
262
|
-
await applyEmailVerificationModule(projectDir);
|
|
284
|
+
const installed = await applyEmailVerificationModule(projectDir);
|
|
285
|
+
if (!installed) {
|
|
286
|
+
spinner.succeed('Email verification is already installed in this project.');
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
263
289
|
|
|
264
290
|
spinner.succeed('Email verification module added!');
|
|
265
291
|
} catch (error) {
|
|
@@ -280,7 +306,7 @@ function registerAddCommand(program) {
|
|
|
280
306
|
console.log(dim(' client/src/features/auth/hooks/useVerification.ts'));
|
|
281
307
|
console.log();
|
|
282
308
|
console.log(green(' ✓ ') + 'Files patched:');
|
|
283
|
-
console.log(dim(' auth.routes.ts, auth.schemas.ts, auth.service.ts,
|
|
309
|
+
console.log(dim(' auth.routes.ts, auth.schemas.ts, auth.service.ts, jobs/index.ts'));
|
|
284
310
|
console.log(dim(' rate-limit.config.ts, api-endpoints.ts, error.ts, useAuth.ts'));
|
|
285
311
|
console.log(dim(' postman/collection.json'));
|
|
286
312
|
console.log();
|
|
@@ -340,10 +366,11 @@ async function main() {
|
|
|
340
366
|
|
|
341
367
|
projectName = toKebabCase(projectName);
|
|
342
368
|
|
|
343
|
-
const
|
|
369
|
+
const parent = await fs.realpath(process.cwd());
|
|
370
|
+
const { file: targetDir, stat: targetStat } = await projectPath(parent, projectName, 'directory');
|
|
344
371
|
|
|
345
372
|
// Check if directory exists and is non-empty
|
|
346
|
-
if (
|
|
373
|
+
if (targetStat) {
|
|
347
374
|
const files = await fs.readdir(targetDir);
|
|
348
375
|
if (files.length > 0) {
|
|
349
376
|
console.error(chalk.red(`\n Directory "${projectName}" already exists and is not empty.\n`));
|
|
@@ -362,6 +389,26 @@ async function main() {
|
|
|
362
389
|
hint: 'Users must verify email before accessing the app',
|
|
363
390
|
});
|
|
364
391
|
|
|
392
|
+
const { enableMetrics } = await ask({
|
|
393
|
+
type: 'toggle',
|
|
394
|
+
name: 'enableMetrics',
|
|
395
|
+
message: 'Enable performance metrics?',
|
|
396
|
+
initial: false,
|
|
397
|
+
active: 'Yes',
|
|
398
|
+
inactive: 'No',
|
|
399
|
+
hint: 'Collect request, runtime and browser measurements',
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
const { enableDiagnostics } = await ask({
|
|
403
|
+
type: 'toggle',
|
|
404
|
+
name: 'enableDiagnostics',
|
|
405
|
+
message: 'Enable error and warning tracking?',
|
|
406
|
+
initial: false,
|
|
407
|
+
active: 'Yes',
|
|
408
|
+
inactive: 'No',
|
|
409
|
+
hint: 'Store grouped server diagnostics for agents',
|
|
410
|
+
});
|
|
411
|
+
|
|
365
412
|
// Generate random port offset (1-200) so multiple projects don't conflict
|
|
366
413
|
const portOffset = crypto.randomInt(1, 201);
|
|
367
414
|
|
|
@@ -386,44 +433,53 @@ async function main() {
|
|
|
386
433
|
const spinner = ora('Scaffolding project...').start();
|
|
387
434
|
|
|
388
435
|
try {
|
|
389
|
-
await
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
436
|
+
await stageScaffold(parent, projectName, async (stage) => {
|
|
437
|
+
await copyTemplate(TEMPLATE_DIR, stage);
|
|
438
|
+
|
|
439
|
+
// Replace template variables in specific files
|
|
440
|
+
for (const filePath of FILES_TO_REPLACE) {
|
|
441
|
+
const fullPath = path.join(stage, filePath);
|
|
442
|
+
if (await fs.pathExists(fullPath)) {
|
|
443
|
+
const content = await fs.readFile(fullPath, 'utf-8');
|
|
444
|
+
const replaced = replaceVariables(content, variables);
|
|
445
|
+
await fs.writeFile(fullPath, replaced, 'utf-8');
|
|
446
|
+
}
|
|
399
447
|
}
|
|
400
|
-
}
|
|
401
448
|
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
449
|
+
// Generate .env from .env.example (so users don't have to copy manually).
|
|
450
|
+
// The real JWT secret is injected HERE and only here — .env is
|
|
451
|
+
// git-ignored, while .env.example is committed and must keep the
|
|
452
|
+
// CHANGE_ME placeholder.
|
|
453
|
+
const jwtSecret = crypto.randomBytes(48).toString('hex');
|
|
454
|
+
for (const envExample of ['server/.env.example', 'client/.env.example']) {
|
|
455
|
+
const examplePath = path.join(stage, envExample);
|
|
456
|
+
const envPath = path.join(stage, envExample.replace('.env.example', '.env'));
|
|
457
|
+
if (await fs.pathExists(examplePath)) {
|
|
458
|
+
const content = await fs.readFile(examplePath, 'utf-8');
|
|
459
|
+
await fs.writeFile(
|
|
460
|
+
envPath,
|
|
461
|
+
content.replaceAll(JWT_SECRET_PLACEHOLDER, jwtSecret),
|
|
462
|
+
{ encoding: 'utf-8', mode: 0o600, flag: 'wx' },
|
|
463
|
+
);
|
|
464
|
+
}
|
|
417
465
|
}
|
|
418
|
-
}
|
|
419
466
|
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
467
|
+
// Apply email verification module if selected. The template ships with
|
|
468
|
+
// REQUIRE_USER_VERIFICATION off everywhere (no verify route without the
|
|
469
|
+
// module); the patcher switches it on in env.ts and every env file.
|
|
470
|
+
if (enableVerification) {
|
|
471
|
+
const { applyEmailVerificationModule } = await import('../lib/patchers/email-verification.patcher.js');
|
|
472
|
+
await applyEmailVerificationModule(stage);
|
|
473
|
+
}
|
|
474
|
+
if (enableMetrics) {
|
|
475
|
+
const { applyMetricsModule } = await import('../lib/patchers/metrics.patcher.js');
|
|
476
|
+
await applyMetricsModule(stage);
|
|
477
|
+
}
|
|
478
|
+
if (enableDiagnostics) {
|
|
479
|
+
const { applyDiagnosticsModule } = await import('../lib/patchers/diagnostics.patcher.js');
|
|
480
|
+
await applyDiagnosticsModule(stage);
|
|
481
|
+
}
|
|
482
|
+
});
|
|
427
483
|
|
|
428
484
|
spinner.succeed('Project scaffolded successfully!');
|
|
429
485
|
} catch (error) {
|
|
@@ -485,6 +541,16 @@ async function main() {
|
|
|
485
541
|
console.log(dim(' Set RESEND_API_KEY in server/.env to send emails'));
|
|
486
542
|
console.log();
|
|
487
543
|
}
|
|
544
|
+
if (enableMetrics) {
|
|
545
|
+
console.log(dim(' Performance metrics: ') + green('enabled after migration'));
|
|
546
|
+
console.log(dim(' See server/docs/performance.md for the admin API and collection settings'));
|
|
547
|
+
console.log();
|
|
548
|
+
}
|
|
549
|
+
if (enableDiagnostics) {
|
|
550
|
+
console.log(dim(' Error and warning diagnostics: ') + green('enabled after migration'));
|
|
551
|
+
console.log(dim(' See server/docs/diagnostics.md for agent read commands'));
|
|
552
|
+
console.log();
|
|
553
|
+
}
|
|
488
554
|
console.log(dim(' Tip: ') + 'npm run docker:down' + dim(' to stop infrastructure'));
|
|
489
555
|
console.log();
|
|
490
556
|
console.log(dim(' Happy coding! 🚀'));
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rmdir, rm, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createParents, INSTALL_PREFIX, INSTALL_STATE, pathParts, privateInstallerPath, projectPath } from './project-files.js';
|
|
5
|
+
|
|
6
|
+
const uuid = '[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}';
|
|
7
|
+
const ownerPattern = new RegExp(`^owner-([1-9][0-9]*)-${uuid}$`);
|
|
8
|
+
const journalPattern = new RegExp(`^${uuid}$`);
|
|
9
|
+
const digestPattern = /^[a-f0-9]{64}$/;
|
|
10
|
+
const hash = (buffer) => buffer === null ? null : createHash('sha256').update(buffer).digest('hex');
|
|
11
|
+
const folder = (file) => path.posix.dirname(file);
|
|
12
|
+
const stateFile = (file) => `${INSTALL_STATE}/${file}`;
|
|
13
|
+
|
|
14
|
+
function normalizedFile(relative) {
|
|
15
|
+
const parts = pathParts(relative);
|
|
16
|
+
if (parts.some((part) => part.toLowerCase().startsWith(INSTALL_PREFIX))) {
|
|
17
|
+
throw new Error('An installer plan cannot change installer state');
|
|
18
|
+
}
|
|
19
|
+
return parts.join('/');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function readSnapshot(root, file) {
|
|
23
|
+
const entry = await projectPath(root, file, 'file');
|
|
24
|
+
return entry.stat
|
|
25
|
+
? { before: await readFile(entry.file), mode: entry.stat.mode & 0o777 }
|
|
26
|
+
: { before: null, mode: null };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function ownerAlive(pid) {
|
|
30
|
+
try {
|
|
31
|
+
process.kill(pid, 0);
|
|
32
|
+
return true;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (error.code === 'ESRCH') return false;
|
|
35
|
+
return true; // Insufficient permissions or ambiguous ownership must not steal a lock.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Publish a nonempty directory so no process can observe a lock without an owner.
|
|
40
|
+
* Recovery claims a dead owner's unique filename with one rename. */
|
|
41
|
+
async function takeLock(root) {
|
|
42
|
+
const mine = `owner-${process.pid}-${randomUUID()}`;
|
|
43
|
+
const candidate = privateInstallerPath(root, 'candidate');
|
|
44
|
+
await mkdir(candidate, { mode: 0o700 });
|
|
45
|
+
try {
|
|
46
|
+
await writeFile(path.join(candidate, mine), '', { flag: 'wx', mode: 0o600 });
|
|
47
|
+
const lock = await projectPath(root, INSTALL_STATE, 'directory');
|
|
48
|
+
if (!lock.stat) {
|
|
49
|
+
try {
|
|
50
|
+
await rename(candidate, lock.file);
|
|
51
|
+
return lock.file;
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (!(await projectPath(root, INSTALL_STATE, 'directory')).stat) throw error;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const owners = (await readdir(lock.file)).filter((entry) => entry.startsWith('owner-'));
|
|
58
|
+
const owner = owners.length === 1 && ownerPattern.exec(owners[0]);
|
|
59
|
+
const pid = Number(owner?.[1]);
|
|
60
|
+
if (!owner || !Number.isSafeInteger(pid) || pid > 0x7fffffff || ownerAlive(pid)) {
|
|
61
|
+
throw new Error('Another installer owns this project lock. Retry after it exits.');
|
|
62
|
+
}
|
|
63
|
+
const prior = await projectPath(root, stateFile(owner[0]), 'file');
|
|
64
|
+
if (!prior.stat) throw new Error('The installer lock changed. Retry the command.');
|
|
65
|
+
// Only one requester can move this exact filename, even if both read the old PID.
|
|
66
|
+
await rename(prior.file, path.join(lock.file, mine)).catch((error) => {
|
|
67
|
+
if (error.code === 'ENOENT') throw new Error('Another installer claimed recovery. Retry after it exits.');
|
|
68
|
+
throw error;
|
|
69
|
+
});
|
|
70
|
+
return lock.file;
|
|
71
|
+
} finally {
|
|
72
|
+
await rm(candidate, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function tempFile(file, id, index) {
|
|
77
|
+
return path.posix.join(folder(file), `${INSTALL_PREFIX}-${id}-${index}.local`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The journal owns the temporary filename. Exclusive open and rename keep writes whole. */
|
|
81
|
+
async function replaceFile(root, file, temp, contents, mode, expected) {
|
|
82
|
+
const destination = await projectPath(root, file, 'file');
|
|
83
|
+
const staging = await projectPath(root, temp, 'file');
|
|
84
|
+
const handle = await open(staging.file, 'wx', 0o600);
|
|
85
|
+
try {
|
|
86
|
+
await handle.writeFile(contents);
|
|
87
|
+
if (mode !== null) await handle.chmod(mode);
|
|
88
|
+
await handle.sync();
|
|
89
|
+
} finally {
|
|
90
|
+
await handle.close();
|
|
91
|
+
}
|
|
92
|
+
if (expected !== undefined && hash((await readSnapshot(root, file)).before) !== expected) {
|
|
93
|
+
throw new Error(`Project file changed before publication: ${file}`);
|
|
94
|
+
}
|
|
95
|
+
await projectPath(root, file, 'file');
|
|
96
|
+
await rename(staging.file, destination.file);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function parseJournal(buffer) {
|
|
100
|
+
const journal = JSON.parse(buffer.toString());
|
|
101
|
+
if (!journal || !journalPattern.test(journal.id ?? '') || !Array.isArray(journal.entries) ||
|
|
102
|
+
!Array.isArray(journal.directories)) throw new Error('Invalid installer recovery journal');
|
|
103
|
+
const files = new Set();
|
|
104
|
+
const directoryCandidates = new Set();
|
|
105
|
+
for (const entry of journal.entries) {
|
|
106
|
+
const file = normalizedFile(entry.file);
|
|
107
|
+
if (file !== entry.file || files.has(file.toLowerCase()) || !digestPattern.test(entry.after ?? '') ||
|
|
108
|
+
(entry.original !== null && (typeof entry.original !== 'string' ||
|
|
109
|
+
!Number.isInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o777))) {
|
|
110
|
+
throw new Error('Invalid installer recovery journal entry');
|
|
111
|
+
}
|
|
112
|
+
files.add(file.toLowerCase());
|
|
113
|
+
for (let dir = folder(file); dir !== '.'; dir = folder(dir)) directoryCandidates.add(dir);
|
|
114
|
+
}
|
|
115
|
+
if (journal.directories.some((dir) => !directoryCandidates.has(dir))) {
|
|
116
|
+
throw new Error('Invalid installer recovery directories');
|
|
117
|
+
}
|
|
118
|
+
return journal;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Verify all files before restoring any. An intervening edit keeps the journal for inspection. */
|
|
122
|
+
async function recover(root) {
|
|
123
|
+
const data = await readSnapshot(root, stateFile('journal.json'));
|
|
124
|
+
if (!data.before) return;
|
|
125
|
+
const journal = parseJournal(data.before);
|
|
126
|
+
if ((await projectPath(root, stateFile('committed'), 'file')).stat) return;
|
|
127
|
+
|
|
128
|
+
const changes = [];
|
|
129
|
+
for (const [index, entry] of journal.entries.entries()) {
|
|
130
|
+
const original = entry.original === null ? null : Buffer.from(entry.original, 'base64');
|
|
131
|
+
const current = await readSnapshot(root, entry.file);
|
|
132
|
+
const currentHash = hash(current.before);
|
|
133
|
+
if (currentHash !== entry.after && currentHash !== hash(original)) {
|
|
134
|
+
throw new Error(`Preserving intervening edit at ${entry.file}. Restore the installer-owned version and retry recovery.`);
|
|
135
|
+
}
|
|
136
|
+
changes.push({ ...entry, original, changed: currentHash !== hash(original), temp: tempFile(entry.file, journal.id, index) });
|
|
137
|
+
}
|
|
138
|
+
for (const change of changes.reverse()) {
|
|
139
|
+
const temp = await projectPath(root, change.temp, 'file');
|
|
140
|
+
if (temp.stat) await unlink(temp.file);
|
|
141
|
+
if (!change.changed) continue;
|
|
142
|
+
if (change.original === null) {
|
|
143
|
+
if (hash((await readSnapshot(root, change.file)).before) !== change.after) {
|
|
144
|
+
throw new Error(`Project file changed during recovery: ${change.file}`);
|
|
145
|
+
}
|
|
146
|
+
await unlink((await projectPath(root, change.file, 'file')).file);
|
|
147
|
+
} else {
|
|
148
|
+
await replaceFile(root, change.file, change.temp, change.original, change.mode, change.after);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
for (const dir of [...journal.directories].sort((a, b) => b.length - a.length)) {
|
|
152
|
+
const entry = await projectPath(root, dir, 'directory');
|
|
153
|
+
if (entry.stat) await rmdir(entry.file).catch((error) => {
|
|
154
|
+
if (!['ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function releaseLock(root, lock) {
|
|
160
|
+
// Retire the directory while it still has an owner. A competing installer
|
|
161
|
+
// sees the whole lock or no lock, and can never reuse the retired path.
|
|
162
|
+
await projectPath(root, INSTALL_STATE, 'directory');
|
|
163
|
+
const retired = privateInstallerPath(root, 'finished');
|
|
164
|
+
await rename(lock, retired);
|
|
165
|
+
await rm(retired, { recursive: true, force: true });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** A patcher reads only guarded files and returns its ordered write set.
|
|
169
|
+
* No project source file is touched until the full plan and journal are ready. */
|
|
170
|
+
export async function installModule(project, plan) {
|
|
171
|
+
const root = await realpath(project);
|
|
172
|
+
const lock = await takeLock(root);
|
|
173
|
+
let keepJournal = false;
|
|
174
|
+
try {
|
|
175
|
+
try {
|
|
176
|
+
await recover(root);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
keepJournal = true;
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
for (const name of ['journal.json', 'journal.tmp', 'committed']) {
|
|
182
|
+
const entry = await projectPath(root, stateFile(name), 'file');
|
|
183
|
+
if (entry.stat) await unlink(entry.file);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const snapshots = new Map();
|
|
187
|
+
async function snapshot(file) {
|
|
188
|
+
const relative = normalizedFile(file);
|
|
189
|
+
if (!snapshots.has(relative)) snapshots.set(relative, await readSnapshot(root, relative));
|
|
190
|
+
return snapshots.get(relative);
|
|
191
|
+
}
|
|
192
|
+
const files = {
|
|
193
|
+
read: async (file, encoding) => {
|
|
194
|
+
const { before } = await snapshot(file);
|
|
195
|
+
if (before === null) throw new Error(`Missing project file: ${file}`);
|
|
196
|
+
return encoding ? before.toString(encoding) : before;
|
|
197
|
+
},
|
|
198
|
+
exists: async (file) => Boolean((await projectPath(root, normalizedFile(file))).stat),
|
|
199
|
+
list: async (dir) => {
|
|
200
|
+
const entry = await projectPath(root, normalizedFile(dir), 'directory');
|
|
201
|
+
return readdir(entry.file, { withFileTypes: true });
|
|
202
|
+
},
|
|
203
|
+
stage: async (paths, transform) => {
|
|
204
|
+
// Legacy AST transforms get a private, allowlisted copy of their inputs.
|
|
205
|
+
// They keep their existing file paths and cannot publish to the checkout.
|
|
206
|
+
const stage = await mkdtemp(path.join(lock, 'patch-'));
|
|
207
|
+
for (const file of paths) {
|
|
208
|
+
const { before } = await snapshot(file);
|
|
209
|
+
if (before === null) continue;
|
|
210
|
+
await createParents(stage, file);
|
|
211
|
+
await writeFile(path.join(stage, file), before, { mode: 0o600, flag: 'wx' });
|
|
212
|
+
}
|
|
213
|
+
await transform(stage);
|
|
214
|
+
const writes = new Map();
|
|
215
|
+
for (const file of paths) {
|
|
216
|
+
const { before: original } = await snapshot(file);
|
|
217
|
+
const { before } = await readSnapshot(stage, file);
|
|
218
|
+
if (before && (original === null || !before.equals(original))) writes.set(file, before);
|
|
219
|
+
}
|
|
220
|
+
return writes;
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
const writes = await plan(files);
|
|
224
|
+
if (!writes?.size) return false;
|
|
225
|
+
|
|
226
|
+
const id = randomUUID();
|
|
227
|
+
const directories = new Set();
|
|
228
|
+
const entries = [];
|
|
229
|
+
for (const [relative, content] of writes) {
|
|
230
|
+
const file = normalizedFile(relative);
|
|
231
|
+
const saved = await snapshot(file);
|
|
232
|
+
const current = await readSnapshot(root, file);
|
|
233
|
+
if (hash(current.before) !== hash(saved.before) || current.mode !== saved.mode) {
|
|
234
|
+
throw new Error(`Project file changed during installer preflight: ${file}`);
|
|
235
|
+
}
|
|
236
|
+
for (let dir = folder(file); dir !== '.'; dir = folder(dir)) {
|
|
237
|
+
if (!(await projectPath(root, dir, 'directory')).stat) directories.add(dir);
|
|
238
|
+
}
|
|
239
|
+
const data = Buffer.from(content);
|
|
240
|
+
entries.push({ file, original: saved.before?.toString('base64') ?? null, mode: saved.mode, after: hash(data), data });
|
|
241
|
+
}
|
|
242
|
+
const journal = JSON.stringify({
|
|
243
|
+
id, directories: [...directories], entries: entries.map(({ data, ...entry }) => entry),
|
|
244
|
+
});
|
|
245
|
+
parseJournal(Buffer.from(journal));
|
|
246
|
+
await replaceFile(root, stateFile('journal.json'), stateFile('journal.tmp'), journal, null);
|
|
247
|
+
try {
|
|
248
|
+
for (const [index, entry] of entries.entries()) {
|
|
249
|
+
const current = await readSnapshot(root, entry.file);
|
|
250
|
+
const original = await snapshot(entry.file);
|
|
251
|
+
if (hash(current.before) !== hash(original.before) || current.mode !== original.mode) {
|
|
252
|
+
throw new Error(`Project file changed during installation: ${entry.file}`);
|
|
253
|
+
}
|
|
254
|
+
await createParents(root, entry.file);
|
|
255
|
+
// Match ordinary source-file creation for new payloads. The journal
|
|
256
|
+
// and its temporary files keep private permissions via replaceFile.
|
|
257
|
+
const mode = entry.mode ?? (0o666 & ~process.umask());
|
|
258
|
+
await replaceFile(root, entry.file, tempFile(entry.file, id, index), entry.data, mode, hash(original.before));
|
|
259
|
+
}
|
|
260
|
+
await writeFile(path.join(lock, 'committed'), '', { flag: 'wx', mode: 0o600 });
|
|
261
|
+
} catch (error) {
|
|
262
|
+
try {
|
|
263
|
+
await recover(root);
|
|
264
|
+
} catch (recoveryError) {
|
|
265
|
+
keepJournal = true;
|
|
266
|
+
throw recoveryError;
|
|
267
|
+
}
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
return true;
|
|
271
|
+
} finally {
|
|
272
|
+
// Preserve a conflicted recovery journal for inspection after the CLI exits.
|
|
273
|
+
if (!keepJournal) await releaseLock(root, lock);
|
|
274
|
+
}
|
|
275
|
+
}
|