shutro 0.0.0-stage → 0.2.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.
Files changed (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/dist/audit/index.d.ts +59 -0
  4. package/dist/audit/index.js +96 -0
  5. package/dist/cli/bin.d.ts +2 -0
  6. package/dist/cli/bin.js +11 -0
  7. package/dist/cli/cli.d.ts +10 -0
  8. package/dist/cli/cli.js +164 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +49 -0
  11. package/dist/cli/errors.d.ts +16 -0
  12. package/dist/cli/errors.js +23 -0
  13. package/dist/cli/generate/generate.d.ts +33 -0
  14. package/dist/cli/generate/generate.js +84 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +249 -0
  17. package/dist/cli/index.d.ts +12 -0
  18. package/dist/cli/index.js +12 -0
  19. package/dist/cli/init.d.ts +2 -0
  20. package/dist/cli/init.js +65 -0
  21. package/dist/cli/inspect.d.ts +10 -0
  22. package/dist/cli/inspect.js +82 -0
  23. package/dist/cli/packages.d.ts +6 -0
  24. package/dist/cli/packages.js +6 -0
  25. package/dist/cli/project.d.ts +18 -0
  26. package/dist/cli/project.js +39 -0
  27. package/dist/cli/resolve.d.ts +2 -0
  28. package/dist/cli/resolve.js +28 -0
  29. package/dist/core/compute/graph.d.ts +52 -0
  30. package/dist/core/compute/graph.js +162 -0
  31. package/dist/core/data/data.d.ts +59 -0
  32. package/dist/core/data/data.js +119 -0
  33. package/dist/core/data/load.d.ts +37 -0
  34. package/dist/core/data/load.js +236 -0
  35. package/dist/core/env/env.d.ts +468 -0
  36. package/dist/core/env/env.js +916 -0
  37. package/dist/core/env/identity.d.ts +43 -0
  38. package/dist/core/env/identity.js +65 -0
  39. package/dist/core/env/inspector.d.ts +55 -0
  40. package/dist/core/env/inspector.js +85 -0
  41. package/dist/core/env/time.d.ts +12 -0
  42. package/dist/core/env/time.js +38 -0
  43. package/dist/core/errors.d.ts +256 -0
  44. package/dist/core/errors.js +360 -0
  45. package/dist/core/events/events.d.ts +44 -0
  46. package/dist/core/events/events.js +58 -0
  47. package/dist/core/events/workers.d.ts +56 -0
  48. package/dist/core/events/workers.js +155 -0
  49. package/dist/core/index.d.ts +51 -0
  50. package/dist/core/index.js +42 -0
  51. package/dist/core/model/company.d.ts +6 -0
  52. package/dist/core/model/company.js +31 -0
  53. package/dist/core/model/faces.d.ts +42 -0
  54. package/dist/core/model/faces.js +1 -0
  55. package/dist/core/model/field.d.ts +479 -0
  56. package/dist/core/model/field.js +461 -0
  57. package/dist/core/model/generated.d.ts +77 -0
  58. package/dist/core/model/generated.js +1 -0
  59. package/dist/core/model/id.d.ts +33 -0
  60. package/dist/core/model/id.js +4 -0
  61. package/dist/core/model/model.d.ts +387 -0
  62. package/dist/core/model/model.js +566 -0
  63. package/dist/core/model/partition.d.ts +31 -0
  64. package/dist/core/model/partition.js +71 -0
  65. package/dist/core/model/related.d.ts +17 -0
  66. package/dist/core/model/related.js +60 -0
  67. package/dist/core/model/typed.d.ts +107 -0
  68. package/dist/core/model/typed.js +46 -0
  69. package/dist/core/money/currency.d.ts +39 -0
  70. package/dist/core/money/currency.js +37 -0
  71. package/dist/core/money/decimal.d.ts +26 -0
  72. package/dist/core/money/decimal.js +51 -0
  73. package/dist/core/money/fx.d.ts +68 -0
  74. package/dist/core/money/fx.js +124 -0
  75. package/dist/core/money/money.d.ts +84 -0
  76. package/dist/core/money/money.js +173 -0
  77. package/dist/core/money/quantity.d.ts +67 -0
  78. package/dist/core/money/quantity.js +108 -0
  79. package/dist/core/money/rounding.d.ts +11 -0
  80. package/dist/core/money/rounding.js +12 -0
  81. package/dist/core/recordset/aggregate.d.ts +22 -0
  82. package/dist/core/recordset/aggregate.js +258 -0
  83. package/dist/core/recordset/audit.d.ts +33 -0
  84. package/dist/core/recordset/audit.js +262 -0
  85. package/dist/core/recordset/compute.d.ts +36 -0
  86. package/dist/core/recordset/compute.js +414 -0
  87. package/dist/core/recordset/constraints.d.ts +9 -0
  88. package/dist/core/recordset/constraints.js +61 -0
  89. package/dist/core/recordset/domain.d.ts +31 -0
  90. package/dist/core/recordset/domain.js +300 -0
  91. package/dist/core/recordset/onchange.d.ts +43 -0
  92. package/dist/core/recordset/onchange.js +240 -0
  93. package/dist/core/recordset/recordset.d.ts +110 -0
  94. package/dist/core/recordset/recordset.js +789 -0
  95. package/dist/core/recordset/relations.d.ts +15 -0
  96. package/dist/core/recordset/relations.js +13 -0
  97. package/dist/core/recordset/rls.d.ts +15 -0
  98. package/dist/core/recordset/rls.js +108 -0
  99. package/dist/core/recordset/security.d.ts +56 -0
  100. package/dist/core/recordset/security.js +269 -0
  101. package/dist/core/recordset/sequences.d.ts +31 -0
  102. package/dist/core/recordset/sequences.js +154 -0
  103. package/dist/core/recordset/source.d.ts +9 -0
  104. package/dist/core/recordset/source.js +19 -0
  105. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  106. package/dist/core/recordset/sqlErrors.js +39 -0
  107. package/dist/core/recordset/transitions.d.ts +10 -0
  108. package/dist/core/recordset/transitions.js +80 -0
  109. package/dist/core/recordset/types.d.ts +415 -0
  110. package/dist/core/recordset/types.js +8 -0
  111. package/dist/core/recordset/values.d.ts +33 -0
  112. package/dist/core/recordset/values.js +177 -0
  113. package/dist/core/recordset/writes.d.ts +42 -0
  114. package/dist/core/recordset/writes.js +786 -0
  115. package/dist/core/registry/ddl.d.ts +31 -0
  116. package/dist/core/registry/ddl.js +174 -0
  117. package/dist/core/registry/extension.d.ts +94 -0
  118. package/dist/core/registry/extension.js +90 -0
  119. package/dist/core/registry/module.d.ts +89 -0
  120. package/dist/core/registry/module.js +98 -0
  121. package/dist/core/registry/registry.d.ts +130 -0
  122. package/dist/core/registry/registry.js +591 -0
  123. package/dist/core/security/runtime.d.ts +102 -0
  124. package/dist/core/security/runtime.js +232 -0
  125. package/dist/driver-pg/driver.d.ts +88 -0
  126. package/dist/driver-pg/driver.js +177 -0
  127. package/dist/driver-pg/errors.d.ts +72 -0
  128. package/dist/driver-pg/errors.js +182 -0
  129. package/dist/driver-pg/index.d.ts +7 -0
  130. package/dist/driver-pg/index.js +7 -0
  131. package/dist/i18n/index.d.ts +25 -0
  132. package/dist/i18n/index.js +51 -0
  133. package/dist/migrate/apply.d.ts +78 -0
  134. package/dist/migrate/apply.js +167 -0
  135. package/dist/migrate/catalog.d.ts +10 -0
  136. package/dist/migrate/catalog.js +122 -0
  137. package/dist/migrate/diff.d.ts +98 -0
  138. package/dist/migrate/diff.js +160 -0
  139. package/dist/migrate/errors.d.ts +21 -0
  140. package/dist/migrate/errors.js +31 -0
  141. package/dist/migrate/index.d.ts +18 -0
  142. package/dist/migrate/index.js +18 -0
  143. package/dist/migrate/render.d.ts +5 -0
  144. package/dist/migrate/render.js +101 -0
  145. package/dist/migrate/schema.d.ts +61 -0
  146. package/dist/migrate/schema.js +233 -0
  147. package/dist/security/index.d.ts +147 -0
  148. package/dist/security/index.js +278 -0
  149. package/dist/sequence/index.d.ts +63 -0
  150. package/dist/sequence/index.js +106 -0
  151. package/dist/sql/ast.d.ts +49 -0
  152. package/dist/sql/ast.js +47 -0
  153. package/dist/sql/builder/builder.d.ts +215 -0
  154. package/dist/sql/builder/builder.js +308 -0
  155. package/dist/sql/builder/expression.d.ts +80 -0
  156. package/dist/sql/builder/expression.js +126 -0
  157. package/dist/sql/compile.d.ts +18 -0
  158. package/dist/sql/compile.js +41 -0
  159. package/dist/sql/errors.d.ts +13 -0
  160. package/dist/sql/errors.js +16 -0
  161. package/dist/sql/index.d.ts +19 -0
  162. package/dist/sql/index.js +19 -0
  163. package/dist/sql/tag.d.ts +47 -0
  164. package/dist/sql/tag.js +123 -0
  165. package/package.json +82 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Isahaq
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,100 @@
1
- # Temporary Holding Version
1
+ # Shutro
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The ORM built for business software.** Shutro is a PostgreSQL-only ORM for Node.js and TypeScript, designed for
4
+ ERP workloads: type-safe, secure by default, modular, multi-company, multi-currency, audit-ready and fast at scale.
5
+ It is the data layer of the Kosh ERP framework.
6
+
7
+ > **Status: alpha (0.x).** The engine is tested end to end against real PostgreSQL (600+ tests, an ERP demo with
8
+ > partner, product, sale and invoice modules), but the API may still change between minor versions. Known gaps are
9
+ > tracked in [`docs/feedback.md`](docs/feedback.md).
10
+
11
+ ```sh
12
+ npm install shutro
13
+ ```
14
+
15
+ Requirements: Node.js ≥ 24, PostgreSQL ≥ 14.
16
+
17
+ ## What it does
18
+
19
+ - **Models and modules**: `defineModel` with typed field builders, modules with dependencies, typed extension of
20
+ other modules' models, explicit method overrides.
21
+ - **Recordsets**: batch-first `search` / `load` / `write` / `unlink`, typed load specs, no N+1 by construction.
22
+ - **Computed fields**: stored and non-stored, dependency graph built at startup, batched recompute before commit.
23
+ - **Constraints and onchange**: Python-free validators at flush points, form drafts with virtual records.
24
+ - **State machines**: transitions, guards and events as generated methods.
25
+ - **Multi-company and multi-currency**: automatic company scoping, cross-company link protection, dated rates,
26
+ `Decimal` money (never floats).
27
+ - **Translations** in JSONB with language fallback; **sequences**, including gapless ones; append-only **audit trail**.
28
+ - **Security**: default-deny ACL, record rules compiled to SQL (following relations, e.g. "lines of my orders"),
29
+ optional PostgreSQL row-level security, field-level security, encrypted fields with keys outside the database,
30
+ verified identities, administrator roles that need no grants, feature permissions, special per-user grants,
31
+ back-date permissions for transactions, and audited elevated methods.
32
+ - **Reports**: `aggregate()` (grouped totals with rules applied, per-currency `Money`), `records.sum()`.
33
+ - **Odoo-ORM parity, typed and checked at startup**: module data with external ids (`record`, `ref`, `env.ref`),
34
+ related fields, delegation (`delegates`), hierarchies (`childOf` / `parentOf`), company-dependent fields, search
35
+ on computed fields, and roles / access / rules editable at runtime.
36
+ - **Beyond Odoo**: compare-and-set writes against lost updates, transactional events (outbox) and PostgreSQL jobs
37
+ with exactly-once database effects, and time travel (`history: true`, `env.asOf(instant)`).
38
+ - **Typed definitions**: `shutro generate` writes per-module bindings, so computes, checks, onchange handlers and
39
+ methods are typed with no casts.
40
+ - **Migrations**: schema diff against the live catalog, versioned migration files, destructive-change guard.
41
+ - **Tooling**: `shutro init | migrate | generate | inspect`, dev-mode query inspector with N+1 warnings, COPY bulk
42
+ loads, partitioned tables, CI benchmarks.
43
+
44
+ ## Quick start
45
+
46
+ ```sh
47
+ npx shutro init
48
+ ```
49
+
50
+ ```ts
51
+ import { buildRegistry, createShutro, defineModel, defineModule, f } from 'shutro';
52
+ import { createDriver } from 'shutro/driver-pg';
53
+
54
+ const Partner = defineModel('res.partner', {
55
+ access: { 'base.user': ['read', 'write', 'create'] },
56
+ fields: { name: f.char({ required: true }), credit: f.decimal({ scale: 2, default: '0' }) },
57
+ });
58
+
59
+ const registry = buildRegistry({ modules: [defineModule({ name: 'base', models: [Partner] })] });
60
+ const shutro = createShutro({ driver: createDriver({ url: process.env.DATABASE_URL ?? '' }), registry });
61
+
62
+ await shutro.run({ user: 1, company: 1, groups: ['base.user'] }, async (env) => {
63
+ const partners = await env.model('res.partner').search({ where: { name: { ilike: 'acme%' } } });
64
+ return partners.length;
65
+ });
66
+ ```
67
+
68
+ Entry points: `shutro` (core), `shutro/sql`, `shutro/driver-pg`, `shutro/migrate`, `shutro/cli`, `shutro/security`,
69
+ `shutro/audit`, `shutro/sequence`, `shutro/i18n`.
70
+
71
+ ## Documentation
72
+
73
+ - Guides: [`docs/guides/`](docs/guides/)
74
+ - Design documents (RFCs): [`docs/rfcs/`](docs/rfcs/README.md)
75
+ - A complete example: [`examples/erp-demo`](examples/erp-demo/README.md)
76
+ - How it compares with Odoo's ORM, including where Odoo is ahead: [`docs/odoo-comparison.md`](docs/odoo-comparison.md)
77
+
78
+ ## Development
79
+
80
+ Requirements: Node.js ≥ 24, pnpm 11, and Docker for integration tests.
81
+
82
+ ```sh
83
+ pnpm install
84
+ pnpm typecheck # TypeScript 7, every package
85
+ pnpm lint # Biome
86
+ pnpm test # Vitest against real PostgreSQL (Testcontainers)
87
+ pnpm build # dist/ for each package
88
+ node scripts/pack-npm.ts # assemble the single `shutro` npm package in dist-npm/shutro
89
+ ```
90
+
91
+ The repository is a pnpm workspace (`packages/*`); the npm package `shutro` bundles all of them. Contribution rules
92
+ (design first, test first, Conventional Commits) are in [`CLAUDE.md`](CLAUDE.md).
93
+
94
+ ## Author
95
+
96
+ **Isahaq**, hmisahaq01@gmail.com, mobile +8801852376598
97
+
98
+ ## License
99
+
100
+ [MIT](LICENSE)
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/audit`: the append-only trail of tracked changes (RFC 0013). The table (with a trigger that refuses
4
+ * `UPDATE` / `DELETE`), the insert statement core runs at flush points, and the queries that read a trail.
5
+ */
6
+ import { type CompiledSql } from '../sql/index.js';
7
+ /** What happened. `su` rows record a superuser scope (RFC 0003 §7.6). */
8
+ export type AuditAction = 'create' | 'write' | 'unlink' | 'su' | 'elevate' | 'security';
9
+ /** One row of the trail. */
10
+ export interface AuditEntry {
11
+ readonly id: number;
12
+ /** The transaction timestamp (`env.now()`): every row of a transaction shares it. */
13
+ readonly at: Date;
14
+ /** Groups the rows of one transaction attempt. */
15
+ readonly tx: string;
16
+ readonly uid: number;
17
+ readonly companyId: number;
18
+ readonly su: boolean;
19
+ readonly reason: string | null;
20
+ readonly action: AuditAction;
21
+ readonly model: string | null;
22
+ readonly recordId: number | null;
23
+ /** The changed field for `write` rows; `null` for record-level rows. */
24
+ readonly field: string | null;
25
+ /** JSON: the previous value (`write`), or the snapshot of tracked fields (`unlink`). */
26
+ readonly old: unknown;
27
+ /** JSON: the new value (`write`), or the snapshot of tracked fields (`create`). */
28
+ readonly new: unknown;
29
+ }
30
+ /** A row to append (the database assigns `id`). */
31
+ export type AuditRowInput = Omit<AuditEntry, 'id'>;
32
+ /** The trail table. */
33
+ export declare const AUDIT_TABLE = "shutro_audit";
34
+ /** DDL of the trail: the table, its indexes, and a trigger that makes it append-only. Idempotent. */
35
+ export declare function auditTableStatements(): readonly CompiledSql[];
36
+ /** One `INSERT ... SELECT FROM unnest(...)` for any number of rows. */
37
+ export declare function insertAuditStatement(rows: readonly AuditRowInput[]): CompiledSql;
38
+ /** Filters of {@link trailQuery}. */
39
+ export interface TrailFilter {
40
+ readonly model?: string | undefined;
41
+ readonly recordIds?: readonly number[] | undefined;
42
+ readonly field?: string | undefined;
43
+ readonly uid?: number | undefined;
44
+ readonly action?: AuditAction | undefined;
45
+ /** Rows at or after this time. */
46
+ readonly since?: Date | undefined;
47
+ /** Rows older than this row id: the cursor of the next page (the `id` of the last row of the previous one). */
48
+ readonly before?: number | undefined;
49
+ /** Newest first; default 100. */
50
+ readonly limit?: number | undefined;
51
+ }
52
+ /** The query that reads a trail, newest first. */
53
+ export declare function trailQuery(filter?: TrailFilter): CompiledSql;
54
+ /** Anything that runs a compiled statement (a driver, a connection, a scope). */
55
+ export interface Runner {
56
+ query<R extends Record<string, unknown>>(query: CompiledSql): Promise<readonly R[]>;
57
+ }
58
+ /** Reads a trail, newest first. */
59
+ export declare function readTrail(runner: Runner, filter?: TrailFilter): Promise<AuditEntry[]>;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/audit`: the append-only trail of tracked changes (RFC 0013). The table (with a trigger that refuses
4
+ * `UPDATE` / `DELETE`), the insert statement core runs at flush points, and the queries that read a trail.
5
+ */
6
+ import { compile, sql } from '../sql/index.js';
7
+ /** The trail table. */
8
+ export const AUDIT_TABLE = 'shutro_audit';
9
+ /** DDL of the trail: the table, its indexes, and a trigger that makes it append-only. Idempotent. */
10
+ export function auditTableStatements() {
11
+ const t = `"${AUDIT_TABLE}"`;
12
+ return [
13
+ `CREATE TABLE IF NOT EXISTS ${t} ("id" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, "at" timestamp with time zone NOT NULL, "tx" text NOT NULL, "uid" bigint NOT NULL, "company_id" bigint NOT NULL, "su" boolean NOT NULL DEFAULT false, "reason" text, "action" text NOT NULL, "model" text, "record_id" bigint, "field" text, "old" jsonb, "new" jsonb)`,
14
+ `CREATE INDEX IF NOT EXISTS "${AUDIT_TABLE}_record_idx" ON ${t} ("model", "record_id", "id")`,
15
+ `CREATE INDEX IF NOT EXISTS "${AUDIT_TABLE}_at_idx" ON ${t} ("at")`,
16
+ `CREATE OR REPLACE FUNCTION "${AUDIT_TABLE}_immutable"() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'shutro_audit is append-only: % is not allowed', TG_OP USING ERRCODE = 'insufficient_privilege'; END $$`,
17
+ `DROP TRIGGER IF EXISTS "${AUDIT_TABLE}_immutable" ON ${t}`,
18
+ `CREATE TRIGGER "${AUDIT_TABLE}_immutable" BEFORE UPDATE OR DELETE ON ${t} FOR EACH ROW EXECUTE FUNCTION "${AUDIT_TABLE}_immutable"()`,
19
+ ].map((text) => Object.freeze({ text, params: Object.freeze([]) }));
20
+ }
21
+ function json(value) {
22
+ return value === undefined || value === null ? null : JSON.stringify(value);
23
+ }
24
+ /** One `INSERT ... SELECT FROM unnest(...)` for any number of rows. */
25
+ export function insertAuditStatement(rows) {
26
+ const columns = [
27
+ 'at',
28
+ 'tx',
29
+ 'uid',
30
+ 'company_id',
31
+ 'su',
32
+ 'reason',
33
+ 'action',
34
+ 'model',
35
+ 'record_id',
36
+ 'field',
37
+ 'old',
38
+ 'new',
39
+ ];
40
+ const arrays = [
41
+ sql.array(rows.map((r) => r.at.toISOString()), 'timestamptz'),
42
+ sql.array(rows.map((r) => r.tx), 'text'),
43
+ sql.array(rows.map((r) => r.uid), 'bigint'),
44
+ sql.array(rows.map((r) => r.companyId), 'bigint'),
45
+ sql.array(rows.map((r) => r.su), 'boolean'),
46
+ sql.array(rows.map((r) => r.reason), 'text'),
47
+ sql.array(rows.map((r) => r.action), 'text'),
48
+ sql.array(rows.map((r) => r.model), 'text'),
49
+ sql.array(rows.map((r) => r.recordId), 'bigint'),
50
+ sql.array(rows.map((r) => r.field), 'text'),
51
+ sql.array(rows.map((r) => json(r.old)), 'text'),
52
+ sql.array(rows.map((r) => json(r.new)), 'text'),
53
+ ];
54
+ const names = columns.map((c) => sql.id(c));
55
+ const refs = columns.map((c) => c === 'old' || c === 'new' ? sql `${sql.id('v', c)}::jsonb` : sql.id('v', c));
56
+ return compile(sql `INSERT INTO ${sql.id(AUDIT_TABLE)} (${sql.join(names)}) SELECT ${sql.join(refs)} FROM unnest(${sql.join(arrays)}) AS ${sql.id('v')}(${sql.join(names)})`);
57
+ }
58
+ /** The query that reads a trail, newest first. */
59
+ export function trailQuery(filter = {}) {
60
+ const conditions = [];
61
+ if (filter.model !== undefined)
62
+ conditions.push(sql `${sql.id('model')} = ${filter.model}`);
63
+ if (filter.recordIds !== undefined)
64
+ conditions.push(sql `${sql.id('record_id')} = ANY(${sql.array([...filter.recordIds], 'bigint')})`);
65
+ if (filter.field !== undefined)
66
+ conditions.push(sql `${sql.id('field')} = ${filter.field}`);
67
+ if (filter.uid !== undefined)
68
+ conditions.push(sql `${sql.id('uid')} = ${filter.uid}`);
69
+ if (filter.action !== undefined)
70
+ conditions.push(sql `${sql.id('action')} = ${filter.action}`);
71
+ if (filter.since !== undefined)
72
+ conditions.push(sql `${sql.id('at')} >= ${filter.since}`);
73
+ if (filter.before !== undefined)
74
+ conditions.push(sql `${sql.id('id')} < ${filter.before}`);
75
+ const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
76
+ return compile(sql `SELECT ${sql.id('id')}, ${sql.id('at')}, ${sql.id('tx')}, ${sql.id('uid')}, ${sql.id('company_id')}, ${sql.id('su')}, ${sql.id('reason')}, ${sql.id('action')}, ${sql.id('model')}, ${sql.id('record_id')}, ${sql.id('field')}, ${sql.id('old')}, ${sql.id('new')} FROM ${sql.id(AUDIT_TABLE)}${where} ORDER BY ${sql.id('id')} DESC LIMIT ${filter.limit ?? 100}`);
77
+ }
78
+ /** Reads a trail, newest first. */
79
+ export async function readTrail(runner, filter = {}) {
80
+ const rows = await runner.query(trailQuery(filter));
81
+ return rows.map((r) => ({
82
+ id: Number(r['id']),
83
+ at: r['at'] instanceof Date ? r['at'] : new Date(String(r['at'])),
84
+ tx: String(r['tx']),
85
+ uid: Number(r['uid']),
86
+ companyId: Number(r['company_id']),
87
+ su: Boolean(r['su']),
88
+ reason: r['reason'] === null ? null : String(r['reason']),
89
+ action: String(r['action']),
90
+ model: r['model'] === null ? null : String(r['model']),
91
+ recordId: r['record_id'] === null ? null : Number(r['record_id']),
92
+ field: r['field'] === null ? null : String(r['field']),
93
+ old: r['old'],
94
+ new: r['new'],
95
+ }));
96
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from './cli.js';
3
+ process.exitCode = await runCli(process.argv.slice(2), {
4
+ cwd: process.cwd(),
5
+ write: (text) => {
6
+ process.stdout.write(text);
7
+ },
8
+ error: (text) => {
9
+ process.stderr.write(text);
10
+ },
11
+ });
@@ -0,0 +1,10 @@
1
+ /** Where output goes, and the environment variables to read. */
2
+ export interface CliIo {
3
+ readonly cwd: string;
4
+ write(text: string): void;
5
+ error(text: string): void;
6
+ /** Defaults to `process.env`. */
7
+ readonly env?: Readonly<Record<string, string | undefined>>;
8
+ }
9
+ /** Runs the CLI and returns the exit code. */
10
+ export declare function runCli(argv: readonly string[], io: CliIo): Promise<number>;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Argument parsing and dispatch. `runCli` returns the exit code; nothing here calls `process.exit`, so tests can
3
+ * drive it directly.
4
+ */
5
+ import { resolve } from 'node:path';
6
+ import { parseArgs } from 'node:util';
7
+ import { createShutro, historyStatements, loadData } from '../core/index.js';
8
+ import { applyMigrations, migrationStatus, planMigration, writeMigrationFile, } from '../migrate/index.js';
9
+ import { loadConfig } from './config.js';
10
+ import { CliError } from './errors.js';
11
+ import { generate } from './generate/generate.js';
12
+ import { initProject } from './init.js';
13
+ import { inspectModel, inspectRegistry } from './inspect.js';
14
+ import { databaseUrl, loadProject, withDriver } from './project.js';
15
+ const USAGE = `Usage: shutro <command> [options]
16
+
17
+ Commands:
18
+ init [dir] Create shutro.config.ts, a base module and a migrations directory
19
+ generate [--check] Write per-module and application type views (.shutro/)
20
+ migrate status Applied and pending migration files
21
+ migrate plan What the database is missing (DDL, destructive statements marked)
22
+ migrate write <name> Write the plan as the next migration file
23
+ migrate apply [--allow-destructive] Apply pending files, data-migration hooks, then module data
24
+ inspect [model] Modules and models, or one model: fields, origins, methods, computes,
25
+ constraints, access and rules
26
+
27
+ Options:
28
+ --config <file> Config file (default: shutro.config.ts in the current directory)
29
+ --check generate: fail (exit 1) when generated files are stale; write nothing
30
+ --allow-destructive migrate apply: run statements that drop data
31
+ --help Show this help
32
+
33
+ Environment:
34
+ SHUTRO_DATABASE_URL PostgreSQL URL for migrate (overrides database in the config)
35
+ `;
36
+ /** Runs the CLI and returns the exit code. */
37
+ export async function runCli(argv, io) {
38
+ const env = io.env ?? process.env;
39
+ try {
40
+ const { values, positionals } = parseArgs({
41
+ args: [...argv],
42
+ allowPositionals: true,
43
+ options: {
44
+ check: { type: 'boolean', default: false },
45
+ config: { type: 'string' },
46
+ help: { type: 'boolean', default: false },
47
+ 'allow-destructive': { type: 'boolean', default: false },
48
+ },
49
+ });
50
+ const [command, sub, arg] = positionals;
51
+ if (values.help || command === undefined) {
52
+ io.write(USAGE);
53
+ return command === undefined && !values.help ? 2 : 0;
54
+ }
55
+ const configFile = values.config ?? `${io.cwd}/shutro.config.ts`;
56
+ switch (command) {
57
+ case 'init': {
58
+ for (const file of initProject(resolve(io.cwd, sub ?? '.')))
59
+ io.write(`created ${file}\n`);
60
+ io.write('Next: list your modules in shutro.config.ts, then run "shutro migrate plan".\n');
61
+ return 0;
62
+ }
63
+ case 'generate': {
64
+ const { config, dir } = await loadConfig(configFile);
65
+ const result = await generate({ config, cwd: dir, check: values.check });
66
+ for (const file of result.files)
67
+ io.write(`${file.status.padEnd(9)} ${file.path}\n`);
68
+ if (values.check && result.changed.length > 0) {
69
+ io.error(`${result.changed.length} generated file(s) are stale. Run "shutro generate".\n`);
70
+ return 1;
71
+ }
72
+ return 0;
73
+ }
74
+ case 'migrate':
75
+ return await migrate(sub, arg, configFile, values['allow-destructive'], io, env);
76
+ case 'inspect': {
77
+ const { registry } = await loadProject(configFile);
78
+ io.write(`${sub === undefined ? inspectRegistry(registry) : inspectModel(registry, sub)}\n`);
79
+ return 0;
80
+ }
81
+ default:
82
+ throw new CliError(`Unknown command '${command}'.`, 'Run "shutro --help".');
83
+ }
84
+ }
85
+ catch (error) {
86
+ if (error instanceof CliError) {
87
+ io.error(`error: ${error.message}\n`);
88
+ return 2;
89
+ }
90
+ const message = error instanceof Error ? error.message : String(error);
91
+ io.error(`error: ${message}\n`);
92
+ return 1;
93
+ }
94
+ }
95
+ async function migrate(sub, name, configFile, allowDestructive, io, env) {
96
+ const { config, registry } = await loadProject(configFile);
97
+ const dir = config.migrations ?? resolve('migrations');
98
+ const url = databaseUrl(config, env);
99
+ return withDriver(url, async (driver) => {
100
+ switch (sub) {
101
+ case 'status': {
102
+ const status = await migrationStatus({ driver, dir });
103
+ for (const a of status.applied)
104
+ io.write(`applied ${a.version}_${a.name} ${a.appliedAt.toISOString()}\n`);
105
+ for (const p of status.pending)
106
+ io.write(`pending ${p.version}_${p.name}\n`);
107
+ if (status.applied.length + status.pending.length === 0)
108
+ io.write('No migrations yet.\n');
109
+ return 0;
110
+ }
111
+ case 'plan': {
112
+ const plan = await planMigration({ driver, registry });
113
+ if (plan.statements.length === 0) {
114
+ io.write('The database matches the models.\n');
115
+ return 0;
116
+ }
117
+ for (const s of plan.statements)
118
+ io.write(`${s.destructive ? '-- destructive\n' : ''}${s.sql};\n`);
119
+ io.write(`\n${plan.statements.length} statement(s), ${plan.destructive.length} destructive. Run "shutro migrate write <name>".\n`);
120
+ return 0;
121
+ }
122
+ case 'write': {
123
+ if (name === undefined)
124
+ throw new CliError('migrate write needs a name.', 'E.g. shutro migrate write add_sale_margin.');
125
+ const plan = await planMigration({ driver, registry });
126
+ if (plan.statements.length === 0) {
127
+ io.write('Nothing to write: the database matches the models.\n');
128
+ return 0;
129
+ }
130
+ const file = await writeMigrationFile({ dir, name, plan });
131
+ io.write(`created ${file.path}${plan.destructive.length > 0 ? ` (${plan.destructive.length} destructive statement(s): review before applying)` : ''}\n`);
132
+ return 0;
133
+ }
134
+ case 'apply': {
135
+ const result = await applyMigrations({ driver, dir, registry, allowDestructive });
136
+ for (const a of result.applied)
137
+ io.write(`applied ${a.version}_${a.name}\n`);
138
+ for (const m of result.modules)
139
+ io.write(`module ${m.module} ${m.from ?? '(new)'} → ${m.to}\n`);
140
+ for (const h of result.hooks)
141
+ io.write(`hook ${h.module} ${h.version}\n`);
142
+ // History triggers (RFC 0018 §7.4): idempotent, after the schema they version.
143
+ for (const statement of historyStatements(registry))
144
+ await driver.query(statement);
145
+ // Module data (RFC 0017), after the schema: idempotent, so it runs at every apply.
146
+ const data = await loadData(createShutro({ driver, registry }));
147
+ let dataChanges = 0;
148
+ for (const d of data) {
149
+ const changes = d.created.length + d.updated.length + d.deleted.length;
150
+ dataChanges += changes;
151
+ if (changes > 0)
152
+ io.write(`data ${d.module}: ${d.created.length} created, ${d.updated.length} updated, ${d.deleted.length} deleted, ${d.unchanged} unchanged\n`);
153
+ for (const r of d.retained)
154
+ io.write(`kept ${r.id} (still referenced: ${r.reason})\n`);
155
+ }
156
+ if (result.applied.length + result.modules.length + dataChanges === 0)
157
+ io.write('Up to date.\n');
158
+ return 0;
159
+ }
160
+ default:
161
+ throw new CliError(`Unknown migrate command '${sub ?? ''}'.`, 'Use status, plan, write <name> or apply.');
162
+ }
163
+ });
164
+ }
@@ -0,0 +1,18 @@
1
+ /** The exported config. Paths are relative to the config file. */
2
+ export interface ShutroConfig {
3
+ /** One module file per module (`modules/sale/module.ts`); every module in the dependency graph must be listed. */
4
+ readonly modules: readonly string[];
5
+ /** Directory of the application view (`.shutro/` is created inside it). Omit for a module-only package. */
6
+ readonly app?: string;
7
+ /** Directory of the versioned SQL migrations (default `./migrations`). */
8
+ readonly migrations?: string;
9
+ /** PostgreSQL URL for `migrate` / `inspect --db`; `SHUTRO_DATABASE_URL` wins over it. */
10
+ readonly database?: string;
11
+ }
12
+ /** Identity helper that types the config file. */
13
+ export declare function defineConfig(config: ShutroConfig): ShutroConfig;
14
+ /** Loads a config file (default export or `config`), resolving its paths against the file's directory. */
15
+ export declare function loadConfig(file: string): Promise<{
16
+ config: ShutroConfig;
17
+ dir: string;
18
+ }>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `shutro.config.ts`: the module files of an application and where its application view goes.
3
+ */
4
+ import { existsSync } from 'node:fs';
5
+ import { isAbsolute, resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { ConfigError } from './errors.js';
8
+ import { allowJsSpecifiersForTs } from './resolve.js';
9
+ /** Identity helper that types the config file. */
10
+ export function defineConfig(config) {
11
+ return config;
12
+ }
13
+ function isConfig(value) {
14
+ if (typeof value !== 'object' || value === null)
15
+ return false;
16
+ const c = value;
17
+ return (Array.isArray(c.modules) &&
18
+ c.modules.every((m) => typeof m === 'string') &&
19
+ (c.app === undefined || typeof c.app === 'string') &&
20
+ (c.migrations === undefined ||
21
+ typeof c.migrations === 'string') &&
22
+ (c.database === undefined ||
23
+ typeof c.database === 'string'));
24
+ }
25
+ /** Loads a config file (default export or `config`), resolving its paths against the file's directory. */
26
+ export async function loadConfig(file) {
27
+ const path = resolve(file);
28
+ if (!existsSync(path)) {
29
+ throw new ConfigError(`Config file ${path} does not exist.`, 'Create shutro.config.ts with `export default defineConfig({ modules: [...] })`, or pass --config.');
30
+ }
31
+ allowJsSpecifiersForTs();
32
+ const loaded = (await import(pathToFileURL(path).href));
33
+ const config = loaded.default ?? loaded.config;
34
+ if (!isConfig(config)) {
35
+ throw new ConfigError(`${path} does not export a config.`, 'Export `defineConfig({ modules: ["./modules/base/module.ts", ...], app: "./app" })` as default.');
36
+ }
37
+ const dir = resolve(path, '..');
38
+ return {
39
+ dir,
40
+ config: {
41
+ modules: config.modules.map((m) => (isAbsolute(m) ? m : resolve(dir, m))),
42
+ ...(config.app === undefined
43
+ ? {}
44
+ : { app: isAbsolute(config.app) ? config.app : resolve(dir, config.app) }),
45
+ migrations: resolve(dir, config.migrations ?? './migrations'),
46
+ ...(config.database === undefined ? {} : { database: config.database }),
47
+ },
48
+ };
49
+ }
@@ -0,0 +1,16 @@
1
+ /** Machine-readable reason for a {@link CliError}. */
2
+ export type CliErrorCode = 'CLI_USAGE' | 'CLI_CONFIG' | 'CLI_MODULE_SOURCE';
3
+ /** A CLI error: the message says what went wrong and ends with `hint`. */
4
+ export declare class CliError extends Error {
5
+ readonly code: CliErrorCode;
6
+ readonly hint: string;
7
+ constructor(problem: string, hint: string, code?: CliErrorCode);
8
+ }
9
+ /** `shutro.config.ts` is missing, malformed, or names a file that doesn't export a module. */
10
+ export declare class ConfigError extends CliError {
11
+ constructor(problem: string, hint: string);
12
+ }
13
+ /** A module in the dependency graph has no source file the generator can import types from. */
14
+ export declare class ModuleSourceError extends CliError {
15
+ constructor(module: string, via: string);
16
+ }
@@ -0,0 +1,23 @@
1
+ /** A CLI error: the message says what went wrong and ends with `hint`. */
2
+ export class CliError extends Error {
3
+ code;
4
+ hint;
5
+ constructor(problem, hint, code = 'CLI_USAGE') {
6
+ super(`${problem} ${hint}`);
7
+ this.name = new.target.name;
8
+ this.code = code;
9
+ this.hint = hint;
10
+ }
11
+ }
12
+ /** `shutro.config.ts` is missing, malformed, or names a file that doesn't export a module. */
13
+ export class ConfigError extends CliError {
14
+ constructor(problem, hint) {
15
+ super(problem, hint, 'CLI_CONFIG');
16
+ }
17
+ }
18
+ /** A module in the dependency graph has no source file the generator can import types from. */
19
+ export class ModuleSourceError extends CliError {
20
+ constructor(module, via) {
21
+ super(`Module '${module}' (a dependency of '${via}') is not listed in the config.`, "Add its file to `modules` in shutro.config.ts: generated views import each module's types from its source.", 'CLI_MODULE_SOURCE');
22
+ }
23
+ }
@@ -0,0 +1,33 @@
1
+ import { type Registry } from '../../core/index.js';
2
+ import type { ShutroConfig } from '../config.js';
3
+ import { type ModuleSource } from './render.js';
4
+ /** Options of {@link generate}. */
5
+ export interface GenerateOptions {
6
+ readonly config: ShutroConfig;
7
+ /** Directory the config paths were resolved against. */
8
+ readonly cwd: string;
9
+ /** Report stale files without writing. */
10
+ readonly check?: boolean | undefined;
11
+ /** Mirror the generated tree under this directory instead of next to the sources (tests, previews). */
12
+ readonly outRoot?: string | undefined;
13
+ }
14
+ /** One generated file and what happened to it. */
15
+ export interface GeneratedFile {
16
+ readonly path: string;
17
+ readonly content: string;
18
+ readonly status: 'unchanged' | 'created' | 'updated';
19
+ }
20
+ /** Result of {@link generate}. */
21
+ export interface GenerateResult {
22
+ readonly files: readonly GeneratedFile[];
23
+ /** Files that were (or, with `check`, would be) created or updated. */
24
+ readonly changed: readonly GeneratedFile[];
25
+ /** Module names in load order. */
26
+ readonly modules: readonly string[];
27
+ }
28
+ /** Imports the module files of a config (one `defineModule` export each). */
29
+ export declare function loadSources(files: readonly string[]): Promise<Map<string, ModuleSource>>;
30
+ /** The module that pulled in `missing` (for error messages). */
31
+ export declare function dependant(registry: Registry, missing: string): string;
32
+ /** Generates the per-module views and the application view described by `config`. */
33
+ export declare function generate(options: GenerateOptions): Promise<GenerateResult>;