domain-hound 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/plugins/marketplace.json +1 -0
- package/.claude-plugin/marketplace.json +1 -0
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +84 -13
- package/assets/readme-search.png +0 -0
- package/clis/domain-check/broker-atom.mjs +78 -0
- package/clis/domain-check/com-site.mjs +64 -25
- package/clis/domain-check/confirm.mjs +10 -5
- package/clis/domain-check/dossier.mjs +603 -0
- package/clis/domain-check/google-play.mjs +24 -11
- package/clis/domain-check/index.mjs +75 -23
- package/clis/domain-check/marketplaces.mjs +107 -0
- package/clis/domain-check/meaning-words.LICENSE.txt +408 -0
- package/clis/domain-check/meaning-words.json +2397 -0
- package/clis/domain-check/meaning.mjs +77 -0
- package/clis/domain-check/name-search.mjs +91 -14
- package/clis/domain-check/naming-method.mjs +6 -4
- package/clis/domain-check/registry.mjs +2 -2
- package/clis/domain-check/safe-web.mjs +207 -0
- package/clis/domain-check/trademarks.mjs +372 -0
- package/clis/domain-check/triage-sources.mjs +39 -12
- package/clis/domain-check/triage.mjs +190 -63
- package/clis/spaceship/buy.mjs +327 -0
- package/clis/spaceship/client.mjs +170 -0
- package/clis/spaceship/dns.mjs +292 -0
- package/clis/spaceship/quote.mjs +123 -0
- package/clis/spaceship/setup.mjs +81 -0
- package/clis/spaceship/store.mjs +104 -0
- package/clis/spaceship/tools.mjs +258 -0
- package/display.mjs +57 -30
- package/dossier.mjs +185 -0
- package/package.json +20 -2
- package/plugin.json +4 -3
- package/results-style.mjs +10 -0
- package/results.mjs +258 -62
- package/server.json +2 -2
- package/server.mjs +223 -96
- package/share.mjs +43 -0
- package/site/r/share-format.mjs +125 -0
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { anySignal, cacheDir, readCache, writeCache } from './cache.mjs';
|
|
2
|
+
import { compactText, day, exactPhrases, letters, markOrder, matchTier, relevantClasses, request } from './triage-sources.mjs';
|
|
3
|
+
|
|
4
|
+
// Optional EU (EUIPO Trademark Search API 1.1.0) and Norwegian (Patentstyret open data MCP) trademark searches.
|
|
5
|
+
// Both need a free key the user sets; without one the office is "off" and the results link to its own search.
|
|
6
|
+
// Keys are sent only to the fixed official hosts below. A failed office never reads as clear.
|
|
7
|
+
export const officeNames = { EU: 'EUIPO', NO: 'Patentstyret' };
|
|
8
|
+
const euipo = {
|
|
9
|
+
production: { api: 'https://api.euipo.europa.eu/trademark-search', token: 'https://euipo.europa.eu/cas-server-webapp/oidc/accessToken' },
|
|
10
|
+
sandbox: { api: 'https://api-sandbox.euipo.europa.eu/trademark-search', token: 'https://auth-sandbox.euipo.europa.eu/oidc/accessToken' },
|
|
11
|
+
};
|
|
12
|
+
const patentstyretMcp = 'https://api.patentstyret.no/external/open-data/mcp';
|
|
13
|
+
const euRecord = number => 'https://euipo.europa.eu/eSearch/#details/trademarks/' + number;
|
|
14
|
+
const noRecord = /^https:\/\/services\.patentstyret\.no\/search-details\/trademark\/[\w-]{4,40}$/;
|
|
15
|
+
// Live EU statuses: everything except withdrawn, refused, cancelled, surrendered, expired and removed marks.
|
|
16
|
+
const euLive = ['RECEIVED', 'UNDER_EXAMINATION', 'APPLICATION_PUBLISHED', 'REGISTRATION_PENDING', 'REGISTERED',
|
|
17
|
+
'OPPOSITION_PENDING', 'APPEALED', 'CANCELLATION_PENDING', 'APPEALABLE', 'START_OF_OPPOSITION_PERIOD',
|
|
18
|
+
'ACCEPTANCE_PENDING', 'ACCEPTED'];
|
|
19
|
+
const euDead = new Set(['WITHDRAWN', 'REFUSED', 'CANCELLED', 'SURRENDERED', 'EXPIRED', 'REMOVED_FROM_REGISTER']);
|
|
20
|
+
const noDead = /withdr|refus|reject|expir|ended|ceas|cancel|laps|invalid|revok|surrend|abandon|remov|dead|terminat|henlag|avsl|opph|slett|trukket|utg/i;
|
|
21
|
+
const noLive = /regist|pend|filed|appli|publish|oppos|appeal|exam|accept|grant|valid|active|søkt|under|innvilg/i;
|
|
22
|
+
const staleLimit = 30 * day;
|
|
23
|
+
const holds = new Map();
|
|
24
|
+
const tokens = new Map();
|
|
25
|
+
const sessions = new Map();
|
|
26
|
+
let rpcId = 0;
|
|
27
|
+
|
|
28
|
+
class Failure extends Error {
|
|
29
|
+
constructor(why, retry = false) {
|
|
30
|
+
super(why);
|
|
31
|
+
this.retry = retry;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const printable = (value, min) => {
|
|
36
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
37
|
+
return text.length >= min && text.length <= 256 && /^[\x21-\x7e]+$/.test(text) ? text : null;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// Which offices have keys. EUIPO needs both the client ID and secret of an app subscribed to Trademark Search.
|
|
41
|
+
export function trademarkKeys(env = process.env) {
|
|
42
|
+
const id = printable(env?.DOMAIN_HOUND_EUIPO_CLIENT_ID, 8);
|
|
43
|
+
const secret = printable(env?.DOMAIN_HOUND_EUIPO_CLIENT_SECRET, 8);
|
|
44
|
+
const key = printable(env?.DOMAIN_HOUND_PATENTSTYRET_KEY, 16);
|
|
45
|
+
return {
|
|
46
|
+
EU: id && secret ? { id, secret, ...euipo[env.DOMAIN_HOUND_EUIPO_SANDBOX === '1' ? 'sandbox' : 'production'] } : null,
|
|
47
|
+
NO: key ? { key } : null,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const budget = options => Math.min(2600, (options.timeLeft?.() ?? Infinity) - 250);
|
|
52
|
+
|
|
53
|
+
function httpFailure(office, response) {
|
|
54
|
+
if (response.status === 429) {
|
|
55
|
+
const wait = Number(response.headers?.get('retry-after'));
|
|
56
|
+
holds.set(office, Date.now() + (wait > 0 && wait < 3600 ? wait * 1000 : 60_000));
|
|
57
|
+
return new Failure('rate limited');
|
|
58
|
+
}
|
|
59
|
+
if (response.status === 401 || response.status === 403) {
|
|
60
|
+
// A refused key stays refused for the rest of this run; the other names do not ask again.
|
|
61
|
+
holds.set(office, Date.now() + 10 * 60_000);
|
|
62
|
+
return new Failure('key refused');
|
|
63
|
+
}
|
|
64
|
+
return new Failure(response.status >= 500 ? 'unavailable' : 'request refused', response.status >= 500);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// One mark row in the same shape as the USPTO rows. Dead marks and loose spellings drop out.
|
|
68
|
+
function markRow(key, { office, text, owner, classes, status, live, url }) {
|
|
69
|
+
const mark = letters(text);
|
|
70
|
+
if (!mark || live === false) return [];
|
|
71
|
+
const tier = matchTier(key, mark);
|
|
72
|
+
if (!tier || (tier === 'Fuzzy' && key.length < 5)) return [];
|
|
73
|
+
const codes = [...new Set((Array.isArray(classes) ? classes : []).map(Number)
|
|
74
|
+
.filter(value => Number.isInteger(value) && value >= 1 && value <= 45))].sort((a, b) => a - b)
|
|
75
|
+
.map(value => String(value).padStart(3, '0'));
|
|
76
|
+
return [{ office, name: compactText(text, 65), owner: compactText(owner, 70), classes: codes, tier,
|
|
77
|
+
status: compactText(status, 30).toLowerCase() || 'status unavailable', live: live === true ? true : null,
|
|
78
|
+
registered: /^regist/i.test(String(status)), url }];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Relevance follows the same class rules as USPTO. A mark whose live status is unclear never forces Avoid.
|
|
82
|
+
function judged(rows, category) {
|
|
83
|
+
const relevant = relevantClasses(category);
|
|
84
|
+
return rows.map(row => {
|
|
85
|
+
const classes = row.classes.filter(value => relevant.includes(value));
|
|
86
|
+
return { ...row, relevant: row.live === true && classes.length > 0, relevantClasses: classes };
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function pluralForms(key) {
|
|
91
|
+
return [key + 's', key + 'es', key.replace(/y$/, 'ies'), key.replace(/(?:es|s)$/, ''), key.replace(/ies$/, 'y')]
|
|
92
|
+
.filter(value => value !== key && matchTier(key, value) === 'Near-identical');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Wildcards find candidates for a vowel swap or doubled letter. The shared matcher scores the returned text.
|
|
96
|
+
function nearPatterns(key) {
|
|
97
|
+
return [...key].flatMap((letter, index) => {
|
|
98
|
+
const start = key.slice(0, index);
|
|
99
|
+
const end = key.slice(index + 1);
|
|
100
|
+
const forms = [start + letter + '*' + end];
|
|
101
|
+
if ('aeiouy'.includes(letter)) forms.push(start + '*' + end);
|
|
102
|
+
if (letter === key[index - 1]) forms.push(start + end);
|
|
103
|
+
return forms;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// RSQL for exact, spaced, split and near spellings in lower, upper and title case.
|
|
108
|
+
// Returns the query and whether every spelling fit under the API's 5000-character limit.
|
|
109
|
+
export function euipoQuery(key, input) {
|
|
110
|
+
const phrases = [...exactPhrases(key, input), ...pluralForms(key), ...nearPatterns(key)];
|
|
111
|
+
const typed = String(input ?? '').trim();
|
|
112
|
+
const forms = [...(/^[\p{L}\p{N} &'.-]{1,80}$/u.test(typed) ? [typed] : []),
|
|
113
|
+
...phrases.flatMap(phrase => [phrase, phrase.toUpperCase(), phrase.replace(/(^|\s)([a-z])/g, (_, space, letter) => space + letter.toUpperCase())])];
|
|
114
|
+
const status = ' and status=in=(' + euLive.join(',') + ')';
|
|
115
|
+
const clauses = [];
|
|
116
|
+
let complete = true;
|
|
117
|
+
for (const form of new Set(forms)) {
|
|
118
|
+
const value = form.includes('*') ? form : '"' + form.replace(/["\\]/g, '\\$&') + '"';
|
|
119
|
+
const clause = 'wordMarkSpecification.verbalElement==' + value;
|
|
120
|
+
if ([...clauses, clause].join(' or ').length + status.length + 2 > 4800) {
|
|
121
|
+
complete = false;
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
clauses.push(clause);
|
|
125
|
+
}
|
|
126
|
+
return { query: '(' + clauses.join(' or ') + ')' + status, complete };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function euipoToken(config, options) {
|
|
130
|
+
const cached = tokens.get(config.token + config.id);
|
|
131
|
+
if (cached && cached.until > Date.now()) return cached.promise;
|
|
132
|
+
const entry = { until: Infinity };
|
|
133
|
+
entry.promise = (async () => {
|
|
134
|
+
// The EUIPO security guide sends the client credentials in the form body.
|
|
135
|
+
const response = await request(config.token, options, { method: 'POST', timeout: budget(options),
|
|
136
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
137
|
+
body: new URLSearchParams({ client_id: config.id, client_secret: config.secret, grant_type: 'client_credentials', scope: 'uid' }) });
|
|
138
|
+
if (!response.ok) {
|
|
139
|
+
await response.body?.cancel();
|
|
140
|
+
// An unknown client or wrong secret answers 400 invalid_client or 401.
|
|
141
|
+
throw httpFailure('EU', { status: response.status === 400 ? 401 : response.status, headers: response.headers });
|
|
142
|
+
}
|
|
143
|
+
const data = await response.json();
|
|
144
|
+
if (typeof data?.access_token !== 'string' || !data.access_token) throw new Failure('no token', true);
|
|
145
|
+
const lifetime = Number(data.expires_in);
|
|
146
|
+
entry.until = Date.now() + Math.max(30, (lifetime > 0 ? lifetime : 600) - 60) * 1000;
|
|
147
|
+
return data.access_token;
|
|
148
|
+
})();
|
|
149
|
+
tokens.set(config.token + config.id, entry);
|
|
150
|
+
entry.promise.catch(() => tokens.delete(config.token + config.id));
|
|
151
|
+
return entry.promise;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function euipoMarks(key, input, config, options) {
|
|
155
|
+
const token = await euipoToken(config, options);
|
|
156
|
+
const { query, complete } = euipoQuery(key, input);
|
|
157
|
+
const response = await request(config.api + '/trademarks?' + new URLSearchParams({ query, page: '0', size: '100' }), options, {
|
|
158
|
+
timeout: budget(options), headers: { Authorization: 'Bearer ' + token, 'X-IBM-Client-Id': config.id, Accept: 'application/json' },
|
|
159
|
+
});
|
|
160
|
+
if (!response.ok) {
|
|
161
|
+
await response.body?.cancel();
|
|
162
|
+
if (response.status === 401) tokens.delete(config.token + config.id);
|
|
163
|
+
throw httpFailure('EU', response);
|
|
164
|
+
}
|
|
165
|
+
const data = await response.json();
|
|
166
|
+
if (!Array.isArray(data?.trademarks)) throw new Failure('unreadable answer', true);
|
|
167
|
+
const { totalElements } = data;
|
|
168
|
+
let partial = !complete || !Number.isSafeInteger(totalElements) || totalElements < 0
|
|
169
|
+
|| totalElements !== data.trademarks.length;
|
|
170
|
+
const rows = data.trademarks.flatMap(item => {
|
|
171
|
+
const number = /^(?:\d{9}|W\d{8}[A-Z]?)$/.test(item?.applicationNumber) ? item.applicationNumber : null;
|
|
172
|
+
const status = typeof item?.status === 'string' ? item.status : '';
|
|
173
|
+
if (euDead.has(status)) return [];
|
|
174
|
+
const text = item?.wordMarkSpecification?.verbalElement;
|
|
175
|
+
const live = euLive.includes(status) ? true : null;
|
|
176
|
+
if (live === null || !letters(text) || !number || !Array.isArray(item?.niceClasses)) partial = true;
|
|
177
|
+
return markRow(key, { office: 'EU', text,
|
|
178
|
+
owner: (Array.isArray(item?.applicants) ? item.applicants : []).map(person => person?.name).find(name => typeof name === 'string') ?? '',
|
|
179
|
+
classes: item?.niceClasses, status: status.replace(/_/g, ' '), live,
|
|
180
|
+
url: number ? euRecord(number) : null });
|
|
181
|
+
});
|
|
182
|
+
return { rows, partial };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Patentstyret: the documented MCP search (JSON-RPC over HTTP). The search tool's argument names come from
|
|
186
|
+
// its own schema, so a renamed argument is picked up without a release.
|
|
187
|
+
async function mcpPost(key, session, body, options) {
|
|
188
|
+
const response = await request(patentstyretMcp, options, { method: 'POST', timeout: budget(options), headers: {
|
|
189
|
+
'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', 'Ocp-Apim-Subscription-Key': key,
|
|
190
|
+
...(session?.id && { 'Mcp-Session-Id': session.id }), ...(session?.version && { 'MCP-Protocol-Version': session.version }),
|
|
191
|
+
}, body: JSON.stringify(body) });
|
|
192
|
+
if (!response.ok) {
|
|
193
|
+
await response.body?.cancel();
|
|
194
|
+
if (response.status === 404 && session) sessions.delete(key);
|
|
195
|
+
throw response.status === 404 && session ? new Failure('session ended', true) : httpFailure('NO', response);
|
|
196
|
+
}
|
|
197
|
+
return response;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function jsonOrNull(text) {
|
|
201
|
+
try { return JSON.parse(text); } catch { return null; }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function rpc(key, session, method, params, options) {
|
|
205
|
+
const id = ++rpcId;
|
|
206
|
+
const response = await mcpPost(key, session, { jsonrpc: '2.0', id, method, params }, options);
|
|
207
|
+
const text = await response.text();
|
|
208
|
+
const messages = /text\/event-stream/i.test(response.headers.get('content-type') ?? '')
|
|
209
|
+
? text.split(/\r?\n\r?\n/).map(event => jsonOrNull(event.split(/\r?\n/).filter(line => line.startsWith('data:'))
|
|
210
|
+
.map(line => line.slice(5).trimStart()).join('\n')))
|
|
211
|
+
: [jsonOrNull(text)];
|
|
212
|
+
const message = messages.flat().find(item => item?.id === id);
|
|
213
|
+
if (!message) throw new Failure('unreadable answer', true);
|
|
214
|
+
if (message.error) throw new Failure('search refused');
|
|
215
|
+
return { result: message.result, response };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// The search tool and its text and size arguments, from tools/list.
|
|
219
|
+
export function searchTool(tools) {
|
|
220
|
+
const tool = (Array.isArray(tools) ? tools : []).find(item => item?.name === 'search_trademarks');
|
|
221
|
+
const properties = tool?.inputSchema?.properties;
|
|
222
|
+
if (!properties || typeof properties !== 'object') return null;
|
|
223
|
+
const entries = Object.entries(properties);
|
|
224
|
+
const strings = entries.filter(([, schema]) => schema?.type === 'string' || schema?.type?.includes?.('string'));
|
|
225
|
+
const text = strings.find(([name]) => /^(?:query|q|search_?text|search_?term|search|text|term|keywords?|word_?mark|mark_?text|mark|trademark|name)$/i.test(name))?.[0]
|
|
226
|
+
?? strings.find(([name]) => tool.inputSchema.required?.includes(name))?.[0];
|
|
227
|
+
const [size, sizeSchema] = entries.find(([name, schema]) => ['integer', 'number'].includes(schema?.type)
|
|
228
|
+
&& /^(?:size|limit|page_?size|max(?:_?results)?|top|take|count|rows)$/i.test(name)) ?? [];
|
|
229
|
+
return text ? { text, ...(size && { size, limit: Math.max(1, Math.min(50, Number(sizeSchema.maximum) || 50)) }) } : null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function mcpSession(key, options) {
|
|
233
|
+
if (!sessions.has(key)) {
|
|
234
|
+
const opening = (async () => {
|
|
235
|
+
const { result, response } = await rpc(key, null, 'initialize', {
|
|
236
|
+
protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'domain-hound', version: '0.1' },
|
|
237
|
+
}, options);
|
|
238
|
+
const session = { id: printable(response.headers.get('mcp-session-id'), 1) ?? undefined,
|
|
239
|
+
version: typeof result?.protocolVersion === 'string' ? result.protocolVersion.slice(0, 20) : '2025-06-18' };
|
|
240
|
+
await (await mcpPost(key, session, { jsonrpc: '2.0', method: 'notifications/initialized' }, options)).body?.cancel();
|
|
241
|
+
const tool = searchTool((await rpc(key, session, 'tools/list', {}, options)).result?.tools);
|
|
242
|
+
if (!tool) throw new Failure('search tool not found');
|
|
243
|
+
return { ...session, tool };
|
|
244
|
+
})();
|
|
245
|
+
sessions.set(key, opening);
|
|
246
|
+
opening.catch(() => sessions.delete(key));
|
|
247
|
+
}
|
|
248
|
+
return sessions.get(key);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const textOf = value => typeof value === 'string' ? value : typeof value?.$ === 'string' ? value.$ : '';
|
|
252
|
+
|
|
253
|
+
function partyName(party) {
|
|
254
|
+
const name = party?.contact?.contactTypeChoiceSequence?.name?.entityName ?? party?.contact?.name?.entityName;
|
|
255
|
+
return [name?.transliterationName?.[0], name?.phraseType, name?.organizationStandardName, name].map(textOf).find(Boolean) ?? '';
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Cases in WIPO ST.96 JSON, as in Patentstyret's published dummy case, wherever the result list nests them.
|
|
259
|
+
export function patentstyretCases(data) {
|
|
260
|
+
const cases = [];
|
|
261
|
+
let visited = 0;
|
|
262
|
+
const walk = (value, depth) => {
|
|
263
|
+
if (!value || typeof value !== 'object' || depth > 8 || ++visited > 5000) return;
|
|
264
|
+
if (value.trademarkApplication && typeof value.trademarkApplication === 'object') cases.push(value.trademarkApplication);
|
|
265
|
+
else if (value.trademarkBag && typeof value.trademarkBag === 'object') cases.push(value);
|
|
266
|
+
else for (const child of Array.isArray(value) ? value : Object.values(value)) walk(child, depth + 1);
|
|
267
|
+
};
|
|
268
|
+
walk(data, 0);
|
|
269
|
+
const total = data && typeof data === 'object' && !Array.isArray(data) ? Object.entries(data)
|
|
270
|
+
.find(([name, value]) => /^(?:total(?:_?(?:count|hits|results|elements))?|number_?of_?hits|hit_?count|count)$/i.test(name)
|
|
271
|
+
&& Number.isSafeInteger(value))?.[1] : undefined;
|
|
272
|
+
return { cases, total };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function caseRow(key, item) {
|
|
276
|
+
const mark = item?.trademarkBag?.trademark?.[0];
|
|
277
|
+
const words = mark?.markRepresentation?.markReproduction?.wordMarkSpecification;
|
|
278
|
+
const number = textOf(mark?.trademarkTypeChoice1?.applicationNumber?.[0]?.applicationNumberText);
|
|
279
|
+
const status = textOf(mark?.markCurrentStatusCode);
|
|
280
|
+
const classes = (Array.isArray(mark?.goodsServicesBag?.goodsServices) ? mark.goodsServicesBag.goodsServices : [])
|
|
281
|
+
.flatMap(goods => (goods?.classDescriptionBag?.classDescription ?? []).map(entry => entry?.classNumber));
|
|
282
|
+
const url = typeof item?.caseUrl === 'string' && noRecord.test(item.caseUrl) ? item.caseUrl
|
|
283
|
+
: /^\d{6,12}$/.test(number) ? 'https://services.patentstyret.no/search-details/trademark/' + number : null;
|
|
284
|
+
return markRow(key, { office: 'NO', text: textOf(words?.markVerbalElementText) || textOf(words?.markSignificantVerbalElementText),
|
|
285
|
+
owner: partyName(item?.holderBag?.holder?.[0]) || partyName(mark?.applicantBag?.applicant?.[0]),
|
|
286
|
+
classes, status, live: !status ? null : noDead.test(status) ? false : noLive.test(status) ? true : null, url });
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function patentstyretSearch(key, session, query, options) {
|
|
290
|
+
const { tool } = session;
|
|
291
|
+
const { result } = await rpc(key, session, 'tools/call', { name: 'search_trademarks',
|
|
292
|
+
arguments: { [tool.text]: query, ...(tool.size && { [tool.size]: tool.limit }) } }, options);
|
|
293
|
+
if (result?.isError) throw new Failure('search refused');
|
|
294
|
+
const content = Array.isArray(result?.content) ? result.content : [];
|
|
295
|
+
const data = result?.structuredContent ?? jsonOrNull(content.filter(part => part?.type === 'text').map(part => part.text).join(''));
|
|
296
|
+
if (data == null || typeof data !== 'object') throw new Failure('unreadable answer');
|
|
297
|
+
const { cases, total } = patentstyretCases(data);
|
|
298
|
+
const empty = Array.isArray(data) ? data.length === 0 : Array.isArray(data.results) && data.results.length === 0;
|
|
299
|
+
if (!cases.length && !empty && !(total > 0)) throw new Failure('unreadable answer');
|
|
300
|
+
return { cases, partial: total !== undefined ? total > cases.length : Boolean(tool.size && cases.length >= tool.limit) };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function patentstyretMarks(key, input, config, options) {
|
|
304
|
+
const session = await mcpSession(config.key, options);
|
|
305
|
+
const spaced = input.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
|
|
306
|
+
const queries = [...new Set([key, spaced].filter(Boolean))];
|
|
307
|
+
const answers = await Promise.all(queries.map(query => patentstyretSearch(config.key, session, query, options)));
|
|
308
|
+
// The glued and spaced searches can return the same case once each.
|
|
309
|
+
const rows = answers.flatMap(answer => answer.cases.flatMap(item => caseRow(key, item)));
|
|
310
|
+
return { rows: [...new Map(rows.map(row => [row.url ?? row.name + row.status, row])).values()],
|
|
311
|
+
partial: answers.some(answer => answer.partial) || rows.some(row => row.live === null || !row.url || !row.classes.length) };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const fetchers = { EU: euipoMarks, NO: patentstyretMarks };
|
|
315
|
+
|
|
316
|
+
// One office for one name. States: off (no key), ok (marks, partial when the answer was cut short) or failed.
|
|
317
|
+
// A failed office keeps the marks of an earlier answer, labelled with its date, and is never read as clear.
|
|
318
|
+
// One retry, only for a transient failure, and only while the shared time budget lasts.
|
|
319
|
+
export async function checkOffice(office, name, input, options = {}) {
|
|
320
|
+
const config = trademarkKeys(options.env ?? process.env)[office];
|
|
321
|
+
if (!config) return { office, state: 'off' };
|
|
322
|
+
const { directory = cacheDir, now = new Date() } = options;
|
|
323
|
+
const key = letters(name);
|
|
324
|
+
const source = config.api === euipo.sandbox.api ? 'eu-sandbox' : office.toLowerCase();
|
|
325
|
+
const filename = 'trademark-' + source + '-' + key + '.json';
|
|
326
|
+
const saved = await readCache(directory, filename);
|
|
327
|
+
const age = now.getTime() - saved?.at;
|
|
328
|
+
const savedRows = Array.isArray(saved?.rows) ? saved.rows : null;
|
|
329
|
+
const finish = (state, rows, extra = {}) => ({ office, state,
|
|
330
|
+
marks: judged(rows, options.category).sort(markOrder(key)), ...extra });
|
|
331
|
+
if (savedRows && age >= 0 && age < day) return finish('ok', savedRows, { partial: false, checkedAt: new Date(saved.at).toISOString() });
|
|
332
|
+
const duration = Math.floor(budget(options));
|
|
333
|
+
const deadline = performance.now() + duration;
|
|
334
|
+
const attempt = async () => {
|
|
335
|
+
if ((holds.get(office) ?? 0) > Date.now()) return { failed: 'rate limited or key refused earlier in this run' };
|
|
336
|
+
if (sourceOptions.signal.aborted || budget(sourceOptions) < 700) return { failed: 'out of time' };
|
|
337
|
+
try {
|
|
338
|
+
return await fetchers[office](key, String(input ?? name), config, sourceOptions);
|
|
339
|
+
} catch (error) {
|
|
340
|
+
return error instanceof Failure ? { failed: error.message, retry: error.retry } : { failed: 'no answer', retry: true };
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
const controller = new AbortController();
|
|
344
|
+
const sourceOptions = { ...options, timeLeft: () => deadline - performance.now(),
|
|
345
|
+
signal: anySignal([options.signal, controller.signal].filter(Boolean)) };
|
|
346
|
+
const timer = setTimeout(() => controller.abort(), Math.max(1, duration));
|
|
347
|
+
let answer;
|
|
348
|
+
try {
|
|
349
|
+
answer = await attempt();
|
|
350
|
+
if (answer.retry && !sourceOptions.signal.aborted && budget(sourceOptions) >= 2000) answer = await attempt();
|
|
351
|
+
} finally {
|
|
352
|
+
clearTimeout(timer);
|
|
353
|
+
}
|
|
354
|
+
if (!answer.failed) {
|
|
355
|
+
if (!answer.partial) await writeCache(directory, filename, { at: now.getTime(), rows: answer.rows }).catch(() => {});
|
|
356
|
+
return finish('ok', answer.rows, { partial: answer.partial, checkedAt: now.toISOString() });
|
|
357
|
+
}
|
|
358
|
+
// Marks from an earlier answer keep their date, so an outage never hides a known mark.
|
|
359
|
+
const stale = savedRows && age >= 0 && age < staleLimit
|
|
360
|
+
? savedRows.map(row => ({ ...row, checkedAt: new Date(saved.at).toISOString().slice(0, 10) })) : [];
|
|
361
|
+
return finish('failed', stale, { why: answer.failed, ...(stale.length && { checkedAt: new Date(saved.at).toISOString() }) });
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Only a complete answer can support "no mark found" for that office.
|
|
365
|
+
export const officeAnswered = result => result?.state === 'ok' && !result.partial;
|
|
366
|
+
|
|
367
|
+
// Clears the in-process token, session and hold memory (tests).
|
|
368
|
+
export function resetOffices() {
|
|
369
|
+
holds.clear();
|
|
370
|
+
tokens.clear();
|
|
371
|
+
sessions.clear();
|
|
372
|
+
}
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import { anySignal, cacheDir, readCache, writeCache } from './cache.mjs';
|
|
2
2
|
import { checkSocialHandles, handlePlatforms } from './handles.mjs';
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
4
|
|
|
4
5
|
const uspto = 'https://tmsearch.uspto.gov';
|
|
5
6
|
const githubState = 'triage-github-limit.json';
|
|
6
7
|
export const day = 86_400_000;
|
|
7
8
|
const userAgent = 'DomainHound/1.0 (public name lookup)';
|
|
9
|
+
// Relevant Nice classes per category, shared by every trademark office. Software covers 9, 35 and 42.
|
|
8
10
|
const niceClasses = new Map(Object.entries({
|
|
9
|
-
travel: ['039', '043'], software: ['009', '042'], finance: ['036'], retail: ['035'],
|
|
11
|
+
travel: ['039', '043'], software: ['009', '035', '042'], finance: ['036'], retail: ['035'],
|
|
10
12
|
health: ['044'], education: ['041'], food: ['043', '030'], media: ['038', '041'],
|
|
11
13
|
}));
|
|
14
|
+
const techClasses = ['009', '042'];
|
|
15
|
+
export const relevantClasses = category => niceClasses.get(String(category ?? '').trim().toLowerCase()) ?? niceClasses.get('software');
|
|
12
16
|
const wikidataHeaders = { 'User-Agent': 'DomainHound/0.1 (https://domainhound.dev)' };
|
|
13
17
|
const brandTypes = new Set([
|
|
14
18
|
'Q783794', 'Q4830453', 'Q891723', 'Q167037', // Companies
|
|
@@ -52,7 +56,7 @@ export async function readJson(url, options, init) {
|
|
|
52
56
|
return null;
|
|
53
57
|
}
|
|
54
58
|
|
|
55
|
-
function exactPhrases(label, input) {
|
|
59
|
+
export function exactPhrases(label, input) {
|
|
56
60
|
const spaced = input.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase()
|
|
57
61
|
.replace(/[^a-z0-9]+/g, ' ').trim();
|
|
58
62
|
// A glued name can have an unknown word boundary. Try each two-word spelling in one request.
|
|
@@ -89,7 +93,7 @@ export function matchTier(a, b) {
|
|
|
89
93
|
}
|
|
90
94
|
|
|
91
95
|
export async function searchMarks(name, input, options = {}) {
|
|
92
|
-
const relevant =
|
|
96
|
+
const relevant = relevantClasses(options.category);
|
|
93
97
|
const variants = exactPhrases(letters(name), input);
|
|
94
98
|
const matches = variants.map(query => ({ match_phrase: { wordmark: { query, boost: 3 } } }));
|
|
95
99
|
const key = variants[0];
|
|
@@ -120,17 +124,24 @@ export async function searchMarks(name, input, options = {}) {
|
|
|
120
124
|
.map(value => String(value).match(/\b\d{3}\b/)?.[0]).filter(Boolean);
|
|
121
125
|
const owner = String([].concat(row.ownerName ?? []).at(-1) ?? '')
|
|
122
126
|
.replace(/\s+\([^;]*;\s*[A-Z ,.-]+\)$/, '').replace(/\s+\([^)]*\)$/, '');
|
|
123
|
-
|
|
127
|
+
const serial = /^\d{8}$/.test(row.id) ? row.id : null;
|
|
128
|
+
return [{ office: 'US', name: compactText(row.wordmark, 65), owner: compactText(owner, 70),
|
|
124
129
|
classes, relevant: classes.some(value => relevant.includes(value)), relevantClasses: classes.filter(value => relevant.includes(value)),
|
|
125
|
-
tier, registered: row.registered === true,
|
|
126
|
-
serial:
|
|
127
|
-
}).sort((
|
|
130
|
+
tier, registered: row.registered === true, live: true, status: row.registered === true ? 'registered' : 'applied',
|
|
131
|
+
serial, url: serial ? usptoRecord(serial) : null }];
|
|
132
|
+
}).sort(markOrder(key));
|
|
128
133
|
}
|
|
129
134
|
|
|
135
|
+
export const usptoRecord = serial => 'https://tsdr.uspto.gov/#caseNumber=' + serial
|
|
136
|
+
+ '&caseSearchType=US_APPLICATION&caseType=DEFAULT&searchType=statusSearch';
|
|
137
|
+
|
|
138
|
+
// Strongest mark first: closer tier, then a relevant class, then a registered mark.
|
|
139
|
+
export const markOrder = key => (a, b) => markWeight(b, key) - markWeight(a, key) || Number(b.registered) - Number(a.registered);
|
|
140
|
+
|
|
130
141
|
function markWeight(mark, key) {
|
|
131
142
|
const tier = ['Fuzzy', 'Near-identical', 'Exact'].indexOf(mark.tier);
|
|
132
143
|
const firstLetter = Number(letters(mark.name)[0] === key[0]);
|
|
133
|
-
const tech = Number(mark.classes.some(value =>
|
|
144
|
+
const tech = Number(mark.classes.some(value => techClasses.includes(value)));
|
|
134
145
|
return 10 * tier + (mark.relevant ? tier ? 25 : 5 : 0) + firstLetter + 0.2 * tech;
|
|
135
146
|
}
|
|
136
147
|
|
|
@@ -158,7 +169,7 @@ export function searchApps(name, input, options = {}) {
|
|
|
158
169
|
async function fetchApps(name, input, options) {
|
|
159
170
|
const data = await readJson('https://itunes.apple.com/search?' + new URLSearchParams({
|
|
160
171
|
term: input, country: 'us', entity: 'software', limit: '25',
|
|
161
|
-
}), options);
|
|
172
|
+
}), options, { timeout: 5000 });
|
|
162
173
|
if (!Array.isArray(data?.results)) return null;
|
|
163
174
|
const rows = data.results.flatMap(row => {
|
|
164
175
|
if (typeof row?.trackName !== 'string' || !/^\d{4,}$/.test(row.trackId) || !appNameMatches(name, row.trackName)) return [];
|
|
@@ -184,18 +195,34 @@ export function searchEntities(name, input, options = {}) {
|
|
|
184
195
|
return cacheTractionSource('wikidata', name, options, () => fetchEntities(name, input, options));
|
|
185
196
|
}
|
|
186
197
|
|
|
198
|
+
// Wikidata can return a "too busy" error inside an HTTP 200 when searches overlap.
|
|
199
|
+
let wikidataSearches = Promise.resolve();
|
|
200
|
+
function searchWikidata(url, options) {
|
|
201
|
+
const turn = wikidataSearches.then(async () => {
|
|
202
|
+
for (const wait of [0, 250, 500]) {
|
|
203
|
+
if (wait) await delay(wait);
|
|
204
|
+
if (options.signal?.aborted) return null;
|
|
205
|
+
const data = await readJson(url, options, { timeout: 5000, headers: wikidataHeaders });
|
|
206
|
+
if (data?.error?.code !== 'cirrussearch-too-busy-error') return data;
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
});
|
|
210
|
+
wikidataSearches = turn.catch(() => {});
|
|
211
|
+
return turn;
|
|
212
|
+
}
|
|
213
|
+
|
|
187
214
|
async function fetchEntities(name, input, options) {
|
|
188
215
|
const api = 'https://www.wikidata.org/w/api.php?';
|
|
189
|
-
const data = await
|
|
216
|
+
const data = await searchWikidata(api + new URLSearchParams({
|
|
190
217
|
action: 'wbsearchentities', search: input, language: 'en', format: 'json', limit: '15',
|
|
191
|
-
}), options
|
|
218
|
+
}), options);
|
|
192
219
|
if (!Array.isArray(data?.search)) return null;
|
|
193
220
|
const key = letters(name);
|
|
194
221
|
const exact = data.search.filter(row => /^Q\d+$/.test(row.id) && letters(row.label) === key);
|
|
195
222
|
if (!exact.length) return [];
|
|
196
223
|
const getClaims = async (ids, props = 'claims') => (await readJson(api + new URLSearchParams({
|
|
197
224
|
action: 'wbgetentities', ids: ids.join('|'), props, format: 'json',
|
|
198
|
-
}), options, { timeout:
|
|
225
|
+
}), options, { timeout: options.detailTimeoutMs ?? 3000, headers: wikidataHeaders }))?.entities;
|
|
199
226
|
// The same request returns sitelinks and the official website (P856) for traction.
|
|
200
227
|
const details = await getClaims(exact.map(row => row.id), 'claims|sitelinks');
|
|
201
228
|
if (!details && options.cacheLifetime) return null;
|