@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.
- package/LICENSE +21 -0
- package/README.md +97 -2
- package/dist/annotation-projection.d.ts +35 -0
- package/dist/annotation-projection.js +78 -0
- package/dist/annotation-projection.js.map +1 -0
- package/dist/artifacts.d.ts +19 -0
- package/dist/artifacts.js +33 -0
- package/dist/artifacts.js.map +1 -0
- package/dist/ask.d.ts +41 -0
- package/dist/ask.js +89 -0
- package/dist/ask.js.map +1 -0
- package/dist/collection-view.d.ts +190 -0
- package/dist/collection-view.js +170 -0
- package/dist/collection-view.js.map +1 -0
- package/dist/composition.d.ts +199 -0
- package/dist/composition.js +473 -0
- package/dist/composition.js.map +1 -0
- package/dist/condition.d.ts +17 -0
- package/dist/condition.js +61 -0
- package/dist/condition.js.map +1 -0
- package/dist/content-schema.d.ts +182 -0
- package/dist/content-schema.js +288 -0
- package/dist/content-schema.js.map +1 -0
- package/dist/context-search.d.ts +168 -0
- package/dist/context-search.js +73 -0
- package/dist/context-search.js.map +1 -0
- package/dist/context-store.d.ts +93 -0
- package/dist/context-store.js +438 -0
- package/dist/context-store.js.map +1 -0
- package/dist/dimension-runtime.d.ts +203 -0
- package/dist/dimension-runtime.js +737 -0
- package/dist/dimension-runtime.js.map +1 -0
- package/dist/dimensions.d.ts +84 -0
- package/dist/dimensions.js +136 -0
- package/dist/dimensions.js.map +1 -0
- package/dist/directory-navigation.d.ts +60 -0
- package/dist/directory-navigation.js +41 -0
- package/dist/directory-navigation.js.map +1 -0
- package/dist/directory-sections.d.ts +9 -0
- package/dist/directory-sections.js +76 -0
- package/dist/directory-sections.js.map +1 -0
- package/dist/document-reader.d.ts +1017 -0
- package/dist/document-reader.js +396 -0
- package/dist/document-reader.js.map +1 -0
- package/dist/document-selection.d.ts +412 -0
- package/dist/document-selection.js +45 -0
- package/dist/document-selection.js.map +1 -0
- package/dist/evidence.d.ts +102 -0
- package/dist/evidence.js +104 -0
- package/dist/evidence.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +23 -0
- package/dist/model.d.ts +89 -0
- package/dist/model.js +31 -0
- package/dist/model.js.map +1 -0
- package/dist/module.d.ts +657 -0
- package/dist/module.js +199 -0
- package/dist/module.js.map +1 -0
- package/dist/navigation-view.d.ts +33 -0
- package/dist/navigation-view.js +68 -0
- package/dist/navigation-view.js.map +1 -0
- package/dist/node.d.ts +2004 -0
- package/dist/node.js +210 -0
- package/dist/node.js.map +1 -0
- package/dist/open-docs.d.ts +1396 -0
- package/dist/open-docs.js +198 -0
- package/dist/open-docs.js.map +1 -0
- package/dist/outline.d.ts +97 -0
- package/dist/outline.js +171 -0
- package/dist/outline.js.map +1 -0
- package/dist/persistence.d.ts +82 -0
- package/dist/persistence.js +377 -0
- package/dist/persistence.js.map +1 -0
- package/dist/projection-catalog.d.ts +23 -0
- package/dist/projection-catalog.js +45 -0
- package/dist/projection-catalog.js.map +1 -0
- package/dist/publication.d.ts +59 -0
- package/dist/publication.js +11 -0
- package/dist/publication.js.map +1 -0
- package/dist/reader.d.ts +236 -0
- package/dist/reader.js +400 -0
- package/dist/reader.js.map +1 -0
- package/dist/references.d.ts +54 -0
- package/dist/references.js +70 -0
- package/dist/references.js.map +1 -0
- package/dist/retrieval.d.ts +82 -0
- package/dist/retrieval.js +135 -0
- package/dist/retrieval.js.map +1 -0
- package/dist/search-view.d.ts +11 -0
- package/dist/search-view.js +30 -0
- package/dist/search-view.js.map +1 -0
- package/dist/search.d.ts +95 -0
- package/dist/search.js +234 -0
- package/dist/search.js.map +1 -0
- package/dist/semantic.d.ts +177 -0
- package/dist/semantic.js +104 -0
- package/dist/semantic.js.map +1 -0
- package/dist/skills.d.ts +21 -0
- package/dist/skills.js +42 -0
- package/dist/skills.js.map +1 -0
- package/docs/index.md +10 -0
- package/docs/sdk/composition.md +72 -0
- package/docs/sdk/reader-storage.md +70 -0
- package/docs/sdk/reader.md +99 -0
- package/docs/zh-CN/sdk/composition.md +72 -0
- package/docs/zh-CN/sdk/reader-storage.md +70 -0
- package/docs/zh-CN/sdk/reader.md +99 -0
- package/package.json +69 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lenso contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,98 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Docs SDK Reader
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Read the [installed guides](docs/index.md) for this release. The package declarations give the exact API signatures.
|
|
4
|
+
|
|
5
|
+
Read immutable documentation publications in Node, browsers or embedded applications. The default entry point has zero install dependencies. The host supplies bytes and SHA-256 and controls which publications are accessible.
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
import { openPinnedReader, createSemanticLoader } from "@docs-sdk-dev/reader"
|
|
9
|
+
|
|
10
|
+
const publication = await openPinnedReader(expectedInventorySha256, host)
|
|
11
|
+
const identity = { scope: "guide", id: "setup", dimensions: { version: "v2" } }
|
|
12
|
+
const section = await publication.reader.read(identity, "body", "install")
|
|
13
|
+
const facts = createSemanticLoader(publication.manifest.semantic, publication.readText)
|
|
14
|
+
const component = await facts.resolve("component:components/button", identity.dimensions)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Document lookup reads the verified manifest. Section reads fetch the selected section. Modern manifests index heading ranges, and short headings in large sections have their own verified file. The Core compatibility entry point supplies the Markdown grammar for heading reads against older manifests. Both readers can read entire documents and sections in historical publications.
|
|
18
|
+
|
|
19
|
+
Import `composeView` from `@docs-sdk-dev/reader/composition` to resolve fragment includes, slots and fact pins against a semantic reader. The returned portable blocks and dependency receipts can be consumed directly by the host.
|
|
20
|
+
|
|
21
|
+
### Apply team knowledge at a slot
|
|
22
|
+
|
|
23
|
+
`composeOverlays` uses the same fragment includes, slots and source policies as `composeView`. A consumer supplies the entity for its example and pins the upstream content it reviewed.
|
|
24
|
+
|
|
25
|
+
```js
|
|
26
|
+
import { composeOverlays } from "@docs-sdk-dev/reader/composition"
|
|
27
|
+
|
|
28
|
+
const result = composeOverlays(
|
|
29
|
+
view,
|
|
30
|
+
[
|
|
31
|
+
{
|
|
32
|
+
owner: "support",
|
|
33
|
+
entity: "fragment:team-install",
|
|
34
|
+
slot: "example",
|
|
35
|
+
priority: 10,
|
|
36
|
+
context: { version: "2" },
|
|
37
|
+
upstreamFactRevision: reviewedUpstreamFact,
|
|
38
|
+
},
|
|
39
|
+
],
|
|
40
|
+
semanticReader,
|
|
41
|
+
)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
A ready result holds the composed blocks, source dependencies and a portable receipt for all candidates, including shadowed owners. The highest priority wins each slot. Equal winning priorities, competing placement overrides, missing targets and changed upstream pins return diagnostics. The host selects eligible overlay providers and grants projection permissions.
|
|
45
|
+
|
|
46
|
+
When upstream content and the team override are separate publications, open each through the host's permitted Reader transport and read its stable export. `composePublishedOverlays` accepts those exact results directly. The upstream export is a semantic content tree with a named slot. Team exports may be plain Markdown. Supply any additional referenced exports as the fourth argument. Conflicting publications claiming the same entity block composition.
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
import { composePublishedOverlays } from "@docs-sdk-dev/reader/composition"
|
|
50
|
+
|
|
51
|
+
const guide = await official.readExport("setup", edition)
|
|
52
|
+
const note = await team.readExport("setup-policy", edition)
|
|
53
|
+
if (guide.status === "exact" && note.status === "exact") {
|
|
54
|
+
const composed = composePublishedOverlays({ id: "help-panel", context: edition }, guide, [
|
|
55
|
+
{
|
|
56
|
+
slot: "example",
|
|
57
|
+
owner: "support",
|
|
58
|
+
priority: 1,
|
|
59
|
+
content: note,
|
|
60
|
+
upstreamFactRevision: reviewedGuideRevision,
|
|
61
|
+
},
|
|
62
|
+
])
|
|
63
|
+
// Save a ready receipt in the optional project documentation lock.
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The receipt identifies the package, version, inventory and public export of each input. A changed team publication is visible during lock verification even when the Markdown bytes match the previous version.
|
|
68
|
+
|
|
69
|
+
### Inspect verification evidence
|
|
70
|
+
|
|
71
|
+
`createEvidenceReader(publication)` from `@docs-sdk-dev/reader/evidence` queries individual facts from an opened publication. For example, `await evidence("example:solid/counter", {}, { contracts: true })` returns per-check Example Runtime outcomes, versioned source provenance and contract findings for that variant. An older publication without a matching verifier receipt returns empty checks. For an installed documentation module, call `module.evidenceFor(publicName, context)` to query its exported fact directly. A Markdown-only module can omit semantic shards. For a page or section in such a module, `evidenceFor` returns `published-content` with the edition, source locations, publication digest and SHA-256 of that Markdown artifact. Verifier checks require separate evidence. A contract finding can be waived and still appears with its reason.
|
|
72
|
+
|
|
73
|
+
`assessFactCheck(receipt, current)` checks the exact entity and revision, installed dependency versions, validator identity and version, and measured environment digest before reusing a result. Compute the environment digest by hashing the UTF-8 bytes of `evidenceEnvironmentPayload(target, toolchain, lockfileSha256)` with SHA-256. A skipped check stays unverified, and a stale result names the fields that changed. The host decides which pinned publication and validator it trusts.
|
|
74
|
+
|
|
75
|
+
### Query a collection
|
|
76
|
+
|
|
77
|
+
`defineView` from `@docs-sdk-dev/reader/collection` filters, sorts and groups records by typed fields. Supply records from your collection or read published facts with `docs.entities(type, project, subjectPrefix)`. The projection receives the provider's data and entity ID. The prefix limits shard reads. Each record retains its edition, revision and provenance.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
const directory = defineView<{ title: string; deprecated: boolean }>({
|
|
81
|
+
id: "deprecated-apis",
|
|
82
|
+
from: "apis",
|
|
83
|
+
where: { deprecated: true },
|
|
84
|
+
sortBy: "title",
|
|
85
|
+
link: (item) => ({ href: apiRoute(item.id), title: item.value.title }),
|
|
86
|
+
})
|
|
87
|
+
const records = await docs.withContext({ version: "v2" }).entities("api", readApiMetadata)
|
|
88
|
+
const result = directory.resolve(new Map([["apis", records]]), {
|
|
89
|
+
context: { version: "v2" },
|
|
90
|
+
limit: 20,
|
|
91
|
+
})
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The result includes stable IDs, navigation and portable content. After a source change, resolve the same view again and pass the two selections to `diffCollectionViews` to find new, removed, moved and revised members.
|
|
95
|
+
|
|
96
|
+
A host can compose local sections with named document exports from other verified publications. Pass the opened modules to `openDocs({ revision, host, packages: [module] })`, then call `docs.compose([doc("guide/start"), packageDoc("controls", "install")])`. Import `doc` and `packageDoc` from `@docs-sdk-dev/reader`. Results retain the requested order and the current reading context. An external result carries its software version, inventory revision, identity, source provenance and projection losses. The host selects one publication per package. An undeclared export reports missing, while an unsupplied package raises `DOCS_REFERENCE_DENIED`.
|
|
97
|
+
|
|
98
|
+
To reuse a named composition, declare `defineView({ id: "integration", content: [include(doc("guide/start")), include(packageDoc("controls", "install"))] })` with the authoring helpers. Pass the resulting view to `docs.compose(view)`. Headless consumers can import `defineView` from `@docs-sdk-dev/reader/collection` and the reference helpers from `@docs-sdk-dev/reader`.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type JsonValue, type InlineAnnotation, type LiteralBlock } from "./content-schema.js";
|
|
2
|
+
import type { AnnotationProjection, BlockOrigin } from "./composition.js";
|
|
3
|
+
import { type ProjectionLoss } from "./model.js";
|
|
4
|
+
/** Build-local render hint. The portable mark still carries its complete semantic fallback. */
|
|
5
|
+
export declare const annotationRenderer: unique symbol;
|
|
6
|
+
export type RenderedMark = {
|
|
7
|
+
[annotationRenderer]?: {
|
|
8
|
+
type: string;
|
|
9
|
+
props: JsonValue;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
export declare function projectAnnotation(node: InlineAnnotation, projection: AnnotationProjection | undefined, source: string, losses: ProjectionLoss[], origin?: BlockOrigin): {
|
|
13
|
+
type: "link";
|
|
14
|
+
url: string;
|
|
15
|
+
title?: string;
|
|
16
|
+
} | {
|
|
17
|
+
type: "strong" | "emphasis" | "strikethrough";
|
|
18
|
+
} | {
|
|
19
|
+
type: "link";
|
|
20
|
+
url: string;
|
|
21
|
+
title?: string;
|
|
22
|
+
[annotationRenderer]: {
|
|
23
|
+
type: string;
|
|
24
|
+
props: JsonValue;
|
|
25
|
+
};
|
|
26
|
+
} | {
|
|
27
|
+
type: "strong" | "emphasis" | "strikethrough";
|
|
28
|
+
[annotationRenderer]: {
|
|
29
|
+
type: string;
|
|
30
|
+
props: JsonValue;
|
|
31
|
+
};
|
|
32
|
+
} | undefined;
|
|
33
|
+
export declare function checkInlineLink(type: string, insideLink: boolean, source: string): void;
|
|
34
|
+
/** Resolve the selected owner's annotations before copying content to a new placement. */
|
|
35
|
+
export declare function materializeAnnotations(block: LiteralBlock, annotations: ReadonlyMap<string, AnnotationProjection>, origin: BlockOrigin): LiteralBlock;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { extensionAttributes } from "./content-schema.js";
|
|
2
|
+
import { DocsError } from "./model.js";
|
|
3
|
+
|
|
4
|
+
// src/annotation-projection.ts
|
|
5
|
+
/** Build-local render hint. The portable mark still carries its complete semantic fallback. */
|
|
6
|
+
const annotationRenderer = Symbol("docs.annotation.renderer");
|
|
7
|
+
function projectAnnotation(node, projection, source, losses, origin) {
|
|
8
|
+
const declined = projection?.allowsSource && (!origin || !projection.allowsSource(origin));
|
|
9
|
+
if (projection && !declined) {
|
|
10
|
+
const props = extensionAttributes(node, projection.schema, source);
|
|
11
|
+
const mark = projection.project(props);
|
|
12
|
+
return projection.renderer ? {
|
|
13
|
+
...mark,
|
|
14
|
+
[annotationRenderer]: {
|
|
15
|
+
type: projection.renderer,
|
|
16
|
+
props
|
|
17
|
+
}
|
|
18
|
+
} : mark;
|
|
19
|
+
}
|
|
20
|
+
const reason = declined ? "Source policy declined" : "No projection for";
|
|
21
|
+
for (const target of ["web", "markdown"]) losses.push({
|
|
22
|
+
target,
|
|
23
|
+
source,
|
|
24
|
+
kind: "custom-mark",
|
|
25
|
+
severity: "warning",
|
|
26
|
+
message: `${reason} annotation ${node.name}. Kept its annotated content.`
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
function checkInlineLink(type, insideLink, source) {
|
|
30
|
+
if (insideLink && type === "link") throw new DocsError("DOCS_CONTENT_MARK", "A projected link cannot contain another link.", { source });
|
|
31
|
+
}
|
|
32
|
+
/** Resolve the selected owner's annotations before copying content to a new placement. */
|
|
33
|
+
function materializeAnnotations(block, annotations, origin) {
|
|
34
|
+
const source = origin.kind === "entity" ? origin.provenance[0]?.source ?? origin.entity : origin.placement;
|
|
35
|
+
const losses = [];
|
|
36
|
+
function inlines(nodes, insideLink = false) {
|
|
37
|
+
return nodes.flatMap((node) => {
|
|
38
|
+
if (!("children" in node)) return [node];
|
|
39
|
+
const wrapper = node.type === "annotation" ? projectAnnotation(node, annotations.get(node.name), source, losses, origin) : node;
|
|
40
|
+
if (!wrapper) return inlines(node.children, insideLink);
|
|
41
|
+
checkInlineLink(wrapper.type, insideLink, source);
|
|
42
|
+
return [{
|
|
43
|
+
...wrapper,
|
|
44
|
+
children: inlines(node.children, insideLink || wrapper.type === "link")
|
|
45
|
+
}];
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function rewrite(value) {
|
|
49
|
+
if (value.type === "heading" || value.type === "paragraph") return {
|
|
50
|
+
...value,
|
|
51
|
+
children: inlines(value.children)
|
|
52
|
+
};
|
|
53
|
+
if (value.type === "blockquote") return {
|
|
54
|
+
...value,
|
|
55
|
+
blocks: value.blocks.map(rewrite)
|
|
56
|
+
};
|
|
57
|
+
if (value.type === "list") return {
|
|
58
|
+
...value,
|
|
59
|
+
items: value.items.map((item) => ({
|
|
60
|
+
...item,
|
|
61
|
+
blocks: item.blocks.map(rewrite)
|
|
62
|
+
}))
|
|
63
|
+
};
|
|
64
|
+
if (value.type === "table") return {
|
|
65
|
+
...value,
|
|
66
|
+
rows: value.rows.map((row) => row.map((cell) => inlines(cell)))
|
|
67
|
+
};
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
const resolved = rewrite(block);
|
|
71
|
+
return losses.length ? {
|
|
72
|
+
...resolved,
|
|
73
|
+
losses: [...resolved.losses ?? [], ...losses]
|
|
74
|
+
} : resolved;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export { annotationRenderer, checkInlineLink, materializeAnnotations, projectAnnotation };
|
|
78
|
+
//# sourceMappingURL=annotation-projection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"annotation-projection.js","names":[],"sources":["../src/annotation-projection.ts"],"sourcesContent":["import {\n extensionAttributes,\n type JsonValue,\n type Inline,\n type InlineAnnotation,\n type LiteralBlock,\n} from \"./content-schema.js\"\nimport type { AnnotationProjection, BlockOrigin } from \"./composition.js\"\nimport { DocsError, type ProjectionLoss } from \"./model.js\"\n\n/** Build-local render hint. The portable mark still carries its complete semantic fallback. */\nexport const annotationRenderer = Symbol(\"docs.annotation.renderer\")\nexport type RenderedMark = { [annotationRenderer]?: { type: string; props: JsonValue } }\n\nexport function projectAnnotation(\n node: InlineAnnotation,\n projection: AnnotationProjection | undefined,\n source: string,\n losses: ProjectionLoss[],\n origin?: BlockOrigin,\n) {\n const declined = projection?.allowsSource && (!origin || !projection.allowsSource(origin))\n if (projection && !declined) {\n const props = extensionAttributes(node, projection.schema, source)\n const mark = projection.project(props)\n return projection.renderer\n ? { ...mark, [annotationRenderer]: { type: projection.renderer, props } }\n : mark\n }\n const reason = declined ? \"Source policy declined\" : \"No projection for\"\n for (const target of [\"web\", \"markdown\"] as const)\n losses.push({\n target,\n source,\n kind: \"custom-mark\",\n severity: \"warning\",\n message: `${reason} annotation ${node.name}. Kept its annotated content.`,\n })\n}\n\nexport function checkInlineLink(type: string, insideLink: boolean, source: string) {\n if (insideLink && type === \"link\")\n throw new DocsError(\"DOCS_CONTENT_MARK\", \"A projected link cannot contain another link.\", {\n source,\n })\n}\n\n/** Resolve the selected owner's annotations before copying content to a new placement. */\nexport function materializeAnnotations(\n block: LiteralBlock,\n annotations: ReadonlyMap<string, AnnotationProjection>,\n origin: BlockOrigin,\n) {\n const source =\n origin.kind === \"entity\" ? (origin.provenance[0]?.source ?? origin.entity) : origin.placement\n const losses: ProjectionLoss[] = []\n function inlines(nodes: readonly Inline[], insideLink = false): Inline[] {\n return nodes.flatMap((node): Inline[] => {\n if (!(\"children\" in node)) return [node]\n const wrapper =\n node.type === \"annotation\"\n ? projectAnnotation(node, annotations.get(node.name), source, losses, origin)\n : node\n if (!wrapper) return inlines(node.children, insideLink)\n checkInlineLink(wrapper.type, insideLink, source)\n return [\n { ...wrapper, children: inlines(node.children, insideLink || wrapper.type === \"link\") },\n ]\n })\n }\n function rewrite<T extends LiteralBlock>(value: T): T {\n if (value.type === \"heading\" || value.type === \"paragraph\")\n return { ...value, children: inlines(value.children) }\n if (value.type === \"blockquote\") return { ...value, blocks: value.blocks.map(rewrite) }\n if (value.type === \"list\")\n return {\n ...value,\n items: value.items.map((item) => ({ ...item, blocks: item.blocks.map(rewrite) })),\n }\n if (value.type === \"table\")\n return { ...value, rows: value.rows.map((row) => row.map((cell) => inlines(cell))) }\n return value\n }\n const resolved = rewrite(block)\n return losses.length ? { ...resolved, losses: [...(resolved.losses ?? []), ...losses] } : resolved\n}\n"],"mappings":";;;;;AAWA,MAAa,qBAAqB,OAAO,0BAA0B;AAGnE,SAAgB,kBACd,MACA,YACA,QACA,QACA,QACA;CACA,MAAM,WAAW,YAAY,iBAAiB,CAAC,UAAU,CAAC,WAAW,aAAa,MAAM;CACxF,IAAI,cAAc,CAAC,UAAU;EAC3B,MAAM,QAAQ,oBAAoB,MAAM,WAAW,QAAQ,MAAM;EACjE,MAAM,OAAO,WAAW,QAAQ,KAAK;EACrC,OAAO,WAAW,WACd;GAAE,GAAG;IAAO,qBAAqB;IAAE,MAAM,WAAW;IAAU;GAAM;EAAE,IACtE;CACN;CACA,MAAM,SAAS,WAAW,2BAA2B;CACrD,KAAK,MAAM,UAAU,CAAC,OAAO,UAAU,GACrC,OAAO,KAAK;EACV;EACA;EACA,MAAM;EACN,UAAU;EACV,SAAS,GAAG,OAAO,cAAc,KAAK,KAAK;CAC7C,CAAC;AACL;AAEA,SAAgB,gBAAgB,MAAc,YAAqB,QAAgB;CACjF,IAAI,cAAc,SAAS,QACzB,MAAM,IAAI,UAAU,qBAAqB,iDAAiD,EACxF,OACF,CAAC;AACL;;AAGA,SAAgB,uBACd,OACA,aACA,QACA;CACA,MAAM,SACJ,OAAO,SAAS,WAAY,OAAO,WAAW,EAAE,EAAE,UAAU,OAAO,SAAU,OAAO;CACtF,MAAM,SAA2B,CAAC;CAClC,SAAS,QAAQ,OAA0B,aAAa,OAAiB;EACvE,OAAO,MAAM,SAAS,SAAmB;GACvC,IAAI,EAAE,cAAc,OAAO,OAAO,CAAC,IAAI;GACvC,MAAM,UACJ,KAAK,SAAS,eACV,kBAAkB,MAAM,YAAY,IAAI,KAAK,IAAI,GAAG,QAAQ,QAAQ,MAAM,IAC1E;GACN,IAAI,CAAC,SAAS,OAAO,QAAQ,KAAK,UAAU,UAAU;GACtD,gBAAgB,QAAQ,MAAM,YAAY,MAAM;GAChD,OAAO,CACL;IAAE,GAAG;IAAS,UAAU,QAAQ,KAAK,UAAU,cAAc,QAAQ,SAAS,MAAM;GAAE,CACxF;EACF,CAAC;CACH;CACA,SAAS,QAAgC,OAAa;EACpD,IAAI,MAAM,SAAS,aAAa,MAAM,SAAS,aAC7C,OAAO;GAAE,GAAG;GAAO,UAAU,QAAQ,MAAM,QAAQ;EAAE;EACvD,IAAI,MAAM,SAAS,cAAc,OAAO;GAAE,GAAG;GAAO,QAAQ,MAAM,OAAO,IAAI,OAAO;EAAE;EACtF,IAAI,MAAM,SAAS,QACjB,OAAO;GACL,GAAG;GACH,OAAO,MAAM,MAAM,KAAK,UAAU;IAAE,GAAG;IAAM,QAAQ,KAAK,OAAO,IAAI,OAAO;GAAE,EAAE;EAClF;EACF,IAAI,MAAM,SAAS,SACjB,OAAO;GAAE,GAAG;GAAO,MAAM,MAAM,KAAK,KAAK,QAAQ,IAAI,KAAK,SAAS,QAAQ,IAAI,CAAC,CAAC;EAAE;EACrF,OAAO;CACT;CACA,MAAM,WAAW,QAAQ,KAAK;CAC9B,OAAO,OAAO,SAAS;EAAE,GAAG;EAAU,QAAQ,CAAC,GAAI,SAAS,UAAU,CAAC,GAAI,GAAG,MAAM;CAAE,IAAI;AAC5F"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The SHA-256 of the exact published bytes of every file except the inventory itself. */
|
|
2
|
+
export interface ArtifactInventory {
|
|
3
|
+
schemaVersion: 1;
|
|
4
|
+
buildRevision: string;
|
|
5
|
+
files: Record<string, {
|
|
6
|
+
sha256: string;
|
|
7
|
+
bytes: number;
|
|
8
|
+
}>;
|
|
9
|
+
}
|
|
10
|
+
/** Raw publication filenames are relative to one host-owned directory. URL hosts encode the individual segments. */
|
|
11
|
+
export declare function isPublicationPath(path: string): boolean;
|
|
12
|
+
/** Stable paths, including assets only one publication contains. */
|
|
13
|
+
export declare function diffArtifacts(before: ArtifactInventory, after: ArtifactInventory): {
|
|
14
|
+
added: string[];
|
|
15
|
+
modified: string[];
|
|
16
|
+
removed: string[];
|
|
17
|
+
};
|
|
18
|
+
/** Decode the v1 inventory used by both complete-directory verification and on-demand reads. */
|
|
19
|
+
export declare function decodeArtifactInventory(bytes: Uint8Array): ArtifactInventory;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { DocsError } from "./model.js";
|
|
2
|
+
|
|
3
|
+
// src/artifacts.ts
|
|
4
|
+
/** Raw publication filenames are relative to one host-owned directory. URL hosts encode the individual segments. */
|
|
5
|
+
function isPublicationPath(path) {
|
|
6
|
+
return typeof path === "string" && path === path.trimStart() && !/[\\:\x00-\x1f]|%(?:25|2e|2f|5c)/i.test(path) && path.split("/").every((part) => !!part && part !== "." && part !== "..");
|
|
7
|
+
}
|
|
8
|
+
/** Stable paths, including assets only one publication contains. */
|
|
9
|
+
function diffArtifacts(before, after) {
|
|
10
|
+
const added = [], modified = [], removed = [];
|
|
11
|
+
for (const path of [.../* @__PURE__ */ new Set([...Object.keys(before.files), ...Object.keys(after.files)])].sort()) if (!Object.hasOwn(before.files, path)) added.push(path);
|
|
12
|
+
else if (!Object.hasOwn(after.files, path)) removed.push(path);
|
|
13
|
+
else if (before.files[path].sha256 !== after.files[path].sha256 || before.files[path].bytes !== after.files[path].bytes) modified.push(path);
|
|
14
|
+
return {
|
|
15
|
+
added,
|
|
16
|
+
modified,
|
|
17
|
+
removed
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** Decode the v1 inventory used by both complete-directory verification and on-demand reads. */
|
|
21
|
+
function decodeArtifactInventory(bytes) {
|
|
22
|
+
let inventory;
|
|
23
|
+
try {
|
|
24
|
+
inventory = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
25
|
+
} catch {
|
|
26
|
+
throw new DocsError("DOCS_ARTIFACT_INTEGRITY", "Invalid artifact inventory JSON.", { source: "artifacts.json" });
|
|
27
|
+
}
|
|
28
|
+
if (inventory?.schemaVersion !== 1 || typeof inventory.buildRevision !== "string" || !inventory.files || typeof inventory.files !== "object" || Array.isArray(inventory.files) || Object.hasOwn(inventory.files, "artifacts.json") || !Object.entries(inventory.files).every(([path, item]) => isPublicationPath(path) && item && typeof item.sha256 === "string" && /^[0-9a-f]{64}$/.test(item.sha256) && Number.isSafeInteger(item.bytes) && item.bytes >= 0)) throw new DocsError("DOCS_ARTIFACT_INTEGRITY", "Invalid artifact inventory schema.", { source: "artifacts.json" });
|
|
29
|
+
return inventory;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export { decodeArtifactInventory, diffArtifacts, isPublicationPath };
|
|
33
|
+
//# sourceMappingURL=artifacts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"artifacts.js","names":[],"sources":["../src/artifacts.ts"],"sourcesContent":["import { DocsError } from \"./model.js\"\n\n/** The SHA-256 of the exact published bytes of every file except the inventory itself. */\nexport interface ArtifactInventory {\n schemaVersion: 1\n buildRevision: string\n files: Record<string, { sha256: string; bytes: number }>\n}\n\n/** Raw publication filenames are relative to one host-owned directory. URL hosts encode the individual segments. */\nexport function isPublicationPath(path: string) {\n return (\n typeof path === \"string\" &&\n path === path.trimStart() &&\n !/[\\\\:\\x00-\\x1f]|%(?:25|2e|2f|5c)/i.test(path) &&\n path.split(\"/\").every((part) => !!part && part !== \".\" && part !== \"..\")\n )\n}\n\n/** Stable paths, including assets only one publication contains. */\nexport function diffArtifacts(before: ArtifactInventory, after: ArtifactInventory) {\n const added: string[] = [],\n modified: string[] = [],\n removed: string[] = []\n for (const path of [\n ...new Set([...Object.keys(before.files), ...Object.keys(after.files)]),\n ].sort()) {\n if (!Object.hasOwn(before.files, path)) added.push(path)\n else if (!Object.hasOwn(after.files, path)) removed.push(path)\n else if (\n before.files[path]!.sha256 !== after.files[path]!.sha256 ||\n before.files[path]!.bytes !== after.files[path]!.bytes\n )\n modified.push(path)\n }\n return { added, modified, removed }\n}\n\n/** Decode the v1 inventory used by both complete-directory verification and on-demand reads. */\nexport function decodeArtifactInventory(bytes: Uint8Array): ArtifactInventory {\n let inventory: ArtifactInventory\n try {\n inventory = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes))\n } catch {\n throw new DocsError(\"DOCS_ARTIFACT_INTEGRITY\", \"Invalid artifact inventory JSON.\", {\n source: \"artifacts.json\",\n })\n }\n if (\n inventory?.schemaVersion !== 1 ||\n typeof inventory.buildRevision !== \"string\" ||\n !inventory.files ||\n typeof inventory.files !== \"object\" ||\n Array.isArray(inventory.files) ||\n Object.hasOwn(inventory.files, \"artifacts.json\") ||\n !Object.entries(inventory.files).every(\n ([path, item]) =>\n isPublicationPath(path) &&\n item &&\n typeof item.sha256 === \"string\" &&\n /^[0-9a-f]{64}$/.test(item.sha256) &&\n Number.isSafeInteger(item.bytes) &&\n item.bytes >= 0,\n )\n )\n throw new DocsError(\"DOCS_ARTIFACT_INTEGRITY\", \"Invalid artifact inventory schema.\", {\n source: \"artifacts.json\",\n })\n return inventory\n}\n"],"mappings":";;;;AAUA,SAAgB,kBAAkB,MAAc;CAC9C,OACE,OAAO,SAAS,YAChB,SAAS,KAAK,UAAU,KACxB,CAAC,mCAAmC,KAAK,IAAI,KAC7C,KAAK,MAAM,GAAG,CAAC,CAAC,OAAO,SAAS,CAAC,CAAC,QAAQ,SAAS,OAAO,SAAS,IAAI;AAE3E;;AAGA,SAAgB,cAAc,QAA2B,OAA0B;CACjF,MAAM,QAAkB,CAAC,GACvB,WAAqB,CAAC,GACtB,UAAoB,CAAC;CACvB,KAAK,MAAM,QAAQ,CACjB,mBAAG,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,OAAO,KAAK,GAAG,GAAG,OAAO,KAAK,MAAM,KAAK,CAAC,CAAC,CACxE,CAAC,CAAC,KAAK,GACL,IAAI,CAAC,OAAO,OAAO,OAAO,OAAO,IAAI,GAAG,MAAM,KAAK,IAAI;MAClD,IAAI,CAAC,OAAO,OAAO,MAAM,OAAO,IAAI,GAAG,QAAQ,KAAK,IAAI;MACxD,IACH,OAAO,MAAM,KAAK,CAAE,WAAW,MAAM,MAAM,KAAK,CAAE,UAClD,OAAO,MAAM,KAAK,CAAE,UAAU,MAAM,MAAM,KAAK,CAAE,OAEjD,SAAS,KAAK,IAAI;CAEtB,OAAO;EAAE;EAAO;EAAU;CAAQ;AACpC;;AAGA,SAAgB,wBAAwB,OAAsC;CAC5E,IAAI;CACJ,IAAI;EACF,YAAY,KAAK,MAAM,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC;CAChF,QAAQ;EACN,MAAM,IAAI,UAAU,2BAA2B,oCAAoC,EACjF,QAAQ,iBACV,CAAC;CACH;CACA,IACE,WAAW,kBAAkB,KAC7B,OAAO,UAAU,kBAAkB,YACnC,CAAC,UAAU,SACX,OAAO,UAAU,UAAU,YAC3B,MAAM,QAAQ,UAAU,KAAK,KAC7B,OAAO,OAAO,UAAU,OAAO,gBAAgB,KAC/C,CAAC,OAAO,QAAQ,UAAU,KAAK,CAAC,CAAC,OAC9B,CAAC,MAAM,UACN,kBAAkB,IAAI,KACtB,QACA,OAAO,KAAK,WAAW,YACvB,iBAAiB,KAAK,KAAK,MAAM,KACjC,OAAO,cAAc,KAAK,KAAK,KAC/B,KAAK,SAAS,CAClB,GAEA,MAAM,IAAI,UAAU,2BAA2B,sCAAsC,EACnF,QAAQ,iBACV,CAAC;CACH,OAAO;AACT"}
|
package/dist/ask.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { openDocs } from "./open-docs.js";
|
|
2
|
+
import type { RetrievalCitation } from "./retrieval.js";
|
|
3
|
+
import type { Context } from "./semantic.js";
|
|
4
|
+
/** A section the answer may draw on, in ranked order. */
|
|
5
|
+
export interface AskSource {
|
|
6
|
+
title: string;
|
|
7
|
+
heading?: string;
|
|
8
|
+
/** The site path of the section, such as `/guide/install/#requirements`. */
|
|
9
|
+
route: string;
|
|
10
|
+
markdown: string;
|
|
11
|
+
citation?: RetrievalCitation;
|
|
12
|
+
}
|
|
13
|
+
export interface AskInput {
|
|
14
|
+
question: string;
|
|
15
|
+
/** The reader's context, such as `{ locale: "fr" }`. */
|
|
16
|
+
context: Context;
|
|
17
|
+
sources: AskSource[];
|
|
18
|
+
/** Aborted when the reader leaves or cancels. Pass it to the model request. */
|
|
19
|
+
signal: AbortSignal;
|
|
20
|
+
}
|
|
21
|
+
export interface AskHandlerOptions {
|
|
22
|
+
/** An opened publication, from `openDocs`. Answers read only its public sections. */
|
|
23
|
+
docs: Awaited<ReturnType<typeof openDocs>>;
|
|
24
|
+
/** Write an answer from the question and its sources with the model of your choice. */
|
|
25
|
+
answer(input: AskInput): string | Promise<string>;
|
|
26
|
+
/** How many sections to pass to `answer`. Defaults to 5. */
|
|
27
|
+
limit?: number;
|
|
28
|
+
/** The longest question accepted, in characters. Defaults to 500. */
|
|
29
|
+
maxQuestionLength?: number;
|
|
30
|
+
}
|
|
31
|
+
/** What the handler returns for a question: the answer and the sections it was given. */
|
|
32
|
+
export interface AskResponse {
|
|
33
|
+
answer: string;
|
|
34
|
+
sources: Omit<AskSource, "markdown">[];
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A fetch-style handler for the Ask AI plugin. It accepts `POST { question, context? }`, finds the best-matching
|
|
38
|
+
* sections with the publication's search index, reads their Markdown, and returns `{ answer, sources }`. The model
|
|
39
|
+
* call is yours: Docs SDK does not choose a provider or hold a key. Mount it at the `endpoint` given to `askAiTheme`.
|
|
40
|
+
*/
|
|
41
|
+
export declare function createAskHandler(options: AskHandlerOptions): (request: Request) => Promise<Response>;
|
package/dist/ask.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { doc } from "./references.js";
|
|
2
|
+
|
|
3
|
+
// src/ask.ts
|
|
4
|
+
const json = (status, body) => new Response(JSON.stringify(body), {
|
|
5
|
+
status,
|
|
6
|
+
headers: {
|
|
7
|
+
"content-type": "application/json; charset=utf-8",
|
|
8
|
+
"cache-control": "no-store"
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
function readContext(value) {
|
|
12
|
+
if (value === void 0) return {};
|
|
13
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
14
|
+
const entries = Object.entries(value);
|
|
15
|
+
if (entries.length > 8) return void 0;
|
|
16
|
+
for (const [name, dimension] of entries) if (!/^[A-Za-z][A-Za-z0-9-]{0,31}$/.test(name) || typeof dimension !== "string" || dimension.length > 64) return void 0;
|
|
17
|
+
return Object.fromEntries(entries);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A fetch-style handler for the Ask AI plugin. It accepts `POST { question, context? }`, finds the best-matching
|
|
21
|
+
* sections with the publication's search index, reads their Markdown, and returns `{ answer, sources }`. The model
|
|
22
|
+
* call is yours: Docs SDK does not choose a provider or hold a key. Mount it at the `endpoint` given to `askAiTheme`.
|
|
23
|
+
*/
|
|
24
|
+
function createAskHandler(options) {
|
|
25
|
+
const limit = options.limit ?? 5;
|
|
26
|
+
const maxLength = options.maxQuestionLength ?? 500;
|
|
27
|
+
return async function handle(request) {
|
|
28
|
+
if (request.method !== "POST") return new Response(null, {
|
|
29
|
+
status: 405,
|
|
30
|
+
headers: { allow: "POST" }
|
|
31
|
+
});
|
|
32
|
+
let body;
|
|
33
|
+
try {
|
|
34
|
+
body = await request.json();
|
|
35
|
+
} catch {
|
|
36
|
+
return json(400, { error: "Send a JSON body such as { \"question\": \"How do I install it?\" }." });
|
|
37
|
+
}
|
|
38
|
+
const question = typeof body?.question === "string" ? body.question.trim() : "";
|
|
39
|
+
if (!question || question.length > maxLength) return json(400, { error: `Ask a question of 1 to ${maxLength} characters.` });
|
|
40
|
+
const context = readContext(body.context);
|
|
41
|
+
if (!context) return json(400, { error: "The context must map dimension names to strings." });
|
|
42
|
+
const docs = options.docs.withContext(context);
|
|
43
|
+
const sources = [];
|
|
44
|
+
let answer;
|
|
45
|
+
try {
|
|
46
|
+
const { hits } = await docs.retrieve(question, {
|
|
47
|
+
limit,
|
|
48
|
+
signal: request.signal
|
|
49
|
+
});
|
|
50
|
+
for (const { result, citation } of hits) {
|
|
51
|
+
request.signal.throwIfAborted();
|
|
52
|
+
const path = result.document.split("@")[0].replace(/^document:/, "");
|
|
53
|
+
const section = result.section.split("@")[0].split("#")[1];
|
|
54
|
+
const heading = result.subheading ? result.route.split("#")[1] : void 0;
|
|
55
|
+
const read = await docs.reader.read({
|
|
56
|
+
...doc(path),
|
|
57
|
+
dimensions: result.context
|
|
58
|
+
}, section, heading).catch(() => void 0);
|
|
59
|
+
if (!read) continue;
|
|
60
|
+
sources.push({
|
|
61
|
+
title: result.title,
|
|
62
|
+
...result.heading && { heading: result.heading },
|
|
63
|
+
route: result.route,
|
|
64
|
+
markdown: read.markdown,
|
|
65
|
+
citation
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
request.signal.throwIfAborted();
|
|
69
|
+
answer = await options.answer({
|
|
70
|
+
question,
|
|
71
|
+
context,
|
|
72
|
+
sources,
|
|
73
|
+
signal: request.signal
|
|
74
|
+
});
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (request.signal.aborted) return new Response(null, { status: 499 });
|
|
77
|
+
console.error("Docs SDK Ask AI answer failed:", error);
|
|
78
|
+
return json(502, { error: "The answer could not be written. Try again later." });
|
|
79
|
+
}
|
|
80
|
+
const response = {
|
|
81
|
+
answer,
|
|
82
|
+
sources: sources.map(({ markdown: _markdown, ...source }) => source)
|
|
83
|
+
};
|
|
84
|
+
return json(200, response);
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export { createAskHandler };
|
|
89
|
+
//# sourceMappingURL=ask.js.map
|
package/dist/ask.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ask.js","names":[],"sources":["../src/ask.ts"],"sourcesContent":["import type { openDocs } from \"./open-docs.js\"\nimport { doc } from \"./references.js\"\nimport type { RetrievalCitation } from \"./retrieval.js\"\nimport type { Context } from \"./semantic.js\"\n\n/** A section the answer may draw on, in ranked order. */\nexport interface AskSource {\n title: string\n heading?: string\n /** The site path of the section, such as `/guide/install/#requirements`. */\n route: string\n markdown: string\n citation?: RetrievalCitation\n}\n\nexport interface AskInput {\n question: string\n /** The reader's context, such as `{ locale: \"fr\" }`. */\n context: Context\n sources: AskSource[]\n /** Aborted when the reader leaves or cancels. Pass it to the model request. */\n signal: AbortSignal\n}\n\nexport interface AskHandlerOptions {\n /** An opened publication, from `openDocs`. Answers read only its public sections. */\n docs: Awaited<ReturnType<typeof openDocs>>\n /** Write an answer from the question and its sources with the model of your choice. */\n answer(input: AskInput): string | Promise<string>\n /** How many sections to pass to `answer`. Defaults to 5. */\n limit?: number\n /** The longest question accepted, in characters. Defaults to 500. */\n maxQuestionLength?: number\n}\n\n/** What the handler returns for a question: the answer and the sections it was given. */\nexport interface AskResponse {\n answer: string\n sources: Omit<AskSource, \"markdown\">[]\n}\n\nconst json = (status: number, body: unknown) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json; charset=utf-8\", \"cache-control\": \"no-store\" },\n })\n\nfunction readContext(value: unknown): Context | undefined {\n if (value === undefined) return {}\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined\n const entries = Object.entries(value)\n if (entries.length > 8) return undefined\n for (const [name, dimension] of entries)\n if (\n !/^[A-Za-z][A-Za-z0-9-]{0,31}$/.test(name) ||\n typeof dimension !== \"string\" ||\n dimension.length > 64\n )\n return undefined\n return Object.fromEntries(entries) as Context\n}\n\n/**\n * A fetch-style handler for the Ask AI plugin. It accepts `POST { question, context? }`, finds the best-matching\n * sections with the publication's search index, reads their Markdown, and returns `{ answer, sources }`. The model\n * call is yours: Docs SDK does not choose a provider or hold a key. Mount it at the `endpoint` given to `askAiTheme`.\n */\nexport function createAskHandler(options: AskHandlerOptions) {\n const limit = options.limit ?? 5\n const maxLength = options.maxQuestionLength ?? 500\n return async function handle(request: Request): Promise<Response> {\n if (request.method !== \"POST\")\n return new Response(null, { status: 405, headers: { allow: \"POST\" } })\n let body: { question?: unknown; context?: unknown }\n try {\n body = await request.json()\n } catch {\n return json(400, {\n error: 'Send a JSON body such as { \"question\": \"How do I install it?\" }.',\n })\n }\n const question = typeof body?.question === \"string\" ? body.question.trim() : \"\"\n if (!question || question.length > maxLength)\n return json(400, { error: `Ask a question of 1 to ${maxLength} characters.` })\n const context = readContext(body.context)\n if (!context) return json(400, { error: \"The context must map dimension names to strings.\" })\n const docs = options.docs.withContext(context)\n const sources: AskSource[] = []\n let answer: string\n try {\n const { hits } = await docs.retrieve(question, { limit, signal: request.signal })\n for (const { result, citation } of hits) {\n request.signal.throwIfAborted()\n const path = result.document.split(\"@\")[0]!.replace(/^document:/, \"\")\n const section = result.section.split(\"@\")[0]!.split(\"#\")[1]\n const heading = result.subheading ? result.route.split(\"#\")[1] : undefined\n const read = await docs.reader\n .read({ ...doc(path), dimensions: result.context }, section, heading)\n .catch(() => undefined)\n if (!read) continue\n sources.push({\n title: result.title,\n ...(result.heading && { heading: result.heading }),\n route: result.route,\n markdown: read.markdown,\n citation,\n })\n }\n request.signal.throwIfAborted()\n answer = await options.answer({ question, context, sources, signal: request.signal })\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 })\n console.error(\"Docs SDK Ask AI answer failed:\", error)\n return json(502, { error: \"The answer could not be written. Try again later.\" })\n }\n const response: AskResponse = {\n answer,\n sources: sources.map(({ markdown: _markdown, ...source }) => source),\n }\n return json(200, response)\n }\n}\n"],"mappings":";;;AAyCA,MAAM,QAAQ,QAAgB,SAC5B,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;CACjC;CACA,SAAS;EAAE,gBAAgB;EAAmC,iBAAiB;CAAW;AAC5F,CAAC;AAEH,SAAS,YAAY,OAAqC;CACxD,IAAI,UAAU,QAAW,OAAO,CAAC;CACjC,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO;CACxE,MAAM,UAAU,OAAO,QAAQ,KAAK;CACpC,IAAI,QAAQ,SAAS,GAAG,OAAO;CAC/B,KAAK,MAAM,CAAC,MAAM,cAAc,SAC9B,IACE,CAAC,+BAA+B,KAAK,IAAI,KACzC,OAAO,cAAc,YACrB,UAAU,SAAS,IAEnB,OAAO;CACX,OAAO,OAAO,YAAY,OAAO;AACnC;;;;;;AAOA,SAAgB,iBAAiB,SAA4B;CAC3D,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,YAAY,QAAQ,qBAAqB;CAC/C,OAAO,eAAe,OAAO,SAAqC;EAChE,IAAI,QAAQ,WAAW,QACrB,OAAO,IAAI,SAAS,MAAM;GAAE,QAAQ;GAAK,SAAS,EAAE,OAAO,OAAO;EAAE,CAAC;EACvE,IAAI;EACJ,IAAI;GACF,OAAO,MAAM,QAAQ,KAAK;EAC5B,QAAQ;GACN,OAAO,KAAK,KAAK,EACf,OAAO,uEACT,CAAC;EACH;EACA,MAAM,WAAW,OAAO,MAAM,aAAa,WAAW,KAAK,SAAS,KAAK,IAAI;EAC7E,IAAI,CAAC,YAAY,SAAS,SAAS,WACjC,OAAO,KAAK,KAAK,EAAE,OAAO,0BAA0B,UAAU,cAAc,CAAC;EAC/E,MAAM,UAAU,YAAY,KAAK,OAAO;EACxC,IAAI,CAAC,SAAS,OAAO,KAAK,KAAK,EAAE,OAAO,mDAAmD,CAAC;EAC5F,MAAM,OAAO,QAAQ,KAAK,YAAY,OAAO;EAC7C,MAAM,UAAuB,CAAC;EAC9B,IAAI;EACJ,IAAI;GACF,MAAM,EAAE,SAAS,MAAM,KAAK,SAAS,UAAU;IAAE;IAAO,QAAQ,QAAQ;GAAO,CAAC;GAChF,KAAK,MAAM,EAAE,QAAQ,cAAc,MAAM;IACvC,QAAQ,OAAO,eAAe;IAC9B,MAAM,OAAO,OAAO,SAAS,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,QAAQ,cAAc,EAAE;IACpE,MAAM,UAAU,OAAO,QAAQ,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,MAAM,GAAG,CAAC,CAAC;IACzD,MAAM,UAAU,OAAO,aAAa,OAAO,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK;IACjE,MAAM,OAAO,MAAM,KAAK,OACrB,KAAK;KAAE,GAAG,IAAI,IAAI;KAAG,YAAY,OAAO;IAAQ,GAAG,SAAS,OAAO,CAAC,CACpE,YAAY,MAAS;IACxB,IAAI,CAAC,MAAM;IACX,QAAQ,KAAK;KACX,OAAO,OAAO;KACd,GAAI,OAAO,WAAW,EAAE,SAAS,OAAO,QAAQ;KAChD,OAAO,OAAO;KACd,UAAU,KAAK;KACf;IACF,CAAC;GACH;GACA,QAAQ,OAAO,eAAe;GAC9B,SAAS,MAAM,QAAQ,OAAO;IAAE;IAAU;IAAS;IAAS,QAAQ,QAAQ;GAAO,CAAC;EACtF,SAAS,OAAO;GACd,IAAI,QAAQ,OAAO,SAAS,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;GACrE,QAAQ,MAAM,kCAAkC,KAAK;GACrD,OAAO,KAAK,KAAK,EAAE,OAAO,oDAAoD,CAAC;EACjF;EACA,MAAM,WAAwB;GAC5B;GACA,SAAS,QAAQ,KAAK,EAAE,UAAU,WAAW,GAAG,aAAa,MAAM;EACrE;EACA,OAAO,KAAK,KAAK,QAAQ;CAC3B;AACF"}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import type { ListBlock } from "./content-schema.js";
|
|
2
|
+
import type { LocalizedText } from "./directory-navigation.js";
|
|
3
|
+
import { type Provenance } from "./model.js";
|
|
4
|
+
import type { ViewPlacement } from "./composition.js";
|
|
5
|
+
import { type Context } from "./semantic.js";
|
|
6
|
+
/** One source-owned edition of a record. Revisions cover metadata and content read by the view. */
|
|
7
|
+
export interface CollectionRecord<Value> {
|
|
8
|
+
id: string;
|
|
9
|
+
context?: Context;
|
|
10
|
+
priority?: number;
|
|
11
|
+
revision: string;
|
|
12
|
+
value: Value;
|
|
13
|
+
provenance?: readonly Provenance[];
|
|
14
|
+
}
|
|
15
|
+
export interface CollectionQueryHost<Value> {
|
|
16
|
+
/** Project the selected record under host authority. Omit a denied record entirely. */
|
|
17
|
+
project?(record: Readonly<CollectionRecord<Value>>): {
|
|
18
|
+
value: Value;
|
|
19
|
+
} | undefined;
|
|
20
|
+
}
|
|
21
|
+
export interface CollectionQuery<Value> {
|
|
22
|
+
context?: Context;
|
|
23
|
+
filter?: (value: Value) => boolean;
|
|
24
|
+
compare?: (left: Value, right: Value) => number;
|
|
25
|
+
groupBy?: (value: Value) => string | readonly string[];
|
|
26
|
+
offset?: number;
|
|
27
|
+
limit?: number;
|
|
28
|
+
}
|
|
29
|
+
/** Group an already selected page. Preserve first-seen group order and item order within each group. */
|
|
30
|
+
export declare function groupCollectionItems<Item>(items: readonly Item[], keysFor: (item: Item) => string | readonly string[]): {
|
|
31
|
+
key: string;
|
|
32
|
+
items: Item[];
|
|
33
|
+
}[];
|
|
34
|
+
/** Resolve editions before filtering. Sort by record ID on ties so paging survives input reordering. */
|
|
35
|
+
export declare function queryCollection<Value>(records: Iterable<CollectionRecord<Value>>, query?: CollectionQuery<Value>, host?: CollectionQueryHost<Value>): {
|
|
36
|
+
total: number;
|
|
37
|
+
items: {
|
|
38
|
+
id: string;
|
|
39
|
+
variant: string;
|
|
40
|
+
value: Value;
|
|
41
|
+
revision: string;
|
|
42
|
+
provenance: readonly Provenance[];
|
|
43
|
+
}[];
|
|
44
|
+
groups: {
|
|
45
|
+
key: string;
|
|
46
|
+
items: {
|
|
47
|
+
id: string;
|
|
48
|
+
variant: string;
|
|
49
|
+
value: Value;
|
|
50
|
+
revision: string;
|
|
51
|
+
provenance: readonly Provenance[];
|
|
52
|
+
}[];
|
|
53
|
+
}[];
|
|
54
|
+
};
|
|
55
|
+
/** Compare two executions of the same query. Re-execution also discovers records outside the previous read set. */
|
|
56
|
+
export declare function diffCollectionViews<Value>(before: ReturnType<typeof queryCollection<Value>>, after: ReturnType<typeof queryCollection<Value>>): {
|
|
57
|
+
added: string[];
|
|
58
|
+
removed: string[];
|
|
59
|
+
updated: string[];
|
|
60
|
+
moved: string[];
|
|
61
|
+
totalChange: number;
|
|
62
|
+
};
|
|
63
|
+
export interface QueryView<Value> extends ViewPlacement {
|
|
64
|
+
query: CollectionQuery<Value>;
|
|
65
|
+
link?: (record: {
|
|
66
|
+
id: string;
|
|
67
|
+
value: Value;
|
|
68
|
+
variant: string;
|
|
69
|
+
}) => {
|
|
70
|
+
href: string;
|
|
71
|
+
title: string;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export declare function resolveQueryView<Value>(view: QueryView<Value>, records: Iterable<CollectionRecord<Value>>, host?: CollectionQueryHost<Value>): {
|
|
75
|
+
placement: {
|
|
76
|
+
id: string;
|
|
77
|
+
route: string | undefined;
|
|
78
|
+
};
|
|
79
|
+
selection: {
|
|
80
|
+
total: number;
|
|
81
|
+
items: {
|
|
82
|
+
id: string;
|
|
83
|
+
variant: string;
|
|
84
|
+
value: Value;
|
|
85
|
+
revision: string;
|
|
86
|
+
provenance: readonly Provenance[];
|
|
87
|
+
}[];
|
|
88
|
+
groups: {
|
|
89
|
+
key: string;
|
|
90
|
+
items: {
|
|
91
|
+
id: string;
|
|
92
|
+
variant: string;
|
|
93
|
+
value: Value;
|
|
94
|
+
revision: string;
|
|
95
|
+
provenance: readonly Provenance[];
|
|
96
|
+
}[];
|
|
97
|
+
}[];
|
|
98
|
+
};
|
|
99
|
+
navigation: {
|
|
100
|
+
href: string;
|
|
101
|
+
title: string;
|
|
102
|
+
id: string;
|
|
103
|
+
variant: string;
|
|
104
|
+
}[];
|
|
105
|
+
content: {
|
|
106
|
+
schemaVersion: 1;
|
|
107
|
+
blocks: ListBlock[];
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
type FieldOf<Value, Kind> = Extract<{
|
|
111
|
+
[Key in keyof Value]-?: Value[Key] extends Kind ? Key : never;
|
|
112
|
+
}[keyof Value], string>;
|
|
113
|
+
type Scalar = string | number | boolean | null;
|
|
114
|
+
/** Portable record predicates use only own scalar fields. A producer can send the same terms to an adapter. */
|
|
115
|
+
export type FieldSelection = Readonly<Record<string, string | number | boolean | null>>;
|
|
116
|
+
export declare function matchesFields(value: unknown, fields: Readonly<Record<string, unknown>>): boolean;
|
|
117
|
+
/** Bind a named record source to a placed view using the ordinary edition, paging and dependency rules. */
|
|
118
|
+
export type QueryDefinition<Value extends object, From = string> = ViewPlacement & {
|
|
119
|
+
dimensionDefinitions?: import("./dimensions.js").DimensionDefinitions;
|
|
120
|
+
from: From;
|
|
121
|
+
content?: never;
|
|
122
|
+
title?: LocalizedText;
|
|
123
|
+
where?: Partial<Pick<Value, FieldOf<Value, Scalar>>>;
|
|
124
|
+
sortBy?: FieldOf<Value, string | number>;
|
|
125
|
+
groupBy?: FieldOf<Value, string | readonly string[]>;
|
|
126
|
+
link?: QueryView<Value>["link"];
|
|
127
|
+
};
|
|
128
|
+
type SourceData<From> = From extends {
|
|
129
|
+
kind: "docs-source";
|
|
130
|
+
load(...args: any[]): infer Output;
|
|
131
|
+
} ? Awaited<Output> extends {
|
|
132
|
+
records?: readonly (infer Row)[];
|
|
133
|
+
} ? Extract<Row, {
|
|
134
|
+
data: object;
|
|
135
|
+
}>["data"] : never : From extends {
|
|
136
|
+
from: infer Source;
|
|
137
|
+
} ? SourceData<Source> : From extends readonly (infer Source)[] ? SourceData<Source> : never;
|
|
138
|
+
type InferredQueryDefinition<Value extends object, From> = Omit<QueryDefinition<Value, From>, "id"> & {
|
|
139
|
+
id?: string;
|
|
140
|
+
};
|
|
141
|
+
export declare function defineView<const Definition extends {
|
|
142
|
+
id?: string;
|
|
143
|
+
route?: string;
|
|
144
|
+
from?: never;
|
|
145
|
+
content: readonly unknown[];
|
|
146
|
+
}>(definition: Definition): Definition;
|
|
147
|
+
export declare function defineView<Value extends object>(definition: QueryDefinition<Value>): ReturnType<typeof queryView<Value, string, QueryDefinition<Value>>>;
|
|
148
|
+
export declare function defineView<From extends object>(definition: QueryDefinition<SourceData<From>, From>): ReturnType<typeof queryView<SourceData<From>, From, QueryDefinition<SourceData<From>, From>>>;
|
|
149
|
+
export declare function defineView<From extends object>(definition: InferredQueryDefinition<SourceData<From>, From>): ReturnType<typeof queryView<SourceData<From>, From, InferredQueryDefinition<SourceData<From>, From>>>;
|
|
150
|
+
declare function queryView<Value extends object, From, Definition extends InferredQueryDefinition<Value, From>>(definition: Definition): Definition & {
|
|
151
|
+
resolve(this: {
|
|
152
|
+
id?: string;
|
|
153
|
+
} | void, sources: ReadonlyMap<From, Iterable<CollectionRecord<Value>>>, page?: Pick<CollectionQuery<Value>, "offset" | "limit" | "context">, host?: CollectionQueryHost<Value>): {
|
|
154
|
+
placement: {
|
|
155
|
+
id: string;
|
|
156
|
+
route: string | undefined;
|
|
157
|
+
};
|
|
158
|
+
selection: {
|
|
159
|
+
total: number;
|
|
160
|
+
items: {
|
|
161
|
+
id: string;
|
|
162
|
+
variant: string;
|
|
163
|
+
value: Value;
|
|
164
|
+
revision: string;
|
|
165
|
+
provenance: readonly Provenance[];
|
|
166
|
+
}[];
|
|
167
|
+
groups: {
|
|
168
|
+
key: string;
|
|
169
|
+
items: {
|
|
170
|
+
id: string;
|
|
171
|
+
variant: string;
|
|
172
|
+
value: Value;
|
|
173
|
+
revision: string;
|
|
174
|
+
provenance: readonly Provenance[];
|
|
175
|
+
}[];
|
|
176
|
+
}[];
|
|
177
|
+
};
|
|
178
|
+
navigation: {
|
|
179
|
+
href: string;
|
|
180
|
+
title: string;
|
|
181
|
+
id: string;
|
|
182
|
+
variant: string;
|
|
183
|
+
}[];
|
|
184
|
+
content: {
|
|
185
|
+
schemaVersion: 1;
|
|
186
|
+
blocks: ListBlock[];
|
|
187
|
+
};
|
|
188
|
+
};
|
|
189
|
+
};
|
|
190
|
+
export {};
|