@things-factory/figure-library 10.1.281 → 10.1.283

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.
Files changed (35) hide show
  1. package/dist-client/index.d.ts +1 -0
  2. package/dist-client/index.js +1 -0
  3. package/dist-client/pages/figure-library-page.d.ts +6 -0
  4. package/dist-client/pages/figure-library-page.js +42 -2
  5. package/dist-client/settings/figure-source-setting-let.d.ts +25 -0
  6. package/dist-client/settings/figure-source-setting-let.js +190 -0
  7. package/dist-client/viewparts/figure-import-result.d.ts +20 -0
  8. package/dist-client/viewparts/figure-import-result.js +50 -0
  9. package/dist-client/viewparts/figure-package-import.d.ts +3 -14
  10. package/dist-client/viewparts/figure-package-import.js +3 -28
  11. package/dist-client/viewparts/figure-source-install.d.ts +24 -0
  12. package/dist-client/viewparts/figure-source-install.js +313 -0
  13. package/dist-server/routers/figure-source-thumbnail-router.d.ts +5 -0
  14. package/dist-server/routers/figure-source-thumbnail-router.js +39 -0
  15. package/dist-server/routes.js +3 -0
  16. package/dist-server/service/figure-library-resolver.js +2 -4
  17. package/dist-server/service/index.d.ts +7 -2
  18. package/dist-server/service/index.js +6 -1
  19. package/dist-server/service/library/import.d.ts +2 -0
  20. package/dist-server/service/library/import.js +3 -0
  21. package/dist-server/service/source/figure-source-resolver.d.ts +57 -0
  22. package/dist-server/service/source/figure-source-resolver.js +287 -0
  23. package/dist-server/service/source/source-client.d.ts +27 -0
  24. package/dist-server/service/source/source-client.js +109 -0
  25. package/dist-server/service/source/source-install.d.ts +57 -0
  26. package/dist-server/service/source/source-install.js +83 -0
  27. package/dist-server/service/source/source-setting-rules.d.ts +39 -0
  28. package/dist-server/service/source/source-setting-rules.js +71 -0
  29. package/package.json +8 -6
  30. package/translations/en.json +33 -1
  31. package/translations/es.json +33 -1
  32. package/translations/ja.json +33 -1
  33. package/translations/ko.json +33 -1
  34. package/translations/ms.json +33 -1
  35. package/translations/zh.json +33 -1
@@ -0,0 +1,287 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FigureSourceResolver = exports.FigureSourceCatalog = exports.FigureSourceCatalogItem = exports.FigureSourceCheck = exports.FigureSourceSettingPatch = exports.FigureSourceSetting = void 0;
4
+ exports.figureSourceOf = figureSourceOf;
5
+ const tslib_1 = require("tslib");
6
+ const type_graphql_1 = require("type-graphql");
7
+ const graphql_scalars_1 = require("graphql-scalars");
8
+ const typeorm_1 = require("typeorm");
9
+ const shell_1 = require("@things-factory/shell");
10
+ const figure_library_types_1 = require("../figure-library-types");
11
+ const source_install_1 = require("./source-install");
12
+ const source_setting_rules_1 = require("./source-setting-rules");
13
+ let FigureSourceSetting = class FigureSourceSetting {
14
+ };
15
+ exports.FigureSourceSetting = FigureSourceSetting;
16
+ tslib_1.__decorate([
17
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The figure server address, e.g. https://figure.hatiolab.com.' }),
18
+ tslib_1.__metadata("design:type", String)
19
+ ], FigureSourceSetting.prototype, "url", void 0);
20
+ tslib_1.__decorate([
21
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The domain on the figure server the figures are read from.' }),
22
+ tslib_1.__metadata("design:type", String)
23
+ ], FigureSourceSetting.prototype, "domain", void 0);
24
+ tslib_1.__decorate([
25
+ (0, type_graphql_1.Field)({ description: 'Whether the access token is set.' }),
26
+ tslib_1.__metadata("design:type", Boolean)
27
+ ], FigureSourceSetting.prototype, "tokenSet", void 0);
28
+ tslib_1.__decorate([
29
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The last characters of the token, to tell which token it is.' }),
30
+ tslib_1.__metadata("design:type", String)
31
+ ], FigureSourceSetting.prototype, "tokenHint", void 0);
32
+ exports.FigureSourceSetting = FigureSourceSetting = tslib_1.__decorate([
33
+ (0, type_graphql_1.ObjectType)({ description: 'The figure server this domain installs figures from (ADR-0114 decision 21) - never the token itself.' })
34
+ ], FigureSourceSetting);
35
+ let FigureSourceSettingPatch = class FigureSourceSettingPatch {
36
+ };
37
+ exports.FigureSourceSettingPatch = FigureSourceSettingPatch;
38
+ tslib_1.__decorate([
39
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The figure server address.' }),
40
+ tslib_1.__metadata("design:type", String)
41
+ ], FigureSourceSettingPatch.prototype, "url", void 0);
42
+ tslib_1.__decorate([
43
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The domain on the figure server.' }),
44
+ tslib_1.__metadata("design:type", String)
45
+ ], FigureSourceSettingPatch.prototype, "domain", void 0);
46
+ tslib_1.__decorate([
47
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The access token the figure server issued for this server.' }),
48
+ tslib_1.__metadata("design:type", String)
49
+ ], FigureSourceSettingPatch.prototype, "token", void 0);
50
+ exports.FigureSourceSettingPatch = FigureSourceSettingPatch = tslib_1.__decorate([
51
+ (0, type_graphql_1.InputType)({ description: 'A change to the figure server setting. A field left out stays as it is; an empty one clears it.' })
52
+ ], FigureSourceSettingPatch);
53
+ let FigureSourceCheck = class FigureSourceCheck {
54
+ };
55
+ exports.FigureSourceCheck = FigureSourceCheck;
56
+ tslib_1.__decorate([
57
+ (0, type_graphql_1.Field)({ description: 'Whether the figure server answered the catalog.' }),
58
+ tslib_1.__metadata("design:type", Boolean)
59
+ ], FigureSourceCheck.prototype, "ok", void 0);
60
+ tslib_1.__decorate([
61
+ (0, type_graphql_1.Field)({ nullable: true, description: 'Why not: figure-source-not-set, -unreachable, -unauthorized, -forbidden or what the server refused with.' }),
62
+ tslib_1.__metadata("design:type", String)
63
+ ], FigureSourceCheck.prototype, "code", void 0);
64
+ tslib_1.__decorate([
65
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The reason in the asker language.' }),
66
+ tslib_1.__metadata("design:type", String)
67
+ ], FigureSourceCheck.prototype, "message", void 0);
68
+ tslib_1.__decorate([
69
+ (0, type_graphql_1.Field)(type => type_graphql_1.Int, { nullable: true, description: 'How many figures the figure server offers this server.' }),
70
+ tslib_1.__metadata("design:type", Number)
71
+ ], FigureSourceCheck.prototype, "total", void 0);
72
+ exports.FigureSourceCheck = FigureSourceCheck = tslib_1.__decorate([
73
+ (0, type_graphql_1.ObjectType)({ description: 'Whether the figure server answers with the setting as it is.' })
74
+ ], FigureSourceCheck);
75
+ let FigureSourceCatalogItem = class FigureSourceCatalogItem {
76
+ };
77
+ exports.FigureSourceCatalogItem = FigureSourceCatalogItem;
78
+ tslib_1.__decorate([
79
+ (0, type_graphql_1.Field)({ description: 'The figure id on the figure server.' }),
80
+ tslib_1.__metadata("design:type", String)
81
+ ], FigureSourceCatalogItem.prototype, "figureId", void 0);
82
+ tslib_1.__decorate([
83
+ (0, type_graphql_1.Field)({ description: 'The full name {namespace}/{type}.' }),
84
+ tslib_1.__metadata("design:type", String)
85
+ ], FigureSourceCatalogItem.prototype, "fullName", void 0);
86
+ tslib_1.__decorate([
87
+ (0, type_graphql_1.Field)({ description: 'The latest release on the figure server, {namespace}/{type}@{version}.' }),
88
+ tslib_1.__metadata("design:type", String)
89
+ ], FigureSourceCatalogItem.prototype, "ref", void 0);
90
+ tslib_1.__decorate([
91
+ (0, type_graphql_1.Field)(type => type_graphql_1.Int, { description: 'The version of that release.' }),
92
+ tslib_1.__metadata("design:type", Number)
93
+ ], FigureSourceCatalogItem.prototype, "version", void 0);
94
+ tslib_1.__decorate([
95
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The display name, as released.' }),
96
+ tslib_1.__metadata("design:type", String)
97
+ ], FigureSourceCatalogItem.prototype, "name", void 0);
98
+ tslib_1.__decorate([
99
+ (0, type_graphql_1.Field)(type => graphql_scalars_1.GraphQLJSON, { nullable: true, description: 'The name in each language, as released.' }),
100
+ tslib_1.__metadata("design:type", Object)
101
+ ], FigureSourceCatalogItem.prototype, "names", void 0);
102
+ tslib_1.__decorate([
103
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The description, as released.' }),
104
+ tslib_1.__metadata("design:type", String)
105
+ ], FigureSourceCatalogItem.prototype, "description", void 0);
106
+ tslib_1.__decorate([
107
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The category, as released.' }),
108
+ tslib_1.__metadata("design:type", String)
109
+ ], FigureSourceCatalogItem.prototype, "category", void 0);
110
+ tslib_1.__decorate([
111
+ (0, type_graphql_1.Field)({ description: 'Its author advises not to use it.' }),
112
+ tslib_1.__metadata("design:type", Boolean)
113
+ ], FigureSourceCatalogItem.prototype, "deprecated", void 0);
114
+ tslib_1.__decorate([
115
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The full name to use instead, when deprecated.' }),
116
+ tslib_1.__metadata("design:type", String)
117
+ ], FigureSourceCatalogItem.prototype, "supersededBy", void 0);
118
+ tslib_1.__decorate([
119
+ (0, type_graphql_1.Field)({ description: 'Another domain on the figure server made it public.' }),
120
+ tslib_1.__metadata("design:type", Boolean)
121
+ ], FigureSourceCatalogItem.prototype, "public", void 0);
122
+ tslib_1.__decorate([
123
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The hash of the release picture, a cache key; none when it has no picture.' }),
124
+ tslib_1.__metadata("design:type", String)
125
+ ], FigureSourceCatalogItem.prototype, "thumbnailHash", void 0);
126
+ tslib_1.__decorate([
127
+ (0, type_graphql_1.Field)(type => type_graphql_1.Int, { nullable: true, description: 'The version the type map here draws this name with; null when none.' }),
128
+ tslib_1.__metadata("design:type", Number)
129
+ ], FigureSourceCatalogItem.prototype, "installedVersion", void 0);
130
+ tslib_1.__decorate([
131
+ (0, type_graphql_1.Field)({ description: 'not-installed, installed, newer, archived or format-unsupported.' }),
132
+ tslib_1.__metadata("design:type", String)
133
+ ], FigureSourceCatalogItem.prototype, "status", void 0);
134
+ exports.FigureSourceCatalogItem = FigureSourceCatalogItem = tslib_1.__decorate([
135
+ (0, type_graphql_1.ObjectType)({ description: 'A figure of the figure server catalog with what this library holds of it (ADR-0114 decision 25).' })
136
+ ], FigureSourceCatalogItem);
137
+ let FigureSourceCatalog = class FigureSourceCatalog {
138
+ };
139
+ exports.FigureSourceCatalog = FigureSourceCatalog;
140
+ tslib_1.__decorate([
141
+ (0, type_graphql_1.Field)(type => [FigureSourceCatalogItem], { description: 'The figures on this page.' }),
142
+ tslib_1.__metadata("design:type", Array)
143
+ ], FigureSourceCatalog.prototype, "items", void 0);
144
+ tslib_1.__decorate([
145
+ (0, type_graphql_1.Field)(type => type_graphql_1.Int, { description: 'How many figures match the query.' }),
146
+ tslib_1.__metadata("design:type", Number)
147
+ ], FigureSourceCatalog.prototype, "total", void 0);
148
+ exports.FigureSourceCatalog = FigureSourceCatalog = tslib_1.__decorate([
149
+ (0, type_graphql_1.ObjectType)({ description: 'A page of the figure server catalog.' })
150
+ ], FigureSourceCatalog);
151
+ async function sourceAttributes(domain, manager) {
152
+ const ids = await (0, shell_1.getDomainIdsWithAncestors)(domain);
153
+ const rows = await manager.getRepository(shell_1.EnvVar).find({ where: { domain: { id: (0, typeorm_1.In)(ids) }, name: (0, typeorm_1.In)(source_setting_rules_1.SOURCE_PARAMS.map(source_setting_rules_1.sourceAttributeOf)), active: true } });
154
+ return Object.fromEntries((0, shell_1.dedupByClosestDomain)(rows, ids, one => one.name).map(one => [one.name, one.value]));
155
+ }
156
+ /** The figure server this domain installs from; refused while it is not set. */
157
+ async function figureSourceOf(domain, manager) {
158
+ const source = (0, source_setting_rules_1.sourceOf)(await sourceAttributes(domain, manager));
159
+ if (!source)
160
+ throw new shell_1.Refusal('figure-source-not-set', {}, 'No figure server is set. Set it in Settings.');
161
+ return source;
162
+ }
163
+ /**
164
+ * Installing figures straight from a figure server (ADR-0114 amendment 2026-11-14). The setting is domain attributes,
165
+ * opened by the EnvVar privilege as the other connection cards are; the catalog and the install are the library's
166
+ * own query and mutation, as a package file import is. Every call to the figure server is made here, never by the
167
+ * browser, so the token stays on this server.
168
+ */
169
+ let FigureSourceResolver = class FigureSourceResolver {
170
+ async figureLibrarySource(context) {
171
+ const { domain, tx } = context.state;
172
+ return (0, source_setting_rules_1.sourceSettingState)(await sourceAttributes(domain, tx ?? (0, shell_1.getDataSource)().manager), shell_1.secretHint);
173
+ }
174
+ async updateFigureLibrarySource(patch, context) {
175
+ const { domain, tx } = context.state;
176
+ let writes;
177
+ try {
178
+ writes = (0, source_setting_rules_1.sourceSettingWrites)(patch);
179
+ }
180
+ catch (error) {
181
+ if (error instanceof source_setting_rules_1.FigureSourceSettingRefusal)
182
+ throw new shell_1.Refusal(error.code, { field: error.field }, error.message);
183
+ throw error;
184
+ }
185
+ const repository = tx.getRepository(shell_1.EnvVar);
186
+ for (const { name, value } of writes) {
187
+ const own = await repository.findOne({ where: { domain: { id: domain.id }, name } });
188
+ if (value === null) {
189
+ if (own)
190
+ await repository.delete(own.id);
191
+ }
192
+ else if (own)
193
+ await repository.save({ ...own, value, active: true });
194
+ else
195
+ await repository.save({ domain, name, value, active: true, description: 'Figure server to install from (ADR-0114) - set on the Settings screen' });
196
+ }
197
+ return (0, source_setting_rules_1.sourceSettingState)(await sourceAttributes(domain, tx), shell_1.secretHint);
198
+ }
199
+ async checkFigureLibrarySource(context) {
200
+ const { domain, tx } = context.state;
201
+ try {
202
+ const source = await figureSourceOf(domain, tx ?? (0, shell_1.getDataSource)().manager);
203
+ const { total } = await (0, source_install_1.sourceCatalogPage)(source, { pagination: { page: 1, limit: 1 } });
204
+ return { ok: true, total };
205
+ }
206
+ catch (error) {
207
+ if (!(error instanceof shell_1.Refusal))
208
+ throw error;
209
+ const t = context.t;
210
+ const message = t ? t(`error.${error.code}`, { ...error.params, defaultValue: error.message }) : error.message;
211
+ return { ok: false, code: error.code, message };
212
+ }
213
+ }
214
+ async figureLibrarySourceSet(context) {
215
+ const { domain, tx } = context.state;
216
+ return !!(0, source_setting_rules_1.sourceOf)(await sourceAttributes(domain, tx ?? (0, shell_1.getDataSource)().manager));
217
+ }
218
+ async figureSourceCatalog(params, context) {
219
+ const { domain, tx } = context.state;
220
+ const manager = tx ?? (0, shell_1.getDataSource)().manager;
221
+ const page = await (0, source_install_1.sourceCatalogPage)(await figureSourceOf(domain, manager), params);
222
+ return { items: (await (0, source_install_1.withLibraryStatus)(manager, domain, page.items)), total: page.total };
223
+ }
224
+ async installFigures(refs, context) {
225
+ const { domain, user, tx } = context.state;
226
+ return await (0, source_install_1.installFromSource)(tx, domain, user, await figureSourceOf(domain, tx), refs);
227
+ }
228
+ };
229
+ exports.FigureSourceResolver = FigureSourceResolver;
230
+ tslib_1.__decorate([
231
+ (0, type_graphql_1.Directive)('@privilege(category: "env-var", privilege: "query", domainOwnerGranted: true)'),
232
+ (0, type_graphql_1.Query)(returns => FigureSourceSetting, { description: 'The figure server this domain installs from - never the token.' }),
233
+ tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
234
+ tslib_1.__metadata("design:type", Function),
235
+ tslib_1.__metadata("design:paramtypes", [Object]),
236
+ tslib_1.__metadata("design:returntype", Promise)
237
+ ], FigureSourceResolver.prototype, "figureLibrarySource", null);
238
+ tslib_1.__decorate([
239
+ (0, type_graphql_1.Directive)('@transaction'),
240
+ (0, type_graphql_1.Directive)('@privilege(category: "env-var", privilege: "mutation", domainOwnerGranted: true)'),
241
+ (0, type_graphql_1.Mutation)(returns => FigureSourceSetting, { description: 'To change the figure server this domain installs from.' }),
242
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('patch', type => FigureSourceSettingPatch)),
243
+ tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
244
+ tslib_1.__metadata("design:type", Function),
245
+ tslib_1.__metadata("design:paramtypes", [FigureSourceSettingPatch, Object]),
246
+ tslib_1.__metadata("design:returntype", Promise)
247
+ ], FigureSourceResolver.prototype, "updateFigureLibrarySource", null);
248
+ tslib_1.__decorate([
249
+ (0, type_graphql_1.Directive)('@privilege(category: "env-var", privilege: "query", domainOwnerGranted: true)'),
250
+ (0, type_graphql_1.Query)(returns => FigureSourceCheck, { description: 'Asks the figure server for one catalog row with the setting as it is.' }),
251
+ tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
252
+ tslib_1.__metadata("design:type", Function),
253
+ tslib_1.__metadata("design:paramtypes", [Object]),
254
+ tslib_1.__metadata("design:returntype", Promise)
255
+ ], FigureSourceResolver.prototype, "checkFigureLibrarySource", null);
256
+ tslib_1.__decorate([
257
+ (0, type_graphql_1.Directive)('@privilege(category: "figure-library", privilege: "query", domainOwnerGranted: true)'),
258
+ (0, type_graphql_1.Query)(returns => Boolean, { description: 'Whether a figure server to install from is set - the library screen offers the install only then.' }),
259
+ tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
260
+ tslib_1.__metadata("design:type", Function),
261
+ tslib_1.__metadata("design:paramtypes", [Object]),
262
+ tslib_1.__metadata("design:returntype", Promise)
263
+ ], FigureSourceResolver.prototype, "figureLibrarySourceSet", null);
264
+ tslib_1.__decorate([
265
+ (0, type_graphql_1.Directive)('@privilege(category: "figure-library", privilege: "query", domainOwnerGranted: true)'),
266
+ (0, type_graphql_1.Query)(returns => FigureSourceCatalog, { description: 'The figures the figure server offers, each as its latest release, with what this library holds of it.' }),
267
+ tslib_1.__param(0, (0, type_graphql_1.Args)()),
268
+ tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
269
+ tslib_1.__metadata("design:type", Function),
270
+ tslib_1.__metadata("design:paramtypes", [shell_1.ListParam, Object]),
271
+ tslib_1.__metadata("design:returntype", Promise)
272
+ ], FigureSourceResolver.prototype, "figureSourceCatalog", null);
273
+ tslib_1.__decorate([
274
+ (0, type_graphql_1.Directive)('@transaction'),
275
+ (0, type_graphql_1.Directive)('@privilege(category: "figure-library", privilege: "mutation", domainOwnerGranted: true)'),
276
+ (0, type_graphql_1.Mutation)(returns => figure_library_types_1.FigureImportResult, { description: 'Installs releases from the figure server: their package is fetched and imported as a package file is.' }),
277
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('refs', type => [String], { description: 'Release references {namespace}/{type}@{version}.' })),
278
+ tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
279
+ tslib_1.__metadata("design:type", Function),
280
+ tslib_1.__metadata("design:paramtypes", [Array, Object]),
281
+ tslib_1.__metadata("design:returntype", Promise)
282
+ ], FigureSourceResolver.prototype, "installFigures", null);
283
+ exports.FigureSourceResolver = FigureSourceResolver = tslib_1.__decorate([
284
+ (0, type_graphql_1.Resolver)(),
285
+ (0, type_graphql_1.UseMiddleware)(shell_1.SpeakRefusals)
286
+ ], FigureSourceResolver);
287
+ //# sourceMappingURL=figure-source-resolver.js.map
@@ -0,0 +1,27 @@
1
+ import type { FigureSource } from './source-setting-rules';
2
+ /**
3
+ * The calls a board server makes to the figure server it installs from (ADR-0114 decisions 22 · 25 · 26). Only an
4
+ * operator's install reaches here: drawing never does (decision 4).
5
+ *
6
+ * The token goes to the configured origin only: a redirect is not followed (to another origin it would carry the
7
+ * token there), each call has a time limit, and a body is read up to a size limit. The headers are the ones
8
+ * `operato-connector` sends another operato server.
9
+ */
10
+ /** How long one call to the figure server may take. */
11
+ export declare const SOURCE_TIMEOUT_MS = 30000;
12
+ export interface SourceFetch {
13
+ (url: string, init: RequestInit): Promise<Response>;
14
+ }
15
+ /** The domain-scoped address of a REST door on the figure server: {url}/domain/{domain}/{path}. */
16
+ export declare const sourceRestUrl: (source: FigureSource, path: string) => string;
17
+ /** One GraphQL query on the figure server, as the token's domain. */
18
+ export declare function sourceQuery<T>(source: FigureSource, query: string, variables: Record<string, unknown>, doFetch?: SourceFetch): Promise<T>;
19
+ /** A package of these releases from the figure server's `/figure-package` door, as bytes. */
20
+ export declare function sourcePackage(source: FigureSource, refs: readonly string[], max: number, doFetch?: SourceFetch): Promise<Buffer>;
21
+ /** The picture of a figure's latest release, as the figure server sends it; null when it has none. */
22
+ export declare function sourceThumbnail(source: FigureSource, figureId: string, doFetch?: SourceFetch): Promise<{
23
+ bytes: Buffer;
24
+ contentType: string;
25
+ } | null>;
26
+ /** Where releases installed from this source say they came from (the release row's package name). */
27
+ export declare const sourcePackageName: (source: FigureSource) => string;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sourcePackageName = exports.sourceRestUrl = exports.SOURCE_TIMEOUT_MS = void 0;
4
+ exports.sourceQuery = sourceQuery;
5
+ exports.sourcePackage = sourcePackage;
6
+ exports.sourceThumbnail = sourceThumbnail;
7
+ const shell_1 = require("@things-factory/shell");
8
+ /**
9
+ * The calls a board server makes to the figure server it installs from (ADR-0114 decisions 22 · 25 · 26). Only an
10
+ * operator's install reaches here: drawing never does (decision 4).
11
+ *
12
+ * The token goes to the configured origin only: a redirect is not followed (to another origin it would carry the
13
+ * token there), each call has a time limit, and a body is read up to a size limit. The headers are the ones
14
+ * `operato-connector` sends another operato server.
15
+ */
16
+ /** How long one call to the figure server may take. */
17
+ exports.SOURCE_TIMEOUT_MS = 30_000;
18
+ const host = (source) => new URL(source.url).host;
19
+ function headersOf(source, extra = {}) {
20
+ return { authorization: `Bearer ${source.token}`, 'x-things-factory-domain': source.domain, ...extra };
21
+ }
22
+ /** The domain-scoped address of a REST door on the figure server: {url}/domain/{domain}/{path}. */
23
+ const sourceRestUrl = (source, path) => `${source.url}/domain/${encodeURIComponent(source.domain)}/${path}`;
24
+ exports.sourceRestUrl = sourceRestUrl;
25
+ async function call(source, url, init, doFetch) {
26
+ let response;
27
+ try {
28
+ response = await doFetch(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(exports.SOURCE_TIMEOUT_MS) });
29
+ }
30
+ catch {
31
+ throw new shell_1.Refusal('figure-source-unreachable', { host: host(source) }, 'Cannot connect to the figure server {host}.');
32
+ }
33
+ if (response.status === 401)
34
+ throw new shell_1.Refusal('figure-source-unauthorized', { host: host(source) }, 'The figure server {host} did not accept the token.');
35
+ if (response.status === 403)
36
+ throw new shell_1.Refusal('figure-source-forbidden', { host: host(source), domain: source.domain }, 'The token has no right to read released figures of {domain} on {host}.');
37
+ if (response.status >= 300 && response.status < 400)
38
+ throw new shell_1.Refusal('figure-source-unreachable', { host: host(source) }, 'Cannot connect to the figure server {host}.');
39
+ return response;
40
+ }
41
+ /** A body read up to `max` bytes; more is refused rather than kept in memory. */
42
+ async function bytesUpTo(response, max) {
43
+ const declared = Number(response.headers.get('content-length'));
44
+ if (declared > max)
45
+ throw new shell_1.Refusal('figure-package-too-large', { max }, 'a figure package is at most {max} bytes.');
46
+ const chunks = [];
47
+ let size = 0;
48
+ const reader = response.body?.getReader();
49
+ if (!reader)
50
+ return Buffer.alloc(0);
51
+ for (;;) {
52
+ const { done, value } = await reader.read();
53
+ if (done)
54
+ break;
55
+ size += value.length;
56
+ if (size > max) {
57
+ await reader.cancel();
58
+ throw new shell_1.Refusal('figure-package-too-large', { max }, 'a figure package is at most {max} bytes.');
59
+ }
60
+ chunks.push(Buffer.from(value));
61
+ }
62
+ return Buffer.concat(chunks);
63
+ }
64
+ /** A refusal the figure server answered with (400 `{ code, params, message }`), passed on as it said it. */
65
+ async function refusalOf(source, response) {
66
+ try {
67
+ const body = (await response.json());
68
+ if (body?.code)
69
+ return new shell_1.Refusal(body.code, body.params ?? {}, body.message ?? body.code);
70
+ }
71
+ catch { }
72
+ return new shell_1.Refusal('figure-source-failed', { host: host(source), status: response.status }, 'The figure server {host} answered {status}.');
73
+ }
74
+ /** One GraphQL query on the figure server, as the token's domain. */
75
+ async function sourceQuery(source, query, variables, doFetch = fetch) {
76
+ const response = await call(source, `${source.url}/graphql`, { method: 'POST', headers: headersOf(source, { 'content-type': 'application/json' }), body: JSON.stringify({ query, variables }) }, doFetch);
77
+ if (!response.ok)
78
+ throw await refusalOf(source, response);
79
+ const body = (await response.json());
80
+ if (body.errors?.length) {
81
+ const [error] = body.errors;
82
+ const message = error.message ?? '';
83
+ if (/unauthori[sz]ed|permission|privilege/i.test(message) || error.extensions?.code === 'FORBIDDEN')
84
+ throw new shell_1.Refusal('figure-source-forbidden', { host: host(source), domain: source.domain }, 'The token has no right to read released figures of {domain} on {host}.');
85
+ throw new shell_1.Refusal('figure-source-failed-message', { host: host(source), message }, 'The figure server {host} refused: {message}');
86
+ }
87
+ return body.data;
88
+ }
89
+ /** A package of these releases from the figure server's `/figure-package` door, as bytes. */
90
+ async function sourcePackage(source, refs, max, doFetch = fetch) {
91
+ const url = `${(0, exports.sourceRestUrl)(source, 'figure-package')}?refs=${refs.map(encodeURIComponent).join(',')}`;
92
+ const response = await call(source, url, { method: 'GET', headers: headersOf(source) }, doFetch);
93
+ if (!response.ok)
94
+ throw await refusalOf(source, response);
95
+ return await bytesUpTo(response, max);
96
+ }
97
+ /** The picture of a figure's latest release, as the figure server sends it; null when it has none. */
98
+ async function sourceThumbnail(source, figureId, doFetch = fetch) {
99
+ const response = await call(source, (0, exports.sourceRestUrl)(source, `figure-release-thumbnail/${encodeURIComponent(figureId)}`), { method: 'GET', headers: headersOf(source) }, doFetch);
100
+ if (response.status === 404)
101
+ return null;
102
+ if (!response.ok)
103
+ throw await refusalOf(source, response);
104
+ return { bytes: await bytesUpTo(response, 4 * 1024 * 1024), contentType: response.headers.get('content-type') ?? 'application/octet-stream' };
105
+ }
106
+ /** Where releases installed from this source say they came from (the release row's package name). */
107
+ const sourcePackageName = (source) => `${host(source)}/${source.domain}`;
108
+ exports.sourcePackageName = sourcePackageName;
109
+ //# sourceMappingURL=source-client.js.map
@@ -0,0 +1,57 @@
1
+ import { EntityManager } from 'typeorm';
2
+ import { type ImportResult } from '../library/import';
3
+ import { type SourceFetch } from './source-client';
4
+ import type { FigureSource } from './source-setting-rules';
5
+ /** The most releases the figure server puts in one package (figure-service FIGURE_PACKAGE_MAX). */
6
+ export declare const SOURCE_PACKAGE_MAX = 200;
7
+ /** One figure of the figure server's catalog, as `figureReleaseCatalog` answers (ADR-0114 decision 24). */
8
+ export interface SourceCatalogRow {
9
+ figureId: string;
10
+ fullName: string;
11
+ ref: string;
12
+ namespace: string;
13
+ type: string;
14
+ version: number;
15
+ name?: string | null;
16
+ names?: Record<string, string> | null;
17
+ description?: string | null;
18
+ category?: string | null;
19
+ deprecated: boolean;
20
+ supersededBy?: string | null;
21
+ public: boolean;
22
+ assetFormat?: string | null;
23
+ kernelVersion?: string | null;
24
+ releasedAt?: string | null;
25
+ thumbnailHash?: string | null;
26
+ }
27
+ /** What this library holds of a catalog row (ADR-0114 decision 25). */
28
+ export type SourceStatus = 'not-installed' | 'installed' | 'newer' | 'archived' | 'format-unsupported';
29
+ export interface SourceCatalogItem extends SourceCatalogRow {
30
+ /** The version the type map draws this name with here; null when none. */
31
+ installedVersion: number | null;
32
+ status: SourceStatus;
33
+ }
34
+ export declare function sourceCatalogPage(source: FigureSource, params: {
35
+ filters?: unknown[];
36
+ pagination?: unknown;
37
+ sortings?: unknown[];
38
+ search?: string;
39
+ }, doFetch?: SourceFetch): Promise<{
40
+ items: SourceCatalogRow[];
41
+ total: number;
42
+ }>;
43
+ /**
44
+ * Each row with what this domain's library holds of it: archived when its name is archived here; installed when this
45
+ * very release is here (format-unsupported when this server cannot draw it); newer when an older release of the name
46
+ * is here; not installed otherwise.
47
+ */
48
+ export declare function withLibraryStatus(tx: EntityManager, domain: {
49
+ id: string;
50
+ }, rows: SourceCatalogRow[]): Promise<SourceCatalogItem[]>;
51
+ /**
52
+ * Installs releases from the figure server (ADR-0114 decision 22): their package is fetched, SOURCE_PACKAGE_MAX at a
53
+ * time, and imported by the same function a package file is. The outcomes are those of every part, in order.
54
+ */
55
+ export declare function installFromSource(tx: EntityManager, domain: {
56
+ id: string;
57
+ }, user: unknown, source: FigureSource, refs: readonly string[], doFetch?: SourceFetch): Promise<ImportResult>;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SOURCE_PACKAGE_MAX = void 0;
4
+ exports.sourceCatalogPage = sourceCatalogPage;
5
+ exports.withLibraryStatus = withLibraryStatus;
6
+ exports.installFromSource = installFromSource;
7
+ const typeorm_1 = require("typeorm");
8
+ const figure_model_1 = require("@hatiolab/figure-model");
9
+ const figure_library_release_1 = require("../figure-library-release/figure-library-release");
10
+ const figure_type_map_entry_1 = require("../figure-type-map/figure-type-map-entry");
11
+ const import_1 = require("../library/import");
12
+ const source_client_1 = require("./source-client");
13
+ /** The most releases the figure server puts in one package (figure-service FIGURE_PACKAGE_MAX). */
14
+ exports.SOURCE_PACKAGE_MAX = 200;
15
+ const CATALOG = `query ($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!], $search: String) {
16
+ figureReleaseCatalog(filters: $filters, pagination: $pagination, sortings: $sortings, search: $search) {
17
+ items { figureId fullName ref namespace type version name names description category deprecated supersededBy public assetFormat kernelVersion releasedAt thumbnailHash }
18
+ total
19
+ }
20
+ }`;
21
+ async function sourceCatalogPage(source, params, doFetch) {
22
+ const data = await (0, source_client_1.sourceQuery)(source, CATALOG, { filters: params.filters ?? [], pagination: params.pagination ?? null, sortings: params.sortings ?? [], search: params.search || null }, doFetch);
23
+ return data.figureReleaseCatalog;
24
+ }
25
+ /**
26
+ * Each row with what this domain's library holds of it: archived when its name is archived here; installed when this
27
+ * very release is here (format-unsupported when this server cannot draw it); newer when an older release of the name
28
+ * is here; not installed otherwise.
29
+ */
30
+ async function withLibraryStatus(tx, domain, rows) {
31
+ if (!rows.length)
32
+ return [];
33
+ const names = rows.map(row => row.fullName);
34
+ const lines = await tx.getRepository(figure_type_map_entry_1.FigureTypeMapEntry).find({ where: { domain: { id: domain.id }, name: (0, typeorm_1.In)(names) }, relations: { release: true } });
35
+ const lineOf = new Map(lines.map(line => [line.name, line]));
36
+ const parsed = rows.map(row => (0, figure_model_1.parseFigureName)(row.fullName)).filter(Boolean);
37
+ const releases = parsed.length
38
+ ? await tx.getRepository(figure_library_release_1.FigureLibraryRelease).find({
39
+ where: parsed.map(name => ({ domain: { id: domain.id }, namespace: name.namespace, type: name.type })),
40
+ select: { id: true, ref: true, namespace: true, type: true, version: true, formatSupported: true }
41
+ })
42
+ : [];
43
+ const releasesOf = new Map();
44
+ for (const release of releases) {
45
+ const name = `${release.namespace}/${release.type}`;
46
+ releasesOf.set(name, [...(releasesOf.get(name) ?? []), release]);
47
+ }
48
+ return rows.map(row => {
49
+ const line = lineOf.get(row.fullName);
50
+ const here = releasesOf.get(row.fullName) ?? [];
51
+ const same = here.find(release => release.ref === row.ref);
52
+ const newest = Math.max(0, ...here.map(release => release.version ?? 0));
53
+ const status = line?.archivedAt
54
+ ? 'archived'
55
+ : same
56
+ ? same.formatSupported
57
+ ? 'installed'
58
+ : 'format-unsupported'
59
+ : here.length
60
+ ? row.version > newest
61
+ ? 'newer'
62
+ : 'installed'
63
+ : 'not-installed';
64
+ return { ...row, installedVersion: line?.release?.version ?? null, status };
65
+ });
66
+ }
67
+ /**
68
+ * Installs releases from the figure server (ADR-0114 decision 22): their package is fetched, SOURCE_PACKAGE_MAX at a
69
+ * time, and imported by the same function a package file is. The outcomes are those of every part, in order.
70
+ */
71
+ async function installFromSource(tx, domain, user, source, refs, doFetch) {
72
+ const unique = [...new Set(refs.map(ref => ref.trim()).filter(Boolean))];
73
+ const result = { problems: [], outcomes: [] };
74
+ for (let at = 0; at < unique.length; at += exports.SOURCE_PACKAGE_MAX) {
75
+ const part = unique.slice(at, at + exports.SOURCE_PACKAGE_MAX);
76
+ const bytes = await (0, source_client_1.sourcePackage)(source, part, import_1.PACKAGE_MAX_BYTES, doFetch);
77
+ const imported = await (0, import_1.importFigurePackage)(tx, domain, user, bytes, (0, source_client_1.sourcePackageName)(source));
78
+ result.problems.push(...imported.problems);
79
+ result.outcomes.push(...imported.outcomes);
80
+ }
81
+ return result;
82
+ }
83
+ //# sourceMappingURL=source-install.js.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The figure server a domain installs from (ADR-0114 decision 21): its address, the domain on it and the token that
3
+ * server issued. They are domain attributes (EnvVar keeps every value encrypted at rest); the token never comes back
4
+ * out. Pure rules here; the resolver reads and writes the attributes.
5
+ */
6
+ export declare const SOURCE_PARAMS: readonly ["url", "domain", "token"];
7
+ export type SourceParam = (typeof SOURCE_PARAMS)[number];
8
+ export declare const sourceAttributeOf: (param: SourceParam) => string;
9
+ export interface FigureSource {
10
+ url: string;
11
+ domain: string;
12
+ token: string;
13
+ }
14
+ export interface FigureSourceState {
15
+ url: string | null;
16
+ domain: string | null;
17
+ tokenSet: boolean;
18
+ /** The token as the framework shows a secret (`secretHint`) - enough to tell which it is, never the token. */
19
+ tokenHint: string | null;
20
+ }
21
+ export interface FigureSourcePatch {
22
+ url?: string | null;
23
+ domain?: string | null;
24
+ token?: string | null;
25
+ }
26
+ export declare class FigureSourceSettingRefusal extends Error {
27
+ code: string;
28
+ field: SourceParam;
29
+ constructor(code: string, field: SourceParam, message: string);
30
+ }
31
+ /** What the Settings screen may see: the address and the domain as they are, whether the token is set. */
32
+ export declare function sourceSettingState(attributes: Record<string, string | undefined>, hint?: (secret: string) => string | undefined): FigureSourceState;
33
+ /** The source to install from, or null while any of the three is missing. */
34
+ export declare function sourceOf(attributes: Record<string, string | undefined>): FigureSource | null;
35
+ /** The attribute writes of a patch: a field left out stays, an empty one is cleared. A refusal names the field. */
36
+ export declare function sourceSettingWrites(patch: FigureSourcePatch): {
37
+ name: string;
38
+ value: string | null;
39
+ }[];