* initial refactor * fixes * test secrets extraction * updated lock * fix secret schema * updated schemas, fixed tests, skipping flow tests for now * added validator for rjsf, hook form via standard schema * removed @sinclair/typebox * remove unneeded vite dep * fix jsonv literal on Field.tsx * fix schema import path * fix schema modals * fix schema modals * fix json field form, replaced auth form * initial waku * finalize waku example * fix jsonv-ts version * fix schema updates with falsy values * fix media api to respect options' init, improve types * checking media controller test * checking media controller test * checking media controller test * clean up mediacontroller test * added cookie option `partitioned`, as well as cors `origin` to be array, option to enable `credentials` (#214) * added cookie option `partitioned`, as well as cors `origin` to be array, option to enable `credentials` * fix server test * fix data api (updated jsonv-ts) * enhance cloudflare image optimization plugin with new options and explain endpoint (#215) * feat: add ability to serve static by using dynamic imports (#197) * feat: add ability to serve static by using dynamic imports * serveStaticViaImport: make manifest optional * serveStaticViaImport: add error log * refactor/imports (#217) * refactored core and core/utils imports * refactored core and core/utils imports * refactored media imports * refactored auth imports * refactored data imports * updated package json exports, fixed mm config * fix tests * feat/deno (#219) * update bun version * fix module manager's em reference * add basic deno example * finalize * docs: fumadocs migration (#185) * feat(docs): initialize documentation structure with Fumadocs * feat(docs): remove home route and move /docs route to /route * feat(docs): add redirect to /start page * feat(docs): migrate Getting Started chapters * feat(docs): migrate Usage and Extending chapters * feat(callout): add CalloutCaution, CalloutDanger, CalloutInfo, and CalloutPositive * feat(layout): add Discord and GitHub links to documentation layout * feat(docs): add integration chapters draft * feat(docs): add modules chapters draft * refactor(mdx-components): remove unused Icon import * refactor(StackBlitz): enhance type safety by using unknown instead of any * refactor(layout): update navigation mode to 'top' in layout configuration * feat(docs): add @iconify/react package * docs(mdx-components): add Icon component to MDX components list * feat(docs): update Next.js integration guide * feat(docs): update React Router integration guide * feat(docs): update Astro integration guide * feat(docs): update Vite integration guide * fix(docs): update package manager initialization commands * feat(docs): migrate Modules chapters * chore(docs): update package.json with new devDependencies * feat(docs): migrate Integration Runtimes chapters * feat(docs): update Database usage chapter * feat(docs): restructure documentation paths * chore(docs): clean up unused imports and files in documentation * style(layout): revert navigation mode to previous state * fix(docs): routing for documentation structure * feat(openapi): add API documentation generation from OpenAPI schema * feat(docs): add icons to documentation pages * chore(dependencies): remove unused content-collections packages * fix(types): fix type error for attachFile in source.ts * feat(redirects): update root redirect destination to '/start' * feat(search): add static search functionality * chore(dependencies): update fumadocs-core and fumadocs-ui to latest versions * feat(search): add Powered by Orama link * feat(generate-openapi): add error handling for missing OpenAPI schema * feat(scripts): add OpenAPI generation to build process * feat(config): enable dynamic redirects and rewrites in development mode * feat(layout): add GitHub token support for improved API rate limits * feat(redirects): add 301 redirects for cloudflare pages * feat(docs): add Vercel redirects configuration * feat(config): enable standalone output for development environment * chore(layout): adjust layout settings * refactor(package): clean up ajv dependency versions * feat(docs): add twoslash support * refactor(layout): update DocsLayout import and navigation configuration * chore(layout): clean up layout.tsx by commenting out GithubInfo * fix(Search): add locale to search initialization * chore(package): update fumadocs and orama to latest versions * docs: add menu items descriptions * feat(layout): add GitHub URL to the layout component * feat(docs): add AutoTypeTable component to MDX components * feat(app): implement AutoTypeTable rendering for AppEvents type * docs(layout): switch callouts back to default components * fix(config): use __filename and __dirname for module paths * docs: add note about node.js 22 requirement * feat(styles): add custom color variables for light and dark themes * docs: add S3 setup instructions for media module * docs: fix typos and indentation in media module docs * docs: add local media adapter example for Node.js * docs(media): add S3/R2 URL format examples and fix typo * docs: add cross-links to initial config and seeding sections * indent numbered lists content, clarified media serve locations * fix mediacontroller tests * feat(layout): add AnimatedGridPattern component for dynamic background * style(layout): configure fancy ToC style ('clerk') * fix(AnimatedGridPattern): correct strokeDasharray type * docs: actualize docs * feat: add favicon * style(cloudflare): format code examples * feat(layout): add Github and Discord footer icons * feat(footer): add SVG social media icons for GitHub and Discord * docs: adjusted auto type table, added llm functions * added static deployment to cloudflare workers * docs: change cf redirects to proxy *.mdx instead of redirecting --------- Co-authored-by: dswbx <dennis.senn@gmx.ch> Co-authored-by: cameronapak <cameronandrewpak@gmail.com> * build: improve build script * add missing exports, fix EntityTypescript imports * media: Dropzone: add programmatic upload, additional events, loading state * schema object: disable extended defaults to allow empty config values * Feat/new docs deploy (#224) * test * try fixing pm * try fixing pm * fix docs on imports, export events correctly --------- Co-authored-by: Tim Seriakov <59409712+timseriakov@users.noreply.github.com> Co-authored-by: cameronapak <cameronandrewpak@gmail.com>
315 lines
10 KiB
TypeScript
315 lines
10 KiB
TypeScript
import type { DB as DefaultDB } from "bknd";
|
|
import { $console } from "bknd/utils";
|
|
import { EventManager } from "core/events";
|
|
import { sql } from "kysely";
|
|
import { Connection } from "../connection/Connection";
|
|
import {
|
|
EntityNotDefinedException,
|
|
TransformRetrieveFailedException,
|
|
UnableToConnectException,
|
|
} from "../errors";
|
|
import { MutatorEvents, RepositoryEvents } from "../events";
|
|
import type { Field } from "../fields/Field";
|
|
import type { EntityIndex } from "../fields/indices/EntityIndex";
|
|
import type { EntityRelation } from "../relations";
|
|
import { RelationAccessor } from "../relations/RelationAccessor";
|
|
import { SchemaManager } from "../schema/SchemaManager";
|
|
import { Entity } from "./Entity";
|
|
import { type EntityData, Mutator, Repository, type RepositoryOptions } from "./index";
|
|
|
|
type EntitySchema<
|
|
TBD extends object = DefaultDB,
|
|
E extends Entity | keyof TBD | string = string,
|
|
> = E extends Entity<infer Name>
|
|
? Name extends keyof TBD
|
|
? Name
|
|
: never
|
|
: E extends keyof TBD
|
|
? E
|
|
: never;
|
|
|
|
export class EntityManager<TBD extends object = DefaultDB> {
|
|
connection: Connection;
|
|
|
|
private _entities: Entity[] = [];
|
|
private _relations: EntityRelation[] = [];
|
|
private _indices: EntityIndex[] = [];
|
|
private _schema?: SchemaManager;
|
|
readonly emgr: EventManager<typeof EntityManager.Events>;
|
|
static readonly Events = { ...MutatorEvents, ...RepositoryEvents };
|
|
|
|
constructor(
|
|
entities: Entity[],
|
|
connection: Connection,
|
|
relations: EntityRelation[] = [],
|
|
indices: EntityIndex[] = [],
|
|
emgr?: EventManager<any>,
|
|
) {
|
|
// add entities & relations
|
|
entities.forEach((entity) => this.addEntity(entity));
|
|
relations.forEach((relation) => this.addRelation(relation));
|
|
indices.forEach((index) => this.addIndex(index));
|
|
|
|
if (!Connection.isConnection(connection)) {
|
|
throw new UnableToConnectException("");
|
|
}
|
|
|
|
this.connection = connection;
|
|
this.emgr = emgr ?? new EventManager();
|
|
this.emgr.registerEvents(EntityManager.Events);
|
|
}
|
|
|
|
/**
|
|
* Forks the EntityManager without the EventManager.
|
|
* This is useful when used inside an event handler.
|
|
*/
|
|
fork(): EntityManager {
|
|
return new EntityManager(this._entities, this.connection, this._relations, this._indices);
|
|
}
|
|
|
|
clear(): this {
|
|
this._entities = [];
|
|
this._relations = [];
|
|
this._indices = [];
|
|
return this;
|
|
}
|
|
|
|
get entities(): Entity[] {
|
|
return this._entities;
|
|
}
|
|
|
|
get relations(): RelationAccessor {
|
|
return new RelationAccessor(this._relations);
|
|
}
|
|
|
|
get indices(): EntityIndex[] {
|
|
return this._indices;
|
|
}
|
|
|
|
async ping(): Promise<boolean> {
|
|
const res = await sql`SELECT 1`.execute(this.connection.kysely);
|
|
return res.rows.length > 0;
|
|
}
|
|
|
|
addEntity(entity: Entity) {
|
|
const existing = this.entities.find((e) => e.name === entity.name);
|
|
// check if already exists by name
|
|
if (existing) {
|
|
// @todo: for now adding a graceful method
|
|
if (JSON.stringify(existing) === JSON.stringify(entity)) {
|
|
$console.warn(
|
|
`Entity "${entity.name}" already exists, but it's the same, skipping adding it.`,
|
|
);
|
|
return;
|
|
}
|
|
|
|
throw new Error(`Entity "${entity.name}" already exists`);
|
|
}
|
|
|
|
this.entities.push(entity);
|
|
}
|
|
|
|
__replaceEntity(entity: Entity, name: string | undefined = entity.name) {
|
|
const entityIndex = this._entities.findIndex((e) => e.name === name);
|
|
|
|
if (entityIndex === -1) {
|
|
throw new Error(`Entity "${name}" not found and cannot be replaced`);
|
|
}
|
|
|
|
this._entities[entityIndex] = entity;
|
|
// caused issues because this.entity() was using a reference (for when initial config was given)
|
|
}
|
|
|
|
entity<Silent extends true | false = false>(
|
|
e: Entity | keyof TBD | string,
|
|
silent?: Silent,
|
|
): Silent extends true ? Entity | undefined : Entity {
|
|
// make sure to always retrieve by name
|
|
const entity = this.entities.find((entity) =>
|
|
Entity.isEntity(e) ? entity.name === e.name : entity.name === e,
|
|
);
|
|
|
|
if (!entity) {
|
|
if (silent === true) return undefined as any;
|
|
throw new EntityNotDefinedException(Entity.isEntity(e) ? e.name : (e as string));
|
|
}
|
|
|
|
return entity;
|
|
}
|
|
|
|
hasEntity(entity: string): boolean;
|
|
hasEntity(entity: Entity): boolean;
|
|
hasEntity(nameOrEntity: string | Entity): boolean {
|
|
const name = typeof nameOrEntity === "string" ? nameOrEntity : nameOrEntity.name;
|
|
return this.entities.some((e) => e.name === name);
|
|
}
|
|
|
|
hasIndex(index: string): boolean;
|
|
hasIndex(index: EntityIndex): boolean;
|
|
hasIndex(nameOrIndex: string | EntityIndex): boolean {
|
|
const name = typeof nameOrIndex === "string" ? nameOrIndex : nameOrIndex.name;
|
|
return this.indices.some((e) => e.name === name);
|
|
}
|
|
|
|
// @todo: add to Connection whether first index is used or not
|
|
getIndexedFields(_entity: Entity | string): Field[] {
|
|
const entity = this.entity(_entity);
|
|
const indices = this.getIndicesOf(entity);
|
|
const rel_fields = entity.fields.filter((f) => f.type === "relation");
|
|
// assuming only first
|
|
const idx_fields = indices.map((index) => index.fields[0]);
|
|
return [entity.getPrimaryField(), ...rel_fields, ...idx_fields].filter(Boolean) as Field[];
|
|
}
|
|
|
|
addRelation(relation: EntityRelation) {
|
|
// check if entities are registered
|
|
if (!this.entity(relation.source.entity.name) || !this.entity(relation.target.entity.name)) {
|
|
throw new Error("Relation source or target entity not found");
|
|
}
|
|
|
|
// @todo: potentially add name to relation in order to have multiple
|
|
const found = this._relations.find((r) => {
|
|
const equalSourceTarget =
|
|
r.source.entity.name === relation.source.entity.name &&
|
|
r.target.entity.name === relation.target.entity.name;
|
|
const equalReferences =
|
|
r.source.reference === relation.source.reference &&
|
|
r.target.reference === relation.target.reference;
|
|
|
|
return (
|
|
//r.type === relation.type && // ignore type for now
|
|
equalSourceTarget && equalReferences
|
|
);
|
|
});
|
|
|
|
if (found) {
|
|
throw new Error(
|
|
`Relation "${relation.type}" between "${relation.source.entity.name}" ` +
|
|
`and "${relation.target.entity.name}" already exists`,
|
|
);
|
|
}
|
|
|
|
this._relations.push(relation);
|
|
relation.initialize(this);
|
|
}
|
|
|
|
relationsOf(entity_name: string): EntityRelation[] {
|
|
return this.relations.relationsOf(this.entity(entity_name));
|
|
}
|
|
|
|
relationOf(entity_name: string, reference: string): EntityRelation | undefined {
|
|
return this.relations.relationOf(this.entity(entity_name), reference);
|
|
}
|
|
|
|
hasRelations(entity_name: string): boolean {
|
|
return this.relations.hasRelations(this.entity(entity_name));
|
|
}
|
|
|
|
relatedEntitiesOf(entity_name: string): Entity[] {
|
|
return this.relations.relatedEntitiesOf(this.entity(entity_name));
|
|
}
|
|
|
|
relationReferencesOf(entity_name: string): string[] {
|
|
return this.relations.relationReferencesOf(this.entity(entity_name));
|
|
}
|
|
|
|
repository<E extends Entity | keyof TBD | string>(
|
|
entity: E,
|
|
opts: Omit<RepositoryOptions, "emgr"> = {},
|
|
): Repository<TBD, EntitySchema<TBD, E>> {
|
|
return this.repo(entity, opts);
|
|
}
|
|
|
|
repo<E extends Entity | keyof TBD | string>(
|
|
entity: E,
|
|
opts: Omit<RepositoryOptions, "emgr"> = {},
|
|
): Repository<TBD, EntitySchema<TBD, E>> {
|
|
return new Repository(this, this.entity(entity), { ...opts, emgr: this.emgr });
|
|
}
|
|
|
|
mutator<E extends Entity | keyof TBD | string>(entity: E): Mutator<TBD, EntitySchema<TBD, E>> {
|
|
return new Mutator(this, this.entity(entity), { emgr: this.emgr });
|
|
}
|
|
|
|
addIndex(index: EntityIndex, force = false) {
|
|
// check if already exists by name
|
|
if (this.indices.find((e) => e.name === index.name)) {
|
|
if (force) {
|
|
throw new Error(`Index "${index.name}" already exists`);
|
|
}
|
|
return;
|
|
}
|
|
|
|
this._indices.push(index);
|
|
}
|
|
|
|
getIndicesOf(_entity: Entity | string): EntityIndex[] {
|
|
const entity = Entity.isEntity(_entity) ? _entity : this.entity(_entity);
|
|
return this.indices.filter((index) => index.entity.name === entity.name);
|
|
}
|
|
|
|
schema() {
|
|
if (!this._schema) {
|
|
this._schema = new SchemaManager(this);
|
|
}
|
|
|
|
return this._schema;
|
|
}
|
|
|
|
// @todo: centralize and add tests
|
|
hydrate(entity_name: string, _data: EntityData[]) {
|
|
const entity = this.entity(entity_name);
|
|
const data: EntityData[] = [];
|
|
|
|
for (const row of _data) {
|
|
for (let [key, value] of Object.entries(row)) {
|
|
const field = entity.getField(key);
|
|
|
|
if (!field || field.isVirtual()) {
|
|
// if relation, use related entity to hydrate
|
|
const relation = this.relationOf(entity_name, key);
|
|
if (relation) {
|
|
if (!value) continue;
|
|
|
|
value = relation.hydrate(key, Array.isArray(value) ? value : [value], this);
|
|
row[key] = value;
|
|
continue;
|
|
} else if (field?.isVirtual()) {
|
|
continue;
|
|
}
|
|
|
|
throw new Error(`Field "${key}" not found on entity "${entity.name}"`);
|
|
}
|
|
|
|
try {
|
|
if (value === null && field.hasDefault()) {
|
|
row[key] = field.getDefault();
|
|
}
|
|
|
|
// transform from driver
|
|
value = this.connection.fromDriver(value, field);
|
|
|
|
// transform from field
|
|
row[key] = field.transformRetrieve(value as any);
|
|
} catch (e: any) {
|
|
throw new TransformRetrieveFailedException(
|
|
`"${field.type}" field "${key}" on entity "${entity.name}": ${e.message}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
data.push(row);
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
toJSON() {
|
|
return {
|
|
entities: Object.fromEntries(this.entities.map((e) => [e.name, e.toJSON()])),
|
|
relations: Object.fromEntries(this.relations.all.map((r) => [r.getName(), r.toJSON()])),
|
|
indices: Object.fromEntries(this.indices.map((i) => [i.name, i.toJSON()])),
|
|
};
|
|
}
|
|
}
|