1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
use futures::future::{BoxFuture, FutureExt};
use hashbrown::HashSet;
use iref::Iri;
use locspan::{Location, MapLocErr, Meta};
use mime::Mime;
use mown::Mown;
use rdf_types::{vocabulary::Index, IriVocabulary, IriVocabularyMut};
use static_iref::iri;
use std::fmt;

pub mod fs;
pub mod none;

pub use fs::FsLoader;
pub use none::NoLoader;

#[cfg(feature = "reqwest")]
pub mod reqwest;

#[cfg(feature = "reqwest")]
pub use self::reqwest::ReqwestLoader;

pub type LoadingResult<I, M, O, E> = Result<RemoteDocument<I, M, O>, E>;

/// Remote document, loaded or not.
///
/// Either an IRI or the actual document content.
#[derive(Clone)]
pub enum RemoteDocumentReference<I = Index, M = Location<I>, T = json_syntax::Value<M>> {
	/// IRI to the remote document.
	Iri(I),

	/// Remote document content.
	Loaded(RemoteDocument<I, M, T>),
}

impl<I, M> RemoteDocumentReference<I, M, json_syntax::Value<M>> {
	/// Creates an IRI to a `json_syntax::Value<M>` JSON document.
	///
	/// This method can replace `RemoteDocumentReference::Iri` to help the type
	/// inference in the case where `T = json_syntax::Value<M>`.
	pub fn iri(iri: I) -> Self {
		Self::Iri(iri)
	}
}

impl<I, M> RemoteDocumentReference<I, M, json_ld_syntax::context::Value<M>> {
	/// Creates an IRI to a `json_ld_syntax::context::Value<M>` JSON-LD context document.
	///
	/// This method can replace `RemoteDocumentReference::Iri` to help the type
	/// inference in the case where `T = json_ld_syntax::context::Value<M>`.
	pub fn context_iri(iri: I) -> Self {
		Self::Iri(iri)
	}
}

impl<I, M, T> RemoteDocumentReference<I, M, T> {
	/// Loads the remote document with the given `vocabulary` and `loader`.
	///
	/// If the document is already [`Self::Loaded`], simply returns the inner
	/// [`RemoteDocument`].
	pub async fn load_with<L: Loader<I, M>>(
		self,
		vocabulary: &mut (impl Sync + Send + IriVocabularyMut<Iri = I>),
		loader: &mut L,
	) -> LoadingResult<I, M, T, L::Error>
	where
		L::Output: Into<T>,
	{
		match self {
			Self::Iri(r) => Ok(loader
				.load_with(vocabulary, r)
				.await?
				.map(|m| m.map(Into::into))),
			Self::Loaded(doc) => Ok(doc),
		}
	}

	/// Loads the remote document with the given `vocabulary` and `loader`.
	///
	/// For [`Self::Iri`] returns an owned [`RemoteDocument`] with
	/// [`Mown::Owned`].
	/// For [`Self::Loaded`] returns a reference to the inner [`RemoteDocument`]
	/// with [`Mown::Borrowed`].
	pub async fn loaded_with<L: Loader<I, M>>(
		&self,
		vocabulary: &mut (impl Sync + Send + IriVocabularyMut<Iri = I>),
		loader: &mut L,
	) -> Result<Mown<'_, RemoteDocument<I, M, T>>, L::Error>
	where
		I: Clone,
		L::Output: Into<T>,
	{
		match self {
			Self::Iri(r) => Ok(Mown::Owned(
				loader
					.load_with(vocabulary, r.clone())
					.await?
					.map(|m| m.map(Into::into)),
			)),
			Self::Loaded(doc) => Ok(Mown::Borrowed(doc)),
		}
	}

	/// Loads the remote context definition with the given `vocabulary` and
	/// `loader`.
	///
	/// If the document is already [`Self::Loaded`], simply returns the inner
	/// [`RemoteDocument`].
	pub async fn load_context_with<L: ContextLoader<I, M>>(
		self,
		vocabulary: &mut (impl Send + Sync + IriVocabularyMut<Iri = I>),
		loader: &mut L,
	) -> LoadingResult<I, M, T, L::ContextError>
	where
		L::Context: Into<T>,
	{
		match self {
			Self::Iri(r) => Ok(loader
				.load_context_with(vocabulary, r)
				.await?
				.map(|m| m.map(Into::into))),
			Self::Loaded(doc) => Ok(doc),
		}
	}

	/// Loads the remote context definition with the given `vocabulary` and
	/// `loader`.
	///
	/// For [`Self::Iri`] returns an owned [`RemoteDocument`] with
	/// [`Mown::Owned`].
	/// For [`Self::Loaded`] returns a reference to the inner [`RemoteDocument`]
	/// with [`Mown::Borrowed`].
	pub async fn loaded_context_with<L: ContextLoader<I, M>>(
		&self,
		vocabulary: &mut (impl Send + Sync + IriVocabularyMut<Iri = I>),
		loader: &mut L,
	) -> Result<Mown<'_, RemoteDocument<I, M, T>>, L::ContextError>
	where
		I: Clone,
		L::Context: Into<T>,
	{
		match self {
			Self::Iri(r) => Ok(Mown::Owned(
				loader
					.load_context_with(vocabulary, r.clone())
					.await?
					.map(|m| m.map(Into::into)),
			)),
			Self::Loaded(doc) => Ok(Mown::Borrowed(doc)),
		}
	}
}

/// Remote document.
///
/// Stores the content of a loaded remote document along with its original URL.
#[derive(Clone)]
pub struct RemoteDocument<I = Index, M = Location<I>, T = json_syntax::Value<M>> {
	/// The final URL of the loaded document, after eventual redirection.
	url: Option<I>,

	/// The HTTP `Content-Type` header value of the loaded document, exclusive
	/// of any optional parameters.
	content_type: Option<Mime>,

	/// If available, the value of the HTTP `Link Header` [RFC 8288] using the
	/// `http://www.w3.org/ns/json-ld#context` link relation in the response.
	///
	/// If the response's `Content-Type` is `application/ld+json`, the HTTP
	/// `Link Header` is ignored. If multiple HTTP `Link Headers` using the
	/// `http://www.w3.org/ns/json-ld#context` link relation are found, the
	/// loader fails with a `multiple context link headers` error.
	///
	/// [RFC 8288]: https://www.rfc-editor.org/rfc/rfc8288
	context_url: Option<I>,

	profile: HashSet<Profile<I>>,

	/// The retrieved document.
	document: Meta<T, M>,
}

impl<I, M, T> RemoteDocument<I, M, T> {
	/// Creates a new remote document.
	///
	/// `url` is the final URL of the loaded document, after eventual
	/// redirection.
	/// `content_type` is the HTTP `Content-Type` header value of the loaded
	/// document, exclusive of any optional parameters.
	pub fn new(url: Option<I>, content_type: Option<Mime>, document: Meta<T, M>) -> Self {
		Self::new_full(url, content_type, None, HashSet::new(), document)
	}

	/// Creates a new remote document.
	///
	/// `url` is the final URL of the loaded document, after eventual
	/// redirection.
	/// `content_type` is the HTTP `Content-Type` header value of the loaded
	/// document, exclusive of any optional parameters.
	/// `context_url` is the value of the HTTP `Link Header` [RFC 8288] using the
	/// `http://www.w3.org/ns/json-ld#context` link relation in the response,
	/// if any.
	/// `profile` is the value of any profile parameter retrieved as part of the
	/// original contentType.
	///
	/// [RFC 8288]: https://www.rfc-editor.org/rfc/rfc8288
	pub fn new_full(
		url: Option<I>,
		content_type: Option<Mime>,
		context_url: Option<I>,
		profile: HashSet<Profile<I>>,
		document: Meta<T, M>,
	) -> Self {
		Self {
			url,
			content_type,
			context_url,
			profile,
			document,
		}
	}

	/// Maps the content of the remote document.
	pub fn map<U, N>(self, f: impl Fn(Meta<T, M>) -> Meta<U, N>) -> RemoteDocument<I, N, U> {
		RemoteDocument {
			url: self.url,
			content_type: self.content_type,
			context_url: self.context_url,
			profile: self.profile,
			document: f(self.document),
		}
	}

	/// Tries to map the content of the remote document.
	pub fn try_map<U, N, E>(
		self,
		f: impl Fn(Meta<T, M>) -> Result<Meta<U, N>, E>,
	) -> Result<RemoteDocument<I, N, U>, E> {
		Ok(RemoteDocument {
			url: self.url,
			content_type: self.content_type,
			context_url: self.context_url,
			profile: self.profile,
			document: f(self.document)?,
		})
	}

	/// Returns a reference to the final URL of the loaded document, after eventual redirection.
	pub fn url(&self) -> Option<&I> {
		self.url.as_ref()
	}

	/// Returns the HTTP `Content-Type` header value of the loaded document,
	/// exclusive of any optional parameters.
	pub fn content_type(&self) -> Option<&Mime> {
		self.content_type.as_ref()
	}

	/// Returns the value of the HTTP `Link Header` [RFC 8288] using the
	/// `http://www.w3.org/ns/json-ld#context` link relation in the response,
	/// if any.
	///
	/// If the response's `Content-Type` is `application/ld+json`, the HTTP
	/// `Link Header` is ignored. If multiple HTTP `Link Headers` using the
	/// `http://www.w3.org/ns/json-ld#context` link relation are found, the
	/// loader fails with a `multiple context link headers` error.
	///
	/// [RFC 8288]: https://www.rfc-editor.org/rfc/rfc8288
	pub fn context_url(&self) -> Option<&I> {
		self.context_url.as_ref()
	}

	/// Returns a reference to the content of the document.
	pub fn document(&self) -> &Meta<T, M> {
		&self.document
	}

	/// Drops the original URL and returns the content of the document.
	pub fn into_document(self) -> Meta<T, M> {
		self.document
	}

	/// Drops the content and returns the original URL of the document.
	pub fn into_url(self) -> Option<I> {
		self.url
	}

	/// Sets the URL of the document.
	pub fn set_url(&mut self, url: Option<I>) {
		self.url = url
	}
}

/// Standard `profile` parameter values defined for the `application/ld+json`.
///
/// See: <https://www.w3.org/TR/json-ld11/#iana-considerations>
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StandardProfile {
	/// To request or specify expanded JSON-LD document form.
	Expanded,

	/// To request or specify compacted JSON-LD document form.
	Compacted,

	/// To request or specify a JSON-LD context document.
	Context,

	/// To request or specify flattened JSON-LD document form.
	Flattened,

	// /// To request or specify a JSON-LD frame document.
	// Frame,
	/// To request or specify a JSON-LD framed document.
	Framed,
}

impl StandardProfile {
	pub fn from_iri(iri: Iri) -> Option<Self> {
		if iri == iri!("http://www.w3.org/ns/json-ld#expanded") {
			Some(Self::Expanded)
		} else if iri == iri!("http://www.w3.org/ns/json-ld#compacted") {
			Some(Self::Compacted)
		} else if iri == iri!("http://www.w3.org/ns/json-ld#context") {
			Some(Self::Context)
		} else if iri == iri!("http://www.w3.org/ns/json-ld#flattened") {
			Some(Self::Flattened)
		} else if iri == iri!("http://www.w3.org/ns/json-ld#framed") {
			Some(Self::Framed)
		} else {
			None
		}
	}

	pub fn iri(&self) -> Iri<'static> {
		match self {
			Self::Expanded => iri!("http://www.w3.org/ns/json-ld#expanded"),
			Self::Compacted => iri!("http://www.w3.org/ns/json-ld#compacted"),
			Self::Context => iri!("http://www.w3.org/ns/json-ld#context"),
			Self::Flattened => iri!("http://www.w3.org/ns/json-ld#flattened"),
			Self::Framed => iri!("http://www.w3.org/ns/json-ld#framed"),
		}
	}
}

/// Value for the `profile` parameter defined for the `application/ld+json`.
///
/// Standard values defined by the JSON-LD specification are defined by the
/// [`StandardProfile`] type.
///
/// See: <https://www.w3.org/TR/json-ld11/#iana-considerations>
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Profile<I> {
	Standard(StandardProfile),
	Custom(I),
}

impl<I> Profile<I> {
	pub fn new(iri: Iri, vocabulary: &mut impl IriVocabularyMut<Iri = I>) -> Self {
		match StandardProfile::from_iri(iri) {
			Some(p) => Self::Standard(p),
			None => Self::Custom(vocabulary.insert(iri)),
		}
	}

	pub fn iri<'a>(&'a self, vocabulary: &'a impl IriVocabulary<Iri = I>) -> Iri<'a> {
		match self {
			Self::Standard(s) => s.iri(),
			Self::Custom(c) => vocabulary.iri(c).unwrap(),
		}
	}
}

/// Document loader.
///
/// A document loader is required by most processing functions to fetch remote
/// documents identified by an IRI.
///
/// This library provides a few default loader implementations:
///   - [`NoLoader`] dummy loader that always fail. Perfect if you are certain
///     that the processing will not require any loading.
///   - [`FsLoader`] that redirect registered IRI prefixes to a local directory
///     on the file system. This way no network calls are performed and the
///     loaded content can be trusted.
///   - `ReqwestLoader` that actually download the remote documents using the
///     [`reqwest`](https://crates.io/crates/reqwest) library.
///     This requires the `reqwest` feature to be enabled.
pub trait Loader<I, M> {
	/// The type of documents that can be loaded.
	type Output;

	/// Error type.
	type Error;

	/// Loads the document behind the given IRI, using the given vocabulary.
	fn load_with<'a>(
		&'a mut self,
		vocabulary: &'a mut (impl Sync + Send + IriVocabularyMut<Iri = I>),
		url: I,
	) -> BoxFuture<'a, LoadingResult<I, M, Self::Output, Self::Error>>
	where
		I: 'a;

	/// Loads the document behind the given IRI.
	fn load<'a>(
		&'a mut self,
		url: I,
	) -> BoxFuture<'a, LoadingResult<I, M, Self::Output, Self::Error>>
	where
		I: 'a,
		(): IriVocabulary<Iri = I>,
	{
		self.load_with(rdf_types::vocabulary::no_vocabulary_mut(), url)
	}
}

/// Context document loader.
///
/// This is a subclass of loaders able to extract a local context from a loaded
/// JSON-LD document.
///
/// It is implemented for any loader where the output type implements
/// [`ExtractContext`].
pub trait ContextLoader<I, M> {
	/// Output of the loader, a context.
	type Context;

	/// Error type.
	type ContextError;

	/// Loads the context behind the given IRI, using the given vocabulary.
	fn load_context_with<'a>(
		&'a mut self,
		vocabulary: &'a mut (impl Send + Sync + IriVocabularyMut<Iri = I>),
		url: I,
	) -> BoxFuture<'a, LoadingResult<I, M, Self::Context, Self::ContextError>>
	where
		I: 'a,
		M: 'a;

	/// Loads the context behind the given IRI.
	fn load_context<'a>(
		&'a mut self,
		url: I,
	) -> BoxFuture<'a, LoadingResult<I, M, Self::Context, Self::ContextError>>
	where
		I: 'a,
		M: 'a,
		(): IriVocabulary<Iri = I>,
	{
		self.load_context_with(rdf_types::vocabulary::no_vocabulary_mut(), url)
	}
}

/// Context extraction method.
///
/// Implemented by documents containing a JSON-LD context definition, providing
/// a method to extract this context.
pub trait ExtractContext<M>: Sized {
	/// Context definition type.
	type Context;

	/// Error type.
	///
	/// May be raised if the inner context is missing or invalid.
	type Error;

	/// Extract the context definition.
	fn extract_context(value: Meta<Self, M>) -> Result<Meta<Self::Context, M>, Self::Error>;
}

/// Context extraction error.
#[derive(Debug)]
pub enum ExtractContextError<M> {
	/// Unexpected JSON value.
	Unexpected(json_syntax::Kind),

	/// No context definition found.
	NoContext,

	/// Multiple context definitions found.
	DuplicateContext(M),

	/// JSON syntax error.
	Syntax(json_ld_syntax::context::InvalidContext),
}

impl<M> ExtractContextError<M> {
	fn duplicate_context(
		json_syntax::object::Duplicate(a, b): json_syntax::object::Duplicate<
			json_syntax::object::Entry<M>,
		>,
	) -> Meta<Self, M> {
		Meta(
			Self::DuplicateContext(a.key.into_metadata()),
			b.key.into_metadata(),
		)
	}
}

impl<M> fmt::Display for ExtractContextError<M> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Unexpected(k) => write!(f, "unexpected {}", k),
			Self::NoContext => write!(f, "missing context"),
			Self::DuplicateContext(_) => write!(f, "duplicate context"),
			Self::Syntax(e) => e.fmt(f),
		}
	}
}

impl<M: Clone> ExtractContext<M> for json_syntax::Value<M> {
	type Context = json_ld_syntax::context::Value<M>;
	type Error = Meta<ExtractContextError<M>, M>;

	fn extract_context(
		Meta(value, meta): Meta<Self, M>,
	) -> Result<Meta<Self::Context, M>, Self::Error> {
		match value {
			json_syntax::Value::Object(mut o) => match o
				.remove_unique("@context")
				.map_err(ExtractContextError::duplicate_context)?
			{
				Some(context) => {
					use json_ld_syntax::TryFromJson;
					json_ld_syntax::context::Value::try_from_json(context.value)
						.map_loc_err(ExtractContextError::Syntax)
				}
				None => Err(Meta(ExtractContextError::NoContext, meta)),
			},
			other => Err(Meta(ExtractContextError::Unexpected(other.kind()), meta)),
		}
	}
}

#[derive(Debug)]
pub enum ContextLoaderError<D, C> {
	LoadingDocumentFailed(D),
	ContextExtractionFailed(C),
}

impl<D: fmt::Display, C: fmt::Display> fmt::Display for ContextLoaderError<D, C> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::LoadingDocumentFailed(e) => e.fmt(f),
			Self::ContextExtractionFailed(e) => e.fmt(f),
		}
	}
}

impl<I: Send, M, L: Loader<I, M>> ContextLoader<I, M> for L
where
	L::Output: ExtractContext<M>,
{
	type Context = <L::Output as ExtractContext<M>>::Context;
	type ContextError = ContextLoaderError<L::Error, <L::Output as ExtractContext<M>>::Error>;

	fn load_context_with<'a>(
		&'a mut self,
		vocabulary: &'a mut (impl Send + Sync + IriVocabularyMut<Iri = I>),
		url: I,
	) -> BoxFuture<'a, Result<RemoteDocument<I, M, Self::Context>, Self::ContextError>>
	where
		I: 'a,
		M: 'a,
	{
		let load_document = self.load_with(vocabulary, url);
		async move {
			let doc = load_document
				.await
				.map_err(ContextLoaderError::LoadingDocumentFailed)?;

			doc.try_map(ExtractContext::extract_context)
				.map_err(ContextLoaderError::ContextExtractionFailed)
		}
		.boxed()
	}
}