shutro 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +99 -2
- package/dist/audit/index.d.ts +59 -0
- package/dist/audit/index.js +96 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +164 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +49 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +84 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +249 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/cli/resolve.d.ts +2 -0
- package/dist/cli/resolve.js +28 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/data/data.d.ts +59 -0
- package/dist/core/data/data.js +119 -0
- package/dist/core/data/load.d.ts +37 -0
- package/dist/core/data/load.js +236 -0
- package/dist/core/env/env.d.ts +468 -0
- package/dist/core/env/env.js +916 -0
- package/dist/core/env/identity.d.ts +43 -0
- package/dist/core/env/identity.js +65 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +256 -0
- package/dist/core/errors.js +360 -0
- package/dist/core/events/events.d.ts +44 -0
- package/dist/core/events/events.js +58 -0
- package/dist/core/events/workers.d.ts +56 -0
- package/dist/core/events/workers.js +155 -0
- package/dist/core/index.d.ts +51 -0
- package/dist/core/index.js +42 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +479 -0
- package/dist/core/model/field.js +461 -0
- package/dist/core/model/generated.d.ts +77 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +387 -0
- package/dist/core/model/model.js +566 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/model/related.d.ts +17 -0
- package/dist/core/model/related.js +60 -0
- package/dist/core/model/typed.d.ts +107 -0
- package/dist/core/model/typed.js +46 -0
- package/dist/core/money/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +68 -0
- package/dist/core/money/fx.js +124 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/aggregate.d.ts +22 -0
- package/dist/core/recordset/aggregate.js +258 -0
- package/dist/core/recordset/audit.d.ts +33 -0
- package/dist/core/recordset/audit.js +262 -0
- package/dist/core/recordset/compute.d.ts +36 -0
- package/dist/core/recordset/compute.js +414 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +31 -0
- package/dist/core/recordset/domain.js +300 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +240 -0
- package/dist/core/recordset/recordset.d.ts +110 -0
- package/dist/core/recordset/recordset.js +789 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +56 -0
- package/dist/core/recordset/security.js +269 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/source.d.ts +9 -0
- package/dist/core/recordset/source.js +19 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +80 -0
- package/dist/core/recordset/types.d.ts +415 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +33 -0
- package/dist/core/recordset/values.js +177 -0
- package/dist/core/recordset/writes.d.ts +42 -0
- package/dist/core/recordset/writes.js +786 -0
- package/dist/core/registry/ddl.d.ts +31 -0
- package/dist/core/registry/ddl.js +174 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +89 -0
- package/dist/core/registry/module.js +98 -0
- package/dist/core/registry/registry.d.ts +130 -0
- package/dist/core/registry/registry.js +591 -0
- package/dist/core/security/runtime.d.ts +102 -0
- package/dist/core/security/runtime.js +232 -0
- package/dist/driver-pg/driver.d.ts +88 -0
- package/dist/driver-pg/driver.js +177 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +233 -0
- package/dist/security/index.d.ts +147 -0
- package/dist/security/index.js +278 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +47 -0
- package/dist/sql/tag.js +123 -0
- package/package.json +82 -4
|
@@ -0,0 +1,84 @@
|
|
|
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 { allowJsSpecifiersForTs } from '../resolve.js';
|
|
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) {
|
|
14
|
+
const sources = new Map();
|
|
15
|
+
for (const file of files) {
|
|
16
|
+
if (!existsSync(file)) {
|
|
17
|
+
throw new ConfigError(`Module file ${file} does not exist.`, 'Check `modules` in shutro.config.ts.');
|
|
18
|
+
}
|
|
19
|
+
allowJsSpecifiersForTs();
|
|
20
|
+
const ns = (await import(pathToFileURL(file).href));
|
|
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).');
|
|
24
|
+
}
|
|
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.');
|
|
29
|
+
}
|
|
30
|
+
sources.set(module.name, { module, file, exportName });
|
|
31
|
+
}
|
|
32
|
+
return sources;
|
|
33
|
+
}
|
|
34
|
+
/** The module that pulled in `missing` (for error messages). */
|
|
35
|
+
export function dependant(registry, missing) {
|
|
36
|
+
const reaches = (m) => m.depends.some((d) => d.name === missing || reaches(d));
|
|
37
|
+
return registry.modules.find((m) => reaches(m))?.name ?? missing;
|
|
38
|
+
}
|
|
39
|
+
/** Generates the per-module views and the application view described by `config`. */
|
|
40
|
+
export async function generate(options) {
|
|
41
|
+
const { config, cwd } = options;
|
|
42
|
+
const sources = await loadSources(config.modules);
|
|
43
|
+
const all = buildRegistry({ modules: [...sources.values()].map((s) => s.module) });
|
|
44
|
+
for (const module of all.modules) {
|
|
45
|
+
if (!sources.has(module.name))
|
|
46
|
+
throw new ModuleSourceError(module.name, dependant(all, module.name));
|
|
47
|
+
}
|
|
48
|
+
const rendered = [];
|
|
49
|
+
for (const module of all.modules) {
|
|
50
|
+
const source = sources.get(module.name);
|
|
51
|
+
const view = buildRegistry({ modules: [source.module] });
|
|
52
|
+
const outDir = outDirOf(source.file);
|
|
53
|
+
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.`;
|
|
54
|
+
rendered.push({
|
|
55
|
+
path: join(outDir, 'schema.d.ts'),
|
|
56
|
+
content: renderSchema(view, sources, outDir, title),
|
|
57
|
+
});
|
|
58
|
+
rendered.push({
|
|
59
|
+
path: join(outDir, 'bindings.ts'),
|
|
60
|
+
content: renderBindings(view, module.name),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
if (config.app !== undefined) {
|
|
64
|
+
const outDir = join(config.app, '.shutro');
|
|
65
|
+
const title = `Application view: every installed module (${all.loadOrder.join(', ')}).`;
|
|
66
|
+
rendered.push({
|
|
67
|
+
path: join(outDir, 'schema.d.ts'),
|
|
68
|
+
content: renderSchema(all, sources, outDir, title),
|
|
69
|
+
});
|
|
70
|
+
rendered.push({ path: join(outDir, 'index.ts'), content: renderAppIndex(all) });
|
|
71
|
+
}
|
|
72
|
+
const files = [];
|
|
73
|
+
for (const { path, content } of rendered) {
|
|
74
|
+
const target = options.outRoot === undefined ? path : join(options.outRoot, relative(cwd, path));
|
|
75
|
+
const current = existsSync(target) ? readFileSync(target, 'utf8') : undefined;
|
|
76
|
+
const status = current === undefined ? 'created' : current === content ? 'unchanged' : 'updated';
|
|
77
|
+
if (status !== 'unchanged' && options.check !== true) {
|
|
78
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
79
|
+
writeFileSync(target, content);
|
|
80
|
+
}
|
|
81
|
+
files.push({ path: target, content, status });
|
|
82
|
+
}
|
|
83
|
+
return { files, changed: files.filter((f) => f.status !== 'unchanged'), modules: all.loadOrder };
|
|
84
|
+
}
|
|
@@ -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,249 @@
|
|
|
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
|
+
// Only what the generated types depend on (feedback #17): field types, origins and transitions. Labels, help,
|
|
12
|
+
// indexes, security metadata and module versions change no type and must not churn the files.
|
|
13
|
+
const names = [...registry.models.keys()].sort();
|
|
14
|
+
const definitions = names.map((name) => {
|
|
15
|
+
const registered = registry.get(name);
|
|
16
|
+
return {
|
|
17
|
+
name,
|
|
18
|
+
module: registered.module,
|
|
19
|
+
extensions: registered.extensions,
|
|
20
|
+
fields: Object.entries(registered.model.fields).map(([key, field]) => [
|
|
21
|
+
key,
|
|
22
|
+
fieldType(name, key, field),
|
|
23
|
+
registered.fieldOrigins[key] ?? null,
|
|
24
|
+
]),
|
|
25
|
+
transitions: transitionNames(registered),
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
return createHash('sha256').update(JSON.stringify(definitions)).digest('hex').slice(0, 16);
|
|
29
|
+
}
|
|
30
|
+
/** Every transition of the model's state fields, extensions' `transitionsAdd` included (feedback #18). */
|
|
31
|
+
function transitionNames(registered) {
|
|
32
|
+
const names = new Set();
|
|
33
|
+
for (const field of Object.values(registered.model.fields)) {
|
|
34
|
+
const transitions = field.transitions;
|
|
35
|
+
if (field.kind === 'state' && transitions !== undefined)
|
|
36
|
+
for (const name of Object.keys(transitions))
|
|
37
|
+
names.add(name);
|
|
38
|
+
}
|
|
39
|
+
return [...names].sort();
|
|
40
|
+
}
|
|
41
|
+
/** `sale.order.line` → `SaleOrderLine`. */
|
|
42
|
+
export function interfaceName(model) {
|
|
43
|
+
return model
|
|
44
|
+
.split(/[._]/)
|
|
45
|
+
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
|
46
|
+
.join('');
|
|
47
|
+
}
|
|
48
|
+
function quote(value) {
|
|
49
|
+
return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
|
|
50
|
+
}
|
|
51
|
+
function union(values) {
|
|
52
|
+
return values.length === 0 ? 'never' : values.map(quote).join(' | ');
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The option literal that reproduces the field's phantom flags through `FlagsOf`. Properties are `readonly`, as
|
|
56
|
+
* the builders' `const` type parameters infer them: TypeScript's identity relation tells the two apart, and the
|
|
57
|
+
* generated field must be identical to the declared one.
|
|
58
|
+
*/
|
|
59
|
+
function flagOptions(field) {
|
|
60
|
+
const parts = [];
|
|
61
|
+
if (field.required)
|
|
62
|
+
parts.push('required: true');
|
|
63
|
+
if (field.readonly)
|
|
64
|
+
parts.push('readonly: true');
|
|
65
|
+
if (field.default !== undefined)
|
|
66
|
+
parts.push('default: true');
|
|
67
|
+
if (field.computed) {
|
|
68
|
+
parts.push(`compute: ${typeof field.compute === 'string' ? quote(field.compute) : 'true'}`);
|
|
69
|
+
if (field.store)
|
|
70
|
+
parts.push('store: true');
|
|
71
|
+
}
|
|
72
|
+
if (field.inverse !== undefined)
|
|
73
|
+
parts.push('inverse: true');
|
|
74
|
+
if (field.translate)
|
|
75
|
+
parts.push('translate: true');
|
|
76
|
+
if (field.sequence !== undefined)
|
|
77
|
+
parts.push('sequence: true');
|
|
78
|
+
return parts.length === 0 ? '' : `{ ${parts.map((p) => `readonly ${p}`).join('; ')} }`;
|
|
79
|
+
}
|
|
80
|
+
function generic(name, ...args) {
|
|
81
|
+
const given = args.filter((a) => a !== '');
|
|
82
|
+
return given.length === 0 ? `F.${name}` : `F.${name}<${given.join(', ')}>`;
|
|
83
|
+
}
|
|
84
|
+
function selectionValues(field) {
|
|
85
|
+
const selection = field.selection;
|
|
86
|
+
if (!Array.isArray(selection))
|
|
87
|
+
return 'string';
|
|
88
|
+
return union(selection.map(([value]) => value));
|
|
89
|
+
}
|
|
90
|
+
/** The `F.*` type of one field. */
|
|
91
|
+
export function fieldType(model, key, field) {
|
|
92
|
+
const o = flagOptions(field);
|
|
93
|
+
const target = field.target ?? '';
|
|
94
|
+
switch (field.kind) {
|
|
95
|
+
case 'bigint':
|
|
96
|
+
return key === 'id' ? generic('Id', quote(model)) : generic('Bigint', o);
|
|
97
|
+
case 'char':
|
|
98
|
+
return generic('Char', o);
|
|
99
|
+
case 'text':
|
|
100
|
+
return generic('Text', o);
|
|
101
|
+
case 'html':
|
|
102
|
+
return generic('Html', o);
|
|
103
|
+
case 'boolean':
|
|
104
|
+
return generic('Bool', o);
|
|
105
|
+
case 'integer':
|
|
106
|
+
return generic('Integer', o);
|
|
107
|
+
case 'float':
|
|
108
|
+
return generic('Float', o);
|
|
109
|
+
case 'decimal':
|
|
110
|
+
return generic('Decimal', o);
|
|
111
|
+
case 'monetary':
|
|
112
|
+
return generic('Monetary', quote(field.currencyField), o);
|
|
113
|
+
case 'quantity':
|
|
114
|
+
return generic('Quantity', quote(field.uomField), o);
|
|
115
|
+
case 'selection':
|
|
116
|
+
return generic('Selection', selectionValues(field), o);
|
|
117
|
+
case 'state':
|
|
118
|
+
return generic('State', selectionValues(field), o);
|
|
119
|
+
case 'json':
|
|
120
|
+
return generic('Json', o === '' ? '' : 'unknown', o);
|
|
121
|
+
case 'binary':
|
|
122
|
+
return generic('Binary', o);
|
|
123
|
+
case 'date':
|
|
124
|
+
return generic('DateOnly', o);
|
|
125
|
+
case 'datetime':
|
|
126
|
+
return generic('Datetime', o);
|
|
127
|
+
case 'many2one':
|
|
128
|
+
return generic('Many2one', quote(target), o);
|
|
129
|
+
case 'one2many':
|
|
130
|
+
return generic('One2many', quote(target), o);
|
|
131
|
+
case 'many2many':
|
|
132
|
+
return generic('Many2many', quote(target), o);
|
|
133
|
+
default:
|
|
134
|
+
throw new Error(`Unknown field kind ${JSON.stringify(field.kind)} on ${model}.${key}.`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Import specifier of `file` from a file in `fromDir`, in ESM spelling (`../module.js`). */
|
|
138
|
+
export function importSpecifier(fromDir, file) {
|
|
139
|
+
const spec = relative(fromDir, file).replace(/\\/g, '/').replace(/\.ts$/, '.js');
|
|
140
|
+
return spec.startsWith('.') ? spec : `./${spec}`;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The methods interface of a model: it extends each contributing module's declared methods and lists the
|
|
144
|
+
* transitions (extensions' `transitionsAdd` included). A named interface, because TypeScript resolves interface
|
|
145
|
+
* bases lazily: typed definition callbacks in a module can then name the view without depending on the module's own
|
|
146
|
+
* type (TS7022, feedback #1).
|
|
147
|
+
*/
|
|
148
|
+
function methodsInterface(registered, sources, outDir) {
|
|
149
|
+
const contributors = [registered.module, ...registered.extensions];
|
|
150
|
+
const bases = contributors.map((name) => {
|
|
151
|
+
const source = sources.get(name);
|
|
152
|
+
if (source === undefined)
|
|
153
|
+
throw new Error(`No source for module '${name}'.`);
|
|
154
|
+
const spec = importSpecifier(outDir, source.file);
|
|
155
|
+
return `F.Methods<typeof import(${quote(spec)}).${source.exportName}, ${quote(registered.model.name)}>`;
|
|
156
|
+
});
|
|
157
|
+
const name = `${interfaceName(registered.model.name)}Methods`;
|
|
158
|
+
return [
|
|
159
|
+
`/** Methods of \`${registered.model.name}\`: declared ones and transitions. */`,
|
|
160
|
+
`export interface ${name} extends ${bases.join(', ')} {`,
|
|
161
|
+
...transitionNames(registered).map((t) => ` readonly ${quote(t)}: () => Promise<void>;`),
|
|
162
|
+
'}',
|
|
163
|
+
];
|
|
164
|
+
}
|
|
165
|
+
/** Renders `schema.d.ts` for a registry (a module view or the application view). */
|
|
166
|
+
export function renderSchema(registry, sources, outDir, title) {
|
|
167
|
+
const names = [...registry.models.keys()].sort();
|
|
168
|
+
const lines = [
|
|
169
|
+
`${HEADER} definitions-hash: ${definitionsHash(registry)}`,
|
|
170
|
+
`// ${title}`,
|
|
171
|
+
`import type { F } from '${CORE_PACKAGE}';`,
|
|
172
|
+
'',
|
|
173
|
+
'/** Model name → model type (RFC 0002 §7.7). */',
|
|
174
|
+
'export interface SchemaView {',
|
|
175
|
+
...names.map((name) => ` readonly ${quote(name)}: ${interfaceName(name)};`),
|
|
176
|
+
'}',
|
|
177
|
+
];
|
|
178
|
+
for (const name of names) {
|
|
179
|
+
const registered = registry.get(name);
|
|
180
|
+
const { model } = registered;
|
|
181
|
+
const origin = registered.extensions.length === 0
|
|
182
|
+
? `owner: ${registered.module}`
|
|
183
|
+
: `owner: ${registered.module}; extended by: ${registered.extensions.join(', ')}`;
|
|
184
|
+
lines.push('', `/** \`${name}\` (${origin}). */`, `export interface ${interfaceName(name)} {`);
|
|
185
|
+
lines.push(` readonly name: ${quote(name)};`, ' readonly fields: {');
|
|
186
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
187
|
+
const from = registered.fieldOrigins[key];
|
|
188
|
+
const comment = from === undefined || from === registered.module ? '' : ` // ${from}`;
|
|
189
|
+
lines.push(` readonly ${key}: ${fieldType(name, key, field)};${comment}`);
|
|
190
|
+
}
|
|
191
|
+
lines.push(' };', ` readonly methods: ${interfaceName(name)}Methods;`, '}');
|
|
192
|
+
lines.push('', ...methodsInterface(registered, sources, outDir));
|
|
193
|
+
}
|
|
194
|
+
return `${lines.join('\n')}\n`;
|
|
195
|
+
}
|
|
196
|
+
const ALIASES = [
|
|
197
|
+
`import type { DefaultLoaded, Env as CoreEnv, RecordSet as CoreRecordSet, Shutro as CoreShutro } from '${CORE_PACKAGE}';`,
|
|
198
|
+
"import type { SchemaView } from './schema.js';",
|
|
199
|
+
'',
|
|
200
|
+
'export type { SchemaView };',
|
|
201
|
+
'/** Every model visible in this view. */',
|
|
202
|
+
'export type ModelName = keyof SchemaView & string;',
|
|
203
|
+
'/** `Env` typed to this view. */',
|
|
204
|
+
'export type Env = CoreEnv<SchemaView>;',
|
|
205
|
+
'/** `Shutro` typed to this view. */',
|
|
206
|
+
'export type Shutro = CoreShutro<SchemaView>;',
|
|
207
|
+
'/** A recordset of `M`, with the default loaded shape unless `L` is given. */',
|
|
208
|
+
'export type Records<M extends ModelName, L = DefaultLoaded<SchemaView, M>> = CoreRecordSet<SchemaView, M, L>;',
|
|
209
|
+
];
|
|
210
|
+
/** Renders `bindings.ts` for a module: the definition API plus aliases typed to its view. */
|
|
211
|
+
export function renderBindings(registry, module) {
|
|
212
|
+
return `${[
|
|
213
|
+
`${HEADER} definitions-hash: ${definitionsHash(registry)}`,
|
|
214
|
+
`// Bindings of module \`${module}\`: import the definition API from here to get types scoped to what it can see.`,
|
|
215
|
+
`export { defineModel, defineModule, extendModel, f, replace } from '${CORE_PACKAGE}';`,
|
|
216
|
+
`import { type DefinitionHelpers, definitions } from '${CORE_PACKAGE}';`,
|
|
217
|
+
...ALIASES,
|
|
218
|
+
'',
|
|
219
|
+
"/** Definition callbacks typed against this module's view: no casts in computes, checks, onchange, methods. */",
|
|
220
|
+
'const helpers: DefinitionHelpers<SchemaView> = definitions<SchemaView>();',
|
|
221
|
+
"export const compute: DefinitionHelpers<SchemaView>['compute'] = helpers.compute;",
|
|
222
|
+
"export const check: DefinitionHelpers<SchemaView>['check'] = helpers.check;",
|
|
223
|
+
"export const onchange: DefinitionHelpers<SchemaView>['onchange'] = helpers.onchange;",
|
|
224
|
+
"export const records: DefinitionHelpers<SchemaView>['records'] = helpers.records;",
|
|
225
|
+
"export const method: DefinitionHelpers<SchemaView>['method'] = helpers.method;",
|
|
226
|
+
"/** Module data (RFC 0017): records, overrides of dependencies' records, and references, typed like creates. */",
|
|
227
|
+
"export const record: DefinitionHelpers<SchemaView>['record'] = helpers.record;",
|
|
228
|
+
"export const override: DefinitionHelpers<SchemaView>['override'] = helpers.override;",
|
|
229
|
+
"export const ref: DefinitionHelpers<SchemaView>['ref'] = helpers.ref;",
|
|
230
|
+
].join('\n')}\n`;
|
|
231
|
+
}
|
|
232
|
+
/** Renders the application's `index.ts`: `createShutro` typed to the full view. */
|
|
233
|
+
export function renderAppIndex(registry) {
|
|
234
|
+
return `${[
|
|
235
|
+
`${HEADER} definitions-hash: ${definitionsHash(registry)}`,
|
|
236
|
+
'// Application view: every installed module. Build the registry from the same modules and pass it here.',
|
|
237
|
+
`import { createShutro as coreCreateShutro, type Registry, type ShutroOptions } from '${CORE_PACKAGE}';`,
|
|
238
|
+
...ALIASES,
|
|
239
|
+
'',
|
|
240
|
+
'/** `createShutro` whose environments are typed to the application view. */',
|
|
241
|
+
"export function createShutro(options: Omit<ShutroOptions<SchemaView>, 'registry'> & { readonly registry: Registry }): Shutro {",
|
|
242
|
+
' return coreCreateShutro<SchemaView>(options as ShutroOptions<SchemaView>);',
|
|
243
|
+
'}',
|
|
244
|
+
].join('\n')}\n`;
|
|
245
|
+
}
|
|
246
|
+
/** Directory of the generated files of a module file. */
|
|
247
|
+
export function outDirOf(file) {
|
|
248
|
+
return `${dirname(file)}/.shutro`;
|
|
249
|
+
}
|
|
@@ -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';
|
package/dist/cli/init.js
ADDED
|
@@ -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'] }, // administrators need no grant
|
|
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'] }, // administrators need no grant
|
|
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'] }, // administrators need no grant
|
|
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'], administrator: true }),
|
|
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,28 @@
|
|
|
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.
|
|
5
|
+
*/
|
|
6
|
+
import { registerHooks } from 'node:module';
|
|
7
|
+
let registered = false;
|
|
8
|
+
/** Registers the `.js` → `.ts` fallback once per process. */
|
|
9
|
+
export function allowJsSpecifiersForTs() {
|
|
10
|
+
if (registered)
|
|
11
|
+
return;
|
|
12
|
+
registered = true;
|
|
13
|
+
registerHooks({
|
|
14
|
+
resolve(specifier, context, nextResolve) {
|
|
15
|
+
try {
|
|
16
|
+
return nextResolve(specifier, context);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
const relative = specifier.startsWith('./') || specifier.startsWith('../');
|
|
20
|
+
const fromTs = context.parentURL?.endsWith('.ts') === true;
|
|
21
|
+
const missing = error.code === 'ERR_MODULE_NOT_FOUND';
|
|
22
|
+
if (relative && fromTs && missing && specifier.endsWith('.js'))
|
|
23
|
+
return nextResolve(`${specifier.slice(0, -3)}.ts`, context);
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
}
|