rapier-math 3.0.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 +5 -3
- package/dist/classic.d.ts +0 -1
- package/dist/cli.mjs +438 -0
- package/dist/delimiters.mjs +56 -17
- package/dist/index.mjs +1 -1
- package/dist/markdown-rules.mjs +22 -5
- package/dist/rapier-math.js +1 -1
- package/docs/api.md +44 -42
- package/docs/font-source.md +22 -22
- package/docs/math-components.json +6 -6
- package/docs/math-resources.json +35 -29
- package/docs/semantics.md +33 -33
- 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 +5 -3
- package/src/tools/build-math.mjs +2 -2
- package/CHANGELOG.md +0 -24
package/README.md
CHANGED
|
@@ -3,9 +3,11 @@
|
|
|
3
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.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
|
-
|
|
6
|
+
npx rapier-math add
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
+
Installs into npm, plain HTML, React, Vue, Svelte, Astro or Next projects, or run `npm install rapier-math`.
|
|
10
|
+
|
|
9
11
|
```js
|
|
10
12
|
import {renderToString} from 'rapier-math';
|
|
11
13
|
|
|
@@ -22,13 +24,13 @@ Try it in [Rapier](https://rapier.website): type \$x^2\$.
|
|
|
22
24
|
| `rapier-math/mathml` | Native MathML, no font |
|
|
23
25
|
| `rapier-math/combined` | SVG and MathML from one parse |
|
|
24
26
|
| `rapier-math/accessible` | Accessible output for your own layout, with `rapier-math/accessible.css` |
|
|
25
|
-
| `rapier-math/markdown-it`, `rapier-math/rehype` | Markdown integrations
|
|
27
|
+
| `rapier-math/markdown-it`, `rapier-math/rehype` | Markdown integrations. Your parser stays in charge |
|
|
26
28
|
| `rapier-math/stream` | Formulas in streamed text, such as model output |
|
|
27
29
|
| `rapier-math/classic` | [dist/rapier-math.js](dist/rapier-math.js): one file, `globalThis.RapierMath` |
|
|
28
30
|
|
|
29
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.
|
|
30
32
|
|
|
31
|
-
[API](docs/api.md) · [MathML and accessibility](docs/semantics.md) · [Examples](examples/README.md) · [Font](docs/font-source.md) · [Changes](
|
|
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)
|
|
32
34
|
|
|
33
35
|
## Build
|
|
34
36
|
|
package/dist/classic.d.ts
CHANGED
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/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 = "3.
|
|
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/markdown-rules.mjs
CHANGED
|
@@ -2,6 +2,19 @@
|
|
|
2
2
|
// Original neutral adapter. The host owns Markdown structure and normalization.
|
|
3
3
|
import {createMathMatcher} from './delimiters.mjs';
|
|
4
4
|
|
|
5
|
+
function isMathFenceInfo(info) {
|
|
6
|
+
if (!info || info.length < 4) return false;
|
|
7
|
+
let start = 0;
|
|
8
|
+
const len = info.length;
|
|
9
|
+
while (start < len && info.charCodeAt(start) <= 0x20) start++;
|
|
10
|
+
if (start + 4 > len) return false;
|
|
11
|
+
if ((info.charCodeAt(start) | 32) !== 0x6d ||
|
|
12
|
+
(info.charCodeAt(start + 1) | 32) !== 0x61 ||
|
|
13
|
+
(info.charCodeAt(start + 2) | 32) !== 0x74 ||
|
|
14
|
+
(info.charCodeAt(start + 3) | 32) !== 0x68) return false;
|
|
15
|
+
return start + 4 === len || info.charCodeAt(start + 4) <= 0x20;
|
|
16
|
+
}
|
|
17
|
+
|
|
5
18
|
export function installMathRules(md, {singleDollar = false, brackets = true, ruleName = 'rapier_math', inLink = false} = {}) {
|
|
6
19
|
// Block tokens share their core owner's array, including nested quotes/lists. Capture
|
|
7
20
|
// fence source while the host still holds those containers' adjusted line bounds.
|
|
@@ -12,15 +25,17 @@ export function installMathRules(md, {singleDollar = false, brackets = true, rul
|
|
|
12
25
|
md.core.ruler.after('block', ruleName + '_source_release', state => authored.delete(state.tokens));
|
|
13
26
|
const tokenize = md.block.tokenize;
|
|
14
27
|
md.block.tokenize = function(state, startLine, endLine) {
|
|
28
|
+
// Tokens before this call are already scanned. A yielding host empties the list between block windows, so a
|
|
29
|
+
// count kept from an earlier window would skip the fences of the next.
|
|
15
30
|
const first = state.tokens.length;
|
|
16
31
|
// A yielding host can leave tokenize at a completed block boundary by throwing.
|
|
17
32
|
// Retain those completed fences before that boundary releases its line tables.
|
|
18
33
|
try { return tokenize.call(this, state, startLine, endLine); }
|
|
19
34
|
finally {
|
|
20
|
-
|
|
35
|
+
const len = state.tokens.length;
|
|
36
|
+
for (let index = first; index < len; index++) {
|
|
21
37
|
const token = state.tokens[index];
|
|
22
|
-
if (token.type !== 'fence' || !token.map || token.meta?.mathSource !== undefined ||
|
|
23
|
-
String(token.info || '').trim().split(/\s+/)[0].toLowerCase() !== 'math') continue;
|
|
38
|
+
if (token.type !== 'fence' || !token.map || token.meta?.mathSource !== undefined || !isMathFenceInfo(token.info)) continue;
|
|
24
39
|
const held = authored.get(state.tokens), source = held?.source ?? state.src;
|
|
25
40
|
let value;
|
|
26
41
|
if (!state.rapierSourceSlice && source === state.src) value = state.getLines(token.map[0], token.map[1], state.blkIndent, false);
|
|
@@ -70,7 +85,8 @@ export function installMathRules(md, {singleDollar = false, brackets = true, rul
|
|
|
70
85
|
}
|
|
71
86
|
md.inline.ruler.before('escape', ruleName, (state, silent) => {
|
|
72
87
|
if (!inLink && state.linkLevel > 0) return false;
|
|
73
|
-
|
|
88
|
+
const ch = state.src.charCodeAt(state.pos);
|
|
89
|
+
if (ch !== 0x24 && (!brackets || ch !== 0x5c)) return false;
|
|
74
90
|
const span = match(state, state.pos, state.posMax);
|
|
75
91
|
if (!span) return false;
|
|
76
92
|
if (!silent) {
|
|
@@ -86,7 +102,8 @@ export function installMathRules(md, {singleDollar = false, brackets = true, rul
|
|
|
86
102
|
// An indented code block belongs to the host even when it begins with dollars.
|
|
87
103
|
if (state.sCount[startLine] - state.blkIndent >= 4) return false;
|
|
88
104
|
const start = state.bMarks[startLine] + state.tShift[startLine];
|
|
89
|
-
|
|
105
|
+
const c0 = state.src.charCodeAt(start), c1 = state.src.charCodeAt(start + 1);
|
|
106
|
+
if (!(c0 === 0x24 && c1 === 0x24) && (!brackets || !(c0 === 0x5c && c1 === 0x5b))) return false;
|
|
90
107
|
const span = match(state, start, state.eMarks[endLine - 1]);
|
|
91
108
|
if (!span?.displayMode) return false;
|
|
92
109
|
let last = startLine;
|
package/dist/rapier-math.js
CHANGED
|
@@ -4451,7 +4451,7 @@ function mathRenderWithMathML(source, options = {}) {
|
|
|
4451
4451
|
|
|
4452
4452
|
// SPDX-License-Identifier: MIT
|
|
4453
4453
|
globalThis.RapierMath=Object.freeze({
|
|
4454
|
-
version:'3.
|
|
4454
|
+
version:'3.1.0', parse:parseMathTex,
|
|
4455
4455
|
render:renderMath, renderToString:mathRenderToString,
|
|
4456
4456
|
fit:mathFit, observe:mathObserve,
|
|
4457
4457
|
toMathML:mathToMathML, renderWithMathML:mathRenderWithMathML,
|