svg-path-interpolator 0.2.5 → 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ All notable changes are documented here.
4
+
5
+ ## 1.0.0
6
+
7
+ ### Breaking changes
8
+
9
+ - Invalid SVG path data and transforms now throw clear errors instead of being
10
+ partially ignored.
11
+ - Sampling now accepts optional `maxSamples` and `maxOutputPoints` limits. A
12
+ limit that is reached throws a `RangeError` rather than returning partial data.
13
+ - The package requires Node.js 22 or newer and is ESM-only.
14
+
15
+ ### Improvements
16
+
17
+ - Transform handling supports complete transform lists, nested transforms, and
18
+ path-level transforms.
19
+ - Browser, Windows, package-consumer, and Node 22/24/26 checks run in CI.
20
+ - The affine matrix implementation is independently maintained by this project.
package/README.md CHANGED
@@ -1,73 +1,121 @@
1
- # SVG Path Interpolator
2
- The SVG Path Interpolator produces point data representing interpolated values within an SVG path. This is handy when you need to calculate complex paths for animation or drawing APIs beforehand. Complex paths that include Bézier curves are converted to polygons with a configurable segment sampling size producing more points with greater precision or fewer points for speed. Polygon path data can be used to animate, draw or for hit detection in games.
3
-
4
- ## Install
5
- ```bash
6
- npm install svg-path-interpolator --save
7
- ```
8
- or as a cli
9
- ```bash
10
- npm install -g svg-path-interpolator
11
- ```
12
-
13
- ## Usage
14
- For Node cli users, create a config.json somewhere in your project. See the `sample.config.json` for configuration options.
15
- ```json
16
- {
17
- "joinPathData": false,
18
- "minDistance": 0.5,
19
- "roundToNearest": 0.25,
20
- "sampleFrequency": 0.001,
21
- "pretty": false,
22
- "prettyIndent": 0
23
- }
24
- ```
25
- Then from your terminal, type
26
- ```bash
27
- svgpi ./path/to/config.json ./path/to/target.svg ./output/fileName.json
28
- ```
29
- For ES6 users, create a new instance of the SVGPathInterpolator
30
- ```js
31
- import SVGPathInterpolator from 'SVGPathInterpolator';
32
- const svgString = `
33
- <svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"
34
- width="792px" height="612px" viewBox="0 0 792 612" enable-background="new 0 0 792 612" xml:space="preserve">
35
- <g>
36
- <path id="path3789" d="M287.168,442.411
37
- c-8.65,0-15.652,7.003-15.652,15.653
38
- c0,8.65,7.003,15.69,15.652,15.69
39
- s15.653-7.04,15.653-15.69
40
- "/>
41
- </g>
42
- </svg>
43
- `;
44
- const config = {
45
- joinPathData: false,
46
- minDistance: 0.5,
47
- roundToNearest: 0.25,
48
- sampleFrequency: 0.001
49
- };
50
- const interpolator = new SVGPathInterpolator(config);
51
- const pathData = interpolator.processSvg(svgString);
52
- ```
53
- ### joinPathData
54
- When `joinPathData` is `true`, all path data is joined in a single array as the output. When `false`, each path is separated by the path `id` attribute in a json object as the output. If no `id` attribute exists on the path, a unique id is created.
55
-
56
- ### minDistance
57
- `minDistance` is the minimum distance between the current and previous points when sampling. If a sample results in a distance less than the specified value, the point is discarded.
58
-
59
- ### roundToNearest
60
- `roundToNearest` is useful when snapping to fractional pixel values. For example, if `roundToNearest` is `.25`, a sample resulting in the point 2.343200092,4.6100923 will round to 2.25,4.5
61
-
62
- ### sampleFrequency
63
- `sampleFrequency` determines the increment of `t` when sampling. If `sampleFrequency` is set to `.001` , since `t` iterates from 0 to 1, there will be 1000 points sampled per command but only points that are greater than `minDistance` are captured.
64
-
65
- ### pretty (cli only)
66
- When `true`, `pretty` creates formatted json output
67
-
68
- ### prettyIndent (cli only)
69
- Then number of spaces to indent when `pretty` is `true`
70
-
71
- ## Examples
72
- ### Animating output
73
- See [this pen](https://codepen.io/justinwilaby/pen/dMQdBo) for an example on animating a simple path.
1
+ # SVG Path Interpolator
2
+
3
+ SVG Path Interpolator samples SVG paths into flat arrays of x/y coordinates for drawing, animation, and hit detection. Sampling distance and precision are configurable.
4
+
5
+ ## Requirements
6
+
7
+ Node.js 22 or newer is required for the CLI and Node API. Browser use requires modern ES modules and WebAssembly support.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install svg-path-interpolator
13
+ ```
14
+
15
+ For the CLI, install globally with `npm install -g svg-path-interpolator` or run it through `npx`.
16
+
17
+ ## CLI
18
+
19
+ Create a config file:
20
+
21
+ ```json
22
+ {
23
+ "joinPathData": false,
24
+ "minDistance": 0.5,
25
+ "roundToNearest": 0.25,
26
+ "sampleFrequency": 0.001,
27
+ "pretty": false,
28
+ "prettyIndent": 0
29
+ }
30
+ ```
31
+
32
+ Then run:
33
+
34
+ ```bash
35
+ svgpi ./config.json ./drawing.svg ./points.json
36
+ ```
37
+
38
+ Omit the output path to print the JSON to stdout. See [sample.config.json](config/sample.config.json) for the same settings.
39
+
40
+ ## Node API
41
+
42
+ `sax-wasm` includes the WebAssembly binary. Load it from that package and pass the bytes to `createInterpolator`:
43
+
44
+ ```js
45
+ import { readFile } from 'node:fs/promises';
46
+ import { createInterpolator } from 'svg-path-interpolator';
47
+
48
+ const wasmUrl = new URL(import.meta.resolve('sax-wasm/lib/sax-wasm.wasm'));
49
+ const wasm = await readFile(wasmUrl);
50
+ const interpolator = await createInterpolator({ joinPathData: true }, wasm);
51
+
52
+ const svg = await readFile('./drawing.svg');
53
+ const points = interpolator.processSVG(svg);
54
+ ```
55
+
56
+ `createInterpolator` also accepts a browser-accessible URL or a `Response` as its second argument. It requires that argument because the package does not copy the WASM binary into its own `lib` directory.
57
+
58
+ ## Browser API
59
+
60
+ With a bundler, copy `node_modules/sax-wasm/lib/sax-wasm.wasm` to a public URL, then pass that URL to `createInterpolator`:
61
+
62
+ ```js
63
+ import { createInterpolator } from 'svg-path-interpolator';
64
+
65
+ const interpolator = await createInterpolator({ joinPathData: true }, '/assets/sax-wasm.wasm');
66
+ const response = await fetch('/drawing.svg');
67
+ const points = interpolator.processSVG(new Uint8Array(await response.arrayBuffer()));
68
+ ```
69
+
70
+ For a browser without a bundler, serve this package's `lib/` directory and the `sax-wasm` package's `lib/` directory. An import map resolves the bare `sax-wasm` import:
71
+
72
+ ```html
73
+ <script type="importmap">
74
+ {"imports": {"sax-wasm": "/vendor/sax-wasm/lib/esm/index.js"}}
75
+ </script>
76
+ <script type="module">
77
+ import { createInterpolator } from '/vendor/svg-path-interpolator/lib/index.js';
78
+
79
+ const interpolator = await createInterpolator(
80
+ { joinPathData: true },
81
+ '/vendor/sax-wasm/lib/sax-wasm.wasm'
82
+ );
83
+ const svg = document.querySelector('svg.my-svg');
84
+ const points = interpolator.processSVG(new TextEncoder().encode(svg.outerHTML));
85
+ </script>
86
+ ```
87
+
88
+ ## Options
89
+
90
+ - `joinPathData`: When true, return one flat array. Otherwise, return an object keyed by each path's `id` or a generated key.
91
+ - `minDistance`: Discard samples closer than this distance to the previous accepted point. Default: `0.5`.
92
+ - `roundToNearest`: Snap coordinates to this increment. Default: `0.25`.
93
+ - `sampleFrequency`: Increment of the curve parameter `t` between samples. Default: `0.001`.
94
+ - `trim`: Translate sampled coordinates so their minimum x and y values are zero. Default: `false`.
95
+ - `maxSamples`: Optional maximum number of sampling attempts for a single `interpolatePath` or `processSVG` call. It is shared across every path and every internally decomposed arc in that operation. This limits attempted samples, including samples later discarded by `minDistance`.
96
+ - `maxOutputPoints`: Optional maximum number of emitted x/y coordinate pairs for a single interpolation operation. It is shared across every path and decomposed arc after distance filtering and rounding.
97
+ - `pretty` and `prettyIndent`: CLI JSON formatting options.
98
+
99
+ Both budgets must be positive finite integers when supplied. Exceeding either budget throws a `RangeError` before the next sample or point is added; no partial result is returned. The same validation runs when interpolation begins, so mutating an option after construction cannot bypass a limit.
100
+
101
+ ## Development
102
+
103
+ Install dependencies with `npm ci`. All package source, including the CLI, lives in `src/` as TypeScript. Run `npm run build` to emit ESM and TypeScript declarations into the generated, Git-ignored `lib/` directory. `npm pack` and `npm publish` build it automatically through `prepack`.
104
+
105
+ - `npm test` builds and runs the Node test suite.
106
+ - `npm run test:coverage` runs the suite with Node's coverage report.
107
+ - `npm run lint` checks maintained TypeScript, tests, examples, configuration, scripts, documentation, and CI files with Biome.
108
+ - `npm run format:check` verifies the tooling, documentation, configuration, example, and CI formatting; use `npm run format` to apply it. Existing `src/` and `test/` formatting is intentionally preserved until its own dedicated migration.
109
+ - `npm run verify:package` tests the packed tarball from a fresh consumer project, including its CLI and declarations.
110
+ - `npm run test:browser` launches Chromium against the actual browser example. Install its local binary first with `npx playwright install chromium`.
111
+ - `npm run check` runs linting, formatting, type checking, coverage, and packed-package verification.
112
+
113
+ GitHub Actions retains runtime coverage on Node 22, 24, and 26, runs quality and package verification once on Ubuntu, and adds Windows plus real-browser smoke coverage.
114
+
115
+ See [CHANGELOG.md](CHANGELOG.md) for release notes and [RELEASING.md](RELEASING.md) for the manual release checklist.
116
+
117
+ The package is ESM-only. Prefer imports from the package root; the existing subpath export remains available for compatibility. The SAX parser's WebAssembly binary remains supplied by `sax-wasm` and must be passed to `createInterpolator`, as shown above.
118
+
119
+ ## Examples
120
+
121
+ See [examples/index.html](examples/index.html) for a browser example and [this animation](https://codepen.io/justinwilaby/pen/dMQdBo) for a use of the point data.
@@ -0,0 +1,149 @@
1
+ import { SAXParser } from 'sax-wasm';
2
+ import { SVGTransform } from './math/SVGTransform.js';
3
+ export interface SVGInterpolatorConfig {
4
+ /** Return all sampled paths in one flat array instead of an object keyed by path ID. */
5
+ joinPathData?: boolean;
6
+ /** Skip points that are closer than this distance to the last saved point. */
7
+ minDistance?: number;
8
+ /** Round each coordinate down to the nearest multiple of this value. */
9
+ roundToNearest?: number;
10
+ /** Set how often curves are sampled. Smaller values create more points and take more work. */
11
+ sampleFrequency?: number;
12
+ /** Move the sampled points so the smallest x and y values become zero. */
13
+ trim?: boolean;
14
+ /** Internal prepared SVG parser. `createInterpolator` supplies this automatically. */
15
+ parser?: SAXParser;
16
+ /** Stop after this many sampling attempts. Leave unset for no attempt limit. */
17
+ maxSamples?: number;
18
+ /** Stop after this many emitted x/y point pairs. Leave unset for no output limit. */
19
+ maxOutputPoints?: number;
20
+ }
21
+ /**
22
+ * Turns SVG path data into sampled x/y coordinate pairs.
23
+ *
24
+ * Create this class directly when you only need `interpolatePath`. Use
25
+ * `createInterpolator` when you also need to read complete SVG documents.
26
+ */
27
+ export declare class SVGPathInterpolator {
28
+ /**
29
+ * When trim is true, paths that were translated
30
+ * are normalized and will begin at 0,0.
31
+ *
32
+ * @var {boolean} trim
33
+ * @memberOf SVGPathInterpolator#
34
+ * @default false
35
+ */
36
+ trim: boolean;
37
+ /**
38
+ * minDistance is the minimum distance between the
39
+ * current and previous points when sampling.
40
+ * If a sample results in a distance less than the
41
+ * specified value, the point is discarded.
42
+ *
43
+ * @var {number} minDistance
44
+ * @memberOf SVGPathInterpolator#
45
+ * @default 0.5
46
+ */
47
+ minDistance: number;
48
+ /**
49
+ * roundToNearest is useful when snapping to fractional
50
+ * pixel values. For example, if roundToNearest is .25,
51
+ * a sample resulting in the point 2.343200092,4.6100923
52
+ * will round to 2.25,4.5.
53
+ *
54
+ * @var {number} roundToNearest
55
+ * @memberOf SVGPathInterpolator#
56
+ * @default 0.25
57
+ */
58
+ roundToNearest: number;
59
+ /**
60
+ * sampleFrequency determines the increment of t when sampling.
61
+ * Values must be between 0.000001 and 1, inclusive, to bound
62
+ * the amount of sampling work performed for each command.
63
+ * If sampleFrequency is set to .001 , since t iterates from
64
+ * 0 to 1, there will be 1000 points sampled per command
65
+ * but only points that are greater than minDistance are captured.
66
+ *
67
+ * @var {number} sampleFrequency
68
+ * @memberOf SVGPathInterpolator#
69
+ * @default 0.001
70
+ */
71
+ sampleFrequency: number;
72
+ /**
73
+ * Maximum sample attempts for one interpolation operation.
74
+ *
75
+ * This limit includes attempts that do not produce a saved point.
76
+ */
77
+ maxSamples?: number;
78
+ /**
79
+ * Maximum emitted coordinate pairs for one interpolation operation.
80
+ *
81
+ * This limit is shared by every path in a processed SVG document.
82
+ */
83
+ maxOutputPoints?: number;
84
+ /**
85
+ * When true, pretty creates formatted json output.
86
+ *
87
+ * @var {boolean} pretty
88
+ * @memberOf SVGPathInterpolator#
89
+ * @default false
90
+ */
91
+ pretty: boolean;
92
+ /**
93
+ * Then number of spaces to indent when pretty is true.
94
+ *
95
+ * @var {int} prettyIndent
96
+ * @memberOf SVGPathInterpolator#
97
+ * @default 0
98
+ */
99
+ prettyIndent: number;
100
+ /**
101
+ * Whether to join path data into a single flat array.
102
+ *
103
+ * @var {boolean} joinPathData
104
+ * @memberOf SVGPathInterpolator#
105
+ * @default false
106
+ */
107
+ joinPathData: boolean;
108
+ /**
109
+ * The SaxWasm parser instance;
110
+ * @var { SAXParser } parser
111
+ * @memberOf SVGPathInterpolator#
112
+ * @default null
113
+ */
114
+ parser?: SAXParser;
115
+ constructor(config?: SVGInterpolatorConfig);
116
+ private validateNumericOptions;
117
+ private validateLimit;
118
+ private createSamplingBudget;
119
+ private validateNumericOption;
120
+ /** Read the numeric values from one SVG path or transform argument string. */
121
+ parseArguments(source: string): number[];
122
+ /**
123
+ * Read every path in an SVG document and return its sampled points.
124
+ *
125
+ * Paths are keyed by `id` unless `joinPathData` is enabled. The configured
126
+ * sample and output limits apply to the whole document, not one path at a time.
127
+ */
128
+ processSVG(data: Uint8Array): number[] | Record<string, number[]>;
129
+ private parseTransform;
130
+ private validateTransformArity;
131
+ private isFiniteTransform;
132
+ private skipWhitespace;
133
+ private skipSeparators;
134
+ private parseStrictNumbers;
135
+ private parseArcArguments;
136
+ private readStrictNumber;
137
+ private validatePath;
138
+ applyTransforms(transforms: Record<string, string>, points: number[]): void;
139
+ applyTransforms(transform: SVGTransform, points: number[]): void;
140
+ /**
141
+ * Sample one SVG path-data string and return a flat x/y coordinate array.
142
+ *
143
+ * Invalid path data and exhausted limits throw a descriptive error.
144
+ */
145
+ interpolatePath(path: string): number[];
146
+ private interpolatePathWithBudget;
147
+ trimPathOffsets(paths: number[]): void;
148
+ applyOffset(offsetX: number, offsetY: number, coords?: number[], setLength?: number): number[];
149
+ }