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.
@@ -5,11 +5,17 @@ import { saleSignal } from './parking.mjs';
5
5
  import { cacheDir, mapLimit, readCache, writeCache } from './cache.mjs';
6
6
 
7
7
  export const bootstrapUrl = 'https://data.iana.org/rdap/dns.json';
8
- const cachedEndings = new Set(['co', 'me', 'io', 'app', 'dev']);
9
- const registrationLifetime = 5 * 60_000;
8
+ // A conclusive registry answer is reused: a registration for a day, an absence for an hour. DNS still runs first,
9
+ // so a name registered since then shows up through its name servers.
10
+ export const takenLifetime = 24 * 3_600_000;
11
+ export const freeLifetime = 3_600_000;
10
12
  const identityDigital = 'https://rdap.identitydigital.services';
11
- const identityDigitalCooldown = 'rdap-identity-digital-cooldown.json';
12
13
  const rdapRateLimit = 'Registry RDAP returned HTTP 429';
14
+ // A rate-limited registry host is left alone for its Retry-After in this process and the next.
15
+ const legacyIdentityCooldown = 'rdap-identity-digital-cooldown.json';
16
+ const cooldownFile = origin => 'rdap-cooldown-' + new URL(origin).hostname + '.json';
17
+ // The fallback steps (registry WHOIS, then DNS) keep this much of the lookup time.
18
+ const fallbackReserve = 800;
13
19
 
14
20
  const overrides = new Map([
15
21
  ['co', 'https://rdap.registry.co/co/'],
@@ -61,7 +67,7 @@ function unknown(source, reason) {
61
67
 
62
68
  // A registry that exposes premium or reserved status says so in plain words. "All rights reserved" never counts.
63
69
  const reservedWords = /\b(?:(?:domain|name) (?:is |has been )?reserved|reserved (?:domain|name)|reserved (?:by|for) (?:the )?registry|not available for registration)\b/i;
64
- const premiumWords = /\bpremium (?:domain|name|price|pricing|tier)\b|\b(?:domain|name) is premium\b/i;
70
+ const premiumWords = /\bregistry premium\b|\bpremium (?:domain|name|price|pricing|tier)\b|\b(?:domain|name) is premium\b/i;
65
71
 
66
72
  export function registrySignal(text) {
67
73
  const value = String(text ?? '');
@@ -84,18 +90,64 @@ function signalled(source, signal) {
84
90
  return { status: 'free', source, ...(signal && { signal }) };
85
91
  }
86
92
 
93
+ // The recursive DNS answer: name servers mean registered; otherwise a reason and the DNS error code.
87
94
  async function dnsStatus(domain, resolveNs) {
88
95
  try {
89
96
  const nameservers = await resolveNs(domain);
90
97
  if (nameservers.length) return { status: 'taken', source: 'dns', nameservers, ...saleSignal(nameservers) };
91
- return 'DNS returned no name servers';
98
+ return { reason: 'DNS returned no name servers', code: null };
92
99
  } catch (error) {
93
- if (['ENOTFOUND', 'ENODATA'].includes(error?.code)) return 'DNS returned no name servers';
94
- if (['ETIMEOUT', 'ECANCELLED'].includes(error?.code)) return 'DNS timed out';
95
- return 'DNS query failed';
100
+ const code = typeof error?.code === 'string' ? error.code : null;
101
+ if (['ENOTFOUND', 'ENODATA'].includes(code)) return { reason: 'DNS returned no name servers', code };
102
+ if (['ETIMEOUT', 'ECANCELLED'].includes(code)) return { reason: 'DNS timed out', code };
103
+ return { reason: 'DNS query failed', code };
96
104
  }
97
105
  }
98
106
 
107
+ // Ask the ending's own authoritative name servers whether they delegate the name. NXDOMAIN means it is not in the
108
+ // zone (likely free, though a registered name without name servers looks the same); a referral or an answer means it
109
+ // is delegated (likely taken). Only a likelihood: a registry or shop still settles it.
110
+ const tldServers = new Map();
111
+ export async function systemAuthoritativeNs(domain, timeout) {
112
+ if (!(timeout >= 150)) return null;
113
+ const deadline = Date.now() + timeout;
114
+ const left = () => Math.max(1, deadline - Date.now());
115
+ const tld = domain.split('.').at(-1);
116
+ const lookup = new Resolver({ timeout: Math.min(800, timeout), tries: 1 });
117
+ const stop = setTimeout(() => lookup.cancel(), timeout);
118
+ let direct;
119
+ let stopDirect;
120
+ try {
121
+ if (!tldServers.has(tld)) {
122
+ tldServers.set(tld, lookup.resolveNs(tld).then(async hosts => (await Promise.all(hosts.slice(0, 3)
123
+ .map(host => lookup.resolve4(host).catch(() => [])))).flat().slice(0, 4)).catch(() => []));
124
+ }
125
+ const servers = await tldServers.get(tld);
126
+ if (!servers.length) {
127
+ tldServers.delete(tld);
128
+ return null;
129
+ }
130
+ direct = new Resolver({ timeout: left(), tries: 1 });
131
+ direct.setServers(servers);
132
+ stopDirect = setTimeout(() => direct.cancel(), left());
133
+ await direct.resolveSoa(domain);
134
+ return 'taken';
135
+ } catch (error) {
136
+ if (!direct) return null;
137
+ if (error?.code === 'ENOTFOUND') return 'free';
138
+ if (error?.code === 'ENODATA') return 'taken';
139
+ return null;
140
+ } finally {
141
+ clearTimeout(stop);
142
+ clearTimeout(stopDirect);
143
+ }
144
+ }
145
+
146
+ // The recursive answer as a likelihood, used when the authoritative check is not available.
147
+ function recursiveLikely(code) {
148
+ return code === 'ENOTFOUND' ? 'free' : null;
149
+ }
150
+
99
151
  export function systemQueryWhois(host, query, timeout) {
100
152
  if (timeout <= 0) return Promise.resolve('');
101
153
  return new Promise(resolve => {
@@ -140,15 +192,29 @@ async function lookupWhois(domain, tld, query, timeLeft, referrals) {
140
192
  return unknown('whois', 'Registry WHOIS returned no definitive answer');
141
193
  }
142
194
 
195
+ // Retry-After as milliseconds from now: delta seconds ("120") or an HTTP date. Null when absent or unreadable.
196
+ export function retryAfterMs(value, now = Date.now()) {
197
+ const text = typeof value === 'string' ? value.trim() : '';
198
+ if (!text) return null;
199
+ if (/^\d+$/.test(text)) {
200
+ const duration = Number(text) * 1000;
201
+ return Number.isSafeInteger(now + duration) ? duration : null;
202
+ }
203
+ if (!/[a-z]/i.test(text)) return null;
204
+ const at = Date.parse(text);
205
+ return Number.isFinite(at) ? Math.max(0, at - now) : null;
206
+ }
207
+
143
208
  function retryWait(value, attempt, limited = false) {
144
209
  const backoff = (limited ? 650 : 150) * 2 ** attempt;
145
- return Math.max(backoff, /^\d+$/.test(value ?? '') ? Number(value) * 1000 : Date.parse(value) - Date.now() || 0);
210
+ return Math.max(backoff, retryAfterMs(value) ?? 0);
146
211
  }
147
212
 
148
213
  async function lookupRdap(base, domain, fetcher, timeLeft, readExpiry, pause, registry, attempts, directory) {
149
214
  let last = unknown('rdap', 'Registry lookup timed out');
150
215
  for (let attempt = 0; attempt < attempts && timeLeft() > 0; attempt++) {
151
216
  const now = Date.now();
217
+ // A queued request never goes to a host that is cooling down.
152
218
  if (registry.limitedUntil > now) return unknown('rdap', rdapRateLimit);
153
219
  const startsAt = Math.max(registry.retryAt, registry.nextStart, now);
154
220
  if (startsAt - now >= timeLeft()) return last;
@@ -159,6 +225,7 @@ async function lookupRdap(base, domain, fetcher, timeLeft, readExpiry, pause, re
159
225
  if (wait >= timeLeft()) return last;
160
226
  if (wait > 0) await pause(wait);
161
227
  }
228
+ if (registry.limitedUntil > Date.now()) return unknown('rdap', rdapRateLimit);
162
229
  if (timeLeft() <= 0) return last;
163
230
  let wait = retryWait(null, attempt);
164
231
  try {
@@ -185,12 +252,16 @@ async function lookupRdap(base, domain, fetcher, timeLeft, readExpiry, pause, re
185
252
  await response.body?.cancel().catch(() => {});
186
253
  last = unknown('rdap', 'Registry RDAP returned HTTP ' + status);
187
254
  if (status !== 429 && status < 500) return last;
188
- wait = retryWait(response.headers?.get('retry-after'), attempt, status === 429);
255
+ const header = response.headers?.get('retry-after');
256
+ wait = retryWait(header, attempt, status === 429);
189
257
  if (status === 429 || status === 503) registry.retryAt = Math.max(registry.retryAt, Date.now() + wait);
190
- if (status === 429 && registry.identity && wait >= timeLeft()) {
191
- registry.limitedUntil = registry.retryAt;
192
- await writeCache(directory, identityDigitalCooldown, { until: registry.limitedUntil }).catch(() => {});
193
- return last;
258
+ // The host's cooldown holds for this process and, through the cache, for the next lookups too.
259
+ if (status === 429 || (status === 503 && retryAfterMs(header) != null)) {
260
+ const outlasts = wait >= timeLeft();
261
+ // Queued requests see the cooldown before the cache write finishes.
262
+ if (outlasts) registry.limitedUntil = Math.max(registry.limitedUntil, registry.retryAt);
263
+ await writeCache(directory, cooldownFile(base), { until: registry.retryAt }).catch(() => {});
264
+ if (outlasts) return last;
194
265
  }
195
266
  } catch {
196
267
  last = unknown('rdap', 'Registry RDAP did not respond');
@@ -202,25 +273,53 @@ async function lookupRdap(base, domain, fetcher, timeLeft, readExpiry, pause, re
202
273
  }
203
274
 
204
275
  export async function lookupRegistrations(candidates, {
205
- directory = cacheDir, fetcher = globalThis.fetch, resolveNs = systemResolveNs, queryWhois = systemQueryWhois,
276
+ directory = cacheDir, fetcher = globalThis.fetch, resolveNs = systemResolveNs, queryWhois, authoritativeNs,
206
277
  now = new Date(), timeLeft = () => 8500, dnsFirst = true, readExpiry = false, pause = delay,
207
278
  onResult = () => {}, concurrency = 4, rdapAttempts = 3,
208
279
  } = {}) {
280
+ const whois = queryWhois ?? systemQueryWhois;
281
+ // The fallbacks use the system network only in live use: a caller that injects its own network gets no other.
282
+ const fallbackWhois = queryWhois ?? (fetcher === globalThis.fetch ? systemQueryWhois : null);
283
+ const dnsSignal = authoritativeNs ?? (resolveNs === systemResolveNs ? systemAuthoritativeNs : null);
284
+ const reserve = Math.min(fallbackReserve, Math.max(0, timeLeft() - 1500));
285
+ const rdapLeft = () => timeLeft() - reserve;
209
286
  const services = candidates.some(({ tld }) => !rdapBase(tld))
210
287
  ? bootstrap(directory, fetcher, now, timeLeft) : null;
211
288
  const referrals = new Map();
212
289
  const pending = candidates.map(async (candidate, index) => {
213
- const dns = dnsFirst ? await dnsStatus(candidate.domain, resolveNs) : '';
290
+ const dns = dnsFirst ? await dnsStatus(candidate.domain, resolveNs) : null;
214
291
  return { candidate, index, dns };
215
292
  });
216
293
  const results = [];
217
294
  function record({ candidate, index, dns }, registry) {
218
- if (registry.status === 'unknown' && dns) registry.reason = dns + '; ' + registry.reason;
295
+ if (registry.status === 'unknown' && dns?.reason) registry.reason = dns.reason + '; ' + registry.reason;
219
296
  results[index] = registry;
220
297
  onResult(candidate, registry);
221
298
  }
299
+ async function finish(row, result, filename) {
300
+ record(row, result);
301
+ if (filename && ['taken', 'free'].includes(result.status)) {
302
+ await writeCache(directory, filename, { at: now.getTime(), result }).catch(() => {});
303
+ }
304
+ }
305
+ // DNS as a likelihood when the registry stays silent: the ending's authoritative servers when available, else the
306
+ // recursive answer from the first DNS step. Never a free result.
307
+ async function dnsLikely(row) {
308
+ const wait = Math.min(900, Math.floor(timeLeft()));
309
+ if (dnsSignal && wait >= 150) {
310
+ // The deadline holds even if a resolver never answers.
311
+ let timer;
312
+ const answer = await Promise.race([
313
+ Promise.resolve().then(() => dnsSignal(row.candidate.domain, wait)).catch(() => null),
314
+ new Promise(resolve => { timer = setTimeout(resolve, wait + 50, null); }),
315
+ ]);
316
+ clearTimeout(timer);
317
+ if (answer === 'free' || answer === 'taken') return answer;
318
+ }
319
+ return recursiveLikely(row.dns?.code);
320
+ }
222
321
  const records = pending.map(entry => entry.then(row => {
223
- if (typeof row.dns !== 'string') {
322
+ if (row.dns?.status === 'taken') {
224
323
  record(row, row.dns);
225
324
  return null;
226
325
  }
@@ -240,35 +339,49 @@ export async function lookupRegistrations(candidates, {
240
339
  }
241
340
  registries.get(origin).jobs.push({ base, entry: records[index] });
242
341
  }));
243
- await Promise.all([...registries.values()].map(async registry => {
244
- if (registry.identity) {
245
- const saved = await readCache(directory, identityDigitalCooldown);
246
- if (Number.isFinite(saved?.until) && saved.until > Date.now()) registry.limitedUntil = saved.until;
342
+ // Rows the registry left open, for the WHOIS and DNS fallbacks once every host has had its turn.
343
+ const unsettled = [];
344
+ await Promise.all([...registries].map(async ([origin, registry]) => {
345
+ if (origin.startsWith('https:')) {
346
+ const saved = await readCache(directory, cooldownFile(origin));
347
+ const legacy = origin === identityDigital ? await readCache(directory, legacyIdentityCooldown) : null;
348
+ registry.limitedUntil = Math.max(saved?.until || 0, legacy?.until || 0);
247
349
  }
248
350
  return mapLimit(registry.jobs, registry.limit, async ({ base, entry }) => {
249
351
  const row = await entry;
250
352
  if (!row) return;
251
353
  const { domain, tld } = row.candidate;
252
- const filename = dnsFirst && cachedEndings.has(tld) ? 'rdap-' + domain + '.json' : null;
354
+ const filename = dnsFirst ? 'rdap-' + domain + '.json' : null;
253
355
  const cached = filename && await readCache(directory, filename);
254
356
  const age = now - cached?.at;
255
- if (age >= 0 && age < registrationLifetime && ['taken', 'free'].includes(cached.result?.status)) {
357
+ const lifetime = { taken: takenLifetime, free: freeLifetime }[cached?.result?.status] ?? 0;
358
+ if (age >= 0 && age < lifetime) {
256
359
  record(row, { ...cached.result, checkedAt: new Date(cached.at).toISOString() });
257
360
  return;
258
361
  }
259
- const fromWhois = () => lookupWhois(domain, tld, queryWhois, timeLeft, referrals)
260
- .catch(() => unknown('whois', 'Registry WHOIS did not respond'));
261
- let result = base ? await lookupRdap(base, domain, fetcher, timeLeft, readExpiry, pause, registry, rdapAttempts, directory)
262
- : await services ? await fromWhois() : unknown('rdap', 'IANA RDAP bootstrap is unavailable');
263
- if ((tld === 'me' || tld === 'io') && result.reason === rdapRateLimit && timeLeft() > 0) {
264
- const fallback = await fromWhois();
265
- if (fallback.status !== 'unknown') result = fallback;
266
- }
267
- record(row, result);
268
- if (filename && result.status !== 'unknown') {
269
- await writeCache(directory, filename, { at: now.getTime(), result }).catch(() => {});
270
- }
362
+ const result = base ? await lookupRdap(base, domain, fetcher, rdapLeft, readExpiry, pause, registry, rdapAttempts, directory)
363
+ : await services ? await lookupWhois(domain, tld, whois, timeLeft, referrals)
364
+ .catch(() => unknown('whois', 'Registry WHOIS did not respond'))
365
+ : unknown('rdap', 'IANA RDAP bootstrap is unavailable');
366
+ if (result.status === 'unknown' && !result.signal) unsettled.push({ row, result, filename, viaWhois: !base });
367
+ else await finish(row, result, filename);
271
368
  });
272
369
  }));
370
+ // Registry WHOIS (where IANA documents one for the ending) and the DNS likelihood run side by side per row, so a
371
+ // slow WHOIS server never uses up the time of the DNS step. A WHOIS answer settles the row; DNS only suggests.
372
+ await mapLimit(unsettled, 6, async ({ row, result, filename, viaWhois }) => {
373
+ const { domain, tld } = row.candidate;
374
+ // IANA lists RDAP as the sole registration service for Google's .app and .dev.
375
+ const query = ['app', 'dev'].includes(tld) ? null : fallbackWhois;
376
+ const [answer, likely] = await Promise.all([
377
+ query && !viaWhois && timeLeft() > 600
378
+ ? lookupWhois(domain, tld, query, () => timeLeft() - 300, referrals)
379
+ .catch(() => unknown('whois', 'Registry WHOIS did not respond')) : null,
380
+ dnsLikely(row),
381
+ ]);
382
+ const settled = answer && (answer.status !== 'unknown' || answer.signal) ? answer
383
+ : likely ? { ...result, likely, likelySource: 'dns' } : result;
384
+ await finish(row, settled, filename);
385
+ });
273
386
  return results;
274
387
  }
@@ -7,8 +7,8 @@ import { cacheDir, mapLimit, readCache, writeCache } from './cache.mjs';
7
7
  import { bootstrapUrl, rdapBase, rdapDomainUrl } from './registry.mjs';
8
8
  import { compactText, day, letters, readJson, request } from './triage-sources.mjs';
9
9
 
10
- // Every traction threshold lives in this table. Tuned with the Notion (strong), RouteMender AI (none)
11
- // and OakenRoom home-improvement site (some) fixtures in traction.test.mjs.
10
+ // Every traction threshold lives in this table. Tuned with the strong, no-traction and some-traction
11
+ // fixtures in traction.test.mjs.
12
12
  // strong: a Goliath. Any one signal is enough.
13
13
  // some: real but small use. Domain age counts only with a live, current site.
14
14
  // dormant: parked or for-sale pages, or stale live sites with a tiny crawl and no Tranco rank.
@@ -348,6 +348,7 @@ export function collectRivals({ name, input = name, sites = {}, entities, topics
348
348
  owner.wikipedia ??= rival.wikipedia;
349
349
  owner.apps.push(...rival.apps);
350
350
  owner.description ??= rival.description;
351
+ owner.website ??= rival.website;
351
352
  if (rival.sources.includes('wikidata') && !owner.sources.includes('wikidata-name')) {
352
353
  owner.name = rival.name;
353
354
  owner.sources.push('wikidata-name');
@@ -371,7 +372,9 @@ export function collectRivals({ name, input = name, sites = {}, entities, topics
371
372
  // A site that redirects to another home of the same name (notion.ai to notion.com) joins that rival.
372
373
  const final = site.state === 'live' && site.host ? siteDomain(site.host) : null;
373
374
  add(base(head?.head ?? domain, 'site', {
374
- domains: [domain, ...(final && final !== domain && ownsName(name, final) ? [final] : [])], refs: [domain], site: { domain, state: site.state, copyright: site.copyright, lastModified: site.lastModified },
375
+ domains: [domain, ...(final && final !== domain && ownsName(name, final) ? [final] : [])], refs: [domain],
376
+ website: final ?? (site.state === 'live' ? domain : undefined),
377
+ site: { domain, state: site.state, copyright: site.copyright, lastModified: site.lastModified },
375
378
  description: compactText([site.title, site.description].filter(Boolean).join(' '), 200) || undefined,
376
379
  sameBusiness: site.state === 'live' && sameBusiness([site.title, site.description].join(' ')),
377
380
  }));
@@ -380,7 +383,7 @@ export function collectRivals({ name, input = name, sites = {}, entities, topics
380
383
  if (!entity?.brand || letters(entity.name) !== letters(name)) continue;
381
384
  const homes = (entity.website ?? []).map(siteDomain).filter(domain => domain && ownsName(name, domain));
382
385
  add(base(entity.name, 'wikidata', {
383
- domains: [...new Set(homes)], refs: [entity], description: entity.description || undefined,
386
+ domains: [...new Set(homes)], website: homes[0], refs: [entity], description: entity.description || undefined,
384
387
  wikipedia: entity.wikipedia ?? null, sitelinks: entity.sitelinks ?? 0,
385
388
  sameBusiness: sameBusiness(entity.name + ' ' + (entity.description ?? '')),
386
389
  }));
@@ -481,7 +484,7 @@ export function assessRival(rival, evidence = new Map(), { now = Date.now(), ans
481
484
  if (best.age && yearsSince(best.age.date, now) >= T.some.domainYears) {
482
485
  signals.push(signal('domain since ' + best.age.date.slice(0, 4), 'some', 0.3));
483
486
  }
484
- const home = best.tranco?.domain ?? best.crawl?.domain ?? best.age?.domain ?? rival.domains[0];
487
+ const home = rival.website ?? (rival.site?.state === 'live' ? rival.site.domain : null);
485
488
  if (rival.wikipedia && T.strong.wikipediaArticle) signals.push(signal('Wikipedia article', 'strong', 0.9));
486
489
  for (const app of rival.apps) {
487
490
  if (!Number.isSafeInteger(app.ratings)) continue;
@@ -590,7 +593,7 @@ export function tractionSummary(judged) {
590
593
  if (!main || level[main.level] < 1) return judged.agent ? { geo } : null;
591
594
  return {
592
595
  rival: rivalLabel(main), level: main.level, ...(main.rival.sameBusiness && { sameBusiness: true }),
593
- signals: main.signals.slice(0, 2).map(item => item.text), geo,
596
+ ...(main.home && { domain: main.home }), signals: main.signals.slice(0, 2).map(item => item.text), geo,
594
597
  };
595
598
  }
596
599
 
@@ -30,7 +30,14 @@ export const handleSearches = {
30
30
  YouTube: 'https://www.youtube.com/@{name}',
31
31
  };
32
32
 
33
- export const letters = value => String(value ?? '').normalize('NFKD').toLowerCase().replace(/[^a-z0-9]/g, '');
33
+ // Latin letters for name matching: accents drop, and letters without a decomposition fold too (ø -> o, æ -> ae).
34
+ const folds = [[/æ/g, 'ae'], [/ø/g, 'o'], [/œ/g, 'oe'], [/ß/g, 'ss'], [/[đð]/g, 'd'], [/þ/g, 'th'], [/ł/g, 'l'], [/ı/g, 'i']];
35
+ export function foldLatin(value) {
36
+ let text = String(value ?? '').normalize('NFC').toLowerCase();
37
+ for (const [pattern, replacement] of folds) text = text.replace(pattern, replacement);
38
+ return text.normalize('NFKD').replace(/\p{M}/gu, '');
39
+ }
40
+ export const letters = value => foldLatin(value).replace(/[^a-z0-9]/g, '');
34
41
  export const compactText = (value, limit) => String(value ?? '')
35
42
  .replace(/[\p{Cc}\p{Cf}\s]+/gu, ' ').trim().slice(0, limit);
36
43
 
@@ -1,5 +1,6 @@
1
- import { canRecommend, defaultEndings, eligibilityNotes, nameCandidates, normalizeName, searchCandidates,
1
+ import { canRecommend, defaultEndings, eligibilityNotes, nameCandidates, normalizeName, searchCandidates, searchKey,
2
2
  validEligibility, validEndings } from './name-search.mjs';
3
+ import { shopSearchUrl } from './prices.mjs';
3
4
  import { checkHandles, compactText, handleSearches, letters, searchApps, searchEntities, searchMarks, trademarkSearches } from './triage-sources.mjs';
4
5
  import { loadEdgarCompanies, matchEdgarCompanies, searchNorwegianCompanies } from './company-search.mjs';
5
6
  import { mapLimit } from './cache.mjs';
@@ -216,12 +217,14 @@ export async function namePresence(input, options = {}) {
216
217
  // Same-name rivals with measured traction follow the traction rules first; evidence whose traction could not be
217
218
  // measured keeps the earlier same-name checks. Trademark and availability guardrails stay in place.
218
219
  function baseVerdict({ rival, overlap, sameName, activeApp, brand, app, entity, mark, site, best, available, marks, apps, android,
219
- androidAnswered = android, com }) {
220
+ androidAnswered = android, company, premium = [] }) {
220
221
  if (rival?.[0] === 'Avoid') return rival;
221
222
  if (overlap) return ['Avoid', overlap.domain + ' is a live business in the same category'];
222
223
  if (activeApp) return ['Avoid', activeApp.name + ' is an app in the same category with ' + activeApp.ratings + ' ' + activeApp.store + ' ratings'];
223
224
  if (mark?.relevant && mark.tier !== 'Fuzzy') return ['Avoid', trademarkReason(mark)];
224
225
  if (rival) return rival;
226
+ if (company) return ['Check first', company.name + ' is an active same-name company' +
227
+ (company.employees > 0 ? ' with ' + company.employees + ' employees' : '')];
225
228
  if (brand) return ['Check first', brand.name + ' is an existing company or product in Wikidata'];
226
229
  if (mark) return ['Check first', trademarkReason(mark)];
227
230
  if (sameName.level !== 'few') return ['Check first', 'Several public sources show same-name use'];
@@ -230,9 +233,11 @@ function baseVerdict({ rival, overlap, sameName, activeApp, brand, app, entity,
230
233
  if (site) return ['Check first', site.domain + ' has a live site under this name'];
231
234
  if (entity) return ['Check first', 'An exact-name Wikidata entity already exists'];
232
235
  if (!marks || !apps || !androidAnswered || sameName.unchecked?.length) return ['Check first', 'A competition source did not answer'];
233
- if (com?.status === 'check-at-shop') return ['Check first', 'The .com registry status is unresolved'];
234
- if (!best) return ['Check first', available.length ? 'The free endings require buyer eligibility' : 'No domain was found free at the registry'];
235
- return ['No conflict found', 'No close US mark, app or site overlap'];
236
+ if (!best) {
237
+ return ['Check first', available.length ? 'The free endings require buyer eligibility'
238
+ : premium.length ? 'The free endings may be premium, price at shop' : 'No domain was found free at the registry'];
239
+ }
240
+ return ['No conflict found', 'No US mark, same-name app or active company found in the sources checked'];
236
241
  }
237
242
 
238
243
  export async function triageNames(inputs, options = {}) {
@@ -244,10 +249,14 @@ export async function triageNames(inputs, options = {}) {
244
249
  if (options.eligible !== undefined && !validEligibility(options.eligible)) return { error: 'Eligible endings must list supported restricted endings, such as no.' };
245
250
  const endings = options.endings ?? defaultEndings;
246
251
  const websiteEndings = [...new Set([...endings, ...coreWebsiteEndings])];
252
+ // Each name has its DNS label (punycode for æøå) for domains, and a Latin key for the rival, app and mark sources.
247
253
  const names = new Map();
254
+ const keys = new Map();
248
255
  for (const input of inputs) {
249
256
  const name = normalizeName(input);
250
- if (!names.has(name)) names.set(name, input.trim());
257
+ if (names.has(name)) continue;
258
+ names.set(name, input.trim());
259
+ keys.set(name, searchKey(input));
251
260
  }
252
261
  const budgetMs = options.budgetMs ?? 13200;
253
262
  const started = performance.now();
@@ -275,7 +284,7 @@ export async function triageNames(inputs, options = {}) {
275
284
  const groups = [...names.keys()].map(name => ({
276
285
  name, candidates: nameCandidates(name, { variants: false, endings: websiteEndings }),
277
286
  }));
278
- const entries = [...names].map(([name, input], index) => [name, input, index]);
287
+ const entries = [...names].map(([name, input], index) => [keys.get(name), input, index]);
279
288
  const check = (concurrency, lookup, after = () => {}) => mapLimit(entries, concurrency, async ([name, input, index]) => {
280
289
  const result = signal.aborted ? null : await retry(() => lookup(name, input, sources), found);
281
290
  after(result, index);
@@ -295,14 +304,16 @@ export async function triageNames(inputs, options = {}) {
295
304
  });
296
305
  const [domains, marksByName, appsByName, entitiesByName, handlesByName, norwayByName, androidApps, edgar, googleByName] =
297
306
  await Promise.all([
298
- searchCandidates(groups, { ...options, bundledCatalog: null, budgetMs: Math.min(budgetMs, 11500),
307
+ // A cold cache still gets the bundled, dated list prices, so free endings never all read "price at shop".
308
+ searchCandidates(groups, { ...options, budgetMs: Math.min(budgetMs, 11500),
299
309
  siteEndings: websiteEndings, siteTimeout: 3000, siteDetails: true, onSite }),
300
310
  check(6, searchMarks), check(8, searchApps, (result, index) => startHomes(entries[index][0],
301
311
  (result ?? []).map(row => siteDomain(row.sellerUrl)).filter(domain => domain?.split('.')[0].includes(entries[index][0])))),
302
312
  entityChecks,
303
313
  Promise.all(entries.map(([name]) => checkHandles(name, sources))),
304
314
  check(8, searchNorwegianCompanies),
305
- searchAndroidApps(names, { ...sources, playBudgetMs: Math.min(12000, options.playBudgetMs ?? Infinity, budgetMs) }),
315
+ searchAndroidApps(new Map(entries.map(([key, input]) => [key, input])),
316
+ { ...sources, playBudgetMs: Math.min(12000, options.playBudgetMs ?? Infinity, budgetMs) }),
306
317
  retry(() => loadEdgarCompanies(sources), found),
307
318
  mapLimit(entries, 5, ([name, input, index]) => searchGoogle(name, input, {
308
319
  ...sources, timeoutMs: timeLeft(),
@@ -315,14 +326,15 @@ export async function triageNames(inputs, options = {}) {
315
326
  const geoByName = new Map(Object.entries(options.geo ?? {}).map(([key, value]) => [normalizeName(key), parseGeo(value)]));
316
327
  const storeAppsByName = domains.groups.map(({ name }, index) => [
317
328
  ...(appsByName[index] ?? []).map(row => ({ ...row, store: 'iOS', ref: row })),
318
- ...(androidApps.get(name) ?? []).map(row => ({ ...row, store: 'Android', ref: row })),
329
+ ...(androidApps.get(keys.get(name)) ?? []).map(row => ({ ...row, store: 'Android', ref: row })),
319
330
  ]);
320
331
  const rivalsByName = domains.groups.map(({ name, sites }, index) => {
321
332
  const raw = googleByName[index].raw ?? {};
333
+ const key = keys.get(name);
322
334
  const rivals = collectRivals({
323
- name, input: names.get(name), sites, entities: entitiesByName[index], topics: raw.topics, suggestions: raw.suggestions,
335
+ name: key, input: names.get(name), sites, entities: entitiesByName[index], topics: raw.topics, suggestions: raw.suggestions,
324
336
  apps: storeAppsByName[index], geo: geoByName.get(name),
325
- sameBusiness: text => describedBusiness(name, text, options.about, options.category),
337
+ sameBusiness: text => describedBusiness(key, text, options.about, options.category),
326
338
  });
327
339
  startEvidence(traction, rivals);
328
340
  return rivals;
@@ -338,14 +350,15 @@ export async function triageNames(inputs, options = {}) {
338
350
  const [app] = apps ?? [];
339
351
  const brand = entities?.find(row => row.brand);
340
352
  const entity = brand ?? entities?.[0];
341
- const android = androidApps.get(name);
353
+ const key = keys.get(name);
354
+ const android = androidApps.get(key);
342
355
  const google = googleByName[index];
343
356
  const judged = judgeRivals(rivalsByName[index], evidence, { now: (options.now ?? new Date()).getTime(),
344
357
  answered: { wikidata: entities != null, apps: apps != null && android != null },
345
358
  geo: geoByName.get(name), entities });
346
359
  const { explained } = judged;
347
360
  const storeApps = storeAppsByName[index];
348
- const activeApp = storeApps.find(row => !explained.has(row.ref) && row.ratings >= 100 && describedBusiness(name,
361
+ const activeApp = storeApps.find(row => !explained.has(row.ref) && row.ratings >= 100 && describedBusiness(key,
349
362
  [row.name, row.category, row.description].join(' '), options.about, options.category));
350
363
  const mark = marks?.[0];
351
364
  const others = marks?.filter(item => letters(item.name) !== letters(mark?.name)) ?? [];
@@ -360,29 +373,31 @@ export async function triageNames(inputs, options = {}) {
360
373
  const live = Object.entries(sites).flatMap(([tld, site]) => {
361
374
  const domain = name + '.' + tld;
362
375
  if (site.state !== 'live' || (site.host && site.host !== domain && !site.host.endsWith('.' + domain)
363
- && !letters([site.title, site.description].join(' ')).includes(letters(name)))) return [];
376
+ && !letters([site.title, site.description].join(' ')).includes(letters(key)))) return [];
364
377
  const business = siteCategories.find(([, pattern]) => pattern.test(site.title ?? ''))?.[0]
365
378
  ?? siteCategories.find(([, pattern]) => pattern.test(site.description ?? ''))?.[0] ?? 'unknown';
366
- const sameBusiness = describedBusiness(name, [site.title, site.description].join(' '), options.about, options.category);
379
+ const sameBusiness = describedBusiness(key, [site.title, site.description].join(' '), options.about, options.category);
367
380
  return [{ domain, title: compactText(site.title, 75), business, ...(sameBusiness && { sameBusiness }) }];
368
381
  });
369
382
  // Only same-name evidence whose traction could not be measured keeps the earlier checks.
370
383
  const unmeasured = live.filter(row => !explained.has(row.domain));
371
384
  const site = unmeasured[0];
372
385
  const overlap = unmeasured.find(row => row.sameBusiness && /\.(com|ai)$/.test(row.domain));
373
- const us = matchEdgarCompanies(name, edgar);
374
- const sameName = sameNameEvidence({ name, live, norway, us, entities, entity, github, handles });
386
+ const us = matchEdgarCompanies(key, edgar);
387
+ const company = norway?.matches.find(row => row.employees > 0 && row.match === 'exact')
388
+ ?? us?.matches.find(row => row.match === 'exact');
389
+ const sameName = sameNameEvidence({ name: key, live, norway, us, entities, entity, github, handles });
375
390
  const otherEntities = entities?.filter(row => !explained.has(row));
376
- const legacy = sameNameEvidence({ name, live: unmeasured, norway, us, entities: otherEntities, entity, github, handles });
391
+ const legacy = sameNameEvidence({ name: key, live: unmeasured, norway, us, entities: otherEntities, entity, github, handles });
377
392
  const silent = silentSources({ marks, apps, android, entities, norway, edgar, github, handles });
378
393
  const otherEntity = otherEntities?.find(row => row.brand) ?? otherEntities?.[0];
379
394
  const [decision, reason] = verdict({
380
395
  rival: tractionVerdict(judged), overlap, sameName: legacy, activeApp,
381
396
  brand: otherEntity?.brand ? otherEntity : undefined, app: apps?.find(row => !explained.has(row)), entity: otherEntity,
382
- mark, otherMark, site, silent, best, available, marks, apps,
383
- android: android?.filter(row => !explained.has(row)), androidAnswered: android, com: results.find(row => row.tld === 'com'),
397
+ mark, otherMark, site, silent, best, available, marks, apps, premium: results.filter(row => row.status === 'premium'),
398
+ android: android?.filter(row => !explained.has(row)), androidAnswered: android, company,
384
399
  });
385
- const googleExplained = explainedGoogle(name, googleByName[index].raw, judged, entities);
400
+ const googleExplained = explainedGoogle(key, googleByName[index].raw, judged, entities);
386
401
  const summary = tractionSummary(judged);
387
402
  const answered = {
388
403
  USPTO: marks, 'App Store': apps, 'Google Play': android, Google: google.google, Wikidata: entities,
@@ -408,12 +423,20 @@ export async function triageNames(inputs, options = {}) {
408
423
  google: { ...(google.google ?? { result: 'not checked', why: google.unchecked }), link: googleSearchLink(names.get(name)) },
409
424
  taken: requested.filter(row => row.status === 'taken').map(row => row.tld),
410
425
  shop_check: requested.filter(row => ['check-at-shop', 'reserved'].includes(row.status)).map(row => row.tld),
411
- // Premium endings never carry a list price; the shop shows their price.
426
+ ...(requested.some(row => row.status === 'reserved') && {
427
+ reserved: requested.filter(row => row.status === 'reserved').map(row => row.tld) }),
428
+ // Subsets of shop_check with a DNS likelihood; only a registry or shop settles them.
429
+ ...likelyEndings(requested),
430
+ // Premium endings never carry a list price; the shop shows their price. A short name may be premium.
412
431
  ...(requested.some(row => row.status === 'premium') && {
413
432
  premium: requested.filter(row => row.status === 'premium').map(row => row.tld) }),
414
- competition, buy: best?.buyUrl ?? null,
433
+ // The checkout is the listed shop's search, or the confirming shop's search when no list price is known.
434
+ competition, buy: best ? best.buyUrl ?? shopSearchUrl(best.confirmShop, best.domain) : null,
435
+ ...(options.receipt && { _receiptEndings: requested.map(row => ({ domain: row.domain, source: row.source,
436
+ checkedAt: row.checkedAt, priceAt: row.priceCheckedAt, shop: row.shop, checkout: row.buyUrl,
437
+ site: sites[row.tld], risk: row.premium === 'risk' || row.premiumRisk })) }),
415
438
  details: {
416
- memorable: memorability(name, names.get(name)),
439
+ memorable: memorability(key, names.get(name)),
417
440
  presence: Object.fromEntries(Object.entries(handles).map(([service, status]) =>
418
441
  [service, status === 'unknown' ? null : status])),
419
442
  sites: Object.fromEntries(seen), appName: appStatus(apps, android),
@@ -430,7 +453,15 @@ export async function triageNames(inputs, options = {}) {
430
453
  for (const row of googleCandidates(rows)) row.google.search = true;
431
454
  const sourcesSummary = Object.fromEntries(Object.entries(counts).map(([source, answered]) =>
432
455
  [source, Math.round(100 * answered / names.size)]));
433
- return packTriage(rows, sourcesSummary, options.compact, endings, options.eligible);
456
+ const receiptDetails = options.receipt ? structuredClone(rows.map(({ competition, details, traction, google, reason, _receiptEndings }) =>
457
+ ({ competition, details, traction, google, reason, endings: _receiptEndings }))) : null;
458
+ const result = packTriage(rows, sourcesSummary, options.compact, endings, options.eligible);
459
+ if (options.receipt) {
460
+ result.checkedAt = (options.now ?? new Date()).toISOString();
461
+ result.priceListDate = domains.priceDate?.slice(0, 10);
462
+ result.receiptDetails = receiptDetails;
463
+ }
464
+ return result;
434
465
  }
435
466
 
436
467
  // The first three ranked names, filled from the screened names in input order when fewer than three rank.
@@ -450,10 +481,17 @@ function priceEntry(row) {
450
481
  };
451
482
  }
452
483
 
484
+ function likelyEndings(rows) {
485
+ const open = rows.filter(row => row.status === 'check-at-shop');
486
+ const free = open.filter(row => row.likely === 'free').map(row => row.tld);
487
+ const taken = open.filter(row => row.likely === 'taken').map(row => row.tld);
488
+ return { ...(free.length && { likely_free: free }), ...(taken.length && { likely_taken: taken }) };
489
+ }
490
+
491
+ // Best value is the lowest total of the payments due in three years; the cheaper first payment breaks a tie.
453
492
  function bestValue(options) {
454
- const value = options.find(row => Number.isFinite(row.firstPayment) && Number.isFinite(row.renewalPayment)
455
- && row.renewalPayment <= 2 * row.firstPayment);
456
- return value === options[0] ? undefined : value;
493
+ return options.filter(row => Number.isFinite(row.threeYear)).reduce((best, row) => !best || row.threeYear < best.threeYear
494
+ || (row.threeYear === best.threeYear && row.firstPayment < best.firstPayment) ? row : best, undefined);
457
495
  }
458
496
 
459
497
  function rankedRows(rows) {
@@ -471,7 +509,7 @@ function topChoices(rows) {
471
509
  name, verdict, reason, domain: best?.domain ?? null, ending: best?.tld ?? null,
472
510
  now: best?.firstPayment ?? null, renew: best?.renewalPayment ?? null, term: best?.minimumYears ?? null,
473
511
  ...(value && { bestValue: { domain: value.domain, now: value.firstPayment,
474
- renew: value.renewalPayment, term: value.minimumYears } }),
512
+ renew: value.renewalPayment, term: value.minimumYears, y3: value.threeYear } }),
475
513
  };
476
514
  });
477
515
  }
@@ -480,7 +518,7 @@ function topChoices(rows) {
480
518
  function packTriage(rows, sources, compact, endings, eligible) {
481
519
  const prices = {};
482
520
  const top = topChoices(rows);
483
- const names = rows.map(({ _free, _recommendable, _mark, _googleExplained, ...row }) => {
521
+ const names = rows.map(({ _free, _recommendable, _mark, _googleExplained, _receiptEndings, ...row }) => {
484
522
  const own = {};
485
523
  for (const option of _free) {
486
524
  const entry = priceEntry(option);