//#region src/standardSchema.d.ts
/**
 * Minimal vendored Standard Schema v1 types.
 * Vendoring keeps schema integration type-only and avoids a runtime dependency.
 *
 * @see https://standardschema.dev
 */
interface StandardSchemaV1<Input = unknown, Output = Input> {
  readonly "~standard": StandardSchemaV1.Props<Input, Output>;
}
declare namespace StandardSchemaV1 {
  interface Props<Input = unknown, Output = Input> {
    readonly version: 1;
    readonly vendor: string;
    readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
    readonly types?: Types<Input, Output> | undefined;
  }
  type Result<Output> = SuccessResult<Output> | FailureResult;
  interface SuccessResult<Output> {
    readonly value: Output;
    readonly issues?: undefined;
  }
  interface FailureResult {
    readonly issues: ReadonlyArray<Issue>;
  }
  interface Issue {
    readonly message: string;
    readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
  }
  interface PathSegment {
    readonly key: PropertyKey;
  }
  interface Types<Input = unknown, Output = Input> {
    readonly input: Input;
    readonly output: Output;
  }
  type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
  type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
}
//#endregion
//#region src/validators.d.ts
/** Unifies schema libraries and parser functions behind one validation contract. */
type Validator<Output> = StandardSchemaV1<unknown, Output> | ((input: unknown) => Output);
/** Preserves a validator's pre-transform payload type in generic APIs. */
type InferValidatorInput<V> = V extends StandardSchemaV1<infer I, unknown> ? I : V extends ((input: infer I) => unknown) ? I : never;
/** Preserves a validator's post-transform payload type in generic APIs. */
type InferValidatorOutput<V> = V extends StandardSchemaV1<unknown, infer O> ? O : V extends ((input: never) => infer O) ? O : never;
/** Schema/parser **input** for validated `open` / {@link ValidatedLayerHandle}. */
type OpenValidatePayload<V extends Validator<unknown>> = V extends StandardSchemaV1 ? StandardSchemaV1.InferInput<V> : InferValidatorInput<V>;
//#endregion
//#region src/types.d.ts
/**
 * Logical identity for a layer (`find` / `upsert` / `gcTime`).
 *
 * Must be JSON-safe: `string` | `boolean` | `null` | finite `number`, or
 * plain objects / arrays of those. Compared via sorted `JSON.stringify` —
 * two keys with the same values in a different object-property order are equal.
 * Invalid keys throw `LayerKeyError` from any path that hashes the key
 * (`hashKey`, `open`, `find`, `cancelQueued`, `createLayer`).
 */
type LayerKey = ReadonlyArray<unknown>;
type LayerPhase = "pending" | "queued" | "active" | "dismissed" | "error";
/** Animation state, independent of resolution phase. */
type LayerTransition = "entering" | "settled" | "exiting";
type LayerActionStatus = "idle" | "running";
/** Instance-scoped predicate — `true` allows dismissal. */
type BlockerFn = () => boolean | Promise<boolean>;
/** Stack-scoped predicate — `true` allows dismissal. */
type StackBlockerFn = (layer: LayerState) => boolean | Promise<boolean>;
/**
 * How {@link LayerStack#dismissAll} treats blockers. All modes still
 * **resolve** `open()` with the dismiss response — unlike {@link LayerStack#cancelAll},
 * which rejects with {@link LayerCancelledError}.
 *
 * - `skipBlocked` — soft-dismiss each layer; leave blocked ones
 * - `stopAtBlocked` — soft-dismiss until the first veto, then stop
 * - `force` — bypass blockers; still completes with the response
 */
type DismissAllMode = "skipBlocked" | "stopAtBlocked" | "force";
interface DismissOptions {
  force?: boolean;
}
interface DismissAllOptions {
  mode?: DismissAllMode;
}
/** Immutable layer snapshot consumed by selectors. */
interface LayerState<P = unknown, R = void, E = DefaultLayerError, D = unknown> {
  id: string;
  key: LayerKey;
  payload: P;
  data?: D;
  response?: R;
  error?: E;
  phase: LayerPhase;
  transition: LayerTransition;
  /** `true` while a user-intent dismiss is consulting blockers. */
  dismissing: boolean;
  actionStatus: LayerActionStatus;
  ended: boolean;
  index: number;
  stackSize: number;
}
/** Imperative controls available to a rendered layer. */
interface LayerCallContext<P, R, RootProps = unknown> {
  end: (response: R, opts?: DismissOptions) => Promise<boolean>;
  dismiss: (response: R, opts?: DismissOptions) => Promise<boolean>;
  addBlocker: (fn: BlockerFn) => () => void;
  update: (patch: Partial<P>) => void;
  setRunning: (running: boolean) => void;
  /** Finishes the current transition immediately. */
  settle: () => void;
  ended: boolean;
  index: number;
  stackSize: number;
  root: RootProps;
  readonly stackId: string;
  readonly layerId: string;
}
interface LayerComponentProps<P = unknown, R = void, E = DefaultLayerError, D = unknown, RootProps = unknown> {
  call: LayerCallContext<P, R, RootProps>;
  payload: P;
  data?: D;
  error?: E;
  phase: LayerPhase;
  transition: LayerTransition;
  dismissing: boolean;
  actionStatus: LayerActionStatus;
}
/** Framework adapters narrow this to their component type. */
type LayerComponent = unknown;
interface LayerOptions<P = unknown, R = void, E = DefaultLayerError, D = unknown, RootProps = unknown> {
  /** @default "default" */
  stack?: string;
  /** Stable identity; same key + `upsert` → update existing instance. */
  key: LayerKey;
  component?: LayerComponent;
  /** Enter duration in milliseconds; `call.settle()` finishes it early. @default 0 */
  enteringDelay?: number;
  /** Exit duration in milliseconds; `call.settle()` finishes it early. @default 0 */
  exitingDelay?: number;
  /** When true, reusing an active key updates its payload instead of stacking. */
  upsert?: boolean;
  /** Loads data before activation; dismissal aborts the signal. */
  loadFn?: (ctx: {
    payload: P;
    signal: AbortSignal;
  }) => Promise<D> | D;
  /** Validates payload before opening; the parsed output becomes the payload. */
  validate?: Validator<P>;
  /** Props passed to every layer in the stack via `call.root`. */
  rootProps?: RootProps;
}
/**
 * Makes `payload` optional only when `P` admits `undefined`.
 * Optional object properties alone do not make the payload omittable.
 */
type PayloadArg<P> = undefined extends P ? {
  payload?: P;
} : {
  payload: P;
};
type OpenLayerOptions<P = unknown, R = void, E = DefaultLayerError, D = unknown, RootProps = unknown> = LayerOptions<P, R, E, D, RootProps> & PayloadArg<P>;
/** Rejects keys that do not exist on `T`. */
type OmitKeyof<T, K extends keyof T> = Omit<T, K>;
/** Serial policy when a mounted layer's `loadFn` rejects. */
type SerialOnLoadError = "block" | "advance";
interface StackOptions {
  /**
   * Serial scope queues unmounted opens until the occupying layer leaves
   * (`pending` / `active` / `error` for `onLoadError: "block"`).
   * @default { strategy: "parallel" }
   */
  scope?: {
    strategy: "serial" | "parallel";
    /**
     * Serial only. `block` — keep `phase: "error"` until dismiss.
     * `advance` — remove the failed layer and drain the next queued open.
     * @default "block"
     */
    onLoadError?: SerialOnLoadError;
  };
  /** Retains loaded data for same-key restoration. @default 0 */
  gcTime?: number;
  /** @default "skipBlocked" */
  dismissAllMode?: DismissAllMode;
}
type StackDefaults = Record<string, StackOptions>;
interface LayerClientOptions {
  defaultStackOptions?: StackDefaults;
}
/**
 * Coarse mutation label for devtools / {@link LayerClient#subscribeNotify}.
 * `dismissAll` = bulk completion; `cancelAll` = teardown that rejects `open()`.
 */
type StackNotifyAction = "register" | "open" | "queue" | "update" | "setRunning" | "settle" | "dismiss" | "dismissVetoed" | "dismissAll" | "cancelAll" | "cancelQueued" | "phase" | "remove";
/** JSON-safe layer projection on {@link StackNotifyEvent}. */
interface LayerNotifyView {
  id: string;
  /** Display string from {@link keySignature}. */
  key: string;
  phase: LayerPhase;
  transition: LayerTransition;
  actionStatus: LayerActionStatus;
  dismissing: boolean;
  ended: boolean;
  index: number;
  stackSize: number;
  payload?: unknown;
  /** `true` when `payload` could not be JSON-cloned and was omitted. */
  payloadTruncated?: boolean;
}
/** Emitted when a stack snapshot changes after a labeled mutation. */
interface StackNotifyEvent {
  stackId: string;
  seq: number;
  ts: number;
  action: StackNotifyAction;
  active: LayerNotifyView[];
  queued: LayerNotifyView[];
}
/**
 * Module-augmentation point for app-wide type defaults.
 * Augment `defaultError` to set the library-wide error type once.
 *
 * @example
 * declare module "@stainless-code/layers" {
 *   interface Register { defaultError: AppError }
 * }
 */
interface Register {}
/** App-wide error type configured through {@link Register}. */
type DefaultLayerError = Register extends {
  defaultError: infer E;
} ? E : Error;
//#endregion
//#region src/utils.d.ts
/**
 * Ensures a layer key is JSON-safe for {@link hashKey}.
 * Allowed: `string` | `boolean` | `null` | finite `number` | plain objects | arrays of those.
 * Throws {@link LayerKeyError} when a segment is outside that domain.
 *
 * @example
 * ```ts
 * import { assertLayerKey } from "@stainless-code/layers";
 *
 * assertLayerKey(["confirm", filterId ?? "none"]);
 * ```
 */
declare function assertLayerKey(key: unknown): asserts key is LayerKey;
/**
 * Serializes a key deterministically by sorting object properties recursively.
 * Throws {@link LayerKeyError} when the key is not JSON-safe.
 */
declare function hashKey(key: LayerKey): string;
/**
 * Produces the canonical identity used to compare layer keys.
 * Throws {@link LayerKeyError} when the key is not JSON-safe (via {@link hashKey}).
 */
declare function keySignature(key: LayerKey): string;
/**
 * Element-wise `Object.is` for arrays.
 * Keeps key-filtered snapshot selections stable when `filter()` reallocates
 * but the matched element refs are unchanged.
 */
declare function shallowArrayEqual<T>(a: T, b: T): boolean;
//#endregion
//#region src/subscribable.d.ts
type Listener = () => void;
/**
 * Base for stores whose listeners participate in {@link notifyManager} batching.
 * Wrapping occurs once at subscription, so repeated notifications in one batch
 * coalesce for framework and bare subscribers alike.
 */
declare class Subscribable {
  protected listeners: Map<Listener, Listener>;
  subscribe(listener: Listener): () => void;
  protected notify(): void;
  protected onSubscribe?(): void;
  protected onUnsubscribe?(): void;
  get size(): number;
}
//#endregion
//#region src/notifyManager.d.ts
/**
 * Coalesces listener calls by identity within a synchronous batch.
 * Nested batches flush only when the outer batch completes; wrapped listeners
 * called repeatedly during that interval run once.
 */
declare const notifyManager: {
  batch<T>(fn: () => T): T;
  batchCalls(listener: () => void): () => void;
};
//#endregion
//#region src/controlledPromise.d.ts
type Resolve<T> = (value: T | PromiseLike<T>) => void;
type Reject = (reason?: unknown) => void;
/** Lets lifecycle code outside the executor settle a promise exactly once. */
declare class ControlledPromise<T> {
  readonly promise: Promise<T>;
  settled: boolean;
  resolve: Resolve<T>;
  reject: Reject;
  constructor();
}
//#endregion
//#region src/layer.d.ts
/** Runtime state and cancellation resources for one stack entry. */
declare class Layer<P = unknown, R = void, E = DefaultLayerError, D = unknown> {
  #private;
  readonly id: string;
  readonly key: LayerKey;
  readonly promise: ControlledPromise<R>;
  readonly abortController: AbortController;
  readonly component?: unknown;
  readonly enteringDelay: number;
  readonly exitingDelay: number;
  enterTimer?: ReturnType<typeof setTimeout>;
  exitTimer?: ReturnType<typeof setTimeout>;
  aborted: boolean;
  dismissPending?: Promise<boolean>;
  constructor(opts: {
    key: LayerKey;
    payload: P;
    index: number;
    stackSize: number;
    component?: unknown;
    enteringDelay?: number;
    exitingDelay?: number;
    data?: D;
  });
  get state(): LayerState<P, R, E, D>;
  get blockers(): ReadonlySet<BlockerFn>;
  addBlocker(fn: BlockerFn): () => void;
  /** Returns true if the snapshot changed. */
  setPartial(patch: Partial<LayerState<P, R, E, D>>): boolean;
  setRunning(running: boolean): void;
  /** Cancel any in-flight `loadFn`; subsequent resolutions are ignored. */
  abort(): void;
  resolve(response: R): void;
  reject(error: E): void;
}
//#endregion
//#region src/errors.d.ts
/** Provides validator-independent details for one payload failure. */
interface ValidationIssue {
  readonly message: string;
  readonly path?: ReadonlyArray<PropertyKey>;
}
/** Normalizes payload failures across supported validator styles. */
declare class PayloadValidationError extends Error {
  readonly issues: ReadonlyArray<ValidationIssue>;
  constructor(issues: ReadonlyArray<ValidationIssue>, options?: {
    cause?: unknown;
  });
}
/**
 * Narrows an unknown rejection to {@link PayloadValidationError}.
 *
 * @example
 * ```ts
 * import { isPayloadValidationError } from "@stainless-code/layers";
 *
 * function validationMessages(error: unknown) {
 *   return isPayloadValidationError(error)
 *     ? error.issues.map((issue) => issue.message)
 *     : [];
 * }
 * ```
 */
declare function isPayloadValidationError(value: unknown): value is PayloadValidationError;
/** Thrown when a layer key is not JSON-safe (from `assertLayerKey` / `hashKey`). */
declare class LayerKeyError extends Error {
  readonly path: ReadonlyArray<PropertyKey>;
  constructor(message: string, path?: ReadonlyArray<PropertyKey>);
}
/**
 * Narrows an unknown synchronous throw to {@link LayerKeyError}.
 *
 * @example
 * ```ts
 * import { isLayerKeyError } from "@stainless-code/layers";
 *
 * try {
 *   client.open({ key: [maybeId], payload });
 * } catch (error) {
 *   if (isLayerKeyError(error)) {
 *     console.error(error.path, error.message);
 *   }
 * }
 * ```
 */
declare function isLayerKeyError(value: unknown): value is LayerKeyError;
/**
 * Why {@link LayerCancelledError} rejected an `open()` promise.
 *
 * - `parentDismiss` — child stack `cancelAll`'d when its parent layer dismissed
 * - `groupDispose` — adapter / host cleaned up a `useLayerGroup` owner
 * - `cancelAll` — explicit {@link LayerStack#cancelAll} / {@link LayerClient#cancelAll}
 * - `stackDisconnect` — host disconnect (e.g. Lit `hostDisconnected`)
 */
type LayerCancelReason = "parentDismiss" | "groupDispose" | "cancelAll" | "stackDisconnect";
/**
 * Rejects `open()` when a stack is torn down without a completion response
 * (`cancelAll`, parent dismiss child clear, group dispose, `stackDisconnect`).
 */
declare class LayerCancelledError extends Error {
  /** {@link LayerCancelReason} that triggered this rejection. */
  readonly reason: LayerCancelReason;
  constructor(reason?: LayerCancelReason);
}
/**
 * Narrows an unknown rejection to {@link LayerCancelledError}.
 * Treat any cancel reason as normal teardown unless you branch on
 * {@link LayerCancelledError#reason}.
 *
 * @example
 * ```ts
 * import { isLayerCancelledError } from "@stainless-code/layers";
 *
 * try {
 *   await confirm.open(payload);
 * } catch (error) {
 *   if (isLayerCancelledError(error)) return;
 *   throw error;
 * }
 * ```
 */
declare function isLayerCancelledError(value: unknown): value is LayerCancelledError;
//#endregion
//#region src/layerStack.d.ts
interface OpenOpts<P, D> {
  key: LayerKey;
  payload: P;
  component?: unknown;
  enteringDelay?: number;
  exitingDelay?: number;
  upsert?: boolean;
  loadFn?: (ctx: {
    payload: P;
    signal: AbortSignal;
  }) => Promise<D> | D;
  validate?: Validator<P>;
}
/**
 * Manages the ordered layers for one surface.
 * Snapshots retain their references across batched notifications until their contents change.
 */
declare class LayerStack<P = unknown, R = void, E = DefaultLayerError, D = unknown> extends Subscribable {
  #private;
  readonly id: string;
  readonly options: StackOptions;
  constructor(id: string, options?: StackOptions);
  /** Returns a referentially stable snapshot between mutations. */
  getSnapshot: () => LayerState<P, R, E, D>[];
  /** Returns serially queued layers, which are excluded from `getSnapshot`. */
  getQueuedSnapshot: () => LayerState<P, R, E, D>[];
  getLayer(id: string): Layer<P, R, E, D> | undefined;
  find(key: LayerKey): Layer<P, R, E, D> | undefined;
  addBlocker(fn: StackBlockerFn): () => void;
  open(opts: OpenOpts<P, D>): Layer<P, R, E, D>;
  /**
   * Resolves the caller and aborts in-flight loading.
   * Exiting layers remain mounted until their transition settles.
   */
  dismiss(layer: Layer<P, R, E, D>, response: R, opts?: DismissOptions): Promise<boolean>;
  settle(layer: Layer<P, R, E, D>): void;
  /**
   * Bulk-dismisses active and queued layers, completing every `open()` with
   * `response` (including `undefined` when `R` is `void`). Honors
   * {@link DismissAllMode}; does not reject — use {@link cancelAll} for
   * teardown without a completion value.
   */
  dismissAll(response: R, opts?: DismissAllOptions): Promise<void>;
  /**
   * Force-clears the stack and rejects every open/queued caller with
   * {@link LayerCancelledError}. Skips blockers. System teardown path —
   * use {@link dismissAll} when completing with a response.
   *
   * @param opts.reason - Propagated on each rejection.
   * @default opts.reason `"cancelAll"`
   */
  cancelAll(opts?: {
    reason?: LayerCancelReason;
  }): Promise<void>;
  /**
   * Resolves and removes a serially queued layer without mounting it (skips blockers).
   * No `id` → FIFO head for the key; `{ id }` → exact queued match.
   */
  cancelQueued(key: LayerKey, response: R, opts?: {
    id?: string;
  }): boolean;
  update(layer: Layer<P, R, E, D>, patch: Partial<P>): void;
  setRunning(layer: Layer<P, R, E, D>, running: boolean): void;
}
//#endregion
//#region src/dataTag.d.ts
declare const dataTagSymbol: unique symbol;
declare const dataTagErrorSymbol: unique symbol;
/**
 * Phantom-brands a {@link LayerKey} so response and error types survive inference
 * without runtime metadata.
 * Tagging is idempotent: the first tag wins, avoiding conflicting brands
 * intersecting into `never`.
 */
type DataTag<Key extends LayerKey, R, E = DefaultLayerError> = Key extends {
  [dataTagSymbol]: unknown;
  [dataTagErrorSymbol]: unknown;
} ? Key : Key & {
  [dataTagSymbol]: R;
  [dataTagErrorSymbol]: E;
};
/** Lets generic APIs recover the response associated with a tagged key. */
type InferDataTagResponse<Key> = Key extends {
  [dataTagSymbol]: infer R;
} ? R : never;
/** Lets generic APIs recover the error associated with a tagged key. */
type InferDataTagError<Key> = Key extends {
  [dataTagErrorSymbol]: infer E;
} ? E : never;
/**
 * Preserves a response default when a generic key is untagged.
 */
type ResponseOf<Key, Fallback = void> = Key extends {
  [dataTagSymbol]: infer R;
} ? R : Fallback;
/** Preserves an error default when a generic key is untagged. */
type ErrorOf<Key, Fallback = DefaultLayerError> = Key extends {
  [dataTagErrorSymbol]: infer E;
} ? E : Fallback;
/**
 * Adds response and error inference to a key without changing it at runtime.
 *
 * @example
 * ```ts
 * import { LayerClient, layerKey } from "@stainless-code/layers";
 *
 * const client = new LayerClient();
 * const removeKey = layerKey<boolean>()(["confirm", "remove"]);
 * const ok = await client.open({ key: removeKey, payload: { title: "Remove?" } });
 * //    ^? boolean
 * ```
 */
declare function layerKey<R, E = DefaultLayerError>(): <const Key extends LayerKey>(key: Key) => DataTag<Key, R, E>;
//#endregion
//#region src/layerClient.d.ts
/** Coordinates named layer stacks. */
declare class LayerClient {
  #private;
  constructor(opts?: LayerClientOptions);
  /** Returns a stack, applying options only when creating it. */
  ensureStack(id: string, options?: StackOptions): LayerStack;
  bindChildStack(parentLayerId: string, childStackId: string): () => void;
  /** Accepts validator input while storing its parsed output as the payload. */
  open<V extends Validator<unknown>, P = InferValidatorOutput<V>, R = void, E = DefaultLayerError, D = unknown, RootProps = unknown>(options: OmitKeyof<OpenLayerOptions<P, R, E, D, RootProps>, "payload" | "validate"> & {
    validate: V;
    payload: NoInfer<OpenValidatePayload<V>>;
  }): Promise<R>;
  /** Infers response and error types from a {@link DataTag} key. */
  open<P, R, E = DefaultLayerError, D = unknown, RootProps = unknown>(options: OmitKeyof<OpenLayerOptions<P, R, E, D, RootProps> & {
    key: DataTag<LayerKey, R, E>;
  }, "validate">): Promise<R>;
  /** Opens a layer and resolves with its dismissal response. */
  open<P, R = void, E = DefaultLayerError, D = unknown, RootProps = unknown>(options: OmitKeyof<OpenLayerOptions<P, R, E, D, RootProps>, "validate">): Promise<R>;
  getStack(id?: string): LayerStack;
  getStackIds(): string[];
  /** Subscribes to first-time stack materialization. */
  subscribeStacks(listener: (stackId: string) => void): () => void;
  /** Subscribes to labeled stack snapshot transitions (devtools). */
  subscribeNotify(listener: (event: StackNotifyEvent) => void): () => void;
  /**
   * Re-emits the current snapshot as a `register` notify for one stack, or all
   * materialized stacks when `stackId` is omitted (devtools seed).
   */
  seedNotify(stackId?: string): void;
  /**
   * Bulk-dismisses a stack, completing every `open()` with `response`
   * (including omitted/`undefined` for void layers). Honors
   * {@link DismissAllMode}; does not reject — prefer {@link cancelAll} for
   * teardown without a completion value.
   */
  dismissAll(stackId?: string, response?: unknown, opts?: DismissAllOptions): Promise<void>;
  /**
   * Force-clears a stack and rejects every open/queued caller with
   * {@link LayerCancelledError}. System teardown — prefer {@link dismissAll}
   * when completing with a response.
   *
   * @param opts.reason - Propagated on each rejection.
   * @default opts.reason `"cancelAll"`
   */
  cancelAll(stackId?: string, opts?: {
    reason?: LayerCancelReason;
  }): Promise<void>;
}
//#endregion
//#region src/layerOptions.d.ts
/**
 * Preserves payload, response, error, and data inference for reusable layer options.
 * Returns the same object at runtime; its {@link DataTag}-branded key lets
 * `LayerClient.open` infer the response without an explicit generic.
 *
 * @example
 * ```ts
 * import { LayerClient, layerOptions } from "@stainless-code/layers";
 *
 * const client = new LayerClient();
 * const confirm = layerOptions<{ title: string }, boolean>({
 *   key: ["confirm", "remove"],
 * });
 * const ok = await client.open({ ...confirm, payload: { title: "Remove?" } });
 * //    ^? boolean
 * ```
 */
declare function layerOptions<P, R = void, E = DefaultLayerError, D = unknown, RootProps = unknown, const Key extends LayerKey = LayerKey>(options: LayerOptions<P, R, E, D, RootProps> & {
  key: Key;
}): LayerOptions<P, R, E, D, RootProps> & {
  key: DataTag<Key, R, E>;
};
//#endregion
//#region src/createLayer.d.ts
/** Prevents validated options from falling through to the unvalidated overload. */
type NoValidateOptions<Opts> = Opts extends {
  validate: Validator<unknown>;
} ? never : Opts;
/**
 * Identity-bound layer ops + escapes (`stack` / `client` / `options` / `current`).
 * `open`/`upsert` take payload only; stack-level ops route via `.stack`.
 */
interface LayerHandle<P, R, E, D, RP> {
  open: (payload: PayloadArg<P>["payload"]) => Promise<R>;
  upsert: (payload: PayloadArg<P>["payload"]) => Promise<R>;
  dismiss: (response?: R, opts?: DismissOptions & {
    id?: string;
  }) => Promise<boolean>;
  update: (patch: Partial<P>, opts?: {
    id?: string;
  }) => void;
  /**
   * Resolves and removes a serially queued layer without mounting (skips blockers).
   * No `id` → FIFO head for this key; `{ id }` → exact queued match.
   */
  cancelQueued: (response?: R, opts?: {
    id?: string;
  }) => boolean;
  readonly client: LayerClient;
  readonly stack: LayerStack<P, R, E, D>;
  readonly options: LayerOptions<P, R, E, D, RP> & {
    key: DataTag<LayerKey, R, E>;
  };
  /** Live-checked bound instance (`null` when not in the stack). */
  readonly current: Layer<P, R, E, D> | null;
}
/**
 * Validated handle: `open`/`upsert` take schema **input** ({@link OpenValidatePayload});
 * `current`/`update` use parsed **output**.
 */
interface ValidatedLayerHandle<V extends Validator<unknown>, R, E, D, RP> extends Omit<LayerHandle<InferValidatorOutput<V>, R, E, D, RP>, "open" | "upsert"> {
  open: (payload: OpenValidatePayload<V>) => Promise<R>;
  upsert: (payload: OpenValidatePayload<V>) => Promise<R>;
}
/**
 * Wire `layerOptions` + a {@link LayerClient} into a headless {@link LayerHandle}.
 *
 * @example
 * ```ts
 * const c = createLayer(confirm, client);
 * const ok = await c.open({ title: "Remove?" });
 * ```
 */
declare function createLayer<V extends Validator<unknown>, R, E = DefaultLayerError, D = unknown, RP = unknown>(options: LayerOptions<InferValidatorOutput<V>, R, E, D, RP> & {
  key: LayerKey;
  validate: V;
}, client: LayerClient): ValidatedLayerHandle<V, R, E, D, RP>;
declare function createLayer<P, R, E = DefaultLayerError, D = unknown, RP = unknown>(options: NoValidateOptions<LayerOptions<P, R, E, D, RP> & {
  key: LayerKey;
}>, client: LayerClient): LayerHandle<P, R, E, D, RP>;
//#endregion
//#region src/callContext.d.ts
/**
 * Creates the framework-neutral imperative context passed to a layer component.
 * Adapters provide rendering; stack and layer instances retain lifecycle control.
 */
declare function createCallContext<P, R, RootProps = unknown>(stack: LayerStack<P, R, DefaultLayerError, unknown>, layer: Layer<P, R, DefaultLayerError, unknown>, state: LayerState<P, R, DefaultLayerError, unknown>, rootProps?: RootProps): LayerCallContext<P, R, RootProps>;
//#endregion
//#region src/layerGroup.d.ts
/** Customizes child-stack identity and lifecycle. */
interface LayerGroupOptions {
  /**
   * Distinguishes sibling groups owned by the same parent.
   * @default "group"
   */
  name?: string;
  scope?: StackOptions["scope"];
  gcTime?: StackOptions["gcTime"];
}
/** Controls a child stack bound to its parent layer's lifetime. */
interface LayerGroupHandle {
  readonly stackId: string;
  /** Opens a layer with the child stack pre-bound. */
  open<P, R = void, E = DefaultLayerError, D = unknown, RootProps = unknown>(options: Omit<OpenLayerOptions<P, R, E, D, RootProps>, "stack">): Promise<R>;
  dismissAll(response?: unknown): void;
  /** Removes the parent-lifetime binding when its owner unmounts. */
  dispose(): void;
}
/** Derives a collision-free path id: `${parentStackId}~${parentLayerId}~${name}`. */
declare function childStackId(parent: Pick<LayerCallContext<unknown, unknown>, "stackId" | "layerId">, name?: string): string;
/**
 * Creates a child stack that is `cancelAll`'d (`LayerCancelledError`, reason
 * `parentDismiss`) when its parent dismisses. Pass the {@link LayerClient} that
 * owns `parent`; another client cannot observe the parent's lifetime.
 *
 * @example
 * ```ts
 * import {
 *   createLayerGroup,
 *   type LayerCallContext,
 *   type LayerClient,
 * } from "@stainless-code/layers";
 *
 * declare const client: LayerClient;
 * declare const parent: LayerCallContext<unknown, unknown>;
 *
 * const group = createLayerGroup(client, parent, { name: "nested" });
 * group.dismissAll();
 * group.dispose();
 * ```
 */
declare function createLayerGroup(client: LayerClient, parent: Pick<LayerCallContext<unknown, unknown>, "stackId" | "layerId">, options?: LayerGroupOptions): LayerGroupHandle;
//#endregion
export { BlockerFn, ControlledPromise, type DataTag, DefaultLayerError, DismissAllMode, DismissAllOptions, DismissOptions, type ErrorOf, type InferDataTagError, type InferDataTagResponse, type InferValidatorInput, type InferValidatorOutput, Layer, LayerActionStatus, LayerCallContext, type LayerCancelReason, LayerCancelledError, LayerClient, LayerClientOptions, LayerComponent, LayerComponentProps, type LayerGroupHandle, type LayerGroupOptions, type LayerHandle, LayerKey, LayerKeyError, LayerNotifyView, LayerOptions, LayerPhase, LayerStack, LayerState, LayerTransition, OmitKeyof, OpenLayerOptions, type OpenValidatePayload, PayloadArg, PayloadValidationError, Register, type Reject, type Resolve, type ResponseOf, SerialOnLoadError, StackBlockerFn, StackDefaults, StackNotifyAction, StackNotifyEvent, StackOptions, type StandardSchemaV1, Subscribable, type ValidatedLayerHandle, type ValidationIssue, type Validator, assertLayerKey, childStackId, createCallContext, createLayer, createLayerGroup, hashKey, isLayerCancelledError, isLayerKeyError, isPayloadValidationError, keySignature, layerKey, layerOptions, notifyManager, shallowArrayEqual };