@docs-sdk-dev/reader 0.0.0-stage → 0.4.0-next.0

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.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -2
  3. package/dist/annotation-projection.d.ts +35 -0
  4. package/dist/annotation-projection.js +78 -0
  5. package/dist/annotation-projection.js.map +1 -0
  6. package/dist/artifacts.d.ts +19 -0
  7. package/dist/artifacts.js +33 -0
  8. package/dist/artifacts.js.map +1 -0
  9. package/dist/ask.d.ts +41 -0
  10. package/dist/ask.js +89 -0
  11. package/dist/ask.js.map +1 -0
  12. package/dist/collection-view.d.ts +190 -0
  13. package/dist/collection-view.js +170 -0
  14. package/dist/collection-view.js.map +1 -0
  15. package/dist/composition.d.ts +199 -0
  16. package/dist/composition.js +473 -0
  17. package/dist/composition.js.map +1 -0
  18. package/dist/condition.d.ts +17 -0
  19. package/dist/condition.js +61 -0
  20. package/dist/condition.js.map +1 -0
  21. package/dist/content-schema.d.ts +182 -0
  22. package/dist/content-schema.js +288 -0
  23. package/dist/content-schema.js.map +1 -0
  24. package/dist/context-search.d.ts +168 -0
  25. package/dist/context-search.js +73 -0
  26. package/dist/context-search.js.map +1 -0
  27. package/dist/context-store.d.ts +93 -0
  28. package/dist/context-store.js +438 -0
  29. package/dist/context-store.js.map +1 -0
  30. package/dist/dimension-runtime.d.ts +203 -0
  31. package/dist/dimension-runtime.js +737 -0
  32. package/dist/dimension-runtime.js.map +1 -0
  33. package/dist/dimensions.d.ts +84 -0
  34. package/dist/dimensions.js +136 -0
  35. package/dist/dimensions.js.map +1 -0
  36. package/dist/directory-navigation.d.ts +60 -0
  37. package/dist/directory-navigation.js +41 -0
  38. package/dist/directory-navigation.js.map +1 -0
  39. package/dist/directory-sections.d.ts +9 -0
  40. package/dist/directory-sections.js +76 -0
  41. package/dist/directory-sections.js.map +1 -0
  42. package/dist/document-reader.d.ts +1017 -0
  43. package/dist/document-reader.js +396 -0
  44. package/dist/document-reader.js.map +1 -0
  45. package/dist/document-selection.d.ts +412 -0
  46. package/dist/document-selection.js +45 -0
  47. package/dist/document-selection.js.map +1 -0
  48. package/dist/evidence.d.ts +102 -0
  49. package/dist/evidence.js +104 -0
  50. package/dist/evidence.js.map +1 -0
  51. package/dist/index.d.ts +19 -0
  52. package/dist/index.js +23 -0
  53. package/dist/model.d.ts +89 -0
  54. package/dist/model.js +31 -0
  55. package/dist/model.js.map +1 -0
  56. package/dist/module.d.ts +657 -0
  57. package/dist/module.js +199 -0
  58. package/dist/module.js.map +1 -0
  59. package/dist/navigation-view.d.ts +33 -0
  60. package/dist/navigation-view.js +68 -0
  61. package/dist/navigation-view.js.map +1 -0
  62. package/dist/node.d.ts +2004 -0
  63. package/dist/node.js +210 -0
  64. package/dist/node.js.map +1 -0
  65. package/dist/open-docs.d.ts +1396 -0
  66. package/dist/open-docs.js +198 -0
  67. package/dist/open-docs.js.map +1 -0
  68. package/dist/outline.d.ts +97 -0
  69. package/dist/outline.js +171 -0
  70. package/dist/outline.js.map +1 -0
  71. package/dist/persistence.d.ts +82 -0
  72. package/dist/persistence.js +377 -0
  73. package/dist/persistence.js.map +1 -0
  74. package/dist/projection-catalog.d.ts +23 -0
  75. package/dist/projection-catalog.js +45 -0
  76. package/dist/projection-catalog.js.map +1 -0
  77. package/dist/publication.d.ts +59 -0
  78. package/dist/publication.js +11 -0
  79. package/dist/publication.js.map +1 -0
  80. package/dist/reader.d.ts +236 -0
  81. package/dist/reader.js +400 -0
  82. package/dist/reader.js.map +1 -0
  83. package/dist/references.d.ts +54 -0
  84. package/dist/references.js +70 -0
  85. package/dist/references.js.map +1 -0
  86. package/dist/retrieval.d.ts +82 -0
  87. package/dist/retrieval.js +135 -0
  88. package/dist/retrieval.js.map +1 -0
  89. package/dist/search-view.d.ts +11 -0
  90. package/dist/search-view.js +30 -0
  91. package/dist/search-view.js.map +1 -0
  92. package/dist/search.d.ts +95 -0
  93. package/dist/search.js +234 -0
  94. package/dist/search.js.map +1 -0
  95. package/dist/semantic.d.ts +177 -0
  96. package/dist/semantic.js +104 -0
  97. package/dist/semantic.js.map +1 -0
  98. package/dist/skills.d.ts +21 -0
  99. package/dist/skills.js +42 -0
  100. package/dist/skills.js.map +1 -0
  101. package/docs/index.md +10 -0
  102. package/docs/sdk/composition.md +72 -0
  103. package/docs/sdk/reader-storage.md +70 -0
  104. package/docs/sdk/reader.md +99 -0
  105. package/docs/zh-CN/sdk/composition.md +72 -0
  106. package/docs/zh-CN/sdk/reader-storage.md +70 -0
  107. package/docs/zh-CN/sdk/reader.md +99 -0
  108. package/package.json +69 -4
package/dist/search.js ADDED
@@ -0,0 +1,234 @@
1
+ import { acceptsSearchEntry, searchEntryResult } from "./search-view.js";
2
+
3
+ // src/search.ts
4
+ const cjk = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
5
+ const segmenters = /* @__PURE__ */ new Map();
6
+ function segmenterFor(text, locale) {
7
+ const language = locale?.toLowerCase().split(/[-_]/)[0];
8
+ const selected = language === "ja" || language === "ko" || language === "zh" ? language : /[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text) ? "ja" : /\p{Script=Hangul}/u.test(text) ? "ko" : "zh";
9
+ let segmenter = segmenters.get(selected);
10
+ if (!segmenter) segmenters.set(selected, segmenter = new Intl.Segmenter(selected, { granularity: "word" }));
11
+ return segmenter;
12
+ }
13
+ /** Insert word boundaries for CJK prose before either search engine builds or queries its index. */
14
+ function segmentSearchText(text, locale) {
15
+ if (!cjk.test(text)) return text;
16
+ return [...segmenterFor(text, locale).segment(text)].filter((part) => part.isWordLike).map((part) => part.segment).join(" ");
17
+ }
18
+ /**
19
+ * Lowercase words of letters and digits in any script. camelCase identifiers also yield their parts, so
20
+ * `defaultOpen` matches both "defaultopen" and "open". Single CJK characters remain searchable.
21
+ */
22
+ function tokenize(text, locale) {
23
+ const tokens = [];
24
+ for (const [word] of segmentSearchText(text, locale).matchAll(/[\p{L}\p{N}]+/gu)) {
25
+ const parts = word.split(/(?<=[\p{Ll}\p{N}])(?=\p{Lu})/u);
26
+ for (const token of parts.length > 1 ? [word, ...parts] : [word]) {
27
+ const lower = token.toLowerCase();
28
+ if (lower.length > 1 || cjk.test(lower)) tokens.push(lower);
29
+ }
30
+ }
31
+ return tokens;
32
+ }
33
+ /**
34
+ * Function words per built-in language: articles, pronouns, prepositions, conjunctions, auxiliaries and question
35
+ * words. They say how a question is asked, not what it is about, so a query leaves them out. Negations stay, since
36
+ * they change the meaning, and so does "have", which often means possession ("no component has this ID"). Single letters are never indexed, so they are not listed.
37
+ */
38
+ const functionWords = {
39
+ en: new Set("about am an and are as at be been being but by can could did do does doing done for from he her here hers him his how if in into is it its me my of on or our ours she should so than that the their theirs them then there these they this those to us was we were what when where which while who whom whose why will with would you your yours".split(" ")),
40
+ fr: new Set("au aux avec ce ces cet cette comment dans de des du elle elles en est et être il ils je la le les leur leurs lui ma mais me mes mon nous on ont ou où par pour qu quand que quel quelle quelles quels qui quoi sa se ses son sont sur ta te tes ton tu un une vos votre vous".split(" "))
41
+ };
42
+ /**
43
+ * The words of a query that carry its meaning: its tokens without the function words of its language. The language
44
+ * is the locale's (`fr-CA` uses `fr`); without a locale it is English, the interface's default, and a language
45
+ * without a built-in list keeps every word. A query of only function words keeps them all, so it still finds something.
46
+ */
47
+ function queryTerms(text, locale) {
48
+ const terms = [...new Set(tokenize(text, locale))];
49
+ const words = functionWords[(locale ?? "en").toLowerCase().split(/[-_]/)[0]];
50
+ if (!words) return terms;
51
+ const meaningful = terms.filter((term) => !words.has(term));
52
+ return meaningful.length ? meaningful : terms;
53
+ }
54
+ /**
55
+ * The subheading of a result that shares the most words with a query, as search results point at it: whole words
56
+ * count fully, and indexed words starting with a query word of four or more letters count half. None if nothing is shared.
57
+ */
58
+ function closestSubheading(subheadings, query, locale) {
59
+ const words = queryTerms(query, locale);
60
+ const expanded = /* @__PURE__ */ new Map();
61
+ for (const subheading of subheadings ?? []) for (const token of tokenize(subheading.text, locale)) for (const word of words) if (token === word) expanded.set(token, 1);
62
+ else if (word.length >= prefixLength && token.startsWith(word) && !expanded.has(token)) expanded.set(token, prefixWeight);
63
+ return closest(subheadings, expanded, locale);
64
+ }
65
+ /**
66
+ * Where a query's words appear in a displayed text, as sorted, non-overlapping `[start, end)` offsets, for highlighting
67
+ * a result. Words match as ranking matches them: function words do not count, camelCase parts match on their own, and
68
+ * a query word of four or more letters marks the start of a longer word it prefixes ("valid" in "validation").
69
+ */
70
+ function matchedRanges(text, query, locale) {
71
+ const terms = queryTerms(query, locale);
72
+ const ranges = [];
73
+ if (!terms.length) return ranges;
74
+ const mark = (token, start) => {
75
+ const lower = token.toLowerCase();
76
+ if (lower.length < 2 && !cjk.test(lower)) return;
77
+ if (terms.includes(lower)) return void ranges.push([start, start + token.length]);
78
+ const prefix = terms.find((term) => term.length >= prefixLength && lower.startsWith(term));
79
+ if (prefix) ranges.push([start, start + (lower.length === token.length ? prefix.length : token.length)]);
80
+ };
81
+ for (const run of text.matchAll(/[\p{L}\p{N}]+/gu)) {
82
+ const words = cjk.test(run[0]) ? [...segmenterFor(run[0], locale).segment(run[0])].filter((part) => part.isWordLike).map((part) => [part.segment, part.index]) : [[run[0], 0]];
83
+ for (const [word, offset] of words) {
84
+ const start = run.index + offset;
85
+ mark(word, start);
86
+ let position = start;
87
+ const parts = word.split(/(?<=[\p{Ll}\p{N}])(?=\p{Lu})/u);
88
+ if (parts.length > 1) for (const part of parts) {
89
+ mark(part, position);
90
+ position += part.length;
91
+ }
92
+ }
93
+ }
94
+ ranges.sort((left, right) => left[0] - right[0] || right[1] - left[1]);
95
+ const merged = [];
96
+ for (const range of ranges) {
97
+ const last = merged.at(-1);
98
+ if (last && range[0] <= last[1]) last[1] = Math.max(last[1], range[1]);
99
+ else merged.push([...range]);
100
+ }
101
+ return merged;
102
+ }
103
+ /**
104
+ * One index per locale for sites with two or more: a locale's index keeps its own entries and those without a locale,
105
+ * which are exactly the entries a search in that locale can return. Empty for sites with fewer locales.
106
+ */
107
+ function splitSearchIndex(index) {
108
+ const localeKey = index.localeDimension ?? "locale";
109
+ const locales = [...new Set(index.entries.flatMap((entry) => entry.context[localeKey] ? [entry.context[localeKey]] : []))].sort();
110
+ if (locales.length < 2) return /* @__PURE__ */ new Map();
111
+ const { frequency, count, average } = statistics(index);
112
+ return new Map(locales.map((locale) => {
113
+ const entries = index.entries.filter((entry) => entry.context[localeKey] === void 0 || entry.context[localeKey] === locale);
114
+ const terms = new Set(entries.flatMap((entry) => Object.keys(entry.terms)));
115
+ return [locale, {
116
+ schemaVersion: 1,
117
+ entries,
118
+ ...index.localeDimension && { localeDimension: index.localeDimension },
119
+ collection: {
120
+ entries: count,
121
+ averageLength: average,
122
+ frequency: Object.fromEntries([...terms].sort().map((term) => [term, frequency.get(term)]))
123
+ }
124
+ }];
125
+ }));
126
+ }
127
+ function statistics(index) {
128
+ if (index.collection) return {
129
+ frequency: new Map(Object.entries(index.collection.frequency)),
130
+ count: index.collection.entries,
131
+ average: index.collection.averageLength
132
+ };
133
+ const frequency = /* @__PURE__ */ new Map();
134
+ for (const entry of index.entries) for (const term of Object.keys(entry.terms)) frequency.set(term, (frequency.get(term) ?? 0) + 1);
135
+ return {
136
+ frequency,
137
+ count: index.entries.length,
138
+ average: index.entries.reduce((total, entry) => total + entry.length, 0) / Math.max(1, index.entries.length)
139
+ };
140
+ }
141
+ /** Words this long also match indexed words that start with them ("install" finds "installation"), at reduced weight. */
142
+ const prefixLength = 4;
143
+ const prefixWeight = .5;
144
+ /** The subheading sharing the most weight with the expanded query terms; the first wins ties, and none if nothing is shared. */
145
+ function closest(subheadings, expanded, locale) {
146
+ let best;
147
+ let bestScore = 0;
148
+ for (const subheading of subheadings ?? []) {
149
+ const score = [...new Set(tokenize(subheading.text, locale))].reduce((total, token) => total + (expanded.get(token) ?? 0), 0);
150
+ if (score > bestScore) [best, bestScore] = [subheading, score];
151
+ }
152
+ return best;
153
+ }
154
+ /**
155
+ * BM25 ranking over section editions (k1 1.2, b 0.75), filtered to editions compatible with the context. A query
156
+ * ranks with its `queryTerms`, so function words of its locale's language do not count. Prefix matches stand in for
157
+ * stemming. Ties break by section ID so results are stable.
158
+ */
159
+ function createSearch(index) {
160
+ const localeKey = index.localeDimension ?? "locale";
161
+ const { frequency, count, average } = statistics(index);
162
+ const postings = /* @__PURE__ */ new Map();
163
+ for (const [position, entry] of index.entries.entries()) for (const term of Object.keys(entry.terms)) {
164
+ const list = postings.get(term);
165
+ if (list) list.push(position);
166
+ else postings.set(term, [position]);
167
+ }
168
+ const vocabulary = [...frequency.keys()].sort();
169
+ return { query(text, options = {}) {
170
+ const terms = queryTerms(text, options.locale ?? options.context?.[localeKey]);
171
+ if (cjk.test(text)) {
172
+ for (const [raw] of text.toLowerCase().matchAll(/[\p{L}\p{N}]+/gu)) if (cjk.test(raw) && postings.has(raw) && !terms.includes(raw)) terms.push(raw);
173
+ }
174
+ const expanded = /* @__PURE__ */ new Map();
175
+ const groups = [];
176
+ for (const term of terms) {
177
+ expanded.set(term, 1);
178
+ const group = [term];
179
+ groups.push(group);
180
+ if (term.length < prefixLength) continue;
181
+ let low = 0;
182
+ let high = vocabulary.length;
183
+ while (low < high) {
184
+ const middle = low + high >> 1;
185
+ if (vocabulary[middle] < term) low = middle + 1;
186
+ else high = middle;
187
+ }
188
+ for (let position = low; position < vocabulary.length && vocabulary[position].startsWith(term); position++) {
189
+ const candidate = vocabulary[position];
190
+ if (candidate !== term) {
191
+ expanded.set(candidate, Math.max(expanded.get(candidate) ?? 0, prefixWeight));
192
+ group.push(candidate);
193
+ }
194
+ }
195
+ }
196
+ const scores = /* @__PURE__ */ new Map();
197
+ for (const [groupIndex, group] of groups.entries()) {
198
+ const best = groupIndex === 0 ? scores : /* @__PURE__ */ new Map();
199
+ for (const term of group) {
200
+ const positions = postings.get(term);
201
+ if (!positions) continue;
202
+ const df = frequency.get(term);
203
+ const weight = expanded.get(term) * Math.log(1 + (count - df + .5) / (df + .5));
204
+ for (const position of positions) {
205
+ const entry = index.entries[position];
206
+ const tf = entry.terms[term];
207
+ const score = weight * (tf * 2.2) / (tf + 1.2 * (.25 + .75 * entry.length / average));
208
+ best.set(position, Math.max(best.get(position) ?? 0, score));
209
+ }
210
+ }
211
+ if (best !== scores) for (const [position, score] of best) scores.set(position, (scores.get(position) ?? 0) + score);
212
+ }
213
+ const scored = [];
214
+ for (const position of [...scores.keys()].sort((left, right) => left - right)) {
215
+ const entry = index.entries[position];
216
+ if (!acceptsSearchEntry(entry, options)) continue;
217
+ const score = scores.get(position);
218
+ if (score > 0) scored.push({
219
+ entry,
220
+ score: Number(score.toFixed(4))
221
+ });
222
+ }
223
+ scored.sort((left, right) => right.score - left.score || (left.entry.section < right.entry.section ? -1 : 1));
224
+ const offset = options.offset ?? 0;
225
+ return {
226
+ query: text,
227
+ terms,
228
+ results: scored.slice(offset, offset + (options.limit ?? 5)).map(({ entry, score }) => searchEntryResult(entry, score, closest(entry.subheadings, expanded, entry.context[localeKey])))
229
+ };
230
+ } };
231
+ }
232
+
233
+ export { closestSubheading, createSearch, matchedRanges, queryTerms, segmentSearchText, splitSearchIndex, tokenize };
234
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.js","names":[],"sources":["../src/search.ts"],"sourcesContent":["import { acceptsSearchEntry, searchEntryResult } from \"./search-view.js\"\nimport type { Context } from \"./semantic.js\"\n\n/** One section edition in the search index. Terms are weighted counts; headings and titles count more than body text. */\nexport interface SearchEntry {\n section: string\n document: string\n route: string\n title: string\n heading?: string\n /** Headings inside the section, so a result can point at the one the query names. */\n subheadings?: { anchor: string; text: string }[]\n context: Context\n /** Preference constraints for this projected result, independent of the document edition. */\n projection?: Context\n /** Sources of the section's content, for citation checks. */\n sources: string[]\n /** Limited observations from published static Web markup. */\n origin?: \"native-ssr-headings\"\n length: number\n terms: Record<string, number>\n snippet: string\n}\nexport interface SearchIndex {\n schemaVersion: 1\n entries: SearchEntry[]\n localeDimension?: string\n /**\n * Statistics of the collection the entries were taken from, when they are a subset of it: BM25 scores depend on how\n * many entries hold each word and on the average entry length, so a subset scores exactly like the whole only with\n * the whole's statistics. Absent for a complete index.\n */\n collection?: { entries: number; averageLength: number; frequency: Record<string, number> }\n}\nexport interface SearchResult extends Omit<SearchEntry, \"terms\" | \"length\" | \"subheadings\"> {\n score: number\n /** The heading inside the section that shares the most words with the query, when one does; `route` then targets it. */\n subheading?: string\n}\n\nconst cjk = /[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}]/u\nconst segmenters = new Map<string, Intl.Segmenter>()\n\nfunction segmenterFor(text: string, locale?: string) {\n const language = locale?.toLowerCase().split(/[-_]/)[0]\n const selected =\n language === \"ja\" || language === \"ko\" || language === \"zh\"\n ? language\n : /[\\p{Script=Hiragana}\\p{Script=Katakana}]/u.test(text)\n ? \"ja\"\n : /\\p{Script=Hangul}/u.test(text)\n ? \"ko\"\n : \"zh\"\n let segmenter = segmenters.get(selected)\n if (!segmenter)\n segmenters.set(selected, (segmenter = new Intl.Segmenter(selected, { granularity: \"word\" })))\n return segmenter\n}\n\n/** Insert word boundaries for CJK prose before either search engine builds or queries its index. */\nexport function segmentSearchText(text: string, locale?: string) {\n if (!cjk.test(text)) return text\n return [...segmenterFor(text, locale).segment(text)]\n .filter((part) => part.isWordLike)\n .map((part) => part.segment)\n .join(\" \")\n}\n\n/**\n * Lowercase words of letters and digits in any script. camelCase identifiers also yield their parts, so\n * `defaultOpen` matches both \"defaultopen\" and \"open\". Single CJK characters remain searchable.\n */\nexport function tokenize(text: string, locale?: string): string[] {\n const tokens: string[] = []\n for (const [word] of segmentSearchText(text, locale).matchAll(/[\\p{L}\\p{N}]+/gu)) {\n const parts = word.split(/(?<=[\\p{Ll}\\p{N}])(?=\\p{Lu})/u)\n for (const token of parts.length > 1 ? [word, ...parts] : [word]) {\n const lower = token.toLowerCase()\n if (lower.length > 1 || cjk.test(lower)) tokens.push(lower)\n }\n }\n return tokens\n}\n\n/**\n * Function words per built-in language: articles, pronouns, prepositions, conjunctions, auxiliaries and question\n * words. They say how a question is asked, not what it is about, so a query leaves them out. Negations stay, since\n * they change the meaning, and so does \"have\", which often means possession (\"no component has this ID\"). Single letters are never indexed, so they are not listed.\n */\nconst functionWords: Record<string, ReadonlySet<string>> = {\n en: new Set(\n (\n \"about am an and are as at be been being but by can could did do does doing done for from he her here hers him his how if in into is it its me my of on or our ours she should so than that the their \" +\n \"theirs them then there these they this those to us was we were what when where which while who whom whose why \" +\n \"will with would you your yours\"\n ).split(\" \"),\n ),\n fr: new Set(\n (\n \"au aux avec ce ces cet cette comment dans de des du elle elles en est et être il ils je la le les leur \" +\n \"leurs lui ma mais me mes mon nous on ont ou où par pour qu quand que quel quelle quelles quels qui quoi sa se ses \" +\n \"son sont sur ta te tes ton tu un une vos votre vous\"\n ).split(\" \"),\n ),\n}\n\n/**\n * The words of a query that carry its meaning: its tokens without the function words of its language. The language\n * is the locale's (`fr-CA` uses `fr`); without a locale it is English, the interface's default, and a language\n * without a built-in list keeps every word. A query of only function words keeps them all, so it still finds something.\n */\nexport function queryTerms(text: string, locale?: string): string[] {\n const terms = [...new Set(tokenize(text, locale))]\n const words = functionWords[(locale ?? \"en\").toLowerCase().split(/[-_]/)[0]!]\n if (!words) return terms\n const meaningful = terms.filter((term) => !words.has(term))\n return meaningful.length ? meaningful : terms\n}\n\n/**\n * The subheading of a result that shares the most words with a query, as search results point at it: whole words\n * count fully, and indexed words starting with a query word of four or more letters count half. None if nothing is shared.\n */\nexport function closestSubheading(\n subheadings: SearchEntry[\"subheadings\"],\n query: string,\n locale?: string,\n) {\n const words = queryTerms(query, locale)\n const expanded = new Map<string, number>()\n for (const subheading of subheadings ?? [])\n for (const token of tokenize(subheading.text, locale))\n for (const word of words)\n if (token === word) expanded.set(token, 1)\n else if (word.length >= prefixLength && token.startsWith(word) && !expanded.has(token))\n expanded.set(token, prefixWeight)\n return closest(subheadings, expanded, locale)\n}\n\n/**\n * Where a query's words appear in a displayed text, as sorted, non-overlapping `[start, end)` offsets, for highlighting\n * a result. Words match as ranking matches them: function words do not count, camelCase parts match on their own, and\n * a query word of four or more letters marks the start of a longer word it prefixes (\"valid\" in \"validation\").\n */\nexport function matchedRanges(text: string, query: string, locale?: string): [number, number][] {\n const terms = queryTerms(query, locale)\n const ranges: [number, number][] = []\n if (!terms.length) return ranges\n const mark = (token: string, start: number) => {\n const lower = token.toLowerCase()\n if (lower.length < 2 && !cjk.test(lower)) return\n if (terms.includes(lower)) return void ranges.push([start, start + token.length])\n const prefix = terms.find((term) => term.length >= prefixLength && lower.startsWith(term))\n // Lowercasing can change a word's length; then the whole word is marked.\n if (prefix)\n ranges.push([start, start + (lower.length === token.length ? prefix.length : token.length)])\n }\n for (const run of text.matchAll(/[\\p{L}\\p{N}]+/gu)) {\n const words = cjk.test(run[0])\n ? [...segmenterFor(run[0], locale).segment(run[0])]\n .filter((part) => part.isWordLike)\n .map((part) => [part.segment, part.index] as const)\n : [[run[0], 0] as const]\n for (const [word, offset] of words) {\n const start = run.index + offset\n mark(word, start)\n let position = start\n const parts = word.split(/(?<=[\\p{Ll}\\p{N}])(?=\\p{Lu})/u)\n if (parts.length > 1)\n for (const part of parts) {\n mark(part, position)\n position += part.length\n }\n }\n }\n ranges.sort((left, right) => left[0] - right[0] || right[1] - left[1])\n const merged: [number, number][] = []\n for (const range of ranges) {\n const last = merged.at(-1)\n if (last && range[0] <= last[1]) last[1] = Math.max(last[1], range[1])\n else merged.push([...range])\n }\n return merged\n}\n\n/**\n * One index per locale for sites with two or more: a locale's index keeps its own entries and those without a locale,\n * which are exactly the entries a search in that locale can return. Empty for sites with fewer locales.\n */\nexport function splitSearchIndex(index: SearchIndex): Map<string, SearchIndex> {\n const localeKey = index.localeDimension ?? \"locale\"\n const locales = [\n ...new Set(\n index.entries.flatMap((entry) =>\n entry.context[localeKey] ? [entry.context[localeKey]] : [],\n ),\n ),\n ].sort()\n if (locales.length < 2) return new Map()\n const { frequency, count, average } = statistics(index)\n return new Map(\n locales.map((locale) => {\n const entries = index.entries.filter(\n (entry) => entry.context[localeKey] === undefined || entry.context[localeKey] === locale,\n )\n const terms = new Set(entries.flatMap((entry) => Object.keys(entry.terms)))\n return [\n locale,\n {\n schemaVersion: 1,\n entries,\n ...(index.localeDimension && { localeDimension: index.localeDimension }),\n collection: {\n entries: count,\n averageLength: average,\n frequency: Object.fromEntries(\n [...terms].sort().map((term) => [term, frequency.get(term)!]),\n ),\n },\n },\n ]\n }),\n )\n}\n\nfunction statistics(index: SearchIndex) {\n if (index.collection)\n return {\n frequency: new Map(Object.entries(index.collection.frequency)),\n count: index.collection.entries,\n average: index.collection.averageLength,\n }\n const frequency = new Map<string, number>()\n for (const entry of index.entries)\n for (const term of Object.keys(entry.terms)) frequency.set(term, (frequency.get(term) ?? 0) + 1)\n return {\n frequency,\n count: index.entries.length,\n average:\n index.entries.reduce((total, entry) => total + entry.length, 0) /\n Math.max(1, index.entries.length),\n }\n}\n\nexport interface SearchQueryOptions {\n context?: Context\n locale?: string\n limit?: number\n offset?: number\n acceptDocument?: (variant: string) => boolean\n}\n\n/** Words this long also match indexed words that start with them (\"install\" finds \"installation\"), at reduced weight. */\nconst prefixLength = 4\nconst prefixWeight = 0.5\n\n/** The subheading sharing the most weight with the expanded query terms; the first wins ties, and none if nothing is shared. */\nfunction closest(\n subheadings: SearchEntry[\"subheadings\"],\n expanded: Map<string, number>,\n locale?: string,\n) {\n let best: { anchor: string; text: string } | undefined\n let bestScore = 0\n for (const subheading of subheadings ?? []) {\n const score = [...new Set(tokenize(subheading.text, locale))].reduce(\n (total, token) => total + (expanded.get(token) ?? 0),\n 0,\n )\n if (score > bestScore) [best, bestScore] = [subheading, score]\n }\n return best\n}\n\n/**\n * BM25 ranking over section editions (k1 1.2, b 0.75), filtered to editions compatible with the context. A query\n * ranks with its `queryTerms`, so function words of its locale's language do not count. Prefix matches stand in for\n * stemming. Ties break by section ID so results are stable.\n */\nexport function createSearch(index: SearchIndex) {\n const localeKey = index.localeDimension ?? \"locale\"\n const { frequency, count, average } = statistics(index)\n // Postings: the entries each word appears in, so a query scores only entries that share a word with it.\n const postings = new Map<string, number[]>()\n for (const [position, entry] of index.entries.entries())\n for (const term of Object.keys(entry.terms)) {\n const list = postings.get(term)\n if (list) list.push(position)\n else postings.set(term, [position])\n }\n // Sorted vocabulary: the words a prefix expands to are one contiguous run, found by binary search.\n const vocabulary = [...frequency.keys()].sort()\n return {\n query(text: string, options: SearchQueryOptions = {}) {\n const terms = queryTerms(text, options.locale ?? options.context?.[localeKey])\n // Earlier v1 indexes stored uninterrupted CJK runs as whole terms.\n if (cjk.test(text))\n for (const [raw] of text.toLowerCase().matchAll(/[\\p{L}\\p{N}]+/gu)) {\n if (cjk.test(raw) && postings.has(raw) && !terms.includes(raw)) terms.push(raw)\n }\n // Each query word expands to itself (weight 1) and longer indexed words it prefixes (prefixWeight), keeping the best.\n // A word counts once per entry, at its best match: a page with \"read\", \"reads\" and \"reader\" does not score\n // \"read\" three times.\n const expanded = new Map<string, number>()\n const groups: string[][] = []\n for (const term of terms) {\n expanded.set(term, 1)\n const group = [term]\n groups.push(group)\n if (term.length < prefixLength) continue\n let low = 0\n let high = vocabulary.length\n while (low < high) {\n const middle = (low + high) >> 1\n if (vocabulary[middle]! < term) low = middle + 1\n else high = middle\n }\n for (\n let position = low;\n position < vocabulary.length && vocabulary[position]!.startsWith(term);\n position++\n ) {\n const candidate = vocabulary[position]!\n if (candidate !== term) {\n expanded.set(candidate, Math.max(expanded.get(candidate) ?? 0, prefixWeight))\n group.push(candidate)\n }\n }\n }\n const scores = new Map<number, number>()\n // Visit only postings that contain each expanded term. Within a query word only its best match counts.\n for (const [groupIndex, group] of groups.entries()) {\n const best = groupIndex === 0 ? scores : new Map<number, number>()\n for (const term of group) {\n const positions = postings.get(term)\n if (!positions) continue\n const df = frequency.get(term)!\n const weight = expanded.get(term)! * Math.log(1 + (count - df + 0.5) / (df + 0.5))\n for (const position of positions) {\n const entry = index.entries[position]!\n const tf = entry.terms[term]!\n const score =\n (weight * (tf * 2.2)) / (tf + 1.2 * (0.25 + (0.75 * entry.length) / average))\n best.set(position, Math.max(best.get(position) ?? 0, score))\n }\n }\n if (best !== scores)\n for (const [position, score] of best)\n scores.set(position, (scores.get(position) ?? 0) + score)\n }\n const scored: { entry: SearchEntry; score: number }[] = []\n for (const position of [...scores.keys()].sort((left, right) => left - right)) {\n const entry = index.entries[position]!\n if (!acceptsSearchEntry(entry, options)) continue\n const score = scores.get(position)!\n if (score > 0) scored.push({ entry, score: Number(score.toFixed(4)) })\n }\n scored.sort(\n (left, right) =>\n right.score - left.score || (left.entry.section < right.entry.section ? -1 : 1),\n )\n // Only the returned results need their subheading chosen and their fields copied.\n const offset = options.offset ?? 0\n const results: SearchResult[] = scored\n .slice(offset, offset + (options.limit ?? 5))\n .map(({ entry, score }) =>\n searchEntryResult(\n entry,\n score,\n closest(entry.subheadings, expanded, entry.context[localeKey]),\n ),\n )\n return { query: text, terms, results }\n },\n }\n}\n"],"mappings":";;;AAwCA,MAAM,MAAM;AACZ,MAAM,6BAAa,IAAI,IAA4B;AAEnD,SAAS,aAAa,MAAc,QAAiB;CACnD,MAAM,WAAW,QAAQ,YAAY,CAAC,CAAC,MAAM,MAAM,CAAC,CAAC;CACrD,MAAM,WACJ,aAAa,QAAQ,aAAa,QAAQ,aAAa,OACnD,WACA,4CAA4C,KAAK,IAAI,IACnD,OACA,qBAAqB,KAAK,IAAI,IAC5B,OACA;CACV,IAAI,YAAY,WAAW,IAAI,QAAQ;CACvC,IAAI,CAAC,WACH,WAAW,IAAI,UAAW,YAAY,IAAI,KAAK,UAAU,UAAU,EAAE,aAAa,OAAO,CAAC,CAAE;CAC9F,OAAO;AACT;;AAGA,SAAgB,kBAAkB,MAAc,QAAiB;CAC/D,IAAI,CAAC,IAAI,KAAK,IAAI,GAAG,OAAO;CAC5B,OAAO,CAAC,GAAG,aAAa,MAAM,MAAM,CAAC,CAAC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,MAAM,QAAQ,UAAU,CAC/D,CAE+B;EAAE;CACvC,EACF;AACF"}
@@ -0,0 +1,177 @@
1
+ import type { Provenance } from "./model.js";
2
+ /** Entity types with first-party meaning. Providers may contribute other lowercase types. */
3
+ export type EntityType = "document" | "section" | "component" | "prop" | "api" | "example" | "symbol" | (string & {});
4
+ export declare const relationTypes: readonly ["contains", "references", "implements", "demonstrates", "requires", "supersedes", "derivedFrom", "derivesFrom", "variantOf"];
5
+ export type RelationType = (typeof relationTypes)[number] | `${string}/${string}`;
6
+ export type Context = Record<string, string>;
7
+ /** A reference to one independently verified publication, with an explicit target edition request. */
8
+ export interface ExternalReference {
9
+ project: string;
10
+ inventoryRevision: string;
11
+ entity: string;
12
+ context?: Context;
13
+ }
14
+ export type Evidence = "declared" | "extracted" | "inferred";
15
+ export interface RelationInput {
16
+ type: RelationType;
17
+ target: string;
18
+ evidence?: Evidence;
19
+ /** Limits the relation to a context. Omit when it holds wherever the source variant holds. */
20
+ context?: Context;
21
+ /** Exact target variant for an edition relation. */
22
+ targetContext?: Context;
23
+ /** Position among the source's relations of the same type, when order is meaningful (sections, props). */
24
+ order?: number;
25
+ }
26
+ /** A source-owned edge contributed separately from either endpoint. The source edition is exact. */
27
+ export interface RelationContribution extends RelationInput {
28
+ source: string;
29
+ sourceContext?: Context;
30
+ provenance: readonly Provenance[];
31
+ }
32
+ /** An entity variant contributed by a provider or preset. Identical contributions merge; differing data conflicts. */
33
+ export interface EntityInput<Data = unknown> {
34
+ priority?: number;
35
+ schemaVersion?: number;
36
+ id: string;
37
+ type: EntityType;
38
+ context?: Context;
39
+ data: Data;
40
+ provenance: readonly Provenance[];
41
+ externalReferences?: readonly ExternalReference[];
42
+ relations?: readonly RelationInput[];
43
+ }
44
+ export interface EntityVariant<Data = unknown> {
45
+ priority?: number;
46
+ schemaVersion?: number;
47
+ variantId: string;
48
+ externalReferences?: ExternalReference[];
49
+ context: Context;
50
+ revision: string;
51
+ /** Available on indexes compiled with the content foundation. */
52
+ factRevision?: string;
53
+ provenanceRevision?: string;
54
+ data: Data;
55
+ provenance: Provenance[];
56
+ }
57
+ export interface SemanticEntity<Data = unknown> {
58
+ id: string;
59
+ type: EntityType;
60
+ variants: EntityVariant<Data>[];
61
+ }
62
+ export interface Relation {
63
+ propagatesImpact?: true;
64
+ factRevision?: string;
65
+ provenanceRevision?: string;
66
+ id: string;
67
+ type: RelationType;
68
+ source: string;
69
+ target: string;
70
+ evidence: Evidence;
71
+ context?: Context;
72
+ targetContext?: Context;
73
+ order?: number;
74
+ provenance: Provenance[];
75
+ }
76
+ export interface SemanticIndex {
77
+ schemaVersion: 1;
78
+ entities: SemanticEntity[];
79
+ relations: Relation[];
80
+ }
81
+ /** Manifest pointer to a sharded semantic index. Shards are keyed by subject; see `shardKey`. */
82
+ export interface SemanticPointer {
83
+ schemaVersion: 2;
84
+ revision: string;
85
+ entities: number;
86
+ relations: number;
87
+ shards: Record<string, {
88
+ path: string;
89
+ revision: string;
90
+ }>;
91
+ }
92
+ /**
93
+ * One subject's entities and every relation that starts or ends at them. Provenance records are stored once per shard
94
+ * and referenced by position; variant and relation IDs are derived on load.
95
+ */
96
+ export interface SemanticShard {
97
+ schemaVersion: 1;
98
+ subject: string;
99
+ sources: Provenance[];
100
+ entities: {
101
+ id: string;
102
+ type: EntityType;
103
+ variants: {
104
+ context: Context;
105
+ priority?: number;
106
+ schemaVersion?: number;
107
+ externalReferences?: ExternalReference[];
108
+ revision: string;
109
+ factRevision?: string;
110
+ provenanceRevision?: string;
111
+ data: unknown;
112
+ provenance: number[];
113
+ }[];
114
+ }[];
115
+ relations: {
116
+ propagatesImpact?: true;
117
+ factRevision?: string;
118
+ provenanceRevision?: string;
119
+ type: RelationType;
120
+ source: string;
121
+ target: string;
122
+ evidence: Evidence;
123
+ context?: Context;
124
+ targetContext?: Context;
125
+ order?: number;
126
+ provenance: number[];
127
+ }[];
128
+ }
129
+ export interface SemanticDiagnostic {
130
+ code: "DOCS_ENTITY_SCHEMA" | "DOCS_ENTITY_INVALID_ID" | "DOCS_ENTITY_CONFLICT" | "DOCS_RELATION_CONFLICT" | "DOCS_RELATION_CONTEXT" | "DOCS_RELATION_UNKNOWN" | "DOCS_DERIVATION_CONFLICT" | "DOCS_DERIVATION_SOURCE_MISSING" | "DOCS_DERIVATION_AMBIGUOUS" | "DOCS_DERIVATION_CYCLE";
131
+ severity: "error" | "warning";
132
+ message: string;
133
+ entity?: string;
134
+ relation?: string;
135
+ source?: string;
136
+ }
137
+ export declare function contextKey(context: Context | undefined): string;
138
+ /**
139
+ * Exact means every dimension the variant declares equals the request. Extra requested dimensions are ignored, so a
140
+ * locale-independent entity resolves under any locale. No partial match is ever returned as a fallback.
141
+ */
142
+ export type Resolution<Value> = {
143
+ status: "exact";
144
+ value: Value;
145
+ } | {
146
+ status: "not-found";
147
+ } | {
148
+ status: "unsupported-context";
149
+ available: Context[];
150
+ } | {
151
+ status: "ambiguous";
152
+ candidates: Context[];
153
+ };
154
+ export declare function resolveContext<Value extends {
155
+ context: Context;
156
+ priority?: number;
157
+ }>(variants: readonly Value[], request: Context): Resolution<Value>;
158
+ export declare const variantId: (entity: string, context?: Context) => string;
159
+ export declare function isExactVariantId(value: string): boolean;
160
+ /** Escape delimiters within endpoint IDs while retaining the common human-readable form. */
161
+ export declare function relationId(type: RelationType, source: string, target: string, context?: Context, targetContext?: Context): string;
162
+ export declare const isEntityId: (id: string) => boolean;
163
+ /**
164
+ * The subject an entity belongs to: its ID without the type prefix and `#` fragment. A document, its sections, a
165
+ * component and its props share a subject, so one shard answers most questions about one page or component.
166
+ */
167
+ export declare function shardKey(id: string): string;
168
+ /** Stable, ordering-independent JSON used for revisions. */
169
+ export declare function canonicalJson(value: unknown): string;
170
+ export declare const documentEntityId: (identity: {
171
+ scope: string;
172
+ id: string;
173
+ }) => string;
174
+ export declare const sectionEntityId: (identity: {
175
+ scope: string;
176
+ id: string;
177
+ }, section: string) => string;
@@ -0,0 +1,104 @@
1
+ import { matchesCondition } from "./condition.js";
2
+
3
+ // src/semantic.ts
4
+ const relationTypes = [
5
+ "contains",
6
+ "references",
7
+ "implements",
8
+ "demonstrates",
9
+ "requires",
10
+ "supersedes",
11
+ "derivedFrom",
12
+ "derivesFrom",
13
+ "variantOf"
14
+ ];
15
+ const entityPattern = /^[a-z][a-z0-9-]*:[^\s@]+$/;
16
+ const sort = (left, right) => left < right ? -1 : left > right ? 1 : 0;
17
+ const escapeDimension = (value) => value.replace(/[%=,]/g, (char) => "%" + char.charCodeAt(0).toString(16));
18
+ function contextKey(context) {
19
+ return Object.entries(context ?? {}).sort(([left], [right]) => sort(left, right)).map(([key, value]) => `${escapeDimension(key)}=${escapeDimension(value)}`).join(",");
20
+ }
21
+ function resolveContext(variants, request) {
22
+ if (!variants.length) return { status: "not-found" };
23
+ const groups = /* @__PURE__ */ new Map();
24
+ for (const value of variants) {
25
+ const keys = Object.keys(value.context).sort();
26
+ if (!matchesCondition(value.context, request)) continue;
27
+ const shape = JSON.stringify(keys);
28
+ const group = groups.get(shape);
29
+ if (group) group.values.push(value);
30
+ else groups.set(shape, {
31
+ keys,
32
+ values: [value]
33
+ });
34
+ }
35
+ const maximal = [];
36
+ const selectors = [];
37
+ for (const group of [...groups.values()].sort((a, b) => b.keys.length - a.keys.length)) {
38
+ if (selectors.some((other) => group.keys.every((key) => Object.hasOwn(other, key)))) continue;
39
+ selectors.push(group.values[0].context);
40
+ for (const value of group.values) maximal.push(value);
41
+ }
42
+ let priority = -1e400;
43
+ for (const candidate of maximal) priority = Math.max(priority, candidate.priority ?? 0);
44
+ const preferred = maximal.filter((candidate) => (candidate.priority ?? 0) === priority);
45
+ if (preferred.length === 1) return {
46
+ status: "exact",
47
+ value: preferred[0]
48
+ };
49
+ if (preferred.length) return {
50
+ status: "ambiguous",
51
+ candidates: preferred.map((value) => value.context).sort((a, b) => sort(contextKey(a), contextKey(b)))
52
+ };
53
+ return {
54
+ status: "unsupported-context",
55
+ available: variants.map((variant) => variant.context)
56
+ };
57
+ }
58
+ const variantId = (entity, context) => {
59
+ const key = contextKey(context);
60
+ return key ? `${entity}@${key}` : entity;
61
+ };
62
+ function isExactVariantId(value) {
63
+ const boundary = value.indexOf("@");
64
+ if (boundary < 0) return isEntityId(value);
65
+ const entity = value.slice(0, boundary);
66
+ if (!isEntityId(entity)) return false;
67
+ const decode = (part) => part.replace(/%(25|3d|2c)/g, (_, code) => String.fromCharCode(Number.parseInt(code, 16)));
68
+ const context = Object.create(null);
69
+ for (const part of value.slice(boundary + 1).split(",")) {
70
+ const fields = part.split("=");
71
+ if (fields.length !== 2 || !fields[0] || !fields[1]) return false;
72
+ const key = decode(fields[0]);
73
+ if (Object.hasOwn(context, key)) return false;
74
+ context[key] = decode(fields[1]);
75
+ }
76
+ return variantId(entity, context) === value;
77
+ }
78
+ /** Escape delimiters within endpoint IDs while retaining the common human-readable form. */
79
+ function relationId(type, source, target, context, targetContext) {
80
+ const escape = (id) => id.replaceAll("%", "%25").replaceAll("->", "%2D%3E");
81
+ const id = variantId(`${type}:${escape(source)}->${escape(target)}`, context);
82
+ return targetContext === void 0 ? id : `edition:${canonicalJson([id, targetContext])}`;
83
+ }
84
+ const isEntityId = (id) => entityPattern.test(id);
85
+ /**
86
+ * The subject an entity belongs to: its ID without the type prefix and `#` fragment. A document, its sections, a
87
+ * component and its props share a subject, so one shard answers most questions about one page or component.
88
+ */
89
+ function shardKey(id) {
90
+ const path = id.slice(id.indexOf(":") + 1);
91
+ const hash = path.indexOf("#");
92
+ return hash === -1 ? path : path.slice(0, hash);
93
+ }
94
+ /** Stable, ordering-independent JSON used for revisions. */
95
+ function canonicalJson(value) {
96
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
97
+ if (value && typeof value === "object") return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => sort(left, right)).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
98
+ return JSON.stringify(value) ?? "null";
99
+ }
100
+ const documentEntityId = (identity) => `document:${identity.scope}/${identity.id}`;
101
+ const sectionEntityId = (identity, section) => `section:${identity.scope}/${identity.id}#${section}`;
102
+
103
+ export { canonicalJson, contextKey, documentEntityId, isEntityId, isExactVariantId, relationId, relationTypes, resolveContext, sectionEntityId, shardKey, variantId };
104
+ //# sourceMappingURL=semantic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semantic.js","names":[],"sources":["../src/semantic.ts"],"sourcesContent":["import { matchesCondition } from \"./condition.js\"\nimport type { Provenance } from \"./model.js\"\n\n/** Entity types with first-party meaning. Providers may contribute other lowercase types. */\nexport type EntityType =\n \"document\" | \"section\" | \"component\" | \"prop\" | \"api\" | \"example\" | \"symbol\" | (string & {})\nexport const relationTypes = [\n \"contains\",\n \"references\",\n \"implements\",\n \"demonstrates\",\n \"requires\",\n \"supersedes\",\n \"derivedFrom\",\n \"derivesFrom\",\n \"variantOf\",\n] as const\nexport type RelationType = (typeof relationTypes)[number] | `${string}/${string}`\nexport type Context = Record<string, string>\n/** A reference to one independently verified publication, with an explicit target edition request. */\nexport interface ExternalReference {\n project: string\n inventoryRevision: string\n entity: string\n context?: Context\n}\nexport type Evidence = \"declared\" | \"extracted\" | \"inferred\"\n\nexport interface RelationInput {\n type: RelationType\n target: string\n evidence?: Evidence\n /** Limits the relation to a context. Omit when it holds wherever the source variant holds. */\n context?: Context\n /** Exact target variant for an edition relation. */\n targetContext?: Context\n /** Position among the source's relations of the same type, when order is meaningful (sections, props). */\n order?: number\n}\n\n/** A source-owned edge contributed separately from either endpoint. The source edition is exact. */\nexport interface RelationContribution extends RelationInput {\n source: string\n sourceContext?: Context\n provenance: readonly Provenance[]\n}\n\n/** An entity variant contributed by a provider or preset. Identical contributions merge; differing data conflicts. */\nexport interface EntityInput<Data = unknown> {\n priority?: number\n schemaVersion?: number\n id: string\n type: EntityType\n context?: Context\n data: Data\n provenance: readonly Provenance[]\n externalReferences?: readonly ExternalReference[]\n relations?: readonly RelationInput[]\n}\n\nexport interface EntityVariant<Data = unknown> {\n priority?: number\n schemaVersion?: number\n variantId: string\n externalReferences?: ExternalReference[]\n context: Context\n revision: string\n /** Available on indexes compiled with the content foundation. */\n factRevision?: string\n provenanceRevision?: string\n data: Data\n provenance: Provenance[]\n}\n\nexport interface SemanticEntity<Data = unknown> {\n id: string\n type: EntityType\n variants: EntityVariant<Data>[]\n}\n\nexport interface Relation {\n propagatesImpact?: true\n factRevision?: string\n provenanceRevision?: string\n id: string\n type: RelationType\n source: string\n target: string\n evidence: Evidence\n context?: Context\n targetContext?: Context\n order?: number\n provenance: Provenance[]\n}\n\nexport interface SemanticIndex {\n schemaVersion: 1\n entities: SemanticEntity[]\n relations: Relation[]\n}\n\n/** Manifest pointer to a sharded semantic index. Shards are keyed by subject; see `shardKey`. */\nexport interface SemanticPointer {\n schemaVersion: 2\n revision: string\n entities: number\n relations: number\n shards: Record<string, { path: string; revision: string }>\n}\n\n/**\n * One subject's entities and every relation that starts or ends at them. Provenance records are stored once per shard\n * and referenced by position; variant and relation IDs are derived on load.\n */\nexport interface SemanticShard {\n schemaVersion: 1\n subject: string\n sources: Provenance[]\n entities: {\n id: string\n type: EntityType\n variants: {\n context: Context\n priority?: number\n schemaVersion?: number\n externalReferences?: ExternalReference[]\n revision: string\n factRevision?: string\n provenanceRevision?: string\n data: unknown\n provenance: number[]\n }[]\n }[]\n relations: {\n propagatesImpact?: true\n factRevision?: string\n provenanceRevision?: string\n type: RelationType\n source: string\n target: string\n evidence: Evidence\n context?: Context\n targetContext?: Context\n order?: number\n provenance: number[]\n }[]\n}\n\nexport interface SemanticDiagnostic {\n code:\n | \"DOCS_ENTITY_SCHEMA\"\n | \"DOCS_ENTITY_INVALID_ID\"\n | \"DOCS_ENTITY_CONFLICT\"\n | \"DOCS_RELATION_CONFLICT\"\n | \"DOCS_RELATION_CONTEXT\"\n | \"DOCS_RELATION_UNKNOWN\"\n | \"DOCS_DERIVATION_CONFLICT\"\n | \"DOCS_DERIVATION_SOURCE_MISSING\"\n | \"DOCS_DERIVATION_AMBIGUOUS\"\n | \"DOCS_DERIVATION_CYCLE\"\n severity: \"error\" | \"warning\"\n message: string\n entity?: string\n relation?: string\n source?: string\n}\n\nconst entityPattern = /^[a-z][a-z0-9-]*:[^\\s@]+$/\nconst sort = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0)\n\nconst escapeDimension = (value: string) =>\n value.replace(/[%=,]/g, (char) => \"%\" + char.charCodeAt(0).toString(16))\n\nexport function contextKey(context: Context | undefined) {\n return Object.entries(context ?? {})\n .sort(([left], [right]) => sort(left, right))\n .map(([key, value]) => `${escapeDimension(key)}=${escapeDimension(value)}`)\n .join(\",\")\n}\n/**\n * Exact means every dimension the variant declares equals the request. Extra requested dimensions are ignored, so a\n * locale-independent entity resolves under any locale. No partial match is ever returned as a fallback.\n */\nexport type Resolution<Value> =\n | { status: \"exact\"; value: Value }\n | { status: \"not-found\" }\n | { status: \"unsupported-context\"; available: Context[] }\n | { status: \"ambiguous\"; candidates: Context[] }\n\nexport function resolveContext<Value extends { context: Context; priority?: number }>(\n variants: readonly Value[],\n request: Context,\n): Resolution<Value> {\n if (!variants.length) return { status: \"not-found\" }\n const groups = new Map<string, { keys: string[]; values: Value[] }>()\n for (const value of variants) {\n const keys = Object.keys(value.context).sort()\n if (!matchesCondition(value.context, request)) continue\n // Matching selectors with identical axes necessarily agree on every value.\n const shape = JSON.stringify(keys)\n const group = groups.get(shape)\n if (group) group.values.push(value)\n else groups.set(shape, { keys, values: [value] })\n }\n const maximal: Value[] = []\n const selectors: Context[] = []\n for (const group of [...groups.values()].sort((a, b) => b.keys.length - a.keys.length)) {\n if (selectors.some((other) => group.keys.every((key) => Object.hasOwn(other, key)))) continue\n selectors.push(group.values[0]!.context)\n for (const value of group.values) maximal.push(value)\n }\n let priority = -Infinity\n for (const candidate of maximal) priority = Math.max(priority, candidate.priority ?? 0)\n const preferred = maximal.filter((candidate) => (candidate.priority ?? 0) === priority)\n if (preferred.length === 1) return { status: \"exact\", value: preferred[0]! }\n if (preferred.length)\n return {\n status: \"ambiguous\",\n candidates: preferred\n .map((value) => value.context)\n .sort((a, b) => sort(contextKey(a), contextKey(b))),\n }\n return { status: \"unsupported-context\", available: variants.map((variant) => variant.context) }\n}\n\nexport const variantId = (entity: string, context?: Context) => {\n const key = contextKey(context)\n return key ? `${entity}@${key}` : entity\n}\nexport function isExactVariantId(value: string): boolean {\n const boundary = value.indexOf(\"@\")\n if (boundary < 0) return isEntityId(value)\n const entity = value.slice(0, boundary)\n if (!isEntityId(entity)) return false\n const decode = (part: string) =>\n part.replace(/%(25|3d|2c)/g, (_, code: string) =>\n String.fromCharCode(Number.parseInt(code, 16)),\n )\n const context: Context = Object.create(null)\n for (const part of value.slice(boundary + 1).split(\",\")) {\n const fields = part.split(\"=\")\n if (fields.length !== 2 || !fields[0] || !fields[1]) return false\n const key = decode(fields[0])\n if (Object.hasOwn(context, key)) return false\n context[key] = decode(fields[1])\n }\n return variantId(entity, context) === value\n}\n\n/** Escape delimiters within endpoint IDs while retaining the common human-readable form. */\nexport function relationId(\n type: RelationType,\n source: string,\n target: string,\n context?: Context,\n targetContext?: Context,\n) {\n const escape = (id: string) => id.replaceAll(\"%\", \"%25\").replaceAll(\"->\", \"%2D%3E\")\n const id = variantId(`${type}:${escape(source)}->${escape(target)}`, context)\n return targetContext === undefined ? id : `edition:${canonicalJson([id, targetContext])}`\n}\nexport const isEntityId = (id: string) => entityPattern.test(id)\n/**\n * The subject an entity belongs to: its ID without the type prefix and `#` fragment. A document, its sections, a\n * component and its props share a subject, so one shard answers most questions about one page or component.\n */\nexport function shardKey(id: string) {\n const path = id.slice(id.indexOf(\":\") + 1)\n const hash = path.indexOf(\"#\")\n return hash === -1 ? path : path.slice(0, hash)\n}\n\n/** Stable, ordering-independent JSON used for revisions. */\nexport function canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(([left], [right]) => sort(left, right))\n .map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`)\n .join(\",\")}}`\n }\n return JSON.stringify(value) ?? \"null\"\n}\n\nexport const documentEntityId = (identity: { scope: string; id: string }) =>\n `document:${identity.scope}/${identity.id}`\nexport const sectionEntityId = (identity: { scope: string; id: string }, section: string) =>\n `section:${identity.scope}/${identity.id}#${section}`\n"],"mappings":";;;AAMA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAuJA,MAAM,gBAAgB;AACtB,MAAM,QAAQ,MAAc,UAAmB,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAEtF,MAAM,mBAAmB,UACvB,MAAM,QAAQ,WAAW,SAAS,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;AAEzE,SAAgB,WAAW,SAA8B;CACvD,OAAO,OAAO,QAAQ,WAAW,CAAC,CAAC,CAAC,CACjC,MAAM,CAAC,OAAO,CAAC,WAAW,KAAK,MAAM,KAAK,CAAC,CAAC,CAC5C,KAAK,CAAC,KAAK,WAAW,GAAG,gBAAgB,GAAG,EAAE,GAAG,gBAAgB,KAAK,GAAG,CAAC,CAC1E,KAAK,GAAG;AACb;AAWA,SAAgB,eACd,UACA,SACmB;CACnB,IAAI,CAAC,SAAS,QAAQ,OAAO,EAAE,QAAQ,YAAY;CACnD,MAAM,yBAAS,IAAI,IAAiD;CACpE,KAAK,MAAM,SAAS,UAAU;EAC5B,MAAM,OAAO,OAAO,KAAK,MAAM,OAAO,CAAC,CAAC,KAAK;EAC7C,IAAI,CAAC,iBAAiB,MAAM,SAAS,OAAO,GAAG;EAE/C,MAAM,QAAQ,KAAK,UAAU,IAAI;EACjC,MAAM,QAAQ,OAAO,IAAI,KAAK;EAC9B,IAAI,OAAO,MAAM,OAAO,KAAK,KAAK;OAC7B,OAAO,IAAI,OAAO;GAAE;GAAM,QAAQ,CAAC,KAAK;E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,CAAC,OAAO,CAAC,WAAW,KAAK,MAAM,KAAK,CAAC,CAAC,CAC5C,KAAK,CAAC,KAAK,UAAU,GAAG,KAAK,UAAU,GAAG,EAAE,GAAG,cAAc,IAAI,GAAG,CAAC,CACrE,KAAK,GAAG,EAAE;CAEf,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC;AAEA,MAAa,oBAAoB,aAC/B,YAAY,SAAS,MAAM,GAAG,SAAS;AACzC,MAAa,mBAAmB,UAAyC,YACvE,WAAW,SAAS,MAAM,GAAG,SAAS,GAAG,GAAG"}
@@ -0,0 +1,21 @@
1
+ import type { openPinnedReader } from "./document-reader.js";
2
+ type Publication = Awaited<ReturnType<typeof openPinnedReader>>;
3
+ /** Compare two pinned releases with a local installation. The caller owns file access and update decisions. */
4
+ export declare function reviewSkillUpdate(name: string, before: Publication, after: Publication, installed: {
5
+ /** Return undefined for a missing file; propagate other read failures. */
6
+ read(path: string): Promise<Uint8Array | undefined>;
7
+ sha256(bytes: Uint8Array): string | Promise<string>;
8
+ }): Promise<{
9
+ name: string;
10
+ baseline: string;
11
+ candidate: string;
12
+ changes: {
13
+ file: string;
14
+ action: string;
15
+ base: string | undefined;
16
+ local: string | undefined;
17
+ next: string | undefined;
18
+ }[];
19
+ hasLocalChanges: boolean;
20
+ }>;
21
+ export {};