-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
443 lines (389 loc) · 17.8 KB
/
index.ts
File metadata and controls
443 lines (389 loc) · 17.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
import { AdminForthPlugin, AdminForthResource, IAdminForth, Filters, AdminUser} from "adminforth";
import { PluginOptions } from "./types.js";
export default class MarkdownPlugin extends AdminForthPlugin {
options: PluginOptions;
resourceConfig!: AdminForthResource;
adminforth!: IAdminForth;
uploadPlugin: AdminForthPlugin;
attachmentResource: AdminForthResource = undefined;
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
}
instanceUniqueRepresentation(pluginOptions: any): string {
return pluginOptions.fieldName;
}
// Placeholder for future Upload Plugin API integration.
// For now, treat all extracted URLs as plugin-owned public URLs.
isPluginPublicUrl(_url: string): boolean {
// todo: here we need to check that host name is same as upload plugin, probably create upload plugin endpoint
// should handle cases that user might define custom preview url
// and that local storage has no host name, here, the fact of luck of hostname might be used as
return true;
}
validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
this.adminforth = adminforth;
const column = resourceConfig.columns.find(c => c.name === this.options.fieldName);
if (!column) {
throw new Error(`Column ${this.options.fieldName} not found in resource ${resourceConfig.label}`);
}
const validDataTypes = ['string', 'text', 'richtext'];
if (!validDataTypes.includes(column.type)) {
throw new Error(`Column ${this.options.fieldName} must be of type 'string', 'text' or 'richtext'.`);
}
}
async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);
this.resourceConfig = resourceConfig;
const fieldName = this.options.fieldName;
const column = resourceConfig.columns.find(c => c.name === fieldName);
if (!column) {
throw new Error(`Column ${fieldName} not found in resource ${resourceConfig.label}`);
}
if (!column.components) {
column.components = {};
}
if (this.options.attachments) {
const resource = await adminforth.config.resources.find(r => r.resourceId === this.options.attachments!.attachmentResource);
if (!resource) {
throw new Error(`Resource '${this.options.attachments!.attachmentResource}' not found`);
}
this.attachmentResource = resource;
const field = await resource.columns.find(c => c.name === this.options.attachments!.attachmentFieldName);
if (!field) {
throw new Error(`Field '${this.options.attachments!.attachmentFieldName}' not found in resource '${this.options.attachments!.attachmentResource}'`);
}
if (this.options.attachments.attachmentTitleFieldName) {
const titleField = await resource.columns.find(c => c.name === this.options.attachments!.attachmentTitleFieldName);
if (!titleField) {
throw new Error(`Field '${this.options.attachments!.attachmentTitleFieldName}' not found in resource '${this.options.attachments!.attachmentResource}'`);
}
}
if (this.options.attachments.attachmentAltFieldName) {
const altField = await resource.columns.find(c => c.name === this.options.attachments!.attachmentAltFieldName);
if (!altField) {
throw new Error(`Field '${this.options.attachments!.attachmentAltFieldName}' not found in resource '${this.options.attachments!.attachmentResource}'`);
}
}
const plugin = await adminforth.activatedPlugins.find(p =>
p.resourceConfig!.resourceId === this.options.attachments!.attachmentResource &&
p.pluginOptions.pathColumnName === this.options.attachments!.attachmentFieldName
);
if (!plugin) {
throw new Error(`${plugin} Plugin for attachment field '${this.options.attachments!.attachmentFieldName}' not found in resource '${this.options.attachments!.attachmentResource}', please check if Upload Plugin is installed on the field ${this.options.attachments!.attachmentFieldName}`);
}
if (!plugin.pluginOptions.storageAdapter.objectCanBeAccesedPublicly()) {
throw new Error(`Upload Plugin for attachment field '${this.options.attachments!.attachmentFieldName}' in resource '${this.options.attachments!.attachmentResource}'
uses adapter which is not configured to store objects in public way, so it will produce only signed private URLs which can not be used in HTML text of blog posts.
Please configure adapter in such way that it will store objects publicly (e.g. for S3 use 'public-read' ACL).
`);
}
this.uploadPlugin = plugin as AdminForthPlugin;
}
column.components.show = {
file: this.componentPath("MarkdownRenderer.vue"),
meta: {
pluginInstanceId: this.pluginInstanceId,
columnName: fieldName,
},
};
column.components.list = {
file: this.componentPath("MarkdownRenderer.vue"),
meta: {
pluginInstanceId: this.pluginInstanceId,
columnName: fieldName,
},
};
column.components.edit = {
file: this.componentPath("MarkdownEditor.vue"),
meta: {
pluginInstanceId: this.pluginInstanceId,
columnName: fieldName,
uploadPluginInstanceId: this.uploadPlugin?.pluginInstanceId,
},
};
column.components.create = {
file: this.componentPath("MarkdownEditor.vue"),
meta: {
pluginInstanceId: this.pluginInstanceId,
columnName: fieldName,
uploadPluginInstanceId: this.uploadPlugin?.pluginInstanceId,
},
};
const editorRecordPkField = resourceConfig.columns.find(c => c.primaryKey);
if (this.options.attachments) {
type AttachmentMeta = { key: string; alt: string | null; title: string | null };
const stripQueryAndHash = (value: string) => value.split('#')[0].split('?')[0];
const extractKeyFromUrl = (url: string) => {
// Supports absolute https/http URLs and protocol-relative URLs.
// Returns the object key as a path without leading slashes.
try {
const normalized = url.startsWith('//') ? `https:${url}` : url;
const u = new URL(normalized);
return u.pathname.replace(/^\/+/, '');
} catch {
// Fallback: strip scheme/host if it looks like a URL, otherwise treat as a path.
return stripQueryAndHash(url).replace(/^https?:\/\/[^\/]+\/+/, '').replace(/^\/+/, '');
}
};
const shouldTrackUrl = (url: string) => {
try {
return this.isPluginPublicUrl(url);
} catch (err) {
console.error('Error checking URL ownership', url, err);
return false;
}
};
const getKeyFromTrackedUrl = (rawUrl: string): string | null => {
const srcTrimmed = rawUrl.trim().replace(/^<|>$/g, '');
if (!srcTrimmed || srcTrimmed.startsWith('data:') || srcTrimmed.startsWith('javascript:')) {
return null;
}
if (!shouldTrackUrl(srcTrimmed)) {
return null;
}
const srcNoQuery = stripQueryAndHash(srcTrimmed);
const key = extractKeyFromUrl(srcNoQuery);
if (!key) {
return null;
}
return key;
};
const upsertMeta = (
byKey: Map<string, AttachmentMeta>,
key: string,
next: { alt?: string | null; title?: string | null }
) => {
const existing = byKey.get(key);
if (!existing) {
byKey.set(key, {
key,
alt: next.alt ?? null,
title: next.title ?? null,
});
return;
}
if ((existing.alt === null || existing.alt === '') && next.alt !== undefined && next.alt !== null) {
existing.alt = next.alt;
}
if ((existing.title === null || existing.title === '') && next.title !== undefined && next.title !== null) {
existing.title = next.title;
}
};
const normalizeAttachmentTitleForDb = (title: string | null): string | null => {
// we can llow to use [xx] in titles, for some meta classes - so they will nto go to attachment titles, but will be available in the ending markdown
if (title === null) {
return null;
}
const cleaned = title
.replace(/\s*(?:\([^()]*\)|\[[^\[\]]*\])\s*$/, '')
.trim();
return cleaned || null;
};
function getAttachmentMetas(markdown: string): AttachmentMeta[] {
if (!markdown) {
return [];
}
// Markdown image syntax:  or  or 
const imageRegex = /!\[([^\]]*)\]\(\s*([^\s)]+)\s*(?:\s+(?:\"([^\"]*)\"|'([^']*)'))?\s*\)/g;
// HTML embedded media links.
const htmlSrcRegex = /<(?:source|video)\b[^>]*\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s"'=<>`]+))[^>]*>/gi;
const byKey = new Map<string, AttachmentMeta>();
for (const match of markdown.matchAll(imageRegex)) {
const altRaw = match[1] ?? '';
const srcRaw = match[2];
const titleRaw = normalizeAttachmentTitleForDb((match[3] ?? match[4]) ?? null);
const key = getKeyFromTrackedUrl(srcRaw);
if (!key) {
continue;
}
upsertMeta(byKey, key, {
alt: altRaw,
title: titleRaw,
});
}
let srcMatch: RegExpExecArray | null;
while ((srcMatch = htmlSrcRegex.exec(markdown)) !== null) {
const srcRaw = srcMatch[1] ?? srcMatch[2] ?? srcMatch[3] ?? '';
const key = getKeyFromTrackedUrl(srcRaw);
if (!key) {
continue;
}
upsertMeta(byKey, key, {});
}
return [...byKey.values()];
}
const createAttachmentRecords = async (
adminforth: IAdminForth,
options: PluginOptions,
recordId: any,
metas: AttachmentMeta[],
adminUser: AdminUser
) => {
if (!metas.length) {
return;
}
process.env.HEAVY_DEBUG && console.log('📸 Creating attachment records', JSON.stringify(recordId))
try {
await Promise.all(metas.map(async (meta) => {
try {
const recordToCreate: any = {
[options.attachments.attachmentFieldName]: meta.key,
[options.attachments.attachmentRecordIdFieldName]: recordId,
[options.attachments.attachmentResourceIdFieldName]: resourceConfig.resourceId,
};
if (options.attachments.attachmentTitleFieldName) {
recordToCreate[options.attachments.attachmentTitleFieldName] = meta.title;
}
if (options.attachments.attachmentAltFieldName) {
recordToCreate[options.attachments.attachmentAltFieldName] = meta.alt;
}
await adminforth.createResourceRecord({
resource: this.attachmentResource,
record: recordToCreate,
adminUser,
});
} catch (err) {
console.error('Error creating record for', meta.key, err);
}
}));
} catch (err) {
console.error('Error in Promise.all', err);
}
}
const deleteAttachmentRecords = async (
adminforth: IAdminForth,
options: PluginOptions,
recordId: any,
keys: string[],
adminUser: AdminUser
) => {
if (!keys.length) {
return;
}
const attachmentPrimaryKeyField = this.attachmentResource.columns.find(c => c.primaryKey);
const attachments = await adminforth.resource(options.attachments.attachmentResource).list([
Filters.EQ(options.attachments.attachmentRecordIdFieldName, recordId),
Filters.EQ(options.attachments.attachmentResourceIdFieldName, resourceConfig.resourceId),
Filters.IN(options.attachments.attachmentFieldName, keys),
]);
await Promise.all(attachments.map(async (a: any) => {
await adminforth.deleteResourceRecord({
resource: this.attachmentResource,
recordId: a[attachmentPrimaryKeyField.name],
adminUser,
record: a,
})
}))
}
const updateAttachmentRecordsMetadata = async (
adminforth: IAdminForth,
options: PluginOptions,
recordId: any,
metas: AttachmentMeta[],
adminUser: AdminUser
) => {
if (!metas.length) {
return;
}
if (!options.attachments.attachmentTitleFieldName && !options.attachments.attachmentAltFieldName) {
return;
}
const attachmentPrimaryKeyField = this.attachmentResource.columns.find(c => c.primaryKey);
const metaByKey = new Map(metas.map(m => [m.key, m] as const));
const existingAparts = await adminforth.resource(options.attachments.attachmentResource).list([
Filters.EQ(options.attachments.attachmentRecordIdFieldName, recordId),
Filters.EQ(options.attachments.attachmentResourceIdFieldName, resourceConfig.resourceId)
]);
await Promise.all(existingAparts.map(async (a: any) => {
const key = a[options.attachments.attachmentFieldName];
const meta = metaByKey.get(key);
if (!meta) {
return;
}
const patch: any = {};
if (options.attachments.attachmentTitleFieldName) {
const field = options.attachments.attachmentTitleFieldName;
if ((a[field] ?? null) !== (meta.title ?? null)) {
patch[field] = meta.title;
}
}
if (options.attachments.attachmentAltFieldName) {
const field = options.attachments.attachmentAltFieldName;
if ((a[field] ?? null) !== (meta.alt ?? null)) {
patch[field] = meta.alt;
}
}
if (!Object.keys(patch).length) {
return;
}
await adminforth.updateResourceRecord({
resource: this.attachmentResource,
recordId: a[attachmentPrimaryKeyField.name],
record: patch,
oldRecord: a,
adminUser,
});
}));
}
(resourceConfig.hooks.create.afterSave).push(async ({ record, adminUser }: { record: any, adminUser: AdminUser }) => {
// find all s3Paths in the html
const metas = getAttachmentMetas(record[this.options.fieldName]);
const keys = metas.map(m => m.key);
process.env.HEAVY_DEBUG && console.log('📸 Found attachment keys', keys);
// create attachment records
await createAttachmentRecords(
adminforth, this.options, record[editorRecordPkField.name], metas, adminUser);
return { ok: true };
});
// after edit we need to delete attachments that are not in the html anymore
// and add new ones
(resourceConfig.hooks.edit.afterSave).push(
async ({ recordId, record, adminUser }: { recordId: any, record: any, adminUser: AdminUser }) => {
process.env.HEAVY_DEBUG && console.log('âš“ Cought hook', recordId, 'rec', record);
if (record[this.options.fieldName] === undefined) {
console.log('âš“ Cought hook', recordId, 'rec', record);
// field was not changed, do nothing
return { ok: true };
}
const existingAparts = await adminforth.resource(this.options.attachments.attachmentResource).list([
Filters.EQ(this.options.attachments.attachmentRecordIdFieldName, recordId),
Filters.EQ(this.options.attachments.attachmentResourceIdFieldName, resourceConfig.resourceId)
]);
const existingKeys = existingAparts.map((a: any) => a[this.options.attachments.attachmentFieldName]);
const metas = getAttachmentMetas(record[this.options.fieldName]);
const newKeys = metas.map(m => m.key);
process.env.HEAVY_DEBUG && console.log('📸 Existing keys (from db)', existingKeys)
process.env.HEAVY_DEBUG && console.log('📸 Found new keys (from text)', newKeys);
const toDelete = existingKeys.filter(key => !newKeys.includes(key));
const toAdd = newKeys.filter(key => !existingKeys.includes(key));
process.env.HEAVY_DEBUG && console.log('📸 Found keys to delete', toDelete)
process.env.HEAVY_DEBUG && console.log('📸 Found keys to add', toAdd);
const metasToAdd = metas.filter(m => toAdd.includes(m.key));
await Promise.all([
deleteAttachmentRecords(adminforth, this.options, recordId, toDelete, adminUser),
createAttachmentRecords(adminforth, this.options, recordId, metasToAdd, adminUser)
]);
// Keep alt/title in sync for existing attachments too
await updateAttachmentRecordsMetadata(adminforth, this.options, recordId, metas, adminUser);
return { ok: true };
}
);
// after delete we need to delete all attachments
(resourceConfig.hooks.delete.afterSave).push(
async ({ record, adminUser }: { record: any, adminUser: AdminUser }) => {
const existingAparts = await adminforth.resource(this.options.attachments.attachmentResource).list(
[
Filters.EQ(this.options.attachments.attachmentRecordIdFieldName, record[editorRecordPkField.name]),
Filters.EQ(this.options.attachments.attachmentResourceIdFieldName, resourceConfig.resourceId)
]
);
const existingKeys = existingAparts.map((a: any) => a[this.options.attachments.attachmentFieldName]);
process.env.HEAVY_DEBUG && console.log('📸 Found keys to delete', existingKeys);
await deleteAttachmentRecords(adminforth, this.options, record[editorRecordPkField.name], existingKeys, adminUser);
return { ok: true };
}
);
}
}
}