Metadata-Version: 2.4
Name: d42-refine
Version: 0.1.0a2
Summary: Schema refinement for d42: narrow one schema with another schema or with data
Author-email: Sagitov Yuriy <pro100.ko10ok@gmail.com>
License: Apache-2.0
Project-URL: Homepage, https://github.com/ko10ok/d42-refine
Project-URL: GitHub, https://github.com/ko10ok/d42-refine
Keywords: d42,schema,validation,refinement,substitution
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: d42<3.0,>=2.4
Requires-Dist: niltype<2.0,>=0.3
Requires-Dist: th<1.0,>=0.3
Provides-Extra: dev
Requires-Dist: baby-steps==1.3.1; extra == "dev"
Requires-Dist: flake8==7.1.1; extra == "dev"
Requires-Dist: isort==5.13.2; extra == "dev"
Requires-Dist: mypy==1.11.2; extra == "dev"
Requires-Dist: pytest==8.3.3; extra == "dev"
Requires-Dist: pytest-cov==5.0.0; extra == "dev"
Dynamic: license-file

# d42-refine

Schema intersection for [d42](https://github.com/d42-schemas/d42).
`refine(base, narrow)` accepts only values accepted by both schemas.
Data is delegated to `d42.substitution.substitute`.

## Install

```shell
pip install d42-refine
```

## Usage

```python
from d42 import optional, schema
from d42_refine import refine

base = schema.dict({
    "id": schema.int,
    "name": schema.str,
    optional("deleted_at"): schema.str,
})
narrow = schema.dict({
    "id": schema.int.min(1),
    "name": schema.str.len(1, 10),
})

refined = refine(base, narrow)
# schema.dict({
#     "id": schema.int.min(1),
#     "name": schema.str.len(1, 10),
#     optional("deleted_at"): schema.str,
# })
```

The result is a normal d42 schema: `validate`, `fake`, `represent`, etc. work.

## Data substitution

```python
refine(schema.dict({"id": schema.int}), {"id": 1})
# same as d42.substitution.substitute(...)
```

## `%` operator (opt-in)

`schema % value` always uses d42 substitution and never changes.

`schema % schema` refines only after `enable_schema_substitution()`, which enables it
globally for all schemas until `disable_schema_substitution()`:

```python
schema.int % 42                                 # schema.int(42) — d42 substitution
schema.int.min(1) % schema.int.min(10).max(20)
# SubstitutionError: IntSchema given where int is expected

from d42_refine import disable_schema_substitution, enable_schema_substitution

enable_schema_substitution()

schema.int.min(1) % schema.int.min(10).max(20)  # schema.int.min(10).max(20)
schema.int % 42                                 # schema.int(42) — unchanged

disable_schema_substitution()
```

## `any` branches

```python
refine(schema.str, schema.any(schema.str("3"), schema.str("4")))
# schema.any(schema.str("3"), schema.str("4"))

refine(schema.str, schema.any(schema.str("3")))
# schema.str("3")  # single branch is collapsed
```

An incompatible branch raises `RefinementError`.

## Check without an exception

```python
from d42_refine import is_refinement

is_refinement(schema.int.min(1), schema.int.min(10))  # True
is_refinement(schema.int.min(1), schema.int)         # False
```

## Rules

- `int` / `float`: stricter `min` / `max`.
- `str` / `bytes`: stricter lengths; `contains` only narrower; `alphabet`
  only a subset; `regex` only equal.
- `list`: elements, `type`, `...`, lengths, and `unique` are merged.
- `dict`: keys are refined recursively; required / optional / absent and
  `...` are preserved only if allowed by the base.
- `any`: every branch is refined; incompatible branch = error.
- Aliases are preserved; `datetime` refines `date`; `bool` refines `int`.
- Equality is allowed. Otherwise `RefinementError` contains the path:
  ```python
  refine(schema.str.regex(r"^[a-z]+$"), schema.str.regex(r"^[0-9]+$"))
  # RefinementError: $: ...
  ```

## Custom type

1. Add the hook to the schema class:
   ```python
   def __d42_refine__(self, refiner, *, narrow, path):
       ...
   ```
2. Refine nested schemas through `refiner`:
   ```python
   from d42.declaration import Props, Schema
   from d42_refine import make_refinement_error

   class BoxSchema(Schema[Props]):
       def __init__(self, item):
           super().__init__(Props({"item": item}))

       @property
       def item(self):
           return self.props.get("item")

       def __d42_refine__(self, refiner, *, narrow, path):
           if not isinstance(narrow, BoxSchema):
               raise make_refinement_error(
                   path, f"BoxSchema can not be refined with {narrow.__class__.__name__}")

           item = refiner.refine(  # recurse into the nested schema
               self.item, narrow.item, refiner.child_path(path, "item"))
           return BoxSchema(item)  # new schema, do not mutate self
   ```
3. Works inside `dict`, `list`, and `any`. Without the hook, equal schemas are
   a no-op and different classes raise `RefinementError`.

## Limitations

Containment of different regexes is undecidable, so `d42-refine` raises
`RefinementError` instead of guessing. Equal patterns and concrete values work.

## Development

```shell
make install
make test
make lint
make coverage
```

An LLM-oriented API summary is packaged as `d42_refine/llms.txt`.

## Release

Base version lives in `d42_refine/version`. CI appends `EXT_VERSION` (`a1`,
`b1`, `rc1`) to it.

```shell
make tag          # v0.1.0
make tag-alpha    # v0.1.0a1
make tag-beta
make tag-rc
make push-tags
```

Publishing uses GitHub OIDC trusted publishing, no PyPI token. Alpha can be
published manually: Actions → Check and publish → Run workflow → Publish alpha.
Configure the PyPI trusted publisher environment as `manual-gate` for it.

## License

Apache-2.0
