domain-hound 0.1.2 → 0.1.3

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.
@@ -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,7 +217,7 @@ 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, com, 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'];
@@ -231,7 +232,10 @@ function baseVerdict({ rival, overlap, sameName, activeApp, brand, app, entity,
231
232
  if (entity) return ['Check first', 'An exact-name Wikidata entity already exists'];
232
233
  if (!marks || !apps || !androidAnswered || sameName.unchecked?.length) return ['Check first', 'A competition source did not answer'];
233
234
  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
+ if (!best) {
236
+ return ['Check first', available.length ? 'The free endings require buyer eligibility'
237
+ : premium.length ? 'The free endings may be premium, price at shop' : 'No domain was found free at the registry'];
238
+ }
235
239
  return ['No conflict found', 'No close US mark, app or site overlap'];
236
240
  }
237
241
 
@@ -244,10 +248,14 @@ export async function triageNames(inputs, options = {}) {
244
248
  if (options.eligible !== undefined && !validEligibility(options.eligible)) return { error: 'Eligible endings must list supported restricted endings, such as no.' };
245
249
  const endings = options.endings ?? defaultEndings;
246
250
  const websiteEndings = [...new Set([...endings, ...coreWebsiteEndings])];
251
+ // Each name has its DNS label (punycode for æøå) for domains, and a Latin key for the rival, app and mark sources.
247
252
  const names = new Map();
253
+ const keys = new Map();
248
254
  for (const input of inputs) {
249
255
  const name = normalizeName(input);
250
- if (!names.has(name)) names.set(name, input.trim());
256
+ if (names.has(name)) continue;
257
+ names.set(name, input.trim());
258
+ keys.set(name, searchKey(input));
251
259
  }
252
260
  const budgetMs = options.budgetMs ?? 13200;
253
261
  const started = performance.now();
@@ -275,7 +283,7 @@ export async function triageNames(inputs, options = {}) {
275
283
  const groups = [...names.keys()].map(name => ({
276
284
  name, candidates: nameCandidates(name, { variants: false, endings: websiteEndings }),
277
285
  }));
278
- const entries = [...names].map(([name, input], index) => [name, input, index]);
286
+ const entries = [...names].map(([name, input], index) => [keys.get(name), input, index]);
279
287
  const check = (concurrency, lookup, after = () => {}) => mapLimit(entries, concurrency, async ([name, input, index]) => {
280
288
  const result = signal.aborted ? null : await retry(() => lookup(name, input, sources), found);
281
289
  after(result, index);
@@ -295,14 +303,16 @@ export async function triageNames(inputs, options = {}) {
295
303
  });
296
304
  const [domains, marksByName, appsByName, entitiesByName, handlesByName, norwayByName, androidApps, edgar, googleByName] =
297
305
  await Promise.all([
298
- searchCandidates(groups, { ...options, bundledCatalog: null, budgetMs: Math.min(budgetMs, 11500),
306
+ // A cold cache still gets the bundled, dated list prices, so free endings never all read "price at shop".
307
+ searchCandidates(groups, { ...options, budgetMs: Math.min(budgetMs, 11500),
299
308
  siteEndings: websiteEndings, siteTimeout: 3000, siteDetails: true, onSite }),
300
309
  check(6, searchMarks), check(8, searchApps, (result, index) => startHomes(entries[index][0],
301
310
  (result ?? []).map(row => siteDomain(row.sellerUrl)).filter(domain => domain?.split('.')[0].includes(entries[index][0])))),
302
311
  entityChecks,
303
312
  Promise.all(entries.map(([name]) => checkHandles(name, sources))),
304
313
  check(8, searchNorwegianCompanies),
305
- searchAndroidApps(names, { ...sources, playBudgetMs: Math.min(12000, options.playBudgetMs ?? Infinity, budgetMs) }),
314
+ searchAndroidApps(new Map(entries.map(([key, input]) => [key, input])),
315
+ { ...sources, playBudgetMs: Math.min(12000, options.playBudgetMs ?? Infinity, budgetMs) }),
306
316
  retry(() => loadEdgarCompanies(sources), found),
307
317
  mapLimit(entries, 5, ([name, input, index]) => searchGoogle(name, input, {
308
318
  ...sources, timeoutMs: timeLeft(),
@@ -315,14 +325,15 @@ export async function triageNames(inputs, options = {}) {
315
325
  const geoByName = new Map(Object.entries(options.geo ?? {}).map(([key, value]) => [normalizeName(key), parseGeo(value)]));
316
326
  const storeAppsByName = domains.groups.map(({ name }, index) => [
317
327
  ...(appsByName[index] ?? []).map(row => ({ ...row, store: 'iOS', ref: row })),
318
- ...(androidApps.get(name) ?? []).map(row => ({ ...row, store: 'Android', ref: row })),
328
+ ...(androidApps.get(keys.get(name)) ?? []).map(row => ({ ...row, store: 'Android', ref: row })),
319
329
  ]);
320
330
  const rivalsByName = domains.groups.map(({ name, sites }, index) => {
321
331
  const raw = googleByName[index].raw ?? {};
332
+ const key = keys.get(name);
322
333
  const rivals = collectRivals({
323
- name, input: names.get(name), sites, entities: entitiesByName[index], topics: raw.topics, suggestions: raw.suggestions,
334
+ name: key, input: names.get(name), sites, entities: entitiesByName[index], topics: raw.topics, suggestions: raw.suggestions,
324
335
  apps: storeAppsByName[index], geo: geoByName.get(name),
325
- sameBusiness: text => describedBusiness(name, text, options.about, options.category),
336
+ sameBusiness: text => describedBusiness(key, text, options.about, options.category),
326
337
  });
327
338
  startEvidence(traction, rivals);
328
339
  return rivals;
@@ -338,14 +349,15 @@ export async function triageNames(inputs, options = {}) {
338
349
  const [app] = apps ?? [];
339
350
  const brand = entities?.find(row => row.brand);
340
351
  const entity = brand ?? entities?.[0];
341
- const android = androidApps.get(name);
352
+ const key = keys.get(name);
353
+ const android = androidApps.get(key);
342
354
  const google = googleByName[index];
343
355
  const judged = judgeRivals(rivalsByName[index], evidence, { now: (options.now ?? new Date()).getTime(),
344
356
  answered: { wikidata: entities != null, apps: apps != null && android != null },
345
357
  geo: geoByName.get(name), entities });
346
358
  const { explained } = judged;
347
359
  const storeApps = storeAppsByName[index];
348
- const activeApp = storeApps.find(row => !explained.has(row.ref) && row.ratings >= 100 && describedBusiness(name,
360
+ const activeApp = storeApps.find(row => !explained.has(row.ref) && row.ratings >= 100 && describedBusiness(key,
349
361
  [row.name, row.category, row.description].join(' '), options.about, options.category));
350
362
  const mark = marks?.[0];
351
363
  const others = marks?.filter(item => letters(item.name) !== letters(mark?.name)) ?? [];
@@ -360,29 +372,29 @@ export async function triageNames(inputs, options = {}) {
360
372
  const live = Object.entries(sites).flatMap(([tld, site]) => {
361
373
  const domain = name + '.' + tld;
362
374
  if (site.state !== 'live' || (site.host && site.host !== domain && !site.host.endsWith('.' + domain)
363
- && !letters([site.title, site.description].join(' ')).includes(letters(name)))) return [];
375
+ && !letters([site.title, site.description].join(' ')).includes(letters(key)))) return [];
364
376
  const business = siteCategories.find(([, pattern]) => pattern.test(site.title ?? ''))?.[0]
365
377
  ?? siteCategories.find(([, pattern]) => pattern.test(site.description ?? ''))?.[0] ?? 'unknown';
366
- const sameBusiness = describedBusiness(name, [site.title, site.description].join(' '), options.about, options.category);
378
+ const sameBusiness = describedBusiness(key, [site.title, site.description].join(' '), options.about, options.category);
367
379
  return [{ domain, title: compactText(site.title, 75), business, ...(sameBusiness && { sameBusiness }) }];
368
380
  });
369
381
  // Only same-name evidence whose traction could not be measured keeps the earlier checks.
370
382
  const unmeasured = live.filter(row => !explained.has(row.domain));
371
383
  const site = unmeasured[0];
372
384
  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 });
385
+ const us = matchEdgarCompanies(key, edgar);
386
+ const sameName = sameNameEvidence({ name: key, live, norway, us, entities, entity, github, handles });
375
387
  const otherEntities = entities?.filter(row => !explained.has(row));
376
- const legacy = sameNameEvidence({ name, live: unmeasured, norway, us, entities: otherEntities, entity, github, handles });
388
+ const legacy = sameNameEvidence({ name: key, live: unmeasured, norway, us, entities: otherEntities, entity, github, handles });
377
389
  const silent = silentSources({ marks, apps, android, entities, norway, edgar, github, handles });
378
390
  const otherEntity = otherEntities?.find(row => row.brand) ?? otherEntities?.[0];
379
391
  const [decision, reason] = verdict({
380
392
  rival: tractionVerdict(judged), overlap, sameName: legacy, activeApp,
381
393
  brand: otherEntity?.brand ? otherEntity : undefined, app: apps?.find(row => !explained.has(row)), entity: otherEntity,
382
- mark, otherMark, site, silent, best, available, marks, apps,
394
+ mark, otherMark, site, silent, best, available, marks, apps, premium: results.filter(row => row.status === 'premium'),
383
395
  android: android?.filter(row => !explained.has(row)), androidAnswered: android, com: results.find(row => row.tld === 'com'),
384
396
  });
385
- const googleExplained = explainedGoogle(name, googleByName[index].raw, judged, entities);
397
+ const googleExplained = explainedGoogle(key, googleByName[index].raw, judged, entities);
386
398
  const summary = tractionSummary(judged);
387
399
  const answered = {
388
400
  USPTO: marks, 'App Store': apps, 'Google Play': android, Google: google.google, Wikidata: entities,
@@ -408,12 +420,15 @@ export async function triageNames(inputs, options = {}) {
408
420
  google: { ...(google.google ?? { result: 'not checked', why: google.unchecked }), link: googleSearchLink(names.get(name)) },
409
421
  taken: requested.filter(row => row.status === 'taken').map(row => row.tld),
410
422
  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.
423
+ // Subsets of shop_check with a DNS likelihood; only a registry or shop settles them.
424
+ ...likelyEndings(requested),
425
+ // Premium endings never carry a list price; the shop shows their price. A short name may be premium.
412
426
  ...(requested.some(row => row.status === 'premium') && {
413
427
  premium: requested.filter(row => row.status === 'premium').map(row => row.tld) }),
414
- competition, buy: best?.buyUrl ?? null,
428
+ // The checkout is the listed shop's search, or the confirming shop's search when no list price is known.
429
+ competition, buy: best ? best.buyUrl ?? shopSearchUrl(best.confirmShop, best.domain) : null,
415
430
  details: {
416
- memorable: memorability(name, names.get(name)),
431
+ memorable: memorability(key, names.get(name)),
417
432
  presence: Object.fromEntries(Object.entries(handles).map(([service, status]) =>
418
433
  [service, status === 'unknown' ? null : status])),
419
434
  sites: Object.fromEntries(seen), appName: appStatus(apps, android),
@@ -450,10 +465,17 @@ function priceEntry(row) {
450
465
  };
451
466
  }
452
467
 
468
+ function likelyEndings(rows) {
469
+ const open = rows.filter(row => row.status === 'check-at-shop');
470
+ const free = open.filter(row => row.likely === 'free').map(row => row.tld);
471
+ const taken = open.filter(row => row.likely === 'taken').map(row => row.tld);
472
+ return { ...(free.length && { likely_free: free }), ...(taken.length && { likely_taken: taken }) };
473
+ }
474
+
475
+ // Best value is the lowest total of the payments due in three years; the cheaper first payment breaks a tie.
453
476
  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;
477
+ return options.filter(row => Number.isFinite(row.threeYear)).reduce((best, row) => !best || row.threeYear < best.threeYear
478
+ || (row.threeYear === best.threeYear && row.firstPayment < best.firstPayment) ? row : best, undefined);
457
479
  }
458
480
 
459
481
  function rankedRows(rows) {
@@ -471,7 +493,7 @@ function topChoices(rows) {
471
493
  name, verdict, reason, domain: best?.domain ?? null, ending: best?.tld ?? null,
472
494
  now: best?.firstPayment ?? null, renew: best?.renewalPayment ?? null, term: best?.minimumYears ?? null,
473
495
  ...(value && { bestValue: { domain: value.domain, now: value.firstPayment,
474
- renew: value.renewalPayment, term: value.minimumYears } }),
496
+ renew: value.renewalPayment, term: value.minimumYears, y3: value.threeYear } }),
475
497
  };
476
498
  });
477
499
  }