import type { HydratedDocument, InferHydratedDocType, InferRawDocType, Schema } from 'mongoose'; import mongoose, { type Model } from 'mongoose'; export type Merge = Omit & N; /** The timestamp fields Mongoose adds when `timestamps` is on (the default). * Typed `required: true` so `InferRawDocType` resolves them to a non-null `Date` * on the hydrated doc — Mongoose always sets them, so a `| null | undefined` * would force a needless guard at every read. */ type Timestamps = { createdAt: { type: DateConstructor; required: true; }; updatedAt: { type: DateConstructor; required: true; }; }; type TimestampFieldName = Value extends false ? never : Value extends string ? Value : DefaultName; type TimestampFieldsFromConfig = { [K in keyof Timestamps as K extends keyof TConfig ? TimestampFieldName : K]: Timestamps[K]; }; /** * Timestamp schema fields implied by the effective Mongoose schema options. * * The framework enables both default timestamp paths unless a model overrides * that default. Object-form options can disable either path independently or * rename it. An omitted key in an object config keeps its default field, which * matches Mongoose's runtime `handleTimestampOption()` behavior. */ export type WithTimestamps = TOptions extends { timestamps: infer TConfig; } ? TConfig extends false ? object : TConfig extends true ? Timestamps : TConfig extends object ? TimestampFieldsFromConfig : Timestamps : Timestamps; export type ExtractProperty = T extends { [P in K]: infer R; } ? R : Default; /** * Phantom per-field type override. Intersect a schema field with this to type * its raw/stored value as `TRaw` instead of the type Mongoose infers from * `type:` — for fields a plugin reshapes at runtime (`mongoose-intl`, encrypted * fields, custom getters). When a getter exposes a different hydrated value, * pass it as `THydrated`; the default preserves the original one-type behavior. * Both marker properties are compile-time only and are never set at runtime. * The override is opt-in and a strict no-op for unmarked fields. * * @example * // app-side, ideally behind a small factory: * title: { type: String, intl: true } as { type: StringConstructor; intl: true } & * TsTypeOverride; */ export interface TsTypeOverride { readonly __tsType?: TRaw; readonly __tsHydratedType?: THydrated; } type TsOverrideSurface = 'raw' | 'hydrated'; type RawTsOverride = S extends { readonly __tsType?: infer T; } ? T : never; type HydratedTsOverride = S extends object ? '__tsHydratedType' extends keyof S ? S extends { readonly __tsHydratedType?: infer T; } ? T : RawTsOverride : RawTsOverride : never; type TsOverrideFor = Surface extends 'hydrated' ? HydratedTsOverride : RawTsOverride; /** * A leaf field definition — a bare constructor (`String`, `ObjectId`), a * `{ type: SomeConstructor, … }` form (String, Number, ObjectId, Date, Map, * Buffer, …), or a pre-built mongoose `Schema` instance reused as a (sub-)doc * definition (`field: SubSchema` / `[SubSchema]`). This mirrors how Mongoose * itself decides "leaf field" vs "nested schema", so {@link ApplyTsOverrides} * and {@link HasTsOverride} recurse only into nested *schemas* (a record of * field defs) and leave built-in instances (ObjectId, Date, Map) and `Schema` * instances untouched. The `Schema` case is essential: a `Schema` instance's own * type is deeply self-referential (`childSchemas`, `options`, …), so scanning * into it triggers a TS2615 circular mapped-type error — and it can carry no * `__tsType` marker anyway, so stopping there is always correct. */ type IsLeafFieldDef = S extends Schema ? true : S extends abstract new (...args: never[]) => unknown ? true : TypeKey extends keyof S ? S[TypeKey] extends Schema ? true : S[TypeKey] extends abstract new (...args: never[]) => unknown ? true : false : false; type SchemaArrayElement = NonNullable extends readonly (infer E)[] ? E : TypeKey extends keyof NonNullable ? NonNullable[TypeKey] extends readonly (infer E)[] ? E : never : never; type SchemaArrayElementWithIdMarker = S extends { readonly _id: false; } ? SchemaArrayElement & { readonly _id: false; } : SchemaArrayElement; type SchemaSingleNestedDefinition = TypeKey extends keyof NonNullable ? NonNullable[TypeKey] extends infer Definition ? Definition extends Schema ? never : Definition extends abstract new (...args: never[]) => unknown ? never : Definition extends readonly unknown[] ? never : Definition extends object ? Definition : never : never : never; type SingleNestedDefinitionOrSelf = [ SchemaSingleNestedDefinition ] extends [never] ? S : SchemaSingleNestedDefinition; type ApplyTsOverrideArray = NonNullable extends mongoose.Types.DocumentArray ? IsLeafFieldDef extends true ? DocField : mongoose.Types.DocumentArray, ApplyTsOverrides extends mongoose.Types.Subdocument ? ApplyTsOverrides : Hydrated> | Extract : NonNullable extends readonly (infer Item)[] ? Item extends object ? IsLeafFieldDef extends true ? DocField : ApplyTsOverrides[] | Exclude : DocField : DocField; /** * Walk an inferred document type alongside its schema and replace each field * marked with {@link TsTypeOverride} by the override for the selected surface. * The default remains `raw` for compatibility with existing two-argument uses. * Recurses into nested objects and subdocument arrays (a reshaped field can * appear at any depth); leaves everything else — including arrays of primitives * and built-in instances (ObjectId/Date/Map, via {@link IsLeafFieldDef}) — * untouched. A schema with no markers maps to a structurally identical type, so * existing models are unaffected. The marker is detected by the *presence* of * the `__tsType` key (not by `extends TsTypeOverride`, which an optional property * would match on every field). */ export type ApplyTsOverrides = { [K in keyof Doc]: K extends keyof Schema ? '__tsType' extends keyof Schema[K] ? TsOverrideFor : [SchemaArrayElement] extends [never] ? NonNullable extends object ? NonNullable extends object ? IsLeafFieldDef, TypeKey> extends true ? Doc[K] : ApplyTsOverrides, SingleNestedDefinitionOrSelf, TypeKey>, Surface, TypeKey> | Exclude : Doc[K] : Doc[K] : ApplyTsOverrideArray, Surface, TypeKey> : Doc[K]; }; /** * True when a schema carries at least one {@link TsTypeOverride} marker anywhere * — at the top level, inside a nested object, or inside a subdocument array. * Recurses with the same leaf/array/object shape as {@link ApplyTsOverrides}, so * it cannot miss a marker the override pass would have applied. Used to skip the * whole override mapping for the overwhelmingly common marker-free model, so its * doc type is the plain Mongoose inference with no `ApplyTsOverrides<…>` wrapper * in hovers and no extra compile work. */ type HasTsOverride = S extends object ? '__tsType' extends keyof S ? true : IsLeafFieldDef extends true ? false : S extends readonly (infer E)[] ? HasTsOverride : true extends { [K in keyof S]: HasTsOverride; }[keyof S] ? true : false : false; /** {@link ApplyTsOverrides} only when the schema actually has a marker; * otherwise the inferred doc verbatim (a strict no-op, but without the wrapper). */ type MaybeApplyOverrides = HasTsOverride extends true ? ApplyTsOverrides : Doc; /** * True for a *plain nested path* — an object of field definitions with no * `type` key, e.g. `name: { first: String, last: String }`. * * Mongoose groups those paths under a prefix but never builds a subdocument for * them, so they carry no `_id` at runtime (`doc.name._id` is `undefined`); only * the `{ type: { … } }` spelling produces a real subdocument with a generated * id. Anything with a `type` key, a leaf definition, or an array is therefore * excluded here — same discriminator {@link SchemaSingleNestedDefinition} uses. */ type IsPlainNestedPath = S extends object ? S extends readonly unknown[] ? false : IsLeafFieldDef extends true ? false : TypeKey extends keyof S ? false : true : false; type HasDisabledSubdocumentId = S extends { readonly _id: false; } ? true : S extends object ? IsLeafFieldDef extends true ? false : S extends readonly (infer E)[] ? HasDisabledSubdocumentId : true extends { [K in keyof S]: HasDisabledSubdocumentId; }[keyof S] ? true : false : false; type CorrectRawSubdocumentElement = Doc extends object ? Schema extends { readonly _id: false; } ? Omit, Schema, TypeKey>, '_id'> : CorrectRawSubdocumentIds, Schema, TypeKey> : Doc; /** Resolve schema structure before mapping document fields. Keeping these * steps separate avoids recursive generic instantiation in Mongoose model types. * Custom-key array elements also need fresh inference: Mongoose 9.9.4 infers * inline array elements using its default `type` key. */ type RawIdFields = { [K in keyof Definition as TypeKey extends 'type' ? HasDisabledSubdocumentId extends true ? K : never : IsLeafFieldDef extends true ? never : K]: RawIdShape; }; type RawIdObject = { fields: RawIdFields; removeId: Definition extends { readonly _id: false; } ? true : false; }; type RawIdShape = [ SchemaArrayElement ] extends [never] ? [SchemaSingleNestedDefinition] extends [never] ? RawIdObject : RawIdObject, TypeKey> : TypeKey extends 'type' ? { array: RawIdObject, TypeKey>; } : IsLeafFieldDef, TypeKey> extends true ? object : { array: RawIdObject, TypeKey>; item: MaybeApplyOverrides>, { typeKey: TypeKey; }>, SchemaArrayElement, 'raw', TypeKey>; }; type ApplyRawIdFields = { [K in keyof Doc]: K extends keyof Fields ? ApplyRawIdShape : Doc[K]; }; type ApplyRawIdShape = Doc extends readonly (infer Item)[] ? Shape extends { array: infer Element; } ? ApplyRawIdShape[] : Doc : Doc extends object ? Shape extends { fields: infer Fields; removeId: infer Remove; } ? Remove extends true ? Omit, '_id'> : ApplyRawIdFields : Doc : Doc; /** Correct disabled IDs and custom-key array inference on the raw surface. */ type CorrectRawSubdocumentIds = ApplyRawIdFields>; type CorrectHydratedSubdocumentElement = CorrectRawSubdocumentElement extends infer CorrectedRaw ? CorrectHydratedSubdocumentIds, { typeKey: TypeKey; }>, Schema, 'hydrated', TypeKey>, Schema, TypeKey> extends infer Fields ? Schema extends { readonly _id: false; } ? mongoose.Types.Subdocument & Omit : mongoose.Types.Subdocument, unknown, CorrectedRaw> & Fields : never : never; /** * The single-nested definition a subdocument is re-derived from, keeping an * `_id: false` the *wrapper* carries. * * A subdocument spelled `field: { type: { … }, _id: false }` puts the marker * next to `type`, so unwrapping to the inner definition loses it and the * subdocument keeps an `_id` the runtime never generates. The * `field: { type: { _id: false, … } }` spelling survives the unwrap on its own * and needs no re-attachment. */ type SingleNestedDefinitionWithIdMarker = S extends { readonly _id: false; } ? SchemaSingleNestedDefinition & { readonly _id: false; } : SchemaSingleNestedDefinition; /** Inspect schema definitions before rebuilding a hydrated subdocument. Most * arrays contain only leaf fields and need no correction or extra inference. */ type HasHydratedCorrection = Definition extends { readonly _id: false; } ? true : IsLeafFieldDef extends true ? false : Definition extends object ? true extends { [K in keyof Definition]: FieldNeedsHydratedCorrection; }[keyof Definition] ? true : false : false; type FieldNeedsHydratedCorrection = Field extends { readonly _id: false; } ? true : IsLeafFieldDef extends true ? false : [SchemaArrayElement] extends [never] ? [SchemaSingleNestedDefinition] extends [never] ? IsPlainNestedPath : HasHydratedCorrection, TypeKey> : TypeKey extends 'type' ? HasHydratedCorrection, TypeKey> : IsLeafFieldDef, TypeKey> extends true ? false : true; /** * Preserve Mongoose's hydrated array APIs while respecting inline `_id: false`, * and drop the `_id` Mongoose's hydrated inference adds to plain nested paths. * Mongoose otherwise exposes a phantom `_id: Types.ObjectId` on `_id: false` * subdocument elements (verified up to 9.9.4 — the correction is still * required), and intersects `{ _id: ObjectId }` onto every nested path — a * field that never exists at runtime, and one that makes assigning the real * runtime shape (`doc.name = { first: 'a' }`) a type error. */ type CorrectHydratedSubdocumentIds = { [K in keyof Doc]: K extends keyof Schema ? IsPlainNestedPath, TypeKey> extends true ? NonNullable extends object ? ('_id' extends keyof NonNullable ? CorrectHydratedSubdocumentIds, NonNullable, TypeKey> : Omit, NonNullable, TypeKey>, '_id'>) | Exclude : Doc[K] : FieldNeedsHydratedCorrection extends true ? [SchemaArrayElement] extends [never] ? [SchemaSingleNestedDefinition] extends [never] ? Doc[K] : NonNullable extends object ? CorrectHydratedSubdocumentElement>, { typeKey: TypeKey; }>, SingleNestedDefinitionWithIdMarker, TypeKey> | Exclude : Doc[K] : NonNullable extends { isMongooseDocumentArray: true; } ? mongoose.Types.DocumentArray>, { typeKey: TypeKey; }>, SchemaArrayElementWithIdMarker, TypeKey>, CorrectHydratedSubdocumentElement>, { typeKey: TypeKey; }>, SchemaArrayElementWithIdMarker, TypeKey>> | Extract : Doc[K] : Doc[K] : Doc[K]; }; /** * Remove readonly modifiers introduced by `as const` before handing a schema * definition to Mongoose's `InferRawDocType`. * * Mongoose recommends literal-preserving schema definitions, but its required * path detection currently recognizes mutable `[true, message]` tuples and * mutable array definitions only. Without this boundary normalization, * `required: [true, 'message'] as const` and `type: [String] as const` are * incorrectly inferred as optional. Literal values (`true`, `false`, enum * members) are preserved; only readonly containers/properties become mutable. * * Runtime/opaque values that can legally appear in schema definitions stop the * recursion. `Schema` and `SchemaType` are especially important because their * instance types are deeply self-referential. */ type SchemaInferenceAtomic = Schema | mongoose.SchemaType | Date | RegExp | Buffer | Map | Set | { readonly _bsontype: string; }; type MutableSchemaForInference = T extends SchemaInferenceAtomic ? T : T extends abstract new (...args: never[]) => unknown ? T : T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? { -readonly [K in keyof T]: MutableSchemaForInference; } : T extends object ? { -readonly [K in keyof T]: MutableSchemaForInference; } : T; /** Schema options after applying the same framework defaults used at runtime. */ type EffectiveSchemaOptions = Merge; type EffectiveTypeKey = EffectiveSchemaOptions extends { typeKey: infer Key extends string; } ? Key : 'type'; type TimestampSchema = { [K in keyof WithTimestamps>]: { [P in keyof WithTimestamps>[K] as P extends 'type' ? EffectiveTypeKey : P]: WithTimestamps>[K][P]; }; }; type InferenceOptions = Omit, 'timestamps'> & { timestamps: false; typeKey: EffectiveTypeKey; }; type UnfinishedSchemaMember = any; type InferredRawDocFromSchema = TOptions extends { typeKey: string; } | { _id: false; } ? InferRawDocType & TimestampSchema, InferenceOptions> : InferRawDocType & WithTimestamps>>; type OverriddenRawDocFromSchema = CorrectTopLevelRawId, TSchema, 'raw', EffectiveTypeKey>, TSchema, EffectiveTypeKey>, TSchema, TOptions>; type InferredHydratedDocFromSchema = TOptions extends { typeKey: string; } | { _id: false; } ? InferHydratedDocType & TimestampSchema, InferenceOptions> : InferHydratedDocType & WithTimestamps>>; type OverriddenHydratedDocFromSchema = MaybeApplyOverrides, TSchema, 'hydrated', EffectiveTypeKey> extends infer Doc ? HasHydratedCorrection> extends true ? CorrectHydratedSubdocumentIds> : Doc : never; type HasDisabledTopLevelId = EffectiveSchemaOptions extends { _id: false; } ? '_id' extends keyof Definition ? false : true : false; /** An optional undefined marker stops Mongoose's lean helpers reintroducing an ObjectId. */ type CorrectTopLevelRawId = HasDisabledTopLevelId extends true ? Doc & { _id?: undefined; } : Doc; type CorrectTopLevelHydratedId = HasDisabledTopLevelId extends true ? Omit & { _id?: undefined; } : Doc; /** Raw schema inference with per-field overrides and runtime-shape corrections. */ type OverriddenRawDoc = OverriddenRawDocFromSchema, ExtractProperty>; type OverriddenHydratedDoc = OverriddenHydratedDocFromSchema, ExtractProperty>; type HydratedDocumentFromClass = CorrectTopLevelHydratedId, VirtualType> & DocFacingMethods>, object, VirtualType>, OverriddenRawDoc, EffectiveSchemaOptions>>, ExtractProperty, ExtractProperty, ExtractProperty>; export type GetModelSchemaTypeFromClass = Schema, // TRawDocType Model, object, // TQueryHelpers ExtractProperty, // TInstanceMethods ExtractProperty, // TVirtuals HydratedDocumentFromClass>, // TModelType ExtractProperty, // TInstanceMethods object, // TQueryHelpers ExtractProperty, // TVirtuals ExtractProperty, // TStaticMethods ExtractProperty>; /** * Project each declared virtual onto the value the document exposes for it: a * getter's return type whatever arguments Mongoose passes it, otherwise the * setter's input type plus `undefined` when there is no getter, and * `unknown` for a virtual with neither — a populate virtual's shape is not * knowable from the schema, so reading it must force a narrowing. */ type VirtualValue = V extends { get: (...args: never[]) => infer R; } ? R : V extends { set: (value: infer S, ...rest: never[]) => unknown; } ? S | undefined : unknown; type SetterVirtualKeys = { [P in keyof T]: T[P] extends { set: (...args: never[]) => unknown; } ? P : never; }[keyof T]; export type VirtualType = [SetterVirtualKeys] extends [never] ? { [P in keyof T]: VirtualValue; } : { [P in keyof T as P extends SetterVirtualKeys ? never : P]: VirtualValue; } & { -readonly [P in keyof T as P extends SetterVirtualKeys ? P : never]: VirtualValue; }; /** * Caller-facing view of instance methods: drop the authored `this` constraint * from each method when projecting them onto the document type. A method body * may declare an explicit `this: ` (a narrower hand-written shape the * body needs — e.g. a populated ref or a plugin-reshaped field); that bridge is * deliberately not assignable-from the framework-computed hydrated doc, so a * direct `doc.method(...)` call would otherwise fail the this-context check * (TS2684) even though `this` is always correctly bound at runtime. Stripping it * here fixes the false positive while leaving the authored definitions * untouched, so method bodies stay type-checked against their declared `this`. * `OmitThisParameter` returns non-function members (and methods with no explicit * `this`) unchanged, so this is a strict no-op for ordinary instance methods. * * Known limitation: a method that is BOTH generic AND declares an explicit * `this` loses its type parameters here (they collapse to their constraint) — * `OmitThisParameter` rebuilds the signature via `infer`, which can't carry * generics. This is rare (instance methods are seldom generic), and the * alternative was worse: such a method was previously uncallable (TS2684). A * generic method WITHOUT an explicit `this` is untouched (no-op) and keeps its * generics; drop the `this` annotation if generic inference matters. */ export type DocFacingMethods = { [K in keyof M]: OmitThisParameter; }; export type GetModelTypeFromClass = Model, // TRawDocType object, // TQueryHelpers DocFacingMethods>, // TInstanceMethods ExtractProperty, // TVirtuals HydratedDocumentFromClass, GetModelSchemaTypeFromClass> & ExtractProperty; /** * A reduced Mongoose model type inferred from the runtime schema definition. * * Use this only as an authoring context inside a model class, where resolving * `GetModelTypeFromClass` would circularly reference the * class member still being inferred. It has native Mongoose model operations * and schema fields, but intentionally cannot contain that unfinished class's * custom statics, methods, or virtuals. * * Pass the model's literal `schemaOptions` as `TOptions` when they affect query * results. In particular, Mongoose 9.9 uses the schema generic to make * schema-level `lean: true` queries return plain objects by default and * `{ lean: false }` queries return hydrated documents. * * This is a TypeScript authoring limitation, not a second runtime schema. Use * {@link GetModelTypeFromClass} for complete model handles after class * definition. */ export type GetModelTypeLiteFromSchema = Model, // TRawDocType object, // TQueryHelpers object, // TInstanceMethods (unfinished in this authoring context) object, // TVirtuals (unfinished in this authoring context) CorrectTopLevelHydratedId, object, object, object, OverriddenRawDocFromSchema, EffectiveSchemaOptions>, T, TOptions>, Schema, UnfinishedSchemaMember, // TModelType: the owning class is unfinished here UnfinishedSchemaMember, // TInstanceMethods: keep complete models assignable UnfinishedSchemaMember, // TQueryHelpers UnfinishedSchemaMember, // TVirtuals UnfinishedSchemaMember, // TStaticMethods EffectiveSchemaOptions>>; export declare const defaultOptions: { readonly timestamps: true; readonly minimize: false; }; export type TBaseModel = GetModelTypeFromClass; export declare class BaseModel { static get modelSchema(): {}; static get schemaOptions(): {}; static get modelInstanceMethods(): {}; static get modelVirtuals(): {}; static get modelStatics(): {}; static initHooks(_schema: Schema): void; static initialize(this: T): GetModelTypeFromClass; } /** * Structural "is a BaseModel subclass" check by static shape (`initialize` + * `modelSchema`), not `instanceof`. The model loader uses it to catch a subclass * extending BaseModel from a *different installed copy* of * `@adaptivestone/framework` (duplicate/undeduped install): `instanceof` * compares prototype identity, so it's false across the copy boundary. Requiring * both markers means a legacy AbstractModel-based model can never match — its * `modelSchema` is an instance getter and it has no static `initialize`. */ export declare function isBaseModelSubclassShape(candidate: unknown): boolean; export {};