@latex-kit/schema 0.0.0-stage → 0.3.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/esm/types.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ import { z } from 'zod';
2
+ /** A calendar date, `2026-11-25`. Use with the `date` filter. */
3
+ export declare const ISODate: z.ZodString;
4
+ /** An amount and an ISO 4217 currency code. Use with the `money` filter. */
5
+ export declare const Money: z.ZodObject<{
6
+ amount: z.ZodNumber;
7
+ currency: z.ZodString;
8
+ }, z.core.$strip>;
9
+ export declare const Address: z.ZodObject<{
10
+ line1: z.ZodString;
11
+ line2: z.ZodOptional<z.ZodString>;
12
+ city: z.ZodString;
13
+ region: z.ZodOptional<z.ZodString>;
14
+ postalCode: z.ZodOptional<z.ZodString>;
15
+ country: z.ZodOptional<z.ZodString>;
16
+ }, z.core.$strip>;
17
+ /** Someone who signs: a name and, usually, a title. */
18
+ export declare const Signer: z.ZodObject<{
19
+ name: z.ZodString;
20
+ title: z.ZodOptional<z.ZodString>;
21
+ email: z.ZodOptional<z.ZodString>;
22
+ }, z.core.$strip>;
23
+ export declare const Person: z.ZodObject<{
24
+ name: z.ZodString;
25
+ title: z.ZodOptional<z.ZodString>;
26
+ email: z.ZodOptional<z.ZodString>;
27
+ address: z.ZodOptional<z.ZodObject<{
28
+ line1: z.ZodString;
29
+ line2: z.ZodOptional<z.ZodString>;
30
+ city: z.ZodString;
31
+ region: z.ZodOptional<z.ZodString>;
32
+ postalCode: z.ZodOptional<z.ZodString>;
33
+ country: z.ZodOptional<z.ZodString>;
34
+ }, z.core.$strip>>;
35
+ }, z.core.$strip>;
36
+ export declare const Organization: z.ZodObject<{
37
+ name: z.ZodString;
38
+ entityType: z.ZodOptional<z.ZodString>;
39
+ jurisdiction: z.ZodOptional<z.ZodString>;
40
+ address: z.ZodOptional<z.ZodObject<{
41
+ line1: z.ZodString;
42
+ line2: z.ZodOptional<z.ZodString>;
43
+ city: z.ZodString;
44
+ region: z.ZodOptional<z.ZodString>;
45
+ postalCode: z.ZodOptional<z.ZodString>;
46
+ country: z.ZodOptional<z.ZodString>;
47
+ }, z.core.$strip>>;
48
+ signer: z.ZodOptional<z.ZodObject<{
49
+ name: z.ZodString;
50
+ title: z.ZodOptional<z.ZodString>;
51
+ email: z.ZodOptional<z.ZodString>;
52
+ }, z.core.$strip>>;
53
+ }, z.core.$strip>;
54
+ /** One side of an agreement: a person or an organization. */
55
+ export declare const Party: z.ZodObject<{
56
+ kind: z.ZodOptional<z.ZodEnum<{
57
+ person: "person";
58
+ organization: "organization";
59
+ }>>;
60
+ name: z.ZodString;
61
+ entityType: z.ZodOptional<z.ZodString>;
62
+ jurisdiction: z.ZodOptional<z.ZodString>;
63
+ title: z.ZodOptional<z.ZodString>;
64
+ email: z.ZodOptional<z.ZodString>;
65
+ address: z.ZodOptional<z.ZodObject<{
66
+ line1: z.ZodString;
67
+ line2: z.ZodOptional<z.ZodString>;
68
+ city: z.ZodString;
69
+ region: z.ZodOptional<z.ZodString>;
70
+ postalCode: z.ZodOptional<z.ZodString>;
71
+ country: z.ZodOptional<z.ZodString>;
72
+ }, z.core.$strip>>;
73
+ signer: z.ZodOptional<z.ZodObject<{
74
+ name: z.ZodString;
75
+ title: z.ZodOptional<z.ZodString>;
76
+ email: z.ZodOptional<z.ZodString>;
77
+ }, z.core.$strip>>;
78
+ }, z.core.$strip>;
79
+ /** Text in several languages, keyed by language tag: `{ en: "…", ja: "…" }`. */
80
+ export declare const Localized: z.ZodRecord<z.ZodString, z.ZodString>;
81
+ export type ISODate = z.infer<typeof ISODate>;
82
+ export type Money = z.infer<typeof Money>;
83
+ export type Address = z.infer<typeof Address>;
84
+ export type Signer = z.infer<typeof Signer>;
85
+ export type Person = z.infer<typeof Person>;
86
+ export type Organization = z.infer<typeof Organization>;
87
+ export type Party = z.infer<typeof Party>;
88
+ export type Localized = z.infer<typeof Localized>;
package/esm/types.js ADDED
@@ -0,0 +1,49 @@
1
+ import { z } from 'zod';
2
+ /** A calendar date, `2026-11-25`. Use with the `date` filter. */
3
+ export const ISODate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'expected a date like 2026-11-25');
4
+ /** An amount and an ISO 4217 currency code. Use with the `money` filter. */
5
+ export const Money = z.object({
6
+ amount: z.number(),
7
+ currency: z.string().regex(/^[A-Z]{3}$/, 'expected a currency code like USD'),
8
+ });
9
+ export const Address = z.object({
10
+ line1: z.string(),
11
+ line2: z.string().optional(),
12
+ city: z.string(),
13
+ region: z.string().optional(),
14
+ postalCode: z.string().optional(),
15
+ country: z.string().optional(),
16
+ });
17
+ /** Someone who signs: a name and, usually, a title. */
18
+ export const Signer = z.object({
19
+ name: z.string(),
20
+ title: z.string().optional(),
21
+ email: z.string().optional(),
22
+ });
23
+ export const Person = z.object({
24
+ name: z.string(),
25
+ title: z.string().optional(),
26
+ email: z.string().optional(),
27
+ address: Address.optional(),
28
+ });
29
+ export const Organization = z.object({
30
+ name: z.string(),
31
+ /** e.g. "Delaware corporation", "Kabushiki Kaisha" */
32
+ entityType: z.string().optional(),
33
+ jurisdiction: z.string().optional(),
34
+ address: Address.optional(),
35
+ signer: Signer.optional(),
36
+ });
37
+ /** One side of an agreement: a person or an organization. */
38
+ export const Party = z.object({
39
+ kind: z.enum(['person', 'organization']).optional(),
40
+ name: z.string(),
41
+ entityType: z.string().optional(),
42
+ jurisdiction: z.string().optional(),
43
+ title: z.string().optional(),
44
+ email: z.string().optional(),
45
+ address: Address.optional(),
46
+ signer: Signer.optional(),
47
+ });
48
+ /** Text in several languages, keyed by language tag: `{ en: "…", ja: "…" }`. */
49
+ export const Localized = z.record(z.string(), z.string());
package/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from './docid';
2
+ export * from './load';
3
+ export * from './record';
4
+ export * from './ref';
5
+ export * from './schema';
6
+ export * from './types';
7
+ export { z } from 'zod';
package/index.js ADDED
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.z = void 0;
18
+ __exportStar(require("./docid"), exports);
19
+ __exportStar(require("./load"), exports);
20
+ __exportStar(require("./record"), exports);
21
+ __exportStar(require("./ref"), exports);
22
+ __exportStar(require("./schema"), exports);
23
+ __exportStar(require("./types"), exports);
24
+ var zod_1 = require("zod");
25
+ Object.defineProperty(exports, "z", { enumerable: true, get: function () { return zod_1.z; } });
package/load.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ export declare const DATA_EXTENSIONS: string[];
2
+ export declare class LoadError extends Error {
3
+ readonly file: string;
4
+ constructor(message: string, file: string);
5
+ }
6
+ /**
7
+ * Resolve these module names to fixed paths when loading project files, e.g.
8
+ * `{ 'latex-kit': '/…/latex-kit' }`. The CLI uses it so schema.ts and records
9
+ * can `import { z } from 'latex-kit'` even in a folder with no node_modules.
10
+ */
11
+ export declare function setModuleAliases(map: Record<string, string>): void;
12
+ /** Load a TypeScript or JavaScript module and return all its exports. */
13
+ export declare function loadModule(file: string): Promise<Record<string, unknown>>;
14
+ /** Load a data file: JSON, YAML, or the default export of a TS/JS module. */
15
+ export declare function loadFile(file: string): Promise<unknown>;
package/load.js ADDED
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoadError = exports.DATA_EXTENSIONS = void 0;
4
+ exports.setModuleAliases = setModuleAliases;
5
+ exports.loadModule = loadModule;
6
+ exports.loadFile = loadFile;
7
+ const fs_1 = require("fs");
8
+ const jiti_1 = require("jiti");
9
+ const path_1 = require("path");
10
+ const yaml_1 = require("yaml");
11
+ exports.DATA_EXTENSIONS = ['.json', '.yaml', '.yml', '.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'];
12
+ const MODULE_EXTENSIONS = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'];
13
+ class LoadError extends Error {
14
+ file;
15
+ constructor(message, file) {
16
+ super(message);
17
+ this.file = file;
18
+ this.name = 'LoadError';
19
+ }
20
+ }
21
+ exports.LoadError = LoadError;
22
+ let jiti = null;
23
+ let aliases = {};
24
+ /**
25
+ * Resolve these module names to fixed paths when loading project files, e.g.
26
+ * `{ 'latex-kit': '/…/latex-kit' }`. The CLI uses it so schema.ts and records
27
+ * can `import { z } from 'latex-kit'` even in a folder with no node_modules.
28
+ */
29
+ function setModuleAliases(map) {
30
+ aliases = { ...map };
31
+ jiti = null;
32
+ }
33
+ function loader() {
34
+ // fsCache off: never write a transpile cache into the user's project
35
+ jiti ??= (0, jiti_1.createJiti)((0, path_1.join)(process.cwd(), 'latex-kit.js'), { fsCache: false, moduleCache: false, interopDefault: false, alias: aliases });
36
+ return jiti;
37
+ }
38
+ /** Load a TypeScript or JavaScript module and return all its exports. */
39
+ async function loadModule(file) {
40
+ try {
41
+ return (await loader().import(file));
42
+ }
43
+ catch (e) {
44
+ throw new LoadError(`could not load ${file}: ${e.message}`, file);
45
+ }
46
+ }
47
+ /** Load a data file: JSON, YAML, or the default export of a TS/JS module. */
48
+ async function loadFile(file) {
49
+ const ext = (0, path_1.extname)(file).toLowerCase();
50
+ if (MODULE_EXTENSIONS.includes(ext)) {
51
+ const mod = await loadModule(file);
52
+ if (!('default' in mod))
53
+ throw new LoadError(`${file} has no default export`, file);
54
+ return mod.default;
55
+ }
56
+ let text;
57
+ try {
58
+ text = (0, fs_1.readFileSync)(file, 'utf8');
59
+ }
60
+ catch {
61
+ throw new LoadError(`cannot read ${file}`, file);
62
+ }
63
+ try {
64
+ if (ext === '.json')
65
+ return JSON.parse(text);
66
+ if (ext === '.yaml' || ext === '.yml')
67
+ return (0, yaml_1.parse)(text, { prettyErrors: true });
68
+ }
69
+ catch (e) {
70
+ throw new LoadError(`${file}: ${e.message}`, file);
71
+ }
72
+ throw new LoadError(`unsupported data file type ${ext} (use ${exports.DATA_EXTENSIONS.join(', ')})`, file);
73
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@latex-kit/schema",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Typed data for latex-kit documents: zod schemas, shared types, references, document IDs",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/latex-kit",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/latex-kit"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/latex-kit/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "makage assets",
24
+ "clean": "makage clean",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "makage build",
27
+ "build:dev": "makage build --dev",
28
+ "lint": "eslint . --fix",
29
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",
30
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
31
+ },
32
+ "devDependencies": {
33
+ "makage": "^0.8.0"
34
+ },
35
+ "keywords": [
36
+ "latex",
37
+ "zod",
38
+ "json-schema",
39
+ "documents"
40
+ ],
41
+ "dependencies": {
42
+ "jiti": "^2.7.0",
43
+ "schema-typescript": "^0.14.4",
44
+ "yaml": "^2.9.1",
45
+ "zod": "^4.6.7"
46
+ },
47
+ "gitHead": "023ede48131a32e9250ec48b0dde17e71c6a1536"
48
+ }
package/record.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { z } from 'zod';
2
+ /** The file that describes one document: which template, its ID, its data. */
3
+ export declare const DocumentRecord: z.ZodObject<{
4
+ $schema: z.ZodOptional<z.ZodString>;
5
+ template: z.ZodString;
6
+ docId: z.ZodOptional<z.ZodString>;
7
+ locale: z.ZodOptional<z.ZodString>;
8
+ data: z.ZodUnknown;
9
+ }, z.core.$strict>;
10
+ export type DocumentRecord = z.infer<typeof DocumentRecord>;
11
+ export interface LoadedDocument {
12
+ file: string;
13
+ record: DocumentRecord;
14
+ /** `data` with every reference resolved. */
15
+ data: unknown;
16
+ /** Shared record files the document read through references. */
17
+ refFiles: string[];
18
+ }
19
+ export declare class RecordError extends Error {
20
+ readonly file: string;
21
+ constructor(message: string, file: string);
22
+ }
23
+ export declare function loadDocument(file: string, options: {
24
+ dataDir: string;
25
+ }): Promise<LoadedDocument>;
package/record.js ADDED
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecordError = exports.DocumentRecord = void 0;
4
+ exports.loadDocument = loadDocument;
5
+ const zod_1 = require("zod");
6
+ const load_1 = require("./load");
7
+ const ref_1 = require("./ref");
8
+ /** The file that describes one document: which template, its ID, its data. */
9
+ exports.DocumentRecord = zod_1.z
10
+ .object({
11
+ $schema: zod_1.z.string().optional(),
12
+ template: zod_1.z.string().min(1),
13
+ docId: zod_1.z.string().min(1).optional(),
14
+ locale: zod_1.z.string().optional(),
15
+ data: zod_1.z.unknown(),
16
+ })
17
+ .strict();
18
+ class RecordError extends Error {
19
+ file;
20
+ constructor(message, file) {
21
+ super(message);
22
+ this.file = file;
23
+ this.name = 'RecordError';
24
+ }
25
+ }
26
+ exports.RecordError = RecordError;
27
+ async function loadDocument(file, options) {
28
+ const raw = await (0, load_1.loadFile)(file);
29
+ const parsed = exports.DocumentRecord.safeParse(raw);
30
+ if (!parsed.success) {
31
+ const msg = parsed.error.issues.map((i) => `${i.path.join('.') || 'record'}: ${i.message}`).join('; ');
32
+ throw new RecordError(`${file}: not a document record (${msg}). Expected { template, docId?, locale?, data }`, file);
33
+ }
34
+ const { value, files } = await (0, ref_1.resolveRefs)(parsed.data.data ?? {}, { dataDir: options.dataDir });
35
+ return { file, record: parsed.data, data: value, refFiles: files };
36
+ }
package/ref.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /** A pointer to a shared record: `{ "$ref": "people/avery" }`. */
2
+ export interface Ref {
3
+ $ref: string;
4
+ }
5
+ /** Point at a shared record in the data folder, e.g. `ref('people/avery')`. */
6
+ export declare function ref(id: string): Ref;
7
+ export declare function isRef(value: unknown): value is Ref;
8
+ export declare class RefError extends Error {
9
+ readonly at: string;
10
+ constructor(message: string, at: string);
11
+ }
12
+ export interface ResolveOptions {
13
+ /** Folder that holds shared records: `<dataDir>/<collection>/<id>.json`. */
14
+ dataDir: string;
15
+ load?: (file: string) => Promise<unknown>;
16
+ }
17
+ /** Find the file for `people/avery` (or `people:avery`). */
18
+ export declare function refFile(id: string, dataDir: string): string | null;
19
+ /**
20
+ * Replace every `{ "$ref": "collection/id" }` with the record it names,
21
+ * recursively. Returns the resolved value and every file it read.
22
+ */
23
+ export declare function resolveRefs(value: unknown, options: ResolveOptions): Promise<{
24
+ value: unknown;
25
+ files: string[];
26
+ }>;
package/ref.js ADDED
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RefError = void 0;
4
+ exports.ref = ref;
5
+ exports.isRef = isRef;
6
+ exports.refFile = refFile;
7
+ exports.resolveRefs = resolveRefs;
8
+ const fs_1 = require("fs");
9
+ const path_1 = require("path");
10
+ const load_1 = require("./load");
11
+ /** Point at a shared record in the data folder, e.g. `ref('people/avery')`. */
12
+ function ref(id) {
13
+ return { $ref: id };
14
+ }
15
+ function isRef(value) {
16
+ return (!!value &&
17
+ typeof value === 'object' &&
18
+ !Array.isArray(value) &&
19
+ Object.keys(value).length === 1 &&
20
+ typeof value.$ref === 'string');
21
+ }
22
+ /** A plain `{}` object, also when it was created in another realm (vm, jest). */
23
+ function isPlainObject(v) {
24
+ if (Object.prototype.toString.call(v) !== '[object Object]')
25
+ return false;
26
+ const proto = Object.getPrototypeOf(v);
27
+ return proto === null || Object.getPrototypeOf(proto) === null;
28
+ }
29
+ class RefError extends Error {
30
+ at;
31
+ constructor(message, at) {
32
+ super(message);
33
+ this.at = at;
34
+ this.name = 'RefError';
35
+ }
36
+ }
37
+ exports.RefError = RefError;
38
+ /** Find the file for `people/avery` (or `people:avery`). */
39
+ function refFile(id, dataDir) {
40
+ const norm = id.replace(':', '/');
41
+ if (!/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_.-]+)+$/.test(norm) || norm.split('/').includes('..')) {
42
+ throw new RefError(`invalid reference "${id}" (use collection/id, like people/avery)`, id);
43
+ }
44
+ const base = (0, path_1.resolve)(dataDir, norm);
45
+ const rel = (0, path_1.relative)((0, path_1.resolve)(dataDir), base);
46
+ if (rel.startsWith('..') || (0, path_1.isAbsolute)(rel))
47
+ throw new RefError(`reference "${id}" leaves the data folder`, id);
48
+ for (const ext of load_1.DATA_EXTENSIONS) {
49
+ if ((0, fs_1.existsSync)(base + ext))
50
+ return base + ext;
51
+ }
52
+ return null;
53
+ }
54
+ /**
55
+ * Replace every `{ "$ref": "collection/id" }` with the record it names,
56
+ * recursively. Returns the resolved value and every file it read.
57
+ */
58
+ async function resolveRefs(value, options) {
59
+ const load = options.load ?? load_1.loadFile;
60
+ const files = new Set();
61
+ const cache = new Map();
62
+ const walk = async (v, path, stack) => {
63
+ if (isRef(v)) {
64
+ const id = v.$ref.replace(':', '/');
65
+ if (stack.includes(id))
66
+ throw new RefError(`reference cycle: ${[...stack, id].join(' → ')}`, path);
67
+ const file = refFile(id, options.dataDir);
68
+ if (!file)
69
+ throw new RefError(`${path}: no record for "${v.$ref}" in ${(0, path_1.join)(options.dataDir, id)}.{json,yaml,ts,…}`, path);
70
+ files.add(file);
71
+ if (!cache.has(file))
72
+ cache.set(file, await load(file));
73
+ return walk(cache.get(file), path, [...stack, id]);
74
+ }
75
+ if (Array.isArray(v))
76
+ return Promise.all(v.map((x, i) => walk(x, `${path}.${i}`, stack)));
77
+ if (isPlainObject(v)) {
78
+ const out = {};
79
+ for (const [k, x] of Object.entries(v))
80
+ out[k] = await walk(x, path ? `${path}.${k}` : k, stack);
81
+ return out;
82
+ }
83
+ return v;
84
+ };
85
+ const resolved = await walk(value, '', []);
86
+ return { value: resolved, files: [...files] };
87
+ }
package/schema.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ export type JsonSchema = Record<string, unknown>;
3
+ /** What a template's schema.ts may export besides its default schema. */
4
+ export interface TemplateMeta {
5
+ /** Prefix for minted document IDs, e.g. "NDA". Default: the template name. */
6
+ docIdPrefix?: string;
7
+ /** Default locale for records that do not set one. */
8
+ locale?: string;
9
+ /** TeX engine for this template. Default: lualatex. */
10
+ engine?: 'lualatex' | 'xelatex' | 'pdflatex';
11
+ title?: string;
12
+ }
13
+ export interface TemplateSchema {
14
+ schema: z.ZodType;
15
+ meta: TemplateMeta;
16
+ }
17
+ export declare function isZodSchema(value: unknown): value is z.ZodType;
18
+ /** Load `templates/<name>/schema.ts`: a default-exported zod schema and optional `meta`. */
19
+ export declare function loadTemplateSchema(file: string): Promise<TemplateSchema>;
20
+ export interface Issue {
21
+ path: string;
22
+ message: string;
23
+ }
24
+ export declare function validate(schema: z.ZodType, value: unknown): {
25
+ ok: true;
26
+ value: unknown;
27
+ } | {
28
+ ok: false;
29
+ issues: Issue[];
30
+ };
31
+ /** JSON Schema of the data, as the record files are written (before defaults/transforms). */
32
+ export declare function toJsonSchema(schema: z.ZodType): JsonSchema;
33
+ /** JSON Schema for a whole document record of one template, for editor autocomplete. */
34
+ export declare function documentJsonSchema(template: string, data: JsonSchema): JsonSchema;
35
+ /** TypeScript declarations for a template's data, named after the template. */
36
+ export declare function generateTypes(name: string, data: JsonSchema): string;
package/schema.js ADDED
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isZodSchema = isZodSchema;
4
+ exports.loadTemplateSchema = loadTemplateSchema;
5
+ exports.validate = validate;
6
+ exports.toJsonSchema = toJsonSchema;
7
+ exports.documentJsonSchema = documentJsonSchema;
8
+ exports.generateTypes = generateTypes;
9
+ const schema_typescript_1 = require("schema-typescript");
10
+ const zod_1 = require("zod");
11
+ const load_1 = require("./load");
12
+ function isZodSchema(value) {
13
+ return !!value && typeof value === 'object' && typeof value.safeParse === 'function' && '_zod' in value;
14
+ }
15
+ /** Load `templates/<name>/schema.ts`: a default-exported zod schema and optional `meta`. */
16
+ async function loadTemplateSchema(file) {
17
+ const mod = await (0, load_1.loadModule)(file);
18
+ const schema = mod.default;
19
+ if (!isZodSchema(schema)) {
20
+ throw new Error(`${file}: the default export must be a zod schema, e.g. export default z.object({ … })`);
21
+ }
22
+ return { schema, meta: mod.meta ?? {} };
23
+ }
24
+ function validate(schema, value) {
25
+ const r = schema.safeParse(value);
26
+ if (r.success)
27
+ return { ok: true, value: r.data };
28
+ return {
29
+ ok: false,
30
+ issues: r.error.issues.map((i) => ({ path: i.path.map(String).join('.') || '(root)', message: i.message })),
31
+ };
32
+ }
33
+ /** JSON Schema of the data, as the record files are written (before defaults/transforms). */
34
+ function toJsonSchema(schema) {
35
+ return zod_1.z.toJSONSchema(schema, { io: 'input', unrepresentable: 'any' });
36
+ }
37
+ /** JSON Schema for a whole document record of one template, for editor autocomplete. */
38
+ function documentJsonSchema(template, data) {
39
+ const { $schema, $defs, ...dataSchema } = data;
40
+ return {
41
+ $schema: $schema ?? 'https://json-schema.org/draft/2020-12/schema',
42
+ title: `${template} document`,
43
+ type: 'object',
44
+ properties: {
45
+ $schema: { type: 'string' },
46
+ template: { const: template },
47
+ docId: { type: 'string', description: 'Minted on the first final build; never reuse one.' },
48
+ locale: { type: 'string', description: 'BCP 47 language tag, e.g. en-US or ja-JP.' },
49
+ data: dataSchema,
50
+ },
51
+ required: ['template', 'data'],
52
+ additionalProperties: false,
53
+ ...($defs ? { $defs } : {}),
54
+ };
55
+ }
56
+ /** TypeScript declarations for a template's data, named after the template. */
57
+ function generateTypes(name, data) {
58
+ const title = name.replace(/(^|[-_ /])(\w)/g, (_m, _s, c) => c.toUpperCase()) + 'Data';
59
+ return (0, schema_typescript_1.generateTypeScript)({ ...data, title }, {
60
+ useSingleQuotes: true,
61
+ strictTypeSafety: true,
62
+ });
63
+ }