_core.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. from __future__ import annotations
  2. from collections.abc import Callable, Iterable, Iterator, Sequence
  3. from enum import Enum
  4. from typing import Any, ClassVar, Generic, Protocol
  5. from urllib.parse import unquote, urldefrag, urljoin
  6. from attrs import evolve, field
  7. from rpds import HashTrieMap, HashTrieSet, List
  8. try:
  9. from typing_extensions import TypeVar
  10. except ImportError: # pragma: no cover
  11. from typing import TypeVar
  12. from referencing import exceptions
  13. from referencing._attrs import frozen
  14. from referencing.typing import URI, Anchor as AnchorType, D, Mapping, Retrieve
  15. EMPTY_UNCRAWLED: HashTrieSet[URI] = HashTrieSet()
  16. EMPTY_PREVIOUS_RESOLVERS: List[URI] = List()
  17. class _Unset(Enum):
  18. """
  19. What sillyness...
  20. """
  21. SENTINEL = 1
  22. _UNSET = _Unset.SENTINEL
  23. class _MaybeInSubresource(Protocol[D]):
  24. def __call__(
  25. self,
  26. segments: Sequence[int | str],
  27. resolver: Resolver[D],
  28. subresource: Resource[D],
  29. ) -> Resolver[D]: ...
  30. def _detect_or_error(contents: D) -> Specification[D]:
  31. if not isinstance(contents, Mapping):
  32. raise exceptions.CannotDetermineSpecification(contents)
  33. jsonschema_dialect_id = contents.get("$schema") # type: ignore[reportUnknownMemberType]
  34. if not isinstance(jsonschema_dialect_id, str):
  35. raise exceptions.CannotDetermineSpecification(contents)
  36. from referencing.jsonschema import specification_with
  37. return specification_with(jsonschema_dialect_id)
  38. def _detect_or_default(
  39. default: Specification[D],
  40. ) -> Callable[[D], Specification[D]]:
  41. def _detect(contents: D) -> Specification[D]:
  42. if not isinstance(contents, Mapping):
  43. return default
  44. jsonschema_dialect_id = contents.get("$schema") # type: ignore[reportUnknownMemberType]
  45. if jsonschema_dialect_id is None:
  46. return default
  47. from referencing.jsonschema import specification_with
  48. return specification_with(
  49. jsonschema_dialect_id, # type: ignore[reportUnknownArgumentType]
  50. default=default,
  51. )
  52. return _detect
  53. class _SpecificationDetector:
  54. def __get__(
  55. self,
  56. instance: Specification[D] | None,
  57. cls: type[Specification[D]],
  58. ) -> Callable[[D], Specification[D]]:
  59. if instance is None:
  60. return _detect_or_error
  61. else:
  62. return _detect_or_default(instance)
  63. @frozen
  64. class Specification(Generic[D]):
  65. """
  66. A specification which defines referencing behavior.
  67. The various methods of a `Specification` allow for varying referencing
  68. behavior across JSON Schema specification versions, etc.
  69. """
  70. #: A short human-readable name for the specification, used for debugging.
  71. name: str
  72. #: Find the ID of a given document.
  73. id_of: Callable[[D], URI | None]
  74. #: Retrieve the subresources of the given document (without traversing into
  75. #: the subresources themselves).
  76. subresources_of: Callable[[D], Iterable[D]]
  77. #: While resolving a JSON pointer, conditionally enter a subresource
  78. #: (if e.g. we have just entered a keyword whose value is a subresource)
  79. maybe_in_subresource: _MaybeInSubresource[D]
  80. #: Retrieve the anchors contained in the given document.
  81. _anchors_in: Callable[
  82. [Specification[D], D],
  83. Iterable[AnchorType[D]],
  84. ] = field(alias="anchors_in")
  85. #: An opaque specification where resources have no subresources
  86. #: nor internal identifiers.
  87. OPAQUE: ClassVar[Specification[Any]]
  88. #: Attempt to discern which specification applies to the given contents.
  89. #:
  90. #: May be called either as an instance method or as a class method, with
  91. #: slightly different behavior in the following case:
  92. #:
  93. #: Recall that not all contents contains enough internal information about
  94. #: which specification it is written for -- the JSON Schema ``{}``,
  95. #: for instance, is valid under many different dialects and may be
  96. #: interpreted as any one of them.
  97. #:
  98. #: When this method is used as an instance method (i.e. called on a
  99. #: specific specification), that specification is used as the default
  100. #: if the given contents are unidentifiable.
  101. #:
  102. #: On the other hand when called as a class method, an error is raised.
  103. #:
  104. #: To reiterate, ``DRAFT202012.detect({})`` will return ``DRAFT202012``
  105. #: whereas the class method ``Specification.detect({})`` will raise an
  106. #: error.
  107. #:
  108. #: (Note that of course ``DRAFT202012.detect(...)`` may return some other
  109. #: specification when given a schema which *does* identify as being for
  110. #: another version).
  111. #:
  112. #: Raises:
  113. #:
  114. #: `CannotDetermineSpecification`
  115. #:
  116. #: if the given contents don't have any discernible
  117. #: information which could be used to guess which
  118. #: specification they identify as
  119. detect = _SpecificationDetector()
  120. def __repr__(self) -> str:
  121. return f"<Specification name={self.name!r}>"
  122. def anchors_in(self, contents: D):
  123. """
  124. Retrieve the anchors contained in the given document.
  125. """
  126. return self._anchors_in(self, contents)
  127. def create_resource(self, contents: D) -> Resource[D]:
  128. """
  129. Create a resource which is interpreted using this specification.
  130. """
  131. return Resource(contents=contents, specification=self)
  132. Specification.OPAQUE = Specification(
  133. name="opaque",
  134. id_of=lambda contents: None,
  135. subresources_of=lambda contents: [],
  136. anchors_in=lambda specification, contents: [],
  137. maybe_in_subresource=lambda segments, resolver, subresource: resolver,
  138. )
  139. @frozen
  140. class Resource(Generic[D]):
  141. r"""
  142. A document (deserialized JSON) with a concrete interpretation under a spec.
  143. In other words, a Python object, along with an instance of `Specification`
  144. which describes how the document interacts with referencing -- both
  145. internally (how it refers to other `Resource`\ s) and externally (how it
  146. should be identified such that it is referenceable by other documents).
  147. """
  148. contents: D
  149. _specification: Specification[D] = field(alias="specification")
  150. @classmethod
  151. def from_contents(
  152. cls,
  153. contents: D,
  154. default_specification: (
  155. type[Specification[D]] | Specification[D]
  156. ) = Specification,
  157. ) -> Resource[D]:
  158. """
  159. Create a resource guessing which specification applies to the contents.
  160. Raises:
  161. `CannotDetermineSpecification`
  162. if the given contents don't have any discernible
  163. information which could be used to guess which
  164. specification they identify as
  165. """
  166. specification = default_specification.detect(contents)
  167. return specification.create_resource(contents=contents)
  168. @classmethod
  169. def opaque(cls, contents: D) -> Resource[D]:
  170. """
  171. Create an opaque `Resource` -- i.e. one with opaque specification.
  172. See `Specification.OPAQUE` for details.
  173. """
  174. return Specification.OPAQUE.create_resource(contents=contents)
  175. def id(self) -> URI | None:
  176. """
  177. Retrieve this resource's (specification-specific) identifier.
  178. """
  179. id = self._specification.id_of(self.contents)
  180. if id is None:
  181. return
  182. return id.rstrip("#")
  183. def subresources(self) -> Iterable[Resource[D]]:
  184. """
  185. Retrieve this resource's subresources.
  186. """
  187. return (
  188. Resource.from_contents(
  189. each,
  190. default_specification=self._specification,
  191. )
  192. for each in self._specification.subresources_of(self.contents)
  193. )
  194. def anchors(self) -> Iterable[AnchorType[D]]:
  195. """
  196. Retrieve this resource's (specification-specific) identifier.
  197. """
  198. return self._specification.anchors_in(self.contents)
  199. def pointer(self, pointer: str, resolver: Resolver[D]) -> Resolved[D]:
  200. """
  201. Resolve the given JSON pointer.
  202. Raises:
  203. `exceptions.PointerToNowhere`
  204. if the pointer points to a location not present in the document
  205. """
  206. if not pointer:
  207. return Resolved(contents=self.contents, resolver=resolver)
  208. contents = self.contents
  209. segments: list[int | str] = []
  210. for segment in unquote(pointer[1:]).split("/"):
  211. if isinstance(contents, Sequence):
  212. segment = int(segment)
  213. else:
  214. segment = segment.replace("~1", "/").replace("~0", "~")
  215. try:
  216. contents = contents[segment] # type: ignore[reportUnknownArgumentType]
  217. except LookupError as lookup_error:
  218. error = exceptions.PointerToNowhere(ref=pointer, resource=self)
  219. raise error from lookup_error
  220. segments.append(segment)
  221. last = resolver
  222. resolver = self._specification.maybe_in_subresource(
  223. segments=segments,
  224. resolver=resolver,
  225. subresource=self._specification.create_resource(contents),
  226. )
  227. if resolver is not last:
  228. segments = []
  229. return Resolved(contents=contents, resolver=resolver) # type: ignore[reportUnknownArgumentType]
  230. def _fail_to_retrieve(uri: URI):
  231. raise exceptions.NoSuchResource(ref=uri)
  232. @frozen
  233. class Registry(Mapping[URI, Resource[D]]):
  234. r"""
  235. A registry of `Resource`\ s, each identified by their canonical URIs.
  236. Registries store a collection of in-memory resources, and optionally
  237. enable additional resources which may be stored elsewhere (e.g. in a
  238. database, a separate set of files, over the network, etc.).
  239. They also lazily walk their known resources, looking for subresources
  240. within them. In other words, subresources contained within any added
  241. resources will be retrievable via their own IDs (though this discovery of
  242. subresources will be delayed until necessary).
  243. Registries are immutable, and their methods return new instances of the
  244. registry with the additional resources added to them.
  245. The ``retrieve`` argument can be used to configure retrieval of resources
  246. dynamically, either over the network, from a database, or the like.
  247. Pass it a callable which will be called if any URI not present in the
  248. registry is accessed. It must either return a `Resource` or else raise a
  249. `NoSuchResource` exception indicating that the resource does not exist
  250. even according to the retrieval logic.
  251. """
  252. _resources: HashTrieMap[URI, Resource[D]] = field(
  253. default=HashTrieMap(),
  254. converter=HashTrieMap.convert, # type: ignore[reportGeneralTypeIssues]
  255. alias="resources",
  256. )
  257. _anchors: HashTrieMap[tuple[URI, str], AnchorType[D]] = HashTrieMap()
  258. _uncrawled: HashTrieSet[URI] = EMPTY_UNCRAWLED
  259. _retrieve: Retrieve[D] = field(default=_fail_to_retrieve, alias="retrieve")
  260. def __getitem__(self, uri: URI) -> Resource[D]:
  261. """
  262. Return the (already crawled) `Resource` identified by the given URI.
  263. """
  264. try:
  265. return self._resources[uri.rstrip("#")]
  266. except KeyError:
  267. raise exceptions.NoSuchResource(ref=uri) from None
  268. def __iter__(self) -> Iterator[URI]:
  269. """
  270. Iterate over all crawled URIs in the registry.
  271. """
  272. return iter(self._resources)
  273. def __len__(self) -> int:
  274. """
  275. Count the total number of fully crawled resources in this registry.
  276. """
  277. return len(self._resources)
  278. def __rmatmul__(
  279. self,
  280. new: Resource[D] | Iterable[Resource[D]],
  281. ) -> Registry[D]:
  282. """
  283. Create a new registry with resource(s) added using their internal IDs.
  284. Resources must have a internal IDs (e.g. the :kw:`$id` keyword in
  285. modern JSON Schema versions), otherwise an error will be raised.
  286. Both a single resource as well as an iterable of resources works, i.e.:
  287. * ``resource @ registry`` or
  288. * ``[iterable, of, multiple, resources] @ registry``
  289. which -- again, assuming the resources have internal IDs -- is
  290. equivalent to calling `Registry.with_resources` as such:
  291. .. code:: python
  292. registry.with_resources(
  293. (resource.id(), resource) for resource in new_resources
  294. )
  295. Raises:
  296. `NoInternalID`
  297. if the resource(s) in fact do not have IDs
  298. """
  299. if isinstance(new, Resource):
  300. new = (new,)
  301. resources = self._resources
  302. uncrawled = self._uncrawled
  303. for resource in new:
  304. id = resource.id()
  305. if id is None:
  306. raise exceptions.NoInternalID(resource=resource)
  307. uncrawled = uncrawled.insert(id)
  308. resources = resources.insert(id, resource)
  309. return evolve(self, resources=resources, uncrawled=uncrawled)
  310. def __repr__(self) -> str:
  311. size = len(self)
  312. pluralized = "resource" if size == 1 else "resources"
  313. if self._uncrawled:
  314. uncrawled = len(self._uncrawled)
  315. if uncrawled == size:
  316. summary = f"uncrawled {pluralized}"
  317. else:
  318. summary = f"{pluralized}, {uncrawled} uncrawled"
  319. else:
  320. summary = f"{pluralized}"
  321. return f"<Registry ({size} {summary})>"
  322. def get_or_retrieve(self, uri: URI) -> Retrieved[D, Resource[D]]:
  323. """
  324. Get a resource from the registry, crawling or retrieving if necessary.
  325. May involve crawling to find the given URI if it is not already known,
  326. so the returned object is a `Retrieved` object which contains both the
  327. resource value as well as the registry which ultimately contained it.
  328. """
  329. resource = self._resources.get(uri)
  330. if resource is not None:
  331. return Retrieved(registry=self, value=resource)
  332. registry = self.crawl()
  333. resource = registry._resources.get(uri)
  334. if resource is not None:
  335. return Retrieved(registry=registry, value=resource)
  336. try:
  337. resource = registry._retrieve(uri)
  338. except (
  339. exceptions.CannotDetermineSpecification,
  340. exceptions.NoSuchResource,
  341. ):
  342. raise
  343. except Exception as error:
  344. raise exceptions.Unretrievable(ref=uri) from error
  345. else:
  346. registry = registry.with_resource(uri, resource)
  347. return Retrieved(registry=registry, value=resource)
  348. def remove(self, uri: URI):
  349. """
  350. Return a registry with the resource identified by a given URI removed.
  351. """
  352. if uri not in self._resources:
  353. raise exceptions.NoSuchResource(ref=uri)
  354. return evolve(
  355. self,
  356. resources=self._resources.remove(uri),
  357. uncrawled=self._uncrawled.discard(uri),
  358. anchors=HashTrieMap(
  359. (k, v) for k, v in self._anchors.items() if k[0] != uri
  360. ),
  361. )
  362. def anchor(self, uri: URI, name: str):
  363. """
  364. Retrieve a given anchor from a resource which must already be crawled.
  365. """
  366. value = self._anchors.get((uri, name))
  367. if value is not None:
  368. return Retrieved(value=value, registry=self)
  369. registry = self.crawl()
  370. value = registry._anchors.get((uri, name))
  371. if value is not None:
  372. return Retrieved(value=value, registry=registry)
  373. resource = self[uri]
  374. canonical_uri = resource.id()
  375. if canonical_uri is not None:
  376. value = registry._anchors.get((canonical_uri, name))
  377. if value is not None:
  378. return Retrieved(value=value, registry=registry)
  379. if "/" in name:
  380. raise exceptions.InvalidAnchor(
  381. ref=uri,
  382. resource=resource,
  383. anchor=name,
  384. )
  385. raise exceptions.NoSuchAnchor(ref=uri, resource=resource, anchor=name)
  386. def contents(self, uri: URI) -> D:
  387. """
  388. Retrieve the (already crawled) contents identified by the given URI.
  389. """
  390. return self[uri].contents
  391. def crawl(self) -> Registry[D]:
  392. """
  393. Crawl all added resources, discovering subresources.
  394. """
  395. resources = self._resources
  396. anchors = self._anchors
  397. uncrawled = [(uri, resources[uri]) for uri in self._uncrawled]
  398. while uncrawled:
  399. uri, resource = uncrawled.pop()
  400. id = resource.id()
  401. if id is not None:
  402. uri = urljoin(uri, id)
  403. resources = resources.insert(uri, resource)
  404. for each in resource.anchors():
  405. anchors = anchors.insert((uri, each.name), each)
  406. uncrawled.extend((uri, each) for each in resource.subresources())
  407. return evolve(
  408. self,
  409. resources=resources,
  410. anchors=anchors,
  411. uncrawled=EMPTY_UNCRAWLED,
  412. )
  413. def with_resource(self, uri: URI, resource: Resource[D]):
  414. """
  415. Add the given `Resource` to the registry, without crawling it.
  416. """
  417. return self.with_resources([(uri, resource)])
  418. def with_resources(
  419. self,
  420. pairs: Iterable[tuple[URI, Resource[D]]],
  421. ) -> Registry[D]:
  422. r"""
  423. Add the given `Resource`\ s to the registry, without crawling them.
  424. """
  425. resources = self._resources
  426. uncrawled = self._uncrawled
  427. for uri, resource in pairs:
  428. # Empty fragment URIs are equivalent to URIs without the fragment.
  429. # TODO: Is this true for non JSON Schema resources? Probably not.
  430. uri = uri.rstrip("#")
  431. uncrawled = uncrawled.insert(uri)
  432. resources = resources.insert(uri, resource)
  433. return evolve(self, resources=resources, uncrawled=uncrawled)
  434. def with_contents(
  435. self,
  436. pairs: Iterable[tuple[URI, D]],
  437. **kwargs: Any,
  438. ) -> Registry[D]:
  439. r"""
  440. Add the given contents to the registry, autodetecting when necessary.
  441. """
  442. return self.with_resources(
  443. (uri, Resource.from_contents(each, **kwargs))
  444. for uri, each in pairs
  445. )
  446. def combine(self, *registries: Registry[D]) -> Registry[D]:
  447. """
  448. Combine together one or more other registries, producing a unified one.
  449. """
  450. if registries == (self,):
  451. return self
  452. resources = self._resources
  453. anchors = self._anchors
  454. uncrawled = self._uncrawled
  455. retrieve = self._retrieve
  456. for registry in registries:
  457. resources = resources.update(registry._resources)
  458. anchors = anchors.update(registry._anchors)
  459. uncrawled = uncrawled.update(registry._uncrawled)
  460. if registry._retrieve is not _fail_to_retrieve:
  461. if registry._retrieve is not retrieve is not _fail_to_retrieve:
  462. raise ValueError( # noqa: TRY003
  463. "Cannot combine registries with conflicting retrieval "
  464. "functions.",
  465. )
  466. retrieve = registry._retrieve
  467. return evolve(
  468. self,
  469. anchors=anchors,
  470. resources=resources,
  471. uncrawled=uncrawled,
  472. retrieve=retrieve,
  473. )
  474. def resolver(self, base_uri: URI = "") -> Resolver[D]:
  475. """
  476. Return a `Resolver` which resolves references against this registry.
  477. """
  478. return Resolver(base_uri=base_uri, registry=self)
  479. def resolver_with_root(self, resource: Resource[D]) -> Resolver[D]:
  480. """
  481. Return a `Resolver` with a specific root resource.
  482. """
  483. uri = resource.id() or ""
  484. return Resolver(
  485. base_uri=uri,
  486. registry=self.with_resource(uri, resource),
  487. )
  488. #: An anchor or resource.
  489. AnchorOrResource = TypeVar(
  490. "AnchorOrResource",
  491. AnchorType[Any],
  492. Resource[Any],
  493. default=Resource[Any],
  494. )
  495. @frozen
  496. class Retrieved(Generic[D, AnchorOrResource]):
  497. """
  498. A value retrieved from a `Registry`.
  499. """
  500. value: AnchorOrResource
  501. registry: Registry[D]
  502. @frozen
  503. class Resolved(Generic[D]):
  504. """
  505. A reference resolved to its contents by a `Resolver`.
  506. """
  507. contents: D
  508. resolver: Resolver[D]
  509. @frozen
  510. class Resolver(Generic[D]):
  511. """
  512. A reference resolver.
  513. Resolvers help resolve references (including relative ones) by
  514. pairing a fixed base URI with a `Registry`.
  515. This object, under normal circumstances, is expected to be used by
  516. *implementers of libraries* built on top of `referencing` (e.g. JSON Schema
  517. implementations or other libraries resolving JSON references),
  518. not directly by end-users populating registries or while writing
  519. schemas or other resources.
  520. References are resolved against the base URI, and the combined URI
  521. is then looked up within the registry.
  522. The process of resolving a reference may itself involve calculating
  523. a *new* base URI for future reference resolution (e.g. if an
  524. intermediate resource sets a new base URI), or may involve encountering
  525. additional subresources and adding them to a new registry.
  526. """
  527. _base_uri: URI = field(alias="base_uri")
  528. _registry: Registry[D] = field(alias="registry")
  529. _previous: List[URI] = field(default=List(), repr=False, alias="previous")
  530. def lookup(self, ref: URI) -> Resolved[D]:
  531. """
  532. Resolve the given reference to the resource it points to.
  533. Raises:
  534. `exceptions.Unresolvable`
  535. or a subclass thereof (see below) if the reference isn't
  536. resolvable
  537. `exceptions.NoSuchAnchor`
  538. if the reference is to a URI where a resource exists but
  539. contains a plain name fragment which does not exist within
  540. the resource
  541. `exceptions.PointerToNowhere`
  542. if the reference is to a URI where a resource exists but
  543. contains a JSON pointer to a location within the resource
  544. that does not exist
  545. """
  546. if ref.startswith("#"):
  547. uri, fragment = self._base_uri, ref[1:]
  548. else:
  549. uri, fragment = urldefrag(urljoin(self._base_uri, ref))
  550. try:
  551. retrieved = self._registry.get_or_retrieve(uri)
  552. except exceptions.NoSuchResource:
  553. raise exceptions.Unresolvable(ref=ref) from None
  554. except exceptions.Unretrievable as error:
  555. raise exceptions.Unresolvable(ref=ref) from error
  556. if fragment.startswith("/"):
  557. resolver = self._evolve(registry=retrieved.registry, base_uri=uri)
  558. return retrieved.value.pointer(pointer=fragment, resolver=resolver)
  559. if fragment:
  560. retrieved = retrieved.registry.anchor(uri, fragment)
  561. resolver = self._evolve(registry=retrieved.registry, base_uri=uri)
  562. return retrieved.value.resolve(resolver=resolver)
  563. resolver = self._evolve(registry=retrieved.registry, base_uri=uri)
  564. return Resolved(contents=retrieved.value.contents, resolver=resolver)
  565. def in_subresource(self, subresource: Resource[D]) -> Resolver[D]:
  566. """
  567. Create a resolver for a subresource (which may have a new base URI).
  568. """
  569. id = subresource.id()
  570. if id is None:
  571. return self
  572. return evolve(self, base_uri=urljoin(self._base_uri, id))
  573. def dynamic_scope(self) -> Iterable[tuple[URI, Registry[D]]]:
  574. """
  575. In specs with such a notion, return the URIs in the dynamic scope.
  576. """
  577. for uri in self._previous:
  578. yield uri, self._registry
  579. def _evolve(self, base_uri: URI, **kwargs: Any):
  580. """
  581. Evolve, appending to the dynamic scope.
  582. """
  583. previous = self._previous
  584. if self._base_uri and (not previous or base_uri != self._base_uri):
  585. previous = previous.push_front(self._base_uri)
  586. return evolve(self, base_uri=base_uri, previous=previous, **kwargs)
  587. @frozen
  588. class Anchor(Generic[D]):
  589. """
  590. A simple anchor in a `Resource`.
  591. """
  592. name: str
  593. resource: Resource[D]
  594. def resolve(self, resolver: Resolver[D]):
  595. """
  596. Return the resource for this anchor.
  597. """
  598. return Resolved(contents=self.resource.contents, resolver=resolver)