@kiri-orm/core 0.1.0 → 0.1.1

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 (126) hide show
  1. package/dist/types/client/create-client.d.ts +32 -0
  2. package/dist/types/client/index.d.ts +4 -0
  3. package/dist/types/client/model-handle.d.ts +148 -0
  4. package/dist/types/client/module.d.ts +54 -0
  5. package/dist/types/client/orm-client.d.ts +107 -0
  6. package/dist/types/connection.d.ts +40 -0
  7. package/dist/types/crud/aggregate-filter.d.ts +36 -0
  8. package/dist/types/crud/aggregate-paths.d.ts +74 -0
  9. package/dist/types/crud/aggregate-spec.d.ts +36 -0
  10. package/dist/types/crud/aggregate.d.ts +59 -0
  11. package/dist/types/crud/create-many.d.ts +42 -0
  12. package/dist/types/crud/errors.d.ts +16 -0
  13. package/dist/types/crud/index.d.ts +12 -0
  14. package/dist/types/crud/insert-many.d.ts +63 -0
  15. package/dist/types/crud/map-filter.d.ts +18 -0
  16. package/dist/types/crud/order.d.ts +58 -0
  17. package/dist/types/crud/paginate.d.ts +55 -0
  18. package/dist/types/crud/prepare-write.d.ts +55 -0
  19. package/dist/types/crud/repository-factory.d.ts +27 -0
  20. package/dist/types/crud/repository.d.ts +297 -0
  21. package/dist/types/crud/resolve-where.d.ts +24 -0
  22. package/dist/types/crud/row-mapping.d.ts +45 -0
  23. package/dist/types/crud/select.d.ts +74 -0
  24. package/dist/types/crud/sequence.d.ts +56 -0
  25. package/dist/types/crud/transaction.d.ts +19 -0
  26. package/dist/types/diagnostics/index.d.ts +1 -0
  27. package/dist/types/diagnostics/n-plus-one.d.ts +108 -0
  28. package/dist/types/dialect/date-bucket.d.ts +46 -0
  29. package/dist/types/dialect/index.d.ts +1 -0
  30. package/dist/types/domain/compile.d.ts +30 -0
  31. package/dist/types/domain/errors.d.ts +20 -0
  32. package/dist/types/domain/index.d.ts +4 -0
  33. package/dist/types/domain/parse.d.ts +30 -0
  34. package/dist/types/dto/field-schema.d.ts +12 -0
  35. package/dist/types/dto/index.d.ts +3 -0
  36. package/dist/types/dto/jsdoc-generator.d.ts +29 -0
  37. package/dist/types/dto/schema-generator.d.ts +59 -0
  38. package/dist/types/fields/auto-id.d.ts +27 -0
  39. package/dist/types/fields/cast-value.d.ts +19 -0
  40. package/dist/types/fields/computed-access.d.ts +22 -0
  41. package/dist/types/fields/default-for.d.ts +11 -0
  42. package/dist/types/fields/default-registry.d.ts +9 -0
  43. package/dist/types/fields/define-computed-field.d.ts +57 -0
  44. package/dist/types/fields/define-field.d.ts +35 -0
  45. package/dist/types/fields/errors.d.ts +30 -0
  46. package/dist/types/fields/index.d.ts +7 -0
  47. package/dist/types/fields/registry.d.ts +55 -0
  48. package/dist/types/fields/types/boolean.d.ts +5 -0
  49. package/dist/types/fields/types/char.d.ts +12 -0
  50. package/dist/types/fields/types/date.d.ts +10 -0
  51. package/dist/types/fields/types/datetime.d.ts +11 -0
  52. package/dist/types/fields/types/enum.d.ts +11 -0
  53. package/dist/types/fields/types/float.d.ts +11 -0
  54. package/dist/types/fields/types/integer.d.ts +11 -0
  55. package/dist/types/fields/types/json.d.ts +9 -0
  56. package/dist/types/fields/types/text.d.ts +10 -0
  57. package/dist/types/fields/types/uuid.d.ts +14 -0
  58. package/dist/types/fields/validate-value.d.ts +14 -0
  59. package/dist/types/global/connect.d.ts +29 -0
  60. package/dist/types/global/create-model.d.ts +189 -0
  61. package/dist/types/global/create-report.d.ts +32 -0
  62. package/dist/types/global/dto.d.ts +31 -0
  63. package/dist/types/global/glob.d.ts +12 -0
  64. package/dist/types/global/identity-scope.d.ts +18 -0
  65. package/dist/types/global/index.d.ts +12 -0
  66. package/dist/types/global/load-models.d.ts +31 -0
  67. package/dist/types/global/migrate.d.ts +68 -0
  68. package/dist/types/global/n-plus-one.d.ts +42 -0
  69. package/dist/types/global/sequences.d.ts +19 -0
  70. package/dist/types/global/state.d.ts +38 -0
  71. package/dist/types/global/sync-models.d.ts +11 -0
  72. package/dist/types/global/transaction.d.ts +22 -0
  73. package/dist/types/index.d.ts +16 -0
  74. package/dist/types/meta/index.d.ts +5 -0
  75. package/dist/types/meta/query.d.ts +34 -0
  76. package/dist/types/meta/reserved-tables.d.ts +10 -0
  77. package/dist/types/meta/schema.d.ts +18 -0
  78. package/dist/types/meta/snapshot.d.ts +35 -0
  79. package/dist/types/meta/sync-meta.d.ts +42 -0
  80. package/dist/types/meta/upsert.d.ts +81 -0
  81. package/dist/types/migrations/apply.d.ts +18 -0
  82. package/dist/types/migrations/describe.d.ts +11 -0
  83. package/dist/types/migrations/diff.d.ts +141 -0
  84. package/dist/types/migrations/errors.d.ts +23 -0
  85. package/dist/types/migrations/foreign-keys-plan.d.ts +27 -0
  86. package/dist/types/migrations/generate.d.ts +51 -0
  87. package/dist/types/migrations/index.d.ts +7 -0
  88. package/dist/types/migrations/render.d.ts +45 -0
  89. package/dist/types/migrations/runner.d.ts +118 -0
  90. package/dist/types/models/define-model.d.ts +52 -0
  91. package/dist/types/models/errors.d.ts +23 -0
  92. package/dist/types/models/index.d.ts +4 -0
  93. package/dist/types/models/inheritance.d.ts +73 -0
  94. package/dist/types/models/naming.d.ts +44 -0
  95. package/dist/types/models/primary-key.d.ts +39 -0
  96. package/dist/types/models/registry.d.ts +112 -0
  97. package/dist/types/relations/attach-detach.d.ts +76 -0
  98. package/dist/types/relations/cascade-delete.d.ts +29 -0
  99. package/dist/types/relations/commands.d.ts +84 -0
  100. package/dist/types/relations/define-relation.d.ts +106 -0
  101. package/dist/types/relations/eager-load.d.ts +28 -0
  102. package/dist/types/relations/errors.d.ts +21 -0
  103. package/dist/types/relations/foreign-keys.d.ts +76 -0
  104. package/dist/types/relations/index.d.ts +7 -0
  105. package/dist/types/relations/keys.d.ts +14 -0
  106. package/dist/types/relations/pivot-schema.d.ts +24 -0
  107. package/dist/types/relations/with-spec.d.ts +33 -0
  108. package/dist/types/reports/define-report.d.ts +37 -0
  109. package/dist/types/reports/errors.d.ts +9 -0
  110. package/dist/types/reports/index.d.ts +3 -0
  111. package/dist/types/reports/report-handle.d.ts +58 -0
  112. package/dist/types/schema/build-column.d.ts +18 -0
  113. package/dist/types/schema/column-builder-registry.d.ts +30 -0
  114. package/dist/types/schema/default-column-builders.d.ts +9 -0
  115. package/dist/types/schema/errors.d.ts +9 -0
  116. package/dist/types/schema/foreign-keys.d.ts +33 -0
  117. package/dist/types/schema/index.d.ts +6 -0
  118. package/dist/types/schema/introspect-foreign-keys.d.ts +23 -0
  119. package/dist/types/schema/sync.d.ts +63 -0
  120. package/dist/types/uow/entity.d.ts +80 -0
  121. package/dist/types/uow/errors.d.ts +8 -0
  122. package/dist/types/uow/hooks.d.ts +35 -0
  123. package/dist/types/uow/index.d.ts +5 -0
  124. package/dist/types/uow/unit-of-work.d.ts +142 -0
  125. package/dist/types/uow/with-unit-of-work.d.ts +23 -0
  126. package/package.json +9 -3
@@ -0,0 +1,9 @@
1
+ import { FieldTypeRegistry } from "./registry.js";
2
+ /**
3
+ * The registry used by defineField()/validateValue()/castValue() when
4
+ * no explicit registry is passed in. Plugins can register additional
5
+ * types onto this instance, or callers can construct their own
6
+ * `new FieldTypeRegistry()` for isolation (e.g. in tests).
7
+ */
8
+ export declare function createDefaultFieldTypeRegistry(): FieldTypeRegistry;
9
+ export declare const defaultFieldTypeRegistry: FieldTypeRegistry;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * True if these raw field options declare a computed (virtual) field.
3
+ * `compute` is the one option that decides it.
4
+ *
5
+ * @param {unknown} options
6
+ */
7
+ export declare function isComputedField(options: unknown): boolean;
8
+ export type ComputedFieldDescriptor = {
9
+ /**
10
+ * - the type of the value `compute` returns (used for casting search values and for DTOs)
11
+ */
12
+ type: string;
13
+ compute: (record: Record<string, unknown>) => unknown;
14
+ /**
15
+ * - fields of the same model `compute` reads
16
+ */
17
+ depends: readonly string[];
18
+ search: ((operator: string, value: unknown) => unknown[]) | undefined;
19
+ };
20
+ /**
21
+ * @typedef {Object} ComputedFieldDescriptor
22
+ * @property {string} type - the type of the value `compute` returns (used for casting search values and for DTOs)
23
+ * @property {(record: Record<string, unknown>) => unknown} compute
24
+ * @property {readonly string[]} depends - fields of the same model `compute` reads
25
+ * @property {((operator: string, value: unknown) => unknown[])|undefined} search
26
+ */
27
+ /**
28
+ * Defines a computed field: a value calculated from a record's other
29
+ * fields when it is read, never stored.
30
+ *
31
+ * fullName: {
32
+ * type: "char",
33
+ * depends: ["firstName", "lastName"],
34
+ * compute: (record) => `${record.firstName} ${record.lastName}`,
35
+ * // What makes it queryable - see compileComputedLeaf() in domain/compile.js:
36
+ * search: (operator, value) => [["firstName", operator, value]],
37
+ * }
38
+ *
39
+ * `compute` must be synchronous and a pure function of `record`. It
40
+ * runs on every access (there's no cache to go stale when a field is
41
+ * edited in memory), so it should be cheap.
42
+ *
43
+ * `search(operator, value)` is Odoo's compute-and-search pattern: given
44
+ * a comparison on the computed field, return a domain over fields that
45
+ * DO exist as columns (or other computed fields) that selects the same
46
+ * records. Without it the field can be read but not filtered on.
47
+ *
48
+ * Stored computed fields (`store: true`) are deliberately not supported:
49
+ * they'd need recomputation whenever a dependency changes - through
50
+ * update(), updateMany(), createMany(), and raw SQL - and a missed path
51
+ * silently leaves stale data in a column that queries trust.
52
+ *
53
+ * @param {Record<string, unknown>} options
54
+ * @param {import('./registry.js').FieldTypeRegistry} [registry]
55
+ * @returns {Readonly<ComputedFieldDescriptor>}
56
+ */
57
+ export declare function defineComputedField(options: Record<string, unknown>, registry?: import('./registry.js').FieldTypeRegistry): Readonly<ComputedFieldDescriptor>;
@@ -0,0 +1,35 @@
1
+ export type FieldDescriptor = {
2
+ type: string;
3
+ required: boolean;
4
+ unique: boolean;
5
+ index: boolean;
6
+ default?: unknown | (() => unknown);
7
+ typeSpecificOptions?: unknown[];
8
+ };
9
+ /**
10
+ * @typedef {Object} FieldDescriptor
11
+ * @property {string} type
12
+ * @property {boolean} required
13
+ * @property {boolean} unique
14
+ * @property {boolean} index
15
+ * @property {unknown|(() => unknown)} [default]
16
+ * @property {...unknown} [typeSpecificOptions]
17
+ */
18
+ /**
19
+ * Defines a single field descriptor: a plain, serializable object
20
+ * describing a piece of data (its type, constraints, and default).
21
+ * This is the runtime "type system" the project uses instead of
22
+ * TypeScript - the object itself is both the schema and the contract
23
+ * that validateValue()/castValue() enforce at runtime.
24
+ *
25
+ * Fields are frozen shallowly so accidental in-place mutation (e.g.
26
+ * `field.required = true` after the fact) fails loudly instead of
27
+ * silently drifting from what was registered.
28
+ *
29
+ * @param {Partial<FieldDescriptor> & { type: string }} options
30
+ * @param {import('./registry.js').FieldTypeRegistry} [registry]
31
+ * @returns {Readonly<FieldDescriptor>}
32
+ */
33
+ export declare function defineField(options: Partial<FieldDescriptor> & {
34
+ type: string;
35
+ }, registry?: import('./registry.js').FieldTypeRegistry): Readonly<FieldDescriptor>;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Thrown by castValue() when a value cannot be coerced into a field's
3
+ * declared type at all (e.g. "abc" cast as integer). This is distinct
4
+ * from validation failures (wrong length, out of range, etc.), which
5
+ * are reported as a list of error strings from validateValue() instead
6
+ * of thrown, since a caller (e.g. a future DTO layer) will often want
7
+ * to collect *all* validation problems for a record at once rather than
8
+ * stopping at the first one.
9
+ */
10
+ export declare class CastError extends TypeError {
11
+ fieldType: string | undefined;
12
+ value: unknown;
13
+ /**
14
+ * @param {string} message
15
+ * @param {{ fieldType?: string, value?: unknown }} [details]
16
+ */
17
+ constructor(message: string, details?: {
18
+ fieldType?: string;
19
+ value?: unknown;
20
+ });
21
+ }
22
+ /**
23
+ * Thrown by defineField() when a field descriptor itself is malformed
24
+ * (unknown type, missing required type-specific option, bad option
25
+ * value). This is a developer-time error about the schema, not a
26
+ * runtime error about a piece of data.
27
+ */
28
+ export declare class InvalidFieldDefinitionError extends Error {
29
+ constructor(message: any);
30
+ }
@@ -0,0 +1,7 @@
1
+ export { defineField } from "./define-field.js";
2
+ export { validateValue } from "./validate-value.js";
3
+ export { castValue } from "./cast-value.js";
4
+ export { defaultFor } from "./default-for.js";
5
+ export { FieldTypeRegistry } from "./registry.js";
6
+ export { defaultFieldTypeRegistry, createDefaultFieldTypeRegistry, } from "./default-registry.js";
7
+ export { CastError, InvalidFieldDefinitionError } from "./errors.js";
@@ -0,0 +1,55 @@
1
+ export type FieldTypeDefinition = {
2
+ name: string;
3
+ /**
4
+ * Validates the type-specific options on a field descriptor at
5
+ * definition time (e.g. enum requires a non-empty `values` array).
6
+ * Returns an array of error strings; empty array means valid.
7
+ */
8
+ validateOptions?: (field: object) => string[];
9
+ /**
10
+ * Validates a runtime value against the field (assumes value is
11
+ * already non-null/undefined - required/null handling happens
12
+ * before this is called). Returns an array of error strings.
13
+ */
14
+ validate: (field: object, value: unknown) => string[];
15
+ /**
16
+ * Coerces a runtime value into the field's canonical JS
17
+ * representation, or throws CastError if coercion isn't possible.
18
+ */
19
+ cast: (field: object, value: unknown) => unknown;
20
+ };
21
+ /**
22
+ * @typedef {Object} FieldTypeDefinition
23
+ * @property {string} name
24
+ * @property {(field: object) => string[]} [validateOptions]
25
+ * Validates the type-specific options on a field descriptor at
26
+ * definition time (e.g. enum requires a non-empty `values` array).
27
+ * Returns an array of error strings; empty array means valid.
28
+ * @property {(field: object, value: unknown) => string[]} validate
29
+ * Validates a runtime value against the field (assumes value is
30
+ * already non-null/undefined - required/null handling happens
31
+ * before this is called). Returns an array of error strings.
32
+ * @property {(field: object, value: unknown) => unknown} cast
33
+ * Coerces a runtime value into the field's canonical JS
34
+ * representation, or throws CastError if coercion isn't possible.
35
+ */
36
+ /**
37
+ * Holds field type definitions (char, integer, etc.) keyed by name.
38
+ * Kept as a class rather than a bare object so multiple independent
39
+ * registries can exist later (useful for plugin isolation or testing)
40
+ * without global mutation.
41
+ */
42
+ export declare class FieldTypeRegistry {
43
+ #private;
44
+ /**
45
+ * @param {FieldTypeDefinition} definition
46
+ */
47
+ register(definition: FieldTypeDefinition): this;
48
+ /**
49
+ * @param {string} name
50
+ * @returns {FieldTypeDefinition}
51
+ */
52
+ get(name: string): FieldTypeDefinition;
53
+ has(name: any): boolean;
54
+ names(): any[];
55
+ }
@@ -0,0 +1,5 @@
1
+ export declare const booleanType: {
2
+ name: string;
3
+ validate(field: any, value: any): string[];
4
+ cast(field: any, value: any): boolean;
5
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * A short, single-line string (maps to VARCHAR in most dialects).
3
+ * Options:
4
+ * - maxLength {number} default 255
5
+ * - minLength {number} default 0
6
+ */
7
+ export declare const charType: {
8
+ name: string;
9
+ validateOptions(field: any): string[];
10
+ validate(field: any, value: any): string[];
11
+ cast(field: any, value: any): string;
12
+ };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A calendar date (no time component, though the canonical runtime
3
+ * representation is still a JS Date - the schema-sync layer in a later
4
+ * phase is what maps this to a DATE vs DATETIME column per dialect).
5
+ */
6
+ export declare const dateType: {
7
+ name: string;
8
+ validate(field: any, value: any): string[];
9
+ cast(field: any, value: any): any;
10
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A date + time value. Kept as a separate type from `date` (rather than
3
+ * an option on it) so the future schema-sync layer can map them to
4
+ * distinct column types (DATE vs TIMESTAMP) per dialect without
5
+ * inspecting field options.
6
+ */
7
+ export declare const datetimeType: {
8
+ name: string;
9
+ validate(field: any, value: any): string[];
10
+ cast(field: any, value: any): any;
11
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A value constrained to a fixed set of options. Requires a `values`
3
+ * array on the field descriptor, e.g.:
4
+ * { type: "enum", values: ["draft", "sent", "paid"] }
5
+ */
6
+ export declare const enumType: {
7
+ name: string;
8
+ validateOptions(field: any): string[];
9
+ validate(field: any, value: any): string[];
10
+ cast(field: any, value: any): string;
11
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A floating-point number. Options:
3
+ * - min {number}
4
+ * - max {number}
5
+ */
6
+ export declare const floatType: {
7
+ name: string;
8
+ validateOptions(field: any): string[];
9
+ validate(field: any, value: any): string[];
10
+ cast(field: any, value: any): number;
11
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A whole number. Options:
3
+ * - min {number}
4
+ * - max {number}
5
+ */
6
+ export declare const integerType: {
7
+ name: string;
8
+ validateOptions(field: any): string[];
9
+ validate(field: any, value: any): string[];
10
+ cast(field: any, value: any): number;
11
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Any JSON-serializable value (object, array, or primitive). Maps to a
3
+ * JSON/JSONB column depending on dialect in a later phase.
4
+ */
5
+ export declare const jsonType: {
6
+ name: string;
7
+ validate(field: any, value: any): string[];
8
+ cast(field: any, value: any): any;
9
+ };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Long-form text (maps to TEXT in most dialects). Unlike `char`, there
3
+ * is no default length cap - set `maxLength` explicitly if you want one.
4
+ */
5
+ export declare const textType: {
6
+ name: string;
7
+ validateOptions(field: any): string[];
8
+ validate(field: any, value: any): string[];
9
+ cast(field: any, value: any): string;
10
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A UUID, stored as a native `uuid` column on Postgres and as
3
+ * `char(36)` on SQLite (Knex's `table.uuid()` already handles that
4
+ * per-dialect difference - see schema/default-column-builders.js).
5
+ *
6
+ * A field named "id" with this type is auto-generated on create() via
7
+ * `crypto.randomUUID()` unless you supply your own value or your own
8
+ * `default` - see fields/auto-id.js.
9
+ */
10
+ export declare const uuidType: {
11
+ name: string;
12
+ validate(field: any, value: any): string[];
13
+ cast(field: any, value: any): string;
14
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Validates a runtime value against a field descriptor. Pure function:
3
+ * no DB, no mutation, just field + value in, error list out.
4
+ *
5
+ * Handles required/null/undefined itself so individual field types
6
+ * don't each need to reimplement that logic - a type's `validate`
7
+ * is only ever called with a genuinely present value.
8
+ *
9
+ * @param {import('./define-field.js').FieldDescriptor} field
10
+ * @param {unknown} value
11
+ * @param {import('./registry.js').FieldTypeRegistry} [registry]
12
+ * @returns {string[]} empty array means valid
13
+ */
14
+ export declare function validateValue(field: import('./define-field.js').FieldDescriptor, value: unknown, registry?: import('./registry.js').FieldTypeRegistry): string[];
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Sets the default connection every `createModel()`-defined Model
3
+ * uses. Accepts either a connection config (`{ dialect, filename }` /
4
+ * `{ dialect, connectionString }`, same as `createConnection()`) or an
5
+ * already-built Knex instance directly, for cases where the app needs
6
+ * to configure Knex itself beyond what `createConnection()` exposes.
7
+ *
8
+ * Call this once at startup, before performing any queries through a
9
+ * Model (defining models with `createModel()` doesn't need a
10
+ * connection yet - only actually running a query does, so model
11
+ * definitions and `connect()` can happen in either order at
12
+ * module-load time).
13
+ *
14
+ * @param {import('../connection.js').ConnectionConfig|import('knex').Knex} configOrConnection
15
+ * @returns {import('knex').Knex}
16
+ */
17
+ export declare function connect(configOrConnection: import('../connection.js').ConnectionConfig | import('knex').Knex): import('knex').Knex;
18
+ /**
19
+ * Returns the default connection set by `connect()`. Throws a clear
20
+ * error if `connect()` hasn't been called yet, rather than failing
21
+ * deep inside a query with a confusing "cannot read property of null".
22
+ *
23
+ * @returns {import('knex').Knex}
24
+ */
25
+ export declare function getConnection(): import('knex').Knex;
26
+ /**
27
+ * Closes the default connection, if one is set.
28
+ */
29
+ export declare function disconnect(): Promise<void>;
@@ -0,0 +1,189 @@
1
+ import { HOOK_NAMES } from "../uow/hooks.js";
2
+ /**
3
+ * Extends a model that some other package defined - Odoo's `_inherit`
4
+ * on an existing model. Adds fields and relations to it (or overrides
5
+ * their options: `{ title: { required: true } }` keeps the field's type
6
+ * and everything else), and can register hooks for it. Same model,
7
+ * same table; the additions are ordinary columns.
8
+ *
9
+ * Call order doesn't matter. If the model isn't defined yet, the
10
+ * extension waits and is applied the moment `createModel(name)` runs -
11
+ * which is what lets independent packages extend each other's models
12
+ * without agreeing on an import order.
13
+ *
14
+ * An override can change a field's options but not its `type`, and
15
+ * can't turn a stored field into a computed one (or back): either would
16
+ * silently change a column.
17
+ *
18
+ * Returns the SAME Model object `createModel(name)` returns - there is
19
+ * only ever one per model name, shared by everyone who calls either
20
+ * function for it - so it is usable straight away, whether
21
+ * `createModel(name)` ran before this or hasn't run yet:
22
+ *
23
+ * export const OrderInvoice = extendModel("invoice", {
24
+ * fields: { orderId: { type: "integer", required: true, unique: true } },
25
+ * relations: { order: { type: "belongsTo", model: "order", foreignKey: "orderId" } },
26
+ * });
27
+ * await OrderInvoice.create({ id: 1, orderId: 7, amountCents: 4200 });
28
+ *
29
+ * The model doesn't need to exist yet for this to work (the extension
30
+ * itself waits, same as always, until `createModel(name)` defines it -
31
+ * see ModelRegistry) - but every one of `OrderInvoice`'s methods does a
32
+ * real database read or write, so calling one before the base model is
33
+ * defined and `syncModels()` has run fails the way it always would.
34
+ *
35
+ * `extension.hooks` on a MIXIN (a name defined with `defineMixin`, not
36
+ * `createModel`) needs the mixin already defined - see `defineMixin()`'s
37
+ * docstring for why hooks on a mixin work differently from its fields.
38
+ *
39
+ * @param {string} name - the model to extend
40
+ * @param {Object} extension
41
+ * @param {Record<string, object>} [extension.fields]
42
+ * @param {Record<string, object>} [extension.relations]
43
+ * @param {string[]} [extension.mixins]
44
+ * @param {Partial<Record<typeof HOOK_NAMES[number], Function|Function[]>>} [extension.hooks]
45
+ * @param {string} [extension.origin] - the contributing package's name, for error messages and `schema.origins`
46
+ * @returns {Model}
47
+ */
48
+ export declare function extendModel(name: string, extension?: {
49
+ fields?: Record<string, object>;
50
+ relations?: Record<string, object>;
51
+ mixins?: string[];
52
+ hooks?: Partial<Record<typeof HOOK_NAMES[number], Function | Function[]>>;
53
+ origin?: string;
54
+ }): Model;
55
+ /**
56
+ * Defines an abstract model: fields and relations (and, unlike a plain
57
+ * `createModel()` schema, hooks too) that other models pull in with
58
+ * `mixins: [name]`. It has no table and no query methods of its own.
59
+ *
60
+ * A model picks up a mixin's hooks - alongside its fields and relations -
61
+ * at the moment IT is created, following whatever the mixin has at that
62
+ * point; they run before the model's own hooks of the same name. That
63
+ * makes the ordering requirement the mirror image of everything else in
64
+ * this file: `defineMixin(name, { hooks })` (or `extendModel(name, {
65
+ * hooks })` once the mixin already exists) must happen BEFORE
66
+ * `createModel(other, { mixins: [name] })`, not after. This is narrower
67
+ * than how a mixin's FIELDS behave - extending a mixin's fields later
68
+ * reaches every model already using it, because fields are just data
69
+ * folded into a descriptor on demand. A hook is a live registration
70
+ * against a running `HookRegistry`; reaching backwards into models that
71
+ * already resolved would mean either firing the same handler twice for
72
+ * models processed once already, or building a way to tell "already
73
+ * applied" apart from "new since last time" - real complexity for a
74
+ * pattern (adding a hook to a mixin after code already depends on it)
75
+ * that's rare in practice. Declare a mixin's hooks up front.
76
+ *
77
+ * @param {string} name
78
+ * @param {Object} definition
79
+ * @param {Record<string, object>} definition.fields
80
+ * @param {Record<string, object>} [definition.relations]
81
+ * @param {string[]} [definition.mixins]
82
+ * @param {Partial<Record<typeof HOOK_NAMES[number], Function|Function[]>>} [definition.hooks]
83
+ * @param {string} [definition.origin]
84
+ */
85
+ export declare function defineMixin(name: string, definition: {
86
+ fields: Record<string, object>;
87
+ relations?: Record<string, object>;
88
+ mixins?: string[];
89
+ hooks?: Partial<Record<typeof HOOK_NAMES[number], Function | Function[]>>;
90
+ origin?: string;
91
+ }): void;
92
+ export type Model = {
93
+ name: string;
94
+ schema: import('../models/define-model.js').ModelDescriptor;
95
+ create: (data: Record<string, unknown>, options?: {
96
+ trx?: object;
97
+ }) => Promise<object>;
98
+ createMany: (dataList: Record<string, unknown>[], options?: {
99
+ trx?: object;
100
+ chunkSize?: number;
101
+ }) => Promise<object[]>;
102
+ find: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<object[]>;
103
+ findOne: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<object | null>;
104
+ updateMany: (filter: Record<string, unknown> | unknown[], data: Record<string, unknown>) => Promise<number>;
105
+ deleteMany: (filter: Record<string, unknown> | unknown[]) => Promise<number>;
106
+ loadMany: (documents: object[], spec: string | string[] | object, options?: object) => Promise<object[]>;
107
+ load: (document: object, relationName: string, options?: object) => Promise<unknown>;
108
+ paginate: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<import('../crud/paginate.js').Page>;
109
+ aggregate: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<Array<Record<string, unknown>>>;
110
+ count: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<number>;
111
+ sum: (field: string, filter?: Record<string, unknown> | unknown[], options?: object) => Promise<number | null>;
112
+ avg: (field: string, filter?: Record<string, unknown> | unknown[], options?: object) => Promise<number | null>;
113
+ min: (field: string, filter?: Record<string, unknown> | unknown[], options?: object) => Promise<unknown>;
114
+ max: (field: string, filter?: Record<string, unknown> | unknown[], options?: object) => Promise<unknown>;
115
+ attach: (source: object | number | string, relationName: string, targetIds: unknown) => Promise<number>;
116
+ attachMany: (relationName: string, links: Array<{
117
+ source: object | number | string;
118
+ targets: unknown;
119
+ }>, options?: {
120
+ trx?: object;
121
+ }) => Promise<number>;
122
+ detach: (source: object | number | string, relationName: string, targetIds: unknown) => Promise<number>;
123
+ };
124
+ /**
125
+ * @typedef {Object} Model
126
+ * @property {string} name
127
+ * @property {import('../models/define-model.js').ModelDescriptor} schema
128
+ * @property {(data: Record<string, unknown>, options?: { trx?: object }) => Promise<object>} create
129
+ * @property {(dataList: Record<string, unknown>[], options?: { trx?: object, chunkSize?: number }) => Promise<object[]>} createMany
130
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<object[]>} find
131
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<object|null>} findOne
132
+ * @property {(filter: Record<string, unknown>|unknown[], data: Record<string, unknown>) => Promise<number>} updateMany
133
+ * @property {(filter: Record<string, unknown>|unknown[]) => Promise<number>} deleteMany
134
+ * @property {(documents: object[], spec: string|string[]|object, options?: object) => Promise<object[]>} loadMany
135
+ * @property {(document: object, relationName: string, options?: object) => Promise<unknown>} load
136
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<import('../crud/paginate.js').Page>} paginate
137
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<Array<Record<string, unknown>>>} aggregate
138
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<number>} count
139
+ * @property {(field: string, filter?: Record<string, unknown>|unknown[], options?: object) => Promise<number|null>} sum
140
+ * @property {(field: string, filter?: Record<string, unknown>|unknown[], options?: object) => Promise<number|null>} avg
141
+ * @property {(field: string, filter?: Record<string, unknown>|unknown[], options?: object) => Promise<unknown>} min
142
+ * @property {(field: string, filter?: Record<string, unknown>|unknown[], options?: object) => Promise<unknown>} max
143
+ * @property {(source: object|number|string, relationName: string, targetIds: unknown) => Promise<number>} attach
144
+ * @property {(relationName: string, links: Array<{ source: object|number|string, targets: unknown }>, options?: { trx?: object }) => Promise<number>} attachMany
145
+ * @property {(source: object|number|string, relationName: string, targetIds: unknown) => Promise<number>} detach
146
+ */
147
+ /**
148
+ * Defines a model against the shared default registry/connection and
149
+ * returns a `Model` object you can export and import anywhere - no
150
+ * `client`, `UnitOfWork`, or registry needs to be threaded through by
151
+ * hand at the call site, the same way a Mongoose model works once
152
+ * `mongoose.connect()` has been called once at startup.
153
+ *
154
+ * Every document `create()`/`find()`/`findOne()` returns is
155
+ * self-contained: it carries its own `.save()`/`.delete()` that know
156
+ * how to persist themselves using this Model's shared connection and
157
+ * hooks, with no external "unit of work" object needed. There is
158
+ * deliberately no identity map here - two `find()` calls for the same
159
+ * row return two DIFFERENT object instances, same as Mongoose. Dirty
160
+ * tracking doesn't need one: each document independently remembers
161
+ * its own as-loaded values (see `uow/entity.js`), so this is a real
162
+ * simplification, not a missing feature. For the cases that do need
163
+ * one, wrap the work in `withIdentityMap(fn)`: inside it every
164
+ * find/create returns one instance per row, scoped to that call (see
165
+ * identity-scope.js). A `UnitOfWork`/`createClient()` also has one.
166
+ *
167
+ * Hooks are declared inline, Mongoose-style, rather than through a
168
+ * separately-constructed `HookRegistry` the caller has to remember to
169
+ * pass around: `{ hooks: { beforeCreate(data) {...} } }`. Each hook
170
+ * name maps to one function or an array of functions (run in order).
171
+ *
172
+ * @param {string} name
173
+ * @param {Object} schema
174
+ * @param {string} [schema.table]
175
+ * @param {Record<string, object>} schema.fields
176
+ * @param {Record<string, object>} [schema.relations]
177
+ * @param {string[]} [schema.mixins] - abstract models (see defineMixin) whose fields this model includes
178
+ * @param {string} [schema.origin]
179
+ * @param {Partial<Record<typeof HOOK_NAMES[number], Function|Function[]>>} [schema.hooks]
180
+ * @returns {Model}
181
+ */
182
+ export declare function createModel(name: string, schema: {
183
+ table?: string;
184
+ fields: Record<string, object>;
185
+ relations?: Record<string, object>;
186
+ mixins?: string[];
187
+ origin?: string;
188
+ hooks?: Partial<Record<typeof HOOK_NAMES[number], Function | Function[]>>;
189
+ }): Model;
@@ -0,0 +1,32 @@
1
+ import { ReportHandle } from "../reports/report-handle.js";
2
+ /**
3
+ * Defines a report on the global API and returns its handle: a read-only, transient model
4
+ * whose rows are summaries - group keys plus aggregates - computed in ONE SQL statement. It has no
5
+ * table, is never synced or migrated, and is not part of the model registry.
6
+ *
7
+ * ```js
8
+ * export const SalesByCustomer = createReport("salesByCustomer", {
9
+ * from: "order",
10
+ * where: [["status", "!=", "cancelled"]],
11
+ * fields: {
12
+ * customerId: true,
13
+ * customerName: "customer.name",
14
+ * orders: { agg: "count" },
15
+ * revenue: { agg: "sum", of: "total" },
16
+ * items: { agg: "sum", of: "items.qty" },
17
+ * },
18
+ * orderBy: "-revenue",
19
+ * });
20
+ *
21
+ * await SalesByCustomer.find([["revenue", ">", 1000]], { limit: 10 });
22
+ * await SalesByCustomer.count();
23
+ * ```
24
+ *
25
+ * See defineReport() for what a definition may contain. The models it reads need not exist yet
26
+ * (they are looked up on first use), so reports can live in their own files.
27
+ *
28
+ * @param {string} name
29
+ * @param {object} definition
30
+ * @returns {ReportHandle}
31
+ */
32
+ export declare function createReport(name: string, definition: object): ReportHandle;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * DTO schemas (create/update/read) for one model registered via
3
+ * `createModel()`, using the default registry - the Mongoose-style
4
+ * API's equivalent of calling `generateDTOSchemas(model)` directly
5
+ * with an explicit `ModelRegistry`.
6
+ *
7
+ * @param {string} modelName
8
+ * @returns {{ create: object, update: object, read: object }}
9
+ */
10
+ export declare function generateModelDTOs(modelName: string): {
11
+ create: object;
12
+ update: object;
13
+ read: object;
14
+ };
15
+ /**
16
+ * DTO schemas for every model registered via `createModel()`.
17
+ *
18
+ * @returns {Record<string, { create: object, update: object, read: object }>}
19
+ */
20
+ export declare function generateAllModelDTOs(): Record<string, {
21
+ create: object;
22
+ update: object;
23
+ read: object;
24
+ }>;
25
+ /**
26
+ * JSDoc `@typedef` blocks for every model registered via
27
+ * `createModel()`, concatenated into one file-ready string.
28
+ *
29
+ * @returns {string}
30
+ */
31
+ export declare function generateModelJSDoc(): string;
@@ -0,0 +1,12 @@
1
+ /** @param {string} glob an absolute, forward-slash pattern */
2
+ export declare function globToRegExp(glob: string): RegExp;
3
+ /**
4
+ * Expands glob patterns to the files they match: absolute paths, sorted, no duplicates.
5
+ * Relative patterns are resolved against `cwd`. A `!pattern` removes files matched by
6
+ * the patterns before it.
7
+ *
8
+ * @param {string[]} patterns
9
+ * @param {string} cwd
10
+ * @returns {Promise<string[]>}
11
+ */
12
+ export declare function expandGlobs(patterns: string[], cwd: string): Promise<string[]>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Runs `fn` with a fresh identity map. Returns whatever `fn` returns;
3
+ * a throw propagates. Nesting starts a new, independent map for the
4
+ * inner call (like a nested `withUnitOfWork`), rather than joining the
5
+ * outer one.
6
+ *
7
+ * @template T
8
+ * @param {() => Promise<T>|T} fn
9
+ * @returns {Promise<T>|T}
10
+ */
11
+ export declare function withIdentityMap<T>(fn: () => Promise<T> | T): Promise<T> | T;
12
+ /**
13
+ * The map for the current async context, or undefined when not inside
14
+ * `withIdentityMap()`. Keys are `${modelName}:${id}`.
15
+ *
16
+ * @returns {Map<string, object>|undefined}
17
+ */
18
+ export declare function currentIdentityMap(): Map<string, object> | undefined;