@astrokjs/okf 0.0.0-stage → 0.1.0-beta.1

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 (59) hide show
  1. package/LICENSE +9 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +9 -0
  4. package/README.md +57 -2
  5. package/dist/graph/compiler.d.ts +14 -0
  6. package/dist/graph/compiler.js +75 -0
  7. package/dist/graph/files.d.ts +7 -0
  8. package/dist/graph/files.js +102 -0
  9. package/dist/graph/index.d.ts +9 -0
  10. package/dist/graph/index.js +7 -0
  11. package/dist/graph/memory.d.ts +41 -0
  12. package/dist/graph/memory.js +144 -0
  13. package/dist/graph/metadata.d.ts +3 -0
  14. package/dist/graph/metadata.js +16 -0
  15. package/dist/graph/model.d.ts +88 -0
  16. package/dist/graph/model.js +18 -0
  17. package/dist/graph/project.d.ts +3 -0
  18. package/dist/graph/project.js +242 -0
  19. package/dist/graph/publish.d.ts +38 -0
  20. package/dist/graph/publish.js +56 -0
  21. package/dist/graph/query-core.d.ts +72 -0
  22. package/dist/graph/query-core.js +124 -0
  23. package/dist/graph/query-guide.d.ts +4 -0
  24. package/dist/graph/query-guide.js +35 -0
  25. package/dist/graph/query-reference.d.ts +4 -0
  26. package/dist/graph/query-reference.js +99 -0
  27. package/dist/graph/query.d.ts +59 -0
  28. package/dist/graph/query.js +191 -0
  29. package/dist/graph/schema.d.ts +5 -0
  30. package/dist/graph/schema.js +86 -0
  31. package/dist/graph/snapshot.d.ts +9 -0
  32. package/dist/graph/snapshot.js +115 -0
  33. package/dist/graph/sqlite-guide.d.ts +2 -0
  34. package/dist/graph/sqlite-guide.js +123 -0
  35. package/dist/graph/sqlite.d.ts +4 -0
  36. package/dist/graph/sqlite.js +4 -0
  37. package/dist/graph/version.d.ts +7 -0
  38. package/dist/graph/version.js +7 -0
  39. package/dist/graph/wasm.d.ts +23 -0
  40. package/dist/graph/wasm.js +60 -0
  41. package/dist/index.d.mts +9 -0
  42. package/dist/index.mjs +9 -0
  43. package/dist/okf/bundle.d.mts +2 -0
  44. package/dist/okf/bundle.mjs +58 -0
  45. package/dist/okf/document.d.mts +8 -0
  46. package/dist/okf/document.mjs +109 -0
  47. package/dist/okf/links.d.mts +11 -0
  48. package/dist/okf/links.mjs +91 -0
  49. package/dist/okf/markdown.d.mts +8 -0
  50. package/dist/okf/markdown.mjs +45 -0
  51. package/dist/okf/metadata.d.mts +18 -0
  52. package/dist/okf/metadata.mjs +127 -0
  53. package/dist/site/generate.d.mts +8 -0
  54. package/dist/site/generate.mjs +187 -0
  55. package/dist/site/ownership.d.ts +4 -0
  56. package/dist/site/ownership.js +78 -0
  57. package/dist/types.d.ts +78 -0
  58. package/dist/types.js +1 -0
  59. package/package.json +58 -4
@@ -0,0 +1,11 @@
1
+ /** @param {string} file @returns {string} */
2
+ export function pageUrl(file: string): string;
3
+ /** @param {string} href @param {string} sourcePath @param {Map<string, Pick<import('../types.js').Document, 'id' | 'headings'>>} documents @param {Map<string, Uint8Array>} assets @returns {import('../types.js').ResolvedLink} */
4
+ export function resolveLink(href: string, sourcePath: string, documents: Map<string, Pick<import("../types.js").Document, "id" | "headings">>, assets: Map<string, Uint8Array>): import("../types.js").ResolvedLink;
5
+ /** Resolve OKF path metadata with the optional <=0.2 compatibility fallback.
6
+ * @param {string} href @param {string} sourcePath
7
+ * @param {Map<string, Pick<import('../types.js').Document, 'id' | 'headings'>>} documents
8
+ * @param {Map<string, Uint8Array>} assets @param {unknown} version
9
+ * @returns {import('../types.js').ResolvedLink}
10
+ */
11
+ export function resolvePathField(href: string, sourcePath: string, documents: Map<string, Pick<import("../types.js").Document, "id" | "headings">>, assets: Map<string, Uint8Array>, version: unknown): import("../types.js").ResolvedLink;
@@ -0,0 +1,91 @@
1
+ import path from 'node:path';
2
+ /** @param {string} file @returns {string} */
3
+ export function pageUrl(file) {
4
+ const id = file.replace(/\.md$/, '').replace(/(^|\/)index$/, '');
5
+ return '/' + id.split('/').filter(Boolean).map(encodeURIComponent).join('/') + (id ? '/' : '');
6
+ }
7
+ /** @param {string} href @param {string} sourcePath @param {Map<string, Pick<import('../types.js').Document, 'id' | 'headings'>>} documents @param {Map<string, Uint8Array>} assets @returns {import('../types.js').ResolvedLink} */
8
+ export function resolveLink(href, sourcePath, documents, assets) {
9
+ if (/[\x00-\x20\x7f]/.test(href))
10
+ return { url: href, warning: 'invalid URL characters' };
11
+ if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href))
12
+ return { url: href, external: true };
13
+ const match = href.match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);
14
+ if (!match)
15
+ return { url: href, warning: 'invalid URL' };
16
+ const [, rawPath, query = '', hash = ''] = match;
17
+ let decoded;
18
+ let fragment;
19
+ try {
20
+ decoded = decodeURIComponent(rawPath);
21
+ fragment = decodeURIComponent(hash.slice(1));
22
+ }
23
+ catch {
24
+ return { url: href, warning: 'invalid URL encoding' };
25
+ }
26
+ let targetPath = decoded
27
+ ? path.posix.normalize(decoded.startsWith('/')
28
+ ? decoded.slice(1)
29
+ : path.posix.join(path.posix.dirname(sourcePath), decoded))
30
+ : sourcePath;
31
+ if (targetPath === '..' ||
32
+ targetPath.startsWith('../') ||
33
+ targetPath.includes('\\') ||
34
+ targetPath.includes('\0')) {
35
+ return {
36
+ url: href,
37
+ external: true,
38
+ warning: 'link escapes the bundle or uses an invalid path',
39
+ };
40
+ }
41
+ if (targetPath === '.' || targetPath.endsWith('/'))
42
+ targetPath = (targetPath === '.' ? '' : targetPath) + 'index.md';
43
+ if (!documents.has(targetPath) && documents.has(targetPath + '/index.md'))
44
+ targetPath += '/index.md';
45
+ const target = documents.get(targetPath);
46
+ if (target) {
47
+ return {
48
+ target: target.id,
49
+ targetPath,
50
+ fragment: fragment || null,
51
+ url: pageUrl(targetPath) + query + hash,
52
+ ...(fragment && !target.headings.includes(fragment)
53
+ ? { warning: `missing heading #${fragment} in ${targetPath}` }
54
+ : {}),
55
+ };
56
+ }
57
+ if (assets.has(targetPath))
58
+ return {
59
+ targetPath,
60
+ url: '/okf/' + targetPath.split('/').map(encodeURIComponent).join('/') + query + hash,
61
+ };
62
+ return {
63
+ targetPath,
64
+ url: targetPath.endsWith('.md') ? pageUrl(targetPath) + query + hash : href,
65
+ warning: `missing target ${targetPath}`,
66
+ };
67
+ }
68
+ /** Resolve OKF path metadata with the optional <=0.2 compatibility fallback.
69
+ * @param {string} href @param {string} sourcePath
70
+ * @param {Map<string, Pick<import('../types.js').Document, 'id' | 'headings'>>} documents
71
+ * @param {Map<string, Uint8Array>} assets @param {unknown} version
72
+ * @returns {import('../types.js').ResolvedLink}
73
+ */
74
+ export function resolvePathField(href, sourcePath, documents, assets, version) {
75
+ const resolved = resolveLink(href, sourcePath, documents, assets);
76
+ const legacy = version == null ||
77
+ version === '' ||
78
+ (typeof version === 'string' && /^0\.[012]$/.test(version));
79
+ if (legacy &&
80
+ !resolved.external &&
81
+ resolved.targetPath &&
82
+ !documents.has(resolved.targetPath) &&
83
+ !assets.has(resolved.targetPath) &&
84
+ !href.startsWith('/')) {
85
+ const fallback = resolveLink('/' + href, sourcePath, documents, assets);
86
+ if (fallback.targetPath &&
87
+ (documents.has(fallback.targetPath) || assets.has(fallback.targetPath)))
88
+ return fallback;
89
+ }
90
+ return resolved;
91
+ }
@@ -0,0 +1,8 @@
1
+ export function walk(node: any, visit: any): void;
2
+ export function textContent(node: any): any;
3
+ export function inspectMarkdown(body: any): {
4
+ tree: import("mdast").Root;
5
+ headings: any[];
6
+ links: any[];
7
+ };
8
+ export const markdown: import("unified").Processor<import("mdast").Root, undefined, undefined, import("mdast").Root, string>;
@@ -0,0 +1,45 @@
1
+ import { unified } from 'unified';
2
+ import remarkParse from 'remark-parse';
3
+ import remarkGfm from 'remark-gfm';
4
+ import remarkStringify from 'remark-stringify';
5
+ import GithubSlugger from 'github-slugger';
6
+ export const markdown = unified().use(remarkParse).use(remarkGfm).use(remarkStringify);
7
+ export function walk(node, visit) {
8
+ visit(node);
9
+ for (const child of node.children ?? [])
10
+ walk(child, visit);
11
+ }
12
+ export function textContent(node) {
13
+ return node.value ?? node.alt ?? (node.children ?? []).map(textContent).join('');
14
+ }
15
+ export function inspectMarkdown(body) {
16
+ const tree = markdown.parse(body);
17
+ const slugger = new GithubSlugger();
18
+ const headings = [];
19
+ const links = [];
20
+ const definitions = new Map();
21
+ walk(tree, (node) => {
22
+ if (node.type === 'definition')
23
+ definitions.set(node.identifier, node.url);
24
+ });
25
+ let sourceFragment = null;
26
+ walk(tree, (node) => {
27
+ if (node.type === 'heading') {
28
+ sourceFragment = slugger.slug(textContent(node));
29
+ headings.push(sourceFragment);
30
+ }
31
+ const href = node.type === 'link' || node.type === 'image'
32
+ ? node.url
33
+ : node.type === 'linkReference' || node.type === 'imageReference'
34
+ ? definitions.get(node.identifier)
35
+ : null;
36
+ if (href != null)
37
+ links.push({
38
+ href,
39
+ sourceFragment,
40
+ line: node.position?.start.line,
41
+ column: node.position?.start.column,
42
+ });
43
+ });
44
+ return { tree, headings, links };
45
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Derive advisory metadata at a caller-chosen instant. This does not attest runs
3
+ * or grant execution permission. Unknown fields remain in the source metadata.
4
+ * @param {Record<string, unknown>} metadata
5
+ * @param {{now?: Date}} [options]
6
+ * @returns {import('../types.js').MetadataState}
7
+ */
8
+ export function readMetadata(metadata: Record<string, unknown>, { now }?: {
9
+ now?: Date;
10
+ }): import("../types.js").MetadataState;
11
+ /** Enumerate only defined path fields, retaining their exact metadata location.
12
+ * @param {Record<string, unknown>} metadata
13
+ * @returns {{field: string, href: string}[]}
14
+ */
15
+ export function metadataPaths(metadata: Record<string, unknown>): {
16
+ field: string;
17
+ href: string;
18
+ }[];
@@ -0,0 +1,127 @@
1
+ /** OKF 0.3 interpretation; the original metadata is never rewritten. */
2
+ const mapping = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date);
3
+ const text = (value) => typeof value === 'string' && value.trim().length > 0;
4
+ const absent = (value) => value == null || value === '' || (Array.isArray(value) && value.length === 0);
5
+ const list = (value) => (absent(value) ? [] : Array.isArray(value) ? value : [value]);
6
+ const actor = (value) => text(value) && /^(?:[^\s:/]+\/[^\s]+|[a-z][a-z\d+.-]*:[\s\S]*\S)$/i.test(value);
7
+ /** Parse only RFC 3339 dates/instants, never JavaScript's permissive date prose. */
8
+ function timestamp(value) {
9
+ if (value instanceof Date)
10
+ return Number.isFinite(value.getTime()) ? value.getTime() : null;
11
+ if (typeof value !== 'string')
12
+ return null;
13
+ const match = /^(\d{4}-\d{2}-\d{2})(?:[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2}))?$/.exec(value);
14
+ if (!match)
15
+ return null;
16
+ const day = Date.parse(match[1] + 'T00:00:00Z');
17
+ if (!Number.isFinite(day) || new Date(day).toISOString().slice(0, 10) !== match[1])
18
+ return null;
19
+ if (match[2] === undefined)
20
+ return day;
21
+ const [, , hour, minute, second, fraction = '', zone] = match;
22
+ if (+hour > 23 || +minute > 59 || +second > 60)
23
+ return null;
24
+ if (zone.length > 1 && (+zone.slice(1, 3) > 23 || +zone.slice(4) > 59))
25
+ return null;
26
+ const instant = Date.parse(`${match[1]}T${hour}:${minute}:${second === '60' ? '59' : second}${fraction}${zone.toUpperCase()}`);
27
+ return Number.isFinite(instant) ? instant + (second === '60' ? 1000 : 0) : null;
28
+ }
29
+ /**
30
+ * Derive advisory metadata at a caller-chosen instant. This does not attest runs
31
+ * or grant execution permission. Unknown fields remain in the source metadata.
32
+ * @param {Record<string, unknown>} metadata
33
+ * @param {{now?: Date}} [options]
34
+ * @returns {import('../types.js').MetadataState}
35
+ */
36
+ export function readMetadata(metadata, { now = new Date() } = {}) {
37
+ if (!Number.isFinite(now.getTime()))
38
+ throw new TypeError('now must be a valid Date');
39
+ const warnings = [];
40
+ const entries = (key, required) => list(metadata[key]).filter((entry, index) => {
41
+ if (mapping(entry) && required.every((field) => text(entry[field])))
42
+ return true;
43
+ warnings.push(`${key}[${index}]: missing or invalid ${required.join(', ')}`);
44
+ return false;
45
+ });
46
+ const tags = list(metadata.tags).filter((tag) => {
47
+ if (text(tag))
48
+ return true;
49
+ warnings.push('tags: expected non-empty strings');
50
+ return false;
51
+ });
52
+ const sources = entries('sources', ['resource']);
53
+ const parameters = entries('parameters', ['name', 'type']);
54
+ let generatedAt = null;
55
+ let hasGeneration = !absent(metadata.generated);
56
+ if (hasGeneration) {
57
+ if (!mapping(metadata.generated) || !actor(metadata.generated.by)) {
58
+ warnings.push('generated: missing or invalid by');
59
+ hasGeneration = false;
60
+ }
61
+ else {
62
+ generatedAt = timestamp(metadata.generated.at);
63
+ if (generatedAt === null)
64
+ warnings.push('generated.at: current verification cannot be determined');
65
+ }
66
+ }
67
+ const verified = list(metadata.verified).filter((event, index) => {
68
+ if (mapping(event) && actor(event.by) && timestamp(event.at) !== null)
69
+ return true;
70
+ warnings.push(`verified[${index}]: valid by and at are required`);
71
+ return false;
72
+ });
73
+ const currentVerifications = verified.filter((event) => !hasGeneration || (generatedAt !== null && timestamp(event.at) >= generatedAt));
74
+ const trustTier = currentVerifications.some((event) => event.by.startsWith('human:'))
75
+ ? 'human-reviewed'
76
+ : currentVerifications.length
77
+ ? 'machine-confirmed'
78
+ : 'unverified';
79
+ const deadline = timestamp(metadata.stale_after);
80
+ const freshness = absent(metadata.stale_after)
81
+ ? 'unspecified'
82
+ : deadline === null
83
+ ? 'malformed'
84
+ : now.getTime() >= deadline
85
+ ? 'stale'
86
+ : 'fresh';
87
+ if (freshness === 'malformed')
88
+ warnings.push('stale_after: malformed timestamp');
89
+ const status = absent(metadata.status) ? 'stable' : metadata.status;
90
+ if (!['draft', 'stable', 'deprecated'].includes(status))
91
+ warnings.push('status: unknown value');
92
+ return {
93
+ tags,
94
+ sources,
95
+ parameters,
96
+ verified,
97
+ currentVerifications,
98
+ trustTier,
99
+ freshness,
100
+ status,
101
+ current: status === 'stable' && freshness !== 'stale' && freshness !== 'malformed',
102
+ warnings,
103
+ };
104
+ }
105
+ /** Enumerate only defined path fields, retaining their exact metadata location.
106
+ * @param {Record<string, unknown>} metadata
107
+ * @returns {{field: string, href: string}[]}
108
+ */
109
+ export function metadataPaths(metadata) {
110
+ const paths = [];
111
+ const add = (field, value, descriptor = false) => {
112
+ if (text(value) && !(descriptor && /\s/.test(value)))
113
+ paths.push({ field, href: value });
114
+ };
115
+ add('resource', metadata.resource);
116
+ list(metadata.sources).forEach((source, index) => {
117
+ if (mapping(source))
118
+ add(`sources[${index}].resource`, source.resource, true);
119
+ });
120
+ add('computation', metadata.computation);
121
+ for (const key of ['executor', 'attester'])
122
+ if (mapping(metadata[key]))
123
+ add(`${key}.resource`, metadata[key].resource);
124
+ if (metadata.status === 'deprecated')
125
+ add('superseded_by', metadata.superseded_by);
126
+ return paths;
127
+ }
@@ -0,0 +1,8 @@
1
+ export function normalizeBase(base?: string): string;
2
+ /** @param {string} url @param {string} [base] @returns {string} */
3
+ export function withBase(url: string, base?: string): string;
4
+ /** @param {import('../types.js').SiteOptions} [options] @returns {Promise<import('../types.js').LoadedSite>} */
5
+ export function loadSite({ root, base, strictLinks }?: import("../types.js").SiteOptions): Promise<import("../types.js").LoadedSite>;
6
+ /** @param {import('../types.js').GenerateOptions} [options] @returns {Promise<import('../types.js').Bundle>} */
7
+ export function generateSite({ root, docsDir, publicDir, base, presentation, strictLinks, }?: import("../types.js").GenerateOptions): Promise<import("../types.js").Bundle>;
8
+ export { assertOwnedDirectory, assertDisjointDirectories } from "./ownership.js";
@@ -0,0 +1,187 @@
1
+ import { mkdir, readFile, writeFile, readdir, rm } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { stringify } from 'yaml';
4
+ import { readBundle } from '../okf/bundle.mjs';
5
+ import { markdown, walk, textContent } from '../okf/markdown.mjs';
6
+ import { pageUrl, resolveLink } from '../okf/links.mjs';
7
+ import { assertOwnedDirectory, assertDisjointDirectories } from "./ownership.js";
8
+ export function normalizeBase(base = '/') {
9
+ if (typeof base !== 'string' ||
10
+ !base.startsWith('/') ||
11
+ base.startsWith('//') ||
12
+ /[?#\\]/.test(base) ||
13
+ base.split('/').some((segment) => segment === '..' || segment === '.'))
14
+ throw new Error('base must be an absolute URL path without traversal, query or fragment');
15
+ return ('/' +
16
+ base.split('/').filter(Boolean).join('/') +
17
+ (base.split('/').filter(Boolean).length ? '/' : ''));
18
+ }
19
+ /** @param {string} url @param {string} [base] @returns {string} */
20
+ export function withBase(url, base = '/') {
21
+ return url.startsWith('/') && !url.startsWith('//')
22
+ ? normalizeBase(base).slice(0, -1) + url
23
+ : url;
24
+ }
25
+ // Only generator-owned directories are passed here. Avoid rewriting unchanged files
26
+ // so Astro's content watcher gets a change only when content actually changed.
27
+ async function syncFiles(directory, files) {
28
+ await mkdir(directory, { recursive: true });
29
+ async function prune(dir, prefix = '') {
30
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
31
+ const relative = prefix + entry.name;
32
+ const full = path.join(dir, entry.name);
33
+ if (entry.isDirectory()) {
34
+ await prune(full, relative + '/');
35
+ if (!(await readdir(full)).length)
36
+ await rm(full, { recursive: true });
37
+ }
38
+ else if (relative !== '.astrok-owned.json' && !files.has(relative))
39
+ await rm(full);
40
+ }
41
+ }
42
+ await prune(directory);
43
+ for (const [file, data] of files) {
44
+ const full = path.join(directory, file);
45
+ const bytes = Buffer.from(data);
46
+ const old = await readFile(full).catch((error) => {
47
+ if (error.code !== 'ENOENT')
48
+ throw error;
49
+ return null;
50
+ });
51
+ if (old?.equals(bytes))
52
+ continue;
53
+ await mkdir(path.dirname(full), { recursive: true });
54
+ await writeFile(full, bytes);
55
+ }
56
+ }
57
+ /** @param {import('../types.js').SiteOptions} [options] @returns {Promise<import('../types.js').LoadedSite>} */
58
+ export async function loadSite({ root = 'knowledge', base = '/', strictLinks = false } = {}) {
59
+ if (typeof strictLinks !== 'boolean')
60
+ throw new Error('strictLinks must be a boolean');
61
+ base = normalizeBase(base);
62
+ const bundle = await readBundle(root);
63
+ if (bundle.errors.length)
64
+ throw new Error(bundle.errors.join('\n'));
65
+ if (strictLinks) {
66
+ // Link diagnostics are publication policy, not minimum OKF conformance.
67
+ const errors = bundle.documents.flatMap((document) => document.links
68
+ .filter((link) => link.warning)
69
+ .map((link) => `${document.path}${link.line === undefined ? '' : `:${link.line}`}: ${link.warning}`));
70
+ if (errors.length)
71
+ throw new Error(`Invalid internal links (${errors.length}):\n${errors.join('\n')}`);
72
+ }
73
+ const routes = new Map();
74
+ for (const document of bundle.documents) {
75
+ const url = pageUrl(document.path);
76
+ if (url === '/404/')
77
+ throw new Error(`Route collision: ${document.path} conflicts with Starlight's 404 page`);
78
+ if (routes.has(url))
79
+ throw new Error(`Route collision: ${document.path} and ${routes.get(url)} map to ${url}`);
80
+ routes.set(url, document.path);
81
+ }
82
+ if (bundle.assets.has('manifest.json'))
83
+ throw new Error('Export collision: knowledge/manifest.json conflicts with the generated manifest');
84
+ const byPath = new Map(bundle.documents.map((document) => [document.path, document]));
85
+ const pages = new Map();
86
+ const documents = [];
87
+ const raw = new Map(bundle.assets);
88
+ for (const document of bundle.documents) {
89
+ const tree = markdown.parse(document.body);
90
+ walk(tree, (node) => {
91
+ if (node.type === 'link' || node.type === 'image' || node.type === 'definition') {
92
+ node.url = withBase(resolveLink(node.url, document.path, byPath, bundle.assets).url, base);
93
+ }
94
+ });
95
+ const first = tree.children[0];
96
+ const hasBodyTitle = first?.type === 'heading' && first.depth === 1 && textContent(first) === document.title;
97
+ // Source metadata never becomes Starlight configuration (e.g. draft, sidebar).
98
+ const frontmatter = {
99
+ title: document.title,
100
+ ...(document.description ? { description: document.description } : {}),
101
+ // Astro expects decoded route parameters; Starlight removes terminal index.
102
+ slug: document.id,
103
+ okf: {
104
+ sourcePath: document.path,
105
+ sourceUrl: withBase('/okf/' + document.path.split('/').map(encodeURIComponent).join('/'), base),
106
+ type: document.type,
107
+ hasBodyTitle,
108
+ },
109
+ };
110
+ // Explicit slugs preserve source paths instead of lowercasing filenames.
111
+ pages.set(document.path, `---\n${stringify(frontmatter)}---\n\n${markdown.stringify(tree)}`);
112
+ raw.set(document.path, document.source);
113
+ documents.push({
114
+ ...document,
115
+ body: markdown.stringify(tree),
116
+ url: withBase(pageUrl(document.path), base),
117
+ sourceUrl: frontmatter.okf.sourceUrl,
118
+ });
119
+ }
120
+ if (!byPath.has('index.md')) {
121
+ const tree = {
122
+ type: 'root',
123
+ children: [
124
+ { type: 'paragraph', children: [{ type: 'text', value: 'Browse the knowledge bundle.' }] },
125
+ {
126
+ type: 'list',
127
+ ordered: false,
128
+ children: bundle.documents.map((document) => ({
129
+ type: 'listItem',
130
+ children: [
131
+ {
132
+ type: 'paragraph',
133
+ children: [
134
+ {
135
+ type: 'link',
136
+ url: withBase(pageUrl(document.path), base),
137
+ children: [{ type: 'text', value: document.title }],
138
+ },
139
+ ],
140
+ },
141
+ ],
142
+ })),
143
+ },
144
+ ],
145
+ };
146
+ pages.set('index.md', `---\ntitle: Knowledge\nslug: ""\n---\n\n${markdown.stringify(tree)}`);
147
+ }
148
+ const manifest = {
149
+ format: 'okf-site-manifest',
150
+ version: 1,
151
+ documents: bundle.documents.map(({ id, path: sourcePath, kind, title, description, type, metadata, headings, links }) => ({
152
+ id,
153
+ path: sourcePath,
154
+ kind,
155
+ title,
156
+ description,
157
+ type,
158
+ metadata,
159
+ headings,
160
+ links: links.map((link) => ({ ...link, url: withBase(link.url, base) })),
161
+ url: withBase(pageUrl(sourcePath), base),
162
+ sourceUrl: withBase('/okf/' + sourcePath.split('/').map(encodeURIComponent).join('/'), base),
163
+ })),
164
+ };
165
+ raw.set('manifest.json', JSON.stringify(manifest, null, 2) + '\n');
166
+ return { bundle, documents, manifest, pages, raw };
167
+ }
168
+ /** @param {import('../types.js').GenerateOptions} [options] @returns {Promise<import('../types.js').Bundle>} */
169
+ export async function generateSite({ root = 'knowledge', docsDir = 'src/content/docs', publicDir = '.generated/public', base = '/', presentation = 'starlight', strictLinks = false, } = {}) {
170
+ if (presentation !== 'plain' && presentation !== 'starlight')
171
+ throw new Error('Unknown presentation');
172
+ const site = await loadSite({ root, base, strictLinks });
173
+ // Check every output before claiming or replacing either directory.
174
+ const outputs = presentation === 'plain'
175
+ ? [path.join(publicDir, 'okf')]
176
+ : [docsDir, path.join(publicDir, 'okf')];
177
+ await assertDisjointDirectories(outputs);
178
+ for (const directory of outputs)
179
+ await assertOwnedDirectory(root, directory, false);
180
+ for (const directory of outputs)
181
+ await assertOwnedDirectory(root, directory, true);
182
+ if (presentation !== 'plain')
183
+ await syncFiles(docsDir, site.pages);
184
+ await syncFiles(path.join(publicDir, 'okf'), site.raw);
185
+ return site.bundle;
186
+ }
187
+ export { assertOwnedDirectory, assertDisjointDirectories } from "./ownership.js";
@@ -0,0 +1,4 @@
1
+ /** Claim empty output directories only. Existing files require our ownership marker. */
2
+ export declare function assertOwnedDirectory(root: string, directory: string, claim?: boolean): Promise<void>;
3
+ /** @param {string[]} directories @returns {Promise<void>} */
4
+ export declare function assertDisjointDirectories(directories: string[]): Promise<void>;
@@ -0,0 +1,78 @@
1
+ import { lstat, readdir, mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ const marker = '.astrok-owned.json';
4
+ // Persisted format identifier: keep existing generated directories usable across npm scope changes.
5
+ const signature = '{"owner":"@astrok/okf","version":1}\n';
6
+ async function physical(file) {
7
+ const { physicalPath } = await import("../graph/files.js");
8
+ return physicalPath(file);
9
+ }
10
+ /** Claim empty output directories only. Existing files require our ownership marker. */
11
+ export async function assertOwnedDirectory(root, directory, claim = false) {
12
+ const resolved = path.resolve(directory);
13
+ // Refuse symbolic links at any existing component, including child entries pruned later.
14
+ async function inspect(current, recursive = false) {
15
+ const stat = await lstat(current).catch((error) => {
16
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
17
+ throw error;
18
+ return null;
19
+ });
20
+ if (!stat)
21
+ return;
22
+ if (stat.isSymbolicLink())
23
+ throw new Error(`Generated output cannot contain symbolic links: ${current}`);
24
+ if (recursive && stat.isDirectory())
25
+ for (const name of await readdir(current))
26
+ await inspect(path.join(current, name), true);
27
+ }
28
+ for (let current = resolved;; current = path.dirname(current)) {
29
+ await inspect(current);
30
+ if (path.dirname(current) === current)
31
+ break;
32
+ }
33
+ const source = await physical(root);
34
+ const output = await physical(directory);
35
+ const inside = (parent, child) => {
36
+ const relative = path.relative(parent, child);
37
+ return (relative === '' ||
38
+ (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative)));
39
+ };
40
+ if (inside(source, output) || inside(output, source))
41
+ throw new Error('Generated output must be outside and must not contain the canonical knowledge directory');
42
+ const names = await readdir(resolved).catch((error) => {
43
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
44
+ throw error;
45
+ return [];
46
+ });
47
+ if (names.length) {
48
+ const existing = await readFile(path.join(resolved, marker), 'utf8').catch((error) => {
49
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
50
+ throw error;
51
+ return null;
52
+ });
53
+ if (existing !== signature)
54
+ throw new Error(`Generated directory ownership is required before replacing existing content: ${resolved}`);
55
+ await inspect(resolved, true);
56
+ }
57
+ if (claim) {
58
+ await mkdir(resolved, { recursive: true });
59
+ if (!names.length)
60
+ await writeFile(path.join(resolved, marker), signature, { flag: 'wx' });
61
+ }
62
+ }
63
+ /** @param {string[]} directories @returns {Promise<void>} */
64
+ export async function assertDisjointDirectories(directories) {
65
+ const resolved = await Promise.all(directories.map(physical));
66
+ for (let i = 0; i < resolved.length; i++)
67
+ for (let j = i + 1; j < resolved.length; j++) {
68
+ for (const [parent, child] of [
69
+ [resolved[i], resolved[j]],
70
+ [resolved[j], resolved[i]],
71
+ ]) {
72
+ const relative = path.relative(parent, child);
73
+ if (relative === '' ||
74
+ (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative)))
75
+ throw new Error('Generated output directories must not overlap');
76
+ }
77
+ }
78
+ }
@@ -0,0 +1,78 @@
1
+ /** Opaque metadata preserves future OKF fields and type vocabularies. */
2
+ export interface SourceLink {
3
+ href: string;
4
+ sourceFragment: string | null;
5
+ line?: number;
6
+ column?: number;
7
+ }
8
+ export interface ResolvedLink {
9
+ url: string;
10
+ external?: boolean;
11
+ target?: string;
12
+ targetPath?: string;
13
+ fragment?: string | null;
14
+ warning?: string;
15
+ }
16
+ export interface Document {
17
+ id: string;
18
+ path: string;
19
+ kind: 'index' | 'log' | 'concept';
20
+ title: string;
21
+ description: string;
22
+ type: string | null;
23
+ metadata: Record<string, unknown>;
24
+ body: string;
25
+ source: string;
26
+ headings: string[];
27
+ links: (SourceLink & Partial<ResolvedLink> & {
28
+ sourcePath?: string;
29
+ })[];
30
+ }
31
+ export interface Bundle {
32
+ documents: Document[];
33
+ assets: Map<string, Uint8Array>;
34
+ errors: string[];
35
+ warnings: string[];
36
+ }
37
+ export interface SiteDocument extends Document {
38
+ url: string;
39
+ sourceUrl: string;
40
+ }
41
+ export interface SiteOptions {
42
+ root?: string;
43
+ base?: string;
44
+ /** Reject link diagnostics before publication; defaults to false in low-level helpers. */
45
+ strictLinks?: boolean;
46
+ }
47
+ export interface GenerateOptions extends SiteOptions {
48
+ docsDir?: string;
49
+ publicDir?: string;
50
+ presentation?: 'plain' | 'starlight';
51
+ }
52
+ export interface ManifestDocument extends Omit<SiteDocument, 'body' | 'source'> {
53
+ }
54
+ export interface SiteManifest {
55
+ format: 'okf-site-manifest';
56
+ version: 1;
57
+ documents: ManifestDocument[];
58
+ }
59
+ export interface LoadedSite {
60
+ bundle: Bundle;
61
+ documents: SiteDocument[];
62
+ manifest: SiteManifest;
63
+ pages: Map<string, string>;
64
+ raw: Map<string, string | Uint8Array>;
65
+ }
66
+ /** Advisory OKF 0.3 interpretation; raw metadata stays on Document.metadata. */
67
+ export interface MetadataState {
68
+ tags: string[];
69
+ sources: Record<string, unknown>[];
70
+ parameters: Record<string, unknown>[];
71
+ verified: Record<string, unknown>[];
72
+ currentVerifications: Record<string, unknown>[];
73
+ trustTier: 'unverified' | 'machine-confirmed' | 'human-reviewed';
74
+ freshness: 'unspecified' | 'fresh' | 'stale' | 'malformed';
75
+ status: unknown;
76
+ current: boolean;
77
+ warnings: string[];
78
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};