-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathextractMeta.js
More file actions
29 lines (27 loc) · 888 Bytes
/
extractMeta.js
File metadata and controls
29 lines (27 loc) · 888 Bytes
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
import { debug } from './debug.js';
const regex = /\B\/\/ ==UserScript==\r?\n([\S\s]*?)\r?\n\/\/ ==\/UserScript==/;
export default function extractMeta(text = '') {
try {
const [, rawMeta] = text.match(regex);
const meta = rawMeta ? rawMeta.split(/[\r\n]/) : [];
if (!Array.isArray(meta)) throw new Error('Invalid meta block');
return meta.reduce((acc, line) => {
if (!line) return acc;
const [key, ...rest] = line.replace(/\/\/ @/, '').trim().split(/\s+/);
const value = rest.join(' ');
const current = acc[key];
if (current === undefined) {
acc[key] = value;
} else if (!Array.isArray(current)) {
acc[key] = [current, value];
} else {
current.push(value);
}
return acc;
}, {});
} catch (err) {
console.error(err);
debug(err, 'debugging.extractMeta');
return null;
}
}