rapier-math 2.7.0 → 3.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/README.md +23 -32
- package/dist/accessible.d.ts +2 -2
- package/dist/classic.d.ts +1 -2
- package/dist/cli.mjs +438 -0
- package/dist/combined.d.ts +2 -2
- package/dist/delimiters.mjs +56 -17
- package/dist/index.mjs +1 -1
- package/dist/integration.d.ts +1 -1
- package/dist/markdown-it.d.ts +2 -0
- package/dist/markdown-rules.mjs +22 -5
- package/dist/rapier-math.js +1 -1
- package/dist/rehype.d.ts +1 -1
- package/docs/api.md +53 -49
- package/docs/font-source.md +24 -24
- package/docs/formula-dark.svg +1 -0
- package/docs/formula-light.svg +1 -0
- package/docs/math-components.json +6 -6
- package/docs/math-resources.json +47 -41
- package/docs/semantics.md +39 -36
- package/examples/README.md +7 -7
- package/package.json +6 -3
- package/skills/rapier-math/SKILL.md +60 -0
- package/src/math/classic.js +1 -1
- package/src/math/package-layout.mjs +2 -2
- package/src/math/package-readme.mjs +23 -32
- package/src/tools/build-math.mjs +10 -3
- package/CHANGELOG.md +0 -10
package/README.md
CHANGED
|
@@ -1,50 +1,41 @@
|
|
|
1
1
|
# Rapier Math
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## Use
|
|
3
|
+
TeX to SVG or MathML, synchronously and offline. Latin Modern outlines are embedded in the SVG, so there are no font requests and no runtime downloads. No dependencies.
|
|
6
4
|
|
|
7
5
|
```sh
|
|
8
|
-
|
|
6
|
+
npx rapier-math add
|
|
9
7
|
```
|
|
10
8
|
|
|
9
|
+
Installs into npm, plain HTML, React, Vue, Svelte, Astro or Next projects, or run `npm install rapier-math`.
|
|
10
|
+
|
|
11
11
|
```js
|
|
12
12
|
import {renderToString} from 'rapier-math';
|
|
13
|
-
|
|
13
|
+
|
|
14
|
+
const svg = renderToString(String.raw`\frac{-b\pm\sqrt{b^2-4ac}}{2a}`);
|
|
14
15
|
```
|
|
15
16
|
|
|
16
|
-
|
|
17
|
-
`globalThis.RapierMath`. The native ESM entry is [dist/index.mjs](dist/index.mjs).
|
|
18
|
-
For one-file copying or inline-script embedding, use the classic file above. The native
|
|
19
|
-
ESM entry imports relative `src/math/` modules: install/serve the whole package or bundle
|
|
20
|
-
that import; copying only `dist/index.mjs` is insufficient. A CDN must retain that graph
|
|
21
|
-
or bundle it. Formula rendering stays synchronous and offline after its chosen script
|
|
22
|
-
or module graph has loaded.
|
|
17
|
+
Try it in [Rapier](https://rapier.website): type \$x^2\$.
|
|
23
18
|
|
|
24
|
-
|
|
25
|
-
`rapier-math/combined` for one-parse SVG and MathML, or `rapier-math/accessible` with its stylesheet
|
|
26
|
-
for host composition. All return synchronously. Type declarations accompany the runtime files.
|
|
19
|
+
## Entry points
|
|
27
20
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
-
|
|
31
|
-
-
|
|
32
|
-
-
|
|
21
|
+
| Import | Gives |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| `rapier-math` | SVG with the font embedded |
|
|
24
|
+
| `rapier-math/mathml` | Native MathML, no font |
|
|
25
|
+
| `rapier-math/combined` | SVG and MathML from one parse |
|
|
26
|
+
| `rapier-math/accessible` | Accessible output for your own layout, with `rapier-math/accessible.css` |
|
|
27
|
+
| `rapier-math/markdown-it`, `rapier-math/rehype` | Markdown integrations. Your parser stays in charge |
|
|
28
|
+
| `rapier-math/stream` | Formulas in streamed text, such as model output |
|
|
29
|
+
| `rapier-math/classic` | [dist/rapier-math.js](dist/rapier-math.js): one file, `globalThis.RapierMath` |
|
|
33
30
|
|
|
34
|
-
|
|
31
|
+
Types ship with every entry. The classic file is the one to copy or inline: 742,684 bytes, 421,701 gzipped, font included. The ES modules import `src/math/`, so serve or bundle the whole package rather than copying `dist/index.mjs` alone.
|
|
35
32
|
|
|
36
|
-
|
|
37
|
-
modules in `src/math/` directly, sharing one parser without a duplicate generated renderer. Build
|
|
38
|
-
tools live in `src/tools/`. Optional adapters have one source copy in `dist/`. Examples and documentation each
|
|
39
|
-
have their own directory. Only the current release is kept in this checkout.
|
|
33
|
+
[API](docs/api.md) · [MathML and accessibility](docs/semantics.md) · [Examples](examples/README.md) · [Font](docs/font-source.md) · [Changes](https://github.com/jackskip22/rapier-math/releases)
|
|
40
34
|
|
|
41
|
-
|
|
35
|
+
## Build
|
|
42
36
|
|
|
43
|
-
|
|
37
|
+
`node src/tools/build-math.mjs --package .` regenerates `dist/` from `src/math/`.
|
|
44
38
|
|
|
45
|
-
|
|
46
|
-
licensed under the GUST Font License. [LICENSE](LICENSE) contains both complete grants.
|
|
47
|
-
[Component provenance](docs/math-components.json) and [source hashes](docs/math-resources.json)
|
|
48
|
-
travel with the package.
|
|
39
|
+
## License
|
|
49
40
|
|
|
50
|
-
|
|
41
|
+
Code: MIT. Embedded Latin Modern outlines and metrics: GUST Font License. Both are in [LICENSE](LICENSE). [Components](docs/math-components.json) and [source hashes](docs/math-resources.json) ship with the package.
|
package/dist/accessible.d.ts
CHANGED
|
@@ -6,5 +6,5 @@ export interface AccessibleResult extends SemanticRenderResult {
|
|
|
6
6
|
/** Authored links use visible native MathML, with standalone SVG still returned. */
|
|
7
7
|
presentation: 'svg-mathml' | 'mathml' | 'refused';
|
|
8
8
|
}
|
|
9
|
-
/** Include accessible.css when inserting the
|
|
10
|
-
export function renderAccessible(source: unknown, options?: RenderOptions): AccessibleResult;
|
|
9
|
+
/** Include accessible.css when inserting the composition. Incomplete source is not repaired. */
|
|
10
|
+
export function renderAccessible(source: unknown, options?: Omit<RenderOptions, 'preview' | 'caret'>): AccessibleResult;
|
package/dist/classic.d.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
import type RapierMath from './index.js';
|
|
3
2
|
import type {toMathML} from './mathml.js';
|
|
4
3
|
import type {renderWithMathML} from './combined.js';
|
|
5
4
|
declare global {
|
|
6
|
-
|
|
5
|
+
var RapierMath: typeof import('./index.js').default & Readonly<{
|
|
7
6
|
toMathML: typeof toMathML; renderWithMathML: typeof renderWithMathML;
|
|
8
7
|
}>;
|
|
9
8
|
}
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
// npx rapier-math add [place] [--path <dir>] [--from <spec>] [--json]
|
|
4
|
+
// npx rapier-math remove [place] [--path <dir>] [--json]
|
|
5
|
+
import {createHash, randomBytes} from 'node:crypto';
|
|
6
|
+
import {spawnSync} from 'node:child_process';
|
|
7
|
+
import {constants, existsSync, readFileSync} from 'node:fs';
|
|
8
|
+
import {mkdir, lstat, open, readdir, readFile, realpath, rename, rm, rmdir, writeFile} from 'node:fs/promises';
|
|
9
|
+
import {dirname, join, resolve} from 'node:path';
|
|
10
|
+
import {fileURLToPath} from 'node:url';
|
|
11
|
+
|
|
12
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
// In the published package, cli.mjs lives at dist/cli.mjs with package.json one folder up.
|
|
14
|
+
const OWN_ROOT = existsSync(join(HERE, '../package.json')) && existsSync(join(HERE, '../skills/rapier-math/SKILL.md'))
|
|
15
|
+
? resolve(HERE, '..') : HERE;
|
|
16
|
+
const PLACES = ['html', 'npm', 'react', 'vue', 'svelte', 'astro', 'next', 'agents'];
|
|
17
|
+
const NOFOLLOW = constants.O_NOFOLLOW || 0;
|
|
18
|
+
const usage = 'usage: rapier-math add [place] [--path <dir>] [--from <spec>] [--json]\n rapier-math remove [place] [--path <dir>] [--json]';
|
|
19
|
+
|
|
20
|
+
const fault = (code, message, hint) => Object.assign(new Error(message), {code, ...(hint ? {hint} : {})});
|
|
21
|
+
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
22
|
+
|
|
23
|
+
function setupArguments(argv) {
|
|
24
|
+
const [command, ...rest] = argv, options = {command, path: process.cwd(), json: false};
|
|
25
|
+
for (let at = 0; at < rest.length; at++) {
|
|
26
|
+
const token = rest[at];
|
|
27
|
+
if (token === '--json') options.json = true;
|
|
28
|
+
else if ((token === '--path' || token === '--from') && rest[at + 1] !== undefined) options[token.slice(2)] = rest[++at];
|
|
29
|
+
else if (!token.startsWith('--') && options.place === undefined) options.place = token;
|
|
30
|
+
else throw fault('MATH_OPTIONS', usage, 'Valid places: ' + PLACES.join(', ') + '. Omit place to detect automatically.');
|
|
31
|
+
}
|
|
32
|
+
if (options.place !== undefined && !PLACES.includes(options.place))
|
|
33
|
+
throw fault('MATH_OPTIONS', 'Unknown place: ' + options.place, 'Choose one of: ' + PLACES.join(', ') + ', or omit place to detect automatically.');
|
|
34
|
+
options.directory = resolve(options.path);
|
|
35
|
+
return options;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function destinationPath(root, name, create) {
|
|
39
|
+
const parts = name.split('/'); let directory = root;
|
|
40
|
+
for (const part of parts.slice(0, -1)) {
|
|
41
|
+
directory = join(directory, part);
|
|
42
|
+
if (create) await mkdir(directory).catch(error => { if (error.code !== 'EEXIST') throw error; });
|
|
43
|
+
const stat = await lstat(directory).catch(error => { if (!create && error.code === 'ENOENT') return null; throw error; });
|
|
44
|
+
if (!stat) return null;
|
|
45
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw fault('MATH_SETUP', 'Project directories cannot traverse symbolic links: ' + name);
|
|
46
|
+
}
|
|
47
|
+
return join(directory, parts.at(-1));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readOwnMeta() {
|
|
51
|
+
const pkgPath = join(OWN_ROOT, 'package.json');
|
|
52
|
+
if (existsSync(pkgPath)) return JSON.parse(readFileSync(pkgPath, 'utf8'));
|
|
53
|
+
const classic = readFileSync(join(OWN_ROOT, 'classic.js'), 'utf8');
|
|
54
|
+
const version = /version:\s*'([^']+)'/.exec(classic)?.[1] || '3.1.0';
|
|
55
|
+
return {name: 'rapier-math', version};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function readClassicBytes() {
|
|
59
|
+
const staged = join(OWN_ROOT, 'dist/rapier-math.js');
|
|
60
|
+
if (existsSync(staged)) return readFileSync(staged);
|
|
61
|
+
throw fault('MATH_SETUP', 'Classic bundle dist/rapier-math.js is missing from this package.', 'Run from the built rapier-math package.');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readProject(directory) {
|
|
65
|
+
const pkgPath = join(directory, 'package.json');
|
|
66
|
+
if (!existsSync(pkgPath)) return {pkg: null, deps: {}, isTs: false};
|
|
67
|
+
let pkg;
|
|
68
|
+
try { pkg = JSON.parse(readFileSync(pkgPath, 'utf8')); }
|
|
69
|
+
catch { throw fault('MATH_SETUP', 'Invalid JSON in ' + pkgPath, 'Fix package.json syntax and rerun `npx rapier-math add`.'); }
|
|
70
|
+
if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg))
|
|
71
|
+
throw fault('MATH_SETUP', 'package.json must contain a JSON object', 'Fix package.json and rerun `npx rapier-math add`.');
|
|
72
|
+
const deps = {...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies};
|
|
73
|
+
const isTs = existsSync(join(directory, 'tsconfig.json')) || Boolean(deps.typescript);
|
|
74
|
+
return {pkg, deps, isTs};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function detectPlace(directory, {pkg, deps}) {
|
|
78
|
+
const has = list => list.some(name => existsSync(join(directory, name)));
|
|
79
|
+
if (!pkg) return 'html';
|
|
80
|
+
if (deps.next || has(['next.config.mjs', 'next.config.js', 'next.config.ts', 'next.config.cjs'])) return 'next';
|
|
81
|
+
if (deps.astro || has(['astro.config.mjs', 'astro.config.js', 'astro.config.ts'])) return 'astro';
|
|
82
|
+
if (deps['@sveltejs/kit'] || deps.svelte || has(['svelte.config.js', 'svelte.config.mjs', 'svelte.config.ts'])) return 'svelte';
|
|
83
|
+
if (deps.nuxt || deps.vue) return 'vue';
|
|
84
|
+
if (deps.react || deps['react-dom'] || deps.preact) return 'react';
|
|
85
|
+
return 'npm';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function reactTemplate(ts, client) {
|
|
89
|
+
const head = client ? "'use client';\n" : '';
|
|
90
|
+
if (ts) return `${head}import {useEffect, useMemo, useRef} from 'react';
|
|
91
|
+
import {render, observe} from 'rapier-math';
|
|
92
|
+
|
|
93
|
+
export function Equation({source, displayMode = false}: {source: string; displayMode?: boolean}) {
|
|
94
|
+
const ref = useRef<HTMLSpanElement>(null);
|
|
95
|
+
const result = useMemo(() => {
|
|
96
|
+
try { return render(source, {displayMode}); }
|
|
97
|
+
catch { return null; }
|
|
98
|
+
}, [source, displayMode]);
|
|
99
|
+
const svg = result && result.errors.length === 0 ? result.svg : null;
|
|
100
|
+
useEffect(() => {
|
|
101
|
+
if (ref.current && svg) return observe(ref.current);
|
|
102
|
+
}, [svg]);
|
|
103
|
+
if (!svg) return <code>{source}</code>;
|
|
104
|
+
return <span ref={ref} dangerouslySetInnerHTML={{__html: svg}} />;
|
|
105
|
+
}
|
|
106
|
+
`;
|
|
107
|
+
return `${head}import {useEffect, useMemo, useRef} from 'react';
|
|
108
|
+
import {render, observe} from 'rapier-math';
|
|
109
|
+
|
|
110
|
+
export function Equation({source, displayMode = false}) {
|
|
111
|
+
const ref = useRef(null);
|
|
112
|
+
const result = useMemo(() => {
|
|
113
|
+
try { return render(source, {displayMode}); }
|
|
114
|
+
catch { return null; }
|
|
115
|
+
}, [source, displayMode]);
|
|
116
|
+
const svg = result && result.errors.length === 0 ? result.svg : null;
|
|
117
|
+
useEffect(() => {
|
|
118
|
+
if (ref.current && svg) return observe(ref.current);
|
|
119
|
+
}, [svg]);
|
|
120
|
+
if (!svg) return <code>{source}</code>;
|
|
121
|
+
return <span ref={ref} dangerouslySetInnerHTML={{__html: svg}} />;
|
|
122
|
+
}
|
|
123
|
+
`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const VUE_TEMPLATE = `<script setup>
|
|
127
|
+
import {computed, nextTick, onBeforeUnmount, onMounted, ref, watch} from 'vue';
|
|
128
|
+
import {render, observe} from 'rapier-math';
|
|
129
|
+
|
|
130
|
+
const props = defineProps({
|
|
131
|
+
source: {type: String, required: true},
|
|
132
|
+
displayMode: {type: Boolean, default: false},
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const root = ref(null);
|
|
136
|
+
let stop = () => {};
|
|
137
|
+
|
|
138
|
+
const svg = computed(() => {
|
|
139
|
+
try {
|
|
140
|
+
const result = render(props.source, {displayMode: props.displayMode});
|
|
141
|
+
return result.errors.length === 0 ? result.svg : null;
|
|
142
|
+
} catch { return null; }
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
function syncObserver() {
|
|
146
|
+
stop(); stop = () => {};
|
|
147
|
+
if (root.value && svg.value) stop = observe(root.value);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
onMounted(syncObserver);
|
|
151
|
+
watch(svg, () => { nextTick(syncObserver); });
|
|
152
|
+
onBeforeUnmount(() => { stop(); stop = () => {}; });
|
|
153
|
+
</script>
|
|
154
|
+
|
|
155
|
+
<template>
|
|
156
|
+
<span v-if="svg" ref="root" v-html="svg"></span>
|
|
157
|
+
<code v-else>{{ props.source }}</code>
|
|
158
|
+
</template>
|
|
159
|
+
`;
|
|
160
|
+
|
|
161
|
+
function svelteTemplate(svelte5) {
|
|
162
|
+
if (svelte5) return `<script>
|
|
163
|
+
import {onMount} from 'svelte';
|
|
164
|
+
import {render, observe} from 'rapier-math';
|
|
165
|
+
|
|
166
|
+
let {source = '', displayMode = false} = $props();
|
|
167
|
+
let root = $state(null);
|
|
168
|
+
let svg = $derived.by(() => {
|
|
169
|
+
try {
|
|
170
|
+
const result = render(source, {displayMode});
|
|
171
|
+
return result.errors.length === 0 ? result.svg : null;
|
|
172
|
+
} catch { return null; }
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
onMount(() => {
|
|
176
|
+
if (root && svg) return observe(root);
|
|
177
|
+
});
|
|
178
|
+
</script>
|
|
179
|
+
|
|
180
|
+
{#if svg}
|
|
181
|
+
<span bind:this={root}>{@html svg}</span>
|
|
182
|
+
{:else}
|
|
183
|
+
<code>{source}</code>
|
|
184
|
+
{/if}
|
|
185
|
+
`;
|
|
186
|
+
return `<script>
|
|
187
|
+
import {afterUpdate, onDestroy} from 'svelte';
|
|
188
|
+
import {render, observe} from 'rapier-math';
|
|
189
|
+
|
|
190
|
+
export let source = '';
|
|
191
|
+
export let displayMode = false;
|
|
192
|
+
|
|
193
|
+
let root;
|
|
194
|
+
let stop = () => {};
|
|
195
|
+
$: svg = (() => {
|
|
196
|
+
try {
|
|
197
|
+
const result = render(source, {displayMode});
|
|
198
|
+
return result.errors.length === 0 ? result.svg : null;
|
|
199
|
+
} catch { return null; }
|
|
200
|
+
})();
|
|
201
|
+
|
|
202
|
+
afterUpdate(() => {
|
|
203
|
+
stop(); stop = () => {};
|
|
204
|
+
if (root && svg) stop = observe(root);
|
|
205
|
+
});
|
|
206
|
+
onDestroy(() => { stop(); });
|
|
207
|
+
</script>
|
|
208
|
+
|
|
209
|
+
{#if svg}
|
|
210
|
+
<span bind:this={root}>{@html svg}</span>
|
|
211
|
+
{:else}
|
|
212
|
+
<code>{source}</code>
|
|
213
|
+
{/if}
|
|
214
|
+
`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const ASTRO_TEMPLATE = `---
|
|
218
|
+
import {render} from 'rapier-math';
|
|
219
|
+
|
|
220
|
+
const {source = '', displayMode = false} = Astro.props;
|
|
221
|
+
let svg = null;
|
|
222
|
+
try {
|
|
223
|
+
const result = render(source, {displayMode});
|
|
224
|
+
if (result.errors.length === 0) svg = result.svg;
|
|
225
|
+
} catch {}
|
|
226
|
+
---
|
|
227
|
+
{svg ? <span data-rapier-equation set:html={svg} /> : <code>{source}</code>}
|
|
228
|
+
<script>
|
|
229
|
+
import {observe} from 'rapier-math';
|
|
230
|
+
const stop = observe(document.body);
|
|
231
|
+
addEventListener('pagehide', () => stop(), {once: true});
|
|
232
|
+
</script>
|
|
233
|
+
`;
|
|
234
|
+
|
|
235
|
+
function npmTemplate(ts) {
|
|
236
|
+
if (ts) return `import {render, renderToString, parse, fit, observe, type RenderOptions, type RenderResult} from 'rapier-math';
|
|
237
|
+
export {render, renderToString, parse, fit, observe};
|
|
238
|
+
|
|
239
|
+
export function typeset(source: string, options?: RenderOptions): RenderResult {
|
|
240
|
+
return render(source, options);
|
|
241
|
+
}
|
|
242
|
+
`;
|
|
243
|
+
return `import {render, renderToString, parse, fit, observe} from 'rapier-math';
|
|
244
|
+
export {render, renderToString, parse, fit, observe};
|
|
245
|
+
|
|
246
|
+
export function typeset(source, options) {
|
|
247
|
+
return render(source, options);
|
|
248
|
+
}
|
|
249
|
+
`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const HTML_TEMPLATE = `<!doctype html>
|
|
253
|
+
<html lang="en">
|
|
254
|
+
<meta charset="utf-8">
|
|
255
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
256
|
+
<title>Equation</title>
|
|
257
|
+
<div id="equation"></div>
|
|
258
|
+
<script src="./rapier-math.js"></script>
|
|
259
|
+
<script>
|
|
260
|
+
const source = String.raw\`\\frac{-b\\pm\\sqrt{b^2-4ac}}{2a}\`;
|
|
261
|
+
const target = document.querySelector('#equation');
|
|
262
|
+
const result = RapierMath.render(source, {displayMode: true});
|
|
263
|
+
if (result.errors.length) target.textContent = source;
|
|
264
|
+
else {
|
|
265
|
+
target.innerHTML = result.svg;
|
|
266
|
+
const stop = RapierMath.observe(target);
|
|
267
|
+
addEventListener('pagehide', () => stop(), {once: true});
|
|
268
|
+
}
|
|
269
|
+
</script>
|
|
270
|
+
</html>
|
|
271
|
+
`;
|
|
272
|
+
|
|
273
|
+
function plannedFiles(directory, place, {deps, isTs}) {
|
|
274
|
+
const hasSrc = existsSync(join(directory, 'src'));
|
|
275
|
+
const skillBytes = readFileSync(join(OWN_ROOT, 'skills/rapier-math/SKILL.md'));
|
|
276
|
+
const list = [{rel: '.agents/skills/rapier-math/SKILL.md', bytes: skillBytes}];
|
|
277
|
+
if (place === 'agents') return list;
|
|
278
|
+
if (place === 'html') {
|
|
279
|
+
const htmlBytes = Buffer.from(HTML_TEMPLATE, 'utf8');
|
|
280
|
+
const indexPath = join(directory, 'index.html');
|
|
281
|
+
const htmlRel = !existsSync(indexPath) || sha256(readFileSync(indexPath)) === sha256(htmlBytes) ? 'index.html' : 'rapier-math.html';
|
|
282
|
+
return [{rel: 'rapier-math.js', bytes: readClassicBytes()}, {rel: htmlRel, bytes: htmlBytes, removeCandidates: ['index.html', 'rapier-math.html']}, ...list];
|
|
283
|
+
}
|
|
284
|
+
if (place === 'npm') {
|
|
285
|
+
const rel = (hasSrc ? 'src/' : '') + 'rapier-math' + (isTs ? '.ts' : '.mjs');
|
|
286
|
+
return [{rel, bytes: Buffer.from(npmTemplate(isTs), 'utf8'),
|
|
287
|
+
removeCandidates: ['src/rapier-math.ts', 'src/rapier-math.mjs', 'rapier-math.ts', 'rapier-math.mjs'],
|
|
288
|
+
matchers: [npmTemplate(true), npmTemplate(false)]}, ...list];
|
|
289
|
+
}
|
|
290
|
+
if (place === 'react' || place === 'next') {
|
|
291
|
+
const client = place === 'next';
|
|
292
|
+
const ext = isTs ? '.tsx' : '.jsx';
|
|
293
|
+
const prefix = place === 'next' ? (hasSrc ? 'src/components/' : 'components/') : (existsSync(join(directory, 'src/components')) ? 'src/components/' : hasSrc ? 'src/' : 'components/');
|
|
294
|
+
return [{rel: prefix + 'Equation' + ext, bytes: Buffer.from(reactTemplate(isTs, client), 'utf8'),
|
|
295
|
+
removeCandidates: ['src/components/Equation.tsx', 'src/components/Equation.jsx', 'src/Equation.tsx', 'src/Equation.jsx', 'components/Equation.tsx', 'components/Equation.jsx'],
|
|
296
|
+
matchers: [reactTemplate(true, client), reactTemplate(false, client)]}, ...list];
|
|
297
|
+
}
|
|
298
|
+
if (place === 'vue') {
|
|
299
|
+
const prefix = hasSrc ? 'src/components/' : 'components/';
|
|
300
|
+
return [{rel: prefix + 'Equation.vue', bytes: Buffer.from(VUE_TEMPLATE, 'utf8'),
|
|
301
|
+
removeCandidates: ['src/components/Equation.vue', 'components/Equation.vue']}, ...list];
|
|
302
|
+
}
|
|
303
|
+
if (place === 'svelte') {
|
|
304
|
+
const svelte5 = /^\D*5\b/.test(String(deps.svelte || ''));
|
|
305
|
+
const prefix = existsSync(join(directory, 'src/lib')) || deps['@sveltejs/kit'] ? 'src/lib/' : hasSrc ? 'src/' : '';
|
|
306
|
+
return [{rel: prefix + 'Equation.svelte', bytes: Buffer.from(svelteTemplate(svelte5), 'utf8'),
|
|
307
|
+
removeCandidates: ['src/lib/Equation.svelte', 'src/Equation.svelte', 'Equation.svelte'],
|
|
308
|
+
matchers: [svelteTemplate(true), svelteTemplate(false)]}, ...list];
|
|
309
|
+
}
|
|
310
|
+
return [{rel: 'src/components/Equation.astro', bytes: Buffer.from(ASTRO_TEMPLATE, 'utf8'),
|
|
311
|
+
removeCandidates: ['src/components/Equation.astro', 'components/Equation.astro']}, ...list];
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function installDependency(directory, ownPkg, fromSpec) {
|
|
315
|
+
const installedPkg = join(directory, 'node_modules', ownPkg.name, 'package.json');
|
|
316
|
+
if (!fromSpec && existsSync(installedPkg)) {
|
|
317
|
+
try {
|
|
318
|
+
if (JSON.parse(readFileSync(installedPkg, 'utf8')).name === ownPkg.name) {
|
|
319
|
+
const pkgPath = join(directory, 'package.json');
|
|
320
|
+
const pkg = JSON.parse(await readFile(pkgPath, 'utf8'));
|
|
321
|
+
if (!pkg.dependencies?.[ownPkg.name] && !pkg.devDependencies?.[ownPkg.name]) {
|
|
322
|
+
pkg.dependencies = {...pkg.dependencies, [ownPkg.name]: '^' + ownPkg.version};
|
|
323
|
+
await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
324
|
+
}
|
|
325
|
+
return 'existing';
|
|
326
|
+
}
|
|
327
|
+
} catch {}
|
|
328
|
+
}
|
|
329
|
+
const spec = fromSpec ? (/^(?:https?:|git\+|npm:|@|[A-Za-z0-9._-]+@)/.test(fromSpec) && !existsSync(fromSpec) ? fromSpec : resolve(fromSpec)) : ownPkg.name + '@^' + ownPkg.version;
|
|
330
|
+
const [cmd, args] = existsSync(join(directory, 'pnpm-lock.yaml')) ? ['pnpm', ['add', spec]]
|
|
331
|
+
: existsSync(join(directory, 'yarn.lock')) ? ['yarn', ['add', spec]]
|
|
332
|
+
: existsSync(join(directory, 'bun.lock')) || existsSync(join(directory, 'bun.lockb')) ? ['bun', ['add', spec]]
|
|
333
|
+
: ['npm', ['install', '--no-audit', '--no-fund', spec]];
|
|
334
|
+
const run = spawnSync(cmd, args, {cwd: directory, encoding: 'utf8'});
|
|
335
|
+
if (run.status !== 0)
|
|
336
|
+
throw fault('MATH_INSTALL', (run.stderr || run.stdout || cmd + ' failed').trim().split('\n').slice(-4).join(' '),
|
|
337
|
+
'Check network access or pass a local tarball with `--from <path>`.');
|
|
338
|
+
return cmd;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function writeManaged(root, rel, bytes) {
|
|
342
|
+
const path = await destinationPath(root, rel, true);
|
|
343
|
+
const stat = await lstat(path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
344
|
+
if (stat) {
|
|
345
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw fault('MATH_SETUP', 'Refusing non-regular target file: ' + rel);
|
|
346
|
+
const current = await readFile(path);
|
|
347
|
+
return sha256(current) === sha256(bytes) ? 'kept' : 'preserved';
|
|
348
|
+
}
|
|
349
|
+
const staged = join(dirname(path), '.rapier-add-' + randomBytes(12).toString('hex'));
|
|
350
|
+
const handle = await open(staged, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 0o644);
|
|
351
|
+
try { await handle.writeFile(bytes); } finally { await handle.close(); }
|
|
352
|
+
await rename(staged, path);
|
|
353
|
+
return 'written';
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function pruneEmptyParents(root, rel) {
|
|
357
|
+
const parts = rel.split('/').slice(0, -1);
|
|
358
|
+
while (parts.length) {
|
|
359
|
+
const dir = join(root, ...parts);
|
|
360
|
+
const entries = await readdir(dir).catch(() => ['keep']);
|
|
361
|
+
if (entries.length) break;
|
|
362
|
+
await rmdir(dir).catch(() => {});
|
|
363
|
+
parts.pop();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export async function add(argv) {
|
|
368
|
+
const options = setupArguments(['add', ...argv]);
|
|
369
|
+
await mkdir(options.directory, {recursive: true});
|
|
370
|
+
const directory = await realpath(options.directory);
|
|
371
|
+
const ownPkg = readOwnMeta();
|
|
372
|
+
const info = readProject(directory);
|
|
373
|
+
const place = options.place || detectPlace(directory, info);
|
|
374
|
+
if (!['html', 'agents'].includes(place) && !info.pkg)
|
|
375
|
+
throw fault('MATH_SETUP', 'No package.json in ' + directory + ' for place `' + place + '`', 'Run `npm init -y` first, or omit `' + place + '` for plain HTML.');
|
|
376
|
+
const installed = ['html', 'agents'].includes(place) ? 'static' : await installDependency(directory, ownPkg, options.from);
|
|
377
|
+
const written = [], kept = [], preserved = [];
|
|
378
|
+
for (const item of plannedFiles(directory, place, info)) {
|
|
379
|
+
const state = await writeManaged(directory, item.rel, item.bytes);
|
|
380
|
+
if (state === 'written') written.push(item.rel);
|
|
381
|
+
else if (state === 'kept') kept.push(item.rel);
|
|
382
|
+
else preserved.push(item.rel);
|
|
383
|
+
}
|
|
384
|
+
const summary = {type: 'add', package: ownPkg.name, version: ownPkg.version, place, directory, installed, written, kept, preserved};
|
|
385
|
+
if (options.json) console.log(JSON.stringify(summary));
|
|
386
|
+
else console.log(`${ownPkg.name}: configured ${place} in ${directory}` + (written.length ? ` (wrote ${written.join(', ')})` : '') + (preserved.length ? ` (preserved ${preserved.join(', ')})` : ''));
|
|
387
|
+
return summary;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
export async function remove(argv) {
|
|
391
|
+
const options = setupArguments(['remove', ...argv]);
|
|
392
|
+
if (!existsSync(options.directory)) throw fault('MATH_SETUP', 'Directory does not exist: ' + options.directory);
|
|
393
|
+
const directory = await realpath(options.directory);
|
|
394
|
+
const ownPkg = readOwnMeta();
|
|
395
|
+
const info = readProject(directory);
|
|
396
|
+
const place = options.place || detectPlace(directory, info);
|
|
397
|
+
const removed = [], preserved = [];
|
|
398
|
+
const seen = new Set();
|
|
399
|
+
for (const item of plannedFiles(directory, place, info)) {
|
|
400
|
+
const hashes = new Set([sha256(item.bytes), ...(item.matchers || []).map(text => sha256(Buffer.from(text, 'utf8')))]);
|
|
401
|
+
for (const rel of item.removeCandidates || [item.rel]) {
|
|
402
|
+
if (seen.has(rel)) continue;
|
|
403
|
+
seen.add(rel);
|
|
404
|
+
const path = await destinationPath(directory, rel, false);
|
|
405
|
+
if (!path) continue;
|
|
406
|
+
const stat = await lstat(path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
407
|
+
if (!stat || !stat.isFile() || stat.isSymbolicLink()) continue;
|
|
408
|
+
const current = await readFile(path);
|
|
409
|
+
if (hashes.has(sha256(current))) {
|
|
410
|
+
await rm(path);
|
|
411
|
+
await pruneEmptyParents(directory, rel);
|
|
412
|
+
removed.push(rel);
|
|
413
|
+
} else if (rel !== 'index.html') preserved.push(rel);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const summary = {type: 'remove', package: ownPkg.name, version: ownPkg.version, place, directory, removed, preserved};
|
|
417
|
+
if (options.json) console.log(JSON.stringify(summary));
|
|
418
|
+
else console.log(`${ownPkg.name}: removed ${removed.length} file(s) from ${directory}` + (preserved.length ? ` (preserved edited ${preserved.join(', ')})` : ''));
|
|
419
|
+
return summary;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async function main(argv) {
|
|
423
|
+
const json = argv.includes('--json');
|
|
424
|
+
try {
|
|
425
|
+
const [command, ...rest] = argv;
|
|
426
|
+
if (command === 'add') await add(rest);
|
|
427
|
+
else if (command === 'remove') await remove(rest);
|
|
428
|
+
else throw fault('MATH_OPTIONS', usage, 'Run `npx rapier-math add` in your project directory.');
|
|
429
|
+
} catch (error) {
|
|
430
|
+
process.exitCode = 1;
|
|
431
|
+
if (json) console.log(JSON.stringify({type: 'error', error: {code: error.code || 'MATH_ERROR', message: error.message, ...(error.hint ? {hint: error.hint} : {})}}));
|
|
432
|
+
else console.error(error.message + (error.hint ? '\n' + error.hint : ''));
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (process.argv[1] && await realpath(fileURLToPath(import.meta.url)) === await realpath(process.argv[1]).catch(() => null)) {
|
|
437
|
+
await main(process.argv.slice(2));
|
|
438
|
+
}
|
package/dist/combined.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
2
|
import type {RenderOptions, SemanticRenderResult} from './index.js';
|
|
3
|
-
/** Render SVG and MathML from one
|
|
4
|
-
export function renderWithMathML(source: unknown, options?: RenderOptions): SemanticRenderResult;
|
|
3
|
+
/** Render SVG and MathML from one strict parse; incomplete source is not repaired. */
|
|
4
|
+
export function renderWithMathML(source: unknown, options?: Omit<RenderOptions, 'preview' | 'caret'>): SemanticRenderResult;
|
package/dist/delimiters.mjs
CHANGED
|
@@ -1,33 +1,72 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
2
|
// A boundary index for a host-owned text region, not a Markdown parser.
|
|
3
|
+
function countLines(source, from, to) {
|
|
4
|
+
let lines = 0;
|
|
5
|
+
for (let i = from; i < to; i++) {
|
|
6
|
+
const code = source.charCodeAt(i);
|
|
7
|
+
if (code === 0x0a || code === 0x0d) lines++;
|
|
8
|
+
}
|
|
9
|
+
return lines;
|
|
10
|
+
}
|
|
11
|
+
|
|
3
12
|
export function createMathMatcher(source, {singleDollar = false, brackets = true} = {}) {
|
|
4
13
|
if (typeof source !== 'string') throw new TypeError('Math boundaries require source text.');
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
14
|
+
const len = source.length;
|
|
15
|
+
if (len === 0 || (source.indexOf('$') < 0 && (!brackets || source.indexOf('\\') < 0))) {
|
|
16
|
+
return () => null;
|
|
17
|
+
}
|
|
18
|
+
const markers = new Map(), list = [], next = Object.create(null);
|
|
19
|
+
if (!brackets) {
|
|
20
|
+
let line = 0, lastAt = 0;
|
|
21
|
+
for (let at = source.indexOf('$'); at >= 0; at = source.indexOf('$', at)) {
|
|
22
|
+
line += countLines(source, lastAt, at);
|
|
23
|
+
let slashes = 0;
|
|
24
|
+
for (let s = at - 1; s >= 0 && source.charCodeAt(s) === 0x5c; s--) slashes++;
|
|
12
25
|
let end = at + 1;
|
|
13
|
-
while (source
|
|
26
|
+
while (end < len && source.charCodeAt(end) === 0x24) end++;
|
|
14
27
|
const count = end - at;
|
|
15
|
-
if (!(slashes & 1) && (count === 2 || count === 1 && singleDollar))
|
|
16
|
-
|
|
28
|
+
if (!(slashes & 1) && (count === 2 || count === 1 && singleDollar)) {
|
|
29
|
+
const entry = {at, marker: count === 2 ? '$$' : '$', line, close: undefined};
|
|
30
|
+
markers.set(at, entry);
|
|
31
|
+
list.push(entry);
|
|
32
|
+
}
|
|
33
|
+
lastAt = end;
|
|
17
34
|
at = end;
|
|
18
|
-
} else {
|
|
19
|
-
if (brackets && slashes & 1 && '()[]'.includes(char))
|
|
20
|
-
markers.set(at - 1, {at: at - 1, marker: '\\' + char, line});
|
|
21
|
-
at++;
|
|
22
35
|
}
|
|
23
|
-
|
|
36
|
+
} else {
|
|
37
|
+
let slashes = 0, line = 0;
|
|
38
|
+
for (let at = 0; at < len;) {
|
|
39
|
+
const code = source.charCodeAt(at);
|
|
40
|
+
if (code === 0x5c) { slashes++; at++; continue; }
|
|
41
|
+
if (code === 0x0a || code === 0x0d) line++;
|
|
42
|
+
if (code === 0x24) {
|
|
43
|
+
let end = at + 1;
|
|
44
|
+
while (end < len && source.charCodeAt(end) === 0x24) end++;
|
|
45
|
+
const count = end - at;
|
|
46
|
+
if (!(slashes & 1) && (count === 2 || count === 1 && singleDollar)) {
|
|
47
|
+
const entry = {at, marker: count === 2 ? '$$' : '$', line, close: undefined};
|
|
48
|
+
markers.set(at, entry);
|
|
49
|
+
list.push(entry);
|
|
50
|
+
}
|
|
51
|
+
at = end;
|
|
52
|
+
} else {
|
|
53
|
+
if (slashes & 1 && (code === 0x28 || code === 0x29 || code === 0x5b || code === 0x5d)) {
|
|
54
|
+
const entry = {at: at - 1, marker: '\\' + source[at], line, close: undefined};
|
|
55
|
+
markers.set(at - 1, entry);
|
|
56
|
+
list.push(entry);
|
|
57
|
+
}
|
|
58
|
+
at++;
|
|
59
|
+
}
|
|
60
|
+
slashes = 0;
|
|
61
|
+
}
|
|
24
62
|
}
|
|
25
|
-
for (
|
|
63
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
64
|
+
const entry = list[i];
|
|
26
65
|
const closing = entry.marker === '\\(' ? '\\)' : entry.marker === '\\[' ? '\\]' : entry.marker;
|
|
27
66
|
entry.close = next[closing];
|
|
28
67
|
next[entry.marker] = entry;
|
|
29
68
|
}
|
|
30
|
-
return function match(start, limit =
|
|
69
|
+
return function match(start, limit = len) {
|
|
31
70
|
const open = markers.get(start), close = open?.close;
|
|
32
71
|
if (!close || open.marker === '\\)' || open.marker === '\\]' || close.at + close.marker.length > limit) return null;
|
|
33
72
|
const bodyStart = start + open.marker.length, bodyEnd = close.at;
|
package/dist/index.mjs
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
import {parseMathTex as parse} from '../src/math/parser.js';
|
|
3
3
|
import {renderMath as render, mathRenderToString as renderToString} from '../src/math/api.js';
|
|
4
4
|
import {mathFit as fit, mathObserve as observe} from '../src/math/browser.js';
|
|
5
|
-
const version = "
|
|
5
|
+
const version = "3.1.0";
|
|
6
6
|
export {version, parse, render, renderToString, fit, observe};
|
|
7
7
|
export default Object.freeze({version, parse, render, renderToString, fit, observe});
|
package/dist/integration.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type {MathSession} from './stream.js';
|
|
|
4
4
|
export interface IntegrationOptions {
|
|
5
5
|
/** Insert SVG with assistive MathML. Include accessible.css. */
|
|
6
6
|
accessible?: boolean;
|
|
7
|
-
/** With
|
|
7
|
+
/** With a session, plain-data options are captured once per render. preview/caret apply only without accessible output. */
|
|
8
8
|
renderOptions?: RenderOptions;
|
|
9
9
|
/** Per document. Default 1024. Exhaustion leaves subsequent math as source. */
|
|
10
10
|
maxFormulas?: number;
|
package/dist/markdown-it.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ import type {MathError} from './index.js';
|
|
|
6
6
|
import type {MathSession} from './stream.js';
|
|
7
7
|
export interface MarkdownMathOptions extends DelimiterOptions, IntegrationOptions {}
|
|
8
8
|
export interface MarkdownMathEnv {
|
|
9
|
+
/** The Markdown host and its other plug-ins may carry additional document data. */
|
|
10
|
+
[key: string | symbol]: unknown;
|
|
9
11
|
/** Optional formula reuse for one message; each render still owns fresh budgets. */
|
|
10
12
|
rapierMathSession?: MathSession;
|
|
11
13
|
rapierMathErrors?: {source: string; errors: MathError[]}[];
|