-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathLDMClient.js
More file actions
338 lines (294 loc) · 13.8 KB
/
LDMClient.js
File metadata and controls
338 lines (294 loc) · 13.8 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
import * as $rdf from 'rdflib';
const DEFAULT_ACCEPT = 'text/turtle, application/rdf+xml;q=0.9, application/ld+json;q=0.8, application/json;q=0.7';
const INVERSE_LINK_TYPES = new Map([
['http://open-services.net/ns/core#related', 'http://open-services.net/ns/core#related'],
['http://open-services.net/ns/rm#constraints', 'http://open-services.net/ns/rm#constrainedBy'],
['http://open-services.net/ns/rm#constrainedBy', 'http://open-services.net/ns/rm#constraints'],
['http://open-services.net/ns/rm#decomposes', 'http://open-services.net/ns/rm#decomposedBy'],
['http://open-services.net/ns/rm#decomposedBy', 'http://open-services.net/ns/rm#decomposes'],
['http://open-services.net/ns/rm#elaborates', 'http://open-services.net/ns/rm#elaboratedBy'],
['http://open-services.net/ns/rm#elaboratedBy', 'http://open-services.net/ns/rm#elaborates'],
['http://open-services.net/ns/rm#satisfies', 'http://open-services.net/ns/rm#satisfiedBy'],
['http://open-services.net/ns/rm#satisfiedBy', 'http://open-services.net/ns/rm#satisfies'],
['http://open-services.net/ns/rm#specifies', 'http://open-services.net/ns/rm#specifiedBy'],
['http://open-services.net/ns/rm#specifiedBy', 'http://open-services.net/ns/rm#specifies'],
['http://open-services.net/ns/qm#validatesRequirement', 'http://open-services.net/ns/rm#validatedBy'],
['http://open-services.net/ns/qm#validatesRequirementCollection', 'http://open-services.net/ns/rm#validatedBy'],
['http://open-services.net/ns/cm#implementsRequirement', 'http://open-services.net/ns/rm#implementedBy'],
['http://open-services.net/ns/cm#tracksRequirement', 'http://open-services.net/ns/rm#trackedBy'],
['http://open-services.net/ns/cm#affectsRequirement', 'http://open-services.net/ns/rm#affectedBy'],
['http://open-services.net/ns/rm#implementedBy', 'http://open-services.net/ns/cm#implementsRequirement'],
['http://open-services.net/ns/rm#trackedBy', 'http://open-services.net/ns/cm#tracksRequirement'],
['http://open-services.net/ns/rm#affectedBy', 'http://open-services.net/ns/cm#affectsRequirement'],
['http://open-services.net/ns/cm#testedByTestCase', 'http://open-services.net/ns/qm#testsChangeRequest'],
['http://open-services.net/ns/qm#testsChangeRequest', 'http://open-services.net/ns/cm#testedByTestCase'],
['http://open-services.net/ns/cm#relatedTestScript', 'http://open-services.net/ns/qm#relatedChangeRequest'],
['http://open-services.net/ns/cm#relatedTestCase', 'http://open-services.net/ns/qm#relatedChangeRequest'],
['http://open-services.net/ns/cm#relatedTestPlan', 'http://open-services.net/ns/qm#relatedChangeRequest'],
['http://open-services.net/ns/cm#relatedTestExecutionRecord', 'http://open-services.net/ns/qm#relatedChangeRequest'],
['http://open-services.net/ns/cm#blocksTestExecutionRecord', 'http://open-services.net/ns/qm#blockedByChangeRequest'],
['http://open-services.net/ns/qm#blockedByChangeRequest', 'http://open-services.net/ns/cm#blocksTestExecutionRecord'],
['http://open-services.net/ns/cm#affectsTestResult', 'http://open-services.net/ns/qm#affectedByChangeRequest'],
['http://open-services.net/ns/qm#affectedByChangeRequest', 'http://open-services.net/ns/cm#affectsTestResult'],
['http://open-services.net/ns/cm#affectedByDefect', 'http://open-services.net/ns/cm#affectsPlanItem'],
['http://open-services.net/ns/cm#affectsPlanItem', 'http://open-services.net/ns/cm#affectedByDefect'],
['http://jazz.net/ns/rm/navigation#parent', 'http://jazz.net/ns/rm/navigation#children'],
['http://jazz.net/ns/rm/navigation#children', 'http://jazz.net/ns/rm/navigation#parent']
]);
function normalizeBaseUrl(url) {
if (!url) {
throw new Error('LDMServerBaseURL is required');
}
return url.endsWith('/') ? url.slice(0, -1) : url;
}
function asUrlString(value, name) {
if (typeof value !== 'string' || !value.trim()) {
throw new Error(`${name} must be a non-empty string`);
}
return value;
}
function parseRdfTriples({ data, contentType, baseIRI }) {
const store = $rdf.graph();
const ct = contentType?.split(';')[0]?.trim() || 'text/turtle';
$rdf.parse(data, store, baseIRI, ct);
return store.statementsMatching(null, null, null).map(st => ({
sourceURL: st.subject.value,
linkType: st.predicate.value,
targetURL: st.object.value
}));
}
/**
* LDMClient is a composition helper that uses an OSLCClient instance for HTTP requests.
* It provides Link Discovery Management (LDM) functionality for discovering
* incoming links to OSLC resources.
*/
export default class LDMClient {
/**
* Create an LDMClient instance.
* @param {OSLCClient} oslcClient - An initialized OSLCClient instance (provides client, userid, password, configuration_context)
* @param {string} ldmServerBaseUrl - Base URL of the LDM server (e.g., https://server/ldm)
*/
constructor(oslcClient, ldmServerBaseUrl) {
this.oslcClient = oslcClient;
this.client = oslcClient.client;
this.LDMServerBaseURL = normalizeBaseUrl(ldmServerBaseUrl);
this._warnedMissingInverseLinkTypes = new Set();
}
/**
* Get incoming links to one or more target resources.
* @param {string[]} targetResourceURLs - Array of resource URLs to find incoming links for
* @param {string[]} linkTypes - Optional array of link type URIs to filter by
* @param {string|null} configurationContext - Optional configuration context (overrides constructor value)
* @returns {Promise<Array<{sourceURL: string, linkType: string, targetURL: string}>>}
*/
async getIncomingLinks(targetResourceURLs, linkTypes = [], configurationContext = null) {
if (!Array.isArray(targetResourceURLs) || targetResourceURLs.length === 0) {
throw new Error('targetResourceURLs must be a non-empty array');
}
if (!Array.isArray(linkTypes)) {
throw new Error('linkTypes must be an array');
}
// Use provided configurationContext or fall back to the one set in constructor
const effectiveConfigContext = configurationContext || this.oslcClient.configuration_context;
const isLqe = this.LDMServerBaseURL.includes('/lqe');
if (isLqe) {
return this.#getIncomingLinksViaLqe(targetResourceURLs, linkTypes, effectiveConfigContext);
}
return this.#getIncomingLinksViaLdm(targetResourceURLs, linkTypes, effectiveConfigContext);
}
/**
* Invert a list of triples, swapping source and target and mapping to inverse link types.
* @param {Array<{sourceURL: string, linkType: string, targetURL: string}>} triples
* @returns {Array<{targetURL: string, inverseLinkType: string, sourceURL: string}>}
*/
invert(triples) {
if (!Array.isArray(triples)) {
throw new Error('triples must be an array');
}
const debugLqe = typeof process !== 'undefined' && process?.env?.DEBUG_LQE === 'true';
return triples.map(t => {
const sourceURL = Array.isArray(t) ? t[0] : t?.sourceURL;
const linkType = Array.isArray(t) ? t[1] : t?.linkType;
const targetURL = Array.isArray(t) ? t[2] : t?.targetURL;
const source = asUrlString(sourceURL, 'sourceURL');
const predicate = asUrlString(linkType, 'linkType');
const target = asUrlString(targetURL, 'targetURL');
let inverseLinkType = INVERSE_LINK_TYPES.get(predicate);
if (!inverseLinkType) {
const matches = [];
for (const [k, v] of INVERSE_LINK_TYPES.entries()) {
if (v === predicate) {
matches.push(k);
}
}
if (matches.length === 1) {
inverseLinkType = matches[0];
} else if (matches.length > 1) {
inverseLinkType = matches[0];
if (debugLqe && !this._warnedMissingInverseLinkTypes.has(predicate)) {
this._warnedMissingInverseLinkTypes.add(predicate);
console.warn(`[LDMClient] Multiple inverse link type mappings found for predicate: ${predicate}. Using: ${inverseLinkType}`);
}
}
}
if (!inverseLinkType) {
if (debugLqe && !this._warnedMissingInverseLinkTypes.has(predicate)) {
this._warnedMissingInverseLinkTypes.add(predicate);
console.warn(`[LDMClient] No inverse link type mapping found for predicate: ${predicate}`);
}
}
return {
targetURL: target,
inverseLinkType: inverseLinkType || predicate,
sourceURL: source
};
});
}
async #getIncomingLinksViaLdm(targetResourceURLs, linkTypes, configurationContext) {
const url = `${this.LDMServerBaseURL}/discover-links`;
const headers = {
'Accept': DEFAULT_ACCEPT
};
if (configurationContext) {
headers['Configuration-Context'] = asUrlString(configurationContext, 'configurationContext');
}
const postRdfRequest = async () => {
const oslcLdmNamespace = 'http://open-services.net/ns/ldm#';
const resourceList = targetResourceURLs
.map(u => `<${asUrlString(u, 'targetResourceURL')}>`)
.join(', ');
const predicateList = (Array.isArray(linkTypes) && linkTypes.length > 0)
? linkTypes.map(u => `<${asUrlString(u, 'linkType')}>`).join(', ')
: null;
let turtle = `@prefix oslc_ldm: <${oslcLdmNamespace}> .\n`;
turtle += `[] oslc_ldm:resources ${resourceList}`;
if (predicateList) {
turtle += ` ;\n oslc_ldm:linkPredicates ${predicateList}`;
}
turtle += ` .\n`;
const response = await this.client.post(url, turtle, {
headers: {
...headers,
'Content-Type': 'text/turtle'
}
});
const contentType = response?.headers?.['content-type'] || 'text/turtle';
return parseRdfTriples({
data: response.data,
contentType,
baseIRI: url
});
};
const postLegacyFormRequest = async objectFieldName => {
const params = new URLSearchParams();
for (const target of targetResourceURLs) {
params.append(objectFieldName, asUrlString(target, 'targetResourceURL'));
}
for (const predicate of linkTypes) {
params.append('predicateFilters', asUrlString(predicate, 'linkType'));
}
const response = await this.client.post(url, params.toString(), {
headers: {
...headers,
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const contentType = response?.headers?.['content-type'] || 'text/turtle';
return parseRdfTriples({
data: response.data,
contentType,
baseIRI: url
});
};
try {
// Prefer the latest LDM spec behavior: RDF request/response bodies.
return await postRdfRequest();
} catch (err) {
// Fallback for older/out-of-date servers.
try {
return await postLegacyFormRequest('objectResources');
} catch (err2) {
return await postLegacyFormRequest('objectConceptResources');
}
}
}
async #getIncomingLinksViaLqe(targetResourceURLs, linkTypes, configurationContext) {
const endpoint = `${this.LDMServerBaseURL}/incoming-links`;
const debugLqe = typeof process !== 'undefined' && process?.env?.DEBUG_LQE === 'true';
if (debugLqe) {
console.debug(`[LDMClient] LQE base URL: ${this.LDMServerBaseURL}`);
console.debug(`[LDMClient] POST incoming-links to: ${endpoint}`);
}
// Build form-encoded body
const params = new URLSearchParams();
for (const url of targetResourceURLs) {
params.append('targetUrl', asUrlString(url, 'targetResourceURL'));
}
// linkType is required by LQE — if none specified, send all known link types
const effectiveLinkTypes = (Array.isArray(linkTypes) && linkTypes.length > 0)
? linkTypes
: [...INVERSE_LINK_TYPES.keys()];
for (const lt of effectiveLinkTypes) {
params.append('linkType', asUrlString(lt, 'linkType'));
}
if (configurationContext) {
params.append('oslc_config.context', asUrlString(configurationContext, 'configurationContext'));
}
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'X-Jazz-CSRF-Prevent': '1',
};
if (configurationContext) {
headers['Configuration-Context'] = asUrlString(configurationContext, 'configurationContext');
}
const hasAuthorizationHeader = () => {
const common = this.client?.defaults?.headers?.common;
return !!(common?.Authorization || common?.authorization);
};
const requestAuth = !hasAuthorizationHeader() && this.oslcClient.userid && this.oslcClient.password
? { username: this.oslcClient.userid, password: this.oslcClient.password }
: undefined;
if (debugLqe) {
console.debug(`[LDMClient] incoming-links request body: ${params.toString()}`);
}
try {
const response = await this.client.post(endpoint, params.toString(), {
auth: requestAuth,
headers,
});
const data = response.data;
if (debugLqe) {
console.debug(`[LDMClient] incoming-links response: numberOfResults=${data?.numberOfResults}`);
}
if (data?.error) {
throw new Error(`LQE incoming-links error: ${data.error}`);
}
// REST API format (LQE 7.1.0+ with relational store)
if (data?.queryResults) {
return data.queryResults.map(r => ({
sourceURL: r.sourceUrl || '',
linkType: r.linkType || '',
targetURL: r.targetUrl || ''
}));
}
// SPARQL JSON format (LQE with Jena store)
// Variables: sURL (source), linkType, tURL (target), indLinkType
if (data?.results?.bindings) {
return data.results.bindings.map(b => ({
sourceURL: b.sURL?.value || '',
linkType: b.linkType?.value || '',
targetURL: b.tURL?.value || ''
}));
}
return [];
} catch (error) {
const status = error?.response?.status;
const msg = error?.response?.data?.error || error?.message || 'Unknown error';
throw new Error(
`request=POST ${endpoint} ` +
`${status ? `status=${status} ` : ''}${msg}`
);
}
}
}