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,176 @@
1
+ import { Readable } from 'node:stream';
2
+ import { pipeline } from 'node:stream/promises';
3
+ import postgres from 'postgres';
4
+ import { DriverError, mapPostgresError } from './errors.js';
5
+ const SETTING_NAME = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/;
6
+ const MIN_GUARDED_LENGTH = 8;
7
+ /** bigint → number, refusing values that a JS number can't hold exactly (RFC 0001: ids are branded numbers). */
8
+ function parseBigint(text) {
9
+ const n = Number(text);
10
+ if (!Number.isSafeInteger(n)) {
11
+ throw new DriverError('BIGINT_OUT_OF_RANGE', `The bigint ${text} is beyond Number.MAX_SAFE_INTEGER and would lose precision as a JavaScript number.`, 'Cast it to text or numeric in the query (e.g. col::text) if the column really holds such values.');
12
+ }
13
+ return n;
14
+ }
15
+ function collectStrings(value, out) {
16
+ if (typeof value === 'string') {
17
+ if (value.length >= MIN_GUARDED_LENGTH)
18
+ out.push(value);
19
+ }
20
+ else if (Array.isArray(value)) {
21
+ for (const item of value)
22
+ collectStrings(item, out);
23
+ }
24
+ }
25
+ function guardParamsInText(query) {
26
+ const strings = [];
27
+ for (const p of query.params)
28
+ collectStrings(p, strings);
29
+ const leaked = strings.find((s) => query.text.includes(s));
30
+ if (leaked !== undefined) {
31
+ throw new DriverError('PARAM_IN_TEXT', `A parameter value (${JSON.stringify(leaked.slice(0, 40))}) also appears in the SQL text, so the text was probably built by string concatenation.`, 'Build queries with sql`...` from @shutro/sql so values only travel as parameters; set checkParamsInText: false only if the overlap is intentional.');
32
+ }
33
+ }
34
+ function settingsFor(options) {
35
+ const entries = Object.entries(options.settings ?? {});
36
+ if (options.statementTimeoutMs !== undefined)
37
+ entries.push(['statement_timeout', String(options.statementTimeoutMs)]);
38
+ if (options.lockTimeoutMs !== undefined)
39
+ entries.push(['lock_timeout', String(options.lockTimeoutMs)]);
40
+ for (const [name, value] of entries) {
41
+ if (!SETTING_NAME.test(name) || typeof value !== 'string') {
42
+ throw new DriverError('INVALID_SETTING', `${JSON.stringify(name)} is not a valid transaction setting.`, "Use lower-case names like 'statement_timeout' or a custom 'namespace.name' (e.g. 'shutro.user_id') with string values.");
43
+ }
44
+ }
45
+ return entries;
46
+ }
47
+ /**
48
+ * Creates the PostgreSQL connection pool (postgres.js, RFC 0007). All type handling is configured on this instance;
49
+ * no global state is touched.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const driver = createDriver({ url: process.env.DATABASE_URL, parseNumeric: toDecimal });
54
+ * await driver.transaction({ settings: { 'shutro.user_id': '42' } }, (conn) => conn.query(compile(q)));
55
+ * ```
56
+ */
57
+ export function createDriver(options) {
58
+ const prepare = options.prepare ?? true;
59
+ const guard = options.checkParamsInText ?? process.env['NODE_ENV'] !== 'production';
60
+ const parseNumeric = options.parseNumeric ?? ((text) => text);
61
+ const sql = postgres(options.url, {
62
+ max: options.max ?? 10,
63
+ prepare,
64
+ onnotice: options.onNotice ?? (() => { }),
65
+ connection: { application_name: options.applicationName ?? 'shutro' },
66
+ ...(options.connectTimeoutSeconds === undefined
67
+ ? {}
68
+ : { connect_timeout: options.connectTimeoutSeconds }),
69
+ ...(options.idleTimeoutSeconds === undefined
70
+ ? {}
71
+ : { idle_timeout: options.idleTimeoutSeconds }),
72
+ types: {
73
+ numeric: {
74
+ to: 1700,
75
+ from: [1700],
76
+ serialize: (v) => String(v),
77
+ parse: parseNumeric,
78
+ },
79
+ bigint: { to: 20, from: [20], serialize: (v) => String(v), parse: parseBigint },
80
+ // Calendar dates stay 'YYYY-MM-DD' strings: a JS Date would shift them by the time zone (RFC 0001 W7).
81
+ calendar_date: {
82
+ to: 1082,
83
+ from: [1082],
84
+ serialize: (v) => String(v),
85
+ parse: (s) => s,
86
+ },
87
+ },
88
+ });
89
+ /**
90
+ * postgres.js infers an array parameter's type from its first element, so an array of booleans is sent as a scalar
91
+ * boolean (and a text array that the server resolves to boolean[] is serialized with the boolean serializer, giving
92
+ * 'f' for anything but the value true). Declaring boolean arrays as boolean[] (OID 1000) avoids both.
93
+ */
94
+ const typed = (params) => params.map((p) => Array.isArray(p) && p.some((v) => typeof v === 'boolean') ? sql.typed(p, 1000) : p);
95
+ const run = async (s, query) => {
96
+ if (guard)
97
+ guardParamsInText(query);
98
+ try {
99
+ return [...(await s.unsafe(query.text, typed(query.params), { prepare }))];
100
+ }
101
+ catch (e) {
102
+ throw mapPostgresError(e);
103
+ }
104
+ };
105
+ const connection = (s) => ({
106
+ query: (query) => run(s, query),
107
+ async *stream(query, batchSize) {
108
+ if (guard)
109
+ guardParamsInText(query);
110
+ try {
111
+ for await (const rows of s
112
+ .unsafe(query.text, query.params, { prepare })
113
+ .cursor(batchSize)) {
114
+ yield [...rows];
115
+ }
116
+ }
117
+ catch (e) {
118
+ throw mapPostgresError(e);
119
+ }
120
+ },
121
+ async savepoint(fn) {
122
+ return (await s.savepoint((sp) => fn(connection(sp))));
123
+ },
124
+ async copyIn(query, lines) {
125
+ let count = 0;
126
+ async function* withNewlines() {
127
+ for await (const line of lines) {
128
+ count++;
129
+ yield `${line}\n`;
130
+ }
131
+ }
132
+ try {
133
+ const writable = await s.unsafe(query.text, typed(query.params)).writable();
134
+ await pipeline(Readable.from(withNewlines()), writable);
135
+ }
136
+ catch (e) {
137
+ throw mapPostgresError(e);
138
+ }
139
+ return count;
140
+ },
141
+ });
142
+ return {
143
+ query: (query) => run(sql, query),
144
+ async transaction(txOptions, fn) {
145
+ const settings = settingsFor(txOptions);
146
+ const mode = `isolation level ${txOptions.isolation ?? 'repeatable read'}${txOptions.readOnly ? ' read only' : ''}`;
147
+ try {
148
+ return (await sql.begin(mode, async (tx) => {
149
+ if (settings.length > 0) {
150
+ // One round-trip for all settings: SELECT set_config($1, $2, true), set_config($3, $4, true), …
151
+ const calls = settings
152
+ .map((_, i) => `set_config($${2 * i + 1}, $${2 * i + 2}, true)`)
153
+ .join(', ');
154
+ await tx.unsafe(`SELECT ${calls}`, settings.flat(), { prepare });
155
+ }
156
+ return fn(connection(tx));
157
+ }));
158
+ }
159
+ catch (e) {
160
+ throw mapPostgresError(e);
161
+ }
162
+ },
163
+ async listen(channel, onMessage) {
164
+ try {
165
+ const subscription = await sql.listen(channel, onMessage);
166
+ return async () => {
167
+ await subscription.unlisten();
168
+ };
169
+ }
170
+ catch (e) {
171
+ throw mapPostgresError(e);
172
+ }
173
+ },
174
+ end: (endOptions) => sql.end({ timeout: endOptions?.timeoutSeconds ?? 5 }),
175
+ };
176
+ }
@@ -0,0 +1,72 @@
1
+ /** Machine-readable reason for a {@link DriverError}. */
2
+ export type DriverErrorCode = 'QUERY_FAILED' | 'CONSTRAINT_VIOLATION' | 'SERIALIZATION_FAILURE' | 'DEADLOCK' | 'STATEMENT_TIMEOUT' | 'LOCK_TIMEOUT' | 'READ_ONLY_TRANSACTION' | 'CONNECTION_FAILED' | 'BIGINT_OUT_OF_RANGE' | 'PARAM_IN_TEXT' | 'INVALID_SETTING';
3
+ /** Server-side details carried by a {@link DriverError}. */
4
+ export interface DriverErrorDetails {
5
+ /** SQLSTATE, e.g. `'23505'`. */
6
+ readonly sqlState?: string | undefined;
7
+ readonly constraint?: string | undefined;
8
+ readonly table?: string | undefined;
9
+ readonly column?: string | undefined;
10
+ /** PostgreSQL's DETAIL line, e.g. `Key (name)=(SO001) already exists.` */
11
+ readonly detail?: string | undefined;
12
+ /** The original error. */
13
+ readonly cause?: unknown;
14
+ }
15
+ /**
16
+ * Base class of every error raised by `@shutro/driver-pg`. Same convention as `ShutroError` in `@shutro/core`: the
17
+ * message says what went wrong and ends with {@link DriverError.hint}, which says how to fix it.
18
+ */
19
+ export declare class DriverError extends Error {
20
+ readonly code: DriverErrorCode;
21
+ readonly hint: string;
22
+ /** True when re-running the whole transaction may succeed (serialization failure, deadlock). */
23
+ readonly retryable: boolean;
24
+ readonly sqlState: string | undefined;
25
+ readonly constraint: string | undefined;
26
+ readonly table: string | undefined;
27
+ readonly column: string | undefined;
28
+ readonly detail: string | undefined;
29
+ constructor(code: DriverErrorCode, problem: string, hint: string, details?: DriverErrorDetails, retryable?: boolean);
30
+ }
31
+ /** Which kind of constraint was violated. */
32
+ export type ConstraintKind = 'unique' | 'foreign_key' | 'not_null' | 'check' | 'exclusion';
33
+ /** A unique, foreign-key, not-null, check or exclusion constraint was violated (SQLSTATE class 23). */
34
+ export declare class ConstraintViolationError extends DriverError {
35
+ readonly kind: ConstraintKind;
36
+ constructor(kind: ConstraintKind, problem: string, hint: string, details: DriverErrorDetails);
37
+ }
38
+ /** 40001: the transaction conflicted with a concurrent one. Retry the whole transaction. */
39
+ export declare class SerializationFailureError extends DriverError {
40
+ constructor(details: DriverErrorDetails);
41
+ }
42
+ /** 40P01: deadlock detected. Retry the whole transaction. */
43
+ export declare class DeadlockError extends DriverError {
44
+ constructor(details: DriverErrorDetails);
45
+ }
46
+ /** 57014: the statement exceeded `statement_timeout`. */
47
+ export declare class StatementTimeoutError extends DriverError {
48
+ constructor(details: DriverErrorDetails);
49
+ }
50
+ /** 55P03: waiting for a lock exceeded `lock_timeout`. */
51
+ export declare class LockTimeoutError extends DriverError {
52
+ constructor(details: DriverErrorDetails);
53
+ }
54
+ /** 25006: a write in a read-only transaction. */
55
+ export declare class ReadOnlyTransactionError extends DriverError {
56
+ constructor(details: DriverErrorDetails);
57
+ }
58
+ /** The server could not be reached, the connection broke, or authentication failed. */
59
+ export declare class ConnectionError extends DriverError {
60
+ constructor(problem: string, hint: string, details: DriverErrorDetails);
61
+ }
62
+ /** Any other PostgreSQL error. */
63
+ export declare class QueryError extends DriverError {
64
+ constructor(problem: string, hint: string, details: DriverErrorDetails);
65
+ }
66
+ /**
67
+ * Maps a postgres.js error to a typed {@link DriverError}. Anything else (including errors thrown by business
68
+ * code and already-mapped errors) is returned unchanged.
69
+ */
70
+ export declare function mapPostgresError(error: unknown): unknown;
71
+ /** True when `error` is a {@link DriverError} worth retrying as a whole transaction. */
72
+ export declare function isRetryable(error: unknown): boolean;
@@ -0,0 +1,182 @@
1
+ import postgres from 'postgres';
2
+ /**
3
+ * Base class of every error raised by `@shutro/driver-pg`. Same convention as `ShutroError` in `@shutro/core`: the
4
+ * message says what went wrong and ends with {@link DriverError.hint}, which says how to fix it.
5
+ */
6
+ export class DriverError extends Error {
7
+ code;
8
+ hint;
9
+ /** True when re-running the whole transaction may succeed (serialization failure, deadlock). */
10
+ retryable;
11
+ sqlState;
12
+ constraint;
13
+ table;
14
+ column;
15
+ detail;
16
+ constructor(code, problem, hint, details = {}, retryable = false) {
17
+ super(`${problem} ${hint}`, details.cause === undefined ? undefined : { cause: details.cause });
18
+ this.name = new.target.name;
19
+ this.code = code;
20
+ this.hint = hint;
21
+ this.retryable = retryable;
22
+ this.sqlState = details.sqlState;
23
+ this.constraint = details.constraint;
24
+ this.table = details.table;
25
+ this.column = details.column;
26
+ this.detail = details.detail;
27
+ }
28
+ }
29
+ /** A unique, foreign-key, not-null, check or exclusion constraint was violated (SQLSTATE class 23). */
30
+ export class ConstraintViolationError extends DriverError {
31
+ kind;
32
+ constructor(kind, problem, hint, details) {
33
+ super('CONSTRAINT_VIOLATION', problem, hint, details);
34
+ this.kind = kind;
35
+ }
36
+ }
37
+ /** 40001: the transaction conflicted with a concurrent one. Retry the whole transaction. */
38
+ export class SerializationFailureError extends DriverError {
39
+ constructor(details) {
40
+ super('SERIALIZATION_FAILURE', 'The transaction conflicted with a concurrent transaction (serialization failure).', 'Retry the whole transaction; shutro.run() does this automatically (RFC 0003 §7.5).', details, true);
41
+ }
42
+ }
43
+ /** 40P01: deadlock detected. Retry the whole transaction. */
44
+ export class DeadlockError extends DriverError {
45
+ constructor(details) {
46
+ super('DEADLOCK', 'The transaction was chosen as a deadlock victim.', 'Retry the whole transaction; to avoid it, lock records in a consistent order (e.g. by id).', details, true);
47
+ }
48
+ }
49
+ /** 57014: the statement exceeded `statement_timeout`. */
50
+ export class StatementTimeoutError extends DriverError {
51
+ constructor(details) {
52
+ super('STATEMENT_TIMEOUT', 'The statement was cancelled because it exceeded statement_timeout.', 'Add an index, process the data in smaller batches, or raise statementTimeoutMs for this transaction.', details);
53
+ }
54
+ }
55
+ /** 55P03: waiting for a lock exceeded `lock_timeout`. */
56
+ export class LockTimeoutError extends DriverError {
57
+ constructor(details) {
58
+ super('LOCK_TIMEOUT', 'Waiting for a lock exceeded lock_timeout.', 'Another transaction holds the lock: retry later, use FOR UPDATE SKIP LOCKED for queues, or raise lockTimeoutMs.', details);
59
+ }
60
+ }
61
+ /** 25006: a write in a read-only transaction. */
62
+ export class ReadOnlyTransactionError extends DriverError {
63
+ constructor(details) {
64
+ super('READ_ONLY_TRANSACTION', 'A write was attempted in a read-only transaction.', 'Run writes in a read-write transaction (readOnly: false), or move the write out of the report/replica code path.', details);
65
+ }
66
+ }
67
+ /** The server could not be reached, the connection broke, or authentication failed. */
68
+ export class ConnectionError extends DriverError {
69
+ constructor(problem, hint, details) {
70
+ super('CONNECTION_FAILED', problem, hint, details);
71
+ }
72
+ }
73
+ /** Any other PostgreSQL error. */
74
+ export class QueryError extends DriverError {
75
+ constructor(problem, hint, details) {
76
+ super('QUERY_FAILED', problem, hint, details);
77
+ }
78
+ }
79
+ const CONSTRAINT_KINDS = {
80
+ '23505': 'unique',
81
+ '23503': 'foreign_key',
82
+ '23502': 'not_null',
83
+ '23514': 'check',
84
+ '23P01': 'exclusion',
85
+ };
86
+ const CONNECTION_CODES = new Set([
87
+ 'ECONNREFUSED',
88
+ 'ECONNRESET',
89
+ 'ENOTFOUND',
90
+ 'ETIMEDOUT',
91
+ 'EPIPE',
92
+ 'CONNECTION_CLOSED',
93
+ 'CONNECTION_ENDED',
94
+ 'CONNECTION_DESTROYED',
95
+ 'CONNECT_TIMEOUT',
96
+ ]);
97
+ function constraintMessage(kind, d, serverMessage = '') {
98
+ const on = d.table === undefined ? '' : ` on "${d.table}"`;
99
+ const detail = d.detail === undefined ? '' : `${d.detail} `;
100
+ switch (kind) {
101
+ case 'unique':
102
+ return [
103
+ `A record with the same value already exists (unique constraint "${d.constraint ?? '?'}"${on}).`,
104
+ `${detail}Use a different value, or update the existing record instead of creating a new one.`,
105
+ ];
106
+ case 'foreign_key':
107
+ return [
108
+ `The record references a missing record, or is still referenced (foreign key "${d.constraint ?? '?'}"${on}).`,
109
+ `${detail}Check that the referenced record exists, or reassign or delete the records that reference it first.`,
110
+ ];
111
+ case 'not_null':
112
+ return [
113
+ `A required value is missing (column "${d.column ?? '?'}"${on}).`,
114
+ 'Provide a value, or give the field a default.',
115
+ ];
116
+ case 'check':
117
+ if (d.constraint === undefined && /no partition/i.test(serverMessage))
118
+ return [
119
+ `No partition accepts the row${on}.`,
120
+ `${detail}Create the partition for this value first (partitionStatements / rangePartitions), or add a DEFAULT partition.`,
121
+ ];
122
+ return [
123
+ `A value breaks the check constraint "${d.constraint ?? '?'}"${on}.`,
124
+ `${detail}Correct the value so it satisfies the constraint.`,
125
+ ];
126
+ case 'exclusion':
127
+ return [
128
+ `The record overlaps an existing one (exclusion constraint "${d.constraint ?? '?'}"${on}).`,
129
+ `${detail}Change the overlapping range or value.`,
130
+ ];
131
+ }
132
+ }
133
+ /**
134
+ * Maps a postgres.js error to a typed {@link DriverError}. Anything else (including errors thrown by business
135
+ * code and already-mapped errors) is returned unchanged.
136
+ */
137
+ export function mapPostgresError(error) {
138
+ if (error instanceof DriverError)
139
+ return error;
140
+ if (error instanceof postgres.PostgresError) {
141
+ const details = {
142
+ sqlState: error.code,
143
+ constraint: error.constraint_name,
144
+ table: error.table_name,
145
+ column: error.column_name,
146
+ detail: error.detail,
147
+ cause: error,
148
+ };
149
+ const kind = CONSTRAINT_KINDS[error.code];
150
+ if (kind !== undefined) {
151
+ const [problem, hint] = constraintMessage(kind, details, error.message);
152
+ return new ConstraintViolationError(kind, problem, hint, details);
153
+ }
154
+ switch (error.code) {
155
+ case '40001':
156
+ return new SerializationFailureError(details);
157
+ case '40P01':
158
+ return new DeadlockError(details);
159
+ case '57014':
160
+ return new StatementTimeoutError(details);
161
+ case '55P03':
162
+ return new LockTimeoutError(details);
163
+ case '25006':
164
+ return new ReadOnlyTransactionError(details);
165
+ }
166
+ if (/^(08|28|57P0)/.test(error.code)) {
167
+ return new ConnectionError(`PostgreSQL closed or refused the connection (${error.code}: ${error.message}).`, 'Check credentials and that the server is running; the transaction outcome is unknown, so verify before retrying.', details);
168
+ }
169
+ return new QueryError(`PostgreSQL error ${error.code}: ${error.message}.`, error.hint ?? 'See sqlState and detail; this usually means the SQL or the schema is wrong.', details);
170
+ }
171
+ if (error instanceof Error) {
172
+ const code = error.code;
173
+ if (typeof code === 'string' && CONNECTION_CODES.has(code)) {
174
+ return new ConnectionError(`Could not talk to PostgreSQL (${code}: ${error.message}).`, 'Check that the server is running and reachable at the configured URL (host, port, firewall, PgBouncer).', { cause: error });
175
+ }
176
+ }
177
+ return error;
178
+ }
179
+ /** True when `error` is a {@link DriverError} worth retrying as a whole transaction. */
180
+ export function isRetryable(error) {
181
+ return error instanceof DriverError && error.retryable;
182
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/driver-pg`: the PostgreSQL connection layer (RFC 0007). It wraps postgres.js behind a small interface
4
+ * (`Driver`, `DriverConnection`). No other Shutro package imports postgres.js.
5
+ */
6
+ export { createDriver, type Driver, type DriverConnection, type DriverOptions, type DriverQuery, type Isolation, type Row, type TxOptions, } from './driver.js';
7
+ export { ConnectionError, type ConstraintKind, ConstraintViolationError, DeadlockError, DriverError, type DriverErrorCode, type DriverErrorDetails, isRetryable, LockTimeoutError, mapPostgresError, QueryError, ReadOnlyTransactionError, SerializationFailureError, StatementTimeoutError, } from './errors.js';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/driver-pg`: the PostgreSQL connection layer (RFC 0007). It wraps postgres.js behind a small interface
4
+ * (`Driver`, `DriverConnection`). No other Shutro package imports postgres.js.
5
+ */
6
+ export { createDriver, } from './driver.js';
7
+ export { ConnectionError, ConstraintViolationError, DeadlockError, DriverError, isRetryable, LockTimeoutError, mapPostgresError, QueryError, ReadOnlyTransactionError, SerializationFailureError, StatementTimeoutError, } from './errors.js';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/i18n`: the pure rules of translatable fields (RFC 0011). A translatable value is a map from language
4
+ * code to text, stored as JSONB; reading resolves the environment language with a fallback to the source language,
5
+ * writing merges into the map. Core applies these on `translate: true` fields; applications can use them on their
6
+ * own JSON.
7
+ */
8
+ /** Language → text, as stored in a `translate: true` column (`{ "en_US": "Laptop", "bn_BD": "ল্যাপটপ" }`). */
9
+ export type Translations = Readonly<Record<string, string>>;
10
+ /** `en_US`, `bn_BD`, `fr`, `pt_BR`. */
11
+ export declare const LANG_CODE: RegExp;
12
+ /** True for a well-formed language code. */
13
+ export declare function isLangCode(value: unknown): value is string;
14
+ /** True for a plain object whose keys are language codes and whose values are strings. */
15
+ export declare function isTranslations(value: unknown): value is Translations;
16
+ /**
17
+ * The text to show for `lang`: the language itself, then the source language, then the first translation by sorted
18
+ * language code (so a record translated only in `fr_FR` still shows something), else `null`.
19
+ */
20
+ export declare function resolveTranslation(value: Translations | null | undefined, lang: string, source: string): string | null;
21
+ /**
22
+ * The map after writing `value` in `lang`: a string sets that language (and the source language when the record has
23
+ * no source text yet, so readers of other languages see the new text); a map sets every language it names.
24
+ */
25
+ export declare function mergeTranslation(existing: Translations | null | undefined, value: string | Translations, lang: string, source: string): Translations;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/i18n`: the pure rules of translatable fields (RFC 0011). A translatable value is a map from language
4
+ * code to text, stored as JSONB; reading resolves the environment language with a fallback to the source language,
5
+ * writing merges into the map. Core applies these on `translate: true` fields; applications can use them on their
6
+ * own JSON.
7
+ */
8
+ /** `en_US`, `bn_BD`, `fr`, `pt_BR`. */
9
+ export const LANG_CODE = /^[a-z]{2,3}(_[A-Z]{2})?$/;
10
+ /** True for a well-formed language code. */
11
+ export function isLangCode(value) {
12
+ return typeof value === 'string' && LANG_CODE.test(value);
13
+ }
14
+ /** True for a plain object whose keys are language codes and whose values are strings. */
15
+ export function isTranslations(value) {
16
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
17
+ return false;
18
+ return Object.entries(value).every(([k, v]) => isLangCode(k) && typeof v === 'string');
19
+ }
20
+ /**
21
+ * The text to show for `lang`: the language itself, then the source language, then the first translation by sorted
22
+ * language code (so a record translated only in `fr_FR` still shows something), else `null`.
23
+ */
24
+ export function resolveTranslation(value, lang, source) {
25
+ if (value === null || value === undefined)
26
+ return null;
27
+ const own = value[lang];
28
+ if (own !== undefined)
29
+ return own;
30
+ const fallback = value[source];
31
+ if (fallback !== undefined)
32
+ return fallback;
33
+ const first = Object.keys(value).sort()[0];
34
+ return first === undefined ? null : (value[first] ?? null);
35
+ }
36
+ /**
37
+ * The map after writing `value` in `lang`: a string sets that language (and the source language when the record has
38
+ * no source text yet, so readers of other languages see the new text); a map sets every language it names.
39
+ */
40
+ export function mergeTranslation(existing, value, lang, source) {
41
+ const base = { ...(existing ?? {}) };
42
+ if (typeof value === 'string') {
43
+ if (base[source] === undefined)
44
+ base[source] = value;
45
+ base[lang] = value;
46
+ return Object.freeze(base);
47
+ }
48
+ for (const [k, v] of Object.entries(value))
49
+ base[k] = v;
50
+ return Object.freeze(base);
51
+ }
@@ -0,0 +1,78 @@
1
+ import { type Registry } from '../core/index.js';
2
+ import type { Driver } from '../driver-pg/index.js';
3
+ import { type Operation } from './diff.js';
4
+ /** A planned migration: operations, the destructive subset, and the rendered statements. */
5
+ export interface MigrationPlan {
6
+ readonly operations: readonly Operation[];
7
+ readonly destructive: readonly Operation[];
8
+ /** Statements with their destructiveness, in execution order. */
9
+ readonly statements: readonly {
10
+ readonly sql: string;
11
+ readonly destructive: boolean;
12
+ }[];
13
+ }
14
+ /** Compares the registry with the live database and plans the changes. */
15
+ export declare function planMigration(options: {
16
+ readonly driver: Driver;
17
+ readonly registry: Registry;
18
+ readonly schema?: string;
19
+ }): Promise<MigrationPlan>;
20
+ /** A migration file on disk. */
21
+ export interface MigrationFile {
22
+ readonly version: string;
23
+ readonly name: string;
24
+ readonly path: string;
25
+ }
26
+ /** Writes the plan as the next versioned file (`0001_name.sql`). */
27
+ export declare function writeMigrationFile(options: {
28
+ readonly dir: string;
29
+ readonly name: string;
30
+ readonly plan: MigrationPlan;
31
+ }): Promise<MigrationFile>;
32
+ /** Parses a migration file into statements (comments dropped; `-- destructive` marks the next statement). */
33
+ export declare function parseMigrationFile(content: string): {
34
+ readonly sql: string;
35
+ readonly destructive: boolean;
36
+ }[];
37
+ /** Applied and pending migrations. */
38
+ export interface MigrationStatus {
39
+ readonly applied: readonly {
40
+ readonly version: string;
41
+ readonly name: string;
42
+ readonly appliedAt: Date;
43
+ }[];
44
+ readonly pending: readonly MigrationFile[];
45
+ }
46
+ /** Reads the ledger and the directory. @throws {MigrationChecksumError} when an applied file was edited. */
47
+ export declare function migrationStatus(options: {
48
+ readonly driver: Driver;
49
+ readonly dir: string;
50
+ }): Promise<MigrationStatus>;
51
+ /** Result of {@link applyMigrations}. */
52
+ export interface MigrationResult {
53
+ readonly applied: readonly MigrationFile[];
54
+ /** Modules whose recorded version changed (fresh installs have `from: null`). */
55
+ readonly modules: readonly {
56
+ readonly module: string;
57
+ readonly from: string | null;
58
+ readonly to: string;
59
+ }[];
60
+ /** Data-migration hooks that ran, in order. */
61
+ readonly hooks: readonly {
62
+ readonly module: string;
63
+ readonly version: string;
64
+ }[];
65
+ }
66
+ /**
67
+ * Applies pending migration files in order (each in its own transaction, recorded in `shutro_migration`), then runs
68
+ * the data-migration hooks of upgraded modules and records module versions in `shutro_module`.
69
+ *
70
+ * @throws {DestructiveMigrationError} for a file with destructive statements unless `allowDestructive` is set.
71
+ * @throws {MigrationChecksumError} when an applied file was edited.
72
+ */
73
+ export declare function applyMigrations(options: {
74
+ readonly driver: Driver;
75
+ readonly dir: string;
76
+ readonly registry: Registry;
77
+ readonly allowDestructive?: boolean;
78
+ }): Promise<MigrationResult>;