@weasel-js/export 0.0.0-stage → 1.19.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 orochi235
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @weasel-js/export
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Regions of a scene written to a file: a page, a selection or any world-space
4
+ rect, as PNG or any format another package registers.
5
+
6
+ Part of [weasel](https://github.com/orochi235/weasel), a domain-agnostic
7
+ scene-graph engine for React. See the
8
+ [API reference](https://orochi235.github.io/weasel/#pkg/export).
9
+
10
+ ```sh
11
+ npm install @weasel-js/export
12
+ ```
13
+
14
+ A registry of export formats, each writing one or more world-space rectangles
15
+ of a `@weasel-js/core` scene to a file. This package registers `png`;
16
+ `@weasel-js/svg` registers `svg` (`registerSvgExport()`) and
17
+ `@weasel-js/pdf/export` registers `pdf` (`registerPdfExport()`), so it depends
18
+ on neither.
19
+
20
+ ```ts
21
+ import { placedPagesOf, viewportWorldRect } from '@weasel-js/core';
22
+ import { exportPages, exportRegions, selectionRegion } from '@weasel-js/export';
23
+
24
+ const pages = placedPagesOf(scene);
25
+ const png = await exportPages(scene, [pages[0]], 'png', { scale: 2, background: '#ffffff' });
26
+ const shown = await exportRegions(scene, [viewportWorldRect(view, { width, height })], 'png');
27
+ const picked = await exportRegions(scene, [selectionRegion(scene, selection.get())!], 'svg');
28
+ ```
29
+
30
+ A region is an `ExportRegion`: `{ x, y, width, height, name? }` in world
31
+ units. `exportPages` makes one of each `PlacedPage`, named as the page order
32
+ shows it; `viewportWorldRect(view, size)` is the one a view shows;
33
+ `selectionRegion(scene, ids)` is the box the ids draw, strokes included.
34
+ `name` labels a PDF page and titles an SVG.
35
+
36
+ A region is of the document: every format draws each layer at its document
37
+ pose, a parallax layer's included, so what a page or selection holds lands
38
+ inside it at any `scale`. Parallax is the camera's, and a region export has
39
+ none. To capture what a camera shows, planes and all, render with that camera:
40
+ `renderSceneToPixels({ scene, sourceRect: viewportWorldRect(view, size), scale, camera: view })`
41
+ places each plane as `view` does, and its `scale` changes only the resolution.
42
+
43
+ `exportRegions(scene, regions, formatId, opts)` writes them in the format
44
+ registered under `formatId` and answers a `Blob`. It rejects for an id nothing
45
+ registered, and for several regions handed to a format that is not
46
+ `multiRegion`. Every format takes `background` (default none: core holds no
47
+ page color), `onDiagnostic`, and `strict`; the rest of `opts`
48
+ goes to the format (`scale` for `png`, `title` for `svg` and `pdf`).
49
+ `exportFormats()` lists what is registered, `png` first, the same array until
50
+ the registry changes; `exportFormatRegistry` is its reflection, with
51
+ `subscribe` for a menu that lists them. `registerExportFormat(format)` adds
52
+ one and returns its disposer; registering an id that is held overrides it.
53
+
54
+ Each export draws the document, not what an open gesture or edit is showing,
55
+ writes nothing to the scene, and leaves annotation layers out. It draws one
56
+ revision of it: `captureExport` loads what the regions need, and reads them
57
+ only if no content changed meanwhile, or starts again, up to
58
+ `EXPORT_CAPTURE_ATTEMPTS` times before rejecting with `ExportRevisionError`.
59
+ Regions may be a function of the document, `(doc) => regions`, read again each
60
+ time, so bounds measured from it belong to the revision drawn: `exportPages`
61
+ places its pages that way, by id, through `pageRegionsOf(pages)`, and
62
+ `pageRegionOf(page)` is the same for one page. A format of your own goes through
63
+ `captureExport` too, warming in `warm` and reading everything it writes in
64
+ `read`.
65
+ What an export draws without reaches `onDiagnostic` once each, as an
66
+ `ExportDiagnostic`: `{ kind, subject, message }`, where `kind` is `image` (a
67
+ picture that failed to load, drawn as a placeholder), `font` (a face that
68
+ failed, or glyphs a format could not carry), `paint-kind` (a kind nothing
69
+ registered, or one whose load failed), `shader` (a program with no source the
70
+ target draws), or `unsupported` (what the format cannot hold), and `subject`
71
+ names the source, family, kind or program. An export is best-effort: it
72
+ writes the file without them, so a caller that heard nothing has a complete
73
+ file. With `strict: true` it writes nothing when it hears anything and rejects
74
+ with `ExportIncompleteError`, whose `diagnostics` lists them. Nothing goes to
75
+ the console. A format of your own reports through `exportReporter(opts)`, and
76
+ `warmRender({ render, report })` reports a headless render's losses the same way.
77
+
78
+ `exportRegionPng(scene, region, { scale, background })` is the `png` format
79
+ on its own: the renderer's pixels, `region × scale` in size. It needs WebGL2.
80
+
81
+ `regionRenderArgs(scene, region, { scale, background })` is the render a
82
+ region draws with, which the PNG and PDF exports build on. Handed to
83
+ `@weasel-js/headless`'s raster host as they are, they render a region from
84
+ Node.
@@ -0,0 +1,221 @@
1
+ import { Reflection } from '@weasel-js/registry';
2
+ import { Rect } from '@weasel-js/geom';
3
+ import { Scene, RectPose, RenderDiagnostic, PlacedPage, RenderSceneToPixelsArgs, RenderDiagnosticSink } from '@weasel-js/core';
4
+
5
+ /** The types the export registry and its formats share. */
6
+
7
+ /**
8
+ * A rectangle of the document to export: a page (`exportPages` makes one of
9
+ * each `PlacedPage`), the world rect a view spans (`viewportWorldRect`), a
10
+ * selection's bounds, or any other. Every format draws each layer in it at its
11
+ * document pose: a parallax layer's camera tracking is not applied. `name` is
12
+ * what a format that labels its pages or documents calls it: a PDF page's
13
+ * label, an SVG's `<title>`.
14
+ */
15
+ interface ExportRegion extends Rect {
16
+ readonly name?: string;
17
+ }
18
+ /**
19
+ * The regions an export writes: fixed rects, or a function reading them from
20
+ * the document. A function is called each time the export reads the document,
21
+ * so bounds that come from it, a page's or a selection's, belong to the same
22
+ * revision as what is drawn in them.
23
+ */
24
+ type ExportRegions = readonly ExportRegion[] | ((doc: ExportScene) => readonly ExportRegion[]);
25
+ /** One region an export writes, fixed or read from the document, as {@link ExportRegions} holds them. */
26
+ type ExportRegionSource = ExportRegion | ((doc: ExportScene) => ExportRegion);
27
+ /** A scene as the exports read it: world-space `RectPose`s. */
28
+ type ExportScene = Scene<unknown, string, RectPose>;
29
+ /** What every format takes. */
30
+ interface ExportOptions {
31
+ /** The color painted under each region. Default none: core holds no page color. */
32
+ background?: string | null;
33
+ /** Hears each thing the export could not draw or load, once: a picture or face
34
+ * that failed, a paint kind or shader nothing can draw, what the format cannot hold. */
35
+ onDiagnostic?: (diagnostic: RenderDiagnostic) => void;
36
+ /** Write nothing when anything is diagnosed, and reject with `ExportIncompleteError`.
37
+ * Default `false`: best-effort, the file is written without it. */
38
+ strict?: boolean;
39
+ }
40
+ /**
41
+ * One way of writing regions of a scene to a file, registered with
42
+ * `registerExportFormat`. `TOptions` is what the format reads beyond
43
+ * {@link ExportOptions}. `exportRegions` hands a format whatever its caller
44
+ * passed, so a format treats every option of its own as optional there.
45
+ */
46
+ interface ExportFormat<TOptions extends ExportOptions = ExportOptions> {
47
+ /** The id `exportRegions` names it by: `'png'`, `'svg'`, `'pdf'`. */
48
+ readonly id: string;
49
+ /** What a menu calls it: "PNG Image". */
50
+ readonly label: string;
51
+ readonly mimeType: string;
52
+ /** The file extension, without the dot. */
53
+ readonly extension: string;
54
+ /** Whether one file holds several regions, as a PDF's pages do. A single-region format takes exactly one. */
55
+ readonly multiRegion: boolean;
56
+ export(scene: ExportScene, regions: ExportRegions, opts: TOptions): Promise<Blob>;
57
+ }
58
+
59
+ /**
60
+ * The export registry: the formats a scene's regions can be written in, each
61
+ * registered by the package that can write it. This package registers `png`;
62
+ * svg and pdf register theirs (`registerSvgExport`, `registerPdfExport`), so it
63
+ * depends on neither.
64
+ */
65
+
66
+ /** Every registered export format, keyed by id, with the overrides each displaced. */
67
+ declare const exportFormatRegistry: Reflection<ExportFormat>;
68
+ /**
69
+ * Register an export format. Returns a disposer that removes this
70
+ * registration. Registering an id already held overrides it, `png` included;
71
+ * disposing uncovers what it displaced.
72
+ */
73
+ declare function registerExportFormat<TOptions extends ExportOptions>(format: ExportFormat<TOptions>): () => void;
74
+ /** Every registered format, `png` first, then in registration order. The same array until the registry changes. */
75
+ declare function exportFormats(): readonly ExportFormat[];
76
+ /**
77
+ * Write `regions` of `scene` in the format registered as `formatId`. Throws
78
+ * for an id nothing registered, and for more or fewer than one region handed
79
+ * to a format that is not `multiRegion`; a multi-region format takes one or
80
+ * more. Regions given as a function of the document are counted each time
81
+ * the export reads them.
82
+ */
83
+ declare function exportRegions(scene: ExportScene, regions: ExportRegions, formatId: string, opts?: ExportOptions & Readonly<Record<string, unknown>>): Promise<Blob>;
84
+
85
+ /** `page` as an export region, named as the page order shows it. */
86
+ declare function pageRegion(page: PlacedPage): ExportRegion;
87
+ /**
88
+ * `pages` as regions read from the document an export draws: each page placed
89
+ * as that document places it, found by its id, and named for it. A page the
90
+ * document no longer holds fails the export.
91
+ */
92
+ declare function pageRegionsOf(pages: readonly PlacedPage[]): (doc: ExportScene) => readonly ExportRegion[];
93
+ /** One page as {@link pageRegionsOf} reads it: the region source of a single-region export. */
94
+ declare function pageRegionOf(page: PlacedPage): (doc: ExportScene) => ExportRegion;
95
+ /**
96
+ * Write `pages` of `scene` in the format registered as `formatId`, each page
97
+ * a region named for the page: `exportRegions` over {@link pageRegionsOf}. A
98
+ * single-region format takes one page.
99
+ */
100
+ declare function exportPages(scene: ExportScene, pages: readonly PlacedPage[], formatId: string, opts?: ExportOptions & Readonly<Record<string, unknown>>): Promise<Blob>;
101
+
102
+ /** Options for {@link exportRegionPng}. */
103
+ interface ExportRegionPngOptions extends Pick<ExportOptions, 'onDiagnostic' | 'strict'> {
104
+ /** Output pixels per world unit: 2 makes an image twice the region's size. */
105
+ scale: number;
106
+ /** The color painted under the region. Default none: the image is transparent where nothing is drawn. */
107
+ background?: string | null;
108
+ }
109
+ /**
110
+ * Draw `region` of `scene` into a PNG, `region × scale` pixels, through the
111
+ * renderer the canvas draws with, so it shows what the canvas shows, cut to
112
+ * the region's edges. It draws the document: a gesture or edit in flight is
113
+ * not shown. Annotation layers are left out.
114
+ *
115
+ * The caller has registered whatever the scene needs painting with, as it
116
+ * must to draw it at all: its painters (`registerNodeShape`) and its fonts.
117
+ * Paint kinds and faces that load on demand are waited for, and the image is
118
+ * of one revision of the document: see `captureExport`. What it draws
119
+ * without goes to `onDiagnostic`, and a `strict` export rejects with
120
+ * `ExportIncompleteError` rather than write it. Needs WebGL2.
121
+ */
122
+ declare function exportRegionPng(scene: ExportScene, region: ExportRegionSource, opts: ExportRegionPngOptions): Promise<Blob>;
123
+ /** The `png` format's own option. */
124
+ interface PngExportOptions extends ExportOptions {
125
+ /** Output pixels per world unit. Default 1. */
126
+ scale?: number;
127
+ }
128
+
129
+ /**
130
+ * The world box `ids` cover as the document draws them, strokes included:
131
+ * the region that exports a selection. Pages and the page run are left out of
132
+ * `ids`. `null` when none of them draws anything.
133
+ */
134
+ declare function selectionRegion(scene: ExportScene, ids: readonly string[], name?: string): ExportRegion | null;
135
+
136
+ /** What {@link regionRenderArgs} answers: the part of `renderSceneToPixels`'s arguments a region decides. */
137
+ type RegionRenderArgs = Pick<RenderSceneToPixelsArgs<unknown, string, RectPose>, 'scene' | 'sourceRect' | 'scale' | 'background'>;
138
+ /** Options for {@link regionRenderArgs}. */
139
+ interface RegionRenderArgsOptions {
140
+ /** Output pixels per world unit. */
141
+ scale: number;
142
+ /** The color painted under the region. Default none: transparent. */
143
+ background?: string | null;
144
+ }
145
+ /**
146
+ * The arguments `region` of `scene` renders with: the scene's document (not
147
+ * what an open gesture or edit is showing), the region as the source rect, and
148
+ * `scale` on both axes. The PNG and PDF exports draw through these.
149
+ *
150
+ * Outside a browser, hand them to `@weasel-js/headless`'s raster host, whose
151
+ * `NodeRenderArgs` they satisfy as they are, to render a page or any other
152
+ * region from Node.
153
+ */
154
+ declare function regionRenderArgs(scene: ExportScene, region: ExportRegion, opts: RegionRenderArgsOptions): RegionRenderArgs;
155
+
156
+ /**
157
+ * The one boundary every export reads the document at: what it draws comes
158
+ * from a single revision, with what that revision needs loaded.
159
+ */
160
+
161
+ /** How many times an export reads the document before giving up on it holding still. */
162
+ declare const EXPORT_CAPTURE_ATTEMPTS = 3;
163
+ /** An export gave up: the document changed while each of its attempts loaded what it draws. */
164
+ declare class ExportRevisionError extends Error {
165
+ readonly attempts: number;
166
+ constructor(attempts: number);
167
+ }
168
+ /** The two halves of an export's read of the document, as {@link captureExport} runs them. Each
169
+ * reports what the export will draw without to `report`. */
170
+ interface ExportCaptureSteps<T> {
171
+ /** Load what drawing `regions` of `doc` needs: fonts, paint kinds, pictures. */
172
+ warm(doc: ExportScene, regions: readonly ExportRegion[], report: RenderDiagnosticSink): Promise<void>;
173
+ /** Read everything the file is written from, synchronously, into values the document cannot change. */
174
+ read(doc: ExportScene, regions: readonly ExportRegion[], report: RenderDiagnosticSink): T;
175
+ }
176
+ /** One region source as the {@link ExportRegions} {@link captureExport} takes. */
177
+ declare const regionsOfOne: (region: ExportRegionSource) => ExportRegions;
178
+ /** `regions` as of `doc`: each a copy, so a caller's later edit to one reaches no export in flight. */
179
+ declare function exportRegionsOf(regions: ExportRegions, doc: ExportScene): readonly ExportRegion[];
180
+ /**
181
+ * Read `regions` of `scene`'s document through `steps`, from one content
182
+ * revision (`getContentVersion`): warm, then, if no content changed while it
183
+ * loaded, read at once, in the same task. Fixed regions are copied when it is
184
+ * called. A change restarts it, with the
185
+ * regions read again when they are a function of the document, so the bounds
186
+ * and the content come from the same revision. After
187
+ * {@link EXPORT_CAPTURE_ATTEMPTS} attempts it rejects with
188
+ * {@link ExportRevisionError}.
189
+ *
190
+ * What a gesture or an open edit shows is never read, and a change of
191
+ * selection restarts nothing. The painters, paint kinds and fonts registered
192
+ * when `read` runs are the ones it draws with. What the steps report reaches
193
+ * `report` only from the attempt that is read, once it has been.
194
+ */
195
+ declare function captureExport<T>(scene: ExportScene, regions: ExportRegions, steps: ExportCaptureSteps<T>, report?: RenderDiagnosticSink): Promise<T>;
196
+
197
+ /** How every export reports what it could not draw, and when it refuses to write a file without it. */
198
+
199
+ /** One thing an export drew without, or drew in part: a `RenderDiagnostic`. */
200
+ type ExportDiagnostic = RenderDiagnostic;
201
+ /** A strict export (`strict: true`) found something it could not draw, and wrote nothing. */
202
+ declare class ExportIncompleteError extends Error {
203
+ readonly diagnostics: readonly ExportDiagnostic[];
204
+ constructor(diagnostics: readonly ExportDiagnostic[]);
205
+ }
206
+ /** One export's diagnostics: `report` hears each, `settle` ends the export's reporting. */
207
+ interface ExportReporter {
208
+ readonly report: RenderDiagnosticSink;
209
+ /** Throws {@link ExportIncompleteError} for a strict export that reported anything. */
210
+ settle(): void;
211
+ }
212
+ /**
213
+ * The reporter an export with `opts` reports through. Each diagnostic reaches
214
+ * `onDiagnostic` once, however often it is found. Best-effort, the default,
215
+ * writes the file without what it reports; `strict` writes none when it
216
+ * reports anything, and `settle` throws instead.
217
+ */
218
+ declare function exportReporter(opts: Pick<ExportOptions, 'onDiagnostic' | 'strict'>): ExportReporter;
219
+
220
+ export { EXPORT_CAPTURE_ATTEMPTS, ExportIncompleteError, ExportRevisionError, captureExport, exportFormatRegistry, exportFormats, exportPages, exportRegionPng, exportRegions, exportRegionsOf, exportReporter, pageRegion, pageRegionOf, pageRegionsOf, regionRenderArgs, regionsOfOne, registerExportFormat, selectionRegion };
221
+ export type { ExportCaptureSteps, ExportDiagnostic, ExportFormat, ExportOptions, ExportRegion, ExportRegionPngOptions, ExportRegionSource, ExportRegions, ExportReporter, ExportScene, PngExportOptions, RegionRenderArgs, RegionRenderArgsOptions };
package/dist/index.js ADDED
@@ -0,0 +1,205 @@
1
+ import { createReflectable } from '@weasel-js/registry';
2
+ import { holdImageBitmaps } from '@weasel-js/renderer';
3
+ import { documentOf, createRasterSession, rasterToPng, pageName, placedPagesOf, worldPoseLookup, scenePoseAdapter, drawnBoundsScene, withoutPageStructure, drawnAABBOf, unionAABB, planPixelRender, warmRender } from '@weasel-js/core';
4
+
5
+ // src/exportFormats.ts
6
+ var EXPORT_CAPTURE_ATTEMPTS = 3;
7
+ var ExportRevisionError = class extends Error {
8
+ constructor(attempts) {
9
+ super(`export: the document changed while the export loaded what it draws, ${attempts} times running; nothing was written`);
10
+ this.attempts = attempts;
11
+ }
12
+ attempts;
13
+ };
14
+ var regionsOfOne = (region) => typeof region === "function" ? (doc) => [region(doc)] : [region];
15
+ function exportRegionsOf(regions, doc) {
16
+ const list = typeof regions === "function" ? regions(doc) : regions;
17
+ return Object.freeze(list.map((r) => Object.freeze({ ...r })));
18
+ }
19
+ async function captureExport(scene, regions, steps, report = () => {
20
+ }) {
21
+ const doc = documentOf(scene);
22
+ const source = typeof regions === "function" ? regions : exportRegionsOf(regions, doc);
23
+ for (let attempt = 1; ; attempt++) {
24
+ const revision = scene.getContentVersion();
25
+ const heard = [];
26
+ const hear = (d) => {
27
+ heard.push(d);
28
+ };
29
+ await steps.warm(doc, exportRegionsOf(source, doc), hear);
30
+ if (scene.getContentVersion() === revision) {
31
+ const read = steps.read(doc, exportRegionsOf(source, doc), hear);
32
+ heard.forEach(report);
33
+ return read;
34
+ }
35
+ if (attempt >= EXPORT_CAPTURE_ATTEMPTS) throw new ExportRevisionError(attempt);
36
+ }
37
+ }
38
+
39
+ // src/exportDiagnostics.ts
40
+ var ExportIncompleteError = class extends Error {
41
+ constructor(diagnostics) {
42
+ super(`export: ${diagnostics.length === 1 ? "one thing" : `${diagnostics.length} things`} could not be drawn, and a strict export writes nothing without them: ${diagnostics.map((d) => d.message).join("; ")}`);
43
+ this.diagnostics = diagnostics;
44
+ }
45
+ diagnostics;
46
+ };
47
+ function exportReporter(opts) {
48
+ const seen = /* @__PURE__ */ new Map();
49
+ return {
50
+ report(d) {
51
+ const key = `${d.kind}\0${d.subject}\0${d.message}`;
52
+ if (seen.has(key)) return;
53
+ seen.set(key, d);
54
+ opts.onDiagnostic?.(d);
55
+ },
56
+ settle() {
57
+ if (opts.strict && seen.size > 0) throw new ExportIncompleteError([...seen.values()]);
58
+ }
59
+ };
60
+ }
61
+ function regionRenderArgs(scene, region, opts) {
62
+ return {
63
+ scene: documentOf(scene),
64
+ sourceRect: { x: region.x, y: region.y, width: region.width, height: region.height },
65
+ scale: { x: opts.scale, y: opts.scale },
66
+ ...opts.background != null ? { background: opts.background } : {}
67
+ };
68
+ }
69
+
70
+ // src/regionPng.ts
71
+ function capturePngRegion(scene, region, opts, report) {
72
+ return captureExport(scene, regionsOfOne(region), {
73
+ warm: (doc, [r], hear) => warmRender({ render: regionRenderArgs(doc, r, opts), report: hear }),
74
+ read: (doc, [r]) => planPixelRender(regionRenderArgs(doc, r, opts))
75
+ }, report);
76
+ }
77
+ async function exportRegionPng(scene, region, opts) {
78
+ const reporter = exportReporter(opts);
79
+ const release = holdImageBitmaps();
80
+ try {
81
+ const plan = await capturePngRegion(scene, region, opts, reporter.report);
82
+ reporter.settle();
83
+ const session = createRasterSession();
84
+ try {
85
+ return await rasterToPng(session.renderPlan(plan));
86
+ } finally {
87
+ session.dispose();
88
+ }
89
+ } finally {
90
+ release();
91
+ }
92
+ }
93
+ var PNG_EXPORT = {
94
+ id: "png",
95
+ label: "PNG Image",
96
+ mimeType: "image/png",
97
+ extension: "png",
98
+ multiRegion: false,
99
+ export: (scene, regions, opts) => exportRegionPng(scene, typeof regions === "function" ? (doc) => regions(doc)[0] : regions[0], {
100
+ scale: opts.scale ?? 1,
101
+ ...opts.background !== void 0 ? { background: opts.background } : {},
102
+ ...opts.onDiagnostic ? { onDiagnostic: opts.onDiagnostic } : {},
103
+ ...opts.strict !== void 0 ? { strict: opts.strict } : {}
104
+ })
105
+ };
106
+
107
+ // src/exportFormats.ts
108
+ var FORMATS = createReflectable();
109
+ var builtInsRegistered = false;
110
+ function ensureBuiltIns() {
111
+ if (builtInsRegistered) return;
112
+ builtInsRegistered = true;
113
+ FORMATS.push(PNG_EXPORT.id, PNG_EXPORT, { source: "kit" });
114
+ }
115
+ var exportFormatRegistry = {
116
+ get: (id) => {
117
+ ensureBuiltIns();
118
+ return FORMATS.get(id);
119
+ },
120
+ has: (id) => {
121
+ ensureBuiltIns();
122
+ return FORMATS.has(id);
123
+ },
124
+ entries: () => {
125
+ ensureBuiltIns();
126
+ return FORMATS.entries();
127
+ },
128
+ subscribe: (listener) => {
129
+ ensureBuiltIns();
130
+ return FORMATS.subscribe(listener);
131
+ },
132
+ getVersion: () => {
133
+ ensureBuiltIns();
134
+ return FORMATS.getVersion();
135
+ }
136
+ };
137
+ function registerExportFormat(format) {
138
+ ensureBuiltIns();
139
+ return FORMATS.push(format.id, format);
140
+ }
141
+ var listed = null;
142
+ function exportFormats() {
143
+ const entries = exportFormatRegistry.entries();
144
+ if (listed?.from !== entries) listed = { from: entries, formats: Object.freeze(entries.map((e) => e.value)) };
145
+ return listed.formats;
146
+ }
147
+ function exportRegions(scene, regions, formatId, opts = {}) {
148
+ const format = exportFormatRegistry.get(formatId);
149
+ if (!format) {
150
+ const known = exportFormats().map((f) => f.id).join(", ");
151
+ return Promise.reject(new Error(`exportRegions: no export format "${formatId}" is registered (registered: ${known})`));
152
+ }
153
+ if (typeof regions !== "function") {
154
+ try {
155
+ checkCount(format, regions);
156
+ } catch (err) {
157
+ return Promise.reject(err);
158
+ }
159
+ return format.export(scene, regions, opts);
160
+ }
161
+ return format.export(scene, (doc) => checkCount(format, regions(doc)), opts);
162
+ }
163
+ function checkCount(format, regions) {
164
+ if (regions.length === 0) throw new Error(`exportRegions: "${format.id}" was handed no regions`);
165
+ if (!format.multiRegion && regions.length > 1) {
166
+ throw new Error(`exportRegions: "${format.id}" writes one region to a file and was handed ${regions.length}; export them one at a time`);
167
+ }
168
+ return regions;
169
+ }
170
+ function pageRegion(page) {
171
+ return { x: page.x, y: page.y, width: page.width, height: page.height, name: pageName(page, page.index) };
172
+ }
173
+ function pageRegionsOf(pages) {
174
+ const ids = pages.map((p) => p.id);
175
+ return (doc) => {
176
+ const placed = new Map(placedPagesOf(doc).map((p) => [p.id, p]));
177
+ return ids.map((id) => {
178
+ const page = placed.get(id);
179
+ if (page === void 0) throw new Error(`exportPages: the document holds no page "${id}"`);
180
+ return pageRegion(page);
181
+ });
182
+ };
183
+ }
184
+ function pageRegionOf(page) {
185
+ const read = pageRegionsOf([page]);
186
+ return (doc) => read(doc)[0];
187
+ }
188
+ function exportPages(scene, pages, formatId, opts = {}) {
189
+ return exportRegions(scene, pageRegionsOf(pages), formatId, opts);
190
+ }
191
+ function selectionRegion(scene, ids, name) {
192
+ const doc = documentOf(scene);
193
+ const world = worldPoseLookup(scenePoseAdapter(doc), doc.composition.compose);
194
+ const drawn = drawnBoundsScene(doc);
195
+ const boxes = withoutPageStructure(doc, ids).map((id) => {
196
+ const pose = world(id);
197
+ return pose === null || doc.get(id) === void 0 ? null : drawnAABBOf(drawn, id, pose, { worldPoseOf: (m) => world(m) });
198
+ });
199
+ const box = unionAABB(boxes);
200
+ return box === null ? null : { x: box.x, y: box.y, width: box.width, height: box.height, ...name !== void 0 ? { name } : {} };
201
+ }
202
+
203
+ export { EXPORT_CAPTURE_ATTEMPTS, ExportIncompleteError, ExportRevisionError, captureExport, exportFormatRegistry, exportFormats, exportPages, exportRegionPng, exportRegions, exportRegionsOf, exportReporter, pageRegion, pageRegionOf, pageRegionsOf, regionRenderArgs, regionsOfOne, registerExportFormat, selectionRegion };
204
+ //# sourceMappingURL=index.js.map
205
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/captureExport.ts","../src/exportDiagnostics.ts","../src/regionRenderArgs.ts","../src/regionPng.ts","../src/exportFormats.ts","../src/exportPages.ts","../src/selectionRegion.ts"],"names":["documentOf"],"mappings":";;;;;AAQO,IAAM,uBAAA,GAA0B;AAGhC,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,YAAqB,QAAA,EAAkB;AACrC,IAAA,KAAA,CAAM,CAAA,oEAAA,EAAuE,QAAQ,CAAA,mCAAA,CAAqC,CAAA;AADvG,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EAErB;AAAA,EAFqB,QAAA;AAGvB;AAYO,IAAM,YAAA,GAAe,CAAC,MAAA,KAC3B,OAAO,WAAW,UAAA,GAAa,CAAC,GAAA,KAAQ,CAAC,MAAA,CAAO,GAAG,CAAC,CAAA,GAAI,CAAC,MAAM;AAG1D,SAAS,eAAA,CAAgB,SAAwB,GAAA,EAA2C;AACjG,EAAA,MAAM,OAAO,OAAO,OAAA,KAAY,UAAA,GAAa,OAAA,CAAQ,GAAG,CAAA,GAAI,OAAA;AAC5D,EAAA,OAAO,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,KAAM,MAAA,CAAO,MAAA,CAAO,EAAE,GAAG,CAAA,EAAG,CAAC,CAAC,CAAA;AAC/D;AAiBA,eAAsB,aAAA,CACpB,KAAA,EAAoB,OAAA,EAAwB,KAAA,EAA8B,SAA+B,MAAM;AAAC,CAAA,EACpG;AACZ,EAAA,MAAM,GAAA,GAAM,WAAW,KAAK,CAAA;AAC5B,EAAA,MAAM,SAAS,OAAO,OAAA,KAAY,aAAa,OAAA,GAAU,eAAA,CAAgB,SAAS,GAAG,CAAA;AACrF,EAAA,KAAA,IAAS,OAAA,GAAU,KAAK,OAAA,EAA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G,GAAA,CAAI,CAAA,EAAG,CAAA,EAAG,GAAA,CAAI,CAAA,EAAG,KAAA,EAAO,IAAI,KAAA,EAAO,MAAA,EAAQ,GAAA,CAAI,MAAA,EAAQ,GAAI,IAAA,KAAS,SAAY,EAAE,IAAA,EAAK,GAAI,EAAC,EAAG;AACnI","file":"index.js","sourcesContent":["/**\n * The one boundary every export reads the document at: what it draws comes\n * from a single revision, with what that revision needs loaded.\n */\nimport { documentOf, type RenderDiagnostic, type RenderDiagnosticSink } from '@weasel-js/core';\nimport type { ExportRegion, ExportRegionSource, ExportRegions, ExportScene } from './exportTypes';\n\n/** How many times an export reads the document before giving up on it holding still. */\nexport const EXPORT_CAPTURE_ATTEMPTS = 3;\n\n/** An export gave up: the document changed while each of its attempts loaded what it draws. */\nexport class ExportRevisionError extends Error {\n constructor(readonly attempts: number) {\n super(`export: the document changed while the export loaded what it draws, ${attempts} times running; nothing was written`);\n }\n}\n\n/** The two halves of an export's read of the document, as {@link captureExport} runs them. Each\n * reports what the export will draw without to `report`. */\nexport interface ExportCaptureSteps<T> {\n /** Load what drawing `regions` of `doc` needs: fonts, paint kinds, pictures. */\n warm(doc: ExportScene, regions: readonly ExportRegion[], report: RenderDiagnosticSink): Promise<void>;\n /** Read everything the file is written from, synchronously, into values the document cannot change. */\n read(doc: ExportScene, regions: readonly ExportRegion[], report: RenderDiagnosticSink): T;\n}\n\n/** One region source as the {@link ExportRegions} {@link captureExport} takes. */\nexport const regionsOfOne = (region: ExportRegionSource): ExportRegions =>\n typeof region === 'function' ? (doc) => [region(doc)] : [region];\n\n/** `regions` as of `doc`: each a copy, so a caller's later edit to one reaches no export in flight. */\nexport function exportRegionsOf(regions: ExportRegions, doc: ExportScene): readonly ExportRegion[] {\n const list = typeof regions === 'function' ? regions(doc) : regions;\n return Object.freeze(list.map((r) => Object.freeze({ ...r })));\n}\n\n/**\n * Read `regions` of `scene`'s document through `steps`, from one content\n * revision (`getContentVersion`): warm, then, if no content changed while it\n * loaded, read at once, in the same task. Fixed regions are copied when it is\n * called. A change restarts it, with the\n * regions read again when they are a function of the document, so the bounds\n * and the content come from the same revision. After\n * {@link EXPORT_CAPTURE_ATTEMPTS} attempts it rejects with\n * {@link ExportRevisionError}.\n *\n * What a gesture or an open edit shows is never read, and a change of\n * selection restarts nothing. The painters, paint kinds and fonts registered\n * when `read` runs are the ones it draws with. What the steps report reaches\n * `report` only from the attempt that is read, once it has been.\n */\nexport async function captureExport<T>(\n scene: ExportScene, regions: ExportRegions, steps: ExportCaptureSteps<T>, report: RenderDiagnosticSink = () => {},\n): Promise<T> {\n const doc = documentOf(scene);\n const source = typeof regions === 'function' ? regions : exportRegionsOf(regions, doc);\n for (let attempt = 1; ; attempt++) {\n const revision = scene.getContentVersion();\n const heard: RenderDiagnostic[] = [];\n const hear = (d: RenderDiagnostic) => { heard.push(d); };\n await steps.warm(doc, exportRegionsOf(source, doc), hear);\n if (scene.getContentVersion() === revision) {\n const read = steps.read(doc, exportRegionsOf(source, doc), hear);\n heard.forEach(report);\n return read;\n }\n if (attempt >= EXPORT_CAPTURE_ATTEMPTS) throw new ExportRevisionError(attempt);\n }\n}\n","/** How every export reports what it could not draw, and when it refuses to write a file without it. */\nimport type { RenderDiagnostic, RenderDiagnosticSink } from '@weasel-js/core';\nimport type { ExportOptions } from './exportTypes';\n\n/** One thing an export drew without, or drew in part: a `RenderDiagnostic`. */\nexport type ExportDiagnostic = RenderDiagnostic;\n\n/** A strict export (`strict: true`) found something it could not draw, and wrote nothing. */\nexport class ExportIncompleteError extends Error {\n constructor(readonly diagnostics: readonly ExportDiagnostic[]) {\n super(`export: ${diagnostics.length === 1 ? 'one thing' : `${diagnostics.length} things`} could not be drawn, and a strict export writes nothing without them: ${\n diagnostics.map((d) => d.message).join('; ')}`);\n }\n}\n\n/** One export's diagnostics: `report` hears each, `settle` ends the export's reporting. */\nexport interface ExportReporter {\n readonly report: RenderDiagnosticSink;\n /** Throws {@link ExportIncompleteError} for a strict export that reported anything. */\n settle(): void;\n}\n\n/**\n * The reporter an export with `opts` reports through. Each diagnostic reaches\n * `onDiagnostic` once, however often it is found. Best-effort, the default,\n * writes the file without what it reports; `strict` writes none when it\n * reports anything, and `settle` throws instead.\n */\nexport function exportReporter(opts: Pick<ExportOptions, 'onDiagnostic' | 'strict'>): ExportReporter {\n const seen = new Map<string, ExportDiagnostic>();\n return {\n report(d) {\n const key = `${d.kind}\\u0000${d.subject}\\u0000${d.message}`;\n if (seen.has(key)) return;\n seen.set(key, d);\n opts.onDiagnostic?.(d);\n },\n settle() {\n if (opts.strict && seen.size > 0) throw new ExportIncompleteError([...seen.values()]);\n },\n };\n}\n","import { documentOf, type RectPose, type RenderSceneToPixelsArgs } from '@weasel-js/core';\nimport type { ExportRegion, ExportScene } from './exportTypes';\n\n/** What {@link regionRenderArgs} answers: the part of `renderSceneToPixels`'s arguments a region decides. */\nexport type RegionRenderArgs = Pick<RenderSceneToPixelsArgs<unknown, string, RectPose>, 'scene' | 'sourceRect' | 'scale' | 'background'>;\n\n/** Options for {@link regionRenderArgs}. */\nexport interface RegionRenderArgsOptions {\n /** Output pixels per world unit. */\n scale: number;\n /** The color painted under the region. Default none: transparent. */\n background?: string | null;\n}\n\n/**\n * The arguments `region` of `scene` renders with: the scene's document (not\n * what an open gesture or edit is showing), the region as the source rect, and\n * `scale` on both axes. The PNG and PDF exports draw through these.\n *\n * Outside a browser, hand them to `@weasel-js/headless`'s raster host, whose\n * `NodeRenderArgs` they satisfy as they are, to render a page or any other\n * region from Node.\n */\nexport function regionRenderArgs(scene: ExportScene, region: ExportRegion, opts: RegionRenderArgsOptions): RegionRenderArgs {\n return {\n scene: documentOf(scene),\n sourceRect: { x: region.x, y: region.y, width: region.width, height: region.height },\n scale: { x: opts.scale, y: opts.scale },\n ...(opts.background != null ? { background: opts.background } : {}),\n };\n}\n","import { holdImageBitmaps } from '@weasel-js/renderer';\nimport { createRasterSession, planPixelRender, rasterToPng, warmRender, type PixelRenderPlan, type RenderDiagnosticSink } from '@weasel-js/core';\nimport { captureExport, regionsOfOne } from './captureExport';\nimport { exportReporter } from './exportDiagnostics';\nimport type { ExportFormat, ExportOptions, ExportRegionSource, ExportScene } from './exportTypes';\nimport { regionRenderArgs } from './regionRenderArgs';\n\n/** Options for {@link exportRegionPng}. */\nexport interface ExportRegionPngOptions extends Pick<ExportOptions, 'onDiagnostic' | 'strict'> {\n /** Output pixels per world unit: 2 makes an image twice the region's size. */\n scale: number;\n /** The color painted under the region. Default none: the image is transparent where nothing is drawn. */\n background?: string | null;\n}\n\n/** The plan a PNG of `region` draws, read through `captureExport` from one revision of the document, its faces,\n * kinds and pictures loaded, and what it draws without told to `report`. */\nexport function capturePngRegion(\n scene: ExportScene, region: ExportRegionSource, opts: ExportRegionPngOptions, report?: RenderDiagnosticSink,\n): Promise<PixelRenderPlan> {\n return captureExport(scene, regionsOfOne(region), {\n warm: (doc, [r], hear) => warmRender({ render: regionRenderArgs(doc, r!, opts), report: hear }),\n read: (doc, [r]) => planPixelRender(regionRenderArgs(doc, r!, opts)),\n }, report);\n}\n\n/**\n * Draw `region` of `scene` into a PNG, `region × scale` pixels, through the\n * renderer the canvas draws with, so it shows what the canvas shows, cut to\n * the region's edges. It draws the document: a gesture or edit in flight is\n * not shown. Annotation layers are left out.\n *\n * The caller has registered whatever the scene needs painting with, as it\n * must to draw it at all: its painters (`registerNodeShape`) and its fonts.\n * Paint kinds and faces that load on demand are waited for, and the image is\n * of one revision of the document: see `captureExport`. What it draws\n * without goes to `onDiagnostic`, and a `strict` export rejects with\n * `ExportIncompleteError` rather than write it. Needs WebGL2.\n */\nexport async function exportRegionPng(scene: ExportScene, region: ExportRegionSource, opts: ExportRegionPngOptions): Promise<Blob> {\n const reporter = exportReporter(opts);\n // The plan's pictures stay open until it is drawn.\n const release = holdImageBitmaps();\n try {\n const plan = await capturePngRegion(scene, region, opts, reporter.report);\n reporter.settle();\n const session = createRasterSession();\n try {\n return await rasterToPng(session.renderPlan(plan));\n } finally {\n session.dispose();\n }\n } finally {\n release();\n }\n}\n\n/** The `png` format's own option. */\nexport interface PngExportOptions extends ExportOptions {\n /** Output pixels per world unit. Default 1. */\n scale?: number;\n}\n\n/** The built-in `png` format: one region as a PNG image, through {@link exportRegionPng}. */\nexport const PNG_EXPORT: ExportFormat<PngExportOptions> = {\n id: 'png',\n label: 'PNG Image',\n mimeType: 'image/png',\n extension: 'png',\n multiRegion: false,\n export: (scene, regions, opts) => exportRegionPng(scene, typeof regions === 'function' ? (doc) => regions(doc)[0]! : regions[0]!, {\n scale: opts.scale ?? 1,\n ...(opts.background !== undefined ? { background: opts.background } : {}),\n ...(opts.onDiagnostic ? { onDiagnostic: opts.onDiagnostic } : {}),\n ...(opts.strict !== undefined ? { strict: opts.strict } : {}),\n }),\n};\n","/**\n * The export registry: the formats a scene's regions can be written in, each\n * registered by the package that can write it. This package registers `png`;\n * svg and pdf register theirs (`registerSvgExport`, `registerPdfExport`), so it\n * depends on neither.\n */\nimport { createReflectable, type Reflection } from '@weasel-js/registry';\nimport type { ExportFormat, ExportOptions, ExportRegion, ExportRegions, ExportScene } from './exportTypes';\nimport { PNG_EXPORT } from './regionPng';\n\nconst FORMATS = createReflectable<ExportFormat>();\n\n// The built-ins go in on first use, not at module load: a bundler may drop an\n// import kept only for its side effect, and the registry would come up empty.\nlet builtInsRegistered = false;\nfunction ensureBuiltIns(): void {\n if (builtInsRegistered) return;\n builtInsRegistered = true;\n FORMATS.push(PNG_EXPORT.id, PNG_EXPORT as ExportFormat, { source: 'kit' });\n}\n\n/** Every registered export format, keyed by id, with the overrides each displaced. */\nexport const exportFormatRegistry: Reflection<ExportFormat> = {\n get: (id) => { ensureBuiltIns(); return FORMATS.get(id); },\n has: (id) => { ensureBuiltIns(); return FORMATS.has(id); },\n entries: () => { ensureBuiltIns(); return FORMATS.entries(); },\n subscribe: (listener) => { ensureBuiltIns(); return FORMATS.subscribe(listener); },\n getVersion: () => { ensureBuiltIns(); return FORMATS.getVersion(); },\n};\n\n/**\n * Register an export format. Returns a disposer that removes this\n * registration. Registering an id already held overrides it, `png` included;\n * disposing uncovers what it displaced.\n */\nexport function registerExportFormat<TOptions extends ExportOptions>(format: ExportFormat<TOptions>): () => void {\n ensureBuiltIns();\n return FORMATS.push(format.id, format as ExportFormat);\n}\n\nlet listed: { from: readonly unknown[]; formats: readonly ExportFormat[] } | null = null;\n\n/** Every registered format, `png` first, then in registration order. The same array until the registry changes. */\nexport function exportFormats(): readonly ExportFormat[] {\n const entries = exportFormatRegistry.entries();\n if (listed?.from !== entries) listed = { from: entries, formats: Object.freeze(entries.map((e) => e.value)) };\n return listed.formats;\n}\n\n/**\n * Write `regions` of `scene` in the format registered as `formatId`. Throws\n * for an id nothing registered, and for more or fewer than one region handed\n * to a format that is not `multiRegion`; a multi-region format takes one or\n * more. Regions given as a function of the document are counted each time\n * the export reads them.\n */\nexport function exportRegions(\n scene: ExportScene,\n regions: ExportRegions,\n formatId: string,\n opts: ExportOptions & Readonly<Record<string, unknown>> = {},\n): Promise<Blob> {\n const format = exportFormatRegistry.get(formatId);\n if (!format) {\n const known = exportFormats().map((f) => f.id).join(', ');\n return Promise.reject(new Error(`exportRegions: no export format \"${formatId}\" is registered (registered: ${known})`));\n }\n if (typeof regions !== 'function') {\n try {\n checkCount(format, regions);\n } catch (err) {\n return Promise.reject(err);\n }\n return format.export(scene, regions, opts);\n }\n return format.export(scene, (doc) => checkCount(format, regions(doc)), opts);\n}\n\nfunction checkCount(format: ExportFormat, regions: readonly ExportRegion[]): readonly ExportRegion[] {\n if (regions.length === 0) throw new Error(`exportRegions: \"${format.id}\" was handed no regions`);\n if (!format.multiRegion && regions.length > 1) {\n throw new Error(`exportRegions: \"${format.id}\" writes one region to a file and was handed ${regions.length}; export them one at a time`);\n }\n return regions;\n}\n\n/** Drop every registration and the built-ins, so the next use registers them again. */\nexport function _resetExportFormatsForTests(): void {\n FORMATS.clear();\n builtInsRegistered = false;\n listed = null;\n}\n","import { pageName, placedPagesOf, type PlacedPage } from '@weasel-js/core';\nimport { exportRegions } from './exportFormats';\nimport type { ExportOptions, ExportRegion, ExportScene } from './exportTypes';\n\n/** `page` as an export region, named as the page order shows it. */\nexport function pageRegion(page: PlacedPage): ExportRegion {\n return { x: page.x, y: page.y, width: page.width, height: page.height, name: pageName(page, page.index) };\n}\n\n/**\n * `pages` as regions read from the document an export draws: each page placed\n * as that document places it, found by its id, and named for it. A page the\n * document no longer holds fails the export.\n */\nexport function pageRegionsOf(pages: readonly PlacedPage[]): (doc: ExportScene) => readonly ExportRegion[] {\n const ids = pages.map((p) => p.id);\n return (doc) => {\n const placed = new Map(placedPagesOf(doc).map((p) => [p.id, p]));\n return ids.map((id) => {\n const page = placed.get(id);\n if (page === undefined) throw new Error(`exportPages: the document holds no page \"${id}\"`);\n return pageRegion(page);\n });\n };\n}\n\n/** One page as {@link pageRegionsOf} reads it: the region source of a single-region export. */\nexport function pageRegionOf(page: PlacedPage): (doc: ExportScene) => ExportRegion {\n const read = pageRegionsOf([page]);\n return (doc) => read(doc)[0]!;\n}\n\n/**\n * Write `pages` of `scene` in the format registered as `formatId`, each page\n * a region named for the page: `exportRegions` over {@link pageRegionsOf}. A\n * single-region format takes one page.\n */\nexport function exportPages(\n scene: ExportScene,\n pages: readonly PlacedPage[],\n formatId: string,\n opts: ExportOptions & Readonly<Record<string, unknown>> = {},\n): Promise<Blob> {\n return exportRegions(scene, pageRegionsOf(pages), formatId, opts);\n}\n","import { documentOf, drawnAABBOf, drawnBoundsScene, scenePoseAdapter, unionAABB, withoutPageStructure, worldPoseLookup, type NodeId } from '@weasel-js/core';\nimport type { ExportRegion, ExportScene } from './exportTypes';\n\n/**\n * The world box `ids` cover as the document draws them, strokes included:\n * the region that exports a selection. Pages and the page run are left out of\n * `ids`. `null` when none of them draws anything.\n */\nexport function selectionRegion(scene: ExportScene, ids: readonly string[], name?: string): ExportRegion | null {\n const doc = documentOf(scene);\n const world = worldPoseLookup(scenePoseAdapter(doc), doc.composition.compose as (p: unknown, c: unknown) => unknown);\n const drawn = drawnBoundsScene(doc);\n const boxes = withoutPageStructure(doc, ids).map((id) => {\n const pose = world(id);\n return pose === null || doc.get(id as NodeId) === undefined\n ? null : drawnAABBOf(drawn, id as NodeId, pose, { worldPoseOf: (m) => world(m) });\n });\n const box = unionAABB(boxes);\n return box === null ? null : { x: box.x, y: box.y, width: box.width, height: box.height, ...(name !== undefined ? { name } : {}) };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@weasel-js/export",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.19.1",
4
+ "description": "Exports regions of a @weasel-js/core scene: a page, a selection or any rect, as PNG or any format another package registers (SVG, PDF), with a diagnostics report and a retry when the scene changes mid-export.",
5
+ "weasel": {
6
+ "tier": "plugin"
7
+ },
8
+ "license": "MIT",
9
+ "type": "module",
10
+ "sideEffects": false,
11
+ "main": "./dist/index.js",
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "author": "orochi235",
22
+ "homepage": "https://orochi235.github.io/weasel/",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/orochi235/weasel.git",
26
+ "directory": "packages/export"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/orochi235/weasel/issues"
30
+ },
31
+ "engines": {
32
+ "node": ">=24"
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "scripts": {
40
+ "build": "tsup",
41
+ "test": "node ../../scripts/package-test.mjs"
42
+ },
43
+ "dependencies": {
44
+ "@weasel-js/geom": "1.19.1",
45
+ "@weasel-js/registry": "1.19.1",
46
+ "@weasel-js/renderer": "1.19.1"
47
+ },
48
+ "peerDependencies": {
49
+ "@weasel-js/core": "1.19.1"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "provenance": true
54
+ }
55
+ }