Files: 7cbc5c587105a7add08d250458303c47bcd0e57a / lib / util.js
2366 bytesRaw
1 | var pull = require('pull-stream') |
2 | var cat = require('pull-cat') |
3 | var h = require('hyperscript') |
4 | var u = exports |
5 | |
6 | u.ssbRefRegex = /((?:@|%|&|ssb:\/\/%)[A-Za-z0-9\/+]{43}=\.[\w\d]+)/g |
7 | |
8 | u.isRef = function (str) { |
9 | u.ssbRefRegex.lastIndex = 0 |
10 | return u.ssbRefRegex.test(str) |
11 | } |
12 | |
13 | u.readNext = function (fn) { |
14 | var next |
15 | return function (end, cb) { |
16 | if (next) return next(end, cb) |
17 | fn(function (err, _next) { |
18 | if (err) return cb(err) |
19 | next = _next |
20 | next(null, cb) |
21 | }) |
22 | } |
23 | } |
24 | |
25 | u.pullReverse = function () { |
26 | return function (read) { |
27 | return u.readNext(function (cb) { |
28 | pull(read, pull.collect(function (err, items) { |
29 | cb(err, items && pull.values(items.reverse())) |
30 | })) |
31 | }) |
32 | } |
33 | } |
34 | |
35 | u.toHTML = function (el) { |
36 | if (!el) return '' |
37 | if (typeof el === 'string' || Array.isArray(el)) { |
38 | return h('div', el).innerHTML |
39 | } |
40 | var html = el.outerHTML || String(el) |
41 | if (el.nodeName === 'html') html = '<!doctype html>' + html + '\n' |
42 | return html |
43 | } |
44 | |
45 | u.hyperwrap = function (fn) { |
46 | var token = '__HYPERWRAP_' + Math.random() + '__' |
47 | return function (read) { |
48 | return u.readNext(function (cb) { |
49 | fn(token, function (err, el) { |
50 | if (err) return cb(err) |
51 | var parts = u.toHTML(el).split(token) |
52 | switch (parts.length) { |
53 | case 0: return cb(null, pull.empty()) |
54 | case 1: return cb(null, pull.once(parts[0])) |
55 | case 2: return cb(null, |
56 | cat([pull.once(parts[0]), read, pull.once(parts[1])])) |
57 | default: return cb(new Error('duplicate wrap')) |
58 | } |
59 | }) |
60 | }) |
61 | } |
62 | } |
63 | |
64 | u.linkDest = function (link) { |
65 | return typeof link === 'string' ? link : link && link.link || link |
66 | } |
67 | |
68 | u.toArray = function (x) { |
69 | return !x ? [] : Array.isArray(x) ? x : [x] |
70 | } |
71 | |
72 | u.fromArray = function (arr) { |
73 | return Array.isArray(arr) && arr.length === 1 ? arr[0] : arr |
74 | } |
75 | |
76 | u.renderError = function(err) { |
77 | return h('div.error', |
78 | h('h3', err.name), |
79 | h('pre', err.stack)) |
80 | } |
81 | |
82 | u.pullLength = function (cb) { |
83 | var len = 0 |
84 | return pull.through(function (data) { |
85 | len += data.length |
86 | }, function (err) { |
87 | cb(err, len) |
88 | }) |
89 | } |
90 | |
91 | u.tryDecodeJSON = function (json) { |
92 | try { |
93 | return JSON.parse(json) |
94 | } catch(e) { |
95 | return null |
96 | } |
97 | } |
98 | |
99 | u.extractFeedIds = function (str) { |
100 | var ids = [] |
101 | String(str).replace(u.ssbRefRegex, function (id) { |
102 | ids.push(id) |
103 | }) |
104 | return ids |
105 | } |
106 |
Built with git-ssb-web