@open-captable/cli 0.0.0-stage → 0.2.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.md +60 -0
- package/README.md +85 -2
- package/build/ObjectTypeSchemaMap.js +146 -0
- package/build/SchemaComposer.js +835 -0
- package/build/SchemaDereferencer.js +207 -0
- package/build/schemas.json +1 -0
- package/cli.mjs +97 -0
- package/lib/export.mjs +148 -0
- package/lib/input.mjs +29 -0
- package/lib/remote.mjs +102 -0
- package/lib/schema.mjs +147 -0
- package/package.json +38 -4
package/cli.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import { exportRecords, verifyDirectory } from "./lib/export.mjs";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { catalog, loadSchemas } from "./lib/schema.mjs";
|
|
6
|
+
import { records } from "./lib/input.mjs";
|
|
7
|
+
|
|
8
|
+
const help = `ocf describe TYPE
|
|
9
|
+
ocf object TYPE [--in FILE|-]
|
|
10
|
+
ocf export FILE|DIR|- --issuer FILE --as-of YYYY-MM-DD --out DIR
|
|
11
|
+
ocf validate FILE|DIR|- [--format json|jsonl]
|
|
12
|
+
Schema source: --schema-dir DIR | --ocf-version VERSION | --schema-ref BRANCH|TAG|SHA
|
|
13
|
+
Options: --json (structured errors), --help`;
|
|
14
|
+
|
|
15
|
+
let resolvedSha;
|
|
16
|
+
async function main() {
|
|
17
|
+
const {
|
|
18
|
+
values,
|
|
19
|
+
positionals: [command, target, ...extra],
|
|
20
|
+
} = parseArgs({
|
|
21
|
+
allowPositionals: true,
|
|
22
|
+
options: {
|
|
23
|
+
issuer: { type: "string" },
|
|
24
|
+
"as-of": { type: "string" },
|
|
25
|
+
out: { type: "string" },
|
|
26
|
+
in: { type: "string" },
|
|
27
|
+
format: { type: "string" },
|
|
28
|
+
"ocf-version": { type: "string" },
|
|
29
|
+
"schema-ref": { type: "string" },
|
|
30
|
+
"schema-dir": { type: "string" },
|
|
31
|
+
json: { type: "boolean" },
|
|
32
|
+
help: { type: "boolean", short: "h" },
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
if (values.help) {
|
|
36
|
+
console.log(help);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (
|
|
40
|
+
!target ||
|
|
41
|
+
extra.length ||
|
|
42
|
+
!["describe", "object", "validate", "export"].includes(command)
|
|
43
|
+
)
|
|
44
|
+
throw new Error(help);
|
|
45
|
+
const schemas = catalog(
|
|
46
|
+
await loadSchemas(values, (sha) => {
|
|
47
|
+
resolvedSha = sha;
|
|
48
|
+
})
|
|
49
|
+
);
|
|
50
|
+
if (command === "describe") {
|
|
51
|
+
console.log(JSON.stringify(schemas.describe(target), null, 2));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (command === "object") {
|
|
55
|
+
const rows = await records(values.in ?? "-", values.format);
|
|
56
|
+
if (rows.length !== 1) throw new Error("Expected one object");
|
|
57
|
+
const [{ data, source }] = rows;
|
|
58
|
+
if (!data || typeof data !== "object" || Array.isArray(data))
|
|
59
|
+
throw new Error(source + " expected an object");
|
|
60
|
+
if (Object.hasOwn(data, "object_type") && data.object_type !== target)
|
|
61
|
+
throw new Error(source + " /object_type conflicts with " + target);
|
|
62
|
+
const object = { ...data, object_type: target };
|
|
63
|
+
schemas.validate(object, source);
|
|
64
|
+
console.log(JSON.stringify(object));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (command === "export") return exportRecords(target, values, schemas);
|
|
68
|
+
if (target !== "-" && (await stat(target)).isDirectory())
|
|
69
|
+
return verifyDirectory(target, schemas);
|
|
70
|
+
for (const { data, source } of await records(target, values.format)) {
|
|
71
|
+
if (data?.file_type) schemas.checkFile(data.file_type, data, source);
|
|
72
|
+
else schemas.validate(data, source);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
main()
|
|
77
|
+
.then(() => {
|
|
78
|
+
if (resolvedSha)
|
|
79
|
+
console.error(
|
|
80
|
+
process.argv.includes("--json")
|
|
81
|
+
? JSON.stringify({ schemaCommit: resolvedSha })
|
|
82
|
+
: "Schema commit " + resolvedSha
|
|
83
|
+
);
|
|
84
|
+
})
|
|
85
|
+
.catch((error) => {
|
|
86
|
+
console.error(
|
|
87
|
+
process.argv.includes("--json")
|
|
88
|
+
? JSON.stringify({
|
|
89
|
+
schemaCommit: resolvedSha,
|
|
90
|
+
errors: error.errors ?? [{ message: error.message }],
|
|
91
|
+
})
|
|
92
|
+
: [resolvedSha && "Schema commit " + resolvedSha, error.message]
|
|
93
|
+
.filter(Boolean)
|
|
94
|
+
.join("\n")
|
|
95
|
+
);
|
|
96
|
+
process.exitCode = 1;
|
|
97
|
+
});
|
package/lib/export.mjs
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
lstat,
|
|
4
|
+
mkdir,
|
|
5
|
+
mkdtemp,
|
|
6
|
+
readdir,
|
|
7
|
+
readFile,
|
|
8
|
+
realpath,
|
|
9
|
+
rename,
|
|
10
|
+
rm,
|
|
11
|
+
stat,
|
|
12
|
+
writeFile,
|
|
13
|
+
} from "node:fs/promises";
|
|
14
|
+
import {
|
|
15
|
+
basename,
|
|
16
|
+
dirname,
|
|
17
|
+
isAbsolute,
|
|
18
|
+
join,
|
|
19
|
+
relative,
|
|
20
|
+
resolve,
|
|
21
|
+
sep,
|
|
22
|
+
} from "node:path";
|
|
23
|
+
import { records } from "./input.mjs";
|
|
24
|
+
|
|
25
|
+
const manifestType = "OCF_MANIFEST_FILE";
|
|
26
|
+
const manifestName = "Manifest.ocf.json";
|
|
27
|
+
const md5 = (bytes) => createHash("md5").update(bytes).digest("hex");
|
|
28
|
+
const serialized = (data) => JSON.stringify(data, null, 2) + "\n";
|
|
29
|
+
|
|
30
|
+
function categories(schemas) {
|
|
31
|
+
const manifest = schemas.files.get(manifestType);
|
|
32
|
+
const result = new Map();
|
|
33
|
+
for (const field of Object.keys(manifest.properties).filter((key) =>
|
|
34
|
+
key.endsWith("_files")
|
|
35
|
+
)) {
|
|
36
|
+
const type = "OCF_" + field.slice(0, -6).toUpperCase() + "_FILE";
|
|
37
|
+
const schema = schemas.files.get(type);
|
|
38
|
+
if (!schema) throw new Error("Missing file schema for " + field);
|
|
39
|
+
const filename = basename(new URL(schema.$id).pathname).replace(
|
|
40
|
+
/File\.schema\.json$/,
|
|
41
|
+
".ocf.json"
|
|
42
|
+
);
|
|
43
|
+
result.set(type, { field, filename });
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function containedFile(root, filepath) {
|
|
49
|
+
if (isAbsolute(filepath))
|
|
50
|
+
throw new Error("Expected relative manifest path: " + filepath);
|
|
51
|
+
const path = await realpath(join(root, filepath));
|
|
52
|
+
const rel = relative(root, path);
|
|
53
|
+
if (!rel || rel === ".." || rel.startsWith(".." + sep) || isAbsolute(rel))
|
|
54
|
+
throw new Error("Path outside export: " + filepath);
|
|
55
|
+
if (!(await stat(path)).isFile())
|
|
56
|
+
throw new Error("Expected file: " + filepath);
|
|
57
|
+
return path;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function verifyDirectory(dir, schemas) {
|
|
61
|
+
const root = await realpath(dir);
|
|
62
|
+
const path = await containedFile(root, manifestName);
|
|
63
|
+
const manifest = JSON.parse(await readFile(path, "utf8"));
|
|
64
|
+
schemas.checkFile(manifestType, manifest, path);
|
|
65
|
+
for (const [type, { field }] of categories(schemas)) {
|
|
66
|
+
for (const { filepath, md5: expected } of manifest[field] ?? []) {
|
|
67
|
+
const file = await containedFile(root, filepath);
|
|
68
|
+
const bytes = await readFile(file);
|
|
69
|
+
if (md5(bytes) !== expected.toLowerCase())
|
|
70
|
+
throw new Error(filepath + " MD5 checksum mismatch");
|
|
71
|
+
schemas.checkFile(type, JSON.parse(bytes), file);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function inputs(target, issuer) {
|
|
77
|
+
if (target === "-" || !(await stat(target)).isDirectory()) return [target];
|
|
78
|
+
const issuerPath = await realpath(issuer);
|
|
79
|
+
const files = [];
|
|
80
|
+
for (const entry of await readdir(target, { withFileTypes: true })) {
|
|
81
|
+
if (!entry.isFile() || !/\.jsonl?$/i.test(entry.name)) continue;
|
|
82
|
+
const path = join(target, entry.name);
|
|
83
|
+
if ((await realpath(path)) !== issuerPath) files.push(path);
|
|
84
|
+
}
|
|
85
|
+
return files.sort();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function exportRecords(target, options, schemas) {
|
|
89
|
+
const { issuer: issuerFile, out, "as-of": asOf } = options;
|
|
90
|
+
if (!issuerFile || !out || !asOf)
|
|
91
|
+
throw new Error(
|
|
92
|
+
"export requires --issuer FILE --as-of YYYY-MM-DD --out DIR"
|
|
93
|
+
);
|
|
94
|
+
const destination = resolve(out);
|
|
95
|
+
// Publishing by rename keeps a failed export from leaving half-written files.
|
|
96
|
+
const existing = await lstat(destination).catch((error) => {
|
|
97
|
+
if (error.code !== "ENOENT") throw error;
|
|
98
|
+
});
|
|
99
|
+
if (
|
|
100
|
+
existing &&
|
|
101
|
+
(!existing.isDirectory() || (await readdir(destination)).length)
|
|
102
|
+
)
|
|
103
|
+
throw new Error("Output must be a new or empty directory: " + out);
|
|
104
|
+
|
|
105
|
+
const issuer = JSON.parse(await readFile(issuerFile, "utf8"));
|
|
106
|
+
const manifestSchema = schemas.files.get(manifestType);
|
|
107
|
+
const manifest = {
|
|
108
|
+
file_type: manifestType,
|
|
109
|
+
ocf_version: schemas.manifestVersion(),
|
|
110
|
+
issuer,
|
|
111
|
+
as_of: asOf,
|
|
112
|
+
generated_at: new Date().toISOString(),
|
|
113
|
+
};
|
|
114
|
+
const groups = new Map();
|
|
115
|
+
const fileCategories = categories(schemas);
|
|
116
|
+
for (const file of await inputs(target, issuerFile)) {
|
|
117
|
+
for (const { data, source } of await records(file, options.format)) {
|
|
118
|
+
schemas.validate(data, source);
|
|
119
|
+
const type = schemas.routes.get(data.object_type);
|
|
120
|
+
if (!fileCategories.has(type))
|
|
121
|
+
throw new Error(
|
|
122
|
+
source + " cannot place " + data.object_type + " in an items file"
|
|
123
|
+
);
|
|
124
|
+
if (!groups.has(type)) groups.set(type, []);
|
|
125
|
+
groups.get(type).push(data);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
129
|
+
const staged = await mkdtemp(join(dirname(destination), ".ocf-export-"));
|
|
130
|
+
try {
|
|
131
|
+
for (const [type, { field, filename }] of fileCategories) {
|
|
132
|
+
const required = manifestSchema.required.includes(field);
|
|
133
|
+
const needsFile =
|
|
134
|
+
required && manifestSchema.properties[field].minItems > 0;
|
|
135
|
+
if (groups.has(type) || needsFile) {
|
|
136
|
+
const items = groups.get(type) ?? [];
|
|
137
|
+
const bytes = serialized({ file_type: type, items });
|
|
138
|
+
await writeFile(join(staged, filename), bytes);
|
|
139
|
+
manifest[field] = [{ filepath: "./" + filename, md5: md5(bytes) }];
|
|
140
|
+
} else if (required) manifest[field] = [];
|
|
141
|
+
}
|
|
142
|
+
await writeFile(join(staged, manifestName), serialized(manifest));
|
|
143
|
+
await verifyDirectory(staged, schemas);
|
|
144
|
+
await rename(staged, destination);
|
|
145
|
+
} finally {
|
|
146
|
+
await rm(staged, { recursive: true, force: true });
|
|
147
|
+
}
|
|
148
|
+
}
|
package/lib/input.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { text } from "node:stream/consumers";
|
|
3
|
+
|
|
4
|
+
function parse(raw, source) {
|
|
5
|
+
try {
|
|
6
|
+
return JSON.parse(raw);
|
|
7
|
+
} catch (error) {
|
|
8
|
+
throw new Error(source + " " + error.message);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function records(file, format) {
|
|
13
|
+
const source = file === "-" ? "<stdin>" : file;
|
|
14
|
+
const raw =
|
|
15
|
+
file === "-" ? await text(process.stdin) : await readFile(file, "utf8");
|
|
16
|
+
const selected = format ?? (file.endsWith(".jsonl") ? "jsonl" : "json");
|
|
17
|
+
if (selected === "jsonl") {
|
|
18
|
+
return raw.split(/\r?\n/).flatMap((line, i) => {
|
|
19
|
+
if (!line.trim()) return [];
|
|
20
|
+
const location = source + ":" + (i + 1);
|
|
21
|
+
return [{ data: parse(line, location), source: location }];
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
if (selected !== "json") throw new Error("Expected format json or jsonl");
|
|
25
|
+
const data = parse(raw, source);
|
|
26
|
+
return Array.isArray(data)
|
|
27
|
+
? data.map((item, i) => ({ data: item, source: source + "[" + i + "]" }))
|
|
28
|
+
: [{ data, source }];
|
|
29
|
+
}
|
package/lib/remote.mjs
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
const repository = "Open-Cap-Table-Coalition/Open-Cap-Format-OCF";
|
|
7
|
+
const api = "https://api.github.com/repos/" + repository;
|
|
8
|
+
const fullSha = /^[0-9a-f]{40}$/i;
|
|
9
|
+
const versionNumber = /^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/;
|
|
10
|
+
|
|
11
|
+
async function fetchJson(url) {
|
|
12
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(30000) });
|
|
13
|
+
if (!response.ok) throw new Error(url + " returned HTTP " + response.status);
|
|
14
|
+
return response.json();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function inventory(sha, get) {
|
|
18
|
+
const tree = await get(api + "/git/trees/" + sha + "?recursive=1");
|
|
19
|
+
if (tree.truncated) throw new Error("Incomplete GitHub tree for " + sha);
|
|
20
|
+
const paths = tree.tree
|
|
21
|
+
.filter(
|
|
22
|
+
(entry) =>
|
|
23
|
+
entry.type === "blob" &&
|
|
24
|
+
entry.path.startsWith("schema/") &&
|
|
25
|
+
entry.path.endsWith(".schema.json")
|
|
26
|
+
)
|
|
27
|
+
.map((entry) => entry.path.slice(7));
|
|
28
|
+
if (!paths.includes("files/OCFManifestFile.schema.json"))
|
|
29
|
+
throw new Error("Missing OCF manifest schema at " + sha);
|
|
30
|
+
return paths;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function remoteSchemas(
|
|
34
|
+
options,
|
|
35
|
+
reportSha,
|
|
36
|
+
{
|
|
37
|
+
get = fetchJson,
|
|
38
|
+
cacheDir = join(
|
|
39
|
+
process.env.XDG_CACHE_HOME || join(homedir(), ".cache"),
|
|
40
|
+
"open-captable",
|
|
41
|
+
"faker",
|
|
42
|
+
"schemas-v1"
|
|
43
|
+
),
|
|
44
|
+
} = {}
|
|
45
|
+
) {
|
|
46
|
+
const version = options["ocf-version"];
|
|
47
|
+
const ref = version === undefined ? options["schema-ref"] : "v" + version;
|
|
48
|
+
if (version !== undefined && !versionNumber.test(version))
|
|
49
|
+
throw new Error("Expected an OCF release version such as 1.2.0");
|
|
50
|
+
if (!ref || ref === "." || ref === "..")
|
|
51
|
+
throw new Error("Expected a GitHub branch, tag, or commit");
|
|
52
|
+
const resolveCommit = async () => {
|
|
53
|
+
if (fullSha.test(ref)) return ref.toLowerCase();
|
|
54
|
+
const { sha } = await get(api + "/commits/" + encodeURIComponent(ref));
|
|
55
|
+
if (!fullSha.test(sha))
|
|
56
|
+
throw new Error("GitHub did not return a commit SHA for " + ref);
|
|
57
|
+
return sha;
|
|
58
|
+
};
|
|
59
|
+
const github = version === undefined;
|
|
60
|
+
const commit = github ? await resolveCommit() : undefined;
|
|
61
|
+
if (github) reportSha(commit);
|
|
62
|
+
const file = join(
|
|
63
|
+
cacheDir,
|
|
64
|
+
github ? "github-" + commit + ".json" : "release-" + version + ".json"
|
|
65
|
+
);
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// GitHub supplies the filename inventory. Every schema body comes from the selected source.
|
|
73
|
+
const paths = await inventory(commit ?? (await resolveCommit()), get);
|
|
74
|
+
const base = github
|
|
75
|
+
? "https://raw.githubusercontent.com/" +
|
|
76
|
+
repository +
|
|
77
|
+
"/" +
|
|
78
|
+
commit +
|
|
79
|
+
"/schema/"
|
|
80
|
+
: "https://schema.opencaptablecoalition.com/v/" + version + "/";
|
|
81
|
+
const schemas = Object.create(null);
|
|
82
|
+
for (let offset = 0; offset < paths.length; offset += 8) {
|
|
83
|
+
await Promise.all(
|
|
84
|
+
paths.slice(offset, offset + 8).map(async (path) => {
|
|
85
|
+
const url = base + path.split("/").map(encodeURIComponent).join("/");
|
|
86
|
+
const schema = await get(url);
|
|
87
|
+
if (typeof schema.$id !== "string")
|
|
88
|
+
throw new Error("Missing schema ID at " + url);
|
|
89
|
+
schemas[path] = schema;
|
|
90
|
+
})
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
await mkdir(cacheDir, { recursive: true });
|
|
94
|
+
const temp = file + "." + randomUUID() + ".tmp";
|
|
95
|
+
try {
|
|
96
|
+
await writeFile(temp, JSON.stringify(schemas), { flag: "wx" });
|
|
97
|
+
await rename(temp, file);
|
|
98
|
+
} finally {
|
|
99
|
+
await rm(temp, { force: true });
|
|
100
|
+
}
|
|
101
|
+
return schemas;
|
|
102
|
+
}
|
package/lib/schema.mjs
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { remoteSchemas } from "./remote.mjs";
|
|
4
|
+
import Ajv from "ajv";
|
|
5
|
+
import addFormats from "ajv-formats";
|
|
6
|
+
import {
|
|
7
|
+
buildSchemaRegistry,
|
|
8
|
+
STABILITY_KEYWORD,
|
|
9
|
+
STABILITY_LEVELS,
|
|
10
|
+
VERSION_DISPATCHER_KEYWORD,
|
|
11
|
+
} from "../build/SchemaComposer.js";
|
|
12
|
+
import { buildObjectTypeSchemaMap } from "../build/ObjectTypeSchemaMap.js";
|
|
13
|
+
import { dereferenceSchema } from "../build/SchemaDereferencer.js";
|
|
14
|
+
|
|
15
|
+
export async function localSchemas(root, prefix = "") {
|
|
16
|
+
const schemas = {};
|
|
17
|
+
for (const entry of await readdir(join(root, prefix), {
|
|
18
|
+
withFileTypes: true,
|
|
19
|
+
})) {
|
|
20
|
+
const path = prefix + entry.name;
|
|
21
|
+
if (entry.isDirectory())
|
|
22
|
+
Object.assign(schemas, await localSchemas(root, path + "/"));
|
|
23
|
+
if (entry.isFile() && path.endsWith(".schema.json"))
|
|
24
|
+
schemas[path] = JSON.parse(await readFile(join(root, path), "utf8"));
|
|
25
|
+
}
|
|
26
|
+
return schemas;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function loadSchemas(options, reportSha) {
|
|
30
|
+
const selected = ["schema-dir", "schema-ref", "ocf-version"].filter(
|
|
31
|
+
(name) => options[name] !== undefined
|
|
32
|
+
);
|
|
33
|
+
if (selected.length > 1)
|
|
34
|
+
throw new Error(
|
|
35
|
+
"Choose one schema source: --schema-dir, --ocf-version, or --schema-ref"
|
|
36
|
+
);
|
|
37
|
+
if (selected.includes("schema-ref") || selected.includes("ocf-version"))
|
|
38
|
+
return remoteSchemas(options, reportSha);
|
|
39
|
+
if (options["schema-dir"]) return localSchemas(options["schema-dir"]);
|
|
40
|
+
return JSON.parse(
|
|
41
|
+
await readFile(new URL("../build/schemas.json", import.meta.url), "utf8")
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function catalog(schemas) {
|
|
46
|
+
const registry = buildSchemaRegistry(Object.values(schemas));
|
|
47
|
+
const partition = (name) =>
|
|
48
|
+
Object.entries(schemas)
|
|
49
|
+
.filter(([path]) => path.startsWith(name + "/"))
|
|
50
|
+
.map(([, schema]) => schema);
|
|
51
|
+
const types = schemas["enums/ObjectType.schema.json"]?.enum;
|
|
52
|
+
if (!types)
|
|
53
|
+
throw new Error("Schema source is missing enums/ObjectType.schema.json");
|
|
54
|
+
const ids = buildObjectTypeSchemaMap(partition("objects"), types, {
|
|
55
|
+
registry,
|
|
56
|
+
});
|
|
57
|
+
const ajv = new Ajv({
|
|
58
|
+
schemas: Object.values(schemas),
|
|
59
|
+
allErrors: true,
|
|
60
|
+
strictTypes: false,
|
|
61
|
+
ownProperties: true,
|
|
62
|
+
});
|
|
63
|
+
ajv.addKeyword({
|
|
64
|
+
keyword: STABILITY_KEYWORD,
|
|
65
|
+
metaSchema: { enum: [...STABILITY_LEVELS] },
|
|
66
|
+
});
|
|
67
|
+
ajv.addKeyword({
|
|
68
|
+
keyword: VERSION_DISPATCHER_KEYWORD,
|
|
69
|
+
metaSchema: { type: "boolean" },
|
|
70
|
+
});
|
|
71
|
+
addFormats(ajv);
|
|
72
|
+
function objectSchema(type) {
|
|
73
|
+
if (typeof type !== "string" || !Object.hasOwn(ids, type))
|
|
74
|
+
throw new Error("Unknown object_type: " + JSON.stringify(type));
|
|
75
|
+
return registry[ids[type]];
|
|
76
|
+
}
|
|
77
|
+
function check(schema, data, source) {
|
|
78
|
+
const validate = ajv.getSchema(schema.$id);
|
|
79
|
+
if (validate(data)) return;
|
|
80
|
+
const errors = validate.errors.map(
|
|
81
|
+
({ instancePath, keyword, params, message }) => {
|
|
82
|
+
const property = params.missingProperty ?? params.additionalProperty;
|
|
83
|
+
const path =
|
|
84
|
+
property === undefined
|
|
85
|
+
? instancePath
|
|
86
|
+
: instancePath +
|
|
87
|
+
"/" +
|
|
88
|
+
property.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
89
|
+
return { source, path, keyword, message };
|
|
90
|
+
}
|
|
91
|
+
);
|
|
92
|
+
throw Object.assign(
|
|
93
|
+
new Error(
|
|
94
|
+
errors
|
|
95
|
+
.map((e) => [source, e.path, e.message].filter(Boolean).join(" "))
|
|
96
|
+
.join("\n")
|
|
97
|
+
),
|
|
98
|
+
{ errors }
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
const files = new Map(
|
|
102
|
+
partition("files").map((schema) => [
|
|
103
|
+
schema.properties.file_type.const,
|
|
104
|
+
schema,
|
|
105
|
+
])
|
|
106
|
+
);
|
|
107
|
+
const routes = new Map();
|
|
108
|
+
for (const [fileType, schema] of files) {
|
|
109
|
+
const items = schema.properties.items?.items;
|
|
110
|
+
if (!items) continue;
|
|
111
|
+
const members = (items.oneOf ?? items.anyOf ?? [items]).map(
|
|
112
|
+
(item) => registry[item.$ref]
|
|
113
|
+
);
|
|
114
|
+
const memberTypes = buildObjectTypeSchemaMap(members, types, { registry });
|
|
115
|
+
for (const type of Object.keys(memberTypes)) routes.set(type, fileType);
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
files,
|
|
119
|
+
manifestVersion() {
|
|
120
|
+
const rule = files.get("OCF_MANIFEST_FILE").properties.ocf_version;
|
|
121
|
+
// Older prereleases list recognized versions in chronological order.
|
|
122
|
+
const version = rule.const ?? (registry[rule.$ref] ?? rule).enum?.at(-1);
|
|
123
|
+
if (!version)
|
|
124
|
+
throw new Error(
|
|
125
|
+
"Cannot determine the export version from the manifest schema"
|
|
126
|
+
);
|
|
127
|
+
return version;
|
|
128
|
+
},
|
|
129
|
+
routes,
|
|
130
|
+
checkFile(expectedType, data, source) {
|
|
131
|
+
const schema = files.get(expectedType);
|
|
132
|
+
if (!schema)
|
|
133
|
+
throw new Error(source + " unknown file type " + expectedType);
|
|
134
|
+
check(schema, data, source);
|
|
135
|
+
},
|
|
136
|
+
describe: (type) => dereferenceSchema(objectSchema(type), registry),
|
|
137
|
+
validate(data, source) {
|
|
138
|
+
let schema;
|
|
139
|
+
try {
|
|
140
|
+
schema = objectSchema(data?.object_type);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
throw new Error(source + " /object_type " + error.message);
|
|
143
|
+
}
|
|
144
|
+
check(schema, data, source);
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-captable/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Command-line tools for authoring and validating Open Cap Format records",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"ocf": "./cli.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"cli.mjs",
|
|
11
|
+
"lib/",
|
|
12
|
+
"build/",
|
|
13
|
+
"LICENSE.md"
|
|
14
|
+
],
|
|
15
|
+
"license": "SEE LICENSE IN LICENSE.md",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/Open-Cap-Table-Coalition/Open-Cap-Format-OCF.git",
|
|
19
|
+
"directory": "packages/cli"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=22"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc -p tsconfig.json && node scripts/bundle.mjs",
|
|
26
|
+
"prepack": "npm run build",
|
|
27
|
+
"pretest": "npm run build",
|
|
28
|
+
"test": "node --test test/*.mjs"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"ajv": "^8.17.1",
|
|
32
|
+
"ajv-formats": "^3.0.1"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"typescript": "~5.9.3"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
}
|
|
40
|
+
}
|