@getstrata/core 3.0.7 → 3.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.
- package/CHANGELOG.md +10 -873
- package/README.md +20 -57
- package/dist/core/database/definitions.d.ts +8 -2
- package/dist/core/database/driverPorts.d.ts +1 -1
- package/dist/core/database/index.d.ts +3 -2
- package/dist/core/database/model.d.ts +19 -4
- package/dist/core/database/modelAuthoring.d.ts +64 -0
- package/dist/core/database/modelRegistry.d.ts +5 -1
- package/dist/core/database/modelRelationTypes.d.ts +14 -0
- package/dist/core/database/ormInternal.d.ts +2 -1
- package/dist/core/database/ormRuntime.d.ts +2 -1
- package/dist/core/http/index.d.ts +2 -2
- package/dist/core/http/parseMultipartUpload.d.ts +1 -0
- package/dist/core/http/streamingUpload.d.ts +20 -0
- package/dist/core/http/uploadContent.d.ts +6 -0
- package/dist/core/media/imageTransform.d.ts +25 -1
- package/dist/entries/database/bindings.js +34 -11
- package/dist/entries/database/definitions.js +6 -0
- package/dist/entries/database/ownedReadOnlyObservation.js +3 -1
- package/dist/entries/http/parseMultipartUpload.js +408 -20
- package/dist/entries/media/imageTransform.js +110 -20
- package/dist/framework/public-api.d.ts +4 -3
- package/dist/index.js +70 -102
- package/dist/internal/ormRuntime.js +173 -9
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,72 +1,35 @@
|
|
|
1
1
|
# @getstrata/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Database models, HTTP utilities, authentication, queues, mail, storage, and security for [Strata](https://github.com/EyK-26/strata/blob/main/README.md) applications. Requires Bun >=1.4.4; tested on Bun 1.4.4.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Start an application with the generator:
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
8
|
bunx create-strata my-app
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
To add the runtime library to an existing project:
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
```typescript
|
|
16
|
-
import { createAuthMiddleware } from "@getstrata/core/http/authMiddleware";
|
|
17
|
-
import { createModel } from "@getstrata/core/database/model";
|
|
18
|
-
import { defineTable } from "@getstrata/core/database/table";
|
|
19
|
-
import { BaseRepository } from "@getstrata/core/database/baseRepository";
|
|
20
|
-
import { FormRequest } from "@getstrata/core/http/formRequest";
|
|
21
|
-
import { Policy } from "@getstrata/core/auth/policy";
|
|
22
|
-
import { withErrorHandling } from "@getstrata/core/http/response";
|
|
23
|
-
import { ValidationError } from "@getstrata/core/errors/http";
|
|
24
|
-
import type { Migration } from "@getstrata/core/database/migrations/types";
|
|
13
|
+
```bash
|
|
14
|
+
bun add @getstrata/core
|
|
25
15
|
```
|
|
26
16
|
|
|
27
|
-
|
|
28
|
-
`@getstrata/core/testing`.
|
|
29
|
-
|
|
30
|
-
## Database
|
|
31
|
-
|
|
32
|
-
The application owns its connection and execution sessions. Configure its selected
|
|
33
|
-
engine at startup, then use `database.model(definition)` or
|
|
34
|
-
`database.repository(definition)` from the current execution. Transactions select
|
|
35
|
-
models and repositories from their supplied transaction session. Global default
|
|
36
|
-
pools, named-connection registries and `bindBunSql` are retired.
|
|
37
|
-
|
|
38
|
-
Use `createModel` and `defineTable` for ordinary models. Custom repository,
|
|
39
|
-
connection and adapter APIs remain available for advanced integrations; see the
|
|
40
|
-
[database guide](https://github.com/EyK-26/strata/blob/main/docs/DATABASE.md).
|
|
41
|
-
|
|
42
|
-
`orderBy` takes `{ column, direction }` objects or column shorthand such as `{ published_at: "desc" }`. `{ ilike }` uses the value as-is, so pass `%term%` yourself.
|
|
43
|
-
|
|
44
|
-
Full-text `tsMatch` is PostgreSQL only.
|
|
17
|
+
Use focused public subpaths. Ordinary models extend `defineModel`; fields supply both runtime metadata and inferred attribute types:
|
|
45
18
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
Generated apps do not include an admin dashboard, and the registry is optional.
|
|
59
|
-
|
|
60
|
-
## Docs
|
|
19
|
+
```typescript
|
|
20
|
+
import { defineModel, field } from "@getstrata/core/database/model";
|
|
21
|
+
|
|
22
|
+
export class Note extends defineModel({
|
|
23
|
+
table: "notes",
|
|
24
|
+
fields: { id: field.number(), body: field.string() },
|
|
25
|
+
}) {
|
|
26
|
+
static $fillable = ["body"] as const;
|
|
27
|
+
static $timestamps = false;
|
|
28
|
+
}
|
|
29
|
+
```
|
|
61
30
|
|
|
62
|
-
|
|
63
|
-
- [Building apps](https://github.com/EyK-26/strata/blob/main/docs/BUILDING-APPS.md)
|
|
64
|
-
- [Auth choices](https://github.com/EyK-26/strata/blob/main/docs/AUTH.md)
|
|
65
|
-
- [Databases](https://github.com/EyK-26/strata/blob/main/docs/DATABASE.md)
|
|
66
|
-
- [Production](https://github.com/EyK-26/strata/blob/main/docs/PRODUCTION.md)
|
|
31
|
+
Register the class with the application, then query through the current execution's `database.model(Note)`. Inside a transaction, use its supplied database session. Schema changes belong in migrations.
|
|
67
32
|
|
|
68
|
-
|
|
33
|
+
Other public APIs include `FormRequest` from `@getstrata/core/http/formRequest`, `Policy` from `@getstrata/core/auth/policy`, and response helpers from `@getstrata/core/http/response`. Testing controls live on `@getstrata/core/testing`.
|
|
69
34
|
|
|
70
|
-
|
|
71
|
-
These controls share the package's private runtime state and are absent from the root
|
|
72
|
-
and every production subpath. Restore changed controls after each test.
|
|
35
|
+
See the [project README](https://github.com/EyK-26/strata/blob/main/README.md) and the guides for [databases](https://github.com/EyK-26/strata/blob/main/docs/DATABASE.md), [authentication](https://github.com/EyK-26/strata/blob/main/docs/AUTH.md), [tenancy](https://github.com/EyK-26/strata/blob/main/docs/TENANCY.md), [queues](https://github.com/EyK-26/strata/blob/main/docs/QUEUES.md), [storage](https://github.com/EyK-26/strata/blob/main/docs/STORAGE.md), and [media](https://github.com/EyK-26/strata/blob/main/docs/MEDIA.md).
|
|
@@ -7,6 +7,7 @@ import type { BaseRepository } from "./baseRepository";
|
|
|
7
7
|
import type { DatabaseCapabilities } from "./driverPorts";
|
|
8
8
|
import type { Model } from "./model";
|
|
9
9
|
import type { ModelCasts } from "./modelAttributes";
|
|
10
|
+
import type { AnyModelClass, ClassModelKey, ClassModelRow } from "./modelAuthoring";
|
|
10
11
|
import type { ModelQuery, RelationNameInput } from "./modelQuery";
|
|
11
12
|
import type { AnyRelationQuery } from "./relationQuery";
|
|
12
13
|
import type { RepositoryQuery } from "./repositoryQuery";
|
|
@@ -80,7 +81,7 @@ interface RepositoryEffect {
|
|
|
80
81
|
}
|
|
81
82
|
declare const effectsBrand: unique symbol;
|
|
82
83
|
interface RepositoryEffectsDeclaration {
|
|
83
|
-
readonly definition: AnyRepositoryDefinition;
|
|
84
|
+
readonly definition: AnyRepositoryDefinition | AnyModelClass;
|
|
84
85
|
readonly effects: readonly RepositoryEffect[];
|
|
85
86
|
readonly [effectsBrand]: object;
|
|
86
87
|
}
|
|
@@ -203,7 +204,12 @@ declare function assertDefinition(value: unknown, kind: "repository"): asserts v
|
|
|
203
204
|
declare function assertDefinition(value: unknown, kind: "model"): asserts value is AnyModelDefinition;
|
|
204
205
|
export type { AfterCommitRepositoryContext, AfterCommitRepositoryListener, AnyModelDefinition, AnyRepositoryDefinition, BoundModel, ModelAttributeOptions, ModelBinding, ModelDefinition, ModelIdentity, ModelObserver, ModelState, RepositoryAction, RepositoryBinding, RepositoryDefinition, RepositoryEffect, RepositoryHooks, RepositoryPublication, TransactionalRepositoryListener, };
|
|
205
206
|
export { assertDefinition, defineModel, defineRepository };
|
|
206
|
-
declare function repositoryEffects<R extends object, K extends keyof R & string, T extends BaseRepository<R, K>>(definition: RepositoryDefinition<R, K, T>, effects: readonly TypedRepositoryEffect<R, K>[]): RepositoryEffectsDeclaration
|
|
207
|
+
declare function repositoryEffects<R extends object, K extends keyof R & string, T extends BaseRepository<R, K>>(definition: RepositoryDefinition<R, K, T>, effects: readonly TypedRepositoryEffect<R, K>[]): RepositoryEffectsDeclaration & {
|
|
208
|
+
readonly definition: AnyRepositoryDefinition;
|
|
209
|
+
};
|
|
207
210
|
declare function assertRepositoryEffectsDeclaration(value: unknown): asserts value is RepositoryEffectsDeclaration;
|
|
208
211
|
export type { RepositoryEffectsDeclaration, TypedRepositoryEffect };
|
|
209
212
|
export { assertRepositoryEffectsDeclaration, repositoryEffects };
|
|
213
|
+
/** Attach effects to a class model's implicit repository at registry snapshot time. */
|
|
214
|
+
declare function modelEffects<C extends AnyModelClass>(model: C, effects: readonly TypedRepositoryEffect<ClassModelRow<C>, ClassModelKey<C>>[]): RepositoryEffectsDeclaration;
|
|
215
|
+
export { modelEffects };
|
|
@@ -38,7 +38,7 @@ type DatabaseDefinition = Readonly<{
|
|
|
38
38
|
default: string;
|
|
39
39
|
connections: Readonly<Record<string, DatabaseConnectionOptions>>;
|
|
40
40
|
repositories?: readonly import("./definitions").AnyRepositoryDefinition[];
|
|
41
|
-
models?: readonly import("./definitions").AnyModelDefinition[];
|
|
41
|
+
models?: readonly (import("./definitions").AnyModelDefinition | import("./modelAuthoring").AnyModelClass)[];
|
|
42
42
|
repositoryEffects?: readonly import("./definitions").RepositoryEffectsDeclaration[];
|
|
43
43
|
preparation?: readonly import("../contracts/token").AnyServiceToken[];
|
|
44
44
|
}>;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
export type { AfterCommitRepositoryContext, AfterCommitRepositoryListener, BoundModel, ModelBinding, ModelDefinition, ModelObserver, ModelState, RepositoryBinding, RepositoryDefinition, RepositoryEffectsDeclaration, RepositoryHooks, TransactionalRepositoryListener, TypedRepositoryEffect, } from "@getstrata/core/database/definitions";
|
|
2
|
-
export {
|
|
2
|
+
export { defineRepository, modelEffects, repositoryEffects, } from "@getstrata/core/database/definitions";
|
|
3
3
|
export { mapDatabaseError, RecordNotFoundError, withDatabaseErrorHandling, } from "@getstrata/core/database/errors";
|
|
4
4
|
export type { FactoryBehavior, FactoryConstruction, FactoryDefinition, FactoryMakeResult, FactoryParent, FactoryPersist, StatelessFactoryConstruction, } from "@getstrata/core/database/factory";
|
|
5
5
|
export { defineFactory, Factory } from "@getstrata/core/database/factory";
|
|
6
|
-
export {
|
|
6
|
+
export type { AnyModelClass, AuthoredModelClass, InferModelFields, ModelClassOptions, ModelField, ModelFields, } from "@getstrata/core/database/model";
|
|
7
|
+
export { BaseRepository, BelongsToManyRelationQuery, BelongsToRelationQuery, createModel, defineModel, field, HasManyRelationQuery, HasManyThroughRelationQuery, HasOneRelationQuery, Model, ModelQuery, MorphManyRelationQuery, MorphOneRelationQuery, MorphToRelationQuery, modelTable, RepositoryQuery, } from "#strata-orm-runtime";
|
|
7
8
|
export { createDatabaseConnection } from "./connection.ts";
|
|
8
9
|
export type { ActiveDatabaseHandle } from "./connectionContext.ts";
|
|
9
10
|
export { getActiveDatabaseConnection, hasActiveDatabaseConnection, runWithDatabaseConnection, } from "./connectionContext.ts";
|
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
import type { AnyModelDefinition, ModelAttributeOptions, ModelBinding, ModelDefinition, ModelObserver, ModelState, RepositoryDefinition } from "@getstrata/core/database/definitions";
|
|
2
|
+
import { defineModel as defineModelDefinition } from "@getstrata/core/database/definitions";
|
|
2
3
|
import type { ServiceToken } from "../contracts/token";
|
|
3
4
|
import type { KeysetOptions } from "../pagination/index.ts";
|
|
4
5
|
import BaseRepository from "./baseRepository.ts";
|
|
5
6
|
import { applyCasts, type CastType, dehydrateValue, filterMassAssignable, hydrateValue, type LoadedAttributes, type ModelCasts } from "./modelAttributes.ts";
|
|
7
|
+
import type { AnyModelClass, AuthoredModelClass, ClassModelInstance, ClassModelKey, ClassModelRow, InferModelFields, ModelClassOptions, ModelFields } from "./modelAuthoring";
|
|
6
8
|
import { type AnyModel, type ModelAttributes, type ModelIdentifier, type ModelProjection, ModelQuery, type RelationNameInput } from "./modelQuery.ts";
|
|
9
|
+
import type { ModelRelation } from "./modelRelationTypes";
|
|
7
10
|
import type { AnyRelationQuery, RelatedModelClass } from "./relationQuery.ts";
|
|
8
11
|
import { BelongsToManyRelationQuery, BelongsToRelationQuery, HasManyRelationQuery, HasManyThroughRelationQuery, HasOneRelationQuery, MorphManyRelationQuery, MorphOneRelationQuery, MorphToRelationQuery } from "./relationQuery.ts";
|
|
9
12
|
import type { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasOneRelation } from "./relationships.ts";
|
|
10
13
|
import type { RepositoryQuery } from "./repositoryQuery.ts";
|
|
11
14
|
import type { TableDefinition } from "./table";
|
|
12
15
|
import type { ModelWhere, ModelWriteValues, QueryOptions } from "./types.ts";
|
|
13
|
-
type RelatedRef<TRelated extends object, RelatedKey extends keyof TRelated & string, M extends Model<TRelated, RelatedKey> = Model<TRelated, RelatedKey>> = ModelDefinition<TRelated, RelatedKey, M> | string | (() => ModelDefinition<TRelated, RelatedKey, M>);
|
|
16
|
+
type RelatedRef<TRelated extends object, RelatedKey extends keyof TRelated & string, M extends Model<TRelated, RelatedKey> = Model<TRelated, RelatedKey>> = ModelDefinition<TRelated, RelatedKey, M> | AuthoredModelClass<TRelated, RelatedKey, M> | string | (() => ModelDefinition<TRelated, RelatedKey, M> | AuthoredModelClass<TRelated, RelatedKey, M>);
|
|
14
17
|
declare let saveRelatedModel: (entity: AnyModel, forced: LoadedAttributes) => Promise<AnyModel>;
|
|
15
18
|
declare function getModelBinding<R extends object, K extends keyof R & string>(entity: Model<R, K>): ModelBinding<R, K, BaseRepository<R, K>>;
|
|
16
19
|
declare function modelFacade(entity: object): BoundModelFacade<Record<string, unknown>, "id", AnyModel>;
|
|
@@ -40,14 +43,21 @@ declare class Model<TEntity extends object, PrimaryKey extends keyof TEntity & s
|
|
|
40
43
|
loadHasOne<TChild extends object, LocalKey extends keyof TEntity & string, ForeignKey extends keyof TChild & string, Alias extends string>(as: Alias, relation: HasOneRelation<TEntity, TChild, LocalKey, ForeignKey>, childRepository: BaseRepository<TChild, keyof TChild & string>, options?: Omit<QueryOptions<TChild>, "where">): Promise<this & Record<Alias, TChild | undefined>>;
|
|
41
44
|
loadBelongsTo<TParent extends object, ForeignKey extends keyof TEntity & string, OwnerKey extends keyof TParent & string, Alias extends string>(as: Alias, relation: BelongsToRelation<TEntity, TParent, ForeignKey, OwnerKey>, parentRepository: BaseRepository<TParent, OwnerKey>, options?: Omit<QueryOptions<TParent>, "where">): Promise<this & Record<Alias, TParent | undefined>>;
|
|
42
45
|
loadBelongsToMany<TRelated extends object, Pivot extends object, ParentKey extends keyof TEntity & string, RelatedKey extends keyof TRelated & string, ForeignPivotKey extends keyof Pivot & string, RelatedPivotKey extends keyof Pivot & string, Alias extends string>(as: Alias, relation: BelongsToManyRelation<TEntity, TRelated, Pivot, ParentKey, RelatedKey, ForeignPivotKey, RelatedPivotKey>, relatedRepository: BaseRepository<TRelated, RelatedKey>, options?: Omit<QueryOptions<TRelated>, "where">): Promise<this & Record<Alias, TRelated[]>>;
|
|
46
|
+
hasMany<C extends AnyModelClass>(related: C | (() => C), foreignKey?: keyof ClassModelRow<C> & string, localKey?: PrimaryKey): ModelRelation<HasManyRelationQuery<TEntity, PrimaryKey, ClassModelRow<C>, ClassModelKey<C>>, ClassModelInstance<C>>;
|
|
43
47
|
hasMany<TRelated extends object, RelatedKey extends keyof TRelated & string, M extends Model<TRelated, RelatedKey>>(related: RelatedRef<TRelated, RelatedKey, M>, foreignKey?: keyof TRelated & string, localKey?: PrimaryKey): HasManyRelationQuery<TEntity, PrimaryKey, TRelated, RelatedKey>;
|
|
48
|
+
hasOne<C extends AnyModelClass>(related: C | (() => C), foreignKey?: keyof ClassModelRow<C> & string, localKey?: PrimaryKey): ModelRelation<HasOneRelationQuery<TEntity, PrimaryKey, ClassModelRow<C>, ClassModelKey<C>>, ClassModelInstance<C>>;
|
|
44
49
|
hasOne<TRelated extends object, RelatedKey extends keyof TRelated & string, M extends Model<TRelated, RelatedKey>>(related: RelatedRef<TRelated, RelatedKey, M>, foreignKey?: keyof TRelated & string, localKey?: PrimaryKey): HasOneRelationQuery<TEntity, PrimaryKey, TRelated, RelatedKey>;
|
|
50
|
+
belongsTo<C extends AnyModelClass>(related: C | (() => C), foreignKey?: keyof TEntity & string, ownerKey?: ClassModelKey<C>): ModelRelation<BelongsToRelationQuery<TEntity, PrimaryKey, ClassModelRow<C>, ClassModelKey<C>>, ClassModelInstance<C>>;
|
|
45
51
|
belongsTo<TRelated extends object, RelatedKey extends keyof TRelated & string, M extends Model<TRelated, RelatedKey>>(related: RelatedRef<TRelated, RelatedKey, M>, foreignKey?: keyof TEntity & string, ownerKey?: RelatedKey): BelongsToRelationQuery<TEntity, PrimaryKey, TRelated, RelatedKey>;
|
|
52
|
+
hasManyThrough<C extends AnyModelClass, TThrough extends object, ThroughKey extends keyof TThrough & string, ThroughM extends Model<TThrough, ThroughKey>>(related: C | (() => C), through: RelatedRef<TThrough, ThroughKey, ThroughM>, firstKey?: string, secondKey?: keyof ClassModelRow<C> & string, localKey?: PrimaryKey, secondLocalKey?: ThroughKey): ModelRelation<HasManyThroughRelationQuery<TEntity, PrimaryKey, ClassModelRow<C>, ClassModelKey<C>>, ClassModelInstance<C>>;
|
|
46
53
|
hasManyThrough<TRelated extends object, TThrough extends object, RelatedKey extends keyof TRelated & string, ThroughKey extends keyof TThrough & string, M extends Model<TRelated, RelatedKey>, ThroughM extends Model<TThrough, ThroughKey>>(related: RelatedRef<TRelated, RelatedKey, M>, through: RelatedRef<TThrough, ThroughKey, ThroughM>, firstKey?: string, secondKey?: keyof TRelated & string, localKey?: PrimaryKey, secondLocalKey?: ThroughKey): HasManyThroughRelationQuery<TEntity, PrimaryKey, TRelated, RelatedKey>;
|
|
54
|
+
belongsToMany<C extends AnyModelClass, Pivot extends object = Record<string, unknown>>(related: C | (() => C), pivotTable?: string, foreignPivotKey?: keyof Pivot & string, relatedPivotKey?: keyof Pivot & string): ModelRelation<BelongsToManyRelationQuery<TEntity, PrimaryKey, ClassModelRow<C>, ClassModelKey<C>, Pivot>, ClassModelInstance<C>>;
|
|
47
55
|
belongsToMany<TRelated extends object, RelatedKey extends keyof TRelated & string, Pivot extends object = Record<string, unknown>, M extends Model<TRelated, RelatedKey> = Model<TRelated, RelatedKey>>(related: RelatedRef<TRelated, RelatedKey, M>, pivotTable?: string, foreignPivotKey?: keyof Pivot & string, relatedPivotKey?: keyof Pivot & string): BelongsToManyRelationQuery<TEntity, PrimaryKey, TRelated, RelatedKey, Pivot>;
|
|
56
|
+
morphMany<C extends AnyModelClass>(related: C | (() => C), morphName: string, typeKey?: keyof ClassModelRow<C> & string, idKey?: keyof ClassModelRow<C> & string, morphType?: string): ModelRelation<MorphManyRelationQuery<TEntity, PrimaryKey, ClassModelRow<C>, ClassModelKey<C>>, ClassModelInstance<C>>;
|
|
48
57
|
morphMany<TRelated extends object, RelatedKey extends keyof TRelated & string, M extends Model<TRelated, RelatedKey>>(related: RelatedRef<TRelated, RelatedKey, M>, morphName: string, typeKey?: keyof TRelated & string, idKey?: keyof TRelated & string, morphType?: string): MorphManyRelationQuery<TEntity, PrimaryKey, TRelated, RelatedKey>;
|
|
58
|
+
morphOne<C extends AnyModelClass>(related: C | (() => C), morphName: string, typeKey?: keyof ClassModelRow<C> & string, idKey?: keyof ClassModelRow<C> & string, morphType?: string): ModelRelation<MorphOneRelationQuery<TEntity, PrimaryKey, ClassModelRow<C>, ClassModelKey<C>>, ClassModelInstance<C>>;
|
|
49
59
|
morphOne<TRelated extends object, RelatedKey extends keyof TRelated & string, M extends Model<TRelated, RelatedKey>>(related: RelatedRef<TRelated, RelatedKey, M>, morphName: string, typeKey?: keyof TRelated & string, idKey?: keyof TRelated & string, morphType?: string): MorphOneRelationQuery<TEntity, PrimaryKey, TRelated, RelatedKey>;
|
|
50
|
-
morphTo(relatedByType: Record<string, AnyModelDefinition | string | (() => AnyModelDefinition)>, morphName?: string, typeKey?: keyof TEntity & string, idKey?: keyof TEntity & string): MorphToRelationQuery<TEntity, PrimaryKey>;
|
|
60
|
+
morphTo(relatedByType: Record<string, AnyModelDefinition | AnyModelClass | string | (() => AnyModelDefinition | AnyModelClass)>, morphName?: string, typeKey?: keyof TEntity & string, idKey?: keyof TEntity & string): MorphToRelationQuery<TEntity, PrimaryKey>;
|
|
51
61
|
load(...names: RelationNameInput[]): Promise<this>;
|
|
52
62
|
loaded<T = unknown>(name: string): T | undefined;
|
|
53
63
|
setLoaded(name: string, value: unknown): this;
|
|
@@ -169,6 +179,9 @@ declare class BoundModelFacade<R extends object, K extends keyof R & string, M e
|
|
|
169
179
|
}, where: NoInfer<ModelWhere<ModelAttributes<TModel>>>, values?: NoInfer<ModelWriteValues<ModelAttributes<TModel>>>): Promise<TModel>;
|
|
170
180
|
}
|
|
171
181
|
declare function createBoundModel<R extends object, K extends keyof R & string, M extends Model<R, K>>(binding: ModelBinding<R, K, BaseRepository<R, K>>): BoundModelFacade<R, K, M>;
|
|
182
|
+
/** Concise class authoring; low-level definitions remain an explicit extension point. */
|
|
183
|
+
type DefineModel = (<F extends ModelFields, K extends keyof F & string = "id" & keyof F & string>(options: ModelClassOptions<F, K>) => AuthoredModelClass<InferModelFields<F>, K, Model<InferModelFields<F>, K>>) & typeof defineModelDefinition;
|
|
184
|
+
declare const defineModel: DefineModel;
|
|
172
185
|
/** Declare an ordinary model without selecting a database session or constructing entities. */
|
|
173
186
|
declare function createModel<R extends object, K extends keyof R & string>(options: {
|
|
174
187
|
name: string;
|
|
@@ -180,7 +193,9 @@ declare function createModel<R extends object, K extends keyof R & string>(optio
|
|
|
180
193
|
}): ModelDefinition<R, K, Model<R, K>> & {
|
|
181
194
|
readonly repository: RepositoryDefinition<R, K, BaseRepository<R, K>>;
|
|
182
195
|
};
|
|
183
|
-
export {
|
|
196
|
+
export { modelEffects } from "@getstrata/core/database/definitions";
|
|
197
|
+
export type { AnyModelClass, AuthoredModelClass, InferModelFields, ModelClassOptions, ModelField, ModelFields, } from "./modelAuthoring";
|
|
198
|
+
export { field, modelTable } from "./modelAuthoring";
|
|
184
199
|
export { BelongsToManyRelationQuery, BelongsToRelationQuery, HasManyRelationQuery, HasManyThroughRelationQuery, HasOneRelationQuery, MorphManyRelationQuery, MorphOneRelationQuery, MorphToRelationQuery, } from "./relationQuery.ts";
|
|
185
200
|
export type { CastType, ModelAttributes, ModelProjection, RelatedRef };
|
|
186
|
-
export { applyCasts, BoundModelFacade, createBoundModel, createModel, dehydrateValue, filterMassAssignable, getModelBinding, hydrateValue, Model, ModelQuery, modelFacade, runObservers, saveRelatedModel, };
|
|
201
|
+
export { applyCasts, BoundModelFacade, createBoundModel, createModel, defineModel, dehydrateValue, filterMassAssignable, getModelBinding, hydrateValue, Model, ModelQuery, modelFacade, runObservers, saveRelatedModel, };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { AnyModelDefinition, ModelBinding, ModelState } from "@getstrata/core/database/definitions";
|
|
2
|
+
import { Model } from "#strata-orm-runtime";
|
|
3
|
+
import type { BaseRepository as Repository } from "./baseRepository";
|
|
4
|
+
import type { CastType } from "./modelAttributes";
|
|
5
|
+
import type { TableDefinition } from "./table";
|
|
6
|
+
declare const fieldBrand: unique symbol;
|
|
7
|
+
declare const modelClassType: unique symbol;
|
|
8
|
+
/** A typed SQL attribute declaration. Migrations still own the database schema. */
|
|
9
|
+
interface ModelField<T> {
|
|
10
|
+
readonly [fieldBrand]: T;
|
|
11
|
+
readonly cast?: CastType;
|
|
12
|
+
nullable(): ModelField<T | null>;
|
|
13
|
+
}
|
|
14
|
+
declare const field: Readonly<{
|
|
15
|
+
string: () => ModelField<string>;
|
|
16
|
+
number: () => ModelField<number>;
|
|
17
|
+
boolean: () => ModelField<number | boolean>;
|
|
18
|
+
nullable: <T>(value: ModelField<T>) => ModelField<T | null>;
|
|
19
|
+
timestamp: () => ModelField<string | Date>;
|
|
20
|
+
date: () => ModelField<string | Date>;
|
|
21
|
+
json: <T = unknown>() => ModelField<T>;
|
|
22
|
+
binary: () => ModelField<Uint8Array<ArrayBufferLike>>;
|
|
23
|
+
}>;
|
|
24
|
+
type ModelFields = Readonly<Record<string, ModelField<unknown>>>;
|
|
25
|
+
type InferModelFields<F extends ModelFields> = {
|
|
26
|
+
-readonly [P in keyof F]: F[P] extends ModelField<infer T> ? T : never;
|
|
27
|
+
};
|
|
28
|
+
interface AuthoredModelClass<R extends object, K extends keyof R & string, M extends Model<R, K>> {
|
|
29
|
+
new (state: ModelState<R>, binding: ModelBinding<R, K, Repository<R, K>>): M;
|
|
30
|
+
readonly prototype: M;
|
|
31
|
+
readonly [modelClassType]: {
|
|
32
|
+
readonly row: R;
|
|
33
|
+
readonly key: K;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Erased registration identity; generic session overloads recover the concrete class. */
|
|
37
|
+
interface AnyModelClass {
|
|
38
|
+
readonly prototype: object;
|
|
39
|
+
readonly [modelClassType]: {
|
|
40
|
+
readonly row: object;
|
|
41
|
+
readonly key: string;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
type ClassModelRow<C extends AnyModelClass> = C[typeof modelClassType]["row"];
|
|
45
|
+
type ClassModelKey<C extends AnyModelClass> = C[typeof modelClassType]["key"] & keyof ClassModelRow<C> & string;
|
|
46
|
+
type ClassModelInstance<C extends AnyModelClass> = C["prototype"] & Model<ClassModelRow<C>, ClassModelKey<C>>;
|
|
47
|
+
type ModelClassOptions<F extends ModelFields, K extends keyof F & string = "id" & keyof F & string> = {
|
|
48
|
+
table: string;
|
|
49
|
+
fields: F;
|
|
50
|
+
primaryKey?: K;
|
|
51
|
+
name?: string;
|
|
52
|
+
defaultOrderBy?: TableDefinition<InferModelFields<F>, K>["defaultOrderBy"];
|
|
53
|
+
softDeletes?: TableDefinition<InferModelFields<F>, K>["softDeletes"];
|
|
54
|
+
} & ("id" extends keyof F ? unknown : {
|
|
55
|
+
primaryKey: K;
|
|
56
|
+
});
|
|
57
|
+
declare function defineAuthoredModel<F extends ModelFields, K extends keyof F & string = "id" & keyof F & string>(options: ModelClassOptions<F, K>): AuthoredModelClass<InferModelFields<F>, K, Model<InferModelFields<F>, K>>;
|
|
58
|
+
declare function isModelClass(value: unknown): value is AnyModelClass;
|
|
59
|
+
/** Called once per registry snapshot, never during session lookup or relation resolution. */
|
|
60
|
+
declare function createClassModelDefinition(model: AnyModelClass): AnyModelDefinition;
|
|
61
|
+
/** Immutable table declaration for bootstrap integrations; performs no database work. */
|
|
62
|
+
declare function modelTable<C extends AnyModelClass>(model: C): Readonly<TableDefinition<ClassModelRow<C>, ClassModelKey<C>>>;
|
|
63
|
+
export type { AnyModelClass, AuthoredModelClass, ClassModelInstance, ClassModelKey, ClassModelRow, InferModelFields, ModelClassOptions, ModelField, ModelFields, };
|
|
64
|
+
export { createClassModelDefinition, defineAuthoredModel, field, isModelClass, modelTable };
|
|
@@ -6,6 +6,7 @@ import type { ExecutionContext } from "../contracts/application";
|
|
|
6
6
|
import type { OwnedExecution } from "../contracts/executionOwnership";
|
|
7
7
|
import { EventBus } from "../events/eventBusClass";
|
|
8
8
|
import type { RawPool } from "./driverPorts";
|
|
9
|
+
import type { AnyModelClass, ClassModelInstance, ClassModelKey, ClassModelRow } from "./modelAuthoring";
|
|
9
10
|
import type { DatabaseSession } from "./session";
|
|
10
11
|
interface PreparedRepository {
|
|
11
12
|
readonly definition: AnyRepositoryDefinition;
|
|
@@ -22,14 +23,16 @@ interface PreparedRegistry {
|
|
|
22
23
|
readonly repositories: ReadonlyMap<AnyRepositoryDefinition, PreparedRepository>;
|
|
23
24
|
readonly models: ReadonlyMap<AnyModelDefinition, PreparedModel>;
|
|
24
25
|
readonly names: ReadonlyMap<string, AnyModelDefinition>;
|
|
26
|
+
readonly classes: ReadonlyMap<AnyModelClass, AnyModelDefinition>;
|
|
25
27
|
}
|
|
26
28
|
interface RegistrySnapshot {
|
|
29
|
+
readonly classes: ReadonlyMap<AnyModelClass, AnyModelDefinition>;
|
|
27
30
|
readonly repositories: readonly AnyRepositoryDefinition[];
|
|
28
31
|
readonly models: readonly AnyModelDefinition[];
|
|
29
32
|
readonly dependencies: readonly AnyServiceToken[];
|
|
30
33
|
readonly repositoryEffects: readonly RepositoryEffectsDeclaration[];
|
|
31
34
|
}
|
|
32
|
-
declare function snapshotRegistry(repositories?: readonly AnyRepositoryDefinition[], models?: readonly AnyModelDefinition[], repositoryEffects?: readonly RepositoryEffectsDeclaration[]): RegistrySnapshot;
|
|
35
|
+
declare function snapshotRegistry(repositories?: readonly AnyRepositoryDefinition[], models?: readonly (AnyModelDefinition | AnyModelClass)[], repositoryEffects?: readonly RepositoryEffectsDeclaration[]): RegistrySnapshot;
|
|
33
36
|
declare function prepareRegistry(snapshot: RegistrySnapshot, values: readonly unknown[], app: object): PreparedRegistry;
|
|
34
37
|
interface SessionAuthority {
|
|
35
38
|
readonly pool: RawPool;
|
|
@@ -42,6 +45,7 @@ interface SessionAuthority {
|
|
|
42
45
|
}
|
|
43
46
|
interface BoundRegistry {
|
|
44
47
|
repository<R extends object, K extends keyof R & string, T extends BaseRepository<R, K>>(definition: RepositoryDefinition<R, K, T>): T;
|
|
48
|
+
model<C extends AnyModelClass>(model: C): BoundModel<ClassModelRow<C>, ClassModelKey<C>, ClassModelInstance<C>>;
|
|
45
49
|
model<R extends object, K extends keyof R & string, M extends Model<R, K>>(definition: ModelDefinition<R, K, M>): BoundModel<R, K, M>;
|
|
46
50
|
}
|
|
47
51
|
/** One closure per execution; every facade attaches exactly one constructor cache. */
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ModelAttributes } from "./modelQuery";
|
|
2
|
+
import type { RelatedRecord } from "./relationQuery";
|
|
3
|
+
import type { ModelWhere } from "./types";
|
|
4
|
+
type RelationValue<V, M> = V extends RelatedRecord[] ? M[] : V extends RelatedRecord ? M : V;
|
|
5
|
+
type RelationQueryShape = {
|
|
6
|
+
get(): Promise<RelatedRecord | RelatedRecord[] | null>;
|
|
7
|
+
};
|
|
8
|
+
type BuilderMethod = "where" | "orderBy" | "limit" | "withPivotValues" | "snapshot";
|
|
9
|
+
type ModelMethod = "get" | "first" | "create" | "createMany" | "save";
|
|
10
|
+
/** Class-reference relations retain the subclass through terminals and builder chaining. */
|
|
11
|
+
type ModelRelation<Q extends RelationQueryShape, M extends object> = Omit<Q, BuilderMethod | ModelMethod | "then"> & {
|
|
12
|
+
[P in keyof Q as P extends BuilderMethod | ModelMethod ? P : never]: P extends "where" ? (where: ModelWhere<ModelAttributes<M>>) => ModelRelation<Q, M> : P extends "create" ? (values?: Partial<ModelAttributes<M>>) => Promise<M> : P extends "createMany" ? (values: readonly Partial<ModelAttributes<M>>[]) => Promise<M[]> : P extends "save" ? (model: M | Partial<ModelAttributes<M>>) => Promise<M> : Q[P] extends (...args: infer A) => infer R ? P extends BuilderMethod ? (...args: A) => ModelRelation<Q, M> : (...args: A) => Promise<RelationValue<Awaited<R>, M>> : never;
|
|
13
|
+
} & PromiseLike<RelationValue<Awaited<ReturnType<Q["get"]>>, M>>;
|
|
14
|
+
export type { ModelRelation };
|
|
@@ -4,6 +4,7 @@ import type { BaseRepository } from "./baseRepository";
|
|
|
4
4
|
import type { AnyModelDefinition, AnyRepositoryDefinition, BoundModel, ModelBinding, ModelDefinition, ModelObserver, ModelState, RepositoryAction, RepositoryBinding, RepositoryDefinition, RepositoryHooks } from "./definitions";
|
|
5
5
|
import type { DatabaseConnectionOptions, DatabaseDriver } from "./driverPorts";
|
|
6
6
|
import type { Model } from "./model";
|
|
7
|
+
import type { AuthoredModelClass } from "./modelAuthoring";
|
|
7
8
|
import type { DatabaseSession } from "./session";
|
|
8
9
|
import type { TransactionSession } from "./transactionSession";
|
|
9
10
|
type Session = DatabaseSession | TransactionSession;
|
|
@@ -16,7 +17,7 @@ interface BindingPorts<R extends object, K extends keyof R & string> {
|
|
|
16
17
|
readonly hooks: RepositoryHooks<R, K> | undefined;
|
|
17
18
|
readonly assertActive: () => void;
|
|
18
19
|
readonly repository: <A extends object, B extends keyof A & string, T extends BaseRepository<A, B>>(definition: RepositoryDefinition<A, B, T>) => T;
|
|
19
|
-
readonly model: <A extends object, B extends keyof A & string, M extends Model<A, B>>(definition: ModelDefinition<A, B, M> | string) => BoundModel<A, B, M>;
|
|
20
|
+
readonly model: <A extends object, B extends keyof A & string, M extends Model<A, B>>(definition: ModelDefinition<A, B, M> | AuthoredModelClass<A, B, M> | string) => BoundModel<A, B, M>;
|
|
20
21
|
readonly reselect: <T extends BaseRepository<R, K>>(session: Session) => T;
|
|
21
22
|
readonly assertMutation: (action: RepositoryAction) => void;
|
|
22
23
|
readonly mutation: <V>(action: RepositoryAction, work: (repository: BaseRepository<R, K>) => V | Promise<V>) => Promise<V>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Canonical ORM classes and private construction accessors; package-private entry. */
|
|
2
2
|
export { default as BaseRepository, getRepositoryBinding } from "./baseRepository";
|
|
3
|
-
export { BelongsToManyRelationQuery, BelongsToRelationQuery, BoundModelFacade, createBoundModel, createModel, getModelBinding, HasManyRelationQuery, HasManyThroughRelationQuery, HasOneRelationQuery, Model, ModelQuery, MorphManyRelationQuery, MorphOneRelationQuery, MorphToRelationQuery, modelFacade, runObservers, } from "./model";
|
|
3
|
+
export { BelongsToManyRelationQuery, BelongsToRelationQuery, BoundModelFacade, createBoundModel, createModel, defineModel, getModelBinding, HasManyRelationQuery, HasManyThroughRelationQuery, HasOneRelationQuery, Model, ModelQuery, MorphManyRelationQuery, MorphOneRelationQuery, MorphToRelationQuery, modelFacade, runObservers, } from "./model";
|
|
4
|
+
export { createClassModelDefinition, defineAuthoredModel, field, isModelClass, modelTable, } from "./modelAuthoring";
|
|
4
5
|
export { RepositoryQuery, snapshotRepositoryQuery } from "./repositoryQuery";
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { BadRequestError, ConflictError, ForbiddenError, HttpError, NotFoundError, PayloadTooLargeError, PreconditionFailedError, UnauthorizedError, UnprocessableEntityError, ValidationError, } from "@getstrata/core/errors/http";
|
|
2
|
+
export type { ParsedUpload } from "@getstrata/core/http/parseMultipartUpload";
|
|
3
|
+
export { parseMultipartUpload, parseMultipartUploadStream, sanitizeUploadFileName, UploadedFile, validateUploadFile, } from "@getstrata/core/http/parseMultipartUpload";
|
|
2
4
|
export type { PaginatedResult, PaginationMeta } from "../pagination";
|
|
3
5
|
export { createAuthMiddleware } from "./authMiddleware";
|
|
4
6
|
export { createAuthorizeMiddleware } from "./authorizeMiddleware";
|
|
@@ -9,8 +11,6 @@ export { FormRequest, QueryFormRequest } from "./formRequest";
|
|
|
9
11
|
export type { Middleware, RouteHandler } from "./middleware";
|
|
10
12
|
export { applyMiddlewareToRoutes, composeMiddleware, requestIdMiddleware, wrapRouteHandler, } from "./middleware";
|
|
11
13
|
export { buildPaginationMeta, DEFAULT_PER_PAGE, MAX_PER_PAGE, paginatedResponse, parsePaginationQuery, } from "./pagination";
|
|
12
|
-
export type { ParsedUpload } from "./parseMultipartUpload";
|
|
13
|
-
export { parseMultipartUpload, sanitizeUploadFileName, validateUploadFile, } from "./parseMultipartUpload";
|
|
14
14
|
export { createRequireAuthMiddleware } from "./requireAuthMiddleware";
|
|
15
15
|
export { serializeDate, toPaginatedResourceCollection, toResourceCollection } from "./resources";
|
|
16
16
|
export { createdResponse, errorResponse, jsonResponse, noContentResponse, withErrorHandling, } from "./response";
|
|
@@ -8,5 +8,6 @@ interface ParsedUpload {
|
|
|
8
8
|
declare function sanitizeUploadFileName(name: string): string;
|
|
9
9
|
declare function validateUploadFile(file: File, fieldName?: string, policy?: UploadPolicy): Promise<ParsedUpload>;
|
|
10
10
|
declare function parseMultipartUpload(request: Request, fieldName?: string, policy?: UploadPolicy): Promise<ParsedUpload>;
|
|
11
|
+
export { parseMultipartUploadStream, UploadedFile } from "./streamingUpload";
|
|
11
12
|
export type { ParsedUpload };
|
|
12
13
|
export { parseMultipartUpload, sanitizeUploadFileName, validateUploadFile };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { StreamingStorage } from "../storage/storage";
|
|
2
|
+
import { type UploadPolicy } from "./uploads";
|
|
3
|
+
/** One file, one consumption. Storage stays an explicit consumer capability. */
|
|
4
|
+
declare class UploadedFile {
|
|
5
|
+
readonly fileName: string;
|
|
6
|
+
readonly mimeType: string;
|
|
7
|
+
private readonly contents;
|
|
8
|
+
private consumed;
|
|
9
|
+
constructor(fileName: string, mimeType: string, contents: ReadableStream<Uint8Array>);
|
|
10
|
+
stream(): ReadableStream<Uint8Array>;
|
|
11
|
+
/** Explicit buffering for bounded operations such as image decoding. */
|
|
12
|
+
bytes(): Promise<Uint8Array>;
|
|
13
|
+
/** Discard an unneeded upload and cancel its request source. */
|
|
14
|
+
discard(): Promise<void>;
|
|
15
|
+
/** Generated keys avoid overwriting an existing object during validation/cleanup. */
|
|
16
|
+
store(storage: Pick<StreamingStorage, "writeStream" | "delete">, directory?: string): Promise<string>;
|
|
17
|
+
}
|
|
18
|
+
/** Single file plus bounded text fields. Validation completes when its stream completes. */
|
|
19
|
+
declare function parseMultipartUploadStream(request: Request, fieldName?: string, policy?: UploadPolicy): Promise<UploadedFile>;
|
|
20
|
+
export { parseMultipartUploadStream, UploadedFile };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Check supported binary signatures. This is type classification, not a malware scan. */
|
|
2
|
+
declare function assertUploadContentType(prefix: Uint8Array, mimeType: string): void;
|
|
3
|
+
/** A separate decoder per file preserves UTF-8 sequences split across chunks. */
|
|
4
|
+
declare function uploadTextDecoder(mimeType: string): TextDecoder | undefined;
|
|
5
|
+
declare function validateUploadText(decoder: TextDecoder | undefined, bytes?: Uint8Array): void;
|
|
6
|
+
export { assertUploadContentType, uploadTextDecoder, validateUploadText };
|
|
@@ -1,4 +1,24 @@
|
|
|
1
1
|
declare const IMAGE_MIME_TYPES: Set<string>;
|
|
2
|
+
type ImageOutputFormat = "jpeg" | "png" | "webp";
|
|
3
|
+
interface ImageTransformOptions {
|
|
4
|
+
readonly width?: number;
|
|
5
|
+
readonly height?: number;
|
|
6
|
+
/** With both dimensions, preserve aspect ratio inside the box or stretch to fill it. */
|
|
7
|
+
readonly fit?: "inside" | "fill";
|
|
8
|
+
readonly format?: ImageOutputFormat;
|
|
9
|
+
/** JPEG/WebP quality, an integer from 1 through 100. PNG uses lossless encoding. */
|
|
10
|
+
readonly quality?: number;
|
|
11
|
+
/** Defaults to true. */
|
|
12
|
+
readonly withoutEnlargement?: boolean;
|
|
13
|
+
/** Optional assertion about input bytes; never selects the output format. */
|
|
14
|
+
readonly contentType?: string;
|
|
15
|
+
}
|
|
16
|
+
interface ImageTransformResult {
|
|
17
|
+
readonly body: Uint8Array;
|
|
18
|
+
readonly contentType: "image/jpeg" | "image/png" | "image/webp";
|
|
19
|
+
readonly width: number;
|
|
20
|
+
readonly height: number;
|
|
21
|
+
}
|
|
2
22
|
declare function normalizeMimeType(mimeType: string): string;
|
|
3
23
|
declare function isImageMimeType(mimeType: string): boolean;
|
|
4
24
|
declare function parseThumbnailWidth(raw: string | null | undefined, options?: {
|
|
@@ -6,8 +26,12 @@ declare function parseThumbnailWidth(raw: string | null | undefined, options?: {
|
|
|
6
26
|
minWidth?: number;
|
|
7
27
|
maxWidth?: number;
|
|
8
28
|
}): number;
|
|
29
|
+
/** Native Bun pipeline. Limits apply before decoding and to the returned encoded image. */
|
|
30
|
+
declare function transformImageContents(contents: Uint8Array, options?: ImageTransformOptions): Promise<ImageTransformResult>;
|
|
31
|
+
/** Compatibility helper: mimeType selects output; width-only resizing retains upscaling. */
|
|
9
32
|
declare function resizeImageContents(contents: Uint8Array, width: number, mimeType: string): Promise<{
|
|
10
33
|
body: Uint8Array;
|
|
11
34
|
contentType: string;
|
|
12
35
|
}>;
|
|
13
|
-
export {
|
|
36
|
+
export type { ImageOutputFormat, ImageTransformOptions, ImageTransformResult };
|
|
37
|
+
export { IMAGE_MIME_TYPES, isImageMimeType, normalizeMimeType, parseThumbnailWidth, resizeImageContents, transformImageContents, };
|
|
@@ -114,8 +114,10 @@ import {
|
|
|
114
114
|
import {
|
|
115
115
|
BaseRepository,
|
|
116
116
|
createBoundModel,
|
|
117
|
+
createClassModelDefinition,
|
|
117
118
|
getModelBinding,
|
|
118
119
|
getRepositoryBinding,
|
|
120
|
+
isModelClass,
|
|
119
121
|
Model
|
|
120
122
|
} from "#strata-orm-runtime";
|
|
121
123
|
|
|
@@ -254,7 +256,19 @@ function definitionArray(values) {
|
|
|
254
256
|
}
|
|
255
257
|
function snapshotRegistry(repositories = [], models = [], repositoryEffects = []) {
|
|
256
258
|
repositories = definitionArray(repositories);
|
|
257
|
-
|
|
259
|
+
const classDefinitions = new Map;
|
|
260
|
+
const implicitRepositories = [];
|
|
261
|
+
const resolvedModels = definitionArray(models).map((model) => {
|
|
262
|
+
if (!isModelClass(model))
|
|
263
|
+
return model;
|
|
264
|
+
if (classDefinitions.has(model))
|
|
265
|
+
throw new TypeError("Duplicate model class.");
|
|
266
|
+
const definition = createClassModelDefinition(model);
|
|
267
|
+
classDefinitions.set(model, definition);
|
|
268
|
+
implicitRepositories.push(definition.repository);
|
|
269
|
+
return definition;
|
|
270
|
+
});
|
|
271
|
+
repositories = Object.freeze([...repositories, ...implicitRepositories]);
|
|
258
272
|
repositoryEffects = definitionArray(repositoryEffects);
|
|
259
273
|
const repos = new Set;
|
|
260
274
|
const repoNames = new Set;
|
|
@@ -281,8 +295,9 @@ function snapshotRegistry(repositories = [], models = [], repositoryEffects = []
|
|
|
281
295
|
}
|
|
282
296
|
for (const declaration of repositoryEffects) {
|
|
283
297
|
assertRepositoryEffectsDeclaration(declaration);
|
|
284
|
-
|
|
285
|
-
|
|
298
|
+
const effectRepository = isModelClass(declaration.definition) ? classDefinitions.get(declaration.definition)?.repository : declaration.definition;
|
|
299
|
+
assertDefinition(effectRepository, "repository");
|
|
300
|
+
if (!repos.has(effectRepository))
|
|
286
301
|
throw new TypeError("Effect repository is not registered.");
|
|
287
302
|
for (const effect of declaration.effects) {
|
|
288
303
|
if (effect.transactional)
|
|
@@ -291,7 +306,7 @@ function snapshotRegistry(repositories = [], models = [], repositoryEffects = []
|
|
|
291
306
|
add(effect.afterCommit);
|
|
292
307
|
}
|
|
293
308
|
}
|
|
294
|
-
for (const definition of
|
|
309
|
+
for (const definition of resolvedModels) {
|
|
295
310
|
assertDefinition(definition, "model");
|
|
296
311
|
if (definitions.has(definition) || !repos.has(definition.repository))
|
|
297
312
|
throw new TypeError("Duplicate model or unregistered repository.");
|
|
@@ -315,7 +330,8 @@ function snapshotRegistry(repositories = [], models = [], repositoryEffects = []
|
|
|
315
330
|
}
|
|
316
331
|
return Object.freeze({
|
|
317
332
|
repositories: Object.freeze([...repositories]),
|
|
318
|
-
models: Object.freeze(
|
|
333
|
+
models: Object.freeze(resolvedModels),
|
|
334
|
+
classes: classDefinitions,
|
|
319
335
|
dependencies: Object.freeze(dependencies),
|
|
320
336
|
repositoryEffects
|
|
321
337
|
});
|
|
@@ -328,7 +344,7 @@ function prepareRegistry(snapshot, values, app) {
|
|
|
328
344
|
const bus = new EventBus;
|
|
329
345
|
for (const effect of [
|
|
330
346
|
...definition.effects,
|
|
331
|
-
...snapshot.repositoryEffects.filter((item) => item.definition === definition).flatMap((item) => item.effects)
|
|
347
|
+
...snapshot.repositoryEffects.filter((item) => (isModelClass(item.definition) ? snapshot.classes.get(item.definition)?.repository : item.definition) === definition).flatMap((item) => item.effects)
|
|
332
348
|
]) {
|
|
333
349
|
if (effect.transactional) {
|
|
334
350
|
const listener = resolve(effect.transactional);
|
|
@@ -363,7 +379,7 @@ function prepareRegistry(snapshot, values, app) {
|
|
|
363
379
|
for (const name of [definition.name, ...definition.aliases])
|
|
364
380
|
names.set(name, definition);
|
|
365
381
|
}
|
|
366
|
-
return Object.freeze({ app, repositories, models, names });
|
|
382
|
+
return Object.freeze({ app, repositories, models, names, classes: snapshot.classes });
|
|
367
383
|
}
|
|
368
384
|
function createBoundRegistryFactory(prepared, context, ownership, configuredPool) {
|
|
369
385
|
const attachments = new WeakMap;
|
|
@@ -397,8 +413,11 @@ function createBoundRegistryFactory(prepared, context, ownership, configuredPool
|
|
|
397
413
|
},
|
|
398
414
|
model(definition) {
|
|
399
415
|
authority.assertActive();
|
|
400
|
-
|
|
401
|
-
|
|
416
|
+
const resolved = typeof definition === "function" ? prepared.classes.get(definition) : definition;
|
|
417
|
+
if (!resolved)
|
|
418
|
+
throw new TypeError("Model is not registered in this application.");
|
|
419
|
+
assertDefinition(resolved, "model");
|
|
420
|
+
const erased = resolved;
|
|
402
421
|
const template = prepared.models.get(erased);
|
|
403
422
|
if (!template)
|
|
404
423
|
throw new TypeError("Model is not registered in this application.");
|
|
@@ -1431,7 +1450,9 @@ class TransactionRuntime {
|
|
|
1431
1450
|
};
|
|
1432
1451
|
const session = {
|
|
1433
1452
|
repository: (definition) => registry.repository(definition),
|
|
1434
|
-
model
|
|
1453
|
+
get model() {
|
|
1454
|
+
return registry.model;
|
|
1455
|
+
},
|
|
1435
1456
|
dialect: branch.pool.dialect,
|
|
1436
1457
|
capabilities: branch.pool.capabilities,
|
|
1437
1458
|
execute: (input) => {
|
|
@@ -1803,7 +1824,9 @@ function createDatabaseSession(manager, context, operations, ownership, prepared
|
|
|
1803
1824
|
};
|
|
1804
1825
|
const session = {
|
|
1805
1826
|
repository: (definition) => registry.repository(definition),
|
|
1806
|
-
model
|
|
1827
|
+
get model() {
|
|
1828
|
+
return registry.model;
|
|
1829
|
+
},
|
|
1807
1830
|
dialect: pool.dialect,
|
|
1808
1831
|
capabilities: pool.capabilities,
|
|
1809
1832
|
execute: (input) => {
|
|
@@ -166,10 +166,16 @@ function assertRepositoryEffectsDeclaration(value) {
|
|
|
166
166
|
if (!value || typeof value !== "object" || !Object.isFrozen(value) || Object.getOwnPropertyDescriptor(value, effectsBrand)?.value !== value)
|
|
167
167
|
throw new TypeError("Expected original repository effects declaration.");
|
|
168
168
|
}
|
|
169
|
+
function modelEffects(model, effects) {
|
|
170
|
+
const declaration = { definition: model, effects: snapshotEffects(effects) };
|
|
171
|
+
Object.defineProperty(declaration, effectsBrand, { value: declaration });
|
|
172
|
+
return Object.freeze(declaration);
|
|
173
|
+
}
|
|
169
174
|
export {
|
|
170
175
|
assertDefinition,
|
|
171
176
|
assertRepositoryEffectsDeclaration,
|
|
172
177
|
defineModel,
|
|
173
178
|
defineRepository,
|
|
179
|
+
modelEffects,
|
|
174
180
|
repositoryEffects
|
|
175
181
|
};
|
|
@@ -837,7 +837,9 @@ class TransactionRuntime {
|
|
|
837
837
|
};
|
|
838
838
|
const session = {
|
|
839
839
|
repository: (definition) => registry.repository(definition),
|
|
840
|
-
model
|
|
840
|
+
get model() {
|
|
841
|
+
return registry.model;
|
|
842
|
+
},
|
|
841
843
|
dialect: branch.pool.dialect,
|
|
842
844
|
capabilities: branch.pool.capabilities,
|
|
843
845
|
execute: (input) => {
|