-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathaccessors.ts
More file actions
606 lines (516 loc) · 14.8 KB
/
accessors.ts
File metadata and controls
606 lines (516 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import getBlockProps, {
normalizeProps,
type json,
} from "~/utils/getBlockProps";
import setBlockProps from "~/utils/setBlockProps";
import getBlockUidByTextOnPage from "roamjs-components/queries/getBlockUidByTextOnPage";
import getPageUidByPageTitle from "roamjs-components/queries/getPageUidByPageTitle";
import internalError from "~/utils/internalError";
import { z } from "zod";
import {
DG_BLOCK_PROP_SETTINGS_PAGE_TITLE,
DISCOURSE_NODE_PAGE_PREFIX,
STATIC_TOP_LEVEL_ENTRIES,
FeatureFlagsSchema,
GlobalSettingsSchema,
PersonalSettingsSchema,
DiscourseNodeSchema,
getPersonalSettingsKey,
type FeatureFlags,
type GlobalSettings,
type PersonalSettings,
type DiscourseNodeSettings,
type DiscourseRelationSettings,
} from "./zodSchema";
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const unwrapSchema = (schema: z.ZodTypeAny): z.ZodTypeAny => {
let current = schema;
let didUnwrap = true;
while (didUnwrap) {
didUnwrap = false;
if (current instanceof z.ZodDefault) {
const defaultSchema = current as z.ZodDefault<z.ZodTypeAny>;
current = defaultSchema._def.innerType;
didUnwrap = true;
continue;
}
if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {
current = current.unwrap() as z.ZodTypeAny;
didUnwrap = true;
continue;
}
if (current instanceof z.ZodEffects) {
const effectsSchema = current as z.ZodEffects<z.ZodTypeAny>;
current = effectsSchema._def.schema;
didUnwrap = true;
continue;
}
if (current instanceof z.ZodCatch) {
const catchSchema = current as z.ZodCatch<z.ZodTypeAny>;
current = catchSchema._def.innerType;
didUnwrap = true;
continue;
}
if (current instanceof z.ZodLazy) {
const lazySchema = current as z.ZodLazy<z.ZodTypeAny>;
current = lazySchema._def.getter();
didUnwrap = true;
}
}
return current;
};
const getSchemaAtPath = (
schema: z.ZodTypeAny,
keys: string[],
): z.ZodTypeAny | null => {
let current = unwrapSchema(schema);
for (const key of keys) {
current = unwrapSchema(current);
if (current instanceof z.ZodObject) {
const shape = current.shape as Record<string, z.ZodTypeAny>;
if (!(key in shape)) return null;
current = shape[key];
continue;
}
if (current instanceof z.ZodRecord) {
current = current.valueSchema as z.ZodTypeAny;
continue;
}
if (current instanceof z.ZodArray) {
current = current.element as z.ZodTypeAny;
continue;
}
return null;
}
return current;
};
const formatSettingPath = (keys: string[]): string =>
keys.length === 0 ? "(root)" : keys.join(" > ");
const validateSettingValue = ({
schema,
keys,
value,
context,
}: {
schema: z.ZodTypeAny;
keys: string[];
value: json;
context: string;
}): boolean => {
const targetSchema = getSchemaAtPath(schema, keys);
if (!targetSchema) {
internalError({
error: `Unknown ${context} setting path: ${formatSettingPath(keys)}`,
type: "DG Accessor",
context: { keys },
});
return false;
}
const result = targetSchema.safeParse(value);
if (!result.success) {
internalError({
error: `Invalid ${context} setting value at path: ${formatSettingPath(keys)}`,
type: "DG Accessor",
context: { keys, zodError: result.error.message },
});
return false;
}
return true;
};
const getBlockPropsByUid = (
blockUid: string,
keys: string[],
): json | undefined => {
if (!blockUid) return undefined;
const allBlockProps = getBlockProps(blockUid);
if (keys.length === 0) {
return allBlockProps;
}
const targetValue = keys.reduce((currentContext: json, currentKey) => {
if (
currentContext &&
typeof currentContext === "object" &&
!Array.isArray(currentContext)
) {
const value = currentContext[currentKey];
return value === undefined ? null : value;
}
return null;
}, allBlockProps);
return targetValue === null ? undefined : targetValue;
};
const setBlockPropAtPath = (
blockUid: string,
keys: string[],
value: json,
): void => {
if (!blockUid) {
internalError({
error: "setBlockPropAtPath called with empty blockUid",
type: "DG Accessor",
});
return;
}
if (keys.length === 0) {
internalError({
error: "setBlockPropAtPath called with empty keys array",
type: "DG Accessor",
});
return;
}
const currentProps = getBlockProps(blockUid);
const updatedProps: Record<string, json> = currentProps || {};
const lastKeyIndex = keys.length - 1;
keys.reduce<Record<string, json>>((currentContext, currentKey, index) => {
if (index === lastKeyIndex) {
currentContext[currentKey] = value;
return currentContext;
}
if (
!currentContext[currentKey] ||
typeof currentContext[currentKey] !== "object" ||
Array.isArray(currentContext[currentKey])
) {
currentContext[currentKey] = {};
}
return currentContext[currentKey];
}, updatedProps);
setBlockProps(blockUid, updatedProps, false);
};
const getBlockPropBasedSettings = ({
keys,
}: {
keys: string[];
}): { blockProps: json | undefined; blockUid: string } => {
if (keys.length === 0) {
internalError({
error: "getBlockPropBasedSettings called with no keys",
type: "DG Accessor",
});
return { blockProps: undefined, blockUid: "" };
}
const blockUid = getBlockUidByTextOnPage({
text: keys[0],
title: DG_BLOCK_PROP_SETTINGS_PAGE_TITLE,
});
if (!blockUid) {
return { blockProps: undefined, blockUid: "" };
}
const blockProps = getBlockPropsByUid(blockUid, keys.slice(1));
return { blockProps, blockUid };
};
const setBlockPropBasedSettings = ({
keys,
value,
}: {
keys: string[];
value: json;
}): void => {
if (keys.length === 0) {
internalError({
error: "setBlockPropBasedSettings called with no keys",
type: "DG Accessor",
});
return;
}
const blockUid = getBlockUidByTextOnPage({
text: keys[0],
title: DG_BLOCK_PROP_SETTINGS_PAGE_TITLE,
});
if (!blockUid) {
internalError({
error: `Block not found for key "${keys[0]}" on settings page`,
type: "DG Accessor",
});
return;
}
setBlockPropAtPath(blockUid, keys.slice(1), value);
};
export const getFeatureFlags = (): FeatureFlags => {
const { blockProps } = getBlockPropBasedSettings({
keys: [STATIC_TOP_LEVEL_ENTRIES.featureFlags.key],
});
return FeatureFlagsSchema.parse(blockProps || {});
};
export const getFeatureFlag = (key: keyof FeatureFlags): boolean => {
const flags = getFeatureFlags();
return flags[key];
};
export const setFeatureFlag = (
key: keyof FeatureFlags,
value: boolean,
): void => {
const validatedValue = z.boolean().parse(value);
setBlockPropBasedSettings({
keys: [STATIC_TOP_LEVEL_ENTRIES.featureFlags.key, key],
value: validatedValue,
});
};
export const getGlobalSettings = (): GlobalSettings => {
const { blockProps } = getBlockPropBasedSettings({
keys: [STATIC_TOP_LEVEL_ENTRIES.global.key],
});
return GlobalSettingsSchema.parse(blockProps || {});
};
export const getGlobalSetting = <T = unknown>(
keys: string[],
): T | undefined => {
const settings = getGlobalSettings();
return keys.reduce<unknown>((current, key) => {
if (!isRecord(current) || !(key in current)) return undefined;
return current[key];
}, settings) as T | undefined;
};
export const setGlobalSetting = (keys: string[], value: json): void => {
if (keys.length === 0) {
internalError({
error: "setGlobalSetting called with empty keys array",
type: "DG Accessor",
});
return;
}
if (
!validateSettingValue({
schema: GlobalSettingsSchema,
keys,
value,
context: "Global",
})
) {
return;
}
setBlockPropBasedSettings({
keys: [STATIC_TOP_LEVEL_ENTRIES.global.key, ...keys],
value,
});
};
export const getAllRelations = (): DiscourseRelationSettings[] => {
const settings = getGlobalSettings();
return Object.entries(settings.Relations).map(([id, relation]) => ({
...relation,
id,
}));
};
export const getPersonalSettings = (): PersonalSettings => {
const personalKey = getPersonalSettingsKey();
const { blockProps } = getBlockPropBasedSettings({
keys: [personalKey],
});
return PersonalSettingsSchema.parse(blockProps || {});
};
export const getPersonalSetting = <T = unknown>(
keys: string[],
): T | undefined => {
const settings = getPersonalSettings();
return keys.reduce<unknown>((current, key) => {
if (!isRecord(current) || !(key in current)) return undefined;
return current[key];
}, settings) as T | undefined;
};
export const setPersonalSetting = (keys: string[], value: json): void => {
if (keys.length === 0) {
internalError({
error: "setPersonalSetting called with empty keys array",
type: "DG Accessor",
});
return;
}
const personalKey = getPersonalSettingsKey();
if (
!validateSettingValue({
schema: PersonalSettingsSchema,
keys,
value,
context: "Personal",
})
) {
return;
}
setBlockPropBasedSettings({
keys: [personalKey, ...keys],
value,
});
};
export const getDiscourseNodeSettings = (
nodeType: string,
): DiscourseNodeSettings | undefined => {
let pageUid = nodeType;
let blockProps = getBlockPropsByUid(pageUid, []);
if (!blockProps || Object.keys(blockProps).length === 0) {
const lookedUpUid = getPageUidByPageTitle(
`${DISCOURSE_NODE_PAGE_PREFIX}${nodeType}`,
);
if (lookedUpUid) {
pageUid = lookedUpUid;
blockProps = getBlockPropsByUid(pageUid, []);
}
}
if (!blockProps) return undefined;
const result = DiscourseNodeSchema.safeParse(blockProps);
if (!result.success) {
internalError({
error: `Failed to parse discourse node settings for ${nodeType}`,
type: "DG Accessor",
context: { zodError: result.error.message },
});
return undefined;
}
return result.data;
};
export const getDiscourseNodeSetting = <T = unknown>(
nodeType: string,
keys: string[],
): T | undefined => {
const settings = getDiscourseNodeSettings(nodeType);
if (!settings) return undefined;
return keys.reduce<unknown>((current, key) => {
if (!isRecord(current) || !(key in current)) return undefined;
return current[key];
}, settings) as T | undefined;
};
export const setDiscourseNodeSetting = (
nodeType: string,
keys: string[],
value: json,
): void => {
if (keys.length === 0) {
internalError({
error: "setDiscourseNodeSetting called with empty keys array",
type: "DG Accessor",
});
return;
}
if (
!validateSettingValue({
schema: DiscourseNodeSchema,
keys,
value,
context: "Discourse Node",
})
) {
return;
}
let pageUid = nodeType;
let blockProps = getBlockPropsByUid(pageUid, []);
if (!blockProps || Object.keys(blockProps).length === 0) {
const lookedUpUid = getPageUidByPageTitle(
`${DISCOURSE_NODE_PAGE_PREFIX}${nodeType}`,
);
if (lookedUpUid) {
pageUid = lookedUpUid;
blockProps = getBlockPropsByUid(pageUid, []);
}
}
if (!blockProps || Object.keys(blockProps).length === 0) {
internalError({
error: `setDiscourseNodeSetting - could not find page for: ${nodeType}`,
type: "DG Accessor",
});
return;
}
setBlockPropAtPath(pageUid, keys, value);
};
/**
* Migrate known legacy block prop shapes to the current schema.
*
* - specification: Condition[] → {enabled, query: {conditions, ...}}
* - specification: {enabled, query: Condition[]} → {enabled, query: {conditions, ...}}
* - suggestiveRules.isFirstChild: {uid, value} → boolean
*/
const migrateNodeBlockProps = (
props: Record<string, json>,
): Record<string, json> => {
const migrated = { ...props };
if (Array.isArray(migrated.specification)) {
migrated.specification = {
enabled: migrated.specification.length > 0,
query: {
conditions: migrated.specification,
selections: [],
custom: "",
returnNode: "node",
},
};
} else if (
typeof migrated.specification === "object" &&
migrated.specification !== null &&
"query" in migrated.specification &&
Array.isArray((migrated.specification as Record<string, json>).query)
) {
const spec = migrated.specification as Record<string, json>;
migrated.specification = {
enabled:
typeof spec.enabled === "boolean"
? spec.enabled
: (spec.query as json[]).length > 0,
query: {
conditions: spec.query,
selections: [],
custom: "",
returnNode: "node",
},
};
}
if (
typeof migrated.suggestiveRules === "object" &&
migrated.suggestiveRules !== null &&
!Array.isArray(migrated.suggestiveRules)
) {
const rules = migrated.suggestiveRules as Record<string, json>;
const ifc = rules.isFirstChild;
if (typeof ifc === "object" && ifc !== null && !Array.isArray(ifc)) {
migrated.suggestiveRules = {
...rules,
isFirstChild: (ifc as Record<string, json>).value ?? false,
};
}
}
return migrated;
};
export const getAllDiscourseNodes = (): DiscourseNodeSettings[] => {
const results = window.roamAlphaAPI.data.fast.q(`
[:find ?uid ?title (pull ?page [:block/props])
:where
[?page :node/title ?title]
[?page :block/uid ?uid]
[(clojure.string/starts-with? ?title "${DISCOURSE_NODE_PAGE_PREFIX}")]]
`) as [string, string, Record<string, json> | null][];
const nodes: DiscourseNodeSettings[] = [];
for (const [pageUid, title, rawProps] of results) {
if (typeof pageUid !== "string" || typeof title !== "string") continue;
const rawBlockProps = rawProps?.[":block/props"];
const blockProps = rawBlockProps
? normalizeProps(rawBlockProps)
: undefined;
if (
!blockProps ||
!isRecord(blockProps) ||
Object.keys(blockProps).length === 0
)
continue;
const nodeText = title.replace(DISCOURSE_NODE_PAGE_PREFIX, "");
const result = DiscourseNodeSchema.safeParse(blockProps);
if (result.success) {
nodes.push({ ...result.data, type: pageUid, text: nodeText });
} else {
// Try migrating legacy field shapes before dropping the node.
const migrated = migrateNodeBlockProps(
blockProps as Record<string, json>,
);
const retryResult = DiscourseNodeSchema.safeParse(migrated);
if (retryResult.success) {
setBlockProps(pageUid, retryResult.data, false);
nodes.push({ ...retryResult.data, type: pageUid, text: nodeText });
} else {
internalError({
error: retryResult.error,
type: "DG Discourse Node Parse",
context: { pageUid, title },
sendEmail: false,
});
}
}
}
return nodes;
};