@ghentcdh/annotation-api 0.0.1-alpha.10 → 0.0.1-alpha.14

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.
package/index.js CHANGED
@@ -1,172 +1,265 @@
1
- import { Controller as e, Get as t, Inject as n, Injectable as r, Module as i, NotFoundException as a, Param as o } from "@nestjs/common";
2
- import { z as s } from "zod";
3
- import { contextBuilder as c, w3cAnnotation as l } from "@ghentcdh/w3c-utils";
4
- import { Debugger as u, PlainTextAdapter as ee, W3CAnnotationAdapter as d, WordSnapper as te, createAnnotatedText as ne, createHighlightStyle as f } from "@ghentcdh/annotated-text";
5
- import { ControlBuilder as p, LayoutBuilder as m } from "@ghentcdh/crouton-forms-vue";
6
- import { existsSync as h, readFileSync as g, readdirSync as _ } from "node:fs";
7
- import { join as v } from "node:path";
8
- import { ApiTags as re } from "@nestjs/swagger";
9
- //#region packages/annotation-core/src/lib/types/source.model.ts
10
- var ie = ["text"], y = s.object({
11
- text: s.string(),
12
- textDirection: s.enum(["ltr", "rtl"]).default("ltr"),
13
- processingLanguage: s.string().default("en"),
14
- label: s.string().optional(),
15
- offset: s.number().optional().default(0)
16
- }), ae = s.object({
17
- id: s.string(),
18
- uri: s.string(),
19
- type: s.enum(ie),
20
- content: y
21
- }), oe = (e) => {
22
- let t = e.areas.map((e) => `"${e.join(" ")}"`).join(" "), n = e.areas[0]?.length ?? 1, r = {
23
- gridTemplateAreas: t,
24
- gridTemplateColumns: e.columns ?? Array(n).fill("minmax(0, 1fr)").join(" ")
1
+ import { Body, Controller, Delete, Get, Inject, Injectable, Module, Param, Patch, Post } from "@nestjs/common";
2
+ import { z } from "zod";
3
+ import { ContextBuilder, contextBuilder, w3cAnnotation } from "@ghentcdh/w3c-utils";
4
+ import { JsonOperationsSchema, ResourceJsonShape, ViewConfigSchema, labelFromId, registerResourceExtensions } from "@ghentcdh/crouton-core";
5
+ import { Debugger, PlainTextAdapter, W3CAnnotationAdapter, WordSnapper, createAnnotatedText, createHighlightStyle } from "@ghentcdh/annotated-text";
6
+ import { CroutonApiModule, ResourceConfigRegistry } from "@ghentcdh/crouton-api";
7
+ import { ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from "@nestjs/swagger";
8
+ //#region src/lib/annotation/annotation.repository.ts
9
+ var AnnotationCrudRepository = class {};
10
+ //#endregion
11
+ //#region ../annotation-core/src/lib/types/key-label.type.ts
12
+ var KeyLabelSchema = z.object();
13
+ //#endregion
14
+ //#region ../annotation-core/src/lib/types/source.model.ts
15
+ var SourceTypesList = ["text"];
16
+ var SourceTextSchema = z.object({
17
+ text: z.string(),
18
+ textDirection: z.enum(["ltr", "rtl"]).default("ltr"),
19
+ processingLanguage: z.string().default("en"),
20
+ label: z.string().optional(),
21
+ offset: z.number().optional().default(0)
22
+ });
23
+ var SourceModelSchema = z.object({
24
+ id: z.string(),
25
+ uri: z.string(),
26
+ type: z.enum(SourceTypesList),
27
+ content: SourceTextSchema
28
+ });
29
+ //#endregion
30
+ //#region ../annotation-core/src/lib/types/grid-layout.types.ts
31
+ /** Computed CSS styles for the grid container */
32
+ var buildGridStyle = (layout) => {
33
+ const templateAreas = layout.areas.map((row) => `"${row.join(" ")}"`).join(" ");
34
+ const colCount = layout.areas[0]?.length ?? 1;
35
+ const style = {
36
+ gridTemplateAreas: templateAreas,
37
+ gridTemplateColumns: layout.columns ?? Array(colCount).fill("minmax(0, 1fr)").join(" ")
25
38
  };
26
- return e.rows && (r.gridTemplateRows = e.rows), r;
27
- }, se = (e, t) => e.panes.find((e) => e.sourceId === t)?.area, b = "AnnotationMetadata", x = s.custom(), ce = s.object({
28
- id: s.string(),
29
- name: s.string(),
30
- columns: s.array(x),
31
- json_schema: s.any().optional(),
32
- json_ld: s.any().optional(),
33
- ui_schema: s.any().optional(),
34
- metadata_schema: s.any().optional(),
35
- color: s.string(),
36
- type: s.string().optional(),
37
- icon: s.string().optional(),
38
- isRoot: s.boolean().default(!0),
39
- allowedChildren: s.array(s.string()).default([]),
40
- allowedLinks: s.array(s.string()).default([]),
41
- context: s.custom(),
42
- target: s.enum([
43
- "gutter",
44
- "underline",
45
- "highlight"
46
- ]).default("highlight")
47
- }), S = {
48
- baseUrl: "http://localhost:3000/",
39
+ if (layout.rows) style["gridTemplateRows"] = layout.rows;
40
+ return style;
41
+ };
42
+ /** Returns the grid-area CSS value for a given source id, or undefined if not configured */
43
+ var getPaneArea = (layout, sourceId) => {
44
+ return layout.panes.find((p) => p.sourceId === sourceId)?.area;
45
+ };
46
+ //#endregion
47
+ //#region ../annotation-core/src/lib/utils/annotation.context-builder.ts
48
+ var defaultConfig = {
49
+ baseUrl: "http://localhost:3333/",
50
+ crudController: "annotation/annotation",
49
51
  app: "ghentcdh",
50
52
  prefix: "ghentcdh",
51
- isDev: !1,
53
+ isDev: false,
52
54
  cacheTTLms: 1200 * 1e3
53
- }, C = (e = {}) => {
54
- let t = e.baseUrl ?? S.baseUrl, n = t.endsWith("/") ? t : `${t}/`, r = e.isDev ?? !1, i = r ? 0 : 1200 * 1e3;
55
+ };
56
+ var resolveConfig = (config = {}) => {
57
+ const baseUrl = config.baseUrl ?? defaultConfig.baseUrl;
58
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
59
+ const isDev = config.isDev ?? false;
60
+ const cacheTTLms = isDev ? 0 : 1200 * 1e3;
55
61
  return {
56
- baseUrl: n,
57
- contextUrl: `${n}ns/`,
58
- app: e.app ?? S.app,
59
- prefix: e.prefix ?? S.prefix,
60
- isDev: r,
61
- cacheTTLms: i
62
+ baseUrl: normalizedBaseUrl,
63
+ contextUrl: `${normalizedBaseUrl}ns/`,
64
+ app: config.app ?? defaultConfig.app,
65
+ prefix: config.prefix ?? defaultConfig.prefix,
66
+ crudController: config.crudController ?? defaultConfig.crudController,
67
+ isDev,
68
+ cacheTTLms
62
69
  };
63
- }, w = (e, t) => {
64
- let { prefix: n, baseUrl: r, contextUrl: i } = C(t), a = b;
65
- return c(n, r).setType(n, a).addPrefix(e, `${n}:${e}`).setContextUri(`${i}${e}.jsonld`);
66
- }, le = "annotation.style", ue = s.object({
67
- id: s.string(),
68
- name: s.string(),
69
- target: s.enum([
70
+ };
71
+ var baseContextBuilder = (id, config) => {
72
+ const { prefix, baseUrl, contextUrl } = resolveConfig(config);
73
+ const metaData = AnnotationMetadataType;
74
+ return contextBuilder(prefix, baseUrl).setType(prefix, metaData).addPrefix(id, `${prefix}:${id}`).setContextUri(`${contextUrl}${id}.jsonld`);
75
+ };
76
+ //#endregion
77
+ //#region ../annotation-core/src/lib/types/annotation.contex.ts
78
+ var AnnotationMetadataType = "AnnotationMetadata";
79
+ var createAnnotationContext = (annotationDefConfig, resource) => {
80
+ const formView = resource.views?.["form"];
81
+ const builder = baseContextBuilder(resource.id, annotationDefConfig);
82
+ if (formView) builder.parseJsonSchema(formView.json_schema);
83
+ return {
84
+ id: resource.id,
85
+ styling: {
86
+ name: resource.name,
87
+ id: resource.id,
88
+ target: resource.annotation.target,
89
+ color: resource.annotation.color
90
+ },
91
+ hasContext: !!formView,
92
+ prefix: buildPrefix(annotationDefConfig, resource),
93
+ uri: builder.uri,
94
+ jsonLd: builder.toJsonLdContext(),
95
+ safeParse: builder.safeParse.bind(builder),
96
+ toAnnotationBody: builder.toAnnotationBody.bind(builder)
97
+ };
98
+ };
99
+ var buildPrefix = (annotationDefConfig, resource) => {
100
+ return `${annotationDefConfig.prefix}:${resource.annotation.type}/`;
101
+ };
102
+ //#endregion
103
+ //#region ../annotation-core/src/lib/types/version.ts
104
+ /**
105
+ * resource.json schema versioning.
106
+ *
107
+ * `schemaVersion` is a monotonic integer stamped on every `resource.json`. It is
108
+ * **decoupled from the crouton package semver** on purpose — bump it only when the
109
+ * resource.json *shape* changes in a way that needs a migration, and ship a matching
110
+ * step in `./migrations`. This keeps the migration chain one-step-per-bump with no
111
+ * version-range math.
112
+ *
113
+ * Files written before versioning existed carry no field and are treated as the
114
+ * baseline. Because `CURRENT_RESOURCE_VERSION` starts equal to the baseline, shipping
115
+ * the versioning machinery is a pure no-op for every existing file until the first
116
+ * real shape change lands (`CURRENT_RESOURCE_VERSION = 2` + a `1 → 2` migration).
117
+ */
118
+ /** Version assumed for a `resource.json` that has no `schemaVersion` field. */
119
+ var BASELINE_RESOURCE_VERSION = 1;
120
+ /**
121
+ * The version the running crouton understands. Bump by 1 whenever resource.json's
122
+ * shape changes, and add a migration step (`from: N, to: N + 1`) in `./migrations`.
123
+ */
124
+ var CURRENT_RESOURCE_VERSION = 1;
125
+ //#endregion
126
+ //#region ../annotation-core/src/lib/types/annotation-json-config.types.ts
127
+ var AnnotationTargetEnum = z.enum([
128
+ "gutter",
129
+ "underline",
130
+ "highlight"
131
+ ]);
132
+ var AnnotationConfigSchema = z.object({
133
+ color: z.string().optional(),
134
+ type: z.string().optional(),
135
+ icon: z.string().optional(),
136
+ isRoot: z.boolean().optional().default(true),
137
+ allowedChildren: z.array(z.string()).optional().default([]),
138
+ allowedLinks: z.array(z.string()).optional().default([]),
139
+ target: AnnotationTargetEnum.optional().default("highlight")
140
+ });
141
+ var AnnotationJsonResourceShape = ResourceJsonShape.extend({
142
+ route: z.string().optional(),
143
+ tag: z.string().optional(),
144
+ operations: JsonOperationsSchema.optional().default(JsonOperationsSchema.parse({})),
145
+ id: z.string(),
146
+ annotation: AnnotationConfigSchema.optional().default(AnnotationConfigSchema.parse({}))
147
+ }).passthrough();
148
+ var AnnotationJsonResourceSchema = AnnotationJsonResourceShape.transform((obj) => {
149
+ const title = labelFromId(obj.name);
150
+ return {
151
+ schemaVersion: obj.schemaVersion ?? 1,
152
+ title,
153
+ ...obj
154
+ };
155
+ });
156
+ //#endregion
157
+ //#region ../annotation-core/src/lib/types/annotation-definition.type.ts
158
+ var annotationColumnDefinition = z.custom();
159
+ var AnnotationResourceSchema = AnnotationJsonResourceShape.pick({
160
+ id: true,
161
+ name: true,
162
+ title: true,
163
+ operations: true,
164
+ annotation: true
165
+ }).extend({
166
+ annotation: AnnotationConfigSchema,
167
+ context: z.instanceof(ContextBuilder).optional().nullish(),
168
+ schemas: z.record(z.string(), ViewConfigSchema.partial()).optional().nullish()
169
+ });
170
+ //#endregion
171
+ //#region ../annotation-core/src/lib/annotation.style.ts
172
+ var CONTEXT = "annotation.style";
173
+ var AnnotationStyleSchema = z.object({
174
+ id: z.string(),
175
+ name: z.string(),
176
+ target: z.enum([
70
177
  "gutter",
71
178
  "underline",
72
179
  "highlight"
73
180
  ]).optional().default("underline"),
74
- color: s.string().optional()
75
- }), T = "AnnotationStyle", E = (e) => {
76
- let { prefix: t, baseUrl: n, contextUrl: r } = C(e);
77
- return c(t, n).setType(t, T).setContextUri(`${r}${T}.jsonld`).parseZodSchema(ue);
78
- }, de = (e, t) => {
79
- let n = E(e).toAnnotationBodyUnsafe(t);
80
- return n.success || (u.debug(le, "AnnotationStyleContextBuilder safe parse failed"), u.warn(n.error)), n;
81
- }, D = (e) => {
82
- let t = p.properties(e.id);
83
- if (t.customLabel(e.label), !e.fieldInput) return t;
84
- let { type: n, options: r = {} } = e.fieldInput;
85
- return n === "autocomplete" ? t.autocomplete({
86
- ...r.uri && { uri: r.uri },
87
- ...r.resource && { resource: r.resource },
88
- ...r.valueKey && { valueKey: r.valueKey },
89
- ...r.labelKey && { labelKey: r.labelKey },
90
- ...r.enableCreate !== void 0 && { enableCreate: r.enableCreate },
91
- ...r.colspan && { colspan: r.colspan }
92
- }) : n === "select" ? t.select({
93
- ...r.values && { values: r.values },
94
- ...r.clearable !== void 0 && { clearable: r.clearable },
95
- ...r.storeValue !== void 0 && { storeValue: r.storeValue },
96
- ...r.emitObject !== void 0 && { emitObject: r.emitObject },
97
- ...r.colspan && { colspan: r.colspan }
98
- }) : t.control(n, { ...r.colspan && { colspan: r.colspan } });
99
- }, O = (e) => {
100
- let t = m.grid();
101
- return e.filter((e) => !e.hiddenInForm).forEach((e) => t.addControl(D(e))), t.build();
102
- }, k = (e) => {
103
- let t = m.grid();
104
- return e.filter((e) => !e.hiddenInMetadata).forEach((e) => t.addControl(D(e).readonly())), t.build();
105
- }, A = (e) => {
106
- if (e.type === "object" && e.properties) {
107
- let t = {};
108
- for (let [n, r] of Object.entries(e.properties)) t[n] = A(r);
109
- return s.object(t);
110
- }
111
- return s.string();
112
- }, j = (e, t, n) => {
113
- let r = w(e, n), i = t.columns ?? [];
114
- if (!i.length) return r;
115
- let a = {};
116
- for (let e of i) {
117
- let t = A(e.type ?? { type: "string" });
118
- a[e.id] = e.required === !1 ? t.optional() : t;
119
- }
120
- return Object.keys(a).length ? r.parseZodSchema(s.object(a)) : r;
121
- }, M = (e, t, n = j) => {
122
- let r = n(e.id, e, t), i = e.columns ?? [], a = i.length > 0, o = e.ui_schema ?? (a ? O(i) : void 0), s = e.metadata_schema ?? (a ? k(i) : void 0), c = {
123
- id: e.id,
124
- name: e.name,
125
- color: e.color,
126
- isRoot: e.isRoot ?? !0,
127
- columns: i,
128
- context: r,
129
- json_ld: r.toJsonLdContext(),
130
- json_schema: o ? r.toJsonSchema() : null,
131
- allowedChildren: e.allowedChildren ?? [],
132
- allowedLinks: e.allowedLinks ?? [],
133
- target: e.target ?? "highlight"
134
- };
135
- return o && (c.ui_schema = o), s && (c.metadata_schema = s), e.type && (c.type = e.type), e.icon && (c.icon = e.icon), c;
136
- }, fe = (e, t, n) => e.map((e) => M(e, t, n)), pe = (e, t, n) => n.map((r) => {
137
- let i = t.get(r.id), a = i.getSpecificResourceTargets(e);
138
- if (!a || a.length === 0) return null;
139
- let o = i.getSpecificResourceTargets().map((e) => e.source).filter((t) => t !== e).map((e) => n.find((t) => t.id === e)).filter(Boolean);
140
- return {
141
- purpose: N(i),
142
- annotation: r,
143
- relations: o
181
+ color: z.string().optional()
182
+ });
183
+ var AnnotationStyleType = "AnnotationStyle";
184
+ var AnnotationStyleContextBuilder = (annotationConfig) => {
185
+ const { prefix, baseUrl, contextUrl } = resolveConfig(annotationConfig);
186
+ return contextBuilder(prefix, baseUrl).setType(prefix, AnnotationStyleType).setContextUri(`${contextUrl}${AnnotationStyleType}.jsonld`).parseZodSchema(AnnotationStyleSchema);
187
+ };
188
+ var createAnnotationStyleBodyUnsafe = (annotationConfig, style) => {
189
+ const resource = {
190
+ ...style,
191
+ ...style.annotation
144
192
  };
145
- }).filter(Boolean), N = (e) => P(e)?.id ?? "text", P = (e) => e.getBodiesByPurpose("styling").find((e) => e.type === "AnnotationStyle"), me = (e, t, n) => {
146
- let r = t.getSpecificResourceTargets()[0]?.source;
147
- if (!r) return null;
148
- let i = t.getTextPositionSelector(r)[0];
149
- if (!i) return null;
150
- let a = P(t)?.id ?? "text";
193
+ const parsed = AnnotationStyleContextBuilder(annotationConfig).toAnnotationBodyUnsafe(resource);
194
+ if (!parsed.success) {
195
+ Debugger.debug(CONTEXT, "AnnotationStyleContextBuilder safe parse failed");
196
+ Debugger.warn(parsed.error);
197
+ }
198
+ return parsed;
199
+ };
200
+ //#endregion
201
+ //#region ../annotation-core/src/lib/utils/annotation-utils.ts
202
+ var mapRelationsToLinks = (sourceUri, builders, annotations) => {
203
+ return annotations.map((link) => {
204
+ const builder = builders.get(link.id);
205
+ const specifyResource = builder.getSpecificResourceTargets(sourceUri);
206
+ if (!specifyResource || specifyResource.length === 0) return null;
207
+ const relations = builder.getSpecificResourceTargets().map((s) => s.source).filter((s) => s !== sourceUri).map((uri) => {
208
+ return annotations.find((a) => a.id === uri);
209
+ }).filter(Boolean);
210
+ return {
211
+ purpose: getAnnotationType(builder),
212
+ annotation: link,
213
+ relations
214
+ };
215
+ }).filter(Boolean);
216
+ };
217
+ var getAnnotationType = (builder) => {
218
+ return getAnnotationStyle(builder)?.id ?? "text";
219
+ };
220
+ var getAnnotationStyle = (builder) => {
221
+ return builder.getBodiesByPurpose("styling").find((b) => b.type === "AnnotationStyle");
222
+ };
223
+ var getAnnotationPosition = (id, builder, allowedChildrenPerType) => {
224
+ const sourceUri = builder.getSpecificResourceTargets()[0]?.source;
225
+ if (!sourceUri) return null;
226
+ const textPositionSelector = builder.getTextPositionSelector(sourceUri)[0];
227
+ if (!textPositionSelector) return null;
228
+ const type = getAnnotationStyle(builder)?.id ?? "text";
151
229
  return {
152
- id: e,
153
- start: i.start,
154
- end: i.end,
155
- allowedChildren: n[a] ?? [],
156
- sourceUri: r ?? "",
157
- type: a,
158
- minX: i.start,
230
+ id,
231
+ start: textPositionSelector.start,
232
+ end: textPositionSelector.end,
233
+ allowedChildren: allowedChildrenPerType[type] ?? [],
234
+ sourceUri: sourceUri ?? "",
235
+ type,
236
+ minX: textPositionSelector.start,
159
237
  minY: 0,
160
- maxX: i.end,
238
+ maxX: textPositionSelector.end,
161
239
  maxY: 0
162
240
  };
163
- }, F = "ROOT", I = () => `mela:new-annotation:${Date.now()}`, L = (e, t) => (e.getSpecificResourceTargets(t.source).length || e.addTarget({
164
- type: "SpecificResource",
165
- source: t.source
166
- }), e.updateTextPositionSelector({
167
- start: t.start,
168
- end: t.end
169
- }, t.source), e), R = class {
241
+ };
242
+ var rootId = "ROOT";
243
+ var createId = () => {
244
+ return `mela:new-annotation:${Date.now()}`;
245
+ };
246
+ var updateSelector = (builder, selector) => {
247
+ if (!builder.getSpecificResourceTargets(selector.source).length) builder.addTarget({
248
+ type: "SpecificResource",
249
+ source: selector.source
250
+ });
251
+ builder.updateTextPositionSelector({
252
+ start: selector.start,
253
+ end: selector.end
254
+ }, selector.source);
255
+ builder.updateTextQuoteSelector({
256
+ prefix: selector.prefix,
257
+ suffix: selector.suffix,
258
+ exact: selector.exact
259
+ }, selector.source);
260
+ return builder;
261
+ };
262
+ var AnnotationUtilsImpl = class {
170
263
  annotationConfig;
171
264
  builderMap = /* @__PURE__ */ new Map();
172
265
  childParentMap = /* @__PURE__ */ new Map();
@@ -174,369 +267,547 @@ var ie = ["text"], y = s.object({
174
267
  linkedAnnotations = /* @__PURE__ */ new Map();
175
268
  annotations = [];
176
269
  allowedChildrenPerType = {};
177
- constructor(e) {
178
- this.annotationConfig = e;
270
+ constructor(annotationConfig) {
271
+ this.annotationConfig = annotationConfig;
179
272
  }
180
- getBuilder(e) {
181
- let t = this.builderMap.get(e.id);
182
- if (!t) throw Error(`Annotation builder not found: ${e.id}`);
183
- return t;
273
+ getBuilder(annotation) {
274
+ const builder = this.builderMap.get(annotation.id);
275
+ if (!builder) throw new Error(`Annotation builder not found: ${annotation.id}`);
276
+ return builder;
184
277
  }
185
- setAnnotations(e, t) {
186
- this.allowedChildrenPerType = t, this.annotations = e, this.parentChildMap.clear(), this.childParentMap.clear(), this.builderMap.clear();
187
- let n = [], r = /* @__PURE__ */ new Map();
188
- return e.forEach((e) => {
189
- let t = l(e);
190
- this.builderMap.set(e.id, t);
191
- let i = me(e.id, t, this.allowedChildrenPerType);
192
- r.set(e.id, e), i && n.push(i);
193
- }), n.forEach((e) => {
194
- let t = n.filter((t) => t.id !== e.id && t.sourceUri === e.sourceUri && t.start <= e.start && t.end >= e.end && t.allowedChildren.some((t) => t.key === e.type)).sort((e, t) => e.end - e.start - (t.end - t.start))[0], i = t?.id ?? F, a = this.parentChildMap.get(i) ?? [];
195
- a.push(r.get(e.id)), this.parentChildMap.set(t?.id ?? F, a), this.childParentMap.set(e.id, r.get(i) ?? null);
196
- }), e.forEach((t) => {
197
- this.linkedAnnotations.set(t.id, pe(t.id, this.builderMap, e));
198
- }), this;
278
+ setAnnotations(annotations, allowedChildrenPerType) {
279
+ this.allowedChildrenPerType = allowedChildrenPerType;
280
+ this.annotations = annotations;
281
+ this.parentChildMap.clear();
282
+ this.childParentMap.clear();
283
+ this.builderMap.clear();
284
+ const annotationsWithPositons = [];
285
+ const annotationIdMap = /* @__PURE__ */ new Map();
286
+ annotations.forEach((annotation) => {
287
+ const builder = w3cAnnotation(annotation);
288
+ this.builderMap.set(annotation.id, builder);
289
+ const position = getAnnotationPosition(annotation.id, builder, this.allowedChildrenPerType);
290
+ annotationIdMap.set(annotation.id, annotation);
291
+ if (position) annotationsWithPositons.push(position);
292
+ });
293
+ annotationsWithPositons.forEach((annotation) => {
294
+ const parentAnnotation = annotationsWithPositons.filter((a) => a.id !== annotation.id && a.sourceUri === annotation.sourceUri && a.start <= annotation.start && a.end >= annotation.end && a.allowedChildren.some((c) => c.key === annotation.type)).sort((a, b) => a.end - a.start - (b.end - b.start))[0];
295
+ const parentId = parentAnnotation?.id ?? rootId;
296
+ const children = this.parentChildMap.get(parentId) ?? [];
297
+ children.push(annotationIdMap.get(annotation.id));
298
+ this.parentChildMap.set(parentAnnotation?.id ?? rootId, children);
299
+ this.childParentMap.set(annotation.id, annotationIdMap.get(parentId) ?? null);
300
+ });
301
+ annotations.forEach((annotation) => {
302
+ this.linkedAnnotations.set(annotation.id, mapRelationsToLinks(annotation.id, this.builderMap, annotations));
303
+ });
304
+ return this;
199
305
  }
200
- getLinks(e) {
201
- return this.linkedAnnotations.get(e.id) ?? [];
306
+ getLinks(annotation) {
307
+ return this.linkedAnnotations.get(annotation.id) ?? [];
202
308
  }
203
- getTextPositionSelector(e, t) {
204
- return this.getBuilder(e).getTextPositionSelector(t)[0];
309
+ getTextPositionSelector(annotation, sourceUri) {
310
+ return this.getBuilder(annotation).getTextPositionSelector(sourceUri)[0];
205
311
  }
206
- isAnnotationUri = (e) => e.startsWith("mela:annotation/");
207
- getParentSelector = (e) => e.getSpecificResourceTargets().find((e) => this.isAnnotationUri(e.source)) ?? null;
208
- getParent(e) {
209
- let t = this.getBuilder(e), n = this.getParentSelector(t);
210
- return n ? this.annotations.find((e) => e.id === n.source) ?? null : null;
312
+ isAnnotationUri = (uri) => {
313
+ return uri.startsWith("mela:annotation/");
314
+ };
315
+ getParentSelector = (builder) => {
316
+ return builder.getSpecificResourceTargets().find((t) => this.isAnnotationUri(t.source)) ?? null;
317
+ };
318
+ getParent(annotation) {
319
+ const builder = this.getBuilder(annotation);
320
+ const parentUri = this.getParentSelector(builder);
321
+ if (!parentUri) return null;
322
+ return this.annotations.find((a) => a.id === parentUri.source) ?? null;
211
323
  }
212
- createAnnotation(e, t, n, r) {
213
- let i = E(this.annotationConfig).toAnnotationBody(t), a = l(e ?? void 0).setMotivation("tagging").addBody(i);
214
- return e?.id || a.setId(I()), n && Object.keys(n).length > 0 && (n.type = n.type ?? "AnnotationMetadata", n.purpose = n.purpose ?? N(a), a.updateBodyByType(n.type, n)), r && L(a, r), a.build();
324
+ createAnnotation(fromAnnotation, type, data, selectors) {
325
+ const styleBody = AnnotationStyleContextBuilder(this.annotationConfig).toAnnotationBody(type);
326
+ const builder = w3cAnnotation(fromAnnotation ?? void 0).setMotivation("tagging").addBody(styleBody);
327
+ if (!fromAnnotation?.id) builder.setId(createId());
328
+ if (data && Object.keys(data).length > 0) {
329
+ data.type = data.type ?? "AnnotationMetadata";
330
+ data.purpose = data.purpose ?? getAnnotationType(builder);
331
+ builder.updateBodyByType(data.type, data);
332
+ }
333
+ for (const selector of selectors) updateSelector(builder, selector);
334
+ return builder.build();
215
335
  }
216
- createLinkAnnotation = (e, t, n, r) => {
217
- let i = E(this.annotationConfig).toAnnotationBody(n), a = l().setMotivation("tagging").setId(I()).addBody(i);
218
- return r && Object.keys(r).length > 0 && (r.type = r.type ?? "AnnotationMetadata", r.purpose = r.purpose ?? N(a), a.updateBodyByType(r.type, r)), a.addTarget({ source: e.id }).addTarget({ source: t.id }), a.build();
336
+ createLinkAnnotation = (sourceAnnotation, targetAnnotation, type, data) => {
337
+ const styleBody = AnnotationStyleContextBuilder(this.annotationConfig).toAnnotationBody(type);
338
+ const builder = w3cAnnotation().setMotivation("tagging").setId(createId()).addBody(styleBody);
339
+ if (data && Object.keys(data).length > 0) {
340
+ data.type = data.type ?? "AnnotationMetadata";
341
+ data.purpose = data.purpose ?? getAnnotationType(builder);
342
+ builder.updateBodyByType(data.type, data);
343
+ }
344
+ builder.addTarget({ source: sourceAnnotation.id }).addTarget({ source: targetAnnotation.id });
345
+ return builder.build();
219
346
  };
220
347
  cancel() {
221
348
  this.setAnnotations(this.annotations, this.allowedChildrenPerType);
222
349
  }
223
- getSourceUri = (e) => {
224
- let t = this.getBuilder(e), n = t.getSourceUri();
225
- return n ? {
226
- textPositionSelector: t.getTextPositionSelector(n)[0],
227
- sourceUri: n
228
- } : (console.warn("no source uri"), null);
350
+ getSourceUri = (annotation) => {
351
+ const builder = this.getBuilder(annotation);
352
+ const sourceUri = builder.getSourceUri();
353
+ if (!sourceUri) {
354
+ console.warn("no source uri");
355
+ return null;
356
+ }
357
+ return {
358
+ textPositionSelector: builder.getTextPositionSelector(sourceUri)[0],
359
+ sourceUri
360
+ };
361
+ };
362
+ getMetadata = (annotation) => {
363
+ return this.getBuilder(annotation).getBodiesByType("AnnotationMetadata")?.[0] ?? null;
364
+ };
365
+ getAnnotationStyle = (annotation) => {
366
+ return getAnnotationStyle(this.getBuilder(annotation));
229
367
  };
230
- getMetadata = (e, t) => this.getBuilder(e).getBodiesByType("AnnotationMetadata")?.[0] ?? null;
231
- getAnnotationStyle = (e) => P(this.getBuilder(e));
232
- getAnnotationType = (e) => N(this.getBuilder(e));
233
- createAnnotationFromSelector(e, t, n) {
234
- let r = l(t ?? void 0).setMotivation("tagging").setId(I()), i = E(this.annotationConfig).toAnnotationBody(e);
235
- return r.addBody(i), n && L(r, n), r.build();
368
+ getAnnotationType = (annotation) => {
369
+ return getAnnotationType(this.getBuilder(annotation));
370
+ };
371
+ createAnnotationFromSelector(type, annotation, selector) {
372
+ const builder = w3cAnnotation(annotation ?? void 0).setMotivation("tagging").setId(createId());
373
+ const styleBody = AnnotationStyleContextBuilder(this.annotationConfig).toAnnotationBody(type);
374
+ builder.addBody(styleBody);
375
+ if (selector) updateSelector(builder, selector);
376
+ return builder.build();
377
+ }
378
+ };
379
+ var annotationUtils = (annotationConfig) => {
380
+ return new AnnotationUtilsImpl(annotationConfig);
381
+ };
382
+ //#endregion
383
+ //#region ../annotation-core/src/lib/utils/annotation-render.style.ts
384
+ var defaultRender = (utils) => (annotation) => {
385
+ return (utils?.getAnnotationStyle(annotation))?.target ?? "default";
386
+ };
387
+ var styleFn = (listStyles, utils) => (annotation) => {
388
+ const style = utils?.getAnnotationStyle(annotation);
389
+ if (!style) return "default";
390
+ const styleId = style?.id ?? "default";
391
+ if (!listStyles.includes(styleId)) {
392
+ Debugger.debug("styleFn", `No style found for ${styleId}`);
393
+ if (style.color) return { default: createHighlightStyle(style.color) };
394
+ return "default";
236
395
  }
237
- }, he = (e) => new R(e), z = (e) => (t) => e?.getAnnotationStyle(t)?.target ?? "default", B = (e, t) => (n) => {
238
- let r = t?.getAnnotationStyle(n);
239
- if (!r) return "default";
240
- let i = r?.id ?? "default";
241
- return e.includes(i) ? i : (u.debug("styleFn", `No style found for ${i}`), r.color ? { default: f(r.color) } : "default");
242
- }, V = (e, t) => e ? e.reduce((e, n) => (e[n.id] = t ? n[t] : n, e), {}) : {}, ge = (e, t, n, r) => {
243
- let i = e ?? [], a = V(i), o = i.filter((e) => e.isRoot).map((e) => ({
244
- key: e.id,
245
- label: e.label
246
- })), s = V(i, "style");
247
- s.default ||= {
396
+ return styleId;
397
+ };
398
+ //#endregion
399
+ //#region ../annotation-core/src/lib/utils/annotation-configuration.factory.ts
400
+ var groupById = (defs, valueKey) => {
401
+ if (!defs) return {};
402
+ return defs.reduce((acc, def) => {
403
+ acc[def.id] = valueKey ? def[valueKey] : def;
404
+ return acc;
405
+ }, {});
406
+ };
407
+ var createAnnotationConfiguration = (annotationDefinitions, utils, textAdapter, annotationAdapter) => {
408
+ const definitions = annotationDefinitions ?? [];
409
+ const definitionsMap = groupById(definitions);
410
+ const rootTypes = definitions.filter((d) => d.annotation.isRoot).map((d) => ({
411
+ key: d.id,
412
+ label: d.label
413
+ }));
414
+ const styles = groupById(definitions, "style");
415
+ if (!styles["default"]) styles["default"] = {
248
416
  label: "Annotation",
249
- isRoot: !0,
250
- style: { default: f("#dd7777") },
417
+ isRoot: true,
418
+ style: { default: createHighlightStyle("#dd7777") },
251
419
  allowedChildren: [],
252
420
  allowedLinks: [],
253
- schema: {
254
- uiSchema: {
255
- type: "VerticalLayout",
256
- elements: []
257
- },
258
- jsonSchema: {
259
- type: "object",
260
- properties: {}
261
- },
262
- metaDataSchema: {
263
- type: "VerticalLayout",
264
- elements: []
265
- },
266
- validation: () => void 0
421
+ views: {}
422
+ };
423
+ const listStyles = Object.keys(styles);
424
+ const allowedChildrenPerType = groupById(definitions, "allowedChildren");
425
+ const defaultAnnotationAdapter = (source) => W3CAnnotationAdapter(source ? { sourceUri: source.uri } : {});
426
+ const renderParams = () => ({ renderFn: defaultRender(utils) });
427
+ const styleParams = () => ({ styleFn: styleFn(listStyles, utils) });
428
+ const _createAnnotatedText = (id, sourceModel) => {
429
+ const _textAdapter = textAdapter?.() ?? PlainTextAdapter();
430
+ const annotatedText = createAnnotatedText(id, {
431
+ annotationAdapter: annotationAdapter?.() ?? defaultAnnotationAdapter(sourceModel),
432
+ textAdapter: _textAdapter
433
+ });
434
+ annotatedText.setSnapper(new WordSnapper()).setRenderParams(renderParams()).setStyleParams(styleParams()).registerStyles(styles);
435
+ if (sourceModel) {
436
+ const { content } = sourceModel;
437
+ annotatedText.setText(content.text).setTextAdapterParams({ textDirection: content.textDirection });
267
438
  }
439
+ return annotatedText;
268
440
  };
269
- let c = Object.keys(s), l = V(i, "allowedChildren"), u = (e) => d(e ? { sourceUri: e.uri } : {}), p = () => ({ renderFn: z(t) }), m = () => ({ styleFn: B(c, t) });
270
441
  return {
271
- allowedChildrenPerType: l,
272
- definitions: i,
273
- getDefinition: (e) => a[e] ?? void 0,
274
- rootTypes: o,
275
- createAnnotatedText: (e, t) => {
276
- let i = ne(e);
277
- if (i.setSnapper(new te()).setAnnotationAdapter(r ?? u(t)).setTextAdapter(n ?? ee()).setRenderParams(p()).setStyleParams(m()).registerStyles(s), t) {
278
- let { content: e } = t;
279
- i.setText(e.text).setTextAdapter({ textDirection: e.textDirection });
280
- }
281
- return i;
282
- }
442
+ allowedChildrenPerType,
443
+ definitions,
444
+ getDefinition: (id) => {
445
+ return definitionsMap[id] ?? void 0;
446
+ },
447
+ rootTypes,
448
+ createAnnotatedText: _createAnnotatedText
283
449
  };
284
- }, H = Symbol("ANNOTATION_DEF_CONFIG_TOKEN");
450
+ };
285
451
  //#endregion
286
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateMetadata.js
287
- function U(e, t) {
288
- if (typeof Reflect == "object" && typeof Reflect.metadata == "function") return Reflect.metadata(e, t);
452
+ //#region src/lib/utils/annotation.context-builder.ts
453
+ var ANNOTATION_DEF_CONFIG_TOKEN = Symbol("ANNOTATION_DEF_CONFIG_TOKEN");
454
+ //#endregion
455
+ //#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorateMetadata.js
456
+ function __decorateMetadata(k, v) {
457
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
289
458
  }
290
459
  //#endregion
291
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateParam.js
292
- function W(e, t) {
293
- return function(n, r) {
294
- t(n, r, e);
460
+ //#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorateParam.js
461
+ function __decorateParam(paramIndex, decorator) {
462
+ return function(target, key) {
463
+ decorator(target, key, paramIndex);
295
464
  };
296
465
  }
297
466
  //#endregion
298
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorate.js
299
- function G(e, t, n, r) {
300
- var i = arguments.length, a = i < 3 ? t : r === null ? r = Object.getOwnPropertyDescriptor(t, n) : r, o;
301
- if (typeof Reflect == "object" && typeof Reflect.decorate == "function") a = Reflect.decorate(e, t, n, r);
302
- else for (var s = e.length - 1; s >= 0; s--) (o = e[s]) && (a = (i < 3 ? o(a) : i > 3 ? o(t, n, a) : o(t, n)) || a);
303
- return i > 3 && a && Object.defineProperty(t, n, a), a;
467
+ //#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorate.js
468
+ function __decorate(decorators, target, key, desc) {
469
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
470
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
471
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
472
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
304
473
  }
305
474
  //#endregion
306
- //#region packages/annotation-api/src/lib/service/annotation-definition.service.ts
307
- var K = class {
308
- config;
309
- definitions = [];
310
- groupedDefinitions = {};
311
- cachedAt = 0;
312
- constructor(e) {
313
- this.config = e;
314
- }
315
- async findAllGrouped() {
316
- return await this.setDefinitions(), Promise.resolve(this.groupedDefinitions);
475
+ //#region src/lib/context/annotation-context.service.ts
476
+ var AnnotationContextService = class AnnotationContextService {
477
+ configRegistry;
478
+ annotationDefConfig;
479
+ contextConfigMap = /* @__PURE__ */ new Map();
480
+ prefixMap = /* @__PURE__ */ new Map();
481
+ constructor(configRegistry, annotationDefConfig) {
482
+ this.configRegistry = configRegistry;
483
+ this.annotationDefConfig = annotationDefConfig;
317
484
  }
318
- async setDefinitions(e = !1) {
319
- let t = Date.now();
320
- if (!e && this.definitions.length && t - this.cachedAt < this.config.cacheTTLms) return;
321
- let n = await this.reloadDefinitions() ?? [];
322
- this.definitions = n, this.groupedDefinitions = n.reduce((e, t) => (e[t.id] = t, e), {}), this.cachedAt = t;
485
+ async reloadAll() {
486
+ this.contextConfigMap.clear();
487
+ this.configRegistry.findAll().forEach((resource) => {
488
+ const context = createAnnotationContext(this.annotationDefConfig, resource);
489
+ this.contextConfigMap.set(resource.id, context);
490
+ this.prefixMap.set(context.prefix, resource.id);
491
+ });
323
492
  }
324
- async findAll() {
325
- return await this.setDefinitions(), Promise.resolve(this.definitions);
493
+ async findById(annotationId) {
494
+ const find = this.contextConfigMap.get(annotationId);
495
+ if (find) return find;
496
+ const resource = await this.configRegistry.findById(annotationId);
497
+ if (!resource) return null;
498
+ const context = createAnnotationContext(this.annotationDefConfig, resource);
499
+ this.contextConfigMap.set(annotationId, context);
500
+ return context;
326
501
  }
327
- async findById(e) {
328
- await this.setDefinitions();
329
- let t = this.groupedDefinitions[e];
330
- if (t || await this.setDefinitions(!0), t = this.groupedDefinitions[e], !t) throw new a();
331
- return Promise.resolve(t);
502
+ getResourceIdFromUri = (uri) => {
503
+ for (const prefix of this.prefixMap.keys()) if (uri.startsWith(prefix)) return uri.substring(prefix.length);
504
+ return null;
505
+ };
506
+ };
507
+ AnnotationContextService = __decorate([
508
+ Injectable(),
509
+ __decorateParam(0, Inject(ResourceConfigRegistry)),
510
+ __decorateParam(1, Inject(ANNOTATION_DEF_CONFIG_TOKEN)),
511
+ __decorateMetadata("design:paramtypes", [typeof ResourceConfigRegistry === "undefined" ? Object : ResourceConfigRegistry, Object])
512
+ ], AnnotationContextService);
513
+ //#endregion
514
+ //#region src/lib/annotation/annotation.mapper.service.ts
515
+ var AnnotationW3cMapperService = class AnnotationW3cMapperService {
516
+ contextService;
517
+ constructor(contextService) {
518
+ this.contextService = contextService;
332
519
  }
333
- async getAllContextBuilders() {
334
- return (await this.findAll()).map((e) => e.context);
520
+ async getW3CAnnotation(type, annotation) {
521
+ const annotationDef = await this.contextService.findById(type);
522
+ return this.mapToW3CAnnotation(annotationDef, annotation);
335
523
  }
336
- async getContextBuilder(e) {
337
- let t = await this.findById(e);
338
- if (!t) throw new a();
339
- return t.context;
524
+ async fromW3CAnnotation(type, annotation) {
525
+ const annotationDef = await this.contextService.findById(type);
526
+ return this.mapFromW3CAnnotation(annotationDef, annotation);
340
527
  }
341
528
  };
342
- K = G([
343
- r(),
344
- W(0, n(H)),
345
- U("design:paramtypes", [Object])
346
- ], K);
529
+ AnnotationW3cMapperService = __decorate([__decorateParam(0, Inject(AnnotationContextService)), __decorateMetadata("design:paramtypes", [typeof AnnotationContextService === "undefined" ? Object : AnnotationContextService])], AnnotationW3cMapperService);
530
+ //#endregion
531
+ //#region src/lib/prefix.ts
532
+ var SCHEMA_PREFIX = "annotation-editor";
347
533
  //#endregion
348
- //#region packages/annotation-api/src/lib/service/annotation-definition-from-files.service.ts
349
- var q = class extends K {
350
- _initialDefinitions;
351
- _loaderFn;
352
- constructor(e, t, n) {
353
- super(e), this._initialDefinitions = t, this._loaderFn = n;
534
+ //#region src/lib/annotation-namespace.controller.ts
535
+ var AnnotationNamespaceController = class AnnotationNamespaceController {
536
+ service;
537
+ annotationContextService;
538
+ constructor(service, annotationContextService) {
539
+ this.service = service;
540
+ this.annotationContextService = annotationContextService;
541
+ }
542
+ async listNames() {
543
+ const basePath = process.env["API_URL"] ?? "";
544
+ const base = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
545
+ return { annotations: (await this.service.getAll()).map((a) => ({
546
+ id: a.id,
547
+ name: a.name,
548
+ schemas: `${base}/${SCHEMA_PREFIX}/${a.id}/schemas`,
549
+ jsonld: `${base}/ns/${a.id}.jsonld`
550
+ })) };
551
+ }
552
+ async getJsonLd_(id) {
553
+ return (await this.annotationContextService.findById(id))?.jsonLd;
354
554
  }
355
- reloadDefinitions = () => this.config.isDev && this._loaderFn ? Promise.resolve(this._loaderFn()) : Promise.resolve(this._initialDefinitions ?? []);
356
555
  };
357
- q = G([
358
- r(),
359
- W(0, n(H)),
360
- U("design:paramtypes", [
361
- Object,
362
- Array,
363
- Object
364
- ])
365
- ], q);
556
+ __decorate([
557
+ Get(),
558
+ __decorateMetadata("design:type", Function),
559
+ __decorateMetadata("design:paramtypes", []),
560
+ __decorateMetadata("design:returntype", Promise)
561
+ ], AnnotationNamespaceController.prototype, "listNames", null);
562
+ __decorate([
563
+ Get(":id.jsonld"),
564
+ __decorateParam(0, Param("id")),
565
+ __decorateMetadata("design:type", Function),
566
+ __decorateMetadata("design:paramtypes", [String]),
567
+ __decorateMetadata("design:returntype", Promise)
568
+ ], AnnotationNamespaceController.prototype, "getJsonLd_", null);
569
+ AnnotationNamespaceController = __decorate([
570
+ Controller("ns"),
571
+ ApiTags("Annotations NS"),
572
+ __decorateParam(0, Inject(ResourceConfigRegistry)),
573
+ __decorateParam(1, Inject(ANNOTATION_DEF_CONFIG_TOKEN)),
574
+ __decorateMetadata("design:paramtypes", [typeof ResourceConfigRegistry === "undefined" ? Object : ResourceConfigRegistry, Object])
575
+ ], AnnotationNamespaceController);
366
576
  //#endregion
367
- //#region packages/annotation-api/src/lib/service/annotation-definition.loader.ts
368
- var J = (e, t, n) => {
369
- if (!h(e)) return [];
370
- let r = _(e, { withFileTypes: !0 }).filter((e) => e.isDirectory()).map((e) => e.name), i = [];
371
- for (let a of r) {
372
- let r = v(e, a, "resource.json");
373
- if (!h(r)) continue;
374
- let o = JSON.parse(g(r, "utf-8"));
375
- i.push(M(o, t, n));
376
- }
377
- return i;
378
- }, Y = class {
379
- service;
380
- annotationDefConfig;
381
- constructor(e, t) {
382
- this.service = e, this.annotationDefConfig = t;
577
+ //#region src/lib/annotation/annotation.controller.ts
578
+ var AnnotationController = class AnnotationController {
579
+ annotationRepository;
580
+ wrapper;
581
+ contextService;
582
+ constructor(annotationRepository, wrapper, contextService) {
583
+ this.annotationRepository = annotationRepository;
584
+ this.wrapper = wrapper;
585
+ this.contextService = contextService;
383
586
  }
384
- getAll() {
385
- return this.service.findAll();
587
+ async create(type, annotationBody) {
588
+ const parsed = await this.wrapper.fromW3CAnnotation(type, annotationBody);
589
+ const annotation = await this.annotationRepository.create(parsed);
590
+ return this.get(annotation.id);
386
591
  }
387
- async getJsonLd_(e) {
388
- return e === "AnnotationStyle" ? E(this.annotationDefConfig).toJsonLdContext() : (await this.service.findById(e))?.json_ld;
592
+ async getByType(id) {
593
+ const { annotation, type } = await this.annotationRepository.findOne(id);
594
+ return this.wrapper.getW3CAnnotation(type, annotation);
389
595
  }
390
- async getSchemas(e) {
391
- let t = await this.service.findById(e);
392
- return {
393
- id: t.id,
394
- name: t.name,
395
- json_schema: t.json_schema,
396
- ui_schema: t.ui_schema,
397
- metadata_schema: t.metadata_schema,
398
- columns: t.columns,
399
- isRoot: t.isRoot,
400
- allowedChildren: t.allowedChildren,
401
- allowedLinks: t.allowedLinks,
402
- type: t.type,
403
- icon: t.icon,
404
- target: t.target
405
- };
596
+ async get(id) {
597
+ const _id = this.contextService.getResourceIdFromUri(id) ?? id;
598
+ const { annotation, type } = await this.annotationRepository.findOne(_id);
599
+ return this.wrapper.getW3CAnnotation(type, annotation);
406
600
  }
407
- async getById(e) {
408
- return await this.service.findById(e);
601
+ async patch(type, id, annotationBody) {
602
+ const _id = this.contextService.getResourceIdFromUri(id) ?? id;
603
+ const _annotation = await this.wrapper.fromW3CAnnotation(type, annotationBody);
604
+ const annotation = await this.annotationRepository.update(_id, _annotation);
605
+ return this.get(annotation.id);
409
606
  }
410
- async getFullJsonLd() {
411
- return (await this.service.getAllContextBuilders()).map((e) => e.toJsonLdContext());
607
+ async delete(id) {
608
+ const _id = this.contextService.getResourceIdFromUri(id) ?? id;
609
+ return this.annotationRepository.delete(_id);
412
610
  }
413
- async getJsonLd(e) {
414
- let t = await this.service.getContextBuilder(e);
415
- return {
416
- jsonLd: t.toJsonLdContext(),
417
- forms: t.toJsonSchema()
418
- };
611
+ async deleteType(id) {
612
+ const _id = this.contextService.getResourceIdFromUri(id) ?? id;
613
+ return this.annotationRepository.delete(_id);
419
614
  }
420
615
  };
421
- G([
422
- t(),
423
- U("design:type", Function),
424
- U("design:paramtypes", []),
425
- U("design:returntype", void 0)
426
- ], Y.prototype, "getAll", null), G([
427
- t(":id.jsonld"),
428
- W(0, o("id")),
429
- U("design:type", Function),
430
- U("design:paramtypes", [String]),
431
- U("design:returntype", Promise)
432
- ], Y.prototype, "getJsonLd_", null), G([
433
- t(":id/schemas"),
434
- W(0, o("id")),
435
- U("design:type", Function),
436
- U("design:paramtypes", [String]),
437
- U("design:returntype", Promise)
438
- ], Y.prototype, "getSchemas", null), G([
439
- t(":id"),
440
- W(0, o("id")),
441
- U("design:type", Function),
442
- U("design:paramtypes", [String]),
443
- U("design:returntype", Promise)
444
- ], Y.prototype, "getById", null), G([
445
- t("anno.jsonld"),
446
- U("design:type", Function),
447
- U("design:paramtypes", []),
448
- U("design:returntype", Promise)
449
- ], Y.prototype, "getFullJsonLd", null), G([
450
- t(":type/anno.jsonld"),
451
- W(0, o("type")),
452
- U("design:type", Function),
453
- U("design:paramtypes", [String]),
454
- U("design:returntype", Promise)
455
- ], Y.prototype, "getJsonLd", null), Y = G([
456
- e("ns"),
457
- re("Annotations NS"),
458
- W(0, n(K)),
459
- W(1, n(H)),
460
- U("design:paramtypes", [K === void 0 ? Object : K, Object])
461
- ], Y);
616
+ __decorate([
617
+ Post(":type"),
618
+ ApiOperation({ summary: "Create a W3C annotation" }),
619
+ ApiBody({ description: "W3C annotation body" }),
620
+ ApiResponse({
621
+ status: 201,
622
+ description: "The created W3C annotation"
623
+ }),
624
+ __decorateParam(0, Param("type")),
625
+ __decorateParam(1, Body()),
626
+ __decorateMetadata("design:type", Function),
627
+ __decorateMetadata("design:paramtypes", [String, Object]),
628
+ __decorateMetadata("design:returntype", Promise)
629
+ ], AnnotationController.prototype, "create", null);
630
+ __decorate([
631
+ Get(":type/:id"),
632
+ ApiOperation({ summary: "Get one annotation by id" }),
633
+ ApiParam({
634
+ name: "id",
635
+ type: "string"
636
+ }),
637
+ ApiParam({
638
+ name: "type",
639
+ type: "string"
640
+ }),
641
+ ApiResponse({
642
+ status: 200,
643
+ description: "The W3C annotation"
644
+ }),
645
+ __decorateParam(0, Param("id")),
646
+ __decorateMetadata("design:type", Function),
647
+ __decorateMetadata("design:paramtypes", [String]),
648
+ __decorateMetadata("design:returntype", Promise)
649
+ ], AnnotationController.prototype, "getByType", null);
650
+ __decorate([
651
+ Get(":id"),
652
+ ApiOperation({ summary: "Get one annotation by id" }),
653
+ ApiParam({
654
+ name: "id",
655
+ type: "string"
656
+ }),
657
+ ApiResponse({
658
+ status: 200,
659
+ description: "The W3C annotation"
660
+ }),
661
+ __decorateParam(0, Param("id")),
662
+ __decorateMetadata("design:type", Function),
663
+ __decorateMetadata("design:paramtypes", [String]),
664
+ __decorateMetadata("design:returntype", Promise)
665
+ ], AnnotationController.prototype, "get", null);
666
+ __decorate([
667
+ Patch(":type/:id"),
668
+ ApiOperation({ summary: "Update an annotation" }),
669
+ ApiParam({
670
+ name: "id",
671
+ type: "string"
672
+ }),
673
+ ApiBody({ description: "W3C annotation body" }),
674
+ ApiResponse({
675
+ status: 200,
676
+ description: "The updated W3C annotation"
677
+ }),
678
+ __decorateParam(0, Param("type")),
679
+ __decorateParam(1, Param("id")),
680
+ __decorateParam(2, Body()),
681
+ __decorateMetadata("design:type", Function),
682
+ __decorateMetadata("design:paramtypes", [
683
+ String,
684
+ String,
685
+ Object
686
+ ]),
687
+ __decorateMetadata("design:returntype", Promise)
688
+ ], AnnotationController.prototype, "patch", null);
689
+ __decorate([
690
+ Delete(":id"),
691
+ ApiOperation({ summary: "Delete an annotation" }),
692
+ ApiParam({
693
+ name: "id",
694
+ type: "string"
695
+ }),
696
+ ApiResponse({
697
+ status: 200,
698
+ description: "Annotation deleted"
699
+ }),
700
+ __decorateParam(0, Param("id")),
701
+ __decorateMetadata("design:type", Function),
702
+ __decorateMetadata("design:paramtypes", [String]),
703
+ __decorateMetadata("design:returntype", Promise)
704
+ ], AnnotationController.prototype, "delete", null);
705
+ __decorate([
706
+ Delete(":type/:id"),
707
+ ApiOperation({ summary: "Delete an annotation" }),
708
+ ApiParam({
709
+ name: "id",
710
+ type: "string"
711
+ }),
712
+ ApiResponse({
713
+ status: 200,
714
+ description: "Annotation deleted"
715
+ }),
716
+ __decorateParam(0, Param("id")),
717
+ __decorateMetadata("design:type", Function),
718
+ __decorateMetadata("design:paramtypes", [String]),
719
+ __decorateMetadata("design:returntype", Promise)
720
+ ], AnnotationController.prototype, "deleteType", null);
721
+ AnnotationController = __decorate([
722
+ Controller(`${SCHEMA_PREFIX}/annotation`),
723
+ ApiTags("Annotations"),
724
+ __decorateParam(0, Inject(AnnotationCrudRepository)),
725
+ __decorateParam(1, Inject(AnnotationW3cMapperService)),
726
+ __decorateParam(2, Inject(AnnotationContextService)),
727
+ __decorateMetadata("design:paramtypes", [
728
+ typeof AnnotationCrudRepository === "undefined" ? Object : AnnotationCrudRepository,
729
+ typeof AnnotationW3cMapperService === "undefined" ? Object : AnnotationW3cMapperService,
730
+ typeof AnnotationContextService === "undefined" ? Object : AnnotationContextService
731
+ ])
732
+ ], AnnotationController);
462
733
  //#endregion
463
- //#region packages/annotation-api/src/lib/resource/annotation-resource.loader.ts
464
- var X = (e, t) => {
465
- let n = v(e, "_resource");
466
- if (!h(n)) return [];
467
- let r = _(n).filter((e) => e.endsWith(".json")), { prefix: i } = C(t);
468
- return r.map((e) => {
469
- let t = JSON.parse(g(v(n, e), "utf-8")), r = t.columns.find((e) => e.displayAs === "id"), a = t.columns.find((e) => e.displayAs === "label");
470
- return {
471
- type: t.type,
472
- table: t.table,
473
- database: t.database,
474
- field: {
475
- id: r?.column ?? "id",
476
- label: a?.column ?? "name"
477
- },
478
- prefix: `${i}:${t.type}/`
479
- };
480
- });
481
- }, Z = class {
482
- byType = /* @__PURE__ */ new Map();
483
- constructor(e) {
484
- for (let t of e) this.byType.set(t.type, t);
485
- }
486
- findAll = () => [...this.byType.values()];
487
- getResourceForType = (e) => this.byType.get(e) ?? null;
488
- getResourceFromUri = (e) => {
489
- for (let t of this.byType.values()) if (e.startsWith(t.prefix)) return {
490
- ...t,
491
- id: e.substring(t.prefix.length)
492
- };
493
- return null;
734
+ //#region src/lib/utils/schemaEnricher.utils.ts
735
+ var createSchemaEnricher = (baseUrl = "") => (schema) => {
736
+ const uri = `${baseUrl}${SCHEMA_PREFIX}/annotation/${schema.route}`;
737
+ const uriId = `${uri}/{id}`;
738
+ schema.operations = {
739
+ findOne: schema.operations.findOne ?? {
740
+ uri: uriId,
741
+ method: "get"
742
+ },
743
+ update: schema.operations.update ?? {
744
+ uri: uriId,
745
+ method: "patch"
746
+ },
747
+ delete: schema.operations.delete ?? {
748
+ uri: uriId,
749
+ method: "delete"
750
+ },
751
+ create: schema.operations.create ?? {
752
+ uri,
753
+ method: "post"
754
+ },
755
+ findAll: schema.operations.findAll
494
756
  };
757
+ return { ...schema };
495
758
  };
496
- Z = G([r(), U("design:paramtypes", [Array])], Z);
497
759
  //#endregion
498
- //#region packages/annotation-api/src/lib/annotation-api.module.ts
499
- var Q, $ = Q = class {
500
- static forService(e) {
501
- return {
502
- module: Q,
503
- global: !0,
504
- controllers: [Y],
505
- providers: [{
506
- provide: K,
507
- useClass: e.annotationDefinitionService
508
- }],
509
- exports: [K]
510
- };
511
- }
512
- static async forResourceDir(e, t) {
513
- let n = () => J(e, t, j), r = new q(t, n(), n), i = new Z(X(e, t));
514
- return {
515
- module: Q,
516
- global: !0,
517
- controllers: [Y],
760
+ //#region src/lib/annotation-api.module.ts
761
+ var _AnnotationApiModule;
762
+ registerResourceExtensions({ annotation: AnnotationConfigSchema });
763
+ var AnnotationApiModule = _AnnotationApiModule = class AnnotationApiModule {
764
+ static async forResourceDir(resourcePath, datasourcePath, config, annotation) {
765
+ const _config = resolveConfig(config);
766
+ const crouton = await CroutonApiModule.forResourceDir(resourcePath, datasourcePath, {
767
+ baseUrl: "",
768
+ prefix: SCHEMA_PREFIX,
769
+ extensions: { annotation: AnnotationConfigSchema },
770
+ schemaEnricher: createSchemaEnricher(_config.baseUrl)
771
+ });
772
+ if (annotation) return {
773
+ module: _AnnotationApiModule,
774
+ global: true,
775
+ imports: [crouton],
776
+ controllers: [AnnotationNamespaceController, AnnotationController],
518
777
  providers: [
778
+ AnnotationContextService,
519
779
  {
520
- provide: H,
521
- useValue: t
780
+ provide: ANNOTATION_DEF_CONFIG_TOKEN,
781
+ useValue: _config
522
782
  },
523
783
  {
524
- provide: K,
525
- useValue: r
784
+ provide: AnnotationCrudRepository,
785
+ useExisting: annotation.repository
526
786
  },
527
787
  {
528
- provide: Z,
529
- useValue: i
788
+ provide: AnnotationW3cMapperService,
789
+ useExisting: annotation.mapper
530
790
  }
531
791
  ],
532
- exports: [K, Z]
792
+ exports: [AnnotationContextService]
793
+ };
794
+ return {
795
+ module: _AnnotationApiModule,
796
+ global: true,
797
+ imports: [crouton],
798
+ controllers: [AnnotationNamespaceController],
799
+ providers: [AnnotationContextService, {
800
+ provide: ANNOTATION_DEF_CONFIG_TOKEN,
801
+ useValue: _config
802
+ }],
803
+ exports: [AnnotationContextService]
533
804
  };
534
805
  }
535
806
  };
536
- $ = Q = G([i({
807
+ AnnotationApiModule = _AnnotationApiModule = __decorate([Module({
537
808
  controllers: [],
538
809
  providers: [],
539
810
  exports: []
540
- })], $);
811
+ })], AnnotationApiModule);
541
812
  //#endregion
542
- export { H as ANNOTATION_DEF_CONFIG_TOKEN, $ as AnnotationApiModule, q as AnnotationDefinitionFromFilesService, K as AnnotationDefinitionService, b as AnnotationMetadataType, Z as AnnotationResourceDefinitionService, E as AnnotationStyleContextBuilder, T as AnnotationStyleType, ae as SourceModelSchema, y as SourceTextSchema, x as annotationColumnDefinition, j as annotationContextBuilderFactory, ce as annotationDefinition, he as annotationUtils, w as baseContextBuilder, M as buildAnnotationDefinition, fe as buildAnnotationDefinitions, oe as buildGridStyle, k as buildMetadataSchema, O as buildUiSchema, ge as createAnnotationConfiguration, de as createAnnotationStyleBodyUnsafe, z as defaultRender, se as getPaneArea, A as jsonSchemaPropertyToZod, J as loadAnnotationDefinitionsFromDir, X as loadAnnotationResourcesFromDir, C as resolveConfig, B as styleFn };
813
+ export { AnnotationApiModule, AnnotationConfigSchema, AnnotationContextService, AnnotationCrudRepository, AnnotationJsonResourceSchema, AnnotationJsonResourceShape, AnnotationMetadataType, AnnotationResourceSchema, AnnotationStyleContextBuilder, AnnotationStyleType, AnnotationW3cMapperService, BASELINE_RESOURCE_VERSION, CURRENT_RESOURCE_VERSION, KeyLabelSchema, SourceModelSchema, SourceTextSchema, annotationColumnDefinition, annotationUtils, baseContextBuilder, buildGridStyle, buildPrefix, createAnnotationConfiguration, createAnnotationContext, createAnnotationStyleBodyUnsafe, defaultRender, getPaneArea, resolveConfig, styleFn };