@okforest/okf 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ OKForest
2
+ Copyright 2026 Preneur LLC
3
+
4
+ This product includes software developed at Preneur LLC (https://okforest.ai/).
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @okforest/okf
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read an [Open Knowledge Format (OKF)](https://github.com/GoogleCloudPlatform/open-knowledge-format)
4
+ v0.2 tree into a model: concepts (path, concept ID, frontmatter, body as
5
+ [mdast](https://github.com/syntax-tree/mdast)), reserved `index.md` and
6
+ `log.md` files, links in both absolute and relative forms, backlinks, and the
7
+ v0.2 fields with their derived values: trust tier, lifecycle status, and
8
+ staleness. Also builds the metadata inventory: every type, tag, and
9
+ frontmatter key in use, with near-duplicates.
10
+
11
+ No SDKs or frameworks: the core is pure and runs in Node, browsers, and
12
+ Workers. Reading from disk is a separate entry point.
13
+
14
+ ```ts
15
+ import { buildInventory } from "@okforest/okf"
16
+ import { readTree } from "@okforest/okf/node"
17
+
18
+ const tree = await readTree("./sales-okf")
19
+ const orders = tree.concept("tables/orders")
20
+ orders?.trustTier // "unverified" | "machine-confirmed" | "human-reviewed"
21
+ orders?.isStale() // now >= stale_after
22
+ tree.backlinks("tables/orders") // links from other concepts
23
+ buildInventory(tree).nearDuplicates // e.g. e-commerce ~ ecommerce
24
+ ```
25
+
26
+ Without a file system, pass the files yourself:
27
+
28
+ ```ts
29
+ import { parseTree } from "@okforest/okf"
30
+
31
+ const tree = parseTree([
32
+ { path: "index.md", text: '---\nokf_version: "0.2"\n---\n# Tables\n' },
33
+ { path: "tables/orders.md", text: "---\ntype: BigQuery Table\n---\n# Schema\n" },
34
+ ])
35
+ ```
36
+
37
+ Parsing never throws on malformed content: problems are recorded on each file
38
+ (`frontmatterError`) for [`@okforest/validate`](https://www.npmjs.com/package/@okforest/validate)
39
+ to report.
40
+
41
+ Part of the [OKForest CLI](https://github.com/okforest/cli) · Apache-2.0 · © Preneur LLC
@@ -0,0 +1,102 @@
1
+ import { a as KeyPath, c as Position, d as Status, f as Tree, g as Verification, h as TrustTier, i as FootnoteReference, l as ReservedFile, m as TreeSettings, n as Concept, o as Link, p as TreeFile, r as Diagnostic, s as MarkdownFile, t as CodeBlock, u as Source } from "./types-D_k23mU8.mjs";
2
+ import { Nodes, Root } from "mdast";
3
+ //#region src/markdown.d.ts
4
+ /** Depth-first, document-order walk over an mdast tree. */
5
+ export declare function visit(node: Nodes, fn: (node: Nodes) => void): void;
6
+ //#endregion
7
+ //#region src/document.d.ts
8
+ /** Strip a byte-order mark and normalize line endings to LF. */
9
+ export declare function normalizeText(text: string): string;
10
+ //#endregion
11
+ //#region src/inventory.d.ts
12
+ /** A value in use and how many concepts use it. */
13
+ interface Count {
14
+ value: string;
15
+ count: number;
16
+ }
17
+ /** Values that are probably meant to be the same thing. */
18
+ interface NearDuplicates {
19
+ field: "type" | "tag" | "key";
20
+ /** The variants, most used first. */
21
+ values: Count[];
22
+ /** Why they were grouped: identical apart from case and punctuation,
23
+ * singular versus plural, or a small spelling difference. */
24
+ reasons: ("case-or-punctuation" | "plural" | "spelling")[];
25
+ }
26
+ /** The metadata inventory: every type, tag, and frontmatter key in use. */
27
+ interface Inventory {
28
+ concepts: number;
29
+ /** Concepts with no usable `type`. */
30
+ untyped: number;
31
+ types: Count[];
32
+ tags: Count[];
33
+ /** Top-level frontmatter keys. */
34
+ keys: Count[];
35
+ statuses: Record<Status, number>;
36
+ trustTiers: Record<TrustTier, number>;
37
+ /** Concepts past their `stale_after` instant. */
38
+ stale: number;
39
+ nearDuplicates: NearDuplicates[];
40
+ }
41
+ /** Build the metadata inventory of a tree. Deterministic: no model calls. */
42
+ export declare function buildInventory(tree: Tree, options?: {
43
+ now?: Date;
44
+ }): Inventory;
45
+ /**
46
+ * Group values that are likely variants of one another, using string
47
+ * comparison only (semantic synonyms such as `Client` and `Customer` need a
48
+ * declared registry or an AI suggestion):
49
+ *
50
+ * - case and punctuation: `SaaS Application`, `saas-application`;
51
+ * - singular and plural: `Policy`, `Policies`;
52
+ * - spelling: an edit distance of 1 (values of 5+ characters) or 2 (10+),
53
+ * unless one value contains the other.
54
+ */
55
+ export declare function findNearDuplicates(counts: readonly Count[], field: NearDuplicates["field"]): NearDuplicates[];
56
+ //#endregion
57
+ //#region src/paths.d.ts
58
+ /** Convert a glob (relative to the tree root) to a regular expression.
59
+ * `*` and `?` stay within one path segment, `**` crosses segments, and a
60
+ * trailing `/` matches everything under a directory. */
61
+ export declare function globToRegExp(glob: string): RegExp;
62
+ //#endregion
63
+ //#region src/tree.d.ts
64
+ /** Where OKForest keeps per-tree settings (an OKForest convention, not OKF). */
65
+ export declare const SETTINGS_PATH = ".okforest/tree.yaml";
66
+ /**
67
+ * Repository files at the tree root that are not concepts, though the OKF
68
+ * spec letter would make them so. Matched case-insensitively. Extend per tree
69
+ * with `ignore:` globs in `.okforest/tree.yaml`.
70
+ */
71
+ export declare const DEFAULT_IGNORED: readonly string[];
72
+ /**
73
+ * Build a {@link Tree} from files. Pure: no file system access, so the same
74
+ * code runs in Node, browsers, and Workers (see `@okforest/okf/node` for
75
+ * reading a directory). Never throws on malformed content; problems are
76
+ * recorded on the files for `@okforest/validate` to report.
77
+ *
78
+ * Markdown files under hidden directories (any path segment starting with
79
+ * `.`) and `node_modules` are not part of the tree.
80
+ */
81
+ export declare function parseTree(input: Iterable<TreeFile>): Tree;
82
+ //#endregion
83
+ //#region src/trust.d.ts
84
+ /** Lifecycle status (spec §5.4): absent, or not a recognized value, means `stable`. */
85
+ export declare function deriveStatus(value: unknown): Status;
86
+ export declare function isStatus(value: unknown): value is Status;
87
+ /**
88
+ * Verification events (spec §5.2). A bare `{ by, at }` mapping is a
89
+ * one-element list; entries without a string `by` are skipped.
90
+ */
91
+ export declare function normalizeVerified(value: unknown): Verification[];
92
+ /** Trust tier (spec §5.3): `human:` verifiers ⇒ human-reviewed; any other
93
+ * verifier ⇒ machine-confirmed; none ⇒ unverified. */
94
+ export declare function deriveTrustTier(verified: readonly Verification[]): TrustTier;
95
+ /** Whether `now >= staleAfter` (spec §5.5). Unparseable instants are never stale. */
96
+ export declare function isStaleAt(staleAfter: string | undefined, now: Date): boolean;
97
+ export declare function normalizeSources(value: unknown): Source[];
98
+ //#endregion
99
+ //#region src/yaml.d.ts
100
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
101
+ //#endregion
102
+ export type { CodeBlock, Concept, Count, Diagnostic, FootnoteReference, Inventory, KeyPath, Link, MarkdownFile, NearDuplicates, Position, ReservedFile, Source, Status, Tree, TreeFile, TreeSettings, TrustTier, Verification };
package/dist/index.mjs ADDED
@@ -0,0 +1,140 @@
1
+ import { a as deriveTrustTier, c as normalizeSources, d as normalizeText, f as isRecord, i as deriveStatus, l as normalizeVerified, n as SETTINGS_PATH, o as isStaleAt, p as visit, r as parseTree, s as isStatus, t as DEFAULT_IGNORED, u as globToRegExp } from "./tree-BkHJPYfm.mjs";
2
+ //#region src/inventory.ts
3
+ /** Build the metadata inventory of a tree. Deterministic: no model calls. */
4
+ function buildInventory(tree, options = {}) {
5
+ const now = options.now ?? /* @__PURE__ */ new Date();
6
+ const types = /* @__PURE__ */ new Map();
7
+ const tags = /* @__PURE__ */ new Map();
8
+ const keys = /* @__PURE__ */ new Map();
9
+ const statuses = {
10
+ draft: 0,
11
+ stable: 0,
12
+ deprecated: 0
13
+ };
14
+ const trustTiers = {
15
+ unverified: 0,
16
+ "machine-confirmed": 0,
17
+ "human-reviewed": 0
18
+ };
19
+ let untyped = 0;
20
+ let stale = 0;
21
+ const bump = (map, value) => map.set(value, (map.get(value) ?? 0) + 1);
22
+ for (const concept of tree.concepts) {
23
+ if (concept.type) bump(types, concept.type);
24
+ else untyped++;
25
+ for (const tag of new Set(concept.tags)) bump(tags, tag);
26
+ for (const key of Object.keys(concept.frontmatter ?? {})) bump(keys, key);
27
+ statuses[concept.status]++;
28
+ trustTiers[concept.trustTier]++;
29
+ if (concept.isStale(now)) stale++;
30
+ }
31
+ const typeCounts = sorted(types);
32
+ const tagCounts = sorted(tags);
33
+ const keyCounts = sorted(keys);
34
+ return {
35
+ concepts: tree.concepts.length,
36
+ untyped,
37
+ types: typeCounts,
38
+ tags: tagCounts,
39
+ keys: keyCounts,
40
+ statuses,
41
+ trustTiers,
42
+ stale,
43
+ nearDuplicates: [
44
+ ...findNearDuplicates(typeCounts, "type"),
45
+ ...findNearDuplicates(tagCounts, "tag"),
46
+ ...findNearDuplicates(keyCounts, "key")
47
+ ]
48
+ };
49
+ }
50
+ /** Most used first; ties in code-point order, so output is the same on every machine. */
51
+ function sorted(map) {
52
+ return [...map].map(([value, count]) => ({
53
+ value,
54
+ count
55
+ })).sort((a, b) => b.count - a.count || (a.value < b.value ? -1 : a.value > b.value ? 1 : 0));
56
+ }
57
+ /**
58
+ * Group values that are likely variants of one another, using string
59
+ * comparison only (semantic synonyms such as `Client` and `Customer` need a
60
+ * declared registry or an AI suggestion):
61
+ *
62
+ * - case and punctuation: `SaaS Application`, `saas-application`;
63
+ * - singular and plural: `Policy`, `Policies`;
64
+ * - spelling: an edit distance of 1 (values of 5+ characters) or 2 (10+),
65
+ * unless one value contains the other.
66
+ */
67
+ function findNearDuplicates(counts, field) {
68
+ const parent = counts.map((_, i) => i);
69
+ const find = (i) => {
70
+ while (parent[i] !== i) i = parent[i] = parent[parent[i]];
71
+ return i;
72
+ };
73
+ const reasons = /* @__PURE__ */ new Map();
74
+ const union = (a, b, reason) => {
75
+ const ra = find(a);
76
+ const rb = find(b);
77
+ const merged = /* @__PURE__ */ new Set([
78
+ ...reasons.get(ra) ?? [],
79
+ ...reasons.get(rb) ?? [],
80
+ reason
81
+ ]);
82
+ if (ra !== rb) parent[rb] = ra;
83
+ reasons.set(ra, merged);
84
+ };
85
+ const folded = counts.map((c) => c.value.toLowerCase().replace(/[^\p{L}\p{N}]/gu, ""));
86
+ const singular = folded.map(singularize);
87
+ for (let i = 0; i < counts.length; i++) for (let j = i + 1; j < counts.length; j++) {
88
+ const a = folded[i];
89
+ const b = folded[j];
90
+ if (a === "" || b === "") continue;
91
+ if (a === b) union(i, j, "case-or-punctuation");
92
+ else if (singular[i] === singular[j]) union(i, j, "plural");
93
+ else if (!a.includes(b) && !b.includes(a)) {
94
+ const shortest = Math.min(a.length, b.length);
95
+ const allowed = shortest >= 10 ? 2 : shortest >= 5 ? 1 : 0;
96
+ if (allowed > 0 && editDistance(a, b, allowed) <= allowed) union(i, j, "spelling");
97
+ }
98
+ }
99
+ const groups = /* @__PURE__ */ new Map();
100
+ counts.forEach((_, i) => {
101
+ const root = find(i);
102
+ groups.set(root, [...groups.get(root) ?? [], i]);
103
+ });
104
+ const order = [
105
+ "case-or-punctuation",
106
+ "plural",
107
+ "spelling"
108
+ ];
109
+ return [...groups].filter(([, members]) => members.length > 1).map(([root, members]) => ({
110
+ field,
111
+ values: members.map((i) => counts[i]),
112
+ reasons: order.filter((r) => reasons.get(root)?.has(r))
113
+ }));
114
+ }
115
+ function singularize(word) {
116
+ if (word.endsWith("ies") && word.length > 4) return `${word.slice(0, -3)}y`;
117
+ if (/(?:ses|xes|zes|ches|shes)$/.test(word)) return word.slice(0, -2);
118
+ if (word.endsWith("s") && !word.endsWith("ss") && word.length > 3) return word.slice(0, -1);
119
+ return word;
120
+ }
121
+ /** Levenshtein distance, stopping early once it exceeds `limit`. */
122
+ function editDistance(a, b, limit) {
123
+ if (Math.abs(a.length - b.length) > limit) return limit + 1;
124
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
125
+ for (let i = 1; i <= a.length; i++) {
126
+ const current = [i];
127
+ let rowMin = i;
128
+ for (let j = 1; j <= b.length; j++) {
129
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
130
+ const value = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
131
+ current.push(value);
132
+ rowMin = Math.min(rowMin, value);
133
+ }
134
+ if (rowMin > limit) return limit + 1;
135
+ previous = current;
136
+ }
137
+ return previous[b.length];
138
+ }
139
+ //#endregion
140
+ export { DEFAULT_IGNORED, SETTINGS_PATH, buildInventory, deriveStatus, deriveTrustTier, findNearDuplicates, globToRegExp, isRecord, isStaleAt, isStatus, normalizeSources, normalizeText, normalizeVerified, parseTree, visit };
@@ -0,0 +1,11 @@
1
+ import { f as Tree, p as TreeFile } from "./types-D_k23mU8.mjs";
2
+ //#region src/node.d.ts
3
+ /**
4
+ * Read a tree from disk and build its model with {@link parseTree}. Reads the
5
+ * text of markdown files and `.okforest/tree.yaml`; other files are listed by
6
+ * path only, so links to them can be checked. Symbolic links are not followed.
7
+ */
8
+ export declare function readTree(root: string): Promise<Tree>;
9
+ /** The files {@link readTree} would hand to `parseTree`. */
10
+ export declare function readTreeFiles(root: string): Promise<TreeFile[]>;
11
+ //#endregion
package/dist/node.mjs ADDED
@@ -0,0 +1,38 @@
1
+ import { r as parseTree } from "./tree-BkHJPYfm.mjs";
2
+ import { readFile, readdir } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ //#region src/node.ts
5
+ /** Directories never walked: version control and installed packages. */
6
+ const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([".git", "node_modules"]);
7
+ /**
8
+ * Read a tree from disk and build its model with {@link parseTree}. Reads the
9
+ * text of markdown files and `.okforest/tree.yaml`; other files are listed by
10
+ * path only, so links to them can be checked. Symbolic links are not followed.
11
+ */
12
+ async function readTree(root) {
13
+ return parseTree(await readTreeFiles(root));
14
+ }
15
+ /** The files {@link readTree} would hand to `parseTree`. */
16
+ async function readTreeFiles(root) {
17
+ const files = [];
18
+ const walk = async (dir, prefix) => {
19
+ const entries = await readdir(dir, { withFileTypes: true });
20
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
21
+ for (const entry of entries) {
22
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
23
+ if (entry.isDirectory()) {
24
+ if (!SKIPPED_DIRECTORIES.has(entry.name)) await walk(join(dir, entry.name), path);
25
+ } else if (entry.isFile()) {
26
+ const needsText = path.endsWith(".md") || path === ".okforest/tree.yaml";
27
+ files.push(needsText ? {
28
+ path,
29
+ text: await readFile(join(dir, entry.name), "utf8")
30
+ } : { path });
31
+ }
32
+ }
33
+ };
34
+ await walk(root, "");
35
+ return files;
36
+ }
37
+ //#endregion
38
+ export { readTree, readTreeFiles };
@@ -0,0 +1,503 @@
1
+ import { fromMarkdown } from "mdast-util-from-markdown";
2
+ import { gfmFootnoteFromMarkdown } from "mdast-util-gfm-footnote";
3
+ import { gfmFootnote } from "micromark-extension-gfm-footnote";
4
+ import { LineCounter, isMap, isScalar, isSeq, parseDocument } from "yaml";
5
+ //#region src/markdown.ts
6
+ /**
7
+ * Parse markdown as CommonMark plus GFM footnotes, the one GitHub extension
8
+ * OKF relies on (per-claim attribution, spec §5.1). Other GFM extensions
9
+ * (tables, strikethrough, task lists, bare-URL autolinks) change nothing the
10
+ * model or rules use, and skipping them parses about 1.5x faster: links in
11
+ * table cells are still found, since a table row parses as a paragraph.
12
+ * Positions are relative to `source`; callers blank out frontmatter lines so
13
+ * they stay relative to the whole file.
14
+ */
15
+ function parseMarkdown(source) {
16
+ const ast = fromMarkdown(source, {
17
+ extensions: [gfmFootnote()],
18
+ mdastExtensions: [gfmFootnoteFromMarkdown()]
19
+ });
20
+ const lines = source.split("\n");
21
+ const definitions = /* @__PURE__ */ new Map();
22
+ visit(ast, (node) => {
23
+ if (node.type === "definition") definitions.set(node.identifier, node);
24
+ });
25
+ const links = [];
26
+ const footnotes = [];
27
+ const codeBlocks = [];
28
+ visit(ast, (node) => {
29
+ const start = node.position?.start;
30
+ if (!start) return;
31
+ switch (node.type) {
32
+ case "link":
33
+ case "image":
34
+ links.push({
35
+ target: node.url,
36
+ line: start.line,
37
+ column: start.column,
38
+ image: node.type === "image"
39
+ });
40
+ break;
41
+ case "linkReference":
42
+ case "imageReference": {
43
+ const definition = definitions.get(node.identifier);
44
+ if (definition) links.push({
45
+ target: definition.url,
46
+ line: start.line,
47
+ column: start.column,
48
+ image: node.type === "imageReference"
49
+ });
50
+ break;
51
+ }
52
+ case "footnoteReference":
53
+ footnotes.push({
54
+ label: node.label ?? node.identifier,
55
+ line: start.line,
56
+ column: start.column
57
+ });
58
+ break;
59
+ case "code": {
60
+ const fenced = /^\s*(`{3,}|~{3,})/.test(lines[start.line - 1] ?? "");
61
+ codeBlocks.push({
62
+ ...node.lang ? { lang: node.lang } : {},
63
+ value: node.value,
64
+ line: start.line,
65
+ contentLine: fenced ? start.line + 1 : start.line
66
+ });
67
+ break;
68
+ }
69
+ }
70
+ });
71
+ return {
72
+ ast,
73
+ links,
74
+ footnotes,
75
+ codeBlocks
76
+ };
77
+ }
78
+ /** Depth-first, document-order walk over an mdast tree. */
79
+ function visit(node, fn) {
80
+ fn(node);
81
+ if ("children" in node) for (const child of node.children) visit(child, fn);
82
+ }
83
+ //#endregion
84
+ //#region src/yaml.ts
85
+ /**
86
+ * Parse YAML 1.2 (core schema), so unquoted timestamps such as
87
+ * `2026-06-30T14:00:00Z` stay strings and can be checked as written, and
88
+ * `yes`/`no` are not booleans. Duplicate keys are errors: consumers disagree
89
+ * on which value wins, so the data is ambiguous.
90
+ *
91
+ * `firstLine` is the file line where `source` begins, so positions are
92
+ * reported relative to the whole file.
93
+ */
94
+ function parseYaml(source, firstLine) {
95
+ const lineCounter = new LineCounter();
96
+ const doc = parseDocument(source, {
97
+ lineCounter,
98
+ prettyErrors: false,
99
+ uniqueKeys: true,
100
+ version: "1.2",
101
+ schema: "core"
102
+ });
103
+ const at = (offset) => {
104
+ const { line, col } = lineCounter.linePos(offset);
105
+ return {
106
+ line: line + firstLine - 1,
107
+ column: col
108
+ };
109
+ };
110
+ const locate = (path) => {
111
+ let node = doc.contents;
112
+ let offset;
113
+ for (const segment of path) {
114
+ if (typeof segment === "number" && isSeq(node)) {
115
+ node = node.items[segment];
116
+ offset = node?.range?.[0];
117
+ } else if (isMap(node)) {
118
+ const pair = node.items.find((p) => isScalar(p.key) && p.key.value === segment);
119
+ if (!pair) return void 0;
120
+ offset = pair.key.range?.[0];
121
+ node = pair.value;
122
+ } else return;
123
+ if (node === void 0 && offset === void 0) return void 0;
124
+ }
125
+ return offset === void 0 ? void 0 : at(offset);
126
+ };
127
+ const first = doc.errors[0];
128
+ if (first) {
129
+ const { line, column } = at(first.pos[0]);
130
+ return {
131
+ value: void 0,
132
+ error: {
133
+ message: first.message,
134
+ line,
135
+ column
136
+ },
137
+ locate
138
+ };
139
+ }
140
+ return {
141
+ value: doc.toJS({ maxAliasCount: 100 }),
142
+ locate
143
+ };
144
+ }
145
+ function isRecord(value) {
146
+ return typeof value === "object" && value !== null && !Array.isArray(value);
147
+ }
148
+ //#endregion
149
+ //#region src/document.ts
150
+ const DELIMITER = /^---[ \t]*$/;
151
+ /** Strip a byte-order mark and normalize line endings to LF. */
152
+ function normalizeText(text) {
153
+ return text.replace(/^/, "").replace(/\r\n?/g, "\n");
154
+ }
155
+ /**
156
+ * Read one markdown file: split the frontmatter block (spec §4: `---` on its
157
+ * own line at the start and a closing `---` on its own line), parse it as
158
+ * YAML, and parse the body. Never throws: problems become `frontmatterError`.
159
+ */
160
+ function readMarkdownFile(path, rawText) {
161
+ const text = normalizeText(rawText);
162
+ const lines = text.split("\n");
163
+ let hasFrontmatter = false;
164
+ let frontmatter;
165
+ let frontmatterError;
166
+ let bodyStartLine = 1;
167
+ let locate = () => void 0;
168
+ if (DELIMITER.test(lines[0] ?? "")) {
169
+ hasFrontmatter = true;
170
+ const close = lines.findIndex((line, i) => i > 0 && DELIMITER.test(line));
171
+ if (close === -1) {
172
+ frontmatterError = {
173
+ message: "Frontmatter block is not closed: add a `---` line after the last key.",
174
+ line: 1,
175
+ column: 1
176
+ };
177
+ bodyStartLine = lines.length + 1;
178
+ } else {
179
+ bodyStartLine = close + 2;
180
+ const parsed = parseYaml(lines.slice(1, close).join("\n"), 2);
181
+ locate = parsed.locate;
182
+ if (parsed.error) frontmatterError = {
183
+ ...parsed.error,
184
+ message: `Invalid YAML: ${parsed.error.message}`
185
+ };
186
+ else if (parsed.value === null || parsed.value === void 0) frontmatter = {};
187
+ else if (isRecord(parsed.value)) frontmatter = parsed.value;
188
+ else frontmatterError = {
189
+ message: "Frontmatter must be a YAML mapping of keys to values.",
190
+ line: 2,
191
+ column: 1
192
+ };
193
+ }
194
+ }
195
+ const { ast, links, footnotes, codeBlocks } = parseMarkdown(lines.map((line, i) => i < bodyStartLine - 1 ? "" : line).join("\n"));
196
+ return {
197
+ path,
198
+ text,
199
+ frontmatter,
200
+ hasFrontmatter,
201
+ ...frontmatterError ? { frontmatterError } : {},
202
+ bodyStartLine,
203
+ ast,
204
+ rawLinks: links,
205
+ footnotes,
206
+ codeBlocks,
207
+ locate
208
+ };
209
+ }
210
+ //#endregion
211
+ //#region src/paths.ts
212
+ /** Bundle-relative POSIX path helpers. No `node:path`: this runs in browsers and Workers. */
213
+ /** Directory of a bundle-relative path (`""` for the root). */
214
+ function dirname(path) {
215
+ const slash = path.lastIndexOf("/");
216
+ return slash === -1 ? "" : path.slice(0, slash);
217
+ }
218
+ function basename(path) {
219
+ return path.slice(path.lastIndexOf("/") + 1);
220
+ }
221
+ /**
222
+ * Join and normalize path segments, resolving `.` and `..`. Returns
223
+ * `undefined` when the result would climb above the root.
224
+ */
225
+ function normalize(...parts) {
226
+ const out = [];
227
+ for (const segment of parts.join("/").split("/")) {
228
+ if (segment === "" || segment === ".") continue;
229
+ if (segment === "..") {
230
+ if (out.length === 0) return void 0;
231
+ out.pop();
232
+ } else out.push(segment);
233
+ }
234
+ return out.join("/");
235
+ }
236
+ /** A URL scheme (`https:`, `mailto:`) or protocol-relative (`//host`) destination. */
237
+ function isExternal(target) {
238
+ return /^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith("//");
239
+ }
240
+ /** Convert a glob (relative to the tree root) to a regular expression.
241
+ * `*` and `?` stay within one path segment, `**` crosses segments, and a
242
+ * trailing `/` matches everything under a directory. */
243
+ function globToRegExp(glob) {
244
+ const pattern = glob.replace(/^\.?\//, "").replace(/\/$/, "/**");
245
+ let source = "";
246
+ for (let i = 0; i < pattern.length; i++) {
247
+ const char = pattern[i];
248
+ if (char === "*" && pattern[i + 1] === "*") {
249
+ const slash = pattern[i + 2] === "/";
250
+ source += slash ? "(?:.*/)?" : ".*";
251
+ i += slash ? 2 : 1;
252
+ } else if (char === "*") source += "[^/]*";
253
+ else if (char === "?") source += "[^/]";
254
+ else source += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
255
+ }
256
+ return new RegExp(`^${source}$`);
257
+ }
258
+ //#endregion
259
+ //#region src/trust.ts
260
+ const STATUSES = [
261
+ "draft",
262
+ "stable",
263
+ "deprecated"
264
+ ];
265
+ /** Lifecycle status (spec §5.4): absent, or not a recognized value, means `stable`. */
266
+ function deriveStatus(value) {
267
+ return STATUSES.includes(value) ? value : "stable";
268
+ }
269
+ function isStatus(value) {
270
+ return STATUSES.includes(value);
271
+ }
272
+ /**
273
+ * Verification events (spec §5.2). A bare `{ by, at }` mapping is a
274
+ * one-element list; entries without a string `by` are skipped.
275
+ */
276
+ function normalizeVerified(value) {
277
+ return (Array.isArray(value) ? value : value === void 0 ? [] : [value]).flatMap((entry) => isRecord(entry) && typeof entry.by === "string" && entry.by !== "" ? [{
278
+ by: entry.by,
279
+ ...typeof entry.at === "string" ? { at: entry.at } : {}
280
+ }] : []);
281
+ }
282
+ /** Trust tier (spec §5.3): `human:` verifiers ⇒ human-reviewed; any other
283
+ * verifier ⇒ machine-confirmed; none ⇒ unverified. */
284
+ function deriveTrustTier(verified) {
285
+ if (verified.some((v) => v.by.startsWith("human:"))) return "human-reviewed";
286
+ return verified.length > 0 ? "machine-confirmed" : "unverified";
287
+ }
288
+ /** Whether `now >= staleAfter` (spec §5.5). Unparseable instants are never stale. */
289
+ function isStaleAt(staleAfter, now) {
290
+ if (staleAfter === void 0) return false;
291
+ const instant = Date.parse(staleAfter);
292
+ return !Number.isNaN(instant) && now.getTime() >= instant;
293
+ }
294
+ function normalizeSources(value) {
295
+ if (!Array.isArray(value)) return [];
296
+ return value.filter(isRecord).map((entry) => {
297
+ const source = {};
298
+ if (typeof entry.id === "string") source.id = entry.id;
299
+ if (typeof entry.resource === "string") source.resource = entry.resource;
300
+ if (typeof entry.title === "string") source.title = entry.title;
301
+ if (typeof entry.author === "string") source.author = entry.author;
302
+ if (typeof entry.usage_count === "number") source.usageCount = entry.usage_count;
303
+ if (typeof entry.last_modified === "string") source.lastModified = entry.last_modified;
304
+ return source;
305
+ });
306
+ }
307
+ //#endregion
308
+ //#region src/tree.ts
309
+ /** Where OKForest keeps per-tree settings (an OKForest convention, not OKF). */
310
+ const SETTINGS_PATH = ".okforest/tree.yaml";
311
+ /**
312
+ * Repository files at the tree root that are not concepts, though the OKF
313
+ * spec letter would make them so. Matched case-insensitively. Extend per tree
314
+ * with `ignore:` globs in `.okforest/tree.yaml`.
315
+ */
316
+ const DEFAULT_IGNORED = [
317
+ "README.md",
318
+ "LICENSE.md",
319
+ "CONTRIBUTING.md",
320
+ "CHANGELOG.md",
321
+ "SECURITY.md",
322
+ "CODE_OF_CONDUCT.md"
323
+ ];
324
+ const RESERVED = /* @__PURE__ */ new Set(["index.md", "log.md"]);
325
+ /**
326
+ * Build a {@link Tree} from files. Pure: no file system access, so the same
327
+ * code runs in Node, browsers, and Workers (see `@okforest/okf/node` for
328
+ * reading a directory). Never throws on malformed content; problems are
329
+ * recorded on the files for `@okforest/validate` to report.
330
+ *
331
+ * Markdown files under hidden directories (any path segment starting with
332
+ * `.`) and `node_modules` are not part of the tree.
333
+ */
334
+ function parseTree(input) {
335
+ const texts = /* @__PURE__ */ new Map();
336
+ for (const file of input) {
337
+ const path = normalize(file.path.replaceAll("\\", "/"));
338
+ if (path) texts.set(path, file.text);
339
+ }
340
+ const files = [...texts.keys()].sort();
341
+ const fileSet = new Set(files);
342
+ const directories = /* @__PURE__ */ new Set([""]);
343
+ for (const path of files) for (let dir = dirname(path); dir !== ""; dir = dirname(dir)) directories.add(dir);
344
+ const settings = readSettings(texts.get(SETTINGS_PATH));
345
+ const ignorePatterns = (settings?.ignore ?? []).map(globToRegExp);
346
+ const defaultIgnored = new Set(DEFAULT_IGNORED.map((name) => name.toLowerCase()));
347
+ const ignored = [];
348
+ const parsed = [];
349
+ for (const path of files) {
350
+ if (!path.endsWith(".md")) continue;
351
+ const segments = path.split("/");
352
+ if (segments.some((s) => s.startsWith(".") || s === "node_modules")) continue;
353
+ if (segments.length === 1 && defaultIgnored.has(path.toLowerCase()) || ignorePatterns.some((pattern) => pattern.test(path))) {
354
+ ignored.push(path);
355
+ continue;
356
+ }
357
+ parsed.push({
358
+ file: readMarkdownFile(path, texts.get(path) ?? ""),
359
+ reserved: RESERVED.has(basename(path))
360
+ });
361
+ }
362
+ const conceptIds = new Set(parsed.filter((p) => !p.reserved).map((p) => p.file.path.slice(0, -3)));
363
+ const resolve = (raw, from) => resolveLink(raw, from, fileSet, directories, conceptIds);
364
+ const concepts = [];
365
+ const reserved = [];
366
+ for (const { file, reserved: isReserved } of parsed) {
367
+ const { rawLinks, ...rest } = file;
368
+ const links = rawLinks.map((raw) => resolve(raw, file.path));
369
+ if (isReserved) reserved.push({
370
+ ...rest,
371
+ links,
372
+ kind: basename(file.path) === "index.md" ? "index" : "log",
373
+ directory: dirname(file.path)
374
+ });
375
+ else concepts.push(buildConcept({
376
+ ...rest,
377
+ links
378
+ }));
379
+ }
380
+ const byId = new Map(concepts.map((c) => [c.id, c]));
381
+ const backlinks = /* @__PURE__ */ new Map();
382
+ for (const concept of concepts) for (const link of concept.links) {
383
+ if (!link.concept) continue;
384
+ const list = backlinks.get(link.concept) ?? [];
385
+ list.push(link);
386
+ backlinks.set(link.concept, list);
387
+ }
388
+ const rootIndex = reserved.find((r) => r.path === "index.md");
389
+ return {
390
+ files,
391
+ concepts,
392
+ reserved,
393
+ ignored,
394
+ ...settings ? { settings } : {},
395
+ ...rootIndex?.frontmatter && "okf_version" in rootIndex.frontmatter ? { okfVersion: rootIndex.frontmatter.okf_version } : {},
396
+ links: [...concepts, ...reserved].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).flatMap((doc) => doc.links),
397
+ concept: (id) => byId.get(id),
398
+ backlinks: (id) => backlinks.get(id) ?? []
399
+ };
400
+ }
401
+ function buildConcept(file) {
402
+ const fm = file.frontmatter ?? {};
403
+ const str = (key) => {
404
+ const value = fm[key];
405
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
406
+ };
407
+ const verified = normalizeVerified(fm.verified);
408
+ const staleAfter = str("stale_after");
409
+ const generated = isRecord(fm.generated) ? {
410
+ ...typeof fm.generated.by === "string" ? { by: fm.generated.by } : {},
411
+ ...typeof fm.generated.at === "string" ? { at: fm.generated.at } : {}
412
+ } : void 0;
413
+ const tags = Array.isArray(fm.tags) ? fm.tags.filter((t) => typeof t === "string") : typeof fm.tags === "string" ? [fm.tags] : [];
414
+ const fields = {
415
+ kind: "concept",
416
+ id: file.path.slice(0, -3),
417
+ tags,
418
+ status: deriveStatus(fm.status),
419
+ verified,
420
+ trustTier: deriveTrustTier(verified),
421
+ sources: normalizeSources(fm.sources),
422
+ isStale: (now = /* @__PURE__ */ new Date()) => isStaleAt(staleAfter, now)
423
+ };
424
+ for (const key of [
425
+ "type",
426
+ "title",
427
+ "description",
428
+ "resource"
429
+ ]) {
430
+ const value = str(key);
431
+ if (value !== void 0) fields[key] = value;
432
+ }
433
+ if (staleAfter !== void 0) fields.staleAfter = staleAfter;
434
+ if (generated) fields.generated = generated;
435
+ return {
436
+ ...file,
437
+ ...fields
438
+ };
439
+ }
440
+ function resolveLink(raw, from, files, directories, conceptIds) {
441
+ const base = {
442
+ from,
443
+ target: raw.target,
444
+ line: raw.line,
445
+ column: raw.column,
446
+ image: raw.image
447
+ };
448
+ const target = raw.target.trim();
449
+ if (isExternal(target)) return {
450
+ ...base,
451
+ kind: "external"
452
+ };
453
+ let path = target.replace(/[?#].*$/, "");
454
+ if (path === "") return {
455
+ ...base,
456
+ kind: "anchor"
457
+ };
458
+ try {
459
+ path = decodeURIComponent(path);
460
+ } catch {}
461
+ const form = path.startsWith("/") ? "absolute" : "relative";
462
+ const resolved = form === "absolute" ? normalize(path) : normalize(dirname(from), path);
463
+ if (resolved === void 0) return {
464
+ ...base,
465
+ kind: "internal",
466
+ form,
467
+ exists: false,
468
+ outside: true
469
+ };
470
+ const isFile = files.has(resolved);
471
+ const isDirectory = !isFile && directories.has(resolved);
472
+ const id = resolved.endsWith(".md") ? resolved.slice(0, -3) : void 0;
473
+ return {
474
+ ...base,
475
+ kind: "internal",
476
+ form,
477
+ resolved,
478
+ exists: isFile || isDirectory,
479
+ ...isDirectory ? { directory: true } : {},
480
+ ...id !== void 0 && conceptIds.has(id) ? { concept: id } : {}
481
+ };
482
+ }
483
+ function readSettings(text) {
484
+ if (text === void 0) return void 0;
485
+ const parsed = parseYaml(text.replace(/^/, "").replace(/\r\n?/g, "\n"), 1);
486
+ const data = parsed.value === null ? {} : isRecord(parsed.value) ? parsed.value : void 0;
487
+ const ignore = Array.isArray(data?.ignore) ? data.ignore.filter((g) => typeof g === "string" && g.trim() !== "") : [];
488
+ const error = parsed.error ?? (data === void 0 ? {
489
+ message: "Settings must be a YAML mapping.",
490
+ line: 1,
491
+ column: 1
492
+ } : void 0);
493
+ return {
494
+ path: SETTINGS_PATH,
495
+ text,
496
+ data,
497
+ ...error ? { error } : {},
498
+ ignore,
499
+ locate: parsed.locate
500
+ };
501
+ }
502
+ //#endregion
503
+ export { deriveTrustTier as a, normalizeSources as c, normalizeText as d, isRecord as f, deriveStatus as i, normalizeVerified as l, SETTINGS_PATH as n, isStaleAt as o, visit as p, parseTree as r, isStatus as s, DEFAULT_IGNORED as t, globToRegExp as u };
@@ -0,0 +1,170 @@
1
+ import { Root } from "mdast";
2
+ //#region src/types.d.ts
3
+ /** A 1-based line and column in a file. */
4
+ interface Position {
5
+ line: number;
6
+ column: number;
7
+ }
8
+ /** A problem found while reading a file, kept for the validator to report. */
9
+ interface Diagnostic {
10
+ message: string;
11
+ line?: number;
12
+ column?: number;
13
+ }
14
+ /** A path into a YAML mapping: keys, or indexes into sequences. */
15
+ type KeyPath = readonly (string | number)[];
16
+ /** OKF v0.2 trust tier, derived from `verified` (spec §5.3). */
17
+ type TrustTier = "unverified" | "machine-confirmed" | "human-reviewed";
18
+ /** OKF v0.2 lifecycle status (spec §5.4). */
19
+ type Status = "draft" | "stable" | "deprecated";
20
+ /** A file handed to {@link parseTree}: a bundle-relative POSIX path and, for
21
+ * markdown and settings files, its text. Other files only need a path, so
22
+ * links to them can be checked. */
23
+ interface TreeFile {
24
+ path: string;
25
+ text?: string;
26
+ }
27
+ /** A markdown link, image, or link reference found in a document body. */
28
+ interface Link {
29
+ /** Bundle-relative path of the file containing the link. */
30
+ from: string;
31
+ /** The destination as written. */
32
+ target: string;
33
+ line: number;
34
+ column: number;
35
+ /** `external`: has a URL scheme; `anchor`: same-document fragment only;
36
+ * `internal`: a path within (or escaping) the bundle. */
37
+ kind: "internal" | "external" | "anchor";
38
+ /** Whether the link is an image. */
39
+ image: boolean;
40
+ /** For internal links: `absolute` (starts with `/`, bundle-relative) or `relative`. */
41
+ form?: "absolute" | "relative";
42
+ /** For internal links: the bundle-relative path the link resolves to
43
+ * (directories have no trailing slash). */
44
+ resolved?: string;
45
+ /** For internal links: the target exists as a file or directory. */
46
+ exists?: boolean;
47
+ /** For internal links: the target is a directory. */
48
+ directory?: boolean;
49
+ /** For internal links: the path climbs above the bundle root. */
50
+ outside?: boolean;
51
+ /** For internal links to a concept: its concept ID. */
52
+ concept?: string;
53
+ }
54
+ /** A markdown footnote reference (`[^label]`), the join key into `sources` ids. */
55
+ interface FootnoteReference {
56
+ label: string;
57
+ line: number;
58
+ column: number;
59
+ }
60
+ /** A fenced or indented code block. */
61
+ interface CodeBlock {
62
+ /** The info-string language (`d2`, `mermaid`, `sql`, ...), if any. */
63
+ lang?: string;
64
+ value: string;
65
+ /** Line of the opening fence (or first line, for indented code). */
66
+ line: number;
67
+ /** Line of the first line of code content. */
68
+ contentLine: number;
69
+ }
70
+ /** What every markdown file in a tree has in common. */
71
+ interface MarkdownFile {
72
+ /** Bundle-relative POSIX path, e.g. `tables/orders.md`. */
73
+ path: string;
74
+ /** The file's text with any byte-order mark removed and CRLF normalized to LF. */
75
+ text: string;
76
+ /** The parsed frontmatter mapping; `undefined` when there is no block or it
77
+ * could not be parsed into a mapping. An empty block is `{}`. */
78
+ frontmatter: Record<string, unknown> | undefined;
79
+ /** Whether the file starts with a `---` frontmatter block (parseable or not). */
80
+ hasFrontmatter: boolean;
81
+ /** Why the frontmatter block could not be read, if it couldn't. */
82
+ frontmatterError?: Diagnostic;
83
+ /** First line after the frontmatter block (1 when there is none). */
84
+ bodyStartLine: number;
85
+ /** The body as mdast, with positions relative to the whole file. */
86
+ ast: Root;
87
+ links: Link[];
88
+ footnotes: FootnoteReference[];
89
+ codeBlocks: CodeBlock[];
90
+ /** Where a frontmatter key (or sequence item) is written, if present. */
91
+ locate(path: KeyPath): Position | undefined;
92
+ }
93
+ /** An entry of a concept's `sources` list (spec §5.1). Fields hold the values
94
+ * as written when they have the expected type, and are absent otherwise. */
95
+ interface Source {
96
+ id?: string;
97
+ resource?: string;
98
+ title?: string;
99
+ author?: string;
100
+ usageCount?: number;
101
+ lastModified?: string;
102
+ }
103
+ /** A verification event (spec §5.2). */
104
+ interface Verification {
105
+ by: string;
106
+ at?: string;
107
+ }
108
+ /** A concept document: any non-reserved `.md` file. */
109
+ interface Concept extends MarkdownFile {
110
+ kind: "concept";
111
+ /** Concept ID: the path without the `.md` suffix (spec §2). */
112
+ id: string;
113
+ type?: string;
114
+ title?: string;
115
+ description?: string;
116
+ resource?: string;
117
+ tags: string[];
118
+ /** Lifecycle status; `stable` when absent or not a recognized value. */
119
+ status: Status;
120
+ generated?: {
121
+ by?: string;
122
+ at?: string;
123
+ };
124
+ /** Verification events, with a bare mapping treated as a one-element list. */
125
+ verified: Verification[];
126
+ trustTier: TrustTier;
127
+ staleAfter?: string;
128
+ sources: Source[];
129
+ /** Whether `now >= stale_after` (spec §5.5). False when there is no valid `stale_after`. */
130
+ isStale(now?: Date): boolean;
131
+ }
132
+ /** A reserved file: `index.md` (spec §8) or `log.md` (spec §9). */
133
+ interface ReservedFile extends MarkdownFile {
134
+ kind: "index" | "log";
135
+ /** Bundle-relative directory the file describes (`""` for the root). */
136
+ directory: string;
137
+ }
138
+ /** `.okforest/tree.yaml`, OKForest's per-tree settings (not part of OKF). */
139
+ interface TreeSettings {
140
+ path: string;
141
+ text: string;
142
+ /** The parsed mapping; `undefined` if it could not be parsed into one. */
143
+ data: Record<string, unknown> | undefined;
144
+ error?: Diagnostic;
145
+ /** Validation ignore globs (`ignore:`), when well-formed. */
146
+ ignore: string[];
147
+ locate(path: KeyPath): Position | undefined;
148
+ }
149
+ /** A tree (an OKF bundle) read into a model. */
150
+ interface Tree {
151
+ /** Every file path in the tree, sorted. */
152
+ files: string[];
153
+ /** Concepts, sorted by path. */
154
+ concepts: Concept[];
155
+ /** `index.md` and `log.md` files, sorted by path. */
156
+ reserved: ReservedFile[];
157
+ /** Markdown files skipped as repository files or by `ignore:` settings. */
158
+ ignored: string[];
159
+ settings?: TreeSettings;
160
+ /** The bundle-root `index.md` `okf_version` value, as written. */
161
+ okfVersion?: unknown;
162
+ /** Every link in every markdown file, in path and position order. */
163
+ links: Link[];
164
+ /** Look up a concept by its concept ID. */
165
+ concept(id: string): Concept | undefined;
166
+ /** Links from concepts (not from `index.md` or `log.md`) to the given concept. */
167
+ backlinks(id: string): Link[];
168
+ }
169
+ //#endregion
170
+ export { KeyPath as a, Position as c, Status as d, Tree as f, Verification as g, TrustTier as h, FootnoteReference as i, ReservedFile as l, TreeSettings as m, Concept as n, Link as o, TreeFile as p, Diagnostic as r, MarkdownFile as s, CodeBlock as t, Source as u };
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@okforest/okf",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Read an Open Knowledge Format (OKF) v0.2 tree into a model: concepts, frontmatter, links, backlinks, trust tiers, staleness, and a metadata inventory. No SDKs or frameworks; runs in Node, browsers, and Workers.",
5
+ "keywords": [
6
+ "okf",
7
+ "open-knowledge-format",
8
+ "knowledge-management",
9
+ "markdown",
10
+ "frontmatter",
11
+ "okforest"
12
+ ],
13
+ "license": "Apache-2.0",
14
+ "author": "Preneur LLC",
15
+ "homepage": "https://okforest.ai",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/okforest/cli.git",
19
+ "directory": "packages/okf"
20
+ },
21
+ "bugs": "https://github.com/okforest/cli/issues",
22
+ "type": "module",
23
+ "main": "./dist/index.mjs",
24
+ "types": "./dist/index.d.mts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.mts",
28
+ "default": "./dist/index.mjs"
29
+ },
30
+ "./node": {
31
+ "types": "./dist/node.d.mts",
32
+ "default": "./dist/node.mjs"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "NOTICE"
38
+ ],
39
+ "sideEffects": false,
40
+ "engines": {
41
+ "node": ">=22"
42
+ },
43
+ "dependencies": {
44
+ "@types/mdast": "^4.0.4",
45
+ "mdast-util-from-markdown": "^2.1.0",
46
+ "mdast-util-gfm-footnote": "^2.1.0",
47
+ "micromark-extension-gfm-footnote": "^2.1.0",
48
+ "yaml": "^2.9.1"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^26.6.5",
52
+ "@vitest/coverage-v8": "^5.0.3",
53
+ "tsdown": "^0.23.0",
54
+ "typescript": "^7.0.2",
55
+ "vitest": "^5.0.3"
56
+ },
57
+ "scripts": {
58
+ "build": "tsdown",
59
+ "test": "vitest run",
60
+ "test:coverage": "vitest run --coverage",
61
+ "typecheck": "tsc --noEmit"
62
+ }
6
63
  }