@dokebi/cli 0.4.54 → 0.4.56

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/AI.md CHANGED
@@ -84,7 +84,7 @@ The `blog` plan, depending on the answers: `init` (when the folder is not a proj
84
84
  | `dokebi describe [--with-db] [--timeout-ms <ms>]` | What the app has, without serving (D-0077): it loads the project like `start` (the settings file — `DOKEBI_CONFIG`, else dokebi.yaml —, `src/dokebi.generated.ts`, the project's `.env` under the environment, the doctor check first: `START_CHECK_FAILED`) in core's describe mode: every plugin's setup runs, no start or ready hook, so nothing listens, no database, Redis or NATS connection is opened and no job is bound. `--json` is `{ schemaVersion: 1, app: { name, core, plugins[{name, version, described}], apps[], domains[], unknownDomain, web, session, csrf, auth, … }, routes[{method, url, id?, app?, host?, constraints?, schema?{body, querystring, params, headers, response}, config?{auth, can, roles, csrf, …}, auth?{mode, realm, via, can?}, seal?, health?}], pages[{app, engine: ejs\|inertia, template, name, file}], jobs[], schedules[], errors[{code, status, message, hint?}], config: { keys[], env[{name, plugin, purpose}] }, db: { connections[{name, adapter, startup?, dialect?, schemas?, tables?, collections?, unavailable?}], unavailable? }, unavailable[{plugin, section?, code, reason}], warnings?, ms }`, checked by the JSON Schema `describe.schema.json` of this package. `route.auth` is the login rule @dokebi/auth applies (its `default` included); `config.keys` are option paths and `config.env` variable names, **never a value**; `errors` are the codes of `src/shared/errors.ts`. A plugin whose setup fails is listed in `unavailable` (with the plugins that need it, `DEPENDENCY_UNAVAILABLE`) and the rest is still described; a database, Redis, NATS, SMTP or S3 that is not running is never the reason (D-0133: plugins on never-connected clients still set up; a nats event bus refuses only `publish`, with `DESCRIBING`), while a real configuration error (an unknown connection name, a connection of the wrong kind) still is. Without `--with-db` the tables are not read (`db.unavailable` says so; describe mode never connects). **`--with-db`** adds a separate step that connects: for each dokebi-db connection it runs the project's `dokebi-migrate schema --connection <name> --json` (@dokebi/migrate 0.4.2) and puts its `dialect` and `tables` (columns with type, nullable, default, identity, generated; primary key, unique, indexes, foreign keys, checks; `isMigrationHistory` on `dokebi_migrations`) or MongoDB `collections` into `db.connections[]`; a connection it cannot read (not listed in `options.dokebi-migrate.connections`, @dokebi/migrate missing, the database refused, `--timeout-ms` passed) gets its own `unavailable` reason and describe still answers. `startup: 'optional'` marks a connection dokebi.yaml lets the app run without ([D-0127](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0127-optional-db-startup.md); the default `required` is left out); `dokebi-migrate schema` opens it as required, so while it is down it is `unavailable` with the open or check error, and `drift` lists it in `unavailable`. No URL or password is printed. Run it before writing a migration so you change what the database really has. Errors: `DESCRIBE_TIMEOUT` (default 30000 ms), `DESCRIBE_FAILED` (the app exited first; `details.output` holds its last lines), `DESCRIBE_UNSUPPORTED` (@dokebi/core older than 0.4.2), or the app's own code (`INVALID_PLUGIN_OPTIONS`, …). Read it before you change an app you did not write |
85
85
  | `dokebi describe --openapi [--app <name>]` | OpenAPI 3.1 of the same description (D-0077 C), **one document per app** (route ids are unique per app): `info.title` the app, `servers` its domains (`http://<host>:<port>` for local hosts, `https://<host>` otherwise), `operationId` the route `config.id` (`<id>_<method>` on every operation when the id names several: a route of several methods, or the routes of one plugin route key such as `oauth.authorize_get` and `oauth.authorize_post`, D-0142), else `<method>_<path>` (`get_posts_id`), numbered `_2` on a collision. Request parameters and bodies (JSON, and form bodies with `formBody`) and responses come from the route schemas (draft-07 `items` tuples, `dependencies`, `nullable` and local `#/definitions` refs rewritten for JSON Schema 2020-12; a ref to an `addSchema` schema becomes an open schema with `x-dokebi-ref`). `components.schemas.DokebiError` is the D-0074 body; operations list 422 `VALIDATION_FAILED` (body or query schema), 400 `INVALID_REQUEST` (params or headers schema), 401 `UNAUTHENTICATED` (a login needed), 403 `FORBIDDEN` (`roles` or `can`) and 403 `CSRF_FAILED` (POST, PUT, PATCH, DELETE under @dokebi/csrf unless `config.csrf: false` or `exclude`, with the token header). Security: `cookieAuth` (the session cookie) and `bearerAuth` (`via: token` or `any`), `{}` added for `optional`; `x-dokebi-auth` keeps `{ mode, realm, via, roles?, can? }` (also `routes[].auth.roles` in `--json`). Health and Vite dev routes are left out; routes outside apps are in every app's document. The app's `defineErrors` codes are `x-dokebi-errors`. Without `--app` and with several apps: `{ apps: { <name>: document } }`; an unknown name is `UNKNOWN_APP`. Without `--json` the document is printed as JSON |
86
86
  | `dokebi drift --expected <file> [--timeout-ms <ms>]` | The databases against an expected file (D-0120): `<file>` is JSON of the describe shape, written by hand or by a design tool (only `db.connections` is read; a whole `describe --with-db --json` envelope works too). The actual side is `describe --with-db` (it connects the same way). Only what the file names is compared: each connection, its `tables` (or MongoDB `collections`) when the file lists them, a table's `columns` when it lists them, and a column's `comment` when it is a non-empty string (empty, `null` or absent means "not decided" and is not compared; whitespace runs and the ends are normalized). `--json` is `{ ok, drift[{kind, connection, target, expected_value, code_value}], unavailable[{connection, reason}], compared{connections, tables, columns, comments}, ms }`; `kind` is `connection`, `table`, `collection`, `column` or `column_comment`; `target` is the connection, `<table>` (`<schema>.<table>` outside the first PostgreSQL schema) or `<table>.<column>`; `expected_value` null = only the database has it, `code_value` null = the database has it not (for `column_comment`: no comment). `dokebi_migrations` is never compared. A connection that cannot be read is in `unavailable` and nothing is compared for it. `ok` only without drift and unavailable connections (otherwise exit 1). A comment comes from the migrations: PostgreSQL `COMMENT ON COLUMN <table>.<column> IS '<text>'` (`IS NULL` removes it), MySQL and MariaDB `COMMENT '<text>'` in the column definition (`ALTER TABLE … MODIFY` repeats the whole definition); `describe --with-db` shows it as `columns[].comment`. MongoDB has no column comments. Errors: `DRIFT_EXPECTED_INVALID` (the file cannot be read, is not JSON or not of the describe shape; `details.path`), and those of describe |
87
- | `dokebi check` | User-code conventions (D-0072). `{ ok, problems[{rule, severity?, file, line, message, fix}], allowed[{rule, file, line, reason}], files, rules, typescript, ms: { total, typescript } }` (`allowed`: every `// dokebi-check: allow <rule> <reason>` marker with a reason under `src/`, the problems silenced on purpose; the human output prints one `allowed` line each, and verify ok asks the final message to list them), exit 1 on a problem (a `severity: 'warning'` problem is reported but never fails: `ok` stays true). The human output prints `file:line rule message` and a `fix:` line per problem, then a summary (`check ok` or `check FAILED: N problems`, files, time). Rules: `empty-catch` (an empty `catch`, `.catch(() => {})`, an empty onRejected of `then`, an empty `on('error', …)`, and the same handlers when they only give back nothing: `() => undefined`, `() => null`, `() => void 0`, `{ return; }`; a fallback value such as `() => false` is not flagged), `missing-cause` (a `catch` that throws a new error and never reads the one it caught — `catch { throw new X() }`, `catch { throw fail() }` (a call that makes the error counts the same) or a named error left unused: the original message and stack are lost; fix `catch (error) { throw new X(…, { cause: error }) }`; a destructured binding counts as read, and throws inside nested functions are not the catch's; D-0118), `floating-promise` (a statement that calls something returning a Promise without await, return, `void` or `.catch`; the project's TypeScript decides the type; `test()` of node:test is exempt), `non-erasable-syntax` (enum, namespaces with values, parameter properties, decorators, `import x =`, `export =`, `<T>x`), `private-import` (a path of `@dokebi/*` outside its exports, such as `@dokebi/core/dist/…`), `missing-package` (an @dokebi package that is not installed → `add`; a feature Dokebi does not have → the absent `instead`; an unknown name), `generated-file` (doctor `MODIFIED_REGISTRATION`, `GUIDE_BLOCK_MODIFIED` and `MODIFIED_TEMPLATE` of CLI-owned files), `secret-in-config` (an option the plugin schema marks secret (`writeOnly`, such as `dokebi-session.secrets`), a plugin check `SECRET_IN_CONFIG`, or any dokebi.yaml value that is a URL with a password such as `postgres://user:password@host`, while dokebi.yaml could be committed; the value is never shown). Warning (D-0074): `inertia-form-only` — an Inertia form submit (`form.post/put/patch/delete/submit(…)` of a `useForm(…)` result, `router.post/put/patch/delete(…)`) whose options are missing or an object literal without `only`; the GET after its redirect would send every prop of the page again. Fix: `form.post(url, { only: ['<props it changes>'] })` (`errors` always comes along). It reads the text of `src/**` files that import `@inertiajs/` (the `<script>` blocks of .vue and .svelte files; comments and strings masked); calls inside a template attribute are not read, and options passed as a variable or with a spread are taken as fine. Security rules (D-0076 §6), on only when their plugin is installed: `plain-password-compare` (an error, with @dokebi/auth) — a value whose name has the word password, passwd, passphrase, pass, pw or pwd compared with `===`, `!==`, `==` or `!=` (not with `''`, `null`, `undefined`, a boolean, a number or `typeof`, and not a password with its confirmation field such as `passwordConfirm` and not two values that both come from the request input, such as `next !== body.confirmPassword` where `next` was read from `body`: a field of `body`, `query`, `params` or a form, or a local made from one; a typed value against a stored one, such as `body.password !== user.passwordHash` (a hash, a field of a user, row, account or credentials object, or a local loaded from one) stays an error), or passed to node:crypto `timingSafeEqual`, `scrypt`, `pbkdf2`, `argon2`, the `update()` of `createHash`/`createHmac`, or a `bcrypt`/`argon2` package; fix: `request.auth.attempt` and `passwords.verify`/`passwords.hash`. `form-without-csrf` (a warning, with @dokebi/csrf) — an EJS `<form method="post">` (any case) without `csrf.field` (also `csrf?.field`) or a `_csrf` field up to its `</form>` (a multipart form may carry `?_csrf=` in its action); fix: `<%- data.csrf.field %>`; EJS is read as text, so a form split over includes is not seen as one. `csrf-exempt-unverified` (a warning, with @dokebi/csrf) — a route `config: { csrf: false }` whose registration call (and its handler functions named in the same file) shows no `rawBody`, signature check (`signature`, `createHmac`, `timingSafeEqual`, `.verify(`), `seal` or @dokebi/auth token refresh (`tokens.refresh(`), and whose `config` has no `oauth` and no `auth: { via: 'token' }` (Bearer only; `via: 'any'` or `'session'` does not count); fix: send the token, or verify the sender. `unknown-error-code` (a warning, [D-0077](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0077-app-self-description.md) D, only when `src/shared/errors.ts` exports a `defineErrors({ … })` result written as an object literal) — app code under `src/apps/` or `src/shared/modules/` that writes an error code as a string: `new DokebiError('CODE', …)`, `Object.assign(new Error(…), { code: 'CODE' })`, `throw { code: 'CODE' }` or `.send({ error: 'CODE' })`. A code missing from the list is unknown (fix: add it to the list and throw `errors.CODE()`), a listed one is written by hand (fix: `throw errors.CODE()`, with the import path from that file). The codes of web, auth and csrf answers (`VALIDATION_FAILED`, `NOT_FOUND`, `INVALID_REQUEST`, `INTERNAL_SERVER_ERROR`, `UNAUTHENTICATED`, `FORBIDDEN`, `CSRF_FAILED`) are fine. The list is read from the file's syntax tree, never by running it; a spread or a computed key turns the rule off. Background work ([D-0103](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0105-check-background-timers-and-structure.md) §1): `background-timer` (an error) — server code under `src/` (not `views/` or `public/`; tests are not read) that runs periodic work on its own timer instead of @dokebi/scheduler and @dokebi/job: any `setInterval` (global, `node:timers`, or the async iterator of `node:timers/promises`), and a `setTimeout` or `setImmediate` whose callback comes back to a function around the call through the functions and methods of the same file (`const tick = () => { …; setTimeout(tick, ms) }`, `#schedule() { setTimeout(() => this.#tick()) }` with `#tick` calling `#schedule`). Fine: one-shot delays and time limits (`setTimeout(() => controller.abort(), ms)`, `new Promise((resolve) => setTimeout(resolve, ms))`), awaited sleeps of `node:timers/promises` (`await setTimeout(ms, undefined, { signal })` between bounded batches of a job handler), and timers inside a function that takes a `request`, `req`, `reply`, `res`, `response`, `socket`, `ws`, `websocket` or `stream` parameter or is passed to a route method (`get`, `post`, …, `route`), unless the timer is stored where it outlives that function: `this.ticker = setInterval(…)` (also `??=`, `||=`) or a variable declared outside it is reported (one worker-wide timer the first request starts). Fix: a job handler registered in the setup of the module that owns the work (`queue(<queue>).handle(<type>, …)`) and an entry of `options.dokebi-scheduler.schedules`. Structure warnings (D-0103 §2–§3): `responsibility-size` — a model (`…/models/…`) with at least 400 code lines (blank and comment-only lines do not count) over at least 8 tables or collections (names after FROM, JOIN, INTO and UPDATE in SQL text, CTE names and upsert columns excluded; Mongo `.collection('x')` and a local helper that wraps it; Kysely `selectFrom`/`insertInto`/`updateTable`/`deleteFrom`), a controller with at least 20 route handlers (public methods and function-valued fields) or 300 code lines, and a service class with at least 5 methods that only pass their parameters on to one call on a field (`return this.model.list(user, filter)`) when they are at least 60% of its methods; files whose first lines say `@generated`, `generated by` or `do not edit` are not read. `memory-filtered-page` — in a model or service, rows an awaited query returned that are skipped by comparing a field of the row with an input of the function and then cut to a page (`for (const row of rows) { if (row.status !== filter.status) continue; …; if (page.length === size) break; }`, or `rows.filter((row) => row.org === input.org).slice(…)`); fix: the filter in the query's WHERE with an index that ends in the sort key, and LIMIT the page size + 1. A search that checks its other terms on a capped candidate set (@dokebi/db AI.md 6.10) compares no input and is not matched; the rule sees only these two shapes, so a clean result does not prove the lists are paged in the database. Dev files ([D-0129](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0129-inertia-dev-file-policy.md)): `vite-dev-files` (a warning, in a project with an Inertia app or @dokebi/template-inertia) — the `vite.config.*` does not use `dokebiInertia()` (a plain `vite` then serves the whole project root: dokebi.yaml, .env, the server code), sets `server.fs.strict: false`, sets `server.fs.deny` (a list of its own replaces Vite's defaults where the framework's policy does not run), or an `allow` list names the project root or server code (`'.'`, `'src'`, `'tests'`, `'scripts'`, `'tools'`, `process.cwd()`, `__dirname`, `searchForWorkspaceRoot(…)`); fix: keep `dokebiInertia()` and drop `server.fs`, add browser folders with `dokebiInertia({ allow: [...] })` and entries with `dokebiInertia({ deny: [...] })`. @dokebi/template-inertia enforces the policy anyway (strict on, its deny entries kept); `formatter-migrations` (a warning, D-0145, when the migrations folder `<dokebi-migrate directory>/migrations` exists) — a code formatter of the project would format it: prettier (a config, a `prettier` key or dependency in package.json) without the folder in `.prettierignore`, biome without `!<folder>` in `files.includes` (biome 1: the folder in `files.ignore`), ESLint with formatting rules (eslint-plugin-prettier, `@stylistic`) whose config does not name it; an applied migration must keep its contents (a reformat is warned as `MIGRATE_REFORMATTED` by @dokebi/migrate, an edit refused); fix: the ignore entry the problem names (`npx dokebi add` writes it for prettier and biome); the rule says that the config asks for less. `formatter-generated` (a warning, R1 measurement) — the same formatters would format `src/dokebi.generated.ts`, which the CLI writes and compares with its record: a reformatted copy is doctor `MODIFIED_REGISTRATION` and add, upgrade and remove refuse to run; fix: `src/dokebi.generated.ts` in `.prettierignore`, `"!src/dokebi.generated.ts"` in biome `files.includes` (`npx dokebi add` writes both). `shared-folder` (a warning, D-0226) — an entry right under `src/shared/` other than the folders `browser`, `locales`, `mail`, `models`, `modules`, `services`, `settings`, `views` and the file `errors.ts` (names that start with a dot are not read): server code of one feature goes into its module, code several features share into `src/shared/models/` or `services/`, browser code several apps or modules share into `src/shared/browser/`; it names a folder, so no marker silences it. `asset-in-views` (a warning, R1 measurement) — a browser file (a style sheet, an image, a font) in the views of an EJS app (`src/apps/<app>/views/`; an Inertia app with `views/app.js` is not read): move it to `src/apps/<app>/public/` and link `/assets/<path>`, which @dokebi/app serves through @dokebi/static. `asset-route` (a warning, R6 measurement) — a GET or HEAD route of server code (a `get` or `head` call with a path and a handler; a lookup by one key such as `manifest.get('main.css')` is none) for a browser file (`.css`, an image, a font): its path is a fixed file name (`/site.css`), or ends in such an extension and its handler reads a file itself (`createReadStream`, `readFile`, `readFileSync`); such a route sends the file without the validator, 304 and Range of `public/`; fix: put the file in `src/apps/<app>/public/` (a file a package ships, such as a font of @dokebi/font-noto-kr, is copied there with its licence file) and link `/assets/<path>`; a file the route makes per request takes `// dokebi-check: allow asset-route <reason>`. `seal-head-copied` (a warning, R7 measurement; only with @dokebi/app) — a file under `src/` (`.ts`, `.js`, `.mjs`, `.ejs`, `.html`; not in a comment) that loads `/dokebi/seal/forms.mjs` itself, a copied seal `<script>` or import map: write `<%- data.seal?.head ?? '' %>` in the layout of an app page, and for a page rendered outside an app route (an oauth consent page) take `context.getDependency(apps).seal(request).head` (`AppGroupApi` of @dokebi/app ^0.4.5, empty on a plain host); a page that is no app page takes `// dokebi-check: allow seal-head-copied <reason>`. `i18n-missing-key` (a warning, community request A2; only with @dokebi/i18n and `src/shared/locales/`) — a fixed translation key a page or server code asks for (`t('ns.a.b')`, `$t(…)`, `request.i18n.t(…)` in `.vue`, `.ts`, `.js`, `.ejs` under `src/`; the first part a namespace of the catalogs) that the catalogs of the default locale (`dokebi-i18n.defaultLocale` of dokebi.yaml, `en`) lack — the end of every fallback chain, so @dokebi/i18n throws `MISSING_MESSAGE` for it (everywhere but under `npx dokebi dev`) in each locale without it; a key only the default locale has falls back and is not reported; keys built at run time, keys with an explicit default (`t('k', 'Text')`) and lines in a comment are not read; locale folders and the default locale are read as @dokebi/i18n reads them (`Intl.Locale(name).baseName`: a folder `en-us` is the locale `en-US`), and a catalog that is not JSON or a folder that is no locale (or a second folder of one locale) is reported; fix: add the key to `src/shared/locales/<default locale>/<namespace>.json`; a key another catalog provides takes `// dokebi-check: allow i18n-missing-key <reason>`. With catalog layers (D-0181) code under `src/apps/<app>/` is checked against that app's layer, the modules and the shared catalogs, other code against the modules and the shared ones. `i18n-layer-override` (a warning) — one key in one language in two layers: an app's `src/apps/<app>/locales/` over a module's `src/shared/modules/<module>/locales/` or the shared `src/shared/locales/`, a module's over the shared ones, or two modules (the first by name wins, always reported); fix: list an intended override in the overriding file's top-level `"$overrides": ["key", …]` (keys inside the namespace), otherwise rename the key or remove it from one layer; a listed key that overrides nothing is reported too. `i18n-layer-missing` (a warning) — a layer gives keys in one language and lacks them in another language of the project, one problem per layer, language and namespace; fix: add them to that file or remove them from the layer's other languages. `shared-state-memory` (an error, [D-0161](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0161-shared-state-redis.md)) — `options.application-runtime.workers` above 1 while an installed plugin keeps the state its workers share in process memory: the dokebi-session store, dokebi-auth `tokens` or `throttle.store`, the dokebi-oauth store, the dokebi-rate-limit driver (`local`), dokebi-seal `nonces` that are not shared, or a dokebi-websocket-hub not in `mode: cluster`; the plugins refuse to start that way in a cluster worker and in production. Fix: `{ driver: redis, connection: <the project's dokebi-redis connection> }` for each (`npx dokebi add @dokebi/redis` first when there is none); the problem's line is that option in dokebi.yaml. `console-output` (a warning, D-0151) — server code under `src/` (not `views/` or `public/`) that calls `console.log`, `console.info`, `console.warn`, `console.error`, `console.debug`, `console.trace`, `process.stdout.write` or `process.stderr.write`: those lines skip the logger level, the redaction and the targets (the rotated files, the JSON lines `dokebi logs` reads); fix: `context.logger.log(level, 'Fixed message', { code, … })` in a plugin or module hook, `app.logger` in `src/main.ts`. A command line tool of the project that prints its results takes `// dokebi-check: allow console-output <reason>` before its first statement (it covers the whole file), or on or above one line. The framework's own sources pass the same rule as the `check:console` gate. `polling-loop` (an error no marker silences, AI-M35) — a loop that sleeps inside a task started in the background (an immediately invoked async function, or a function the file calls without awaiting or returning it), such as `(async () => { while (!stopped) { await step(); await sleep(ms); } })()` in a module's `start`: move it to an @dokebi/outbox handler (one coalesced item per owner and window) or a @dokebi/job handler with a schedule; per-process upkeep uses a timer (`background-timer` with a marker), never a sleeping loop. A `setInterval` or self-rescheduling timer whose callback reaches database work (a `query`, `execute` or `transaction` call, or a call on a model, repository, pool, client, transaction or outbox object, through the functions of the same file) is reported as `polling-loop` too, marker or not. `in-process-queue` (a warning, AI-M35) — the resolve of a `new Promise` stored in a collection (`.push`, `.unshift`, `.set`, `.add`), directly or through a variable that holds it (`const pending = { input, resolve }`), to be called later: callers wait in a queue of one worker without a bound or deadline; send the work at once and let the pool's `waitTimeoutMs` bound the wait (503 with Retry-After). `wait-count-refusal` (a warning, @dokebi/db AI.md 1.2 and 6.4) — server code under `src/` that compares how many callers wait for a pool connection with a number (pg `pool.waitingCount`, mariadb `pool.taskQueueSize()`, MongoDB `waitQueueSize`, mysql2 `pool._connectionQueue.length`): the count of waiters is not overload, so refusing on it refuses work the database can still do; fix: bound the wait by its deadline (`waitTimeoutMs`, then 503 with Retry-After) and shed a tenant by time, not by waiters; a metric or log line that only reports the number takes `// dokebi-check: allow wait-count-refusal <reason>`. `private-pool` (an error, AI-M37) — server code under `src/` outside `src/infra/db/` that makes a database pool or client with the driver itself (`new Pool`/`new Client` of `pg`, `createPool`/`createConnection`/`createPoolCluster` of `mysql2` and `mariadb`, `new MongoClient` of `mongodb`): it escapes dokebi.yaml (its size and `waitTimeoutMs`, past which the caller gets 503 with Retry-After), the connection sum and the cleanup at stop (M37: private pools with a 30 s wait held callers for 22–51 s); fix: the configured connection (`context.getDependency(db).connection(main)`), `derive('main', { purpose, overrides: { max } })` for a pool of one kind of work, or one more connection in dokebi.yaml; a connection that must stay outside (a LISTEN client) takes `// dokebi-check: allow private-pool <reason>`. `overload-off` (an error, AI-M37) — a route `config: { overload: false }`: under a burst its callers queue behind a stalled worker instead of getting 503 `OVERLOADED` with Retry-After (@dokebi/web AI.md 2.5); fix: remove it (raise `overload.maxEventLoopDelayMs` if it refuses too early); a metrics scrape or an operator status page takes `// dokebi-check: allow overload-off <reason>`. `readiness-off` (an error, M51) — a route `config: { readiness: false }`: it is served while a required dependency is down and while the app drains, so an API route runs its handler against a missing database or Redis; fix: remove it; a metrics scrape or status page that must answer during an outage takes `// dokebi-check: allow readiness-off <reason>`. `fixed-owner-cap` (a warning, AI-M37) — a per-owner count of requests in progress (a Map entry that goes up and down by one, read into a variable) compared with a fixed limit by an `if` that throws or returns, without a free or idle connection in the condition: it refuses work while the database is idle; fix: the owner share of @dokebi/db, `share(main).enter(owner)`, which refuses only while the pool is full (@dokebi/db AI.md 6.4, D-0156); a budget that bounds something else (the report CPU budget of db AI.md 6.9, a plan's quota) takes `// dokebi-check: allow fixed-owner-cap <reason>`. `undeclared-section` (a warning, D-0155) — a section of dokebi.yaml nothing declares (code reads `options.<name>` by hand); fix: `npx dokebi settings add <name>`. `template-fix-missing` (a warning) — doctor's `TEMPLATE_FIX_MISSING` and `RELOAD_NOT_WIRED`: a copied template file lacks a later fix, or an entry passes no `configFile`; fix: doctor's hint. `module-point-not-installed` (D-0130) — a point in `contributes` of `defineModule` imported from an `@dokebi/*` plugin package that is in node_modules but not installed in the project (`dokebi add`): nothing registers its collector, so the app drops the values (warn `POINT_NOT_COLLECTED`); fix: `npx dokebi add <package>` or remove the point (a plugin you register yourself takes the allow marker with a reason). When an empty catch, a background promise, a full-page form submit (a login) or one of the security cases is really intended, put `// dokebi-check: allow <rule> <reason>` on that line or the line above (EJS: `<%# dokebi-check: allow form-without-csrf <reason> %>` on the line above the form; only `empty-catch`, `missing-cause`, `floating-promise`, `inertia-form-only`, `unknown-error-code`, the three security rules, the two mail warnings, the three D-0103 rules, `untyped-browser-import`, `vite-dev-files`, `module-point-not-installed`, `asset-route`, `seal-head-copied`, `i18n-missing-key`, `console-output`, `wait-count-refusal`, `in-process-queue`, `fixed-owner-cap`, `private-pool` and `overload-off` — for example a per-process eviction of in-memory state that no job can reach; without a reason the marker is ignored). The sources are the program of `tsconfig.json` (generated files, `.d.ts` and node_modules excluded), read with the API of the TypeScript 7 installed in the project (`typescript/unstable/sync`). Browser code outside that program is read too (D-0120): the `<script>` and `<script setup>` blocks (`lang` ts or js) of every `.vue` file under `src/`, and the `.js`/`.mjs` files under a `views/` folder (files above 1 MiB are skipped). They get `empty-catch`, `missing-cause` and `floating-promise` only, typed by a second program that extends `tsconfig.json` but resolves imports as the bundler does (`moduleResolution: bundler`, `module: esnext`, the DOM in `lib`; relative imports resolve from the file's folder). An import whose bound names all have no type (the module did not resolve) is the warning `untyped-browser-import` on its line, since floating-promise cannot judge what comes from it; an import of a `.vue`, style, image or JSON file and `import type` are not judged; a module that really has no types takes `// dokebi-check: allow untyped-browser-import <reason>`, and the problems name the `.vue` or `.js` file and its line; the markers work the same inside a script block. A browser promise left floating is an unhandled rejection the page never handles: `await` it, or end it with `.catch(error => …)` that shows or reports the error. When it cannot be loaded `TYPESCRIPT_UNAVAILABLE` (`npm install`), when tsconfig cannot be opened `TSCONFIG_INVALID` |
87
+ | `dokebi check` | User-code conventions (D-0072). `{ ok, problems[{rule, severity?, file, line, message, fix}], allowed[{rule, file, line, reason}], files, rules, typescript, ms: { total, typescript } }` (`allowed`: every `// dokebi-check: allow <rule> <reason>` marker with a reason under `src/`, the problems silenced on purpose; the human output prints one `allowed` line each, and verify ok asks the final message to list them), exit 1 on a problem (a `severity: 'warning'` problem is reported but never fails: `ok` stays true). The human output prints `file:line rule message` and a `fix:` line per problem, then a summary (`check ok` or `check FAILED: N problems`, files, time). Rules: `empty-catch` (an empty `catch`, `.catch(() => {})`, an empty onRejected of `then`, an empty `on('error', …)`, and the same handlers when they only give back nothing: `() => undefined`, `() => null`, `() => void 0`, `{ return; }`; a fallback value such as `() => false` is not flagged), `missing-cause` (a `catch` that throws a new error and never reads the one it caught — `catch { throw new X() }`, `catch { throw fail() }` (a call that makes the error counts the same) or a named error left unused: the original message and stack are lost; fix `catch (error) { throw new X(…, { cause: error }) }`; a destructured binding counts as read, and throws inside nested functions are not the catch's; D-0118), `floating-promise` (a statement that calls something returning a Promise without await, return, `void` or `.catch`; the project's TypeScript decides the type; `test()` of node:test is exempt), `non-erasable-syntax` (enum, namespaces with values, parameter properties, decorators, `import x =`, `export =`, `<T>x`), `private-import` (a path of `@dokebi/*` outside its exports, such as `@dokebi/core/dist/…`), `missing-package` (an @dokebi package that is not installed → `add`; a feature Dokebi does not have → the absent `instead`; an unknown name), `generated-file` (doctor `MODIFIED_REGISTRATION`, `GUIDE_BLOCK_MODIFIED` and `MODIFIED_TEMPLATE` of CLI-owned files), `secret-in-config` (an option the plugin schema marks secret (`writeOnly`, such as `dokebi-session.secrets`), a plugin check `SECRET_IN_CONFIG`, or any dokebi.yaml value that is a URL with a password such as `postgres://user:password@host`, while dokebi.yaml could be committed; the value is never shown). Warning (D-0074): `inertia-form-only` — an Inertia form submit (`form.post/put/patch/delete/submit(…)` of a `useForm(…)` result, `router.post/put/patch/delete(…)`) whose options are missing or an object literal without `only`; the GET after its redirect would send every prop of the page again. Fix: `form.post(url, { only: ['<props it changes>'] })` (`errors` always comes along). It reads the text of `src/**` files that import `@inertiajs/` (the `<script>` blocks of .vue and .svelte files; comments and strings masked); calls inside a template attribute are not read, and options passed as a variable or with a spread are taken as fine. Security rules (D-0076 §6), on only when their plugin is installed: `plain-password-compare` (an error, with @dokebi/auth) — a value whose name has the word password, passwd, passphrase, pass, pw or pwd compared with `===`, `!==`, `==` or `!=` (not with `''`, `null`, `undefined`, a boolean, a number or `typeof`, and not a password with its confirmation field such as `passwordConfirm` and not two values that both come from the request input, such as `next !== body.confirmPassword` where `next` was read from `body`: a field of `body`, `query`, `params` or a form, or a local made from one; a typed value against a stored one, such as `body.password !== user.passwordHash` (a hash, a field of a user, row, account or credentials object, or a local loaded from one) stays an error), or passed to node:crypto `timingSafeEqual`, `scrypt`, `pbkdf2`, `argon2`, the `update()` of `createHash`/`createHmac`, or a `bcrypt`/`argon2` package; fix: `request.auth.attempt` and `passwords.verify`/`passwords.hash`. `form-without-csrf` (a warning, with @dokebi/csrf) — an EJS `<form method="post">` (any case) without `csrf.field` (also `csrf?.field`) or a `_csrf` field up to its `</form>` (a multipart form may carry `?_csrf=` in its action); fix: `<%- data.csrf.field %>`; EJS is read as text, so a form split over includes is not seen as one. `csrf-exempt-unverified` (a warning, with @dokebi/csrf) — a route `config: { csrf: false }` whose registration call (and its handler functions named in the same file) shows no `rawBody`, signature check (`signature`, `createHmac`, `timingSafeEqual`, `.verify(`), `seal` or @dokebi/auth token refresh (`tokens.refresh(`), and whose `config` has no `oauth` and no `auth: { via: 'token' }` (Bearer only; `via: 'any'` or `'session'` does not count); fix: send the token, or verify the sender. `unknown-error-code` (a warning, [D-0077](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0077-app-self-description.md) D, only when `src/shared/errors.ts` exports a `defineErrors({ … })` result written as an object literal) — app code under `src/apps/` or `src/shared/modules/` that writes an error code as a string: `new DokebiError('CODE', …)`, `Object.assign(new Error(…), { code: 'CODE' })`, `throw { code: 'CODE' }` or `.send({ error: 'CODE' })`. A code missing from the list is unknown (fix: add it to the list and throw `errors.CODE()`), a listed one is written by hand (fix: `throw errors.CODE()`, with the import path from that file). The codes of web, auth and csrf answers (`VALIDATION_FAILED`, `NOT_FOUND`, `INVALID_REQUEST`, `INTERNAL_SERVER_ERROR`, `UNAUTHENTICATED`, `FORBIDDEN`, `CSRF_FAILED`) are fine. The list is read from the file's syntax tree, never by running it; a spread or a computed key turns the rule off. Background work ([D-0103](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0105-check-background-timers-and-structure.md) §1): `background-timer` (an error) — server code under `src/` (not `views/` or `public/`; tests are not read) that runs periodic work on its own timer instead of @dokebi/scheduler and @dokebi/job: any `setInterval` (global, `node:timers`, or the async iterator of `node:timers/promises`), and a `setTimeout` or `setImmediate` whose callback comes back to a function around the call through the functions and methods of the same file (`const tick = () => { …; setTimeout(tick, ms) }`, `#schedule() { setTimeout(() => this.#tick()) }` with `#tick` calling `#schedule`). Fine: one-shot delays and time limits (`setTimeout(() => controller.abort(), ms)`, `new Promise((resolve) => setTimeout(resolve, ms))`), awaited sleeps of `node:timers/promises` (`await setTimeout(ms, undefined, { signal })` between bounded batches of a job handler), and timers inside a function that takes a `request`, `req`, `reply`, `res`, `response`, `socket`, `ws`, `websocket` or `stream` parameter or is passed to a route method (`get`, `post`, …, `route`), unless the timer is stored where it outlives that function: `this.ticker = setInterval(…)` (also `??=`, `||=`) or a variable declared outside it is reported (one worker-wide timer the first request starts). Fix: a job handler registered in the setup of the module that owns the work (`queue(<queue>).handle(<type>, …)`) and an entry of `options.dokebi-scheduler.schedules`. Structure warnings (D-0103 §2–§3): `responsibility-size` — a model (`…/models/…`) with at least 400 code lines (blank and comment-only lines do not count) over at least 8 tables or collections (names after FROM, JOIN, INTO and UPDATE in SQL text, CTE names and upsert columns excluded; Mongo `.collection('x')` and a local helper that wraps it; Kysely `selectFrom`/`insertInto`/`updateTable`/`deleteFrom`), a controller with at least 20 route handlers (public methods and function-valued fields) or 300 code lines, and a service class with at least 5 methods that only pass their parameters on to one call on a field (`return this.model.list(user, filter)`) when they are at least 60% of its methods; files whose first lines say `@generated`, `generated by` or `do not edit` are not read. `memory-filtered-page` — in a model or service, rows an awaited query returned that are skipped by comparing a field of the row with an input of the function and then cut to a page (`for (const row of rows) { if (row.status !== filter.status) continue; …; if (page.length === size) break; }`, or `rows.filter((row) => row.org === input.org).slice(…)`); fix: the filter in the query's WHERE with an index that ends in the sort key, and LIMIT the page size + 1. A search that checks its other terms on a capped candidate set (@dokebi/db AI.md 6.10) compares no input and is not matched; the rule sees only these two shapes, so a clean result does not prove the lists are paged in the database. Dev files ([D-0129](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0129-inertia-dev-file-policy.md)): `vite-dev-files` (a warning, in a project with an Inertia app or @dokebi/template-inertia) — the `vite.config.*` does not use `dokebiInertia()` (a plain `vite` then serves the whole project root: dokebi.yaml, .env, the server code), sets `server.fs.strict: false`, sets `server.fs.deny` (a list of its own replaces Vite's defaults where the framework's policy does not run), or an `allow` list names the project root or server code (`'.'`, `'src'`, `'tests'`, `'scripts'`, `'tools'`, `process.cwd()`, `__dirname`, `searchForWorkspaceRoot(…)`); fix: keep `dokebiInertia()` and drop `server.fs`, add browser folders with `dokebiInertia({ allow: [...] })` and entries with `dokebiInertia({ deny: [...] })`. @dokebi/template-inertia enforces the policy anyway (strict on, its deny entries kept); `formatter-migrations` (a warning, D-0145, when the migrations folder `<dokebi-migrate directory>/migrations` exists) — a code formatter of the project would format it: prettier (a config, a `prettier` key or dependency in package.json) without the folder in `.prettierignore`, biome without `!<folder>` in `files.includes` (biome 1: the folder in `files.ignore`), ESLint with formatting rules (eslint-plugin-prettier, `@stylistic`) whose config does not name it; an applied migration must keep its contents (a reformat is warned as `MIGRATE_REFORMATTED` by @dokebi/migrate, an edit refused); fix: the ignore entry the problem names (`npx dokebi add` writes it for prettier and biome); the rule says that the config asks for less. `formatter-generated` (a warning, R1 measurement) — the same formatters would format `src/dokebi.generated.ts`, which the CLI writes and compares with its record: a reformatted copy is doctor `MODIFIED_REGISTRATION` and add, upgrade and remove refuse to run; fix: `src/dokebi.generated.ts` in `.prettierignore`, `"!src/dokebi.generated.ts"` in biome `files.includes` (`npx dokebi add` writes both). `shared-folder` (a warning, D-0226) — an entry right under `src/shared/` other than the folders `browser`, `locales`, `mail`, `models`, `modules`, `services`, `settings`, `views` and the file `errors.ts` (names that start with a dot are not read): server code of one feature goes into its module, code several features share into `src/shared/models/` or `services/`, browser code several apps or modules share into `src/shared/browser/`; it names a folder, so no marker silences it. `asset-in-views` (a warning, R1 measurement) — a browser file (a style sheet, an image, a font) in the views of an EJS app (`src/apps/<app>/views/`; an Inertia app with `views/app.js` is not read): move it to `src/apps/<app>/public/` and link `/assets/<path>`, which @dokebi/app serves through @dokebi/static. `asset-route` (a warning, R6 measurement) — a GET or HEAD route of server code (a `get` or `head` call with a path and a handler; a lookup by one key such as `manifest.get('main.css')` is none) for a browser file (`.css`, an image, a font): its path is a fixed file name (`/site.css`), or ends in such an extension and its handler reads a file itself (`createReadStream`, `readFile`, `readFileSync`); such a route sends the file without the validator, 304 and Range of `public/`; fix: put the file in `src/apps/<app>/public/` (a file a package ships, such as a font of @dokebi/font-noto-kr, is copied there with its licence file) and link `/assets/<path>`; a file the route makes per request takes `// dokebi-check: allow asset-route <reason>`. `seal-head-copied` (a warning, R7 measurement; only with @dokebi/app) — a file under `src/` (`.ts`, `.js`, `.mjs`, `.ejs`, `.html`; not in a comment) that loads `/dokebi/seal/forms.mjs` itself, a copied seal `<script>` or import map: write `<%- data.seal?.head ?? '' %>` in the layout of an app page, and for a page rendered outside an app route (an oauth consent page) take `context.getDependency(apps).seal(request).head` (`AppGroupApi` of @dokebi/app ^0.4.5, empty on a plain host); a page that is no app page takes `// dokebi-check: allow seal-head-copied <reason>`. `i18n-missing-key` (a warning, community request A2; only with @dokebi/i18n and `src/shared/locales/`) — a fixed translation key a page or server code asks for (`t('ns.a.b')`, `$t(…)`, `request.i18n.t(…)` in `.vue`, `.ts`, `.js`, `.ejs` under `src/`; the first part a namespace of the catalogs, or any key of a call that is certainly the translation function — `$t(…)`, `….i18n.t(…)`, or `t(…)` in a file that takes `t` from `useI18n()` of `@dokebi/template-inertia/i18n` — so a key whose namespace no catalog has, or one without a namespace, is reported too: the page throws `PageI18nError` and does not render, cli 0.4.56) that the catalogs of the default locale (`dokebi-i18n.defaultLocale` of dokebi.yaml, `en`) lack — the end of every fallback chain, so @dokebi/i18n throws `MISSING_MESSAGE` for it (everywhere but under `npx dokebi dev`) in each locale without it; a key only the default locale has falls back and is not reported; keys built at run time, keys with an explicit default (`t('k', 'Text')`) and lines in a comment are not read; locale folders and the default locale are read as @dokebi/i18n reads them (`Intl.Locale(name).baseName`: a folder `en-us` is the locale `en-US`), and a catalog that is not JSON or a folder that is no locale (or a second folder of one locale) is reported; fix: add the key to `src/shared/locales/<default locale>/<namespace>.json`; a key another catalog provides takes `// dokebi-check: allow i18n-missing-key <reason>`. With catalog layers (D-0181) code under `src/apps/<app>/` is checked against that app's layer, the modules and the shared catalogs, other code against the modules and the shared ones. `i18n-layer-override` (a warning) — one key in one language in two layers: an app's `src/apps/<app>/locales/` over a module's `src/shared/modules/<module>/locales/` or the shared `src/shared/locales/`, a module's over the shared ones, or two modules (the first by name wins, always reported); fix: list an intended override in the overriding file's top-level `"$overrides": ["key", …]` (keys inside the namespace), otherwise rename the key or remove it from one layer; a listed key that overrides nothing is reported too. `i18n-layer-missing` (a warning) — a layer gives keys in one language and lacks them in another language of the project, one problem per layer, language and namespace; fix: add them to that file or remove them from the layer's other languages. `shared-state-memory` (an error, [D-0161](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0161-shared-state-redis.md)) — `options.application-runtime.workers` above 1 while an installed plugin keeps the state its workers share in process memory: the dokebi-session store, dokebi-auth `tokens` or `throttle.store`, the dokebi-oauth store, the dokebi-rate-limit driver (`local`), dokebi-seal `nonces` that are not shared, or a dokebi-websocket-hub not in `mode: cluster`; the plugins refuse to start that way in a cluster worker and in production. Fix: `{ driver: redis, connection: <the project's dokebi-redis connection> }` for each (`npx dokebi add @dokebi/redis` first when there is none); the problem's line is that option in dokebi.yaml. `console-output` (a warning, D-0151) — server code under `src/` (not `views/` or `public/`) that calls `console.log`, `console.info`, `console.warn`, `console.error`, `console.debug`, `console.trace`, `process.stdout.write` or `process.stderr.write`: those lines skip the logger level, the redaction and the targets (the rotated files, the JSON lines `dokebi logs` reads); fix: `context.logger.log(level, 'Fixed message', { code, … })` in a plugin or module hook, `app.logger` in `src/main.ts`. A command line tool of the project that prints its results takes `// dokebi-check: allow console-output <reason>` before its first statement (it covers the whole file), or on or above one line. The framework's own sources pass the same rule as the `check:console` gate. `polling-loop` (an error no marker silences, AI-M35) — a loop that sleeps inside a task started in the background (an immediately invoked async function, or a function the file calls without awaiting or returning it), such as `(async () => { while (!stopped) { await step(); await sleep(ms); } })()` in a module's `start`: move it to an @dokebi/outbox handler (one coalesced item per owner and window) or a @dokebi/job handler with a schedule; per-process upkeep uses a timer (`background-timer` with a marker), never a sleeping loop. A `setInterval` or self-rescheduling timer whose callback reaches database work (a `query`, `execute` or `transaction` call, or a call on a model, repository, pool, client, transaction or outbox object, through the functions of the same file) is reported as `polling-loop` too, marker or not. `in-process-queue` (a warning, AI-M35) — the resolve of a `new Promise` stored in a collection (`.push`, `.unshift`, `.set`, `.add`), directly or through a variable that holds it (`const pending = { input, resolve }`), to be called later: callers wait in a queue of one worker without a bound or deadline; send the work at once and let the pool's `waitTimeoutMs` bound the wait (503 with Retry-After). `wait-count-refusal` (a warning, @dokebi/db AI.md 1.2 and 6.4) — server code under `src/` that compares how many callers wait for a pool connection with a number (pg `pool.waitingCount`, mariadb `pool.taskQueueSize()`, MongoDB `waitQueueSize`, mysql2 `pool._connectionQueue.length`): the count of waiters is not overload, so refusing on it refuses work the database can still do; fix: bound the wait by its deadline (`waitTimeoutMs`, then 503 with Retry-After) and shed a tenant by time, not by waiters; a metric or log line that only reports the number takes `// dokebi-check: allow wait-count-refusal <reason>`. `private-pool` (an error, AI-M37) — server code under `src/` outside `src/infra/db/` that makes a database pool or client with the driver itself (`new Pool`/`new Client` of `pg`, `createPool`/`createConnection`/`createPoolCluster` of `mysql2` and `mariadb`, `new MongoClient` of `mongodb`): it escapes dokebi.yaml (its size and `waitTimeoutMs`, past which the caller gets 503 with Retry-After), the connection sum and the cleanup at stop (M37: private pools with a 30 s wait held callers for 22–51 s); fix: the configured connection (`context.getDependency(db).connection(main)`), `derive('main', { purpose, overrides: { max } })` for a pool of one kind of work, or one more connection in dokebi.yaml; a connection that must stay outside (a LISTEN client) takes `// dokebi-check: allow private-pool <reason>`. `overload-off` (an error, AI-M37) — a route `config: { overload: false }`: under a burst its callers queue behind a stalled worker instead of getting 503 `OVERLOADED` with Retry-After (@dokebi/web AI.md 2.5); fix: remove it (raise `overload.maxEventLoopDelayMs` if it refuses too early); a metrics scrape or an operator status page takes `// dokebi-check: allow overload-off <reason>`. `readiness-off` (an error, M51) — a route `config: { readiness: false }`: it is served while a required dependency is down and while the app drains, so an API route runs its handler against a missing database or Redis; fix: remove it; a metrics scrape or status page that must answer during an outage takes `// dokebi-check: allow readiness-off <reason>`. `fixed-owner-cap` (a warning, AI-M37) — a per-owner count of requests in progress (a Map entry that goes up and down by one, read into a variable) compared with a fixed limit by an `if` that throws or returns, without a free or idle connection in the condition: it refuses work while the database is idle; fix: the owner share of @dokebi/db, `share(main).enter(owner)`, which refuses only while the pool is full (@dokebi/db AI.md 6.4, D-0156); a budget that bounds something else (the report CPU budget of db AI.md 6.9, a plan's quota) takes `// dokebi-check: allow fixed-owner-cap <reason>`. `undeclared-section` (a warning, D-0155) — a section of dokebi.yaml nothing declares (code reads `options.<name>` by hand); fix: `npx dokebi settings add <name>`. `template-fix-missing` (a warning) — doctor's `TEMPLATE_FIX_MISSING` and `RELOAD_NOT_WIRED`: a copied template file lacks a later fix, or an entry passes no `configFile`; fix: doctor's hint. `module-point-not-installed` (D-0130) — a point in `contributes` of `defineModule` imported from an `@dokebi/*` plugin package that is in node_modules but not installed in the project (`dokebi add`): nothing registers its collector, so the app drops the values (warn `POINT_NOT_COLLECTED`); fix: `npx dokebi add <package>` or remove the point (a plugin you register yourself takes the allow marker with a reason). When an empty catch, a background promise, a full-page form submit (a login) or one of the security cases is really intended, put `// dokebi-check: allow <rule> <reason>` on that line or the line above (EJS: `<%# dokebi-check: allow form-without-csrf <reason> %>` on the line above the form; only `empty-catch`, `missing-cause`, `floating-promise`, `inertia-form-only`, `unknown-error-code`, the three security rules, the two mail warnings, the three D-0103 rules, `untyped-browser-import`, `vite-dev-files`, `module-point-not-installed`, `asset-route`, `seal-head-copied`, `i18n-missing-key`, `console-output`, `wait-count-refusal`, `in-process-queue`, `fixed-owner-cap`, `private-pool` and `overload-off` — for example a per-process eviction of in-memory state that no job can reach; without a reason the marker is ignored). The sources are the program of `tsconfig.json` (generated files, `.d.ts` and node_modules excluded), read with the API of the TypeScript 7 installed in the project (`typescript/unstable/sync`). Browser code outside that program is read too (D-0120): the `<script>` and `<script setup>` blocks (`lang` ts or js) of every `.vue` file under `src/`, and the `.js`/`.mjs` files under a `views/` folder (files above 1 MiB are skipped). They get `empty-catch`, `missing-cause` and `floating-promise` only, typed by a second program that extends `tsconfig.json` but resolves imports as the bundler does (`moduleResolution: bundler`, `module: esnext`, the DOM in `lib`; relative imports resolve from the file's folder). An import whose bound names all have no type (the module did not resolve) is the warning `untyped-browser-import` on its line, since floating-promise cannot judge what comes from it; an import of a `.vue`, style, image or JSON file and `import type` are not judged; a module that really has no types takes `// dokebi-check: allow untyped-browser-import <reason>`, and the problems name the `.vue` or `.js` file and its line; the markers work the same inside a script block. A browser promise left floating is an unhandled rejection the page never handles: `await` it, or end it with `.catch(error => …)` that shows or reports the error. When it cannot be loaded `TYPESCRIPT_UNAVAILABLE` (`npm install`), when tsconfig cannot be opened `TSCONFIG_INVALID` |
88
88
  | `dokebi upgrade <plugin id> [--to <version\|package\|tgz>] [--dry-run]` | Change the version. Do not use remove and add instead. Without `--to` it picks the highest version that fits the core and the installed packages, as `add` does (`NEWER_VERSION_HELD_BACK` names a newer one and what it waits for; the same version again changes nothing); an unreachable registry or a workspace package takes npm's `latest`. The copies of templates the project owns (the @dokebi/db adapters, `vite.config.ts` and `vite.ssr.config.ts`) are never rewritten: fixes of the new templates they lack are the warnings `TEMPLATE_FIX_MISSING` (`path`, `plugin`, `hint`: the change to make), as doctor reports them. With the same version and a changed manifest it applies the manifest again (D-0037, `reason: MANIFEST_CHANGED`); with the same version and manifest but other package content (an unpublished version rebuilt, given as `--to <tgz>`; the package-lock integrity differs) it installs the new code (`reason: PACKAGE_CHANGED`) — the way to replace a local snapshot. After package.json moved several plugins at once, upgrade them one by one, dependencies first: each result lists the ones still to do as `MANIFEST_CHANGED` warnings with their `hint`. A required plugin the new version needs and the project lacks is installed with it, as `add` would (`autoInstalled`, D-0116), when its manifest names the package and it needs no choice or settings; otherwise nothing is written and it is `MISSING_DEPENDENCY` (`mutation: none`) whose `details.fix` is the command to run first (`npx dokebi add <package>`, then the same upgrade again) |
89
89
  | `dokebi remove <plugin id> [--dry-run]` | Remove a plugin. `REVERSE_DEPENDENCY` when a remaining plugin depends on it, `REQUIRED_PLUGIN` for a required part. An id that is not installed is no change; the package name of an installed plugin is `UNKNOWN_PLUGIN` (`details.fix`: `npx dokebi remove <id>`) |
90
90
  | `dokebi migrate [--dry-run]` | Move a 0.1.x project with JSON settings to YAML |
@@ -181,7 +181,7 @@ One document on stdout: `{ schemaVersion, cliVersion, command, ok, result?, erro
181
181
  | `src/dokebi.modules.generated.ts` | CLI | The registered modules (D-0227, with `@dokebi/module`): `registeredModules` (`{ <name>: module }` in registration order) and the type `RegisteredModuleName`. It imports the modules only, so apps and project files import it where code needs every module (an app that mounts each one, permission keys or menu entries collected from each module's declarations); never keep a module list of your own (D-0032 §5). `module add`, `remove` and `sync` write it; an edited copy is doctor `MODULE_LIST_MODIFIED` (error), a missing one `MODULE_LIST_MISSING` (warning: `npx dokebi module sync`) |
182
182
  | `src/main.ts` | user | The entry point (YAML loading → Application → create and register plugins → start). Every plugin factory checks its options against its own declaration: a wrong value stops the start with `INVALID_PLUGIN_OPTIONS` (`plugin`, `fix`, and the cause `INVALID_OPTIONS` naming `options.<plugin>.<path>`). The generated code carries no JSON Schema validator (D-0070) |
183
183
  | `src/apps/<app>/` | user | One app (app.ts, routes.ts or routes/, controllers, services, models, validation, views) |
184
- | `src/shared/modules/<module>/` | user | Feature modules (module.ts, routes.ts and the same folders); job handlers and event subscriptions are registered in the owning module's setup. Declarations the project adds to every module (menu entries, permission keys) are files at the module root named for what they declare (`menu.ts`, `permissions.ts`) that `module.ts` passes on; pages declared but not built yet are routes (`routes.ts`) (D-0227). A pure rule the module's server code and its pages both use (a code check, a rich-text schema) stays in its `validation/`, imports neither Node nor browser APIs, and the pages import it with a relative path |
184
+ | `src/shared/modules/<module>/` | user | Feature modules (module.ts, routes.ts and the same folders); job handlers and event subscriptions are registered in the owning module's setup. Declarations the project adds to every module (menu entries, permission keys) are files at the module root named for what they declare (`menu.ts`, `permissions.ts`) that `module.ts` passes on; pages declared but not built yet are routes (`routes.ts`) (D-0227). A pure rule the module's server code and its pages both use (a code check, a rich-text schema) stays in its `validation/`, imports neither Node nor browser APIs, and the pages import it with a relative path. A module whose screens show parts of other modules offers slots (`slots.ts`); the others fill them from `slot-entries.ts` in their setup (D-0228, @dokebi/module AI.md §3b) |
185
185
  | `src/shared/{models,services,views,locales,mail}/` · `src/shared/errors.ts` | user | Shared models and services, layouts and partials, translation catalogs (`locales/<locale>/<namespace>.json`), mail templates (`mail/<template>/<locale>/`) and the app error catalog |
186
186
  | `src/shared/validation/` | user | Input rules several apps or modules share (D-0227): reading a list query (`?page`, `?sort`, `?ids`), a reason field. They take the values (query, body), never import app or module code; the rules of one app or module stay in its own `validation/` |
187
187
  | `src/shared/browser/` | user | Browser code several apps or modules share (D-0226): `components/` (a design system's UI components), `layouts/`, `composables/`, `styles/` (CSS, tokens) and `lib/` (browser modules that are not Vue: a socket client, formatters); a project with two looks puts one folder per look first (`browser/staff/components/`). Pages import it with a relative path and the dev server serves what they import; server code never imports it. Browser code — this folder and the `views/` of apps and modules — is checked by `tsconfig.vue.json` (vue-tsc, Vite's types), not `tsconfig.json`: a project made before cli 0.4.53 adds `"exclude": ["src/apps/*/views/**", "src/shared/modules/*/views/**", "src/shared/browser/**"]` to `tsconfig.json`, and to `tsconfig.vue.json` the include entries `"src/apps/*/views/**/*.ts"`, `"src/shared/modules/*/views/**/*.ts"`, `"src/shared/browser/**/*.ts"` with `"exclude": ["node_modules", "dist"]`. Code one app or module uses stays in its `views/` |
package/catalog.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$comment": "Generated by scripts/catalog/build.ts from package.json dokebiCatalog fields and packages/cli/catalog-src (D-0065). Do not edit; run node scripts/catalog/build.ts.",
3
3
  "schemaVersion": 1,
4
- "cli": "0.4.54",
4
+ "cli": "0.4.56",
5
5
  "core": {
6
6
  "package": "@dokebi/core",
7
7
  "version": "0.4.7"
@@ -825,7 +825,7 @@
825
825
  {
826
826
  "id": null,
827
827
  "package": "@dokebi/cli",
828
- "version": "0.4.54",
828
+ "version": "0.4.56",
829
829
  "kind": "cli",
830
830
  "summary": "Commands to create a project, browse the plugin catalog, run recipes, install plugins and verify (dokebi)",
831
831
  "description": "Project scaffolding, plugin catalog, recipes, install and verification CLI for Dokebi.",
@@ -2143,7 +2143,7 @@
2143
2143
  {
2144
2144
  "id": "dokebi-module",
2145
2145
  "package": "@dokebi/module",
2146
- "version": "0.4.9",
2146
+ "version": "0.4.10",
2147
2147
  "kind": "plugin",
2148
2148
  "summary": "Modules that hold one feature each (src/shared/modules/<module>); an app attaches them under a prefix",
2149
2149
  "description": "Feature modules for Dokebi apps: controllers, models, views and routes in one folder mounted under a prefix.",
@@ -37,7 +37,7 @@ export const INTEGRATION_RULES = [
37
37
  '- Background work (D-0141): deliveries (webhooks, mail, notifications), exports, imports, copies, grace periods and cleanups are work items of @dokebi/outbox, not loops you write. Enqueue with outbox.enqueue(tx, { type, owner, destination, payload, dedupeKey, notBefore }) inside the business transaction and register outbox.handle(type, handler, { onDone }) in the setup of the module that owns the work; its runner claims fair batches across owners through one due-time index, retries with backoff, waits out a destination that is down (a breaker per destination, dead only after a horizon of days), keeps dead items for outbox.resend and removes finished rows after a retention. It derives its own small pool of the main connection (pool.max, default 4), so add nothing but run the migration that npx dokebi add @dokebi/outbox writes, keep handlers idempotent with item.key, query in handlers through context.db (the outbox handler pool, never the main pool: an owner whose handlers wait on a locked row then holds at most runner.maxInFlightPerOwner of them while the other owners keep flowing), and put the arrival and drain per second of npx dokebi-outbox stats in the section 6 table of the final report. Never hand-write a claim loop, a retry or dead-letter table or a timer for such work. A destination is one endpoint (one webhook id or URL, one mailbox provider), never a whole host or a shared name such as database: items of one failing endpoint must not pause the others. Database-only cleanup has no destination, and a batch handler records a failing row and skips it rather than failing the whole item. Best-effort signals after a commit (an SSE change notice, a cache invalidation) are not outbox work: send them directly.',
38
38
  '- Recipe fit: pick the recipe whose scaffold matches the app (npx dokebi recipe list shows each recipe and its match); when you build on a scaffold made for something else, rename or remove its sample names (tables, option keys, routes, view titles) so none of them remains in the finished app.',
39
39
  '- Responsibility boundaries: use Controller -> Service -> Model for application data. Controllers translate HTTP input/output and call services; models own SQL, services provide data and coordinate workflows, and jobs invoke those services. Put app-specific services in src/apps/<app>/services, cross-app services in src/shared/services, and feature-module services in src/shared/modules/<module>/services. Shared services must not import app-specific code. Services accept explicit inputs and return DTOs, never request/reply or template objects; do not expose models or SQL pools through a service for controllers/routes to bypass it. Compose dependencies once during setup. Periodic and background work runs only through the scheduler and job plugins, registered by the module that owns it; never start timers, intervals or background loops in controllers, services or setup code. Keep auth extension wiring separate from reusable member persistence. Audit the final route and registration graph after replacing scaffold flows; remove obsolete unreferenced implementations that duplicate the active behavior, while preserving required engine entries, mail templates and user-owned resources. Split by responsibility, not by arbitrary file counts. When a browser UI is present, keep views/runtime for browser integration and requested reusable editor/upload UI in the template components, and display helpers separate from transport. Use explicit DTO types through services, browser adapters and Vue props; a default any response or any page state defeats SFC checking. Keep readable formatting. Keep original TS/JS/Vue source formatted; minification belongs only to generated build output. Declare a formatter that supports the source formats, include its check in project verification, and inspect the final source rather than claiming readability from build success. Include Vue SFC scripts/templates in type checking; a successful Vite build or server-only tsc is not a Vue type check. dokebi app add --inertia prepares it: npm run typecheck runs tsc and then vue-tsc (typecheck-vue.mjs with tsconfig.vue.json), so keep that step, write pages as <script setup lang="ts">, and type the shared page props in src/infra/inertia/page.d.ts. Preserve the shared error catalog at src/shared/errors.ts.',
40
- '- Files and folders (maintained layout; refreshed by guide --sync like every rule here): src holds only main.ts and the files the CLI writes at its root: dokebi.generated.ts and dokebi.modules.generated.ts (the registered modules; import registeredModules from it where code needs every module, an app that mounts each one or keys collected from each, and never keep a module list of your own). One app per src/apps/<app>: app.ts, routes.ts (or routes/ for route groups), controllers/, services/, models/, validation/ and views/<template>/ (Inertia pages in views/<template>/Pages, components in components/, browser integration in views/runtime/). Shared code: src/shared/models, src/shared/services, src/shared/views (layouts, partials), src/shared/locales/<locale>/<namespace>.json, src/shared/mail/<template>/<locale>/, application settings in src/shared/settings, input rules several apps or modules share (reading a list query, a reason) in src/shared/validation and the error catalog src/shared/errors.ts. Browser code several apps or modules share (a design system, shared layouts, composables, a socket client) goes in src/shared/browser: components/, layouts/, composables/, styles/ and lib/ (a project with two looks, an operator console and a member site, puts one folder per look first, src/shared/browser/staff/components/); pages import it with a relative path, server code never imports it. Browser code (the views of apps and modules and src/shared/browser) is type-checked by tsconfig.vue.json with vue-tsc, not by tsconfig.json. Code one app or module uses stays in the views/ of that app or module. src/shared holds nothing else (dokebi check warns shared-folder). One feature per module in src/shared/modules/<module> (module.ts, routes.ts and the same controllers/services/models/validation/views folders; create it with npx dokebi module add). Declarations the project adds to every module (its menu entries, its permission keys) are files at the module root named for what they declare (menu.ts, permissions.ts) that module.ts passes on; pages declared but not built yet are routes and stay in routes.ts. A feature several apps show is one module, a login of two apps included; when each app needs route ids of its own, each app mounts a set of its own whose routes carry those ids and call the same controllers. Plugin connection and extension code in src/infra/<name> (src/infra/db/connections.ts, src/infra/auth/extension.ts), including the project wrapper of a plugin (a defineModule wrapper in src/infra/module/) and code several apps share that reads a request through a plugin (the viewer from request.auth in src/infra/auth/, Inertia props several apps build the same way beside src/infra/inertia/shared.ts, a gate of every route of an app, a dokebi-web routeHook each app registers in its setup, in src/infra/web/); services never take the request; your own plugins in src/plugins/<name>. Migrations in src/infra/db/migrations/<connection> and seeds in src/infra/db/seeds/<connection> (npx dokebi-migrate make writes the file). Job handlers and event subscriptions are registered in the setup of the module that owns the feature (src/shared/modules/<module>/module.ts) and call its services; schedules are entries of options.dokebi-scheduler.schedules in dokebi.yaml whose job type such a handler takes; CPU tasks go in src/infra/worker/tasks.ts, event payload types in src/infra/events/types.ts and the cluster worker factory in src/infra/runtime/application.ts. Input validation (route schemas and validators) lives in validation/ of the app or module that owns the route; a pure rule both the server and the pages of that app or module use (a code check, a rich-text schema) stays in that validation/ folder, imports neither Node nor browser APIs, and the pages import it with a relative path (one several apps or modules use goes in src/shared/validation); a DTO type is exported by the service that returns it (cross-app DTOs with their service in src/shared/services). Tests: tests/unit (no external service), tests/integration (a real database, HTTP or broker) and tests/support (helpers and fixtures, never named *.test.ts); npm test runs node --test "tests/**/*.test.ts", which covers both test folders, and tsconfig.json includes tests/**/*.ts. Development tools (imports, measurements, one-off maintenance) go in scripts/ at the project root, run with node scripts/<name>.ts and never imported by src. Name .ts files and folders in kebab-case (Vue components and Inertia pages are PascalCase, as Pages/Posts/Show.vue), and give each file one responsibility.',
40
+ '- Files and folders (maintained layout; refreshed by guide --sync like every rule here): src holds only main.ts and the files the CLI writes at its root: dokebi.generated.ts and dokebi.modules.generated.ts (the registered modules; import registeredModules from it where code needs every module, an app that mounts each one or keys collected from each, and never keep a module list of your own). One app per src/apps/<app>: app.ts, routes.ts (or routes/ for route groups), controllers/, services/, models/, validation/ and views/<template>/ (Inertia pages in views/<template>/Pages, components in components/, browser integration in views/runtime/). Shared code: src/shared/models, src/shared/services, src/shared/views (layouts, partials), src/shared/locales/<locale>/<namespace>.json, src/shared/mail/<template>/<locale>/, application settings in src/shared/settings, input rules several apps or modules share (reading a list query, a reason) in src/shared/validation and the error catalog src/shared/errors.ts. Browser code several apps or modules share (a design system, shared layouts, composables, a socket client) goes in src/shared/browser: components/, layouts/, composables/, styles/ and lib/ (a project with two looks, an operator console and a member site, puts one folder per look first, src/shared/browser/staff/components/); pages import it with a relative path, server code never imports it. Browser code (the views of apps and modules and src/shared/browser) is type-checked by tsconfig.vue.json with vue-tsc, not by tsconfig.json. Code one app or module uses stays in the views/ of that app or module. src/shared holds nothing else (dokebi check warns shared-folder). One feature per module in src/shared/modules/<module> (module.ts, routes.ts and the same controllers/services/models/validation/views folders; create it with npx dokebi module add). Declarations the project adds to every module (its menu entries, its permission keys) are files at the module root named for what they declare (menu.ts, permissions.ts) that module.ts passes on; pages declared but not built yet are routes and stay in routes.ts. A module whose screens show parts of other modules (detail sections, list columns, filters, row menu items, dashboard cards) offers slots in slots.ts at its root, returned from its setup; a module that fills them requires it and adds data entries from slot-entries.ts in its own setup, open while its set is (module.enabled(set)); pages never import components of another module: entries are drawn by generic components of src/shared/browser, and a section with a screen of its own is a page of the filling module. A feature several apps show is one module, a login of two apps included; when each app needs route ids of its own, each app mounts a set of its own whose routes carry those ids and call the same controllers. Plugin connection and extension code in src/infra/<name> (src/infra/db/connections.ts, src/infra/auth/extension.ts), including the project wrapper of a plugin (a defineModule wrapper in src/infra/module/) and code several apps share that reads a request through a plugin (the viewer from request.auth in src/infra/auth/, Inertia props several apps build the same way beside src/infra/inertia/shared.ts, a gate of every route of an app, a dokebi-web routeHook each app registers in its setup, in src/infra/web/); services never take the request; your own plugins in src/plugins/<name>. Migrations in src/infra/db/migrations/<connection> and seeds in src/infra/db/seeds/<connection> (npx dokebi-migrate make writes the file). Job handlers and event subscriptions are registered in the setup of the module that owns the feature (src/shared/modules/<module>/module.ts) and call its services; schedules are entries of options.dokebi-scheduler.schedules in dokebi.yaml whose job type such a handler takes; CPU tasks go in src/infra/worker/tasks.ts, event payload types in src/infra/events/types.ts and the cluster worker factory in src/infra/runtime/application.ts. Input validation (route schemas and validators) lives in validation/ of the app or module that owns the route; a pure rule both the server and the pages of that app or module use (a code check, a rich-text schema) stays in that validation/ folder, imports neither Node nor browser APIs, and the pages import it with a relative path (one several apps or modules use goes in src/shared/validation); a DTO type is exported by the service that returns it (cross-app DTOs with their service in src/shared/services). Tests: tests/unit (no external service), tests/integration (a real database, HTTP or broker) and tests/support (helpers and fixtures, never named *.test.ts); npm test runs node --test "tests/**/*.test.ts", which covers both test folders, and tsconfig.json includes tests/**/*.ts. Development tools (imports, measurements, one-off maintenance) go in scripts/ at the project root, run with node scripts/<name>.ts and never imported by src. Name .ts files and folders in kebab-case (Vue components and Inertia pages are PascalCase, as Pages/Posts/Show.vue), and give each file one responsibility.',
41
41
  '- Apps split by host (D-0132): with several @dokebi/app apps on different hosts, routes that plugins add answer on every host unless they are bound to apps. Bind each plugin endpoint to its app in dokebi.yaml: dokebi-mcp.app: mcp (the MCP route), dokebi-oauth.app: studio (the authorization server: metadata, authorize with the consent page, token, revoke, register; the issuer origin is a domain of that app) and dokebi-oauth.resources.<id>.app: mcp (the protected resource metadata, on the app of the resource uri host). Every other host then answers the 404 of an unknown route. Put the sign-in page on the issuer app. A route of your own module or plugin on web takes app: <name> or app: [<name>, ...] the same way. Never write an onRequest hook that compares the Host header to hide an endpoint, and never answer 403 on the wrong host. Without @dokebi/app a bound route fails the start (ROUTE_APP_UNAVAILABLE), an unknown app name too (ROUTE_APP_UNKNOWN), and an issuer or resource uri on a domain of another app fails it with INVALID_OPTIONS naming the option to set; health routes stay on every host.',
42
42
  '- Module contributions (D-0130): a feature module that offers values to a plugin point (MCP tools, prompts and resources of @dokebi/mcp, mail template folders) declares the points in defineModule({ contributes: [mcpTools] }) and calls module.contribute(point, value) in its own setup, after it builds its services; the contributed objects (an McpTool subclass) take those services in their constructors. Core sets the module up before the plugin that collects the point, so the services exist when the collector reads them, and contributions close when every setup has finished. A module never collects. Never rebuild module services in a separate definePlugin, and never register an app plugin by hand in src/main.ts or src/infra/runtime/application.ts to reach them: describe, the tests and the other entry do not see such a plugin, and doctor and check do not read it. A second module reaches the services through requires: [workspace] and module.get(workspace). Values that no registered plugin collects are dropped with warn POINT_NOT_COLLECTED, npx dokebi check reports module-point-not-installed when the plugin package of a point is not installed, and npx dokebi describe lists each module point and its collector. MCP tool names are unique across modules and plugins (INVALID_TOOL names both owners).',
43
43
  "- What `npx dokebi check` enforces from these rules (D-0105), so a broken one fails before you report: background-timer (an error, so verify fails) is a setInterval, a setTimeout/setImmediate that reschedules itself, or a loop that sleeps inside a task started in the background (an immediately invoked async function or a function called without await, such as a polling loop in a module start), in server code under src/ (views and tests are not read): move the work to a @dokebi/job handler registered in the owning module's setup and an entry of options.dokebi-scheduler.schedules; one-shot delays, time limits, awaited sleeps of node:timers/promises and timers of one request or socket are fine (a timer a request stores on this or in an outer variable outlives it and is reported). polling-loop (an error no marker silences) is a loop that sleeps inside a task started in the background, or a timer whose callback does database work: move it to an @dokebi/outbox or @dokebi/job handler. private-pool (an error) is a database pool or client made with the driver outside src/infra/db (new pg.Pool, mysql2 createPool, new MongoClient): take connections from @dokebi/db (connection(main), derive('main', { purpose, overrides: { max } }) for a pool of one kind of work, or another connection in dokebi.yaml) so dokebi.yaml sets their size and waitTimeoutMs and a caller past the wait gets 503 with Retry-After. overload-off (an error) is a route config overload: false: keep the overload protection on every API route (a metrics scrape or status page takes a marker). readiness-off (an error) is a route config readiness: false: an API route keeps refusing with 503 NOT_READY while a required dependency is down (a metrics scrape or status page that must answer then takes a marker). Warnings: in-process-queue (the resolve of a new Promise stored in a collection to call later: a queue of one worker without bound or deadline), fixed-owner-cap (a per-owner count of requests in progress compared with a fixed limit: use the owner share of @dokebi/db, share(main).enter(owner), which refuses only while the pool is full, @dokebi/db AI.md 6.4), wait-count-refusal (a comparison of the callers waiting for a pool connection, such as pool.waitingCount, with a number: refuse by the wait deadline, never by how many wait), responsibility-size (a model of 400+ code lines over 8+ tables or collections, a controller with 20+ route handlers or 300+ code lines, a service whose methods mostly only pass their arguments to a model) and memory-filtered-page (rows a query returned, skipped in code by an input such as filter.status and then cut to a page). A warning is still a broken rule: fix it, or keep it with // dokebi-check: allow <rule> <reason> and say why in your final message. An allow marker on background-timer is only for per-process upkeep of in-memory state (a cache of this worker); a loop that reads or writes the database (claiming, folding, polling a queue table) is never a valid reason: move it to a job or an outbox handler. check lists every marker with a reason under allowed, and verify ok asks your final message to list them with their reasons. With @dokebi/db installed, verify ok lists finalReport: the section 6 table your final message must contain.",
@@ -16,9 +16,13 @@
16
16
  // i18n-layer-missing a layer has a key in one language and not in another language of the
17
17
  // project: users of that language see a lower layer's or another
18
18
  // language's text. One problem per layer, language and namespace.
19
- // Only literal keys whose first part is a namespace of the catalogs are read (`t('auth.login')`
20
- // with an auth.json); a key built at run time, one with an explicit default (`t('k', 'Text')`)
21
- // and lines in a comment are not.
19
+ // Literal keys whose first part is a namespace of the catalogs are read (`t('auth.login')` with
20
+ // an auth.json). A call that is certainly the translation function — `$t(…)`, `….i18n.t(…)`, or
21
+ // `t(…)` in a file that takes `t` from `useI18n()` of @dokebi/template-inertia/i18n — is read
22
+ // whatever its key: a key whose namespace no catalog has, or one without a namespace
23
+ // (`t('flow.in')` for `t('dashboard.flow.in')`), is reported too (the page throws PageI18nError).
24
+ // A key built at run time, one with an explicit default (`t('k', 'Text')`) and lines in a
25
+ // comment are not read.
22
26
  import { readdir, readFile } from 'node:fs/promises';
23
27
  import { join } from 'node:path';
24
28
  import { CONFIG_FILE, parseProjectConfig } from '../configuration.js';
@@ -34,7 +38,10 @@ const FILES = /\.(?:vue|ts|mts|js|mjs|ejs)$/;
34
38
  const MAX_BYTES = 1024 * 1024;
35
39
  const CATEGORIES = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);
36
40
  /** `t(` or `$t(` (also `.t(`, `i18n.t(`) with a quoted key, then `,` or `)`. */
37
- const CALL = /(^|[^\w$])\$?t\(\s*(['"`])([A-Za-z][\w-]*(?:\.[\w-]+)+)\2\s*([,)])/g;
41
+ const CALL = /(^|[^\w$])(\$?)t\(\s*(['"`])([A-Za-z][\w-]*(?:\.[\w-]+)*)\3\s*([,)])/g;
42
+ /** A file whose `t` is the page translation function: it imports useI18n and takes `t` from it. */
43
+ const PAGE_I18N_IMPORT = /from\s*['"]@dokebi\/template-inertia\/i18n['"]/;
44
+ const PAGE_T = /\{[^}]*\bt\b[^}]*\}\s*=\s*useI18n\(/;
38
45
  /** Keys a missing-layer problem names before "and N more". */
39
46
  const NAMED = 5;
40
47
  /** @dokebi/i18n's rule (catalogs.ts): `other` and only plural categories with strings. */
@@ -294,31 +301,55 @@ defaultFolder = defaultLocale) {
294
301
  namespaces.add(key.slice(0, key.indexOf('.')));
295
302
  const markers = readMarkers(text).filter((marker) => marker.rule === RULE);
296
303
  const problems = [];
304
+ const pageT = PAGE_I18N_IMPORT.test(text) && PAGE_T.test(text);
297
305
  for (const [index, content] of text.split('\n').entries()) {
298
306
  if (/^\s*(?:\/\/|\*|\/\*|<%#|<!--)/.test(content))
299
307
  continue;
300
308
  for (const match of content.matchAll(CALL)) {
301
- const key = match[3];
302
- if (!namespaces.has(key.slice(0, key.indexOf('.'))))
309
+ const key = match[4];
310
+ const dot = key.indexOf('.');
311
+ const namespace = dot < 0 ? '' : key.slice(0, dot);
312
+ const at = match.index ?? 0;
313
+ // Certainly the translation function: $t, ….i18n.t, or the t of useI18n() in this file.
314
+ const certain = match[2] === '$' ||
315
+ content.slice(0, at + match[1].length).endsWith('i18n.') ||
316
+ (pageT && match[1] !== '.');
317
+ const known = namespaces.has(namespace);
318
+ if (!known && !certain)
303
319
  continue;
304
320
  // An explicit default (`t('k', 'Text')`) is shown when the key is missing.
305
- const after = content.slice((match.index ?? 0) + match[0].length);
306
- if (match[4] === ',' && /^\s*['"`]/.test(after))
321
+ const after = content.slice(at + match[0].length);
322
+ if (match[5] === ',' && /^\s*['"`]/.test(after))
307
323
  continue;
308
- if (fallback?.has(key))
324
+ if (known && fallback?.has(key))
309
325
  continue;
310
- const having = [...catalogs].filter(([, keys]) => keys.has(key)).map(([locale]) => locale);
311
326
  const line = index + 1;
312
327
  const marker = markers.find((item) => item.line === line || item.line === line - 1);
313
328
  if (marker?.reason.replace(/\s*[-_%]*>\s*$/, '').trim())
314
329
  continue;
315
- const namespace = key.slice(0, key.indexOf('.'));
330
+ const unmarked = marker
331
+ ? ' (the dokebi-check marker has no reason, so it does not count)'
332
+ : '';
333
+ if (!known) {
334
+ const names = [...namespaces].sort();
335
+ const listed = `${names.slice(0, NAMED).join(', ')}${names.length > NAMED ? ` and ${names.length - NAMED} more` : ''}`;
336
+ problems.push({
337
+ rule: RULE,
338
+ severity: 'warning',
339
+ file: path,
340
+ line,
341
+ message: `${path} asks for the translation ${key}, ${namespace ? `but no catalog has the namespace ${namespace}` : 'a key without a namespace'} (${names.length ? `the namespaces are ${listed}` : 'there are no catalogs'}): @dokebi/i18n throws MISSING_MESSAGE for it, and a page throws PageI18nError and does not render${unmarked}`,
342
+ fix: `correct the key: a key is <namespace>.<path>, the namespace being a catalog file name (${LOCALES}/${defaultFolder}/<namespace>.json, or the locales folder of its app or module)${namespace ? `; or add ${LOCALES}/${defaultFolder}/${namespace}.json` : ''}`,
343
+ });
344
+ continue;
345
+ }
346
+ const having = [...catalogs].filter(([, keys]) => keys.has(key)).map(([locale]) => locale);
316
347
  problems.push({
317
348
  rule: RULE,
318
349
  severity: 'warning',
319
350
  file: path,
320
351
  line,
321
- message: `${path} asks for the translation ${key}, which ${having.length ? `only the ${having.join(', ')} catalog${having.length > 1 ? 's have' : ' has'}, not the default locale ${defaultLocale}` : 'no catalog has'}: @dokebi/i18n throws MISSING_MESSAGE for it${having.length ? ' in the other locales' : ''} (under npx dokebi dev the page shows the key)${marker ? ' (the dokebi-check marker has no reason, so it does not count)' : ''}`,
352
+ message: `${path} asks for the translation ${key}, which ${having.length ? `only the ${having.join(', ')} catalog${having.length > 1 ? 's have' : ' has'}, not the default locale ${defaultLocale}` : 'no catalog has'}: @dokebi/i18n throws MISSING_MESSAGE for it${having.length ? ' in the other locales' : ''} (under npx dokebi dev the page shows the key)${unmarked}`,
322
353
  fix: `add ${key.slice(namespace.length + 1)} to ${LOCALES}/${defaultFolder}/${namespace}.json (the fallback of every locale; or to the locales folder of its app or module), or correct the key`,
323
354
  });
324
355
  }
package/dist/output.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export declare const CLI_VERSION = "0.4.54";
1
+ export declare const CLI_VERSION = "0.4.56";
2
2
  export declare function envelope(command: string, result: unknown, ok?: boolean): object;
3
3
  export declare function failure(command: string, error: unknown, mutationStarted: boolean): object;
package/dist/output.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CliError } from './errors.js';
2
- export const CLI_VERSION = '0.4.54';
2
+ export const CLI_VERSION = '0.4.56';
3
3
  export function envelope(command, result, ok = true) {
4
4
  return { schemaVersion: 1, cliVersion: CLI_VERSION, command, ok, result, error: null };
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/cli",
3
- "version": "0.4.54",
3
+ "version": "0.4.56",
4
4
  "description": "Project scaffolding, plugin catalog, recipes, install and verification CLI for Dokebi.",
5
5
  "keywords": [
6
6
  "dokebi",