-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathai-help-macros.js
More file actions
786 lines (721 loc) · 21.6 KB
/
Copy pathai-help-macros.js
File metadata and controls
786 lines (721 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
/** @import { CheerioAPI } from "cheerio" */
/** @import { BrowserName, BrowserStatement, SimpleSupportStatement, VersionValue } from "@mdn/browser-compat-data/types" */
/** @import { SimpleSupportStatementExtended } from "@mdn/bcd-utils-api" */
/** @import * as Rari from "@mdn/rari" */
/** @import { IndexedDoc, Doc, FormattingUpdate, EmbeddingUpdate, DocMetadata } from "./types.js" */
/** @import OpenAI from "openai" */
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import pg from "pg";
import pgvector from "pgvector/pg";
import { fdir } from "fdir";
import OpenAIClient from "openai";
import { load as cheerio } from "cheerio";
import { BUILD_OUT_ROOT, OPENAI_KEY, PG_URI } from "./env.js";
import { getBCDDataForPath } from "@mdn/bcd-utils-api";
import path from "node:path";
import { h2mSync } from "./libs/markdown.js";
const EMBEDDING_MODEL = "text-embedding-3-small";
const EMBEDDING_MODEL_NEXT = "text-embedding-3-small";
/**
* @param {string} directory
* @param {boolean} updateFormatting
* @param {boolean} usePlainHtml
*/
export async function updateEmbeddings(
directory,
updateFormatting,
usePlainHtml
) {
if (!OPENAI_KEY || !PG_URI) {
throw Error("Please set these environment variables: OPENAI_KEY, PG_URI");
}
// Postgres.
const pgClient = new pg.Client({
connectionString: PG_URI,
});
await pgClient.connect();
await pgClient.query("CREATE EXTENSION IF NOT EXISTS vector");
await pgvector.registerType(pgClient);
// Open AI.
const openai = new OpenAIClient({
apiKey: OPENAI_KEY,
});
/**
* @param {string} input
* @param {string} model
*/
const createEmbedding = async (input, model) => {
/** @type {OpenAI.Embeddings.CreateEmbeddingResponse} */
let embeddingResponse;
try {
embeddingResponse = await openai.embeddings.create({
model,
input,
});
} catch (/** @type {any} */ e) {
const {
error: { message, type },
status,
} = e;
console.error(
`[!] Failed to create embedding (${status}): ${type} - ${message}`
);
// Try again with trimmed content.
embeddingResponse = await openai.embeddings.create({
model,
input: input.substring(0, 15000),
});
}
const {
data: [{ embedding }],
usage: { total_tokens },
} = embeddingResponse;
return {
total_tokens,
embedding,
};
};
console.log(`Retrieving all indexed documents...`);
const existingDocs = await fetchAllExistingDocs(pgClient);
console.log(`-> Done.`);
/** @type {Map<string, IndexedDoc>} */
const existingDocByUrl = new Map(
existingDocs.map((doc) => [doc.mdn_url, doc])
);
console.log(`Determining changed and deleted documents...`);
/** @type {Set<string>} */
const seenUrls = new Set();
/** @type {Doc[]} */
const updates = [];
/** @type {FormattingUpdate[]} */
const formattingUpdates = [];
/** @type {EmbeddingUpdate[]} */
const embeddingUpdates = [];
for await (const { mdn_url, title, title_short, markdown, text } of builtDocs(
directory,
usePlainHtml
)) {
seenUrls.add(mdn_url);
// Check for existing document in DB and compare checksums.
const existingDoc = existingDocByUrl.get(mdn_url);
const text_hash = createHash("sha256").update(text).digest("base64");
const markdown_hash = createHash("sha256")
.update(markdown)
.digest("base64");
if (existingDoc?.text_hash !== text_hash) {
// Document added or content changed => (re)generate embeddings.
updates.push({
mdn_url,
title,
title_short,
markdown,
markdown_hash,
text,
text_hash,
});
} else {
if (updateFormatting || existingDoc?.markdown_hash !== markdown_hash) {
// Document formatting changed => update markdown.
formattingUpdates.push({
mdn_url,
title,
title_short,
markdown,
markdown_hash,
});
}
if (
!existingDoc.has_embedding ||
!existingDoc.has_embedding_next !== !EMBEDDING_MODEL_NEXT
) {
// Embedding missing => add embeddings.
const { has_embedding, has_embedding_next } = existingDoc;
embeddingUpdates.push({
mdn_url,
text,
has_embedding,
has_embedding_next,
});
}
}
}
console.log(
`-> ${updates.length} (${formattingUpdates.length}) of ${seenUrls.size} documents were changed or added (or formatted).`
);
if (embeddingUpdates.length > 0) {
console.log(
`-> ${embeddingUpdates.length} documents have outdated embeddings.`
);
}
/** @type {IndexedDoc[]} */
const deletions = [...existingDocByUrl.entries()]
.filter(([key]) => !seenUrls.has(key))
.map(([, value]) => value);
console.log(
`-> ${deletions.length} of ${existingDocs.length} indexed documents were deleted (or moved).`
);
if (
updates.length > 0 ||
formattingUpdates.length > 0 ||
embeddingUpdates.length > 0
) {
console.log(`Applying updates...`);
for (const {
mdn_url,
title,
title_short,
markdown,
markdown_hash,
text,
text_hash,
} of updates) {
try {
console.log(`-> [${mdn_url}] Updating document...`);
// Embedding for full document.
const [{ total_tokens, embedding }, embedding_next] = await Promise.all(
[
createEmbedding(text, EMBEDDING_MODEL),
EMBEDDING_MODEL_NEXT && EMBEDDING_MODEL_NEXT !== EMBEDDING_MODEL
? createEmbedding(text, EMBEDDING_MODEL_NEXT).then(
({ embedding }) => embedding
)
: null,
]
);
// Create/update document record.
const query = {
name: "upsert-embedding-doc",
text: `
INSERT INTO mdn_doc_macro(
mdn_url,
title,
title_short,
markdown,
markdown_hash,
token_count,
embedding,
embedding_next,
text_hash
)
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (mdn_url) DO
UPDATE
SET mdn_url = $1,
title = $2,
title_short = $3,
markdown = $4,
markdown_hash = $5,
token_count = $6,
embedding = $7,
embedding_next = $8,
text_hash = $9
`,
values: [
mdn_url,
title,
title_short,
markdown,
markdown_hash,
total_tokens,
pgvector.toSql(embedding),
pgvector.toSql(embedding_next ?? embedding),
text_hash,
],
rowMode: "array",
};
await pgClient.query(query);
} catch (/** @type {any} */ err) {
console.error(`!> [${mdn_url}] Failed to update document.`);
const context = err?.response?.data ?? err?.response ?? err;
console.error(context);
}
}
for (const {
mdn_url,
title,
title_short,
markdown,
markdown_hash,
} of formattingUpdates) {
try {
console.log(
`-> [${mdn_url}] Updating document without generating new embedding...`
);
// Create/update document record.
const query = {
name: "upsert-doc",
text: `
INSERT INTO mdn_doc_macro(mdn_url, title, title_short, markdown, markdown_hash)
VALUES($1, $2, $3, $4, $5) ON CONFLICT (mdn_url) DO
UPDATE
SET mdn_url = $1,
title = $2,
title_short = $3,
markdown = $4,
markdown_hash = $5
`,
values: [mdn_url, title, title_short, markdown, markdown_hash],
rowMode: "array",
};
await pgClient.query(query);
} catch (/** @type {any} */ err) {
console.error(`!> [${mdn_url}] Failed to update document.`);
const context = err?.response?.data ?? err?.response ?? err;
console.error(context);
}
}
for (const {
mdn_url,
text,
has_embedding,
has_embedding_next,
} of embeddingUpdates) {
try {
console.log(`-> [${mdn_url}] Updating embeddings...`);
if (!has_embedding) {
const { total_tokens, embedding } = await createEmbedding(
text,
EMBEDDING_MODEL
);
const query = {
name: "upsert-doc-embedding",
text: "UPDATE mdn_doc_macro SET total_tokens = $2, embedding = $3 WHERE mdn_url = $1",
values: [
mdn_url,
total_tokens,
embedding ? pgvector.toSql(embedding) : null,
],
rowMode: "array",
};
await pgClient.query(query);
}
if (!has_embedding_next) {
const embedding = EMBEDDING_MODEL_NEXT
? (await createEmbedding(text, EMBEDDING_MODEL_NEXT)).embedding
: null;
const query = {
name: "upsert-doc-embedding-next",
text: "UPDATE mdn_doc_macro SET embedding_next = $2 WHERE mdn_url = $1",
values: [mdn_url, embedding ? pgvector.toSql(embedding) : null],
rowMode: "array",
};
await pgClient.query(query);
}
} catch (/** @type {any} */ err) {
console.error(`!> [${mdn_url}] Failed to add embeddings.`);
const context = err?.response?.data ?? err?.response ?? err;
console.error(context);
}
}
console.log(`-> Done.`);
}
if (deletions.length > 0) {
console.log(`Applying deletions...`);
for (const { id, mdn_url } of deletions) {
console.log(`-> [${mdn_url}] Deleting indexed document...`);
const query = {
name: "delete-doc",
text: `DELETE from mdn_doc_macro WHERE id = $1`,
values: [id],
rowMode: "array",
};
await pgClient.query(query);
}
console.log(`-> Done.`);
}
pgClient.end();
}
/**
* @param {string} directory
* @param {boolean} usePlainHtml
*/
async function formatDocs(directory, usePlainHtml) {
for await (const { markdown, text } of builtDocs(directory, usePlainHtml)) {
console.log(markdown, text);
}
}
/**
* @param {string} directory
* @returns {AsyncGenerator<string>}
*/
async function* builtPaths(directory) {
const api = new fdir()
.withFullPaths()
.withErrors()
.filter((filePath) => filePath.endsWith("metadata.json"))
.crawl(directory);
const paths = await api.withPromise();
for (const path of paths) {
yield path;
}
}
/**
* @param {string} directory
* @param {boolean} usePlainHtml
*/
async function* builtDocs(directory, usePlainHtml) {
for await (const metadataPath of builtPaths(directory)) {
try {
const raw = await readFile(metadataPath, "utf-8");
const { title, short_title, mdn_url, hash } = /** @type {DocMetadata} */ (
JSON.parse(raw)
);
/** @type {CheerioAPI} */
let $;
if (usePlainHtml) {
const plainPath = path.join(path.dirname(metadataPath), "plain.html");
const plainHTML = await readFile(plainPath, "utf-8");
// reformat HTML version, used as context
$ = cheerio(plainHTML);
} else {
const jsonPath = path.join(path.dirname(metadataPath), "index.json");
const json = JSON.parse(await readFile(jsonPath, "utf-8"));
const doc = /** @type {Rari.Doc} */ (json.doc);
// Assemble the interim HTML from the json data
$ = cheerio("<html><head></head><body></body></html>");
for (const section of doc.body ?? []) {
const tag = section.value.isH3 ? "h3" : "h2";
if (section.value.title) {
$("body").append("\n");
$("body").append(
`<${tag} id="${section.value.id ?? ""}">${section.value.title}</${tag}>`
);
}
switch (section.type) {
case "prose": {
$("body").append("\n");
$("body").append(section.value.content);
break;
}
case "specifications":
break;
case "browser_compatibility": {
$("body").append("\n");
$("body").append(
` <div>${buildBCDTable(section.value.query)}</div> `
);
break;
}
}
}
$("span.language-name").remove();
}
$("#specifications, .bc-specs").remove();
$("body").prepend(`<h1>${title}</h1>`);
$("head").prepend(`<title>${title}</title>`);
$("head").prepend(`<link rel="canonical" href="${mdn_url}" />`);
$("[width], [height]").each((_, el) => {
$(el).removeAttr("width").removeAttr("height");
});
$(".bc-data[data-query]").each((_, el) => {
$(el).replaceWith(
buildBCDTable(/** @type {string} */ ($(el).data("query")))
);
});
const html = $.html();
const markdown = h2mSync(html);
// reformat text version, used for embedding
$("title").remove();
$("#browser_compatibility, .bc-table").remove();
const text = $.text().trim().replace(/\n+/g, "\n");
yield {
mdn_url,
title,
title_short: short_title || title,
hash,
markdown,
text,
};
} catch (e) {
console.error(`Error preparing doc: ${metadataPath}`, e);
}
}
}
/**
* @param {string} query
* @returns {string}
*/
function buildBCDTable(query) {
const bcdData = getBCDDataForPath(query);
if (!bcdData) return "";
const { browsers, data } = bcdData;
return data.__compat?.support
? `<table class="bc-table">
<thead><tr><th>Browser</th><th>Support</th>
<tbody>
${Object.entries(data.__compat?.support)
.map(
([browser, support]) =>
`<tr><td>${browsers[/** @type {BrowserName} */ (browser)].name}</td><td>${buildBCDSupportString(
browsers[/** @type {BrowserName} */ (browser)],
support
)}</td></tr>`
)
.join("\n")}
</tbody>
</table>`
: "";
}
/**
* @param {BrowserStatement} browser
* @param {(SimpleSupportStatement & SimpleSupportStatementExtended)[]} support
* @returns {string}
*/
function buildBCDSupportString(browser, support) {
return support
.flatMap((item) => {
return [
item.version_removed &&
!support.some(
(otherItem) => otherItem.version_added === item.version_removed
)
? `Removed in ${labelFromString(
item.version_removed,
browser
)} and later`
: null,
item.partial_implementation ? "Partial support" : null,
item.prefix
? `Implemented with the vendor prefix: ${item.prefix}`
: null,
item.alternative_name
? `Alternate name: ${item.alternative_name}`
: null,
item.flags ? FlagsNote(item, browser) : null,
item.notes
? (Array.isArray(item.notes) ? item.notes : [item.notes]).join(". ")
: null,
versionIsPreview(item.version_added, browser)
? "Preview browser support"
: null,
isFullySupportedWithoutLimitation(item) &&
!versionIsPreview(item.version_added, browser)
? `Full support since version ${item.version_added}${
item.release_date ? ` (released ${item.release_date})` : ""
}`
: isNotSupportedAtAll(item)
? "No support"
: null,
]
.flat()
.filter((x) => Boolean(x));
})
.join(". ");
}
/**
* @param {string | boolean | null | undefined} version
* @param {BrowserStatement} browser
*/
function labelFromString(version, browser) {
if (typeof version !== "string") {
return "?";
}
// Treat BCD ranges as exact versions to avoid confusion for the reader
// See https://github.com/mdn/yari/issues/3238
if (version.startsWith("≤")) {
return version.slice(1);
}
if (version === "preview") {
return browser.preview_name;
}
return version;
}
/**
* @param {SimpleSupportStatement} supportItem
* @param {BrowserStatement} browser
* @returns {string}
*/
function FlagsNote(supportItem, browser) {
const hasAddedVersion = typeof supportItem.version_added === "string";
const hasRemovedVersion = typeof supportItem.version_removed === "string";
const flags = supportItem.flags || [];
return `${
hasAddedVersion ? `From version ${supportItem.version_added}` : ""
}${
hasRemovedVersion
? `${hasAddedVersion ? " until" : "Until"} version ${
supportItem.version_removed
} (exclusive)`
: ""
}${
hasAddedVersion || hasRemovedVersion ? ": this" : "This"
} feature is behind the ${flags.map((flag, i) => {
const valueToSet = flag.value_to_set
? ` (needs to be set to <code>${flag.value_to_set}</code>)`
: "";
return `<code>${flag.name}</code>${
flag.type === "preference" ? ` preference${valueToSet}` : ""
}${flag.type === "runtime_flag" ? ` runtime flag${valueToSet}` : ""}${
i < flags.length - 1 ? " and the " : ""
}`;
})}.${
browser.pref_url && flags.some((flag) => flag.type === "preference")
? ` To change preferences in ${browser.name}, visit ${browser.pref_url}.`
: ""
}`;
}
/**
* @param {VersionValue | string | undefined} version
* @param {BrowserStatement} browser
* @returns {boolean}
*/
function versionIsPreview(version, browser) {
if (version === "preview") {
return true;
}
if (browser && typeof version === "string" && browser.releases[version]) {
return ["beta", "nightly", "planned"].includes(
browser.releases[version].status
);
}
return false;
}
/**
* @param {SimpleSupportStatement} support
*/
export function isFullySupportedWithoutLimitation(support) {
return support.version_added && !hasLimitation(support);
}
/**
* @param {SimpleSupportStatement} support
*/
function hasLimitation(support) {
return hasMajorLimitation(support) || support.notes;
}
/**
* @param {SimpleSupportStatement} support
*/
function hasMajorLimitation(support) {
return (
support.partial_implementation ||
support.alternative_name ||
support.flags ||
support.prefix ||
support.version_removed
);
}
/**
* @param {SimpleSupportStatement} support
*/
export function isNotSupportedAtAll(support) {
return !support.version_added && !hasLimitation(support);
}
/**
* @param {pg.Client} pgClient
* @returns {Promise<IndexedDoc[]>}
*/
async function fetchAllExistingDocs(pgClient) {
const PAGE_SIZE = 1000;
/** @param {number} lastId */
const selectDocs = async (lastId) => {
const query = {
name: "fetch-all-doc",
text: `
SELECT id,
mdn_url,
title,
token_count,
embedding IS NOT NULL as has_embedding,
embedding_next IS NOT NULL as has_embedding_next,
markdown_hash,
text_hash
from mdn_doc_macro
WHERE id > $1
ORDER BY id ASC
LIMIT $2
`,
values: [lastId, PAGE_SIZE],
rowMode: "array",
};
const result = await pgClient.query(query);
return result.rows.map(
([
id,
mdn_url,
title,
token_count,
has_embedding,
has_embedding_next,
markdown_hash,
text_hash,
]) => {
return /** @type {IndexedDoc} */ ({
id,
mdn_url,
title,
token_count,
has_embedding,
has_embedding_next,
markdown_hash,
text_hash,
});
}
);
};
/** @type {IndexedDoc[]} */
const allDocs = [];
let docs = await selectDocs(0);
allDocs.push(...docs);
while (docs.length === PAGE_SIZE) {
const lastItem = docs[docs.length - 1];
docs = await selectDocs(lastItem.id);
allDocs.push(...docs);
}
return allDocs;
}
// CLI.
yargs(hideBin(process.argv))
.command(
"update-index [directory]",
"Generates OpenAI embeddings for all documents and uploads them to Supabase.",
(yargs) => {
return yargs
.positional("directory", {
describe: "Path in which to execute it",
type: "string",
default: path.join(BUILD_OUT_ROOT, "en-us", "docs"),
})
.option("use-plain-html", {
describe: "Use `plain.html` files instead of `index.json` files.",
type: "boolean",
default: false,
})
.option("update-formatting", {
describe:
"Even if hashes match, update without generating a new embedding.",
type: "boolean",
default: false,
});
},
async (argv) => {
const { directory, updateFormatting, usePlainHtml } = argv;
return updateEmbeddings(directory, updateFormatting, usePlainHtml);
}
)
.command(
"format-docs [directory]",
"Generates formatted docs for local debugging",
(yargs) => {
return yargs
.positional("directory", {
describe: "Path in which to execute it",
type: "string",
default: path.join(BUILD_OUT_ROOT, "en-us", "docs"),
})
.option("use-plain-html", {
describe: "Use `plain.html` files instead of `index.json` files.",
type: "boolean",
default: false,
});
},
async (argv) => {
const { directory, usePlainHtml } = argv;
return formatDocs(directory, usePlainHtml);
}
)
.demandCommand(1, "You need at least one command before moving on")
.help()
.alias("help", "h")
.parse();