dsh-inline-link-preview 0.0.0-stage → 0.5.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/title.js ADDED
@@ -0,0 +1,183 @@
1
+ // Static HTML only. The result is a plain-text label, never trusted HTML.
2
+ const MAX_HTML = 1024 * 1024 // UTF-16 units; the transport also bounds the response bytes
3
+ const MAX_TITLE = 200
4
+ const space = c => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f'
5
+
6
+ const named = new Map(Object.entries({
7
+ amp: '&', AMP: '&', lt: '<', LT: '<', gt: '>', GT: '>', quot: '"', QUOT: '"', apos: "'",
8
+ nbsp: ' ', ensp: ' ', emsp: ' ', thinsp: ' ', ndash: '–', mdash: '—', hellip: '…',
9
+ lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”', laquo: '«', raquo: '»', middot: '·',
10
+ bull: '•', copy: '©', reg: '®', trade: '™', times: '×', divide: '÷', euro: '€',
11
+ pound: '£', yen: '¥', cent: '¢', deg: '°', eacute: 'é', Eacute: 'É',
12
+ lrm: '', rlm: '', shy: '', zwj: '\u200d', zwnj: '\u200c',
13
+ }))
14
+
15
+ function plain(raw) {
16
+ const text = raw.replace(/&#(?:x([\da-f]+)|(\d+));?|&([a-z][a-z\d]{0,31});|&(amp|quot|lt|gt|nbsp)(?![a-z\d=;])/gi,
17
+ (whole, hex, decimal, name, legacy) => {
18
+ if (name || legacy) return named.get(name || legacy) ?? whole
19
+ const n = hex ? Number.parseInt(hex, 16) : Number(decimal)
20
+ return n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : '\ufffd'
21
+ })
22
+ return text.replace(/[\u0000-\u0008\u000e-\u001f\u007f-\u009f\p{Bidi_Control}\p{Cs}\u00ad\u200b\u2060-\u206f\ufffc]/gu, '')
23
+ .replace(/\s+/gu, ' ').trim()
24
+ }
25
+
26
+ // Match status phrases, not keywords: a real issue titled “Fix sign-in error” is useful.
27
+ const statusTitles = new Set([
28
+ 'just a moment', 'attention required', 'one more step', 'captcha', 'robot check',
29
+ 'access denied', 'access forbidden', 'forbidden', 'unauthorized', 'unauthorised', 'not found',
30
+ 'page not found', 'site not found', 'repository not found', 'repository access blocked',
31
+ 'error', 'bad gateway', 'internal server error', 'service unavailable', 'too many requests',
32
+ 'something went wrong', 'authentication required', 'login required', 'sign in required',
33
+ '登录', '登陆', '请先登录', '请登录', '安全验证', '人机验证', '验证码', '访问受限', '拒绝访问', '页面不存在', '出错了',
34
+ ])
35
+ const statusPatterns = [
36
+ /^(?:sign[ -]?in|log[ -]?in)(?: to .+)?$/i, /^please (?:log|sign) in(?: .+)?$/i,
37
+ /^(?:checking|verifying) your browser(?: .+)?$/i, /^are you (?:a )?(?:human|robot)$/i,
38
+ /^(?:please )?(?:verify|confirm)(?: that)? you(?: are|'re) (?:a )?human$/i,
39
+ /^(?:security|human|captcha) (?:check|verification|challenge)$/i,
40
+ /^(?:(?:http(?: error)?|error)\s*)?[45]\d\d(?:[ :.\-–—]+(?:error|page not found|not found|forbidden|unauthorized|bad gateway|internal server error|service unavailable|too many requests))?$/i,
41
+ ]
42
+ const wechatNotices = [
43
+ /^(?:(?:当前|访问)?环境异常|(?:访问|操作)(?:过于)?频繁|系统繁忙|请(?:进行|完成)?(?:安全)?验证)(?:$|[,,。!!::]|后继续)/u,
44
+ /^请在微信(?:客户端)?(?:中)?打开(?:$|此链接|该链接|链接)/u,
45
+ /^(?:该|此|本)?(?:文章|内容|链接|页面)(?:已被(?:发布者|作者|用户)?删除|已删除|不存在|已过期|暂(?:时)?不(?:可见|可访问|能查看)|无法(?:访问|查看)|因违规无法查看|已被(?:作者)?(?:设置为|设为)(?:仅自己可见|不可见))/u,
46
+ /^(?:发布者|作者)已删除(?:该|此)?(?:文章|内容)/u,
47
+ ]
48
+ const wechatNotice = text => wechatNotices.some(re => re.test(text))
49
+ const generic = /^(?:home|homepage|index(?:\.html?)?|untitled(?: (?:page|document))?|loading|redirecting|please wait|首页|无标题|加载中|正在加载)$/i
50
+ const wechatBrand = /^(?:微信公众平台|公众号|微信公众号(?:平台)?|微信|weixin|wechat|(?:wechat|weixin) official accounts? platform)$/iu
51
+ const githubBrand = /^github(?:\.com)?$/i
52
+
53
+ function label(raw, kind) {
54
+ const text = plain(raw)
55
+ // Bound all phrase/segment matching, independent of the size of an attribute or title.
56
+ const sample = text.slice(0, 1000)
57
+ const parts = sample.split(/\s+[-·—–]\s+|[||]/u).map(s => s.trim().replace(/[.!?…。!?]+$/u, '').toLowerCase())
58
+ const gate = parts.some(s => statusTitles.has(s) || statusPatterns.some(re => re.test(s)) || (kind === 'wechat' && wechatNotice(s)))
59
+ const empty = parts.every(s => !s || generic.test(s) || (kind === 'wechat' && wechatBrand.test(s)) || (kind === 'github' && githubBrand.test(s)))
60
+ if (gate || empty || !/[^\s\p{P}\ufffd]/u.test(sample)) return { gate, text: '' }
61
+ if (text.length <= MAX_TITLE) return { gate, text }
62
+ return { gate, text: text.slice(0, MAX_TITLE - 1).replace(/[\ud800-\udbff]$/, '').trimEnd() + '…' }
63
+ }
64
+
65
+ // Scan forward once, including through quoted attributes with embedded '>'. This is a
66
+ // metadata reader, not a browser tree builder: an incomplete tag never becomes evidence.
67
+ const tagName = /<(\/?)([a-z][^\t\n\f\r />]*)/iy
68
+ function tagAt(html, at) {
69
+ tagName.lastIndex = at
70
+ const match = tagName.exec(html)
71
+ if (!match) return null
72
+ const name = match[2].toLowerCase(), closing = !!match[1]
73
+ const attrs = Object.create(null)
74
+ let i = tagName.lastIndex, selfClosing = false
75
+ while (i < html.length) {
76
+ const c = html[i++]
77
+ if (c === '>') return { name, closing, attrs, selfClosing, end: i }
78
+ if (space(c)) continue
79
+ if (c === '/') { selfClosing = html[i] === '>'; continue }
80
+ const start = i - 1
81
+ while (i < html.length && !space(html[i]) && html[i] !== '/' && html[i] !== '=' && html[i] !== '>') i++
82
+ const key = html.slice(start, i).toLowerCase()
83
+ while (space(html[i])) i++
84
+ let value = ''
85
+ if (html[i] === '=') {
86
+ i++
87
+ while (space(html[i])) i++
88
+ const q = html[i]
89
+ if (q === '"' || q === "'") {
90
+ const end = html.indexOf(q, ++i)
91
+ if (end < 0) break
92
+ value = html.slice(i, end)
93
+ i = end + 1
94
+ } else {
95
+ const begin = i
96
+ while (i < html.length && !space(html[i]) && html[i] !== '>') i++
97
+ value = html.slice(begin, i)
98
+ }
99
+ }
100
+ if ((key === 'id' || key === 'property' || key === 'name' || key === 'content') && attrs[key] === undefined) attrs[key] = value
101
+ }
102
+ return { incomplete: true }
103
+ }
104
+
105
+ const rawEnd = new Map('script style title textarea noscript iframe xmp noembed noframes'.split(' ')
106
+ .map(name => [name, new RegExp(`</${name}(?=[\\t\\n\\f\\r />])`, 'ig')]))
107
+ const inert = new Set(['template', 'svg', 'math'])
108
+
109
+ function* pageParts(html) {
110
+ const hidden = []
111
+ const commentEnd = /--!?>/g
112
+ let i = 0
113
+ while (i < html.length) {
114
+ const at = html.indexOf('<', i)
115
+ if (at !== i && !hidden.length) yield html.slice(i, at < 0 ? html.length : at)
116
+ if (at < 0) break
117
+ if (html.startsWith('<!--', at)) {
118
+ commentEnd.lastIndex = at + 4
119
+ if (!commentEnd.test(html)) break
120
+ i = commentEnd.lastIndex
121
+ continue
122
+ }
123
+ if (html.startsWith('<!', at) || html.startsWith('<?', at)) {
124
+ const end = html.indexOf('>', at + 2)
125
+ if (end < 0) break
126
+ i = end + 1
127
+ continue
128
+ }
129
+ const tag = tagAt(html, at)
130
+ if (!tag) { if (!hidden.length) yield '<'; i = at + 1; continue }
131
+ if (tag.incomplete) break
132
+ i = tag.end
133
+ if (tag.name === 'plaintext' && !tag.closing) break
134
+ const end = rawEnd.get(tag.name)
135
+ if (end && !tag.closing) {
136
+ end.lastIndex = i
137
+ const match = end.exec(html)
138
+ if (!match) break
139
+ const close = tagAt(html, match.index)
140
+ if (close.incomplete) break
141
+ if (tag.name === 'title' && !hidden.length) yield { ...tag, title: html.slice(i, match.index) }
142
+ i = close.end
143
+ } else if (inert.has(tag.name)) {
144
+ if (tag.closing) { if (hidden.at(-1) === tag.name) hidden.pop() }
145
+ else if (!tag.selfClosing || tag.name === 'template') hidden.push(tag.name)
146
+ } else if (!hidden.length) yield tag
147
+ }
148
+ }
149
+
150
+ /** Extract only static page metadata (or the WeChat article heading) from a fetched HTML prefix. */
151
+ export function extractPageTitle(html, kind) {
152
+ if (typeof html !== 'string' || !['github', 'wechat', 'web'].includes(kind)) return ''
153
+ let og = '', document = '', article = '', heading = null
154
+ for (const part of pageParts(html.slice(0, MAX_HTML))) {
155
+ if (typeof part === 'string') {
156
+ if (heading) heading.chunks.push(part)
157
+ // WeChat can serve a 200 response with a short, visible removal/verification notice.
158
+ // Match only short visible text nodes, not script templates or arbitrary page source.
159
+ else if (kind === 'wechat' && part.length <= 1024 && wechatNotice(plain(part))) return ''
160
+ continue
161
+ }
162
+ const { name, attrs, closing } = part
163
+ if (!closing && name === 'title') {
164
+ const result = label(part.title, kind)
165
+ if (result.gate) return '' // don't trust stale OG metadata on a sign-in/error page
166
+ document ||= result.text
167
+ } else if (!closing && name === 'meta' && [attrs.property, attrs.name].some(x => x?.trim().toLowerCase() === 'og:title')) {
168
+ const result = label(attrs.content ?? '', kind)
169
+ if (result.gate) return ''
170
+ og ||= result.text
171
+ } else if (!closing && name === 'form' && attrs.id === 'challenge-form') return ''
172
+ else if (name === 'h1' || (kind === 'wechat' && name === 'h2')) {
173
+ if (!closing) heading = { name, article: kind === 'wechat' && attrs.id?.trim() === 'activity-name', chunks: [] }
174
+ else if (heading?.name === name) {
175
+ const result = label(heading.chunks.join(''), kind)
176
+ if (result.gate) return ''
177
+ if (heading.article) article ||= result.text
178
+ heading = null
179
+ }
180
+ } else if (heading && name === 'br' && !closing) heading.chunks.push(' ')
181
+ }
182
+ return article || og || document
183
+ }