-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconceptConversion.ts
More file actions
353 lines (339 loc) · 10.9 KB
/
conceptConversion.ts
File metadata and controls
353 lines (339 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import type { TFile } from "obsidian";
import type {
DiscourseNode,
DiscourseRelation,
DiscourseRelationType,
RelationInstance,
} from "~/types";
import type { SupabaseContext } from "./supabaseContext";
import type { DiscourseNodeInVault } from "./getDiscourseNodes";
import type { LocalConceptDataInput } from "@repo/database/inputTypes";
import type { ObsidianDiscourseNodeData } from "./syncDgNodesToSupabase";
import type { Json } from "@repo/database/dbTypes";
/**
* Get extra data (author, timestamps) from file metadata
*/
const getNodeExtraData = (
file: TFile,
accountLocalId: string,
): {
/* eslint-disable @typescript-eslint/naming-convention */
author_local_id: string;
created: string;
last_modified: string;
} => {
return {
author_local_id: accountLocalId,
created: new Date(file.stat.ctime).toISOString(),
last_modified: new Date(file.stat.mtime).toISOString(),
};
/* eslint-enable @typescript-eslint/naming-convention */
};
export const discourseNodeSchemaToLocalConcept = ({
context,
node,
accountLocalId,
}: {
context: SupabaseContext;
node: DiscourseNode;
accountLocalId: string;
}): LocalConceptDataInput => {
const {
description,
template,
id,
name,
created,
modified,
importedFromRid,
...otherData
} = node;
/* eslint-disable @typescript-eslint/naming-convention */
const literal_content: Record<string, Json> = {
label: name,
source_data: otherData,
};
if (template) literal_content.template = template;
if (importedFromRid) literal_content.importedFromRid = importedFromRid;
return {
space_id: context.spaceId,
name,
source_local_id: id,
is_schema: true,
author_local_id: accountLocalId,
created: new Date(created).toISOString(),
last_modified: new Date(modified).toISOString(),
description: description,
literal_content,
/* eslint-enable @typescript-eslint/naming-convention */
};
};
const STANDARD_ROLES = ["source", "destination"];
export const discourseRelationTypeToLocalConcept = ({
context,
relationType,
accountLocalId,
}: {
context: SupabaseContext;
relationType: DiscourseRelationType;
accountLocalId: string;
}): LocalConceptDataInput => {
const {
id,
label,
complement,
created,
modified,
importedFromRid,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
status, //destructuring status to not upload it to the database
...otherData
} = relationType;
// eslint-disable-next-line @typescript-eslint/naming-convention
const literal_content: Record<string, Json> = {
roles: STANDARD_ROLES,
label,
complement,
// eslint-disable-next-line @typescript-eslint/naming-convention
source_data: otherData,
};
if (importedFromRid) literal_content.importedFromRid = importedFromRid;
return {
/* eslint-disable @typescript-eslint/naming-convention */
space_id: context.spaceId,
name: label,
source_local_id: id,
is_schema: true,
author_local_id: accountLocalId,
created: new Date(created).toISOString(),
last_modified: new Date(modified).toISOString(),
literal_content,
/* eslint-enable @typescript-eslint/naming-convention */
};
};
export const discourseRelationTripleSchemaToLocalConcept = ({
context,
relation,
accountLocalId,
nodeTypesById,
relationTypesById,
}: {
context: SupabaseContext;
relation: DiscourseRelation;
accountLocalId: string;
nodeTypesById: Record<string, DiscourseNode>;
relationTypesById: Record<string, DiscourseRelationType>;
}): LocalConceptDataInput | null => {
const {
id,
relationshipTypeId,
sourceId,
destinationId,
created,
modified,
importedFromRid,
} = relation;
const sourceName = nodeTypesById[sourceId]?.name ?? sourceId;
const destinationName = nodeTypesById[destinationId]?.name ?? destinationId;
const relationType = relationTypesById[relationshipTypeId];
if (!relationType) return null;
const { label, complement } = relationType;
// eslint-disable-next-line @typescript-eslint/naming-convention
const literal_content: Record<string, Json> = {
roles: STANDARD_ROLES,
label,
complement,
};
if (importedFromRid) literal_content.importedFromRid = importedFromRid;
return {
/* eslint-disable @typescript-eslint/naming-convention */
space_id: context.spaceId,
name: `${sourceName} -${label}-> ${destinationName}`,
source_local_id: id,
is_schema: true,
author_local_id: accountLocalId,
created: new Date(created).toISOString(),
last_modified: new Date(modified).toISOString(),
literal_content,
local_reference_content: {
relation_type: relationshipTypeId,
source: sourceId,
destination: destinationId,
},
/* eslint-enable @typescript-eslint/naming-convention */
};
};
/**
* Convert discourse node instance (file) to LocalConceptDataInput
*/
export const discourseNodeInstanceToLocalConcept = ({
context,
nodeData,
accountLocalId,
}: {
context: SupabaseContext;
nodeData: ObsidianDiscourseNodeData;
accountLocalId: string;
}): LocalConceptDataInput => {
const extraData = getNodeExtraData(nodeData.file, accountLocalId);
const { nodeInstanceId, nodeTypeId, importedFromRid, ...otherData } =
nodeData.frontmatter;
// eslint-disable-next-line @typescript-eslint/naming-convention
const literal_content: Record<string, Json> = {
label: nodeData.file.basename,
// eslint-disable-next-line @typescript-eslint/naming-convention
source_data: otherData as unknown as Json,
};
if (importedFromRid && typeof importedFromRid === "string")
literal_content.importedFromRid = importedFromRid;
return {
/* eslint-disable @typescript-eslint/naming-convention */
space_id: context.spaceId,
name: nodeData.file.path,
source_local_id: nodeInstanceId as string,
schema_represented_by_local_id: nodeTypeId as string,
is_schema: false,
literal_content,
/* eslint-enable @typescript-eslint/naming-convention */
...extraData,
};
};
export const relationInstanceToLocalConcept = ({
context,
relationTypesById,
allNodesById,
relationInstanceData,
}: {
context: SupabaseContext;
relationTypesById: Record<string, DiscourseRelationType>;
allNodesById: Record<string, DiscourseNodeInVault>;
relationInstanceData: RelationInstance;
}): LocalConceptDataInput | null => {
const { type, created, lastModified, source, destination, importedFromRid } =
relationInstanceData;
const relationType = relationTypesById[type];
if (!relationType) {
console.error("Missing relationType id " + type);
return null;
}
const sourceNode = allNodesById[source];
const destinationNode = allNodesById[destination];
if (sourceNode === undefined || destinationNode === undefined) {
console.error("Cannot find the nodes");
return null;
}
/* eslint-disable @typescript-eslint/naming-convention */
const literal_content: Record<string, Json> = {};
if (importedFromRid) literal_content.importedFromRid = importedFromRid;
return {
space_id: context.spaceId,
name: `[[${sourceNode.file.basename}]] -${relationType.label}-> [[${destinationNode.file.basename}]]`,
source_local_id: relationInstanceData.id,
author_local_id: relationInstanceData.author,
schema_represented_by_local_id: type,
is_schema: false,
created: new Date(created).toISOString(),
last_modified: new Date(lastModified ?? created).toISOString(),
literal_content,
local_reference_content: {
source:
(sourceNode.frontmatter.importedFromRid as string | undefined) ??
source,
destination:
(destinationNode.frontmatter.importedFromRid as string | undefined) ??
destination,
},
/* eslint-enable @typescript-eslint/naming-convention */
};
};
export const relatedConcepts = (concept: LocalConceptDataInput): string[] => {
const relations = Object.values(
concept.local_reference_content || {},
).flat() as string[];
if (concept.schema_represented_by_local_id) {
relations.push(concept.schema_represented_by_local_id);
}
// remove duplicates
return [...new Set(relations)];
};
/**
* Recursively order concepts by dependency so that dependents (e.g. instances)
* come after their dependencies (e.g. schemas). When we look up a related
* concept by id in `remainder`, we use the same id that appears in
* schema_represented_by_local_id or local_reference_content — so that id
* must equal some concept's source_local_id or it is reported as "missing".
*/
const orderConceptsRec = ({
ordered,
concept,
remainder,
processed,
}: {
ordered: LocalConceptDataInput[];
concept: LocalConceptDataInput;
remainder: { [key: string]: LocalConceptDataInput };
processed: Set<string>;
}): Set<string> => {
// Add to processed at the start to prevent cycles
processed.add(concept.source_local_id!);
const relatedConceptIds = relatedConcepts(concept);
let missing: Set<string> = new Set();
while (relatedConceptIds.length > 0) {
const relatedConceptId = relatedConceptIds.shift()!;
if (processed.has(relatedConceptId)) continue;
const relatedConcept = remainder[relatedConceptId];
if (relatedConcept === undefined) {
missing.add(relatedConceptId);
} else {
missing = new Set([
...missing,
...orderConceptsRec({
ordered,
concept: relatedConcept,
remainder,
processed,
}),
]);
delete remainder[relatedConceptId];
}
}
ordered.push(concept);
delete remainder[concept.source_local_id!];
return missing;
};
/**
* Order concepts so dependencies (schemas) are before dependents (instances).
* Assumes every concept has source_local_id; concepts without it are excluded
* from the map (same as Roam). A node type is "missing" when an instance
* references schema_represented_by_local_id = X but no concept in the input
* has source_local_id === X (e.g. schema not included, or id vs nodeTypeId mismatch).
*/
export const orderConceptsByDependency = (
concepts: LocalConceptDataInput[],
): { ordered: LocalConceptDataInput[]; missing: string[] } => {
if (concepts.length === 0) return { ordered: concepts, missing: [] };
const conceptById: { [key: string]: LocalConceptDataInput } =
Object.fromEntries(
concepts
.filter((c) => c.source_local_id != null && c.source_local_id !== "")
.map((c) => [c.source_local_id!, c]),
);
const ordered: LocalConceptDataInput[] = [];
let missing: Set<string> = new Set();
const processed: Set<string> = new Set();
while (Object.keys(conceptById).length > 0) {
const first = Object.values(conceptById)[0];
if (!first) break;
missing = new Set([
...missing,
...orderConceptsRec({
ordered,
concept: first,
remainder: conceptById,
processed,
}),
]);
if (missing.size > 0) console.error(`missing: ${[...missing].join(", ")}`);
}
return { ordered, missing: Array.from(missing) };
};