@fluid-topics/public-api 1.0.39 → 1.0.40

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.
@@ -0,0 +1,360 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
+ return new (P || (P = Promise))(function (resolve, reject) {
19
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23
+ });
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.FluidTopicsApi = exports.HttpError = void 0;
27
+ require("cross-fetch/polyfill");
28
+ const wnd = (typeof window === "undefined" ? globalThis : window);
29
+ __exportStar(require("./types/ft-common/public"), exports);
30
+ __exportStar(require("./types/ft-server/public"), exports);
31
+ __exportStar(require("./roles/roles"), exports);
32
+ __exportStar(require("./preferences/unauthenticated-preferences"), exports);
33
+ function toBase64(s) {
34
+ return typeof Buffer !== "undefined" ? Buffer.from(s).toString("base64") : btoa(s);
35
+ }
36
+ class HttpError extends Error {
37
+ constructor(status, statusText, body) {
38
+ super(`${status} - ${statusText}: ${body}`);
39
+ this.status = status;
40
+ this.statusText = statusText;
41
+ this.body = body;
42
+ }
43
+ }
44
+ exports.HttpError = HttpError;
45
+ function handleError(response) {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ if (!response.ok) {
48
+ throw new HttpError(response.status, response.statusText, yield response.text());
49
+ }
50
+ return response;
51
+ });
52
+ }
53
+ function getBody(response) {
54
+ return response.headers.get("Content-Type") === "application/json" ? response.json() : response.text();
55
+ }
56
+ class FluidTopicsApi {
57
+ get defaultHeaders() {
58
+ return Object.assign(Object.assign(Object.assign({}, this.authorization), this.searchLabel), { "Ft-Calling-App": this.ftCallingApp });
59
+ }
60
+ constructor(tenantBaseUrl, integrationIdentifier, overrideIdentifierIfOnTenant) {
61
+ var _a, _b, _c, _d, _e, _f;
62
+ this.endpoints = {
63
+ authentication: {
64
+ login: `api/authentication/login`,
65
+ logout: `api/authentication/logout`,
66
+ currentSession: `api/authentication/current-session`,
67
+ },
68
+ khub: {
69
+ maps: {
70
+ mapId: (mapId) => ({
71
+ info: `api/khub/maps/${mapId}`,
72
+ toc: `api/khub/maps/${mapId}/toc`,
73
+ pages: `api/khub/maps/${mapId}/pages`,
74
+ feedback: `api/khub/maps/${mapId}/feedback`,
75
+ rating: `api/khub/maps/${mapId}/rating`,
76
+ attachments: {
77
+ list: `api/khub/maps/${mapId}/attachments`,
78
+ attachmentId: (attachmentId) => ({
79
+ content: `api/khub/maps/${mapId}/attachments/${attachmentId}/content`,
80
+ })
81
+ },
82
+ resources: {
83
+ list: `api/khub/maps/${mapId}/resources`,
84
+ resourceId: (resourceId) => ({
85
+ content: `api/khub/maps/${mapId}/resources/${resourceId}/content`,
86
+ })
87
+ },
88
+ topics: {
89
+ contentId: (contentId) => ({
90
+ info: `api/khub/maps/${mapId}/topics/${contentId}`,
91
+ content: `api/khub/maps/${mapId}/topics/${contentId}/content`,
92
+ }),
93
+ tocId: (tocId) => ({
94
+ feedback: `api/khub/maps/${mapId}/topics/${tocId}/feedback`,
95
+ rating: `api/khub/maps/${mapId}/topics/${tocId}/rating`,
96
+ })
97
+ },
98
+ })
99
+ },
100
+ documents: {
101
+ documentId: (documentId) => ({
102
+ info: `api/khub/documents/${documentId}`,
103
+ content: `api/khub/documents/${documentId}/content`,
104
+ text: `api/khub/documents/${documentId}/content/text`,
105
+ feedback: `api/khub/documents/${documentId}/feedback`,
106
+ rating: `api/khub/documents/${documentId}/rating`,
107
+ })
108
+ },
109
+ suggest: `api/khub/suggest`,
110
+ clusteredSearch: `api/khub/clustered-search`,
111
+ locales: `api/khub/locales`,
112
+ },
113
+ users: {
114
+ userId: (userId) => ({
115
+ collections: {
116
+ collectionId: (collectionId) => ({
117
+ documents: `api/users/${userId}/collections/${collectionId}/documents`,
118
+ })
119
+ },
120
+ searches: {
121
+ list: `api/users/${userId}/searches`
122
+ }
123
+ }),
124
+ },
125
+ stylesheets: {
126
+ fonts: `api/stylesheets/fonts.css`,
127
+ theme: `api/stylesheets/theme.css`,
128
+ content: {
129
+ title: `api/stylesheets/content/title.css`,
130
+ topic: `api/stylesheets/content/topic.css`,
131
+ },
132
+ },
133
+ configuration: {
134
+ reader: `api/configuration/reader`
135
+ },
136
+ locales: {
137
+ ui: `api/locales/ui`
138
+ },
139
+ messages: {
140
+ locale: (locale) => ({
141
+ fluidTopics: {
142
+ contextName: (contextName) => ({
143
+ endpoint: `api/messages/${locale}/fluid-topics/${contextName}`,
144
+ })
145
+ },
146
+ custom: {
147
+ contextName: (contextName) => ({
148
+ endpoint: `api/messages/${locale}/custom/${contextName}`,
149
+ })
150
+ }
151
+ })
152
+ },
153
+ };
154
+ //@ts-ignore
155
+ tenantBaseUrl = ((_f = (_c = (_a = tenantBaseUrl !== null && tenantBaseUrl !== void 0 ? tenantBaseUrl : wnd.__gwt_ft_moduleBase) !== null && _a !== void 0 ? _a : (_b = wnd.fluidtopicsclient) === null || _b === void 0 ? void 0 : _b.__moduleBase) !== null && _c !== void 0 ? _c : (_e = (_d = wnd.__gwt_activeModules) === null || _d === void 0 ? void 0 : _d.fluidtopicsclient) === null || _e === void 0 ? void 0 : _e.moduleBase) !== null && _f !== void 0 ? _f : "").trim();
156
+ this.tenantBaseUrl = tenantBaseUrl.endsWith("/") ? tenantBaseUrl : tenantBaseUrl + "/";
157
+ if (overrideIdentifierIfOnTenant && typeof wnd.location !== "undefined" && wnd.location.href.startsWith(this.tenantBaseUrl)) {
158
+ this.ftCallingApp = integrationIdentifier;
159
+ }
160
+ else {
161
+ this.ftCallingApp = `ft-public-api/${integrationIdentifier}`;
162
+ }
163
+ }
164
+ setApiKey(apiKey) {
165
+ this.authorization = { "Authorization": "Bearer " + apiKey };
166
+ }
167
+ setCredentials(login, password) {
168
+ this.authorization = { "Authorization": "Basic " + toBase64(`${login}:${password}`) };
169
+ }
170
+ clearAuthentication() {
171
+ this.authorization = undefined;
172
+ }
173
+ setSearchLabel(searchLabel) {
174
+ this.searchLabel = { "FT-search-label": searchLabel };
175
+ }
176
+ clearSearchLabel() {
177
+ this.searchLabel = undefined;
178
+ }
179
+ login(login, password) {
180
+ let credentials = {
181
+ login: login,
182
+ password: password,
183
+ rememberMe: true
184
+ };
185
+ return this.post(this.endpoints.authentication.login, credentials)
186
+ .then(result => {
187
+ this.setCredentials(login, password);
188
+ return result;
189
+ });
190
+ }
191
+ logout() {
192
+ return this.post(this.endpoints.authentication.logout)
193
+ .then(() => this.clearAuthentication());
194
+ }
195
+ getCurrentSession() {
196
+ return this.get(this.endpoints.authentication.currentSession);
197
+ }
198
+ getReaderConfiguration() {
199
+ return this.get(this.endpoints.configuration.reader);
200
+ }
201
+ getMap(mapId) {
202
+ return this.get(this.endpoints.khub.maps.mapId(mapId).info);
203
+ }
204
+ getTableOfContent(mapId) {
205
+ return this.get(this.endpoints.khub.maps.mapId(mapId).toc);
206
+ }
207
+ getPages(mapId) {
208
+ return this.get(this.endpoints.khub.maps.mapId(mapId).pages);
209
+ }
210
+ getTopic(mapId, topicContentId) {
211
+ return this.get(this.endpoints.khub.maps.mapId(mapId).topics.contentId(topicContentId).info);
212
+ }
213
+ getTopicHTMLContent(mapId, topicContentId, target) {
214
+ return this.get(this.endpoints.khub.maps.mapId(mapId).topics.contentId(topicContentId).content + (target ? "?target=" + target : ""));
215
+ }
216
+ getMapAttachments(mapId) {
217
+ return this.get(this.endpoints.khub.maps.mapId(mapId).attachments.list);
218
+ }
219
+ getMapAttachmentContent(mapId, attachmentId) {
220
+ return this.fetchRawData(this.endpoints.khub.maps.mapId(mapId).attachments.attachmentId(attachmentId).content);
221
+ }
222
+ getMapResources(mapId) {
223
+ return this.get(this.endpoints.khub.maps.mapId(mapId).resources.list);
224
+ }
225
+ getMapResourceContent(mapId, resourceId) {
226
+ return this.fetchRawData(this.endpoints.khub.maps.mapId(mapId).resources.resourceId(resourceId).content);
227
+ }
228
+ getUnstructuredDocument(documentId) {
229
+ return this.get(this.endpoints.khub.documents.documentId(documentId).info);
230
+ }
231
+ getUnstructuredDocumentContent(documentId) {
232
+ return this.fetchRawData(this.endpoints.khub.documents.documentId(documentId).content);
233
+ }
234
+ getUnstructuredDocumentTextContent(documentId) {
235
+ return this.get(this.endpoints.khub.documents.documentId(documentId).text);
236
+ }
237
+ getCollectionDocuments(userId, collectionId) {
238
+ return this.get(this.endpoints.users.userId(userId).collections.collectionId(collectionId).documents);
239
+ }
240
+ getSuggestions(request) {
241
+ return this.post(this.endpoints.khub.suggest, request);
242
+ }
243
+ search(request) {
244
+ return this.post(this.endpoints.khub.clusteredSearch, request);
245
+ }
246
+ getAvailableSearchLocales() {
247
+ return this.get(this.endpoints.khub.locales);
248
+ }
249
+ getAvailableUiLocales() {
250
+ return this.get(this.endpoints.khub.locales);
251
+ }
252
+ getMapRating(mapId) {
253
+ return this.get(this.endpoints.khub.maps.mapId(mapId).rating);
254
+ }
255
+ rateMap(mapId, type, value) {
256
+ return this.post(this.endpoints.khub.maps.mapId(mapId).rating, { type, value });
257
+ }
258
+ unrateMap(mapId) {
259
+ return this.delete(this.endpoints.khub.maps.mapId(mapId).rating);
260
+ }
261
+ sendMapFeedback(mapId, message, from) {
262
+ return this.post(this.endpoints.khub.maps.mapId(mapId).feedback, { message, from });
263
+ }
264
+ rateTopic(mapId, tocId, type, value) {
265
+ return this.post(this.endpoints.khub.maps.mapId(mapId).topics.tocId(tocId).rating, {
266
+ type, value
267
+ });
268
+ }
269
+ unrateTopic(mapId, tocId) {
270
+ return this.delete(this.endpoints.khub.maps.mapId(mapId).topics.tocId(tocId).rating);
271
+ }
272
+ sendTopicFeedback(mapId, tocId, message, from) {
273
+ return this.post(this.endpoints.khub.maps.mapId(mapId).topics.tocId(tocId).feedback, { message, from });
274
+ }
275
+ getDocumentRating(docId) {
276
+ return this.get(this.endpoints.khub.documents.documentId(docId).rating);
277
+ }
278
+ rateDocument(docId, type, value) {
279
+ return this.post(this.endpoints.khub.documents.documentId(docId).rating, { type, value });
280
+ }
281
+ unrateDocument(docId) {
282
+ return this.delete(this.endpoints.khub.documents.documentId(docId).rating);
283
+ }
284
+ sendDocumentFeedback(docId, message, from) {
285
+ return this.post(this.endpoints.khub.documents.documentId(docId).feedback, { message, from });
286
+ }
287
+ getFluidTopicsMessageContext(locale, name) {
288
+ return this.get(this.endpoints.messages.locale(locale).fluidTopics.contextName(name).endpoint);
289
+ }
290
+ getCustomMessageContext(locale, name) {
291
+ return this.get(this.endpoints.messages.locale(locale).custom.contextName(name).endpoint);
292
+ }
293
+ listMySearches(userId) {
294
+ return this.get(this.endpoints.users.userId(userId).searches.list);
295
+ }
296
+ get(endpoint) {
297
+ return this.makeRequest("GET", endpoint);
298
+ }
299
+ post(endpoint, data) {
300
+ return this.makeRequest("POST", endpoint, data);
301
+ }
302
+ put(endpoint, data) {
303
+ return this.makeRequest("PUT", endpoint, data);
304
+ }
305
+ delete(endpoint) {
306
+ return this.makeRequest("DELETE", endpoint);
307
+ }
308
+ makeAbsolute(endpoint) {
309
+ return this.tenantBaseUrl + endpoint.replace(/^\//, "");
310
+ }
311
+ fetch(endpoint, init) {
312
+ var _a;
313
+ return __awaiter(this, void 0, void 0, function* () {
314
+ const requestInit = init;
315
+ return yield fetch(this.makeAbsolute(endpoint), Object.assign(Object.assign({}, (requestInit !== null && requestInit !== void 0 ? requestInit : {})), { headers: Object.assign(Object.assign({}, this.defaultHeaders), ((_a = requestInit === null || requestInit === void 0 ? void 0 : requestInit.headers) !== null && _a !== void 0 ? _a : {})) }));
316
+ });
317
+ }
318
+ upload(method, endpoint, body, onProgress = () => undefined) {
319
+ if (typeof XMLHttpRequest !== "undefined") {
320
+ return new Promise((resolve, reject) => {
321
+ let xhr = new XMLHttpRequest();
322
+ xhr.onload = () => {
323
+ if (xhr.status >= 200 && xhr.status < 300) {
324
+ let data = xhr.getResponseHeader("Content-Type") === "application/json" ? JSON.parse(xhr.responseText) : xhr.responseText;
325
+ resolve(data);
326
+ }
327
+ else {
328
+ reject(new HttpError(xhr.status, xhr.statusText, xhr.responseText));
329
+ }
330
+ };
331
+ xhr.upload.onprogress = (e) => onProgress(e);
332
+ xhr.open(method, this.makeAbsolute(endpoint), true);
333
+ xhr.send(body);
334
+ });
335
+ }
336
+ else {
337
+ return this.fetch(endpoint, { method, body }).then(handleError).then(getBody);
338
+ }
339
+ }
340
+ makeRequest(method, endpoint, data) {
341
+ return this.fetch(endpoint, {
342
+ method: method,
343
+ headers: Object.assign({}, (data != null ? { "Content-Type": "application/json" } : {})),
344
+ body: data != null ? JSON.stringify(data) : undefined,
345
+ credentials: this.authorization == null ? "include" : undefined
346
+ })
347
+ .then(handleError)
348
+ .then(getBody);
349
+ }
350
+ fetchRawData(endpoint) {
351
+ return fetch(this.makeAbsolute(endpoint), {
352
+ headers: this.defaultHeaders,
353
+ credentials: this.authorization == null ? "include" : undefined
354
+ })
355
+ .then(handleError)
356
+ .then(response => response.arrayBuffer());
357
+ }
358
+ }
359
+ exports.FluidTopicsApi = FluidTopicsApi;
360
+ exports.default = FluidTopicsApi;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addUnauthenticatedUserSearchPreferencesChangeHandler = exports.getUnauthenticatedUserSearchPreferences = exports.setUnauthenticatedUserSearchPreferences = void 0;
4
+ const wnd = (typeof window === "undefined" ? globalThis : window);
5
+ function normalizeMetadataPreferences(metadata) {
6
+ let normalized = {};
7
+ for (let key in metadata) {
8
+ let values = metadata[key];
9
+ if (typeof values !== "object" || Array.isArray(values)) {
10
+ values = { prior: values };
11
+ }
12
+ for (let property of ["prior", "filter"]) {
13
+ values[property] = Array.isArray(values[property]) ? values[property] : [values[property]];
14
+ values[property] = values[property]
15
+ .map(v => v != null ? "" + v : "")
16
+ .filter(v => v !== "");
17
+ }
18
+ normalized[key] = values;
19
+ }
20
+ return normalized;
21
+ }
22
+ function getStorageKey(tenantBaseUrl) {
23
+ return `${tenantBaseUrl}-FluidTopicsUnauthenticatedUserSearchPreferences`;
24
+ }
25
+ function setUnauthenticatedUserSearchPreferences(tenantBaseUrl, input) {
26
+ var _a;
27
+ if (wnd.localStorage) {
28
+ let preferences = Object.assign(Object.assign({}, input), { metadata: normalizeMetadataPreferences((_a = input.metadata) !== null && _a !== void 0 ? _a : {}) });
29
+ const key = getStorageKey(tenantBaseUrl);
30
+ const newValue = JSON.stringify(preferences);
31
+ wnd.localStorage.setItem(key, newValue);
32
+ wnd.dispatchEvent(new StorageEvent("storage", {
33
+ key,
34
+ newValue,
35
+ storageArea: wnd.localStorage,
36
+ url: wnd.location.href
37
+ }));
38
+ return preferences;
39
+ }
40
+ console.error("Cannot set unauthenticated preferences: local storage is unavailable.");
41
+ }
42
+ exports.setUnauthenticatedUserSearchPreferences = setUnauthenticatedUserSearchPreferences;
43
+ function getUnauthenticatedUserSearchPreferences(tenantBaseUrl) {
44
+ var _a;
45
+ if (wnd.localStorage) {
46
+ return JSON.parse((_a = wnd.localStorage.getItem(getStorageKey(tenantBaseUrl))) !== null && _a !== void 0 ? _a : "{}");
47
+ }
48
+ console.error("Cannot get unauthenticated preferences: local storage is unavailable.");
49
+ }
50
+ exports.getUnauthenticatedUserSearchPreferences = getUnauthenticatedUserSearchPreferences;
51
+ function addUnauthenticatedUserSearchPreferencesChangeHandler(tenantBaseUrl, handler) {
52
+ if (wnd.localStorage) {
53
+ const key = getStorageKey(tenantBaseUrl);
54
+ const eventListener = (event) => {
55
+ var _a;
56
+ if (event.storageArea === wnd.localStorage && event.key === key) {
57
+ handler(JSON.parse((_a = event.newValue) !== null && _a !== void 0 ? _a : "{}"));
58
+ }
59
+ };
60
+ wnd.addEventListener("storage", eventListener);
61
+ return {
62
+ removeHandler: () => wnd.removeEventListener("storage", eventListener)
63
+ };
64
+ }
65
+ console.error("Cannot handle unauthenticated preferences: local storage is unavailable.");
66
+ }
67
+ exports.addUnauthenticatedUserSearchPreferencesChangeHandler = addUnauthenticatedUserSearchPreferencesChangeHandler;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.userHasRole = exports.roleMatches = void 0;
4
+ const public_1 = require("../types/ft-common/public");
5
+ const rolesInheritance = {
6
+ [public_1.FtUserRole.PERSONAL_BOOK_SHARE_USER]: [public_1.FtUserRole.PERSONAL_BOOK_USER],
7
+ [public_1.FtUserRole.HTML_EXPORT_USER]: [public_1.FtUserRole.PERSONAL_BOOK_USER],
8
+ [public_1.FtUserRole.PDF_EXPORT_USER]: [public_1.FtUserRole.PERSONAL_BOOK_USER],
9
+ [public_1.FtUserRole.KHUB_ADMIN]: [public_1.FtUserRole.CONTENT_PUBLISHER],
10
+ [public_1.FtUserRole.ADMIN]: [public_1.FtUserRole.KHUB_ADMIN, public_1.FtUserRole.USERS_ADMIN, public_1.FtUserRole.PORTAL_ADMIN],
11
+ [public_1.FtUserRole.DEVELOPER]: [public_1.FtUserRole.BETA_USER, public_1.FtUserRole.DEBUG_USER],
12
+ };
13
+ function roleMatches(actual, expected) {
14
+ var _a;
15
+ return actual === expected || ((_a = rolesInheritance[actual]) !== null && _a !== void 0 ? _a : []).some((inherited) => roleMatches(inherited, expected));
16
+ }
17
+ exports.roleMatches = roleMatches;
18
+ function userHasRole(userRoles, expectedRole) {
19
+ return userRoles.some(role => roleMatches(role, expectedRole));
20
+ }
21
+ exports.userHasRole = userHasRole;