import { AsyncLocalStorage } from "node:async_hooks";
import { z as z$1 } from "zod";
import { Middleware as Middleware$1 } from "alepha";
import { Readable } from "node:stream";
import { ReadableStream as ReadableStream$1 } from "node:stream/web";
//#region ../../src/core/constants/KIND.d.ts
/**
 * Used for identifying primitives.
 *
 * @internal
 */
declare const KIND: unique symbol;
//#endregion
//#region ../../src/core/constants/MODULE.d.ts
/**
 * Used for identifying modules.
 *
 * @internal
 */
declare const MODULE: unique symbol;
//#endregion
//#region ../../src/core/interfaces/Service.d.ts
/**
 * In Alepha, a service is a class that can be instantiated or an abstract class. Nothing more, nothing less...
 */
type Service<T extends object = any> = InstantiableClass<T> | AbstractClass<T> | RunFunction<T>;
type RunFunction<T extends object = any> = (...args: any[]) => T | undefined;
type InstantiableClass<T extends object = any> = new (...args: any[]) => T;
/**
 * Abstract class is a class that cannot be instantiated directly!
 * It widely used for defining interfaces.
 */
type AbstractClass<T extends object = any> = abstract new (...args: any[]) => T;
/**
 * Service substitution allows you to register a class as a different class.
 * Providing class A, but using class B instead.
 * This is useful for testing, mocking, or providing a different implementation of a service.
 *
 * class A is mostly an AbstractClass, while class B is an InstantiableClass.
 */
interface ServiceSubstitution<T extends object = any> {
  /**
   * Every time someone asks for this class, it will be provided with the 'use' class.
   */
  provide: Service<T>;
  /**
   * Service to use instead of the 'provide' service.
   *
   * Syntax is inspired by Angular's DI system.
   */
  use: Service<T>;
  /**
   * If true, if the service already exists -> just ignore the substitution and do not throw an error.
   * Mostly used for plugins to enforce a substitution without throwing an error.
   */
  optional?: boolean;
}
/**
 * Every time you register a service, you can use this type to define it.
 *
 * alepha.with( ServiceEntry )
 * or
 * alepha.with( provide: ServiceEntry, use: MyOwnServiceEntry )
 *
 * And yes, you declare the *type* of the service, not the *instance*.
 */
type ServiceEntry<T extends object = any> = Service<T> | ServiceSubstitution<T>;
declare function isClass(func: any): func is InstantiableClass;
//#endregion
//#region ../../src/core/helpers/primitive.d.ts
interface PrimitiveArgs<T extends object = {}> {
  options: T;
  alepha: Alepha;
  service: InstantiableClass<Service>;
  module?: Service;
}
interface PrimitiveConfig {
  propertyKey: string;
  service: InstantiableClass<Service>;
  module?: Service;
}
declare abstract class Primitive<T extends object = {}> {
  protected readonly alepha: Alepha;
  readonly options: T;
  readonly config: PrimitiveConfig;
  constructor(args: PrimitiveArgs<T>);
  /**
   * Called automatically by Alepha after the primitive is created.
   */
  protected onInit(): void;
  /**
   * Override (partially) the options of this primitive.
   *
   * Options are shallow-merged into the existing options — fields not present
   * in `partial` are preserved. Must be called BEFORE `alepha.start()`;
   * throws once the container has started because options are consumed during
   * start-up (route registration, etc.) and later mutations would have no effect.
   *
   * Typical use case: customize a built-in primitive from a module without
   * forking the whole module.
   *
   * @example Instance-level override
   * ```ts
   * const auth = alepha.inject(AuthRouter);
   * auth.login.override({ lazy: () => import("./MyLogin.tsx") });
   * ```
   *
   * @example Subclass override (constructor body, after super())
   * ```ts
   * class MyAuthRouter extends AuthRouter {
   *   constructor() {
   *     super();
   *     this.login.override({ lazy: () => import("./MyLogin.tsx") });
   *   }
   * }
   * ```
   */
  override(partial: Partial<T>): this;
}
type PrimitiveFactoryLike<T extends object = any> = {
  (options: T): any;
  [KIND]: any;
};
declare const createPrimitive: <TPrimitive extends Primitive>(primitive: InstantiableClass<TPrimitive> & {
  [MODULE]?: Service;
}, options: TPrimitive["options"]) => TPrimitive;
//#endregion
//#region ../../src/core/interfaces/Async.d.ts
/**
 * Represents a value that can be either a value or a promise of value.
 */
type Async<T> = T | Promise<T>;
/**
 * Represents a function that returns an async value.
 */
type AsyncFn = (...args: any[]) => Async<any>;
/**
 * Transforms a type T into a promise if it is not already a promise.
 */
type MaybePromise<T> = T extends Promise<any> ? T : Promise<T>;
//#endregion
//#region ../../src/core/interfaces/LoggerInterface.d.ts
type LogLevel = "ERROR" | "WARN" | "INFO" | "DEBUG" | "TRACE" | "SILENT";
interface LoggerInterface {
  trace(message: string, data?: unknown): void;
  debug(message: string, data?: unknown): void;
  info(message: string, data?: unknown): void;
  warn(message: string, data?: unknown): void;
  error(message: string, data?: unknown): void;
}
//#endregion
//#region ../../src/core/helpers/FileLike.d.ts
interface FileLike {
  /**
   * Filename.
   * @default "file"
   */
  name: string;
  /**
   * Mandatory MIME type of the file.
   * @default "application/octet-stream"
   */
  type: string;
  /**
   * Size of the file in bytes.
   *
   * Always 0 for streams, as the size is not known until the stream is fully read.
   *
   * @default 0
   */
  size: number;
  /**
   * Last modified timestamp in milliseconds since epoch.
   *
   * Always the current timestamp for streams, as the last modified time is not known.
   * We use this field to ensure compatibility with File API.
   *
   * @default Date.now()
   */
  lastModified: number;
  /**
   * Returns a ReadableStream or Node.js Readable stream of the file content.
   *
   * For streams, this is the original stream.
   */
  stream(): StreamLike;
  /**
   * Returns the file content as an ArrayBuffer.
   *
   * For streams, this reads the entire stream into memory.
   */
  arrayBuffer(): Promise<ArrayBuffer>;
  /**
   * Returns the file content as a string.
   *
   * For streams, this reads the entire stream into memory and converts it to a string.
   */
  text(): Promise<string>;
  /**
   * Optional file path, if the file is stored on disk.
   *
   * This is not from the File API, but rather a custom field to indicate where the file is stored.
   */
  filepath?: string;
}
/**
 * TypeBox view of FileLike.
 */
type TFile = TUnsafe<FileLike>;
declare const isTypeFile: (value: TSchema) => value is TFile;
declare const isFileLike: (value: any) => value is FileLike;
type StreamLike = ReadableStream | ReadableStream$1 | Readable | NodeJS.ReadableStream;
type TStream = TUnsafe<StreamLike>;
//#endregion
//#region ../../src/core/providers/zodAugment.d.ts
/**
 * Legacy-compatibility shims so typebox-era structural accessors keep working
 * on zod schemas (the "short path" for the migration — avoids rewriting
 * hundreds of schema-walking call-sites):
 *
 *   typebox            zod            alias added here
 *   ----------------   ------------   ----------------
 *   obj.properties     obj.shape      .properties -> .shape
 *   array.items        array.element  .items      -> .element
 *   union.anyOf        union.options  .anyOf      -> .options
 *
 * Both the runtime (prototype getters) and the type-level (`declare module`
 * interface merge) are provided, so `schema.properties` resolves and typechecks.
 *
 * Imported for side-effects by ZodProvider so it loads with the `z` core.
 */
declare module "zod" {
  interface ZodObject {
    /** typebox-compat alias for {@link ZodObject.shape}. */
    readonly properties: this["shape"];
  }
  interface ZodArray {
    /** typebox-compat alias for {@link ZodArray.element}. */
    readonly items: this["element"];
  }
  interface ZodUnion {
    /** typebox-compat alias for {@link ZodUnion.options}. */
    readonly anyOf: this["options"];
  }
  interface ZodTuple {
    /** typebox-compat alias for the tuple's element schemas. */
    readonly items: readonly import("zod").ZodType[];
  }
}
//#endregion
//#region ../../src/core/providers/ZodProvider.d.ts
/**
 * Alepha's `z` — a thin, enhanceable wrapper over zod 4 that mirrors the
 * ergonomics of the legacy typebox `t` provider (same call-shapes, so existing
 * `t.*` call-sites become a near-mechanical rename), while delegating all
 * validation + static-type inference to zod.
 *
 * Design notes:
 * - No encode/decode. string -> string, number -> number. Validation is a plain
 *   `schema.parse(value)` — zod does NOT use `Function`/`eval`, so this is safe
 *   inside Cloudflare Workers (unlike typebox's `Compile`).
 * - Metadata (`title`, `description`, `format`, custom `~options`) rides on zod's
 *   native `.meta()` registry, so `z.toJSONSchema()` round-trips it for OpenAPI
 *   + form generation. Defaults use `.default()`.
 */
type ZType = z$1.ZodType;
type ZObject<T extends z$1.ZodRawShape = any> = z$1.ZodObject<T>;
/** Replaces typebox `Static<T>`. */
type Infer<T extends z$1.ZodType> = z$1.infer<T>;
/**
 * Shallow output-extraction for `T extends SomeSchema ? Static<T> : Fallback`
 * conditional positions.
 *
 * Reads zod's `_zod.output` directly (a single shallow conditional) instead of
 * first testing `T extends TRequestBody` / `TResponseBody` — those tests compare
 * `T` against 5-6 member unions of deeply-recursive zod class types, and that
 * structural assignability check is what trips TypeScript's instantiation-depth
 * limit (TS2589) inside `$action`'s generics. The extracted type is identical to
 * `Static<T>` for any real schema; non-schema `T` (e.g. `undefined`) yields
 * `Fallback`.
 */
type SchemaOutput<T, Fallback = any> = [T] extends [{
  _zod: {
    output: infer O;
  };
}] ? O : Fallback;
interface SchemaOptions {
  title?: string;
  description?: string;
  default?: unknown;
  format?: string;
  /** Alepha string transforms, kept for JSON-Schema round-trip parity. */
  "~options"?: {
    trim?: boolean;
    lowercase?: boolean;
  };
  [key: string]: unknown;
}
interface StringOptions extends SchemaOptions {
  minLength?: number;
  maxLength?: number;
  pattern?: string | RegExp;
}
interface NumberOptions extends SchemaOptions {
  minimum?: number;
  maximum?: number;
}
interface TextOptions extends StringOptions {
  size?: "short" | "regular" | "long" | "rich";
  trim?: boolean;
  lowercase?: boolean;
}
/** Defaults mirroring TypeProvider's static length caps. */
declare const Z_LIMITS: {
  short: number;
  regular: number;
  long: number;
  rich: number;
  arrayMaxItems: number;
};
declare const z: {
  /**
   * Native zod coercion namespace (`z.coerce.number()`, `z.coerce.boolean()`…).
   * Used at the HTTP/string boundary (query, headers, env) where everything
   * arrives as a string; request bodies and the ORM stay strict (no coercion).
   */
  coerce: typeof z$1.coerce;
  object: typeof z$1.object;
  array: typeof z$1.array;
  record: typeof z$1.record;
  tuple: typeof z$1.tuple;
  union: typeof z$1.union;
  string: typeof z$1.string;
  number: typeof z$1.number;
  boolean: typeof z$1.boolean;
  null: typeof z$1.null;
  any: typeof z$1.any;
  void: typeof z$1.void;
  undefined: typeof z$1.undefined;
  literal: typeof z$1.literal;
  /** Alias for `zod.literal` (legacy `t.const`). */
  const: typeof z$1.literal;
  enum: typeof z$1.enum;
  /** Integer — native `z.int()` (format `safeint`, drives PG INT column). */
  integer: typeof z$1.int;
  /** Free-form JSON object (`Record<string, any>`). */
  json: () => z$1.ZodRecord<z$1.ZodString, z$1.ZodAny>;
  text: (options?: TextOptions) => z$1.ZodString;
  shortText: (options?: TextOptions) => z$1.ZodString;
  longText: (options?: TextOptions) => z$1.ZodString;
  richText: (options?: TextOptions) => z$1.ZodString;
  email: () => z$1.ZodString;
  uuid: () => z$1.ZodString;
  url: () => z$1.ZodString;
  datetime: () => z$1.ZodString;
  date: () => z$1.ZodString;
  time: () => z$1.ZodString;
  /** bigint as a validated string (no codec). */
  bigint: () => z$1.ZodString;
  binary: () => z$1.ZodString;
  duration: () => z$1.ZodString;
  e164: () => z$1.ZodString;
  bcp47: () => z$1.ZodString;
  constantCase: () => z$1.ZodString;
  int32: () => z$1.ZodInt;
  int64: () => z$1.ZodInt;
  file: (options?: {
    maxSize?: number;
  }) => z$1.ZodAny;
  stream: () => z$1.ZodAny;
  valueLabel: () => z$1.ZodObject<{
    value: z$1.ZodString;
    label: z$1.ZodString;
    description: z$1.ZodOptional<z$1.ZodString>;
  }, z$1.core.$strip>;
  /** Pagination wrapper, mirrors `pageSchema(item)`. */
  page: <T extends z$1.ZodType>(item: T) => z$1.ZodObject<{
    content: z$1.ZodArray<T>;
    page: z$1.ZodObject<{
      number: z$1.ZodInt;
      size: z$1.ZodInt;
      offset: z$1.ZodInt;
      numberOfElements: z$1.ZodInt;
      totalElements: z$1.ZodOptional<z$1.ZodInt>;
      totalPages: z$1.ZodOptional<z$1.ZodInt>;
      isEmpty: z$1.ZodBoolean;
      isFirst: z$1.ZodBoolean;
      isLast: z$1.ZodBoolean;
    }, z$1.core.$strip>;
  }, z$1.core.$strip>;
  /** Export a schema to JSON Schema (OpenAPI / form generation). */
  toJSONSchema: typeof z$1.toJSONSchema;
  /** Runtime type guards (`z.schema.*`) — schema introspection for ORM + forms. */
  schema: {
    isOptional: (s: any) => s is z$1.ZodOptional<z$1.core.$ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>>>;
    isDefault: (s: any) => s is z$1.ZodDefault<z$1.core.$ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>>>;
    isObject: (s: any) => s is z$1.ZodObject<z$1.core.$ZodLooseShape, z$1.core.$strip>;
    isString: (s: any) => boolean;
    isNumber: (s: any) => boolean;
    isBoolean: (s: any) => s is z$1.ZodBoolean;
    isArray: (s: any) => s is z$1.ZodArray<z$1.core.$ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>>>;
    isUnion: (s: any) => s is z$1.ZodUnion<readonly z$1.core.$ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>>[]>;
    isNull: (s: any) => s is z$1.ZodNull;
    isRecord: (s: any) => s is z$1.ZodRecord<z$1.core.$ZodRecordKey, z$1.core.$ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>>>;
    isEnum: (s: any) => boolean;
    isLiteral: (s: any) => boolean;
    isAny: (s: any) => s is z$1.ZodAny;
    isNullable: (s: any) => s is z$1.ZodNullable<z$1.core.$ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>>>;
    isInteger: (s: any) => boolean;
    isText: (s: any) => boolean;
    isDateTime: (s: any) => boolean;
    isDate: (s: any) => boolean;
    isTime: (s: any) => boolean;
    isBigInt: (s: any) => boolean;
    isUuid: (s: any) => boolean;
    isEmail: (s: any) => boolean;
    isUrl: (s: any) => boolean;
    isBinary: (s: any) => boolean;
    isUUID: (s: any) => boolean;
    isScalar: (s: any) => boolean;
    isSchema: (s: any) => s is z$1.ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>>;
    isTuple: (s: any) => s is z$1.ZodTuple<readonly z$1.core.$ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>>[], z$1.core.$ZodType<unknown, unknown, z$1.core.$ZodTypeInternals<unknown, unknown>> | null>;
    isUndefined: (s: any) => s is z$1.ZodUndefined;
    isUnsafe: (s: any) => s is z$1.ZodAny | z$1.ZodUnknown;
    isVoid: (s: any) => s is z$1.ZodVoid;
    format: (s: any) => string | undefined;
    /** The string values of a `ZodEnum` (typebox-compat for `value.enum`). */
    enumValues: (s: any) => string[];
    /** Peel optional / nullable / default wrappers to the inner schema. */
    unwrap: (s: any) => any;
    /**
     * Read a schema's default value (peeling optional/nullable wrappers), or
     * `undefined` if there is none. In zod, defaults are a `ZodDefault` wrapper
     * (not a `default` data property as in typebox), so `"default" in schema`
     * is NOT a valid test — every schema has a `.default()` method.
     */
    getDefault: (s: any) => unknown;
    /** typebox-compat: the object's required (non-optional) field names. */
    requiredKeys: (s: any) => string[];
  };
};
type Z = typeof z;
//#endregion
//#region ../../src/core/providers/TypeProvider.d.ts
/** Raw zod namespace (legacy `Type` escape hatch). */
declare const Type: typeof z$1;
type Static<T extends ZType> = Infer<T>;
type StaticDecode<T extends ZType> = Infer<T>;
type StaticEncode<T extends ZType> = Infer<T>;
type TSchema = ZType;
type TObject<T extends z$1.ZodRawShape = any> = ZObject<T>;
type TProperties = z$1.ZodRawShape;
type TString = z$1.ZodString;
type TNumber = z$1.ZodNumber;
type TInteger = z$1.ZodNumber;
type TBoolean = z$1.ZodBoolean;
type TArray<T extends ZType = ZType> = z$1.ZodArray<T>;
type TUnion<_T extends ZType[] = ZType[]> = z$1.ZodUnion;
type TRecord = z$1.ZodRecord<any, any>;
type TTuple = ZType;
type TNull = z$1.ZodNull;
type TAny = z$1.ZodAny;
type TVoid = z$1.ZodVoid;
type TBigInt = z$1.ZodString;
type TUnsafe<_T = unknown> = ZType;
type TOptional<T extends ZType = ZType> = z$1.ZodOptional<T>;
type TOptionalAdd<T extends ZType = ZType> = z$1.ZodOptional<T>;
type TPick<T extends ZObject = ZObject, _K = unknown> = T;
type TOmit<T extends ZObject = ZObject, _K = unknown> = T;
type TPartial<_T extends ZObject = ZObject> = ZObject;
type TInterface<_T = unknown, _U = unknown> = ZObject;
type TKeysToIndexer<_T = unknown> = any;
type TSchemaOptions = SchemaOptions;
type TStringOptions = StringOptions;
type TNumberOptions = NumberOptions;
type TObjectOptions = SchemaOptions;
type TArrayOptions = SchemaOptions;
type TextLength = "short" | "regular" | "long" | "rich";
type TTextOptions = TextOptions;
interface TEnumOptions extends TextOptions {
  /** `"text"` = TEXT column; omitted = a real PostgreSQL ENUM type. */
  mode?: "text";
  /** Custom PG ENUM type name (shared across tables). */
  name?: string;
}
/** Legacy `TypeProvider` — kept for its static config knobs. */
declare class TypeProvider {
  static DEFAULT_STRING_MAX_LENGTH: number | undefined;
  static DEFAULT_SHORT_STRING_MAX_LENGTH: number | undefined;
  static DEFAULT_LONG_STRING_MAX_LENGTH: number | undefined;
  static DEFAULT_RICH_STRING_MAX_LENGTH: number | undefined;
  static DEFAULT_ARRAY_MAX_ITEMS: number;
  static translateError: (error: {
    message?: string;
  }, _locale?: string) => string;
  static setLocale: (_locale: string) => void;
  static isValidBigInt: (value: string | number) => boolean;
}
//#endregion
//#region ../../src/core/primitives/$atom.d.ts
/**
 * Define an atom for state management.
 *
 * Atom lets you define a piece of state with a name, schema, and default value.
 *
 * By default, Alepha state is just a simple key-value store.
 * Using atoms allows you to have type safety, validation, and default values for your state.
 *
 * You control how state is structured and validated.
 *
 * Features:
 * - Schema validation on every write (invalid writes throw)
 * - Default value for initial state
 * - Automatic getter access in services with {@link $state}
 * - SSR support (server state automatically serialized and hydrated on client)
 * - React integration (useStore / useSelector hooks for automatic re-renders)
 * - Derived values with {@link $computed} (useComputed hook)
 * - Persistence adapters: cookie (SSR-safe), localStorage, sessionStorage
 * - `serverOnly` flag to keep an atom out of the hydration payload
 * - reset / watch helpers on the state manager
 * - Documentation generation & devtools integration (mutation log)
 *
 * Common use cases:
 * - user preferences
 * - feature flags
 * - configuration options
 * - session data
 *
 * Atom must contain only serializable data.
 * Avoid storing complex objects like class instances, functions, or DOM elements.
 * If you need to store complex data, consider using identifiers or references instead.
 */
declare const $atom: {
  <T extends ZType, N extends string>(options: AtomOptions<T, N>): Atom<T, N>;
  [KIND]: string;
};
/**
 * Persistence adapter for an atom.
 */
type AtomPersist = "cookie" | "localStorage" | "sessionStorage";
type AtomOptions<T extends ZType, N extends string> = {
  name: N;
  schema: T;
  description?: string;
  /**
   * Persist this atom outside the in-memory store.
   *
   * - `"cookie"` — synced to an HTTP cookie by the `alepha/server/cookies`
   *   module. Works on the server AND in the browser, so it is the only
   *   correct adapter for SSR apps: the server reads it while rendering and
   *   the first paint matches the persisted state.
   * - `"localStorage"` / `"sessionStorage"` — browser Web Storage. Fine for
   *   pure SPA apps. The server cannot see these values; registering such
   *   an atom during SSR logs a warning.
   *
   * Values are validated against the schema when read back; invalid or
   * corrupted entries are discarded and the default is used.
   *
   * **Security: cookie-persisted atoms are attacker-controlled.** The
   * cookie written by `persist: "cookie"` is unsigned, unencrypted, and
   * freely writable by any client-side script (`AtomCookiePersistence`'s
   * `cookieOptions()` sets no `sign`, `encrypt`, or `httpOnly`) — a request
   * can present any value it wants for it. Never persist trust-bearing
   * state — user ids, roles, entitlements, permissions — in a
   * `persist: "cookie"` atom. If you need a signed, encrypted, and/or
   * `httpOnly` cookie, declare an explicit
   * `$cookie({ key: atom.key, sign: true, encrypt: true, httpOnly: true, ... })`
   * binding instead — that is the escape hatch for trust-bearing values.
   */
  persist?: AtomPersist;
  /**
   * Exclude this atom from the SSR hydration export
   * (`StateManager.exportAtoms()`).
   *
   * This is the ONLY guarantee `serverOnly` makes: the value is never
   * written into the `<script id="__ssr">` JSON block serialized into the
   * HTML payload. It says nothing about any other channel a value can
   * reach the browser through.
   *
   * **Cannot be combined with `persist`.** Every persistence adapter
   * (`"cookie"`, `"localStorage"`, `"sessionStorage"`) targets the browser
   * by definition — cookie persistence ships the value in a `Set-Cookie`
   * response header, and web-storage persistence IS the browser. Declaring
   * `serverOnly: true` together with any `persist` value throws
   * `AlephaError` at `$atom()` call time, because the persistence channel
   * would leak the exact value `serverOnly` is meant to keep server-side.
   *
   * Use `serverOnly` for atoms that may hold secrets or internal
   * request-scoped state that must never leave the server, and never pair
   * it with `persist`.
   *
   * **Never make a `serverOnly` atom a dependency of a `$computed` that the
   * browser reads through `useComputed`.** A computed is re-derived, never
   * serialized: the server derives it from the atom's real value, and the
   * browser — which never received that value — re-derives it from the
   * atom's default. The two disagree, producing a React hydration mismatch
   * and a silently wrong value from then on. Keep such a computed
   * server-side (`alepha.store.get`), or derive it from atoms that ship.
   */
  serverOnly?: boolean;
} & (T extends z$1.ZodOptional<any> ? {
  default?: Static<T>;
} : {
  default: Static<T>;
});
declare class Atom<T extends ZType = TObject, N extends string = string> {
  readonly options: AtomOptions<T, N>;
  get schema(): T;
  get key(): N;
  constructor(options: AtomOptions<T, N>);
}
type TAtomObject = ZType;
type AtomStatic<T extends ZType> = T extends z$1.ZodOptional<any> ? Static<T> | undefined : Static<T>;
//#endregion
//#region ../../src/core/primitives/$computed.d.ts
/**
 * Define a derived, read-only value computed from one or more atoms
 * (or other computed values).
 *
 * Dependencies are declared statically, which keeps the data flow explicit
 * and lets subscribers know exactly which mutations invalidate the value.
 *
 * Computed values are never stored, serialized, hydrated, or persisted —
 * they are recomputed from their dependencies on every read, so they are
 * always correct inside request-scoped (fork) state on the server.
 *
 * ```ts
 * const cartTotal = $computed({
 *   name: "cartTotal",
 *   deps: [cartAtom],
 *   get: (cart) => cart.items.reduce((sum, it) => sum + it.price, 0),
 * });
 *
 * alepha.store.get(cartTotal); // number
 * ```
 *
 * ### Footgun: a `serverOnly` dependency breaks hydration
 *
 * A computed whose deps include a `serverOnly` atom will NOT agree across the
 * SSR boundary. `serverOnly` keeps the atom out of the hydration payload, so
 * the server derives the value from the atom's real value while the browser
 * re-derives it from the atom's *default* — React then hydrates a DOM that
 * does not match the markup it received (a hydration mismatch, and a
 * silently wrong value afterwards).
 *
 * Either keep the computed server-side only (read it via `alepha.store.get`,
 * never through `useComputed`), or derive it from atoms that ship to the
 * browser. Note this cuts the other way too: if the value is safe to send to
 * the browser, the dependency should not have been `serverOnly` to begin
 * with.
 */
declare const $computed: {
  <const D extends ReadonlyArray<AnyDep>, R, N extends string = string>(options: ComputedOptions<D, R, N>): Computed<R, N>;
  [KIND]: string;
};
type AnyDep = Atom<any, any> | Computed<any, any>;
type DepValues<D extends ReadonlyArray<AnyDep>> = { [K in keyof D]: D[K] extends Atom<infer T, any> ? AtomStatic<T> : D[K] extends Computed<infer R2, any> ? R2 : never; };
interface ComputedOptions<D extends ReadonlyArray<AnyDep>, R, N extends string = string> {
  name: N;
  deps: D;
  get: (...values: DepValues<D>) => R;
  description?: string;
}
declare class Computed<R = unknown, N extends string = string> {
  readonly options: ComputedOptions<any, R, N>;
  constructor(options: ComputedOptions<any, R, N>);
  get key(): N;
  /**
   * Reentrancy guard for {@link keys}. Deps are declared as a `readonly`
   * array at construction time, so a cycle can't be built through the
   * public API — but the array itself isn't frozen, so nothing stops a
   * caller from reaching in and creating one anyway. Without this guard,
   * a cycle would recurse until the JS engine throws a native
   * `RangeError`, which violates the repo's "never throw a bare `Error`"
   * convention.
   */
  protected resolvingKeys: boolean;
  /**
   * Reentrancy guard for {@link compute}, same rationale as
   * {@link resolvingKeys}.
   */
  protected computing: boolean;
  /**
   * Transitive atom keys this computed value depends on. Subscribers
   * (useComputed, StateManager.watch) use this to know which `state:mutate`
   * events invalidate the value.
   */
  keys(): string[];
  /**
   * Resolve the value using the given dependency resolver.
   */
  compute(resolve: (dep: AnyDep) => unknown): R;
}
//#endregion
//#region ../../src/core/primitives/$inject.d.ts
/**
 * Get the instance of the specified type from the context.
 *
 * ```ts
 * class A { }
 * class B {
 *   a = $inject(A);
 * }
 * ```
 */
declare const $inject: <T extends object>(type: Service<T>, opts?: InjectOptions<T>) => T;
declare class InjectPrimitive extends Primitive {}
interface InjectOptions<T extends object = any> {
  /**
   * - 'transient' → Always a new instance on every inject. Zero caching.
   * - 'singleton' → One instance per Alepha runtime (per-thread). Never disposed until Alepha shuts down. (default)
   * - 'scoped' → One instance per AsyncLocalStorage context.
   *   - A new scope is created when Alepha handles a request, a scheduled job, a queue worker task...
   *   - You can also start a manual scope via alepha.context.run(() => { ... }).
   *   - When the scope ends, the scoped registry is discarded.
   *
   * @default "singleton"
   */
  lifetime?: "transient" | "singleton" | "scoped";
  /**
   * Constructor arguments to pass when creating a new instance.
   */
  args?: ConstructorParameters<InstantiableClass<T>>;
  /**
   * Parent that requested the instance.
   *
   * @internal
   */
  parent?: Service | null;
}
//#endregion
//#region ../../src/core/primitives/$module.d.ts
/**
 * Wrap Services and Primitives into a Module.
 *
 * - A module is just a Service with some extra {@link Module}.
 * - You must attach a `name` to it.
 * - Name must follow the pattern: `project.module.submodule`. (e.g. `myapp.users.auth`).
 *
 * @example
 * ```ts
 * import { $module } from "alepha";
 * import { MyService } from "./MyService.ts";
 *
 * export default $module({
 *  name: "my.project.module",
 *  services: [MyService],
 * });
 * ```
 *
 * ### Slots
 *
 * - `services[]` — always auto-injected. Module metadata attached.
 * - `variants[]` — module metadata attached but NOT auto-injected. Two typical uses:
 *   (1) alternative implementations picked at register-time via `alepha.with({ provide, use })`;
 *   (2) services whose instantiation is driven externally (e.g., the framework core).
 * - `imports[]` — other modules this one depends on. Wired before `register()` runs.
 * - `atoms[]` — registered on the store.
 * - `primitives[]` — tagged with module metadata.
 * - `register(alepha)` — purely additive side-effect hook. Runs AFTER `imports[]`
 *   are wired and BEFORE `services[]` are auto-injected — so substitutions it
 *   records (e.g. `alepha.with({ provide, use })`) apply to the subsequent
 *   auto-injection. It can never suppress auto-registration.
 *
 * ### Why Modules?
 *
 * #### Logging
 *
 * By default, AlephaLogger will log the module name in the logs.
 * This helps to identify where the logs are coming from.
 *
 * You can also set different log levels for different modules.
 *
 * #### Modulith
 *
 * Force to structure your application in modules, even if it's a single deployable unit.
 * It helps to keep a clean architecture and avoid monolithic applications.
 *
 * ### When not to use Modules?
 *
 * Small applications do not need modules. Modules earn their keep when the application
 * grows — as a rule of thumb, once a module has 30+ `$actions`, consider splitting it.
 */
declare const $module: (options: ModulePrimitiveOptions) => Service<Module>;
interface ModulePrimitiveOptions {
  /**
   * Name of the module.
   *
   * It should be in the format of `project.module.submodule`.
   */
  name: string;
  /**
   * Services that belong to this module. All services listed here are:
   * - tagged with module metadata (used for logging, boundary checks)
   * - auto-injected when the module is registered
   *
   * If you need an alternative implementation that should NOT be eagerly instantiated
   * (picked at register-time instead), list it under `variants` instead.
   */
  services?: Array<Service>;
  /**
   * Alternative implementations that belong to this module but are NOT auto-injected.
   * Module metadata is still attached.
   *
   * Typical use: abstract provider in `services[]`, concrete impls here, with
   * `register()` choosing one via `alepha.with({ provide, use })`.
   *
   * @example
   * ```ts
   * $module({
   *   name: "alepha.email",
   *   services: [EmailProvider],
   *   variants: [MemoryEmailProvider, SmtpEmailProvider],
   *   register: (alepha) => {
   *     alepha.with({
   *       provide: EmailProvider,
   *       use: alepha.isTest() ? MemoryEmailProvider : SmtpEmailProvider,
   *     });
   *   },
   * });
   * ```
   */
  variants?: Array<Service>;
  /**
   * Other modules this module depends on. They are wired via `alepha.with(Module)`
   * before `register()` runs and before `services[]` are injected.
   *
   * Prefer this over calling `alepha.with(OtherModule)` manually inside `register()`.
   */
  imports?: Array<Service<Module>>;
  /**
   * List of $primitives to register in the module.
   */
  primitives?: Array<PrimitiveFactoryLike>;
  /**
   * Additive side-effect hook. Runs AFTER `imports[]` are wired and BEFORE
   * `services[]` are auto-injected — so substitutions it records apply to
   * the subsequent injection. Use it for:
   * - variant substitution: `alepha.with({ provide, use })`
   * - env parsing: `alepha.parseEnv(schema)`
   * - state seeding: `alepha.store.set(...)`
   *
   * It cannot suppress auto-registration — `services[]` are always injected.
   */
  register?: (alepha: Alepha) => void;
  /**
   * List of atoms to register in the module.
   */
  atoms?: Array<Atom<any>>;
}
/**
 * Base class for all modules.
 */
declare abstract class Module {
  abstract readonly options: ModulePrimitiveOptions;
  abstract register(alepha: Alepha): void;
  static NAME_REGEX: RegExp;
  /**
   * Check if a Service is a Module.
   */
  static is(ctor: Service): boolean;
  /**
   * Get the Module of a Service.
   *
   * Returns undefined if the Service is not part of a Module.
   */
  static of(ctor: Service): Service<Module> | undefined;
}
/**
 * Helper type to add Module metadata to a Service.
 */
type WithModule<T extends object = any> = T & {
  [MODULE]?: Service;
};
//#endregion
//#region ../../src/core/providers/AlsProvider.d.ts
type AsyncLocalStorageData = any;
type StateScope = "current" | "app" | "parent";
declare const ALS_PARENT: unique symbol;
declare class AlsProvider {
  static create: () => AsyncLocalStorage<AsyncLocalStorageData> | undefined;
  als?: AsyncLocalStorage<AsyncLocalStorageData>;
  constructor();
  createContextId(): string;
  run<R>(callback: () => R, data?: Record<string, any>): R;
  exists(): boolean;
  get<T>(key: string, scope?: StateScope): T | undefined;
  /**
   * Return the raw ALS layer object that owns `key`, walking from the
   * current layer up through parent forks — the same resolution order as
   * the default-scope branch of {@link get}. Returns `undefined` when no
   * active ALS layer (current or any ancestor) has the key.
   *
   * Used by `StateManager.register()` to decode a value in place, in
   * whichever fork layer it physically lives, instead of flattening
   * fork-scoped state into the app-level store.
   */
  getLayer(key: string): AsyncLocalStorageData | undefined;
  has(key: string): boolean;
  set<T>(key: string, value: T): void;
}
//#endregion
//#region ../../src/core/providers/Json.d.ts
/**
 * Mimics the JSON global object with stringify and parse methods.
 *
 * Used across the codebase via dependency injection.
 */
declare class Json {
  stringify: {
    (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
    (value: any, replacer?: (number | string)[] | null, space?: string | number): string;
  };
  parse: (text: string, reviver?: (this: any, key: string, value: any) => any) => any;
}
//#endregion
//#region ../../src/core/providers/SchemaCodec.d.ts
declare abstract class SchemaCodec {
  /**
   * Encode the value to a string format.
   */
  abstract encodeToString<T extends TSchema>(schema: T, value: Static<T>): string;
  /**
   * Encode the value to a binary format.
   */
  abstract encodeToBinary<T extends TSchema>(schema: T, value: Static<T>): Uint8Array;
  /**
   * Decode string, binary, or other formats to the schema type.
   */
  abstract decode<T>(schema: TSchema, value: unknown): T;
}
//#endregion
//#region ../../src/core/providers/JsonSchemaCodec.d.ts
declare class JsonSchemaCodec extends SchemaCodec {
  protected readonly json: Json;
  protected readonly encoder: TextEncoder;
  protected readonly decoder: TextDecoder;
  encodeToString<T extends TSchema>(schema: T, value: Static<T>): string;
  encodeToBinary<T extends TSchema>(schema: T, value: Static<T>): Uint8Array;
  decode<T>(schema: TSchema, value: unknown): T;
}
//#endregion
//#region ../../src/core/providers/KeylessJsonSchemaCodec.d.ts
interface KeylessCodec<T = any> {
  encode: (value: T) => string;
  decode: (str: string) => T;
}
interface KeylessCodecOptions {
  /**
   * Whether to use `new Function()` for code compilation.
   * When false, uses an interpreter-based approach (safer but slower).
   *
   * @default Auto-detected: false in browser (CSP compatibility), true on server
   */
  useFunctionCompilation?: boolean;
}
/**
 * KeylessJsonSchemaCodec provides schema-driven JSON encoding without keys.
 *
 * It uses the schema to determine field order, allowing the encoded output
 * to be a simple JSON array instead of an object with keys.
 */
declare class KeylessJsonSchemaCodec extends SchemaCodec {
  protected readonly cache: Map<import("alepha").ZType, KeylessCodec<any>>;
  protected readonly textEncoder: TextEncoder;
  protected readonly textDecoder: TextDecoder;
  protected varCounter: number;
  protected useFunctionCompilation: boolean;
  /**
   * Configure codec options.
   */
  configure(options: KeylessCodecOptions): this;
  /**
   * Hook to auto-detect safe mode on configure.
   * Disables function compilation in browser by default.
   */
  protected onConfigure: import("alepha").HookPrimitive<"configure">;
  /**
   * Encode value to a keyless JSON string.
   */
  encodeToString<T extends TSchema>(schema: T, value: Static<T>): string;
  /**
   * Encode value to binary (UTF-8 encoded keyless JSON).
   */
  encodeToBinary<T extends TSchema>(schema: T, value: Static<T>): Uint8Array;
  /**
   * Decode keyless JSON string or binary to value.
   */
  decode<T>(schema: TSchema, value: unknown): T;
  /**
   * Test if `new Function()` is available (not blocked by CSP).
   */
  protected canUseFunction(): boolean;
  /**
   * Get a compiled codec for the given schema.
   * Codecs are cached for reuse.
   */
  protected getCodec<T>(schema: TSchema): KeylessCodec<T>;
  protected nextVar(): string;
  /**
   * Compile codec using `new Function()` for maximum performance.
   * Only used when CSP allows and useFunctionCompilation is true.
   */
  protected compileWithFunction(schema: TSchema): KeylessCodec;
  /**
   * Compile codec using interpreter-based approach.
   * Safer (no eval/Function) but slower. Used in browser by default.
   */
  protected compileInterpreted(schema: TSchema): KeylessCodec;
  protected interpretEncode(schema: TSchema, value: any): any;
  protected interpretDecode(schema: TSchema, ctx: {
    arr: any[];
    i: number;
  }): any;
  protected interpretDecodeFromValue(schema: TSchema, value: any): any;
  protected genEnc(schema: TSchema, ve: string): string;
  protected genDec(schema: TSchema): {
    code: string;
    result: string;
  };
  protected genDecFromValue(schema: TSchema, expr: string): string;
  protected isLeaf(schema: TSchema): boolean;
  protected getObjectFields(schema: TObject): Array<{
    key: string;
    isOpt: boolean;
    isNullable: boolean;
    inner: TSchema;
  }>;
  protected isEnum(schema: TSchema): boolean;
  protected isNullable(schema: TSchema): boolean;
  protected unwrap(schema: TSchema): TSchema;
  /**
   * Reconstruct an object from a parsed array (for when input is already parsed).
   */
  protected reconstructObject(schema: TSchema, arr: any[]): any;
}
//#endregion
//#region ../../src/core/providers/SchemaValidator.d.ts
interface ValidateOptions {
  trim?: boolean;
  nullToUndefined?: boolean;
  deleteUndefined?: boolean;
}
/**
 * Validates + coerces a value against a zod schema.
 *
 * Trimming / lowercasing / defaults / unknown-key stripping all live in the
 * schema itself now (zod), so this is a thin wrapper over `schema.parse`.
 * No typebox `Compile`, no `eval` — safe inside Cloudflare Workers.
 */
declare class SchemaValidator {
  validate<T extends TSchema>(schema: T, value: unknown, _options?: ValidateOptions): Static<T>;
  safeValidate<T extends TSchema>(schema: T, value: unknown): import("zod").ZodSafeParseResult<import("zod").output<T>>;
  /** Zod schemas are immutable — clone is a pass-through. */
  clone<T extends TSchema>(schema: T): T;
  /**
   * Legacy pre-processing entry point. Coercion now happens inside `parse`,
   * so this is a no-op kept for call-site compatibility.
   */
  beforeParse(_schema: unknown, value: unknown, _options?: ValidateOptions): unknown;
}
//#endregion
//#region ../../src/core/providers/CodecManager.d.ts
type Encoding = "object" | "string" | "binary";
interface EncodeOptions<T extends Encoding = Encoding> {
  /**
   * The output encoding format:
   * - 'string': Returns JSON string
   * - 'binary': Returns Uint8Array (for protobuf, msgpack, etc.)
   *
   * @default "string"
   */
  as?: T;
  /**
   * The encoder to use (e.g., 'json', 'protobuf', 'msgpack')
   *
   * @default "json"
   */
  encoder?: string;
  /**
   * Validation options to apply before encoding.
   */
  validation?: ValidateOptions | false;
}
type EncodeResult<T extends TSchema, E extends Encoding> = E extends "string" ? string : E extends "binary" ? Uint8Array : StaticEncode<T>;
interface DecodeOptions {
  /**
   * The encoder to use (e.g., 'json', 'protobuf', 'msgpack')
   *
   * @default "json"
   */
  encoder?: string;
  /**
   * Validation options to apply before encoding.
   */
  validation?: ValidateOptions | false;
}
/**
 * CodecManager manages multiple codec formats and provides a unified interface
 * for encoding and decoding data with different formats.
 */
declare class CodecManager {
  protected readonly codecs: Map<string, SchemaCodec>;
  protected readonly jsonCodec: JsonSchemaCodec;
  protected readonly keylessCodec: KeylessJsonSchemaCodec;
  protected readonly schemaValidator: SchemaValidator;
  default: string;
  constructor();
  /**
   * Register a new codec format.
   */
  register(opts: CodecRegisterOptions): void;
  /**
   * Get a specific codec by name.
   *
   * @param name - The name of the codec
   * @returns The codec instance
   * @throws {AlephaError} If the codec is not found
   */
  getCodec(name: string): SchemaCodec;
  /**
   * Encode data using the specified codec and output format.
   */
  encode<T extends TSchema, E extends Encoding = "object">(schema: T, value: unknown, options?: EncodeOptions<E>): EncodeResult<T, E>;
  /**
   * Decode data using the specified codec.
   */
  decode<T extends TSchema>(schema: T, data: any, options?: DecodeOptions): Static<T>;
  /**
   * Validate decoded data against the schema.
   *
   * This is automatically called before encoding or after decoding.
   */
  validate<T extends TSchema>(schema: T, value: unknown, options?: ValidateOptions): Static<T>;
}
interface CodecRegisterOptions {
  name: string;
  codec: SchemaCodec;
  default?: boolean;
}
//#endregion
//#region ../../src/core/providers/EventManager.d.ts
/**
 * Compiled event executor - optimized for hot paths.
 * Returns void for sync-only chains, Promise<void> for chains with async hooks.
 */
type CompiledEventExecutor<T extends keyof Hooks> = (payload: Hooks[T]) => void | Promise<void>;
/**
 * Options for compiled event executors.
 */
interface CompileOptions {
  /**
   * If true, errors will be caught and logged instead of throwing.
   * @default false
   */
  catch?: boolean;
}
declare class EventManager {
  logFn?: () => LoggerInterface | undefined;
  /**
   * Three-list storage for hooks, split by priority tier.
   */
  protected events: Record<string, {
    first: Array<Hook>;
    normal: Array<Hook>;
    last: Array<Hook>;
  }>;
  /**
   * Cache of compiled executors, auto-built on first emit per event.
   */
  protected cache: Map<string, CompiledEventExecutor<any>>;
  /**
   * Cache of resolved (topo-sorted) hook arrays per event.
   */
  protected sortedCache: Map<string, Hook<any>[]>;
  constructor(logFn?: () => LoggerInterface | undefined);
  protected get log(): LoggerInterface | undefined;
  clear(): void;
  /**
   * Registers a hook for the specified event.
   */
  on<T extends keyof Hooks>(event: T, hookOrFunc: Hook<T> | ((payload: Hooks[T]) => Async<void>)): () => void;
  protected invalidateCache(event: string): void;
  /**
   * Resolves the final ordered hook list for an event.
   * Applies topological sort (Kahn's algorithm) within each priority tier
   * based on before/after constraints.
   */
  protected resolve(event: string): Array<Hook>;
  /**
   * Topological sort using Kahn's algorithm.
   * Hooks with no constraints maintain registration order (stable).
   */
  protected topoSort(hooks: Array<Hook>): Array<Hook>;
  /**
   * Compiles an event into an optimized executor function.
   *
   * Called automatically by emit() on first use. Can also be called
   * manually for direct access to the executor.
   */
  compile<T extends keyof Hooks>(event: T, options?: CompileOptions): CompiledEventExecutor<T>;
  /**
   * Emits the specified event with the given payload.
   *
   * Auto-compiles and caches an optimized executor on first call per event.
   * Use `{ log: true }` for startup events that need timing information.
   */
  emit<T extends keyof Hooks>(event: T, payload: Hooks[T], options?: {
    /**
     * If true, the hooks will be logged with their execution time.
     *
     * @default false
     */
    log?: boolean;
    /**
     * If true, errors will be caught and logged instead of throwing.
     *
     * @default false
     */
    catch?: boolean;
  }): Promise<void>;
}
//#endregion
//#region ../../src/core/providers/StateManager.d.ts
interface AtomWithValue {
  atom: Atom;
  value: unknown;
}
declare class StateManager<State$1 extends object = State> {
  protected readonly als: AlsProvider;
  protected readonly events: EventManager;
  protected readonly codec: JsonSchemaCodec;
  protected readonly validator: SchemaValidator;
  protected readonly atoms: Map<keyof State$1, Atom<TObject, string>>;
  protected store: Partial<State$1>;
  constructor(store?: Partial<State$1>);
  /**
   * Export all registered atoms as a plain object.
   *
   * @param scope - Controls which store layer to read from:
   *   - `undefined` (default): Resolved value (walks fork tree then app store).
   *   - `"current"`: Only the current ALS layer — intentionally does NOT walk
   *     the parent chain so that SSR serialisation captures exactly what the
   *     current request set, without leaking parent-fork state.
   *   - `"app"`: Only the root (app-level) store.
   */
  exportAtoms(scope?: "current" | "app"): Record<string, unknown>;
  getAtoms(context?: boolean): Array<AtomWithValue>;
  /**
   * Return the registered atom for a state key, if any.
   */
  getAtom(key: string): Atom | undefined;
  /**
   * Every atom registered so far, whatever store layer (if any) currently
   * holds its value.
   *
   * This is the order-independent way to discover atoms. The
   * `"state:register"` event fires exactly once per key and `EventManager`
   * has no replay buffer, so a service instantiated after an atom registered
   * never hears about it — a real hazard, since `$module.register()`
   * registers `atoms[]` BEFORE it wires `imports[]` and injects `services[]`.
   * Services that act on atoms (e.g. the cookie persistence adapter) must
   * read this registry on demand rather than build their own map from the
   * event.
   */
  listAtoms(): Array<Atom>;
  register(atom: Atom<any>): this;
  /**
   * Install the atom's declared default into the app-level store.
   *
   * Deliberately bypasses {@link set}, for two reasons:
   *
   * 1. `set()` short-circuits when the new value equals the currently
   *    *resolved* value (`prevValue === value` for non-objects) — inside a
   *    fork that already holds the same primitive value, the app-store write
   *    would simply never happen.
   * 2. A registration seed is initialisation, NOT a mutation, so it must not
   *    emit `state:mutate`. Persistence adapters listen on that event: an
   *    atom registering lazily mid-request would otherwise emit a mutation
   *    carrying its *default*, and the cookie adapter would dutifully write
   *    it back as a `Set-Cookie` — overwriting the very cookie the request
   *    arrived with.
   *
   * A `undefined` default (only reachable for an optional schema) is not
   * written at all, so the key stays absent from the store — matching the
   * previous behaviour of `set(key, undefined)`.
   */
  protected seedDefault(atom: Atom<any>, key: keyof State$1): void;
  /**
   * A fresh, schema-validated copy of the atom's declared default.
   *
   * `atom.options.default` is a module-level object shared by every
   * container and every request in the process. Handing that exact reference
   * to the store would let an ordinary `store.mut(atom, s => ...)` mutate the
   * declaration itself, permanently and process-wide. Every other write path
   * round-trips through the validator (zod always returns a new object), so
   * these must too.
   */
  protected cloneDefault(atom: Atom<any>): unknown;
  /**
   * Decode a value that already exists under an atom's key at registration
   * time, in place, in whichever layer it physically lives (an ALS fork
   * layer or the app store) — never flattening a fork-scoped value into the
   * app-level store.
   *
   * On schema mismatch, falls back to the atom's default (written into that
   * same layer) and emits a warning: a bad seed silently reverting a whole
   * atom to its defaults should be visible, not indistinguishable from
   * "nothing was ever set".
   */
  protected decodeExisting(atom: Atom<any>, key: keyof State$1, layer: Record<string, any>): void;
  /**
   * Web-storage persistence (localStorage / sessionStorage) for atoms
   * declared with `persist`. Best-effort: quota errors and privacy modes
   * are swallowed. Cookie persistence is NOT handled here — it needs the
   * HTTP request cycle and lives in `alepha/server/cookies`
   * (AtomCookiePersistence), which discovers its atoms through
   * {@link listAtoms}. Both adapters are therefore registration-order
   * independent: one `persist` option, one reliability contract.
   */
  protected bindWebStorage(atom: Atom<any>): void;
  /**
   * Best-effort `Storage#removeItem`. Some privacy modes throw on every
   * Storage method, including `removeItem` — this must never escape a
   * recovery `catch`, or persistence stops being best-effort.
   */
  protected safeRemoveItem(storage: Storage, key: string): void;
  /**
   * Resolve a Web Storage area, or undefined when unavailable (server,
   * privacy mode that throws on access).
   */
  protected getWebStorage(kind: "localStorage" | "sessionStorage"): Storage | undefined;
  /**
   * Best-effort logger lookup. `StateManager` lives in `core`, which cannot
   * depend on the logger module, so this reads the `"alepha.logger"` state
   * key directly (set by `Alepha.create()`, see `Alepha.ts`) instead of
   * injecting a logger service. May be `undefined` during early boot, before
   * the logger is wired up — callers must stay null-safe.
   */
  protected get logger(): LoggerInterface | undefined;
  /**
   * Get a value from the state with proper typing.
   *
   * @param scope - Optional scope to control resolution:
   *   - `undefined` (default): Walk up the fork tree from current layer to root, then fall back to the app store.
   *   - `"current"`: Read only from the current fork layer (no tree walking).
   *   - `"parent"`: Read only from the immediate parent fork layer.
   *   - `"app"`: Read only from the root (app-level) store.
   */
  get<R>(target: Computed<R>, scope?: StateScope): R;
  get<T extends TAtomObject>(target: Atom<T>, scope?: StateScope): Static<T>;
  get<Key extends keyof State$1>(target: Key, scope?: StateScope): State$1[Key] | undefined;
  /**
   * Set a value in the state
   */
  set<T extends TAtomObject>(target: Atom<T>, value: AtomStatic<T>, options?: SetStateOptions): this;
  set<Key extends keyof State$1>(target: Key, value: State$1[Key] | undefined, options?: SetStateOptions): this;
  /**
   * Reset an atom back to its declared default value.
   */
  reset<T extends TAtomObject>(atom: Atom<T>): this;
  /**
   * Observe mutations of an atom, a computed value, or a raw state key
   * outside React. Returns an unsubscribe function.
   *
   * **`Computed` overload, server-side caveat.** A computed has no stored
   * value, so the watcher keeps the last computed result in a single `prev`
   * closure variable, created once at subscription time and shared by every
   * invocation. Request-scoped (fork) state is not: two concurrent requests
   * resolve different values for the same dependency atoms. So the
   * `prevValue` handed to the callback is "the value this watcher computed
   * last time it fired", which may well have been computed inside a
   * *different* request's fork. `value` is always correct (it is computed
   * fresh, inside the mutating context); only `prevValue` can cross request
   * boundaries.
   *
   * That is fine for `watch`'s intended use — app-level, non-React
   * observation of app-level state (React subscribes through `useComputed`,
   * which is per-component and browser-side, where there is only ever one
   * "request"). Do not build per-request logic on a computed's `prevValue`
   * on the server.
   */
  watch<T extends TAtomObject>(target: Atom<T>, callback: (value: Static<T>, prevValue: Static<T> | undefined) => void): () => void;
  watch<R>(target: Computed<R>, callback: (value: R, prevValue: R | undefined) => void): () => void;
  watch<Key extends keyof State$1>(target: Key, callback: (value: State$1[Key] | undefined, prevValue: State$1[Key] | undefined) => void): () => void;
  /**
   * Mutate a value in the state.
   */
  mut<T extends TObject>(target: Atom<T>, mutator: (current: Static<T>) => Static<T>): this;
  mut<Key extends keyof State$1>(target: Key, mutator: (current: State$1[Key] | undefined) => State$1[Key] | undefined): this;
  /**
   * Check if a key exists in the state.
   * Walks the ALS fork tree when inside a fork context.
   */
  has<Key extends keyof State$1>(key: Key): boolean;
  /**
   * Delete a key from the state (set to undefined)
   */
  del<Key extends keyof State$1>(key: Key): this;
  /**
   * Push a value to an array in the state
   */
  push<Key extends keyof OnlyArray<State$1>>(key: Key, ...value: Array<NonNullable<State$1[Key]> extends Array<infer U> ? U : never>): this;
  /**
   * Clear all state
   */
  clear(): this;
  /**
   * Get all keys that exist in the state
   */
  keys(): (keyof State$1)[];
}
type OnlyArray<T extends object> = { [K in keyof T]: NonNullable<T[K]> extends Array<any> ? K : never; };
interface SetStateOptions {
  skipContext?: boolean;
  skipEvents?: boolean;
  /**
   * Skip schema validation for this write. Internal escape hatch for
   * callers that have already validated the value (e.g. hydration).
   */
  skipValidation?: boolean;
}
//#endregion
//#region ../../src/core/Alepha.d.ts
/**
 * Core container of the Alepha framework.
 *
 * It is responsible for managing the lifecycle of services,
 * handling dependency injection,
 * and providing a unified interface for the application.
 *
 * @example
 * ```ts
 * import { Alepha, run } from "alepha";
 *
 * class MyService {
 *   // business logic here
 * }
 *
 * const alepha = Alepha.create({
 *   // state, env, and other properties
 * })
 *
 * alepha.with(MyService);
 *
 * run(alepha); // trigger .start (and .stop) automatically
 * ```
 *
 * ### Alepha Factory
 *
 * Alepha.create() is an enhanced version of new Alepha().
 * - It merges `process.env` with the provided state.env when available.
 * - It populates the test hooks for Vitest or Jest environments when available.
 *
 * new Alepha() is fine if you don't need these helpers.
 *
 * ### Platforms & Environments
 *
 * Alepha is designed to work in various environments:
 * - **Browser**: Runs in the browser, using the global `window` object.
 * - **Serverless**: Runs in serverless environments like Vercel or Vite.
 * - **Test**: Runs in test environments like Jest or Vitest.
 * - **Production**: Runs in production environments, typically with NODE_ENV set to "production".
 * * You can check the current environment using the following methods:
 *
 * - `isBrowser()`: Returns true if the App is running in a browser environment.
 * - `isServerless()`: Returns true if the App is running in a serverless environment.
 * - `isTest()`: Returns true if the App is running in a test environment.
 * - `isProduction()`: Returns true if the App is running in a production environment.
 *
 * ### State & Environment
 *
 * The state of the Alepha container is stored in the `store` property.
 * Most important property is `store.env`, which contains the environment variables.
 *
 * ```ts
 * const alepha = Alepha.create({ env: { MY_VAR: "value" } });
 *
 * // You can access the environment variables using alepha.env
 * console.log(alepha.env.MY_VAR); // "value"
 *
 * // But you should use $env() primitive to get typed values from the environment.
 * class App {
 *   env = $env(
 *     z.object({
 *  	   MY_VAR: z.text(),
 *     })
 *   );
 * }
 * ```
 *
 * ### Modules
 *
 * Modules are a way to group services together.
 * You can register a module using the `$module` primitive.
 *
 * ```ts
 * import { $module } from "alepha";
 *
 * class MyLib {}
 *
 * const myModule = $module({
 *   name: "my.project.module",
 *   services: [MyLib],
 * });
 * ```
 *
 * Do not use modules for small applications.
 *
 * ### Hooks
 *
 * Hooks are a way to run async functions from all registered providers/services.
 * You can register a hook using the `$hook` primitive.
 *
 * ```ts
 * import { $hook } from "alepha";
 *
 * class App {
 * 	 log = $logger();
 * 	 onCustomerHook = $hook({
 * 			on: "my:custom:hook",
 * 			handler: () => {
 * 		 	  this.log?.info("App is being configured");
 * 	 		},
 * 	  });
 * 	}
 *
 * Alepha.create()
 * 	 .with(App)
 * 	 .start()
 * 	 .then(alepha => alepha.events.emit("my:custom:hook"));
 * ```
 *
 * 	Hooks are fully typed. You can create your own hooks by using module augmentation:
 *
 * 	```ts
 * 	declare module "alepha" {
 * 		interface Hooks {
 * 		  "my:custom:hook": {
 * 				arg1: string;
 * 		  }
 * 		}
 * 	}
 * 	```
 *
 * 	@module alepha
 */
declare class Alepha {
  /**
   * Creates a new instance of the Alepha container with some helpers:
   *
   * - merges `process.env` with the provided state.env when available.
   * - populates the test hooks for Vitest or Jest environments when available.
   *
   * If you are not interested about these helpers, you can use the constructor directly.
   */
  static create(state?: Partial<State>): Alepha;
  /**
   * Flag indicating whether the App won't accept any further changes.
   * Pass to true when #start() is called.
   */
  protected locked: boolean;
  /**
   * True if the App has been configured.
   */
  protected configured: boolean;
  /**
   * True if the App has started.
   */
  protected started: boolean;
  /**
   * True if the App is ready.
   */
  protected ready: boolean;
  /**
   * In-flight startup promise returned by boot().
   *
   * Concurrent callers of start() share this same promise. Cleared on
   * success, failure, or stale-detection.
   */
  protected startPromise?: Promise<this>;
  /**
   * Timestamp (performance.now) when the current boot() began.
   *
   * In serverless environments (e.g. Cloudflare Workers), the runtime can
   * kill an invocation mid-startup without running cleanup. The global
   * Alepha instance persists, leaving startPromise as a never-settling
   * promise. We detect this by comparing elapsed time against STARTUP_TIMEOUT.
   */
  protected startedAt: number;
  /**
   * During the instantiation process, we keep a list of pending instantiations.
   * > It allows us to detect circular dependencies.
   */
  protected pendingInstantiations: Service[];
  /**
   * Cache for environment variables.
   * > It allows us to avoid parsing the same schema multiple times.
   */
  protected cacheEnv: Map<TSchema, any>;
  /**
   * List of modules that are registered in the container.
   *
   * Modules are used to group services and provide a way to register them in the container.
   */
  protected modules: Array<Module>;
  /**
   * List of service substitutions.
   *
   * Services registered here will be replaced by the specified service when injected.
   */
  protected substitutions: Map<Service, {
    use: Service;
  }>;
  /**
   * Registry of primitives.
   */
  protected primitiveRegistry: Map<Service<Primitive<{}>>, Primitive<{}>[]>;
  /**
   *  List of all services + how they are provided.
   */
  protected registry: Map<Service, ServiceDefinition>;
  /**
   * Node.js feature that allows to store context across asynchronous calls.
   *
   * This is used for logging, tracing, and other context-related features.
   *
   * Mocked for browser environments.
   */
  context: AlsProvider;
  /**
   * Event manager to handle lifecycle events and custom events.
   */
  events: EventManager;
  /**
   * State manager to store arbitrary values.
   */
  store: StateManager<State>;
  /**
   * Codec manager for encoding and decoding data with different formats.
   *
   * Supports multiple codec formats (JSON, Protobuf, etc.) with a unified interface.
   */
  codec: CodecManager;
  /**
   * Get logger instance.
   */
  get log(): LoggerInterface | undefined;
  /**
   * The environment variables for the App.
   */
  get env(): Readonly<Env>;
  constructor(state?: Partial<State>);
  fork<R>(callback: () => R, data?: Record<string, any>): R;
  get<R>(target: Computed<R>, scope?: StateScope): R;
  get<T extends TAtomObject>(target: Atom<T>, scope?: StateScope): Static<T>;
  get<Key extends keyof State>(target: Key, scope?: StateScope): State[Key] | undefined;
  set<T extends TAtomObject>(target: Atom<T>, value: AtomStatic<T>): this;
  set<Key extends keyof State>(target: Key, value: State[Key] | undefined): this;
  /**
   * Reset an atom back to its declared default value.
   */
  reset<T extends TAtomObject>(target: Atom<T>): this;
  /**
   * True when start() is called.
   *
   * -> No more services can be added, it's over, bye!
   */
  isLocked(): boolean;
  /**
   * Returns whether the App is configured.
   *
   * It means that Alepha#configure() has been called.
   *
   * > By default, configure() is called automatically when start() is called, but you can also call it manually.
   */
  isConfigured(): boolean;
  /**
   * Returns whether the App has started.
   *
   * It means that #start() has been called but maybe not all services are ready.
   */
  isStarted(): boolean;
  /**
   * True if the App is ready. It means that Alepha is started AND ready() hook has beed called.
   */
  isReady(): boolean;
  /**
   * True if the App is running in a Continuous Integration environment.
   */
  isCI(): boolean;
  /**
   * True if the App is running in a browser environment.
   */
  isBrowser(): boolean;
  /**
   * Returns whether the App is running in Vite dev mode.
   */
  isViteDev(): boolean;
  /**
   * Returns whether the App is running in Bun.js environment.
   */
  isBun(): boolean;
  /**
   * Returns whether the App is running in a serverless environment.
   */
  isServerless(): boolean;
  /**
   * Returns whether the App is in test mode. (Running in a test environment)
   *
   * > This is automatically set when running tests with Jest or Vitest.
   */
  isTest(): boolean;
  /**
   * Returns whether the App is in production mode. (Running in a production environment)
   *
   * > This is automatically set by Vite or Vercel. However, you have to set it manually when running Docker apps.
   */
  isProduction(): boolean;
  /**
   * Max time (ms) a boot() is allowed to run before being considered stale.
   *
   * In serverless runtimes (Cloudflare Workers, etc.) an invocation can be
   * killed mid-startup. The global Alepha instance survives, but
   * `startPromise` becomes a zombie that never settles.
   * Any new invocation that sees an older-than-STARTUP_TIMEOUT promise
   * discards it and boots fresh.
   */
  protected static readonly STARTUP_TIMEOUT = 30000;
  /**
   * Starts the App.
   *
   * - Lock any further changes to the container.
   * - Run "configure" hook for all services. Primitives will be processed.
   * - Run "start" hook for all services. Providers will connect/listen/...
   * - Run "ready" hook for all services. This is the point where the App is ready to serve requests.
   *
   * Concurrent callers share the same boot promise. If a previous boot was
   * abandoned (serverless invocation killed), the stale promise is detected
   * and a fresh boot is triggered.
   *
   * @return A promise that resolves when the App has started.
   */
  start(): Promise<this>;
  /**
   * Perform the actual startup sequence.
   *
   * Separated from start() so that start() remains a thin state-machine
   * and boot() owns the real work. The promise returned here is stored as
   * `startPromise` and shared with concurrent callers.
   */
  protected boot(): Promise<this>;
  /**
   * Reset startup state so that a fresh boot() can be attempted.
   *
   * Called when:
   * - boot() fails (error during configure/start/ready hooks)
   * - a stale startPromise is detected (serverless invocation was killed)
   */
  protected resetStartup(): void;
  /**
   * Stops the App.
   *
   * - Run "stop" hook for all services.
   *
   * Stop will NOT reset the container.
   * Stop will NOT unlock the container.
   *
   * > Stop is used to gracefully shut down the application, nothing more. There is no "restart".
   *
   * @return A promise that resolves when the App has stopped.
   */
  stop(): Promise<void>;
  /**
   * Destroys the App and clears all internal state.
   *
   * Use this for HMR in development mode to prevent duplicate class registrations.
   * Unlike stop(), this method fully resets the container state.
   *
   * @return A promise that resolves when the App has been destroyed.
   */
  destroy(): Promise<void>;
  /**
   * Check if entry is registered in the container.
   */
  has(entry: ServiceEntry, opts?: {
    /**
     * Check if the entry is registered in the pending instantiation stack.
     *
     * @default true
     */
    inStack?: boolean;
    /**
     * Check if the entry is registered in the container registry.
     *
     * @default true
     */
    inRegistry?: boolean;
    /**
     * Check if the entry is registered in the substitutions.
     *
     * @default true
     */
    inSubstitutions?: boolean;
    /**
     * Where to look for registered services.
     *
     * @default this.registry
     */
    registry?: Map<Service, ServiceDefinition>;
  }): boolean;
  /**
   * Registers the specified service in the container.
   *
   * - If the service is ALREADY registered, the method does nothing.
   * - If the service is NOT registered, a new instance is created and registered.
   *
   * Method is chainable, so you can register multiple services in a single call.
   *
   * > ServiceEntry allows to provide a service **substitution** feature.
   *
   * @example
   * ```ts
   * class A { value = "a"; }
   * class B { value = "b"; }
   * class M { a = $inject(A); }
   *
   * Alepha.create().with({ provide: A, use: B }).get(M).a.value; // "b"
   * ```
   *
   * > **Substitution** is an advanced feature that allows you to replace a service with another service.
   * > It's useful for testing or for providing different implementations of a service.
   * > If you are interested in configuring a service, use Alepha#configure() instead.
   *
   * @param serviceEntry - The service to register in the container.
   * @return Current instance of Alepha.
   */
  with<T extends object>(serviceEntry: ServiceEntry<T> | {
    default: ServiceEntry<T>;
  }): this;
  /**
   * @alias {@link Alepha#with}.
   */
  register<T extends object>(serviceEntry: ServiceEntry<T> | {
    default: ServiceEntry<T>;
  }): this;
  /**
   * Get an instance of the specified service from the container.
   *
   * @see {@link InjectOptions} for the available options.
   */
  inject<T extends object>(service: Service<T> | string, opts?: InjectOptions<T>): T;
  /**
   * Merge additional environment variables into the env store at runtime.
   *
   * Serverless entrypoints (Cloudflare Workers) receive their secrets and
   * vars on the runtime `env` binding rather than `process.env`, so they are
   * absent from `alepha.env` — which is frozen at `create()` from
   * `process.env`. Call this from the entrypoint to lift the binding's string
   * values into `alepha.env`, so `$env` and `alepha.env.*` resolve them (e.g.
   * `PUBLIC_URL`).
   *
   * Only string values are lifted; non-string bindings (D1, R2, KV, queues,
   * …) are skipped. Existing env values win, so explicit configuration is
   * never clobbered. The env cache is cleared so subsequent `$env` reads see
   * the merged values.
   */
  loadEnv(env: Record<string, unknown>): this;
  /**
   * Applies environment variables to the provided schema and state object.
   *
   * It replaces also all templated $ENV inside string values.
   *
   * @param schema - The schema object to apply environment variables to.
   * @return The schema object with environment variables applied.
   */
  parseEnv<T extends TObject>(schema: T): Static<T>;
  /**
   * Get all environment variable schemas and their parsed values.
   *
   * This is useful for DevTools to display all expected environment variables.
   */
  getEnvSchemas(): Array<{
    schema: TSchema;
    values: Record<string, any>;
  }>;
  /**
   * Dump the current dependency graph of the App.
   *
   * This method returns a record where the keys are the names of the services.
   */
  graph(): Record<string, {
    from: string[];
    as?: string[];
    module?: string;
  }>;
  dump(): AlephaDump;
  services<T extends object>(base: Service<T>): Array<T>;
  /**
   * Get all primitives of the specified type.
   */
  primitives<TPrimitive extends Primitive>(factory: {
    [KIND]: InstantiableClass<TPrimitive>;
  } | string): Array<TPrimitive>;
  protected new<T extends object>(service: Service<T>, args?: any[]): T;
  protected processPrimitive(value: Primitive, propertyKey?: string): void;
}
interface Hook<T extends keyof Hooks = any> {
  caller?: Service;
  priority?: "first" | "last";
  before?: Service[];
  after?: Service[];
  callback: (payload: Hooks[T]) => Async<void>;
}
interface AlephaDump {
  env: Record<string, AlephaDumpEnvVariable>;
  providers: Record<string, {
    from: string[];
    as?: string[];
    module?: string;
  }>;
}
interface AlephaDumpEnvVariable {
  description: string;
  default?: string;
  required?: boolean;
  enum?: Array<string>;
}
/**
 * This is how we store services in the Alepha container.
 */
interface ServiceDefinition<T extends object = any> {
  /**
   * The instance of the class or type definition.
   * Mostly used for caching / singleton but can be used for other purposes like forcing the instance.
   */
  instance: T;
  /**
   * List of classes which use this class.
   */
  parents: Array<Service | null>;
}
interface Env {
  [key: string]: string | boolean | number | undefined;
  /**
   * Optional environment variable that indicates the current environment.
   */
  NODE_ENV?: string;
  /**
   * Optional name of the application.
   */
  APP_NAME?: string;
  /**
   * Optional root module name.
   */
  MODULE_NAME?: string;
  /**
   * The secret key used for signing JWTs, encrypting cookies, and other security features.
   */
  APP_SECRET?: string;
  /**
   * Public-facing base URL of the deployed app (e.g. "https://lore.alepha.dev").
   *
   * Used to render absolute links — emails, OAuth callbacks, sitemap. On the
   * Cloudflare platform it is auto-derived from the configured production
   * domain and pushed as a Worker secret by `alepha platform up`; otherwise
   * set it explicitly in `.env.<env>`. Unset → empty, and absolute-link
   * builders fall back to relative URLs.
   */
  PUBLIC_URL?: string;
}
interface State {
  [key: string]: unknown;
  /**
   * Environment variables for the application.
   */
  env?: Readonly<Env>;
  /**
   * Logger instance to be used by the Alepha container.
   *
   * @internal
   */
  "alepha.logger"?: LoggerInterface;
  /**
   * If defined, the Alepha container will only register this service and its dependencies.
   *
   * @example
   * ```ts
   * class MigrateCmd {
   *   db = $inject(DatabaseProvider);
   *   alepha = $inject(Alepha);
   *   env = $env(
   *     z.object({
   *       MIGRATE: z.boolean().optional(),
   *     }),
   *   );
   *
   *   constructor() {
   *     if (this.env.MIGRATE) {
   *       this.alepha.set("alepha.target", MigrateCmd);
   *     }
   *   }
   *
   *   ready = $hook({
   *     on: "ready",
   *     handler: async () => {
   *       if (this.env.MIGRATE) {
   *         await this.db.migrate();
   *       }
   *     },
   *   });
   * }
   * ```
   */
  "alepha.target"?: Service;
  /**
   * Bind to Vitest 'beforeAll' hook.
   * Used for testing purposes.
   * This is automatically attached if Alepha#create() detects a test environment and global 'beforeAll' is available.
   */
  "alepha.test.beforeAll"?: (run: any) => any;
  /**
   * Bind to Vitest 'afterAll' hook.
   * Used for testing purposes.
   * This is automatically attached if Alepha#create() detects a test environment and global 'afterAll' is available.
   */
  "alepha.test.afterAll"?: (run: any) => any;
  /**
   * Bind to Vitest 'afterEach' hook.
   * Used for testing purposes.
   * This is automatically attached if Alepha#create() detects a test environment and global 'afterEach' is available.
   */
  "alepha.test.afterEach"?: (run: any) => any;
  /**
   * Bind to Vitest 'onTestFinished' hook.
   * Used for testing purposes.
   * This is automatically attached if Alepha#create() detects a test environment and global 'onTestFinished' is available.
   */
  "alepha.test.onTestFinished"?: (run: any) => any;
  /**
   * List of static assets to be copied to the output directory during the build process.
   *
   * Used for Alepha-based applications that require static assets.
   *
   * See cli/services/ViteUtils for more details.
   */
  "alepha.build.assets"?: Array<string>;
}
interface Hooks {
  /**
   * Used for testing purposes.
   */
  echo: unknown;
  /**
   * Triggered during the configuration phase. Before the start phase.
   */
  configure: Alepha;
  /**
   * Triggered during the start phase. When `Alepha#start()` is called.
   */
  start: Alepha;
  /**
   * Triggered during the ready phase. After the start phase.
   */
  ready: Alepha;
  /**
   * Triggered during the stop phase.
   *
   * - Stop should be called after a SIGINT or SIGTERM signal in order to gracefully shutdown the application. (@see `run()` method)
   *
   */
  stop: Alepha;
  /**
   * Triggered when a state value is mutated.
   */
  "state:mutate": {
    /**
     * The key of the state that was mutated.
     */
    key: keyof State;
    /**
     * The new value of the state.
     */
    value: any;
    /**
     * The previous value of the state.
     */
    prevValue: any;
  };
  /**
   * Triggered the first time an atom is registered in the state manager.
   */
  "state:register": {
    /**
     * The atom that was registered.
     */
    atom: Atom<any, any>;
  };
}
//#endregion
//#region ../../src/core/interfaces/Run.d.ts
interface RunOptions {
  /**
   * Environment variables to be used by the application.
   * It will be merged with the current process environment.
   */
  env?: Env;
  /**
   * A callback that will be executed before the application starts.
   */
  configure?: (alepha: Alepha) => Async<void>;
  /**
   * A callback that will be executed once the application is ready.
   * This is useful for initializing resources or starting background tasks.
   */
  ready?: (alepha: Alepha) => Async<void>;
  /**
   * If true, the application will .stop() after the ready callback is executed.
   * Useful for one-time tasks!
   */
  once?: boolean;
}
//#endregion
//#region ../../src/core/constants/OPTIONS.d.ts
/**
 * Used for primitives options.
 *
 * @internal
 */
declare const OPTIONS: unique symbol;
//#endregion
//#region ../../src/core/errors/AlephaError.d.ts
/**
 * Default error class for Alepha.
 */
declare class AlephaError extends Error {
  name: string;
}
//#endregion
//#region ../../src/core/errors/AppNotStartedError.d.ts
declare class AppNotStartedError extends AlephaError {
  readonly name = "AppNotStartedError";
  constructor();
}
//#endregion
//#region ../../src/core/errors/CircularDependencyError.d.ts
declare class CircularDependencyError extends AlephaError {
  readonly name = "CircularDependencyError";
  constructor(provider: string, parents?: string[]);
}
//#endregion
//#region ../../src/core/errors/ContainerLockedError.d.ts
declare class ContainerLockedError extends AlephaError {
  readonly name = "ContainerLockedError";
  constructor(message?: string);
}
//#endregion
//#region ../../src/core/errors/TooLateSubstitutionError.d.ts
declare class TooLateSubstitutionError extends AlephaError {
  readonly name = "TooLateSubstitutionError";
  constructor(original: string, substitution: string);
}
//#endregion
//#region ../../src/core/errors/TypeBoxError.d.ts
/** Minimal validation-error shape (decoupled from any schema lib). */
interface ValidationErrorLike {
  message: string;
  instancePath?: string;
  params?: unknown;
}
declare class TypeBoxError extends AlephaError {
  name: string;
  readonly cause: ValidationErrorLike;
  readonly value: {
    path: string;
    message: string;
  };
  constructor(error: ValidationErrorLike);
}
interface TypeBoxErrorParams {
  requiredProperties?: string[];
}
//#endregion
//#region ../../src/core/helpers/coerceStrings.d.ts
/**
 * Coerce a single string value coming from a string-only boundary (HTTP query,
 * HTTP headers, environment variables) to the JS type its schema declares.
 *
 * This is the zod-standard `z.coerce` behavior applied only at the edges where
 * inputs are inherently strings — request bodies and the ORM stay strict. A
 * value that cannot be coerced is returned unchanged so the subsequent
 * validation produces a proper rejection. Arrays coerce element-wise.
 */
declare const coerceScalar: (schema: unknown, value: unknown) => unknown;
/**
 * Coerce each declared field of an object against its object schema. Used to
 * normalize string-only boundary maps (env vars, query objects) before strict
 * validation. Undeclared keys are passed through untouched.
 */
declare const coerceObject: (schema: unknown, value: Record<string, unknown>) => Record<string, unknown>;
//#endregion
//#region ../../src/core/schemas/pageSchema.d.ts
declare const pageMetadataSchema: import("zod").ZodObject<{
  number: import("zod").ZodInt;
  size: import("zod").ZodInt;
  offset: import("zod").ZodInt;
  numberOfElements: import("zod").ZodInt;
  totalElements: import("zod").ZodOptional<import("zod").ZodInt>;
  totalPages: import("zod").ZodOptional<import("zod").ZodInt>;
  isEmpty: import("zod").ZodBoolean;
  isFirst: import("zod").ZodBoolean;
  isLast: import("zod").ZodBoolean;
  sort: import("zod").ZodOptional<import("zod").ZodObject<{
    sorted: import("zod").ZodBoolean;
    fields: import("zod").ZodArray<import("zod").ZodObject<{
      field: import("zod").ZodString;
      direction: import("zod").ZodEnum<{
        asc: "asc";
        desc: "desc";
      }>;
    }, import("zod/v4/core").$strip>>;
  }, import("zod/v4/core").$strip>>;
}, import("zod/v4/core").$strip>;
/**
 * Create a pagination schema for the given object schema.
 *
 * Provides a standardized pagination response format compatible with Spring Data's Page interface.
 * This schema can be used across any data source (databases, APIs, caches, etc.).
 *
 * @example
 * ```ts
 * const userSchema = z.object({ id: z.integer(), name: z.text() });
 * const userPageSchema = pageSchema(userSchema);
 * ```
 *
 * @example In an API endpoint
 * ```ts
 * $action({
 *   output: pageSchema(UserSchema),
 *   handler: async () => {
 *     return await userRepo.paginate();
 *   }
 * })
 * ```
 */
declare const pageSchema: <T extends TObject | TRecord>(objectSchema: T) => TPage<T>;
type TPage<T extends TObject | TRecord> = TObject<{
  content: TArray<T>;
  page: typeof pageMetadataSchema;
}>;
/**
 * Opinionated type definition for a paginated response.
 *
 * Inspired by Spring Data's Page interface with all essential pagination metadata.
 * This generic type can be used with any data source.
 *
 * @example
 * ```ts
 * const page: Page<User> = {
 *   content: [user1, user2, ...],
 *   page: {
 *     number: 0,
 *     size: 10,
 *     offset: 0,
 *     numberOfElements: 10,
 *     totalElements: 1200,
 *     totalPages: 120,
 *     isEmpty: false,
 *     isFirst: true,
 *     isLast: false,
 *     sort: {
 *       sorted: true,
 *       fields: [
 *         { field: "name", direction: "asc" }
 *       ]
 *     }
 *   }
 * }
 * ```
 */
type Page<T> = {
  /**
   * Array of items on the current page.
   */
  content: T[];
  page: Static<typeof pageMetadataSchema>;
};
type PageMetadata = Static<typeof pageMetadataSchema>;
declare module "alepha" {
  interface TypeProvider {
    /**
     * Create a schema for a paginated response.
     */
    page<T extends TObject | TRecord>(itemSchema: T): TPage<T>;
  }
}
//#endregion
//#region ../../src/core/helpers/createPagination.d.ts
/**
 * Create a pagination object from an array of entities.
 *
 * This is a pure function that works with any data source (databases, APIs, caches, arrays, etc.).
 * It handles the core pagination logic including:
 * - Slicing the content to the requested page size
 * - Calculating pagination metadata (offset, page number, etc.)
 * - Determining navigation state (isFirst, isLast)
 * - Including sort metadata when provided
 *
 * @param entities - The entities to paginate (should include one extra item to detect if there's a next page)
 * @param limit - The limit of the pagination (page size)
 * @param offset - The offset of the pagination (starting position)
 * @param sort - Optional sort metadata to include in response
 * @returns A complete Page object with content and metadata
 *
 * @example Basic pagination
 * ```ts
 * const users = await fetchUsers({ limit: 11, offset: 0 }); // Fetch limit + 1
 * const page = createPagination(users, 10, 0);
 * // page.content has max 10 items
 * // page.page.isLast tells us if there are more pages
 * ```
 *
 * @example With sorting
 * ```ts
 * const page = createPagination(
 *   entities,
 *   10,
 *   0,
 *   [{ column: "name", direction: "asc" }]
 * );
 * ```
 *
 * @example In a custom service
 * ```ts
 * class MyService {
 *   async listItems(page: number, size: number) {
 *     const items = await this.fetchItems({ limit: size + 1, offset: page * size });
 *     return createPagination(items, size, page * size);
 *   }
 * }
 * ```
 */
declare function createPagination<T>(entities: T[], limit?: number, offset?: number, sort?: Array<{
  column: string;
  direction: "asc" | "desc";
}>): Page<T>;
//#endregion
//#region ../../src/core/helpers/jsonSchemaToZod.d.ts
/**
 * Convert a JSON Schema object into a zod schema (the inverse of
 * `z.toJSONSchema`). zod 4 has no native `fromJSONSchema`, so this provides the
 * round-trip needed by dynamic, schema-driven UIs (e.g. devtools forms built
 * from an entity's or action's published JSON Schema).
 *
 * Covers the JSON Schema subset Alepha emits: object/array/string (+formats),
 * number/integer, boolean, null, enum, and `anyOf`/`oneOf` (including the
 * nullable `anyOf: [..., { type: "null" }]` shape). Anything unrecognized falls
 * back to `z.any()`.
 */
declare const jsonSchemaToZod: (schema: any) => ZType;
//#endregion
//#region ../../src/core/helpers/ref.d.ts
/**
 * Store the current context and definition during injection phase.
 *
 * @internal
 */
declare const __alephaRef: {
  alepha?: Alepha;
  service?: Service & {
    [MODULE]?: Service;
  };
  parent?: Service;
};
/**
 * Note:
 *
 * This file is used to share context between $primitives and the Alepha core during the injection phase.
 *
 * There is no side effect as long as Alepha is not used concurrently in multiple contexts (which is not the case).
 *
 * // __alephaRef === undefined
 * // begin alepha.with()
 * //   __alephaRef.context = alepha
 * //   ... injection phase ...
 * //   __alephaRef.context = undefined
 * // end alepha.with()
 * // __alephaRef === undefined
 *
 * As .with() is synchronous, there is no risk of context leakage.
 *
 * ---------------------------------------------------------------------------------------------------------------------
 *
 * Why this helper?
 *
 * It allows to avoid passing Alepha instance to every $hook, $inject, etc. calls. It's a beautiful syntactic sugar.
 *
 * With sugar:
 *
 * class A {
 *   on = $hook( ... ) // <- __alephaRef is set here
 * }
 *
 * Without sugar:
 *
 * class A {
 *   constructor(alepha: Alepha) {
 *     this.on = $hook(alepha, ... ) // <- no need of __alephaRef
 *   }
 * }
 *
 * One main goal of Alepha is working with classes but without the class verbosity.
 * Forcing to pass Alepha instance in constructors would be a step back in that direction!
 *
 * ---------------------------------------------------------------------------------------------------------------------
 *
 * TODO: harden the cursor against mid-instantiation throws.
 *
 * Today, the cleanup of `__alephaRef.alepha`, `__alephaRef.service`, `__alephaRef.parent`
 * is performed by the caller after the synchronous instantiation returns. If the
 * instantiation throws (e.g., a primitive factory blows up, or a user constructor
 * raises), the cursor can be left holding stale references until the next
 * instantiation overwrites them. In practice this is harmless because Alepha is
 * single-threaded synchronous during boot and the next inject() rewrites the
 * cursor — but it is a sharp edge for debuggers (frame inspection shows ghost
 * state) and any future tooling that introspects __alephaRef out-of-band.
 *
 * Plan: wrap each cursor mutation in Alepha.ts in a try/finally that snapshots
 * the previous value and restores it on exit (even on throw). Equivalent to a
 * lexically-scoped "with" — pushes/pops cleanly. Should be a 5-line refactor in
 * Alepha.ts:1131-1132 once we touch it.
 */
//#endregion
//#region ../../src/core/interfaces/Pagination.d.ts
/**
 * Generic pagination request parameters.
 *
 * This interface defines the common structure for pagination queries
 * across all data sources. Individual packages can extend or adapt this
 * interface for their specific needs.
 *
 * @example Basic usage
 * ```ts
 * const query: PageRequest = {
 *   page: 0,
 *   size: 20
 * };
 * ```
 *
 * @example With all parameters
 * ```ts
 * const query: PageRequest = {
 *   page: 2,
 *   size: 50
 * };
 * ```
 */
interface PageRequest {
  /**
   * The page number to retrieve (0-indexed).
   * @default 0
   */
  page?: number;
  /**
   * The number of items per page.
   * @default 10
   */
  size?: number;
}
/**
 * Sort direction for ordering results.
 */
type SortDirection = "asc" | "desc";
/**
 * Sort field specification.
 */
interface SortField {
  /**
   * The field/column name to sort by.
   */
  field: string;
  /**
   * The sort direction.
   * @default "asc"
   */
  direction: SortDirection;
}
//#endregion
//#region ../../src/core/primitives/$context.d.ts
/**
 * Get Alepha instance and current service from the current context.
 *
 * It can only be used inside $primitive functions.
 *
 * ```ts
 * import { $context } from "alepha";
 *
 * const $hello = () => {
 *   const { alepha, service, module } = $context();
 *
 *   // alepha - alepha instance
 *   // service - class which is creating this primitive, this is NOT the instance but the service definition
 *   // module - module definition, if any
 *
 *   return {};
 * }
 *
 * class MyService {
 *   hello = $hello();
 * }
 *
 * const alepha = new Alepha().with(MyService);
 * ```
 *
 * @internal
 */
declare const $context: () => ContextPrimitive;
interface ContextPrimitive {
  /**
   * Alepha instance.
   */
  alepha: Alepha;
  /**
   * Service definition which is creating this primitive.
   * This is NOT the instance but the service definition.
   */
  service?: Service;
  /**
   * Module definition, if any.
   */
  module?: Service;
}
//#endregion
//#region ../../src/core/primitives/$env.d.ts
/**
 * Get typed values from environment variables.
 *
 * @example
 * ```ts
 * const alepha = Alepha.create({
 *   env: {
 *     // Alepha.create() will also use process.env when running on Node.js
 *     HELLO: "world",
 *   }
 * });
 *
 * class App {
 *   log = $logger();
 *
 *   // program expect a var env "HELLO" as string to works
 *   env = $env(z.object({
 *     HELLO: z.text()
 *   }));
 *
 *   sayHello = () => this.log.info("Hello ${this.env.HELLO}")
 * }
 *
 * run(alepha.with(App));
 * ```
 */
declare const $env: <T extends TObject>(type: T) => Static<T>;
//#endregion
//#region ../../src/core/primitives/$hook.d.ts
/**
 * Registers a new hook.
 *
 * ```ts
 * import { $hook } from "alepha";
 *
 * class MyProvider {
 *   onStart = $hook({
 *     name: "start", // or "configure", "ready", "stop", ...
 *     handler: async (app) => {
 *       // await db.connect(); ...
 *     }
 *   });
 * }
 * ```
 *
 * Hooks are used to run async functions from all registered providers/services.
 *
 * You can't register a hook after the App has started.
 *
 * It's used under the hood by the `configure`, `start`, and `stop` methods.
 * Some modules also use hooks to run their own logic. (e.g. `alepha/server`).
 *
 * You can create your own hooks by using module augmentation:
 *
 * ```ts
 * declare module "alepha" {
 *
 *   interface Hooks {
 *     "my:custom:hook": {
 *       arg1: string;
 *     }
 *   }
 * }
 *
 * await alepha.events.emit("my:custom:hook", { arg1: "value" });
 * ```
 *
 */
declare const $hook: {
  <T extends keyof Hooks>(options: HookOptions<T>): HookPrimitive<T>;
  [KIND]: typeof HookPrimitive;
};
interface HookOptions<T extends keyof Hooks> {
  /**
   * The name of the hook. "configure", "start", "ready", "stop", ...
   */
  on: T;
  /**
   * The handler to run when the hook is triggered.
   */
  handler: (args: Hooks[T]) => Async<any>;
  /**
   * Force the hook to run first or last on the list of hooks.
   */
  priority?: "first" | "last";
  /**
   * Run this hook before the hooks owned by the specified services.
   */
  before?: object | Array<object>;
  /**
   * Run this hook after the hooks owned by the specified services.
   */
  after?: object | Array<object>;
}
declare class HookPrimitive<T extends keyof Hooks> extends Primitive<HookOptions<T>> {
  called: number;
  protected onInit(): void;
}
//#endregion
//#region ../../src/core/primitives/$memoize.d.ts
/**
 * Lightweight in-process memoization middleware.
 *
 * Caches handler results in a plain `Map` — no external store, no serialization,
 * no provider dependency. Process-local only. Entries live until eviction by capacity.
 *
 * ```typescript
 * class Api {
 *   getStats = $action({
 *     use: [$memoize({ max: 100 })],
 *     handler: async () => this.repo.aggregate(),
 *   });
 * }
 * ```
 *
 * > For more advanced caching, use `$cache` from "alepha/cache" instead — it supports TTL, invalidation, external stores (Redis).
 */
declare const $memoize: (options?: MemoizeOptions) => Middleware$1;
interface MemoizeOptions {
  /**
   * Maximum number of entries to keep in the cache.
   * When exceeded, the oldest entry is evicted (FIFO).
   *
   * @default 1000
   */
  max?: number;
  /**
   * Custom key function. Receives the handler's arguments.
   * By default, `JSON.stringify(args)` is used.
   */
  key?: (...args: any[]) => string;
}
//#endregion
//#region ../../src/core/primitives/$mode.d.ts
interface ModeOptions {
  /**
   * Environment variable to check for.
   *
   * The mode activates when:
   * - The env variable is truthy (e.g. `MIGRATE=true`), OR
   * - The `MODE` env equals this value (e.g. `MODE=MIGRATE`)
   *
   * @example "MIGRATE"
   * @example "SEED"
   * @example "CONSOLE"
   */
  env: string;
  /**
   * Callback to execute when the mode is activated and the app is ready.
   *
   * After the callback completes (or throws), `alepha.stop()` is called automatically
   * to ensure graceful shutdown (close DB connections, etc.).
   *
   * If omitted, the mode activates (graph is pruned) but the process stays alive.
   * Useful for long-running modes like queue workers or cron.
   */
  ready?: (alepha: Alepha) => void | Promise<void>;
}
/**
 * Activate a selective bootstrap mode.
 *
 * When the environment condition matches, the owning class becomes `alepha.target`:
 * the DI graph is pruned to only this class and its transitive dependencies.
 * Everything else (HTTP server, job scheduler, etc.) is discarded.
 *
 * Returns `true` if the mode is active, `false` otherwise.
 *
 * @example
 * ```ts
 * import { $mode, $inject } from "alepha";
 * import { DatabaseProvider } from "alepha/orm";
 *
 * class DbMigrationMode {
 *   db = $inject(DatabaseProvider);
 *
 *   mode = $mode({
 *     env: "MIGRATE",
 *     ready: async () => {
 *       await this.db.migrate();
 *     },
 *   });
 * }
 * ```
 *
 * ```bash
 * MIGRATE=true node app.js    # runs migrations, then exits
 * MODE=MIGRATE node app.js    # same effect
 * ```
 */
declare const $mode: (args: ModeOptions) => boolean;
//#endregion
//#region ../../src/core/primitives/$pipeline.d.ts
/**
 * Creates a pipeline primitive that composes middleware with a handler.
 *
 * It makes a big function which runs all functions (middleware) inside `use` array before and after the `handler` function.
 * The middleware functions are applied in the order they are defined in the `use` array.
 *
 * So PipelinePrimitive is also a base for primitives with `handler` which need some sort of plugins.
 *
 * Use `$pipeline` for standalone composition outside host primitives (`$action`, `$job`, `$page`).
 * Host primitives extend `PipelinePrimitive` directly to get middleware support.
 *
 * ```ts
 * class OrderService {
 *   processOrder = $pipeline({
 *     use: [$lock({ name: "process-order" }), $retry({ max: 3 })],
 *     handler: async (orderId: string) => {
 *       return await this.orders.updateById(orderId, { status: "paid" });
 *     },
 *   });
 * }
 * ```
 */
declare function $pipeline<T extends (...args: any[]) => any>(options: PipelineOptions<T>): PipelinePrimitiveFn<T>;
declare class PipelinePrimitive<TOptions extends PipelinePrimitiveOptions = PipelinePrimitiveOptions> extends Primitive<TOptions> {
  readonly handler: PipelineHandler;
  get middlewares(): MiddlewareMetadata[];
  /**
   * Execute the wrapped handler.
   */
  run(...args: any[]): any;
}
interface MiddlewareMetadata {
  name: string;
  options?: Record<string, unknown>;
}
type Middleware = (<T extends (...args: any[]) => any>(handler: T) => T) & {
  [OPTIONS]?: MiddlewareMetadata;
};
interface PipelinePrimitiveOptions<THandler extends (...args: any[]) => any = (...args: any[]) => any> {
  use?: Middleware[];
  handler: THandler;
}
interface PipelineOptions<T extends (...args: any[]) => any = (...args: any[]) => any> {
  use: Middleware[];
  handler: T;
}
interface CreateMiddlewareOptions {
  name: string;
  options?: any;
  handler: (context: {
    alepha: Alepha;
    next: (...args: any[]) => any;
  }) => (...args: any[]) => any;
}
/**
 * Internal class that composes middleware and the handler function.
 * This is required when adding more middleware dynamically. See `$middleware()`.
 */
declare class PipelineHandler {
  protected fn: (...args: any[]) => any;
  protected middlewares: Middleware[];
  constructor(fn: (...args: any[]) => any, middlewares?: Middleware[]);
  protected wrapped?: (...args: any[]) => any;
  use(...middleware: Middleware[]): void;
  run(...args: any[]): any;
}
interface PipelinePrimitiveFn<T extends (...args: any[]) => any = (...args: any[]) => any> extends PipelinePrimitive<PipelineOptions<T>> {
  (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;
}
/**
 * Creates a middleware with automatic `$context()` resolution, type handling, and metadata.
 *
 * Eliminates the boilerplate of calling `$context()`, casting types, and attaching
 * `MiddlewareMetadata`. The handler receives `{ alepha, next }` and returns the
 * wrapped function directly.
 *
 * ```typescript
 * export const $logElastic = (options?: LogOptions): Middleware => {
 *   return createMiddleware({
 *     name: "$logElastic",
 *     options,
 *     handler: ({ alepha, next }) => {
 *       const elastic = alepha.inject(ElasticProvider);
 *       return async (...args) => {
 *         const result = await next(...args);
 *         elastic.push({ ... }).catch(() => {});
 *         return result;
 *       };
 *     },
 *   });
 * };
 * ```
 */
declare const createMiddleware: (config: CreateMiddlewareOptions) => Middleware;
//#endregion
//#region ../../src/core/primitives/$scope.d.ts
/**
 * Middleware that wraps the handler in an ALS (AsyncLocalStorage) context.
 *
 * Gives the handler its own isolated scope — `alepha.context.get()` / `.set()` are scoped
 * to this execution. Useful for `$pipeline` where no host primitive provides a scope.
 *
 * Host primitives (`$action`, `$job`, `$page`) include `$scope` by default.
 * Adding `$scope()` to their `use` array will throw — you're already in a scope.
 *
 * ```typescript
 * class OrderService {
 *   processOrder = $pipeline({
 *     use: [$scope(), $retry({ max: 3 })],
 *     handler: async (orderId: string) => {
 *       // alepha.context.set/get are scoped here
 *       return await this.orders.updateById(orderId, { status: "paid" });
 *     },
 *   });
 * }
 * ```
 */
declare const $scope: () => Middleware;
//#endregion
//#region ../../src/core/primitives/$state.d.ts
/**
 * Subscribes to an atom's state and returns its current value for use in components.
 *
 * Creates a reactive connection between an atom and a component, automatically registering
 * the atom in the application state if not already registered. The returned value is reactive
 * and will update when the atom's state changes.
 *
 * **Use Cases**: Accessing global state, sharing data between components, reactive UI updates
 *
 * @example
 * ```ts
 * const userState = $atom({ schema: z.object({ name: z.text(), role: z.text() }) });
 *
 * class UserComponent {
 *   user = $state(userState); // Reactive reference to atom state
 *
 *   render() {
 *     return <div>Hello {this.user.name}!</div>;
 *   }
 * }
 * ```
 */
declare const $state: <T extends TAtomObject, N extends string>(atom: Atom<T, N>) => Readonly<Static<T>>;
//#endregion
//#region ../../src/core/schemas/pageQuerySchema.d.ts
declare const pageQuerySchema: import("zod").ZodObject<{
  page: import("zod").ZodOptional<import("zod").ZodDefault<import("zod").ZodInt>>;
  size: import("zod").ZodOptional<import("zod").ZodDefault<import("zod").ZodInt>>;
  sort: import("zod").ZodOptional<import("zod").ZodString>;
}, import("zod/v4/core").$strip>;
type PageQuery = Static<typeof pageQuerySchema>;
//#endregion
//#region ../../src/core/index.d.ts
/**
 * Foundation of the entire framework with dependency injection and lifecycle management.
 *
 * **Features:**
 * - Dependency injection for services
 * - Service substitution/mocking
 * - Type-safe environment variable loading with TypeBox schemas
 * - Lifecycle hooks (start, stop, log, etc.)
 * - Module definitions and composition
 * - Request-scoped context access via Async Local Storage (ALS)
 * - Reactive state management with atoms
 * - Full TypeScript generics and type inference
 *
 * @module alepha.core
 */
declare const AlephaCore: Service<import("alepha").Module>;
/**
 * Run Alepha application, trigger start lifecycle.
 *
 * ```ts
 * import { Alepha, run } from "alepha";
 * import { MyService } from "./services/MyService.ts";
 *
 * const alepha = new Alepha({ env: { APP_NAME: "MyAlephaApp" } });
 *
 * alepha.with(MyService);
 *
 * export default run(alepha);
 * ```
 */
declare const run: (entry: Alepha | Service | Array<Service>, opts?: RunOptions) => Alepha;
//#endregion
export { $atom, $computed, $context, $env, $hook, $inject, $memoize, $mode, $module, $pipeline, $scope, $state, ALS_PARENT, AbstractClass, Alepha, AlephaCore, AlephaDump, AlephaDumpEnvVariable, AlephaError, AlsProvider, AnyDep, AppNotStartedError, Async, AsyncFn, AsyncLocalStorageData, Atom, AtomOptions, AtomPersist, AtomStatic, AtomWithValue, CircularDependencyError, CodecManager, CodecRegisterOptions, CompileOptions, CompiledEventExecutor, Computed, ComputedOptions, ContainerLockedError, ContextPrimitive, CreateMiddlewareOptions, DecodeOptions, DepValues, EncodeOptions, EncodeResult, Encoding, Env, EventManager, FileLike, Hook, HookOptions, HookPrimitive, Hooks, Infer, InjectOptions, InjectPrimitive, InstantiableClass, Json, JsonSchemaCodec, KIND, KeylessCodec, KeylessCodecOptions, KeylessJsonSchemaCodec, LogLevel, LoggerInterface, MaybePromise, MemoizeOptions, Middleware, MiddlewareMetadata, ModeOptions, Module, ModulePrimitiveOptions, NumberOptions, OPTIONS, Page, PageMetadata, PageQuery, PageRequest, PipelineHandler, PipelineOptions, PipelinePrimitive, PipelinePrimitiveFn, PipelinePrimitiveOptions, Primitive, PrimitiveArgs, PrimitiveConfig, PrimitiveFactoryLike, RunFunction, SchemaCodec, SchemaOptions, SchemaOutput, SchemaValidator, Service, ServiceEntry, ServiceSubstitution, SetStateOptions, SortDirection, SortField, State, StateManager, StateScope, Static, StaticDecode, StaticEncode, StreamLike, StringOptions, TAny, TArray, TArrayOptions, TAtomObject, TBigInt, TBoolean, TEnumOptions, TFile, TInteger, TInterface, TKeysToIndexer, TNull, TNumber, TNumberOptions, TObject, TObjectOptions, TOmit, TOptional, TOptionalAdd, TPage, TPartial, TPick, TProperties, TRecord, TSchema, TSchemaOptions, TStream, TString, TStringOptions, TTextOptions, TTuple, TUnion, TUnsafe, TVoid, TextLength, TextOptions, TooLateSubstitutionError, Type, TypeBoxError, TypeBoxErrorParams, TypeProvider, ValidateOptions, ValidationErrorLike, WithModule, Z, ZObject, ZType, Z_LIMITS, __alephaRef, coerceObject, coerceScalar, createMiddleware, createPagination, createPrimitive, isClass, isFileLike, isTypeFile, jsonSchemaToZod, pageMetadataSchema, pageQuerySchema, pageSchema, run, z };
//# sourceMappingURL=index.d.ts.map