wesley-python 0.1.0a1__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.
@@ -0,0 +1,11 @@
1
+ # Copyright 2026 Captain James
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """wesley-python: a generic Wesley target that emits standard-library Python.
4
+
5
+ The syntax API is in :mod:`wesley_python.types` and :mod:`wesley_python.syntax`; the plain-GraphQL
6
+ emitter is in :mod:`wesley_python.emit`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ __version__ = "0.1.0a1"
@@ -0,0 +1,9 @@
1
+ # Copyright 2026 Captain James
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Run the command line: ``python -m wesley_python``."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from wesley_python.cli import main
8
+
9
+ raise SystemExit(main())
wesley_python/cli.py ADDED
@@ -0,0 +1,59 @@
1
+ # Copyright 2026 Captain James
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The command line: ``python -m wesley_python emit [--ir FILE] [--out FILE]``."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import json
9
+ import sys
10
+ from typing import TYPE_CHECKING
11
+
12
+ from wesley_python.emit import module_from_ir
13
+ from wesley_python.syntax import render
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Sequence
17
+
18
+ PROG = "wesley-python"
19
+
20
+
21
+ def _parser() -> argparse.ArgumentParser:
22
+ parser = argparse.ArgumentParser(prog=PROG, description="Generate Python from Wesley IR.")
23
+ commands = parser.add_subparsers(dest="command", required=True)
24
+ emit = commands.add_parser(
25
+ "emit",
26
+ help="emit TypedDicts for plain GraphQL types",
27
+ description="Read Wesley IR JSON and write a Python module of TypedDicts and aliases.",
28
+ )
29
+ emit.add_argument("--ir", metavar="FILE", help="the IR JSON to read (default: standard input)")
30
+ emit.add_argument("--out", metavar="FILE", help="the module to write (default: standard output)")
31
+ return parser
32
+
33
+
34
+ def _emit(ir_path: str | None, out_path: str | None) -> None:
35
+ if ir_path is None:
36
+ text = sys.stdin.read()
37
+ else:
38
+ with open(ir_path, encoding="utf-8") as handle: # noqa: PTH123 - pathlib is not needed
39
+ text = handle.read()
40
+ output = render(module_from_ir(json.loads(text)))
41
+ if out_path is None:
42
+ sys.stdout.write(output)
43
+ else:
44
+ with open(out_path, "w", encoding="utf-8", newline="\n") as handle: # noqa: PTH123
45
+ handle.write(output)
46
+
47
+
48
+ def main(argv: Sequence[str] | None = None) -> int:
49
+ """Run the command line and return its exit status: 0 on success, 1 on any error."""
50
+ args = _parser().parse_args(argv)
51
+ try:
52
+ _emit(args.ir, args.out)
53
+ except json.JSONDecodeError as error:
54
+ sys.stderr.write(f"{PROG}: error: the IR is not valid JSON: {error}\n")
55
+ return 1
56
+ except (OSError, ValueError, TypeError) as error:
57
+ sys.stderr.write(f"{PROG}: error: {error}\n")
58
+ return 1
59
+ return 0
wesley_python/emit.py ADDED
@@ -0,0 +1,218 @@
1
+ # Copyright 2026 Captain James
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Plain GraphQL: Wesley IR in, a :class:`~wesley_python.syntax.Module` of ``TypedDict`` classes out.
4
+
5
+ This target is generic. It reads every type in the IR and ignores every directive.
6
+
7
+ - ``OBJECT``, ``INPUT_OBJECT`` and ``INTERFACE`` become ``TypedDict`` classes. Every field is a required
8
+ key: GraphQL nullability means a value may be ``null``, not that the key may be absent, so a
9
+ nullable field is typed ``Union[T, None]``.
10
+ - ``ENUM`` becomes an alias of a ``Literal`` of its value names.
11
+ - ``UNION`` becomes an alias of a ``Union`` of its members.
12
+ - ``SCALAR`` declarations emit nothing. ``String`` and ``ID`` are ``str``, ``Int`` is ``int``,
13
+ ``Float`` is ``float``, ``Boolean`` is ``bool``, and any other scalar is ``Any``.
14
+ - A list is ``List[...]``. Its items are nullable unless ``listItemNullable`` is ``false``, as in
15
+ GraphQL, where ``[T]`` holds nullable items.
16
+
17
+ Types are emitted in IR order, except that a union alias moves to just after the last of its members,
18
+ because a type checker reads ``A = 'B'`` as a string and not as an alias. A reference to a type emitted
19
+ later inside a field or a subscript is a string forward reference.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import TYPE_CHECKING
25
+
26
+ from wesley_python.syntax import AliasDef, Definition, Field, Module, TypedDictDef
27
+ from wesley_python.types import (
28
+ AnyValue,
29
+ Bool,
30
+ Float,
31
+ Int,
32
+ ListOf,
33
+ Literal,
34
+ NoneType,
35
+ Ref,
36
+ Str,
37
+ TypeExpr,
38
+ UnionOf,
39
+ )
40
+
41
+ if TYPE_CHECKING:
42
+ from collections.abc import Mapping
43
+
44
+ __all__ = ["SUPPORTED_IR_VERSION", "IRError", "module_from_ir"]
45
+
46
+ SUPPORTED_IR_VERSION = "1.0.0"
47
+
48
+ _RECORD_KINDS = frozenset({"OBJECT", "INPUT_OBJECT", "INTERFACE"})
49
+ _KINDS = _RECORD_KINDS | {"ENUM", "UNION", "SCALAR"}
50
+
51
+ _BUILTIN_SCALARS: Mapping[str, TypeExpr] = {
52
+ "String": Str(),
53
+ "ID": Str(),
54
+ "Int": Int(),
55
+ "Float": Float(),
56
+ "Boolean": Bool(),
57
+ }
58
+
59
+
60
+ class IRError(ValueError):
61
+ """The input is not Wesley IR this target reads."""
62
+
63
+
64
+ def _object(value: object, path: str) -> dict[str, object]:
65
+ if not isinstance(value, dict):
66
+ msg = f"{path} must be an object"
67
+ raise IRError(msg)
68
+ return {str(key): item for key, item in value.items()}
69
+
70
+
71
+ def _get(record: dict[str, object], key: str, path: str) -> object:
72
+ if key not in record:
73
+ msg = f"{path}.{key} is missing"
74
+ raise IRError(msg)
75
+ return record[key]
76
+
77
+
78
+ def _string(value: object, path: str) -> str:
79
+ if not isinstance(value, str):
80
+ msg = f"{path} must be a string"
81
+ raise IRError(msg)
82
+ return value
83
+
84
+
85
+ def _boolean(value: object, path: str) -> bool:
86
+ if not isinstance(value, bool):
87
+ msg = f"{path} must be a boolean"
88
+ raise IRError(msg)
89
+ return value
90
+
91
+
92
+ def _array(value: object, path: str) -> list[object]:
93
+ if not isinstance(value, list):
94
+ msg = f"{path} must be an array"
95
+ raise IRError(msg)
96
+ return value
97
+
98
+
99
+ def _description(record: dict[str, object], path: str) -> str | None:
100
+ if "description" not in record or record["description"] is None:
101
+ return None
102
+ return _string(record["description"], f"{path}.description")
103
+
104
+
105
+ def _strings(record: dict[str, object], key: str, path: str) -> list[str]:
106
+ items = _array(_get(record, key, path), f"{path}.{key}")
107
+ if not items:
108
+ msg = f"{path}.{key} must not be empty"
109
+ raise IRError(msg)
110
+ return [_string(item, f"{path}.{key}[{index}]") for index, item in enumerate(items)]
111
+
112
+
113
+ class _Reader:
114
+ """Turns IR records into definitions, knowing every declared type's kind."""
115
+
116
+ def __init__(self, kinds: dict[str, str]) -> None:
117
+ self.kinds = kinds
118
+
119
+ def named(self, base: str) -> TypeExpr:
120
+ if base in _BUILTIN_SCALARS:
121
+ return _BUILTIN_SCALARS[base]
122
+ kind = self.kinds.get(base, "SCALAR")
123
+ return AnyValue() if kind == "SCALAR" else Ref(base)
124
+
125
+ def reference(self, value: object, path: str) -> TypeExpr:
126
+ record = _object(value, path)
127
+ base = _string(_get(record, "base", path), f"{path}.base")
128
+ nullable = _boolean(_get(record, "nullable", path), f"{path}.nullable")
129
+ is_list = _boolean(_get(record, "isList", path), f"{path}.isList")
130
+ result = self.named(base)
131
+ if is_list:
132
+ item_nullable = True
133
+ if "listItemNullable" in record:
134
+ item_nullable = _boolean(record["listItemNullable"], f"{path}.listItemNullable")
135
+ result = ListOf(UnionOf(result, NoneType()) if item_nullable else result)
136
+ return UnionOf(result, NoneType()) if nullable else result
137
+
138
+ def field(self, value: object, path: str) -> Field:
139
+ record = _object(value, path)
140
+ name = _string(_get(record, "name", path), f"{path}.name")
141
+ type_ = self.reference(_get(record, "type", path), f"{path}.type")
142
+ return Field(name, type_, required=True, doc=_description(record, path))
143
+
144
+ def definition(self, record: dict[str, object], name: str, kind: str, path: str) -> Definition | None:
145
+ doc = _description(record, path)
146
+ if kind in _RECORD_KINDS:
147
+ raw = _array(record.get("fields", []), f"{path}.fields")
148
+ fields = [self.field(item, f"{path}.fields[{index}]") for index, item in enumerate(raw)]
149
+ return TypedDictDef(name, fields, doc=doc)
150
+ if kind == "ENUM":
151
+ values = _strings(record, "enumValues", path)
152
+ return AliasDef(name, UnionOf(*(Literal(value) for value in values)), doc=doc)
153
+ if kind == "UNION":
154
+ members = _strings(record, "unionMembers", path)
155
+ return AliasDef(name, UnionOf(*(Ref(member) for member in members)), doc=doc)
156
+ return None
157
+
158
+
159
+ def _alias_order(items: list[tuple[Definition, set[str]]]) -> list[Definition]:
160
+ """Order definitions so that each follows the definitions it depends on, keeping IR order otherwise.
161
+
162
+ Each step takes the first definition, in IR order, whose dependencies in the module are all
163
+ placed. Only a union alias has dependencies (its members): an alias must follow a type it names
164
+ bare, while a forward reference in a ``TypedDict`` field is a string and needs no ordering.
165
+ """
166
+ names = {definition.name for definition, _ in items}
167
+ pending = [(definition, depends & names) for definition, depends in items]
168
+ placed: set[str] = set()
169
+ ordered: list[Definition] = []
170
+ while pending:
171
+ ready = next((index for index, (_, depends) in enumerate(pending) if depends <= placed), None)
172
+ if ready is None:
173
+ cycle = ", ".join(sorted(definition.name for definition, _ in pending))
174
+ msg = f"union members form a cycle among: {cycle}"
175
+ raise IRError(msg)
176
+ definition, _ = pending.pop(ready)
177
+ placed.add(definition.name)
178
+ ordered.append(definition)
179
+ return ordered
180
+
181
+
182
+ def module_from_ir(ir: object) -> Module:
183
+ """Build the module for a Wesley IR document (the parsed JSON of ``wesley schema lower --json``).
184
+
185
+ Raises :class:`IRError` when the IR is malformed or its version is not ``1.0.0``, and
186
+ ``ValueError`` when a type name cannot be a Python name.
187
+ """
188
+ root = _object(ir, "IR")
189
+ version = root.get("version")
190
+ if version != SUPPORTED_IR_VERSION:
191
+ msg = f"unsupported IR version {version!r}: this target reads IR version {SUPPORTED_IR_VERSION}"
192
+ raise IRError(msg)
193
+ types = _array(_get(root, "types", "IR"), "IR.types")
194
+
195
+ records: list[tuple[dict[str, object], str, str, str]] = []
196
+ kinds: dict[str, str] = {}
197
+ for index, value in enumerate(types):
198
+ path = f"types[{index}]"
199
+ record = _object(value, path)
200
+ name = _string(_get(record, "name", path), f"{path}.name")
201
+ kind = _string(_get(record, "kind", path), f"{path}.kind")
202
+ if kind not in _KINDS:
203
+ msg = f"{path}.kind {kind!r} is not one of {', '.join(sorted(_KINDS))}"
204
+ raise IRError(msg)
205
+ kinds[name] = kind
206
+ records.append((record, name, kind, path))
207
+
208
+ reader = _Reader(kinds)
209
+ emitted: list[tuple[Definition, set[str]]] = []
210
+ for record, name, kind, path in records:
211
+ definition = reader.definition(record, name, kind, path)
212
+ if definition is not None:
213
+ members = _strings(record, "unionMembers", path) if kind == "UNION" else []
214
+ emitted.append((definition, set(members)))
215
+ return Module(
216
+ _alias_order(emitted),
217
+ doc=f"Generated by wesley-python from Wesley IR {SUPPORTED_IR_VERSION}. Do not edit.",
218
+ )
wesley_python/py.typed ADDED
File without changes
@@ -0,0 +1,270 @@
1
+ # Copyright 2026 Captain James
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Definitions and modules: the statements of a generated module, built as an ``ast`` tree.
4
+
5
+ A :class:`Module` holds definitions in the order the caller gives. :func:`to_ast` builds the
6
+ ``ast.Module`` and :func:`render` prints it with ``ast.unparse``. No source text is assembled here:
7
+ every identifier, key and docstring enters the tree as a node, and the printer does the escaping.
8
+
9
+ A ``TypedDict`` is rendered so that it runs on Python 3.9, accepts keys that are Python keywords and
10
+ marks optional keys without ``typing.NotRequired`` (new in 3.11). The required keys and the optional
11
+ keys are each a functional-form ``TypedDict`` (the second one ``total=False``), and a class named by
12
+ the definition inherits from both, carrying the docstring. A side with no keys is left out.
13
+
14
+ Definitions are emitted in the given order; the caller orders them. A reference to a definition
15
+ that comes later in the module is printed as a string forward reference, so the module imports. An
16
+ alias whose whole type is such a reference is refused, because a type checker reads ``A = 'B'`` as
17
+ a string, not an alias; define the referenced type first.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import ast
23
+ from dataclasses import dataclass
24
+ from typing import TYPE_CHECKING, Union
25
+
26
+ from wesley_python.types import RenderContext, TypeExpr, check_identifier
27
+
28
+ if TYPE_CHECKING:
29
+ from collections.abc import Sequence
30
+
31
+ __all__ = ["AliasDef", "Definition", "Field", "Module", "TypedDictDef", "render", "to_ast"]
32
+
33
+ _CLASS_INDENT = " "
34
+
35
+
36
+ def _check_instance(value: object, kinds: type | tuple[type, ...], message: str) -> None:
37
+ """Raise ``TypeError`` with ``message`` unless ``value`` is an instance of ``kinds``.
38
+
39
+ The annotations already say this; the check is for callers that are not type-checked.
40
+ """
41
+ if not isinstance(value, kinds):
42
+ raise TypeError(message)
43
+
44
+
45
+ def _check_doc(doc: object) -> None:
46
+ _check_instance(doc, (str, type(None)), f"a doc must be a string or None, not {doc!r}")
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Field:
51
+ """One key of a ``TypedDict``. The key may be any string, including a Python keyword."""
52
+
53
+ name: str
54
+ type: TypeExpr
55
+ required: bool
56
+ doc: str | None = None
57
+
58
+ def __post_init__(self) -> None:
59
+ """Check the parts."""
60
+ _check_instance(self.name, str, f"a field name must be a string, not {self.name!r}")
61
+ _check_instance(self.type, TypeExpr, f"field {self.name!r} needs a type expression, not {self.type!r}")
62
+ _check_instance(self.required, bool, f"field {self.name!r}: required must be a bool")
63
+ _check_doc(self.doc)
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class TypedDictDef:
68
+ """A ``TypedDict`` named ``name`` with the given fields."""
69
+
70
+ name: str
71
+ fields: Sequence[Field]
72
+ doc: str | None = None
73
+
74
+ def __post_init__(self) -> None:
75
+ """Check the parts and keep the fields as a tuple."""
76
+ check_identifier(self.name, "a TypedDict name")
77
+ fields = tuple(self.fields)
78
+ seen: set[str] = set()
79
+ for field in fields:
80
+ _check_instance(field, Field, f"{self.name}: {field!r} is not a Field")
81
+ if field.name in seen:
82
+ msg = f"{self.name}: field {field.name!r} is defined twice"
83
+ raise ValueError(msg)
84
+ seen.add(field.name)
85
+ _check_doc(self.doc)
86
+ object.__setattr__(self, "fields", fields)
87
+
88
+ @property
89
+ def required_name(self) -> str:
90
+ """The name bound to the functional ``TypedDict`` of required keys."""
91
+ return f"_{self.name}Required"
92
+
93
+ @property
94
+ def optional_name(self) -> str:
95
+ """The name bound to the functional ``TypedDict`` of optional keys."""
96
+ return f"_{self.name}Optional"
97
+
98
+ def bound_names(self) -> list[str]:
99
+ """Every module-level name this definition binds."""
100
+ names: list[str] = []
101
+ if any(field.required for field in self.fields):
102
+ names.append(self.required_name)
103
+ if any(not field.required for field in self.fields):
104
+ names.append(self.optional_name)
105
+ names.append(self.name)
106
+ return names
107
+
108
+ def statements(self, context: RenderContext) -> list[ast.stmt]:
109
+ """Build the helper assignments and the class."""
110
+ statements: list[ast.stmt] = []
111
+ bases: list[ast.expr] = []
112
+ for name, required in ((self.required_name, True), (self.optional_name, False)):
113
+ fields = [field for field in self.fields if field.required is required]
114
+ if not fields:
115
+ continue
116
+ keys: list[ast.expr | None] = [ast.Constant(value=field.name) for field in fields]
117
+ values = [field.type.to_ast(context) for field in fields]
118
+ call = ast.Call(
119
+ func=context.typing_name("TypedDict"),
120
+ args=[ast.Constant(value=name), ast.Dict(keys=keys, values=values)],
121
+ keywords=[] if required else [ast.keyword(arg="total", value=ast.Constant(value=False))],
122
+ )
123
+ statements.append(ast.Assign(targets=[ast.Name(id=name, ctx=ast.Store())], value=call))
124
+ bases.append(ast.Name(id=name, ctx=ast.Load()))
125
+ if not bases:
126
+ bases.append(context.typing_name("TypedDict"))
127
+ field_docs = [(field.name, field.doc) for field in self.fields if field.doc is not None]
128
+ docstring = _docstring(self.doc, field_docs, _CLASS_INDENT)
129
+ body: list[ast.stmt] = [ast.Pass()] if docstring is None else [_string_statement(docstring)]
130
+ statements.append(ast.ClassDef(name=self.name, bases=bases, keywords=[], body=body, decorator_list=[]))
131
+ return statements
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class AliasDef:
136
+ """A type alias, ``name = type``. A doc follows it as a string statement."""
137
+
138
+ name: str
139
+ type: TypeExpr
140
+ doc: str | None = None
141
+
142
+ def __post_init__(self) -> None:
143
+ """Check the parts."""
144
+ check_identifier(self.name, "an alias name")
145
+ _check_instance(self.type, TypeExpr, f"alias {self.name} needs a type expression, not {self.type!r}")
146
+ _check_doc(self.doc)
147
+
148
+ def bound_names(self) -> list[str]:
149
+ """Every module-level name this definition binds."""
150
+ return [self.name]
151
+
152
+ def statements(self, context: RenderContext) -> list[ast.stmt]:
153
+ """Build the assignment and its doc.
154
+
155
+ Raises ``ValueError`` when the whole type is a reference to a definition that comes later:
156
+ ``Name = 'Later'`` would bind a string, which a type checker does not read as an alias, and
157
+ Python 3.9 has no ``typing.TypeAlias`` to say otherwise. A forward reference inside a
158
+ subscript, such as ``List['Later']``, is a type expression and stays allowed.
159
+
160
+ A whole type of ``None`` is written ``Literal[None]``: ``Name = None`` would bind the value
161
+ ``None``, not an alias, and ``Literal[None]`` means the same type (PEP 586).
162
+ """
163
+ value = self.type.to_ast(context)
164
+ if isinstance(value, ast.Constant) and value.value is None:
165
+ value = ast.Subscript(value=context.typing_name("Literal"), slice=value, ctx=ast.Load())
166
+ # Only a forward reference renders as a bare string: a Literal's string sits in a subscript.
167
+ forward = _bare_string(value)
168
+ if forward is not None:
169
+ msg = f"alias {self.name} is a bare reference to {forward}, which is defined later; define {forward} first"
170
+ raise ValueError(msg)
171
+ target = ast.Name(id=self.name, ctx=ast.Store())
172
+ statements: list[ast.stmt] = [ast.Assign(targets=[target], value=value)]
173
+ if self.doc is not None:
174
+ statements.append(_string_statement(self.doc))
175
+ return statements
176
+
177
+
178
+ Definition = Union[TypedDictDef, AliasDef]
179
+
180
+
181
+ @dataclass(frozen=True)
182
+ class Module:
183
+ """A module: an optional docstring, the ``typing`` import, then the definitions in order."""
184
+
185
+ definitions: Sequence[Definition]
186
+ doc: str | None = None
187
+
188
+ def __post_init__(self) -> None:
189
+ """Check the parts and keep the definitions as a tuple."""
190
+ definitions = tuple(self.definitions)
191
+ for definition in definitions:
192
+ _check_instance(
193
+ definition, (TypedDictDef, AliasDef), f"{definition!r} is not a TypedDictDef or an AliasDef"
194
+ )
195
+ _check_doc(self.doc)
196
+ object.__setattr__(self, "definitions", definitions)
197
+
198
+
199
+ def _bare_string(value: ast.expr) -> str | None:
200
+ """Return the string if ``value`` is a bare string constant, else ``None``."""
201
+ if isinstance(value, ast.Constant) and isinstance(value.value, str):
202
+ return value.value
203
+ return None
204
+
205
+
206
+ def _string_statement(text: str) -> ast.Expr:
207
+ return ast.Expr(value=ast.Constant(value=text))
208
+
209
+
210
+ def _indent_continuation(text: str, indent: str) -> str:
211
+ """Indent every line after the first that has content."""
212
+ first, *rest = text.split("\n")
213
+ return "\n".join([first, *[indent + line if line else line for line in rest]])
214
+
215
+
216
+ def _docstring(doc: str | None, field_docs: list[tuple[str, str]], indent: str) -> str | None:
217
+ """Compose the docstring value: the doc, then a definition list of field docs.
218
+
219
+ ``ast.unparse`` prints the value as it is, so lines after the first carry the indentation of the
220
+ body they sit in, and a docstring of several lines ends on a line of its own.
221
+ """
222
+ paragraphs = [] if doc is None else [doc]
223
+ if field_docs:
224
+ entries = [_indent_continuation(f"{name}: {text}", " ") for name, text in field_docs]
225
+ paragraphs.append("\n".join(entries))
226
+ if not paragraphs:
227
+ return None
228
+ text = "\n\n".join(paragraphs)
229
+ if "\n" not in text:
230
+ return text
231
+ return _indent_continuation(text, indent) + "\n" + indent
232
+
233
+
234
+ def to_ast(module: Module) -> ast.Module:
235
+ """Build the ``ast.Module`` for ``module``, with locations filled in so that it compiles.
236
+
237
+ Raises ``ValueError`` when two definitions bind the same name, or a definition shadows a name
238
+ the module uses from ``typing`` or the builtins.
239
+ """
240
+ bound = [(index, name) for index, d in enumerate(module.definitions) for name in d.bound_names()]
241
+ names = [name for _, name in bound]
242
+ duplicates = sorted({name for name in names if names.count(name) > 1})
243
+ if duplicates:
244
+ msg = f"names bound more than once: {', '.join(duplicates)}"
245
+ raise ValueError(msg)
246
+
247
+ context = RenderContext()
248
+ statements: list[ast.stmt] = []
249
+ for index, definition in enumerate(module.definitions):
250
+ context.unbound = frozenset(name for at, name in bound if at >= index)
251
+ statements.extend(definition.statements(context))
252
+
253
+ shadowed = sorted(set(names) & (context.typing_names | context.builtin_names))
254
+ if shadowed:
255
+ msg = f"definitions shadow names the module uses: {', '.join(shadowed)}"
256
+ raise ValueError(msg)
257
+
258
+ head: list[ast.stmt] = []
259
+ docstring = _docstring(module.doc, [], "")
260
+ if docstring is not None:
261
+ head.append(_string_statement(docstring))
262
+ if context.typing_names:
263
+ aliases = [ast.alias(name=name) for name in sorted(context.typing_names)]
264
+ head.append(ast.ImportFrom(module="typing", names=aliases, level=0))
265
+ return ast.fix_missing_locations(ast.Module(body=[*head, *statements], type_ignores=[]))
266
+
267
+
268
+ def render(module: Module) -> str:
269
+ """Print ``module`` with ``ast.unparse``, ending in exactly one newline."""
270
+ return ast.unparse(to_ast(module)).rstrip("\n") + "\n"
wesley_python/types.py ADDED
@@ -0,0 +1,220 @@
1
+ # Copyright 2026 Captain James
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Type expressions: the right-hand side of a field or an alias, built as ``ast`` nodes.
4
+
5
+ Each class describes one Python type and knows how to become an ``ast.expr``. Rendering records
6
+ which ``typing`` names it used, so the module imports exactly those.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import keyword
13
+ from dataclasses import dataclass
14
+ from typing import TYPE_CHECKING, Union
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Iterable
18
+
19
+ LiteralValue = Union[str, int, bool]
20
+
21
+
22
+ def check_identifier(name: object, what: str) -> str:
23
+ """Return ``name`` if it can be bound as a Python name; raise ``ValueError`` otherwise."""
24
+ if not isinstance(name, str) or not name.isidentifier() or keyword.iskeyword(name):
25
+ msg = f"{what} {name!r} is not a Python identifier"
26
+ raise ValueError(msg)
27
+ return name
28
+
29
+
30
+ class RenderContext:
31
+ """What a type expression needs while it is rendered: imports to record, names not yet bound."""
32
+
33
+ def __init__(self, unbound: Iterable[str] = ()) -> None:
34
+ """Start with no imports; ``unbound`` are module names defined at or after this point."""
35
+ self.typing_names: set[str] = set()
36
+ self.builtin_names: set[str] = set()
37
+ self.unbound: frozenset[str] = frozenset(unbound)
38
+
39
+ def typing_name(self, name: str) -> ast.Name:
40
+ """Build a name from ``typing`` and record it for the module's import."""
41
+ self.typing_names.add(name)
42
+ return ast.Name(id=name, ctx=ast.Load())
43
+
44
+ def builtin_name(self, name: str) -> ast.Name:
45
+ """Build a builtin type name and record it so that no definition may shadow it."""
46
+ self.builtin_names.add(name)
47
+ return ast.Name(id=name, ctx=ast.Load())
48
+
49
+
50
+ class TypeExpr:
51
+ """A Python type expression."""
52
+
53
+ def to_ast(self, context: RenderContext) -> ast.expr:
54
+ """Build the expression, recording in ``context`` the names it uses."""
55
+ raise NotImplementedError
56
+
57
+
58
+ def _subscript(value: ast.expr, items: list[ast.expr]) -> ast.Subscript:
59
+ """``value[items]``; one item is the slice itself, several are a tuple."""
60
+ index: ast.expr = items[0] if len(items) == 1 else ast.Tuple(elts=items, ctx=ast.Load())
61
+ return ast.Subscript(value=value, slice=index, ctx=ast.Load())
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Str(TypeExpr):
66
+ """``str``."""
67
+
68
+ def to_ast(self, context: RenderContext) -> ast.expr:
69
+ """Build ``str``."""
70
+ return context.builtin_name("str")
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class Int(TypeExpr):
75
+ """``int``."""
76
+
77
+ def to_ast(self, context: RenderContext) -> ast.expr:
78
+ """Build ``int``."""
79
+ return context.builtin_name("int")
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class Float(TypeExpr):
84
+ """``float``."""
85
+
86
+ def to_ast(self, context: RenderContext) -> ast.expr:
87
+ """Build ``float``."""
88
+ return context.builtin_name("float")
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class Bool(TypeExpr):
93
+ """``bool``."""
94
+
95
+ def to_ast(self, context: RenderContext) -> ast.expr:
96
+ """Build ``bool``."""
97
+ return context.builtin_name("bool")
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class AnyValue(TypeExpr):
102
+ """``typing.Any``."""
103
+
104
+ def to_ast(self, context: RenderContext) -> ast.expr:
105
+ """Build ``Any``."""
106
+ return context.typing_name("Any")
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class NoneType(TypeExpr):
111
+ """``None``."""
112
+
113
+ def to_ast(self, context: RenderContext) -> ast.expr: # noqa: ARG002 - the interface's signature
114
+ """Build ``None``."""
115
+ return ast.Constant(value=None)
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class Literal(TypeExpr):
120
+ """``typing.Literal[value]`` for one ``str``, ``int`` or ``bool``."""
121
+
122
+ value: LiteralValue
123
+
124
+ def __post_init__(self) -> None:
125
+ """Refuse a value ``typing.Literal`` cannot hold."""
126
+ if type(self.value) not in {str, int, bool}:
127
+ msg = f"a Literal holds a str, int or bool, not {self.value!r}"
128
+ raise TypeError(msg)
129
+
130
+ def to_ast(self, context: RenderContext) -> ast.expr:
131
+ """Build ``Literal[value]``."""
132
+ return _subscript(context.typing_name("Literal"), [ast.Constant(value=self.value)])
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class ListOf(TypeExpr):
137
+ """``typing.List[item]``."""
138
+
139
+ item: TypeExpr
140
+
141
+ def __post_init__(self) -> None:
142
+ """Refuse an item that is not a type expression."""
143
+ _check_type(self.item, "a list item")
144
+
145
+ def to_ast(self, context: RenderContext) -> ast.expr:
146
+ """Build ``List[item]``."""
147
+ return _subscript(context.typing_name("List"), [self.item.to_ast(context)])
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class DictOf(TypeExpr):
152
+ """``typing.Dict[str, value]``."""
153
+
154
+ value: TypeExpr
155
+
156
+ def __post_init__(self) -> None:
157
+ """Refuse a value that is not a type expression."""
158
+ _check_type(self.value, "a dict value")
159
+
160
+ def to_ast(self, context: RenderContext) -> ast.expr:
161
+ """Build ``Dict[str, value]``."""
162
+ key = context.builtin_name("str")
163
+ return _subscript(context.typing_name("Dict"), [key, self.value.to_ast(context)])
164
+
165
+
166
+ @dataclass(frozen=True)
167
+ class Ref(TypeExpr):
168
+ """A named type defined in the module, or imported into it by the caller.
169
+
170
+ A reference to a name the module defines later is a string forward reference, so the module
171
+ imports at run time; every other reference is a plain name.
172
+ """
173
+
174
+ name: str
175
+
176
+ def __post_init__(self) -> None:
177
+ """Refuse a name that cannot be bound."""
178
+ check_identifier(self.name, "a referenced type name")
179
+
180
+ def to_ast(self, context: RenderContext) -> ast.expr:
181
+ """Build ``Name`` or, for a definition not yet bound, ``'Name'``."""
182
+ if self.name in context.unbound:
183
+ return ast.Constant(value=self.name)
184
+ return ast.Name(id=self.name, ctx=ast.Load())
185
+
186
+
187
+ @dataclass(frozen=True, init=False)
188
+ class UnionOf(TypeExpr):
189
+ """``typing.Union[...]``.
190
+
191
+ One member renders as itself. Members that are all literals render as one ``Literal[...]``.
192
+ """
193
+
194
+ members: tuple[TypeExpr, ...]
195
+
196
+ def __init__(self, *members: TypeExpr) -> None:
197
+ """Hold at least one member."""
198
+ if not members:
199
+ msg = "a union needs at least one member"
200
+ raise ValueError(msg)
201
+ for member in members:
202
+ _check_type(member, "a union member")
203
+ object.__setattr__(self, "members", tuple(members))
204
+
205
+ def to_ast(self, context: RenderContext) -> ast.expr:
206
+ """Build ``Union[...]``, ``Literal[...]`` or the single member."""
207
+ if len(self.members) == 1:
208
+ return self.members[0].to_ast(context)
209
+ literals = [member for member in self.members if isinstance(member, Literal)]
210
+ if len(literals) == len(self.members):
211
+ values: list[ast.expr] = [ast.Constant(value=literal.value) for literal in literals]
212
+ return _subscript(context.typing_name("Literal"), values)
213
+ name = context.typing_name("Union")
214
+ return _subscript(name, [member.to_ast(context) for member in self.members])
215
+
216
+
217
+ def _check_type(value: object, what: str) -> None:
218
+ if not isinstance(value, TypeExpr):
219
+ msg = f"{what} must be a type expression, not {value!r}"
220
+ raise TypeError(msg)
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.4
2
+ Name: wesley-python
3
+ Version: 0.1.0a1
4
+ Summary: A generic Wesley target that emits standard-library Python TypedDicts from Wesley IR.
5
+ Author: flyingrobots
6
+ Maintainer: flyingrobots
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/flyingrobots/wesley-python
9
+ Project-URL: Repository, https://github.com/flyingrobots/wesley-python
10
+ Project-URL: Changelog, https://github.com/flyingrobots/wesley-python/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/flyingrobots/wesley-python/issues
12
+ Keywords: wesley,graphql,typeddict,codegen,code-generation,typing
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Software Development :: Code Generators
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.9
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ License-File: NOTICE
30
+ Dynamic: license-file
31
+
32
+ # wesley-python
33
+
34
+ A [Wesley](https://github.com/flyingrobots/wesley) target that emits stdlib-only Python: `TypedDict` models embeddable in a single-file module.
35
+
36
+ Wesley compiles GraphQL SDL into an intermediate representation (IR), and does nothing else: it attaches no meaning to any directive and runs no targets. Every output language is its own repository, a standalone program and library that reads the IR (`wesley schema lower --json`). This one is a **generic** target: it understands no directives and emits Python from plain GraphQL, and it is the language tooling other targets (such as [wesley-parley](https://github.com/flyingrobots/wesley-parley)) render through. The decisions are recorded in flyingrobots/parley#116 and flyingrobots/wesley#882.
37
+
38
+ ## Status
39
+
40
+ The first release is 0.1.0a1, a pre-release: the package `wesley_python`, with a syntax API for building Python modules of `TypedDict` classes and type aliases, and a plain-GraphQL emitter on the command line. It reads IR version `1.0.0` as Wesley prints it today; the versioned IR contract is still flyingrobots/wesley#881. There is no `--fragment` mode, no marker-wrapped output and no generated header naming the schema hash yet (#1).
41
+
42
+ The package runs on Python 3.9 or later and imports nothing outside the standard library. Its generated modules do the same.
43
+
44
+ ## Install
45
+
46
+ ```sh
47
+ pip install wesley-python==0.1.0a1
48
+ ```
49
+
50
+ The package is `wesley-python` on PyPI and `wesley_python` to import. While every release is a pre-release, `pip install wesley-python` needs `--pre` or an exact version.
51
+
52
+ ## Usage
53
+
54
+ ### The command line
55
+
56
+ ```sh
57
+ wesley schema lower --schema schema.graphql --json | python -m wesley_python emit > models.py
58
+ python -m wesley_python emit --ir ir.json --out models.py
59
+ ```
60
+
61
+ `emit` reads Wesley IR JSON from `--ir` (standard input by default) and writes a module to `--out` (standard output by default). An IR whose `version` is not `1.0.0`, malformed IR or invalid JSON is an error: a message on standard error and exit status 1. Installing the package also installs the same command as `wesley-python`.
62
+
63
+ The emitter is generic: it ignores every directive. It maps GraphQL as follows.
64
+
65
+ | GraphQL | Python |
66
+ | --- | --- |
67
+ | `type`, `input`, `interface` | a `TypedDict`; every field is a required key |
68
+ | nullable field `T` | `Union[T, None]`: GraphQL null is a value, not an absent key |
69
+ | `[T!]`, `[T]` | `List[T]`, `List[Union[T, None]]` |
70
+ | `enum` | an alias of `Literal['A', 'B', ...]` of the value names |
71
+ | `union` | an alias of `Union[...]` of the members |
72
+ | `String`, `ID`, `Int`, `Float`, `Boolean` | `str`, `str`, `int`, `float`, `bool` |
73
+ | any other scalar | `Any` |
74
+
75
+ Types are written in IR order, except that a union alias moves to just after the last of its members: a type checker reads `A = 'B'` as a string, not as an alias, and Python 3.9 has no `typing.TypeAlias`. A reference to a type written later, inside a field or a subscript such as `List['B']`, is a string forward reference, so the module imports.
76
+
77
+ ### The syntax API
78
+
79
+ Other targets build modules with the syntax API and print them with `render`. Optional keys, keys that are Python keywords and `Literal` values all work on Python 3.9.
80
+
81
+ ```python
82
+ from wesley_python.syntax import Field, Module, TypedDictDef, render
83
+ from wesley_python.types import Int, Literal, Ref
84
+
85
+ module = Module(
86
+ [
87
+ TypedDictDef(
88
+ "Window",
89
+ [
90
+ Field("from", Int(), required=True, doc="The first line, inclusive."),
91
+ Field("to", Int(), required=False),
92
+ ],
93
+ doc="A range of line numbers.",
94
+ ),
95
+ TypedDictDef(
96
+ "End",
97
+ [
98
+ Field("event", Literal("end"), required=True),
99
+ Field("window", Ref("Window"), required=False),
100
+ ],
101
+ ),
102
+ ]
103
+ )
104
+ print(render(module), end="")
105
+ ```
106
+
107
+ prints, exactly as `ast.unparse` lays it out,
108
+
109
+ ```text
110
+ from typing import Literal, TypedDict
111
+ _WindowRequired = TypedDict('_WindowRequired', {'from': int})
112
+ _WindowOptional = TypedDict('_WindowOptional', {'to': int}, total=False)
113
+
114
+ class Window(_WindowRequired, _WindowOptional):
115
+ """A range of line numbers.
116
+
117
+ from: The first line, inclusive.
118
+ """
119
+ _EndRequired = TypedDict('_EndRequired', {'event': Literal['end']})
120
+ _EndOptional = TypedDict('_EndOptional', {'window': Window}, total=False)
121
+
122
+ class End(_EndRequired, _EndOptional):
123
+ pass
124
+ ```
125
+
126
+ - `wesley_python.types`: `Str()`, `Int()`, `Float()`, `Bool()`, `AnyValue()`, `NoneType()`, `Literal(value)` for a `str`, `int` or `bool`, `ListOf(item)`, `DictOf(value)` (string keys), `Ref(name)` for a type the module defines, and `UnionOf(*members)`. A union of one member prints as that member, and a union of literals prints as one `Literal[...]`.
127
+ - `wesley_python.syntax`: `Field(name, type, required, doc=None)`, `TypedDictDef(name, fields, doc=None)`, `AliasDef(name, type, doc=None)`, `Module(definitions, doc=None)`, `to_ast(module)` returning the `ast.Module`, and `render(module)` returning its source, ending in one newline.
128
+
129
+ How a `TypedDict` is written: `typing.NotRequired` is new in Python 3.11, and the class syntax cannot name a key such as `from`. So the required keys and the optional keys are each a functional-form `TypedDict`, the optional one `total=False`, and the class inherits from both; a side with no keys is left out, and a definition with no keys inherits from `TypedDict`. `ast.unparse` cannot print comments, so field docs go into the class docstring as a `name: doc` list, and an alias's doc is a string statement after it. The `from typing import ...` line names exactly the names used, sorted.
130
+
131
+ The caller orders the definitions; `render` keeps the given order. A reference to a later definition is a string forward reference, which is allowed inside a field type or a subscript but not as the whole type of an alias: `AliasDef('Result', Ref('Item'))` before `Item` is a `ValueError` naming both. An alias whose whole type is `None` is written `Name = Literal[None]`, because `Name = None` binds a value rather than an alias. A definition name must be a Python identifier; two definitions may not bind the same name (including the `_NameRequired` and `_NameOptional` helpers), and a definition may not shadow a `typing` or builtin name the module uses. These are `ValueError`s.
132
+
133
+ ## Development
134
+
135
+ ```sh
136
+ uv venv -p 3.9 .venv && uv pip install -p .venv -r requirements-dev.txt
137
+ git config --local core.hooksPath scripts/hooks
138
+ PYTHONPATH=src .venv/bin/python -m unittest discover -s tests -t .
139
+ .venv/bin/ruff check . && .venv/bin/ruff format --check . && .venv/bin/mypy
140
+ ```
141
+
142
+ `requirements-dev.txt` pins mypy, ruff, build and twine exactly; they are development tools, not dependencies. The pre-commit hook runs ruff and mypy, and the pre-push hook runs the test suite. CI runs all of it on Python 3.9 and 3.13. It also builds the sdist and wheel, checks them with `twine check --strict` and for `LICENSE` and `NOTICE`, and installs the wheel into fresh environments to run it (`scripts/check-dist`).
143
+
144
+ Releases are made by pushing an annotated tag; [RELEASING.md](https://github.com/flyingrobots/wesley-python/blob/main/RELEASING.md) describes the procedure.
145
+
146
+ The goldens under `tests/golden/` are compared byte for byte, compiled with `py_compile`, imported, and type-checked by `mypy --strict --python-version 3.9` together with the fixtures under `tests/typecheck/`: the good uses must pass and each `bad_*.py` must fail with its expected error (a wrong `event` literal, a keyword key read as the wrong type, a missing required key). To rewrite the goldens after an intended change, run the suite with `WESLEY_PYTHON_UPDATE_GOLDENS=1` and review the diff.
147
+
148
+ ## Where it comes from
149
+
150
+ The plan is issue #1 (transferred from flyingrobots/wesley#858). Its first consumer is Parley's vendorable Python writer (flyingrobots/parley#121).
151
+
152
+ ## How it generates code
153
+
154
+ The output is built as a syntax tree of the target language and printed by that language's printer. There is no string templating and no regex anywhere in the generator.
155
+
156
+ | Concern | Choice |
157
+ | --- | --- |
158
+ | Written in | Python 3.9 or later, standard library only |
159
+ | Syntax tree | the standard library `ast` module |
160
+ | Printer | `ast.unparse` |
161
+ | Checked by | `py_compile` and a static type checker on every golden module, on the oldest and newest supported Python |
162
+
163
+ Rules every change keeps:
164
+
165
+ - **No code as strings.** A generated identifier, literal or comment enters the output as a node of the tree, never by concatenating source text. Escaping is the printer's job.
166
+ - **Golden output is checked by the real toolchain.** Every golden file is compiled or type-checked in CI by the toolchain named above, not only compared byte for byte.
167
+ - **Deterministic to the byte.** The same IR and options give the same bytes on every machine. CI runs the generator twice and compares.
168
+ - **The IR is the only input.** The target reads the published IR (flyingrobots/wesley#881) and never depends on Wesley's internals.
169
+
170
+ ## License
171
+
172
+ Apache 2.0. See [LICENSE](https://github.com/flyingrobots/wesley-python/blob/main/LICENSE) and [NOTICE](https://github.com/flyingrobots/wesley-python/blob/main/NOTICE).
@@ -0,0 +1,14 @@
1
+ wesley_python/__init__.py,sha256=ZBeC_SqWoFK7RDmFiLkzqoIcorIBjv8xdliBEirZ0lk,353
2
+ wesley_python/__main__.py,sha256=erV09OnNzShBpZFIvn7KyAYIwdFizhe9KY7Wxj3WeSQ,224
3
+ wesley_python/cli.py,sha256=dJXqv01iUltKp88ExvAD5-KAvgez20KiXLgU-dCREN4,2071
4
+ wesley_python/emit.py,sha256=jLq-geOkhscu7tpZGdztT9IPW1eGtBqVHiHp_q6OtPQ,8586
5
+ wesley_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ wesley_python/syntax.py,sha256=n866Ov461L89pwmyIR0uc7bhhNLVViOgUsSnPDRTTUk,11523
7
+ wesley_python/types.py,sha256=rjpMuJhlAWVBLrjyZYw_1WQWbAhBOk3sMvFtCqGtN8I,7251
8
+ wesley_python-0.1.0a1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ wesley_python-0.1.0a1.dist-info/licenses/NOTICE,sha256=Ej9_TIhF04uKryJEGksVNYp1Ufue6VxvP9F1UBVsHTk,131
10
+ wesley_python-0.1.0a1.dist-info/METADATA,sha256=cQ_WXFriu0HtYtEysxTpjGeIqZ9qOyGU461vSrc3mfI,10561
11
+ wesley_python-0.1.0a1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ wesley_python-0.1.0a1.dist-info/entry_points.txt,sha256=UFuSbY4LPi_rDQXyl81tYRLDVl8UpXuhkGzvb5A61uw,57
13
+ wesley_python-0.1.0a1.dist-info/top_level.txt,sha256=mu-XH4pF_5Gk2f4d-Kb0ASoWDZpAMllAvIf_13yETnU,14
14
+ wesley_python-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ wesley-python = wesley_python.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ wesley-python
2
+ Copyright 2026 Captain James
3
+
4
+ This product includes software developed at
5
+ FLYING ROBOTS (https://flyingrobots.dev/).
@@ -0,0 +1 @@
1
+ wesley_python