shutro 0.0.0-stage → 0.1.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 (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/dist/audit/index.d.ts +57 -0
  4. package/dist/audit/index.js +94 -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 +149 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +47 -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 +82 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +200 -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/core/compute/graph.d.ts +52 -0
  28. package/dist/core/compute/graph.js +162 -0
  29. package/dist/core/env/env.d.ts +295 -0
  30. package/dist/core/env/env.js +631 -0
  31. package/dist/core/env/identity.d.ts +33 -0
  32. package/dist/core/env/identity.js +49 -0
  33. package/dist/core/env/inspector.d.ts +55 -0
  34. package/dist/core/env/inspector.js +85 -0
  35. package/dist/core/env/time.d.ts +12 -0
  36. package/dist/core/env/time.js +38 -0
  37. package/dist/core/errors.d.ts +242 -0
  38. package/dist/core/errors.js +339 -0
  39. package/dist/core/index.d.ts +43 -0
  40. package/dist/core/index.js +34 -0
  41. package/dist/core/model/company.d.ts +6 -0
  42. package/dist/core/model/company.js +31 -0
  43. package/dist/core/model/faces.d.ts +42 -0
  44. package/dist/core/model/faces.js +1 -0
  45. package/dist/core/model/field.d.ts +446 -0
  46. package/dist/core/model/field.js +398 -0
  47. package/dist/core/model/generated.d.ts +75 -0
  48. package/dist/core/model/generated.js +1 -0
  49. package/dist/core/model/id.d.ts +33 -0
  50. package/dist/core/model/id.js +4 -0
  51. package/dist/core/model/model.d.ts +347 -0
  52. package/dist/core/model/model.js +538 -0
  53. package/dist/core/model/partition.d.ts +31 -0
  54. package/dist/core/model/partition.js +71 -0
  55. package/dist/core/money/currency.d.ts +39 -0
  56. package/dist/core/money/currency.js +37 -0
  57. package/dist/core/money/decimal.d.ts +26 -0
  58. package/dist/core/money/decimal.js +51 -0
  59. package/dist/core/money/fx.d.ts +60 -0
  60. package/dist/core/money/fx.js +109 -0
  61. package/dist/core/money/money.d.ts +84 -0
  62. package/dist/core/money/money.js +173 -0
  63. package/dist/core/money/quantity.d.ts +67 -0
  64. package/dist/core/money/quantity.js +108 -0
  65. package/dist/core/money/rounding.d.ts +11 -0
  66. package/dist/core/money/rounding.js +12 -0
  67. package/dist/core/recordset/audit.d.ts +25 -0
  68. package/dist/core/recordset/audit.js +205 -0
  69. package/dist/core/recordset/compute.d.ts +34 -0
  70. package/dist/core/recordset/compute.js +405 -0
  71. package/dist/core/recordset/constraints.d.ts +9 -0
  72. package/dist/core/recordset/constraints.js +61 -0
  73. package/dist/core/recordset/domain.d.ts +27 -0
  74. package/dist/core/recordset/domain.js +228 -0
  75. package/dist/core/recordset/onchange.d.ts +43 -0
  76. package/dist/core/recordset/onchange.js +207 -0
  77. package/dist/core/recordset/recordset.d.ts +101 -0
  78. package/dist/core/recordset/recordset.js +723 -0
  79. package/dist/core/recordset/relations.d.ts +15 -0
  80. package/dist/core/recordset/relations.js +13 -0
  81. package/dist/core/recordset/rls.d.ts +15 -0
  82. package/dist/core/recordset/rls.js +108 -0
  83. package/dist/core/recordset/security.d.ts +42 -0
  84. package/dist/core/recordset/security.js +184 -0
  85. package/dist/core/recordset/sequences.d.ts +31 -0
  86. package/dist/core/recordset/sequences.js +154 -0
  87. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  88. package/dist/core/recordset/sqlErrors.js +39 -0
  89. package/dist/core/recordset/transitions.d.ts +10 -0
  90. package/dist/core/recordset/transitions.js +77 -0
  91. package/dist/core/recordset/types.d.ts +296 -0
  92. package/dist/core/recordset/types.js +8 -0
  93. package/dist/core/recordset/values.d.ts +27 -0
  94. package/dist/core/recordset/values.js +147 -0
  95. package/dist/core/recordset/writes.d.ts +37 -0
  96. package/dist/core/recordset/writes.js +581 -0
  97. package/dist/core/registry/ddl.d.ts +22 -0
  98. package/dist/core/registry/ddl.js +127 -0
  99. package/dist/core/registry/extension.d.ts +94 -0
  100. package/dist/core/registry/extension.js +90 -0
  101. package/dist/core/registry/module.d.ts +80 -0
  102. package/dist/core/registry/module.js +96 -0
  103. package/dist/core/registry/registry.d.ts +105 -0
  104. package/dist/core/registry/registry.js +496 -0
  105. package/dist/driver-pg/driver.d.ts +86 -0
  106. package/dist/driver-pg/driver.js +176 -0
  107. package/dist/driver-pg/errors.d.ts +72 -0
  108. package/dist/driver-pg/errors.js +182 -0
  109. package/dist/driver-pg/index.d.ts +7 -0
  110. package/dist/driver-pg/index.js +7 -0
  111. package/dist/i18n/index.d.ts +25 -0
  112. package/dist/i18n/index.js +51 -0
  113. package/dist/migrate/apply.d.ts +78 -0
  114. package/dist/migrate/apply.js +167 -0
  115. package/dist/migrate/catalog.d.ts +10 -0
  116. package/dist/migrate/catalog.js +122 -0
  117. package/dist/migrate/diff.d.ts +98 -0
  118. package/dist/migrate/diff.js +160 -0
  119. package/dist/migrate/errors.d.ts +21 -0
  120. package/dist/migrate/errors.js +31 -0
  121. package/dist/migrate/index.d.ts +18 -0
  122. package/dist/migrate/index.js +18 -0
  123. package/dist/migrate/render.d.ts +5 -0
  124. package/dist/migrate/render.js +101 -0
  125. package/dist/migrate/schema.d.ts +61 -0
  126. package/dist/migrate/schema.js +195 -0
  127. package/dist/security/index.d.ts +123 -0
  128. package/dist/security/index.js +262 -0
  129. package/dist/sequence/index.d.ts +63 -0
  130. package/dist/sequence/index.js +106 -0
  131. package/dist/sql/ast.d.ts +49 -0
  132. package/dist/sql/ast.js +47 -0
  133. package/dist/sql/builder/builder.d.ts +215 -0
  134. package/dist/sql/builder/builder.js +308 -0
  135. package/dist/sql/builder/expression.d.ts +80 -0
  136. package/dist/sql/builder/expression.js +126 -0
  137. package/dist/sql/compile.d.ts +18 -0
  138. package/dist/sql/compile.js +41 -0
  139. package/dist/sql/errors.d.ts +13 -0
  140. package/dist/sql/errors.js +16 -0
  141. package/dist/sql/index.d.ts +19 -0
  142. package/dist/sql/index.js +19 -0
  143. package/dist/sql/tag.d.ts +42 -0
  144. package/dist/sql/tag.js +95 -0
  145. package/package.json +82 -4
@@ -0,0 +1,82 @@
1
+ /**
2
+ * `shutro generate`: loads the module files of the config, builds one registry per module (its view) and one for
3
+ * the application, and writes the generated files, or reports which ones are stale (`--check`).
4
+ */
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
6
+ import { dirname, join, relative } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { buildRegistry, isModule } from '../../core/index.js';
9
+ import { ConfigError, ModuleSourceError } from '../errors.js';
10
+ import { outDirOf, renderAppIndex, renderBindings, renderSchema, } from './render.js';
11
+ /** Imports the module files of a config (one `defineModule` export each). */
12
+ export async function loadSources(files) {
13
+ const sources = new Map();
14
+ for (const file of files) {
15
+ if (!existsSync(file)) {
16
+ throw new ConfigError(`Module file ${file} does not exist.`, 'Check `modules` in shutro.config.ts.');
17
+ }
18
+ const ns = (await import(pathToFileURL(file).href));
19
+ const found = Object.entries(ns).filter(([, value]) => isModule(value));
20
+ if (found.length !== 1) {
21
+ throw new ConfigError(`${file} exports ${found.length} modules; expected exactly one.`, 'Export one `defineModule(...)` per file (models can live in other files).');
22
+ }
23
+ const [exportName, module] = found[0];
24
+ const existing = sources.get(module.name);
25
+ if (existing !== undefined) {
26
+ throw new ConfigError(`Module '${module.name}' is exported by both ${existing.file} and ${file}.`, 'List each module file once.');
27
+ }
28
+ sources.set(module.name, { module, file, exportName });
29
+ }
30
+ return sources;
31
+ }
32
+ /** The module that pulled in `missing` (for error messages). */
33
+ export function dependant(registry, missing) {
34
+ const reaches = (m) => m.depends.some((d) => d.name === missing || reaches(d));
35
+ return registry.modules.find((m) => reaches(m))?.name ?? missing;
36
+ }
37
+ /** Generates the per-module views and the application view described by `config`. */
38
+ export async function generate(options) {
39
+ const { config, cwd } = options;
40
+ const sources = await loadSources(config.modules);
41
+ const all = buildRegistry({ modules: [...sources.values()].map((s) => s.module) });
42
+ for (const module of all.modules) {
43
+ if (!sources.has(module.name))
44
+ throw new ModuleSourceError(module.name, dependant(all, module.name));
45
+ }
46
+ const rendered = [];
47
+ for (const module of all.modules) {
48
+ const source = sources.get(module.name);
49
+ const view = buildRegistry({ modules: [source.module] });
50
+ const outDir = outDirOf(source.file);
51
+ 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.`;
52
+ rendered.push({
53
+ path: join(outDir, 'schema.d.ts'),
54
+ content: renderSchema(view, sources, outDir, title),
55
+ });
56
+ rendered.push({
57
+ path: join(outDir, 'bindings.ts'),
58
+ content: renderBindings(view, module.name),
59
+ });
60
+ }
61
+ if (config.app !== undefined) {
62
+ const outDir = join(config.app, '.shutro');
63
+ const title = `Application view: every installed module (${all.loadOrder.join(', ')}).`;
64
+ rendered.push({
65
+ path: join(outDir, 'schema.d.ts'),
66
+ content: renderSchema(all, sources, outDir, title),
67
+ });
68
+ rendered.push({ path: join(outDir, 'index.ts'), content: renderAppIndex(all) });
69
+ }
70
+ const files = [];
71
+ for (const { path, content } of rendered) {
72
+ const target = options.outRoot === undefined ? path : join(options.outRoot, relative(cwd, path));
73
+ const current = existsSync(target) ? readFileSync(target, 'utf8') : undefined;
74
+ const status = current === undefined ? 'created' : current === content ? 'unchanged' : 'updated';
75
+ if (status !== 'unchanged' && options.check !== true) {
76
+ mkdirSync(dirname(target), { recursive: true });
77
+ writeFileSync(target, content);
78
+ }
79
+ files.push({ path: target, content, status });
80
+ }
81
+ return { files, changed: files.filter((f) => f.status !== 'unchanged'), modules: all.loadOrder };
82
+ }
@@ -0,0 +1,23 @@
1
+ import type { Field, ModuleBase, Registry } from '../../core/index.js';
2
+ /** A module and the file it is exported from. */
3
+ export interface ModuleSource {
4
+ readonly module: ModuleBase;
5
+ readonly file: string;
6
+ readonly exportName: string;
7
+ }
8
+ /** Short, stable hash of everything the view depends on (RFC 0002 §7.7 "definitions hash"). */
9
+ export declare function definitionsHash(registry: Registry): string;
10
+ /** `sale.order.line` → `SaleOrderLine`. */
11
+ export declare function interfaceName(model: string): string;
12
+ /** The `F.*` type of one field. */
13
+ export declare function fieldType(model: string, key: string, field: Field): string;
14
+ /** Import specifier of `file` from a file in `fromDir`, in ESM spelling (`../module.js`). */
15
+ export declare function importSpecifier(fromDir: string, file: string): string;
16
+ /** Renders `schema.d.ts` for a registry (a module view or the application view). */
17
+ export declare function renderSchema(registry: Registry, sources: ReadonlyMap<string, ModuleSource>, outDir: string, title: string): string;
18
+ /** Renders `bindings.ts` for a module: the definition API plus aliases typed to its view. */
19
+ export declare function renderBindings(registry: Registry, module: string): string;
20
+ /** Renders the application's `index.ts`: `createShutro` typed to the full view. */
21
+ export declare function renderAppIndex(registry: Registry): string;
22
+ /** Directory of the generated files of a module file. */
23
+ export declare function outDirOf(file: string): string;
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Renders a registry as the generated files of RFC 0002 §7.7: `schema.d.ts` (interfaces only, relations by model
3
+ * name, methods typed from the module sources) plus the typed re-exports next to it.
4
+ */
5
+ import { createHash } from 'node:crypto';
6
+ import { dirname, relative } from 'node:path';
7
+ import { CORE_PACKAGE } from '../packages.js';
8
+ const HEADER = '// GENERATED by `shutro generate`. Do not edit.';
9
+ /** Short, stable hash of everything the view depends on (RFC 0002 §7.7 "definitions hash"). */
10
+ export function definitionsHash(registry) {
11
+ const names = [...registry.models.keys()].sort();
12
+ const definitions = {
13
+ modules: registry.modules.map((m) => [m.name, m.version]),
14
+ models: names.map((name) => registry.describe(name)),
15
+ };
16
+ return createHash('sha256').update(JSON.stringify(definitions)).digest('hex').slice(0, 16);
17
+ }
18
+ /** `sale.order.line` → `SaleOrderLine`. */
19
+ export function interfaceName(model) {
20
+ return model
21
+ .split(/[._]/)
22
+ .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
23
+ .join('');
24
+ }
25
+ function quote(value) {
26
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
27
+ }
28
+ function union(values) {
29
+ return values.length === 0 ? 'never' : values.map(quote).join(' | ');
30
+ }
31
+ /**
32
+ * The option literal that reproduces the field's phantom flags through `FlagsOf`. Properties are `readonly`, as
33
+ * the builders' `const` type parameters infer them: TypeScript's identity relation tells the two apart, and the
34
+ * generated field must be identical to the declared one.
35
+ */
36
+ function flagOptions(field) {
37
+ const parts = [];
38
+ if (field.required)
39
+ parts.push('required: true');
40
+ if (field.readonly)
41
+ parts.push('readonly: true');
42
+ if (field.default !== undefined)
43
+ parts.push('default: true');
44
+ if (field.computed) {
45
+ parts.push(`compute: ${typeof field.compute === 'string' ? quote(field.compute) : 'true'}`);
46
+ if (field.store)
47
+ parts.push('store: true');
48
+ }
49
+ if (field.inverse !== undefined)
50
+ parts.push('inverse: true');
51
+ if (field.translate)
52
+ parts.push('translate: true');
53
+ if (field.sequence !== undefined)
54
+ parts.push('sequence: true');
55
+ return parts.length === 0 ? '' : `{ ${parts.map((p) => `readonly ${p}`).join('; ')} }`;
56
+ }
57
+ function generic(name, ...args) {
58
+ const given = args.filter((a) => a !== '');
59
+ return given.length === 0 ? `F.${name}` : `F.${name}<${given.join(', ')}>`;
60
+ }
61
+ function selectionValues(field) {
62
+ const selection = field.selection;
63
+ if (!Array.isArray(selection))
64
+ return 'string';
65
+ return union(selection.map(([value]) => value));
66
+ }
67
+ /** The `F.*` type of one field. */
68
+ export function fieldType(model, key, field) {
69
+ const o = flagOptions(field);
70
+ const target = field.target ?? '';
71
+ switch (field.kind) {
72
+ case 'bigint':
73
+ return key === 'id' ? generic('Id', quote(model)) : generic('Bigint', o);
74
+ case 'char':
75
+ return generic('Char', o);
76
+ case 'text':
77
+ return generic('Text', o);
78
+ case 'html':
79
+ return generic('Html', o);
80
+ case 'boolean':
81
+ return generic('Bool', o);
82
+ case 'integer':
83
+ return generic('Integer', o);
84
+ case 'float':
85
+ return generic('Float', o);
86
+ case 'decimal':
87
+ return generic('Decimal', o);
88
+ case 'monetary':
89
+ return generic('Monetary', quote(field.currencyField), o);
90
+ case 'quantity':
91
+ return generic('Quantity', quote(field.uomField), o);
92
+ case 'selection':
93
+ return generic('Selection', selectionValues(field), o);
94
+ case 'state':
95
+ return generic('State', selectionValues(field), o);
96
+ case 'json':
97
+ return generic('Json', o === '' ? '' : 'unknown', o);
98
+ case 'binary':
99
+ return generic('Binary', o);
100
+ case 'date':
101
+ return generic('DateOnly', o);
102
+ case 'datetime':
103
+ return generic('Datetime', o);
104
+ case 'many2one':
105
+ return generic('Many2one', quote(target), o);
106
+ case 'one2many':
107
+ return generic('One2many', quote(target), o);
108
+ case 'many2many':
109
+ return generic('Many2many', quote(target), o);
110
+ default:
111
+ throw new Error(`Unknown field kind ${JSON.stringify(field.kind)} on ${model}.${key}.`);
112
+ }
113
+ }
114
+ /** Import specifier of `file` from a file in `fromDir`, in ESM spelling (`../module.js`). */
115
+ export function importSpecifier(fromDir, file) {
116
+ const spec = relative(fromDir, file).replace(/\\/g, '/').replace(/\.ts$/, '.js');
117
+ return spec.startsWith('.') ? spec : `./${spec}`;
118
+ }
119
+ function methodsType(registered, sources, outDir) {
120
+ const contributors = [registered.module, ...registered.extensions];
121
+ const parts = contributors.map((name) => {
122
+ const source = sources.get(name);
123
+ if (source === undefined)
124
+ throw new Error(`No source for module '${name}'.`);
125
+ const spec = importSpecifier(outDir, source.file);
126
+ return `F.Methods<typeof import(${quote(spec)}).${source.exportName}, ${quote(registered.model.name)}>`;
127
+ });
128
+ return parts.join(' & ');
129
+ }
130
+ /** Renders `schema.d.ts` for a registry (a module view or the application view). */
131
+ export function renderSchema(registry, sources, outDir, title) {
132
+ const names = [...registry.models.keys()].sort();
133
+ const lines = [
134
+ `${HEADER} definitions-hash: ${definitionsHash(registry)}`,
135
+ `// ${title}`,
136
+ `import type { F } from '${CORE_PACKAGE}';`,
137
+ '',
138
+ '/** Model name → model type (RFC 0002 §7.7). */',
139
+ 'export interface SchemaView {',
140
+ ...names.map((name) => ` readonly ${quote(name)}: ${interfaceName(name)};`),
141
+ '}',
142
+ ];
143
+ for (const name of names) {
144
+ const registered = registry.get(name);
145
+ const { model } = registered;
146
+ const origin = registered.extensions.length === 0
147
+ ? `owner: ${registered.module}`
148
+ : `owner: ${registered.module}; extended by: ${registered.extensions.join(', ')}`;
149
+ lines.push('', `/** \`${name}\` (${origin}). */`, `export interface ${interfaceName(name)} {`);
150
+ lines.push(` readonly name: ${quote(name)};`, ' readonly fields: {');
151
+ for (const [key, field] of Object.entries(model.fields)) {
152
+ const from = registered.fieldOrigins[key];
153
+ const comment = from === undefined || from === registered.module ? '' : ` // ${from}`;
154
+ lines.push(` readonly ${key}: ${fieldType(name, key, field)};${comment}`);
155
+ }
156
+ lines.push(' };', ` readonly methods: ${methodsType(registered, sources, outDir)};`, '}');
157
+ }
158
+ return `${lines.join('\n')}\n`;
159
+ }
160
+ const ALIASES = [
161
+ `import type { DefaultLoaded, Env as CoreEnv, RecordSet as CoreRecordSet, Shutro as CoreShutro } from '${CORE_PACKAGE}';`,
162
+ "import type { SchemaView } from './schema.js';",
163
+ '',
164
+ 'export type { SchemaView };',
165
+ '/** Every model visible in this view. */',
166
+ 'export type ModelName = keyof SchemaView & string;',
167
+ '/** `Env` typed to this view. */',
168
+ 'export type Env = CoreEnv<SchemaView>;',
169
+ '/** `Shutro` typed to this view. */',
170
+ 'export type Shutro = CoreShutro<SchemaView>;',
171
+ '/** A recordset of `M`, with the default loaded shape unless `L` is given. */',
172
+ 'export type Records<M extends ModelName, L = DefaultLoaded<SchemaView, M>> = CoreRecordSet<SchemaView, M, L>;',
173
+ ];
174
+ /** Renders `bindings.ts` for a module: the definition API plus aliases typed to its view. */
175
+ export function renderBindings(registry, module) {
176
+ return `${[
177
+ `${HEADER} definitions-hash: ${definitionsHash(registry)}`,
178
+ `// Bindings of module \`${module}\`: import the definition API from here to get types scoped to what it can see.`,
179
+ `export { defineModel, defineModule, extendModel, f, replace } from '${CORE_PACKAGE}';`,
180
+ ...ALIASES,
181
+ ].join('\n')}\n`;
182
+ }
183
+ /** Renders the application's `index.ts`: `createShutro` typed to the full view. */
184
+ export function renderAppIndex(registry) {
185
+ return `${[
186
+ `${HEADER} definitions-hash: ${definitionsHash(registry)}`,
187
+ '// Application view: every installed module. Build the registry from the same modules and pass it here.',
188
+ `import { createShutro as coreCreateShutro, type Registry, type ShutroOptions } from '${CORE_PACKAGE}';`,
189
+ ...ALIASES,
190
+ '',
191
+ '/** `createShutro` whose environments are typed to the application view. */',
192
+ "export function createShutro(options: Omit<ShutroOptions<SchemaView>, 'registry'> & { readonly registry: Registry }): Shutro {",
193
+ ' return coreCreateShutro<SchemaView>(options as ShutroOptions<SchemaView>);',
194
+ '}',
195
+ ].join('\n')}\n`;
196
+ }
197
+ /** Directory of the generated files of a module file. */
198
+ export function outDirOf(file) {
199
+ return `${dirname(file)}/.shutro`;
200
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/cli`: `shutro init | generate | migrate | inspect`.
4
+ */
5
+ export { type CliIo, runCli } from './cli.js';
6
+ export { defineConfig, loadConfig, type ShutroConfig } from './config.js';
7
+ export { CliError, type CliErrorCode, ConfigError, ModuleSourceError } from './errors.js';
8
+ export { type GeneratedFile, type GenerateOptions, type GenerateResult, generate, } from './generate/generate.js';
9
+ export { definitionsHash, fieldType, importSpecifier, interfaceName, type ModuleSource, renderAppIndex, renderBindings, renderSchema, } from './generate/render.js';
10
+ export { initProject } from './init.js';
11
+ export { inspectModel, inspectRegistry } from './inspect.js';
12
+ export { databaseUrl, loadProject, type Project, withDriver } from './project.js';
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/cli`: `shutro init | generate | migrate | inspect`.
4
+ */
5
+ export { runCli } from './cli.js';
6
+ export { defineConfig, loadConfig } from './config.js';
7
+ export { CliError, ConfigError, ModuleSourceError } from './errors.js';
8
+ export { generate, } from './generate/generate.js';
9
+ export { definitionsHash, fieldType, importSpecifier, interfaceName, renderAppIndex, renderBindings, renderSchema, } from './generate/render.js';
10
+ export { initProject } from './init.js';
11
+ export { inspectModel, inspectRegistry } from './inspect.js';
12
+ export { databaseUrl, loadProject, withDriver } from './project.js';
@@ -0,0 +1,2 @@
1
+ /** Writes the starter files under `dir` and returns their paths. @throws {CliError} if any exists. */
2
+ export declare function initProject(dir: string): string[];
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `shutro init`: a minimal project — config, a `base` module with users, currencies and companies, an empty
3
+ * migrations directory. Refuses to overwrite existing files.
4
+ */
5
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { CliError } from './errors.js';
8
+ import { CLI_PACKAGE, CORE_PACKAGE } from './packages.js';
9
+ const FILES = {
10
+ 'shutro.config.ts': `import { defineConfig } from '${CLI_PACKAGE}';
11
+
12
+ export default defineConfig({
13
+ modules: ['./modules/base/module.ts'],
14
+ app: './app',
15
+ migrations: './migrations',
16
+ });
17
+ `,
18
+ 'modules/base/module.ts': `import { defineGroup, defineModel, defineModule, f } from '${CORE_PACKAGE}';
19
+
20
+ export const ResUsers = defineModel('res.users', {
21
+ access: { 'base.user': ['read'], 'base.admin': ['read', 'write', 'create', 'unlink'] },
22
+ fields: { login: f.char({ required: true, index: 'unique' }), name: f.char({ required: true }) },
23
+ });
24
+
25
+ export const ResCurrency = defineModel('res.currency', {
26
+ access: { 'base.user': ['read'], 'base.admin': ['read', 'write', 'create', 'unlink'] },
27
+ fields: {
28
+ name: f.char({ required: true, size: 3, index: 'unique' }),
29
+ rounding: f.decimal({ scale: 6, required: true, default: '0.01' }),
30
+ decimalPlaces: f.integer({ default: 2 }),
31
+ },
32
+ });
33
+
34
+ export const ResCompany = defineModel('res.company', {
35
+ access: { 'base.user': ['read'], 'base.admin': ['read', 'write', 'create', 'unlink'] },
36
+ fields: { name: f.char({ required: true }), currency: f.many2one('res.currency', { required: true }) },
37
+ });
38
+
39
+ export const base = defineModule({
40
+ name: 'base',
41
+ version: '0.1.0',
42
+ groups: [
43
+ defineGroup({ code: 'base.user', label: 'User' }),
44
+ defineGroup({ code: 'base.admin', label: 'Administrator', implies: ['base.user'] }),
45
+ ],
46
+ models: [ResUsers, ResCurrency, ResCompany],
47
+ });
48
+ `,
49
+ 'migrations/.gitkeep': '',
50
+ };
51
+ /** Writes the starter files under `dir` and returns their paths. @throws {CliError} if any exists. */
52
+ export function initProject(dir) {
53
+ const existing = Object.keys(FILES).filter((f) => existsSync(join(dir, f)));
54
+ if (existing.length > 0) {
55
+ throw new CliError(`${existing.join(', ')} already exist(s) in ${dir}.`, 'shutro init never overwrites files: run it in an empty directory, or remove them first.');
56
+ }
57
+ const written = [];
58
+ for (const [file, content] of Object.entries(FILES)) {
59
+ const path = join(dir, file);
60
+ mkdirSync(dirname(path), { recursive: true });
61
+ writeFileSync(path, content);
62
+ written.push(path);
63
+ }
64
+ return written;
65
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `shutro inspect`: the schema explorer (RFC 0002 §9). Without a model, the modules and their models; with one, its
3
+ * fields (kind, column, origin module), methods with their override chains, computed fields with ranks and
4
+ * dependencies, constraints, access and record rules.
5
+ */
6
+ import type { Registry } from '../core/index.js';
7
+ /** The registry overview: modules in load order and the models each owns or extends. */
8
+ export declare function inspectRegistry(registry: Registry): string;
9
+ /** One model in detail. */
10
+ export declare function inspectModel(registry: Registry, name: string): string;
@@ -0,0 +1,82 @@
1
+ import { CliError } from './errors.js';
2
+ /** The registry overview: modules in load order and the models each owns or extends. */
3
+ export function inspectRegistry(registry) {
4
+ const lines = [`${registry.modules.length} module(s), ${registry.models.size} model(s)`, ''];
5
+ for (const module of registry.modules) {
6
+ const owned = [...registry.models.values()]
7
+ .filter((m) => m.module === module.name)
8
+ .map((m) => m.model.name);
9
+ const extended = [...registry.models.values()]
10
+ .filter((m) => m.extensions.includes(module.name))
11
+ .map((m) => m.model.name);
12
+ lines.push(`${module.name} ${module.version}${module.depends.length > 0 ? ` (depends: ${module.depends.map((d) => d.name).join(', ')})` : ''}`);
13
+ if (owned.length > 0)
14
+ lines.push(` owns: ${owned.join(', ')}`);
15
+ if (extended.length > 0)
16
+ lines.push(` extends: ${extended.join(', ')}`);
17
+ }
18
+ return lines.join('\n');
19
+ }
20
+ /** One model in detail. */
21
+ export function inspectModel(registry, name) {
22
+ if (!registry.has(name)) {
23
+ throw new CliError(`Unknown model '${name}'.`, `Models: ${[...registry.models.keys()].sort().join(', ')}.`);
24
+ }
25
+ const registered = registry.get(name);
26
+ const { model } = registered;
27
+ const d = registry.describe(name);
28
+ const lines = [
29
+ `${name} table ${model.table} owner ${registered.module}${registered.extensions.length > 0 ? ` extended by ${registered.extensions.join(', ')}` : ''}`,
30
+ '',
31
+ 'fields',
32
+ ];
33
+ const width = Math.max(...Object.keys(d.fields).map((k) => k.length));
34
+ for (const [key, field] of Object.entries(d.fields)) {
35
+ const flags = [
36
+ field.required ? 'required' : '',
37
+ field.readonly ? 'readonly' : '',
38
+ field.computed ? (field.store ? 'computed+stored' : 'computed') : '',
39
+ field.translate ? 'translate' : '',
40
+ field['encrypted'] === true ? 'encrypted' : '',
41
+ field.tracking ? 'tracked' : '',
42
+ field.groups.read.length > 0 ? `groups:${field.groups.read.join('|')}` : '',
43
+ ].filter((f) => f !== '');
44
+ const target = typeof field['target'] === 'string' ? ` → ${field['target']}` : '';
45
+ lines.push(` ${key.padEnd(width)} ${`${field.kind}${target}`.padEnd(28)} ${(field.column ?? '-').padEnd(20)} ${field.origin.module.padEnd(14)} ${flags.join(' ')}`);
46
+ }
47
+ const methods = Object.entries(registered.methodLayers);
48
+ if (methods.length > 0) {
49
+ lines.push('', 'methods');
50
+ for (const [method, layers] of methods)
51
+ lines.push(` ${method}: ${layers.map((l) => (l.kind === 'definition' ? l.module : `${l.module}(${l.kind})`)).join(' → ')}`);
52
+ }
53
+ const computed = registry.compute.fields.filter((f) => f.model === name);
54
+ if (computed.length > 0) {
55
+ lines.push('', 'computed');
56
+ for (const f of computed)
57
+ lines.push(` ${f.key} rank ${f.rank} ${f.stored ? 'stored' : 'on load'} depends ${f.paths.map((p) => p.map((s) => s.key).join('.')).join(', ') || '-'}`);
58
+ }
59
+ if (d.constraints.length > 0) {
60
+ lines.push('', 'constraints');
61
+ for (const c of d.constraints)
62
+ lines.push(` ${c.key} depends ${c.depends.join(', ')}`);
63
+ }
64
+ if (d.sqlConstraints.length > 0) {
65
+ lines.push('', 'sql constraints');
66
+ for (const c of d.sqlConstraints)
67
+ lines.push(` ${c.name} ${c.kind} ${c.message}`);
68
+ }
69
+ const access = Object.entries(d.access);
70
+ lines.push('', 'access');
71
+ if (access.length === 0)
72
+ lines.push(' (none: denied to everyone but superuser scopes)');
73
+ for (const [group, perms] of access)
74
+ lines.push(` ${group}: ${perms.join(', ')}`);
75
+ const rules = Object.entries(d.rules);
76
+ if (rules.length > 0) {
77
+ lines.push('', 'rules');
78
+ for (const [key, r] of rules)
79
+ lines.push(` ${key} ${r.groups === 'global' ? 'global' : r.groups.join('|')} ${r.perms.join(',')} ${JSON.stringify(r.domain)}`);
80
+ }
81
+ return lines.join('\n');
82
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Package specifiers written into generated and starter files. The single-package npm build (`shutro`) replaces
3
+ * this module so user code imports `shutro` and `shutro/cli` instead (scripts/pack-npm.ts).
4
+ */
5
+ export declare const CORE_PACKAGE: string;
6
+ export declare const CLI_PACKAGE: string;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Package specifiers written into generated and starter files. The single-package npm build (`shutro`) replaces
3
+ * this module so user code imports `shutro` and `shutro/cli` instead (scripts/pack-npm.ts).
4
+ */
5
+ export const CORE_PACKAGE = 'shutro';
6
+ export const CLI_PACKAGE = 'shutro/cli';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The project a command works on: the config, its modules loaded into a registry, and (when needed) a driver.
3
+ */
4
+ import { type Registry } from '../core/index.js';
5
+ import { type Driver } from '../driver-pg/index.js';
6
+ import { type ShutroConfig } from './config.js';
7
+ /** A loaded project. */
8
+ export interface Project {
9
+ readonly config: ShutroConfig;
10
+ readonly dir: string;
11
+ readonly registry: Registry;
12
+ }
13
+ /** Loads the config and builds the registry of its modules. */
14
+ export declare function loadProject(configFile: string): Promise<Project>;
15
+ /** The database URL: `SHUTRO_DATABASE_URL`, else the config's `database`. */
16
+ export declare function databaseUrl(config: ShutroConfig, env: Readonly<Record<string, string | undefined>>): string;
17
+ /** Runs `fn` with a driver on the project's database and closes it afterwards. */
18
+ export declare function withDriver<T>(url: string, fn: (driver: Driver) => Promise<T>): Promise<T>;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The project a command works on: the config, its modules loaded into a registry, and (when needed) a driver.
3
+ */
4
+ import { buildRegistry } from '../core/index.js';
5
+ import { createDriver } from '../driver-pg/index.js';
6
+ import { loadConfig } from './config.js';
7
+ import { CliError, ModuleSourceError } from './errors.js';
8
+ import { dependant, loadSources } from './generate/generate.js';
9
+ /** Loads the config and builds the registry of its modules. */
10
+ export async function loadProject(configFile) {
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
+ });
16
+ for (const module of registry.modules) {
17
+ if (!sources.has(module.name))
18
+ throw new ModuleSourceError(module.name, dependant(registry, module.name));
19
+ }
20
+ return { config, dir, registry };
21
+ }
22
+ /** The database URL: `SHUTRO_DATABASE_URL`, else the config's `database`. */
23
+ export function databaseUrl(config, env) {
24
+ const url = env['SHUTRO_DATABASE_URL'] ?? config.database;
25
+ if (url === undefined || url === '') {
26
+ throw new CliError('No database is configured.', 'Set SHUTRO_DATABASE_URL, or database: "postgres://..." in shutro.config.ts.');
27
+ }
28
+ return url;
29
+ }
30
+ /** Runs `fn` with a driver on the project's database and closes it afterwards. */
31
+ export async function withDriver(url, fn) {
32
+ const driver = createDriver({ url, max: 2 });
33
+ try {
34
+ return await fn(driver);
35
+ }
36
+ finally {
37
+ await driver.end();
38
+ }
39
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The dependency graph of computed fields (RFC 0008 §7.1): every `depends` path becomes triggers that say which
3
+ * computed field a change reaches and how to walk back to its records; computed fields get a rank so chains compute
4
+ * in order.
5
+ */
6
+ import type { Field } from '../model/field.js';
7
+ import { type AnyModel, type ResolvedConstraint } from '../model/model.js';
8
+ /** One step of a depends path: field `key` of `model`, leading to `target` for relations. */
9
+ export interface PathStep {
10
+ readonly model: string;
11
+ readonly key: string;
12
+ readonly kind: Field['kind'];
13
+ readonly target: string | undefined;
14
+ /** For one2many: the many2one on the target pointing back. */
15
+ readonly inverse: string | undefined;
16
+ }
17
+ /** A computed field and its parsed dependencies. */
18
+ export interface ComputedField {
19
+ readonly model: string;
20
+ readonly key: string;
21
+ readonly stored: boolean;
22
+ /** Identity of the compute: the function, or the method name. One compute may fill several fields. */
23
+ readonly compute: string | ((records: never) => unknown);
24
+ readonly paths: readonly (readonly PathStep[])[];
25
+ /** Dependency depth: 0 when no path touches a computed field. */
26
+ readonly rank: number;
27
+ }
28
+ /** How a change of `(model, key)` reaches a computed field: walk `reverse` from the changed records, last step first. */
29
+ export interface Trigger {
30
+ readonly field: ComputedField;
31
+ /** The steps from the computed field's model down to the changed model (empty when they are the same). */
32
+ readonly reverse: readonly PathStep[];
33
+ }
34
+ /** The built graph (RFC 0008 §9). */
35
+ export interface ComputeGraph {
36
+ readonly fields: readonly ComputedField[];
37
+ /** model → key → the computed fields a change of that key reaches. */
38
+ readonly triggers: ReadonlyMap<string, ReadonlyMap<string, readonly Trigger[]>>;
39
+ field(model: string, key: string): ComputedField | undefined;
40
+ /** Stored computed fields of a model. */
41
+ stored(model: string): readonly ComputedField[];
42
+ /** many2one keys of `model` that are inverses of one2many steps in some path: changing or deleting them moves records between parents. */
43
+ inverseKeys(model: string): ReadonlySet<string>;
44
+ /** Business constraints of `model` that a change of `key` triggers (RFC 0009 §7.1). */
45
+ constraints(model: string, key: string): readonly ResolvedConstraint[];
46
+ }
47
+ type Models = ReadonlyMap<string, {
48
+ readonly model: AnyModel;
49
+ }>;
50
+ /** Builds the graph for the registry's models. @throws {ComputeCycleError} */
51
+ export declare function buildComputeGraph(models: Models): ComputeGraph;
52
+ export {};