domain-hound 0.1.8 → 0.1.9

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.
@@ -1,15 +1,20 @@
1
- import { randomInt } from 'node:crypto';
1
+ import { createHash, randomInt } from 'node:crypto';
2
+ import { setTimeout as delay } from 'node:timers/promises';
2
3
  import { anySignal, cacheDir, readCache, writeCache } from './cache.mjs';
4
+ import { classifyYouTubeHandle, validYouTubeHandle, youtubeHandleUrl } from './youtube-handle.mjs';
5
+ import { archiveKinds, archiveLabel, checkPublicArchives, classifyPublicCheck, fetchPublicCheck, findCommonCrawlIndex, playCacheName,
6
+ publicBodyComplete, publicCacheKind, publicCheckTiming, publicHeaders, publicHtmlLimit, publicPageKinds, publicUrls,
7
+ readsArchiveBody, readsPublicBody, threadsFromInstagram, validPlayName } from './public-name-checks.mjs';
3
8
 
4
- // Social handles. Three states only, never "free": a missing public profile does not mean the handle can be had.
5
9
  export const handleStates = {
6
10
  taken: 'Taken',
7
- 'not-found': 'No public profile found',
8
- check: 'Check yourself',
11
+ 'not-found': 'No profile found',
12
+ 'not-seen': 'No page found in public archives',
13
+ unknown: "Couldn't check",
9
14
  };
10
15
  const hour = 3_600_000;
11
- // A taken handle is reused for a week, a missing one for an hour. "Check yourself" is never cached.
12
- export const handleLifetime = { taken: 7 * 24 * hour, 'not-found': hour };
16
+ // Default lifetimes for confirmed results. Public page and embed results of either kind last an hour.
17
+ export const handleLifetime = { taken: 7 * 24 * hour, 'not-found': hour, 'not-seen': hour };
13
18
  // One platform's whole run (its two controls, the exact handles and any variants) shares this budget.
14
19
  export const platformBudgetMs = 2000;
15
20
  export const handleVariants = name => ['get' + name, name + 'app', name + 'hq'];
@@ -29,9 +34,56 @@ async function readStrictJson(response) {
29
34
  try { return JSON.parse(text); } catch { return null; }
30
35
  }
31
36
 
32
- // Each automatic check uses a documented public API that needs no login. Anything the parser does not recognise is
33
- // "check yourself".
37
+ export const publicProfiles = Object.freeze({ YouTube: 'youtube', X: 'x', Instagram: 'instagram', TikTok: 'tiktok', Threads: 'threads',
38
+ Facebook: 'facebook', LinkedIn: 'linkedin', Reddit: 'reddit', Twitch: 'twitch' });
39
+ const publicKinds = { ...publicProfiles, 'Google Play': 'googlePlay' };
40
+ export const embedChecksEnabled = (env = process.env) => env.DOMAIN_HOUND_EMBED_CHECKS !== 'off';
41
+ const disabledReason = { Instagram: 'embed only', TikTok: 'embed only', X: 'lookup requires approved API access' };
42
+ const disabled = (platform, env) => !embedChecksEnabled(env) && platform !== 'YouTube' && Object.hasOwn(publicKinds, platform);
43
+
44
+ async function readPublicBody(response, maxBytes, read, complete) {
45
+ const { status } = response;
46
+ const contentType = response.headers.get('content-type') ?? '';
47
+ const meta = { status, contentType };
48
+ if (!read(status, contentType)) {
49
+ void response.body?.cancel().catch(() => {});
50
+ return meta;
51
+ }
52
+ if (Number(response.headers.get('content-length')) > maxBytes) {
53
+ void response.body?.cancel().catch(() => {});
54
+ return { ...meta, error: 'too-large' };
55
+ }
56
+ let size = 0;
57
+ let body = '';
58
+ const decoder = new TextDecoder();
59
+ for await (const chunk of response.body ?? []) {
60
+ size += chunk.byteLength;
61
+ if (size > maxBytes) return { ...meta, error: 'too-large' };
62
+ body += decoder.decode(chunk, { stream: true });
63
+ if (complete?.(status, contentType, body)) break;
64
+ }
65
+ return { ...meta, body: body + decoder.decode() };
66
+ }
67
+
68
+ // Anything the parser does not recognise is unknown.
34
69
  const apis = {
70
+ ...Object.fromEntries(Object.entries(publicKinds).map(([platform, kind]) => [platform, {
71
+ valid: kind === 'googlePlay' ? validPlayName : kind === 'youtube' ? validYouTubeHandle
72
+ : archiveKinds.includes(kind) ? label : handle => /^[a-z0-9]+$/.test(handle),
73
+ url: publicUrls[kind],
74
+ archive: archiveKinds.includes(kind),
75
+ read: async (response, name) => classifyPublicCheck(kind, await readPublicBody(response,
76
+ publicPageKinds.includes(kind) ? publicHtmlLimit : 512 * 1024,
77
+ (status, type) => readsPublicBody(kind, status, type),
78
+ (status, type, body) => publicBodyComplete(kind, status, type, body, name)), name),
79
+ public: true,
80
+ }])),
81
+ youtubeApi: {
82
+ valid: validYouTubeHandle,
83
+ url: youtubeHandleUrl,
84
+ headers: { Accept: 'application/json' },
85
+ read: async response => classifyYouTubeHandle(response.status, await readStrictJson(response)),
86
+ },
35
87
  // GitHub REST "Get a user" (users and organizations): https://docs.github.com/en/rest/users/users#get-a-user
36
88
  GitHub: {
37
89
  valid: handle => /^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/.test(handle),
@@ -41,10 +93,10 @@ const apis = {
41
93
  const data = await readStrictJson(response);
42
94
  if (response.status === 200) {
43
95
  return typeof data?.login === 'string' && data.login.toLowerCase() === handle
44
- && ['User', 'Organization'].includes(data.type) ? 'taken' : 'check';
96
+ && ['User', 'Organization'].includes(data.type) ? 'taken' : 'unknown';
45
97
  }
46
- if (response.status === 404) return data?.message === 'Not Found' ? 'not-found' : 'check';
47
- return 'check';
98
+ if (response.status === 404) return data?.message === 'Not Found' ? 'not-found' : 'unknown';
99
+ return 'unknown';
48
100
  },
49
101
  controls: () => ({ taken: 'github', missing: syntheticLabel(28) }),
50
102
  },
@@ -55,9 +107,9 @@ const apis = {
55
107
  headers: { Accept: 'application/vnd.npm.install-v1+json' },
56
108
  read: async (response, handle) => {
57
109
  const data = await readStrictJson(response);
58
- if (response.status === 200) return data?.name === handle ? 'taken' : 'check';
59
- if (response.status === 404) return typeof data?.error === 'string' && /^not found$/i.test(data.error) ? 'not-found' : 'check';
60
- return 'check';
110
+ if (response.status === 200) return data?.name === handle ? 'taken' : 'unknown';
111
+ if (response.status === 404) return typeof data?.error === 'string' && /^not found$/i.test(data.error) ? 'not-found' : 'unknown';
112
+ return 'unknown';
61
113
  },
62
114
  controls: () => ({ taken: 'lodash', missing: syntheticLabel(24) }),
63
115
  },
@@ -70,11 +122,11 @@ const apis = {
70
122
  headers: { Accept: 'application/json' },
71
123
  read: async response => {
72
124
  const data = await readStrictJson(response);
73
- if (response.status === 200) return typeof data?.did === 'string' && /^did:(?:plc|web):[a-z0-9._:%-]+$/i.test(data.did) ? 'taken' : 'check';
125
+ if (response.status === 200) return typeof data?.did === 'string' && /^did:(?:plc|web):[a-z0-9._:%-]+$/i.test(data.did) ? 'taken' : 'unknown';
74
126
  if (response.status === 400) {
75
- return data?.error === 'InvalidRequest' && /^unable to resolve handle$/i.test(String(data.message ?? '').trim()) ? 'not-found' : 'check';
127
+ return data?.error === 'InvalidRequest' && /^unable to resolve handle$/i.test(String(data.message ?? '').trim()) ? 'not-found' : 'unknown';
76
128
  }
77
- return 'check';
129
+ return 'unknown';
78
130
  },
79
131
  // bsky.app is Bluesky's own account.
80
132
  controls: () => ({ taken: 'bsky.app', missing: syntheticLabel(14) + '.bsky.social' }),
@@ -82,26 +134,31 @@ const apis = {
82
134
  };
83
135
 
84
136
  // Display order (Lars, 2026-11-25): YouTube, X, Instagram, TikTok, Facebook, LinkedIn, then GitHub, npm, PyPI, Bluesky.
85
- // YouTube, X, Instagram, TikTok, Facebook and LinkedIn have no public no-login lookup their terms allow: link only.
86
- // PyPI is link only by decision.
137
+ export const linkedInSearch = name => 'https://www.linkedin.com/search/results/companies/?' + new URLSearchParams({ keywords: name });
138
+ const redditSearch = name => 'https://www.reddit.com/search/?' + new URLSearchParams({ q: name, type: 'users' });
139
+ export const handleLabel = row => row?.state === 'taken' && row.seenYear ? archiveLabel(row.seenYear) : handleStates[row?.state] ?? handleStates.unknown;
140
+ export const linkedInSearchHint = row => row?.platform === 'LinkedIn' && row.state === 'not-seen' && label(row.handle)
141
+ ? 'You can confirm with a web search for `site:linkedin.com/company/' + row.handle + '`.' : null;
142
+
87
143
  export const handlePlatforms = [
88
- { id: 'YouTube', link: handle => 'https://www.youtube.com/@' + handle },
89
- { id: 'X', link: handle => 'https://x.com/' + handle },
90
- { id: 'Instagram', link: handle => 'https://www.instagram.com/' + handle + '/' },
91
- { id: 'TikTok', link: handle => 'https://www.tiktok.com/@' + handle },
92
- { id: 'Facebook', link: handle => 'https://www.facebook.com/' + handle },
93
- { id: 'LinkedIn', link: handle => 'https://www.linkedin.com/company/' + handle + '/' },
144
+ { id: 'YouTube', link: handle => 'https://www.youtube.com/@' + handle, auto: true },
145
+ { id: 'X', link: handle => 'https://x.com/' + handle, auto: true },
146
+ { id: 'Instagram', link: handle => 'https://www.instagram.com/' + handle + '/', auto: true },
147
+ { id: 'TikTok', link: handle => 'https://www.tiktok.com/@' + handle, auto: true },
148
+ { id: 'Threads', link: handle => 'https://www.threads.com/@' + handle, auto: true },
149
+ { id: 'Facebook', link: handle => 'https://www.facebook.com/' + handle, auto: true },
150
+ { id: 'LinkedIn', link: handle => 'https://www.linkedin.com/company/' + handle, search: linkedInSearch, linkLabel: 'Search LinkedIn', auto: true },
94
151
  { id: 'GitHub', link: handle => 'https://github.com/' + handle, auto: true },
95
152
  { id: 'npm', link: handle => 'https://www.npmjs.com/package/' + handle, auto: true },
96
153
  { id: 'PyPI', link: handle => 'https://pypi.org/project/' + handle + '/' },
97
154
  { id: 'Bluesky', link: handle => 'https://bsky.app/profile/' + handle + '.bsky.social', auto: true },
98
155
  ];
99
- // Shown only when the person asks for them; always check links.
156
+ // Shown when the person asks for them in a local name screen.
100
157
  export const requestPlatforms = [
101
158
  { id: 'Snapchat', link: handle => 'https://www.snapchat.com/add/' + handle },
102
- { id: 'Reddit', link: handle => 'https://www.reddit.com/user/' + handle + '/' },
103
- { id: 'Twitch', link: handle => 'https://www.twitch.tv/' + handle },
104
- { id: 'Threads', link: handle => 'https://www.threads.com/@' + handle },
159
+ { id: 'Reddit', link: handle => 'https://www.reddit.com/user/' + handle + '/', search: redditSearch, linkLabel: 'Search Reddit', auto: true },
160
+ { id: 'Twitch', link: handle => 'https://www.twitch.tv/' + handle, auto: true },
161
+ handlePlatforms.find(platform => platform.id === 'Threads'),
105
162
  { id: 'Pinterest', link: handle => 'https://www.pinterest.com/' + handle + '/' },
106
163
  { id: 'Discord', link: () => 'https://support.discord.com/hc/en-us/articles/12620128861463-New-Usernames-Display-Names' },
107
164
  ];
@@ -110,7 +167,7 @@ export const autoPlatforms = handlePlatforms.filter(platform => platform.auto).m
110
167
  // In-flight lookups and control batches are shared inside one run (one process).
111
168
  const inFlight = new Map();
112
169
  const controlRuns = new Map();
113
- // Every answer this run already has, "check yourself" included, so a later step never asks again.
170
+ // Reused by the registry sources when lookup stages overlap.
114
171
  const runAnswers = new Map();
115
172
  export function resetHandleRuns() {
116
173
  inFlight.clear();
@@ -124,27 +181,55 @@ async function githubHeld(directory, now) {
124
181
  }
125
182
 
126
183
  // One request, and one retry inside the same budget when the platform fails (5xx or no response).
127
- async function request(platform, identifier, { fetcher, signal, githubToken }, retry = true) {
128
- const api = apis[platform];
129
- let failed;
184
+ async function requestWithRetry(platform, options, url, api, read, retry = true) {
185
+ const { fetcher, signal, githubToken, youtubeApiKey } = options;
186
+ const youtubeApi = platform === 'YouTube' && Boolean(youtubeApiKey);
130
187
  // An optional token lifts GitHub's 60 requests an hour for anonymous callers. It is sent only to api.github.com.
131
- const auth = platform === 'GitHub' && githubToken ? { Authorization: 'Bearer ' + githubToken } : {};
188
+ const auth = youtubeApi ? { 'x-goog-api-key': youtubeApiKey }
189
+ : platform === 'GitHub' && githubToken ? { Authorization: 'Bearer ' + githubToken } : {};
190
+ const bounded = Object.hasOwn(publicKinds, platform);
191
+ const page = api.public && publicPageKinds.includes(publicKinds[platform]);
192
+ const timeout = page ? publicCheckTiming.pageTimeoutMs : api.archive ? publicCheckTiming.archiveTimeoutMs : publicCheckTiming.timeoutMs;
193
+ const attemptSignal = bounded ? anySignal([signal, AbortSignal.timeout(timeout)]) : signal;
194
+ if (attemptSignal?.aborted) return { error: 'timeout' };
195
+ let error = 'network';
132
196
  try {
133
- const response = await fetcher(api.url(identifier), {
134
- redirect: 'error', signal, headers: { 'User-Agent': userAgent, ...api.headers, ...auth },
135
- });
136
- failed = response.status >= 500;
137
- const state = await api.read(response, identifier);
138
- const limited = platform === 'GitHub' && [403, 429].includes(response.status);
139
- if (!failed) return { state, ...(limited && { limited: Number(response.headers.get('x-ratelimit-reset')) * 1000 || null }) };
197
+ const init = { redirect: api.archive ? 'manual' : 'error', signal: attemptSignal,
198
+ headers: { 'User-Agent': userAgent, ...api.headers, ...auth, ...(api.public && !api.archive && publicHeaders) } };
199
+ const response = api.public ? await fetchPublicCheck(fetcher, url, init) : await fetcher(url, init);
200
+ if (response.status < 500) return await read(response);
201
+ void response.body?.cancel().catch(() => {});
140
202
  } catch {
141
- failed = true;
203
+ if (attemptSignal?.aborted) error = 'timeout';
142
204
  }
143
- return retry && failed && !signal?.aborted ? request(platform, identifier, { fetcher, signal, githubToken }, false) : { state: 'check' };
205
+ if (retry && !signal?.aborted) {
206
+ if (!bounded) return requestWithRetry(platform, options, url, api, read, false);
207
+ const waited = await delay(randomInt(80, 161), true, { signal }).catch(() => false);
208
+ if (waited) return requestWithRetry(platform, options, url, api, read, false);
209
+ }
210
+ return { error: signal?.aborted ? 'timeout' : error };
211
+ }
212
+
213
+ async function request(platform, identifier, options) {
214
+ const api = apis[platform === 'YouTube' && options.youtubeApiKey ? 'youtubeApi' : platform];
215
+ if (api.archive) {
216
+ const read = url => requestWithRetry(platform, options, url, api,
217
+ response => readPublicBody(response, 512 * 1024, readsArchiveBody));
218
+ return checkPublicArchives(publicKinds[platform], identifier, read, () => options.commonIndex ??= findCommonCrawlIndex(read));
219
+ }
220
+ const result = await requestWithRetry(platform, options, api.url(identifier), api, async response => {
221
+ const limited = platform === 'GitHub' && [403, 429].includes(response.status);
222
+ const why = response.status === 429 ? 'rate-limited' : 'no clear answer';
223
+ if (response.status === 429) void response.body?.cancel().catch(() => {});
224
+ const state = response.status === 429 ? 'unknown' : await api.read(response, identifier);
225
+ return { state, ...(state === 'unknown' && { why }),
226
+ ...(limited && { limited: Number(response.headers.get('x-ratelimit-reset')) * 1000 || null }) };
227
+ });
228
+ return result.error ? { state: 'unknown', why: result.error === 'timeout' ? 'timeout' : 'upstream-error' } : result;
144
229
  }
145
230
 
146
231
  // The run's two controls for one platform: a handle known to exist and a random one that cannot. When either comes
147
- // back wrong, every answer from that platform in this run becomes "check yourself".
232
+ // back wrong, the platform's live results are unknown for this run.
148
233
  function controlsFor(platform, options) {
149
234
  const key = platform + '|' + (options.directory?.href ?? '');
150
235
  const runs = options.controlRuns ?? controlRuns;
@@ -157,18 +242,28 @@ function controlsFor(platform, options) {
157
242
  return runs.get(key);
158
243
  }
159
244
 
245
+ const cachePlatform = (platform, options) => {
246
+ if (platform === 'YouTube' && !options.youtubeApiKey) return 'youtube-page';
247
+ return publicCacheKind(publicKinds[platform] ?? platform).toLowerCase().replace(' ', '-');
248
+ };
249
+
160
250
  function lookup(platform, identifier, options) {
161
- const key = platform + '|' + identifier + '|' + (options.directory?.href ?? '');
251
+ const key = cachePlatform(platform, options) + '|' + identifier + '|' + (options.directory?.href ?? '');
162
252
  if (!inFlight.has(key)) inFlight.set(key, request(platform, identifier, options).finally(() => inFlight.delete(key)));
163
253
  return inFlight.get(key);
164
254
  }
165
255
 
166
- const cacheFile = (platform, identifier) => 'handle-' + platform.toLowerCase() + '-' + identifier + '.json';
256
+ function cacheFile(platform, identifier, options) {
257
+ const name = platform === 'Google Play' ? createHash('sha256').update(playCacheName(identifier)).digest('hex') : identifier;
258
+ return 'handle-' + cachePlatform(platform, options) + '-' + name + '.json';
259
+ }
167
260
 
168
- async function cached(directory, platform, identifier, now) {
169
- const saved = await readCache(directory, cacheFile(platform, identifier));
170
- const age = now.getTime() - saved?.at;
171
- return age >= 0 && age < (handleLifetime[saved?.state] ?? 0) ? saved : null;
261
+ async function cached(platform, identifier, options) {
262
+ const saved = await readCache(options.directory, cacheFile(platform, identifier, options));
263
+ const age = options.now.getTime() - saved?.at;
264
+ const lifetime = handleLifetime[saved?.state] ?? 0;
265
+ return age >= 0 && age < (Object.hasOwn(publicKinds, platform) ? Math.min(lifetime, publicCheckTiming.ttlMs) : lifetime)
266
+ ? saved : null;
172
267
  }
173
268
 
174
269
  // Answer a list of handles on one platform inside one shared time budget. Cached answers need no request; any live
@@ -176,33 +271,34 @@ async function cached(directory, platform, identifier, now) {
176
271
  async function platformBatch(platform, handles, options, deadline) {
177
272
  const { directory, now } = options;
178
273
  const api = apis[platform];
179
- const runCache = options.runAnswers ?? runAnswers;
274
+ const runCache = Object.hasOwn(publicKinds, platform) ? null : options.runAnswers ?? runAnswers;
180
275
  const answers = new Map();
181
276
  const live = [];
182
277
  for (const handle of new Set(handles)) {
183
- if (!label(handle) || !api.valid(handle)) {
184
- answers.set(handle, { state: 'check', why: 'cannot check this handle form' });
278
+ if ((platform !== 'Google Play' && !label(handle)) || !api.valid(handle)) {
279
+ answers.set(handle, { state: 'unknown', why: platform === 'Google Play' ? 'cannot check this name form' : 'cannot check this handle form' });
185
280
  continue;
186
281
  }
187
282
  const identifier = api.identifier?.(handle) ?? handle;
188
- const earlier = runCache.get(platform + '|' + identifier + '|' + (directory?.href ?? ''));
283
+ const earlier = runCache?.get(platform + '|' + identifier + '|' + (directory?.href ?? ''));
189
284
  if (earlier) {
190
285
  answers.set(handle, earlier);
191
286
  continue;
192
287
  }
193
- const saved = await cached(directory, platform, identifier, now);
194
- if (saved) answers.set(handle, { state: saved.state, checkedAt: new Date(saved.at).toISOString(), via: 'cache' });
288
+ const saved = await cached(platform, identifier, options);
289
+ if (saved) answers.set(handle, { state: saved.state, checkedAt: new Date(saved.at).toISOString(), via: 'cache',
290
+ ...(saved.seenYear && { seenYear: saved.seenYear }) });
195
291
  else live.push([handle, identifier]);
196
292
  }
197
293
  if (!live.length && (!options.controlRuns || !answers.size)) return answers;
198
294
  if (platform === 'GitHub' && await githubHeld(directory, now)) {
199
- for (const handle of [...answers.keys(), ...live.map(([handle]) => handle)]) answers.set(handle, { state: 'check', why: 'rate limited' });
295
+ for (const handle of [...answers.keys(), ...live.map(([handle]) => handle)]) answers.set(handle, { state: 'unknown', why: 'rate limited' });
200
296
  return answers;
201
297
  }
202
298
  const signal = options.signal ? anySignal([options.signal, deadline]) : deadline;
203
299
  const run = { ...options, signal };
204
300
  const [control, results] = await Promise.all([
205
- controlsFor(platform, run),
301
+ api.controls ? controlsFor(platform, run) : { ok: true },
206
302
  Promise.all(live.map(([, identifier]) => lookup(platform, identifier, run))),
207
303
  ]);
208
304
  const limited = control.limited ?? results.find(result => result.limited !== undefined)?.limited;
@@ -212,37 +308,42 @@ async function platformBatch(platform, handles, options, deadline) {
212
308
  }
213
309
  if (!control.ok) {
214
310
  for (const handle of [...answers.keys(), ...live.map(([handle]) => handle)]) {
215
- answers.set(handle, { state: 'check', why: 'control check failed' });
311
+ answers.set(handle, { state: 'unknown', why: 'control check failed' });
216
312
  }
217
313
  return answers;
218
314
  }
219
315
  const checkedAt = now.toISOString();
220
316
  for (const [index, [handle, identifier]] of live.entries()) {
221
- const { state } = results[index];
317
+ const { state, why, seenYear } = results[index];
222
318
  const key = platform + '|' + identifier + '|' + (directory?.href ?? '');
223
- if (state === 'check') {
224
- const answer = { state: 'check', why: 'no clear answer in time' };
319
+ if (state === 'unknown') {
320
+ const answer = { state: 'unknown', why: why ?? 'no clear answer in time' };
225
321
  answers.set(handle, answer);
226
- runCache.set(key, answer);
322
+ runCache?.set(key, answer);
227
323
  continue;
228
324
  }
229
- answers.set(handle, { state, checkedAt, via: 'api' });
230
- runCache.set(key, { state, checkedAt, via: 'api' });
231
- await writeCache(directory, cacheFile(platform, identifier), { at: now.getTime(), state }).catch(() => {});
325
+ const archive = seenYear ? { seenYear } : {};
326
+ answers.set(handle, { state, checkedAt, via: 'api', ...archive });
327
+ runCache?.set(key, { state, checkedAt, via: 'api', ...archive });
328
+ await writeCache(directory, cacheFile(platform, identifier, options), { at: now.getTime(), state, ...archive }).catch(() => {});
232
329
  }
233
330
  return answers;
234
331
  }
235
332
 
236
- function linkRow(platform, handle, why = 'link only') {
237
- return { platform: platform.id, handle, state: 'check', link: platform.link(handle), why };
333
+ function linkRow(platform, handle, why = platform.why ?? 'link only') {
334
+ const search = platform.id === 'LinkedIn';
335
+ return { platform: platform.id, handle, state: 'unknown', link: (search ? platform.search : platform.link)(handle), why,
336
+ ...(search && { linkLabel: platform.linkLabel }) };
238
337
  }
239
338
 
240
339
  function selectedPlatforms(extra) {
241
- return [...handlePlatforms, ...requestPlatforms.filter(platform => extra === true || Array.isArray(extra) && extra.includes(platform.id))];
340
+ return [...handlePlatforms, ...requestPlatforms.filter(platform => !handlePlatforms.includes(platform) &&
341
+ (extra === true || Array.isArray(extra) && extra.includes(platform.id)))];
242
342
  }
243
343
 
244
344
  export function pendingHandleRows(name, extra) {
245
- return selectedPlatforms(extra).map(platform => linkRow(platform, name, platform.auto ? 'still checking' : 'link only'));
345
+ return selectedPlatforms(extra).map(platform => linkRow(platform, name, disabled(platform.id, process.env)
346
+ ? disabledReason[platform.id] : platform.auto ? 'still checking' : undefined));
246
347
  }
247
348
 
248
349
  export const handlePriorities = {
@@ -252,58 +353,85 @@ export const handlePriorities = {
252
353
  media: ['YouTube', 'TikTok'],
253
354
  };
254
355
 
356
+ async function withinPlatformBudget(budget, run) {
357
+ const deadline = new AbortController();
358
+ // Keep Node alive until the platform answers or the deadline aborts its requests.
359
+ const timer = setTimeout(() => deadline.abort(new DOMException('The operation timed out', 'TimeoutError')), budget);
360
+ try {
361
+ return await run(deadline.signal);
362
+ } finally {
363
+ clearTimeout(timer);
364
+ }
365
+ }
366
+
367
+ export async function checkGooglePlayNames(names, {
368
+ directory = cacheDir, now = new Date(), fetcher = globalThis.fetch, signal, env = process.env,
369
+ } = {}) {
370
+ if (!embedChecksEnabled(env) || !names.length) return new Map();
371
+ return withinPlatformBudget(publicCheckTiming.budgetMs,
372
+ deadline => platformBatch('Google Play', names, { directory, now, fetcher, signal }, deadline));
373
+ }
374
+
255
375
  // rows: [{ name, platforms?: ['GitHub', 'npm', 'Bluesky'], variants?: boolean, links?: boolean }]
256
376
  // Returns a Map from name to its handle rows in display order. Exact handle first; getNAME, NAMEapp and NAMEhq only
257
377
  // when the exact handle is taken, inside the same per-platform budget.
258
378
  export async function checkSocialHandles(rows, {
259
- directory = cacheDir, now = new Date(), fetcher = globalThis.fetch, signal, budgetMs = platformBudgetMs,
260
- controls, extraPlatforms = false, env = process.env, freshRun = false,
379
+ directory = cacheDir, now = new Date(), fetcher = globalThis.fetch, signal, budgetMs,
380
+ controls, extraPlatforms = false, env = process.env, freshRun = false, instagramAnswers = new Map(),
261
381
  } = {}) {
262
382
  const githubToken = typeof env?.DOMAIN_HOUND_GITHUB_TOKEN === 'string' && /^[\w-]{20,255}$/.test(env.DOMAIN_HOUND_GITHUB_TOKEN)
263
383
  ? env.DOMAIN_HOUND_GITHUB_TOKEN : null;
264
- const options = { directory, now, fetcher, signal, controls, githubToken,
384
+ const youtubeApiKey = typeof env?.YOUTUBE_API_KEY === 'string' ? env.YOUTUBE_API_KEY.trim() : '';
385
+ const options = { directory, now, fetcher, signal, controls, githubToken, youtubeApiKey,
265
386
  ...(freshRun && { controlRuns: new Map(), runAnswers: new Map() }) };
266
- const wanted = platform => rows.filter(row => (row.platforms ?? autoPlatforms).includes(platform));
267
- const perPlatform = new Map(await Promise.all(autoPlatforms.map(async platform => {
268
- const names = wanted(platform);
269
- if (!names.length) return [platform, new Map()];
387
+ const platforms = selectedPlatforms(extraPlatforms);
388
+ const automatic = platforms.filter(platform => platform.auto).map(platform => platform.id);
389
+ const requested = (row, platform) => (row.platforms ?? automatic).includes(platform);
390
+ const perPlatform = new Map(await Promise.all(automatic.map(async platform => {
391
+ const names = rows.filter(row => requested(row, platform) ||
392
+ (platform === 'Instagram' && requested(row, 'Threads') && !instagramAnswers.has(row.name)));
393
+ if (!names.length || disabled(platform, env)) return [platform, null];
394
+ const platformBudget = Object.hasOwn(publicKinds, platform)
395
+ ? Math.min(budgetMs ?? publicCheckTiming.budgetMs, publicCheckTiming.budgetMs) : budgetMs ?? platformBudgetMs;
270
396
  const started = performance.now();
271
- const deadline = new AbortController();
272
- // Keep Node alive until the platform answers or the deadline aborts its requests.
273
- const timer = setTimeout(() => {
274
- deadline.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));
275
- }, budgetMs);
276
- try {
277
- const exact = await platformBatch(platform, names.map(row => row.name), options, deadline.signal);
278
- const taken = names.filter(row => row.variants && exact.get(row.name)?.state === 'taken');
279
- const left = budgetMs - (performance.now() - started);
397
+ return withinPlatformBudget(platformBudget, async deadline => {
398
+ const exact = await platformBatch(platform, names.map(row => row.name), options, deadline);
399
+ const taken = archiveKinds.includes(publicKinds[platform]) ? []
400
+ : names.filter(row => row.variants && requested(row, platform) && exact.get(row.name)?.state === 'taken');
401
+ const left = platformBudget - (performance.now() - started);
280
402
  const variants = taken.length && left >= 300
281
- ? await platformBatch(platform, taken.flatMap(row => handleVariants(row.name)), options, deadline.signal)
403
+ ? await platformBatch(platform, taken.flatMap(row => handleVariants(row.name)), options, deadline)
282
404
  : new Map();
283
- return [platform, { exact, variants, skipped: taken.length > 0 && left < 300 }];
284
- } finally {
285
- clearTimeout(timer);
286
- }
405
+ return [platform, { exact, variants }];
406
+ });
287
407
  })));
288
408
  const result = new Map();
289
409
  for (const row of rows) {
290
- const platforms = selectedPlatforms(extraPlatforms);
291
410
  const entries = [];
292
411
  for (const platform of platforms) {
293
- const checked = (row.platforms ?? autoPlatforms).includes(platform.id) ? perPlatform.get(platform.id) : null;
412
+ const wanted = requested(row, platform.id);
413
+ if (wanted && disabled(platform.id, env)) {
414
+ entries.push(linkRow(platform, row.name, disabledReason[platform.id]));
415
+ continue;
416
+ }
417
+ const checked = wanted ? perPlatform.get(platform.id) : null;
294
418
  if (!platform.auto || !checked?.exact) {
295
419
  if (row.links === false) continue;
296
- entries.push(linkRow(platform, row.name, platform.auto ? 'not checked for this name' : 'link only'));
420
+ entries.push(linkRow(platform, row.name, platform.auto ? 'not checked for this name' : undefined));
297
421
  continue;
298
422
  }
299
- const answer = checked.exact.get(row.name) ?? { state: 'check', why: 'no clear answer in time' };
300
- const entry = { platform: platform.id, handle: row.name, state: answer.state, link: platform.link(row.name),
423
+ const raw = checked.exact.get(row.name) ?? { state: 'unknown', why: 'no clear answer in time' };
424
+ const instagram = instagramAnswers.get(row.name) ?? perPlatform.get('Instagram')?.exact.get(row.name);
425
+ const answer = platform.id === 'Threads' ? threadsFromInstagram(raw, instagram) : raw;
426
+ const search = (answer.state === 'not-seen' || (answer.state === 'unknown' && platform.id === 'LinkedIn')) && platform.search;
427
+ const entry = { platform: platform.id, handle: row.name, state: answer.state, link: (search || platform.link)(row.name),
428
+ ...(search && { linkLabel: platform.linkLabel }), ...(answer.seenYear && { seenYear: answer.seenYear }),
301
429
  ...(answer.checkedAt && { checkedAt: answer.checkedAt }), ...(answer.why && { why: answer.why }) };
302
- if (row.variants && answer.state === 'taken') {
430
+ if (row.variants && answer.state === 'taken' && !platform.search) {
303
431
  entry.variants = handleVariants(row.name).map(handle => {
304
- const variant = checked.variants.get(handle) ?? { state: 'check', why: 'no clear answer in time' };
432
+ const variant = checked.variants.get(handle) ?? { state: 'unknown', why: 'no clear answer in time' };
305
433
  return { handle, state: variant.state, link: platform.link(handle),
306
- ...(variant.checkedAt && { checkedAt: variant.checkedAt }) };
434
+ ...(variant.checkedAt && { checkedAt: variant.checkedAt }), ...(variant.why && { why: variant.why }) };
307
435
  });
308
436
  }
309
437
  entries.push(entry);
@@ -313,11 +441,11 @@ export async function checkSocialHandles(rows, {
313
441
  return result;
314
442
  }
315
443
 
316
- // "GitHub taken · npm no public profile found · Bluesky taken; check yourself: YouTube, X, …".
317
444
  export function handleSummary(entries, { limit = Infinity, manualLimit = Infinity, ordered = false } = {}) {
318
445
  if (!Array.isArray(entries) || !entries.length) return null;
319
- const checked = entries.filter(entry => entry.state !== 'check');
320
- const open = entries.filter(entry => entry.state === 'check');
446
+ const checked = entries.filter(entry => ['taken', 'not-found', 'not-seen'].includes(entry.state));
447
+ const open = entries.filter(entry => !checked.includes(entry));
448
+ const describe = entry => entry.platform + ' · ' + handleLabel(entry);
321
449
  if (ordered) {
322
450
  const shown = new Set([...entries.slice(0, 2), ...checked.slice(0, 2)]);
323
451
  for (const entry of entries) {
@@ -325,13 +453,14 @@ export function handleSummary(entries, { limit = Infinity, manualLimit = Infinit
325
453
  shown.add(entry);
326
454
  }
327
455
  const states = entries.filter(entry => shown.has(entry))
328
- .map(entry => entry.platform + ' ' + handleStates[entry.state].toLowerCase()).join(', ');
456
+ .map(describe).join(', ');
329
457
  const more = entries.length - shown.size;
330
458
  return states + (more ? ' (' + more + ' more on the page)' : '');
331
459
  }
332
- const shown = checked.slice(0, limit).map(entry => entry.platform + ' ' + handleStates[entry.state].toLowerCase());
460
+ const shown = checked.slice(0, limit).map(describe);
333
461
  const manual = open.slice(0, manualLimit);
334
462
  const more = checked.length - shown.length + open.length - manual.length;
335
- return [shown.join(' · '), manual.length ? 'check yourself: ' + manual.map(entry => entry.platform).join(', ') : '',
336
- more > 0 ? '(' + more + ' more on the page)' : ''].filter(Boolean).join('; ');
463
+ const unchecked = manual.map(entry => entry.platform);
464
+ return [shown.join(', '), unchecked.length ? handleStates.unknown + ' (' + unchecked.join(', ') + ')' : '',
465
+ more > 0 ? '(' + more + ' more on the page)' : ''].filter(Boolean).join(' · ');
337
466
  }
@@ -14,6 +14,7 @@ import { lookupRegistrations } from './registry.mjs';
14
14
  import { namingRecipe, purchaseLine } from './naming-method.mjs';
15
15
  import { progressReporter } from './progress.mjs';
16
16
  import { namePresence, triageNames } from './triage.mjs';
17
+ import { validCandidate } from './name-score.mjs';
17
18
  import { refreshTranco } from './traction.mjs';
18
19
  import {
19
20
  catalogPrice, dynadotOffer, linkable, money, offer, porkbunOffer, rankedFirstYear, shops, shopSearchUrl, threeYearCost, transferStrategy, vatNorway,
@@ -280,8 +281,8 @@ function quoteTime(value) {
280
281
  }
281
282
 
282
283
  const agentLegend = {
283
- nc: 'Free at the registry; list price, not confirmed',
284
- ok: 'Free, price confirmed at the shop (at = quote time)',
284
+ nc: 'Available at the registry. List price, not confirmed',
285
+ ok: 'Available. Price confirmed at the shop (at = quote time)',
285
286
  prem: 'Premium: price at the shop, never a list price',
286
287
  resale: 'Taken, possible resale',
287
288
  shop_check: 'Registry did not settle; check at a shop',
@@ -292,7 +293,7 @@ const agentLegend = {
292
293
  term: 'Years per payment when more than one',
293
294
  jump: 'Renewal over twice the first annual price',
294
295
  risk: 'Short name: may be premium, price at the shop',
295
- likely_free: 'Registry silent, DNS has no delegation: likely free, confirm at a shop',
296
+ likely_free: 'Registry silent, DNS has no delegation: possibly available, confirm at a shop',
296
297
  likely_taken: 'Registry silent, DNS has a delegation: likely taken',
297
298
  };
298
299
  const googleEndings = new Set(['app', 'dev']);
@@ -437,7 +438,7 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
437
438
  // Fourteen endings for twenty long names: an unconfirmed list-price row drops its s, as the display layer does.
438
439
  if (batch && Buffer.byteLength(JSON.stringify(result)) >= 7900) {
439
440
  for (const row of byName.values()) if (row.free) row.free = row.free.map(({ s, ...option }) => s === 'nc' ? option : { ...option, s });
440
- result.legend = { ...result.legend, d: agentLegend.d + '; a free entry without s is nc' };
441
+ result.legend = { ...result.legend, d: agentLegend.d + '; an available entry without s is nc' };
441
442
  }
442
443
  return result;
443
444
  }
@@ -570,7 +571,8 @@ async function endingBenchmarks(domain, options) {
570
571
  const bundled = options.bundledCatalog === undefined ? bundledCatalog : options.bundledCatalog;
571
572
  const catalog = await loadCachedCatalog(options.directory).catch(() => null);
572
573
  const prices = {};
573
- for (const tld of defaultEndings.filter(ending => ending !== 'com' && canRecommend(ending, options.eligible))) {
574
+ const endings = [...new Set([...defaultEndings, ...(options.eligible ?? [])])];
575
+ for (const tld of endings.filter(ending => ending !== 'com' && canRecommend(ending, options.eligible))) {
574
576
  const quote = listQuote(catalog, { domain: label + '.' + tld, tld }, now, bundled);
575
577
  if (quote.price == null) continue;
576
578
  const costs = termCosts(tld, quote.price, quote.renewal);
@@ -676,6 +678,17 @@ function readGeo(value) {
676
678
  return null;
677
679
  }
678
680
 
681
+ // Per-name naming evidence from the calling agent ({"Name":{"realWord":true,...}}); invalid input is ignored, which leaves
682
+ // every semantic ban unchecked for the score.
683
+ function readCandidates(value) {
684
+ try {
685
+ const candidates = JSON.parse(value ?? '');
686
+ if (candidates && typeof candidates === 'object' && !Array.isArray(candidates) && Object.keys(candidates).length <= 20
687
+ && Object.entries(candidates).every(([key, entry]) => key.length <= 100 && validCandidate(entry))) return candidates;
688
+ } catch { /* ignored */ }
689
+ return null;
690
+ }
691
+
679
692
  function lookupArgs(args) {
680
693
  const options = {};
681
694
  const positional = [];
@@ -693,6 +706,7 @@ function lookupArgs(args) {
693
706
  else if (arg === '--confirm') options.browser = true;
694
707
  else if (arg === '--geo' && options.geo === undefined) options.geo = readGeo(args[++index]);
695
708
  else if (arg === '--about' && options.about === undefined) options.about = (args[++index] ?? '').slice(0, 160);
709
+ else if (arg === '--candidates' && options.candidates === undefined) options.candidates = readCandidates(args[++index]);
696
710
  else positional.push(arg);
697
711
  }
698
712
  return { options, positional };
@@ -701,7 +715,8 @@ function lookupArgs(args) {
701
715
  function triageOutput(result, options) {
702
716
  if (options.compact) {
703
717
  for (const row of result.names ?? []) {
704
- row.checks = nameCheckLines(row).map(({ label, text, link }) => label + ': ' + text + ' · ' + link);
718
+ row.checks = nameCheckLines(row).map(({ label, text, link, linkLabel }) =>
719
+ (linkLabel ? text + ' · ' + linkLabel : label + ': ' + text) + ' · ' + link);
705
720
  }
706
721
  }
707
722
  return result;