coffeejson 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
coffeejson/__init__.py ADDED
@@ -0,0 +1,134 @@
1
+ """The CoffeeJSON codec for Python.
2
+
3
+ Decode share links and files, validate against the shipped schemas, project
4
+ documents onto a typed view, and encode them back — as https://coffeejson.org/docs
5
+ specifies.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ._units import (
11
+ Measurement,
12
+ UnitSystem,
13
+ convert_measurement,
14
+ )
15
+ from .codec import (
16
+ DECODE_ERROR_KINDS,
17
+ MAX_PAYLOAD_BYTES,
18
+ DecodeError,
19
+ DecodeErrorKind,
20
+ check_envelope,
21
+ decode_document_bytes,
22
+ decode_document_text,
23
+ decode_payload,
24
+ decode_scanned,
25
+ dump,
26
+ dumps,
27
+ encode_payload,
28
+ share_url,
29
+ )
30
+ from .gear_labels import GEAR_LABELS, gear_label
31
+ from .normalize import (
32
+ NormalizedAddition,
33
+ NormalizedBean,
34
+ NormalizedDoc,
35
+ NormalizedFilter,
36
+ NormalizedGenerator,
37
+ NormalizedGrind,
38
+ NormalizedMeasured,
39
+ NormalizedOriginItem,
40
+ NormalizedParty,
41
+ NormalizedPerceived,
42
+ NormalizedRecipe,
43
+ NormalizedStep,
44
+ NormalizedTasting,
45
+ normalize,
46
+ )
47
+ from .schema import Issue, is_valid, load_schema, validate
48
+ from .version import FORMAT_VERSION, MEDIA_TYPE, SUPPORTED_MAJOR
49
+ from .vocabularies import (
50
+ ALTITUDE_UNITS,
51
+ BEAN_FORMS,
52
+ BREW_METHODS,
53
+ DEFAULT_QUANTITY_BASIS,
54
+ DEFAULT_STEP_KIND,
55
+ FILTER_MATERIALS,
56
+ GRIND_SIZES,
57
+ MASS_UNITS,
58
+ ORIGIN_TYPES,
59
+ PARTY_TYPES,
60
+ PREFERRED_EXTRACTIONS,
61
+ PRESSURE_UNITS,
62
+ PROCESSES,
63
+ QUANTITY_BASES,
64
+ RECOMMENDED_ADDITION_TYPES,
65
+ RECOMMENDED_PRODUCER_ROLES,
66
+ ROAST_LEVELS,
67
+ STEP_KINDS,
68
+ TEMPERATURE_UNITS,
69
+ UNITS,
70
+ WATER_UNITS,
71
+ )
72
+
73
+ __all__ = [
74
+ "ALTITUDE_UNITS",
75
+ "BEAN_FORMS",
76
+ "BREW_METHODS",
77
+ "DECODE_ERROR_KINDS",
78
+ "DEFAULT_QUANTITY_BASIS",
79
+ "DEFAULT_STEP_KIND",
80
+ "FILTER_MATERIALS",
81
+ "FORMAT_VERSION",
82
+ "GEAR_LABELS",
83
+ "GRIND_SIZES",
84
+ "MASS_UNITS",
85
+ "MAX_PAYLOAD_BYTES",
86
+ "MEDIA_TYPE",
87
+ "ORIGIN_TYPES",
88
+ "PARTY_TYPES",
89
+ "PREFERRED_EXTRACTIONS",
90
+ "PRESSURE_UNITS",
91
+ "PROCESSES",
92
+ "QUANTITY_BASES",
93
+ "RECOMMENDED_ADDITION_TYPES",
94
+ "RECOMMENDED_PRODUCER_ROLES",
95
+ "ROAST_LEVELS",
96
+ "STEP_KINDS",
97
+ "SUPPORTED_MAJOR",
98
+ "TEMPERATURE_UNITS",
99
+ "UNITS",
100
+ "WATER_UNITS",
101
+ "DecodeError",
102
+ "DecodeErrorKind",
103
+ "Issue",
104
+ "Measurement",
105
+ "NormalizedAddition",
106
+ "NormalizedBean",
107
+ "NormalizedDoc",
108
+ "NormalizedFilter",
109
+ "NormalizedGenerator",
110
+ "NormalizedGrind",
111
+ "NormalizedMeasured",
112
+ "NormalizedOriginItem",
113
+ "NormalizedParty",
114
+ "NormalizedPerceived",
115
+ "NormalizedRecipe",
116
+ "NormalizedStep",
117
+ "NormalizedTasting",
118
+ "UnitSystem",
119
+ "check_envelope",
120
+ "convert_measurement",
121
+ "decode_document_bytes",
122
+ "decode_document_text",
123
+ "decode_payload",
124
+ "decode_scanned",
125
+ "dump",
126
+ "dumps",
127
+ "encode_payload",
128
+ "gear_label",
129
+ "is_valid",
130
+ "load_schema",
131
+ "normalize",
132
+ "share_url",
133
+ "validate",
134
+ ]
coffeejson/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,37 @@
1
+ """The association rule shared by ``bean_ref`` and ``recipe_ref``.
2
+
3
+ A reference present resolves to the member whose ``id`` matches it byte for
4
+ byte; unresolved, the referrer is left unlinked rather than an error is raised.
5
+ A reference absent yields every member, because co-location links only a
6
+ single bean (https://coffeejson.org/docs/spec/02-envelope#association-explicit-reference).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable, Sequence
12
+ from typing import TypeVar
13
+
14
+ T = TypeVar("T")
15
+
16
+
17
+ def associated_members(
18
+ members: Sequence[T], ref: str | None, id_of: Callable[[T], str | None]
19
+ ) -> list[T]:
20
+ if not members:
21
+ return []
22
+ if ref is not None:
23
+ # Ids are unique within a collection; a document breaking that is
24
+ # malformed, and every reference to the shared id is unresolved rather
25
+ # than a guess at which member was meant.
26
+ hits = [m for m in members if id_of(m) == ref]
27
+ return hits if len(hits) == 1 else []
28
+ return list(members)
29
+
30
+
31
+ def associated_member(
32
+ members: Sequence[T], ref: str | None, id_of: Callable[[T], str | None]
33
+ ) -> T | None:
34
+ """The one member a referrer is about — ``None`` unless there is exactly
35
+ one, since naming one of three candidates invents a link."""
36
+ hits = associated_members(members, ref, id_of)
37
+ return hits[0] if len(hits) == 1 else None
coffeejson/_data.py ADDED
@@ -0,0 +1,27 @@
1
+ """Package data: the vendored schemas and the gear registry, read once."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from functools import cache
7
+ from importlib.resources import files
8
+ from typing import Any
9
+
10
+ RUNTIME_SCHEMA_FILE = "coffeejson-1.0.schema.json"
11
+ AUTHORING_SCHEMA_FILE = "coffeejson-1.0.authoring.schema.json"
12
+ GEAR_REGISTRY_FILE = "gear.json"
13
+
14
+
15
+ def data_bytes(name: str) -> bytes:
16
+ """The bytes of one vendored file, exactly as shipped."""
17
+ return files("coffeejson").joinpath("data").joinpath(name).read_bytes()
18
+
19
+
20
+ @cache
21
+ def _parsed(name: str) -> Any:
22
+ return json.loads(data_bytes(name).decode("utf-8"))
23
+
24
+
25
+ def data_json(name: str) -> Any:
26
+ """One vendored file, parsed. Shared; callers must not mutate it."""
27
+ return _parsed(name)
coffeejson/_readers.py ADDED
@@ -0,0 +1,119 @@
1
+ """Tolerant readers: any JSON value in, a typed value or ``None`` out.
2
+
3
+ ``normalize`` reads documents that were only checked at the envelope, so every
4
+ member it touches goes through one of these and never raises.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+ from typing import Any, TypeGuard
12
+
13
+ from ._units import Measurement
14
+ from .vocabularies import UNITS
15
+
16
+ # ECMAScript's WhiteSpace and LineTerminator sets, which `String.prototype.trim`
17
+ # strips. Python's `str.strip()` uses a different set (it strips U+001C-U+001F
18
+ # and keeps U+FEFF), so a name would trim differently across implementations.
19
+ _JS_WHITESPACE = "\t\n\v\f\r " + "".join(
20
+ chr(c)
21
+ for c in (0xA0, 0x1680, *range(0x2000, 0x200B), 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF)
22
+ )
23
+
24
+ _CALENDAR_DAY = re.compile(r"([0-9]{4})-([0-9]{2})-([0-9]{2})")
25
+
26
+
27
+ def is_obj(v: object) -> TypeGuard[dict[str, Any]]:
28
+ return isinstance(v, dict)
29
+
30
+
31
+ def string(v: object) -> str | None:
32
+ return v if isinstance(v, str) else None
33
+
34
+
35
+ def num(v: object) -> float | None:
36
+ """A finite JSON number. A boolean is not a number, though Python says so."""
37
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
38
+ return None
39
+ try:
40
+ finite = math.isfinite(v)
41
+ except OverflowError: # an integer past the double range reads as infinite
42
+ return None
43
+ if not finite:
44
+ return None
45
+ # Past 2^53 an integer is not a double, so the arithmetic downstream could overflow.
46
+ return v if abs(v) <= 2**53 else float(v)
47
+
48
+
49
+ def arr(v: object) -> list[Any]:
50
+ return v if isinstance(v, list) else []
51
+
52
+
53
+ def obj_items(v: object) -> list[dict[str, Any]]:
54
+ return [x for x in arr(v) if is_obj(x)]
55
+
56
+
57
+ def str_arr(v: object) -> list[str]:
58
+ return [x for x in arr(v) if isinstance(x, str)]
59
+
60
+
61
+ def is_leap_year(year: int) -> bool:
62
+ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
63
+
64
+
65
+ def names_real_day(s: str) -> bool:
66
+ """Whether ``s`` is ``YYYY-MM-DD`` naming a day the proleptic Gregorian
67
+ calendar has. Year 0000 is such a year; ``datetime.date`` cannot hold it."""
68
+ m = _CALENDAR_DAY.fullmatch(s)
69
+ if m is None:
70
+ return False
71
+ year, month, day = (int(g) for g in m.groups())
72
+ if not 1 <= month <= 12:
73
+ return False
74
+ days = (31, 29 if is_leap_year(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
75
+ return 1 <= day <= days[month - 1]
76
+
77
+
78
+ def calendar_day(v: object) -> str | None:
79
+ """A date-only member naming a real day. A string outside that states no
80
+ day, so a consumer that showed it would be asserting one."""
81
+ s = string(v)
82
+ return s if s is not None and names_real_day(s) else None
83
+
84
+
85
+ def js_trim(s: str) -> str:
86
+ return s.strip(_JS_WHITESPACE)
87
+
88
+
89
+ def party_name(v: object) -> str | None:
90
+ """A party's display name; whitespace-only counts as absent."""
91
+ if not is_obj(v):
92
+ return None
93
+ name = string(v.get("name"))
94
+ if name is None:
95
+ return None
96
+ trimmed = js_trim(name)
97
+ return trimmed or None
98
+
99
+
100
+ _KNOWN_UNITS = frozenset(UNITS)
101
+
102
+
103
+ def measurement(v: object) -> Measurement | None:
104
+ """A recognized unit plus at least one magnitude; missing either, it states nothing.
105
+
106
+ A unit outside the Units vocabulary is treated as absent, never guessed:
107
+ https://coffeejson.org/docs/spec/03-recipe#measurement-object
108
+ """
109
+ if not is_obj(v):
110
+ return None
111
+ unit = string(v.get("unit"))
112
+ if unit is None or unit not in _KNOWN_UNITS:
113
+ return None
114
+ value = num(v.get("value"))
115
+ low = num(v.get("min"))
116
+ high = num(v.get("max"))
117
+ if value is None and low is None and high is None:
118
+ return None
119
+ return Measurement(unit=unit, value=value, min=low, max=high)
coffeejson/_units.py ADDED
@@ -0,0 +1,110 @@
1
+ """Measurements and the unit conversions the format defines.
2
+
3
+ Units travel as identifiers (``gram``, ``celsius``), never display symbols
4
+ (https://coffeejson.org/docs/spec/06-vocabularies#units). Mass converts
5
+ gram⇄ounce, temperature celsius⇄fahrenheit and altitude meter⇄foot;
6
+ ``milliliter`` and ``bar`` pass through, because water's density varies with
7
+ temperature and pressure has one unit.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass
15
+ from typing import Final, Literal
16
+
17
+ GRAMS_PER_OUNCE: Final = 28.349523125
18
+ METERS_PER_FOOT: Final = 0.3048
19
+
20
+ UnitSystem = Literal["as-authored", "metric", "imperial"]
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Measurement:
25
+ """A quantity: a single ``value``, or a ``min``/``max`` window when the
26
+ source published one. At least one magnitude is present."""
27
+
28
+ unit: str
29
+ value: float | None = None
30
+ min: float | None = None
31
+ max: float | None = None
32
+
33
+
34
+ def round1(n: float) -> float:
35
+ """Round to one decimal as ECMAScript's ``Math.round(n * 10) / 10`` does:
36
+ half rounds toward positive infinity, never to even."""
37
+ scaled = n * 10
38
+ if not math.isfinite(scaled):
39
+ return scaled
40
+ whole = math.floor(scaled)
41
+ return (whole + 1 if scaled - whole >= 0.5 else whole) / 10
42
+
43
+
44
+ def magnitude(m: Measurement | None) -> float | None:
45
+ """A single number to compute with — a window yields its midpoint, a
46
+ one-sided window its stated bound. Never for display."""
47
+ if m is None:
48
+ return None
49
+ if m.value is not None:
50
+ return m.value
51
+ if m.min is not None and m.max is not None:
52
+ return (m.min + m.max) / 2
53
+ return m.min if m.min is not None else m.max
54
+
55
+
56
+ def convert_mass_value(value: float, from_unit: str, to_unit: str) -> float | None:
57
+ """Convert a mass magnitude, unrounded. ``None`` when either unit is not a
58
+ mass the format defines."""
59
+ if from_unit == to_unit:
60
+ return value
61
+ if from_unit == "gram" and to_unit == "ounce":
62
+ return value / GRAMS_PER_OUNCE
63
+ if from_unit == "ounce" and to_unit == "gram":
64
+ return value * GRAMS_PER_OUNCE
65
+ return None
66
+
67
+
68
+ def _as_double(n: float) -> float:
69
+ # Not `float(n)` alone: an integer past the double range raises there.
70
+ try:
71
+ return float(n)
72
+ except OverflowError:
73
+ return math.inf if n > 0 else -math.inf
74
+
75
+
76
+ def map_magnitudes(m: Measurement, f: Callable[[float], float], unit: str) -> Measurement:
77
+ """Apply ``f`` bound by bound, rounding each to one decimal, so a window
78
+ stays a window."""
79
+ return Measurement(
80
+ unit=unit,
81
+ value=None if m.value is None else round1(f(_as_double(m.value))),
82
+ min=None if m.min is None else round1(f(_as_double(m.min))),
83
+ max=None if m.max is None else round1(f(_as_double(m.max))),
84
+ )
85
+
86
+
87
+ def round_measurement(m: Measurement) -> Measurement:
88
+ """Each magnitude rounded to one decimal, unit unchanged."""
89
+ return map_magnitudes(m, lambda n: n, m.unit)
90
+
91
+
92
+ def convert_measurement(m: Measurement, system: UnitSystem) -> Measurement:
93
+ """Express ``m`` in ``system``. Every unit without a conversion passes
94
+ through untouched."""
95
+ if system == "as-authored":
96
+ return m
97
+ to_metric = system == "metric"
98
+ if m.unit == "ounce":
99
+ return map_magnitudes(m, lambda n: n * GRAMS_PER_OUNCE, "gram") if to_metric else m
100
+ if m.unit == "gram":
101
+ return m if to_metric else map_magnitudes(m, lambda n: n / GRAMS_PER_OUNCE, "ounce")
102
+ if m.unit == "fahrenheit":
103
+ return map_magnitudes(m, lambda n: (n - 32) * 5 / 9, "celsius") if to_metric else m
104
+ if m.unit == "celsius":
105
+ return m if to_metric else map_magnitudes(m, lambda n: n * 9 / 5 + 32, "fahrenheit")
106
+ if m.unit == "foot":
107
+ return map_magnitudes(m, lambda n: n * METERS_PER_FOOT, "meter") if to_metric else m
108
+ if m.unit == "meter":
109
+ return m if to_metric else map_magnitudes(m, lambda n: n / METERS_PER_FOOT, "foot")
110
+ return m
coffeejson/cli.py ADDED
@@ -0,0 +1,136 @@
1
+ """``python -m coffeejson``: validate a file, decode a link, encode a document."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import io
7
+ import json
8
+ import re
9
+ import sys
10
+ from collections.abc import Sequence
11
+ from pathlib import Path
12
+
13
+ from .codec import (
14
+ DecodeError,
15
+ _escape_lone_surrogates,
16
+ decode_document_bytes,
17
+ decode_payload,
18
+ decode_scanned,
19
+ encode_payload,
20
+ share_url,
21
+ )
22
+ from .schema import validate
23
+
24
+ _HAS_SCHEME = re.compile(r"\s*[A-Za-z][A-Za-z0-9+.\-]*:")
25
+ _DEEPEST_PRINTED = 500
26
+
27
+
28
+ def _too_deep(document: object) -> bool:
29
+ level: list[object] = [document]
30
+ for _ in range(_DEEPEST_PRINTED):
31
+ level = [
32
+ child
33
+ for value in level
34
+ for child in (
35
+ value.values()
36
+ if isinstance(value, dict)
37
+ else value
38
+ if isinstance(value, list)
39
+ else ()
40
+ )
41
+ ]
42
+ if not level:
43
+ return False
44
+ return True
45
+
46
+
47
+ def _read_document(path: str) -> dict[str, object]:
48
+ return decode_document_bytes(Path(path).read_bytes())
49
+
50
+
51
+ def _report_decode_error(e: DecodeError) -> int:
52
+ detail = f" ({e.detail})" if e.detail else ""
53
+ print(f"error: {e.kind}{detail}", file=sys.stderr)
54
+ return 1
55
+
56
+
57
+ def _validate(args: argparse.Namespace) -> int:
58
+ try:
59
+ doc = _read_document(args.file)
60
+ except DecodeError as e:
61
+ return _report_decode_error(e)
62
+ issues = validate(doc, strict=args.strict)
63
+ for issue in issues:
64
+ where = "/" + "/".join(str(s) for s in issue.path)
65
+ print(f"{where}: {issue.keyword}: {issue.message}")
66
+ if issues:
67
+ print(f"{args.file}: {len(issues)} issue(s)", file=sys.stderr)
68
+ return 1
69
+ print(f"{args.file}: valid")
70
+ return 0
71
+
72
+
73
+ def _decode(args: argparse.Namespace) -> int:
74
+ text: str = args.input
75
+ try:
76
+ # A payload is base64url and never contains a colon; anything with a
77
+ # scheme is a link and goes through the whole scanned-input binding.
78
+ doc = decode_scanned(text) if _HAS_SCHEME.match(text) else decode_payload(text.strip())
79
+ except DecodeError as e:
80
+ return _report_decode_error(e)
81
+ # Not `dumps`, which writes for a producer: it drops nulls and composes ids.
82
+ if _too_deep(doc):
83
+ raise ValueError("the document is nested too deeply to print")
84
+ print(_escape_lone_surrogates(json.dumps(doc, ensure_ascii=False, indent=2, allow_nan=False)))
85
+ return 0
86
+
87
+
88
+ def _encode(args: argparse.Namespace) -> int:
89
+ try:
90
+ doc = _read_document(args.file)
91
+ except DecodeError as e:
92
+ return _report_decode_error(e)
93
+ if args.url:
94
+ print(share_url(doc, args.host, compress=args.compress))
95
+ else:
96
+ print(encode_payload(doc, compress=args.compress))
97
+ return 0
98
+
99
+
100
+ def _parser() -> argparse.ArgumentParser:
101
+ parser = argparse.ArgumentParser(
102
+ prog="coffeejson", description="Validate, decode and encode CoffeeJSON documents."
103
+ )
104
+ commands = parser.add_subparsers(dest="command", required=True)
105
+
106
+ p = commands.add_parser("validate", help="validate a document file against the schema")
107
+ p.add_argument("file")
108
+ p.add_argument("--strict", action="store_true", help="use the authoring schema")
109
+ p.set_defaults(run=_validate)
110
+
111
+ p = commands.add_parser(
112
+ "decode", help="print the document a share URL or a bare payload carries, unchanged"
113
+ )
114
+ p.add_argument("input", metavar="url-or-payload")
115
+ p.set_defaults(run=_decode)
116
+
117
+ p = commands.add_parser("encode", help="encode a document file as a share payload")
118
+ p.add_argument("file")
119
+ p.add_argument("--compress", action="store_true", help="zlib-compress the payload")
120
+ p.add_argument("--url", action="store_true", help="print a share URL, not a payload")
121
+ p.add_argument("--host", default="coffeejson.org", help="the share URL's host")
122
+ p.set_defaults(run=_encode)
123
+ return parser
124
+
125
+
126
+ def main(argv: Sequence[str] | None = None) -> int:
127
+ args = _parser().parse_args(argv)
128
+ if isinstance(sys.stdout, io.TextIOWrapper):
129
+ # A console encoding that cannot hold the document is not the document's error.
130
+ sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace")
131
+ try:
132
+ status: int = args.run(args)
133
+ except (OSError, ValueError, RecursionError) as e:
134
+ print(f"error: {e}", file=sys.stderr)
135
+ return 1
136
+ return status