pg-codegen 5.10.11 → 5.12.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/README.md +89 -57
- package/cli.d.ts +9 -0
- package/cli.js +115 -0
- package/emit/babel.d.ts +11 -0
- package/emit/babel.js +81 -0
- package/emit/barrel.d.ts +4 -0
- package/emit/barrel.js +24 -0
- package/emit/enums.d.ts +6 -0
- package/emit/enums.js +45 -0
- package/emit/record.d.ts +6 -0
- package/emit/record.js +238 -0
- package/esm/cli.js +110 -0
- package/esm/emit/babel.js +36 -0
- package/esm/emit/barrel.js +18 -0
- package/esm/emit/enums.js +37 -0
- package/esm/emit/record.js +234 -0
- package/esm/generate.js +63 -0
- package/esm/index.js +5 -69
- package/esm/ir.js +152 -0
- package/generate.d.ts +20 -0
- package/generate.js +74 -0
- package/index.d.ts +5 -1
- package/index.js +17 -72
- package/ir.d.ts +47 -0
- package/ir.js +156 -0
- package/package.json +12 -11
- package/codegen/codegen.d.ts +0 -7
- package/codegen/codegen.js +0 -162
- package/codegen/namespaces.d.ts +0 -7
- package/codegen/namespaces.js +0 -110
- package/esm/codegen/codegen.js +0 -122
- package/esm/codegen/namespaces.js +0 -70
- package/esm/introspect.js +0 -26
- package/esm/query.js +0 -420
- package/esm/types.js +0 -1
- package/introspect.d.ts +0 -11
- package/introspect.js +0 -30
- package/query.d.ts +0 -5
- package/query.js +0 -424
- package/types.d.ts +0 -128
- package/types.js +0 -2
package/README.md
CHANGED
|
@@ -12,31 +12,31 @@
|
|
|
12
12
|
<a href="https://www.npmjs.com/package/pg-codegen"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=postgres%2Fpg-codegen%2Fpackage.json"/></a>
|
|
13
13
|
</p>
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
Type-safe TypeScript from a live PostgreSQL schema: application and row types, runtime decoders, serializers, column metadata and enum unions — one tree-shakable module per table.
|
|
16
16
|
|
|
17
|
-
>
|
|
17
|
+
> A database row arrives as `unknown`. `pg-codegen` is what turns it into a value TypeScript can trust, without a hand-written `as string` in sight.
|
|
18
18
|
|
|
19
19
|
---
|
|
20
20
|
|
|
21
|
-
## ✨
|
|
21
|
+
## ✨ What it generates
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
Pulls schema structure using native SQL introspection — no GraphQL required.
|
|
23
|
+
For every table, view, materialized view and partitioned table in the schemas you name, one module:
|
|
25
24
|
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
| Export | What it is |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `AgentRuns` | application shape, camelCase |
|
|
28
|
+
| `AgentRunsRow` | database row shape, snake_case |
|
|
29
|
+
| `AGENT_RUNS_TABLE` | `schema`, `name`, `qualifiedName`, `columns`, `primaryKey`, `columnByField` |
|
|
30
|
+
| `AGENT_RUNS_FIELDS` | one decoder per column, for projections |
|
|
31
|
+
| `decodeAgentRuns` | decode an untrusted camelCase envelope (a wire payload, a parsed body) |
|
|
32
|
+
| `decodeAgentRunsRow` | decode an untrusted database row |
|
|
33
|
+
| `agentRunsFromRow` | row → application shape |
|
|
34
|
+
| `decodeAgentRunsFromRow` | both, composed |
|
|
35
|
+
| `serializeAgentRuns` | `Partial<AgentRuns>` → `Partial<AgentRunsRow>` for INSERT/UPDATE |
|
|
28
36
|
|
|
29
|
-
|
|
30
|
-
Writes files into `schemas/<schema>.ts`, grouped and re-exported from an `index.ts`.
|
|
37
|
+
Plus an `enums.ts` per schema: a literal union, a `readonly` value list and `as*`/`require*` checkers for every PostgreSQL enum a column references.
|
|
31
38
|
|
|
32
|
-
|
|
33
|
-
Supports `UUID`, `Timestamp`, `Boolean`, `Text`, `Int`, and nullable detection.
|
|
34
|
-
|
|
35
|
-
🪴 **Auto Imports from \_common.ts**
|
|
36
|
-
Deduplicates and imports shared scalar types intelligently.
|
|
37
|
-
|
|
38
|
-
🧪 **Snapshot-Ready for Testing**
|
|
39
|
-
Babel AST-based output is stable and perfect for inline snapshot tests.
|
|
39
|
+
Every decoder is backed by [`@constructive-io/coerce`](../../packages/coerce): a NOT NULL column throws `CoerceError` naming the offending column, a nullable column answers `null`, and the text forms `pg` returns for `int8`/`numeric` are parsed rather than passed through as strings. Nothing is silently coerced across types, so a malformed row cannot become a default value.
|
|
40
40
|
|
|
41
41
|
## 🛠️ Install
|
|
42
42
|
|
|
@@ -46,57 +46,89 @@ npm install pg-codegen
|
|
|
46
46
|
|
|
47
47
|
## 🚀 Usage
|
|
48
48
|
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const rows = await getIntrospectionRows({
|
|
54
|
-
client: pgClient,
|
|
55
|
-
introspectionOptions: {
|
|
56
|
-
pgLegacyFunctionsOnly: false,
|
|
57
|
-
pgIgnoreRBAC: true
|
|
58
|
-
},
|
|
59
|
-
namespacesToIntrospect: ['my_schema'],
|
|
60
|
-
includeExtensions: false
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
const output = generateCodeTree(rows, {
|
|
64
|
-
includeUUID: true,
|
|
65
|
-
includeTimestamps: true
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
// Example: write output['schemas/my_schema.ts'] to disk
|
|
49
|
+
```bash
|
|
50
|
+
pg-codegen --schema app_public --out src/generated
|
|
51
|
+
pg-codegen --schema app_public,app_jobs --out src/generated
|
|
52
|
+
pg-codegen --schema app_public --out src/generated --check
|
|
69
53
|
```
|
|
70
54
|
|
|
71
|
-
|
|
55
|
+
`--check` re-introspects and compares against the committed output, exiting non-zero on drift — run it in CI so generated types cannot go stale against a migration.
|
|
72
56
|
|
|
73
|
-
|
|
74
|
-
// schemas/_common.ts
|
|
75
|
-
export type UUID = string;
|
|
76
|
-
export type Timestamp = string;
|
|
57
|
+
Connection settings come from the standard PG environment (`PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`) via `pg-env`.
|
|
77
58
|
|
|
78
|
-
|
|
79
|
-
import { UUID, Timestamp } from './_common';
|
|
59
|
+
Programmatically — for a schema whose physical name is per-tenant, say, where you want to rewrite it to a stable alias before emitting:
|
|
80
60
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
61
|
+
```ts
|
|
62
|
+
import { Client } from 'pg';
|
|
63
|
+
import { introspect } from 'introspectron';
|
|
64
|
+
import { buildIr, emitFileTree, writeFileTree, checkFileTree } from 'pg-codegen';
|
|
65
|
+
|
|
66
|
+
const introspection = await introspect(client, { schemas: [physicalSchema] });
|
|
67
|
+
const ir = buildIr(introspection, { schemas: [physicalSchema] });
|
|
68
|
+
for (const schema of ir.schemas) {
|
|
69
|
+
schema.name = 'agent';
|
|
70
|
+
for (const table of schema.tables) table.schema = 'agent';
|
|
85
71
|
}
|
|
72
|
+
await writeFileTree(outDir, emitFileTree(ir));
|
|
73
|
+
```
|
|
86
74
|
|
|
87
|
-
|
|
88
|
-
id: UUID;
|
|
89
|
-
email: string;
|
|
90
|
-
created_at: Timestamp;
|
|
75
|
+
## 📟 Example output
|
|
91
76
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
77
|
+
```ts
|
|
78
|
+
// generated/codegen_test/agent-runs.ts
|
|
79
|
+
export interface AgentRuns {
|
|
80
|
+
id: string;
|
|
81
|
+
threadId: string;
|
|
82
|
+
status: RunStatus;
|
|
83
|
+
tags: string[];
|
|
84
|
+
retrySeconds: number[] | null;
|
|
85
|
+
lastEventSeq: number;
|
|
86
|
+
finishedAt: string | null;
|
|
97
87
|
}
|
|
88
|
+
|
|
89
|
+
export const decodeAgentRunsFromRow = (value: unknown, label = 'codegen_test.agent_runs'): AgentRuns =>
|
|
90
|
+
agentRunsFromRow(decodeAgentRunsRow(value, label));
|
|
98
91
|
```
|
|
99
92
|
|
|
93
|
+
Consume per table, so a bundle carries only the tables it touches:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { decodeAgentRunsFromRow } from '@my/db-types/codegen_test/agent-runs';
|
|
97
|
+
|
|
98
|
+
const { rows } = await db.query('SELECT * FROM agent_runs WHERE id = $1', [id]);
|
|
99
|
+
const run = decodeAgentRunsFromRow(rows[0]); // AgentRuns, or CoerceError naming the column
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Projections
|
|
103
|
+
|
|
104
|
+
A joined or partial SELECT is not a whole row, so a record decoder would reject it. Decode it column by column instead — `FIELDS` takes an overridable label so the error names the alias the query actually used:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { AGENT_RUNS_FIELDS } from '@my/db-types/codegen_test/agent-runs';
|
|
108
|
+
import { THREADS_FIELDS } from '@my/db-types/codegen_test/threads';
|
|
109
|
+
|
|
110
|
+
const { rows } = await db.query(`
|
|
111
|
+
SELECT r.id, r.status, t.title AS thread_title
|
|
112
|
+
FROM agent_runs r JOIN threads t ON t.id = r.thread_id
|
|
113
|
+
`);
|
|
114
|
+
|
|
115
|
+
const summaries = rows.map(row => ({
|
|
116
|
+
id: AGENT_RUNS_FIELDS.id(row.id),
|
|
117
|
+
status: AGENT_RUNS_FIELDS.status(row.status),
|
|
118
|
+
threadTitle: THREADS_FIELDS.title(row.thread_title, 'run_summary.thread_title')
|
|
119
|
+
}));
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## 🧱 How it works
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
PostgreSQL → introspectron → IR (ir.ts) → emitters (emit/*) → file tree
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`buildIr` normalizes an introspection result into the shape every emitter consumes: columns with a resolved scalar, nullability, defaults, primary keys, and the enums they reference. Domains are unwrapped to their base type, arrays carry their element scalar, and a type with no mapping degrades to `unknown` rather than to `any` — the generator never claims to know a shape it does not.
|
|
129
|
+
|
|
130
|
+
Emission is Babel AST rather than string templates, so output is stable enough to snapshot and to diff in `--check`.
|
|
131
|
+
|
|
100
132
|
---
|
|
101
133
|
|
|
102
134
|
## Education and Tutorials
|
package/cli.d.ts
ADDED
package/cli.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.main = exports.parseArgs = void 0;
|
|
5
|
+
/**
|
|
6
|
+
* pg-codegen CLI.
|
|
7
|
+
*
|
|
8
|
+
* pg-codegen --schema app_public --out src/generated
|
|
9
|
+
* pg-codegen --schema app_public --schema app_jobs --out src/generated --check
|
|
10
|
+
*
|
|
11
|
+
* Connection settings come from the standard PG environment (pg-env):
|
|
12
|
+
* PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE.
|
|
13
|
+
*/
|
|
14
|
+
const pg_1 = require("pg");
|
|
15
|
+
const pg_env_1 = require("pg-env");
|
|
16
|
+
const generate_1 = require("./generate");
|
|
17
|
+
const USAGE = `Usage: pg-codegen --schema <name> [--schema <name> ...] --out <dir> [--check]
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
--schema <name> A schema to generate records for (repeatable, or comma-separated)
|
|
21
|
+
--out <dir> Directory the generated files are written to (or compared against)
|
|
22
|
+
--check Compare against the files already in --out and exit non-zero on drift
|
|
23
|
+
--help Show this message
|
|
24
|
+
|
|
25
|
+
Connection settings come from the standard PG environment variables.`;
|
|
26
|
+
const parseArgs = (argv) => {
|
|
27
|
+
const schemas = [];
|
|
28
|
+
let out = '';
|
|
29
|
+
let check = false;
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
const arg = argv[i];
|
|
32
|
+
switch (arg) {
|
|
33
|
+
case '--schema': {
|
|
34
|
+
const value = argv[++i];
|
|
35
|
+
if (!value)
|
|
36
|
+
throw new Error('--schema requires a value');
|
|
37
|
+
schemas.push(...value.split(',').map(name => name.trim()).filter(Boolean));
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
case '--out': {
|
|
41
|
+
const value = argv[++i];
|
|
42
|
+
if (!value)
|
|
43
|
+
throw new Error('--out requires a value');
|
|
44
|
+
out = value;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
case '--check':
|
|
48
|
+
check = true;
|
|
49
|
+
break;
|
|
50
|
+
case '--help':
|
|
51
|
+
case '-h':
|
|
52
|
+
console.log(USAGE);
|
|
53
|
+
process.exit(0);
|
|
54
|
+
break;
|
|
55
|
+
default:
|
|
56
|
+
throw new Error(`Unknown argument: ${arg}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (schemas.length === 0)
|
|
60
|
+
throw new Error('At least one --schema is required');
|
|
61
|
+
if (!out)
|
|
62
|
+
throw new Error('--out is required');
|
|
63
|
+
return { schemas, out, check };
|
|
64
|
+
};
|
|
65
|
+
exports.parseArgs = parseArgs;
|
|
66
|
+
const main = async (argv) => {
|
|
67
|
+
let args;
|
|
68
|
+
try {
|
|
69
|
+
args = (0, exports.parseArgs)(argv);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
console.error(error.message);
|
|
73
|
+
console.error();
|
|
74
|
+
console.error(USAGE);
|
|
75
|
+
return 2;
|
|
76
|
+
}
|
|
77
|
+
const pg = (0, pg_env_1.getPgEnvOptions)();
|
|
78
|
+
const client = new pg_1.Client({
|
|
79
|
+
host: pg.host,
|
|
80
|
+
port: pg.port,
|
|
81
|
+
user: pg.user,
|
|
82
|
+
password: pg.password,
|
|
83
|
+
database: pg.database
|
|
84
|
+
});
|
|
85
|
+
await client.connect();
|
|
86
|
+
try {
|
|
87
|
+
const files = await (0, generate_1.generate)(client, { schemas: args.schemas });
|
|
88
|
+
if (args.check) {
|
|
89
|
+
const report = await (0, generate_1.checkFileTree)(args.out, files);
|
|
90
|
+
if ((0, generate_1.isClean)(report)) {
|
|
91
|
+
console.log(`pg-codegen: ${Object.keys(files).length} files up to date in ${args.out}`);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
for (const file of report.missing)
|
|
95
|
+
console.error(`missing: ${file}`);
|
|
96
|
+
for (const file of report.stale)
|
|
97
|
+
console.error(`stale: ${file}`);
|
|
98
|
+
console.error('pg-codegen --check failed: regenerate with the same command without --check');
|
|
99
|
+
return 1;
|
|
100
|
+
}
|
|
101
|
+
await (0, generate_1.writeFileTree)(args.out, files);
|
|
102
|
+
console.log(`pg-codegen: wrote ${Object.keys(files).length} files to ${args.out}`);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
await client.end();
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
exports.main = main;
|
|
110
|
+
if (require.main === module) {
|
|
111
|
+
(0, exports.main)(process.argv.slice(2)).then(code => process.exit(code), error => {
|
|
112
|
+
console.error(error);
|
|
113
|
+
process.exit(1);
|
|
114
|
+
});
|
|
115
|
+
}
|
package/emit/babel.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
export { t };
|
|
3
|
+
export declare const HEADER: string;
|
|
4
|
+
export declare const generateCode: (statements: t.Statement[]) => string;
|
|
5
|
+
/** Attach a JSDoc block as a leading comment. */
|
|
6
|
+
export declare const withJsDoc: <T extends t.Statement>(node: T, text: string) => T;
|
|
7
|
+
export declare const namedImport: (names: string[], source: string) => t.ImportDeclaration;
|
|
8
|
+
export declare const asConst: (expression: t.Expression) => t.TSAsExpression;
|
|
9
|
+
export declare const exportConst: (name: string, init: t.Expression, typeAnnotation?: t.TSType) => t.ExportNamedDeclaration;
|
|
10
|
+
/** `` `${label}.suffix` `` */
|
|
11
|
+
export declare const labelTemplate: (suffix: string) => t.TemplateLiteral;
|
package/emit/babel.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.labelTemplate = exports.exportConst = exports.asConst = exports.namedImport = exports.withJsDoc = exports.generateCode = exports.HEADER = exports.t = void 0;
|
|
40
|
+
const generator_1 = __importDefault(require("@babel/generator"));
|
|
41
|
+
const t = __importStar(require("@babel/types"));
|
|
42
|
+
exports.t = t;
|
|
43
|
+
exports.HEADER = [
|
|
44
|
+
'/**',
|
|
45
|
+
' * Generated by pg-codegen. DO NOT EDIT.',
|
|
46
|
+
' */',
|
|
47
|
+
'/* eslint-disable */',
|
|
48
|
+
''
|
|
49
|
+
].join('\n');
|
|
50
|
+
const generateCode = (statements) => {
|
|
51
|
+
const program = t.program(statements);
|
|
52
|
+
const { code } = (0, generator_1.default)(program, {
|
|
53
|
+
jsescOption: { quotes: 'single' },
|
|
54
|
+
retainLines: false
|
|
55
|
+
});
|
|
56
|
+
return `${exports.HEADER}${code}\n`;
|
|
57
|
+
};
|
|
58
|
+
exports.generateCode = generateCode;
|
|
59
|
+
/** Attach a JSDoc block as a leading comment. */
|
|
60
|
+
const withJsDoc = (node, text) => {
|
|
61
|
+
t.addComment(node, 'leading', `* ${text} `, false);
|
|
62
|
+
return node;
|
|
63
|
+
};
|
|
64
|
+
exports.withJsDoc = withJsDoc;
|
|
65
|
+
const namedImport = (names, source) => t.importDeclaration(names.map(name => t.importSpecifier(t.identifier(name), t.identifier(name))), t.stringLiteral(source));
|
|
66
|
+
exports.namedImport = namedImport;
|
|
67
|
+
const asConst = (expression) => t.tsAsExpression(expression, t.tsTypeReference(t.identifier('const')));
|
|
68
|
+
exports.asConst = asConst;
|
|
69
|
+
const exportConst = (name, init, typeAnnotation) => {
|
|
70
|
+
const id = t.identifier(name);
|
|
71
|
+
if (typeAnnotation)
|
|
72
|
+
id.typeAnnotation = t.tsTypeAnnotation(typeAnnotation);
|
|
73
|
+
return t.exportNamedDeclaration(t.variableDeclaration('const', [t.variableDeclarator(id, init)]));
|
|
74
|
+
};
|
|
75
|
+
exports.exportConst = exportConst;
|
|
76
|
+
/** `` `${label}.suffix` `` */
|
|
77
|
+
const labelTemplate = (suffix) => t.templateLiteral([
|
|
78
|
+
t.templateElement({ raw: '', cooked: '' }),
|
|
79
|
+
t.templateElement({ raw: `.${suffix}`, cooked: `.${suffix}` }, true)
|
|
80
|
+
], [t.identifier('label')]);
|
|
81
|
+
exports.labelTemplate = labelTemplate;
|
package/emit/barrel.d.ts
ADDED
package/emit/barrel.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.emitRootIndex = exports.emitSchemaIndex = exports.tableFileName = void 0;
|
|
4
|
+
/** Emits the per-schema and root index modules. */
|
|
5
|
+
const inflekt_1 = require("inflekt");
|
|
6
|
+
const babel_1 = require("./babel");
|
|
7
|
+
const tableFileName = (tableName) => (0, inflekt_1.toKebabCase)(tableName);
|
|
8
|
+
exports.tableFileName = tableFileName;
|
|
9
|
+
const emitSchemaIndex = (schema) => {
|
|
10
|
+
const statements = [];
|
|
11
|
+
if (schema.enums.length > 0) {
|
|
12
|
+
statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral('./enums')));
|
|
13
|
+
}
|
|
14
|
+
for (const table of schema.tables) {
|
|
15
|
+
statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral(`./${(0, exports.tableFileName)(table.name)}`)));
|
|
16
|
+
}
|
|
17
|
+
return (0, babel_1.generateCode)(statements);
|
|
18
|
+
};
|
|
19
|
+
exports.emitSchemaIndex = emitSchemaIndex;
|
|
20
|
+
const emitRootIndex = (schemas) => {
|
|
21
|
+
const statements = schemas.map(schema => babel_1.t.exportNamedDeclaration(null, [babel_1.t.exportNamespaceSpecifier(babel_1.t.identifier((0, inflekt_1.toCamelCase)(schema.name)))], babel_1.t.stringLiteral(`./${schema.name}`)));
|
|
22
|
+
return (0, babel_1.generateCode)(statements);
|
|
23
|
+
};
|
|
24
|
+
exports.emitRootIndex = emitRootIndex;
|
package/emit/enums.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { IrEnum } from '../ir';
|
|
2
|
+
export declare const enumConstName: (enumName: string) => string;
|
|
3
|
+
export declare const enumTypeName: (enumName: string) => string;
|
|
4
|
+
export declare const enumAsName: (enumName: string) => string;
|
|
5
|
+
export declare const enumRequireName: (enumName: string) => string;
|
|
6
|
+
export declare const emitEnumsModule: (enums: IrEnum[]) => string;
|
package/emit/enums.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.emitEnumsModule = exports.enumRequireName = exports.enumAsName = exports.enumTypeName = exports.enumConstName = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Emits one `enums.ts` module per schema: a literal tuple, a union type, and
|
|
6
|
+
* lenient/strict runtime checkers for every PostgreSQL enum the schema's
|
|
7
|
+
* tables reference.
|
|
8
|
+
*/
|
|
9
|
+
const inflekt_1 = require("inflekt");
|
|
10
|
+
const babel_1 = require("./babel");
|
|
11
|
+
const enumConstName = (enumName) => (0, inflekt_1.toConstantCase)(enumName);
|
|
12
|
+
exports.enumConstName = enumConstName;
|
|
13
|
+
const enumTypeName = (enumName) => (0, inflekt_1.toPascalCase)(enumName);
|
|
14
|
+
exports.enumTypeName = enumTypeName;
|
|
15
|
+
const enumAsName = (enumName) => `as${(0, inflekt_1.toPascalCase)(enumName)}`;
|
|
16
|
+
exports.enumAsName = enumAsName;
|
|
17
|
+
const enumRequireName = (enumName) => `require${(0, inflekt_1.toPascalCase)(enumName)}`;
|
|
18
|
+
exports.enumRequireName = enumRequireName;
|
|
19
|
+
const emitEnumsModule = (enums) => {
|
|
20
|
+
const statements = [(0, babel_1.namedImport)(['asOneOf', 'requireOneOf'], '@constructive-io/coerce')];
|
|
21
|
+
for (const irEnum of enums) {
|
|
22
|
+
const constName = (0, exports.enumConstName)(irEnum.name);
|
|
23
|
+
const typeName = (0, exports.enumTypeName)(irEnum.name);
|
|
24
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)(constName, (0, babel_1.asConst)(babel_1.t.arrayExpression(irEnum.values.map(value => babel_1.t.stringLiteral(value))))), `Values of the \`${irEnum.schema}.${irEnum.name}\` enum.`));
|
|
25
|
+
statements.push(babel_1.t.exportNamedDeclaration(babel_1.t.tsTypeAliasDeclaration(babel_1.t.identifier(typeName), null, babel_1.t.tsIndexedAccessType(babel_1.t.tsTypeQuery(babel_1.t.identifier(constName)), babel_1.t.tsNumberKeyword()))));
|
|
26
|
+
const valueParam = babel_1.t.identifier('value');
|
|
27
|
+
valueParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
|
|
28
|
+
const asFn = babel_1.t.arrowFunctionExpression([valueParam], babel_1.t.callExpression(babel_1.t.identifier('asOneOf'), [babel_1.t.identifier('value'), babel_1.t.identifier(constName)]));
|
|
29
|
+
asFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnionType([babel_1.t.tsTypeReference(babel_1.t.identifier(typeName)), babel_1.t.tsNullKeyword()]));
|
|
30
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)((0, exports.enumAsName)(irEnum.name), asFn), `A \`${typeName}\`, else \`null\`.`));
|
|
31
|
+
const requireValueParam = babel_1.t.identifier('value');
|
|
32
|
+
requireValueParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
|
|
33
|
+
const labelParam = babel_1.t.identifier('label');
|
|
34
|
+
labelParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsStringKeyword());
|
|
35
|
+
const requireFn = babel_1.t.arrowFunctionExpression([requireValueParam, labelParam], babel_1.t.callExpression(babel_1.t.identifier('requireOneOf'), [
|
|
36
|
+
babel_1.t.identifier('value'),
|
|
37
|
+
babel_1.t.identifier(constName),
|
|
38
|
+
babel_1.t.identifier('label')
|
|
39
|
+
]));
|
|
40
|
+
requireFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(typeName)));
|
|
41
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)((0, exports.enumRequireName)(irEnum.name), requireFn), `A \`${typeName}\`, throwing \`CoerceError\` when the value is not one of its members.`));
|
|
42
|
+
}
|
|
43
|
+
return (0, babel_1.generateCode)(statements);
|
|
44
|
+
};
|
|
45
|
+
exports.emitEnumsModule = emitEnumsModule;
|