@dbx-tools/dbx-model-catalog 0.1.5 → 0.1.6

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.
Files changed (42) hide show
  1. package/README.md +46 -9
  2. package/dist/_generated/json-schema.d.ts +3830 -0
  3. package/dist/_generated/published.d.ts +1 -1
  4. package/dist/_generated/schemas.d.ts +27 -2
  5. package/dist/browser.d.ts +11 -3
  6. package/dist/browser.js +9480 -1150
  7. package/dist/browser.js.map +32 -10
  8. package/dist/catalog-index.d.ts +28 -0
  9. package/dist/catalog.json +1 -0
  10. package/dist/cli.js +8847 -49461
  11. package/dist/cli.js.map +16 -223
  12. package/dist/filter.d.ts +2 -0
  13. package/dist/identity.d.ts +15 -0
  14. package/dist/index.d.ts +8 -4
  15. package/dist/index.js +8843 -49453
  16. package/dist/index.js.map +15 -222
  17. package/dist/local-client.d.ts +4 -0
  18. package/dist/{client.d.ts → pynect.d.ts} +1 -1
  19. package/dist/pynect.js +553 -0
  20. package/dist/pynect.js.map +15 -0
  21. package/dist/search-index.json +1 -0
  22. package/dist/search.d.ts +10 -0
  23. package/dist/snapshot.d.ts +6 -0
  24. package/dist/snapshot.js +9494 -0
  25. package/dist/snapshot.js.map +36 -0
  26. package/dist/types.d.ts +5 -0
  27. package/dist/validation.d.ts +5 -0
  28. package/package.json +27 -2
  29. package/dist/python/pyproject.toml +0 -16
  30. package/dist/python/src/dbx_model_catalog/__init__.py +0 -93
  31. package/dist/python/src/dbx_model_catalog/client.py +0 -256
  32. package/dist/python/src/dbx_model_catalog/database.py +0 -296
  33. package/dist/python/src/dbx_model_catalog/filters.py +0 -41
  34. package/dist/python/src/dbx_model_catalog/models.py +0 -853
  35. package/dist/python/src/dbx_model_catalog/publishing.py +0 -118
  36. package/dist/python/src/dbx_model_catalog/py.typed +0 -0
  37. package/dist/python/src/dbx_model_catalog/query.py +0 -593
  38. package/dist/python/src/dbx_model_catalog/schema/__init__.py +0 -0
  39. package/dist/python/src/dbx_model_catalog/schema/model-catalog.schema.json +0 -1016
  40. package/dist/python/src/dbx_model_catalog/search.py +0 -912
  41. package/dist/python/src/dbx_model_catalog_server/__init__.py +0 -3
  42. package/dist/python/src/dbx_model_catalog_server/app.py +0 -142
@@ -1,593 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import json
4
- import re
5
- from collections.abc import Callable, Mapping, Sequence
6
- from functools import cmp_to_key
7
- from importlib.resources import files
8
- from typing import Any, Literal, TypeAlias
9
-
10
- from pydantic import (
11
- AliasChoices,
12
- BaseModel,
13
- ConfigDict,
14
- Field,
15
- JsonValue,
16
- model_validator,
17
- )
18
-
19
- from .models import CatalogModelRecord
20
-
21
- CatalogQueryExpression: TypeAlias = Mapping[str, JsonValue]
22
- CatalogPredicate: TypeAlias = Callable[[CatalogModelRecord], bool]
23
- CatalogQuery: TypeAlias = CatalogQueryExpression | CatalogPredicate
24
- SortDirection: TypeAlias = Literal["asc", "desc"]
25
-
26
- _OPERATORS = {
27
- "$gt",
28
- "$gte",
29
- "$lt",
30
- "$lte",
31
- "$eq",
32
- "$ne",
33
- "$in",
34
- "$nin",
35
- "$contains",
36
- "$size",
37
- "$startsWith",
38
- "$endsWith",
39
- "$regex",
40
- "$match",
41
- }
42
- _LOGICAL_OPERATORS = {"$and", "$or", "$not"}
43
- _NUMBER_OPERATORS = {"$gt", "$gte", "$lt", "$lte"}
44
- _STRING_OPERATORS = {"$startsWith", "$endsWith", "$regex", "$match"}
45
- _ARRAY_OPERATORS = {"$in", "$nin"}
46
-
47
-
48
- class CatalogOrderByField(BaseModel):
49
- model_config = ConfigDict(extra="forbid")
50
-
51
- field: str
52
- direction: SortDirection
53
-
54
-
55
- CatalogOrderBy: TypeAlias = (
56
- str
57
- | CatalogOrderByField
58
- | Sequence[str | CatalogOrderByField | Mapping[str, str]]
59
- | Mapping[str, str]
60
- )
61
-
62
-
63
- class CatalogQueryOptions(BaseModel):
64
- model_config = ConfigDict(extra="forbid", populate_by_name=True)
65
-
66
- case_sensitive: bool = Field(
67
- default=False,
68
- validation_alias=AliasChoices("case_sensitive", "caseSensitive"),
69
- serialization_alias="caseSensitive",
70
- )
71
- max_depth: int = Field(
72
- default=3,
73
- ge=0,
74
- validation_alias=AliasChoices("max_depth", "maxDepth"),
75
- serialization_alias="maxDepth",
76
- )
77
- order_by: CatalogOrderBy | None = Field(
78
- default=None,
79
- validation_alias=AliasChoices("order_by", "orderBy"),
80
- serialization_alias="orderBy",
81
- )
82
- limit: int | None = Field(default=None, ge=0)
83
-
84
- @model_validator(mode="after")
85
- def validate_order_by(self) -> CatalogQueryOptions:
86
- for order in _normalize_order_by(self.order_by):
87
- _validate_sort_field(order.field)
88
- return self
89
-
90
-
91
- class SerializableCatalogQuery(BaseModel):
92
- model_config = ConfigDict(extra="forbid")
93
-
94
- expression: dict[str, JsonValue]
95
- options: CatalogQueryOptions | None = None
96
-
97
- @model_validator(mode="after")
98
- def validate_expression(self) -> SerializableCatalogQuery:
99
- _validate_expression(self.expression, [_record_schema()], [])
100
- return self
101
-
102
-
103
- def parse_catalog_query(value: str | Mapping[str, object]) -> SerializableCatalogQuery:
104
- parsed = json.loads(value) if isinstance(value, str) else value
105
- return SerializableCatalogQuery.model_validate(parsed)
106
-
107
-
108
- def serialize_catalog_query(query: SerializableCatalogQuery | Mapping[str, object]) -> str:
109
- parsed = SerializableCatalogQuery.model_validate(query)
110
- return parsed.model_dump_json(
111
- by_alias=True,
112
- exclude_none=True,
113
- exclude_unset=True,
114
- )
115
-
116
-
117
- def query_catalog_records(
118
- records: Sequence[CatalogModelRecord],
119
- expression: CatalogQuery | None = None,
120
- options: CatalogQueryOptions | Mapping[str, object] | None = None,
121
- ) -> list[CatalogModelRecord]:
122
- parsed_options = CatalogQueryOptions.model_validate(options or {})
123
- predicate = expression or (lambda _: True)
124
- if not callable(predicate):
125
- _validate_expression(predicate, [_record_schema()], [])
126
-
127
- result = [
128
- record
129
- for record in records
130
- if (
131
- predicate(record)
132
- if callable(predicate)
133
- else _matches_value(
134
- record.model_dump(mode="json"),
135
- predicate,
136
- parsed_options.case_sensitive,
137
- )
138
- )
139
- ]
140
-
141
- order_by = _normalize_order_by(parsed_options.order_by)
142
- if order_by:
143
- result.sort(
144
- key=cmp_to_key(
145
- lambda left, right: _compare_records(
146
- left,
147
- right,
148
- order_by,
149
- parsed_options.case_sensitive,
150
- )
151
- )
152
- )
153
- if parsed_options.limit is not None:
154
- result = result[: parsed_options.limit]
155
- return result
156
-
157
-
158
- def _matches_value(actual: object, expression: object, case_sensitive: bool) -> bool:
159
- if _is_field_operator_expression(expression):
160
- return _matches_operators(actual, expression, case_sensitive)
161
-
162
- if isinstance(actual, list):
163
- expressions = expression if isinstance(expression, list) else [expression]
164
- return any(
165
- _matches_value(item, item_expression, case_sensitive)
166
- for item in actual
167
- for item_expression in expressions
168
- )
169
-
170
- if isinstance(expression, Mapping):
171
- if not isinstance(actual, Mapping):
172
- return False
173
- for key, field_expression in expression.items():
174
- if key == "$and":
175
- if not isinstance(field_expression, list) or not all(
176
- _matches_value(actual, child, case_sensitive)
177
- for child in field_expression
178
- ):
179
- return False
180
- elif key == "$or":
181
- if not isinstance(field_expression, list) or not any(
182
- _matches_value(actual, child, case_sensitive)
183
- for child in field_expression
184
- ):
185
- return False
186
- elif key == "$not":
187
- if _matches_value(actual, field_expression, case_sensitive):
188
- return False
189
- elif not _matches_value(
190
- actual.get(key), field_expression, case_sensitive
191
- ):
192
- return False
193
- return True
194
-
195
- if isinstance(expression, list):
196
- return any(
197
- _matches_array_alternative(actual, alternative, case_sensitive)
198
- for alternative in expression
199
- )
200
- return _matches_literal(actual, expression, case_sensitive)
201
-
202
-
203
- def _matches_operators(
204
- actual: object,
205
- operators: Mapping[str, object],
206
- case_sensitive: bool,
207
- ) -> bool:
208
- if "$eq" in operators and actual != operators["$eq"]:
209
- return False
210
- if "$ne" in operators and actual == operators["$ne"]:
211
- return False
212
-
213
- for operator in _NUMBER_OPERATORS:
214
- if operator not in operators:
215
- continue
216
- if not isinstance(actual, (int, float)) or isinstance(actual, bool):
217
- return False
218
- operand = operators[operator]
219
- if not isinstance(operand, (int, float)) or isinstance(operand, bool):
220
- return False
221
- if operator == "$gt" and not actual > operand:
222
- return False
223
- if operator == "$gte" and not actual >= operand:
224
- return False
225
- if operator == "$lt" and not actual < operand:
226
- return False
227
- if operator == "$lte" and not actual <= operand:
228
- return False
229
-
230
- if "$in" in operators and not any(
231
- actual == candidate for candidate in operators["$in"] # type: ignore[union-attr]
232
- ):
233
- return False
234
- if "$nin" in operators and any(
235
- actual == candidate for candidate in operators["$nin"] # type: ignore[union-attr]
236
- ):
237
- return False
238
-
239
- if "$size" in operators:
240
- if not isinstance(actual, list) or len(actual) != operators["$size"]:
241
- return False
242
-
243
- if "$contains" in operators:
244
- operand = operators["$contains"]
245
- if isinstance(actual, str) and isinstance(operand, str):
246
- source, target = _string_pair(actual, operand, case_sensitive)
247
- if target not in source:
248
- return False
249
- elif isinstance(actual, list):
250
- if not any(candidate == operand for candidate in actual):
251
- return False
252
- else:
253
- return False
254
-
255
- for operator, method in (
256
- ("$startsWith", str.startswith),
257
- ("$endsWith", str.endswith),
258
- ):
259
- if operator in operators:
260
- operand = operators[operator]
261
- if not isinstance(actual, str) or not isinstance(operand, str):
262
- return False
263
- source, target = _string_pair(actual, operand, case_sensitive)
264
- if not method(source, target):
265
- return False
266
-
267
- for operator in ("$regex", "$match"):
268
- if operator in operators:
269
- operand = operators[operator]
270
- if not isinstance(actual, str) or not isinstance(operand, str):
271
- return False
272
- flags = 0 if case_sensitive else re.IGNORECASE
273
- if re.search(operand, actual, flags) is None:
274
- return False
275
- return True
276
-
277
-
278
- def _matches_array_alternative(
279
- actual: object, alternative: object, case_sensitive: bool
280
- ) -> bool:
281
- if isinstance(alternative, str) and ("%" in alternative or "_" in alternative):
282
- return _matches_wildcard(actual, alternative, case_sensitive)
283
- return actual == alternative
284
-
285
-
286
- def _matches_literal(actual: object, expression: object, case_sensitive: bool) -> bool:
287
- negate = isinstance(expression, str) and expression.startswith("!")
288
- candidate = expression[1:] if negate else expression
289
- if isinstance(candidate, str) and ("%" in candidate or "_" in candidate):
290
- matches = _matches_wildcard(actual, candidate, case_sensitive)
291
- elif isinstance(actual, str) and isinstance(candidate, str) and not case_sensitive:
292
- matches = actual.casefold() == candidate.casefold()
293
- else:
294
- matches = actual == candidate
295
- return not matches if negate else matches
296
-
297
-
298
- def _matches_wildcard(actual: object, pattern: str, case_sensitive: bool) -> bool:
299
- if not isinstance(actual, str):
300
- return False
301
- escaped = re.escape(pattern).replace("%", ".*").replace("_", ".")
302
- flags = 0 if case_sensitive else re.IGNORECASE
303
- return re.fullmatch(escaped, actual, flags) is not None
304
-
305
-
306
- def _string_pair(left: str, right: str, case_sensitive: bool) -> tuple[str, str]:
307
- return (left, right) if case_sensitive else (left.casefold(), right.casefold())
308
-
309
-
310
- def _normalize_order_by(order_by: CatalogOrderBy | None) -> list[CatalogOrderByField]:
311
- if order_by is None:
312
- return []
313
- if isinstance(order_by, str):
314
- return [CatalogOrderByField(field=order_by, direction="asc")]
315
- if isinstance(order_by, (CatalogOrderByField, Mapping)):
316
- return [CatalogOrderByField.model_validate(order_by)]
317
- return [
318
- CatalogOrderByField(field=item, direction="asc")
319
- if isinstance(item, str)
320
- else CatalogOrderByField.model_validate(item)
321
- for item in order_by
322
- ]
323
-
324
-
325
- def _compare_records(
326
- left: CatalogModelRecord,
327
- right: CatalogModelRecord,
328
- order_by: Sequence[CatalogOrderByField],
329
- case_sensitive: bool,
330
- ) -> int:
331
- for order in order_by:
332
- comparison = _compare_values(
333
- _nested_value(left, order.field),
334
- _nested_value(right, order.field),
335
- order.direction,
336
- case_sensitive,
337
- )
338
- if comparison:
339
- return comparison
340
- return 0
341
-
342
-
343
- def _nested_value(value: object, path: str) -> object:
344
- current = value.model_dump(mode="json") if isinstance(value, BaseModel) else value
345
- for key in path.split("."):
346
- if not isinstance(current, Mapping):
347
- return None
348
- current = current.get(key)
349
- return current
350
-
351
-
352
- def _compare_values(
353
- left: object,
354
- right: object,
355
- direction: SortDirection,
356
- case_sensitive: bool,
357
- ) -> int:
358
- if left is None:
359
- return 1
360
- if right is None:
361
- return -1
362
- if left == right:
363
- return 0
364
- if isinstance(left, str) and isinstance(right, str) and not case_sensitive:
365
- left, right = left.casefold(), right.casefold()
366
- try:
367
- comparison = -1 if left < right else 1 # type: ignore[operator]
368
- except TypeError:
369
- comparison = -1 if str(left) < str(right) else 1
370
- return comparison if direction == "asc" else -comparison
371
-
372
-
373
- def _validate_expression(
374
- value: object,
375
- schemas: Sequence[Mapping[str, object]],
376
- path: list[str | int],
377
- ) -> None:
378
- if value is None or isinstance(value, (str, int, float, bool)):
379
- return
380
- if not isinstance(value, Mapping):
381
- raise ValueError(f"Catalog queries must be JSON primitives or objects at {_path(path)}")
382
-
383
- for key, field_expression in value.items():
384
- field_path = [*path, key]
385
- if key in {"$and", "$or"}:
386
- if not isinstance(field_expression, list) or not field_expression:
387
- raise ValueError(f"{key} requires a non-empty array of expressions")
388
- for index, child in enumerate(field_expression):
389
- _validate_expression(child, schemas, [*field_path, index])
390
- continue
391
- if key == "$not":
392
- _validate_expression(field_expression, schemas, field_path)
393
- continue
394
- if key.startswith("$"):
395
- raise ValueError(f"Unknown logical operator: {key}")
396
-
397
- field_schemas = _child_schemas(schemas, key)
398
- if not field_schemas:
399
- raise ValueError(f"Unknown catalog field: {_path(field_path)}")
400
- if _has_operator_key(field_expression):
401
- _validate_operators(field_expression)
402
- continue
403
- if isinstance(field_expression, Mapping):
404
- nested = [
405
- schema
406
- for field_schema in field_schemas
407
- for schema in _unwrap_array_schemas(field_schema)
408
- if _supports_object(schema)
409
- ]
410
- if not nested:
411
- raise ValueError(
412
- f"Field {_path(field_path)} does not support nested queries"
413
- )
414
- _validate_expression(field_expression, nested, field_path)
415
- continue
416
- if isinstance(field_expression, list):
417
- item_schemas = [
418
- schema
419
- for field_schema in field_schemas
420
- for schema in _unwrap_array_schemas(field_schema)
421
- ]
422
- if any(_supports_object(schema) for schema in item_schemas):
423
- for index, item in enumerate(field_expression):
424
- if isinstance(item, Mapping):
425
- _validate_expression(item, item_schemas, [*field_path, index])
426
- try:
427
- json.dumps(field_expression)
428
- except (TypeError, ValueError) as error:
429
- raise ValueError(
430
- f"Field {_path(field_path)} must use a JSON-compatible value"
431
- ) from error
432
-
433
-
434
- def _validate_operators(operators: Mapping[str, object]) -> None:
435
- for operator, operand in operators.items():
436
- if operator not in _OPERATORS:
437
- raise ValueError(f"Unknown filter operator: {operator}")
438
- if operator in _NUMBER_OPERATORS and not _is_number(operand):
439
- raise ValueError(f"Invalid operand for {operator}")
440
- if operator in _ARRAY_OPERATORS and not isinstance(operand, list):
441
- raise ValueError(f"Invalid operand for {operator}")
442
- if operator == "$size" and (
443
- not isinstance(operand, int) or isinstance(operand, bool) or operand < 0
444
- ):
445
- raise ValueError(f"Invalid operand for {operator}")
446
- if operator in _STRING_OPERATORS and not isinstance(operand, str):
447
- raise ValueError(f"Invalid operand for {operator}")
448
- try:
449
- json.dumps(operand)
450
- except (TypeError, ValueError) as error:
451
- raise ValueError(f"Invalid operand for {operator}") from error
452
-
453
-
454
- def _validate_sort_field(field: str) -> None:
455
- if not field or not _is_catalog_path(field, [_record_schema()]):
456
- raise ValueError(f"Unknown catalog sort field: {field}")
457
-
458
-
459
- def _is_catalog_path(path: str, schemas: Sequence[Mapping[str, object]]) -> bool:
460
- current = list(schemas)
461
- for segment in path.split("."):
462
- current = _child_schemas(
463
- [
464
- schema
465
- for current_schema in current
466
- for schema in _unwrap_array_schemas(current_schema)
467
- ],
468
- segment,
469
- )
470
- if not current:
471
- return False
472
- return True
473
-
474
-
475
- def _child_schemas(
476
- schemas: Sequence[Mapping[str, object]], key: str
477
- ) -> list[Mapping[str, object]]:
478
- result: list[Mapping[str, object]] = []
479
- for schema in schemas:
480
- for variant in _expand_schema(schema):
481
- properties = variant.get("properties")
482
- if isinstance(properties, Mapping) and isinstance(properties.get(key), Mapping):
483
- result.append(properties[key]) # type: ignore[arg-type]
484
- continue
485
- additional = variant.get("additionalProperties")
486
- if isinstance(additional, Mapping) and _matches_property_name(
487
- key, variant.get("propertyNames")
488
- ):
489
- result.append(additional)
490
- return result
491
-
492
-
493
- def _unwrap_array_schemas(
494
- schema: Mapping[str, object],
495
- ) -> list[Mapping[str, object]]:
496
- result: list[Mapping[str, object]] = []
497
- for variant in _expand_schema(schema):
498
- items = variant.get("items")
499
- if variant.get("type") == "array" and isinstance(items, Mapping):
500
- result.extend(_expand_schema(items))
501
- else:
502
- result.append(variant)
503
- return result
504
-
505
-
506
- def _expand_schema(schema: Mapping[str, object]) -> list[Mapping[str, object]]:
507
- variants = schema.get("oneOf") or schema.get("anyOf")
508
- if not isinstance(variants, list):
509
- return [schema]
510
- return [
511
- expanded
512
- for variant in variants
513
- if isinstance(variant, Mapping)
514
- for expanded in _expand_schema(variant)
515
- ]
516
-
517
-
518
- def _supports_object(schema: Mapping[str, object]) -> bool:
519
- return any(
520
- variant.get("type") == "object"
521
- or "properties" in variant
522
- or isinstance(variant.get("additionalProperties"), Mapping)
523
- for variant in _expand_schema(schema)
524
- )
525
-
526
-
527
- def _matches_property_name(key: str, schema: object) -> bool:
528
- if not isinstance(schema, Mapping):
529
- return True
530
- enum = schema.get("enum")
531
- if isinstance(enum, list) and key not in enum:
532
- return False
533
- minimum = schema.get("minLength")
534
- if isinstance(minimum, int) and len(key) < minimum:
535
- return False
536
- pattern = schema.get("pattern")
537
- return not isinstance(pattern, str) or re.search(pattern, key) is not None
538
-
539
-
540
- def _has_operator_key(value: object) -> bool:
541
- return (
542
- isinstance(value, Mapping)
543
- and bool(value)
544
- and any(key.startswith("$") for key in value)
545
- )
546
-
547
-
548
- def _is_field_operator_expression(value: object) -> bool:
549
- return (
550
- isinstance(value, Mapping)
551
- and bool(value)
552
- and all(key in _OPERATORS for key in value)
553
- )
554
-
555
-
556
- def _is_number(value: object) -> bool:
557
- return isinstance(value, (int, float)) and not isinstance(value, bool)
558
-
559
-
560
- def _path(path: Sequence[str | int]) -> str:
561
- return ".".join(str(item) for item in path) or "<root>"
562
-
563
-
564
- def _record_schema() -> Mapping[str, object]:
565
- schema = _catalog_schema()["$defs"]["CatalogModel"]
566
- record = json.loads(json.dumps(schema))
567
- properties = record.setdefault("properties", {})
568
- properties["id"] = {"type": "string", "minLength": 1}
569
- record.setdefault("required", []).append("id")
570
- return record
571
-
572
-
573
- def _catalog_schema() -> dict[str, Any]:
574
- if not hasattr(_catalog_schema, "value"):
575
- schema_file = files("dbx_model_catalog.schema").joinpath(
576
- "model-catalog.schema.json"
577
- )
578
- _catalog_schema.value = json.loads(schema_file.read_text()) # type: ignore[attr-defined]
579
- return _catalog_schema.value # type: ignore[attr-defined,no-any-return]
580
-
581
-
582
- __all__ = [
583
- "CatalogOrderBy",
584
- "CatalogOrderByField",
585
- "CatalogPredicate",
586
- "CatalogQuery",
587
- "CatalogQueryExpression",
588
- "CatalogQueryOptions",
589
- "SerializableCatalogQuery",
590
- "parse_catalog_query",
591
- "query_catalog_records",
592
- "serialize_catalog_query",
593
- ]