domain-hound 0.1.5 → 0.1.7

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.
Files changed (39) hide show
  1. package/.agents/plugins/marketplace.json +1 -0
  2. package/.claude-plugin/marketplace.json +1 -0
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/README.md +84 -13
  5. package/assets/readme-search.png +0 -0
  6. package/clis/domain-check/broker-atom.mjs +78 -0
  7. package/clis/domain-check/com-site.mjs +64 -25
  8. package/clis/domain-check/confirm.mjs +10 -5
  9. package/clis/domain-check/dossier.mjs +603 -0
  10. package/clis/domain-check/google-play.mjs +24 -11
  11. package/clis/domain-check/index.mjs +75 -23
  12. package/clis/domain-check/marketplaces.mjs +107 -0
  13. package/clis/domain-check/meaning-words.LICENSE.txt +408 -0
  14. package/clis/domain-check/meaning-words.json +2397 -0
  15. package/clis/domain-check/meaning.mjs +77 -0
  16. package/clis/domain-check/name-search.mjs +91 -14
  17. package/clis/domain-check/naming-method.mjs +6 -4
  18. package/clis/domain-check/registry.mjs +2 -2
  19. package/clis/domain-check/safe-web.mjs +207 -0
  20. package/clis/domain-check/trademarks.mjs +372 -0
  21. package/clis/domain-check/triage-sources.mjs +39 -12
  22. package/clis/domain-check/triage.mjs +190 -63
  23. package/clis/spaceship/buy.mjs +327 -0
  24. package/clis/spaceship/client.mjs +170 -0
  25. package/clis/spaceship/dns.mjs +292 -0
  26. package/clis/spaceship/quote.mjs +123 -0
  27. package/clis/spaceship/setup.mjs +81 -0
  28. package/clis/spaceship/store.mjs +104 -0
  29. package/clis/spaceship/tools.mjs +258 -0
  30. package/display.mjs +57 -30
  31. package/dossier.mjs +185 -0
  32. package/package.json +20 -2
  33. package/plugin.json +4 -3
  34. package/results-style.mjs +10 -0
  35. package/results.mjs +258 -62
  36. package/server.json +2 -2
  37. package/server.mjs +223 -96
  38. package/share.mjs +43 -0
  39. package/site/r/share-format.mjs +125 -0
@@ -0,0 +1,603 @@
1
+ // Broker dossier for a taken domain (read only). Registry facts, what the site does, public listing evidence, a
2
+ // likely owner type from public signals, the track, a price range only from shown evidence, up to three free
3
+ // alternatives from the name engine with the triage name screen, and drafted (never sent) notes to the owner. Nothing is sent, submitted or
4
+ // bought, no shop credentials are used, and no background refresh starts. Every part shares one total deadline.
5
+ import { classifyComSite } from './com-site.mjs';
6
+ import { anySignal, cacheDir, readCache } from './cache.mjs';
7
+ import { asciiDomain, canRecommend, defaultEndings, domainEnding, fallbackEndings, listQuote, mainstreamEndings, nameCandidates,
8
+ premiumRisk, searchCandidates, supportedEndings, unicodeName } from './name-search.mjs';
9
+ import { bundledCatalog, loadCachedCatalog } from './price-catalog.mjs';
10
+ import { bestValue, triageNames } from './triage.mjs';
11
+ import { bootstrap, bootstrapUrl, documentedWhois, lookupRegistrations, rdapBase, rdapDomainUrl, systemResolveNs } from './registry.mjs';
12
+ import { saleMarketplace } from './parking.mjs';
13
+ import { checkListings, marketplaceFor, providers, stopReason, urlBindsDomain } from './marketplaces.mjs';
14
+ import { evidenceUrl, followSite, loadPage, pageText, safeUrl } from './safe-web.mjs';
15
+
16
+ const day = 86_400_000;
17
+ export const totalBudgetMs = 11_500;
18
+ export const expiringDays = 45;
19
+ const label = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
20
+ const registrarPriceUrls = {
21
+ Spaceship: 'https://www.spaceship.com/domain-search/pricing/',
22
+ Dynadot: 'https://www.dynadot.com/domain/prices?currency=USD',
23
+ };
24
+ const priceSourceUrl = (quote, tld) => quote.shop === 'Gandi'
25
+ ? 'https://www.gandi.net/en/domain/tld/' + encodeURIComponent(tld) + '?currency=USD'
26
+ : registrarPriceUrls[quote.shop] ?? quote.buyUrl ?? null;
27
+
28
+ // The exact domain in DNS form: one label plus an ending, or a label under co.uk. Null for anything else.
29
+ export function dossierDomain(value) {
30
+ if (typeof value !== 'string' || value.length > 127) return null;
31
+ const domain = asciiDomain(value.trim().replace(/\.$/, ''));
32
+ if (!domain) return null;
33
+ const parts = domain.split('.');
34
+ const ok = (parts.length === 2 || (parts.length === 3 && parts.slice(1).join('.') === 'co.uk'))
35
+ && label.test(parts[0]) && /^(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/.test(parts.at(-1));
36
+ return ok && safeUrl('https://' + domain) ? domain : null;
37
+ }
38
+
39
+ const iso = value => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : null;
40
+ const hostname = value => typeof value === 'string' && /^[a-z0-9.-]{3,253}$/i.test(value.replace(/\.$/, ''))
41
+ ? value.toLowerCase().replace(/\.$/, '') : null;
42
+ // Registry text fields (a registrar's name) keep plain characters only.
43
+ const plainField = value => typeof value === 'string'
44
+ ? value.replace(/[^\p{L}\p{N} .,&()'/-]/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, 80) || null : null;
45
+
46
+ const normalizeStatus = value => value.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();
47
+
48
+ // Facts from one RDAP domain object, bound to the exact domain.
49
+ export function readRdap(data, domain) {
50
+ if (String(data?.ldhName ?? '').toLowerCase().replace(/\.$/, '') !== domain) return null;
51
+ const events = Array.isArray(data.events) ? data.events : [];
52
+ const event = action => iso(events.find(row => row?.eventAction === action)?.eventDate);
53
+ const registrar = (Array.isArray(data.entities) ? data.entities : [])
54
+ .find(entity => Array.isArray(entity?.roles) && entity.roles.includes('registrar'));
55
+ const card = Array.isArray(registrar?.vcardArray?.[1]) ? registrar.vcardArray[1] : [];
56
+ const name = plainField(card.find(row => Array.isArray(row) && row[0] === 'fn')?.[3]);
57
+ const ianaId = (Array.isArray(registrar?.publicIds) ? registrar.publicIds : [])
58
+ .find(row => /iana/i.test(String(row?.type)))?.identifier;
59
+ return {
60
+ created: event('registration'), expires: event('expiration'), changed: event('last changed'),
61
+ registrar: name, registrarIanaId: /^\d{1,6}$/.test(String(ianaId ?? '')) ? String(ianaId) : null,
62
+ status: (Array.isArray(data.status) ? data.status : [])
63
+ .filter(value => typeof value === 'string' && /^[a-z ]{3,40}$/i.test(value)).map(normalizeStatus).slice(0, 24),
64
+ nameservers: (Array.isArray(data.nameservers) ? data.nameservers : [])
65
+ .map(row => hostname(row?.ldhName)).filter(Boolean).slice(0, 8),
66
+ };
67
+ }
68
+
69
+ async function rdapLookup(domain, { fetcher, signal, services }) {
70
+ const tld = domainEnding(domain);
71
+ const base = rdapBase(tld) ?? rdapBase(tld, await services);
72
+ if (!base?.startsWith('https://')) return { state: 'unknown', reason: 'no HTTPS RDAP service for this ending' };
73
+ const url = rdapDomainUrl(base, domain);
74
+ try {
75
+ const response = await fetcher(url, { headers: { Accept: 'application/rdap+json, application/json' },
76
+ credentials: 'omit', redirect: 'error', signal });
77
+ if (response.status === 404) {
78
+ await response.body?.cancel?.().catch(() => {});
79
+ return { state: 'free', url };
80
+ }
81
+ if (response.status !== 200) {
82
+ await response.body?.cancel?.().catch(() => {});
83
+ return { state: 'unknown', url, reason: 'RDAP returned HTTP ' + response.status };
84
+ }
85
+ const text = await response.text();
86
+ if (text.length > 1_000_000) return { state: 'unknown', url, reason: 'RDAP answer too large' };
87
+ const facts = readRdap(JSON.parse(text), domain);
88
+ return facts ? { state: 'taken', url, facts } : { state: 'unknown', url, reason: 'RDAP answer is for another name' };
89
+ } catch {
90
+ return { state: 'unknown', url, reason: signal?.aborted ? 'RDAP timed out' : 'RDAP did not respond' };
91
+ }
92
+ }
93
+
94
+ // Registry facts: RDAP for the details, with the existing DNS-and-WHOIS lookup alongside for the basic answer.
95
+ export async function registryFacts(domain, { fetcher = globalThis.fetch, resolveNs = systemResolveNs, queryWhois,
96
+ directory = cacheDir, signal, deadline = performance.now() + 5500, clock = () => new Date() } = {}) {
97
+ const tld = domainEnding(domain);
98
+ const timeLeft = () => Math.max(0, Math.floor(deadline - performance.now()));
99
+ const services = rdapBase(tld) ? null : bootstrap(directory, fetcher, clock(), () => Math.min(1800, timeLeft()));
100
+ const rdapSignal = anySignal([signal ?? new AbortController().signal, AbortSignal.timeout(Math.max(1, Math.min(3500, timeLeft())))]);
101
+ const [rdap, [basic]] = await Promise.all([
102
+ rdapLookup(domain, { fetcher, signal: rdapSignal, services }),
103
+ lookupRegistrations([{ domain, tld }], { directory, fetcher, resolveNs, queryWhois, timeLeft, now: clock(),
104
+ dnsFirst: true, readExpiry: true, rdapAttempts: 1 }).catch(() => [null]),
105
+ ]);
106
+ const checkedAt = clock().toISOString();
107
+ const facts = rdap.facts ?? {};
108
+ const registered = rdap.state === 'taken' || basic?.status === 'taken' ? 'taken'
109
+ : rdap.state === 'free' || basic?.status === 'free' ? 'free' : 'unknown';
110
+ const nameservers = facts.nameservers?.length ? facts.nameservers
111
+ : (basic?.nameservers ?? []).map(hostname).filter(Boolean).slice(0, 8);
112
+ const source = rdap.state === registered ? { method: 'rdap', url: rdap.url }
113
+ : basic?.source ? { method: basic.source,
114
+ url: basic.source === 'dns' ? 'dns:NS ' + domain : rdap.url ?? bootstrapUrl } : null;
115
+ return {
116
+ registered, checkedAt, source,
117
+ created: facts.created ?? null,
118
+ expires: facts.expires ?? iso(basic?.expires) ?? null,
119
+ changed: facts.changed ?? null,
120
+ registrar: facts.registrar ?? null, registrarIanaId: facts.registrarIanaId ?? null,
121
+ status: facts.status ?? [], nameservers,
122
+ marketplaceNameservers: saleMarketplace(nameservers),
123
+ ...(registered === 'unknown' && { reason: [rdap.reason, basic?.reason].filter(Boolean).join('; ') || 'no registry answer' }),
124
+ };
125
+ }
126
+
127
+ const escapeDomain = domain => domain.replace(/[.]/g, '\\.');
128
+
129
+ const saleStatement = /\b(?:(?:this )?domain(?: name)? is (?:for sale|available for (?:purchase|sale))|is for sale|buy this domain|purchase this domain|domain for sale)\b/i;
130
+ const notForSale = /\bnot (?:for sale|available for (?:purchase|sale))\b/i;
131
+ const priceCue = /\b(?:price|asking|buy (?:it )?now|for sale (?:for|at)|listed (?:for|at)|purchase (?:for|at))\b/i;
132
+ const offerCue = /\b(?:offer|minimum|bid|lease|rent|monthly|per month|\/mo|installments?|down payment|financing|from)\b/i;
133
+ const pricePattern = /(?:(US\$|\$|USD|€|EUR|£|GBP)\s?((?:\d{1,3}(?:,\d{3})+|\d{1,9})(?:\.\d{2})?)(?![\d,]|\.\d)|(?<![\d,.])((?:\d{1,3}(?:,\d{3})+|\d{1,9})(?:\.\d{2})?)\s?(USD|EUR|GBP)\b)/g;
134
+ const currencyOf = symbol => ({ 'US$': 'USD', $: 'unspecified', USD: 'USD', '€': 'EUR', EUR: 'EUR', '£': 'GBP', GBP: 'GBP' })[symbol];
135
+
136
+ // The owner's own sale statement and asking price on the domain's own page. A price counts only when the page names
137
+ // the exact domain, says it is for sale, and shows one unambiguous price next to a price cue (not an offer floor,
138
+ // lease or instalment). Anything else is no price.
139
+ export function readOwnSale(text, domain) {
140
+ if (!text || notForSale.test(text) || !saleStatement.test(text)) return { sale: false };
141
+ const mentions = new RegExp('(?:^|[^a-z0-9.-])' + escapeDomain(domain) + '(?![a-z0-9-]|\\.[a-z0-9])', 'gi');
142
+ const saleContext = [...text.matchAll(mentions)].find(match => {
143
+ const context = text.slice(Math.max(0, match.index - 60), match.index + domain.length + 75);
144
+ const names = context.match(/\b[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,63}\b/gi) ?? [];
145
+ return saleStatement.test(context) && names.every(name => name.toLowerCase() === domain);
146
+ });
147
+ if (!saleContext) return { sale: true, bound: false };
148
+ const amounts = new Map();
149
+ let offerNearby = false;
150
+ for (const match of text.matchAll(pricePattern)) {
151
+ if (Math.abs(match.index - saleContext.index) > 250) continue;
152
+ const before = text.slice(Math.max(0, match.index - 60), match.index);
153
+ const after = text.slice(match.index + match[0].length, match.index + match[0].length + 20);
154
+ if (!priceCue.test(before)) continue;
155
+ if (offerCue.test(before.slice(-25)) || /^\s*(?:\/|per\b|a month|monthly)/i.test(after)) { offerNearby = true; continue; }
156
+ const amount = Number((match[2] ?? match[3]).replace(/,/g, ''));
157
+ const currency = currencyOf(match[1] ?? match[4]);
158
+ if (!(amount >= 1 && amount <= 100_000_000) || !currency) continue;
159
+ amounts.set(currency + amount, { amount, currency });
160
+ }
161
+ if (amounts.size === 1) return { sale: true, bound: true, price: [...amounts.values()][0] };
162
+ return { sale: true, bound: true, ...(amounts.size > 1 ? { note: 'several prices on the page; none read' }
163
+ : offerNearby ? { note: 'only an offer floor or instalment on the page; not an asking price' } : {}) };
164
+ }
165
+
166
+ const investorCue = /\b(?:domain (?:portfolio|investor|investments?|holdings?)|premium domains?|we (?:buy|sell|acquire|invest in) domains|domains? (?:we own|in our portfolio))\b/i;
167
+ const individualCue = /\b(?:my personal (?:site|website|blog|homepage)|personal (?:site|website|blog|homepage) of)\b/i;
168
+ const businessCue = /\b(?:our (?:products|customers|services|company)|pricing|shop now|book a demo|customer support|terms of service|all rights reserved)\b/i;
169
+
170
+ // What the site does now, from a followed chain. Only states, hosts and sanitized URLs leave this function.
171
+ export function readSite(domain, visit, checkedAt) {
172
+ const own = host => host === domain || host === 'www.' + domain;
173
+ const chain = visit.hops.map(hop => evidenceUrl(hop.url)).filter(Boolean);
174
+ const base = { checkedAt, url: chain[0] ?? 'https://' + domain + '/', chain };
175
+ if (visit.stopped) {
176
+ const target = visit.stopped.url;
177
+ const host = target?.hostname ?? null;
178
+ if (!host) return { ...base, state: 'unknown', reason: visit.stopped.reason };
179
+ const provider = marketplaceFor(host);
180
+ const finalUrl = evidenceUrl(target);
181
+ if (!visit.hops.length) return { ...base, state: 'unknown', host, finalUrl,
182
+ reason: ['marketplace', 'parking'].includes(visit.stopped.reason) ? 'site access limited by provider policy' : visit.stopped.reason };
183
+ if (visit.stopped.reason === 'parking') return { ...base, state: 'parked', host, finalUrl };
184
+ if (visit.stopped.reason === 'marketplace') {
185
+ // The marketplace page is not fetched; a URL that names this exact domain is a sale signal, not a listing.
186
+ if (urlBindsDomain(target, domain)) return { ...base, state: 'for-sale-lander', host, finalUrl,
187
+ marketplace: provider?.name ?? host, boundToDomain: true, fetched: false };
188
+ return { ...base, state: 'redirect', host, finalUrl, finalState: 'destination not opened' };
189
+ }
190
+ return { ...base, state: 'unknown', host, finalUrl, reason: visit.stopped.reason };
191
+ }
192
+ if (visit.failed || !visit.final) return { ...base, state: 'no-site', reason: visit.failed?.reason ?? 'no response' };
193
+ const { url, status, contentType, body, truncated } = visit.final;
194
+ const host = url.hostname;
195
+ const finalUrl = evidenceUrl(url);
196
+ const kind = classifyComSite({ url: url.href, status, contentType, body }).state;
197
+ const text = kind === 'no-site' ? '' : pageText(body);
198
+ const signals = { investorSignals: investorCue.test(text), individualSignals: individualCue.test(text),
199
+ businessSignals: businessCue.test(text) };
200
+ if (!own(host)) {
201
+ return { ...base, state: 'redirect', host, finalUrl, finalState: kind === 'for-sale' ? 'for-sale' : kind,
202
+ ...signals };
203
+ }
204
+ if (kind === 'no-site') return { ...base, state: 'no-site', host, finalUrl, reason: status ? 'HTTP ' + status : 'no page' };
205
+ const sale = readOwnSale(text, domain);
206
+ if (sale.sale || kind === 'for-sale') {
207
+ return { ...base, state: 'for-sale-lander', host, finalUrl, fetched: true, boundToDomain: Boolean(sale.bound && !truncated),
208
+ ...(sale.price && !truncated && { price: sale.price }), ...(sale.note && { priceNote: sale.note }) };
209
+ }
210
+ if (kind === 'parked') return { ...base, state: 'parked', host, finalUrl };
211
+ return { ...base, state: 'live', host, finalUrl, ...signals };
212
+ }
213
+
214
+ export const hopTimeoutMs = 3500;
215
+
216
+ // The site over https and http side by side, each hop with its own timeout. https wins when it answered at all.
217
+ export async function siteFacts(domain, { signal, load = loadPage, clock = () => new Date(), hopMs = hopTimeoutMs } = {}) {
218
+ const outer = signal ?? new AbortController().signal;
219
+ const runs = ['https', 'http'].map(scheme => {
220
+ const controller = new AbortController();
221
+ const own = anySignal([outer, controller.signal]);
222
+ const hop = (url, hopSignal, stopAt) => load(url, anySignal([hopSignal ?? own, AbortSignal.timeout(hopMs)]), stopAt);
223
+ return { controller, done: followSite(scheme + '://' + domain + '/', { signal: own, stopAt: stopReason, load: hop }) };
224
+ });
225
+ try {
226
+ const secure = readSite(domain, await runs[0].done, clock().toISOString());
227
+ if (!['no-site', 'unknown'].includes(secure.state)) return secure;
228
+ const plain = readSite(domain, await runs[1].done, clock().toISOString());
229
+ return ['no-site', 'unknown'].includes(plain.state) ? secure : plain;
230
+ } finally {
231
+ for (const run of runs) run.controller.abort();
232
+ }
233
+ }
234
+
235
+ // Positive listings: the owner's own bound sale page, and enabled marketplace adapters that answered "listed".
236
+ export function listingEvidence(site, listings) {
237
+ const listed = [];
238
+ const signals = [];
239
+ if (site?.state === 'for-sale-lander' && site.fetched && site.boundToDomain) {
240
+ listed.push({ source: 'own site', url: site.finalUrl, checkedAt: site.checkedAt, ...(site.price && { price: site.price }) });
241
+ } else if (site?.state === 'for-sale-lander') {
242
+ signals.push({ signal: site.fetched ? 'sale page that does not name this exact domain' : 'redirects to ' + site.marketplace
243
+ + (site.boundToDomain ? ' page for this exact domain (not opened)' : ' (not opened)'), url: site.finalUrl, checkedAt: site.checkedAt });
244
+ }
245
+ if (site?.state === 'redirect' && site.finalState === 'for-sale') {
246
+ signals.push({ signal: 'redirects to a sale page at ' + site.host, url: site.finalUrl, checkedAt: site.checkedAt });
247
+ }
248
+ for (const row of listings ?? []) {
249
+ if (row.state === 'listed') listed.push({ source: row.name, url: row.url, checkedAt: row.checkedAt,
250
+ ...(row.sourceUrl && { sourceUrl: row.sourceUrl }), ...(row.price && { price: row.price }) });
251
+ }
252
+ return { listed, signals };
253
+ }
254
+
255
+ // A range only from asking prices that were shown, in one currency. Never from renewal cost or appraisal.
256
+ export function fairRange(listed) {
257
+ const prices = listed.filter(row => row.price).map(row => ({ ...row.price, url: row.url, checkedAt: row.checkedAt }));
258
+ if (!prices.length) return null;
259
+ const currencies = new Set(prices.map(row => row.currency));
260
+ if (currencies.size > 1) return { low: null, high: null, note: 'asking prices in several currencies; not combined', evidence: prices };
261
+ const amounts = prices.map(row => row.amount);
262
+ return { currency: prices[0].currency, low: Math.min(...amounts), high: Math.max(...amounts), evidence: prices };
263
+ }
264
+
265
+ export function ownerSignal(registry, site, listing) {
266
+ const result = (type, confidence, basis, evidence) => ({
267
+ type, confidence, basis, url: evidence?.url ?? null, checkedAt: evidence?.checkedAt ?? null,
268
+ });
269
+ const siteEvidence = { url: site?.finalUrl ?? site?.url, checkedAt: site?.checkedAt };
270
+ if (site?.investorSignals) {
271
+ return result('investor', 'medium', 'the destination describes a domain portfolio', siteEvidence);
272
+ }
273
+ if (site?.individualSignals) {
274
+ return result('individual', 'medium', 'the site describes itself as a personal site', siteEvidence);
275
+ }
276
+ if (site?.businessSignals) {
277
+ return result('business', site.state === 'live' ? 'medium' : 'low', 'the live site has business signals', siteEvidence);
278
+ }
279
+ if (listing.listed.length) {
280
+ return result('investor', 'low', 'the domain has a public sale listing', listing.listed[0]);
281
+ }
282
+ const market = registry?.marketplaceNameservers;
283
+ if (market && !['Bodis', 'ParkingCrew'].includes(market)) {
284
+ return result('investor', 'low', 'name servers at ' + market,
285
+ { url: registry.source?.url, checkedAt: registry.checkedAt });
286
+ }
287
+ return result('unknown', 'none', 'no reliable public owner signal', siteEvidence);
288
+ }
289
+
290
+ export function expiryOutlook(registry, now) {
291
+ const pendingDelete = registry.status.includes('pending delete');
292
+ const redemption = registry.status.includes('redemption period');
293
+ const at = Date.parse(registry.expires);
294
+ const days = Number.isFinite(at) ? Math.floor((at - now) / day) : null;
295
+ return { pendingDelete, redemption, days, soon: days != null && days <= expiringDays };
296
+ }
297
+
298
+ export function chooseTrack(registry, listing, outlook) {
299
+ if (registry.registered === 'free') return 'available';
300
+ if (registry.registered !== 'taken') return 'unknown';
301
+ if (outlook.pendingDelete || outlook.redemption) return 'expiring';
302
+ if (listing.listed.length) return 'listed';
303
+ if (outlook.soon) return 'expiring';
304
+ return 'not-listed';
305
+ }
306
+
307
+ // Broker ending order: the anchors, then established mainstream endings (the shared attractiveness tiers). .xyz and
308
+ // .tech are a fallback tier, ranked after every mainstream ending however cheap their first year is. Other supported
309
+ // endings follow in catalog order.
310
+ const brokerEndingOrder = [...new Set([...mainstreamEndings, ...fallbackEndings, ...supportedEndings])];
311
+ const labelOf = domain => domain.slice(0, domain.indexOf('.'));
312
+ const threeYearOf = row => Number.isFinite(row?.threeYear) ? row.threeYear : Infinity;
313
+
314
+ // No renewal jump sits above an option without one whose three-year total is the same or lower, whatever slot put it
315
+ // there. Each move takes one jump-above-non-jump pair away, so the loop ends.
316
+ export function orderByValue(options) {
317
+ const ordered = [...options];
318
+ for (let moved = true; moved;) {
319
+ moved = false;
320
+ search: for (let i = 0; i < ordered.length; i++) {
321
+ if (!ordered[i].renewalJump) continue;
322
+ for (let j = i + 1; j < ordered.length; j++) {
323
+ if (!ordered[j].renewalJump && threeYearOf(ordered[j]) <= threeYearOf(ordered[i])) {
324
+ ordered.splice(i, 0, ...ordered.splice(j, 1));
325
+ moved = true;
326
+ break search;
327
+ }
328
+ }
329
+ }
330
+ }
331
+ return ordered;
332
+ }
333
+
334
+ function variantForms(name) {
335
+ return nameCandidates(name, { endings: ['com'] }).filter(row => !row.exact).map(row => row.domain).filter(domain => {
336
+ const label = labelOf(domain);
337
+ return label.endsWith(name) ? !name.startsWith(label.slice(0, -name.length)) : !name.endsWith(label.slice(name.length));
338
+ });
339
+ }
340
+
341
+ // Pick the best value for the exact name, a natural .com variant, and the strongest remaining exact ending.
342
+ // Fill open slots in ending order, then with additional variants.
343
+ export function pickAlternatives(rows, domain) {
344
+ const name = labelOf(domain);
345
+ const forms = variantForms(name);
346
+ const pool = rows.filter(row => row.domain !== domain && ['probably-free', 'confirmed'].includes(row.status)
347
+ && row.price != null && canRecommend(row.tld) && !premiumRisk(row.domain)
348
+ && (row.exact ? labelOf(row.domain) === name : forms.includes(row.domain)));
349
+ const exact = pool.filter(row => row.exact)
350
+ .sort((a, b) => brokerEndingOrder.indexOf(a.tld) - brokerEndingOrder.indexOf(b.tld));
351
+ const variants = pool.filter(row => !row.exact)
352
+ .sort((a, b) => threeYearOf(a) - threeYearOf(b) || a.domain.length - b.domain.length
353
+ || forms.indexOf(a.domain) - forms.indexOf(b.domain));
354
+ const picks = [];
355
+ const open = list => list.filter(row => !picks.some(pick => pick.row === row));
356
+ const take = (row, role) => { if (row && open([row]).length) picks.push({ row, role }); };
357
+ const attractive = exact.filter(row => mainstreamEndings.includes(row.tld));
358
+ take(bestValue(attractive) ?? bestValue(exact), 'best-value');
359
+ take(variants[0], 'variant');
360
+ for (const row of [...open(exact), ...open(variants)]) {
361
+ if (picks.length >= 3) break;
362
+ take(row, !row.exact ? 'variant' : row.tld === 'com' ? 'exact-com' : 'exact-ending');
363
+ }
364
+ const chosen = orderByValue(picks.map(({ row, role }) => ({ ...row, role })));
365
+ const cheapest = pool.reduce((best, row) => !best || (row.firstPayment ?? Infinity) < (best.firstPayment ?? Infinity)
366
+ || (row.firstPayment === best.firstPayment && threeYearOf(row) < threeYearOf(best)) ? row : best, undefined);
367
+ const covered = cheapest && chosen.some(row => (row.firstPayment ?? Infinity) <= (cheapest.firstPayment ?? Infinity));
368
+ return { picks: chosen, priceContext: cheapest && !covered ? cheapest : null };
369
+ }
370
+
371
+ function alternativeRow(row, services) {
372
+ const rdap = row.source === 'rdap' && rdapBase(row.tld, services);
373
+ return {
374
+ domain: row.domain, label: labelOf(row.domain), exact: Boolean(row.exact), ...(row.role && { role: row.role }),
375
+ status: row.status, registryCheckedAt: row.checkedAt ?? null,
376
+ registrySource: row.source ? { method: row.source, url: rdap ? rdapDomainUrl(rdap, row.domain) : bootstrapUrl,
377
+ ...(row.source === 'whois' && documentedWhois.has(row.tld) && { host: documentedWhois.get(row.tld) }) } : null,
378
+ price: row.price, renewal: row.renewal ?? null, firstPayment: row.firstPayment ?? null,
379
+ renewalPayment: row.renewalPayment ?? null, minimumYears: row.minimumYears ?? 1, threeYear: row.threeYear ?? null,
380
+ renewalJump: Boolean(row.renewalJump),
381
+ shop: row.shop ?? null, priceCheckedAt: row.priceCheckedAt ?? null, priceUrl: priceSourceUrl(row, row.tld),
382
+ };
383
+ }
384
+
385
+ // The existing name engine for free alternatives: list prices from the local cache or the bundled snapshot only,
386
+ // so no refresh starts and no shop credentials are read. The checked rows come back too, so the name screen reuses
387
+ // the registry answers instead of asking again.
388
+ export async function findAlternatives(domain, { search = searchCandidates, budgetMs = 6500, clock = () => new Date(),
389
+ directory = cacheDir } = {}) {
390
+ const name = labelOf(domain);
391
+ const tld = domainEnding(domain);
392
+ const endings = [...new Set([tld, ...defaultEndings])].filter(ending => supportedEndings.includes(ending));
393
+ const candidates = nameCandidates(name, { endings }).filter(row => row.domain !== domain);
394
+ const { groups: [group] = [] } = await search([{ name, candidates }], {
395
+ budgetMs, now: clock(), cachedOnly: true, skipComSite: true, directory,
396
+ verifyFreeSite: async (name, timeout) => {
397
+ const site = await siteFacts(name, { signal: AbortSignal.timeout(Math.max(1, Math.floor(timeout))) });
398
+ if (['live', 'redirect', 'parked', 'for-sale-lander'].includes(site.state)) return { state: 'live' };
399
+ return null;
400
+ } });
401
+ const services = (await readCache(directory, 'iana.json'))?.value;
402
+ const results = group?.results ?? [];
403
+ const { picks, priceContext } = pickAlternatives(results, domain);
404
+ return { rows: picks.map(row => alternativeRow(row, services)),
405
+ priceContext: priceContext ? alternativeRow(priceContext, services) : null, results, endings };
406
+ }
407
+
408
+ const screenTrim = (value, limit) => value && value.length > limit ? value.slice(0, limit - 1).trimEnd() + '…' : value ?? null;
409
+
410
+ // The same trademark, iOS and Android app and rival judgement as triageNames, run on one name label. Registry
411
+ // answers and site evidence come in from the dossier, handle rows stay off and no search key is read.
412
+ export async function screenName(label, { endings, domains, budgetMs, clock = () => new Date(), directory = cacheDir,
413
+ triage = triageNames } = {}) {
414
+ const report = await triage([unicodeName(label) ?? label], { endings, budgetMs: Math.max(1, Math.floor(budgetMs)), now: clock(), directory,
415
+ domainSearch: () => domains, deferHandles: true, handleRows: false, env: {} });
416
+ const row = report?.names?.[0];
417
+ if (!row || report.error) return null;
418
+ const competition = row.competition ?? {};
419
+ const app = value => Array.isArray(value) ? value[0] ?? null : value ?? null;
420
+ const ios = app(competition.AppStore);
421
+ const android = app(competition.GooglePlay);
422
+ return {
423
+ state: 'settled', verdict: row.verdict,
424
+ // The first two reasons, short: the verdict's cause and the strongest supporting fact.
425
+ reason: screenTrim(String(row.reason ?? '').split(' · ').slice(0, 2).join(' · '), 180),
426
+ trademark: typeof competition.US === 'string' ? competition.US : null,
427
+ trademarkUrl: competition.mark ?? null,
428
+ apps: row.details?.appName ?? null,
429
+ appEvidence: [ios && { store: 'iOS', name: ios.name, url: ios.url ?? null },
430
+ android && { store: 'Android', name: android.name, url: android.url ?? null }].filter(Boolean),
431
+ sameName: competition.sameName?.summary ?? null,
432
+ ...(row.traction && { traction: row.traction }),
433
+ google: row.google?.link ?? null,
434
+ };
435
+ }
436
+
437
+ // The registry rows the alternatives search already holds for one label, plus the taken domain and its site.
438
+ function screenGroup(label, domain, alternatives, registry, site) {
439
+ const results = (alternatives?.results ?? []).filter(row => labelOf(row.domain) === label);
440
+ const sites = {};
441
+ if (label === labelOf(domain)) {
442
+ const tld = domainEnding(domain);
443
+ const state = { live: 'live', parked: 'parked', 'for-sale-lander': 'for-sale' }[site?.state];
444
+ if (state) sites[tld] = { state, host: site.host ?? domain };
445
+ if (registry?.registered === 'taken' || state) {
446
+ results.push({ domain, tld, exact: true, status: 'taken', checkedAt: registry?.checkedAt ?? null,
447
+ source: registry?.source?.method ?? 'web' });
448
+ }
449
+ }
450
+ return { groups: [{ name: label, candidates: [], results, sites, comSite: sites.com ?? null }], complete: true, priceDate: null };
451
+ }
452
+
453
+ // What the owner pays to renew at a list price, as one cost fact (never a value estimate).
454
+ export async function renewalFact(domain, { directory = cacheDir, clock = () => new Date() } = {}) {
455
+ const tld = domainEnding(domain);
456
+ if (!supportedEndings.includes(tld)) return null;
457
+ const quote = listQuote(await loadCachedCatalog(directory), { domain, tld }, clock(), bundledCatalog);
458
+ return quote.renewal != null ? { renewal: quote.renewal, shop: quote.shop, checkedAt: quote.priceCheckedAt,
459
+ url: priceSourceUrl(quote, tld) } : null;
460
+ }
461
+
462
+ const symbols = { USD: '$', EUR: '€', GBP: '£' };
463
+ export const formatMoney = ({ amount, currency }) => {
464
+ const value = amount.toLocaleString('en-US');
465
+ if (currency === 'unspecified') return '$' + value + ' (currency unspecified)';
466
+ return (symbols[currency] ?? currency + ' ') + value;
467
+ };
468
+
469
+ // The opening note and up to two follow-ups. One ask each, an AI agent disclosed, no budget, dates, legal language
470
+ // or personal details: the requester signs and sends it themselves.
471
+ export function draftNotes(domain, { asking, maxBudget, throughMarketplace = false } = {}) {
472
+ const sign = '\n\nThanks,\n[your name]';
473
+ const disclosure = 'An AI agent helped me look into the domain.';
474
+ let kind = 'ask-price';
475
+ let ask = 'What price would you consider for it?';
476
+ if (asking) {
477
+ const price = formatMoney(asking);
478
+ if (asking.currency === 'USD' && maxBudget != null && asking.amount < maxBudget) {
479
+ kind = 'offer-listed-price';
480
+ ask = 'Would you sell it to me for the listed ' + price + '?';
481
+ } else if (asking.currency === 'USD' && maxBudget != null && asking.amount > maxBudget) {
482
+ kind = 'ask-flexibility';
483
+ ask = 'I saw it offered at ' + price + '. Is there any room on that price?';
484
+ } else {
485
+ kind = 'confirm-price';
486
+ ask = 'I saw it offered at ' + price + '. Is that price still current?';
487
+ }
488
+ }
489
+ const opening = 'Subject: Question about ' + domain + '\n\nHi,\n\nI’m interested in buying ' + domain
490
+ + '. ' + disclosure + '\n\n' + ask + sign;
491
+ const followUps = [
492
+ { after: '7 days without a reply', text: 'Subject: Re: Question about ' + domain + '\n\nHi again,\n\nA short follow-up on '
493
+ + domain + '. ' + (asking ? 'Is it still available?' : 'Would you be open to selling it? A rough price is fine.') + sign },
494
+ { after: '14 days without a reply', text: 'Subject: Re: Question about ' + domain + '\n\nHi,\n\nThis is my last note about '
495
+ + domain + '. If you ever want to sell it, could you reply with a price? If not, no problem, and thanks for reading.' + sign },
496
+ ];
497
+ const channel = throughMarketplace ? 'marketplace' : 'public owner inquiry';
498
+ return { kind, channel, opening, followUps };
499
+ }
500
+
501
+ function bounded(promise, ms, fallback) {
502
+ let timer;
503
+ return Promise.race([
504
+ Promise.resolve(promise).catch(() => fallback),
505
+ new Promise(resolve => { timer = setTimeout(resolve, Math.max(0, ms), fallback); }),
506
+ ]).finally(() => clearTimeout(timer));
507
+ }
508
+
509
+ // The screen stops this long before the dossier deadline, so its own partial answer arrives before the cut.
510
+ export const screenReserveMs = 400;
511
+ const pendingScreen = { state: 'pending', verdict: null,
512
+ reason: 'Name screen still running at the deadline: no trademark, app or rival result yet' };
513
+
514
+ // Older alternatives callers return a plain list; the engine returns rows, price context and the checked rows.
515
+ const alternativesOf = value => Array.isArray(value) ? { rows: value, priceContext: null, results: [], endings: [] }
516
+ : value && typeof value === 'object' ? { rows: value.rows ?? [], priceContext: value.priceContext ?? null,
517
+ results: value.results ?? [], endings: value.endings ?? [] } : null;
518
+
519
+ export async function buildDossier(domain, { maxBudget, budgetMs = totalBudgetMs, clock = () => new Date(),
520
+ registry = registryFacts, site = siteFacts, listings = checkListings, alternatives = findAlternatives,
521
+ renewal = renewalFact, providerList = providers, screen = screenName, ...deps } = {}) {
522
+ const started = performance.now();
523
+ const deadline = started + budgetMs;
524
+ const controller = new AbortController();
525
+ const stop = setTimeout(() => controller.abort(), budgetMs);
526
+ const { signal } = controller;
527
+ const left = share => Math.max(0, Math.min(budgetMs * share, deadline - performance.now()));
528
+ const screenLeft = () => Math.max(0, deadline - performance.now() - screenReserveMs);
529
+ try {
530
+ const registryRun = bounded(registry(domain, { ...deps, signal, deadline: started + left(0.5), clock }), left(0.55), null);
531
+ const siteRun = bounded(site(domain, { ...deps, signal, clock }), left(0.6), null);
532
+ const alternativesRun = bounded(alternatives(domain, { ...deps, budgetMs: Math.floor(left(0.55)), clock }), left(0.7), null)
533
+ .then(alternativesOf);
534
+ // One screen per name label: two exact endings share one. The taken name's own label starts at once, alongside
535
+ // the registry and price work, and gets the reused answers when they land; a variant label starts once picked.
536
+ const screens = new Map();
537
+ const name = labelOf(domain);
538
+ const startScreen = (label, endings, domains) => {
539
+ if (screens.has(label)) return;
540
+ screens.set(label, Promise.resolve().then(() => screen(label, { endings, domains, budgetMs: screenLeft(), clock,
541
+ directory: deps.directory })).catch(() => null));
542
+ };
543
+ const exactEndings = [...new Set([domainEnding(domain), ...defaultEndings])].filter(ending => supportedEndings.includes(ending));
544
+ startScreen(name, exactEndings, Promise.all([alternativesRun, registryRun, siteRun])
545
+ .then(([found, facts, siteNow]) => screenGroup(name, domain, found, facts, siteNow)));
546
+ const screened = alternativesRun.then(async found => {
547
+ if (!found?.rows.length) return new Map();
548
+ const labels = [...new Set([name, ...found.rows.map(row => row.label ?? labelOf(row.domain))])];
549
+ for (const label of labels.slice(1)) startScreen(label, ['com'], screenGroup(label, domain, found, null, null));
550
+ const settled = await Promise.all(labels.map(label =>
551
+ bounded(screens.get(label), Math.max(0, deadline - performance.now() - 50), undefined)));
552
+ return new Map(labels.map((label, index) => [label, settled[index] === undefined ? pendingScreen
553
+ : settled[index] ?? { state: 'unavailable', verdict: null, reason: 'Name screen could not run' }]));
554
+ });
555
+ const [registryResult, siteResult, listingRows, alternativeData, renewalResult, screenResults] = await Promise.all([
556
+ registryRun, siteRun,
557
+ bounded(listings(domain, { list: providerList, signal, clock }), left(0.8), null),
558
+ alternativesRun,
559
+ bounded(renewal(domain, { ...deps, clock }), left(0.2), null),
560
+ screened,
561
+ ]);
562
+ const now = clock();
563
+ const registryData = registryResult ?? { registered: 'unknown', checkedAt: now.toISOString(), source: null, created: null,
564
+ expires: null, changed: null, registrar: null, registrarIanaId: null, status: [], nameservers: [], marketplaceNameservers: null,
565
+ reason: 'registry check ran out of time' };
566
+ const siteData = siteResult ?? { state: 'unknown', checkedAt: now.toISOString(), url: 'https://' + domain + '/', chain: [], reason: 'site check ran out of time' };
567
+ const listingData = listingRows ?? providerList.map(provider => ({ id: provider.id, name: provider.name,
568
+ manualUrl: provider.manualUrl(domain) ?? null, state: 'unavailable', reason: 'ran out of time' }));
569
+ const listing = listingEvidence(siteData, listingData);
570
+ const outlook = expiryOutlook(registryData, now.getTime());
571
+ const track = chooseTrack(registryData, listing, outlook);
572
+ const range = fairRange(listing.listed);
573
+ const asking = range && range.low != null && range.low === range.high ? { amount: range.low, currency: range.currency } : null;
574
+ const baseScreen = screenResults.get(name);
575
+ return {
576
+ domain, checkedAt: now.toISOString(), elapsedMs: Math.round(performance.now() - started),
577
+ track, registry: registryData, expiry: outlook, site: siteData,
578
+ listings: {
579
+ found: listing.listed, signals: listing.signals,
580
+ checked: listingData.filter(row => ['listed', 'not-listed', 'unknown'].includes(row.state)),
581
+ unavailable: listingData.filter(row => row.state === 'unavailable'),
582
+ unchecked: listingData.filter(row => row.state === 'unchecked'),
583
+ absence: listingData.length && listingData.every(row => row.state === 'not-listed') ? 'confirmed' : 'unknown',
584
+ },
585
+ owner: ownerSignal(registryData, siteData, listing),
586
+ fairRange: range, renewalCost: renewalResult,
587
+ alternatives: (alternativeData?.rows ?? []).map(row => {
588
+ const label = row.label ?? labelOf(row.domain);
589
+ return { ...row, screen: screenResults.get(label) ?? pendingScreen,
590
+ ...(label !== name && baseScreen && baseScreen.verdict !== 'No conflict found' && { baseScreen }) };
591
+ }),
592
+ priceContext: alternativeData?.priceContext ?? null,
593
+ // One entry per screened name label, shared by every alternative with that label.
594
+ screens: Object.fromEntries(screenResults),
595
+ drafts: ['available', 'unknown', 'expiring'].includes(track) ? null
596
+ : draftNotes(domain, { asking, maxBudget, throughMarketplace: listing.listed.some(row => row.source !== 'own site') }),
597
+ private: { maxBudget: maxBudget ?? null, note: 'Private: never in drafts or messages to the owner.' },
598
+ };
599
+ } finally {
600
+ clearTimeout(stop);
601
+ controller.abort();
602
+ }
603
+ }