@warlock.js/core 5.12.0 → 5.13.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 CHANGED
@@ -4,7 +4,24 @@ All notable changes to `@warlock.js/core` are documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `@warlock.js/*` packages are released in lockstep — every package shares the same version number, so a version below may list only the changes that affected this package.
6
6
 
7
- > ⚠ **Versioning: `@warlock.js/*` does not follow SemVer strictly — breaking changes may ship in a minor.** This is a deliberate decision, not an oversight: the framework is pre-adoption and the cost of a major per behaviour fix currently outweighs the benefit. **Pin an exact version or a tilde range (`~4.13.0`) if you need to opt into changes rather than receive them.** Every breaking change is marked **BREAKING** in its entry and summarised in an *Upgrading* section at the top of the release. **This policy will change once the framework has consumers beyond its author.**
7
+ > ⚠ **Versioning: `@warlock.js/*` does not follow SemVer strictly — breaking changes may ship in a minor.** This is a deliberate decision, not an oversight: the framework is pre-adoption and the cost of a major per behaviour fix currently outweighs the benefit. **Pin an exact version or a tilde range (`~4.13.0`) if you need to opt into changes rather than receive them.** Every breaking change is marked **BREAKING** in its entry and summarised in an _Upgrading_ section at the top of the release. **This policy will change once the framework has consumers beyond its author.**
8
+
9
+ ## 5.13.0 - 2026-09-17
10
+
11
+ ### Added
12
+
13
+ - `warlock add queue` installs `@warlock.js/queue`, generates Redis-backed `src/config/queue.ts`, and registers `queueConnector()` in `warlock.config.ts`.
14
+ - `warlock add auth-google` and `warlock add auth-passkeys` install `@warlock.js/auth`'s Google sign-in (`jose`) and passkey (`@simplewebauthn/server`) login methods.
15
+ - `warlock dev` generates `.warlock/typings/translations.d.ts` from literal `groupedTranslations` dictionaries, augmenting web's typed translation-key registry.
16
+
17
+ ### Changed
18
+
19
+ - `warlock dev` now uses a 12ms quiet window for isolated file saves while extending multi-file bursts up to a 60ms maximum, reducing routine HMR latency without splitting formatter or checkout reloads.
20
+
21
+ ### Fixed
22
+
23
+ - Safely return no alias resolution when a configured alias has no first target.
24
+ - `@warlock.js/core` no longer imports `@warlock.js/auth`; `useHashedPassword` now calls core's own `hashPassword` directly instead of an auth-service delegate that only called back into core, and `@warlock.js/auth` moves to a dev-only dependency. A guard spec now fails the build if any `core/src` module imports `@warlock.js/auth`.
8
25
 
9
26
  ## 5.12.0 - 2026-09-16
10
27
 
@@ -84,6 +101,7 @@ _Released in lockstep with the `@warlock.js/*` family; no package-specific chang
84
101
  - Internal type-safety hardening across the CLI, dev server and request handling; no other behaviour change.
85
102
 
86
103
  ## 5.6.0 - 2026-09-08
104
+
87
105
  ### Fixed
88
106
 
89
107
  - **A production build asked the APP to resolve packages only the framework declares, so a built app could not boot under a strict pnpm tree.** Every bare specifier was left external, including the `@fastify/*`, `find-my-way`, `fast-jwt` and `@mongez/*` imports that reach the bundle through the framework's own code — none of which an app has any reason to declare. Under npm/yarn hoisting they resolved by accident; under pnpm the app died with `ERR_MODULE_NOT_FOUND` at startup, after a build that reported success. Externality is now decided per import edge: a bare specifier stays external unless the importer is not the app's own code AND the specifier names a package that importer's own `dependencies` declare.
@@ -214,7 +232,7 @@ _Released in lockstep with the `@warlock.js/*` family; no package-specific chang
214
232
  first run every time.
215
233
 
216
234
  ⚠ **What a clean diff does not prove.** The manifest records what each page's route
217
- name was *derived* as, not what it was *registered* as: `warlock build` boots no
235
+ name was _derived_ as, not what it was _registered_ as: `warlock build` boots no
218
236
  connectors, so it cannot see the API routes a page name may collide with, and the
219
237
  router appends a `.<method>` suffix to a name another method already claimed —
220
238
  which the comparison accepts rather than reporting. `Page routes match` therefore
@@ -282,14 +300,14 @@ _Released in lockstep with the `@warlock.js/*` family; no package-specific chang
282
300
  verbatim and live, and its failure summary now reports whether a cause actually arrived:
283
301
  `the cause is printed above, in the application's own output` when output was seen, and
284
302
  `no output was captured from the application process — its cause did not reach this
285
- terminal` when none was. It previously pointed at "above" unconditionally, which on a
303
+ terminal` when none was. It previously pointed at "above" unconditionally, which on a
286
304
  silent child meant pointing at an empty terminal
287
305
 
288
306
  - **The HTTP connector now preflights its port before binding.** `warlock dev` and
289
307
  `warlock start` both go through `HttpConnector.start()`, which now calls
290
308
  `assertPortIsAvailable(port, host)` immediately before `listen()`. A collision now
291
309
  surfaces as `EADDRINUSE: Port <port> is already in use on <host>. Stop the dev server
292
- (or whatever else is listening on port <port>) and run again...` — the code and the
310
+ (or whatever else is listening on port <port>) and run again...` — the code and the
293
311
  port named in the same sentence — instead of a bare `EADDRINUSE` thrown from inside
294
312
  Fastify with no indication of which port it meant. `EACCES` on the port is treated
295
313
  the same way, since "cannot bind" is one problem from the operator's side. The test
@@ -307,8 +325,8 @@ _Released in lockstep with the `@warlock.js/*` family; no package-specific chang
307
325
  `src/app/contact/controllers/contact.controller.ts` (a `POST /api/contact` route
308
326
  validated with `@warlock.js/seal`), and `src/web/home.page.tsx` ships an
309
327
  interactive, localized (en/ar) contact form wired to that route via `@mongez/http`
310
- + `@mongez/react-form` + `@mongez/react-localization`. The `web` feature now also
311
- installs those three packages as dependencies.
328
+ - `@mongez/react-form` + `@mongez/react-localization`. The `web` feature now also
329
+ installs those three packages as dependencies.
312
330
 
313
331
  ### Fixed
314
332
 
@@ -337,7 +355,7 @@ _Released in lockstep with the `@warlock.js/*` family; no package-specific chang
337
355
  ### Added
338
356
 
339
357
  - **`warlock add tailwind`** — installs and wires Tailwind CSS v4 through PostCSS.
340
- - **`warlock add shadcn`** — sets up the prerequisites shadcn/ui expects. It is *not* a
358
+ - **`warlock add shadcn`** — sets up the prerequisites shadcn/ui expects. It is _not_ a
341
359
  wrapper around the shadcn CLI: you still run that yourself to add components, this
342
360
  only makes the project ready for it.
343
361
 
@@ -396,15 +414,15 @@ resolution pin and the `@warlock.js/web` peer narrowing — see those packages'
396
414
 
397
415
  ⚠ **If your app runs behind a proxy and relied on `detectIp()` reading the forwarding headers without setting `http.trustProxy`, set `http.trustProxy: true`** (or a Fastify `trustProxy` value matching your edge). With `true` set, behaviour is unchanged: `X-Real-IP` first, then the leftmost `X-Forwarded-For` hop, then the peer address. Only enable `true` when your edge overwrites those headers — it trusts them wholesale
398
416
 
399
- - **`http.trustProxy` now accepts a hop count or a trusted-proxy list, and `detectIp()` honours them.** `true` is the wrong shape for the common topology: an edge that *appends* to `X-Forwarded-For` leaves whatever the client prepended as the leftmost entry, so "trust the leftmost hop" hands the client its own IP back. The config value is passed to Fastify untouched, and `detectIp()` now reads the resolved client off `request.ip` instead of re-parsing the header — so both agree, and every Fastify shape works:
417
+ - **`http.trustProxy` now accepts a hop count or a trusted-proxy list, and `detectIp()` honours them.** `true` is the wrong shape for the common topology: an edge that _appends_ to `X-Forwarded-For` leaves whatever the client prepended as the leftmost entry, so "trust the leftmost hop" hands the client its own IP back. The config value is passed to Fastify untouched, and `detectIp()` now reads the resolved client off `request.ip` instead of re-parsing the header — so both agree, and every Fastify shape works:
400
418
 
401
- | `http.trustProxy` | Client IP |
402
- | --- | --- |
403
- | `false` *(default)* | Socket peer address; forwarding headers ignored |
404
- | `true` | Leftmost `X-Forwarded-For` entry (whole chain trusted) |
405
- | `2` | Walks past the 2 rightmost hops — for an edge that appends |
419
+ | `http.trustProxy` | Client IP |
420
+ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
421
+ | `false` _(default)_ | Socket peer address; forwarding headers ignored |
422
+ | `true` | Leftmost `X-Forwarded-For` entry (whole chain trusted) |
423
+ | `2` | Walks past the 2 rightmost hops — for an edge that appends |
406
424
  | `"10.0.0.0/8"`, `"loopback, 10.0.0.0/8"`, `["10.0.0.0/8", "192.168.0.0/16"]` | Walks left while each hop is a listed proxy, stops at the first that isn't |
407
- | `(address, hop) => boolean` | Your predicate |
425
+ | `(address, hop) => boolean` | Your predicate |
408
426
 
409
427
  Prefer the narrowest shape your topology allows: with `true`, any client that can reach the process directly picks its own IP, and an `ipFilter` allowlist in front of it is decorative
410
428
 
@@ -432,8 +450,8 @@ resolution pin and the `@warlock.js/web` peer narrowing — see those packages'
432
450
  import { afterAll } from "vitest";
433
451
  import { setupTest, teardownTest } from "@warlock.js/core/tests";
434
452
 
435
- await setupTest(); // ← was setupTest({ connectors: true })
436
- afterAll(teardownTest); // ← is new
453
+ await setupTest(); // ← was setupTest({ connectors: true })
454
+ afterAll(teardownTest); // ← is new
437
455
  ```
438
456
 
439
457
  1. **`{ connectors: true }` must become a bare `setupTest()`.** Under the new precedence it is an **explicit** value, so it now overrides your `src/config/tests.ts` where it previously deferred to it.
@@ -442,12 +460,12 @@ afterAll(teardownTest); // ← is new
442
460
 
443
461
  **This is the migration step nobody can skip.** `warlock add test` emits the corrected file for new projects.
444
462
 
445
- | What changes | How you'll see it | What to do |
446
- |---|---|---|
463
+ | What changes | How you'll see it | What to do |
464
+ | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
447
465
  | **`setupTest({ connectors })` now beats `tests.connectors` config** — the precedence flipped | a test file that passes `connectors` explicitly starts a **different connector set** than it did in 4.13.0 | grep for `setupTest({` — a call passing `connectors` was previously **ignored** and is now honoured. **Including the one in your generated setup file** |
448
- | **A second `setupTest` call with different options now REJECTS** | an error naming the active and the requested selection, where 4.13.0 silently did nothing | call `teardownTest()` first, or don't call `setupTest` again at all |
449
- | **The generated setup file now registers `afterAll(teardownTest)`** | your test files tear the framework down when they finish, instead of leaving it running | **add it to your existing `src/test-setup.ts`** — see below |
450
- | **Docs corrected: `setupTest` is called per TEST FILE, not per worker** | no runtime effect on its own — the *invocation* always worked this way | fix the comment in `src/test-setup.ts` as above |
466
+ | **A second `setupTest` call with different options now REJECTS** | an error naming the active and the requested selection, where 4.13.0 silently did nothing | call `teardownTest()` first, or don't call `setupTest` again at all |
467
+ | **The generated setup file now registers `afterAll(teardownTest)`** | your test files tear the framework down when they finish, instead of leaving it running | **add it to your existing `src/test-setup.ts`** — see below |
468
+ | **Docs corrected: `setupTest` is called per TEST FILE, not per worker** | no runtime effect on its own — the _invocation_ always worked this way | fix the comment in `src/test-setup.ts` as above |
451
469
 
452
470
  ### Added
453
471
 
@@ -461,15 +479,15 @@ afterAll(teardownTest); // ← is new
461
479
 
462
480
  - **BREAKING — an explicit `setupTest({ connectors })` now wins over `tests.connectors` config.** The order was `config > parameter > true`; it is now **`explicit parameter > config > true`**
463
481
 
464
- 4.13.0's changelog said this question was open, not settled: *"a per-call override is a contract decision for a later release."* This is that decision. **Call-site intent should beat a project default** — a caller who names a connector set is being specific on purpose, and silently overruling them was the wrong behaviour
482
+ 4.13.0's changelog said this question was open, not settled: _"a per-call override is a contract decision for a later release."_ This is that decision. **Call-site intent should beat a project default** — a caller who names a connector set is being specific on purpose, and silently overruling them was the wrong behaviour
465
483
 
466
484
  **"Explicit" means a non-`undefined` value.** `setupTest()`, `setupTest({})` and `setupTest({ connectors: undefined })` **all fall through to config, then to `true`.** The `undefined` rule is deliberate: an optional variable that happens to be `undefined` must not silently erase project config
467
485
 
468
486
  ⚠ **The generated `src/test-setup.ts` now calls `setupTest()` with no argument**, where it previously passed `{ connectors: true }`. Under the new order, passing `true` explicitly would erase the `tests.connectors` layer for the entire project. **If you edit your setup file, leave the call bare**
469
487
 
470
- ⚠ **This is user-visible and it is why the change is marked BREAKING:** an application that sets `tests.connectors` *and* passes `connectors` from any test file will start a different connector set after upgrading
488
+ ⚠ **This is user-visible and it is why the change is marked BREAKING:** an application that sets `tests.connectors` _and_ passes `connectors` from any test file will start a different connector set after upgrading
471
489
 
472
- - **BREAKING — a conflicting `setupTest` call rejects instead of being ignored.** While a setup is starting or ready, a call with *different* effective options now rejects with an error naming both the active and the requested selection. The same options remain a no-op, and concurrent identical calls share one startup
490
+ - **BREAKING — a conflicting `setupTest` call rejects instead of being ignored.** While a setup is starting or ready, a call with _different_ effective options now rejects with an error naming both the active and the requested selection. The same options remain a no-op, and concurrent identical calls share one startup
473
491
 
474
492
  Through 4.13.0 this was a silent early-return on an `isSetupComplete` flag — so `setupTest({ connectors: false })` in a file whose `src/test-setup.ts` had already run **did nothing at all, reported nothing, and started every connector anyway.** Connector arrays are compared as **sets** after deduplication, so caller order never counts as a conflict
475
493
 
@@ -497,7 +515,7 @@ afterAll(teardownTest); // ← is new
497
515
 
498
516
  ⚠ **A stranded lifecycle must fail with a message, not a dead process** — a crash mid-file is indistinguishable from an infrastructure flake, which is the worst way for a framework to report its own bug
499
517
 
500
- ⚠ **Scope of the proof, stated because a green here is easy to over-read:** all nine guards were seen to fail under their own mutation, **but every spec injects its scheduler** — the default *value* is tested while the production timer, and whether its `unref` releases the worker, is not. **No spec observes a real hang**; the stuck attempt is a mock gate, not a socket that never returns
518
+ ⚠ **Scope of the proof, stated because a green here is easy to over-read:** all nine guards were seen to fail under their own mutation, **but every spec injects its scheduler** — the default _value_ is tested while the production timer, and whether its `unref` releases the worker, is not. **No spec observes a real hang**; the stuck attempt is a mock gate, not a socket that never returns
501
519
 
502
520
  ### Documentation
503
521
 
@@ -507,7 +525,7 @@ afterAll(teardownTest); // ← is new
507
525
 
508
526
  **The lifetime this release commits to is FILE-SCOPED:** the setup file bootstraps the framework and its `afterAll(teardownTest)` closes it, once per test file. **One owner, one pairing, correct under every pool, every isolation setting, and watch mode**
509
527
 
510
- ⚠ **This deliberately declines a faster option.** Holding lifecycle state in the worker runtime makes a worker-scoped lifetime *possible* — bootstrap once, reuse across every file in that worker — and an earlier draft of this release simply left the framework running to get it. **We are not shipping that**, for two reasons neither of which is performance:
528
+ ⚠ **This deliberately declines a faster option.** Holding lifecycle state in the worker runtime makes a worker-scoped lifetime _possible_ — bootstrap once, reuse across every file in that worker — and an earlier draft of this release simply left the framework running to get it. **We are not shipping that**, for two reasons neither of which is performance:
511
529
 
512
530
  1. **Under `pool: "threads"` we cannot honestly claim the runner cleans up.** Vitest tears the thread down while the process lives, and whether Node reclaims that thread's sockets and pools is **unmeasured** — so "the runner owns cleanup by termination" would be a promise we cannot observe being kept
513
531
  2. **In watch mode Vitest reuses workers between reruns**, so there is no recycle and therefore **no cleanup owner at all** between reruns. Declaring watch mode unsupported was the alternative, and a test framework whose lifecycle is undefined in the mode people use all day does not have a lifecycle
@@ -520,12 +538,12 @@ afterAll(teardownTest); // ← is new
520
538
 
521
539
  **Four breaking changes. Every one of them fails visibly, and every one is fixed by a single line or a single config key.** Three are security defaults that were wrong; the fourth is an import path.
522
540
 
523
- | What breaks | How you'll see it | The fix |
524
- |---|---|---|
525
- | **`http.cors` now actually applies** — it never had any effect in any release through 4.12.0 | requests from origins you never allow-listed start being rejected | check `http.cors` before upgrading; it now means what it says |
526
- | **`http.bodyLimit` defaults to Fastify's 1 MB**, not 200 GB | large uploads that used to be accepted answer `413` | set `http.bodyLimit` explicitly if you need more |
527
- | **`http.trustProxy` defaults to `false`** | `request.ip` becomes the socket address instead of `X-Forwarded-For` | set `http.trustProxy: true` **only if** you are genuinely behind a proxy that strips the header |
528
- | **The package entry no longer re-exports the CLI, dev server, test helpers or Vite integration** | build fails with `has no exported member` | test helpers move to `@warlock.js/core/tests`, `lowerStage3Decorators` to `@warlock.js/core/vite` — **one line per import.** The CLI and dev-server internals are **not** public and have no replacement specifier |
541
+ | What breaks | How you'll see it | The fix |
542
+ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
543
+ | **`http.cors` now actually applies** — it never had any effect in any release through 4.12.0 | requests from origins you never allow-listed start being rejected | check `http.cors` before upgrading; it now means what it says |
544
+ | **`http.bodyLimit` defaults to Fastify's 1 MB**, not 200 GB | large uploads that used to be accepted answer `413` | set `http.bodyLimit` explicitly if you need more |
545
+ | **`http.trustProxy` defaults to `false`** | `request.ip` becomes the socket address instead of `X-Forwarded-For` | set `http.trustProxy: true` **only if** you are genuinely behind a proxy that strips the header |
546
+ | **The package entry no longer re-exports the CLI, dev server, test helpers or Vite integration** | build fails with `has no exported member` | test helpers move to `@warlock.js/core/tests`, `lowerStage3Decorators` to `@warlock.js/core/vite` — **one line per import.** The CLI and dev-server internals are **not** public and have no replacement specifier |
529
547
 
530
548
  **If your app configures none of the three HTTP keys, the first three changes make it strictly safer with no action from you.** The `trustProxy` default in particular meant per-IP rate limiting was bypassable by anyone sending their own `X-Forwarded-For`.
531
549
 
@@ -561,9 +579,9 @@ Details for each are in the entries below.
561
579
 
562
580
  - **Shutdown survives a throwing log channel.** A connector whose `shutdown()` failed was reported through `log.error(...)` **from inside the catch block** — and `Logger.log()` hands each entry to `channel.log()` with no isolation, so a channel that throws synchronously (a misconfigured transport, an unserialisable payload) made that report reject. The rejection escaped `shutdown()` entirely, and the consequences went well past a missing log line: **`log.flush()` never ran, so every buffered entry from the whole run was lost; the remaining connectors were never torn down; and `process.exit(0)` — the line `gracefulShutdown` runs once `shutdown()` resolves — was never reached, leaving the process alive on the handles those connectors still held**
563
581
 
564
- ⚠ **This hardens the shutdown path, not the logger.** `Logger.log()` still aborts its fan-out on the first throwing channel, so the other channels never receive that entry, and an *asynchronously* rejecting channel is not covered at all — `channel.log()` is never awaited. **Logger-wide isolation is a separate fix in a later release**
582
+ ⚠ **This hardens the shutdown path, not the logger.** `Logger.log()` still aborts its fan-out on the first throwing channel, so the other channels never receive that entry, and an _asynchronously_ rejecting channel is not covered at all — `channel.log()` is never awaited. **Logger-wide isolation is a separate fix in a later release**
565
583
 
566
- - **A test server that fails to start no longer leaves half of itself running.** `startHttpTestServer()` publishes the resolved port before the late connector phase and sets `isServerRunning` only on its last line, so a failure in between left **live early-phase connectors and a published port pointing at a server that never came up** — while `stopHttpTestServer()` in `globalTeardown` reported *"No server to stop"* and walked away from them. Startup now unwinds what it started, always withdraws the port and resets its state. ⚠ **The error you get back is unchanged — it always was.** Startup had no `catch` at all, so the original failure already propagated correctly; what was missing was the cleanup, and the new `catch` exists only to run it. A failure *during* that cleanup is reported and never substituted for the cause, which is the one propagation guarantee the wrapper had to be careful not to break
584
+ - **A test server that fails to start no longer leaves half of itself running.** `startHttpTestServer()` publishes the resolved port before the late connector phase and sets `isServerRunning` only on its last line, so a failure in between left **live early-phase connectors and a published port pointing at a server that never came up** — while `stopHttpTestServer()` in `globalTeardown` reported _"No server to stop"_ and walked away from them. Startup now unwinds what it started, always withdraws the port and resets its state. ⚠ **The error you get back is unchanged — it always was.** Startup had no `catch` at all, so the original failure already propagated correctly; what was missing was the cleanup, and the new `catch` exists only to run it. A failure _during_ that cleanup is reported and never substituted for the cause, which is the one propagation guarantee the wrapper had to be careful not to break
567
585
 
568
586
  **`stopHttpTestServer()` withdraws the port and resets state in a `finally`.** They previously ran after the `await`, so a shutdown that threw left the published port behind and the next run in the same process inherited it
569
587
 
@@ -573,17 +591,18 @@ Details for each are in the entries below.
573
591
 
574
592
  **Why it had to change:** those five put dev-only tooling into the **static module graph of every application that imports the framework** — 39 files, reaching ESLint and, through it, ESLint's optional `jiti` import. It cost nothing while the builder kept `packages: "external"`, because esbuild never walked into the framework. **Anything that bundles walks it, and the build fails.** That is why `singleBundle` could not build a single real application
575
593
 
576
- ⚠ **Making those imports lazy does not help and should not be attempted.** esbuild resolves `import()` at build time; a dynamic import defers *evaluation*, not resolution. Measured: `await import("jiti")` in an otherwise empty file still fails with `Could not resolve "jiti"`. **Only unreachability from the entry removes a module from the graph**
594
+ ⚠ **Making those imports lazy does not help and should not be attempted.** esbuild resolves `import()` at build time; a dynamic import defers _evaluation_, not resolution. Measured: `await import("jiti")` in an otherwise empty file still fails with `Could not resolve "jiti"`. **Only unreachability from the entry removes a module from the graph**
577
595
 
578
596
  **The two public halves are now reachable from a subpath — and in 4.12.0 and earlier they were reachable from nowhere at all.** `./tests` and `./vite` are **real build entries with their own emitted files and `exports` entries**, not reachable from the root barrel, which is the entire point:
579
597
 
580
598
  ```ts
581
599
  // before // after
582
- import { setupTest } from "@warlock.js/core"; import { setupTest } from "@warlock.js/core/tests";
600
+ import { setupTest } from "@warlock.js/core";
601
+ import { setupTest } from "@warlock.js/core/tests";
583
602
  import { startHttpTestServer } from "@warlock.js/core";
584
- import { startHttpTestServer } from "@warlock.js/core/tests";
603
+ import { startHttpTestServer } from "@warlock.js/core/tests";
585
604
  import { lowerStage3Decorators } from "@warlock.js/core";
586
- import { lowerStage3Decorators } from "@warlock.js/core/vite";
605
+ import { lowerStage3Decorators } from "@warlock.js/core/vite";
587
606
  ```
588
607
 
589
608
  **The CLI and dev-server internals are different — they were never a public API and have no replacement specifier.** If you were importing from those, you were reaching into framework internals; open an issue describing what you needed.
@@ -592,7 +611,7 @@ Details for each are in the entries below.
592
611
 
593
612
  `Path` is unaffected — it moved to a genuine utility module and remains exported
594
613
 
595
- **Removing the five lines was necessary but not sufficient.** Three production modules — `connectors/http-connector`, `connectors/connectors-manager` and `warlock-config/warlock-config.manager` — imported the dev server's console formatter directly. In `http-connector` the dev-console call was simply **deleted**: the same error was already routed through `log.fatal` on the following line. `connectors-manager` now logs a connector's shutdown failure through `@warlock.js/logger`, **awaited and then flushed** — `process.exit(0)` follows immediately, so an un-awaited log is a log that never happens. `warlock-config.manager`'s *"`warlock.config.ts` is missing"* warning writes **straight to the console instead**: it runs during CLI bootstrap, before the logger has a single channel configured, so routing it through the logger would drop it in every application
614
+ **Removing the five lines was necessary but not sufficient.** Three production modules — `connectors/http-connector`, `connectors/connectors-manager` and `warlock-config/warlock-config.manager` — imported the dev server's console formatter directly. In `http-connector` the dev-console call was simply **deleted**: the same error was already routed through `log.fatal` on the following line. `connectors-manager` now logs a connector's shutdown failure through `@warlock.js/logger`, **awaited and then flushed** — `process.exit(0)` follows immediately, so an un-awaited log is a log that never happens. `warlock-config.manager`'s _"`warlock.config.ts` is missing"_ warning writes **straight to the console instead**: it runs during CLI bootstrap, before the logger has a single channel configured, so routing it through the logger would drop it in every application
596
615
 
597
616
  `tests/unit/meta/production-entry-graph.test.ts` enforces this from now on. It keys on **our own directory names** rather than a denylist of third-party packages, because a denylist rots the moment a dependency changes its imports and can only catch names someone thought of
598
617
 
@@ -634,15 +653,15 @@ Details for each are in the entries below.
634
653
 
635
654
  - **`warlock migrate --pending` — what will run next, in the order it will run.** `migrate` could report what had already run (`--list`) and what files existed on disk (`--all`), but not the one thing an operator asks before a schema change against a live database. The pending set was already computed on every migrate run; it simply had no read-only exit
636
655
 
637
- The gap forced a workaround that is **unsound in the dangerous direction**. `--all` globs `src/app` only, so it cannot see migrations a *package* registers through `database.migrations` — `@warlock.js/auth` alone contributes two. `--list` reads the migrations table, which does contain them. Differencing the two counts subtracts populations that do not overlap, and it under-counts pending by roughly the number of package migrations installed — reporting "nothing else is pending" when something is
656
+ The gap forced a workaround that is **unsound in the dangerous direction**. `--all` globs `src/app` only, so it cannot see migrations a _package_ registers through `database.migrations` — `@warlock.js/auth` alone contributes two. `--list` reads the migrations table, which does contain them. Differencing the two counts subtracts populations that do not overlap, and it under-counts pending by roughly the number of package migrations installed — reporting "nothing else is pending" when something is
638
657
 
639
658
  **`migrate --list` now prints both sections**, executed and pending, so the question can be answered without knowing a second flag exists. The executed section prints **first and unconditionally**: it is a table read that cannot fail because of a broken file on disk, and `--list` is the command reached for while something is already wrong. `--list` always exits `0` — it is a report
640
659
 
641
- **`--pending` is the gate**, and its exit code is its entire API: **`0`** computed and nothing pending, **`1`** computed and N pending, **`2`** could not be computed. Two codes would fold "three migrations are waiting" into "I could not work out what is waiting", and those demand opposite responses — the first is *run them*, the second is *stop*. `migrate --pending && deploy` behaves correctly under all three
660
+ **`--pending` is the gate**, and its exit code is its entire API: **`0`** computed and nothing pending, **`1`** computed and N pending, **`2`** could not be computed. Two codes would fold "three migrations are waiting" into "I could not work out what is waiting", and those demand opposite responses — the first is _run them_, the second is _stop_. `migrate --pending && deploy` behaves correctly under all three
642
661
 
643
- **A failure to read the migrations never reports `0`.** Computing pending requires loading project code, and a single migration file missing its default export throws. That degrades to an explicit `Pending: unavailable — <reason>` line with the executed listing intact above it, and `--pending` exits `2`. An empty pending set means *nothing is pending*, and nothing else
662
+ **A failure to read the migrations never reports `0`.** Computing pending requires loading project code, and a single migration file missing its default export throws. That degrades to an explicit `Pending: unavailable — <reason>` line with the executed listing intact above it, and `--pending` exits `2`. An empty pending set means _nothing is pending_, and nothing else
644
663
 
645
- `--all` deliberately does **not** gain a migration name beside each path. The only identifier available without loading is the one derived from the filename, and that derivation is a *fallback* used when a migration does not set `migrationName` — so any migration that names itself (`auth`'s do) would be listed under a name that does not exist. A wrong identifier in a listing whose purpose is cross-referencing is worse than no identifier, and `--list`'s two sections answer the comparison directly
664
+ `--all` deliberately does **not** gain a migration name beside each path. The only identifier available without loading is the one derived from the filename, and that derivation is a _fallback_ used when a migration does not set `migrationName` — so any migration that names itself (`auth`'s do) would be listed under a name that does not exist. A wrong identifier in a listing whose purpose is cross-referencing is worse than no identifier, and `--list`'s two sections answer the comparison directly
646
665
 
647
666
  Proven against a real Postgres: an executed package migration and a pending local one land in the correct sections, a fully-migrated database reports an empty pending list rather than an absent one, and the reporter's `files − executed` arithmetic is pinned as a test that fails if it is ever reintroduced
648
667
 
@@ -654,17 +673,17 @@ Details for each are in the entries below.
654
673
 
655
674
  ### Fixed
656
675
 
657
- - **A build artifact that names an entry point it does not contain is now refused before it can be packed.** An interrupted build leaves a directory that looks finished — `package.json`, `README`, `CHANGELOG`, `bin/`, `skills/` — and holds no compiled code at all. Nineteen existed in this tree at once, and nothing in the release path noticed: the only related guard compares **modification times**, so a hollow directory with a freshly written manifest is *newer than source* and passes, and it runs solely on the artifact-reuse path, which is not how the hollow directories were produced
676
+ - **A build artifact that names an entry point it does not contain is now refused before it can be packed.** An interrupted build leaves a directory that looks finished — `package.json`, `README`, `CHANGELOG`, `bin/`, `skills/` — and holds no compiled code at all. Nineteen existed in this tree at once, and nothing in the release path noticed: the only related guard compares **modification times**, so a hollow directory with a freshly written manifest is _newer than source_ and passes, and it runs solely on the artifact-reuse path, which is not how the hollow directories were produced
658
677
 
659
678
  Each artifact is now verified immediately before `npm pack`, on the normal build path and the reuse path alike. **The manifest is the specification:** `main`, `module` and the typings field name the exact files the package promises to ship, so they are resolved against the artifact and must exist. Fields a manifest does not declare are skipped — `core` and `auth` point `main` at `esm/` while `cascade`, `ai` and `seal` point it at `cjs/`, and any check that assumed one build shape would have raised a false failure on packages that are entirely correct. A manifest declaring no entry point at all is also a failure: a published package nothing can import is not a package
660
679
 
661
680
  - **The production acceptance gate no longer inherits the environment it is supposed to be testing.** `run-pnpm-acceptance.mjs` spawned every child with `env: { ...process.env }` and set no `NODE_ENV`. It exercised the production path only because the shell it was written in happened to carry `NODE_ENV=production`; on a clean checkout, a new contributor's machine, or CI, the same gate boots the app in **development** — and does not fail, it passes while testing something other than the thing it is named after. That is the worst outcome available to a gate, and it sat underneath the proof for 4.11.0's headline fix
662
681
 
663
- `NODE_ENV=production` is now set explicitly on every spawn, and — more importantly — **asserted from inside the running app**: `/acceptance` reports the environment it actually booted in, and the run fails if it is anything else. Setting a variable and never checking it arrived is how the original defect survived. The remaining `{ ...process.env }` is documented as a deliberate inheritance of `PATH` and the package-manager store paths, with everything the *verdict* depends on set after it
682
+ `NODE_ENV=production` is now set explicitly on every spawn, and — more importantly — **asserted from inside the running app**: `/acceptance` reports the environment it actually booted in, and the run fails if it is anything else. Setting a variable and never checking it arrived is how the original defect survived. The remaining `{ ...process.env }` is documented as a deliberate inheritance of `PATH` and the package-manager store paths, with everything the _verdict_ depends on set after it
664
683
 
665
684
  Consequence for the roadmap, recorded because the ordering matters: **CI wiring for this gate is now blocked on this fix, not parallel to it.** Wiring it up first would have produced a green from CI — which carries more weight than a local one — for a run that never touched the production path
666
685
 
667
- - **`warlock migrate --rollback=false` no longer drops every table.** CLI options were parsed as raw strings and nothing ever coerced them: `--rollback=false` reached the action as the string `"false"`, `if (rollback)` saw a truthy value, and the run rolled back *everything*. The declared `type: "boolean"` on the option was decorative — used only to render help. The same shape existed on every boolean option, including `warlock drop.tables --force=false`, where it turned a confirmation prompt into an unattended drop
686
+ - **`warlock migrate --rollback=false` no longer drops every table.** CLI options were parsed as raw strings and nothing ever coerced them: `--rollback=false` reached the action as the string `"false"`, `if (rollback)` saw a truthy value, and the run rolled back _everything_. The declared `type: "boolean"` on the option was decorative — used only to render help. The same shape existed on every boolean option, including `warlock drop.tables --force=false`, where it turned a confirmation prompt into an unattended drop
668
687
 
669
688
  Its twin was worse. A bare `--flag` swallowed the following token as its value, so `warlock migrate --rollback 2024_users.ts` produced `rollback: "2024_users.ts"` — the filename was never read as a path, and every table went down while the operator believed they had named one file. **A declared boolean now never consumes the next positional**: `--rollback 2024_users.ts` is `rollback: true` plus the positional `2024_users.ts`
670
689
 
@@ -676,7 +695,7 @@ Details for each are in the entries below.
676
695
 
677
696
  - **`warlock generate.module users --force=false` no longer overwrites your files.** The coercion above is opt-in by design — it applies only to options a command declares `type: "boolean"`, so a string option whose value is genuinely the word `false` survives. The generate family and `add` never carried that declaration, so the fix reached none of them and both faces of the defect stayed live on the commands most likely to be run against existing source
678
697
 
679
- `--force=false` arrived at every generator as the truthy string `"false"` and the overwrite guard (`if (exists && !force)`) let it through — a flag written to *prevent* clobbering did the clobbering. Its twin ate the target: `warlock generate.module --force users` parsed `users` as the value of `--force`, so the module name was lost entirely and the generator ran with no name
698
+ `--force=false` arrived at every generator as the truthy string `"false"` and the overwrite guard (`if (exists && !force)`) let it through — a flag written to _prevent_ clobbering did the clobbering. Its twin ate the target: `warlock generate.module --force users` parsed `users` as the value of `--force`, so the module name was lost entirely and the generator ran with no name
680
699
 
681
700
  Twenty-three option declarations are now typed: `--force, -f` and `--dry-run` on all eight `generate.*` commands, plus `--minimal, -m`, `--with-validation, -v`, `--with-resource, -rs`, and both `--timestamps [bool]` declarations, and `--list, -l` / `--no-install` on `add`. Options that carry real data are deliberately untouched and still take a value — `--table`, `--add`, `--drop`, `--rename` on the generators, `--package-manager` on `add`, and `seed --drop="Seed Name"`, whose value scopes which seeder is undone
682
701
 
@@ -684,17 +703,17 @@ Details for each are in the entries below.
684
703
 
685
704
  The guard drives the real command objects through the manager's own resolution path (`tests/unit/cli/generate-flag-options.test.ts`) and asserts what the action is handed. Asserting the declaration object instead would pass against a fixture while the CLI stayed broken
686
705
 
687
- - **`new Image(...)` no longer fails depending on how soon you call it.** The `Image` module fired `import("sharp")` at load time without awaiting it, and the constructor only checked whether that import had *failed* — never whether it was still in flight. Constructing an image in the first tick after importing the package therefore ran with an undefined sharp function and died with `TypeError: sharpFn is not a function`; the exact same code passed if something had awaited a timer first. Anything that builds an image during boot — a startup thumbnail job, a module-level warm-up — hit it, and it presented as a mysterious "works locally, breaks in prod" timing bug rather than as a missing dependency
706
+ - **`new Image(...)` no longer fails depending on how soon you call it.** The `Image` module fired `import("sharp")` at load time without awaiting it, and the constructor only checked whether that import had _failed_ — never whether it was still in flight. Constructing an image in the first tick after importing the package therefore ran with an undefined sharp function and died with `TypeError: sharpFn is not a function`; the exact same code passed if something had awaited a timer first. Anything that builds an image during boot — a startup thumbnail job, a module-level warm-up — hit it, and it presented as a mysterious "works locally, breaks in prod" timing bug rather than as a missing dependency
688
707
 
689
708
  Sharp is now resolved **synchronously on the first construction that needs it**, via `createRequire`, and the outcome is cached for the process. There is no longer a window in which the constructor can proceed without a real sharp function: it either has the module or throws. A missing sharp still throws the same install-hint error, at the same point (construction), with the same wording
690
709
 
691
710
  Resolution stays **lazy** — importing `@warlock.js/core` still does not load sharp's native binary, so apps that never touch images pay nothing — and constructing an `Image` from an existing sharp instance short-circuits before any module load
692
711
 
693
- The guard for this is a spawned fresh Node process that imports and constructs with nothing in between (`tests/unit/image/image-sharp-resolution.test.ts`). A same-process test cannot catch it: importing at collection time and constructing later *is* the delay that hides the bug
712
+ The guard for this is a spawned fresh Node process that imports and constructs with nothing in between (`tests/unit/image/image-sharp-resolution.test.ts`). A same-process test cannot catch it: importing at collection time and constructing later _is_ the delay that hides the bug
694
713
 
695
714
  - **A sharp that is installed but will not load no longer reports itself as "not installed".** The resolution above swallowed every failure into a single outcome, so the most common real-world sharp problem — the package present but its native binary built for another platform — arrived as `sharp is not installed.` plus instructions to run `npm install sharp`, which cannot fix it. sharp throws its own long, actionable error naming the runtime, the failing `.node` file and the exact install flags to use; that text was discarded and replaced with a different, wrong cause
696
715
 
697
- Only **genuine absence** now produces the install hint: a `MODULE_NOT_FOUND` whose message names the specifier `'sharp'` exactly. Matching on the code alone is not sufficient — a dependency missing *inside* sharp raises the very same code (`Cannot find module 'color'`), and would have been reported as sharp itself being absent. Any other failure surfaces sharp's own message, inlined as `Failed to load "sharp": …` **and** chained as `cause`, so a terminal that never prints `cause` still shows the text that helps. The absent-sharp path is unchanged, wording included
716
+ Only **genuine absence** now produces the install hint: a `MODULE_NOT_FOUND` whose message names the specifier `'sharp'` exactly. Matching on the code alone is not sufficient — a dependency missing _inside_ sharp raises the very same code (`Cannot find module 'color'`), and would have been reported as sharp itself being absent. Any other failure surfaces sharp's own message, inlined as `Failed to load "sharp": …` **and** chained as `cause`, so a terminal that never prints `cause` still shows the text that helps. The absent-sharp path is unchanged, wording included
698
717
 
699
718
  **The failure reason is cached, not just the fact of failure.** The resolution attempt runs once per process; a second `new Image(...)` skips the load entirely, so caching only "there is no sharp function" would have re-told the same lie one call later. The guard therefore constructs **twice** in each spawned process and asserts the second error matches the first (`tests/unit/image/image-sharp-load-failure.test.ts`) — a one-shot test passes even with that bug present
700
719
 
@@ -710,7 +729,7 @@ Details for each are in the entries below.
710
729
 
711
730
  As with sharp, the failure **reason** is cached rather than only the fact of failure, so the second call cannot fall through to the "not installed" branch and re-tell a lie the first call got right
712
731
 
713
- The guard is a spawned fresh Node process (`tests/unit/react/react-module-resolution.test.ts`); a same-process test cannot catch this, which is why the pre-existing suite was green against it. Against the live bug all five cases failed, and — the detail that shows how much the race hid — all five failed with the *same* `Cannot read properties of undefined` symptom, including the case that only asserts the install message. The present-but-broken states are staged by copying the module source next to a fixture `node_modules`, since resolution anchors to the importing file; the real workspace is not mutated
732
+ The guard is a spawned fresh Node process (`tests/unit/react/react-module-resolution.test.ts`); a same-process test cannot catch this, which is why the pre-existing suite was green against it. Against the live bug all five cases failed, and — the detail that shows how much the race hid — all five failed with the _same_ `Cannot read properties of undefined` symptom, including the case that only asserts the install message. The present-but-broken states are staged by copying the module source next to a fixture `node_modules`, since resolution anchors to the importing file; the real workspace is not mutated
714
733
 
715
734
  ## 4.11.0
716
735
 
@@ -733,17 +752,17 @@ Details for each are in the entries below.
733
752
 
734
753
  ### Fixed
735
754
 
736
- - **A production bundle no longer imports a package your app does not declare.** `warlock build`'s generated config loader emitted `import config from "@mongez/config"` — one of *core's* dependencies, never the app's. npm and yarn hoist flat so it resolved by accident; under pnpm's strict layout the shipped bundle died at boot with `ERR_MODULE_NOT_FOUND` for a package the app had no reason to install. The generator now emits `setConfig` from `@warlock.js/core`, which the app does declare, and Node resolves `@mongez/config` from core's own install — correct under pnpm, and portable, unlike baking absolute paths into an artifact meant to be copied between machines
755
+ - **A production bundle no longer imports a package your app does not declare.** `warlock build`'s generated config loader emitted `import config from "@mongez/config"` — one of _core's_ dependencies, never the app's. npm and yarn hoist flat so it resolved by accident; under pnpm's strict layout the shipped bundle died at boot with `ERR_MODULE_NOT_FOUND` for a package the app had no reason to install. The generator now emits `setConfig` from `@warlock.js/core`, which the app does declare, and Node resolves `@mongez/config` from core's own install — correct under pnpm, and portable, unlike baking absolute paths into an artifact meant to be copied between machines
737
756
 
738
757
  **The rule is now enforced, not just followed.** `warlock build` fails if any specifier written into generated code is missing from the app's `dependencies`, listing every violation at once. Rewriting the one bad import fixes today's bundle; the check is what stops the next change to the generator from reintroducing it invisibly — under npm and yarn the mistake never surfaces
739
758
 
740
759
  Two scaffolding sites had the same defect and are fixed with it: `warlock generate.module` emitted `groupedTranslations` from `@mongez/localization`, and the communicators config stub emitted `env` from `@mongez/dotenv`. Both now come from `@warlock.js/core`, which already re-exports them
741
760
 
742
- - **`env()` inside `warlock.config.ts` no longer always returns its default.** The config module was evaluated *before* any `.env` file was read, so a project following the documented `build: { outdir: env("BUILD_OUT", "dist") }` recipe silently got `dist` no matter what the environment said — under every command, `dev` included, and under `build` and `start` env was never loaded at all. Env files are now loaded before `warlock.config.ts` is evaluated, for every command
761
+ - **`env()` inside `warlock.config.ts` no longer always returns its default.** The config module was evaluated _before_ any `.env` file was read, so a project following the documented `build: { outdir: env("BUILD_OUT", "dist") }` recipe silently got `dist` no matter what the environment said — under every command, `dev` included, and under `build` and `start` env was never loaded at all. Env files are now loaded before `warlock.config.ts` is evaluated, for every command
743
762
 
744
763
  Loading is guarded: a project with no `.env` is legitimate and must not start failing `warlock build` now that env loads everywhere. `NODE_ENV` remains authoritative for which file is chosen — no command forces the environment, so a deliberate `NODE_ENV=staging` build still reads `.env.staging`. With `NODE_ENV` unset, plain `.env` is read
745
764
 
746
- - **An application without `src/config/storage.ts` can boot again.** The storage connector starts unconditionally, on the documented grounds that `storage.init()` falls back to a built-in `local` driver so file storage works out of the box. That fallback was never implemented: `init()` resolved the default driver *name* and then found nothing registered under it, so any app without a storage config died at boot with `Storage driver "local" is not configured`. A built-in `local` driver rooted at `uploadsPath()` is now registered before configured drivers — so an app defining its own `local` still overrides it, and naming a driver that genuinely does not exist still fails loudly
765
+ - **An application without `src/config/storage.ts` can boot again.** The storage connector starts unconditionally, on the documented grounds that `storage.init()` falls back to a built-in `local` driver so file storage works out of the box. That fallback was never implemented: `init()` resolved the default driver _name_ and then found nothing registered under it, so any app without a storage config died at boot with `Storage driver "local" is not configured`. A built-in `local` driver rooted at `uploadsPath()` is now registered before configured drivers — so an app defining its own `local` still overrides it, and naming a driver that genuinely does not exist still fails loudly
747
766
 
748
767
  Only scaffolded apps hid this, because `create-warlock` always ships a storage config
749
768
 
@@ -3,7 +3,11 @@ import { Model } from "@warlock.js/cascade";
3
3
 
4
4
  //#region ../core/src/database/utils.d.ts
5
5
  /**
6
- * Hash password on saving if password changes
6
+ * Hash password on saving if password changes.
7
+ *
8
+ * Uses core's own bcrypt `hashPassword` (salt rounds from
9
+ * `encryption.password.salt`). Core must never import `@warlock.js/auth`:
10
+ * auth depends on core, and its `authService.hashPassword` only delegates here.
7
11
  */
8
12
  declare const useHashedPassword: () => import("@warlock.js/seal").TransformerCallback;
9
13
  type ComputedCallbackModel = (data: any, model: Model, context: SchemaContext) => any | Promise<any>;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"mappings":";;;;;;AASA;cAAa,iBAAA,mCAAiB,mBAO1B;AAAA,KAEC,qBAAA,IACH,IAAA,OACA,KAAA,EAAO,KAAA,EACP,OAAA,EAAS,aAAA,WACA,OAAA;;AANP;AAAC;iBAWW,gBAAA,CAAiB,QAAA,EAAU,qBAAA,GAAqB,gBAAA;;;;iBAWhD,eAAA,CAAgB,KAAA,WAAiB,KAAA,0BAAuC,gBAAA"}
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"mappings":";;;;;;AAaA;;;;AAOI;cAPS,iBAAA,mCAAiB,mBAO1B;AAAA,KAEC,qBAAA,IACH,IAAA,OACA,KAAA,EAAO,KAAA,EACP,OAAA,EAAS,aAAA,WACA,OAAA;;;;iBAKK,gBAAA,CAAiB,QAAA,EAAU,qBAAA,GAAqB,gBAAA;;;;iBAWhD,eAAA,CAAgB,KAAA,WAAiB,KAAA,0BAAuC,gBAAA"}
@@ -1,16 +1,20 @@
1
+ import { hashPassword } from "../encryption/password.mjs";
1
2
  import { useModelTransformer } from "@warlock.js/cascade";
2
3
  import { slugify } from "@mongez/slug";
3
4
  import { get } from "@mongez/reinforcements";
4
- import { authService } from "@warlock.js/auth";
5
5
 
6
6
  //#region ../core/src/database/utils.ts
7
7
  /**
8
- * Hash password on saving if password changes
8
+ * Hash password on saving if password changes.
9
+ *
10
+ * Uses core's own bcrypt `hashPassword` (salt rounds from
11
+ * `encryption.password.salt`). Core must never import `@warlock.js/auth`:
12
+ * auth depends on core, and its `authService.hashPassword` only delegates here.
9
13
  */
10
14
  const useHashedPassword = () => useModelTransformer(({ value, isChanged, isNew }) => {
11
15
  if (!value) return value;
12
16
  if (!isNew && !isChanged) return value;
13
- return authService.hashPassword(String(value));
17
+ return hashPassword(String(value));
14
18
  });
15
19
  /**
16
20
  * Generate computed value based on other fields
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"sourcesContent":["import { get } from \"@mongez/reinforcements\";\nimport { slugify } from \"@mongez/slug\";\nimport { authService } from \"@warlock.js/auth\";\nimport { Model, useModelTransformer } from \"@warlock.js/cascade\";\nimport { type ComputedCallback, type SchemaContext } from \"@warlock.js/seal\";\n\n/**\n * Hash password on saving if password changes\n */\nexport const useHashedPassword = () =>\n useModelTransformer(({ value, isChanged, isNew }) => {\n if (!value) return value;\n\n if (!isNew && !isChanged) return value;\n\n return authService.hashPassword(String(value));\n });\n\ntype ComputedCallbackModel = (\n data: any,\n model: Model,\n context: SchemaContext,\n) => any | Promise<any>;\n\n/**\n * Generate computed value based on other fields\n */\nexport function useComputedModel(callback: ComputedCallbackModel) {\n const computedCallback: ComputedCallback = (data, context) => {\n return callback(data, context.rootContext!.model, context);\n };\n\n return computedCallback;\n}\n\n/**\n * Generate slug based on a field on saving\n */\nexport function useComputedSlug(field = \"title\", scope: \"global\" | \"sibling\" = \"sibling\") {\n return useComputedModel((data, model, context) => {\n const value = scope === \"sibling\" ? data[field] : get(context.allValues, field);\n\n if (!value) return model.get(field);\n\n return slugify(value);\n });\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,0BACX,qBAAqB,EAAE,OAAO,WAAW,YAAY;CACnD,IAAI,CAAC,OAAO,OAAO;CAEnB,IAAI,CAAC,SAAS,CAAC,WAAW,OAAO;CAEjC,OAAO,YAAY,aAAa,OAAO,KAAK,CAAC;AAC/C,CAAC;;;;AAWH,SAAgB,iBAAiB,UAAiC;CAChE,MAAM,oBAAsC,MAAM,YAAY;EAC5D,OAAO,SAAS,MAAM,QAAQ,YAAa,OAAO,OAAO;CAC3D;CAEA,OAAO;AACT;;;;AAKA,SAAgB,gBAAgB,QAAQ,SAAS,QAA8B,WAAW;CACxF,OAAO,kBAAkB,MAAM,OAAO,YAAY;EAChD,MAAM,QAAQ,UAAU,YAAY,KAAK,SAAS,IAAI,QAAQ,WAAW,KAAK;EAE9E,IAAI,CAAC,OAAO,OAAO,MAAM,IAAI,KAAK;EAElC,OAAO,QAAQ,KAAK;CACtB,CAAC;AACH"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"sourcesContent":["import { get } from \"@mongez/reinforcements\";\nimport { slugify } from \"@mongez/slug\";\nimport { Model, useModelTransformer } from \"@warlock.js/cascade\";\nimport { type ComputedCallback, type SchemaContext } from \"@warlock.js/seal\";\nimport { hashPassword } from \"../encryption/password\";\n\n/**\n * Hash password on saving if password changes.\n *\n * Uses core's own bcrypt `hashPassword` (salt rounds from\n * `encryption.password.salt`). Core must never import `@warlock.js/auth`:\n * auth depends on core, and its `authService.hashPassword` only delegates here.\n */\nexport const useHashedPassword = () =>\n useModelTransformer(({ value, isChanged, isNew }) => {\n if (!value) return value;\n\n if (!isNew && !isChanged) return value;\n\n return hashPassword(String(value));\n });\n\ntype ComputedCallbackModel = (\n data: any,\n model: Model,\n context: SchemaContext,\n) => any | Promise<any>;\n\n/**\n * Generate computed value based on other fields\n */\nexport function useComputedModel(callback: ComputedCallbackModel) {\n const computedCallback: ComputedCallback = (data, context) => {\n return callback(data, context.rootContext!.model, context);\n };\n\n return computedCallback;\n}\n\n/**\n * Generate slug based on a field on saving\n */\nexport function useComputedSlug(field = \"title\", scope: \"global\" | \"sibling\" = \"sibling\") {\n return useComputedModel((data, model, context) => {\n const value = scope === \"sibling\" ? data[field] : get(context.allValues, field);\n\n if (!value) return model.get(field);\n\n return slugify(value);\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,0BACX,qBAAqB,EAAE,OAAO,WAAW,YAAY;CACnD,IAAI,CAAC,OAAO,OAAO;CAEnB,IAAI,CAAC,SAAS,CAAC,WAAW,OAAO;CAEjC,OAAO,aAAa,OAAO,KAAK,CAAC;AACnC,CAAC;;;;AAWH,SAAgB,iBAAiB,UAAiC;CAChE,MAAM,oBAAsC,MAAM,YAAY;EAC5D,OAAO,SAAS,MAAM,QAAQ,YAAa,OAAO,OAAO;CAC3D;CAEA,OAAO;AACT;;;;AAKA,SAAgB,gBAAgB,QAAQ,SAAS,QAA8B,WAAW;CACxF,OAAO,kBAAkB,MAAM,OAAO,YAAY;EAChD,MAAM,QAAQ,UAAU,YAAY,KAAK,SAAS,IAAI,QAAQ,WAAW,KAAK;EAE9E,IAAI,CAAC,OAAO,OAAO,MAAM,IAAI,KAAK;EAElC,OAAO,QAAQ,KAAK;CACtB,CAAC;AACH"}
@@ -2,10 +2,13 @@ import { Path } from "../utils/normalized-path.mjs";
2
2
  import { devLogSuccess } from "./dev-logger.mjs";
3
3
  import { isTimingsEnabled } from "./flags.mjs";
4
4
  import { clearFileExistsCache } from "./parse-imports.mjs";
5
- import { debounce } from "@mongez/reinforcements";
6
5
  import events from "@mongez/events";
7
6
 
8
7
  //#region ../core/src/dev-server/file-event-handler.ts
8
+ /** Lets an isolated editor save reach HMR without the former fixed 50ms delay. */
9
+ const ISOLATED_SAVE_QUIET_WINDOW_MS = 12;
10
+ /** Bounds a sustained formatter or checkout stream so it cannot postpone HMR forever. */
11
+ const BATCH_MAX_WAIT_MS = 60;
9
12
  /**
10
13
  * Receives raw watcher events and processes them in a single debounced batch.
11
14
  * Order within a batch: adds → changes → deletes, so changes can reference
@@ -20,22 +23,37 @@ var FileEventHandler = class {
20
23
  this.pendingChanges = /* @__PURE__ */ new Set();
21
24
  this.pendingAdds = /* @__PURE__ */ new Set();
22
25
  this.pendingDeletes = /* @__PURE__ */ new Set();
23
- this.processPendingEvents = debounce(() => this.processBatch(), 50);
24
26
  }
25
27
  handleFileChange(absolutePath, settleMs) {
26
28
  this.recordTimingStart(settleMs);
27
29
  this.pendingChanges.add(Path.toRelative(absolutePath));
28
- this.processPendingEvents();
30
+ this.schedulePendingEvents();
29
31
  }
30
32
  handleFileAdd(absolutePath, settleMs) {
31
33
  this.recordTimingStart(settleMs);
32
34
  this.pendingAdds.add(Path.toRelative(absolutePath));
33
- this.processPendingEvents();
35
+ this.schedulePendingEvents();
34
36
  }
35
37
  handleFileDelete(absolutePath, settleMs) {
36
38
  this.recordTimingStart(settleMs);
37
39
  this.pendingDeletes.add(Path.toRelative(absolutePath));
38
- this.processPendingEvents();
40
+ this.schedulePendingEvents();
41
+ }
42
+ schedulePendingEvents() {
43
+ if (this.debounceTimer !== void 0) clearTimeout(this.debounceTimer);
44
+ this.debounceTimer = setTimeout(() => this.flushPendingEvents(), ISOLATED_SAVE_QUIET_WINDOW_MS);
45
+ if (this.maxWaitTimer === void 0) this.maxWaitTimer = setTimeout(() => this.flushPendingEvents(), BATCH_MAX_WAIT_MS);
46
+ }
47
+ flushPendingEvents() {
48
+ if (this.debounceTimer !== void 0) {
49
+ clearTimeout(this.debounceTimer);
50
+ this.debounceTimer = void 0;
51
+ }
52
+ if (this.maxWaitTimer !== void 0) {
53
+ clearTimeout(this.maxWaitTimer);
54
+ this.maxWaitTimer = void 0;
55
+ }
56
+ this.processBatch();
39
57
  }
40
58
  /**
41
59
  * Mark the debounce-wait phase start on the first event of a batch, and
@@ -1 +1 @@
1
- {"version":3,"file":"file-event-handler.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/file-event-handler.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport { debounce } from \"@mongez/reinforcements\";\nimport type { DependencyGraph } from \"./dependency-graph\";\nimport { devLogSuccess } from \"./dev-logger\";\nimport type { FileManager } from \"./file-manager\";\nimport type { FileOperations } from \"./file-operations\";\nimport { FILE_PROCESSING_BATCH_SIZE, isTimingsEnabled } from \"./flags\";\nimport type { ManifestManager } from \"./manifest-manager\";\nimport { clearFileExistsCache } from \"./parse-imports\";\nimport { Path } from \"../utils/normalized-path\";\n\n/**\n * Receives raw watcher events and processes them in a single debounced batch.\n * Order within a batch: adds → changes → deletes, so changes can reference\n * newly-added files and deletes fire last.\n */\nexport class FileEventHandler {\n private pendingChanges = new Set<string>();\n private pendingAdds = new Set<string>();\n private pendingDeletes = new Set<string>();\n\n /** When this batch's first watcher event arrived — the debounce-wait phase start. */\n private batchStartedAt?: number;\n\n /** Slowest watcher-settle duration seen so far this batch, when `devServer.timings` is on. */\n private watcherSettleMs?: number;\n\n private readonly processPendingEvents = debounce(() => this.processBatch(), 50);\n\n constructor(\n private readonly fileOperations: FileOperations,\n private readonly manifest: ManifestManager,\n private readonly dependencyGraph: DependencyGraph,\n private readonly files: Map<string, FileManager>,\n ) {}\n\n public handleFileChange(absolutePath: string, settleMs?: number): void {\n this.recordTimingStart(settleMs);\n this.pendingChanges.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n public handleFileAdd(absolutePath: string, settleMs?: number): void {\n this.recordTimingStart(settleMs);\n this.pendingAdds.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n public handleFileDelete(absolutePath: string, settleMs?: number): void {\n this.recordTimingStart(settleMs);\n this.pendingDeletes.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n /**\n * Mark the debounce-wait phase start on the first event of a batch, and\n * track the slowest watcher-settle duration seen this batch. `settleMs`\n * only arrives when `devServer.timings` is on (see `FilesWatcher`), so\n * this is a no-op past the cheap `performance.now()` call when it's off.\n */\n private recordTimingStart(settleMs?: number): void {\n if (this.batchStartedAt === undefined) {\n this.batchStartedAt = performance.now();\n }\n\n if (settleMs === undefined) return;\n\n this.watcherSettleMs =\n this.watcherSettleMs === undefined ? settleMs : Math.max(this.watcherSettleMs, settleMs);\n }\n\n private async processBatch(): Promise<void> {\n const changes = Array.from(this.pendingChanges);\n const adds = Array.from(this.pendingAdds);\n const deletes = Array.from(this.pendingDeletes);\n\n this.pendingChanges.clear();\n this.pendingAdds.clear();\n this.pendingDeletes.clear();\n\n const debounceWaitMs =\n this.batchStartedAt !== undefined ? performance.now() - this.batchStartedAt : undefined;\n const watcherSettleMs = this.watcherSettleMs;\n this.batchStartedAt = undefined;\n this.watcherSettleMs = undefined;\n\n if (changes.length === 0 && adds.length === 0 && deletes.length === 0) return;\n\n // Both .env files and warlock.config.ts live outside src/ — they should\n // never enter the dep graph, only ride along in the batch event so the\n // dev server can react (config reload / restart warning).\n const externalChanges = changes.filter(isExternalPath);\n const externalAdds = adds.filter(isExternalPath);\n const codeChanges = changes.filter((p) => !isExternalPath(p));\n const codeAdds = adds.filter((p) => !isExternalPath(p));\n\n // Multi-file batches can race the filesystem on Windows.\n if (codeAdds.length + codeChanges.length > 1) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n clearFileExistsCache();\n }\n\n const { added: addedCodePaths, vanished } = await this.processBatchAdds(codeAdds);\n const changedCodePaths = await this.processBatchChanges(codeChanges);\n await this.processBatchDeletes(deletes);\n\n this.fileOperations.updateFileDependents();\n this.fileOperations.syncFilesToManifest();\n await this.manifest.save();\n\n // Emit only the code paths that genuinely changed (hash differs). A no-op\n // save — an editor that fsyncs without writing — reports no change and is\n // dropped here, where we still know the pre-change hash. (Doing this\n // downstream is impossible: the source has already been overwritten, so a\n // content compare always looks unchanged — which is exactly why emptying a\n // file used to silently skip HMR.) External paths (.env / warlock.config.ts)\n // ride along untouched so the dev server can still react to them. Paths\n // that vanished between the add event and their read/stat (a rename or\n // move racing the filesystem) are folded into `deleted` instead of\n // `added` — they were already unwound as deletions in processBatchAdds.\n events.trigger(\"dev-server:batch-complete\", {\n added: [...externalAdds, ...addedCodePaths],\n changed: [...externalChanges, ...changedCodePaths],\n deleted: [...deletes, ...vanished],\n timings: isTimingsEnabled()\n ? { watcherSettleMs: watcherSettleMs ?? 0, debounceWaitMs: debounceWaitMs ?? 0 }\n : undefined,\n });\n }\n\n /**\n * Reprocess each changed file and return only the paths that genuinely\n * changed. `updateFile` returns false when the on-disk hash matches the\n * last-processed hash (e.g. an editor that fsyncs on save without writing),\n * so those no-ops are kept out of the reload batch. Emptying a file changes\n * its hash, so it is correctly reported as changed.\n */\n private async processBatchChanges(relativePaths: string[]): Promise<string[]> {\n const changed: string[] = [];\n await runInBatches(relativePaths, FILE_PROCESSING_BATCH_SIZE, async (path) => {\n if (await this.fileOperations.updateFile(path)) {\n changed.push(path);\n }\n });\n return changed;\n }\n\n /**\n * Process pending add events. Returns the paths that genuinely became\n * available (`added`) separately from paths that no longer existed by the\n * time they were read/stat'd (`vanished`) — the latter is a rename or move\n * racing the filesystem, not a failure, so it is unwound as a deletion\n * instead of being logged as an error.\n */\n private async processBatchAdds(\n relativePaths: string[],\n ): Promise<{ added: string[]; vanished: string[] }> {\n const added: string[] = [];\n const vanished: string[] = [];\n\n await runInBatches(relativePaths, FILE_PROCESSING_BATCH_SIZE, async (path) => {\n try {\n const fileManager = await this.fileOperations.addFile(path);\n\n if (fileManager.state === \"deleted\") {\n await this.fileOperations.deleteFile(path);\n vanished.push(path);\n return;\n }\n\n added.push(path);\n devLogSuccess(`Added file: ${path}`);\n } catch (error) {\n console.error(`Failed to add file ${path}:`, error);\n }\n });\n\n return { added, vanished };\n }\n\n private async processBatchDeletes(relativePaths: string[]): Promise<void> {\n for (const relativePath of relativePaths) {\n await this.fileOperations.deleteFile(relativePath);\n devLogSuccess(`Deleted file: ${relativePath}`);\n }\n }\n}\n\nfunction isEnvFile(path: string): boolean {\n const basename = path.split(\"/\").pop() || path;\n return basename === \".env\" || basename.startsWith(\".env.\");\n}\n\n/** Paths watched but never added to the dependency graph. */\nfunction isExternalPath(path: string): boolean {\n return isEnvFile(path) || path === \"warlock.config.ts\";\n}\n\nasync function runInBatches<T>(\n items: T[],\n size: number,\n fn: (item: T) => Promise<unknown>,\n): Promise<void> {\n if (items.length === 0) return;\n for (let i = 0; i < items.length; i += size) {\n await Promise.all(items.slice(i, i + size).map(fn));\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,IAAa,mBAAb,MAA8B;CAa5B,YACE,AAAiB,gBACjB,AAAiB,UACjB,AAAiB,iBACjB,AAAiB,OACjB;EAJiB;EACA;EACA;EACA;wCAhBM,IAAI,IAAY;qCACnB,IAAI,IAAY;wCACb,IAAI,IAAY;8BAQD,eAAe,K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sBAAsB,KAAK,IAAI,KAAK;GACpD;EACF,CAAC;EAED,OAAO;GAAE;GAAO;EAAS;CAC3B;CAEA,MAAc,oBAAoB,eAAwC;EACxE,KAAK,MAAM,gBAAgB,eAAe;GACxC,MAAM,KAAK,eAAe,WAAW,YAAY;GACjD,cAAc,iBAAiB,cAAc;EAC/C;CACF;AACF;AAEA,SAAS,UAAU,MAAuB;CACxC,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC1C,OAAO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D;;AAGA,SAAS,eAAe,MAAuB;CAC7C,OAAO,UAAU,IAAI,KAAK,SAAS;AACrC;AAEA,eAAe,aACb,OACA,MACA,IACe;CACf,IAAI,MAAM,WAAW,GAAG;CACxB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MACrC,MAAM,QAAQ,IAAI,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAEtD"}
1
+ {"version":3,"file":"file-event-handler.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/file-event-handler.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport type { DependencyGraph } from \"./dependency-graph\";\nimport { devLogSuccess } from \"./dev-logger\";\nimport type { FileManager } from \"./file-manager\";\nimport type { FileOperations } from \"./file-operations\";\nimport { FILE_PROCESSING_BATCH_SIZE, isTimingsEnabled } from \"./flags\";\nimport type { ManifestManager } from \"./manifest-manager\";\nimport { clearFileExistsCache } from \"./parse-imports\";\nimport { Path } from \"../utils/normalized-path\";\n\n/** Lets an isolated editor save reach HMR without the former fixed 50ms delay. */\nconst ISOLATED_SAVE_QUIET_WINDOW_MS = 12;\n\n/** Bounds a sustained formatter or checkout stream so it cannot postpone HMR forever. */\nconst BATCH_MAX_WAIT_MS = 60;\n\n/**\n * Receives raw watcher events and processes them in a single debounced batch.\n * Order within a batch: adds → changes → deletes, so changes can reference\n * newly-added files and deletes fire last.\n */\nexport class FileEventHandler {\n private pendingChanges = new Set<string>();\n private pendingAdds = new Set<string>();\n private pendingDeletes = new Set<string>();\n\n /** When this batch's first watcher event arrived — the debounce-wait phase start. */\n private batchStartedAt?: number;\n\n /** Slowest watcher-settle duration seen so far this batch, when `devServer.timings` is on. */\n private watcherSettleMs?: number;\n\n private debounceTimer?: ReturnType<typeof setTimeout>;\n private maxWaitTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n private readonly fileOperations: FileOperations,\n private readonly manifest: ManifestManager,\n private readonly dependencyGraph: DependencyGraph,\n private readonly files: Map<string, FileManager>,\n ) {}\n\n public handleFileChange(absolutePath: string, settleMs?: number): void {\n this.recordTimingStart(settleMs);\n this.pendingChanges.add(Path.toRelative(absolutePath));\n this.schedulePendingEvents();\n }\n\n public handleFileAdd(absolutePath: string, settleMs?: number): void {\n this.recordTimingStart(settleMs);\n this.pendingAdds.add(Path.toRelative(absolutePath));\n this.schedulePendingEvents();\n }\n\n public handleFileDelete(absolutePath: string, settleMs?: number): void {\n this.recordTimingStart(settleMs);\n this.pendingDeletes.add(Path.toRelative(absolutePath));\n this.schedulePendingEvents();\n }\n\n private schedulePendingEvents(): void {\n if (this.debounceTimer !== undefined) {\n clearTimeout(this.debounceTimer);\n }\n\n this.debounceTimer = setTimeout(() => this.flushPendingEvents(), ISOLATED_SAVE_QUIET_WINDOW_MS);\n\n if (this.maxWaitTimer === undefined) {\n this.maxWaitTimer = setTimeout(() => this.flushPendingEvents(), BATCH_MAX_WAIT_MS);\n }\n }\n\n private flushPendingEvents(): void {\n if (this.debounceTimer !== undefined) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n if (this.maxWaitTimer !== undefined) {\n clearTimeout(this.maxWaitTimer);\n this.maxWaitTimer = undefined;\n }\n\n void this.processBatch();\n }\n\n /**\n * Mark the debounce-wait phase start on the first event of a batch, and\n * track the slowest watcher-settle duration seen this batch. `settleMs`\n * only arrives when `devServer.timings` is on (see `FilesWatcher`), so\n * this is a no-op past the cheap `performance.now()` call when it's off.\n */\n private recordTimingStart(settleMs?: number): void {\n if (this.batchStartedAt === undefined) {\n this.batchStartedAt = performance.now();\n }\n\n if (settleMs === undefined) return;\n\n this.watcherSettleMs =\n this.watcherSettleMs === undefined ? settleMs : Math.max(this.watcherSettleMs, settleMs);\n }\n\n private async processBatch(): Promise<void> {\n const changes = Array.from(this.pendingChanges);\n const adds = Array.from(this.pendingAdds);\n const deletes = Array.from(this.pendingDeletes);\n\n this.pendingChanges.clear();\n this.pendingAdds.clear();\n this.pendingDeletes.clear();\n\n const debounceWaitMs =\n this.batchStartedAt !== undefined ? performance.now() - this.batchStartedAt : undefined;\n const watcherSettleMs = this.watcherSettleMs;\n this.batchStartedAt = undefined;\n this.watcherSettleMs = undefined;\n\n if (changes.length === 0 && adds.length === 0 && deletes.length === 0) return;\n\n // Both .env files and warlock.config.ts live outside src/ — they should\n // never enter the dep graph, only ride along in the batch event so the\n // dev server can react (config reload / restart warning).\n const externalChanges = changes.filter(isExternalPath);\n const externalAdds = adds.filter(isExternalPath);\n const codeChanges = changes.filter((p) => !isExternalPath(p));\n const codeAdds = adds.filter((p) => !isExternalPath(p));\n\n // Multi-file batches can race the filesystem on Windows.\n if (codeAdds.length + codeChanges.length > 1) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n clearFileExistsCache();\n }\n\n const { added: addedCodePaths, vanished } = await this.processBatchAdds(codeAdds);\n const changedCodePaths = await this.processBatchChanges(codeChanges);\n await this.processBatchDeletes(deletes);\n\n this.fileOperations.updateFileDependents();\n this.fileOperations.syncFilesToManifest();\n await this.manifest.save();\n\n // Emit only the code paths that genuinely changed (hash differs). A no-op\n // save — an editor that fsyncs without writing — reports no change and is\n // dropped here, where we still know the pre-change hash. (Doing this\n // downstream is impossible: the source has already been overwritten, so a\n // content compare always looks unchanged — which is exactly why emptying a\n // file used to silently skip HMR.) External paths (.env / warlock.config.ts)\n // ride along untouched so the dev server can still react to them. Paths\n // that vanished between the add event and their read/stat (a rename or\n // move racing the filesystem) are folded into `deleted` instead of\n // `added` — they were already unwound as deletions in processBatchAdds.\n events.trigger(\"dev-server:batch-complete\", {\n added: [...externalAdds, ...addedCodePaths],\n changed: [...externalChanges, ...changedCodePaths],\n deleted: [...deletes, ...vanished],\n timings: isTimingsEnabled()\n ? { watcherSettleMs: watcherSettleMs ?? 0, debounceWaitMs: debounceWaitMs ?? 0 }\n : undefined,\n });\n }\n\n /**\n * Reprocess each changed file and return only the paths that genuinely\n * changed. `updateFile` returns false when the on-disk hash matches the\n * last-processed hash (e.g. an editor that fsyncs on save without writing),\n * so those no-ops are kept out of the reload batch. Emptying a file changes\n * its hash, so it is correctly reported as changed.\n */\n private async processBatchChanges(relativePaths: string[]): Promise<string[]> {\n const changed: string[] = [];\n await runInBatches(relativePaths, FILE_PROCESSING_BATCH_SIZE, async (path) => {\n if (await this.fileOperations.updateFile(path)) {\n changed.push(path);\n }\n });\n return changed;\n }\n\n /**\n * Process pending add events. Returns the paths that genuinely became\n * available (`added`) separately from paths that no longer existed by the\n * time they were read/stat'd (`vanished`) — the latter is a rename or move\n * racing the filesystem, not a failure, so it is unwound as a deletion\n * instead of being logged as an error.\n */\n private async processBatchAdds(\n relativePaths: string[],\n ): Promise<{ added: string[]; vanished: string[] }> {\n const added: string[] = [];\n const vanished: string[] = [];\n\n await runInBatches(relativePaths, FILE_PROCESSING_BATCH_SIZE, async (path) => {\n try {\n const fileManager = await this.fileOperations.addFile(path);\n\n if (fileManager.state === \"deleted\") {\n await this.fileOperations.deleteFile(path);\n vanished.push(path);\n return;\n }\n\n added.push(path);\n devLogSuccess(`Added file: ${path}`);\n } catch (error) {\n console.error(`Failed to add file ${path}:`, error);\n }\n });\n\n return { added, vanished };\n }\n\n private async processBatchDeletes(relativePaths: string[]): Promise<void> {\n for (const relativePath of relativePaths) {\n await this.fileOperations.deleteFile(relativePath);\n devLogSuccess(`Deleted file: ${relativePath}`);\n }\n }\n}\n\nfunction isEnvFile(path: string): boolean {\n const basename = path.split(\"/\").pop() || path;\n return basename === \".env\" || basename.startsWith(\".env.\");\n}\n\n/** Paths watched but never added to the dependency graph. */\nfunction isExternalPath(path: string): boolean {\n return isEnvFile(path) || path === \"warlock.config.ts\";\n}\n\nasync function runInBatches<T>(\n items: T[],\n size: number,\n fn: (item: T) => Promise<unknown>,\n): Promise<void> {\n if (items.length === 0) return;\n for (let i = 0; i < items.length; i += size) {\n await Promise.all(items.slice(i, i + size).map(fn));\n }\n}\n"],"mappings":";;;;;;;;AAWA,MAAM,gCAAgC;;AAGtC,MAAM,oBAAoB;;;;;;AAO1B,IAAa,mBAAb,MAA8B;CAc5B,YACE,AAAiB,gBACjB,AAAiB,UACjB,AAAiB,iBACjB,AAAiB,OACjB;EAJiB;EACA;EACA;EACA;wCAjBM,IAAI,IAAY;qCACnB,IAAI,IAAY;wCACb,IAAI,IAAY;CAgBtC;CAEH,AAAO,iBAAiB,cAAsB,UAAyB;EACrE,KAAK,kBAAkB,QAAQ;EAC/B,KAAK,eAAe,IAAI,KAAK,WAAW,YAAY,CAAC;EACrD,KAAK,sBAAsB;CAC7B;CAEA,AAAO,cAAc,cAAsB,UAAyB;EAClE,KAAK,kBAAkB,QAAQ;EAC/B,KAAK,YAAY,IAAI,KAAK,WAAW,YAAY,CAAC;EAClD,KAAK,sBAAsB;CAC7B;CAEA,AAAO,iBAAiB,cAAsB,UAAyB;EACrE,KAAK,kBAAkB,QAAQ;EAC/B,KAAK,eAAe,IAAI,KAAK,WAAW,YAAY,CAAC;EACrD,KAAK,sBAAsB;CAC7B;CAEA,AAAQ,wBAA8B;EACpC,IAAI,KAAK,kBAAkB,QACzB,aAAa,KAAK,aAAa;EAGjC,KAAK,gBAAgB,iBAAiB,KAAK,mBAAmB,GAAG,6BAA6B;EAE9F,IAAI,KAAK,iBAAiB,QACxB,KAAK,eAAe,iBAAiB,KAAK,mBAAmB,GAAG,iBAAiB;CAErF;CAEA,AAAQ,qBAA2B;EACjC,IAAI,KAAK,k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AAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC1C,OAAO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D;;AAGA,SAAS,eAAe,MAAuB;CAC7C,OAAO,UAAU,IAAI,KAAK,SAAS;AACrC;AAEA,eAAe,aACb,OACA,MACA,IACe;CACf,IAAI,MAAM,WAAW,GAAG;CACxB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MACrC,MAAM,QAAQ,IAAI,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAEtD"}
@@ -0,0 +1,28 @@
1
+ import ts from "typescript";
2
+
3
+ //#region ../core/src/dev-server/translation-type-generator.ts
4
+ /** Extract literal lookup keys registered through groupedTranslations calls. */
5
+ function extractTranslationKeys(sourceFile) {
6
+ const keys = /* @__PURE__ */ new Set();
7
+ const visit = (node) => {
8
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "groupedTranslations") {
9
+ const [groupArgument, dictionaryArgument] = node.arguments;
10
+ if (ts.isStringLiteral(groupArgument) && dictionaryArgument && ts.isObjectLiteralExpression(dictionaryArgument)) for (const property of dictionaryArgument.properties) {
11
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) continue;
12
+ const key = getPropertyName(property.name);
13
+ if (key !== void 0) keys.add(`${groupArgument.text}.${key}`);
14
+ }
15
+ }
16
+ ts.forEachChild(node, visit);
17
+ };
18
+ ts.forEachChild(sourceFile, visit);
19
+ return Array.from(keys).sort();
20
+ }
21
+ function getPropertyName(name) {
22
+ if (name === void 0) return;
23
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text;
24
+ }
25
+
26
+ //#endregion
27
+ export { extractTranslationKeys };
28
+ //# sourceMappingURL=translation-type-generator.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translation-type-generator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/translation-type-generator.ts"],"sourcesContent":["import ts from \"typescript\";\n\n/** Extract literal lookup keys registered through groupedTranslations calls. */\nexport function extractTranslationKeys(sourceFile: ts.SourceFile): string[] {\n const keys = new Set<string>();\n\n const visit = (node: ts.Node): void => {\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n node.expression.text === \"groupedTranslations\"\n ) {\n const [groupArgument, dictionaryArgument] = node.arguments;\n\n if (\n ts.isStringLiteral(groupArgument) &&\n dictionaryArgument &&\n ts.isObjectLiteralExpression(dictionaryArgument)\n ) {\n for (const property of dictionaryArgument.properties) {\n if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) {\n continue;\n }\n\n const key = getPropertyName(property.name);\n if (key !== undefined) {\n keys.add(`${groupArgument.text}.${key}`);\n }\n }\n }\n }\n\n ts.forEachChild(node, visit);\n };\n\n ts.forEachChild(sourceFile, visit);\n\n return Array.from(keys).sort();\n}\n\nfunction getPropertyName(name: ts.PropertyName | undefined): string | undefined {\n if (name === undefined) {\n return undefined;\n }\n\n if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {\n return name.text;\n }\n\n return undefined;\n}\n"],"mappings":";;;;AAGA,SAAgB,uBAAuB,YAAqC;CAC1E,MAAM,uBAAO,IAAI,IAAY;CAE7B,MAAM,SAAS,SAAwB;EACrC,IACE,GAAG,iBAAiB,IAAI,KACxB,GAAG,aAAa,KAAK,UAAU,KAC/B,KAAK,WAAW,SAAS,uBACzB;GACA,MAAM,CAAC,eAAe,sBAAsB,KAAK;GAEjD,IACE,GAAG,gBAAgB,aAAa,KAChC,sBACA,GAAG,0BAA0B,kBAAkB,GAE/C,KAAK,MAAM,YAAY,mBAAmB,YAAY;IACpD,IAAI,CAAC,GAAG,qBAAqB,QAAQ,KAAK,CAAC,GAAG,8BAA8B,QAAQ,GAClF;IAGF,MAAM,MAAM,gBAAgB,SAAS,IAAI;IACzC,IAAI,QAAQ,QACV,KAAK,IAAI,GAAG,cAAc,KAAK,GAAG,KAAK;GAE3C;EAEJ;EAEA,GAAG,aAAa,MAAM,KAAK;CAC7B;CAEA,GAAG,aAAa,YAAY,KAAK;CAEjC,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,KAAK;AAC/B;AAEA,SAAS,gBAAgB,MAAuD;CAC9E,IAAI,SAAS,QACX;CAGF,IAAI,GAAG,aAAa,IAAI,KAAK,GAAG,gBAAgB,IAAI,KAAK,GAAG,iBAAiB,IAAI,GAC/E,OAAO,KAAK;AAIhB"}