"""Generate `src/instantdb/_sync/` from `src/instantdb/_async/`. Discovers every `.py` file under `_async/` and runs `unasync` over each, except for entries in `ASYNC_ONLY` below. Excluded modules document the reason in their own docstrings — keep the rationale next to the code so it doesn't drift as the set changes. Adding a new HTTP-shaped surface: just drop it under `_async/` and re-run `make unasync`. Adding a new async-only surface: drop it under `_async/`, add the path to `ASYNC_ONLY`, and note the reason in that module's docstring. Lines between `# UNASYNC_REMOVE_START` and `# UNASYNC_REMOVE_END` markers are stripped before unasync runs — used when an otherwise-unasynced module has individual methods or imports that should exist only on the async client. Run via `make unasync` (or `uv run python scripts/run_unasync.py`). """ from __future__ import annotations import re import shutil import tempfile from pathlib import Path import unasync ROOT = Path(__file__).resolve().parent.parent SRC = ROOT / "src" / "instantdb" # Async-only files / directories that should NOT be unasynced. Anything else # under _async/ is picked up automatically. Directory entries end with "/" # and match as a prefix (covers everything under that subtree). The "why" # for each entry lives in the excluded module's docstring. ASYNC_ONLY: set[str] = { "_async/subscribe.py", "_async/streams/", } def discover_async_files() -> list[str]: async_dir = SRC / "_async" files: list[str] = [] for path in sorted(async_dir.rglob("*.py")): relpath = path.relative_to(SRC).as_posix() if any( relpath.startswith(excl) if excl.endswith("/") else relpath == excl for excl in ASYNC_ONLY ): continue files.append(relpath) return files REMOVE_BLOCK = re.compile( # Allow either a trailing newline or end-of-file after the end marker # so a block at EOF without a final newline still gets stripped. r"^[ \t]*# UNASYNC_REMOVE_START[ \t]*\n.*?# UNASYNC_REMOVE_END[ \t]*(?:\n|\Z)", flags=re.MULTILINE | re.DOTALL, ) # Names where unasync's default (Async → Sync prefix) is wrong for us — we # want the Async prefix stripped entirely. Plus the in-package _async path # segment (otherwise import strings in the generated _sync/ would still # reference _async). REPLACEMENTS = { "AsyncInstant": "Instant", "AsyncAuth": "Auth", "AsyncStorage": "Storage", "AsyncRooms": "Rooms", "AsyncWebhooks": "Webhooks", "AsyncWebhooksManager": "WebhooksManager", "_AsyncHTTP": "_HTTP", "_async": "_sync", "aclose": "close", "AsyncClient": "Client", "AsyncBaseTransport": "BaseTransport", # Sync flavor reads directly; async offloads via asyncio.to_thread. "_read_chunk_offloaded_async": "_read_chunk_offloaded_sync", } # Prepended to every generated sync file so teammates who open one don't # silently edit it. Lives above the module docstring (no module-docstring # conflict — comments outside a string don't displace it). GENERATED_HEADER = """\ # AUTOGENERATED from ../_async/. DO NOT EDIT THIS FILE BY HAND. # Run `make unasync` from client/packages/python/ to regenerate. """ def main() -> None: sync_dir = SRC / "_sync" if sync_dir.exists(): shutil.rmtree(sync_dir) async_files = discover_async_files() with tempfile.TemporaryDirectory() as tmpdir: tmp = Path(tmpdir) # Stage preprocessed copies under tmp/_async/ so unasync sees a clean # tree without the marker blocks. Mirror directory layout. staged: list[str] = [] for relpath in async_files: src = SRC / relpath dst = tmp / relpath dst.parent.mkdir(parents=True, exist_ok=True) dst.write_text(REMOVE_BLOCK.sub("", src.read_text())) staged.append(str(dst)) rule = unasync.Rule( fromdir=str(tmp / "_async") + "/", todir=str(SRC / "_sync") + "/", additional_replacements=REPLACEMENTS, ) unasync.unasync_files(staged, [rule]) # Prepend the "do not edit" header to every generated file. unasync # writes its output verbatim, so the header has to be added after the # fact rather than as part of the rule. for path in sync_dir.rglob("*.py"): path.write_text(GENERATED_HEADER + path.read_text()) print(f"✓ generated {sync_dir.relative_to(ROOT)} from _async/") if __name__ == "__main__": main()