-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathparseHydraDocumentation.ts
More file actions
612 lines (551 loc) · 18.1 KB
/
parseHydraDocumentation.ts
File metadata and controls
612 lines (551 loc) · 18.1 KB
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
import jsonld from "jsonld";
import type { OperationType, Parameter } from "../core/index.js";
import { Api, Field, Operation, Resource } from "../core/index.js";
import type { ManagesBlock } from "../core/Resource.js";
import type { RequestInitExtended } from "../core/types.js";
import { removeTrailingSlash } from "../core/utils/index.js";
import fetchJsonLd from "./fetchJsonLd.js";
import getParameters from "./getParameters.js";
import getType from "./getType.js";
import type {
Entrypoint,
ExpandedClass,
ExpandedDoc,
ExpandedOperation,
ExpandedRdfProperty,
} from "./types.js";
/**
* Extracts the short name of a resource.
* @param {string} url The resource URL.
* @param {string} entrypointUrl The API entrypoint URL.
* @returns {string} The short name of the resource.
*/
function guessNameFromUrl(url: string, entrypointUrl: string): string {
return url.slice(entrypointUrl.length + 1);
}
/**
* Gets the title or label from an ExpandedOperation object.
* @param {ExpandedOperation} obj The operation object.
* @returns {string} The title or label.
*/
function getTitleOrLabel(obj: ExpandedOperation): string {
const a =
obj["http://www.w3.org/2000/01/rdf-schema#label"] ??
obj["http://www.w3.org/ns/hydra/core#title"] ??
null;
if (a === null) {
throw new Error("No title nor label defined on this operation.");
}
return a[0]["@value"];
}
/**
* Finds the description of the class with the given id.
* @param {ExpandedDoc[]} docs The expanded documentation array.
* @param {string} classToFind The class ID to find.
* @returns {ExpandedClass} The matching expanded class.
*/
function findSupportedClass(
docs: ExpandedDoc[],
classToFind: string,
): ExpandedClass {
const supportedClasses =
docs?.[0]?.["http://www.w3.org/ns/hydra/core#supportedClass"];
if (!Array.isArray(supportedClasses)) {
throw new TypeError(
'The API documentation has no "http://www.w3.org/ns/hydra/core#supportedClass" key or its value is not an array.',
);
}
for (const supportedClass of supportedClasses) {
if (supportedClass["@id"] === classToFind) {
return supportedClass;
}
}
throw new Error(
`The class "${classToFind}" is not defined in the API documentation.`,
);
}
export function getDocumentationUrlFromHeaders(headers: Headers): string {
const linkHeader = headers.get("Link");
if (!linkHeader) {
throw new Error('The response has no "Link" HTTP header.');
}
const matches =
/<([^<]+)>; rel="http:\/\/www.w3.org\/ns\/hydra\/core#apiDocumentation"/.exec(
linkHeader,
);
if (matches === null) {
throw new Error(
'The "Link" HTTP header is not of the type "http://www.w3.org/ns/hydra/core#apiDocumentation".',
);
}
if (typeof matches[1] !== "string") {
throw new TypeError(
'The "Link" HTTP header does not contain a documentation URL.',
);
}
return matches[1];
}
/**
* Retrieves Hydra's entrypoint and API docs.
* @param {string} entrypointUrl The URL of the API entrypoint.
* @param {RequestInitExtended} [options] Optional fetch options.
* @returns {Promise<{ entrypointUrl: string; docsUrl: string; response: Response; entrypoint: Entrypoint[]; docs: ExpandedDoc[]; }>} An object containing entrypointUrl, docsUrl, response, entrypoint, and docs.
*/
async function fetchEntrypointAndDocs(
entrypointUrl: string,
options: RequestInitExtended = {},
): Promise<{
entrypointUrl: string;
docsUrl: string;
response: Response;
entrypoint: Entrypoint[];
docs: ExpandedDoc[];
}> {
/**
* Loads a JSON-LD document from the given input.
* @param {string} input The URL or IRI to load.
* @returns {Promise<any>} The fetched JSON-LD response.
*/
async function documentLoader(input: string) {
const response = await fetchJsonLd(input, options);
if (!("body" in response)) {
throw new Error(
"An empty response was received when expanding documentation or entrypoint JSON-LD documents.",
);
}
return response;
}
try {
const d = await fetchJsonLd(entrypointUrl, options);
if (!("body" in d)) {
throw new Error("An empty response was received for the entrypoint URL.");
}
const entrypointJsonLd = d.body;
const docsUrl = getDocumentationUrlFromHeaders(d.response.headers);
const docsResponse = await fetchJsonLd(docsUrl, options);
if (!("body" in docsResponse)) {
throw new Error(
"An empty response was received for the documentation URL.",
);
}
const docsJsonLd = docsResponse.body;
const [docs, entrypoint] = (await Promise.all([
jsonld.expand(docsJsonLd, {
base: docsUrl,
documentLoader,
}),
jsonld.expand(entrypointJsonLd, {
base: entrypointUrl,
documentLoader,
}),
])) as unknown as [ExpandedDoc[], Entrypoint[]];
return {
entrypointUrl,
docsUrl,
entrypoint,
response: d.response,
docs,
};
} catch (error) {
const { response } = error as { response: Response };
// oxlint-disable-next-line no-throw-literal
throw {
api: new Api(entrypointUrl, { resources: [] }),
error,
response,
status: response?.status,
};
}
}
/**
* Finds the related class for a property.
* @param {ExpandedDoc[]} docs The expanded documentation array.
* @param {ExpandedRdfProperty} property The property to find the related class for.
* @returns {ExpandedClass} The related expanded class.
*/
function findRelatedClass(
docs: ExpandedDoc[],
property: ExpandedRdfProperty,
): ExpandedClass {
// Try to use hydra:manages if available (new approach)
// Otherwise fall back to owl:equivalentClass (legacy approach)
for (const range of property["http://www.w3.org/2000/01/rdf-schema#range"] ??
[]) {
const equivalentClass =
"http://www.w3.org/2002/07/owl#equivalentClass" in range
? range?.["http://www.w3.org/2002/07/owl#equivalentClass"]?.[0]
: undefined;
if (!equivalentClass) {
continue;
}
const onProperty =
equivalentClass["http://www.w3.org/2002/07/owl#onProperty"]?.[0]?.["@id"];
const allValuesFrom =
equivalentClass["http://www.w3.org/2002/07/owl#allValuesFrom"]?.[0]?.[
"@id"
];
if (
allValuesFrom &&
typeof onProperty === "string" &&
onProperty.endsWith("#member")
) {
return findSupportedClass(docs, allValuesFrom);
}
}
// As a fallback, find an operation available on the property of the entrypoint returning the searched type (usually POST)
for (const entrypointSupportedOperation of property[
"http://www.w3.org/ns/hydra/core#supportedOperation"
] || []) {
if (
!entrypointSupportedOperation["http://www.w3.org/ns/hydra/core#returns"]
) {
continue;
}
const returns =
entrypointSupportedOperation?.[
"http://www.w3.org/ns/hydra/core#returns"
]?.[0]?.["@id"];
if (
typeof returns === "string" &&
returns.indexOf("http://www.w3.org/ns/hydra/core") !== 0
) {
try {
return findSupportedClass(docs, returns);
} catch {
continue;
}
}
}
// Third strategy: For read-only resources, look for rdfs:range with a direct class reference
// This handles enums and other resources that only have GET collection operations
if (Array.isArray(property["http://www.w3.org/2000/01/rdf-schema#range"])) {
for (const range of property[
"http://www.w3.org/2000/01/rdf-schema#range"
]) {
// Check if this range has a direct @id that's not a Hydra core type
if ("@id" in range) {
const rangeId = range["@id"];
if (
rangeId &&
typeof rangeId === "string" &&
rangeId.indexOf("http://www.w3.org/ns/hydra/core") !== 0
) {
try {
return findSupportedClass(docs, rangeId);
} catch {
// Not a valid class, continue to next range
continue;
}
}
}
// Also check if there's an owl:allValuesFrom without strict onProperty checking
// This is a more lenient version of Strategy 1
const equivalentClass =
"http://www.w3.org/2002/07/owl#equivalentClass" in range
? range?.["http://www.w3.org/2002/07/owl#equivalentClass"]?.[0]
: undefined;
if (equivalentClass) {
const allValuesFrom =
equivalentClass["http://www.w3.org/2002/07/owl#allValuesFrom"]?.[0]?.[
"@id"
];
if (allValuesFrom) {
try {
return findSupportedClass(docs, allValuesFrom);
} catch {
// Not a valid class, continue to next range
continue;
}
}
}
}
}
throw new Error(`Cannot find the class related to ${property["@id"]}.`);
}
/**
* Extracts manages blocks from a property.
* A manages block describes the relations between collection members and other resources.
* @param {ExpandedRdfProperty} property The property containing manages blocks.
* @returns {ManagesBlock[]} Array of manages blocks.
*/
function getManagesBlocks(property: ExpandedRdfProperty): ManagesBlock[] {
const manages = property["http://www.w3.org/ns/hydra/core#manages"];
if (!manages || !Array.isArray(manages)) {
return [];
}
return manages
.map((manage) => {
const prop = manage["http://www.w3.org/ns/hydra/core#property"]?.[0]?.["@id"];
const object = manage["http://www.w3.org/ns/hydra/core#object"]?.[0]?.["@id"];
if (!prop && !object) {
return null;
}
return {
...(prop && { property: prop }),
...(object && { object }),
} as ManagesBlock;
})
.filter((block): block is ManagesBlock => block !== null);
}
/**
* Parses Hydra documentation and converts it to an intermediate representation.
* @param {string} entrypointUrl The API entrypoint URL.
* @param {RequestInitExtended} [options] Optional fetch options.
* @returns {Promise<{ api: Api; response: Response; status: number; }>} The parsed API, response, and status.
*/
export default async function parseHydraDocumentation(
entrypointUrl: string,
options: RequestInitExtended = {},
): Promise<{
api: Api;
response: Response;
status: number;
}> {
entrypointUrl = removeTrailingSlash(entrypointUrl);
const { entrypoint, docs, response } = await fetchEntrypointAndDocs(
entrypointUrl,
options,
);
const resources = [],
fields = [],
operations = [];
const title =
docs?.[0]?.["http://www.w3.org/ns/hydra/core#title"]?.[0]?.["@value"] ??
"API Platform";
const entrypointType = entrypoint?.[0]?.["@type"]?.[0];
if (!entrypointType) {
throw new Error('The API entrypoint has no "@type" key.');
}
const entrypointClass = findSupportedClass(docs, entrypointType);
if (
!Array.isArray(
entrypointClass["http://www.w3.org/ns/hydra/core#supportedProperty"],
)
) {
throw new TypeError(
'The entrypoint definition has no "http://www.w3.org/ns/hydra/core#supportedProperty" key or it is not an array.',
);
}
// Add resources
for (const properties of entrypointClass[
"http://www.w3.org/ns/hydra/core#supportedProperty"
]) {
const readableFields = [],
resourceFields = [],
writableFields = [],
resourceOperations = [];
const property =
properties?.["http://www.w3.org/ns/hydra/core#property"]?.[0];
const propertyIri = property?.["@id"];
if (!property || !propertyIri) {
continue;
}
const resourceProperty = entrypoint?.[0]?.[propertyIri]?.[0];
const url =
typeof resourceProperty === "object"
? resourceProperty["@id"]
: undefined;
if (!url) {
console.error(
new Error(
`Unable to find the URL for "${propertyIri}" in the entrypoint, make sure your API resource has at least one GET collection operation declared.`,
),
);
continue;
}
// Add fields
const relatedClass = findRelatedClass(docs, property);
for (const supportedProperties of relatedClass?.[
"http://www.w3.org/ns/hydra/core#supportedProperty"
] ?? []) {
const supportedProperty =
supportedProperties?.["http://www.w3.org/ns/hydra/core#property"]?.[0];
const id = supportedProperty?.["@id"];
const range =
supportedProperty?.[
"http://www.w3.org/2000/01/rdf-schema#range"
]?.[0]?.["@id"] ?? null;
const field = new Field(
supportedProperties?.["http://www.w3.org/ns/hydra/core#title"]?.[0]?.[
"@value"
] ??
supportedProperty?.[
"http://www.w3.org/2000/01/rdf-schema#label"
]?.[0]?.["@value"],
{
id,
range,
type: getType(id, range),
reference: supportedProperty?.["@type"]?.[0]?.endsWith("#Link")
? range // Will be updated in a subsequent pass
: null,
embedded: supportedProperty?.["@type"]?.[0]?.endsWith("#Link")
? null
: (range as unknown as Resource), // Will be updated in a subsequent pass
required:
supportedProperties?.[
"http://www.w3.org/ns/hydra/core#required"
]?.[0]?.["@value"] ?? false,
description:
supportedProperties?.[
"http://www.w3.org/ns/hydra/core#description"
]?.[0]?.["@value"] ?? "",
maxCardinality:
supportedProperty?.[
"http://www.w3.org/2002/07/owl#maxCardinality"
]?.[0]?.["@value"] ?? null,
deprecated:
supportedProperties?.[
"http://www.w3.org/2002/07/owl#deprecated"
]?.[0]?.["@value"] ?? false,
},
);
fields.push(field);
resourceFields.push(field);
if (
supportedProperties?.[
"http://www.w3.org/ns/hydra/core#readable"
]?.[0]?.["@value"]
) {
readableFields.push(field);
}
if (
supportedProperties?.[
"http://www.w3.org/ns/hydra/core#writeable"
]?.[0]?.["@value"] ||
supportedProperties?.[
"http://www.w3.org/ns/hydra/core#writable"
]?.[0]?.["@value"]
) {
writableFields.push(field);
}
}
// parse entrypoint's operations (a.k.a. collection operations)
if (property["http://www.w3.org/ns/hydra/core#supportedOperation"]) {
for (const entrypointOperation of property[
"http://www.w3.org/ns/hydra/core#supportedOperation"
]) {
if (!entrypointOperation["http://www.w3.org/ns/hydra/core#returns"]) {
continue;
}
const range =
entrypointOperation["http://www.w3.org/ns/hydra/core#returns"]?.[0]?.[
"@id"
];
const method =
entrypointOperation["http://www.w3.org/ns/hydra/core#method"]?.[0]?.[
"@value"
];
let type: OperationType = "list";
if (method === "POST") {
type = "create";
}
const operation = new Operation(
getTitleOrLabel(entrypointOperation),
type,
{
method,
expects:
entrypointOperation[
"http://www.w3.org/ns/hydra/core#expects"
]?.[0]?.["@id"],
returns: range,
types: entrypointOperation["@type"],
deprecated:
entrypointOperation?.[
"http://www.w3.org/2002/07/owl#deprecated"
]?.[0]?.["@value"] ?? false,
},
);
resourceOperations.push(operation);
operations.push(operation);
}
}
// parse resource operations (a.k.a. item operations)
for (const supportedOperation of relatedClass[
"http://www.w3.org/ns/hydra/core#supportedOperation"
] || []) {
if (!supportedOperation["http://www.w3.org/ns/hydra/core#returns"]) {
continue;
}
const range =
supportedOperation["http://www.w3.org/ns/hydra/core#returns"]?.[0]?.[
"@id"
];
const method =
supportedOperation["http://www.w3.org/ns/hydra/core#method"]?.[0]?.[
"@value"
];
let type: OperationType = "show";
if (method === "POST") {
type = "create";
}
if (method === "PUT" || method === "PATCH") {
type = "edit";
}
if (method === "DELETE") {
type = "delete";
}
const operation = new Operation(
getTitleOrLabel(supportedOperation),
type,
{
method,
expects:
supportedOperation[
"http://www.w3.org/ns/hydra/core#expects"
]?.[0]?.["@id"],
returns: range,
types: supportedOperation["@type"],
deprecated:
supportedOperation?.[
"http://www.w3.org/2002/07/owl#deprecated"
]?.[0]?.["@value"] ?? false,
},
);
resourceOperations.push(operation);
operations.push(operation);
}
const manages = getManagesBlocks(property);
const resource = new Resource(guessNameFromUrl(url, entrypointUrl), url, {
id: relatedClass["@id"],
title:
relatedClass?.["http://www.w3.org/ns/hydra/core#title"]?.[0]?.[
"@value"
] ?? "",
fields: resourceFields,
readableFields,
writableFields,
operations: resourceOperations,
deprecated:
relatedClass?.["http://www.w3.org/2002/07/owl#deprecated"]?.[0]?.[
"@value"
] ?? false,
...(manages.length > 0 && { manages }),
});
resource.parameters = [];
resource.getParameters =
/**
* Gets the parameters for the resource.
* @returns {Promise<Parameter[]>} The parameters for the resource.
*/
(): Promise<Parameter[]> => getParameters(resource, options);
resources.push(resource);
}
// Resolve references and embedded
for (const field of fields) {
if (field.reference !== null) {
field.reference =
resources.find((resource) => resource.id === field.reference) || null;
}
if (field.embedded !== null) {
field.embedded =
resources.find((resource) => resource.id === field.embedded) || null;
}
}
return {
api: new Api(entrypointUrl, { title, resources }),
response,
status: response.status,
};
}