Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

1.3 KB
Raw Blame
/* Copyright 2026 Marimo. All rights reserved. */

import { getIframeCapabilities } from "../capabilities";

/**
 * In-memory storage implementation of the Storage interface.
 */
class InMemoryStorage implements Storage {
  private store = new Map<string, string>();

  public get length(): number {
    return this.store.size;
  }

  public clear(): void {
    this.store.clear();
  }

  public getItem(key: string): string | null {
    return this.store.get(key) || null;
  }

  public key(index: number): string | null {
    const keys = [...this.store.keys()];
    return keys[index] || null;
  }

  public removeItem(key: string): void {
    this.store.delete(key);
  }

  public setItem(key: string, value: string): void {
    this.store.set(key, value);
  }
}

/**
 * Gets the best available storage. Should only be called once.
 */
function getAvailableStorage(): Storage {
  const { hasLocalStorage, hasSessionStorage } = getIframeCapabilities();

  if (hasLocalStorage) {
    return window.localStorage;
  }

  if (hasSessionStorage) {
    return window.sessionStorage;
  }

  return new InMemoryStorage();
}

/**
 * The best available storage. Either localStorage, sessionStorage, or in-memory storage.
 */
export const availableStorage: Storage = getAvailableStorage();