@lofcz/tikz 0.0.0-stage → 0.2.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.
Files changed (118) hide show
  1. package/LICENSE +674 -0
  2. package/NOTICE.md +30 -0
  3. package/README.md +127 -2
  4. package/package.json +56 -4
  5. package/runtime/LICENSE +165 -0
  6. package/runtime/NOTICE.md +32 -0
  7. package/runtime/dist/auto.d.ts +68 -0
  8. package/runtime/dist/auto.js +564 -0
  9. package/runtime/dist/bibtex.mjs +2 -0
  10. package/runtime/dist/bibtex.wasm +0 -0
  11. package/runtime/dist/bundles/cm-tfm/files.br +0 -0
  12. package/runtime/dist/bundles/cm-tfm/files.index.json +1 -0
  13. package/runtime/dist/bundles/cm-tfm/manifest.json +1 -0
  14. package/runtime/dist/bundles/cm-type1/files.br +0 -0
  15. package/runtime/dist/bundles/cm-type1/files.index.json +1 -0
  16. package/runtime/dist/bundles/cm-type1/manifest.json +1 -0
  17. package/runtime/dist/bundles/core/files.br +0 -0
  18. package/runtime/dist/bundles/core/files.index.json +1 -0
  19. package/runtime/dist/bundles/core/manifest.json +1 -0
  20. package/runtime/dist/bundles/hot.json +1 -0
  21. package/runtime/dist/bundles/index.json +80 -0
  22. package/runtime/dist/bundles/latex-core/files.br +0 -0
  23. package/runtime/dist/bundles/latex-core/files.index.json +1 -0
  24. package/runtime/dist/bundles/latex-core/manifest.json +1 -0
  25. package/runtime/dist/bundles/latex-extra/files.br +0 -0
  26. package/runtime/dist/bundles/latex-extra/files.index.json +1 -0
  27. package/runtime/dist/bundles/latex-extra/manifest.json +1 -0
  28. package/runtime/dist/bundles/lm-fonts/files.br +0 -0
  29. package/runtime/dist/bundles/lm-fonts/files.index.json +1 -0
  30. package/runtime/dist/bundles/lm-fonts/manifest.json +1 -0
  31. package/runtime/dist/bundles/luatex/files.br +0 -0
  32. package/runtime/dist/bundles/luatex/files.index.json +1 -0
  33. package/runtime/dist/bundles/luatex/manifest.json +1 -0
  34. package/runtime/dist/bundles/ps-fonts/files.br +0 -0
  35. package/runtime/dist/bundles/ps-fonts/files.index.json +1 -0
  36. package/runtime/dist/bundles/ps-fonts/manifest.json +1 -0
  37. package/runtime/dist/bundles/tex-plain/files.br +0 -0
  38. package/runtime/dist/bundles/tex-plain/files.index.json +1 -0
  39. package/runtime/dist/bundles/tex-plain/manifest.json +1 -0
  40. package/runtime/dist/bundles/tikz-snapshot/files.br +0 -0
  41. package/runtime/dist/bundles/tikz-snapshot/files.index.json +1 -0
  42. package/runtime/dist/bundles/tikz-snapshot/manifest.json +1 -0
  43. package/runtime/dist/bundles-config.d.ts +3 -0
  44. package/runtime/dist/bundles-config.js +16 -0
  45. package/runtime/dist/cli.d.ts +2 -0
  46. package/runtime/dist/cli.js +372 -0
  47. package/runtime/dist/core.d.ts +124 -0
  48. package/runtime/dist/core.js +927 -0
  49. package/runtime/dist/diagnostics.d.ts +53 -0
  50. package/runtime/dist/diagnostics.js +184 -0
  51. package/runtime/dist/dvisvgm.d.ts +20 -0
  52. package/runtime/dist/dvisvgm.js +46 -0
  53. package/runtime/dist/dvisvgm.mjs +2 -0
  54. package/runtime/dist/dvisvgm.wasm +0 -0
  55. package/runtime/dist/figures.d.ts +92 -0
  56. package/runtime/dist/figures.js +250 -0
  57. package/runtime/dist/ghostscript.d.ts +92 -0
  58. package/runtime/dist/ghostscript.js +218 -0
  59. package/runtime/dist/index.d.ts +87 -0
  60. package/runtime/dist/index.js +364 -0
  61. package/runtime/dist/logger.d.ts +48 -0
  62. package/runtime/dist/logger.js +55 -0
  63. package/runtime/dist/luatex.mjs +2 -0
  64. package/runtime/dist/luatex.wasm +0 -0
  65. package/runtime/dist/makeindex.mjs +2 -0
  66. package/runtime/dist/makeindex.wasm +0 -0
  67. package/runtime/dist/mplib.d.ts +106 -0
  68. package/runtime/dist/mplib.js +85 -0
  69. package/runtime/dist/mplib.mjs +2 -0
  70. package/runtime/dist/mplib.wasm +0 -0
  71. package/runtime/dist/node.d.ts +4 -0
  72. package/runtime/dist/node.js +49 -0
  73. package/runtime/dist/postscript.d.ts +21 -0
  74. package/runtime/dist/postscript.js +130 -0
  75. package/runtime/dist/prerender.d.ts +55 -0
  76. package/runtime/dist/prerender.js +106 -0
  77. package/runtime/dist/render/svg.d.ts +20 -0
  78. package/runtime/dist/render/svg.js +96 -0
  79. package/runtime/dist/tex/bridge.d.ts +93 -0
  80. package/runtime/dist/tex/bridge.js +223 -0
  81. package/runtime/dist/tex/cache-key.d.ts +33 -0
  82. package/runtime/dist/tex/cache-key.js +150 -0
  83. package/runtime/dist/tex/mpto.d.ts +60 -0
  84. package/runtime/dist/tex/mpto.js +112 -0
  85. package/runtime/dist/tex/mpx.d.ts +25 -0
  86. package/runtime/dist/tex/mpx.js +54 -0
  87. package/runtime/dist/tex/scanner.d.ts +78 -0
  88. package/runtime/dist/tex/scanner.js +326 -0
  89. package/runtime/dist/tex.mjs +2 -0
  90. package/runtime/dist/tex.wasm +0 -0
  91. package/runtime/dist/texengine.d.ts +35 -0
  92. package/runtime/dist/texengine.js +57 -0
  93. package/runtime/dist/texutils.d.ts +19 -0
  94. package/runtime/dist/texutils.js +60 -0
  95. package/runtime/dist/types.d.ts +376 -0
  96. package/runtime/dist/types.js +6 -0
  97. package/runtime/dist/vfs/bundle.d.ts +88 -0
  98. package/runtime/dist/vfs/bundle.js +315 -0
  99. package/runtime/dist/vfs/lazyfs.d.ts +62 -0
  100. package/runtime/dist/vfs/lazyfs.js +133 -0
  101. package/runtime/dist/worker.d.ts +15 -0
  102. package/runtime/dist/worker.js +143 -0
  103. package/runtime/licenses/COPYING.AFPL +230 -0
  104. package/runtime/licenses/COPYING.makeindex +42 -0
  105. package/runtime/licenses/GPL-3.0.txt +674 -0
  106. package/runtime/licenses/LGPL-3.0.txt +165 -0
  107. package/runtime/licenses/OFL-1.1.txt +93 -0
  108. package/runtime/package.json +1 -0
  109. package/runtime/upstream.json +27 -0
  110. package/src/browser-worker.js +26 -0
  111. package/src/browser.d.ts +18 -0
  112. package/src/browser.js +68 -0
  113. package/src/deploy.d.ts +5 -0
  114. package/src/deploy.js +48 -0
  115. package/src/index.d.ts +28 -0
  116. package/src/index.js +103 -0
  117. package/src/worker.js +15 -0
  118. package/upstream.json +27 -0
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,93 @@
1
+ Copyright 2017 The EB Garamond Project Authors (https://github.com/octaviopardo/EBGaramond12)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1 @@
1
+ {"type":"module","version":"0.5.0"}
@@ -0,0 +1,27 @@
1
+ {
2
+ "repository": "https://github.com/lofcz/mp-tikz-wasm",
3
+ "version": "0.5.0",
4
+ "commit": "d44aeeba98b0e60d13c35dfd080076e6b05c68b5",
5
+ "archive": "https://github.com/lofcz/mp-tikz-wasm/releases/download/native-v0.5.0-r1/tikz-native-0.5.0.tar.gz",
6
+ "sha256": "fa5b8752f7e59e83ad9ffa934022ced278b3f19c7c4d0205b5c3cb028ffc5560",
7
+ "bundles": [
8
+ "core",
9
+ "cm-tfm",
10
+ "cm-type1",
11
+ "lm-fonts",
12
+ "ps-fonts",
13
+ "tex-plain",
14
+ "latex-core",
15
+ "latex-extra",
16
+ "tikz-snapshot",
17
+ "luatex"
18
+ ],
19
+ "upstream": {
20
+ "repository": "https://github.com/jmckalex/mp-tikz-wasm",
21
+ "version": "0.5.0",
22
+ "commit": "d44aeeba98b0e60d13c35dfd080076e6b05c68b5",
23
+ "archive": "https://github.com/jmckalex/mp-tikz-wasm/releases/download/v0.5.0/mp-tikz-wasm-0.5.0.tar.gz",
24
+ "sha256": "76b5591a83adfb96e8087b8560fd993c6ebba475ad15a63269a8aa47517dd575"
25
+ },
26
+ "distribution": "brotli-bundle-archives-v1"
27
+ }
@@ -0,0 +1,26 @@
1
+ import { MetaPost } from '../runtime/dist/index.js';
2
+
3
+ try {
4
+ const engine = await MetaPost.create({ worker: false, logLevel: 'silent' });
5
+ self.onmessage = async ({ data: { source: code, maxOutputBytes } }) => {
6
+ try {
7
+ const source = /^\s*\\documentclass\b/m.test(code) ? code : String.raw`\documentclass[tikz,border=6pt]{standalone}
8
+ \usetikzlibrary{calc,intersections,angles,quotes,arrows.meta,positioning}
9
+ \begin{document}
10
+ ${code}
11
+ \end{document}`;
12
+ const result = await engine.latex(source, { fonts: 'paths' });
13
+ if (result.status === 'error' || result.status === 'fatal' || result.pages?.length !== 1)
14
+ throw new Error('TikZ requires one valid page. ' + JSON.stringify(result.diagnostics).slice(0, 2000));
15
+ const svg = result.pages[0], bytes = new TextEncoder().encode(svg);
16
+ if (bytes.length > maxOutputBytes) throw new Error('TikZ output too large; simplify the picture.');
17
+ const dimensions = svg.match(/viewBox=['"]([^'"]+)['"]/)?.[1].trim().split(/[ ,]+/).map(Number);
18
+ if (!dimensions || dimensions.length !== 4 || !dimensions.every(Number.isFinite) || dimensions[2] <= 0 || dimensions[3] <= 0)
19
+ throw new Error('TikZ returned an invalid picture size');
20
+ let binary = '';
21
+ for (let start = 0; start < bytes.length; start += 8192) binary += String.fromCharCode(...bytes.subarray(start, start + 8192));
22
+ self.postMessage({ image: { svg, width: dimensions[2], height: dimensions[3], dataUrl: `data:image/svg+xml;base64,${btoa(binary)}` } });
23
+ } catch (error) { self.postMessage({ error: String(error).slice(0, 3000) }); }
24
+ };
25
+ self.postMessage({ ready: true });
26
+ } catch (error) { self.postMessage({ error: String(error).slice(0, 3000) }); }
@@ -0,0 +1,18 @@
1
+ import type { TikzImage, TikzRenderOptions } from './index.js';
2
+ export declare const TIKZ_MAX_SOURCE: 12000;
3
+ export interface BrowserTikzRendererOptions {
4
+ /** Same-origin URL ending in /, populated with copyTikzBrowserAssets. */
5
+ assetBaseUrl: string | URL;
6
+ /** Compilation deadline, default 30000 ms. */
7
+ timeoutMs?: number;
8
+ /** Initial worker/runtime loading deadline, default 60000 ms. */
9
+ loadTimeoutMs?: number;
10
+ maxQueue?: number;
11
+ maxSourceLength?: number;
12
+ maxOutputBytes?: number;
13
+ }
14
+ export interface BrowserTikzRenderer {
15
+ render(source: string, options?: TikzRenderOptions): Promise<TikzImage>;
16
+ dispose(): void;
17
+ }
18
+ export declare function createTikzRenderer(options: BrowserTikzRendererOptions): BrowserTikzRenderer;
package/src/browser.js ADDED
@@ -0,0 +1,68 @@
1
+ export const TIKZ_MAX_SOURCE = 12_000;
2
+ const aborted = () => new DOMException('TikZ rendering aborted', 'AbortError');
3
+
4
+ /** A lazy, reusable worker. TeX never runs on the UI thread. */
5
+ export function createTikzRenderer(options) {
6
+ const { assetBaseUrl, timeoutMs = 30_000, loadTimeoutMs = 60_000,
7
+ maxQueue = 8, maxSourceLength = TIKZ_MAX_SOURCE, maxOutputBytes = 4_000_000 } = options ?? {};
8
+ if (!assetBaseUrl) throw new TypeError('TikZ assetBaseUrl is required');
9
+ for (const [name, value] of Object.entries({ timeoutMs, loadTimeoutMs, maxQueue, maxSourceLength, maxOutputBytes }))
10
+ if (!Number.isSafeInteger(value) || value < (name === 'maxQueue' ? 0 : 1)) throw new TypeError(`Invalid TikZ ${name}`);
11
+ let worker, ready = false, active, disposed = false;
12
+ const queue = [];
13
+ function stop() { worker?.terminate(); worker = undefined; ready = false; }
14
+ function finish(error, image) {
15
+ const job = active; if (!job) return;
16
+ active = undefined; clearTimeout(job.timer); job.signal?.removeEventListener('abort', job.abort);
17
+ if (error) { stop(); job.reject(error); } else job.resolve(image);
18
+ pump();
19
+ }
20
+ function execute() {
21
+ if (!active) return;
22
+ clearTimeout(active.timer);
23
+ active.timer = setTimeout(() => finish(new Error('TikZ execution timed out; simplify or split the picture.')), timeoutMs);
24
+ worker.postMessage({ source: active.source, maxOutputBytes });
25
+ }
26
+ function pump() {
27
+ if (active || disposed || !queue.length) return;
28
+ active = queue.shift(); clearTimeout(active.timer);
29
+ if (ready) { execute(); return; }
30
+ active.timer = setTimeout(() => finish(new Error('TikZ runtime loading timed out.')), loadTimeoutMs);
31
+ try {
32
+ worker = new Worker(new URL('src/browser-worker.js', new URL(assetBaseUrl, location.href)), { type: 'module', name: 'tikz' });
33
+ worker.onmessage = ({ data }) => {
34
+ if (data.ready) { ready = true; execute(); }
35
+ else if (data.error) finish(new Error(data.error));
36
+ else if (data.image) finish(undefined, data.image);
37
+ };
38
+ worker.onerror = event => { event.preventDefault(); finish(new Error(event.message || 'TikZ worker failed')); };
39
+ worker.onmessageerror = () => finish(new Error('Invalid TikZ worker response'));
40
+ } catch (error) { finish(error); }
41
+ }
42
+ return {
43
+ render(source, { signal } = {}) {
44
+ if (disposed) return Promise.reject(new Error('TikZ renderer disposed'));
45
+ if (signal?.aborted) return Promise.reject(aborted());
46
+ if (typeof source !== 'string' || !source.trim() || source.length > maxSourceLength)
47
+ return Promise.reject(new Error(`TikZ: use 1–${maxSourceLength.toLocaleString('en-US')} characters.`));
48
+ if (active && queue.length >= maxQueue) return Promise.reject(new Error('TikZ renderer busy; retry shortly.'));
49
+ return new Promise((resolve, reject) => {
50
+ const job = { source, signal, resolve, reject, timer: undefined, abort: undefined };
51
+ const remove = error => {
52
+ if (active === job) { finish(error); return; }
53
+ const index = queue.indexOf(job); if (index < 0) return;
54
+ queue.splice(index, 1); clearTimeout(job.timer); signal?.removeEventListener('abort', job.abort); reject(error);
55
+ };
56
+ job.abort = () => remove(aborted());
57
+ signal?.addEventListener('abort', job.abort, { once: true });
58
+ job.timer = setTimeout(() => remove(new Error('TikZ queue wait timed out')), loadTimeoutMs + timeoutMs);
59
+ queue.push(job); pump();
60
+ });
61
+ },
62
+ dispose() {
63
+ disposed = true;
64
+ finish(new Error('TikZ renderer disposed')); stop();
65
+ for (const job of queue.splice(0)) { clearTimeout(job.timer); job.signal?.removeEventListener('abort', job.abort); job.reject(new Error('TikZ renderer disposed')); }
66
+ },
67
+ };
68
+ }
@@ -0,0 +1,5 @@
1
+ /** Include the full package in a standalone Node function's node_modules. */
2
+ export declare function copyTikzAssets(functionDirectory: string): Promise<{ directory: string; version: string }>;
3
+
4
+ /** Copy worker, WASM, licenses and expanded TeX bundles to a static directory. */
5
+ export declare function copyTikzBrowserAssets(directory: string): Promise<{ directory: string; version: string }>;
package/src/deploy.js ADDED
@@ -0,0 +1,48 @@
1
+ import { cp, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
2
+ import { brotliDecompressSync } from 'node:zlib';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join, resolve } from 'node:path';
5
+
6
+ /** Copy a complete package into an otherwise standalone Node function artifact. */
7
+ export async function copyTikzAssets(functionDirectory) {
8
+ const source = dirname(createRequire(import.meta.url).resolve('@lofcz/tikz/package.json'));
9
+ const destination = resolve(functionDirectory, 'node_modules/@lofcz/tikz');
10
+ if (await realpath(destination).catch(() => '') === await realpath(source))
11
+ throw new Error('TikZ deployment destination must differ from the installed package');
12
+ await mkdir(destination, { recursive: true });
13
+ const manifest = JSON.parse(await readFile(join(source, 'package.json'), 'utf8'));
14
+ for (const entry of ['src', 'runtime', 'LICENSE', 'NOTICE.md', 'upstream.json', 'package.json'])
15
+ await cp(join(source, entry), join(destination, entry), { recursive: true, dereference: true });
16
+ // Validate resolution from the output, never accidentally use the developer's install.
17
+ const resolved = createRequire(join(resolve(functionDirectory), 'handler.mjs')).resolve('@lofcz/tikz/package.json');
18
+ if (await realpath(dirname(resolved)) !== await realpath(destination))
19
+ throw new Error('TikZ resolves outside the deployment artifact');
20
+ return { directory: destination, version: manifest.version };
21
+ }
22
+
23
+ /** Produce ordinary static assets; no backend endpoint or special HTTP encoding. */
24
+ export async function copyTikzBrowserAssets(directory) {
25
+ const source = dirname(createRequire(import.meta.url).resolve('@lofcz/tikz/package.json'));
26
+ const destination = resolve(directory);
27
+ if (destination === source || destination.startsWith(source + '/'))
28
+ throw new Error('TikZ browser assets must be outside the installed package');
29
+ await mkdir(join(destination, 'src'), { recursive: true });
30
+ await cp(join(source, 'runtime'), join(destination, 'runtime'), { recursive: true });
31
+ for (const name of ['browser.js', 'browser-worker.js'])
32
+ await cp(join(source, 'src', name), join(destination, 'src', name));
33
+ for (const name of ['LICENSE', 'NOTICE.md', 'upstream.json'])
34
+ await cp(join(source, name), join(destination, name));
35
+ const pin = JSON.parse(await readFile(join(source, 'upstream.json'), 'utf8'));
36
+ for (const name of pin.bundles) {
37
+ const base = join(destination, 'runtime/dist/bundles', name);
38
+ const index = JSON.parse(await readFile(join(base, 'files.index.json'), 'utf8'));
39
+ const bytes = brotliDecompressSync(await readFile(join(base, 'files.br')));
40
+ for (const [path, [offset, size]] of Object.entries(index)) {
41
+ const file = join(base, 'files', path);
42
+ await mkdir(dirname(file), { recursive: true });
43
+ await writeFile(file, bytes.subarray(offset, offset + size));
44
+ }
45
+ await rm(join(base, 'files.br')); await rm(join(base, 'files.index.json'));
46
+ }
47
+ return { directory: destination, version: JSON.parse(await readFile(join(source, 'package.json'), 'utf8')).version };
48
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ export interface TikzImage {
2
+ svg: string;
3
+ width: number;
4
+ height: number;
5
+ /** Inert SVG image URL, suitable for an img element. */
6
+ dataUrl: string;
7
+ }
8
+ export interface TikzRenderOptions { signal?: AbortSignal }
9
+ export interface TikzRendererOptions {
10
+ /** Running child processes. Default: 2. */
11
+ concurrency?: number;
12
+ /** Waiting renders; overflow rejects immediately. Default: 8. */
13
+ maxQueue?: number;
14
+ /** Per-render execution deadline, and maximum queue wait. Default: 30000. */
15
+ timeoutMs?: number;
16
+ /** Default: 12000 UTF-16 code units. */
17
+ maxSourceLength?: number;
18
+ /** Default: 4000000 UTF-8 bytes. */
19
+ maxOutputBytes?: number;
20
+ /** Optional Node executable for Bun hosts that do not have node on PATH. */
21
+ nodeExecutable?: string;
22
+ }
23
+ export interface TikzRenderer {
24
+ render(source: string, options?: TikzRenderOptions): Promise<TikzImage>;
25
+ }
26
+ export declare const TIKZ_MAX_SOURCE: 12000;
27
+ export declare function createTikzRenderer(options?: TikzRendererOptions): TikzRenderer;
28
+ export declare function renderTikz(source: string, options?: TikzRenderOptions): Promise<TikzImage>;
package/src/index.js ADDED
@@ -0,0 +1,103 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join } from 'node:path';
4
+
5
+ export const TIKZ_MAX_SOURCE = 12_000;
6
+ const packageRoot = () => dirname(createRequire(import.meta.url).resolve('@lofcz/tikz/package.json'));
7
+ const abortError = () => new DOMException('TikZ rendering aborted', 'AbortError');
8
+ const busyError = () => new Error('TikZ renderer busy; retry shortly.');
9
+
10
+ /** @param {import('./index.js').TikzRendererOptions} [options] */
11
+ export function createTikzRenderer(options = {}) {
12
+ const settings = {
13
+ concurrency: 2, maxQueue: 8, timeoutMs: 30_000,
14
+ maxSourceLength: TIKZ_MAX_SOURCE, maxOutputBytes: 4_000_000,
15
+ nodeExecutable: process.versions.bun ? 'node' : process.execPath,
16
+ ...options,
17
+ };
18
+ for (const name of ['concurrency', 'maxQueue', 'timeoutMs', 'maxSourceLength', 'maxOutputBytes']) {
19
+ if (!Number.isSafeInteger(settings[name]) || settings[name] < (name === 'maxQueue' ? 0 : 1))
20
+ throw new TypeError(`Invalid TikZ ${name}`);
21
+ }
22
+ if (typeof settings.nodeExecutable !== 'string' || !settings.nodeExecutable)
23
+ throw new TypeError('Invalid TikZ nodeExecutable');
24
+ let active = 0;
25
+ const queue = [];
26
+ function release() {
27
+ const next = queue.shift();
28
+ if (next) next.ready();
29
+ else active--;
30
+ }
31
+ async function acquire(signal) {
32
+ if (signal?.aborted) throw abortError();
33
+ if (active < settings.concurrency) { active++; return; }
34
+ if (queue.length >= settings.maxQueue) throw busyError();
35
+ await new Promise((resolve, reject) => {
36
+ const cleanup = () => { clearTimeout(timer); signal?.removeEventListener('abort', aborted); };
37
+ const remove = (error) => {
38
+ const index = queue.indexOf(entry);
39
+ if (index >= 0) queue.splice(index, 1);
40
+ cleanup(); reject(error);
41
+ };
42
+ const aborted = () => remove(abortError());
43
+ const entry = { ready() { cleanup(); resolve(); } };
44
+ const timer = setTimeout(() => remove(busyError()), settings.timeoutMs);
45
+ signal?.addEventListener('abort', aborted, { once: true });
46
+ queue.push(entry);
47
+ });
48
+ }
49
+ function compile(source, signal) {
50
+ return new Promise((resolve, reject) => {
51
+ if (signal?.aborted) { reject(abortError()); return; }
52
+ const root = packageRoot();
53
+ const child = spawn(settings.nodeExecutable, ['--max-old-space-size=512', join(root, 'src/worker.js')], {
54
+ env: {}, cwd: root, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true,
55
+ });
56
+ const chunks = [];
57
+ let bytes = 0, stderr = '', failure;
58
+ // Keep the semaphore slot until close confirms the killed process is gone.
59
+ const fail = (error) => { failure ??= error; child.kill('SIGKILL'); };
60
+ const aborted = () => fail(abortError());
61
+ const timer = setTimeout(() => fail(new Error(`TikZ exceeded ${settings.timeoutMs}ms; simplify or split the picture.`)), settings.timeoutMs);
62
+ signal?.addEventListener('abort', aborted, { once: true });
63
+ child.stdout.on('data', chunk => {
64
+ bytes += chunk.length;
65
+ if (bytes > settings.maxOutputBytes) fail(new Error('TikZ output too large; simplify the picture.'));
66
+ else chunks.push(chunk);
67
+ });
68
+ child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); });
69
+ child.on('error', error => { failure ??= error; });
70
+ child.stdin.on('error', () => {});
71
+ child.on('close', (code, terminationSignal) => {
72
+ clearTimeout(timer);
73
+ signal?.removeEventListener('abort', aborted);
74
+ if (failure) { reject(failure); return; }
75
+ if (code !== 0 || terminationSignal) { reject(new Error(stderr || 'TikZ compilation failed')); return; }
76
+ try {
77
+ const { svg } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
78
+ const dimensions = typeof svg === 'string' && svg.match(/viewBox=['"]([^'"]+)['"]/)?.[1].trim().split(/[ ,]+/).map(Number);
79
+ if (!dimensions || dimensions.length !== 4 || !dimensions.every(Number.isFinite) || dimensions[2] <= 0 || dimensions[3] <= 0)
80
+ throw new Error('TikZ returned an invalid picture size');
81
+ resolve({ svg, width: dimensions[2], height: dimensions[3], dataUrl: `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}` });
82
+ } catch (error) { reject(error); }
83
+ });
84
+ child.stdin.end(JSON.stringify({ source }));
85
+ });
86
+ }
87
+ return {
88
+ async render(code, { signal } = {}) {
89
+ if (typeof code !== 'string' || !code.trim() || code.length > settings.maxSourceLength)
90
+ throw new Error(`TikZ: use 1–${settings.maxSourceLength.toLocaleString('en-US')} characters.`);
91
+ const source = /^\s*\\documentclass\b/m.test(code) ? code : String.raw`\documentclass[tikz,border=6pt]{standalone}
92
+ \usetikzlibrary{calc,intersections,angles,quotes,arrows.meta,positioning}
93
+ \begin{document}
94
+ ${code}
95
+ \end{document}`;
96
+ await acquire(signal);
97
+ try { return await compile(source, signal); }
98
+ finally { release(); }
99
+ },
100
+ };
101
+ }
102
+ const defaultRenderer = createTikzRenderer();
103
+ export const renderTikz = (source, options) => defaultRenderer.render(source, options);
package/src/worker.js ADDED
@@ -0,0 +1,15 @@
1
+ // A separate process makes synchronous TeX loops terminable. The Emscripten
2
+ // filesystem is in-memory; no host texmf tree, shell or caller environment.
3
+ import { readFileSync } from 'node:fs';
4
+ import { MetaPost } from '../runtime/dist/index.js';
5
+ const { source } = JSON.parse(readFileSync(0, 'utf8'));
6
+ const engine = await MetaPost.create({ worker: false, logLevel: 'silent' });
7
+ try {
8
+ const result = await engine.latex(source, { fonts: 'paths' });
9
+ if (result.status === 'error' || result.status === 'fatal' || result.pages?.length !== 1)
10
+ throw new Error('TikZ requires one valid page. ' + JSON.stringify(result.diagnostics).slice(0, 2000));
11
+ process.stdout.write(JSON.stringify({ svg: result.pages[0] }));
12
+ } catch (error) {
13
+ process.stderr.write(String(error).slice(0, 3000));
14
+ process.exitCode = 1;
15
+ } finally { engine.dispose(); }
package/upstream.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "repository": "https://github.com/lofcz/mp-tikz-wasm",
3
+ "version": "0.5.0",
4
+ "commit": "d44aeeba98b0e60d13c35dfd080076e6b05c68b5",
5
+ "archive": "https://github.com/lofcz/mp-tikz-wasm/releases/download/native-v0.5.0-r1/tikz-native-0.5.0.tar.gz",
6
+ "sha256": "fa5b8752f7e59e83ad9ffa934022ced278b3f19c7c4d0205b5c3cb028ffc5560",
7
+ "bundles": [
8
+ "core",
9
+ "cm-tfm",
10
+ "cm-type1",
11
+ "lm-fonts",
12
+ "ps-fonts",
13
+ "tex-plain",
14
+ "latex-core",
15
+ "latex-extra",
16
+ "tikz-snapshot",
17
+ "luatex"
18
+ ],
19
+ "upstream": {
20
+ "repository": "https://github.com/jmckalex/mp-tikz-wasm",
21
+ "version": "0.5.0",
22
+ "commit": "d44aeeba98b0e60d13c35dfd080076e6b05c68b5",
23
+ "archive": "https://github.com/jmckalex/mp-tikz-wasm/releases/download/v0.5.0/mp-tikz-wasm-0.5.0.tar.gz",
24
+ "sha256": "76b5591a83adfb96e8087b8560fd993c6ebba475ad15a63269a8aa47517dd575"
25
+ },
26
+ "distribution": "brotli-bundle-archives-v1"
27
+ }