@molecule/app-svelte

Framework · framework · App (browser) · v4.0.3 · Apache-2.0

Svelte framework bindings for molecule.dev

npm install @molecule/app-svelte

npm · Source on GitHub

How it works

@molecule/app-svelte adapts the @molecule/* cores to the framework framework on the app (browser) side.

<!-- +layout.svelte — wire providers ONCE, during component init -->
<script lang="ts">
  import type { Snippet } from 'svelte'
  import { setMoleculeContext } from '@molecule/app-svelte'
  import { provider as stateProvider } from '@molecule/app-state-zustand'
  import { provider as themeProvider } from '@molecule/app-theme-css-variables'
  import { createJWTAuthClient } from '@molecule/app-auth'

  setMoleculeContext({
    state: stateProvider,
    auth: createJWTAuthClient({ baseURL: '/api' }),
    theme: themeProvider,
  })

  let { children }: { children: Snippet } = $props()
</script>

{@render children()}

Works with: @molecule/app-device, @molecule/app-forms, @molecule/app-i18n, @molecule/app-logger, @molecule/app-platform, @molecule/app-routing, @molecule/app-state, @molecule/app-storage, @molecule/app-version

Reference

Svelte framework bindings for molecule.dev.

Provides Svelte stores and context utilities for all molecule core interfaces: call setMoleculeContext(config) once in the root layout, then consume services anywhere below via store factories (createAuthStores, createThemeStores, createI18nStores, …).

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

<!-- +layout.svelte — wire providers ONCE, during component init -->
<script lang="ts">
  import type { Snippet } from 'svelte'
  import { setMoleculeContext } from '@molecule/app-svelte'
  import { provider as stateProvider } from '@molecule/app-state-zustand'
  import { provider as themeProvider } from '@molecule/app-theme-css-variables'
  import { createJWTAuthClient } from '@molecule/app-auth'

  setMoleculeContext({
    state: stateProvider,
    auth: createJWTAuthClient({ baseURL: '/api' }),
    theme: themeProvider,
  })

  let { children }: { children: Snippet } = $props()
</script>

{@render children()}
<!-- Component.svelte — consume via stores -->
<script lang="ts">
  import { createAuthStores, createThemeStores } from '@molecule/app-svelte'

  const { user, isAuthenticated, logout } = createAuthStores<{ name?: string }>()
  const { theme, toggleTheme, mode } = createThemeStores()
</script>

{#if $isAuthenticated}
  <div style:background={$theme.colors.background}>
    <h1>Welcome, {$user?.name}!</h1>
    <button onclick={toggleTheme}>Toggle ({$mode})</button>
    <button onclick={() => logout()}>Logout</button>
  </div>
{/if}
<!-- Dashboard.svelte — the session, the theme and translations as stores -->
<script lang="ts">
  import { useAuth, useTheme, useTranslation } from '@molecule/app-svelte'

  const { user, status, logout } = useAuth<{ name?: string }>()
  const { t } = useTranslation()
  const { theme, toggleTheme } = useTheme()
</script>

{#if $status === 'loading'}
  <p>{t('auth.restoring', undefined, { defaultValue: 'Restoring session...' })}</p>
{:else if $status === 'unauthenticated'}
  <p>{t('auth.required', undefined, { defaultValue: 'Please log in.' })}</p>
{:else}
  <div style:background={$theme.colors.background}>
    <h1>
      {t('greeting.welcome', { name: $user?.name ?? '' }, { defaultValue: 'Welcome, {{name}}!' })}
    </h1>
    <button onclick={toggleTheme}>
      {t('theme.toggle', undefined, { defaultValue: 'Toggle theme' })}
    </button>
    <button onclick={() => logout()}>
      {t('auth.logout', undefined, { defaultValue: 'Log out' })}
    </button>
  </div>
{/if}
<!-- FavoriteButton.svelte — a server-backed favorite that changes at once -->
<script lang="ts">
  import { useHttpClient, useOptimisticValue, useTranslation } from '@molecule/app-svelte'

  interface FavoriteRecord {
    slug: string
    favorited: boolean
    favoritesCount: number
  }

  let {
    article,
    onChanged,
  }: {
    article: FavoriteRecord
    onChanged?: (saved: FavoriteRecord) => void
  } = $props()

  const http = useHttpClient()
  const { t } = useTranslation()
  const { value: favorite, update } = useOptimisticValue({
    value: { favorited: article.favorited, count: article.favoritesCount },
    commit: async (next) => {
      const path = `/articles/${article.slug}/favorite`
      const response = next.favorited
        ? await http.post<{ article: FavoriteRecord }>(path)
        : await http.delete<{ article: FavoriteRecord }>(path)
      const saved = response.data.article
      onChanged?.(saved)
      return { favorited: saved.favorited, count: saved.favoritesCount }
    },
  })
</script>

<button
  aria-pressed={$favorite.favorited}
  aria-label={t('article.favorite', undefined, { defaultValue: 'Favorite article' })}
  onclick={() =>
    update((current) => ({
      favorited: !current.favorited,
      count: current.count + (current.favorited ? -1 : 1),
    }))}>{$favorite.count}</button
>
<!-- PortaledNode.svelte — content in document.body, exactly as React renders it -->
<script lang="ts">
  import { BodyPortal } from '@molecule/app-svelte'
</script>

<BodyPortal><div role="dialog">…</div></BodyPortal>

Session state is a three-way decision, not a boolean: status === 'loading' is undecided, so wait for it and redirect only on status === 'unauthenticated'; 'unavailable' keeps the session candidate for retry, so a restore that failed with anything other than a 401/403 never signs the user out.

Type

framework

Installation

npm install @molecule/app-svelte @molecule/app-device @molecule/app-forms @molecule/app-i18n @molecule/app-logger @molecule/app-platform @molecule/app-routing @molecule/app-state @molecule/app-storage @molecule/app-version svelte

API

Interfaces

Readable

Readable interface for subscribing.

interface Readable<T> {
  /**
   * Subscribe on value changes.
   * @param run subscription callback
   * @param invalidate cleanup callback
   */
  subscribe(this: void, run: Subscriber<T>, invalidate?: () => void): Unsubscriber
}

Writable

Writable interface for both updating and subscribing.

interface Writable<T> extends Readable<T> {
  /**
   * Set value and inform subscribers.
   * @param value to set
   */
  set(this: void, value: T): void

  /**
   * Update value using callback and inform subscribers.
   * @param updater callback
   */
  update(this: void, updater: Updater<T>): void
}

AuthState

Reactive authentication state snapshot (initialized, authenticated, user, loading, and error).

interface AuthState<T = UserProfile> {
  /**
   * The session's state as one value — render from this instead of combining
   * `initialized`/`authenticated`/`loading`. `'loading'` is undecided, so wait
   * and redirect only on `'unauthenticated'`; `'unavailable'` keeps the candidate
   * for retry and can have a null profile. A restore failure other than 401/403
   * never signs out. See `AuthStatus`.
   */
  status: AuthStatus

  /**
   * Whether auth state has been initialized.
   */
  initialized: boolean

  /**
   * Whether the client has an authenticated session. This is not a server
   * confirmation flag: during `'unavailable'` it can be false for a retained
   * token/cookie-only candidate with no cached profile. Use `status` for redirects.
   */
  authenticated: boolean

  /**
   * Current user, or null when none is cached. In particular, an `'unavailable'`
   * token/cookie-only restore has a retained candidate but no profile yet.
   */
  user: T | null

  /**
   * Whether an auth operation is in progress.
   */
  loading: boolean

  /**
   * Last auth error (if any).
   */
  error: string | null
}

AuthClient

Auth client interface that all auth bond packages must implement. Provides login/logout/register flows, token management, profile updates, and auth state subscription.

interface AuthClient<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /**
   * Returns the current authentication state snapshot.
   *
   * READING the state starts the client's one session restore when nobody has called
   * `initialize` yet — lazily and exactly once, sharing the promise an explicit
   * `initialize()` returns. A hook (`useAuth()`), a subscriber, `isAuthenticated()` and
   * `getUser()` are reads too, so a client whose entry file dropped the template's
   * `authClient.initialize()` line still restores instead of reporting `'loading'`
   * forever.
   */
  getState(): AuthState<T>

  /**
   * Returns whether the user is currently authenticated.
   */
  isAuthenticated(): boolean

  /**
   * Gets the current user.
   */
  getUser(): T | null

  /**
   * Optional ownership marker for the current session. Compare values only within
   * this client: replacing or ending a session changes it, including re-adopting
   * the same token and user. Profile updates and same-session refreshes keep it.
   * Consumers can use it to discard stale async work without treating editable
   * user fields as an immutable account identifier. Providers without this
   * capability require the consumer's own stable identity check.
   */
  getSessionRevision?(): number

  /** Updates the cached user object (state + persistent storage) without hitting the network. */
  setUser(user: T | null): void

  /**
   * Gets the current access token.
   */
  getAccessToken(): string | null

  /**
   * Stores the access token in the configured token storage adapter (in a
   * browser, Web Storage; `'memory'` where no browser store exists). Use this
   * to seed the token after an out-of-band exchange (e.g. the OAuth
   * code→token redirect) instead of writing to `localStorage` directly,
   * which would violate the storage contract and make a stored bearer token
   * JS-readable (XSS-exfiltratable). Pass `null` to clear it.
   *
   * Passing `null` does not by itself sign a signed-in client out: use
   * `logout` to end a session, or `setUser` with `null` for
   * local-only sign-out. A non-null token on a client that is not signed in is
   * the first or second half of the app's own sign-in pair: together with
   * `setUser` it adopts the session (see there). Prefer `setSession`
   * with the token and user, or `login` / `register` for a
   * credential exchange.
   */
  setAccessToken(token: string | null): void

  /**
   * Adopts a session an out-of-band exchange already established: stores the
   * access token (and the refresh token when given), caches the user, and
   * sets the COMPLETE state — `initialized`, `authenticated`, `status:
   * 'authenticated'`, no error — in one update, with one subscriber
   * notification. Every hook reading the shared client sees the user as
   * signed in immediately.
   *
   * This is the way to seed an OAuth/custom sign-in. The field-setter pair
   * (`setAccessToken` then `setUser`, or the reverse) on a client
   * that is not signed in adopts the session the same way.
   */
  setSession(session: AuthSessionSeed<T>): void

  /**
   * Gets the refresh token.
   */
  getRefreshToken(): string | null

  /**
   * Logs in with credentials.
   */
  login(credentials: LoginCredentials): Promise<AuthResult<T>>

  /**
   * Logs out the current user. The server request is best-effort: a missing
   * logout route (404), any other HTTP failure, or a network error never makes
   * this method reject. It always clears the access token, refresh token and
   * cached user, stops automatic refresh, and publishes one settled
   * `authenticated: false`, `status: 'unauthenticated'` transition. Every pending
   * session operation loses ownership; a persistent marker prevents reload from
   * restoring an older session, and late credentials are revoked best-effort.
   *
   * When the API has no logout route, set `AuthClientConfigOptions.logoutEndpoint`
   * to `null` (or `''`) to skip the request. Local sign-out still happens.
   */
  logout(): Promise<void>

  /**
   * Registers a new user. Accepts the base fields plus the app's own fields
   * (`TRegister`) at the top level — see `RegisterData`.
   */
  register(data: RegisterData<TRegister>): Promise<AuthResult<T>>

  /**
   * Exchanges a stored refresh token, or re-reads `currentUserEndpoint` with the
   * existing access token/session cookie when the API has no refresh credential.
   * That fallback maps, stores and publishes the server user without renewing
   * the access token. Failures reject. A 401/403 ends the session, as does an
   * additional `AuthClientConfigOptions.currentUserRejectionStatuses`
   * code from the fallback. Transient failures retain it as unavailable. Use `updateProfile` for a profile
   * save, or `setUser` with the canonical row from an app-owned mutation.
   */
  refresh(): Promise<AuthResult<T>>

  /**
   * Requests a password reset.
   */
  requestPasswordReset(data: PasswordResetRequest): Promise<void>

  /**
   * Confirms a password reset.
   */
  confirmPasswordReset(data: PasswordResetConfirm): Promise<void>

  /**
   * Updates the current user's profile.
   * Returns the saved profile: the answer applied onto the signed-in user field
   * by field, with or without an `id` — a field it carries replaces the value
   * (`null` clears it), one it omits or leaves `undefined` is kept, so a field
   * cleared by omission must arrive as `null`. A non-object answer is returned
   * as it came. An answer for a replaced or ended session leaves the current one
   * untouched.
   */
  updateProfile(data: Partial<T>): Promise<T>

  /**
   * Changes the current user's password.
   */
  changePassword(oldPassword: string, newPassword: string): Promise<void>

  /** Initializes auth state (e.g., from stored tokens). */
  initialize(): Promise<void>

  /** Re-checks a restored session against the server, in the background — the boot-time validation an app with a stored token needs when a revoked or expired token… */
  validateSession?(): Promise<void>

  /** Resolves when the session restore started by `initialize()` has settled — the point after which the client knows whether this visitor is signed in. */
  whenRestored?(): Promise<void>

  /**
   * Subscribes to auth state changes.
   */
  subscribe(callback: (state: AuthState<T>) => void): () => void

  /**
   * Subscribes to auth state changes (alias for subscribe).
   */
  onAuthChange(callback: (state: AuthState<T>) => void): () => void

  /**
   * Gets the current access token (alias for getAccessToken).
   */
  getToken?(): string | null

  /**
   * Adds an auth event listener.
   *
   * The listener is typed by this client's profile: one signature,
   * `AuthEventListener<T>`, so an inline arrow is contextually typed and `event`
   * is never implicitly `any`. A client whose profile extends
   * `UserProfile` also accepts a default `AuthEventListener`: when
   * `T` extends `UserProfile`, `AuthEvent<T>` is assignable to
   * `AuthEvent<UserProfile>`, so a listener that takes the wider default event
   * accepts every event this client emits and keeps compiling. (`UserProfile`
   * is the wider type here — it has fewer required fields — and the assignable
   * direction runs from the client's `AuthEvent<T>` to the listener's
   * `AuthEvent<UserProfile>`.) A profile that does not extend `UserProfile`
   * (no `id`) rejects the default listener: an `AuthEvent<UserProfile>` would
   * promise an `id` the runtime user does not have, and the narrower-typed
   * event is not assignable to it.
   */
  addEventListener(listener: AuthEventListener<T>): () => void

  /**
   * Destroys the auth client.
   */
  destroy(): void
}

(The 4 longest member comments are shortened to their first sentence to fit; the full declaration is in node_modules/@molecule/app-auth/dist/types.d.ts.)

FormController

Form controller interface.

All form providers must implement this interface.

interface FormController<T extends FormValuesConstraint<T> = Record<string, unknown>> {
  /**
   * Gets the current form state.
   */
  getState(): FormState<T>

  /**
   * Gets the value of a specific field.
   */
  getValue(name: string): unknown
  getValue<K extends keyof T>(name: K): T[K]

  /**
   * Gets all form values.
   */
  getValues(): T

  /**
   * Sets the value of a specific field.
   */
  setValue(
    name: string,
    value: unknown,
    options?: { shouldValidate?: boolean; shouldDirty?: boolean; shouldTouch?: boolean },
  ): void

  /**
   * Sets multiple values at once.
   */
  setValues(values: Partial<T>, options?: { shouldValidate?: boolean }): void

  /**
   * Gets the error for a specific field.
   */
  getError(name: string): string | undefined

  /**
   * Sets the error for a specific field.
   */
  setError(name: string, error: string | undefined): void

  /**
   * Clears the error for a specific field.
   */
  clearError<K extends keyof T>(name: K): void

  /**
   * Clears all errors.
   */
  clearErrors(): void

  /**
   * Gets the field state for a specific field.
   */
  getFieldState<K extends keyof T>(name: K): FieldState<T[K]>

  /**
   * Registers a field for form management. A `defaultValue` that fills an
   * empty field is announced to subscribers once, in a microtask, so a field
   * registered during a render does not update other components mid-render.
   */
  register(nameOrOptions: string | RegisterOptions, options?: RegisterOptions): FieldRegistration

  /**
   * Unregisters a field.
   */
  unregister(name: string): void

  /**
   * Validates a specific field.
   */
  validateField<K extends keyof T>(name: K): Promise<boolean>

  /**
   * Validates all fields.
   */
  validate(): Promise<boolean>

  /**
   * Resets the form and clears errors, touched fields and submission state.
   *
   * With no argument it restores the current baseline — the initial
   * `defaultValues`, or the values a previous `reset(values)` established.
   * Passing `values` merges them over the current baseline and makes the
   * result the new baseline, so a form reset to freshly loaded or saved data
   * reads clean (`isDirty === false`). A changed non-null `id` replaces the
   * record and cancels a pending submit.
   */
  reset(values?: Partial<T>): void

  /**
   * Applies externally loaded values without clearing submission state.
   *
   * The new clean baseline is the original `defaultValues` plus this latest
   * record, never a merge of earlier records. With `keepDirtyValues`, edited
   * fields retain their values while pristine fields take the loaded values.
   * A changed non-null `id` still replaces the record and cancels a pending
   * submit. Equal-content baselines cause no update. `keepOmittedValues` opts
   * into incremental top-level field fills using the current clean baseline.
   */
  updateValues(values: Partial<T>, resetOptions?: FormUpdateOptions): void

  /**
   * Handles form submission.
   */
  handleSubmit(
    onSubmit: (values: T) => void | Promise<void>,
    onError?: (errors: Partial<Record<keyof T, string>>) => void,
  ): (event?: { preventDefault?: () => void }) => Promise<void>

  /**
   * Sets focus to a field.
   */
  setFocus(name: keyof T): void

  /**
   * Subscribes to form state changes.
   */
  subscribe(callback: (state: FormState<T>) => void): () => void

  /**
   * Destroys the form controller.
   */
  destroy(): void
}

FormResetOptions

Options controlling how externally supplied values replace a form's baseline.

interface FormResetOptions {
  /**
   * Keep fields whose current value differs from their baseline when `values`
   * changes. Pristine fields still take the new values. False by default, so a
   * new record can replace edits from the previous record.
   */
  keepDirtyValues?: boolean
}

FormOptions

Form creation options.

interface FormOptions<T extends FormValuesConstraint<T>> {
  /**
   * Default values, captured as the form's clean baseline when the controller
   * is created. Mutating this object afterwards does not change the baseline.
   */
  defaultValues?: Partial<T>

  /**
   * Externally loaded values, merged over `defaultValues` as the clean
   * baseline. Framework bindings also apply later content changes; use
   * `resetOptions.keepDirtyValues` to preserve edits while pristine fields fill.
   */
  values?: Partial<T>

  /** Controls how framework bindings apply changed `values`. */
  resetOptions?: FormResetOptions

  /**
   * Validation mode.
   */
  mode?: 'onSubmit' | 'onChange' | 'onBlur' | 'all'

  /**
   * Revalidation mode.
   */
  reValidateMode?: 'onChange' | 'onBlur' | 'onSubmit'

  /**
   * Whether to focus the first error field on submit.
   */
  shouldFocusError?: boolean

  /**
   * Form-level validation function.
   */
  validate?: (
    values: T,
  ) => Partial<Record<keyof T, string>> | Promise<Partial<Record<keyof T, string>>>
}

HttpClient

HTTP client interface.

All HTTP providers must implement this interface. An explicit text, blob or arraybuffer parser determines the data type even when a JSON generic is supplied. Keep JSON as the default for mutations returning a record. A successful DELETE with no body already resolves with null data.

Every verb also takes a URL alone, through a signature with the same three parameters on every verb, so a verb chosen at runtime (client[verb](url)) type-checks and a wrapper can implement a verb with an arrow (get: (url, config) => inner.get(url, config)). With a body or a config, choose the verb through request({ method, url, data }) instead: the second argument is the body for post/put/patch but the config for get/delete, so one call cannot serve both.

interface HttpClient {
  /**
   * Base URL for all requests.
   */
  baseURL: string

  /**
   * Default headers for all requests.
   */
  defaultHeaders: Record<string, string>

  /**
   * Makes a generic HTTP request. `data` is a field of THIS config object — the same body
   * `post(url, data, config)` takes as its second argument.
   */
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  request<T = unknown>(config: FullRequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a GET request.
   */
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  get<T = unknown>(url: string, config?: undefined, unused?: undefined): Promise<HttpResponse<T>>
  get<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a POST request. `data` is the request BODY, not a config object: the wire body is
   * `data` itself, so `post(url, { data: body })` sends `{"data":body}` — pass `body` directly.
   * A config (headers, params) is the THIRD argument.
   */
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  post<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  post<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a PUT request. `data` is the request BODY (second argument) — never `{ data: body }`,
   * which sends `{"data":body}`; a config is the THIRD argument.
   */
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  put<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  put<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a PATCH request. `data` is the request BODY (second argument) — never `{ data: body }`,
   * which sends `{"data":body}`; a config is the THIRD argument.
   */
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  patch<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  patch<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a DELETE request.
   */
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  delete<T = unknown>(url: string, config?: undefined, unused?: undefined): Promise<HttpResponse<T>>
  delete<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Adds a request interceptor.
   * Returns a function to remove the interceptor.
   */
  addRequestInterceptor(interceptor: RequestInterceptor): () => void

  /**
   * Adds a response interceptor.
   * Returns a function to remove the interceptor.
   */
  addResponseInterceptor(interceptor: ResponseInterceptor): () => void

  /**
   * Adds an error interceptor.
   * Returns a function to remove the interceptor.
   */
  addErrorInterceptor(interceptor: ErrorInterceptor): () => void

  /**
   * Sets the authorization token.
   *
   * A static token: every request carries it until the next `setAuthToken` call. A client
   * that has a `resolver` (registered through
   * `@molecule/app-http`'s `setAuthTokenSource`) ignores this value when it assembles a
   * request — the resolver IS the session, and reading it per request is what keeps a
   * session adopted without an auth event from sending the previous account's bearer. Once
   * the resolver is removed, the static token is sent again.
   */
  setAuthToken(token: string | null): void

  /**
   * Returns the token the client applies to its next request: the resolver's answer when one
   * is registered, else the static token from `setAuthToken`.
   */
  getAuthToken(): string | null

  /** Registers the LIVE token resolver every request of this client reads, or clears it with `null`. */
  setAuthTokenResolver?(resolver: AuthTokenResolver | null): void

  /**
   * Registers a handler for authentication errors (401), with the rejected request's metadata.
   *
   * @param handler - Receives the method, URL and credential state of the rejected request.
   * @returns An unsubscribe function.
   */
  onAuthError(handler: (event: HttpAuthErrorEvent) => void): () => void
}

(The longest member comment is shortened to its first sentence to fit; the full declaration is in node_modules/@molecule/app-http/dist/client.d.ts.)

Logger

Logger instance with leveled logging methods, child logger creation, and transport management.

interface Logger {
  /**
   * Logs a trace message.
   */
  trace(message: string, ...args: unknown[]): void

  /**
   * Logs a debug message.
   */
  debug(message: string, ...args: unknown[]): void

  /**
   * Logs an info message.
   */
  info(message: string, ...args: unknown[]): void

  /**
   * Logs a warning message.
   */
  warn(message: string, ...args: unknown[]): void

  /**
   * Logs an error message.
   */
  error(message: string | Error, ...args: unknown[]): void

  /**
   * Sets the log level.
   */
  setLevel(level: LogLevel): void

  /**
   * Gets the current log level.
   */
  getLevel(): LogLevel

  /**
   * Creates a child logger with a namespace.
   */
  child(name: string, context?: Record<string, unknown>): Logger

  /**
   * Adds additional context to the logger.
   */
  withContext(context: Record<string, unknown>): Logger

  /**
   * Adds a transport.
   */
  addTransport(transport: LogTransport): () => void

  /**
   * Removes a transport.
   */
  removeTransport(transport: LogTransport): void
}

RouteLocation

Current URL decomposed into pathname, search string, hash, navigation state, and unique key.

interface RouteLocation {
  /**
   * Current pathname.
   */
  pathname: string

  /**
   * Query string (including leading ?).
   */
  search: string

  /**
   * Hash (including leading #).
   */
  hash: string

  /**
   * State data passed with navigation.
   */
  state?: unknown

  /**
   * Unique key for this location.
   */
  key?: string
}

Router

Client-side router providing navigation, guards, route matching, and history control.

All routing providers must implement this interface.

interface Router {
  /**
   * Returns the current route location (pathname, search, hash, state).
   */
  getLocation(): RouteLocation

  /**
   * Gets the current route params.
   */
  getParams<T extends RouteParams = RouteParams>(): T

  /**
   * Gets the current query params.
   */
  getQuery(): QueryParams

  /**
   * Gets a specific query parameter.
   */
  getQueryParam(key: string): string | undefined

  /**
   * Gets the current hash.
   */
  getHash(): string

  /**
   * Navigates to a path. A path that is only a query or a hash (`'?tab=2'`, `'#top'`) stays on
   * the current page, as React Router's `navigate` does; a hash alone drops the current query.
   */
  navigate(path: string, options?: NavigateOptions): void

  /**
   * Navigates to a named route.
   */
  navigateTo(
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ): void

  /**
   * Goes back in history.
   */
  back(): void

  /**
   * Goes forward in history.
   */
  forward(): void

  /**
   * Goes to a specific point in history.
   */
  go(delta: number): void

  /**
   * Updates the current query params.
   */
  setQuery(params: QueryParams, options?: NavigateOptions): void

  /**
   * Updates a specific query parameter.
   */
  setQueryParam(key: string, value: string | undefined, options?: NavigateOptions): void

  /**
   * Updates the current hash.
   */
  setHash(hash: string, options?: NavigateOptions): void

  /**
   * Checks if a path matches the current location.
   *
   * @returns `true` if the path matches the current route.
   */
  isActive(path: string, exact?: boolean): boolean

  /**
   * Matches a path pattern against a pathname.
   */
  matchPath<Params extends RouteParams = RouteParams>(
    pattern: string,
    pathname: string,
  ): RouteMatch<Params> | null

  /**
   * Generates a URL from a named route.
   */
  generatePath(name: string, params?: RouteParams, query?: QueryParams): string

  /**
   * The `href` an anchor to the in-app `path` carries, as the native router's own link
   * writes it (its base path prefixed, or `#/…` under a hash history), so a middle-click,
   * a new tab or a copied link opens the same page a click does. A `path` that is only a
   * query or a hash (`'?tab=2'`, `'#top'`) is the current page's, as `navigate` reads it
   * and as React Router's `<Link>` writes it: `'#top'` on `/docs?x=1` is `/docs#top`.
   *
   * @param path - Pathname with optional query string and hash, as passed to `navigate`.
   * @returns The `href`.
   */
  createHref(path: string): string

  /**
   * Calls `listener` once after each navigation the router commits, however it started (a
   * link, the back button, `navigate`), with the new location and the navigation action.
   * A router calls it before the browser paints the new page, so a component that renders
   * from a listener (the framework bindings' `useLocation` and `useParams` do) shows the new
   * location in the same paint as the new page. Molecule's router conformance tests check
   * that at every paint.
   *
   * @param listener - Called with the new location and the navigation action.
   * @returns Stops calling `listener`.
   */
  subscribe(listener: RouteChangeListener): () => void

  /**
   * Adds a navigation guard.
   */
  addGuard(guard: NavigationGuard): () => void

  /**
   * Registers route definitions.
   */
  registerRoutes(routes: RouteDefinition[]): void

  /**
   * Gets all registered routes.
   */
  getRoutes(): RouteDefinition[]

  /**
   * Destroys the router.
   */
  destroy(): void
}

RouterConfig (deprecated)

Deprecated: Use BrowserRouterConfig (createBrowserRouter) or MemoryRouterConfig (createMemoryRouter): each takes only the options it acts on.

Configuration options for creating a router instance.

interface RouterConfig {
  /**
   * Router mode.
   */
  mode?: 'history' | 'hash' | 'memory'

  /**
   * Base path.
   */
  basePath?: string

  /**
   * Initial routes.
   */
  routes?: RouteDefinition[]
}

StoreConfig

Configuration for creating a store (initial state, optional name, and middleware chain).

interface StoreConfig<T> {
  /**
   * Initial state value.
   */
  initialState: T

  /**
   * Optional name for debugging.
   */
  name?: string

  /**
   * Optional middleware functions.
   */
  middleware?: StoreMiddleware<T>[]
}

MoleculeStore

Reactive state container with getState, setState, subscribe, and destroy.

All state management providers must implement this interface.

interface Store<T> {
  /**
   * Gets the current state.
   */
  getState(): T

  /**
   * Sets the state (partial or via updater function).
   */
  setState(partial: Partial<T> | ((state: T) => Partial<T>)): void

  /**
   * Subscribes to state changes.
   * Returns an unsubscribe function.
   */
  subscribe(listener: StateListener<T>): () => void

  /**
   * Destroys the store and cleans up subscriptions.
   */
  destroy(): void
}

Store

Reactive state container with getState, setState, subscribe, and destroy.

All state management providers must implement this interface.

interface Store<T> {
  /**
   * Gets the current state.
   */
  getState(): T

  /**
   * Sets the state (partial or via updater function).
   */
  setState(partial: Partial<T> | ((state: T) => Partial<T>)): void

  /**
   * Subscribes to state changes.
   * Returns an unsubscribe function.
   */
  subscribe(listener: StateListener<T>): () => void

  /**
   * Destroys the store and cleans up subscriptions.
   */
  destroy(): void
}

Theme

Complete theme definition.

interface Theme {
  name: string
  mode: 'light' | 'dark'
  colors: ThemeColors
  breakpoints: ThemeBreakpoints
  spacing: ThemeSpacing
  typography: ThemeTypography
  borderRadius: ThemeBorderRadius
  shadows: ThemeShadows
  transitions: ThemeTransitions
  zIndex: ThemeZIndex
}

UseAuthOptions

Options for useAuth.

interface UseAuthOptions {
  /**
   * Whether to automatically refresh the session on mount, and again whenever
   * the flag turns on or the session decision changes while it is on.
   */
  autoRefresh?: boolean
}

UseAuthResult

What useAuth returns: the session's value fields as readable stores ($status, $user, …) and the client's actions as plain functions.

interface UseAuthResult<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /**
   * The session state as one value — render from this instead of combining
   * `initialized`/`authenticated`/`loading`. Only `'loading'` means "no
   * decision yet"; redirect on `'unauthenticated'` alone.
   */
  status: Readable<AuthState<T>['status']>
  /** The whole session state. */
  state: Readable<AuthState<T>>
  /** The client's `login`. */
  login: AuthClient<T>['login']
  /** The client's `logout`. */
  logout: AuthClient<T>['logout']
  /** The client's `register` (there is no separate `useRegister`). */
  register: AuthClient<T, TRegister>['register']
  /** The client's `refresh`. */
  refresh: AuthClient<T>['refresh']
  /** Saves through the configured auth transport and publishes the saved user. */
  updateProfile: AuthClient<T>['updateProfile']
  /** Caches a user without signing in. */
  setUser: AuthClient<T>['setUser']
  /**
   * Adopts a session an exchange outside the client already established (an
   * OAuth code→token redirect, the app's own sign-in endpoint) in one update.
   */
  setSession: AuthClient<T>['setSession']
  /** Whether a session is authenticated locally. */
  isAuthenticated: Readable<boolean>
  /** Whether the client is working on a decision. */
  isLoading: Readable<boolean>
  /** The cached profile, which can be null while an unavailable candidate is retained. */
  user: Readable<T | null>
}

UseChangePasswordReturn

What useChangePassword returns.

interface UseChangePasswordReturn {
  /** The latest call's status. */
  status: Readable<UsePromiseState<void>['status']>
  /** The latest call's rejection. */
  error: Readable<UsePromiseState<void>['error']>
  /** Runs the password change. */
  changePassword: (oldPassword: string, newPassword: string) => Promise<void>
  /** Returns the tracker to idle. */
  reset: () => void
}

UseDeviceResult

Hook return type.

interface UseDeviceResult {
  /** The parsed device identity. */
  deviceInfo: DeviceInfo
  /** The screen dimensions and mode. */
  screenInfo: ScreenInfo
  /** The hardware capabilities. */
  hardwareInfo: HardwareInfo
  /** The feature flags. */
  featureSupport: FeatureSupport
  /** Whether a feature is supported. */
  supports: (feature: keyof FeatureSupport) => boolean
  /** Whether the device is online. */
  isOnline: () => boolean
  /** Whether the app runs standalone. */
  isStandalone: () => boolean
  /** The preferred language. */
  language: string
  /** The preferred languages, best first. */
  languages: string[]
}

UseEditorResult

Hook result for useEditor: the tab state as readable stores and the editor actions as plain functions.

interface UseEditorResult {
  /** The provider's open tabs. */
  tabs: Readable<EditorTab[]>
  /** The path of the tab marked active, or null when none is. */
  activeFile: Readable<string | null>
  /** Opens a file in a tab and activates it. */
  openFile: (file: EditorFile) => void
  /** Closes a tab. */
  closeFile: (path: string) => void
  /** The active tab's content. */
  getContent: () => string | null
  /** Writes a tab's content. */
  setContent: (path: string, content: string) => void
  /** Activates the tab with the given path. */
  setActiveTab: (path: string) => void
  /** Mounts the editor into an element. */
  mount: EditorProvider['mount']
  /** Disposes the editor. */
  dispose: () => void
  /** Focuses the editor. */
  focus: () => void
  /** Opens a diff tab (provider optional method). */
  openDiff: (file: DiffFile) => void
  /** Closes the diff tab (provider optional method). */
  closeDiff: () => void
  /** Converts a preview tab into a normal one (provider optional method). */
  pinTab: (path: string) => void
  /** Adds an extra type library (provider optional method). */
  addExtraLib: (content: string, filePath: string) => void
  /** Subscribes a Fix-with-AI request listener; returns its unsubscribe. */
  onFixWithAI: (callback: (request: FixWithAIRequest) => void) => () => void
}

UseFormOptions

Options for useForm hook.

Every FormOptions field is supported. createForm is only an override — omit it and the hook creates the controller through the bonded forms provider (createForm from @molecule/app-forms), which uses the built-in native provider until the app bonds its own.

interface UseFormOptions<T extends FormValuesConstraint<T>> extends FormOptions<T> {
  /** External values preserve dirty fields by default. Set keepDirtyValues: false to replace them explicitly. */
  resetOptions?: FormResetOptions
  /** New record identity. Serialize composite keys; fresh objects/arrays must not reset drafts on each mount. */
  resetKey?: string | number | boolean | bigint | null
  /**
   * Explicit form factory for this one form. Defaults to the bonded forms
   * provider; pass it only to pin a specific provider instance.
   */
  createForm?: (options: FormOptions<T>) => FormController<T>
}

UseFormResult

Result of useForm hook: the state fields as readable stores, the methods as plain functions.

interface UseFormResult<T extends FormValuesConstraint<T>> {
  /** The whole form state. */
  formState: Readable<FormState<T>>
  /** Whether every field passes validation. */
  isValid: Readable<boolean>
  /** Whether any field differs from the baseline. */
  isDirty: Readable<boolean>
  /** Whether a submit is running. */
  isSubmitting: Readable<boolean>

  /** Registers a field; returns its native bindings. */
  register: (
    name: keyof T,
    options?: Omit<RegisterOptions, 'name'> & { name?: string },
  ) => FieldRegistration
  /** Reads one field's value. */
  getValue: <K extends keyof T>(name: K) => T[K]
  /** Writes one field's value (marks it touched and dirty). */
  setValue: <K extends keyof T>(name: K, value: T[K]) => void
  /** Reads one field's error. */
  getError: (name: keyof T) => string | undefined
  /** Sets or clears one field's error. */
  setError: (name: keyof T, error: string | undefined) => void
  /** Clears every field error. */
  clearErrors: () => void

  /** Validates and runs the handler; returns the submit runner. */
  handleSubmit: (
    onSubmit: (values: T) => void | Promise<void>,
    onError?: (errors: Partial<Record<keyof T, string>>) => void,
  ) => (event?: { preventDefault?: () => void }) => Promise<void>
  /** Restores the baseline (optionally a new one) and clears touched, errors and submit state. */
  reset: (values?: Partial<T>) => void
  /** Applies externally loaded values without clearing submission state. */
  updateValues: (values: Partial<T>, resetOptions?: FormUpdateOptions) => void
  /** Whole-form state tuple: edits mark only changed fields dirty; fills preserve them. */
  asState(): readonly [
    T,
    (value: T | ((previous: T) => T)) => void,
    (value: Partial<T> | ((previous: T) => Partial<T>)) => void,
  ]
  /** One field as [value, edit, fill]. Fill preserves edits made before data arrives. */
  asState<K extends keyof T>(
    name: K,
  ): readonly [
    T[K],
    (value: T[K] | ((previous: T[K]) => T[K])) => void,
    (value: T[K] | ((previous: T[K]) => T[K])) => void,
  ]
  /** Runs every registered rule and publishes field errors. */
  validate: () => Promise<boolean>
}

UseHttpState

State for async HTTP operations.

interface UseHttpState<T> {
  data: T | null
  loading: boolean
  error: Error | null
}

UseHttpResult

What useHttp returns: the state fields as stores plus execute and reset.

interface UseHttpResult<T> {
  /** The newest request's data, or null. */
  data: Readable<T | null>
  /** Whether a request is in flight. */
  loading: Readable<boolean>
  /** The newest request's failure. */
  error: Readable<Error | null>
  /**
   * Runs the request and resolves with its own data, or `null` on failure,
   * even when a newer request or `reset` has superseded its displayed state.
   *
   * This function keeps ONE identity for the component's life, so it is safe
   * wherever a stable function matters. Its request options are read when it
   * is CALLED.
   */
  execute: () => Promise<T | null>
  /** Clears the state and supersedes any in-flight request. */
  reset: () => void
}

UseHttpOptions

Options for the useHttp hooks.

Every request option — headers, params, body data, signal, onSuccess, onError — is read at the moment execute runs, not when the hook was called. Only immediate is read on mount.

interface UseHttpOptions<T> extends RequestConfig {
  /** Whether to execute the request immediately on mount. */
  immediate?: boolean
  /**
   * Callback for each request that succeeds while mounted, including a request
   * superseded by another `execute` or `reset`. Read `data` from the hook when
   * only the newest request's result should drive the UI.
   */
  onSuccess?: (data: T) => void
  /** Callback for each request that fails while mounted, including a superseded one. */
  onError?: (error: Error) => void
}

UseLoginReturn

What useLogin returns: the promise state's value fields as stores plus the action.

interface UseLoginReturn<T = unknown> {
  /** The latest call's status. */
  status: Readable<UsePromiseState<AuthResult<T>>['status']>
  /** The latest call's resolved value. */
  value: Readable<UsePromiseState<AuthResult<T>>['value']>
  /** The latest call's rejection. */
  error: Readable<UsePromiseState<AuthResult<T>>['error']>
  /** Runs the login. */
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  /** Returns the tracker to idle. */
  reset: () => void
}

UseOAuthReturn

Return type for useOAuth hook.

interface UseOAuthReturn {
  /**
   * The configured provider names (React's `string[]`), read live: each read
   * returns the list the current config holds, and a read in markup or
   * `$derived` re-runs when a config store changes. Read it off the result
   * (`oauth.providers`); a destructured copy keeps the list of the moment it
   * was taken.
   */
  readonly providers: string[]
  /** Builds the provider's initiation URL (provider encoded as one path segment). */
  getOAuthUrl: (provider: string) => string
  /** Full-page redirect to the provider (default). The opener page navigates away. */
  redirect: (provider: string) => void
  /**
   * Open the provider in a popup so the opener page does NOT navigate. On success
   * the session is established in the opener in place and `config.onSuccess` fires;
   * on failure `config.onError` fires. Falls back to a full-page `redirect`
   * when the popup is blocked.
   */
  loginViaPopup: (provider: string) => void
}

UseOAuthConfig

OAuth configuration override options.

interface UseOAuthConfig {
  /** Base URL for the API server (e.g. "https://api.example.com"). */
  baseURL?: string
  /** List of supported OAuth provider names (e.g. ["google", "github"]). */
  oauthProviders?: string[]
  /** Path prefix for OAuth routes (defaults to "/oauth"). */
  oauthEndpoint?: string
  /** Path for the OAuth login POST endpoint (defaults to "/users/log-in/oauth"). */
  loginEndpoint?: string
  /** Callback after successful OAuth login. */
  onSuccess?: () => void
  /** Callback on OAuth login failure. */
  onError?: (error: string) => void
  /**
   * How the page leaves for the provider: `UseOAuthReturn.redirect` and the
   * blocked-popup fallback call it with the provider URL. Defaults to a full-page
   * navigation (`window.location.href = url`); pass an in-app browser opener on
   * native, or a router's external navigation.
   */
  navigate?: (url: string) => void
}

UseOptimisticToggleOptions

Options for useOptimisticToggle.

interface UseOptimisticToggleOptions {
  /** The loaded server value. Mount the control only after its record exists. */
  value: boolean
  /** Saves the DESIRED value and returns the server-confirmed value; reject on failure. */
  commit: (desired: boolean) => Promise<boolean>
  /** Receives the newest failed save and the confirmed value restored by the controller. */
  onError?: (error: unknown, value: boolean) => void
}

UseOptimisticToggleResult

What useOptimisticToggle returns: the boolean to render as readable stores and an argument-free action (the same names React returns).

interface UseOptimisticToggleResult {
  /** The value to render. */
  value: Readable<boolean>
  /** Whether a save is running or waiting. */
  pending: Readable<boolean>
  /** The failure of the newest change. */
  error: Readable<unknown>
  /** Flips the value shown now and saves it; the same function for the component's life. */
  toggle: () => void
}

UseOptimisticValueResult

What useOptimisticValue returns: the state to render as readable stores and the two ways to change it (the same names React returns).

interface UseOptimisticValueResult<T> {
  /** The value to render. */
  value: Readable<T>
  /** Whether a save is running or waiting. */
  pending: Readable<boolean>
  /** The failure of the newest change. */
  error: Readable<unknown>
  /** Shows `next` at once and saves it, after any save already running. */
  set: (next: T) => void
  /** Like `set`, computed from the value shown now (`update((on) => !on)`). */
  update: (change: (current: T) => T) => void
}

UsePasswordResetReturn

What usePasswordReset returns: two independent trackers plus a combined reset.

interface UsePasswordResetReturn {
  /** The request step's status. */
  requestStatus: Readable<UsePromiseState<void>['status']>
  /** The request step's rejection. */
  requestError: Readable<UsePromiseState<void>['error']>
  /** The confirm step's status. */
  confirmStatus: Readable<UsePromiseState<void>['status']>
  /** The confirm step's rejection. */
  confirmError: Readable<UsePromiseState<void>['error']>
  /** Sends the reset email (step 1). */
  requestReset: (data: PasswordResetRequest) => Promise<void>
  /** Sets the new password (step 2). */
  confirmReset: (data: PasswordResetConfirm) => Promise<void>
  /** Returns BOTH trackers to idle. */
  reset: () => void
}

UsePlatformResult

Hook return type.

interface UsePlatformResult {
  /** The detected platform. */
  platform: Platform
  /** Whether the app runs in a native shell. */
  isNative: boolean
  /** Whether the platform is a phone or tablet. */
  isMobile: boolean
  /** Whether the platform is a desktop. */
  isDesktop: boolean
  /** Whether the platform is the web. */
  isWeb: boolean
  /** Whether the app runs in development. */
  isDevelopment: boolean
  /** Whether the app runs in production. */
  isProduction: boolean
  /** Whether the current platform is one of the candidates. */
  isPlatform: (...platforms: Platform[]) => boolean
}

UsePreviewResult

Hook result for usePreview: the preview state as a readable store and the controls as plain functions.

interface UsePreviewResult {
  /** The preview's full state (url, currentUrl, isLoading, device, error, isConnected, canGoBack, canGoForward, loadNonce). */
  state: Readable<PreviewState>
  /** Loads a url. */
  setUrl: (url: string) => void
  /** Reloads the current document. */
  refresh: () => void
  /** Switches the device frame. */
  setDevice: (device: DeviceFrame) => void
  /** Opens the current url outside the app. */
  openExternal: () => void
  /**
   * Records a navigation the running preview reported via its `molecule:navigate`
   * message — updates the displayed current location without reloading the iframe.
   * Pass `isReplace` when the preview REPLACED its current history entry (a
   * `replaceState` redirect/canonicalization) so the forward stack is preserved
   * instead of truncated (a `pushState`, the default, truncates forward).
   */
  recordNavigation: (url: string, isReplace?: boolean) => void
  /** Navigates the preview to the previous navigation-history entry (Back). */
  back: () => void
  /** Navigates the preview to the next navigation-history entry (Forward). */
  forward: () => void
}

UseProfileFormOptions

Configuration for a profile form; transport stays in the auth bond.

TValues is the page's own controlled-values type, named once as an interface or a type alias — both satisfy the shared form-values constraint.

interface UseProfileFormOptions<TUser, TValues extends FormValuesConstraint<TValues>> extends Omit<
  UseFormOptions<TValues>,
  'defaultValues'
> {
  /** Complete controlled-field defaults, including blank write-only fields. */
  defaultValues: TValues
  /**
   * Optional additional account identity check; changing it discards prior edits.
   * By default ownership follows the auth client's session revision, so editable
   * fields can change during a save. Providers without getSessionRevision must
   * supply this callback with an identity that remains stable across profile edits.
   */
  getIdentity?: (user: TUser) => string
  /** Maps the current/saved user into controlled values, e.g. nullable text to ''. */
  toValues: (user: TUser) => TValues
  /**
   * Maps ONLY changed fields into an API patch. Omit blank optional credentials
   * here; preserve undefined/absent fields rather than turning them into null.
   * The second argument is the complete value snapshot taken at submit time.
   */
  toPatch: (changes: Partial<TValues>, values: Readonly<TValues>) => Partial<TUser>
  /**
   * Propagates the server's saved user to other caches, then navigates if needed.
   * Awaited before submission finishes. The auth client already persists and
   * publishes the saved user; never seed caches from the submitted patch.
   */
  onSaved?: (user: TUser) => void | Promise<void>
}

UseProfileFormResult

Controlled profile form state and native form bindings.

interface UseProfileFormResult<TUser, TValues extends FormValuesConstraint<TValues>> extends Omit<
  UseFormResult<TValues>,
  'register' | 'handleSubmit' | 'reset'
> {
  /** The shared auth user's current profile, as a readable store. */
  user: Readable<TUser | null>
  /** A user has been loaded; disable submission until this is true. */
  ready: Readable<boolean>
  /**
   * The latest save/propagation failure. Rejected saves retain edits; a failed
   * onSaved callback can be retried by submit without repeating the mutation.
   */
  error: Readable<unknown>
  /** Native input/textarea bindings with the field's concrete value type. */
  register: <K extends keyof TValues>(
    name: K,
    options?: Parameters<UseFormResult<TValues>['register']>[1],
  ) => Omit<FieldRegistration, 'value'> & { value: TValues[K] }
  /** Bind to the native form, with a type="submit" button inside it. */
  formProps: { onSubmit: (event: { preventDefault: () => void }) => void }
  /**
   * Validates and saves one submit-time snapshot. Concurrent submits share the
   * same promise. Resolves undefined on validation, save or propagation failure.
   */
  submit: () => Promise<TUser | undefined>
  /** Discards edits and restores the newest loaded/saved profile baseline. */
  reset: () => void
}

UsePromiseState

Extended promise state with actions, React's UsePromiseState.

interface UsePromiseState<T> {
  status: PromiseStatus
  value: T | null
  error: Error | null
  cancel: (message?: string) => void
  reset: () => void
}

UseRouterResult

What useRouter returns.

interface UseRouterResult {
  /** The current location. */
  location: Readable<RouteLocation>
  /** The current route's path parameters. */
  params: Readable<Record<string, string>>
  /** The current query parameters. */
  query: Readable<QueryParams>
  /** Navigates to a path. */
  navigate: Router['navigate']
  /** Navigates to a named route. */
  navigateTo: Router['navigateTo']
  /** Goes back one history entry. */
  back: Router['back']
  /** Goes forward one history entry. */
  forward: Router['forward']
  /** Whether a path is active (prefix, or exact with `exact`). */
  isActive: Router['isActive']
}

UseListRouteResult

What useListRoute returns: each list field as a readable store, the actions as plain functions.

interface UseListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** The current 1-indexed page. */
  page: Readable<number>
  /** The configured items per page. */
  pageSize: Readable<number>
  /** The zero-indexed item offset for an API request. */
  offset: Readable<number>
  /** The current URL filter values, including values supplied by path parameters. */
  filters: Readable<Record<Filter, string | undefined>>
  /** The matching view, or the configured fallback. */
  selection: Readable<Selection | undefined>
  /** The decoded current path parameters, also usable as API-only filters. */
  params: Readable<RouteParams>
  /** False while a protected selection is awaiting auth, signed out, or unavailable. */
  canLoad: Readable<boolean>
  /** Readiness for the current view; a public view always stays ready. */
  status: Readable<ListRouteResult<Filter, Selection>['status']>
  /** The sign-in destination while a signed-out protected view is being redirected. */
  redirectTo: Readable<string | undefined>
  /** Builds a real link target, preserving the pathname, unrelated query values and hash. */
  href: ListRouteResult<Filter, Selection>['href']
  /** Navigates atomically; location state is preserved unless options replace it. */
  navigate: ListRouteResult<Filter, Selection>['navigate']
  /** Changes only the page, retaining the current filters and view. */
  setPage: ListRouteResult<Filter, Selection>['setPage']
  /** Patches URL filters and returns to page one. */
  setFilters: ListRouteResult<Filter, Selection>['setFilters']
  /** Selects a configured view at page one. */
  select: ListRouteResult<Filter, Selection>['select']
}

UseSignupReturn

What useSignup returns.

interface UseSignupReturn<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /** The latest call's status. */
  status: Readable<UsePromiseState<AuthResult<T>>['status']>
  /** The latest call's resolved value. */
  value: Readable<UsePromiseState<AuthResult<T>>['value']>
  /** The latest call's rejection. */
  error: Readable<UsePromiseState<AuthResult<T>>['error']>
  /** Runs the signup. */
  signup: (data: RegisterData<TRegister>) => Promise<AuthResult<T>>
  /** Returns the tracker to idle. */
  reset: () => void
}

UseStorageValueOptions

Options for useStorageValue.

interface UseStorageValueOptions<T> {
  /**
   * Default value if key doesn't exist.
   */
  defaultValue?: T
  /**
   * Whether to sync across tabs/windows (if supported by storage provider).
   */
  sync?: boolean
}

UseStorageValueResult

Result of useStorageValue.

interface UseStorageValueResult<T> {
  /** The stored value, or the default while none is stored. */
  value: Readable<T | undefined>
  /** Persists the value; rejects when the provider refuses the write. */
  setValue: (value: T) => Promise<void>
  /** Removes the key and falls back to the default; rejects on failure. */
  removeValue: () => Promise<void>
  /** Whether the first read is still in flight. */
  loading: Readable<boolean>
  /** The failing read's or write's error. */
  error: Readable<Error | null>
}

UseStoragePreferenceOptions

Options for useStoragePreference.

interface UseStoragePreferenceOptions<T> {
  /**
   * Value reported until the provider supplies one. It is NEVER written to
   * storage: a default is a display fallback, not a decision the user made.
   */
  defaultValue?: T
}

UseStoragePreferenceResult

Result of useStoragePreference.

interface UseStoragePreferenceResult<T> {
  /** The persisted value, or `defaultValue` while none is known. */
  value: Readable<T | undefined>
  /**
   * Writes the value through the preference store: subscribers update
   * immediately and persistence is best-effort.
   */
  setValue: (next: T | ((previous: T | undefined) => T)) => void
  /** Removes the key through the preference store. */
  removeValue: () => void
  /**
   * `true` once the store has a definite answer — the synchronous snapshot on
   * a synchronous provider, or the hydration result on an asynchronous one.
   */
  ready: Readable<boolean>
}

UseStoreOptions

Options for useStore.

interface UseStoreOptions<T, S> {
  /** Selects part of the state. */
  selector?: (state: T) => S
  /** Compares two selected values; equal keeps the previous result. */
  equalityFn?: (a: S, b: S) => boolean
}

SelectingStoreOptions

Options for useStore that pick part of the store: a selector is required, so the selected type S always comes from it.

interface SelectingStoreOptions<T, S> extends UseStoreOptions<T, S> {
  /** Picks the value the hook returns from the store's state. */
  selector: (state: T) => S
}

UseThemeResult

What useTheme returns.

interface UseThemeResult {
  /** The current theme object. */
  theme: Readable<Theme>
  /** The current theme's name. */
  themeName: Readable<string>
  /** Switches the active theme by name. */
  setTheme: (name: string) => void
  /** Toggles light/dark (the provider's `toggleMode`, or an index cycle). */
  toggleTheme: () => void
  /** The current mode: 'light' or 'dark'. */
  mode: Readable<'light' | 'dark'>
}

UseTranslationResult

What useTranslation returns: the locale-reactive values as readable stores and the provider's functions as plain functions.

interface UseTranslationResult {
  /**
   * Translates a key in the active locale. A call made while markup, `$derived` or an
   * effect evaluates re-runs on every locale switch (like React's `t`, which is
   * rebuilt on every locale change), so `{t('key', {}, { defaultValue })}` needs no
   * store read beside it.
   */
  t: I18nProvider['t']
  /** The active locale code. */
  locale: Readable<string>
  /** Switches the active locale. */
  setLocale: I18nProvider['setLocale']
  /** The registered locales. */
  locales: Readable<ReturnType<I18nProvider['getLocales']>>
  /** Formats a number for the active locale. */
  formatNumber: I18nProvider['formatNumber']
  /** Formats a date for the active locale. */
  formatDate: I18nProvider['formatDate']
  /** The active locale's text direction. */
  direction: Readable<'ltr' | 'rtl'>
}

UseVerifyPaymentReturnOptions

Options for useVerifyPaymentReturn.

interface UseVerifyPaymentReturnOptions {
  /**
   * Provider name to verify with, when the return URL carries no `provider`
   * query parameter. Leave unset to verify only what the URL names.
   */
  provider?: string

  /** Set `false` to skip verification entirely (e.g. behind a feature flag). */
  enabled?: boolean

  /**
   * Remove the provider's query parameters from the address bar once the
   * purchase is verified, so a reload (or a shared link) cannot replay the
   * verification. Defaults to `true`.
   */
  cleanUrl?: boolean

  /** Called once, after the purchase verifies. */
  onVerified?: () => void

  /** Called when verification fails. */
  onError?: (error: Error) => void
}

UseVerifyPaymentReturnResult

State of the post-checkout verification.

interface UseVerifyPaymentReturnResult {
  /**
   * `idle` when this page load is not a checkout return (no transaction id in
   * the URL) or auth is still hydrating; `verifying` while the API call is in
   * flight; then `verified` or `failed`.
   */
  status: Readable<VerifyPaymentReturnStatus>

  /** `true` when the URL identifies a purchase to verify. */
  isReturn: Readable<boolean>

  /** The provider named by the URL (or the `provider` option). */
  provider: Readable<string | null>

  /** The provider transaction/session id read from the URL. */
  transactionId: Readable<string | null>

  /** Why verification failed, when it did. */
  error: Readable<Error | null>

  /** Re-run the verification — wire this to a retry button. */
  retry: () => void
}

UseVersionResult

Hook return type.

interface UseVersionResult {
  /** The provider's full state. */
  state: Readable<VersionState>
  /** Whether an update is available. */
  isUpdateAvailable: Readable<boolean>
  /** Whether a check is running. */
  isChecking: Readable<boolean>
  /** Whether a service worker waits to activate. */
  isServiceWorkerWaiting: Readable<boolean>
  /** The version an available update reports. */
  newVersion: Readable<string | undefined>
  /** Checks the provider for an update. */
  checkForUpdates: () => Promise<boolean>
  /** Applies an available update. */
  applyUpdate: (options?: { force?: boolean }) => void
  /** Hides an available update. */
  dismissUpdate: () => void
  /** Starts polling the provider for updates. */
  startPeriodicChecks: (options?: UpdateCheckOptions) => void
  /** Stops the polling. */
  stopPeriodicChecks: () => void
}

UseWorkspaceResult

Hook result for useWorkspace: the layout fields as readable stores and the layout actions as plain functions.

interface UseWorkspaceResult {
  /** The panel layout. */
  layout: Readable<WorkspaceLayout>
  /** The panel showing the keyboard focus, if any. */
  activePanel: Readable<PanelId | null>
  /** The panels collapsed. */
  collapsedPanels: Readable<Set<PanelId>>
  /** Shows or hides a panel. */
  togglePanel: (panelId: PanelId) => void
  /** Resizes a panel. */
  resizePanel: (panelId: PanelId, size: number) => void
  /** Focuses a panel. */
  setActivePanel: (panelId: PanelId) => void
  /** Restores the provider's default layout. */
  resetLayout: () => void
}

LinkProps

Props for Link. Every other anchor attribute (class, target, rel, aria-*, data-*, onclick) goes on the anchor.

interface LinkProps extends Omit<HTMLAnchorAttributes, 'href' | 'children'> {
  /**
   * Destination: an app path (`/settings?tab=billing#plan`) or a URL. An app path's `href` is the
   * one the router writes for it (`routerLinkHref`), base path included; a URL's is the URL as
   * written.
   */
  to: string
  /**
   * Replace the current history entry instead of pushing one. When omitted, a
   * link to the location already shown replaces it and any other link pushes,
   * as with react-router's `<Link>`.
   */
  replace?: boolean
  /** State stored with the new history entry (read back with `useLocation()`). */
  state?: unknown
  /** The link's content. */
  children?: Snippet
  /** The rendered anchor (`bind:ref`), as React's `ref` receives it. */
  ref?: HTMLAnchorElement | null
}

AsyncStateStore

Async state store.

interface AsyncStateStore<T> extends Writable<T> {
  setState: (value: T | ((prev: T) => T) | Promise<T | ((prev: T) => T)>) => void
  extendState: (
    partial:
      Partial<T> | ((prev: T) => Partial<T>) | Promise<Partial<T> | ((prev: T) => Partial<T>)>,
  ) => void
}

OAuthOptions

OAuth configuration options.

interface OAuthOptions {
  /** Base URL for the API server (e.g. `https://api.example.com`). */
  baseURL?: string
  /** List of supported OAuth provider names (e.g. `['google', 'github']`). */
  oauthProviders?: string[]
  /** Path prefix for OAuth initiation routes. Defaults to `/oauth`. */
  oauthEndpoint?: string
  /** Path for the OAuth login POST endpoint. Defaults to `/users/log-in/oauth`. */
  loginEndpoint?: string
  /** Callback fired after a successful OAuth login. */
  onSuccess?: () => void
  /** Callback fired with an error message when the OAuth login fails. */
  onError?: (error: string) => void
  /**
   * Explicit auth client used to establish the session after the callback
   * exchange. Defaults to the client in Svelte context (only resolvable when
   * called during component initialization) — pass one explicitly for
   * callers/tests outside a component/context.
   */
  authClient?: AuthClient<unknown>
}

OAuthHelpers

OAuth helpers returned by createOAuthHelpers.

interface OAuthHelpers {
  /** Readable store of available OAuth provider names. */
  providers: Readable<string[]>
  /** Builds the OAuth initiation URL for a provider. */
  getOAuthUrl: (provider: string) => string
  /** Full-page redirect to the provider's OAuth initiation endpoint. */
  redirect: (provider: string) => void
  /**
   * Handles an OAuth callback: when the current URL carries a `code` param and
   * a provider was stashed by `redirect`, exchanges the code for a
   * session. A guarded no-op otherwise. Runs automatically when
   * `createOAuthHelpers` is called in a browser; exposed for manual
   * invocation (e.g. tests or custom callback screens).
   */
  handleCallback: () => Promise<void>
}

PasswordResetStores

Password reset stores.

interface PasswordResetStores {
  request: Readable<PromiseState<void>> & {
    call: (data: PasswordResetRequest) => Promise<void>
    cancel: (message?: string) => void
    reset: () => void
  }
  confirm: Readable<PromiseState<void>> & {
    call: (data: PasswordResetConfirm) => Promise<void>
    cancel: (message?: string) => void
    reset: () => void
  }
  resetAll: () => void
}

PromiseStore

Promise store with action methods.

interface PromiseStore<T, A extends unknown[] = unknown[]> extends Readable<PromiseState<T>> {
  call: (...args: A) => Promise<T>
  cancel: (message?: string) => void
  reset: () => void
}

MoleculeConfig

Configuration for molecule Svelte context.

interface MoleculeConfig {
  state?: StateProvider
  auth?: AuthClient<unknown>
  theme?: ThemeProvider
  router?: Router
  i18n?: I18nProvider
  http?: HttpClient
  storage?: StorageProvider
  logger?: LoggerProvider
  /** The IDE workspace provider useWorkspace and useWorkspaceProvider use. */
  workspace?: WorkspaceProvider
  /** The code editor provider useEditor and useEditorProvider use. */
  editor?: EditorProvider
  /** The live preview provider usePreview and usePreviewProvider use. */
  preview?: PreviewProvider
}

SessionReadyProps

Props for the SessionReady component: its children snippet renders once the auth client has decided the session, fallback until then.

interface SessionReadyProps {
  /** What renders once the initial restore settles — signed in, signed out, or unavailable. */
  children?: Snippet
  /** What renders while the session restore is still undecided; default nothing. */
  fallback?: Snippet
}

ProviderProps

What every provider component takes besides its service: the tree that reads it, as React's children (a snippet here).

interface ProviderProps {
  /** The tree that reads the provided service. */
  children?: Snippet
}

StateProviderProps

Props for the StateProvider component.

interface StateProviderProps extends ProviderProps {
  provider: StateProvider
}

AuthProviderProps

Props for the AuthProvider component.

interface AuthProviderProps<T = unknown> extends ProviderProps {
  client: AuthClient<T>
  /** Wait for initial session restoration by default. Set false for a deliberately ungated shell or synchronous SSR. */
  awaitSession?: boolean
  /** Content shown while the initial session status is loading; default nothing. */
  sessionFallback?: Snippet
}

ThemeProviderProps

Props for the ThemeProvider component.

interface ThemeProviderProps extends ProviderProps {
  provider: ThemeProvider
  /**
   * Not read: the theme a page starts on comes from the theme provider itself (`defaultTheme` and the
   * saved choice in `@molecule/app-theme-css-variables`), and setting one here would overwrite a
   * visitor's saved theme on every load.
   *
   * @deprecated Ignored. Pass `defaultTheme` to the theme provider (`createCSSVariablesThemeProvider({ defaultTheme })`) instead.
   */
  initialTheme?: string
}

RouterProviderProps

Props for the RouterProvider component.

interface RouterProviderProps extends ProviderProps {
  router: Router
  /**
   * The component that renders the matched child route where a layout or guard puts it, so
   * `<RoutedView />` works under any routing bond. A routing bond passes it; leave it out when
   * the bond has none (SvelteKit gives a layout its page as `children`), and `<RoutedView />`
   * then throws an error saying so.
   */
  routedView?: Component
}

I18nProviderProps

Props for the I18nProvider component.

interface I18nProviderProps extends ProviderProps {
  provider: I18nProvider
}

HttpProviderProps

Props for the HttpProvider component.

interface HttpProviderProps extends ProviderProps {
  client: HttpClient
}

StorageProviderProps

Props for the StorageProvider component.

interface StorageProviderProps extends ProviderProps {
  provider: StorageProvider
}

LoggerProviderProps

Props for the LoggerProvider component.

interface LoggerProviderProps extends ProviderProps {
  provider: LoggerProvider
}

WorkspaceProviderProps

Props for the WorkspaceProvider component.

interface WorkspaceProviderProps extends ProviderProps {
  provider: WorkspaceProvider
}

EditorProviderProps

Props for the EditorProvider component.

interface EditorProviderProps extends ProviderProps {
  provider: EditorProvider
}

PreviewProviderProps

Props for the PreviewProvider component.

interface PreviewProviderProps extends ProviderProps {
  provider: PreviewProvider
}

MoleculeProviderProps

Props for the MoleculeProvider component: each service is optional, and only the services passed are provided (state falls back to the bonded state provider).

interface MoleculeProviderProps extends ProviderProps, MoleculeConfig {
  /**
   * Render the app only once `auth` leaves its initial loading status (`SessionReadyProps`). Defaults to true.
   * With the bundled JWT client, a stored token AND cached user restore synchronously.
   * Token-only and cookie-only sessions need an asynchronous current-user request;
   * until it answers `useAuth().user` is `null` — a public page's signed-in action
   * (`if (!$user) return`, a redirect to `/login`) then treats a signed-in visitor as signed out.
   * When restoration succeeds, every page's first render reads the restored user. An
   * `'unavailable'` session also renders, but remains unconfirmed and may have a null user.
   * A visitor with no session candidate settles synchronously without a request.
   * Ignored without `auth`.
   */
  awaitSession?: boolean
  /** Rendered instead of the app while `MoleculeProviderProps.awaitSession` waits; default nothing. */
  sessionFallback?: Snippet
}

HttpState

State for async HTTP operations.

interface HttpState<T> {
  data: T | null
  loading: boolean
  error: Error | null
}

StorageValueState

State for async storage values.

interface StorageValueState<T> {
  value: T | undefined
  loading: boolean
  error: Error | null
}

Types

RouteParams

URL path parameter key-value map extracted from dynamic route segments (e.g. { id: '123' }).

type RouteParams = Record<string, string>

QueryParams

URL query string parameter map (single values or arrays for repeated keys).

type QueryParams = Record<string, string | string[] | undefined>

MaybeReadable

A plain value or a readable store of one (a store of undefined stands for an omitted argument). Hooks read the current value when they use it and follow changes for as long as the component lives.

type MaybeReadable<T> = T | Readable<T>

AsyncSetState

Async-capable setState function.

type AsyncSetState<T> = (
  value: T | ((prev: T) => T) | Promise<T | ((prev: T) => T)>,
) => Promise<void>
  • T — The state type.

AsyncExtendState

Async-capable extendState function for partial updates.

type AsyncExtendState<T> = (
  partial: Partial<T> | ((prev: T) => Partial<T>) | Promise<Partial<T> | ((prev: T) => Partial<T>)>,
) => Promise<void>
  • T — The state type.

UseAsyncStateStore

The store useAsyncState returns: the current [state, setState, extendState] tuple.

type UseAsyncStateStore<T> = Readable<readonly [T, AsyncSetState<T>, AsyncExtendState<T>]>

UseCapacitorAppResult

Hook return type.

type UseCapacitorAppResult = {
  /** Whether the app is fully initialized. */
  ready: Readable<boolean>
  /** Whether device ready has fired. */
  deviceReady: Readable<boolean>
  /** Whether push notifications are initialized. */
  pushReady: Readable<boolean>
  /** The initialization error, if any. */
  error: Readable<Error | null>
} & {
  /** Runs the coordinator's initialization again. */
  initialize: () => Promise<void>
}

UseChangePasswordResult (deprecated)

Deprecated: Renamed to UseChangePasswordReturn, @molecule/app-react's name for it.

The former name of UseChangePasswordReturn.

type UseChangePasswordResult = UseChangePasswordReturn

UseLoginResult (deprecated)

Deprecated: Renamed to UseLoginReturn, @molecule/app-react's name for it.

The former name of UseLoginReturn.

type UseLoginResult<T = unknown> = UseLoginReturn<T>

UsePasswordResetResult (deprecated)

Deprecated: Renamed to UsePasswordResetReturn, @molecule/app-react's name for it.

The former name of UsePasswordResetReturn.

type UsePasswordResetResult = UsePasswordResetReturn

UsePromiseStore

The store usePromise returns: the current [state, call] tuple.

type UsePromiseStore<T, A extends unknown[]> = Readable<
  readonly [UsePromiseState<T>, (...args: A) => Promise<T>]
>

UseConsumedSearchParamStore

The store useConsumedSearchParam returns: the current [value, set] tuple.

type UseConsumedSearchParamStore = Readable<readonly [string, (value: string) => void]>

UseSignupResult (deprecated)

Deprecated: Renamed to UseSignupReturn, @molecule/app-react's name for it.

The former name of UseSignupReturn.

type UseSignupResult<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> = UseSignupReturn<T, TRegister>

UseTShorthandOptions

Options for the shorthand form of UseTFunction: the fallback text is passed positionally, so only count remains here.

type UseTShorthandOptions = Omit<TranslateOptions, 'defaultValue'>

UseTFunction

Translation function returned by useT().

Two compatible call forms:

  • t(key, values?, options?) — the provider's signature.
  • t(key, fallback, options?) — a string second argument is the inline English defaultValue, with optional count for pluralization.
type UseTFunction = TranslateFunctionWithFallback

VerifyPaymentReturnStatus

How far the return-page verification has got.

type VerifyPaymentReturnStatus = 'idle' | 'verifying' | 'verified' | 'failed'

CapacitorAppStore

Return type for the Capacitor app store.

type CapacitorAppStore = Readable<CapacitorAppState> & {
  initialize: () => Promise<void>
}

ChangePasswordStore

Change password store type.

type ChangePasswordStore = PromiseStore<void, [string, string]>

LoginStore

Login store type.

type LoginStore<T = unknown> = PromiseStore<AuthResult<T>, [LoginCredentials]>

SignupStore

Signup store type.

type SignupStore<T = unknown> = PromiseStore<AuthResult<T>, [RegisterData]>

Functions

contentNodes(node)

The children of a node that render something: elements, and text nodes with text. Comments and empty text nodes are Svelte's own anchors (and other components' placeholders), not content.

function contentNodes(node: Node): ChildNode[]
  • node — The node whose children are read.

Returns: Those children, in order.

isContentNode(node)

Whether one node renders something: an element, or a text node with text. Comments and empty text nodes are Svelte's own anchors (and other components' placeholders), not content.

function isContentNode(node: Node): boolean
  • node — The node.

Returns: True when it renders something.

rendersContent(node)

Whether a node's children render anything (see contentNodes). A Svelte component cannot tell from a snippet's value whether it renders anything ({#each} over no rows, {#if false}), so a component that renders a wrapper only while its content has something to show, as React's slot(children) !== undefined && <div>…</div> does, asks the rendered DOM instead (see PresentWhileContent).

function rendersContent(node: Node): boolean
  • node — The node whose children are read.

Returns: True when one of them renders something.

setMoleculeContext(config)

Set all molecule providers in Svelte context.

Call this in your root layout/component. Only the services passed are set, except state, which falls back to the state provider bonded under @molecule/app-state (as MoleculeProvider does), so useStore() works without a state option. To hold the app until the session is decided, render MoleculeProvider (its awaitSession) or SessionReady instead.

function setMoleculeContext(config: MoleculeConfig): void
  • config — Provider instances to register (state, auth, theme, router, i18n, http, storage, logger, workspace, editor, preview).

setStateContext(provider)

Sets the state context.

function setStateContext(provider: StateProvider): void
  • provider — The state provider to store in Svelte context.

setAuthContext(client)

Sets the auth context.

function setAuthContext<T>(client: AuthClient<T>): void
  • client — The auth client to store in Svelte context.

setThemeContext(provider)

Sets the theme context.

function setThemeContext(provider: ThemeProvider): void
  • provider — The theme provider to store in Svelte context.

setRouterContext(router, options)

Sets the router context.

function setRouterContext(router: Router, options?: { routedView?: Component }): void
  • router — The router instance to store in Svelte context.
  • options — From a routing bond: its routed view (see RoutedView). Given, it is set too (null without routedView).
  • options.routedView — The component that renders the matched child route.

setI18nContext(provider)

Sets the i18n context.

function setI18nContext(provider: I18nProvider): void
  • provider — The i18n provider to store in Svelte context.

setHttpContext(client)

Sets the HTTP context.

function setHttpContext(client: HttpClient): void
  • client — The HTTP client to store in Svelte context.

setStorageContext(provider)

Sets the storage context.

function setStorageContext(provider: StorageProvider): void
  • provider — The storage provider to store in Svelte context.

setLoggerContext(provider)

Sets the logger context.

function setLoggerContext(provider: LoggerProvider): void
  • provider — The logger provider to store in Svelte context.

setWorkspaceContext(provider)

Sets the IDE workspace context.

function setWorkspaceContext(provider: WorkspaceProvider): void
  • provider — The workspace provider to store in Svelte context.

setEditorContext(provider)

Sets the code editor context.

function setEditorContext(provider: EditorProvider): void
  • provider — The editor provider to store in Svelte context.

setPreviewContext(provider)

Sets the live preview context.

function setPreviewContext(provider: PreviewProvider): void
  • provider — The preview provider to store in Svelte context.

getStateProvider()

Gets the state provider from Svelte context.

function getStateProvider(): StateProvider

Returns: The state provider instance.

getAuthClient()

Gets the auth client from Svelte context.

function getAuthClient<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): AuthClient<T, TRegister>

Returns: The auth client instance.

getThemeProvider()

Gets the theme provider from Svelte context.

function getThemeProvider(): ThemeProvider

Returns: The theme provider instance.

getRouter()

Gets the router from Svelte context.

function getRouter(): Router

Returns: The router instance.

getI18nProvider()

Gets the i18n provider from Svelte context.

function getI18nProvider(): I18nProvider

Returns: The i18n provider instance.

getHttpClient()

Gets the HTTP client from Svelte context.

function getHttpClient(): HttpClient

Returns: The HTTP client instance.

getStorageProvider()

Gets the storage provider from Svelte context.

function getStorageProvider(): StorageProvider

Returns: The storage provider instance.

getLoggerProvider()

Gets the logger provider from Svelte context.

function getLoggerProvider(): LoggerProvider

Returns: The logger provider instance.

useWorkspaceProvider()

Gets the IDE workspace provider from Svelte context (setMoleculeContext({ workspace })).

function useWorkspaceProvider(): WorkspaceProvider

Returns: The workspace provider instance.

useEditorProvider()

Gets the code editor provider from Svelte context (setMoleculeContext({ editor })).

function useEditorProvider(): EditorProvider

Returns: The editor provider instance.

usePreviewProvider()

Gets the live preview provider from Svelte context (setMoleculeContext({ preview })).

function usePreviewProvider(): PreviewProvider

Returns: The preview provider instance.

useAuthClient(T, TRegister)

Gets the auth client from Svelte context under the React hook's name (setMoleculeContext({ auth })).

function useAuthClient<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): AuthClient<T, TRegister>
  • T — The user profile the API returns.
  • TRegister — The app's own registration fields.

Returns: The auth client instance.

useI18nProvider()

Gets the i18n provider: the one the nearest setMoleculeContext({ i18n }) supplies, otherwise the bonded @molecule/app-i18n provider, which is the one the static t reads — React's useI18nProvider contract. A component can therefore translate through useTranslation wherever the static t works, and it re-renders when the locale changes.

function useI18nProvider(): I18nProvider

Returns: The i18n provider from context, or the bonded provider.

useThemeProvider()

Gets the theme provider from Svelte context under the React hook's name.

function useThemeProvider(): ThemeProvider

Returns: The theme provider instance.

useRouterInstance()

Gets the router from Svelte context under the React hook's name.

function useRouterInstance(): Router

Returns: The router instance.

useLinkRouter(path)

The router a link navigates through, under React's hook name: the router set in context, or null for a URL outside the app when none is. The browser, or on a device the URL handler, opens such a URL, so a link to it renders in an app with no router (a widget, a static page). A link to an app path still fails without one: that is how an app that forgot to mount its router finds out.

Link uses it. With a destination it answers for that one and follows it while the component lives. Without one (the destination is a $state prop of a runes component, which is no store) it returns a function to call with the destination wherever it is known; call it during component initialisation, which reads the context once.

function useLinkRouter(path: MaybeReadable<string>): Readable<Router | null>
  • path — The link's destination: an app path or a URL, or a readable store of one.

Returns: A readable store of the router the link navigates through, or null for a URL outside the app with no router in context.

useHttpClient()

Gets the HTTP client from Svelte context under the React hook's name.

function useHttpClient(): HttpClient

Returns: The HTTP client instance.

useStorageProvider()

Gets the storage provider from Svelte context under the React hook's name.

function useStorageProvider(): StorageProvider

Returns: The storage provider instance.

useLoggerProvider()

Gets the logger provider from Svelte context under the React hook's name.

function useLoggerProvider(): LoggerProvider

Returns: The logger provider instance.

useStateProvider()

Gets the state provider from Svelte context under the React hook's name.

Only hooks that read the context call this; useStore(store) takes its store as an argument and works with no provider at all.

function useStateProvider(): StateProvider

Returns: The state provider instance.

isReadable(value)

Whether a value is a readable store. A molecule store (@molecule/app-state's Store: it has getState AND subscribe) is a VALUE, never a source — useStore takes the store itself as its argument.

function isReadable(value: unknown): value is Readable<unknown>
  • value — A hook argument: a plain value or a store.

Returns: True for a Svelte readable store.

toReadable(value)

The readable-store view of a hook argument: the store itself when it is one, a constant store of the plain value otherwise.

function toReadable<T>(value: MaybeReadable<T>): Readable<T>
  • value — A plain value or a store of one.

Returns: A readable store of the value.

useAsyncState(initialState)

State that accepts Promises and partial updates, React's useAsyncState in Svelte's idiom: a readable store of the [state, setState, extendState] tuple.

Like React's, this has NO latest-wins guard: a promise that settles after a newer synchronous set overwrites it — whatever settles last wins. Rejections of resolved promises are silently swallowed (React's deliberate behavior), leaving the previous state in place.

function useAsyncState<T>(initialState: T): UseAsyncStateStore<T>
  • initialState — Initial state value.

Returns: A readable store of the [state, setState, extendState] tuple.

useAuth(options)

Authentication state and actions, React's useAuth in Svelte's idiom: call it during component init under setMoleculeContext({ auth }).

status === 'loading' is undecided: wait for it and redirect only on status === 'unauthenticated'. 'unavailable' keeps the session candidate (and may keep a cached user) for retry; a restore failure other than 401/403 never signs out. Save profile edits with updateProfile(patch); an app-owned mutation instead passes its canonical response to setUser. For a sign-in the app itself runs, call setSession({ accessToken, user }).

function useAuth<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(options?: MaybeReadable<UseAuthOptions | undefined>): UseAuthResult<T, TRegister>
  • options — Hook options (autoRefresh), or a store of them: setting autoRefresh later probes on the same component, the way React's re-render re-runs its effect.

Returns: Auth state as stores and the actions as functions.

useUser(T)

The authenticated user, React's useUser in Svelte's idiom: a readable store of the cached profile (or null).

function useUser<T = UserProfile>(): Readable<T | null>
  • T — The user profile the API returns.

Returns: A readable store of the authenticated user or null.

useIsAuthenticated()

Whether a session is authenticated, React's useIsAuthenticated in Svelte's idiom.

function useIsAuthenticated(): Readable<boolean>

Returns: A readable store of whether a session exists.

useCapacitorApp(options)

Capacitor app initialization state and actions, React's useCapacitorApp in Svelte's idiom: called during component init, one coordinator per hook instance whose state fields are readable stores and whose initialize is a plain function.

Creates the CapacitorApp coordinator during init, subscribes its state and auto-initializes (the way React's mount effect does); the component's destroy unsubscribes and calls destroy(), releasing the coordinator's deep-link subscription. Init errors land in the error store through the coordinator's own state, so the auto-init rejection is swallowed there.

function useCapacitorApp(options?: CapacitorAppOptions): UseCapacitorAppResult
  • options — Capacitor app configuration options

Returns: Current app state stores and an initialize function for manual re-initialization

useChangePassword()

Password change with async state tracking, React's useChangePassword in Svelte's idiom: call it during component init under setMoleculeContext({ auth }). There is no value field — the call resolves void.

function useChangePassword(): UseChangePasswordReturn

Returns: Change-password state as stores and the action.

useDevice()

Device information and utility methods, React's useDevice in Svelte's idiom: called during component init; device info is static, so the result is a plain object (nothing reactive).

Uses module-level getProvider() — device info is a singleton, not context-provided.

function useDevice(): UseDeviceResult

Returns: Device information and utility methods.

useEditor()

Code editor management, React's useEditor in Svelte's idiom: call it during component init under setMoleculeContext({ editor }).

tabs and activeFile always come from the provider's own tab list: activeFile is the path of the tab marked isActive, or null when no tab is. They are read at mount (tabs opened before the component mounted show at once), on every provider change event, and after each action that changes the tab list (openFile, closeFile, setActiveTab, openDiff, closeDiff, pinTab).

function useEditor(): UseEditorResult

Returns: Editor state stores and controls.

useForm(options)

Hook for form state management, React's useForm in Svelte's idiom: call it during component init (no provider needed — the controller comes from the bonded forms provider).

Creates its controller through the bonded forms provider, so an app wires a form library once (setProvider from @molecule/app-forms) and every form picks it up. Passing createForm overrides that for one form. When the values option changes by content, it becomes the new baseline; resetOptions.keepDirtyValues retains edited fields while pristine fields take the loaded values. A changed resetKey starts a fresh form; fresh defaultValues without one leave the drafts alone.

The options may be a plain value or a readable store of one (a store holding undefined means the options were omitted): setting the store re-runs the work React's re-render does, on the same controller — a changed values object is applied (dirty fields kept by default) and a changed resetKey replaces the controller with a fresh one. Edits, touched fields and pending submits survive every other change.

function useForm<T extends FormValuesConstraint<T> = Record<string, unknown>>(
  options?: MaybeReadable<UseFormOptions<T> | undefined>,
): UseFormResult<T>
  • options — Form options (or a store of them). defaultValues, mode and the form-level validate are forwarded to the provider.

Returns: Form state stores and methods

useWatch(form, name)

Hook to watch a specific field value, React's useWatch in Svelte's idiom: a readable store of the field's current value.

function useWatch<T extends FormValuesConstraint<T>, K extends keyof T>(
  form: MaybeReadable<FormController<T>>,
  name: MaybeReadable<K>,
): Readable<T[K]>
  • form — Form controller, or a readable store of one
  • name — Field name to watch, or a readable store of one

Returns: A readable store of the current field value

useFieldState(form, name)

Hook to get field-level state, React's useFieldState in Svelte's idiom: a readable store of the field's state.

function useFieldState<T extends FormValuesConstraint<T>>(
  form: MaybeReadable<FormController<T>>,
  name: MaybeReadable<keyof T>,
): Readable<FieldState<T[keyof T]>>
  • form — Form controller, or a readable store of one
  • name — Field name, or a readable store of one

Returns: A readable store of the field state (value, error, touched, dirty, valid, validating)

useHttp(method, url, options)

HTTP requests with state management, React's useHttp in Svelte's idiom: call it during component init under setMoleculeContext({ http }).

Every argument may be a plain value or a readable store of one (a store holding undefined means the argument was omitted): method, url and the request options are read at the moment execute runs, so setting the url store retargets the next execute on the same component, the way React's re-render does. immediate is read on mount only — its request runs once per component even when the arguments change later.

The newest request owns the displayed state: an older response answering after a newer execute or reset cannot touch it (callbacks still report every request's own outcome). A failure resolves null — it never rejects to the caller. reset takes ownership too, so a request it superseded cannot repopulate the state.

function useHttp<T>(
  method: MaybeReadable<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'>,
  url: MaybeReadable<string>,
  options?: MaybeReadable<UseHttpOptions<T> | undefined>,
): UseHttpResult<T>
  • method — HTTP method (or a store of it).
  • url — Request URL (or a store of it).
  • options — Request options, read at call time (or a store of them).

Returns: Request state as stores and the controls.

useGet(url, options)

GET requests, React's useGet in Svelte's idiom.

function useGet<T>(
  url: MaybeReadable<string>,
  options?: MaybeReadable<UseHttpOptions<T> | undefined>,
): UseHttpResult<T>
  • url — Request URL to fetch from (or a store of it).
  • options — HTTP request options including callbacks and request config (or a store of them).

Returns: Request state as stores and the controls.

usePost(url, options)

POST requests, React's usePost in Svelte's idiom.

function usePost<T>(
  url: MaybeReadable<string>,
  options?: MaybeReadable<UseHttpOptions<T> | undefined>,
): UseHttpResult<T>
  • url — Request URL to post to (or a store of it).
  • options — HTTP request options including body data and callbacks (or a store of them).

Returns: Request state as stores and the controls.

usePut(url, options)

PUT requests, React's usePut in Svelte's idiom.

function usePut<T>(
  url: MaybeReadable<string>,
  options?: MaybeReadable<UseHttpOptions<T> | undefined>,
): UseHttpResult<T>
  • url — Request URL to send the PUT request to (or a store of it).
  • options — HTTP request options including the replacement body (or a store of them).

Returns: Request state as stores and the controls.

usePatch(url, options)

PATCH requests, React's usePatch in Svelte's idiom.

function usePatch<T>(
  url: MaybeReadable<string>,
  options?: MaybeReadable<UseHttpOptions<T> | undefined>,
): UseHttpResult<T>
  • url — Request URL to send the partial body to (or a store of it).
  • options — HTTP request options including the partial body (or a store of them).

Returns: Request state as stores and the controls.

useDelete(url, options)

DELETE requests, React's useDelete in Svelte's idiom.

function useDelete<T>(
  url: MaybeReadable<string>,
  options?: MaybeReadable<UseHttpOptions<T> | undefined>,
): UseHttpResult<T>
  • url — Request URL of the resource to delete (or a store of it).
  • options — HTTP request options including callbacks (or a store of them).

Returns: Request state as stores and the controls.

useLogger(name, config)

Gets a logger instance, React's useLogger in Svelte's idiom: called during component init under setMoleculeContext, it returns the logger itself (a plain object — there is nothing reactive in a logger).

function useLogger(name: string, config?: Partial<LoggerConfig>): Logger
  • name — Logger name (usually component or module name).
  • config — Optional logger configuration.

Returns: Logger instance.

useRootLogger()

Gets the root logger, React's useRootLogger in Svelte's idiom: called during component init under setMoleculeContext.

function useRootLogger(): Logger

Returns: Root logger instance.

useChildLogger(parentName, context)

Creates a child logger with additional context, React's useChildLogger in Svelte's idiom: called during component init under setMoleculeContext.

function useChildLogger(parentName: string, context: Record<string, unknown>): Logger
  • parentName — Parent logger name.
  • context — Additional context to include in logs.

Returns: Child logger instance.

useLogin(T)

Login with async state tracking, React's useLogin in Svelte's idiom: call it during component init under setMoleculeContext({ auth }).

Registration is available through const { register } = useAuth(); call register({ email, password, name }) to create an account. There is no separate useRegister hook; use usePromise(register) when a form needs the same pending/error tracking as this login hook.

function useLogin<T = unknown>(): UseLoginReturn<T>
  • T — The user profile the API returns.

Returns: Login state as stores and the action.

useOAuth(config)

OAuth authentication, React's useOAuth in Svelte's idiom: call it during component init under setMoleculeContext({ auth }). Reads OAuth configuration and provides helpers to build OAuth URLs and start a login (full-page or popup). Automatically handles OAuth callbacks by detecting code and state URL parameters and exchanging them for a session — and, when the callback is running inside a popup we opened, relaying the result to the opener instead.

The config may be a plain value or a readable store of one (a store holding undefined means no config): every field — the provider list, the URL pieces, the callbacks, the navigate option — is read at the moment it is used, so setting the store retargets the next getOAuthUrl/redirect/popup flow on the same component, the way React's re-render does. providers is React's string[], read live (see UseOAuthReturn.providers). The callback exchange, when it finds a code in the URL, runs once with the config the hook was called with.

function useOAuth(config?: MaybeReadable<UseOAuthConfig | undefined>): UseOAuthReturn
  • config — Optional OAuth configuration override (or a store of it).

Returns: OAuth helpers: providers, getOAuthUrl, redirect, and loginViaPopup.

useOptimisticToggle(options)

Owns the state and save ordering of a follow, favorite, star or subscription control while all markup stays in the app. Pass toggle straight to the click handler: it takes no argument and flips the value shown now. commit(desired) receives the value to SAVE, never the old one, and returns the server's boolean answer. Only the newest failure rolls the shown value back.

Saves run one at a time; clicks during a save coalesce to the newest desired value. Use pending for feedback, not to disable the control or drop a click. Mount it only after the record loads, key it by record identity, and keep it mounted through refetches. For a flag with a related count, use useOptimisticValue with both fields in one value.

function useOptimisticToggle(
  options: MaybeReadable<UseOptimisticToggleOptions>,
): UseOptimisticToggleResult
  • options — The server value, the save and an optional error callback (or a readable store of them: a new value syncs in while nothing is saving).

Returns: The value, pending and error state as readable stores, and the stable toggle.

useOptimisticValue(options)

A server-backed value — a favorite, follow, like or bookmark button, a rating, a quantity, a setting switch — that changes on the first render after a tap and is saved one change at a time, in order. See createOptimisticValue in @molecule/app-state, under React's hook name.

A new server value is taken only when it differs (by equals) from the one the hook last received, and only while nothing is being saved, so a refetch of older data never flips the button mid-save. The latest commit and onError are always used. Give the component a key per record, so one record's pending change never shows on another. Keep related fields, such as a favorite flag and its count, in the SAME value. Let commit reject on failure: a catch that returns old data hides the failure.

The options may be a plain value or a readable store of one: setting the store applies the new server value (and the new commit, equals and onError) on the same component, the way React's re-render does — the controller, and any save it is running, survive the change.

function useOptimisticValue<T>(
  options: MaybeReadable<OptimisticValueOptions<T>>,
): UseOptimisticValueResult<T>
  • options — The server's current value and how to save a change (or a store of them).

Returns: The value to render, whether a save is pending, the newest failure, and set/update.

usePasswordReset()

The password-reset flow with separate tracking for the request and confirm steps, React's usePasswordReset in Svelte's idiom: call it during component init under setMoleculeContext({ auth }).

function usePasswordReset(): UsePasswordResetReturn

Returns: Both steps' state as stores and their actions.

usePlatform()

Detected platform info plus the isPlatform helper, React's usePlatform in Svelte's idiom: called during component init; platform info is static, so the result is a plain object (nothing reactive).

Uses module-level functions — platform is a singleton, not context-provided.

function usePlatform(): UsePlatformResult

Returns: Platform information and utility methods.

usePreview()

Live preview management, React's usePreview in Svelte's idiom: call it during component init under setMoleculeContext({ preview }).

The state is a snapshot store over provider.subscribe, cached field-wise the way React's useSyncExternalStore snapshot is, so a provider that answers fresh objects does not publish a new snapshot per read.

function usePreview(): UsePreviewResult

Returns: Preview state store and controls.

useProfileForm(options)

Owns load → edit → submit → publish for the signed-in user's profile, React's useProfileForm in Svelte's idiom: call it during component init under setMoleculeContext({ auth }).

Same-account background updates refresh untouched fields but preserve dirty controls. Session ownership comes from the auth client, independently of mutable profile fields; an explicit getIdentity adds the caller's identity check. Submission snapshots the registered values before asynchronous validation, sends only changed fields through toPatch, and uses the auth client's configured updateProfile transport. The saved server response becomes the clean baseline; edits made while saving remain dirty. No request is made for a patch with no fields. A failed request retains the edits and shared user.

function useProfileForm<TUser, TValues extends FormValuesConstraint<TValues>>(
  options: UseProfileFormOptions<TUser, TValues>,
): UseProfileFormResult<TUser, TValues>
  • options — Controlled defaults, identity and wire adapters, optional cache/navigation callback.

Returns: Form state stores, typed control bindings, native submit binding and save error store.

usePromise(asyncFn)

Wraps an async function with state tracking, React's usePromise in Svelte's idiom.

For one UI action, pass $store[0].status === 'pending' to Button loading from @molecule/app-ui-svelte (or disable a native control). The control then refuses input while the request is pending and re-enables when the tracked call settles. Handle the returned promise's rejection; the hook also records the failure in state.error.

This hook tracks the latest call: it does not serialize invocations or cancel their network requests. An explicit reset/cancel changes the tracked state, so it is not proof that an outstanding request has stopped. Use an app-owned queue when every click must be accepted in order.

The result is a readable store of the [state, call] tuple (React's tuple shape): $store[0] is the current state, $store[1] the tracked function. A pending call keeps the PREVIOUS value; a rejection records the error (keeping the previous value) and rethrows to its caller; cancel(message?) marks the state rejected with new Error(message) — or no error when no message is given; reset() returns to idle.

function usePromise<T, A extends unknown[]>(
  asyncFn: (...args: A) => Promise<T>,
): UsePromiseStore<T, A>
  • asyncFn — The async function to wrap.

Returns: A readable store of the [state, wrappedFunction] tuple.

useRouter()

Routing state and navigation, React's useRouter in Svelte's idiom: call it during component init under setMoleculeContext({ router }).

function useRouter(): UseRouterResult

Returns: Router state as stores and the navigation methods.

useLocation()

The current location, React's useLocation in Svelte's idiom.

function useLocation(): Readable<RouteLocation>

Returns: A readable store of the current route location.

useParams(T)

The current route's path parameters, React's useParams in Svelte's idiom.

function useParams<T extends Record<string, string> = RouteParams>(): Readable<T>
  • T — The params record type.

Returns: A readable store of the route parameters.

useQuery(T)

The current query parameters, React's useQuery in Svelte's idiom.

function useQuery<T extends QueryParams = QueryParams>(): Readable<T>
  • T — The query record type.

Returns: A readable store of the query parameters.

useNavigate()

The navigate function, React's useNavigate in Svelte's idiom.

function useNavigate(): (path: string, options?: NavigateOptions) => void

Returns: A function that navigates to a path.

useIsActive(path, exact)

Whether a path is active, React's useIsActive in Svelte's idiom: a readable store that re-evaluates on every route change.

Both arguments may be a plain value or a readable store of one: the store re-evaluates when one changes (the way React's re-render re-reads its snapshot), so a navigation-driven nav link can take its path from a store.

function useIsActive(path: MaybeReadable<string>, exact?: MaybeReadable<boolean>): Readable<boolean>
  • path — The path to check (or a store of it).
  • exact — Whether to match exactly (default: false; or a store of it).

Returns: A readable store of whether the path is active.

useListRoute(options)

URL-backed pagination, filters and selected views, React's useListRoute in Svelte's idiom: the page, the filters and the view live in the URL only, so a reload, a shared link and Back all show the same list. Each list field is a readable store that follows the location, and the actions are plain functions, through whichever routing bond the app wired. Built on resolveListRoute from @molecule/app-routing, so every framework binding returns the same result.

A signed-out visit to a view with requiresAuth replaces the entry with options.auth.redirectTo, carrying state.returnTo; until auth is confirmed canLoad is false.

The options may be a plain value or a readable store of one (a store holding undefined means the default options): an auth status moving from loading to unauthenticated re-resolves the list — and performs the sign-in redirect — on the same component, the way React re-renders useListRoute.

function useListRoute<Filter extends string = string, Selection extends string = string>(
  options?: MaybeReadable<ListRouteOptions<Filter, Selection> | undefined>,
): UseListRouteResult<Filter, Selection>
  • options — Filter sources, view paths, pagination and optional auth readiness (or a store of them).

Returns: Each list field as a readable store, and its link builder and navigation actions.

useConsumedSearchParam(name)

Takes a one-time credential (a reset token, an OAuth code) out of the URL and keeps it in memory, React's useConsumedSearchParam in Svelte's idiom: a readable store of the [value, set] tuple, through whichever routing bond the app wired. The parameter is removed with a replace navigation that keeps the path, the hash, the other query values and the location state; the value survives re-renders and later query-only navigation, Back to an entry restores the value consumed there, and a new value arriving on the same mounted route is consumed too.

function useConsumedSearchParam(name: string): UseConsumedSearchParamStore
  • name — The query key to consume, for example token or code.

Returns: A readable store of the consumed value ('' before the parameter was ever present) and a setter (a form clears it after a successful submit).

useSignup(T, TRegister)

User registration with async state tracking, React's useSignup in Svelte's idiom: call it during component init under setMoleculeContext({ auth }).

function useSignup<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): UseSignupReturn<T, TRegister>
  • T — The user profile the API returns.
  • TRegister — The app's own registration fields.

Returns: Signup state as stores and the action.

useStorageValue(key, options)

One storage key as Svelte stores, React's useStorageValue in Svelte's idiom: call it during component init under setMoleculeContext({ storage }).

Both arguments may be a plain value or a readable store of one (a store holding undefined means the argument was omitted): setting the key store starts the new key over — its value is unknown until its read lands, so the default shows and loading is true, exactly as a fresh mount — while writes go to the key the hook holds at the moment they run. The latest defaultValue and sync always apply.

A read that started before a newer local write keeps that write's value (it still ends loading), and with sync an outside write reaches the hook through the provider's own subscription — so a non-browser backend (native, encrypted, memory) propagates the same way, not just the browser storage event.

function useStorageValue<T>(
  key: MaybeReadable<string>,
  options?: MaybeReadable<UseStorageValueOptions<T> | undefined>,
): UseStorageValueResult<T>
  • key — Storage key (or a store of it).
  • options — Hook options (or a store of them).

Returns: Storage value state (value, loading, error) and mutators (setValue, removeValue).

useStoragePreference(key, options)

Subscribes Svelte stores to ONE persisted preference, React's useStoragePreference in Svelte's idiom.

This is the component-side half of getPreferenceStore(): an init-time value is available immediately when the bonded provider can answer synchronously, and an asynchronous provider's hydration CONVERGES onto the same component without a remount. Ordering is the store's: a read that started before a newer write, remove or external change is discarded, so a slow hydration never overwrites an edit the user already made.

Both arguments may be a plain value or a readable store of one (a store holding undefined means the argument was omitted): setting the key store re-reads, re-subscribes and re-hydrates the new key on the same component (a null/undefined key is local state around the default and persists nothing), and writes go to the key the hook holds at the moment they run. The latest defaultValue always applies.

function useStoragePreference<T = unknown>(
  key: MaybeReadable<string | null | undefined>,
  options?: MaybeReadable<UseStoragePreferenceOptions<T> | undefined>,
): UseStoragePreferenceResult<T>
  • key — The storage key, or null when there is nothing to persist (or a store of either).
  • options — defaultValue, reported until the provider supplies one (or a store of them).

Returns: The current value, its mutators, and whether it is definite yet.

useStorage()

Storage operations without local state sync, React's useStorage in Svelte's idiom: plain passthroughs of the context provider.

function useStorage(): {
  get: <T>(key: string) => Promise<T | null>
  set: <T>(key: string, value: T) => Promise<void>
  remove: (key: string) => Promise<void>
  clear: () => Promise<void>
  keys: () => Promise<string[]>
}

Returns: Storage operation methods

useStore(store, options)

Subscribes a store with an optional selector and equality function, React's useStore in Svelte's idiom: a readable store of the selected value.

The store argument may be the store itself (a molecule store has getState AND subscribe, and is always a VALUE, never a source) or a readable store OF a store: setting it re-subscribes to the new store and re-reads its snapshot on the same component, the way React's re-render does. The options (or a store of them) are read whenever the snapshot is.

The store is the argument, so this hook needs NO state provider: it reads store.getState() and subscribes with store.subscribe(). When equalityFn says a new selected value equals the previous one, the previous result is kept (the same value, not a fresh object).

The selector and equality function run with the same cadence as React's useSyncExternalStore binding, because React re-reads its snapshot around every render; useSyncExternalStore documents the cadence.

function useStore<T>(
  store: MaybeReadable<Store<T>>,
  options?: MaybeReadable<UseStoreOptions<T, T> | undefined>,
): Readable<T>
  • store — The store to subscribe to (or a readable store of it).
  • options — Hook options (selector, equalityFn), or a store of them.

Returns: A readable store of the selected state.

useSetStore(store)

The store's setState function, React's useSetStore in Svelte's idiom.

function useSetStore<T>(store: Store<T>): Store<T>['setState']
  • store — The store to get setState from.

Returns: The store's setState function.

useStoreAction(store, action)

A bound action for a store, React's useStoreAction in Svelte's idiom.

function useStoreAction<T, Args extends unknown[], R>(
  store: Store<T>,
  action: (setState: Store<T>['setState'], getState: Store<T>['getState']) => (...args: Args) => R,
): (...args: Args) => R
  • store — The store to bind to.
  • action — The action function that receives setState and getState.

Returns: A bound action function.

useTheme()

Theme state and actions, React's useTheme in Svelte's idiom: call it during component init under setMoleculeContext({ theme }).

function useTheme(): UseThemeResult

Returns: Theme state as stores and the actions as functions.

useCurrentTheme()

The current theme object, React's useCurrentTheme in Svelte's idiom.

function useCurrentTheme(): Readable<Theme>

Returns: A readable store of the current theme.

useThemeMode()

The current theme mode, React's useThemeMode in Svelte's idiom.

function useThemeMode(): Readable<'light' | 'dark'>

Returns: A readable store of 'light' or 'dark'.

useThemeColors()

The current theme's colors, React's useThemeColors in Svelte's idiom.

function useThemeColors(): Readable<Theme['colors']>

Returns: A readable store of the current theme's colors.

useRichTranslation()

Reads rich catalog messages from the active provider. Call the returned translation function in render so it follows locale and catalog changes.

function useRichTranslation(): RichTranslateFunction

Returns: The locale-reactive rich translation function.

useTranslation()

Internationalization, React's useTranslation in Svelte's idiom: call it during component init under setMoleculeContext({ i18n }).

function useTranslation(): UseTranslationResult

Returns: The translation function and the locale values as stores.

useT()

The translation function alone, React's useT in Svelte's idiom.

Call it in either of two compatible forms:

  • t(key, values?, options?) — the provider signature.
  • t(key, fallback, options?) — a string second argument is the inline English defaultValue.
function useT(): UseTFunction

Returns: The translation function.

useLocale()

The current locale, React's useLocale in Svelte's idiom.

function useLocale(): Readable<string>

Returns: A readable store of the locale code.

useDirection()

The text direction, React's useDirection in Svelte's idiom.

function useDirection(): Readable<'ltr' | 'rtl'>

Returns: A readable store of 'ltr' or 'rtl'.

useI18nError(error)

Translates an error at render time so the displayed message updates automatically when the locale changes, React's useI18nError in Svelte's idiom: a readable store of the translated message.

Always use this hook to display errors — reading error.message directly leaves stale text after a locale switch. If error is an I18nError (thrown via throw new I18nError(key)), its key is translated using the current locale. For plain Error instances, error.message is returned unchanged.

The error may be a plain value or a readable store of one: setting the store replaces the message on the same component, the way React's re-render does.

function useI18nError(error: MaybeReadable<Error | null | undefined>): Readable<string | null>
  • error — The error to translate, or null/undefined (or a store of either).

Returns: A readable store of the translated error string, or null.

useVerifyPaymentReturn(options)

Reads the payment id a provider put in the return URL and confirms the purchase server-side with POST /users/:id/verify-payment/:provider, React's useVerifyPaymentReturn in Svelte's idiom: call it during component init under setMoleculeContext({ auth, http }).

This is why a hosted checkout returns the buyer to the APP and not the API. Session cookies are host-only on the app's origin, so a top-level redirect from the provider straight to an authenticated API callback on a different host arrives with NO credentials — it answers 401 and the paid plan is never granted. The request this hook makes is a same-origin call from a loaded app page, so the credentials apply. It waits for auth to hydrate first: after the redirect the page is a cold load, and the session is restored from the httpOnly cookie via GET /users/me.

Verification is idempotent server-side (first-claim-wins on the transaction), and this hook additionally runs at most once per transaction id per page. Safe on pages that are also reached normally: with no id in the URL it stays idle and issues no request.

If the component unmounts while the request is in flight, a verified purchase still refreshes the cached profile (the plan is paid for), but the hook calls neither onVerified nor onError and leaves the URL alone: by then the address may belong to another page. A failure after unmount is logged instead.

function useVerifyPaymentReturn(
  options?: UseVerifyPaymentReturnOptions,
): UseVerifyPaymentReturnResult
  • options — Provider fallback + lifecycle callbacks (see UseVerifyPaymentReturnOptions).

Returns: The verification state (see UseVerifyPaymentReturnResult).

useVersion()

Version state and update actions, React's useVersion in Svelte's idiom: a readable store per value field and plain functions for the actions, created during component init.

Uses module-level getProvider() — version is a singleton, not context-provided.

function useVersion(): UseVersionResult

Returns: Version state and action methods.

useWorkspace()

IDE workspace layout management, React's useWorkspace in Svelte's idiom: call it during component init under setMoleculeContext({ workspace }).

The state is a snapshot store over provider.subscribe, cached the way React's useSyncExternalStore snapshot is (a provider without getState fabricates the non-layout fields from getLayout() until its first emission supplies the real ones).

function useWorkspace(): UseWorkspaceResult

Returns: The workspace state stores and management methods.

createAsyncState(initialValue)

Creates a writable store with async-capable setState and extendState.

function createAsyncState<T>(initialValue: T): AsyncStateStore<T>
  • initialValue — The initial state value

Returns: The created instance.

createAuthStores()

Create auth stores from the auth client in context.

function createAuthStores<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): AuthStores<T, TRegister> & {
  error: Readable<string | null>
}

Returns: Auth stores and actions

createAuthStoresFromClient(client)

Create auth stores from a specific auth client.

Use this when you don't want to use context.

function createAuthStoresFromClient<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(client: AuthClient<T, TRegister>): AuthStores<T, TRegister>
  • client — Auth client

Returns: Auth stores and actions

createCapacitorAppStore(options)

Create a Svelte store wrapping the Capacitor app coordinator.

Creates a CapacitorApp instance, subscribes to state changes, and auto-initializes. The returned store is readable and also exposes an initialize method for manual re-initialization.

function createCapacitorAppStore(options?: CapacitorAppOptions): CapacitorAppStore
  • options — Capacitor app options

Returns: A readable store of CapacitorAppState with an initialize method

createChangePasswordStore()

Creates a change password store with async state tracking.

function createChangePasswordStore(): ChangePasswordStore

Returns: Change password promise store

createDeviceStores()

Create device stores from the module-level device provider.

Device information is static (no reactive subscription needed), so this returns plain values rather than Svelte stores.

function createDeviceStores(): {
  deviceInfo: DeviceInfo
  screenInfo: ScreenInfo
  hardwareInfo: HardwareInfo
  featureSupport: FeatureSupport
  supports: (feature: keyof FeatureSupport) => boolean
  isOnline: () => boolean
  isStandalone: () => boolean
  language: string
  languages: string[]
}

Returns: Device information and utility functions

createFormStores(provider, options)

Create form stores from a form provider and options.

function createFormStores<T extends FormValuesConstraint<T>>(
  provider: FormProvider,
  options: SvelteFormOptions<T>,
): FormStores<T>
  • provider — Form provider instance
  • options — Narrowed creation options; values and resetOptions are not accepted.

Returns: Form stores and actions, including updateValues(values, { keepDirtyValues }) for explicit late-record delivery. keepDirtyValues defaults to false; true retains edited fields while pristine fields take the delivered record.

createFieldStore(controller, name)

Create a readable store that tracks a single field's state.

function createFieldStore<T extends FormValuesConstraint<T>, K extends keyof T>(
  controller: FormController<T>,
  name: K,
): Readable<FieldState<T[K]>>
  • controller — Form controller
  • name — Field name to track

Returns: Readable store of the field state

createWatchStore(controller, name)

Create a readable store that tracks a single field's value.

function createWatchStore<T extends FormValuesConstraint<T>, K extends keyof T>(
  controller: FormController<T>,
  name: K,
): Readable<T[K]>
  • controller — Form controller
  • name — Field name to watch

Returns: Readable store of the field value

createHttpStore(method, url, config)

Create an HTTP request store.

function createHttpStore<T>(
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
  url: string,
  config?: RequestConfig,
): HttpStore<T>
  • method — HTTP method
  • url — Request URL
  • config — Request configuration

Returns: Store with state and actions

createGetStore(url, config)

Creates a GET request store.

function createGetStore<T>(url: string, config?: RequestConfig): HttpStore<T>
  • url — The request endpoint URL.
  • config — Optional request configuration such as headers or params.

Returns: A subscribable HTTP store for the GET request with execute and reset methods.

createPostStore(url, config)

Creates a POST request store.

function createPostStore<T>(url: string, config?: RequestConfig): HttpStore<T>
  • url — The request endpoint URL.
  • config — Optional request configuration such as headers or body data.

Returns: A subscribable HTTP store for the POST request with execute and reset methods.

createPutStore(url, config)

Creates a PUT request store.

function createPutStore<T>(url: string, config?: RequestConfig): HttpStore<T>
  • url — The request endpoint URL.
  • config — Optional request configuration such as headers or body data.

Returns: A subscribable HTTP store for the PUT request with execute and reset methods.

createPatchStore(url, config)

Creates a PATCH request store.

function createPatchStore<T>(url: string, config?: RequestConfig): HttpStore<T>
  • url — The request endpoint URL.
  • config — Optional request configuration such as headers or body data.

Returns: A subscribable HTTP store for the PATCH request with execute and reset methods.

createDeleteStore(url, config)

Creates a DELETE request store.

function createDeleteStore<T>(url: string, config?: RequestConfig): HttpStore<T>
  • url — The request endpoint URL.
  • config — Optional request configuration such as headers or params.

Returns: A subscribable HTTP store for the DELETE request with execute and reset methods.

createHttpStoresFromClient(client)

Creates HTTP store factory methods bound to a specific client instance.

function createHttpStoresFromClient(client: HttpClient): HttpStoreFactory
  • client — The HTTP client to use for all created stores.

Returns: An object with get, post, put, patch, and delete factory methods.

createI18nStores()

Create i18n stores from the i18n provider in context.

function createI18nStores(): I18nStores

Returns: I18n stores and actions

createI18nStoresFromProvider(provider)

Create i18n stores from a specific provider.

function createI18nStoresFromProvider(provider: I18nProvider): I18nStores
  • provider — I18n provider

Returns: I18n stores and actions

getLogger(name)

Get a logger instance.

function getLogger(name?: string): Logger
  • name — Logger name

Returns: Logger instance

createLogger(config)

Create a logger with custom configuration.

function createLogger(config: LoggerConfig): Logger
  • config — Logger configuration

Returns: Logger instance

getRootLogger()

Get the root logger.

function getRootLogger(): Logger

Returns: Root logger instance

getChildLogger(name, context)

Create a child logger with additional context.

function getChildLogger(name: string, context: Record<string, unknown>): Logger
  • name — Parent logger name
  • context — Additional context

Returns: Child logger instance

createLoggerHelpers()

Create logger helpers from context.

function createLoggerHelpers(): LoggerHelpers

Returns: Logger helper functions

createLoggerHelpersFromProvider(provider)

Create logger helpers from a specific provider.

function createLoggerHelpersFromProvider(provider: LoggerProvider): LoggerHelpers
  • provider — Logger provider

Returns: Logger helper functions

createLoginStore()

Creates a login store with async state tracking.

function createLoginStore<T = unknown>(): LoginStore<T>

Returns: Login promise store

createOAuthHelpers(options)

Creates OAuth helpers for provider-based authentication flows.

When created in a browser, automatically handles OAuth callbacks by detecting code and state URL parameters and exchanging them for a session (a guarded no-op when there is no callback code in the URL).

Session establishment: the exchange result is applied to the resolved auth client (an explicit options.authClient, else the Svelte-context client when created during component initialization). When NO client is available, the server has already established the httpOnly-cookie session via the exchange, so a user-carrying response still counts as success — options.onSuccess fires; a response with no user fires options.onError.

function createOAuthHelpers(options?: OAuthOptions): OAuthHelpers
  • options — OAuth configuration (base URL, providers, endpoint paths, callbacks, auth client).

Returns: An object containing a readable providers store, URL builder, redirect function, and callback handler.

createPasswordResetStores()

Creates password reset stores with async state tracking.

function createPasswordResetStores(): PasswordResetStores

Returns: Password reset stores for request and confirm steps

createPlatformStores()

Create platform stores from the module-level platform info.

Platform information is static (no reactive subscription needed), so this returns plain values rather than Svelte stores.

function createPlatformStores(): {
  platform: Platform
  isNative: boolean
  isMobile: boolean
  isDesktop: boolean
  isWeb: boolean
  isDevelopment: boolean
  isProduction: boolean
  isPlatform: (...platforms: Platform[]) => boolean
}

Returns: Platform information and utility functions

createPromiseStore(asyncFn)

Creates a store that tracks async function state.

function createPromiseStore<T, A extends unknown[]>(
  asyncFn: (...args: A) => Promise<T>,
): PromiseStore<T, A>
  • asyncFn — The async function to track

Returns: Promise store with subscribe, call, cancel, and reset

createRouterStores()

Create router stores from the router in context.

function createRouterStores(): RouterStores

Returns: Router stores and actions

createIsActiveStore(location, router, path, exact)

Create a derived store that checks if a path is active.

function createIsActiveStore(
  location: Readable<RouteLocation>,
  router: Router,
  path: string,
  exact?: boolean,
): Readable<boolean>
  • location — A readable location store (from createRouterStores or createRouterStoresFromRouter)
  • router — Router instance (for isActive check)
  • path — Path to check
  • exact — Whether to require exact match (default: false)

Returns: Readable store of whether the path is active

createRouterStoresFromRouter(router)

Create router stores from a specific router.

function createRouterStoresFromRouter(router: Router): RouterStores
  • router — Router instance

Returns: Router stores and actions

createSignupStore()

Creates a signup store with async state tracking.

function createSignupStore<T = unknown>(): SignupStore<T>

Returns: Signup promise store

createStoreReadable(store)

Create a readable Svelte store from a molecule store.

function createStoreReadable<T>(store: MoleculeStore<T>): Readable<T>
  • store — The molecule store

Returns: Readable Svelte store

createStoreSelector(store, selector)

Create a derived Svelte store with a selector.

function createStoreSelector<T, S>(store: MoleculeStore<T>, selector: (state: T) => S): Readable<S>
  • store — The molecule store
  • selector — Selector function

Returns: Derived Svelte store

getSetStore(store)

Get the setState function from a molecule store.

function getSetStore<T>(store: MoleculeStore<T>): MoleculeStore<T>['setState']
  • store — The molecule store

Returns: setState function

createStoreAction(store, action)

Create a bound action for a store.

function createStoreAction<T, Args extends unknown[], R>(
  store: MoleculeStore<T>,
  action: (
    setState: MoleculeStore<T>['setState'],
    getState: MoleculeStore<T>['getState'],
  ) => (...args: Args) => R,
): (...args: Args) => R
  • store — The store
  • action — Action creator function

Returns: Bound action

createStorageStore(key, defaultValue)

Create a storage value store.

function createStorageStore<T>(key: string, defaultValue?: T): StorageStore<T>
  • key — Storage key
  • defaultValue — Default value if not found

Returns: Store with value and actions

createStorageHelpers()

Create storage helper functions from context.

function createStorageHelpers(): StorageHelpers

Returns: Storage functions

createStorageStoreFromProvider(storage, key, defaultValue)

Create storage store from a specific provider.

function createStorageStoreFromProvider<T>(
  storage: StorageProvider,
  key: string,
  defaultValue?: T,
): StorageStore<T>
  • storage — Storage provider
  • key — Storage key
  • defaultValue — Default value

Returns: Store with value and actions

createThemeStores()

Create theme stores from the theme provider in context.

function createThemeStores(): ThemeStores & { colors: Readable<Theme['colors']> }

Returns: Theme stores and actions

createThemeColorsStore(theme)

Create a derived store that returns just the theme colors.

function createThemeColorsStore(theme: Readable<Theme>): Readable<Theme['colors']>
  • theme — A readable theme store (from createThemeStores or createThemeStoresFromProvider)

Returns: Readable store of theme colors

createThemeStoresFromProvider(provider)

Create theme stores from a specific theme provider.

function createThemeStoresFromProvider(provider: ThemeProvider): ThemeStores
  • provider — Theme provider

Returns: Theme stores and actions

createVersionStores()

Create version stores from the module-level version provider.

function createVersionStores(): {
  state: Readable<VersionState>
  isUpdateAvailable: Readable<boolean>
  isChecking: Readable<boolean>
  isServiceWorkerWaiting: Readable<boolean>
  newVersion: Readable<string | undefined>
  checkForUpdates: () => Promise<boolean>
  applyUpdate: (options?: { force?: boolean }) => void
  dismissUpdate: () => void
  startPeriodicChecks: (options?: UpdateCheckOptions) => void
  stopPeriodicChecks: () => void
}

Returns: Version stores and actions

Constants

BodyPortal

const BodyPortal: LegacyComponentType

ContentOrElse

const ContentOrElse: LegacyComponentType

PresentWhileContent

const PresentWhileContent: LegacyComponentType
const Link: LegacyComponentType

RoutedView

const RoutedView: LegacyComponentType

SessionReady

const SessionReady: LegacyComponentType

MoleculeProvider

Combined provider for every molecule service, as @molecule/app-react's MoleculeProvider.

Only the services passed are provided, except state, which falls back to the state provider bonded under @molecule/app-state (set by setupAllDefaultBonds() or a state bond) so useStore() works without a state prop. Given auth, it renders its children only once the session is decided (awaitSession, default true), with the sessionFallback snippet meanwhile.

const MoleculeProvider: LegacyComponentType

AuthProvider

Provider for authentication, as @molecule/app-react's AuthProvider: it provides the client and, unless awaitSession is false, renders its children only once the session is decided (SessionReady), with the sessionFallback snippet meanwhile.

const AuthProvider: LegacyComponentType

StateProvider

Provider for state management, as @molecule/app-react's StateProvider.

const StateProvider: LegacyComponentType

ThemeProvider

Provider for theming, as @molecule/app-react's ThemeProvider.

const ThemeProvider: LegacyComponentType

RouterProvider

Provider for routing, as @molecule/app-react's RouterProvider.

const RouterProvider: LegacyComponentType

I18nProvider

Provider for internationalization, as @molecule/app-react's I18nProvider.

const I18nProvider: LegacyComponentType

HttpProvider

Provider for the HTTP client, as @molecule/app-react's HttpProvider.

const HttpProvider: LegacyComponentType

StorageProvider

Provider for storage, as @molecule/app-react's StorageProvider.

const StorageProvider: LegacyComponentType

LoggerProvider

Provider for logging, as @molecule/app-react's LoggerProvider.

const LoggerProvider: LegacyComponentType

WorkspaceProvider

Provider for the IDE workspace, as @molecule/app-react's WorkspaceProvider.

const WorkspaceProvider: LegacyComponentType

EditorProvider

Provider for the code editor, as @molecule/app-react's EditorProvider.

const EditorProvider: LegacyComponentType

PreviewProvider

Provider for the live preview, as @molecule/app-react's PreviewProvider.

const PreviewProvider: LegacyComponentType

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-ai-chat ^1.8.0 (optional)
  • @molecule/app-ai-models ^1.0.1 (optional)
  • @molecule/app-auth ^3.0.0 (optional)
  • @molecule/app-code-editor ^1.0.1 (optional)
  • @molecule/app-device ^1.0.1
  • @molecule/app-forms ^2.4.0
  • @molecule/app-http ^1.0.1 (optional)
  • @molecule/app-i18n ^1.4.0
  • @molecule/app-ide ^1.1.0 (optional)
  • @molecule/app-live-preview ^1.0.1 (optional)
  • @molecule/app-logger ^1.0.1
  • @molecule/app-platform ^1.0.1
  • @molecule/app-push ^1.0.1 (optional)
  • @molecule/app-routing ^1.4.0
  • @molecule/app-routing-sveltekit >=3.0.0 (optional)
  • @molecule/app-state ^1.2.0
  • @molecule/app-storage ^1.1.1
  • @molecule/app-theme ^1.0.2 (optional)
  • @molecule/app-ui ^1.0.1 (optional)
  • @molecule/app-utilities ^1.0.1 (optional)
  • @molecule/app-version ^1.0.1
  • svelte ^5.43.15

Runtime Dependencies

  • @molecule/app-ai-chat (optional)

  • @molecule/app-ai-models (optional)

  • @molecule/app-auth (optional)

  • @molecule/app-code-editor (optional)

  • @molecule/app-device

  • @molecule/app-forms

  • @molecule/app-http (optional)

  • @molecule/app-i18n

  • @molecule/app-ide (optional)

  • @molecule/app-live-preview (optional)

  • @molecule/app-logger

  • @molecule/app-platform

  • @molecule/app-push (optional)

  • @molecule/app-routing

  • @molecule/app-routing-sveltekit (optional)

  • @molecule/app-state

  • @molecule/app-storage

  • @molecule/app-theme (optional)

  • @molecule/app-ui (optional)

  • @molecule/app-utilities (optional)

  • @molecule/app-version

  • svelte

  • setMoleculeContext and every create*Stores factory use Svelte context — they are only legal during component initialization (the top level of a component <script>), never in module scope, after onMount, in event handlers, or in async callbacks. Wire the context in the ROOT layout so every route inherits it.

  • Factories throw per missing service: the context carries ONLY the services you passed — createAuthStores() under a context without auth throws. Fix the setMoleculeContext config; don't wrap in try/catch.

  • Results are Svelte stores — read them with the $ prefix ($isAuthenticated, $theme); actions (logout, toggleTheme, setTheme) are plain functions.

  • In-app links are Link (<Link to="/settings">): it navigates through the router with react-router <Link>'s click rules. A hand-written click handler that calls navigate() breaks ctrl/cmd-click (new tab) unless it repeats those rules.

  • BodyPortal is React's createPortal(children, document.body) for Svelte: Svelte itself renders the content in the target (a nested mount), so no node is moved after Svelte placed it. Nothing renders on the server; target replaces the body and null renders nothing until a target exists.

Use @molecule/app-svelte/chat, @molecule/app-svelte/ai-models, and @molecule/app-svelte/push for those features.

Translations

Translation strings are provided by @molecule/app-locales-svelte.