@starci/eslint-canon-be 3.9.3 → 3.11.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 +19 -0
- package/README.md +1 -1
- package/dist/ai-gateway.d.ts +5 -0
- package/dist/ai-gateway.js +48 -1
- package/dist/lib/hfs-view.d.ts +5 -0
- package/dist/no-raw-sql.d.ts +1 -1
- package/dist/no-raw-sql.js +95 -35
- package/dist/query-safety.js +1 -1
- package/package.json +1 -1
- package/runtime/knowledge/hfs/canon-pins.yaml +7 -7
- package/runtime/knowledge/hfs/rules.yaml +25 -2
- package/runtime/knowledge/hfs/slots.yaml +6 -2
- package/runtime/scripts/hfs/declaration-shape.mjs +4 -2
- package/runtime/scripts/hfs/rule-params-shape.mjs +7 -2
- package/runtime/scripts/hfs/slots.mjs +15 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.11.0 - 2026-10-31
|
|
4
|
+
|
|
5
|
+
- Changed (breaking for a lite app that kept raw SQL): R334 `no-raw-sql` is one style, no SQL text in lite TypeScript outside the test world. New messages: `query` (a `.query(` outside the world, except the one composer `platform/database/database.client.ts` with its template statements, a file `ruleParams.be.sqlPassThrough` or hfs.json `sides.be.sqlPassThrough` lists with a plain-string argument, and the `*.spec.ts` beside it; `platform/database` loses its blanket exemption), `template` (a `sql` template outside the world), `sqlFile` (a `*.sql.ts` outside the world), `sqlTagImport` (an import of `sql`, `ident`, `SqlText` or `SqlIdent` outside the world; the tag's own module `database.sql.ts` is exempt), `worldCallHelper` (a world `sql` statement that only calls a listed function: it is `callDbFunction`) and `worldTableWrite` (a world statement that writes a `public` or `be_access` table: it goes through the entity or the area's builder). `builder` and `unlisted` are kept; the world keeps raw SQL for probes.
|
|
6
|
+
- Changed: the R68 text names the call and LISTEN statements of `database.client.ts`; `HfsRuleParams` carries `sqlPassThrough`.
|
|
7
|
+
- Changed: the bundled runtime copies follow @starci/hfs 4.14.0 (R334 law, `ruleParams.be.sqlPassThrough` with the seed runner, the world allows `<name>.sql.ts`) and the canon pins name the cohort hfs 4.15.0, eslint-canon-be 3.11.0, eslint-canon-fe 9.7.0, @starci/grammar, eslint-grammar-core and eslint-grammar-offset-pop 0.17.0.
|
|
8
|
+
|
|
9
|
+
## 3.10.1 - 2026-10-31
|
|
10
|
+
|
|
11
|
+
- Changed: the bundled canon pins name @starci/ai-router 0.5.0 (many providers behind one virtual key, the persisted key blacklist) and the cohort that carries them: hfs 4.13.3, eslint-canon-be 3.10.1, eslint-canon-fe 9.6.6, eslint-grammar-core and eslint-grammar-offset-pop 0.16.6; no rule changed.
|
|
12
|
+
|
|
13
|
+
## 3.10.0 - 2026-10-31
|
|
14
|
+
|
|
15
|
+
- Added: `ai-virtual-key-name` (R344 `BE_AI_VIRTUAL_KEY`): inside `integrations/ai` every `<env>.secret(...)` names exactly `STARCI_AI_KEY`, as a literal: the one virtual key the ai-router gateway mounts and every client uses; the custody owner `integrations/ai-gateway` passes the gateway no `adminToken`, since it exposes no admin API (ruling be-ai-one-virtual-key). Exported: `VIRTUAL_KEY_VARIABLE`.
|
|
16
|
+
- Changed: the bundled runtime copies follow @starci/hfs 4.13.2 (R344 in the catalog and on the `be.integrations` slot) and the canon pins name the lint cohort eslint-canon-be 3.10.0, eslint-canon-fe 9.6.5, eslint-grammar-core and eslint-grammar-offset-pop 0.16.5.
|
|
17
|
+
|
|
18
|
+
## 3.9.4 - 2026-10-31
|
|
19
|
+
|
|
20
|
+
- Changed: the bundled canon pins name @starci/hfs 4.13.1 and the lint cohort (eslint-canon-be 3.9.4, eslint-canon-fe 9.6.4, eslint-grammar-core and eslint-grammar-offset-pop 0.16.4); no rule changed.
|
|
21
|
+
|
|
3
22
|
## 3.9.3 - 2026-10-31
|
|
4
23
|
|
|
5
24
|
- Changed: the bundled canon pins name the 0.16.3 cohort (@starci/grammar, eslint-grammar-core and eslint-grammar-offset-pop 0.16.3, eslint-canon-fe 9.6.3, eslint-canon-be 3.9.3, stylelint-canon 2.3.0, jest-preset 2.6.0, hfs 4.13.0); ChatWorkspace and PaneLayout are removed with no alias; PaneGrid and Pane are the one generic pane grid: grammar names are generic.
|
package/README.md
CHANGED
|
@@ -40,7 +40,7 @@ A sample, not the list:
|
|
|
40
40
|
| **Errors** | A `catch` rethrows, calls a method on a `Logger` receiver (typed, from `platform/logging`) or returns an outcome carrying its cause; a `DomainError` subclass lives only in `errors/<capability>.error.ts` of its owner, and that file is one code enum, one `Record<Code, ErrorKind>` table and one empty class; a `throw` throws a `DomainError`, never a bare `Error`, a framework exception or a platform error out of a domain (`catch-must-account`, `error-home`, `throw-domain-error`, `error-family-shape`) |
|
|
41
41
|
| **Schema authority** | Migrations only: every DataSource or TypeORM options object states the literal `synchronize: false` (found by the contextual type), no `migrationsRun`, no DDL string outside a migration, no entity glob; no `@Entity` type reachable from a transport signature, a handler `execute`, a contract or a message, and no GraphQL or validator import in an entity file (`no-runtime-schema`, `no-entity-in-contract`) |
|
|
42
42
|
| **Config and secrets** | `process.env` (any form) is allowed in the `platform/config` file declaring `EnvSource`, the test world (slot `be.tests.world`) and the app bootstrap roles `apps/<app>/src/main.ts` and its matching `<app>.env.ts`; only those two app roles may read `EnvSource` or capability parse helpers. Compose groups and `<app>.options.ts` never read `process.env` or `EnvSource`. `@nestjs/config` and `dotenv` are forbidden config paths. A function exported by a `<capability>.config.ts` keeps its existing name and is called only from these bootstrap roles, its own config file or spec, the test world and a provider contract spec (`config-parsed-in-main`). Secrets use `EnvSource.secret()`: `<NAME>_FILE` takes priority for `.starcistacks` custody, and plain `<NAME>` is read only when the file key is absent; a declared file supplies exact contents and an empty or unreadable path fails startup without fallback. No default of any kind for a value typed `Secret` or `Url`; secrets compare with `timingSafeEqual` (`no-direct-env-read`, `config-parsed-in-main`, `no-secret-default`, `secret-compare-timing-safe`) |
|
|
43
|
-
| **Model calls** (R326, R327) | Every model call goes through the `@starci/ai-router` gateway: an upstream provider key variable (`PROVIDER_KEY_VARIABLES` of `src/ai-gateway.ts`, with its `_FILE` twin) is named only in the gateway's custody owner `integrations/ai-gateway`, specs and the test world included; code builds only `ChatOpenAI` and `OpenAIEmbeddings` of `@langchain/openai`, each from an inline options object whose `configuration.baseURL` is read from a `<c>.options.ts` type and whose `apiKey` is a `platform/config` `Secret` revealed
|
|
43
|
+
| **Model calls** (R326, R327, R344) | Every model call goes through the `@starci/ai-router` gateway: an upstream provider key variable (`PROVIDER_KEY_VARIABLES` of `src/ai-gateway.ts`, with its `_FILE` twin) is named only in the gateway's custody owner `integrations/ai-gateway`, specs and the test world included; code builds only `ChatOpenAI` and `OpenAIEmbeddings` of `@langchain/openai`, each from an inline options object whose `configuration.baseURL` is read from a `<c>.options.ts` type and whose `apiKey` is a `platform/config` `Secret` revealed; `integrations/ai` reads exactly `STARCI_AI_KEY`, the one virtual key of every client, and the custody owner passes the gateway no `adminToken`. Which owner may import LangChain, `openai`, a provider SDK or an agent framework is the infrastructure table (`provider-key-custody`, `ai-client-through-gateway`, `ai-virtual-key-name`, `infra-import-owner`) |
|
|
44
44
|
| **Ambient ids** (R142) | `randomUUID` of Node's crypto (named, namespace or global), the `v1`, `v4`, `v6` and `v7` generators of `uuid`, `nanoid` and `ulid` are used only inside `platform/ids`, specs included: code asks the injected `Ids` port and a spec provides `fakeIds()`; the generators are found by the module they are imported from, never by a local name (`no-ambient-id`) |
|
|
45
45
|
| **App composition** (R245, R246) | `apps/<app>/src/<app>.env.ts` exports an explicit typed `<App>Env` interface and `read<App>Env(env: EnvSource): <App>Env` (for example `ApiEnv` and `readApiEnv`). The interface declares its own readonly parsed members, such as `readonly server: ReturnType<typeof parseServerConfig>`, structurally compatible with the app's options. The role name stays `<app>.env.ts`, never `env.ts`; capability `<capability>.config.ts` files stay unchanged. `main.ts` creates `EnvSource` once, imports and calls the reader, builds options and boots. The env file holds fail-fast parsing only, with no localhost or default host fallback, logic, module composition, business code or feature imports; `<app>.options.ts` holds env-derived options and port bindings only, with no parsing. Both refuse an array listing `*Module` classes, module or queue registrations (`register`, `forRoot`, `registerQueue`) or scheduler entries, and an `imports`, `modules`, `schedulers` or `processors` list; the env file also refuses standalone module or queue registration calls. Composition belongs in a `compose/<area>.ts` group that `app.module.ts` spreads (`app-options-composition-free`, `BE_APP_OPTIONS_COMPOSITION`). Each app file stays within its slot's line budget: `main.ts` 80, env 150, options 200, group 120, root 250 (`app-file-budget`, `BE_APP_COMPOSITION_BUDGET`). The interface and reader exports are a documented scaffold contract; they need no new lint rule |
|
|
46
46
|
| **Sonar parity** (R235) | The smells SonarCloud measures that a lint rule can decide: no `await` inside a loop (`no-await-in-loop`, S9382; `for (;;)` and `while (true)` are spared), no `charCodeAt`/`fromCharCode` (`prefer-code-point`), no string that only escapes backslashes (`prefer-string-raw`), no nested conditional (`no-nested-conditional`), `void` only on a call (`no-void-operator`), no unused import (`no-unused-import`), `export ... from` for an import that is only handed on (`prefer-export-from`); the factory also turns on typescript-eslint `no-deprecated`, `no-base-to-string` and `require-await`. The files `*.spec.ts` and `*.e2e-spec.ts` are outside the scan, so outside these rules |
|
package/dist/ai-gateway.d.ts
CHANGED
|
@@ -6,14 +6,19 @@ export declare const GATEWAY_CUSTODY = "integrations/ai-gateway";
|
|
|
6
6
|
* gateway's custody owner. A provider the gateway adds joins this list.
|
|
7
7
|
*/
|
|
8
8
|
export declare const PROVIDER_KEY_VARIABLES: readonly string[];
|
|
9
|
+
/** The one virtual key every client of the gateway authenticates with (`sk-starci-<app>-<48 hex>`, sealed in the `ai` member). */
|
|
10
|
+
export declare const VIRTUAL_KEY_VARIABLE = "STARCI_AI_KEY";
|
|
9
11
|
/** Only the gateway's custody owner names an upstream provider key. */
|
|
10
12
|
export declare const providerKeyCustody: RuleModule;
|
|
11
13
|
/** The LangChain clients point at the gateway: base URL from options, virtual key from a `Secret`. */
|
|
12
14
|
export declare const aiClientThroughGateway: RuleModule;
|
|
15
|
+
/** The gateway's one client key is `STARCI_AI_KEY`, read by `integrations/ai`; the gateway gets no admin token. */
|
|
16
|
+
export declare const aiVirtualKeyName: RuleModule;
|
|
13
17
|
/** The rules this law contributes to the plugin. */
|
|
14
18
|
export declare const rules: {
|
|
15
19
|
"provider-key-custody": RuleModule;
|
|
16
20
|
"ai-client-through-gateway": RuleModule;
|
|
21
|
+
"ai-virtual-key-name": RuleModule;
|
|
17
22
|
};
|
|
18
23
|
/** Every rule of this law at `error`. */
|
|
19
24
|
export declare const recommended: Recommended;
|
package/dist/ai-gateway.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The rules that hold model calls behind the ai-router gateway (catalog R326 `BE_AI_KEY_CUSTODY`, R327
|
|
3
|
-
* `BE_AI_GATEWAY_CLIENT`; contexts/code/be/ai.md BE-AI-1 and BE-AI-3).
|
|
3
|
+
* `BE_AI_GATEWAY_CLIENT`, R344 `BE_AI_VIRTUAL_KEY`; contexts/code/be/ai.md BE-AI-1 and BE-AI-3).
|
|
4
4
|
*
|
|
5
5
|
* - `provider-key-custody` keeps every upstream provider key inside the gateway's custody owner, `integrations/ai-gateway`,
|
|
6
6
|
* the one owner that registers `@starci/ai-router` with the provider pool. Anywhere else a provider key variable
|
|
@@ -15,6 +15,9 @@
|
|
|
15
15
|
* virtual key). A literal provider URL, a missing base URL (the library falls back to the provider's own) and a
|
|
16
16
|
* missing key (the library falls back to `OPENAI_API_KEY`) are refused. The constructor is found by its import, never
|
|
17
17
|
* by its spelling.
|
|
18
|
+
* - `ai-virtual-key-name` holds the one client key of the gateway: inside `integrations/ai` every `<env>.secret(...)` names
|
|
19
|
+
* exactly `STARCI_AI_KEY` (`VIRTUAL_KEY_VARIABLE`) as a literal, the virtual key the gateway mounts from the sealed `ai`
|
|
20
|
+
* member; and the custody owner hands the gateway no `adminToken`, since the gateway exposes no admin API.
|
|
18
21
|
*
|
|
19
22
|
* Which owner may import LangChain, `openai` or another provider SDK at all is the infrastructure table of the slot
|
|
20
23
|
* manifest (`ruleParams.be.infraOwners`, judged by `infra-import-owner`, R90).
|
|
@@ -53,6 +56,10 @@ export const PROVIDER_KEY_VARIABLES = Object.freeze([
|
|
|
53
56
|
"HF_TOKEN",
|
|
54
57
|
]);
|
|
55
58
|
const PROVIDER_KEYS = new Set(PROVIDER_KEY_VARIABLES.flatMap((name) => [name, `${name}_FILE`]));
|
|
59
|
+
/** The one virtual key every client of the gateway authenticates with (`sk-starci-<app>-<48 hex>`, sealed in the `ai` member). */
|
|
60
|
+
export const VIRTUAL_KEY_VARIABLE = "STARCI_AI_KEY";
|
|
61
|
+
/** The owner id of the app's LangChain integration, whose config reads the virtual key. */
|
|
62
|
+
const AI_INTEGRATION = "integrations/ai";
|
|
56
63
|
/** The LangChain provider package whose clients are judged, and the clients code may build from it. */
|
|
57
64
|
const LANGCHAIN_OPENAI = "@langchain/openai";
|
|
58
65
|
const GATEWAY_CLIENTS = new Set(["ChatOpenAI", "OpenAIEmbeddings"]);
|
|
@@ -172,13 +179,53 @@ export const aiClientThroughGateway = {
|
|
|
172
179
|
};
|
|
173
180
|
},
|
|
174
181
|
};
|
|
182
|
+
/** `<x>.secret(<arg>)`: the first argument of a non-computed `secret` member call, or null. */
|
|
183
|
+
const secretArgumentOf = (node) => node.callee.type === "MemberExpression" && !node.callee.computed && keyName(node.callee.property) === "secret" ? (node.arguments[0] ?? null) : null;
|
|
184
|
+
/** The gateway's one client key is `STARCI_AI_KEY`, read by `integrations/ai`; the gateway gets no admin token. */
|
|
185
|
+
export const aiVirtualKeyName = {
|
|
186
|
+
meta: {
|
|
187
|
+
type: "problem",
|
|
188
|
+
docs: { description: "`integrations/ai` reads exactly `STARCI_AI_KEY` as its secret, and the gateway's custody owner passes no admin token." },
|
|
189
|
+
schema: [],
|
|
190
|
+
messages: {
|
|
191
|
+
name: "`integrations/ai` reads one secret, the gateway's virtual key `STARCI_AI_KEY` (`env.secret(\"STARCI_AI_KEY\")`); `{{name}}` is not it. Every client of the gateway, this integration and the agent runtime alike, uses that one key.",
|
|
192
|
+
dynamic: "`integrations/ai` names its secret as the literal `\"STARCI_AI_KEY\"`, so the one virtual key the gateway mounts is visible here.",
|
|
193
|
+
adminToken: "The ai-router gateway exposes no admin API: pass no `adminToken`. The one virtual key `STARCI_AI_KEY` is mounted from the sealed `ai` member (`mountedKeys`) and rotated by resealing it and deploying.",
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
create(context) {
|
|
197
|
+
const owner = ownerIdOf(context, context.filename);
|
|
198
|
+
return {
|
|
199
|
+
Property(node) {
|
|
200
|
+
if (node.computed || node.key.type !== "Identifier")
|
|
201
|
+
return;
|
|
202
|
+
if (owner === GATEWAY_CUSTODY && node.key.name === "adminToken")
|
|
203
|
+
context.report({ node: node.key, messageId: "adminToken" });
|
|
204
|
+
},
|
|
205
|
+
CallExpression(node) {
|
|
206
|
+
if (owner !== AI_INTEGRATION)
|
|
207
|
+
return;
|
|
208
|
+
const argument = secretArgumentOf(node);
|
|
209
|
+
if (argument === null)
|
|
210
|
+
return;
|
|
211
|
+
const name = staticText(argument);
|
|
212
|
+
if (name === null)
|
|
213
|
+
context.report({ node: argument, messageId: "dynamic" });
|
|
214
|
+
else if (name !== VIRTUAL_KEY_VARIABLE)
|
|
215
|
+
context.report({ node: argument, messageId: "name", data: { name } });
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
},
|
|
219
|
+
};
|
|
175
220
|
/** The rules this law contributes to the plugin. */
|
|
176
221
|
export const rules = {
|
|
177
222
|
"provider-key-custody": providerKeyCustody,
|
|
178
223
|
"ai-client-through-gateway": aiClientThroughGateway,
|
|
224
|
+
"ai-virtual-key-name": aiVirtualKeyName,
|
|
179
225
|
};
|
|
180
226
|
/** Every rule of this law at `error`. */
|
|
181
227
|
export const recommended = {
|
|
182
228
|
"starci-be/provider-key-custody": "error",
|
|
183
229
|
"starci-be/ai-client-through-gateway": "error",
|
|
230
|
+
"starci-be/ai-virtual-key-name": "error",
|
|
184
231
|
};
|
package/dist/lib/hfs-view.d.ts
CHANGED
|
@@ -109,6 +109,11 @@ export interface HfsRuleParams {
|
|
|
109
109
|
readonly name: string;
|
|
110
110
|
readonly reason: string;
|
|
111
111
|
}[];
|
|
112
|
+
/** The files whose `.query(` passes through SQL text that is not the app's own, side-relative with a reason (`ruleParams.be.sqlPassThrough` plus hfs.json `sides.be.sqlPassThrough`). */
|
|
113
|
+
readonly sqlPassThrough?: readonly {
|
|
114
|
+
readonly file: string;
|
|
115
|
+
readonly reason: string;
|
|
116
|
+
}[];
|
|
112
117
|
}
|
|
113
118
|
/** The frozen view of one side of an app. */
|
|
114
119
|
export interface HfsView {
|
package/dist/no-raw-sql.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RuleModule, Recommended } from "./lib/rule.js";
|
|
2
|
-
/**
|
|
2
|
+
/** Lite TypeScript holds no SQL text outside the test world: entities, or a function through `callDbFunction`. */
|
|
3
3
|
export declare const noRawSql: RuleModule;
|
|
4
4
|
/** The rule of the lite persistence law, by name. */
|
|
5
5
|
export declare const rules: {
|
package/dist/no-raw-sql.js
CHANGED
|
@@ -1,49 +1,67 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The lite persistence law (catalog R334 `BE_PERSISTENCE_NO_RAW_SQL`; contexts/code/be/persistence.md BE-PERSISTENCE-4):
|
|
3
|
-
*
|
|
4
|
-
* `delete`, `upsert`, `createQueryBuilder(Entity, "alias")`
|
|
3
|
+
* lite TypeScript holds no SQL text outside the test world. A table is read and written through its TypeORM entity on an
|
|
4
|
+
* EntityManager (`find`, `save`, `update`, `delete`, `upsert`, a pessimistic `lock` option, `createQueryBuilder(Entity, "alias")`
|
|
5
|
+
* with named parameters); anything else is a database function called through `callDbFunction` of `platform/database`.
|
|
5
6
|
*
|
|
6
|
-
* - `
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
7
|
+
* - `query`: a `.query(` call is refused everywhere except (1) the test world `src/tests/world`; (2) `platform/database/database.client.ts`,
|
|
8
|
+
* the one composer, whose statements are the templates R68 checks; (3) a file `ruleParams.be.sqlPassThrough` or hfs.json
|
|
9
|
+
* `sides.be.sqlPassThrough` lists with a reason, while its first argument is not a template literal or a `+` expression;
|
|
10
|
+
* (4) the `*.spec.ts` beside such a file. `platform/database` has no blanket exemption.
|
|
11
|
+
* - `template`: a `sql` tagged template outside the world. `sqlFile`: a `*.sql.ts` file outside the world. `sqlTagImport`: an import
|
|
12
|
+
* of `sql`, `ident`, `SqlText` or `SqlIdent` outside the world. The tag's own module (`platform/database/database.sql.ts`) is exempt.
|
|
13
|
+
* - `worldCallHelper`, `worldTableWrite`: a `sql` template inside the world that only calls a listed function (it is
|
|
14
|
+
* `callDbFunction`), or writes an application table (`public.` or `be_access.`: it goes through the entity or a builder).
|
|
15
|
+
* The world keeps raw SQL for probes: privileges, row-level security, catalogs, cron, pgmq queue tables, locks, failures.
|
|
16
|
+
* - `unlisted`: a literal function name handed to `callDbFunction` must be one `ruleParams.be.dbFunctions` lists (the canon's
|
|
17
|
+
* pg built-ins, bare, plus every other function schema-qualified, including hfs.json `sides.be.dbFunctions`).
|
|
18
|
+
* - `builder`: a query builder names its entity (`createQueryBuilder(Entity, "alias")`); a builder over a table-name string, a
|
|
19
|
+
* builder with no entity, and a `getRepository(...)` are refused (the world excepted).
|
|
20
|
+
* The rule runs in lite only (the catalog's `editions`); full keeps R36.
|
|
19
21
|
*
|
|
20
22
|
* Schema authority stays `db/migrations/*.sql`; whether the entities match it is `BE_ENTITY_SCHEMA_DRIFT` of `starci app db drift`.
|
|
21
23
|
*/
|
|
22
24
|
import { staticText } from "./lib/ast.js";
|
|
23
25
|
import { hfsOf } from "./lib/hfs.js";
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
*/
|
|
28
|
-
const RAW_SQL_OWNERS = ["src/modules/platform/database/", "src/tests/world/"];
|
|
26
|
+
import { baseNameOf, inDatabaseCapability } from "./lib/persistence.js";
|
|
27
|
+
/** The test world, the only place that may hold raw SQL text, by side-relative folder. */
|
|
28
|
+
const WORLD = "src/tests/world/";
|
|
29
29
|
/** The helper of platform/database whose second argument names the function it calls. */
|
|
30
30
|
const CALL_HELPER = "callDbFunction";
|
|
31
|
+
/** The one composer of SQL text in platform/database. */
|
|
32
|
+
const COMPOSER_FILE = "database.client.ts";
|
|
33
|
+
/** The module of platform/database that defines the `sql` tag. */
|
|
34
|
+
const TAG_FILE = "database.sql.ts";
|
|
35
|
+
/** The names that carry SQL text: the tag, its identifier check and their brands. */
|
|
36
|
+
const SQL_TEXT_NAMES = new Set(["sql", "ident", "SqlText", "SqlIdent"]);
|
|
37
|
+
/** The suffix of a spec file. */
|
|
38
|
+
const SPEC_SUFFIX = ".spec.ts";
|
|
39
|
+
/** A statement that writes an application table: it goes through the entity or the area's builder. */
|
|
40
|
+
const TABLE_WRITE = /^\s*(?:INSERT\s+INTO|UPDATE|DELETE\s+FROM)\s+(?:public|be_access)\./i;
|
|
31
41
|
/** True when a builder's first argument can be an entity class: neither absent nor a string. */
|
|
32
|
-
const namesEntity = (argument) =>
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
42
|
+
const namesEntity = (argument) => argument !== undefined && argument.type !== "TemplateLiteral" && !(argument.type === "Literal" && typeof argument.value === "string");
|
|
43
|
+
/** The text of a template literal, each substitution standing as `?`. */
|
|
44
|
+
const templateText = (template) => template.quasis.map((quasi) => quasi.value.cooked ?? quasi.value.raw).join("?");
|
|
45
|
+
/** The pattern of a statement that is only a call of one listed function: `SELECT [* FROM] <fn>(...) [AS x]`. */
|
|
46
|
+
const callPattern = (names) => {
|
|
47
|
+
if (names.length === 0)
|
|
48
|
+
return null;
|
|
49
|
+
const alternatives = names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
|
|
50
|
+
return new RegExp(`^\\s*SELECT\\s+(?:\\*\\s+FROM\\s+)?(?:${alternatives})\\s*\\([\\s\\S]*\\)\\s*(?:AS\\s+\\w+)?\\s*;?\\s*$`, "i");
|
|
37
51
|
};
|
|
38
|
-
/**
|
|
52
|
+
/** Lite TypeScript holds no SQL text outside the test world: entities, or a function through `callDbFunction`. */
|
|
39
53
|
export const noRawSql = {
|
|
40
54
|
meta: {
|
|
41
55
|
type: "problem",
|
|
42
|
-
docs: { description: "Lite
|
|
56
|
+
docs: { description: "Lite TypeScript holds no SQL text outside the test world: tables go through entities on an EntityManager, functions through callDbFunction of a listed name." },
|
|
43
57
|
schema: [],
|
|
44
58
|
messages: {
|
|
45
|
-
query: "`.query(` runs
|
|
46
|
-
template: "A `sql` template outside
|
|
59
|
+
query: "`.query(` runs SQL text outside the test world. Read and write through the entity on the EntityManager (`find`, `save`, `update`, `upsert`, a `lock` option, `createQueryBuilder(Entity, \"alias\")` with named parameters; a spec, builder or fixture on `world.db.<connection>`), and call a database function through `callDbFunction(manager, name, args)` (`advisoryXactLock` and `notify` do). Only `platform/database/database.client.ts` composes SQL text; a file whose text is not the app's own (the tracked seed, a customer data source, an outside session) is listed in hfs.json `sides.be.sqlPassThrough` with a reason and passes a plain string, never a template or a `+`.",
|
|
60
|
+
template: "A `sql` template outside the test world. Lite TypeScript holds no SQL text: build the query with the EntityManager or `createQueryBuilder(Entity, \"alias\")`, or call a database function through `callDbFunction`. Raw SQL for a privilege, row-level-security, catalog, cron or pgmq probe lives in `src/tests/world`.",
|
|
61
|
+
sqlFile: "A `*.sql.ts` file outside the test world. Only `src/tests/world` holds SQL text files; a query fragment or a function wrapper is named for what it is (`<name>.columns.ts`, `auth-doors.ts`).",
|
|
62
|
+
sqlTagImport: "`sql`, `ident`, `SqlText` and `SqlIdent` are imported outside the test world. Lite TypeScript holds no SQL text: use an entity on the EntityManager or `callDbFunction`.",
|
|
63
|
+
worldCallHelper: "This world statement only calls a listed database function. Call it through `callDbFunction(world.db.<connection>, name, args)`; the world keeps raw SQL for what neither an entity nor a listed function expresses.",
|
|
64
|
+
worldTableWrite: "This world statement writes an application table. Write it through the entity on `world.db.<connection>` (`save`, `update`, `delete`, `upsert`), or seed it with the area's builder (R98); the world keeps raw SQL for probes.",
|
|
47
65
|
builder: "A query builder must name its entity: `manager.createQueryBuilder(Entity, \"alias\")` on the injected EntityManager. A table-name string, a builder with no entity and a Repository bypass the entity mapping.",
|
|
48
66
|
unlisted: "`{{name}}` is not a listed database function. Name a function of a migration schema-qualified (`public.job_claim`) and add it to hfs.json `sides.be.dbFunctions` with the reason TypeORM cannot express it; a pg built-in is named bare only when the canon lists it; or map the work with an entity.",
|
|
49
67
|
},
|
|
@@ -51,9 +69,31 @@ export const noRawSql = {
|
|
|
51
69
|
create(context) {
|
|
52
70
|
const hfs = hfsOf(context);
|
|
53
71
|
const relative = hfs.relative(context.filename);
|
|
54
|
-
const
|
|
72
|
+
const inWorld = relative.startsWith(WORLD);
|
|
73
|
+
const base = baseNameOf(relative);
|
|
74
|
+
const inDatabase = inDatabaseCapability(hfs, context.filename);
|
|
75
|
+
const isComposer = base === COMPOSER_FILE && inDatabase;
|
|
76
|
+
const isTagModule = base === TAG_FILE && inDatabase;
|
|
55
77
|
const listed = new Set((hfs.ruleParams.dbFunctions ?? []).map((entry) => entry.name));
|
|
78
|
+
const passThrough = new Set((hfs.ruleParams.sqlPassThrough ?? []).map((entry) => entry.file));
|
|
79
|
+
const passThroughSpec = relative.endsWith(SPEC_SUFFIX) && passThrough.has(`${relative.slice(0, -SPEC_SUFFIX.length)}.ts`);
|
|
80
|
+
const callOnly = callPattern([...listed]);
|
|
56
81
|
return {
|
|
82
|
+
Program(node) {
|
|
83
|
+
if (!inWorld && !isTagModule && relative.endsWith(".sql.ts"))
|
|
84
|
+
context.report({ node, messageId: "sqlFile" });
|
|
85
|
+
},
|
|
86
|
+
ImportDeclaration(node) {
|
|
87
|
+
if (inWorld || isTagModule)
|
|
88
|
+
return;
|
|
89
|
+
for (const specifier of node.specifiers) {
|
|
90
|
+
if (specifier.type !== "ImportSpecifier")
|
|
91
|
+
continue;
|
|
92
|
+
const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
|
|
93
|
+
if (SQL_TEXT_NAMES.has(imported))
|
|
94
|
+
context.report({ node: specifier, messageId: "sqlTagImport" });
|
|
95
|
+
}
|
|
96
|
+
},
|
|
57
97
|
CallExpression(node) {
|
|
58
98
|
const callee = node.callee;
|
|
59
99
|
if (callee.type === "Identifier" && callee.name === CALL_HELPER) {
|
|
@@ -62,20 +102,40 @@ export const noRawSql = {
|
|
|
62
102
|
context.report({ node, messageId: "unlisted", data: { name } });
|
|
63
103
|
return;
|
|
64
104
|
}
|
|
65
|
-
if (
|
|
105
|
+
if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier")
|
|
66
106
|
return;
|
|
67
107
|
const method = callee.property.name;
|
|
68
|
-
if (method === "query")
|
|
108
|
+
if (method === "query") {
|
|
109
|
+
if (inWorld || passThroughSpec)
|
|
110
|
+
return;
|
|
111
|
+
const first = node.arguments[0];
|
|
112
|
+
if (isComposer && first?.type === "TemplateLiteral")
|
|
113
|
+
return;
|
|
114
|
+
const built = first?.type === "TemplateLiteral" || (first?.type === "BinaryExpression" && first.operator === "+");
|
|
115
|
+
if (passThrough.has(relative) && !built)
|
|
116
|
+
return;
|
|
69
117
|
context.report({ node, messageId: "query" });
|
|
70
|
-
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (inWorld)
|
|
121
|
+
return;
|
|
122
|
+
if (method === "getRepository")
|
|
71
123
|
context.report({ node, messageId: "builder" });
|
|
72
124
|
else if (method === "createQueryBuilder" && !namesEntity(node.arguments[0]))
|
|
73
125
|
context.report({ node, messageId: "builder" });
|
|
74
126
|
},
|
|
75
127
|
TaggedTemplateExpression(node) {
|
|
76
|
-
if (
|
|
128
|
+
if (node.tag.type !== "Identifier" || node.tag.name !== "sql")
|
|
77
129
|
return;
|
|
78
|
-
|
|
130
|
+
if (!inWorld) {
|
|
131
|
+
context.report({ node, messageId: "template" });
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const text = templateText(node.quasi);
|
|
135
|
+
if (callOnly?.test(text) === true)
|
|
136
|
+
context.report({ node, messageId: "worldCallHelper" });
|
|
137
|
+
else if (TABLE_WRITE.test(text))
|
|
138
|
+
context.report({ node, messageId: "worldTableWrite" });
|
|
79
139
|
},
|
|
80
140
|
};
|
|
81
141
|
},
|
package/dist/query-safety.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* tag is called only in a persistence `<name>.sql.ts`.
|
|
12
12
|
* - `no-query-builder` (R36) - no `createQueryBuilder(` call.
|
|
13
13
|
* - `no-interpolated-sql` (R68 `BE_SQL_INTERPOLATED`) - a substitution inside the `sql` tag is a `SqlIdent`; a `.query(`
|
|
14
|
-
* string built by template or concatenation is refused. One file is the owner R334 names for the lite
|
|
14
|
+
* string built by template or concatenation is refused. One file is the owner R334 names for the lite call and LISTEN statements,
|
|
15
15
|
* `platform/database/database.client.ts` of a lite app: there a `.query(` template may substitute only the checked parts its own
|
|
16
16
|
* validator brands (`DbFunctionPart`, `DbParameterList` declared in that file); any other substitution, a `+` and the same
|
|
17
17
|
* template in any other file stay refused.
|
package/package.json
CHANGED
|
@@ -31,35 +31,35 @@ pins:
|
|
|
31
31
|
source: packages/event-stream/package.json
|
|
32
32
|
why: 'the one server-sent-events client of every front end (fe-stack event-stream, owner:event-stream-package): the transport client layer (modules/api/sse/clients) creates one instance for the app with the bearer token source and the stream operations follow on it; it carries Last-Event-ID resume, the capped doubling backoff, the heartbeat timeout, the single 401 renewal and the useSWRSubscription adapter, so no app keeps a hand-written reader.'
|
|
33
33
|
'@starci/grammar':
|
|
34
|
-
version: 0.
|
|
34
|
+
version: 0.17.0
|
|
35
35
|
group: starci
|
|
36
36
|
install: registry
|
|
37
37
|
side: fe
|
|
38
38
|
source: packages/grammar/package.json
|
|
39
39
|
why: 'the grammar front ends read: the brand layer sets `--font-sans` and `--font-mono` and the grammar reads them; it carries the Input tel kind, the copyable and read-only Input, the IconButton disclosure props and count badge, ChatBubble, FillViewport, Textarea mentions and Enter-to-send, the leading PrimaryRailLayout rail, the plate-less Image, ListRow, the soft Alert, Progress steps, the floating primary IconButton, FlowGraph, the STATE-8 loading views and the bordered selectable TagGroup chips. The runtime source version wins for a @starci package.'
|
|
40
40
|
'@starci/eslint-canon-be':
|
|
41
|
-
version: 3.
|
|
41
|
+
version: 3.11.0
|
|
42
42
|
group: starci
|
|
43
43
|
install: registry
|
|
44
44
|
side: be
|
|
45
45
|
source: packages/eslint-canon-be/package.json
|
|
46
46
|
why: 'the back-end ESLint canon: `loadHfs(import.meta.url)` of be/eslint.config.mjs finds the app-root hfs.json (kind app) and gives every linted file the view of the be side, and the project graph is built per side; its bundled runtime copies (slots, canon-pins, failure codes, the architecture machine) put .starcistacks and .sops.yaml at the app root; `starciBeConfig({ hfs: loadHfs(import.meta.url) })` is the typed factory and the BE-CONVENTION laws are its rules.'
|
|
47
47
|
'@starci/eslint-canon-fe':
|
|
48
|
-
version: 9.
|
|
48
|
+
version: 9.7.0
|
|
49
49
|
group: starci
|
|
50
50
|
install: registry
|
|
51
51
|
side: fe
|
|
52
52
|
source: packages/eslint-canon-fe/package.json
|
|
53
53
|
why: 'the front-end ESLint canon: `loadHfs(import.meta.url)` of fe/eslint.config.mjs finds the app-root hfs.json (kind app) and gives every linted file the view of the fe side, and the project graph is built per side; its bundled runtime copies (slots, canon-pins, failure codes, the architecture machine) put .starcistacks and .sops.yaml at the app root; the front end has no tests (FE_NO_TESTS R97 in hfs) and no-vietnamese-in-source (R91) applies.'
|
|
54
54
|
'@starci/eslint-grammar-core':
|
|
55
|
-
version: 0.
|
|
55
|
+
version: 0.17.0
|
|
56
56
|
group: starci
|
|
57
57
|
install: registry
|
|
58
58
|
side: fe
|
|
59
59
|
source: packages/eslint-grammar-core/package.json
|
|
60
60
|
why: 'the StarCi Grammar component API lint, versioned with @starci/grammar; front ends compose this family package with the universal FE canon.'
|
|
61
61
|
'@starci/eslint-grammar-offset-pop':
|
|
62
|
-
version: 0.
|
|
62
|
+
version: 0.17.0
|
|
63
63
|
group: starci
|
|
64
64
|
install: registry
|
|
65
65
|
side: fe
|
|
@@ -99,14 +99,14 @@ pins:
|
|
|
99
99
|
source: packages/test-world/package.json
|
|
100
100
|
why: 'the shared e2e library of every back end (R47, R48), a devDependency of every back end: the warm stack behind toxiproxy, the network-edge fakes, the Nest boot, the typed useTestWorld handle, useSandbox for contract specs and the outage lock. A fake declared https (defineHttpFake) serves TLS with the run''s ephemeral in-memory fake CA and publishes its PEM as w.fake.<name>.ca for the app''s own client to trust; verification is never turned off. Kafka is real own infra (the one digest-pinned apache/kafka KRaft image, a broker listener and proxy per slot, slot-prefixed topics, consumer groups and client ids) and Postgres is schema-per-context (a schema and a login role per context in a shared database). Each worker has its own data slot (<ns>_w<k>) with its own databases, Keycloak realm, leased Redis DB, bucket/collection/topic prefixes, fakes host, toxiproxy proxies and outage lock; a run provisions min(jest workers, workers cap, default 2) slots, and state file protocol 2 pairs exactly with @starci/jest-preset (TEST_WORLD_PAIR_MISMATCH otherwise). A modules world boots real peer apps beside its modules, world.apps.<name>.during(fn) is the outage of a peer app, w.keycloak.clientSecret(client) answers the run-generated secret of a confidential realm client, world.keycloak.events/sessions read the realm user events and live sessions, world.infra.postgresql.connection(name) takes one database connection down while the others serve, and world.resolve and scope.resolve take any Nest token. Every path a declaration names (`stack`, seeds, the realm, Dockerfiles) resolves from the app root (the directory of hfs.json); the globalSetup registers the path aliases as TypeScript resolves them. Its CLI main is exported at ./cli for starci app stack.'
|
|
101
101
|
'@starci/ai-router':
|
|
102
|
-
version: 0.
|
|
102
|
+
version: 0.5.0
|
|
103
103
|
group: starci
|
|
104
104
|
install: registry
|
|
105
105
|
side: be
|
|
106
106
|
source: packages/ai-router/package.json
|
|
107
107
|
why: 'the AI pool router of a back end: a NestJS module that routes OpenAI-compatible chat, stream and embeddings calls across keys, models and providers, with @starci/ai-router/testing for its specs; @starci/jest-preset compiles it as an ESM-only dependency.'
|
|
108
108
|
'@starci/hfs':
|
|
109
|
-
version: 4.
|
|
109
|
+
version: 4.15.0
|
|
110
110
|
group: starci
|
|
111
111
|
install: registry
|
|
112
112
|
side: both
|
|
@@ -1407,7 +1407,7 @@ rules:
|
|
|
1407
1407
|
witness:
|
|
1408
1408
|
- {"path":"packages/eslint/be/legacy-sql-http-log-proof.spec.mjs","edition":"lite","codes":["BE_SQL_INTERPOLATED"]}
|
|
1409
1409
|
- {"path":"packages/eslint/be/legacy-sql-http-log-proof.spec.mjs","edition":"full","codes":["BE_SQL_INTERPOLATED"]}
|
|
1410
|
-
law: "SQL text carries no runtime substitution; values are numbered parameters. The one exception is R334's
|
|
1410
|
+
law: "SQL text carries no runtime substitution; values are numbered parameters. The one exception is R334's call and LISTEN statements in platform/database/database.client.ts, which splice only the name parts and parameter list its own validator checked."
|
|
1411
1411
|
kinds: [lint, codemod]
|
|
1412
1412
|
gates: [pre-commit, settle, land, ci]
|
|
1413
1413
|
failureCodes: ["BE_SQL_INTERPOLATED"]
|
|
@@ -5828,7 +5828,7 @@ rules:
|
|
|
5828
5828
|
ruling: "Lite entities only map tables the migrations create, so each entity column is checked against the migrated schema by starci app db drift, which CI runs in the build job and the release gate runs as its db-drift row."
|
|
5829
5829
|
- id: R334
|
|
5830
5830
|
code: "BE_PERSISTENCE_NO_RAW_SQL"
|
|
5831
|
-
law: "Lite
|
|
5831
|
+
law: "Lite TypeScript holds no SQL text, outside the test world. A table is read and written through its TypeORM entity on an EntityManager (domain code the injected one; specs, builders, fixtures and the test world the world's `world.db.<connection>`): find, save, update, delete, upsert, a pessimistic `lock` option, `createQueryBuilder(Entity, \"alias\")` with named parameters; never a table-name builder or a Repository. Every table a migration creates has an entity. Anything else is a database function, called through `callDbFunction` of `platform/database/database.client.ts`, which names only a function that `ruleParams.be.dbFunctions` or hfs.json `sides.be.dbFunctions` lists with a reason: a function of a migration, schema-qualified (`public.job_claim`); an extension function, schema-qualified; a pg built-in of the canon's list, bare (`pg_notify`, called in pg_catalog). `database.client.ts` alone composes SQL text (the call statement and LISTEN), from parts its validator checked; `advisoryXactLock` and `notify` are `callDbFunction` calls of built-ins there. The only other `.query(` outside the world is the pass-through of a file that `ruleParams.be.sqlPassThrough` or hfs.json `sides.be.sqlPassThrough` lists with a reason, whose text is not the app's own (the tracked seed, a customer data-source read, an outside session's setup), with a plain string first argument, never a template or a `+`. The test world `src/tests/world` may hold raw SQL, as `sql`-tagged text with numbered `$n` parameters (and `<name>.sql.ts` files), only for what neither an entity nor a listed function expresses: a privilege or row-level-security probe, catalog, cron or trigger introspection, a pgmq queue table, a lock or failure probe; in the world too plain CRUD on an application table goes through its entity, an application function through `callDbFunction`, and seeded rows come from builders (R98). No `sql` template, `*.sql.ts`, `sql`/`ident` import or other `.query(` exists anywhere else."
|
|
5832
5832
|
kinds: [lint]
|
|
5833
5833
|
gates: [pre-commit, settle, land, ci]
|
|
5834
5834
|
failureCodes: ["BE_PERSISTENCE_NO_RAW_SQL"]
|
|
@@ -5913,3 +5913,26 @@ rules:
|
|
|
5913
5913
|
source: owner
|
|
5914
5914
|
quote: "Entities do not repeat the columns every table shares; the owner approved a lint so they never repeat them again (ruling entity-base, 2026-10-31)."
|
|
5915
5915
|
ruling: "A table whose migration has created_at, updated_at (set by the database) and the generated uuid id maps them by extending AbstractEntity or UuidAbstractEntity from @modules/platform/database; an entity that declares them itself is a finding. A table without them extends nothing."
|
|
5916
|
+
- id: R344
|
|
5917
|
+
code: "BE_AI_VIRTUAL_KEY"
|
|
5918
|
+
law: "An app's ai-router gateway has one client key, STARCI_AI_KEY (sk-starci-<app>-<48 hex>, sealed in the ai member, used by the integrations/ai LangChain client and the agent runtime alike), and no admin token: integrations/ai reads exactly that secret name with env.secret, as a literal, and the custody owner integrations/ai-gateway passes the gateway no adminToken."
|
|
5919
|
+
kinds: [lint]
|
|
5920
|
+
gates: [pre-commit, settle, land, ci]
|
|
5921
|
+
failureCodes: ["BE_AI_VIRTUAL_KEY"]
|
|
5922
|
+
enforcers:
|
|
5923
|
+
- {kind: eslint-be, id: ai-virtual-key-name}
|
|
5924
|
+
editions: [lite, full]
|
|
5925
|
+
docs: [contexts/code/be/ai.md]
|
|
5926
|
+
templateNa: "The skeleton scaffolds no model call; an app adds the ai and ai-gateway integrations and the ai member when it calls a model."
|
|
5927
|
+
proves:
|
|
5928
|
+
- {path: packages/eslint-canon-be/src/ai-gateway.spec.ts, editions: [lite, full], codes: [BE_AI_VIRTUAL_KEY]}
|
|
5929
|
+
exemplifiedBy:
|
|
5930
|
+
- {path: packages/eslint-canon-be/src/ai-gateway.spec.ts, editions: [lite, full], codes: [BE_AI_VIRTUAL_KEY]}
|
|
5931
|
+
witness:
|
|
5932
|
+
- {path: packages/eslint-canon-be/src/ai-gateway.spec.ts, editions: [lite, full], codes: [BE_AI_VIRTUAL_KEY]}
|
|
5933
|
+
cases:
|
|
5934
|
+
- id: case-1
|
|
5935
|
+
date: "2026-10-31"
|
|
5936
|
+
source: owner
|
|
5937
|
+
quote: "Xóa ai api key và openclaw ai key chỉnh thành starci ai key là key ảo"
|
|
5938
|
+
ruling: "Per app and environment the ai member holds the upstream provider keys and one random virtual key STARCI_AI_KEY that the gateway mounts and every client uses; the gateway has no admin API (ruling be-ai-one-virtual-key)."
|
|
@@ -460,6 +460,10 @@ ruleParams:
|
|
|
460
460
|
- {name: public.event_bus_bury, reason: "platform/event-bus (add webhook, lite): the move of an exhausted or malformed message to its consumer's dead-letter queue"}
|
|
461
461
|
- {name: public.event_bus_dead_letters, reason: "platform/event-bus (add webhook, lite): the operator read of a consumer's dead-letter queue"}
|
|
462
462
|
- {name: public.event_bus_requeue, reason: "platform/event-bus (add webhook, lite): the operator requeue of one dead letter"}
|
|
463
|
+
# R334 (lite): the only `.query(` outside platform/database's composer and the test world is the pass-through of a file listed here
|
|
464
|
+
# (or in hfs.json sides.be.sqlPassThrough), whose SQL text is not the app's own. Paths are relative to the side folder.
|
|
465
|
+
sqlPassThrough:
|
|
466
|
+
- {file: src/modules/platform/database/seed-runner.service.ts, reason: "the tracked seed file's text, run as it is (db/seed.sql); the app writes no SQL there"}
|
|
463
467
|
|
|
464
468
|
lite:
|
|
465
469
|
schemaAuthority: sql
|
|
@@ -1956,7 +1960,7 @@ slots:
|
|
|
1956
1960
|
tests: unit-beside # <name>.service.spec.ts beside each <name>.service.ts; plus src/tests/integration/<provider>/ (R112)
|
|
1957
1961
|
coverage: required
|
|
1958
1962
|
budget: {indexExports: 80} # a provider's port surface includes clients, config, options, tokens and errors
|
|
1959
|
-
rules: [BE_TIER_DIRECTION, BE_ERROR_HOME, BE_SECRET_DEFAULT, BE_INTEGRATION_SPEC_MISSING, BE_AI_KEY_CUSTODY, BE_AI_GATEWAY_CLIENT]
|
|
1963
|
+
rules: [BE_TIER_DIRECTION, BE_ERROR_HOME, BE_SECRET_DEFAULT, BE_INTEGRATION_SPEC_MISSING, BE_AI_KEY_CUSTODY, BE_AI_GATEWAY_CLIENT, BE_AI_VIRTUAL_KEY]
|
|
1960
1964
|
- id: be.integrations.model
|
|
1961
1965
|
since: 3.1.0
|
|
1962
1966
|
profiles: [be]
|
|
@@ -2027,7 +2031,7 @@ slots:
|
|
|
2027
2031
|
own; use-test-world.ts exports useTestWorld({ modules: [...] }) -> world.db.<connection> (the shared EntityManager) and
|
|
2028
2032
|
world.fake.<provider> (a network-edge fake of an external SaaS). There is no world.apps (no e2e) and no world.infra
|
|
2029
2033
|
(no self-hosted service to cut)
|
|
2030
|
-
allows: [global-setup.ts, global-teardown.ts, use-test-world.ts, "fakes/<provider>/server.ts", fakes
|
|
2034
|
+
allows: [global-setup.ts, global-teardown.ts, use-test-world.ts, "fakes/<provider>/server.ts", fakes/, "<name>.sql.ts"] # jest globalSetup/globalTeardown default-export (Jest API); fakes/<provider>/server.ts is the fake server of a provider, a literal file name BE_SOURCE_FORM reads as its role; plus root files with a role suffix (test-world-files, R47)
|
|
2031
2035
|
tests: none
|
|
2032
2036
|
coverage: none
|
|
2033
2037
|
why: >-
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isPlainObject } from '../../engine/plain-object.mjs';
|
|
2
2
|
import { APP_KIND, connectionShapeProblems, NAME, PACKAGE_NAME, RUNTIME_KIND, SLOT_ID } from './manifest-shape.mjs';
|
|
3
|
-
import { dbFunctionsOk } from './rule-params-shape.mjs';
|
|
3
|
+
import { dbFunctionsOk, sqlPassThroughOk } from './rule-params-shape.mjs';
|
|
4
4
|
import { kindShapeProblems, patternShapeProblems } from './declaration-slots.mjs';
|
|
5
5
|
import { byCodeUnit } from '../lib/list.mjs';
|
|
6
6
|
/** Shape problems of the optional hfs.json `db` block of a lite app: the environment variable naming its database, its image, forced RLS and its application role. */
|
|
@@ -91,10 +91,12 @@ function declarationSideProblems(side, value, names) {
|
|
|
91
91
|
if (!isPlainObject(value))
|
|
92
92
|
return [`${at} must be an object`];
|
|
93
93
|
for (const key of Object.keys(value))
|
|
94
|
-
if (!['apps', 'optionalSlots', 'patterns', 'kinds', 'connections', 'reads', 'extraPackages', 'grammar', 'backing', 'dbFunctions'].includes(key))
|
|
94
|
+
if (!['apps', 'optionalSlots', 'patterns', 'kinds', 'connections', 'reads', 'extraPackages', 'grammar', 'backing', 'dbFunctions', 'sqlPassThrough'].includes(key))
|
|
95
95
|
bad.push(`${at} has unknown key ${key}`);
|
|
96
96
|
if (value.dbFunctions !== undefined && (side !== 'be' || !dbFunctionsOk(value.dbFunctions, { bare: true })))
|
|
97
97
|
bad.push(`${at}.dbFunctions belongs to the be side and lists {name, reason} database functions, each schema-qualified (schema.name, never pg_catalog) or a bare pg built-in of the canon's list, with unique names`);
|
|
98
|
+
if (value.sqlPassThrough !== undefined && (side !== 'be' || !sqlPassThroughOk(value.sqlPassThrough)))
|
|
99
|
+
bad.push(`${at}.sqlPassThrough belongs to the be side and lists {file, reason} files relative to the side folder, forward slashes, unique, each with the reason its SQL text is not the app's own`);
|
|
98
100
|
bad.push(...appShapeProblems(value.apps, at, side, names));
|
|
99
101
|
if (isBadUniqueList(value.optionalSlots, (slot) => SLOT_ID.test(String(slot))))
|
|
100
102
|
bad.push(`${at}.optionalSlots must be a unique list of slot ids`);
|
|
@@ -73,6 +73,11 @@ const dbFunctionNameOk = (name, bare) => typeof name === 'string' && (/^[a-z_][a
|
|
|
73
73
|
* a bare name, which only the canon's list (ruleParams.be.dbFunctions) uses, for the pg built-ins its helpers call.
|
|
74
74
|
*/
|
|
75
75
|
export const dbFunctionsOk = (list, { bare = false } = {}) => list === undefined || (Array.isArray(list) && list.every((entry) => isPlainObject(entry) && Object.keys(entry).sort().join() === 'name,reason' && dbFunctionNameOk(entry.name, bare) && typeof entry.reason === 'string' && entry.reason.trim().length > 0) && new Set(list.map((entry) => entry.name)).size === list.length);
|
|
76
|
+
/**
|
|
77
|
+
* True for an absent list or a list of {file, reason} SQL pass-through files (R334): `file` is a forward-slash path relative to the
|
|
78
|
+
* side folder (no leading slash, no `..`), unique, and the reason names whose text the file passes through.
|
|
79
|
+
*/
|
|
80
|
+
export const sqlPassThroughOk = (list) => list === undefined || (Array.isArray(list) && list.every((entry) => isPlainObject(entry) && Object.keys(entry).sort().join() === 'file,reason' && typeof entry.file === 'string' && /^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*$/.test(entry.file) && !entry.file.split('/').includes('..') && typeof entry.reason === 'string' && entry.reason.trim().length > 0) && new Set(list.map((entry) => entry.file)).size === list.length);
|
|
76
81
|
/** The shape problems of `m.ruleParams`. */
|
|
77
82
|
export function ruleParamsProblems(m) {
|
|
78
83
|
const bad = [];
|
|
@@ -84,8 +89,8 @@ export function ruleParamsProblems(m) {
|
|
|
84
89
|
// Edition lite: a side's optional `lite` map overrides keys of the same side (never `lite` itself) when the app declares edition lite.
|
|
85
90
|
if (!sideOk(rp.common, []) || !fileLinesOk(rp.common.fileLines) || !blockOk(rp.common.duplicateBlock))
|
|
86
91
|
bad.push('ruleParams.common needs fileLines {soft, hardGrowth} and duplicateBlock {lines >= 2, tokens >= 1}; optional functionLines and featureFiles must be positive integers');
|
|
87
|
-
if (!sideOk(rp.be, BE_OWN, ['schemaAuthority', 'lite', 'dbFunctions']) || (rp.be.schemaAuthority !== undefined && !SCHEMA_AUTHORITIES.includes(rp.be.schemaAuthority)) || !dbFunctionsOk(rp.be.dbFunctions, { bare: true }) || !liteOk(rp.be.lite, [...BE_OWN, ...SHARED_KEYS, 'schemaAuthority', 'dbFunctions']))
|
|
88
|
-
bad.push('ruleParams.be needs infraOwners, eventBus, specDoubles, paramNames, suffixes, bannedSuffixes, contractShape {helper}, unitRoles, logicRoles, thinRoles, patternScenarios, kindPatterns, addKinds and backing (shared parameters live in ruleParams.common, a side may override them); optional: schemaAuthority (' + SCHEMA_AUTHORITIES.join(' | ') + '), dbFunctions ([{name, reason}]: a pg built-in bare, every other function schema.name) and lite (overrides of the same keys)');
|
|
92
|
+
if (!sideOk(rp.be, BE_OWN, ['schemaAuthority', 'lite', 'dbFunctions', 'sqlPassThrough']) || (rp.be.schemaAuthority !== undefined && !SCHEMA_AUTHORITIES.includes(rp.be.schemaAuthority)) || !dbFunctionsOk(rp.be.dbFunctions, { bare: true }) || !sqlPassThroughOk(rp.be.sqlPassThrough) || !liteOk(rp.be.lite, [...BE_OWN, ...SHARED_KEYS, 'schemaAuthority', 'dbFunctions', 'sqlPassThrough']))
|
|
93
|
+
bad.push('ruleParams.be needs infraOwners, eventBus, specDoubles, paramNames, suffixes, bannedSuffixes, contractShape {helper}, unitRoles, logicRoles, thinRoles, patternScenarios, kindPatterns, addKinds and backing (shared parameters live in ruleParams.common, a side may override them); optional: schemaAuthority (' + SCHEMA_AUTHORITIES.join(' | ') + '), dbFunctions ([{name, reason}]: a pg built-in bare, every other function schema.name), sqlPassThrough ([{file, reason}]: a file whose SQL text is not written by the app) and lite (overrides of the same keys)');
|
|
89
94
|
else
|
|
90
95
|
bad.push(...unitRolesProblems(rp.be), ...roleListProblems(rp.be));
|
|
91
96
|
bad.push(...beSpecificProblems(rp.be, m));
|
|
@@ -125,6 +125,7 @@ function sideDeclaration(manifest, declaration, name, edition, providers) {
|
|
|
125
125
|
providers,
|
|
126
126
|
reads: Object.freeze([...(s.reads ?? [])]),
|
|
127
127
|
dbFunctions: Object.freeze((s.dbFunctions ?? []).map((entry) => Object.freeze({ ...entry }))),
|
|
128
|
+
sqlPassThrough: Object.freeze((s.sqlPassThrough ?? []).map((entry) => Object.freeze({ ...entry }))),
|
|
128
129
|
...(s.grammar === undefined ? {} : { grammar: s.grammar }),
|
|
129
130
|
...(s.extraPackages === undefined ? {} : { extraPackages: Object.freeze(s.extraPackages.map((entry) => Object.freeze({ ...entry }))) }),
|
|
130
131
|
manifestVersion: manifest.version,
|
|
@@ -251,8 +252,8 @@ function createScopeResolver(manifest, repo) {
|
|
|
251
252
|
trackingOf,
|
|
252
253
|
/** True only for a path a slot owns and requires to be committed. */
|
|
253
254
|
isTracked: (p) => trackingOf(p) === 'tracked',
|
|
254
|
-
// The app's own database functions (hfs.json sides.be.dbFunctions) join the canon's
|
|
255
|
-
ruleParams: () =>
|
|
255
|
+
// The app's own database functions and SQL pass-through files (hfs.json sides.be.dbFunctions, sides.be.sqlPassThrough) join the canon's lists (R334).
|
|
256
|
+
ruleParams: () => withDeclaredLists(ruleParams(manifest, profile, edition), repo),
|
|
256
257
|
allowedImports: (tier) => manifest.tiers[profile]?.[tier]?.mayImport ?? null,
|
|
257
258
|
});
|
|
258
259
|
}
|
|
@@ -274,9 +275,18 @@ export function createSlotResolver(manifest, repo) {
|
|
|
274
275
|
const sides = Object.fromEntries(PROFILES.map((side) => [side, createScopeResolver(manifest, app.sides[side])]));
|
|
275
276
|
return appResolver(app, root, sides);
|
|
276
277
|
}
|
|
277
|
-
/** The rule parameters with the app's declared database functions appended to `dbFunctions` (be only), frozen. */
|
|
278
|
-
const
|
|
279
|
-
|
|
278
|
+
/** The rule parameters with the app's declared database functions and SQL pass-through files appended to `dbFunctions` and `sqlPassThrough` (be only), the result frozen. */
|
|
279
|
+
const withDeclaredLists = (params, repo) => {
|
|
280
|
+
const functions = repo.dbFunctions ?? [];
|
|
281
|
+
const passThrough = repo.sqlPassThrough ?? [];
|
|
282
|
+
if ((params.dbFunctions === undefined && !functions.length) && (params.sqlPassThrough === undefined && !passThrough.length))
|
|
283
|
+
return params;
|
|
284
|
+
return Object.freeze({
|
|
285
|
+
...params,
|
|
286
|
+
...(params.dbFunctions === undefined && !functions.length ? {} : { dbFunctions: [...(params.dbFunctions ?? []), ...functions] }),
|
|
287
|
+
...(params.sqlPassThrough === undefined && !passThrough.length ? {} : { sqlPassThrough: [...(params.sqlPassThrough ?? []), ...passThrough] }),
|
|
288
|
+
});
|
|
289
|
+
};
|
|
280
290
|
/** The rule parameters of one profile (be: infraOwners, suffixes, bannedSuffixes and the rest over the shared ruleParams.common fileLines and duplicateBlock; fe: common alone or with its overrides; runtime: ruleParams.runtime of a runtime manifest), as a frozen deep copy. Under `edition` lite the `lite` overrides of ruleParams.<profile> merge over the base (the `lite` key itself is never returned). */
|
|
281
291
|
export function ruleParams(manifest, profile, edition = 'full') {
|
|
282
292
|
const profiles = manifestKind(manifest) === RUNTIME_KIND ? [RUNTIME_KIND] : PROFILES;
|