@typfolio/dev-tools 0.1.0 → 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/README.md +17 -2
- package/dist/index.d.ts +37 -9
- package/dist/index.js +89 -8
- package/dist/sample-source.generated.d.ts +1 -1
- package/dist/sample-source.generated.js +1 -1
- package/package.json +8 -2
package/README.md
CHANGED
|
@@ -17,9 +17,24 @@ try {
|
|
|
17
17
|
}
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
`
|
|
20
|
+
`template` is a template made with `defineTemplate`. The check compiles only the files it declares, with each piece of data's JSON Schema at its `schemaPath`, made from its schema, so a file the template imports without declaring it fails, with what to do.
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
`check` also takes `assets`, the files a template reads besides its data (a logo), exactly as `compile`'s `assets`. A JSON Schema file given there at a data path is used as it is instead of one made from the schema: this is how data without a schema, or a schema without Standard JSON Schema, is checked.
|
|
23
|
+
|
|
24
|
+
`checkTemplate(template, { wasm, fonts, modes?, pdf?, assets? })` is the one-shot form that creates and disposes a checker.
|
|
25
|
+
|
|
26
|
+
`inputSchemaFiles(definitions, { toJSONSchema? })` returns the JSON Schema file of every piece of data these templates and partials read (nested partials included), or of `{ schema, schemaPath }` pairs, by path, as JSON text. It writes nothing: a script writes the files where the editor reads them, and a test compares them, so a schema that changed without its file fails CI. Schemas that implement Standard JSON Schema (`~standard.jsonSchema`, as Zod's do) need no option; for Zod Mini, pass `toJSONSchema: schema => z.toJSONSchema(schema, { io: 'input' })`.
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { inputSchemaFiles } from '@typfolio/dev-tools';
|
|
30
|
+
|
|
31
|
+
// Every template's own schema file and each of its partials', once per path.
|
|
32
|
+
for (const [path, text] of Object.entries(inputSchemaFiles([outcomes, results]))) {
|
|
33
|
+
assert.deepEqual(JSON.parse(await readFile(new URL(path, templatesRoot), 'utf8')), JSON.parse(text), `${path} is out of date`);
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
A check compiles the template once per sample mode (`minimal`, then `full`) the way an editor does, so `input()` builds a sample from the JSON Schema at each data path. A compile error is reported in that mode's result; a malformed template or option is thrown. Nothing is written to disk. See "Build-time checks" in [docs/template-authoring.md](../../docs/template-authoring.md) for the rules and a test recipe.
|
|
23
38
|
|
|
24
39
|
## `inspectPdf`
|
|
25
40
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,37 @@
|
|
|
1
|
-
import { TypstPdfError, type CompilerOptions, type Diagnostic, type PdfOptions, type
|
|
1
|
+
import { TypstPdfError, type AnyTemplate, type Assets, type CompilerOptions, type Diagnostic, type PartialDefinition, type PdfOptions, type StandardSchemaV1 } from '@typfolio/core';
|
|
2
2
|
/** Which sample `@local/typfolio`'s `input()` builds: every property, or only what the schema requires. */
|
|
3
3
|
export type SampleMode = 'minimal' | 'full';
|
|
4
|
-
export interface
|
|
4
|
+
export interface JSONSchemaOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Turns a schema into JSON Schema. Needed only for a schema that does not implement Standard JSON
|
|
7
|
+
* Schema (`~standard.jsonSchema`), such as Zod Mini's: `toJSONSchema: schema => z.toJSONSchema(schema, { io: 'input' })`.
|
|
8
|
+
*/
|
|
9
|
+
toJSONSchema?(schema: StandardSchemaV1): unknown;
|
|
10
|
+
}
|
|
11
|
+
/** A schema and the path its Typst file reads the data from, for a script that cannot import the definitions. */
|
|
12
|
+
export interface SchemaFile {
|
|
13
|
+
readonly schema: StandardSchemaV1;
|
|
14
|
+
readonly schemaPath: string;
|
|
15
|
+
}
|
|
16
|
+
type Definition = AnyTemplate | PartialDefinition | SchemaFile;
|
|
17
|
+
/**
|
|
18
|
+
* The JSON Schema file of each input of these templates, partials (nested ones included) or
|
|
19
|
+
* `{ schema, schemaPath }` pairs, by its path, such as `common/header.schema.json`, as JSON text. Write
|
|
20
|
+
* each next to the Typst files, where its `input(json.with("./header.schema.json"))` reads it in an
|
|
21
|
+
* editor for a sample, and in a test compare the parsed files with these to catch a schema that
|
|
22
|
+
* changed without its file. An input without a schema is left out. Nothing is written here.
|
|
23
|
+
*/
|
|
24
|
+
export declare function inputSchemaFiles(definitions: Definition | readonly Definition[], options?: JSONSchemaOptions): Record<string, string>;
|
|
25
|
+
export interface TemplateCheckOptions extends JSONSchemaOptions {
|
|
5
26
|
/** Defaults to `['minimal', 'full']`. Each mode is a separate compile. */
|
|
6
27
|
modes?: readonly SampleMode[];
|
|
7
|
-
/** Same options as
|
|
28
|
+
/** Same options as `compile`'s `pdf`. */
|
|
8
29
|
pdf?: PdfOptions;
|
|
30
|
+
/**
|
|
31
|
+
* Files the template reads besides its data, such as a logo: as `compile`'s `assets`. A JSON Schema
|
|
32
|
+
* file given here at a data path is used as it is, instead of one made from the schema.
|
|
33
|
+
*/
|
|
34
|
+
assets?: Assets;
|
|
9
35
|
}
|
|
10
36
|
export interface TemplateCheckResult {
|
|
11
37
|
mode: SampleMode;
|
|
@@ -24,16 +50,18 @@ export interface TemplateCheckReport {
|
|
|
24
50
|
}
|
|
25
51
|
export interface TemplateChecker {
|
|
26
52
|
/**
|
|
27
|
-
* Compiles `template` once per mode in editor mode: no runtime marker, so `input()` reads the
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
53
|
+
* Compiles `template` once per mode in editor mode: no runtime marker, so `input()` reads the JSON
|
|
54
|
+
* Schema at each data path (made from the schema, see `inputSchemaFiles`, or given in `assets`) and
|
|
55
|
+
* builds the sample. The template is compiled from the files it declares only: a file it imports
|
|
56
|
+
* without declaring it fails, with what to do. A failed compile is reported in its result;
|
|
57
|
+
* a malformed template or option rejects with `INVALID_REQUEST` or `UNSUPPORTED_OPTION`.
|
|
31
58
|
*/
|
|
32
|
-
check(template:
|
|
59
|
+
check(template: AnyTemplate, options?: TemplateCheckOptions): Promise<TemplateCheckReport>;
|
|
33
60
|
/** Stops accepting checks; waits for an accepted one and frees the compiler. */
|
|
34
61
|
dispose(): Promise<void>;
|
|
35
62
|
}
|
|
36
63
|
/** Same options as `createCompiler`. One active check per checker. */
|
|
37
64
|
export declare function createTemplateChecker(options: CompilerOptions): Promise<TemplateChecker>;
|
|
38
65
|
/** One-shot form of `createTemplateChecker`: creates a checker, runs one check, disposes it. */
|
|
39
|
-
export declare function checkTemplate(template:
|
|
66
|
+
export declare function checkTemplate(template: AnyTemplate, options: CompilerOptions & TemplateCheckOptions): Promise<TemplateCheckReport>;
|
|
67
|
+
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,70 @@
|
|
|
1
1
|
// Dev-time tools. Nothing here is needed at runtime: applications install this package as a devDependency
|
|
2
2
|
// and core never imports it, so none of it (nor the generated sample source it embeds) reaches a production bundle.
|
|
3
|
-
import { TypstPdfError } from '@typfolio/core';
|
|
4
|
-
import { createEngine, initialize,
|
|
3
|
+
import { TypstPdfError, } from '@typfolio/core';
|
|
4
|
+
import { bundledPackageDirectory, createEngine, explainCompileError, initialize, isTemplateDefinition, packageFileMounts, prepareRequest, resolveFonts, } from '@typfolio/core/internal';
|
|
5
5
|
import { sampleFile, sampleSource } from './sample-source.generated.js';
|
|
6
6
|
const sampleModes = ['minimal', 'full'];
|
|
7
|
+
// Each input of these templates, partials and schema files, nested partials included, once per path.
|
|
8
|
+
function inputsOf(definitions) {
|
|
9
|
+
const found = new Map();
|
|
10
|
+
const add = (path, schema) => {
|
|
11
|
+
if (found.has(path) && found.get(path) !== schema) {
|
|
12
|
+
throw new TypstPdfError('INVALID_REQUEST', `Two different schemas read their input from ${path}`);
|
|
13
|
+
}
|
|
14
|
+
found.set(path, schema);
|
|
15
|
+
};
|
|
16
|
+
const visit = (definition) => {
|
|
17
|
+
if (isTemplateDefinition(definition)) {
|
|
18
|
+
for (const slot of definition.inputs)
|
|
19
|
+
add(slot.path, slot.schema);
|
|
20
|
+
}
|
|
21
|
+
else if (definition?.kind === 'typfolio-partial') {
|
|
22
|
+
const partial = definition;
|
|
23
|
+
add(partial.schemaPath, partial.schema);
|
|
24
|
+
for (const nested of Object.values(partial.partials))
|
|
25
|
+
visit(nested);
|
|
26
|
+
}
|
|
27
|
+
else if (typeof definition?.schemaPath === 'string') {
|
|
28
|
+
const file = definition;
|
|
29
|
+
add(file.schemaPath.replace(/^\/+/, ''), file.schema);
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
throw new TypstPdfError('INVALID_REQUEST', 'Expected a defineTemplate(...), a definePartial(...) or { schema, schemaPath }');
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
for (const definition of definitions)
|
|
36
|
+
visit(definition);
|
|
37
|
+
return found;
|
|
38
|
+
}
|
|
39
|
+
function jsonSchemaOf(schema, path, options) {
|
|
40
|
+
if (options.toJSONSchema)
|
|
41
|
+
return options.toJSONSchema(schema);
|
|
42
|
+
const converter = schema['~standard'].jsonSchema;
|
|
43
|
+
if (typeof converter?.input === 'function')
|
|
44
|
+
return converter.input({ target: 'draft-2020-12' });
|
|
45
|
+
throw new TypstPdfError('INVALID_REQUEST', `The schema of ${path} does not implement Standard JSON Schema (~standard.jsonSchema): pass toJSONSchema, for Zod Mini \`schema => z.toJSONSchema(schema, { io: 'input' })\``);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The JSON Schema file of each input of these templates, partials (nested ones included) or
|
|
49
|
+
* `{ schema, schemaPath }` pairs, by its path, such as `common/header.schema.json`, as JSON text. Write
|
|
50
|
+
* each next to the Typst files, where its `input(json.with("./header.schema.json"))` reads it in an
|
|
51
|
+
* editor for a sample, and in a test compare the parsed files with these to catch a schema that
|
|
52
|
+
* changed without its file. An input without a schema is left out. Nothing is written here.
|
|
53
|
+
*/
|
|
54
|
+
export function inputSchemaFiles(definitions, options = {}) {
|
|
55
|
+
const files = {};
|
|
56
|
+
for (const [path, schema] of inputsOf(Array.isArray(definitions) ? definitions : [definitions])) {
|
|
57
|
+
if (schema !== undefined)
|
|
58
|
+
files[path] = `${JSON.stringify(jsonSchemaOf(schema, path, options), null, 2)}\n`;
|
|
59
|
+
}
|
|
60
|
+
return files;
|
|
61
|
+
}
|
|
7
62
|
function parseOptions(options) {
|
|
8
63
|
if (options === undefined)
|
|
9
64
|
return { modes: sampleModes };
|
|
10
65
|
if (!options || typeof options !== 'object' || Array.isArray(options))
|
|
11
66
|
throw new TypstPdfError('INVALID_REQUEST', 'check options must be a plain object');
|
|
12
|
-
const { modes = sampleModes, pdf, ...rest } = options;
|
|
67
|
+
const { modes = sampleModes, pdf, assets, toJSONSchema, ...rest } = options;
|
|
13
68
|
for (const key of Object.keys(rest))
|
|
14
69
|
throw new TypstPdfError('UNSUPPORTED_OPTION', `Unsupported check option ${key}`);
|
|
15
70
|
if (!Array.isArray(modes) || !modes.length)
|
|
@@ -19,7 +74,33 @@ function parseOptions(options) {
|
|
|
19
74
|
throw new TypstPdfError('UNSUPPORTED_OPTION', `Unsupported sample mode ${String(mode)}`);
|
|
20
75
|
if (new Set(modes).size !== modes.length)
|
|
21
76
|
throw new TypstPdfError('INVALID_REQUEST', 'modes must not repeat');
|
|
22
|
-
|
|
77
|
+
if (toJSONSchema !== undefined && typeof toJSONSchema !== 'function')
|
|
78
|
+
throw new TypstPdfError('INVALID_REQUEST', 'toJSONSchema must be a function');
|
|
79
|
+
return { modes, pdf, assets, ...(toJSONSchema === undefined ? {} : { toJSONSchema }) };
|
|
80
|
+
}
|
|
81
|
+
// A template as the editor sees it: its declared files, and each input's JSON Schema at the path its data is read.
|
|
82
|
+
function editorRequest(template, options) {
|
|
83
|
+
const { pdf, assets } = options;
|
|
84
|
+
if (!isTemplateDefinition(template))
|
|
85
|
+
throw new TypstPdfError('INVALID_REQUEST', 'check takes a template made with defineTemplate');
|
|
86
|
+
// A JSON Schema is JSON: mounted like data, where `input(json.with(...))` reads it in the editor branch.
|
|
87
|
+
const schemas = {};
|
|
88
|
+
const given = new Set(Object.keys(assets ?? {}).map(path => path.replace(/^\/+/, '')));
|
|
89
|
+
for (const [path, schema] of inputsOf([template])) {
|
|
90
|
+
if (given.has(path))
|
|
91
|
+
continue;
|
|
92
|
+
if (schema === undefined) {
|
|
93
|
+
throw new TypstPdfError('INVALID_REQUEST', `The data at ${path} has no schema: give its JSON Schema file in assets`);
|
|
94
|
+
}
|
|
95
|
+
schemas[path] = jsonSchemaOf(schema, path, options);
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
entrypoint: template.entrypoint,
|
|
99
|
+
files: template.files,
|
|
100
|
+
documents: schemas,
|
|
101
|
+
...(assets === undefined ? {} : { assets }),
|
|
102
|
+
...(pdf === undefined ? {} : { pdf }),
|
|
103
|
+
};
|
|
23
104
|
}
|
|
24
105
|
/** Same options as `createCompiler`. One active check per checker. */
|
|
25
106
|
export async function createTemplateChecker(options) {
|
|
@@ -39,9 +120,8 @@ export async function createTemplateChecker(options) {
|
|
|
39
120
|
throw new TypstPdfError('DISPOSED', 'The template checker is disposed');
|
|
40
121
|
if (busy)
|
|
41
122
|
throw new TypstPdfError('BUSY', 'The template checker already has an active check');
|
|
42
|
-
const { modes,
|
|
43
|
-
|
|
44
|
-
const prepared = prepareRequest({ template, input: null, pdf });
|
|
123
|
+
const { modes, ...rest } = parseOptions(checkOptions);
|
|
124
|
+
const prepared = prepareRequest(editorRequest(template, rest));
|
|
45
125
|
busy = true;
|
|
46
126
|
let release;
|
|
47
127
|
finished = new Promise(resolve => { release = resolve; });
|
|
@@ -56,7 +136,8 @@ export async function createTemplateChecker(options) {
|
|
|
56
136
|
catch (error) {
|
|
57
137
|
if (!(error instanceof TypstPdfError) || error.code !== 'COMPILATION')
|
|
58
138
|
throw error;
|
|
59
|
-
|
|
139
|
+
const explained = explainCompileError(error, prepared.files);
|
|
140
|
+
results.push({ mode, ok: false, diagnostics: explained.diagnostics, error: explained });
|
|
60
141
|
}
|
|
61
142
|
}
|
|
62
143
|
return { ok: results.every(result => result.ok), results };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const sampleFile = "sample.typ";
|
|
2
|
-
export declare const sampleSource = "// @local/typfolio: sample builder. Not used at runtime.\n//\n// `lib.typ` imports this file only from the editor branch of `input()`, so a compile under Typfolio\n// never loads it (and core does not even mount it). It ships next to `lib.typ` because an editor reads\n// the package folder from disk. `@typfolio/dev-tools` mounts it for build-time template checks.\n//\n// `sample-from-schema(schema, mode: \"full\")` builds a value from a JSON Schema (a dictionary):\n// \"full\" shape-complete, for editor completion: every property, one array item, non-null shapes.\n// \"minimal\" the sparsest value the schema allows, to expose templates that assume optional data.\n// The sample is not validated against the schema.\n\n#let _is-empty(v) = (type(v) == array or type(v) == dictionary) and v.len() == 0\n\n#let _formats = (\n \"date\": \"2024-01-15\",\n \"date-time\": \"2024-01-15T09:30:00Z\",\n \"email\": \"user@example.com\",\n \"uri\": \"https://example.com\",\n \"uuid\": \"123e4567-e89b-12d3-a456-426614174000\",\n)\n\n// Resolves a local \"#/...\" reference against the root schema.\n#let _resolve(root, ref) = {\n let node = root\n for part in ref.slice(2).split(\"/\") {\n node = node.at(part.replace(\"~1\", \"/\").replace(\"~0\", \"~\"))\n }\n node\n}\n\n// `seen` holds the $ref values being expanded on the current path, so a recursive
|
|
2
|
+
export declare const sampleSource = "// @local/typfolio: sample builder. Not used at runtime.\n//\n// `lib.typ` imports this file only from the editor branch of `input()`, so a compile under Typfolio\n// never loads it (and core does not even mount it). It ships next to `lib.typ` because an editor reads\n// the package folder from disk. `@typfolio/dev-tools` mounts it for build-time template checks.\n//\n// `sample-from-schema(schema, mode: \"full\")` builds a value from a JSON Schema (a dictionary):\n// \"full\" shape-complete, for editor completion: every property, one array item, non-null shapes.\n// \"minimal\" the sparsest value the schema allows, to expose templates that assume optional data.\n// In both, an image field (`contentMediaType: \"image/...\"`) is a placeholder image's bytes.\n// The sample is not validated against the schema.\n\n#let _is-empty(v) = (type(v) == array or type(v) == dictionary) and v.len() == 0\n\n// A field that holds the path of an image file says so with `contentMediaType: \"image/...\"`. In the\n// editor and in template checks there is no such file to read, so the sample is the bytes of a grey\n// placeholder image instead, which `image()` draws: write `image(data.logo)`, not `image(\"/\" + ...)`.\n#let _placeholder = bytes(\"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" width=\\\"400\\\" height=\\\"200\\\" viewBox=\\\"0 0 400 200\\\"><rect width=\\\"400\\\" height=\\\"200\\\" fill=\\\"#e6e8eb\\\"/><path d=\\\"M0 0L400 200M400 0L0 200\\\" stroke=\\\"#c4c8cd\\\" stroke-width=\\\"2\\\"/></svg>\")\n#let _is-image(node) = {\n let media = node.at(\"contentMediaType\", default: none)\n type(media) == str and media.starts-with(\"image/\")\n}\n\n#let _formats = (\n \"date\": \"2024-01-15\",\n \"date-time\": \"2024-01-15T09:30:00Z\",\n \"email\": \"user@example.com\",\n \"uri\": \"https://example.com\",\n \"uuid\": \"123e4567-e89b-12d3-a456-426614174000\",\n)\n\n// Resolves a local \"#\" or \"#/...\" reference against the root schema.\n#let _resolve(root, ref) = {\n if ref == \"#\" { return root }\n let node = root\n for part in ref.slice(2).split(\"/\") {\n node = node.at(part.replace(\"~1\", \"/\").replace(\"~0\", \"~\"))\n }\n node\n}\n\n// `seen` holds the $ref values being expanded on the current path. A recursive schema is expanded\n// one level (a tree gets one child) and then cut: the cut value is `_cut`, which an array turns into\n// no items and an object into a missing optional property, so a recursive list ends empty instead\n// of holding `none`. `depth` bounds anything else.\n#let _cut = \"\\u{E000}typfolio-recursion-cut\"\n#let _recursing(seen, ref) = seen.filter(r => r == ref).len() >= 2\n\n// An object's properties from their samples: a cut optional property is left out, a cut required\n// one is `none` (the schema demands an endless value there).\n#let _object(node, sampled) = {\n let required = node.at(\"required\", default: ())\n let out = (:)\n for (key, v) in sampled {\n if v == _cut {\n if key in required { out.insert(key, none) }\n } else {\n out.insert(key, v)\n }\n }\n out\n}\n\n#let _sample(root, node, depth, seen) = {\n if depth > 16 or type(node) != dictionary { return none }\n if _is-image(node) { return _placeholder }\n let candidates = ()\n if \"examples\" in node { candidates += node.at(\"examples\") }\n if \"default\" in node { candidates.push(node.at(\"default\")) }\n // An empty [] or {} default is not preferred over a generated shape.\n let filled = candidates.filter(v => v != none and not _is-empty(v))\n if filled.len() > 0 and type(filled.first()) != dictionary { return filled.first() }\n if \"const\" in node and node.at(\"const\") != none { return node.at(\"const\") }\n if \"enum\" in node {\n let e = node.at(\"enum\").filter(v => v != none)\n if e.len() > 0 { return e.first() }\n }\n if \"$ref\" in node {\n let ref = node.at(\"$ref\")\n if _recursing(seen, ref) { return _cut }\n return _sample(root, _resolve(root, ref), depth + 1, seen + (ref,))\n }\n for key in (\"anyOf\", \"oneOf\") {\n if key in node {\n for branch in node.at(key) {\n let v = _sample(root, branch, depth + 1, seen)\n if v != none and v != _cut { return v }\n }\n }\n }\n if \"allOf\" in node {\n let merged = (:)\n for part in node.at(\"allOf\") {\n let v = _sample(root, part, depth + 1, seen)\n if type(v) == dictionary { merged += v }\n }\n return merged\n }\n let t = node.at(\"type\", default: none)\n if type(t) == array { t = t.filter(x => x != \"null\").at(0, default: \"null\") }\n if t == none {\n if \"properties\" in node { t = \"object\" } else if \"items\" in node { t = \"array\" }\n }\n if t == \"object\" {\n let sampled = (:)\n for (key, sub) in node.at(\"properties\", default: (:)) {\n sampled.insert(key, _sample(root, sub, depth + 1, seen))\n }\n let out = _object(node, sampled)\n // A partial object default fills in the generated shape rather than replacing it.\n if filled.len() > 0 { out += filled.first() }\n return out\n }\n if t == \"array\" {\n let items = node.at(\"items\", default: none)\n if items == none { return () }\n let item = _sample(root, items, depth + 1, seen)\n if item == _cut { return () }\n return range(calc.max(1, node.at(\"minItems\", default: 1))).map(_ => item)\n }\n if t == \"string\" { return _formats.at(node.at(\"format\", default: \"\"), default: \"Sample text\") }\n if t == \"integer\" or t == \"number\" { return node.at(\"minimum\", default: 1) }\n if t == \"boolean\" { return true }\n none\n}\n\n// Minimal mode. Only `required` properties, nullable values are `none`, arrays are empty unless\n// `minItems` says otherwise, `examples` and `default` are ignored. `$ref` and `allOf` follow full mode.\n#let _is-nullable(node) = {\n let t = node.at(\"type\", default: none)\n if t == \"null\" or (type(t) == array and \"null\" in t) { return true }\n for key in (\"anyOf\", \"oneOf\") {\n for branch in node.at(key, default: ()) {\n if type(branch) == dictionary and branch.at(\"type\", default: none) == \"null\" { return true }\n }\n }\n false\n}\n\n#let _minimal(root, node, depth, seen) = {\n if depth > 16 or type(node) != dictionary { return none }\n if _is-nullable(node) { return none }\n if _is-image(node) { return _placeholder }\n if \"const\" in node { return node.at(\"const\") }\n if \"enum\" in node and node.at(\"enum\").len() > 0 { return node.at(\"enum\").first() }\n if \"$ref\" in node {\n let ref = node.at(\"$ref\")\n if _recursing(seen, ref) { return _cut }\n return _minimal(root, _resolve(root, ref), depth + 1, seen + (ref,))\n }\n for key in (\"anyOf\", \"oneOf\") {\n if key in node and node.at(key).len() > 0 {\n let v = _minimal(root, node.at(key).first(), depth + 1, seen)\n return if v == _cut { none } else { v }\n }\n }\n if \"allOf\" in node {\n let merged = (:)\n for part in node.at(\"allOf\") {\n let v = _minimal(root, part, depth + 1, seen)\n if type(v) == dictionary { merged += v }\n }\n return merged\n }\n let t = node.at(\"type\", default: none)\n if type(t) == array { t = t.at(0, default: none) }\n if t == none {\n if \"properties\" in node { t = \"object\" } else if \"items\" in node { t = \"array\" }\n }\n if t == \"object\" {\n let sampled = (:)\n let properties = node.at(\"properties\", default: (:))\n for key in node.at(\"required\", default: ()) {\n sampled.insert(key, _minimal(root, properties.at(key, default: none), depth + 1, seen))\n }\n return _object(node, sampled)\n }\n if t == \"array\" {\n let items = node.at(\"items\", default: none)\n let count = node.at(\"minItems\", default: 0)\n if items == none or count <= 0 { return () }\n let item = _minimal(root, items, depth + 1, seen)\n if item == _cut { return () }\n return range(count).map(_ => item)\n }\n if t == \"string\" { return \"a\" * node.at(\"minLength\", default: 0) }\n if t == \"integer\" or t == \"number\" {\n if \"minimum\" in node { return node.at(\"minimum\") }\n let above = node.at(\"exclusiveMinimum\", default: none)\n if t == \"integer\" and type(above) in (int, float) { return above + 1 }\n return 0\n }\n if t == \"boolean\" { return false }\n none\n}\n\n/// Builds a sample value from a JSON Schema (a dictionary). `mode` is \"full\" or \"minimal\".\n#let sample-from-schema(schema, mode: \"full\") = {\n // The root is itself an expansion of \"#\", so a schema that refers to itself recurses one level too.\n let value = if mode == \"full\" { _sample(schema, schema, 0, (\"#\",)) }\n else if mode == \"minimal\" { _minimal(schema, schema, 0, (\"#\",)) }\n else { panic(\"@local/typfolio: sample mode must be \\\"full\\\" or \\\"minimal\\\", got \" + repr(mode)) }\n if value == _cut { none } else { value }\n}\n";
|
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
// Only @typfolio/dev-tools may import this module; the runtime entry must never reach it.
|
|
4
4
|
// Regenerate with `node tools/generate-typst-package.mjs` (the root `npm run build` does this first).
|
|
5
5
|
export const sampleFile = 'sample.typ';
|
|
6
|
-
export const sampleSource = "// @local/typfolio: sample builder. Not used at runtime.\n//\n// `lib.typ` imports this file only from the editor branch of `input()`, so a compile under Typfolio\n// never loads it (and core does not even mount it). It ships next to `lib.typ` because an editor reads\n// the package folder from disk. `@typfolio/dev-tools` mounts it for build-time template checks.\n//\n// `sample-from-schema(schema, mode: \"full\")` builds a value from a JSON Schema (a dictionary):\n// \"full\" shape-complete, for editor completion: every property, one array item, non-null shapes.\n// \"minimal\" the sparsest value the schema allows, to expose templates that assume optional data.\n// The sample is not validated against the schema.\n\n#let _is-empty(v) = (type(v) == array or type(v) == dictionary) and v.len() == 0\n\n#let _formats = (\n \"date\": \"2024-01-15\",\n \"date-time\": \"2024-01-15T09:30:00Z\",\n \"email\": \"user@example.com\",\n \"uri\": \"https://example.com\",\n \"uuid\": \"123e4567-e89b-12d3-a456-426614174000\",\n)\n\n// Resolves a local \"#/...\" reference against the root schema.\n#let _resolve(root, ref) = {\n let node = root\n for part in ref.slice(2).split(\"/\") {\n node = node.at(part.replace(\"~1\", \"/\").replace(\"~0\", \"~\"))\n }\n node\n}\n\n// `seen` holds the $ref values being expanded on the current path, so a recursive
|
|
6
|
+
export const sampleSource = "// @local/typfolio: sample builder. Not used at runtime.\n//\n// `lib.typ` imports this file only from the editor branch of `input()`, so a compile under Typfolio\n// never loads it (and core does not even mount it). It ships next to `lib.typ` because an editor reads\n// the package folder from disk. `@typfolio/dev-tools` mounts it for build-time template checks.\n//\n// `sample-from-schema(schema, mode: \"full\")` builds a value from a JSON Schema (a dictionary):\n// \"full\" shape-complete, for editor completion: every property, one array item, non-null shapes.\n// \"minimal\" the sparsest value the schema allows, to expose templates that assume optional data.\n// In both, an image field (`contentMediaType: \"image/...\"`) is a placeholder image's bytes.\n// The sample is not validated against the schema.\n\n#let _is-empty(v) = (type(v) == array or type(v) == dictionary) and v.len() == 0\n\n// A field that holds the path of an image file says so with `contentMediaType: \"image/...\"`. In the\n// editor and in template checks there is no such file to read, so the sample is the bytes of a grey\n// placeholder image instead, which `image()` draws: write `image(data.logo)`, not `image(\"/\" + ...)`.\n#let _placeholder = bytes(\"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" width=\\\"400\\\" height=\\\"200\\\" viewBox=\\\"0 0 400 200\\\"><rect width=\\\"400\\\" height=\\\"200\\\" fill=\\\"#e6e8eb\\\"/><path d=\\\"M0 0L400 200M400 0L0 200\\\" stroke=\\\"#c4c8cd\\\" stroke-width=\\\"2\\\"/></svg>\")\n#let _is-image(node) = {\n let media = node.at(\"contentMediaType\", default: none)\n type(media) == str and media.starts-with(\"image/\")\n}\n\n#let _formats = (\n \"date\": \"2024-01-15\",\n \"date-time\": \"2024-01-15T09:30:00Z\",\n \"email\": \"user@example.com\",\n \"uri\": \"https://example.com\",\n \"uuid\": \"123e4567-e89b-12d3-a456-426614174000\",\n)\n\n// Resolves a local \"#\" or \"#/...\" reference against the root schema.\n#let _resolve(root, ref) = {\n if ref == \"#\" { return root }\n let node = root\n for part in ref.slice(2).split(\"/\") {\n node = node.at(part.replace(\"~1\", \"/\").replace(\"~0\", \"~\"))\n }\n node\n}\n\n// `seen` holds the $ref values being expanded on the current path. A recursive schema is expanded\n// one level (a tree gets one child) and then cut: the cut value is `_cut`, which an array turns into\n// no items and an object into a missing optional property, so a recursive list ends empty instead\n// of holding `none`. `depth` bounds anything else.\n#let _cut = \"\\u{E000}typfolio-recursion-cut\"\n#let _recursing(seen, ref) = seen.filter(r => r == ref).len() >= 2\n\n// An object's properties from their samples: a cut optional property is left out, a cut required\n// one is `none` (the schema demands an endless value there).\n#let _object(node, sampled) = {\n let required = node.at(\"required\", default: ())\n let out = (:)\n for (key, v) in sampled {\n if v == _cut {\n if key in required { out.insert(key, none) }\n } else {\n out.insert(key, v)\n }\n }\n out\n}\n\n#let _sample(root, node, depth, seen) = {\n if depth > 16 or type(node) != dictionary { return none }\n if _is-image(node) { return _placeholder }\n let candidates = ()\n if \"examples\" in node { candidates += node.at(\"examples\") }\n if \"default\" in node { candidates.push(node.at(\"default\")) }\n // An empty [] or {} default is not preferred over a generated shape.\n let filled = candidates.filter(v => v != none and not _is-empty(v))\n if filled.len() > 0 and type(filled.first()) != dictionary { return filled.first() }\n if \"const\" in node and node.at(\"const\") != none { return node.at(\"const\") }\n if \"enum\" in node {\n let e = node.at(\"enum\").filter(v => v != none)\n if e.len() > 0 { return e.first() }\n }\n if \"$ref\" in node {\n let ref = node.at(\"$ref\")\n if _recursing(seen, ref) { return _cut }\n return _sample(root, _resolve(root, ref), depth + 1, seen + (ref,))\n }\n for key in (\"anyOf\", \"oneOf\") {\n if key in node {\n for branch in node.at(key) {\n let v = _sample(root, branch, depth + 1, seen)\n if v != none and v != _cut { return v }\n }\n }\n }\n if \"allOf\" in node {\n let merged = (:)\n for part in node.at(\"allOf\") {\n let v = _sample(root, part, depth + 1, seen)\n if type(v) == dictionary { merged += v }\n }\n return merged\n }\n let t = node.at(\"type\", default: none)\n if type(t) == array { t = t.filter(x => x != \"null\").at(0, default: \"null\") }\n if t == none {\n if \"properties\" in node { t = \"object\" } else if \"items\" in node { t = \"array\" }\n }\n if t == \"object\" {\n let sampled = (:)\n for (key, sub) in node.at(\"properties\", default: (:)) {\n sampled.insert(key, _sample(root, sub, depth + 1, seen))\n }\n let out = _object(node, sampled)\n // A partial object default fills in the generated shape rather than replacing it.\n if filled.len() > 0 { out += filled.first() }\n return out\n }\n if t == \"array\" {\n let items = node.at(\"items\", default: none)\n if items == none { return () }\n let item = _sample(root, items, depth + 1, seen)\n if item == _cut { return () }\n return range(calc.max(1, node.at(\"minItems\", default: 1))).map(_ => item)\n }\n if t == \"string\" { return _formats.at(node.at(\"format\", default: \"\"), default: \"Sample text\") }\n if t == \"integer\" or t == \"number\" { return node.at(\"minimum\", default: 1) }\n if t == \"boolean\" { return true }\n none\n}\n\n// Minimal mode. Only `required` properties, nullable values are `none`, arrays are empty unless\n// `minItems` says otherwise, `examples` and `default` are ignored. `$ref` and `allOf` follow full mode.\n#let _is-nullable(node) = {\n let t = node.at(\"type\", default: none)\n if t == \"null\" or (type(t) == array and \"null\" in t) { return true }\n for key in (\"anyOf\", \"oneOf\") {\n for branch in node.at(key, default: ()) {\n if type(branch) == dictionary and branch.at(\"type\", default: none) == \"null\" { return true }\n }\n }\n false\n}\n\n#let _minimal(root, node, depth, seen) = {\n if depth > 16 or type(node) != dictionary { return none }\n if _is-nullable(node) { return none }\n if _is-image(node) { return _placeholder }\n if \"const\" in node { return node.at(\"const\") }\n if \"enum\" in node and node.at(\"enum\").len() > 0 { return node.at(\"enum\").first() }\n if \"$ref\" in node {\n let ref = node.at(\"$ref\")\n if _recursing(seen, ref) { return _cut }\n return _minimal(root, _resolve(root, ref), depth + 1, seen + (ref,))\n }\n for key in (\"anyOf\", \"oneOf\") {\n if key in node and node.at(key).len() > 0 {\n let v = _minimal(root, node.at(key).first(), depth + 1, seen)\n return if v == _cut { none } else { v }\n }\n }\n if \"allOf\" in node {\n let merged = (:)\n for part in node.at(\"allOf\") {\n let v = _minimal(root, part, depth + 1, seen)\n if type(v) == dictionary { merged += v }\n }\n return merged\n }\n let t = node.at(\"type\", default: none)\n if type(t) == array { t = t.at(0, default: none) }\n if t == none {\n if \"properties\" in node { t = \"object\" } else if \"items\" in node { t = \"array\" }\n }\n if t == \"object\" {\n let sampled = (:)\n let properties = node.at(\"properties\", default: (:))\n for key in node.at(\"required\", default: ()) {\n sampled.insert(key, _minimal(root, properties.at(key, default: none), depth + 1, seen))\n }\n return _object(node, sampled)\n }\n if t == \"array\" {\n let items = node.at(\"items\", default: none)\n let count = node.at(\"minItems\", default: 0)\n if items == none or count <= 0 { return () }\n let item = _minimal(root, items, depth + 1, seen)\n if item == _cut { return () }\n return range(count).map(_ => item)\n }\n if t == \"string\" { return \"a\" * node.at(\"minLength\", default: 0) }\n if t == \"integer\" or t == \"number\" {\n if \"minimum\" in node { return node.at(\"minimum\") }\n let above = node.at(\"exclusiveMinimum\", default: none)\n if t == \"integer\" and type(above) in (int, float) { return above + 1 }\n return 0\n }\n if t == \"boolean\" { return false }\n none\n}\n\n/// Builds a sample value from a JSON Schema (a dictionary). `mode` is \"full\" or \"minimal\".\n#let sample-from-schema(schema, mode: \"full\") = {\n // The root is itself an expansion of \"#\", so a schema that refers to itself recurses one level too.\n let value = if mode == \"full\" { _sample(schema, schema, 0, (\"#\",)) }\n else if mode == \"minimal\" { _minimal(schema, schema, 0, (\"#\",)) }\n else { panic(\"@local/typfolio: sample mode must be \\\"full\\\" or \\\"minimal\\\", got \" + repr(mode)) }\n if value == _cut { none } else { value }\n}\n";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@typfolio/dev-tools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Dev-time tools for Typfolio templates: schema-based template checks and PDF inspection (install as a devDependency)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -13,12 +13,18 @@
|
|
|
13
13
|
"homepage": "https://github.com/HelioCampus/typfolio#readme",
|
|
14
14
|
"bugs": { "url": "https://github.com/HelioCampus/typfolio/issues" },
|
|
15
15
|
"files": ["dist", "README.md"],
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
16
17
|
"exports": {
|
|
17
18
|
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
|
|
18
19
|
"./pdf": { "types": "./dist/pdf.d.ts", "import": "./dist/pdf.js" }
|
|
19
20
|
},
|
|
21
|
+
"typesVersions": {
|
|
22
|
+
"*": {
|
|
23
|
+
"pdf": ["./dist/pdf.d.ts"]
|
|
24
|
+
}
|
|
25
|
+
},
|
|
20
26
|
"dependencies": {
|
|
21
|
-
"@typfolio/core": "^0.
|
|
27
|
+
"@typfolio/core": "^0.3.0"
|
|
22
28
|
},
|
|
23
29
|
"peerDependencies": {
|
|
24
30
|
"pdfjs-dist": "^6.3.0"
|