shutro 0.2.1 → 0.3.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 (42) hide show
  1. package/README.md +12 -9
  2. package/dist/cli/config.d.ts +7 -2
  3. package/dist/cli/config.js +29 -11
  4. package/dist/cli/generate/generate.d.ts +2 -2
  5. package/dist/cli/generate/generate.js +21 -10
  6. package/dist/cli/generate/render.d.ts +2 -0
  7. package/dist/cli/generate/render.js +1 -1
  8. package/dist/cli/index.d.ts +1 -1
  9. package/dist/cli/index.js +1 -1
  10. package/dist/cli/project.d.ts +4 -1
  11. package/dist/cli/project.js +6 -7
  12. package/dist/cli/resolve.d.ts +9 -0
  13. package/dist/cli/resolve.js +72 -3
  14. package/dist/core/data/data.d.ts +0 -2
  15. package/dist/core/data/data.js +1 -1
  16. package/dist/core/data/load.d.ts +1 -3
  17. package/dist/core/data/load.js +1 -1
  18. package/dist/core/env/env.d.ts +15 -2
  19. package/dist/core/env/env.js +32 -12
  20. package/dist/core/model/model.d.ts +6 -0
  21. package/dist/core/model/model.js +1 -0
  22. package/dist/core/recordset/audit.d.ts +0 -2
  23. package/dist/core/recordset/audit.js +1 -1
  24. package/dist/core/recordset/changes.d.ts +29 -0
  25. package/dist/core/recordset/changes.js +48 -0
  26. package/dist/core/recordset/compute.d.ts +0 -2
  27. package/dist/core/recordset/compute.js +10 -2
  28. package/dist/core/recordset/onchange.js +3 -1
  29. package/dist/core/recordset/recordset.d.ts +1 -3
  30. package/dist/core/recordset/recordset.js +4 -2
  31. package/dist/core/recordset/security.d.ts +0 -4
  32. package/dist/core/recordset/security.js +0 -21
  33. package/dist/core/recordset/sequences.d.ts +0 -13
  34. package/dist/core/recordset/sequences.js +2 -2
  35. package/dist/core/recordset/values.d.ts +0 -2
  36. package/dist/core/recordset/values.js +1 -1
  37. package/dist/core/recordset/writes.js +11 -1
  38. package/dist/core/registry/extension.d.ts +3 -0
  39. package/dist/core/registry/extension.js +1 -0
  40. package/dist/core/registry/registry.js +4 -0
  41. package/dist/driver-pg/driver.js +7 -1
  42. package/package.json +1 -1
package/README.md CHANGED
@@ -4,9 +4,11 @@
4
4
  ERP workloads: type-safe, secure by default, modular, multi-company, multi-currency, audit-ready and fast at scale.
5
5
  It is the data layer of the Kosh ERP framework.
6
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).
7
+ Shutro is **only the ORM**. Business apps, installing and uninstalling apps, and the web client belong to the
8
+ Kosh framework.
9
+
10
+ > **Status: alpha (0.x).** The engine is tested end to end against real PostgreSQL (600+ tests), but the API may
11
+ > still change between minor versions. Known gaps are tracked in [`docs/feedback.md`](docs/feedback.md).
10
12
 
11
13
  ```sh
12
14
  npm install shutro
@@ -38,15 +40,17 @@ Requirements: Node.js ≥ 24, PostgreSQL ≥ 14.
38
40
  - **Typed definitions**: `shutro generate` writes per-module bindings, so computes, checks, onchange handlers and
39
41
  methods are typed with no casts.
40
42
  - **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
+ - **Tooling**: `shutro init | migrate | generate | inspect`, dev-mode query inspector with N+1
44
+ warnings, COPY bulk loads, partitioned tables, CI benchmarks.
43
45
 
44
46
  ## Quick start
45
47
 
46
48
  ```sh
47
- npx shutro init
49
+ npx shutro init my-erp # shutro.config.ts, a base module and a migrations directory
48
50
  ```
49
51
 
52
+ Then define models and modules:
53
+
50
54
  ```ts
51
55
  import { buildRegistry, createShutro, defineModel, defineModule, f } from 'shutro';
52
56
  import { createDriver } from 'shutro/driver-pg';
@@ -72,7 +76,6 @@ Entry points: `shutro` (core), `shutro/sql`, `shutro/driver-pg`, `shutro/migrate
72
76
 
73
77
  - Guides: [`docs/guides/`](docs/guides/)
74
78
  - Design documents (RFCs): [`docs/rfcs/`](docs/rfcs/README.md)
75
- - A complete example: [`examples/erp-demo`](examples/erp-demo/README.md)
76
79
  - How it compares with Odoo's ORM, including where Odoo is ahead: [`docs/odoo-comparison.md`](docs/odoo-comparison.md)
77
80
 
78
81
  ## Development
@@ -88,8 +91,8 @@ pnpm build # dist/ for each package
88
91
  node scripts/pack-npm.ts # assemble the single `shutro` npm package in dist-npm/shutro
89
92
  ```
90
93
 
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).
94
+ The repository is a pnpm workspace (`packages/*`); the npm package `shutro` bundles all of them. How to contribute is in
95
+ [`CONTRIBUTING.md`](CONTRIBUTING.md); security reports go to [`SECURITY.md`](SECURITY.md).
93
96
 
94
97
  ## Author
95
98
 
@@ -1,13 +1,18 @@
1
1
  /** The exported config. Paths are relative to the config file. */
2
2
  export interface ShutroConfig {
3
- /** One module file per module (`modules/sale/module.ts`); every module in the dependency graph must be listed. */
3
+ /**
4
+ * Module files (`./modules/sale/module.ts`, one module each) and module packages (`'@acme/erp-modules'`, any number
5
+ * of modules each). Every module in the dependency graph must be listed.
6
+ */
4
7
  readonly modules: readonly string[];
5
8
  /** Directory of the application view (`.shutro/` is created inside it). Omit for a module-only package. */
6
9
  readonly app?: string;
7
10
  /** Directory of the versioned SQL migrations (default `./migrations`). */
8
11
  readonly migrations?: string;
9
- /** PostgreSQL URL for `migrate` / `inspect --db`; `SHUTRO_DATABASE_URL` wins over it. */
12
+ /** PostgreSQL URL for `migrate`; `SHUTRO_DATABASE_URL` wins over it. */
10
13
  readonly database?: string;
14
+ /** Filled by {@link loadConfig}: resolved entry file → the package specifier it came from. */
15
+ readonly packages?: Readonly<Record<string, string>>;
11
16
  }
12
17
  /** Identity helper that types the config file. */
13
18
  export declare function defineConfig(config: ShutroConfig): ShutroConfig;
@@ -5,45 +5,63 @@ import { existsSync } from 'node:fs';
5
5
  import { isAbsolute, resolve } from 'node:path';
6
6
  import { pathToFileURL } from 'node:url';
7
7
  import { ConfigError } from './errors.js';
8
- import { allowJsSpecifiersForTs } from './resolve.js';
8
+ import { allowJsSpecifiersForTs, isPackageSpecifier, resolvePackageEntry } from './resolve.js';
9
9
  /** Identity helper that types the config file. */
10
10
  export function defineConfig(config) {
11
11
  return config;
12
12
  }
13
+ const isStringList = (v) => Array.isArray(v) && v.every((m) => typeof m === 'string');
13
14
  function isConfig(value) {
14
15
  if (typeof value !== 'object' || value === null)
15
16
  return false;
16
17
  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'));
18
+ const optionalString = (key) => c[key] === undefined || typeof c[key] === 'string';
19
+ return (isStringList(c['modules']) &&
20
+ optionalString('app') &&
21
+ optionalString('migrations') &&
22
+ optionalString('database'));
24
23
  }
25
24
  /** Loads a config file (default export or `config`), resolving its paths against the file's directory. */
26
25
  export async function loadConfig(file) {
27
26
  const path = resolve(file);
28
27
  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.');
28
+ throw new ConfigError(`Config file ${path} does not exist.`, 'Run "shutro init" to create a project, or create shutro.config.ts with `export default defineConfig({ modules: [...] })`, or pass --config.');
30
29
  }
31
30
  allowJsSpecifiersForTs();
32
- const loaded = (await import(pathToFileURL(path).href));
31
+ let loaded;
32
+ try {
33
+ loaded = (await import(pathToFileURL(path).href));
34
+ }
35
+ catch (error) {
36
+ if (error.code === 'ERR_MODULE_NOT_FOUND')
37
+ throw new ConfigError(`${path} imports a package that is not installed (${error instanceof Error ? error.message : String(error)}).`, 'Install the project dependencies first: npm install (or pnpm install).');
38
+ throw error;
39
+ }
33
40
  const config = loaded.default ?? loaded.config;
34
41
  if (!isConfig(config)) {
35
42
  throw new ConfigError(`${path} does not export a config.`, 'Export `defineConfig({ modules: ["./modules/base/module.ts", ...], app: "./app" })` as default.');
36
43
  }
37
44
  const dir = resolve(path, '..');
45
+ const packages = {};
46
+ const modules = config.modules.map((m) => {
47
+ if (isAbsolute(m))
48
+ return m;
49
+ if (!isPackageSpecifier(m))
50
+ return resolve(dir, m);
51
+ const entry = resolvePackageEntry(m, dir);
52
+ packages[entry] = m;
53
+ return entry;
54
+ });
38
55
  return {
39
56
  dir,
40
57
  config: {
41
- modules: config.modules.map((m) => (isAbsolute(m) ? m : resolve(dir, m))),
58
+ modules,
42
59
  ...(config.app === undefined
43
60
  ? {}
44
61
  : { app: isAbsolute(config.app) ? config.app : resolve(dir, config.app) }),
45
62
  migrations: resolve(dir, config.migrations ?? './migrations'),
46
63
  ...(config.database === undefined ? {} : { database: config.database }),
64
+ ...(Object.keys(packages).length === 0 ? {} : { packages }),
47
65
  },
48
66
  };
49
67
  }
@@ -25,8 +25,8 @@ export interface GenerateResult {
25
25
  /** Module names in load order. */
26
26
  readonly modules: readonly string[];
27
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>>;
28
+ /** Imports the module files (one `defineModule` export each) and module packages (any number) of a config. */
29
+ export declare function loadSources(files: readonly string[], packages?: Readonly<Record<string, string>>): Promise<Map<string, ModuleSource>>;
30
30
  /** The module that pulled in `missing` (for error messages). */
31
31
  export declare function dependant(registry: Registry, missing: string): string;
32
32
  /** Generates the per-module views and the application view described by `config`. */
@@ -9,8 +9,8 @@ import { buildRegistry, isModule } from '../../core/index.js';
9
9
  import { ConfigError, ModuleSourceError } from '../errors.js';
10
10
  import { allowJsSpecifiersForTs } from '../resolve.js';
11
11
  import { outDirOf, renderAppIndex, renderBindings, renderSchema, } from './render.js';
12
- /** Imports the module files of a config (one `defineModule` export each). */
13
- export async function loadSources(files) {
12
+ /** Imports the module files (one `defineModule` export each) and module packages (any number) of a config. */
13
+ export async function loadSources(files, packages = {}) {
14
14
  const sources = new Map();
15
15
  for (const file of files) {
16
16
  if (!existsSync(file)) {
@@ -19,15 +19,24 @@ export async function loadSources(files) {
19
19
  allowJsSpecifiersForTs();
20
20
  const ns = (await import(pathToFileURL(file).href));
21
21
  const found = Object.entries(ns).filter(([, value]) => isModule(value));
22
- if (found.length !== 1) {
23
- throw new ConfigError(`${file} exports ${found.length} modules; expected exactly one.`, 'Export one `defineModule(...)` per file (models can live in other files).');
22
+ const specifier = packages[file];
23
+ if (specifier === undefined ? found.length !== 1 : found.length === 0) {
24
+ throw new ConfigError(`${file} exports ${found.length} modules; expected ${specifier === undefined ? 'exactly one' : 'at least one'}.`, specifier === undefined
25
+ ? 'Export one `defineModule(...)` per file (models can live in other files).'
26
+ : `Check that '${specifier}' is a module package (it exports defineModule results).`);
24
27
  }
25
- const [exportName, module] = found[0];
26
- const existing = sources.get(module.name);
27
- if (existing !== undefined) {
28
- throw new ConfigError(`Module '${module.name}' is exported by both ${existing.file} and ${file}.`, 'List each module file once.');
28
+ for (const [exportName, module] of found) {
29
+ const existing = sources.get(module.name);
30
+ if (existing !== undefined) {
31
+ throw new ConfigError(`Module '${module.name}' is exported by both ${existing.specifier ?? existing.file} and ${specifier ?? file}.`, 'List each module file or package once.');
32
+ }
33
+ sources.set(module.name, {
34
+ module,
35
+ file,
36
+ exportName,
37
+ ...(specifier === undefined ? {} : { specifier }),
38
+ });
29
39
  }
30
- sources.set(module.name, { module, file, exportName });
31
40
  }
32
41
  return sources;
33
42
  }
@@ -39,7 +48,7 @@ export function dependant(registry, missing) {
39
48
  /** Generates the per-module views and the application view described by `config`. */
40
49
  export async function generate(options) {
41
50
  const { config, cwd } = options;
42
- const sources = await loadSources(config.modules);
51
+ const sources = await loadSources(config.modules, config.packages);
43
52
  const all = buildRegistry({ modules: [...sources.values()].map((s) => s.module) });
44
53
  for (const module of all.modules) {
45
54
  if (!sources.has(module.name))
@@ -48,6 +57,8 @@ export async function generate(options) {
48
57
  const rendered = [];
49
58
  for (const module of all.modules) {
50
59
  const source = sources.get(module.name);
60
+ if (source.specifier !== undefined)
61
+ continue; // module packages ship their own views
51
62
  const view = buildRegistry({ modules: [source.module] });
52
63
  const outDir = outDirOf(source.file);
53
64
  const title = `Schema view of module \`${module.name}\` (RFC 0002 §7.7): the models it owns or depends on, with the extensions it can see.`;
@@ -4,6 +4,8 @@ export interface ModuleSource {
4
4
  readonly module: ModuleBase;
5
5
  readonly file: string;
6
6
  readonly exportName: string;
7
+ /** The package the module comes from (`'@acme/erp-modules'`): views import it by name, not by path. */
8
+ readonly specifier?: string;
7
9
  }
8
10
  /** Short, stable hash of everything the view depends on (RFC 0002 §7.7 "definitions hash"). */
9
11
  export declare function definitionsHash(registry: Registry): string;
@@ -151,7 +151,7 @@ function methodsInterface(registered, sources, outDir) {
151
151
  const source = sources.get(name);
152
152
  if (source === undefined)
153
153
  throw new Error(`No source for module '${name}'.`);
154
- const spec = importSpecifier(outDir, source.file);
154
+ const spec = source.specifier ?? importSpecifier(outDir, source.file);
155
155
  return `F.Methods<typeof import(${quote(spec)}).${source.exportName}, ${quote(registered.model.name)}>`;
156
156
  });
157
157
  const name = `${interfaceName(registered.model.name)}Methods`;
@@ -5,7 +5,7 @@
5
5
  export { type CliIo, runCli } from './cli.js';
6
6
  export { defineConfig, loadConfig, type ShutroConfig } from './config.js';
7
7
  export { CliError, type CliErrorCode, ConfigError, ModuleSourceError } from './errors.js';
8
- export { type GeneratedFile, type GenerateOptions, type GenerateResult, generate, } from './generate/generate.js';
8
+ export { type GeneratedFile, type GenerateOptions, type GenerateResult, generate, loadSources, } from './generate/generate.js';
9
9
  export { definitionsHash, fieldType, importSpecifier, interfaceName, type ModuleSource, renderAppIndex, renderBindings, renderSchema, } from './generate/render.js';
10
10
  export { initProject } from './init.js';
11
11
  export { inspectModel, inspectRegistry } from './inspect.js';
package/dist/cli/index.js CHANGED
@@ -5,7 +5,7 @@
5
5
  export { runCli } from './cli.js';
6
6
  export { defineConfig, loadConfig } from './config.js';
7
7
  export { CliError, ConfigError, ModuleSourceError } from './errors.js';
8
- export { generate, } from './generate/generate.js';
8
+ export { generate, loadSources, } from './generate/generate.js';
9
9
  export { definitionsHash, fieldType, importSpecifier, interfaceName, renderAppIndex, renderBindings, renderSchema, } from './generate/render.js';
10
10
  export { initProject } from './init.js';
11
11
  export { inspectModel, inspectRegistry } from './inspect.js';
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * The project a command works on: the config, its modules loaded into a registry, and (when needed) a driver.
3
3
  */
4
- import { type Registry } from '../core/index.js';
4
+ import { type ModuleBase, type Registry } from '../core/index.js';
5
5
  import { type Driver } from '../driver-pg/index.js';
6
6
  import { type ShutroConfig } from './config.js';
7
7
  /** A loaded project. */
8
8
  export interface Project {
9
9
  readonly config: ShutroConfig;
10
10
  readonly dir: string;
11
+ /** Every listed module, with its dependencies. */
11
12
  readonly registry: Registry;
13
+ /** The listed modules. */
14
+ readonly modules: readonly ModuleBase[];
12
15
  }
13
16
  /** Loads the config and builds the registry of its modules. */
14
17
  export declare function loadProject(configFile: string): Promise<Project>;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The project a command works on: the config, its modules loaded into a registry, and (when needed) a driver.
3
3
  */
4
- import { buildRegistry } from '../core/index.js';
4
+ import { buildRegistry, toDecimal } from '../core/index.js';
5
5
  import { createDriver } from '../driver-pg/index.js';
6
6
  import { loadConfig } from './config.js';
7
7
  import { CliError, ModuleSourceError } from './errors.js';
@@ -9,15 +9,14 @@ import { dependant, loadSources } from './generate/generate.js';
9
9
  /** Loads the config and builds the registry of its modules. */
10
10
  export async function loadProject(configFile) {
11
11
  const { config, dir } = await loadConfig(configFile);
12
- const sources = await loadSources(config.modules);
13
- const registry = buildRegistry({
14
- modules: [...sources.values()].map((s) => s.module),
15
- });
12
+ const sources = await loadSources(config.modules, config.packages);
13
+ const modules = [...sources.values()].map((s) => s.module);
14
+ const registry = buildRegistry({ modules });
16
15
  for (const module of registry.modules) {
17
16
  if (!sources.has(module.name))
18
17
  throw new ModuleSourceError(module.name, dependant(registry, module.name));
19
18
  }
20
- return { config, dir, registry };
19
+ return { config, dir, registry, modules };
21
20
  }
22
21
  /** The database URL: `SHUTRO_DATABASE_URL`, else the config's `database`. */
23
22
  export function databaseUrl(config, env) {
@@ -29,7 +28,7 @@ export function databaseUrl(config, env) {
29
28
  }
30
29
  /** Runs `fn` with a driver on the project's database and closes it afterwards. */
31
30
  export async function withDriver(url, fn) {
32
- const driver = createDriver({ url, max: 2 });
31
+ const driver = createDriver({ url, max: 3, parseNumeric: toDecimal });
33
32
  try {
34
33
  return await fn(driver);
35
34
  }
@@ -1,2 +1,11 @@
1
1
  /** Registers the `.js` → `.ts` fallback once per process. */
2
2
  export declare function allowJsSpecifiersForTs(): void;
3
+ /** True for `@scope/name[/sub]` and `name[/sub]`: not a relative or absolute path. */
4
+ export declare function isPackageSpecifier(spec: string): boolean;
5
+ /**
6
+ * The entry file of a module package (`'@acme/erp-modules'`, `'@acme/erp/sale'`), looked up in the `node_modules`
7
+ * above `fromDir`, then in those above the CLI itself (a globally installed CLI).
8
+ *
9
+ * @throws {ConfigError} when the package or its entry cannot be found.
10
+ */
11
+ export declare function resolvePackageEntry(specifier: string, fromDir: string): string;
@@ -1,9 +1,15 @@
1
1
  /**
2
- * Loading TypeScript module sources (feedback #16). Node runs `.ts` files by stripping types, but the `nodenext`
3
- * convention writes imports between them as `./sale.js`. This resolve hook retries a missing relative `.js`
4
- * specifier imported from a `.ts` file as `.ts`, so both spellings work without a loader.
2
+ * Loading TypeScript module sources (feedback #16), and module packages named in the config.
3
+ *
4
+ * Node runs `.ts` files by stripping types, but the `nodenext` convention writes imports between them as `./sale.js`.
5
+ * The resolve hook retries a missing relative `.js` specifier imported from a `.ts` file as `.ts`, so both spellings
6
+ * work without a loader.
5
7
  */
8
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
6
9
  import { registerHooks } from 'node:module';
10
+ import { dirname, join, resolve } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { ConfigError } from './errors.js';
7
13
  let registered = false;
8
14
  /** Registers the `.js` → `.ts` fallback once per process. */
9
15
  export function allowJsSpecifiersForTs() {
@@ -26,3 +32,66 @@ export function allowJsSpecifiersForTs() {
26
32
  },
27
33
  });
28
34
  }
35
+ /** True for `@scope/name[/sub]` and `name[/sub]`: not a relative or absolute path. */
36
+ export function isPackageSpecifier(spec) {
37
+ return !spec.startsWith('.') && !spec.startsWith('/') && !/^[A-Za-z]:[\\/]/.test(spec);
38
+ }
39
+ /** When the CLI itself runs from TypeScript sources (the workspace), workspace packages resolve to sources too. */
40
+ const FROM_SOURCE = import.meta.url.endsWith('.ts');
41
+ function pick(entry) {
42
+ if (typeof entry === 'string')
43
+ return entry;
44
+ if (typeof entry !== 'object' || entry === null)
45
+ return undefined;
46
+ const conditions = entry;
47
+ for (const condition of [...(FROM_SOURCE ? ['@shutro/source'] : []), 'import', 'default']) {
48
+ const found = pick(conditions[condition]);
49
+ if (found !== undefined)
50
+ return found;
51
+ }
52
+ return undefined;
53
+ }
54
+ function entryIn(packageJson, subpath) {
55
+ const pkg = JSON.parse(readFileSync(packageJson, 'utf8'));
56
+ const root = dirname(realpathSync(packageJson));
57
+ const exportsField = pkg.exports;
58
+ const isMap = typeof exportsField === 'object' &&
59
+ exportsField !== null &&
60
+ Object.keys(exportsField).some((k) => k.startsWith('.'));
61
+ const target = exportsField === undefined
62
+ ? subpath === '.'
63
+ ? (pkg.main ?? 'index.js')
64
+ : subpath
65
+ : isMap
66
+ ? pick(exportsField[subpath])
67
+ : subpath === '.'
68
+ ? pick(exportsField)
69
+ : undefined;
70
+ return target === undefined ? undefined : resolve(root, target);
71
+ }
72
+ /**
73
+ * The entry file of a module package (`'@acme/erp-modules'`, `'@acme/erp/sale'`), looked up in the `node_modules`
74
+ * above `fromDir`, then in those above the CLI itself (a globally installed CLI).
75
+ *
76
+ * @throws {ConfigError} when the package or its entry cannot be found.
77
+ */
78
+ export function resolvePackageEntry(specifier, fromDir) {
79
+ const parts = specifier.split('/');
80
+ const scoped = specifier.startsWith('@');
81
+ const name = parts.slice(0, scoped ? 2 : 1).join('/');
82
+ const subpath = ['.', ...parts.slice(scoped ? 2 : 1)].join('/');
83
+ const starts = [fromDir, dirname(fileURLToPath(import.meta.url))];
84
+ for (const start of starts) {
85
+ for (let dir = start;; dir = dirname(dir)) {
86
+ const packageJson = join(dir, 'node_modules', name, 'package.json');
87
+ if (existsSync(packageJson)) {
88
+ const entry = entryIn(packageJson, subpath);
89
+ if (entry !== undefined && existsSync(entry))
90
+ return entry;
91
+ }
92
+ if (dirname(dir) === dir)
93
+ break;
94
+ }
95
+ }
96
+ throw new ConfigError(`The module package '${specifier}' cannot be found from ${fromDir}.`, `Install it (npm install ${name}), or list module files instead.`);
97
+ }
@@ -38,8 +38,6 @@ export declare function override(model: string, id: string, values: Readonly<Rec
38
38
  export declare function ref<M extends string>(model: M, id: string): Id<M>;
39
39
  /** The full external id of a record of `module`. */
40
40
  export declare function fullId(module: string, record: DataRecord): string;
41
- /** Every reference inside a value (nested commands and arrays included). */
42
- export declare function refsIn(value: unknown, out?: DataRef[]): DataRef[];
43
41
  interface DataModule {
44
42
  readonly name: string;
45
43
  readonly depends: readonly DataModule[];
@@ -49,7 +49,7 @@ export function fullId(module, record) {
49
49
  return record.kind === 'override' ? record.name : `${module}.${record.name}`;
50
50
  }
51
51
  /** Every reference inside a value (nested commands and arrays included). */
52
- export function refsIn(value, out = []) {
52
+ function refsIn(value, out = []) {
53
53
  if (isRef(value))
54
54
  out.push(value);
55
55
  else if (Array.isArray(value))
@@ -1,4 +1,4 @@
1
- import { type Env, type ScopeInternals, type Shutro } from '../env/env.js';
1
+ import { type Env, type Shutro } from '../env/env.js';
2
2
  import type { Id } from '../model/id.js';
3
3
  /** The external-id table (RFC 0017 §4). */
4
4
  export declare const EXTERNAL_ID_TABLE = "shutro_external_id";
@@ -7,8 +7,6 @@ export declare function externalIdTableStatements(): readonly {
7
7
  readonly text: string;
8
8
  readonly params: readonly [];
9
9
  }[];
10
- /** The record id of external id `id` (cached per transaction). @throws {UnknownExternalIdError} */
11
- export declare function resolveExternalId(internals: ScopeInternals, id: string, model?: string): Promise<number>;
12
10
  /** `env.refId(model, id)`. */
13
11
  export declare function refId<M extends string>(env: Env, model: M, id: string): Promise<Id<M>>;
14
12
  /** What {@link loadData} did for one module. */
@@ -29,7 +29,7 @@ function split(id) {
29
29
  return [id.slice(0, dot), id.slice(dot + 1)];
30
30
  }
31
31
  /** The record id of external id `id` (cached per transaction). @throws {UnknownExternalIdError} */
32
- export async function resolveExternalId(internals, id, model) {
32
+ async function resolveExternalId(internals, id, model) {
33
33
  let cache = lookups.get(internals.cache);
34
34
  if (cache === undefined) {
35
35
  cache = new Map();
@@ -6,6 +6,7 @@ import { type EnqueueOptions } from '../events/events.js';
6
6
  import { type DeliveredEvent, type RunningJob, type Worker } from '../events/workers.js';
7
7
  import type { Id } from '../model/id.js';
8
8
  import { type Fx } from '../money/fx.js';
9
+ import type { ChangeRow } from '../recordset/changes.js';
9
10
  import { type RecordCache } from '../recordset/recordset.js';
10
11
  import type { ListLoaded, ModelName, ModelRef, RecordSet } from '../recordset/types.js';
11
12
  import type { Registry } from '../registry/registry.js';
@@ -85,6 +86,8 @@ interface RootScope {
85
86
  readonly compute: ComputeState;
86
87
  /** Pending audit rows of this attempt (RFC 0013 §7.2). */
87
88
  readonly audit: AuditRowInput[];
89
+ /** Pending change events of this attempt (RFC 0018 §7.5). */
90
+ readonly changes: ChangeRow[];
88
91
  /** Groups the audit rows of this attempt. */
89
92
  readonly tx: string;
90
93
  /** Next virtual id for drafts (negative, RFC 0009 §7.4). */
@@ -106,7 +109,8 @@ export interface ComputeState {
106
109
  interface Runtime {
107
110
  readonly als: AsyncLocalStorage<Scope>;
108
111
  readonly onHookError: (error: unknown, phase: 'afterCommit' | 'onRollback') => void;
109
- readonly registry: Registry | undefined;
112
+ /** The current registry; each scope captures the one it started with (see `useRegistry`). */
113
+ registry: Registry | undefined;
110
114
  /** Dev-mode query inspector, if any. */
111
115
  readonly inspector: Inspector | undefined;
112
116
  /** The pool, for autonomous transactions (standard sequences, RFC 0012 §7.2). */
@@ -152,6 +156,8 @@ export interface ScopeInternals {
152
156
  readonly keys: KeyRing | undefined;
153
157
  /** Pending audit rows (RFC 0013 §7.2). */
154
158
  readonly auditRows: AuditRowInput[];
159
+ /** Pending change events (RFC 0018 §7.5). */
160
+ readonly changeRows: ChangeRow[];
155
161
  readonly tx: string;
156
162
  flush(model?: string): Promise<void>;
157
163
  /** Records that `(model, key)` changed for `ids` and invalidates cached dependents (RFC 0008 §7.2). */
@@ -444,8 +450,15 @@ export interface Shutro<S = unknown> {
444
450
  bootstrap<T>(options: BootstrapOptions, fn: (env: Env<S>) => Promise<T>): Promise<T>;
445
451
  /** The environment of the innermost active scope. @throws {NoEnvironmentError} outside `run()`. */
446
452
  currentEnv(): Env<S>;
447
- /** The registry this instance was created with. */
453
+ /** The current registry (the one new scopes start with). */
448
454
  readonly registry: Registry | undefined;
455
+ /**
456
+ * Replaces the registry, e.g. after modules were added to a running application. Running transactions finish on
457
+ * the registry they started with; the next `run()` uses the new one.
458
+ *
459
+ * @throws {InvalidSequenceError} when the new registry needs a larger pool.
460
+ */
461
+ useRegistry(registry: Registry): void;
449
462
  /** The driver this instance was created with. */
450
463
  readonly driver: Driver;
451
464
  /** Reloads runtime security now (changes are also reloaded automatically after they commit). */
@@ -208,7 +208,7 @@ export class Env {
208
208
  async emit(topic, payload) {
209
209
  const scope = internalsOf(this);
210
210
  const query = (q) => scope.query(q);
211
- await ensureEventTables(this.#runtime.driver, query);
211
+ await this.#ensureEventTables();
212
212
  return emitEvent(query, this.#actor(), topic, payload);
213
213
  }
214
214
  /**
@@ -218,9 +218,17 @@ export class Env {
218
218
  async enqueue(name, payload, options) {
219
219
  const scope = internalsOf(this);
220
220
  const query = (q) => scope.query(q);
221
- await ensureEventTables(this.#runtime.driver, query);
221
+ await this.#ensureEventTables();
222
222
  return enqueueJob(query, this.#actor(), name, payload, options);
223
223
  }
224
+ /**
225
+ * Makes the event and job tables on first use **outside** this transaction, through the driver: made inside it,
226
+ * they would vanish if it rolled back while being remembered as made, and every later emit would fail.
227
+ */
228
+ async #ensureEventTables() {
229
+ const driver = this.#runtime.driver;
230
+ await ensureEventTables(driver, (q) => driver.query(q));
231
+ }
224
232
  #actor() {
225
233
  return { uid: this.uid, companyId: this.companyId, groups: [...this.groups] };
226
234
  }
@@ -277,6 +285,7 @@ export class Env {
277
285
  const root = parent.root;
278
286
  let child;
279
287
  const auditMark = root.audit.length;
288
+ const changeMark = root.changes.length;
280
289
  try {
281
290
  const result = await parent.conn.savepoint(async (conn) => {
282
291
  const scope = {
@@ -313,6 +322,7 @@ export class Env {
313
322
  if (child.journal !== undefined)
314
323
  undo(child.journal, root);
315
324
  root.audit.length = auditMark; // rows of a rolled-back savepoint never reach the trail
325
+ root.changes.length = changeMark; // nor its change events
316
326
  await runHooks(child.onRollback, this.#runtime, 'onRollback');
317
327
  }
318
328
  throw error;
@@ -402,6 +412,7 @@ export class Env {
402
412
  toCompute: new Map(),
403
413
  toCheck: new Map(),
404
414
  audit: [],
415
+ changes: [],
405
416
  compute: {
406
417
  recomputing: false,
407
418
  computing: new Set(),
@@ -596,6 +607,7 @@ function scopeInternals(env, scope, registry, query, driver, overlay) {
596
607
  driver,
597
608
  keys: env.keys,
598
609
  auditRows: root.audit,
610
+ changeRows: root.changes,
599
611
  tx: root.tx,
600
612
  flush: (model) => flushAll(internalsOf(env), model),
601
613
  trigger(model, key, ids) {
@@ -705,10 +717,9 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
705
717
  * Standard sequences allocate in a short autonomous transaction on a second connection (RFC 0012 §7.3): with a pool
706
718
  * of one, that waits forever for the connection the business transaction holds (feedback #21).
707
719
  */
708
- function assertPoolFits(options) {
709
- if (options.driver.max === undefined || options.driver.max > 1)
720
+ function assertPoolFits(driver, registry) {
721
+ if (driver.max === undefined || driver.max > 1)
710
722
  return;
711
- const registry = options.registry;
712
723
  const standard = [...(registry?.sequences.values() ?? [])]
713
724
  .filter((d) => !d.gapless)
714
725
  .map((d) => d.code);
@@ -727,7 +738,7 @@ function workerHost(shutro) {
727
738
  export function createShutro(options) {
728
739
  const attempts = options.retry?.attempts ?? 5;
729
740
  const backoff = options.retry?.backoffMs ?? defaultBackoff;
730
- assertPoolFits(options);
741
+ assertPoolFits(options.driver, options.registry);
731
742
  const runtime = {
732
743
  als: new AsyncLocalStorage(),
733
744
  onHookError: options.onHookError ?? defaultHookError,
@@ -804,7 +815,13 @@ export function createShutro(options) {
804
815
  };
805
816
  return execute(identity, { user: 1, company: 1 }, (env) => env.asSuperuser({ reason }, fn));
806
817
  },
807
- registry: options.registry,
818
+ get registry() {
819
+ return runtime.registry;
820
+ },
821
+ useRegistry(registry) {
822
+ assertPoolFits(options.driver, registry);
823
+ runtime.registry = registry;
824
+ },
808
825
  driver: options.driver,
809
826
  reloadSecurity: reload,
810
827
  subscribe(name, topic, handler, subscribeOptions) {
@@ -822,11 +839,13 @@ export function createShutro(options) {
822
839
  };
823
840
  async function execute(identity, runOptions, fn) {
824
841
  {
825
- const groups = options.registry === undefined
842
+ // The scope keeps the registry it started with, even if useRegistry() swaps it meanwhile.
843
+ const registry = runtime.registry;
844
+ const scoped = { ...runtime, registry };
845
+ const groups = registry === undefined
826
846
  ? new Set(identity.groups)
827
- : closureWith(options.registry, runtime.security.current, identity.groups);
828
- const administrator = options.registry !== undefined &&
829
- isAdministratorWith(options.registry, runtime.security.current, groups);
847
+ : closureWith(registry, runtime.security.current, identity.groups);
848
+ const administrator = registry !== undefined && isAdministratorWith(registry, runtime.security.current, groups);
830
849
  const maxAttempts = runOptions.retry === false ? 1 : attempts;
831
850
  for (let attempt = 1;; attempt++) {
832
851
  let scope;
@@ -856,6 +875,7 @@ export function createShutro(options) {
856
875
  toCompute: new Map(),
857
876
  toCheck: new Map(),
858
877
  audit: [],
878
+ changes: [],
859
879
  tx: randomUUID(),
860
880
  virtual: -1,
861
881
  compute: {
@@ -882,7 +902,7 @@ export function createShutro(options) {
882
902
  su: false,
883
903
  flags: DEFAULT_FLAGS,
884
904
  readOnly: runOptions.readOnly ?? false,
885
- }, s, runtime);
905
+ }, s, scoped);
886
906
  scope = s;
887
907
  return runtime.als.run(s, async () => {
888
908
  const value = await fn(s.env);
@@ -178,6 +178,11 @@ export interface ModelDefinition<Fs extends FieldsRecord, Ms extends MethodsReco
178
178
  * `env.asOf(instant, fn)` reads the model as it was then.
179
179
  */
180
180
  readonly history?: boolean;
181
+ /**
182
+ * Emit a `record.changed` outbox event per model and action at each flush (RFC 0018 §7.5): the ids and the stored
183
+ * keys written, in the writing transaction.
184
+ */
185
+ readonly changeEvents?: boolean;
181
186
  readonly indexes?: readonly IndexSpec<ModelKeys<Fs, A, C>>[];
182
187
  readonly sqlConstraints?: Readonly<Record<string, SqlUniqueConstraint<ModelKeys<Fs, A, C>> | SqlCheckConstraint>>;
183
188
  readonly constraints?: Readonly<Record<string, ConstraintSpec>>;
@@ -271,6 +276,7 @@ export interface Model<N extends string, Fs extends FieldsRecord, Ms extends Met
271
276
  readonly hierarchy: HierarchySpec<keyof Fs & string> | undefined;
272
277
  readonly delegates: readonly (keyof Fs & string)[];
273
278
  readonly history: boolean;
279
+ readonly changeEvents: boolean;
274
280
  readonly indexes: readonly ResolvedIndex<keyof Fs & string>[];
275
281
  readonly sqlConstraints: readonly ResolvedSqlConstraint<keyof Fs & string>[];
276
282
  readonly constraints: readonly ResolvedConstraint[];
@@ -435,6 +435,7 @@ export function defineModel(name, definition) {
435
435
  hierarchy: hierarchy === undefined ? undefined : Object.freeze({ ...hierarchy }),
436
436
  delegates: Object.freeze(delegates),
437
437
  history: definition.history === true,
438
+ changeEvents: definition.changeEvents === true,
438
439
  indexes: Object.freeze(indexes),
439
440
  sqlConstraints: Object.freeze(sqlConstraints),
440
441
  constraints: Object.freeze(constraints),
@@ -9,8 +9,6 @@ import type { AnyModel } from '../model/model.js';
9
9
  export declare function isTracked(model: AnyModel, key: string): boolean;
10
10
  /** Tracked field keys of a model (with the sibling currency / unit fields needed to render money). */
11
11
  export declare function trackedKeys(model: AnyModel): Set<string>;
12
- /** The JSON form of a cached value, as `read()` would return it (RFC 0013 §7.3). */
13
- export declare function auditValue(internals: ScopeInternals, model: AnyModel, key: string, raw: unknown, siblings: (key: string) => unknown): unknown;
14
12
  /** Records a change of a tracked field (no-op for untracked fields or with `flags.tracking` off). */
15
13
  export declare function trackChange(internals: ScopeInternals, model: AnyModel, id: number, key: string, prev: unknown, next: unknown, siblings: (key: string) => unknown): void;
16
14
  /** Records a creation or deletion with a snapshot of the tracked fields. */
@@ -43,7 +43,7 @@ export function trackedKeys(model) {
43
43
  return keys;
44
44
  }
45
45
  /** The JSON form of a cached value, as `read()` would return it (RFC 0013 §7.3). */
46
- export function auditValue(internals, model, key, raw, siblings) {
46
+ function auditValue(internals, model, key, raw, siblings) {
47
47
  if (raw === undefined || raw === null)
48
48
  return null;
49
49
  if (model.fields[key]?.encrypted)
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Change events (RFC 0018 §7.5): a model with `changeEvents: true` emits one `record.changed` outbox event per model
3
+ * and action at each flush, in the writing transaction, so it exists if and only if the change committed. The event
4
+ * names the ids and the stored keys written; it carries no values (subscribers read the records in their own scope).
5
+ */
6
+ import type { AnyModel } from '../model/model.js';
7
+ /** The topic of change events. */
8
+ export declare const CHANGE_TOPIC = "record.changed";
9
+ /** At most this many ids per event: a larger change is split. */
10
+ export declare const CHANGE_IDS_PER_EVENT = 1000;
11
+ export interface ChangeRow {
12
+ readonly model: string;
13
+ readonly action: 'create' | 'write' | 'unlink';
14
+ readonly ids: readonly number[];
15
+ readonly keys: readonly string[];
16
+ }
17
+ /** What recording and emitting need of a scope. */
18
+ export interface ChangeHost {
19
+ readonly changeRows: ChangeRow[];
20
+ readonly env: {
21
+ emit(topic: string, payload: unknown): Promise<number>;
22
+ /** Why the scope acts (`env.reason`): subscribers tell their own writes apart (loop guards). */
23
+ readonly reason?: string | undefined;
24
+ };
25
+ }
26
+ /** Records a change of `model`'s rows (a no-op unless the model asks for change events; drafts are left out). */
27
+ export declare function recordChange(host: Pick<ChangeHost, 'changeRows'>, model: AnyModel, action: ChangeRow['action'], ids: readonly number[], keys?: readonly string[]): void;
28
+ /** Emits the recorded changes: one event per model and action (keys merged), split by {@link CHANGE_IDS_PER_EVENT}. */
29
+ export declare function flushChanges(host: ChangeHost): Promise<void>;
@@ -0,0 +1,48 @@
1
+ /** The topic of change events. */
2
+ export const CHANGE_TOPIC = 'record.changed';
3
+ /** At most this many ids per event: a larger change is split. */
4
+ export const CHANGE_IDS_PER_EVENT = 1000;
5
+ /** Records a change of `model`'s rows (a no-op unless the model asks for change events; drafts are left out). */
6
+ export function recordChange(host, model, action, ids, keys = []) {
7
+ if (!model.changeEvents)
8
+ return;
9
+ const real = ids.filter((id) => id > 0);
10
+ if (real.length > 0)
11
+ host.changeRows.push({ model: model.name, action, ids: real, keys });
12
+ }
13
+ /** Emits the recorded changes: one event per model and action (keys merged), split by {@link CHANGE_IDS_PER_EVENT}. */
14
+ export async function flushChanges(host) {
15
+ if (host.changeRows.length === 0)
16
+ return;
17
+ const rows = host.changeRows.splice(0);
18
+ const merged = new Map();
19
+ for (const row of rows) {
20
+ const key = `${row.model}\u0000${row.action}`;
21
+ const entry = merged.get(key) ?? {
22
+ model: row.model,
23
+ action: row.action,
24
+ ids: [],
25
+ seen: new Set(),
26
+ keys: new Set(),
27
+ };
28
+ for (const id of row.ids)
29
+ if (!entry.seen.has(id)) {
30
+ entry.seen.add(id);
31
+ entry.ids.push(id);
32
+ }
33
+ for (const k of row.keys)
34
+ entry.keys.add(k);
35
+ merged.set(key, entry);
36
+ }
37
+ for (const entry of merged.values()) {
38
+ const keys = [...entry.keys].sort();
39
+ for (let i = 0; i < entry.ids.length; i += CHANGE_IDS_PER_EVENT)
40
+ await host.env.emit(CHANGE_TOPIC, {
41
+ model: entry.model,
42
+ action: entry.action,
43
+ ids: entry.ids.slice(i, i + CHANGE_IDS_PER_EVENT),
44
+ ...(entry.action === 'unlink' ? {} : { keys }),
45
+ ...(host.env.reason === undefined ? {} : { reason: host.env.reason }),
46
+ });
47
+ }
48
+ }
@@ -23,8 +23,6 @@ export interface ComputeHost {
23
23
  }
24
24
  /** Drops the cached values of the dependents of `(model, key)` that are in the cache (RFC 0008 §7.2). Cache only. */
25
25
  export declare function invalidateCached(internals: ScopeInternals, model: string, key: string, ids: readonly number[]): void;
26
- /** The load spec covering the `depends` of `fields` (RFC 0004 §7.5), plus the sibling currency / unit fields. */
27
- export declare function dependsSpec(internals: ScopeInternals, model: AnyModel, fields: readonly ComputedField[]): ComputeSpec;
28
26
  /** Assigns a computed value from inside its compute (the record accessors' setter). */
29
27
  export declare function assignComputed(host: ComputeHost, model: AnyModel, id: number, key: string, value: unknown): void;
30
28
  /**
@@ -3,6 +3,7 @@
3
3
  * affected records (database + cache), batched recompute in rank order before flushes, computation of non-stored
4
4
  * fields on load, and the assignment protocol inside computes.
5
5
  */
6
+ import { resolveTranslation } from '../../i18n/index.js';
6
7
  import { compile, sql } from '../../sql/index.js';
7
8
  import { ComputeAssignmentError, RecomputeLimitError, ValidationError } from '../errors.js';
8
9
  import { defaultDisplayName } from '../model/model.js';
@@ -176,7 +177,7 @@ function addSibling(model, key, fields) {
176
177
  fields.add(field.uomField);
177
178
  }
178
179
  /** The load spec covering the `depends` of `fields` (RFC 0004 §7.5), plus the sibling currency / unit fields. */
179
- export function dependsSpec(internals, model, fields) {
180
+ function dependsSpec(internals, model, fields) {
180
181
  const root = { fields: new Set(['id']), relations: new Map() };
181
182
  for (const f of fields) {
182
183
  addSibling(model, f.key, root.fields);
@@ -289,9 +290,16 @@ export async function computeFields(host, model, ids, fields) {
289
290
  try {
290
291
  const compute = group[0].compute;
291
292
  if (compute === defaultDisplayName) {
293
+ // A translated record name is shown in the environment's language (its source text as the fallback).
294
+ const translated = model.fields[model.recName]?.translate === true;
292
295
  for (const id of ids) {
293
296
  const value = host.values(model.name, id)?.get(model.recName);
294
- assignComputed(host, model, id, 'displayName', value === null || value === undefined ? '' : String(value));
297
+ const text = value === null || value === undefined
298
+ ? ''
299
+ : translated && typeof value === 'object'
300
+ ? (resolveTranslation(value, internals.env.lang, internals.sourceLang) ?? '')
301
+ : String(value);
302
+ assignComputed(host, model, id, 'displayName', text);
295
303
  }
296
304
  }
297
305
  else {
@@ -195,7 +195,9 @@ export async function runOnchange(host, model, input) {
195
195
  fields: new Set(keys.filter((k) => model.columns[k] !== undefined)),
196
196
  relations: new Map(),
197
197
  });
198
- const [beforeRow] = host.read(model, [vid], keys.filter((k) => values.has(k)));
198
+ // The input to compare against: a record's values and the given ones; for a new draft the given ones only, so
199
+ // its defaults come back (a new form shows them).
200
+ const [beforeRow] = host.read(model, [vid], keys.filter((k) => input.id === undefined || input.id === null ? k in input.values : values.has(k)));
199
201
  // Handlers, cascading once per key: the draft's, then each new child row's for the fields it was given
200
202
  // (feedback #10), so a line's product handler runs inside the order being edited and sees its values.
201
203
  await runHandlers(host, model, vid, input.id ?? null, input.changed, warnings);
@@ -21,8 +21,6 @@ export interface RecordCache {
21
21
  }
22
22
  /** @internal */
23
23
  export declare function createRecordCache(): RecordCache;
24
- /** Stored, non-binary, not x2many (RFC 0004 §6.1). */
25
- export declare function defaultKeys(model: AnyModel): string[];
26
24
  /** Ids shared by the records loaded together (RFC 0004 §7.3). */
27
25
  interface Group {
28
26
  readonly ids: readonly number[];
@@ -36,7 +34,7 @@ interface Pending {
36
34
  readonly parents: readonly number[];
37
35
  }
38
36
  /** @internal Runtime recordset. Typed through `RecordSet` / `Rec` / `PendingSet` (types.ts). */
39
- export declare class RecordSetImpl {
37
+ declare class RecordSetImpl {
40
38
  #private;
41
39
  readonly env: Env;
42
40
  readonly registered: RegisteredModel;
@@ -13,6 +13,7 @@ import { defineUom, Quantity } from '../money/quantity.js';
13
13
  import { targetOf } from '../registry/registry.js';
14
14
  import { runAggregate } from './aggregate.js';
15
15
  import { flushAudit, trailOf } from './audit.js';
16
+ import { flushChanges } from './changes.js';
16
17
  import { assignComputed, computeFields, recompute, } from './compute.js';
17
18
  import { checkConstraints } from './constraints.js';
18
19
  import { compileDomain, compileOrder, scopingConditions } from './domain.js';
@@ -48,7 +49,7 @@ function isX2Many(field) {
48
49
  return field.kind === 'one2many' || field.kind === 'many2many';
49
50
  }
50
51
  /** Stored, non-binary, not x2many (RFC 0004 §6.1). */
51
- export function defaultKeys(model) {
52
+ function defaultKeys(model) {
52
53
  return Object.entries(model.fields)
53
54
  .filter(([, f]) => f.store && f.kind !== 'binary' && !isX2Many(f))
54
55
  .map(([key]) => key);
@@ -318,7 +319,7 @@ async function loadInto(loader, model, ids, spec, user = false) {
318
319
  }
319
320
  const prototypes = new WeakMap();
320
321
  /** @internal Runtime recordset. Typed through `RecordSet` / `Rec` / `PendingSet` (types.ts). */
321
- export class RecordSetImpl {
322
+ class RecordSetImpl {
322
323
  env;
323
324
  registered;
324
325
  modelName;
@@ -733,6 +734,7 @@ export async function flushAll(internals, model) {
733
734
  await checkConstraints(computeHost(loader));
734
735
  await flushDirty(writeHost(loader), model);
735
736
  await flushAudit(internals, model);
737
+ await flushChanges(internals);
736
738
  }
737
739
  /** @internal `env.model(name)`. */
738
740
  export function modelRef(env, name) {
@@ -37,12 +37,8 @@ export declare function readableKeys(internals: ScopeInternals, model: AnyModel,
37
37
  * related models: a filter on a hidden field would leak it through which records match (RFC 0014 §7.4).
38
38
  */
39
39
  export declare function assertDomainFields(internals: ScopeInternals, model: AnyModel, domain: unknown): void;
40
- /** The field keys a domain mentions (through `or` / `and` / `not`). */
41
- export declare function domainKeys(domain: unknown, out?: Set<string>): Set<string>;
42
40
  /** Record-rule conditions for `perm` (RFC 0014 §7.3): globals ANDed, applicable group rules ORed. Empty under `su`. */
43
41
  export declare function ruleConditions(internals: ScopeInternals, model: AnyModel, perm: RulePerm): SqlFragment[];
44
- /** True when `perm` has rules for the model that apply to this environment. */
45
- export declare function hasRules(internals: ScopeInternals, model: AnyModel, perm: RulePerm): boolean;
46
42
  /**
47
43
  * Checks that every id passes the rules for `perm` (RFC 0014 §7.3). Ids that exist but are out of scope are an
48
44
  * {@link AccessError}; ids that do not exist are a {@link MissingRecordError}.
@@ -168,23 +168,6 @@ export function assertDomainFields(internals, model, domain) {
168
168
  }
169
169
  }
170
170
  }
171
- /** The field keys a domain mentions (through `or` / `and` / `not`). */
172
- export function domainKeys(domain, out = new Set()) {
173
- if (Array.isArray(domain)) {
174
- for (const d of domain)
175
- domainKeys(d, out);
176
- return out;
177
- }
178
- if (typeof domain !== 'object' || domain === null)
179
- return out;
180
- for (const [key, value] of Object.entries(domain)) {
181
- if (key === 'or' || key === 'and' || key === 'not')
182
- domainKeys(value, out);
183
- else
184
- out.add(key);
185
- }
186
- return out;
187
- }
188
171
  /** Record-rule conditions for `perm` (RFC 0014 §7.3): globals ANDed, applicable group rules ORed. Empty under `su`. */
189
172
  export function ruleConditions(internals, model, perm) {
190
173
  const { env } = internals;
@@ -212,10 +195,6 @@ export function ruleConditions(internals, model, perm) {
212
195
  }
213
196
  return out;
214
197
  }
215
- /** True when `perm` has rules for the model that apply to this environment. */
216
- export function hasRules(internals, model, perm) {
217
- return ruleConditions(internals, model, perm).length > 0;
218
- }
219
198
  /**
220
199
  * Checks that every id passes the rules for `perm` (RFC 0014 §7.3). Ids that exist but are out of scope are an
221
200
  * {@link AccessError}; ids that do not exist are a {@link MissingRecordError}.
@@ -3,24 +3,11 @@
3
3
  * transaction for gapless sequences or in a short autonomous one otherwise; filling sequence fields at create time;
4
4
  * `records.assignNumber()` for manual numbering.
5
5
  */
6
- import { type SequenceDefinition } from '../../sequence/index.js';
7
6
  import type { ScopeInternals } from '../env/env.js';
8
- import type { Field } from '../model/field.js';
9
7
  import type { AnyModel } from '../model/model.js';
10
8
  import type { ComputeHost } from './compute.js';
11
9
  /** The placeholder of a manually numbered document (RFC 0012 §7.4). */
12
10
  export declare const UNNUMBERED = "/";
13
- /** Allocates one formatted number per request, in one statement per (company, period) group. */
14
- export declare function allocateNumbers(internals: ScopeInternals, definition: SequenceDefinition, requests: readonly {
15
- readonly company: number | null;
16
- readonly date: string;
17
- }[]): Promise<string[]>;
18
- /** Sequence fields of a model with their options. */
19
- export declare function sequenceFields(model: AnyModel): {
20
- readonly key: string;
21
- readonly field: Field;
22
- readonly options: NonNullable<Field['sequence']>;
23
- }[];
24
11
  /** Fills the `on: 'create'` sequence fields of rows that have no value (RFC 0012 §7.4). */
25
12
  export declare function fillSequences(internals: ScopeInternals, model: AnyModel, rows: readonly {
26
13
  readonly stored: Map<string, unknown>;
@@ -37,7 +37,7 @@ function groupRequests(definition, requests) {
37
37
  return [...groups.values()];
38
38
  }
39
39
  /** Allocates one formatted number per request, in one statement per (company, period) group. */
40
- export async function allocateNumbers(internals, definition, requests) {
40
+ async function allocateNumbers(internals, definition, requests) {
41
41
  const out = new Array(requests.length);
42
42
  if (requests.length === 0)
43
43
  return out;
@@ -56,7 +56,7 @@ export async function allocateNumbers(internals, definition, requests) {
56
56
  return out;
57
57
  }
58
58
  /** Sequence fields of a model with their options. */
59
- export function sequenceFields(model) {
59
+ function sequenceFields(model) {
60
60
  return Object.entries(model.fields)
61
61
  .filter(([, f]) => f.sequence !== undefined)
62
62
  .map(([key, field]) => ({
@@ -20,8 +20,6 @@ import type { AnyModel } from '../model/model.js';
20
20
  export declare function fail(model: AnyModel, fields: readonly string[], problem: string, hint: string): never;
21
21
  /** The PostgreSQL array element type for a field (for `unnest($n::type[])`). */
22
22
  export declare function arrayType(field: Field): string;
23
- /** The SQL cast applied to a bound value before it reaches the column (`jsonb` for json and translatable fields). */
24
- export declare function columnCast(field: Field): 'jsonb' | undefined;
25
23
  /** A reference to the bound value of `column` in the `v` row alias, cast when needed. */
26
24
  export declare function valueRef(field: Field, column: string): SqlFragment;
27
25
  /** Converts a cached value into what the driver binds. */
@@ -40,7 +40,7 @@ export function arrayType(field) {
40
40
  return field.pgType;
41
41
  }
42
42
  /** The SQL cast applied to a bound value before it reaches the column (`jsonb` for json and translatable fields). */
43
- export function columnCast(field) {
43
+ function columnCast(field) {
44
44
  return field.kind === 'json' || field.translate || field.companyDependent ? 'jsonb' : undefined;
45
45
  }
46
46
  /** A reference to the bound value of `column` in the `v` row alias, cast when needed. */
@@ -9,6 +9,7 @@ import { SYSTEM_UID } from '../env/identity.js';
9
9
  import { MissingRecordError, StaleRecordError } from '../errors.js';
10
10
  import { targetOf } from '../registry/registry.js';
11
11
  import { trackChange, trackedKeys, trackSnapshot } from './audit.js';
12
+ import { recordChange } from './changes.js';
12
13
  import { junctionTable } from './relations.js';
13
14
  import { assertAccess, assertBackdate, assertFields, assertRecords, storedValue, } from './security.js';
14
15
  import { fillSequences, UNNUMBERED } from './sequences.js';
@@ -337,6 +338,9 @@ export async function createRecords(host, model, input, options = {}) {
337
338
  prepared.forEach((p, i) => {
338
339
  trackSnapshot(internals, model, ids[i], 'create', p.stored);
339
340
  });
341
+ recordChange(internals, model, 'create', ids,
342
+ // The stored fields the caller gave (defaults and the bookkeeping columns are not "changes" of interest).
343
+ [...new Set(input.flatMap((row) => Object.keys(row)))].filter((key) => model.columns[key] !== undefined && !model.fields[key].computed));
340
344
  // Triggers: every stored value of a new record "changed"; its own stored computes are computed at the next flush point.
341
345
  for (const key of columns) {
342
346
  const field = model.fields[key];
@@ -344,8 +348,12 @@ export async function createRecords(host, model, input, options = {}) {
344
348
  continue;
345
349
  internals.trigger(model.name, key, ids);
346
350
  }
347
- for (const [key, parents] of parentsByKey)
351
+ for (const [key, parents] of parentsByKey) {
348
352
  triggerParents(internals, model, key, parents);
353
+ // The parents' cached child lists don't hold the new records yet (a payment created for a loaded invoice).
354
+ for (const parent of new Set(parents))
355
+ invalidateInverseLists(host, model, key, null, parent);
356
+ }
349
357
  for (const f of internals.registry.compute.stored(model.name))
350
358
  internals.markToCompute(model.name, f.key, ids);
351
359
  // one2many `create` commands of every new parent become one child insert per field (no INSERT per parent).
@@ -552,6 +560,7 @@ export async function unlinkRecords(host, model, ids) {
552
560
  if (absent.length > 0)
553
561
  throw new MissingRecordError(model.name, absent);
554
562
  }
563
+ recordChange(internals, model, 'unlink', ids);
555
564
  for (const id of ids) {
556
565
  const values = host.values(model.name, id);
557
566
  if (values !== undefined)
@@ -775,6 +784,7 @@ export async function flushDirty(host, modelName) {
775
784
  const absent = chunk.filter((id) => !updated.has(id));
776
785
  if (absent.length > 0)
777
786
  throw new MissingRecordError(name, absent);
787
+ recordChange(internals, model, 'write', chunk, group.fields);
778
788
  for (const id of chunk) {
779
789
  const values = host.values(name, id);
780
790
  values?.set('updatedAt', internals.now);
@@ -54,6 +54,8 @@ export interface ExtensionDefinition<Fs extends FieldsRecord, Ms extends Methods
54
54
  readonly sqlConstraints?: Readonly<Record<string, SqlUniqueConstraint<string> | SqlCheckConstraint>>;
55
55
  readonly indexes?: readonly IndexSpec<string>[];
56
56
  readonly tracking?: readonly string[];
57
+ /** Turn on change events for the model (RFC 0018 §7.5); an extension cannot turn them off. */
58
+ readonly changeEvents?: boolean;
57
59
  }
58
60
  /** An extension as `extendModel` returns it. `fields` / `methods` carry types for the registry's schema view. */
59
61
  export interface Extension<N extends string = string, Fs extends FieldsRecord = FieldsRecord, Ms extends MethodsRecord = MethodsRecord> {
@@ -73,6 +75,7 @@ export interface Extension<N extends string = string, Fs extends FieldsRecord =
73
75
  readonly sqlConstraints: Readonly<Record<string, SqlUniqueConstraint<string> | SqlCheckConstraint>>;
74
76
  readonly indexes: readonly IndexSpec<string>[];
75
77
  readonly tracking: readonly string[];
78
+ readonly changeEvents: boolean;
76
79
  }
77
80
  /** Any extension. */
78
81
  export type AnyExtension = Extension<string, FieldsRecord, MethodsRecord>;
@@ -84,6 +84,7 @@ export function extendModel(name, definition) {
84
84
  sqlConstraints: Object.freeze({ ...(definition.sqlConstraints ?? {}) }),
85
85
  indexes: Object.freeze([...(definition.indexes ?? [])]),
86
86
  tracking: Object.freeze([...(definition.tracking ?? [])]),
87
+ changeEvents: definition.changeEvents === true,
87
88
  });
88
89
  extensions.add(extension);
89
90
  return extension;
@@ -101,6 +101,7 @@ function draftOf(model, module) {
101
101
  sqlConstraints: { ...(def.sqlConstraints ?? {}) },
102
102
  indexes: [...(def.indexes ?? [])],
103
103
  tracking: [...(def.tracking ?? [])],
104
+ changeEvents: def.changeEvents === true,
104
105
  };
105
106
  }
106
107
  /** Wraps `prev` with `layer`: `layer.call(this, next, ...args)` where `next` is `prev` bound to `this`. */
@@ -289,6 +290,8 @@ function applyExtension(draft, ext, module, reachable) {
289
290
  for (const key of ext.tracking)
290
291
  if (!draft.tracking.includes(key))
291
292
  draft.tracking.push(key);
293
+ if (ext.changeEvents)
294
+ draft.changeEvents = true;
292
295
  draft.extensions.push(module);
293
296
  }
294
297
  /** Rebuilds the final model from the draft through `defineModel`, so every model-level check applies to it. */
@@ -305,6 +308,7 @@ function finalize(draft) {
305
308
  sqlConstraints: draft.sqlConstraints,
306
309
  indexes: draft.indexes,
307
310
  tracking: draft.tracking,
311
+ changeEvents: draft.changeEvents,
308
312
  });
309
313
  const fieldOrigins = {};
310
314
  for (const key of Object.keys(model.fields))
@@ -22,11 +22,17 @@ function collectStrings(value, out) {
22
22
  collectStrings(item, out);
23
23
  }
24
24
  }
25
+ /** Quoted identifiers (`"purchase_order"`): `sql.id()` validates them, so a value inside one is not a leak. */
26
+ const QUOTED_IDENTIFIER = /"(?:[^"]|"")*"/g;
25
27
  function guardParamsInText(query) {
26
28
  const strings = [];
27
29
  for (const p of query.params)
28
30
  collectStrings(p, strings);
29
- const leaked = strings.find((s) => query.text.includes(s));
31
+ if (strings.length === 0)
32
+ return;
33
+ // A state 'purchase' written to "purchase_order" is a value equal to part of a table name, not concatenation.
34
+ const text = query.text.replace(QUOTED_IDENTIFIER, '""');
35
+ const leaked = strings.find((s) => text.includes(s));
30
36
  if (leaked !== undefined) {
31
37
  throw new DriverError('PARAM_IN_TEXT', `A parameter value (${JSON.stringify(leaked.slice(0, 40))}) also appears in the SQL text, so the text was probably built by string concatenation.`, 'Build queries with sql`...` from @shutro/sql so values only travel as parameters; set checkParamsInText: false only if the overlap is intentional.');
32
38
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shutro",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "The ORM built for business software: type-safe, secure-by-default, multi-company, audit-ready PostgreSQL ORM for Node.js and TypeScript.",
5
5
  "keywords": [
6
6
  "orm",