GitHub

API reference for build.

Self-installing modules of ahead-of-time compiled decoders (Effect's SchemaAOTCompiler/Build).

build(modules=..., out_file=...) loads each module, compiles its exported schemas and writes a module that imports them and installs their decoders when it is imported. Keys of modules are the dotted names the generated module imports; their loaders run during the build, in sorted order, and must return that module (or its namespace mapping). A module's exports are its __all__, else its public names; only schemas count. Decoding is prepared by default; "is" and "make" prepare the type side, "encode" the flipped AST. Regenerate after a schema or pyfect changes.

Re-exports

Types

TypeDefinitionDescription
Operationtype Operation = Literal['decode', 'encode', 'is', 'make']

An operation whose root AST build prepares.

ModuleLoadertype ModuleLoader = Callable[[], object]

Loads a module's namespace during a build.

Classes

Functions

build

build(*, modules, out_file, operations=None) -> Effect[BuildResult, BuildError | PlatformError, FileSystem | Path]

Write a self-installing module for the schemas modules export (see the module).

ParameterTypeDescription
modulesMapping[str, ModuleLoader]
out_filestr
operationsSequence[Operation] | None = None

Returns Effect[BuildResult, BuildError | PlatformError, FileSystem | Path]

def build(
    *,
    modules: Mapping[str, ModuleLoader],
    out_file: str,
    operations: Sequence[Operation] | None = None,
) -> Effect[BuildResult, BuildError | PlatformError, FileSystem | Path]:
    """Write a self-installing module for the schemas ``modules`` export
    (see the module)."""

    def run() -> Any:
        fs = yield from FileSystem()
        path = yield from Path()
        out = path.resolve(out_file)
        requested: set[Operation] = set(operations or ("decode",))
        chosen: list[Operation] = [operation for operation in _ORDER if operation in requested]
        imports: list[str] = []
        exported: list[_Exported] = []
        for specifier in sorted(modules):
            loaded = yield from _load(specifier, modules[specifier])
            if isinstance(loaded, types.ModuleType):
                namespace: Mapping[str, object] = vars(loaded)
            elif isinstance(loaded, Mapping):
                namespace = loaded  # pyright: ignore[reportUnknownVariableType]
            else:
                return (
                    yield from fail(
                        BuildError(
                            loaded,
                            "InvalidModule",
                            f"Schema module {stringify(specifier)} did not load a module namespace",
                            specifier,
                        )
                    )
                )
            names = _exports(namespace)
            if not names:
                continue
            if not _valid_name(specifier):
                return (
                    yield from fail(
                        BuildError(
                            None,
                            "ResolveModule",
                            f"Could not resolve schema module {stringify(specifier)}",
                            specifier,
                        )
                    )
                )
            alias = f"m{len(imports)}"
            imports.append(f"import {specifier} as {alias}")
            exported += [_Exported(alias, n, namespace[n]) for n in names]  # pyright: ignore[reportArgumentType]
        source = yield from _generate(imports, exported, chosen)
        yield from fs.make_directory(path.dirname(out), recursive=True)
        yield from fs.write_file_string(out, source)
        return BuildResult(out, len(imports), len(exported))

    return gen(run)