#!/usr/bin/env python3 """Add Bare's conditional builtin map to CommonJS packages in node_modules. Bare resolves package imports at the package boundary. A number of otherwise portable npm packages (notably dbus-next's XML parser dependency) still use bare Node builtin specifiers without declaring a map. Applying the official bare-node-runtime map at build time keeps those packages usable in the shipped bundle while leaving the source packages untouched. """ import json import sys from pathlib import Path root = Path(sys.argv[1] if len(sys.argv) > 1 else "node_modules") mapping = json.loads(Path(__file__).with_name("bare-imports.json").read_text()) changed = 0 for directory, subdirs, files in __import__("os").walk(root): # Native model payloads can be gigabytes. They never contain package # manifests, so do not walk them while preparing JavaScript packages. subdirs[:] = [d for d in subdirs if d not in {"prebuilds", ".git", ".cache"}] if "package.json" not in files: continue package_json = Path(directory) / "package.json" try: package = json.loads(package_json.read_text()) except (OSError, json.JSONDecodeError): continue imports = package.get("imports") if imports is not None and not isinstance(imports, dict): continue merged = dict(mapping) if isinstance(imports, dict): merged.update(imports) if imports == merged: continue package["imports"] = merged package_json.write_text(json.dumps(package, indent=2) + "\n") changed += 1 print(f"prepared {changed} package import maps for Bare")