domain-hound 0.1.2 → 0.1.4

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/results.mjs ADDED
@@ -0,0 +1,383 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdir, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
4
+ import { homedir, userInfo } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { canRecommend, defaultEndings, normalizeName } from './clis/domain-check/name-search.mjs';
8
+ import { shopSearchUrl, shops } from './clis/domain-check/prices.mjs';
9
+ import { safeLink } from './display.mjs';
10
+ import { receiptStyle } from './results-style.mjs';
11
+
12
+ const cash = value => Number.isFinite(value) ? '$' + value.toFixed(2) : null;
13
+ const escape = value => String(value ?? '').replace(/[&<>"']/g, char =>
14
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
15
+ const plain = value => String(value ?? '').replace(/[\r\n\p{Cc}\p{Cf}]+/gu, ' ').replace(/\s*[—–]\s*/g, '. ').trim();
16
+ const evidenceText = value => plain(value).replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
17
+ .replace(/https?:\/\/[^\s)]+/gi, '').replace(/[\[\]<>]/g, '').replace(/\s{2,}/g, ' ').trim();
18
+ const markdown = value => plain(value).replace(/[\\|<>\[\]`*]/g, '\\$&');
19
+ const shopIds = new Map(Object.entries(shops).map(([id, { name }]) => [name, id]));
20
+ const endingOf = value => value.split('.').at(-1);
21
+ const fallbackShop = ending => ending === 'no' ? 'dynadot' : ending === 'so' ? 'namecheap' : 'spaceship';
22
+ const markOf = row => row.competition?.US;
23
+ const marksText = row => {
24
+ const mark = markOf(row);
25
+ return 'US marks: ' + (typeof mark === 'string' ? evidenceText(mark) : mark == null ? 'not checked' : 'no match found');
26
+ };
27
+ const watchLink = domain => 'https://domainhound.dev/watch/?domain=' + encodeURIComponent(domain);
28
+ const verdictOrder = { 'No conflict found': 0, 'Check first': 1, Avoid: 2 };
29
+
30
+ function resultGroups(data) {
31
+ return data.names.map((row, index) => {
32
+ const detail = data.receiptDetails?.[index] ?? {};
33
+ const exact = row.name.includes('.');
34
+ const label = exact ? row.name : normalizeName(row.name);
35
+ const variants = [...(row.free ?? []), ...(row.taken ?? []), ...(row.shop_check ?? []), ...(row.resale ?? [])]
36
+ .map(value => value.d ?? value).filter(value => value.includes('.'));
37
+ const targets = exact ? [row.name] : [...new Set([...defaultEndings.map(ending => label + '.' + ending), ...variants])];
38
+ const records = targets.map(domain => {
39
+ const ending = endingOf(domain);
40
+ const lookupKey = domain === label + '.' + ending || exact ? ending : domain;
41
+ const match = list => list?.find(value => (value.d ?? value) === domain || (value.d ?? value) === lookupKey);
42
+ const option = match(row.free);
43
+ const raw = detail.endings?.find(item => item.domain === domain);
44
+ const confirmed = option?.s === 'ok';
45
+ const quote = confirmed ? option : { ...data.listPrices?.[ending], ...data.listPrices?.[domain],
46
+ ...data.prices?.[ending], ...row.own?.[ending], ...(typeof option === 'object' ? option : {}) };
47
+ const taken = Boolean(match(row.taken) || match(row.resale));
48
+ const reserved = Boolean(match(row.reserved));
49
+ const risk = Boolean(option?.risk || raw?.risk);
50
+ const premium = Boolean(match(row.premium) || option?.s === 'prem' || option?.prem || risk);
51
+ const includePrice = !reserved && (!premium || confirmed) && (!taken || exact);
52
+ const likely = match(row.likely_free) ? 'likely free by DNS' : match(row.likely_taken) ? 'likely taken by DNS' : null;
53
+ const state = taken ? 'taken' : premium ? 'premium' : option ? 'free' : 'check';
54
+ const status = taken ? (match(row.resale) ? 'Taken, possible resale' : 'Taken')
55
+ : reserved ? 'Not offered for registration' : confirmed ? 'Confirmed at shop'
56
+ : premium ? (risk ? 'May be premium, price at shop' : 'Premium, price at shop')
57
+ : option ? 'Free at the registry' : likely ? 'Check at shop, ' + likely : 'Check at shop';
58
+ const usd = includePrice ? { now: quote.now, renew: quote.renew, y3: quote.y3, term: quote.term,
59
+ jump: quote.jump, shop: quote.shop } : {};
60
+ const term = usd.term ?? 1;
61
+ const total = usd.y3 ?? (usd.now != null && usd.renew != null ? usd.now + (Math.ceil(3 / term) - 1) * usd.renew : null);
62
+ const source = ({ web: 'Live site', dns: 'DNS', rdap: 'Registry RDAP', whois: 'Registry WHOIS',
63
+ shop: 'Shop', list: 'Price list' })[raw?.source] ?? (confirmed ? 'Shop' : likely ? 'DNS' : 'Registry');
64
+ const shop = usd.shop ?? raw?.shop ?? shops[fallbackShop(ending)]?.name;
65
+ const eligible = canRecommend(ending, data.eligible);
66
+ const shopUrl = shopSearchUrl(shopIds.get(shop) ?? fallbackShop(ending), domain);
67
+ const checkout = taken || reserved || !eligible ? null : [raw?.checkout, shopUrl].find(url => safeLink(url, domain)) ?? null;
68
+ return { domain, ending, state, status, ...usd, total, shop, checkout, eligible, source,
69
+ priceLabel: usd.now != null || usd.renew != null ? (confirmed ? 'Shop quote' : taken ? 'Standard list price benchmark' : 'List price') : '',
70
+ checkedAt: raw?.checkedAt ?? data.checkedAt, priceAt: raw?.priceAt ?? option?.at ?? data.priceListDate,
71
+ site: raw?.site ?? detail.details?.sites?.[ending] ?? row.details?.sites?.[ending] };
72
+ });
73
+ records.sort((a, b) => Number(b.state === 'free' || b.priceLabel === 'Shop quote')
74
+ - Number(a.state === 'free' || a.priceLabel === 'Shop quote') || (a.now ?? Infinity) - (b.now ?? Infinity));
75
+ return { row: { ...row, ...detail, name: row.name }, records };
76
+ });
77
+ }
78
+
79
+ function offerText(offer, linked = false) {
80
+ const { domain, checkout, now, renew, term, jump, priceLabel } = offer;
81
+ const price = now != null ? cash(now) + (renew != null ? ', then ' + cash(renew) : ', renewal at shop')
82
+ : renew != null ? cash(renew) + ' renewal' : 'price at shop';
83
+ return (linked && checkout ? '[' + domain + '](' + checkout + ')' : domain) + ' ' + price
84
+ + (term > 1 ? ' every ' + term + ' years' : '') + (jump ? ' (renewal jumps)' : '')
85
+ + (priceLabel ? ' ' + priceLabel.toLowerCase() : '');
86
+ }
87
+
88
+ function appFinding(value) {
89
+ if (value == null) return 'check incomplete';
90
+ return Array.isArray(value) && !value.length ? 'no app with this name' : 'same-name app found';
91
+ }
92
+
93
+ function signals(group) {
94
+ const { row, records } = group;
95
+ const comp = row.competition ?? {};
96
+ const site = records.map(record => record.site).find(site => site?.state === 'live')?.host;
97
+ const states = records.map(record => typeof record.site === 'string' ? record.site : record.site?.state).filter(Boolean);
98
+ const checked = states.some(state => /^(?:live|parked|for.sale|no(?:-site| site found))/i.test(state));
99
+ const web = site ? 'live site at ' + plain(site) : states.some(state => /live/i.test(state)) ? 'live site'
100
+ : states.some(state => /parked|for sale|for-sale/i.test(state)) ? 'parked'
101
+ : row.traction?.domain ? 'rival listed at ' + plain(row.traction.domain)
102
+ : checked ? 'no live site found on checked endings' : 'not checked';
103
+ return 'iOS: ' + appFinding(comp.AppStore) + ' | Android: ' + appFinding(comp.GooglePlay) + ' | web: ' + web;
104
+ }
105
+
106
+ function summary(groups, args, triage) {
107
+ const [wanted] = groups;
108
+ const preferred = args.endings ?? [];
109
+ const budget = args.budget;
110
+ const isExact = !triage && groups.length === 1 && wanted.row.name.includes('.');
111
+ const constraints = [...(!isExact && preferred.length ? [preferred.map(ending => '.' + ending).join(', ') + ' first'] : []),
112
+ ...(budget != null ? ['Up to ' + cash(budget) + ' today'] : [])];
113
+ const inScope = record => record.eligible && (!preferred.length || preferred.includes(record.ending))
114
+ && (budget == null || (record.now ?? Infinity) <= budget);
115
+ const candidates = groups.flatMap(group => group.row.verdict === 'Avoid' ? [] : group.records
116
+ .filter(record => inScope(record) && (record.state === 'free' || record.priceLabel === 'Shop quote'))
117
+ .map(record => ({ group, record })));
118
+ const cost = item => item.record.now ?? Infinity;
119
+ const compareCost = (a, b) => cost(a) - cost(b);
120
+ const position = item => preferred.length ? preferred.indexOf(item.record.ending) : 0;
121
+ candidates.sort((a, b) => (verdictOrder[a.group.row.verdict] ?? 0) - (verdictOrder[b.group.row.verdict] ?? 0)
122
+ || position(a) - position(b) || compareCost(a, b) || a.record.domain.localeCompare(b.record.domain));
123
+ const best = candidates[0];
124
+ const picks = [...new Map(candidates.toReversed().map(item => [item.group, item])).values()].reverse().slice(0, 3);
125
+ const cheapest = candidates.filter(item => item.record.now != null).sort(compareCost)[0];
126
+ const value = candidates.filter(item => item.record.total != null)
127
+ .sort((a, b) => a.record.total - b.record.total || compareCost(a, b))[0];
128
+ const target = wanted.records.find(record => record.ending === (preferred[0] ?? 'com')) ?? wanted.records[0];
129
+ const watch = target?.state === 'taken' ? 'Want it anyway? [Watch ' + target.domain + '](' + watchLink(target.domain) + ').' : null;
130
+ if (isExact) {
131
+ const picked = wanted.records[0];
132
+ const hasPrice = picked.now != null || picked.renew != null;
133
+ let price = hasPrice ? ' ' + offerText(picked).slice(picked.domain.length + 1) + '.' : '';
134
+ if (picked.state === 'taken' && picked.renew != null) {
135
+ price = ' Standard list renewal: ' + cash(picked.renew) + (picked.term > 1
136
+ ? ' every ' + picked.term + ' years (' + cash(picked.renew / picked.term) + ' a year)' : ' a year') + '.';
137
+ }
138
+ const overBudget = budget != null && picked.now != null && picked.now > budget && picked.state !== 'taken';
139
+ const intro = picked.domain + ': ' + picked.status.toLowerCase() + '.' + price + (overBudget ? ' Over budget.' : '');
140
+ const step = overBudget ? 'Next: try a cheaper domain.' : picked.checkout
141
+ ? 'Next: [check at ' + plain(picked.shop) + '](' + picked.checkout + ').' : watch ?? 'Next: check another domain.';
142
+ return [...constraints, intro, ...(args.purchase ? ['Domain Hound cannot buy or complete checkout.'] : []), step];
143
+ }
144
+ const reason = evidenceText(wanted.row.reason).replace('David vs Goliath: ', 'Established rival: ');
145
+ const keep = triage ? 'Keep ' + evidenceText(wanted.row.name) + '? ' + plain(wanted.row.verdict) + '. '
146
+ + reason.replaceAll(' · ', '. ') + '.'
147
+ + (typeof markOf(wanted.row) === 'string' && reason.includes(markOf(wanted.row)) ? ' US trademark screen.' : ' ' + marksText(wanted.row) + '.')
148
+ + (wanted.row.verdict === 'Avoid' && best ? (best.group.row.verdict === 'No conflict found' ? ' Best free rename: ' : ' Next name to check: ')
149
+ + plain(best.group.row.name) + '.' : '')
150
+ + (picks.some(item => item.group === wanted) ? '' : ' | ' + signals(wanted)) : null;
151
+ const next = watch ?? (args.shortlist ? 'Next: screen the best names.' : best ? 'Next: check your pick at the shop.' : 'Next: try another name.');
152
+ const caution = item => item.group.row.verdict === 'Check first' ? ' (Check first)' : '';
153
+ const label = item => offerText(item.record, true) + caution(item);
154
+ const offerLines = picks.map(({ group, record }, index) =>
155
+ (budget != null && index === 0 ? 'Pick: ' : (index + 1) + '. ') + offerText(record) + ' (' + plain(record.status.toLowerCase()) + ') | '
156
+ + (triage ? plain(group.row.verdict) + ' | ' + marksText(group.row) + ' | ' : '') + signals(group));
157
+ const scope = constraints.length ? constraints.join(' | ') + '. ' : '';
158
+ const leadPick = scope && offerLines.length ? scope + offerLines.shift() : null;
159
+ const eligibility = args.eligible?.includes('no') || cheapest?.record.ending === 'no'
160
+ || value?.record.ending === 'no' || preferred.includes('no')
161
+ ? ' .no needs a Norwegian address and organization or personal ID.' : '';
162
+ const lines = [
163
+ leadPick || (scope ? scope + 'All endings are on the page.' : null),
164
+ keep,
165
+ ...offerLines,
166
+ 'Cheapest: ' + (cheapest ? label(cheapest) : 'none found in scope.'),
167
+ 'Best value: ' + (value ? value.record.domain + ', ' + cash(value.record.total) + ' in payments due in 3 years'
168
+ + caution(value) : 'needs a shop quote') + '.',
169
+ (args.purchase ? 'Domain Hound cannot buy or complete checkout. ' : '') + next + eligibility,
170
+ ];
171
+ return lines.filter(Boolean);
172
+ }
173
+
174
+ function httpsLink(value) {
175
+ if (typeof value !== 'string') return null;
176
+ try {
177
+ const url = new URL(value);
178
+ return url.protocol === 'https:' && !url.username && !url.password ? url.href : null;
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
183
+
184
+ function details(group) {
185
+ const { row } = group;
186
+ const comp = row.competition ?? {};
187
+ const titleAndLink = value => value && typeof value === 'object'
188
+ ? [plain(value.name ?? value.domain ?? value.title), httpsLink(value.url)] : [plain(value)];
189
+ const ios = Array.isArray(comp.AppStore) ? comp.AppStore : comp.AppStore ? [comp.AppStore] : [];
190
+ const android = Array.isArray(comp.GooglePlay) ? comp.GooglePlay : comp.GooglePlay ? [comp.GooglePlay] : [];
191
+ const matches = [
192
+ ['US marks: ' + (typeof markOf(row) === 'string' ? plain(markOf(row)) : markOf(row) == null ? 'check incomplete' : 'no match found'), httpsLink(comp.mark)],
193
+ ...ios.map(value => ['iOS: ' + titleAndLink(value)[0], titleAndLink(value)[1]]),
194
+ ...android.map(value => ['Android: ' + titleAndLink(value)[0], titleAndLink(value)[1]]),
195
+ ...[...(comp.sameName?.Norway ?? []), ...(comp.sameName?.EDGAR ?? [])].map(company => [plain(
196
+ [company.name, company.employees != null ? company.employees + ' employees' : null].filter(Boolean).join(', ')), httpsLink(company.url)]),
197
+ ...group.records.filter(row => row.site).map(({ domain, site }) => [
198
+ (site.host ?? domain) + ': ' + plain(site.state ?? site) + (site.title ? ', ' + plain(site.title) : ''),
199
+ httpsLink('https://' + (site.host ?? domain))]),
200
+ ['Web search: ' + plain(row.google?.result ?? 'check incomplete'), httpsLink(row.google?.link)],
201
+ ['iOS search', 'https://apps.apple.com/us/iphone/search?term=' + encodeURIComponent(row.name)],
202
+ ['Android search', 'https://play.google.com/store/search?q=' + encodeURIComponent(row.name) + '&c=apps'],
203
+ ...(row.traction ? [[plain(row.traction.rival ?? row.traction.name ?? ''),
204
+ httpsLink(row.traction.domain && 'https://' + row.traction.domain)],
205
+ ...Object.values(row.traction).flat().filter(value => typeof value === 'string').map(value => [plain(value)])] : []),
206
+ ...(typeof row.reason === 'string' ? row.reason.split(' · ').slice(1).map(value => [plain(value)]) : []),
207
+ ];
208
+ return matches.filter(([text, href]) => text && (href || !/ search$/.test(text)));
209
+ }
210
+
211
+ const anchor = (label, url) => '<a href="' + escape(url) + '">' + escape(label) + '</a>';
212
+ function summaryHtml(line) {
213
+ return Array.from(line.matchAll(/\[([^\]]+)\]\((https:\/\/[^\s)]+)\)/g)).reduce(({ html, offset }, match) =>
214
+ ({ html: html + escape(line.slice(offset, match.index)) + anchor(match[1], match[2]), offset: match.index + match[0].length }),
215
+ { html: '', offset: 0 });
216
+ }
217
+ function paragraph(line) {
218
+ const { html, offset } = summaryHtml(line);
219
+ return '<p>' + html + escape(line.slice(offset)) + '</p>';
220
+ }
221
+ const amountsFor = ({ now, renew }) => [cash(now) ?? 'No price', cash(renew) ?? 'No price'];
222
+
223
+ function rowNote(row) {
224
+ return [row.status, row.priceLabel, row.term > 1 ? row.term + ' years per payment' : null,
225
+ row.jump ? 'Renewal jumps' : null, !row.eligible ? '.no buyer eligibility required' : null,
226
+ row.source, row.checkedAt, row.priceAt ? 'Price checked ' + row.priceAt : null].filter(Boolean).join(' · ');
227
+ }
228
+
229
+ function render(groups, lines, checkedAt, coverage, watch) {
230
+ const title = watch ? 'Domain watch' : 'Domain results';
231
+ const [intro, ...body] = lines;
232
+ const comparison = body.filter(line => /^(?:Cheapest|Best value):/.test(line));
233
+ const before = body.filter(line => !comparison.includes(line)).slice(0, comparison.length ? -1 : undefined);
234
+ const after = comparison.length ? body.slice(-1) : [];
235
+ const sources = watch?.source ? 'Registry: ' + String(watch.source).toUpperCase() :
236
+ Object.entries(coverage ?? {}).map(([name, count]) => name + ' ' + count + '% answered').join(' · ');
237
+ const articles = groups.map((group, index) => {
238
+ const { row } = group;
239
+ const rows = group.records.map(record => {
240
+ const [now, renew] = amountsFor(record);
241
+ return '<tr><th scope="row"><code>' + escape(record.domain) + '</code><small>' + escape(rowNote(record))
242
+ + (record.checkout ? ' · ' + anchor(record.shop ?? 'Check at shop', record.checkout) : '')
243
+ + '</small></th><td>' + escape(now) + '</td><td>' + escape(renew) + '</td></tr>';
244
+ });
245
+ return '<article id="name-' + index + '"><h2>' + escape(row.name) + '</h2>'
246
+ + (row.verdict ? paragraph(plain(row.verdict) + '. ' + evidenceText(row.reason).split(' · ')[0]) + paragraph(signals(group)) : '')
247
+ + '<table><caption>Endings · USD before tax</caption><thead><tr><th scope="col">Ending</th><th scope="col">Today</th><th scope="col">Renewal</th></tr></thead><tbody>'
248
+ + rows.join('') + '</tbody></table>'
249
+ + (row.verdict ? '<details><summary>Trademark, app and web evidence</summary><ul>'
250
+ + details(group).map(([label, url]) => '<li>' + (url ? anchor(label, url) : escape(label)) + '</li>').join('') + '</ul></details>' : '')
251
+ + '</article>';
252
+ });
253
+ const html = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">'
254
+ + '<meta name="referrer" content="no-referrer"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'; base-uri \'none\'; form-action \'none\'">'
255
+ + '<title>' + title + ' | Domain Hound</title><style>' + receiptStyle + '</style></head><body><main>'
256
+ + '<header><small>Domain Hound</small><h1>' + title + '</h1><time>' + escape(checkedAt) + '</time></header><section>'
257
+ + [intro, ...before].filter(Boolean).map(paragraph).join('')
258
+ + (comparison.length ? '<div class="comparison">' + comparison.map(paragraph).join('') + '</div>' : '')
259
+ + after.map(paragraph).join('') + '</section>'
260
+ + (groups.length > 1 ? '<nav aria-label="Jump to a name">' + groups.map(({ row }, index) => anchor(row.name, '#name-' + index)).join(' ') + '</nav>' : '')
261
+ + articles.join('') + '<footer>' + (sources ? paragraph(sources) : '') + '<p>You hold the leash.</p></footer></main></body></html>\n';
262
+ const md = ['# ' + title, '', 'Domain Hound · ' + checkedAt, '', ...lines, '',
263
+ ...groups.flatMap(group => ['## ' + markdown(group.row.name), '',
264
+ ...(group.row.verdict ? [markdown(group.row.verdict + '. ' + group.row.reason), markdown(signals(group)), ''] : []),
265
+ '| Ending | Today (USD) | Renewal (USD) | Evidence | Shop |', '| --- | --- | --- | --- | --- |',
266
+ ...group.records.map(record => '| ' + [record.domain, ...amountsFor(record), markdown(rowNote(record)),
267
+ record.checkout ? '[' + markdown(record.shop ?? 'Check at shop') + '](' + record.checkout + ')' : ''].join(' | ') + ' |'),
268
+ '', ...(group.row.verdict ? details(group).map(([label, url]) => '- ' + (url ? '[' + markdown(label) + '](' + url + ')' : markdown(label))) : []), '']),
269
+ ...(sources ? [markdown(sources), ''] : []), 'You hold the leash.', ''].join('\n');
270
+ return { html, md };
271
+ }
272
+
273
+ export async function backgroundCommand(filename, env = process.env, platform = process.platform) {
274
+ if (env.DOMAIN_HOUND_OPEN === 'off' || env.CI || env.DOMAIN_HOUND_HEADLESS || env.SSH_CONNECTION || env.SSH_TTY) return null;
275
+ if (platform === 'darwin') {
276
+ const console = await stat('/dev/console').catch(() => null);
277
+ if (console?.uid === userInfo().uid) return ['/usr/bin/open', ['-g', filename]];
278
+ }
279
+ if (platform === 'win32' && /^(?:Console|RDP-Tcp#\d+)$/i.test(env.SESSIONNAME ?? '')) {
280
+ // SW_SHOWNOACTIVATE is forwarded to the file association handler. The existing browser may ignore it.
281
+ const path = Buffer.from(filename, 'utf8').toString('base64');
282
+ const script = `Add-Type -Namespace DomainHound -Name Shell -MemberDefinition @'
283
+ [System.Runtime.InteropServices.DllImport("shell32.dll", CharSet=System.Runtime.InteropServices.CharSet.Unicode, ExactSpelling=true)]
284
+ public static extern System.IntPtr ShellExecuteW(System.IntPtr parent, string verb, string file, string args, string directory, int show);
285
+ '@
286
+ $file = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${path}'))
287
+ $result = [DomainHound.Shell]::ShellExecuteW([IntPtr]::Zero, 'open', $file, $null, $null, 4)
288
+ if ($result.ToInt64() -le 32) { exit 1 }`;
289
+ return ['powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]];
290
+ }
291
+ if (platform === 'linux' && env.WAYLAND_DISPLAY && env.DBUS_SESSION_BUS_ADDRESS) {
292
+ // Leave activation to the compositor without giving the browser a startup or activation token.
293
+ const { XDG_ACTIVATION_TOKEN, DESKTOP_STARTUP_ID, ...backgroundEnv } = env;
294
+ return ['gio', ['open', pathToFileURL(filename).href], backgroundEnv];
295
+ }
296
+ return null;
297
+ }
298
+
299
+ async function writePrivate(filename, content) {
300
+ const temporary = filename + '.' + randomUUID() + '.tmp';
301
+ try {
302
+ await writeFile(temporary, content, { flag: 'wx', mode: 0o600 });
303
+ await rename(temporary, filename);
304
+ } finally {
305
+ await unlink(temporary).catch(() => {});
306
+ }
307
+ }
308
+
309
+ async function prune(directory, current) {
310
+ const owned = /^(?:\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[a-z0-9-]+-[a-f0-9]{8}\.(?:html|md)|session-[a-f0-9]{8}\.html)$/;
311
+ const files = (await readdir(directory)).filter(file => owned.test(file));
312
+ const groups = new Map();
313
+ for (const file of files) {
314
+ const base = file.slice(0, file.lastIndexOf('.'));
315
+ if (!groups.has(base)) groups.set(base, []);
316
+ groups.get(base).push(file);
317
+ }
318
+ const ranked = await Promise.all([...groups].map(async ([base, entries]) => ({ base, entries,
319
+ at: (await stat(join(directory, entries[0])).catch(() => null))?.mtimeMs ?? 0,
320
+ })));
321
+ ranked.sort((a, b) => Number(b.base === current) - Number(a.base === current) || b.at - a.at || b.base.localeCompare(a.base));
322
+ let slots = 20;
323
+ for (const { base, entries, at } of ranked) {
324
+ // A second MCP process may be committing a twin. Leave a recent incomplete pair alone.
325
+ if (!base.startsWith('session-') && entries.length === 1 && Date.now() - at < 60_000) continue;
326
+ if (entries.length <= slots) {
327
+ slots -= entries.length;
328
+ continue;
329
+ }
330
+ await Promise.all(entries.map(file => unlink(join(directory, file)).catch(() => {})));
331
+ }
332
+ }
333
+
334
+ export function resultPages({ env = process.env,
335
+ directory = env.DOMAIN_HOUND_RESULTS_DIR || join(homedir(), '.domain-hound', 'results') } = {}) {
336
+ const session = randomUUID().slice(0, 8);
337
+ let writes = Promise.resolve();
338
+ return (data, args, { triage = false, watch = false } = {}) => {
339
+ const work = writes.then(async () => {
340
+ const at = data.checkedAt ?? new Date().toISOString();
341
+ const groups = watch ? [] : resultGroups(data);
342
+ const lines = watch ? data.say.split('\n') : summary(groups, args, triage);
343
+ const title = watch ? data.domain : groups[0]?.row.name;
344
+ await mkdir(directory, { recursive: true, mode: 0o700 });
345
+ // If a caller points us at a shared directory, don't expose the searched name in its listing.
346
+ const privateListing = process.platform === 'win32' || ((await stat(directory)).mode & 0o077) === 0;
347
+ const slug = (privateListing && normalizeName(String(title).split('.')[0]) || 'results').slice(0, 30);
348
+ const base = new Date().toISOString().replaceAll(/[:.]/g, '-') + '-' + slug + '-' + randomUUID().slice(0, 8);
349
+ const filename = resolve(directory, base + '.html');
350
+ const page = render(groups, lines, at, data.sources, watch ? data : null);
351
+ const markdownPath = resolve(directory, base + '.md');
352
+ await writePrivate(markdownPath, page.md);
353
+ try {
354
+ await writePrivate(filename, page.html);
355
+ } catch (error) {
356
+ await unlink(markdownPath).catch(() => {});
357
+ throw error;
358
+ }
359
+ const exact = !triage && groups.length === 1 && groups[0].row.name.includes('.');
360
+ if (!watch && !exact) {
361
+ const latest = resolve(directory, 'session-' + session + '.html');
362
+ await backgroundCommand(latest, env).then(async command => {
363
+ if (!command) return;
364
+ await writePrivate(latest, page.html);
365
+ const [executable, args, launchEnv] = command;
366
+ const browser = spawn(executable, args, { stdio: 'ignore', windowsHide: true, env: launchEnv });
367
+ browser.on('error', () => {});
368
+ browser.unref();
369
+ }).catch(() => {});
370
+ }
371
+ await prune(directory, base).catch(() => {});
372
+ const url = pathToFileURL(filename).href.replaceAll('(', '%28').replaceAll(')', '%29');
373
+ const say = [...lines, 'All endings: [Results page](' + url + ')'].join('\n');
374
+ const { receiptDetails, say: priorSay, display: priorDisplay, ...structured } = data;
375
+ if (triage && receiptDetails) structured.names = structured.names.map((row, index) => ({
376
+ ...row, details: { ...row.details, sites: receiptDetails[index]?.details?.sites ?? {} },
377
+ }));
378
+ return { display: say, say, ...structured, checkedAt: at, resultPage: url };
379
+ });
380
+ writes = work.catch(() => {});
381
+ return work;
382
+ };
383
+ }
package/server.json CHANGED
@@ -4,21 +4,12 @@
4
4
  "title": "Domain Hound",
5
5
  "description": "Check domain availability and prices, and screen product names, from your AI assistant.",
6
6
  "websiteUrl": "https://domainhound.dev",
7
- "version": "0.1.2",
7
+ "version": "0.1.4",
8
8
  "packages": [
9
9
  {
10
10
  "registryType": "npm",
11
11
  "identifier": "domain-hound",
12
- "version": "0.1.2",
13
- "transport": {
14
- "type": "stdio"
15
- }
16
- },
17
- {
18
- "registryType": "mcpb",
19
- "identifier": "https://github.com/lars-hv/domain-hound/releases/download/v0.1.2/domain-hound-0.1.2.mcpb",
20
- "version": "0.1.2",
21
- "fileSha256": "3545b3607c1ed95f4fd6cbcc0edf247dc987933b93274b197a70e5de07499cf9",
12
+ "version": "0.1.4",
22
13
  "transport": {
23
14
  "type": "stdio"
24
15
  }