#!/usr/bin/env node var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res, err) => function __init() { if (err) throw err[0]; try { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; } catch (e) { throw err = [e], e; } }; var __commonJS = (cb, mod) => function __require() { try { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; } catch (e) { throw mod = 0, e; } }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // var define_L2W_CONFIG_default; var init_define_L2W_CONFIG = __esm({ ""() { define_L2W_CONFIG_default = { environment: "production", baseUrl: "https://texconverter.com", licenseServerUrl: "https://api.texconverter.com", licensePublicKeys: { kNpTbvHCbVq: "kck_ebq5MSquxITgIhAeUaUnBZuGH8K3K-zTGun2t9c" }, isProduction: true, debug: false }; } }); // node_modules/@xmldom/xmldom/lib/conventions.js var require_conventions = __commonJS({ "node_modules/@xmldom/xmldom/lib/conventions.js"(exports) { "use strict"; init_define_L2W_CONFIG(); function find(list, predicate, ac) { if (ac === void 0) { ac = Array.prototype; } if (list && typeof ac.find === "function") { return ac.find.call(list, predicate); } for (var i = 0; i < list.length; i++) { if (hasOwn(list, i)) { var item = list[i]; if (predicate.call(void 0, item, i, list)) { return item; } } } } function freeze(object, oc) { if (oc === void 0) { oc = Object; } if (oc && typeof oc.getOwnPropertyDescriptors === "function") { object = oc.create(null, oc.getOwnPropertyDescriptors(object)); } return oc && typeof oc.freeze === "function" ? oc.freeze(object) : object; } function hasOwn(object, key) { return Object.prototype.hasOwnProperty.call(object, key); } function assign(target, source) { if (target === null || typeof target !== "object") { throw new TypeError("target is not an object"); } for (var key in source) { if (hasOwn(source, key)) { target[key] = source[key]; } } return target; } var HTML_BOOLEAN_ATTRIBUTES = freeze({ allowfullscreen: true, async: true, autofocus: true, autoplay: true, checked: true, controls: true, default: true, defer: true, disabled: true, formnovalidate: true, hidden: true, ismap: true, itemscope: true, loop: true, multiple: true, muted: true, nomodule: true, novalidate: true, open: true, playsinline: true, readonly: true, required: true, reversed: true, selected: true }); function isHTMLBooleanAttribute(name) { return hasOwn(HTML_BOOLEAN_ATTRIBUTES, name.toLowerCase()); } var HTML_VOID_ELEMENTS = freeze({ area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, link: true, meta: true, param: true, source: true, track: true, wbr: true }); function isHTMLVoidElement(tagName) { return hasOwn(HTML_VOID_ELEMENTS, tagName.toLowerCase()); } var HTML_RAW_TEXT_ELEMENTS = freeze({ script: false, style: false, textarea: true, title: true }); function isHTMLRawTextElement(tagName) { var key = tagName.toLowerCase(); return hasOwn(HTML_RAW_TEXT_ELEMENTS, key) && !HTML_RAW_TEXT_ELEMENTS[key]; } function isHTMLEscapableRawTextElement(tagName) { var key = tagName.toLowerCase(); return hasOwn(HTML_RAW_TEXT_ELEMENTS, key) && HTML_RAW_TEXT_ELEMENTS[key]; } function isHTMLMimeType(mimeType) { return mimeType === MIME_TYPE.HTML; } function hasDefaultHTMLNamespace(mimeType) { return isHTMLMimeType(mimeType) || mimeType === MIME_TYPE.XML_XHTML_APPLICATION; } var MIME_TYPE = freeze({ /** * `text/html`, the only mime type that triggers treating an XML document as HTML. * * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration * @see https://en.wikipedia.org/wiki/HTML Wikipedia * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring * WHATWG HTML Spec */ HTML: "text/html", /** * `application/xml`, the standard mime type for XML documents. * * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType * registration * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303 * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia */ XML_APPLICATION: "application/xml", /** * `text/xml`, an alias for `application/xml`. * * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303 * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia */ XML_TEXT: "text/xml", /** * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace, * but is parsed as an XML document. * * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType * registration * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec * @see https://en.wikipedia.org/wiki/XHTML Wikipedia */ XML_XHTML_APPLICATION: "application/xhtml+xml", /** * `image/svg+xml`, * * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1 * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia */ XML_SVG_IMAGE: "image/svg+xml" }); var _MIME_TYPES = Object.keys(MIME_TYPE).map(function(key) { return MIME_TYPE[key]; }); function isValidMimeType(mimeType) { return _MIME_TYPES.indexOf(mimeType) > -1; } var NAMESPACE = freeze({ /** * The XHTML namespace. * * @see http://www.w3.org/1999/xhtml */ HTML: "http://www.w3.org/1999/xhtml", /** * The SVG namespace. * * @see http://www.w3.org/2000/svg */ SVG: "http://www.w3.org/2000/svg", /** * The `xml:` namespace. * * @see http://www.w3.org/XML/1998/namespace */ XML: "http://www.w3.org/XML/1998/namespace", /** * The `xmlns:` namespace. * * @see https://www.w3.org/2000/xmlns/ */ XMLNS: "http://www.w3.org/2000/xmlns/" }); exports.assign = assign; exports.find = find; exports.freeze = freeze; exports.HTML_BOOLEAN_ATTRIBUTES = HTML_BOOLEAN_ATTRIBUTES; exports.HTML_RAW_TEXT_ELEMENTS = HTML_RAW_TEXT_ELEMENTS; exports.HTML_VOID_ELEMENTS = HTML_VOID_ELEMENTS; exports.hasDefaultHTMLNamespace = hasDefaultHTMLNamespace; exports.hasOwn = hasOwn; exports.isHTMLBooleanAttribute = isHTMLBooleanAttribute; exports.isHTMLRawTextElement = isHTMLRawTextElement; exports.isHTMLEscapableRawTextElement = isHTMLEscapableRawTextElement; exports.isHTMLMimeType = isHTMLMimeType; exports.isHTMLVoidElement = isHTMLVoidElement; exports.isValidMimeType = isValidMimeType; exports.MIME_TYPE = MIME_TYPE; exports.NAMESPACE = NAMESPACE; } }); // node_modules/@xmldom/xmldom/lib/errors.js var require_errors = __commonJS({ "node_modules/@xmldom/xmldom/lib/errors.js"(exports) { "use strict"; init_define_L2W_CONFIG(); var conventions = require_conventions(); function extendError(constructor, writableName) { constructor.prototype = Object.create(Error.prototype, { constructor: { value: constructor }, name: { value: constructor.name, enumerable: true, writable: writableName } }); } var DOMExceptionName = conventions.freeze({ /** * the default value as defined by the spec */ Error: "Error", /** * @deprecated * Use RangeError instead. */ IndexSizeError: "IndexSizeError", /** * @deprecated * Just to match the related static code, not part of the spec. */ DomstringSizeError: "DomstringSizeError", HierarchyRequestError: "HierarchyRequestError", WrongDocumentError: "WrongDocumentError", InvalidCharacterError: "InvalidCharacterError", /** * @deprecated * Just to match the related static code, not part of the spec. */ NoDataAllowedError: "NoDataAllowedError", NoModificationAllowedError: "NoModificationAllowedError", NotFoundError: "NotFoundError", NotSupportedError: "NotSupportedError", InUseAttributeError: "InUseAttributeError", InvalidStateError: "InvalidStateError", SyntaxError: "SyntaxError", InvalidModificationError: "InvalidModificationError", NamespaceError: "NamespaceError", /** * @deprecated * Use TypeError for invalid arguments, * "NotSupportedError" DOMException for unsupported operations, * and "NotAllowedError" DOMException for denied requests instead. */ InvalidAccessError: "InvalidAccessError", /** * @deprecated * Just to match the related static code, not part of the spec. */ ValidationError: "ValidationError", /** * @deprecated * Use TypeError instead. */ TypeMismatchError: "TypeMismatchError", SecurityError: "SecurityError", NetworkError: "NetworkError", AbortError: "AbortError", /** * @deprecated * Just to match the related static code, not part of the spec. */ URLMismatchError: "URLMismatchError", QuotaExceededError: "QuotaExceededError", TimeoutError: "TimeoutError", InvalidNodeTypeError: "InvalidNodeTypeError", DataCloneError: "DataCloneError", EncodingError: "EncodingError", NotReadableError: "NotReadableError", UnknownError: "UnknownError", ConstraintError: "ConstraintError", DataError: "DataError", TransactionInactiveError: "TransactionInactiveError", ReadOnlyError: "ReadOnlyError", VersionError: "VersionError", OperationError: "OperationError", NotAllowedError: "NotAllowedError", OptOutError: "OptOutError" }); var DOMExceptionNames = Object.keys(DOMExceptionName); function isValidDomExceptionCode(value) { return typeof value === "number" && value >= 1 && value <= 25; } function endsWithError(value) { return typeof value === "string" && value.substring(value.length - DOMExceptionName.Error.length) === DOMExceptionName.Error; } function DOMException(messageOrCode, nameOrMessage) { if (isValidDomExceptionCode(messageOrCode)) { this.name = DOMExceptionNames[messageOrCode]; this.message = nameOrMessage || ""; } else { this.message = messageOrCode; this.name = endsWithError(nameOrMessage) ? nameOrMessage : DOMExceptionName.Error; } if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException); } extendError(DOMException, true); Object.defineProperties(DOMException.prototype, { code: { enumerable: true, get: function() { var code = DOMExceptionNames.indexOf(this.name); if (isValidDomExceptionCode(code)) return code; return 0; } } }); var ExceptionCode = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; var entries = Object.entries(ExceptionCode); for (i = 0; i < entries.length; i++) { key = entries[i][0]; DOMException[key] = entries[i][1]; } var key; var i; function ParseError(message, locator, cause) { this.message = message; this.locator = locator; this.cause = cause; if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError); } extendError(ParseError); exports.DOMException = DOMException; exports.DOMExceptionName = DOMExceptionName; exports.ExceptionCode = ExceptionCode; exports.ParseError = ParseError; } }); // node_modules/@xmldom/xmldom/lib/grammar.js var require_grammar = __commonJS({ "node_modules/@xmldom/xmldom/lib/grammar.js"(exports) { "use strict"; init_define_L2W_CONFIG(); function detectUnicodeSupport(RegExpImpl) { try { if (typeof RegExpImpl !== "function") { RegExpImpl = RegExp; } var match = new RegExpImpl("\u{1D306}", "u").exec("\u{1D306}"); return !!match && match[0].length === 2; } catch (error) { } return false; } var UNICODE_SUPPORT = detectUnicodeSupport(); function chars(regexp) { if (regexp.source[0] !== "[") { throw new Error(regexp + " can not be used with chars"); } return regexp.source.slice(1, regexp.source.lastIndexOf("]")); } function chars_without(regexp, search) { if (regexp.source[0] !== "[") { throw new Error("/" + regexp.source + "/ can not be used with chars_without"); } if (!search || typeof search !== "string") { throw new Error(JSON.stringify(search) + " is not a valid search"); } if (regexp.source.indexOf(search) === -1) { throw new Error('"' + search + '" is not is /' + regexp.source + "/"); } if (search === "-" && regexp.source.indexOf(search) !== 1) { throw new Error('"' + search + '" is not at the first postion of /' + regexp.source + "/"); } return new RegExp(regexp.source.replace(search, ""), UNICODE_SUPPORT ? "u" : ""); } function reg(args2) { var self = this; return new RegExp( Array.prototype.slice.call(arguments).map(function(part) { var isStr = typeof part === "string"; if (isStr && self === void 0 && part === "|") { throw new Error("use regg instead of reg to wrap expressions with `|`!"); } return isStr ? part : part.source; }).join(""), UNICODE_SUPPORT ? "u" : "" ); } function regg(args2) { if (arguments.length === 0) { throw new Error("no parameters provided"); } return reg.apply(regg, ["(?:"].concat(Array.prototype.slice.call(arguments), [")"])); } var UNICODE_REPLACEMENT_CHARACTER = "\uFFFD"; var Char = /[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/; if (UNICODE_SUPPORT) { Char = reg("[", chars(Char), "\\u{10000}-\\u{10FFFF}", "]"); } var InvalidChar = new RegExp("[^" + chars(Char) + "]", UNICODE_SUPPORT ? "u" : ""); var _SChar = /[\x20\x09\x0D\x0A]/; var SChar_s = chars(_SChar); var S = reg(_SChar, "+"); var S_OPT = reg(_SChar, "*"); var NameStartChar = /[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; if (UNICODE_SUPPORT) { NameStartChar = reg("[", chars(NameStartChar), "\\u{10000}-\\u{10FFFF}", "]"); } var NameStartChar_s = chars(NameStartChar); var NameChar = reg("[", NameStartChar_s, chars(/[-.0-9\xB7]/), chars(/[\u0300-\u036F\u203F-\u2040]/), "]"); var Name = reg(NameStartChar, NameChar, "*"); var Name_exact = reg("^", Name, "$"); var Nmtoken = reg(NameChar, "+"); var EntityRef = reg("&", Name, ";"); var CharRef = regg(/&#[0-9]+;|&#x[0-9a-fA-F]+;/); var Reference = regg(EntityRef, "|", CharRef); var PEReference = reg("%", Name, ";"); var EntityValue = regg( reg('"', regg(/[^%&"]/, "|", PEReference, "|", Reference), "*", '"'), "|", reg("'", regg(/[^%&']/, "|", PEReference, "|", Reference), "*", "'") ); var AttValue = regg('"', regg(/[^<&"]/, "|", Reference), "*", '"', "|", "'", regg(/[^<&']/, "|", Reference), "*", "'"); var NCNameStartChar = chars_without(NameStartChar, ":"); var NCNameChar = chars_without(NameChar, ":"); var NCName = reg(NCNameStartChar, NCNameChar, "*"); var NCName_exact = reg("^", NCName, "$"); var QName = reg(NCName, regg(":", NCName), "?"); var QName_exact = reg("^", QName, "$"); var QName_group = reg("(", QName, ")"); var SystemLiteral = regg(/"[^"]*"|'[^']*'/); var PI = reg(/^<\?/, "(", Name, ")", regg(S, "(?!", _SChar, ")(", Char, "*?)"), "?", /\?>/); var PubidChar = /[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/; var PubidLiteral = regg('"', PubidChar, '*"', "|", "'", chars_without(PubidChar, "'"), "*'"); var COMMENT_START = ""; var Comment = reg(COMMENT_START, regg(chars_without(Char, "-"), "|", reg("-", chars_without(Char, "-"))), "*", COMMENT_END); var PCDATA = "#PCDATA"; var Mixed = regg( reg(/\(/, S_OPT, PCDATA, regg(S_OPT, /\|/, S_OPT, QName), "*", S_OPT, /\)\*/), "|", reg(/\(/, S_OPT, PCDATA, S_OPT, /\)/) ); var _children_quantity = /[?*+]?/; var children2 = reg( /\([^>]+\)/, _children_quantity /*regg(choice, '|', seq), _children_quantity*/ ); var contentspec = regg("EMPTY", "|", "ANY", "|", Mixed, "|", children2); var ELEMENTDECL_START = ""); var NotationType = reg("NOTATION", S, /\(/, S_OPT, Name, regg(S_OPT, /\|/, S_OPT, Name), "*", S_OPT, /\)/); var Enumeration = reg(/\(/, S_OPT, Nmtoken, regg(S_OPT, /\|/, S_OPT, Nmtoken), "*", S_OPT, /\)/); var EnumeratedType = regg(NotationType, "|", Enumeration); var AttType = regg(/CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS/, "|", EnumeratedType); var DefaultDecl = regg(/#REQUIRED|#IMPLIED/, "|", regg(regg("#FIXED", S), "?", AttValue)); var AttDef = regg(S, Name, S, AttType, S, DefaultDecl); var ATTLIST_DECL_START = ""); var ABOUT_LEGACY_COMPAT = "about:legacy-compat"; var ABOUT_LEGACY_COMPAT_SystemLiteral = regg('"' + ABOUT_LEGACY_COMPAT + '"', "|", "'" + ABOUT_LEGACY_COMPAT + "'"); var SYSTEM = "SYSTEM"; var PUBLIC = "PUBLIC"; var ExternalID = regg(regg(SYSTEM, S, SystemLiteral), "|", regg(PUBLIC, S, PubidLiteral, S, SystemLiteral)); var ExternalID_match = reg( "^", regg( regg(SYSTEM, S, "(?", SystemLiteral, ")"), "|", regg(PUBLIC, S, "(?", PubidLiteral, ")", S, "(?", SystemLiteral, ")") ) ); var PubidLiteral_match = reg("^", PubidLiteral, "$"); var SystemLiteral_match = reg("^", SystemLiteral, "$"); var NDataDecl = regg(S, "NDATA", S, Name); var EntityDef = regg(EntityValue, "|", regg(ExternalID, NDataDecl, "?")); var ENTITY_DECL_START = ""); var PEDef = regg(EntityValue, "|", ExternalID); var PEDecl = reg(ENTITY_DECL_START, S, "%", S, Name, S, PEDef, S_OPT, ">"); var EntityDecl = regg(GEDecl, "|", PEDecl); var PublicID = reg(PUBLIC, S, PubidLiteral); var NotationDecl = reg(""); var Eq = reg(S_OPT, "=", S_OPT); var VersionNum = /1[.]\d+/; var VersionInfo = reg(S, "version", Eq, regg("'", VersionNum, "'", "|", '"', VersionNum, '"')); var EncName = /[A-Za-z][-A-Za-z0-9._]*/; var EncodingDecl = regg(S, "encoding", Eq, regg('"', EncName, '"', "|", "'", EncName, "'")); var SDDecl = regg(S, "standalone", Eq, regg("'", regg("yes", "|", "no"), "'", "|", '"', regg("yes", "|", "no"), '"')); var XMLDecl = reg(/^<\?xml/, VersionInfo, EncodingDecl, "?", SDDecl, "?", S_OPT, /\?>/); var DOCTYPE_DECL_START = ""; var CDStart = //; var CData = reg(Char, "*?", CDEnd); var CDSect = reg(CDStart, CData); exports.chars = chars; exports.chars_without = chars_without; exports.detectUnicodeSupport = detectUnicodeSupport; exports.reg = reg; exports.regg = regg; exports.ABOUT_LEGACY_COMPAT = ABOUT_LEGACY_COMPAT; exports.ABOUT_LEGACY_COMPAT_SystemLiteral = ABOUT_LEGACY_COMPAT_SystemLiteral; exports.AttlistDecl = AttlistDecl; exports.CDATA_START = CDATA_START; exports.CDATA_END = CDATA_END; exports.CDSect = CDSect; exports.Char = Char; exports.Comment = Comment; exports.COMMENT_START = COMMENT_START; exports.COMMENT_END = COMMENT_END; exports.DOCTYPE_DECL_START = DOCTYPE_DECL_START; exports.elementdecl = elementdecl; exports.EntityDecl = EntityDecl; exports.EntityValue = EntityValue; exports.ExternalID = ExternalID; exports.ExternalID_match = ExternalID_match; exports.Name = Name; exports.Name_exact = Name_exact; exports.NCName_exact = NCName_exact; exports.NotationDecl = NotationDecl; exports.Reference = Reference; exports.PEReference = PEReference; exports.PI = PI; exports.PUBLIC = PUBLIC; exports.PubidLiteral = PubidLiteral; exports.PubidLiteral_match = PubidLiteral_match; exports.QName = QName; exports.QName_exact = QName_exact; exports.QName_group = QName_group; exports.S = S; exports.SChar_s = SChar_s; exports.S_OPT = S_OPT; exports.SYSTEM = SYSTEM; exports.SystemLiteral = SystemLiteral; exports.SystemLiteral_match = SystemLiteral_match; exports.InvalidChar = InvalidChar; exports.UNICODE_REPLACEMENT_CHARACTER = UNICODE_REPLACEMENT_CHARACTER; exports.UNICODE_SUPPORT = UNICODE_SUPPORT; exports.XMLDecl = XMLDecl; } }); // node_modules/@xmldom/xmldom/lib/dom.js var require_dom = __commonJS({ "node_modules/@xmldom/xmldom/lib/dom.js"(exports) { "use strict"; init_define_L2W_CONFIG(); var conventions = require_conventions(); var find = conventions.find; var hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace; var hasOwn = conventions.hasOwn; var isHTMLMimeType = conventions.isHTMLMimeType; var isHTMLRawTextElement = conventions.isHTMLRawTextElement; var isHTMLVoidElement = conventions.isHTMLVoidElement; var MIME_TYPE = conventions.MIME_TYPE; var NAMESPACE = conventions.NAMESPACE; var PDC = /* @__PURE__ */ Symbol(); var errors = require_errors(); var DOMException = errors.DOMException; var DOMExceptionName = errors.DOMExceptionName; var g = require_grammar(); function checkSymbol(symbol) { if (symbol !== PDC) { throw new TypeError("Illegal constructor"); } } function notEmptyString(input) { return input !== ""; } function splitOnASCIIWhitespace(input) { return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : []; } function orderedSetReducer(current, element) { if (!hasOwn(current, element)) { current[element] = true; } return current; } function toOrderedSet(input) { if (!input) return []; var list = splitOnASCIIWhitespace(input); return Object.keys(list.reduce(orderedSetReducer, {})); } function arrayIncludes(list) { return function(element) { return list && list.indexOf(element) !== -1; }; } function validateQualifiedName(qualifiedName) { if (!g.QName_exact.test(qualifiedName)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'invalid character in qualified name "' + qualifiedName + '"'); } } function validateAndExtract(namespace, qualifiedName) { validateQualifiedName(qualifiedName); namespace = namespace || null; var prefix = null; var localName = qualifiedName; if (qualifiedName.indexOf(":") >= 0) { var splitResult = qualifiedName.split(":"); prefix = splitResult[0]; localName = splitResult[1]; } if (prefix !== null && namespace === null) { throw new DOMException(DOMException.NAMESPACE_ERR, "prefix is non-null and namespace is null"); } if (prefix === "xml" && namespace !== conventions.NAMESPACE.XML) { throw new DOMException(DOMException.NAMESPACE_ERR, 'prefix is "xml" and namespace is not the XML namespace'); } if ((prefix === "xmlns" || qualifiedName === "xmlns") && namespace !== conventions.NAMESPACE.XMLNS) { throw new DOMException( DOMException.NAMESPACE_ERR, 'either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace' ); } if (namespace === conventions.NAMESPACE.XMLNS && prefix !== "xmlns" && qualifiedName !== "xmlns") { throw new DOMException( DOMException.NAMESPACE_ERR, 'namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"' ); } return [namespace, prefix, localName]; } function copy(src, dest) { for (var p in src) { if (hasOwn(src, p)) { dest[p] = src[p]; } } } function _extends(Class, Super) { var pt = Class.prototype; if (!(pt instanceof Super)) { let t = function() { }; t.prototype = Super.prototype; t = new t(); copy(pt, t); Class.prototype = pt = t; } if (pt.constructor != Class) { if (typeof Class != "function") { console.error("unknown Class:" + Class); } pt.constructor = Class; } } var NodeType = {}; var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; var TEXT_NODE = NodeType.TEXT_NODE = 3; var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; var ENTITY_NODE = NodeType.ENTITY_NODE = 6; var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; var COMMENT_NODE = NodeType.COMMENT_NODE = 8; var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; var NOTATION_NODE = NodeType.NOTATION_NODE = 12; var DocumentPosition = conventions.freeze({ DOCUMENT_POSITION_DISCONNECTED: 1, DOCUMENT_POSITION_PRECEDING: 2, DOCUMENT_POSITION_FOLLOWING: 4, DOCUMENT_POSITION_CONTAINS: 8, DOCUMENT_POSITION_CONTAINED_BY: 16, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32 }); function commonAncestor(a, b) { if (b.length < a.length) return commonAncestor(b, a); var c = null; for (var n in a) { if (a[n] !== b[n]) return c; c = a[n]; } return c; } function docGUID(doc) { if (!doc.guid) doc.guid = Math.random(); return doc.guid; } function NodeList() { } NodeList.prototype = { /** * The number of nodes in the list. The range of valid child node indices is 0 to length-1 * inclusive. * * @type {number} */ length: 0, /** * Returns the item at `index`. If index is greater than or equal to the number of nodes in * the list, this returns null. * * @param index * Unsigned long Index into the collection. * @returns {Node | null} * The node at position `index` in the NodeList, * or null if that is not a valid index. */ item: function(index) { return index >= 0 && index < this.length ? this[index] : null; }, /** * Returns a string representation of the NodeList. * * Accepts the same `options` object as `XMLSerializer.prototype.serializeToString` * (`requireWellFormed`, `splitCDATASections`, `nodeFilter`). Passing a function is treated as * a legacy `nodeFilter` for backward compatibility. * * @param {Object | function} [options] * @param {boolean} [options.requireWellFormed=false] * @param {boolean} [options.splitCDATASections=true] * @param {function} [options.nodeFilter] * @returns {string} */ toString: function(options) { var opts; if (typeof options === "function") { opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: options }; } else if (!!options) { opts = { requireWellFormed: !!options.requireWellFormed, splitCDATASections: options.splitCDATASections !== false, nodeFilter: options.nodeFilter || null }; } else { opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: null }; } for (var buf = [], i = 0; i < this.length; i++) { serializeToString(this[i], buf, null, opts); } return buf.join(""); }, /** * Filters the NodeList based on a predicate. * * @param {function(Node): boolean} predicate * - A predicate function to filter the NodeList. * @returns {Node[]} * An array of nodes that satisfy the predicate. * @private */ filter: function(predicate) { return Array.prototype.filter.call(this, predicate); }, /** * Returns the first index at which a given node can be found in the NodeList, or -1 if it is * not present. * * @param {Node} item * - The Node item to locate in the NodeList. * @returns {number} * The first index of the node in the NodeList; -1 if not found. * @private */ indexOf: function(item) { return Array.prototype.indexOf.call(this, item); } }; NodeList.prototype[Symbol.iterator] = function() { var me = this; var index = 0; return { next: function() { if (index < me.length) { return { value: me[index++], done: false }; } else { return { done: true }; } }, return: function() { return { done: true }; } }; }; function LiveNodeList(node, refresh) { this._node = node; this._refresh = refresh; _updateLiveList(this); } function _updateLiveList(list) { var inc = list._node._inc || list._node.ownerDocument._inc; if (list._inc !== inc) { var ls = list._refresh(list._node); __set__(list, "length", ls.length); if (!list.$$length || ls.length < list.$$length) { for (var i = ls.length; i in list; i++) { if (hasOwn(list, i)) { delete list[i]; } } } copy(ls, list); list._inc = inc; } } LiveNodeList.prototype.item = function(i) { _updateLiveList(this); return this[i] || null; }; _extends(LiveNodeList, NodeList); function NamedNodeMap() { this._nsIndex = /* @__PURE__ */ Object.create(null); this._noNsIndex = /* @__PURE__ */ Object.create(null); } function _findNodeIndex(list, node) { var i = 0; while (i < list.length) { if (list[i] === node) { return i; } i++; } } function _nnmBucket(map, namespaceURI, create) { if (!namespaceURI) { return map._noNsIndex; } var bucket = map._nsIndex[namespaceURI]; if (!bucket && create) { bucket = map._nsIndex[namespaceURI] = /* @__PURE__ */ Object.create(null); } return bucket; } function _nnmIndexFind(map, namespaceURI, localName) { var bucket = _nnmBucket(map, namespaceURI, false); var found = bucket && bucket[localName]; return found ? found : null; } function _nnmIndexAdd(map, attr2) { _nnmBucket(map, attr2.namespaceURI, true)[attr2.localName] = attr2; } function _nnmIndexRemove(map, attr2) { var bucket = _nnmBucket(map, attr2.namespaceURI, false); if (bucket) { delete bucket[attr2.localName]; } } function _addNamedNode(el, list, newAttr, oldAttr) { if (oldAttr) { list[_findNodeIndex(list, oldAttr)] = newAttr; } else { list[list.length] = newAttr; list.length++; } _nnmIndexAdd(list, newAttr); if (el) { newAttr.ownerElement = el; var doc = el.ownerDocument; if (doc) { oldAttr && _onRemoveAttribute(doc, el, oldAttr); _onAddAttribute(doc, el, newAttr); } } } function _removeNamedNode(el, list, attr2) { var i = _findNodeIndex(list, attr2); if (i >= 0) { var lastIndex = list.length - 1; while (i <= lastIndex) { list[i] = list[++i]; } list.length = lastIndex; _nnmIndexRemove(list, attr2); if (el) { var doc = el.ownerDocument; if (doc) { _onRemoveAttribute(doc, el, attr2); } attr2.ownerElement = null; } } } NamedNodeMap.prototype = { length: 0, item: NodeList.prototype.item, /** * Get an attribute by name. Note: Name is in lower case in case of HTML namespace and * document. * * @param {string} localName * The local name of the attribute. * @returns {Attr | null} * The attribute with the given local name, or null if no such attribute exists. * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name */ getNamedItem: function(localName) { if (this._ownerElement && this._ownerElement._isInHTMLDocumentAndNamespace()) { localName = localName.toLowerCase(); } var i = 0; while (i < this.length) { var attr2 = this[i]; if (attr2.nodeName === localName) { return attr2; } i++; } return null; }, /** * Set an attribute. * * @param {Attr} attr * The attribute to set. * @returns {Attr | null} * The old attribute with the same local name and namespace URI as the new one, or null if no * such attribute exists. * @throws {DOMException} * With code: * - {@link INUSE_ATTRIBUTE_ERR} - If the attribute is already an attribute of another * element. * @see https://dom.spec.whatwg.org/#concept-element-attributes-set */ setNamedItem: function(attr2) { var el = attr2.ownerElement; if (el && el !== this._ownerElement) { throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR); } var oldAttr = _nnmIndexFind(this, attr2.namespaceURI, attr2.localName); if (oldAttr === attr2) { return attr2; } _addNamedNode(this._ownerElement, this, attr2, oldAttr); return oldAttr; }, /** * Set an attribute, replacing an existing attribute with the same local name and namespace * URI if one exists. * * @param {Attr} attr * The attribute to set. * @returns {Attr | null} * The old attribute with the same local name and namespace URI as the new one, or null if no * such attribute exists. * @throws {DOMException} * Throws a DOMException with the name "InUseAttributeError" if the attribute is already an * attribute of another element. * @see https://dom.spec.whatwg.org/#concept-element-attributes-set */ setNamedItemNS: function(attr2) { return this.setNamedItem(attr2); }, /** * Removes an attribute specified by the local name. * * @param {string} localName * The local name of the attribute to be removed. * @returns {Attr} * The attribute node that was removed. * @throws {DOMException} * With code: * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given name is found. * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name */ removeNamedItem: function(localName) { var attr2 = this.getNamedItem(localName); if (!attr2) { throw new DOMException(DOMException.NOT_FOUND_ERR, localName); } _removeNamedNode(this._ownerElement, this, attr2); return attr2; }, /** * Removes an attribute specified by the namespace and local name. * * @param {string | null} namespaceURI * The namespace URI of the attribute to be removed. * @param {string} localName * The local name of the attribute to be removed. * @returns {Attr} * The attribute node that was removed. * @throws {DOMException} * With code: * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given namespace URI and local * name is found. * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-namespace */ removeNamedItemNS: function(namespaceURI, localName) { var attr2 = this.getNamedItemNS(namespaceURI, localName); if (!attr2) { throw new DOMException(DOMException.NOT_FOUND_ERR, namespaceURI ? namespaceURI + " : " + localName : localName); } _removeNamedNode(this._ownerElement, this, attr2); return attr2; }, /** * Get an attribute by namespace and local name. * * @param {string | null} namespaceURI * The namespace URI of the attribute. * @param {string} localName * The local name of the attribute. * @returns {Attr | null} * The attribute with the given namespace URI and local name, or null if no such attribute * exists. * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace */ getNamedItemNS: function(namespaceURI, localName) { if (!namespaceURI) { namespaceURI = null; } var i = 0; while (i < this.length) { var node = this[i]; if (node.localName === localName && node.namespaceURI === namespaceURI) { return node; } i++; } return null; } }; NamedNodeMap.prototype[Symbol.iterator] = function() { var me = this; var index = 0; return { next: function() { if (index < me.length) { return { value: me[index++], done: false }; } else { return { done: true }; } }, return: function() { return { done: true }; } }; }; function DOMImplementation() { } DOMImplementation.prototype = { /** * Test if the DOM implementation implements a specific feature and version, as specified in * {@link https://www.w3.org/TR/DOM-Level-3-Core/core.html#DOMFeatures DOM Features}. * * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given * feature is supported. The different implementations fairly diverged in what kind of * features were reported. The latest version of the spec settled to force this method to * always return true, where the functionality was accurate and in use. * * @deprecated * It is deprecated and modern browsers return true in all cases. * @function DOMImplementation#hasFeature * @param {string} feature * The name of the feature to test. * @param {string} [version] * This is the version number of the feature to test. * @returns {boolean} * Always returns true. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-5CED94D7 DOM Level 3 Core */ hasFeature: function(feature, version2) { return true; }, /** * Creates a DOM Document object of the specified type with its document element. Note that * based on the {@link DocumentType} * given to create the document, the implementation may instantiate specialized * {@link Document} objects that support additional features than the "Core", such as "HTML" * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#DOM2HTML DOM Level 2 HTML}. * On the other hand, setting the {@link DocumentType} after the document was created makes * this very unlikely to happen. Alternatively, specialized {@link Document} creation methods, * such as createHTMLDocument * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#DOM2HTML DOM Level 2 HTML}, * can be used to obtain specific types of {@link Document} objects. * * __It behaves slightly different from the description in the living standard__: * - There is no interface/class `XMLDocument`, it returns a `Document` * instance (with it's `type` set to `'xml'`). * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. * * @function DOMImplementation.createDocument * @param {string | null} namespaceURI * The * {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-namespaceURI namespace URI} * of the document element to create or null. * @param {string | null} qualifiedName * The * {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified name} * of the document element to be created or null. * @param {DocumentType | null} [doctype=null] * The type of document to be created or null. When doctype is not null, its * {@link Node#ownerDocument} attribute is set to the document being created. Default is * `null` * @returns {Document} * A new {@link Document} object with its document element. If the NamespaceURI, * qualifiedName, and doctype are null, the returned {@link Document} is empty with no * document element. * @throws {DOMException} * With code: * * - `INVALID_CHARACTER_ERR`: Raised if the specified qualified name is not an XML name * according to {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#XML XML 1.0}. * - `NAMESPACE_ERR`: Raised if the qualifiedName is malformed, if the qualifiedName has a * prefix and the namespaceURI is null, or if the qualifiedName is null and the namespaceURI * is different from null, or if the qualifiedName has a prefix that is "xml" and the * namespaceURI is different from "{@link http://www.w3.org/XML/1998/namespace}" * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#Namespaces XML Namespaces}, * or if the DOM implementation does not support the "XML" feature but a non-null namespace * URI was provided, since namespaces were defined by XML. * - `WRONG_DOCUMENT_ERR`: Raised if doctype has already been used with a different document * or was created from a different implementation. * - `NOT_SUPPORTED_ERR`: May be raised if the implementation does not support the feature * "XML" and the language exposed through the Document does not support XML Namespaces (such * as {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#HTML40 HTML 4.01}). * @since DOM Level 2. * @see {@link #createHTMLDocument} * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Living Standard * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Level-2-Core-DOM-createDocument DOM * Level 3 Core * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM * Level 2 Core (initial) */ createDocument: function(namespaceURI, qualifiedName, doctype) { var contentType = MIME_TYPE.XML_APPLICATION; if (namespaceURI === NAMESPACE.HTML) { contentType = MIME_TYPE.XML_XHTML_APPLICATION; } else if (namespaceURI === NAMESPACE.SVG) { contentType = MIME_TYPE.XML_SVG_IMAGE; } var doc = new Document(PDC, { contentType }); doc.implementation = this; doc.childNodes = new NodeList(); doc.doctype = doctype || null; if (doctype) { doc.appendChild(doctype); } if (qualifiedName) { var root = doc.createElementNS(namespaceURI, qualifiedName); doc.appendChild(root); } return doc; }, /** * Creates an empty DocumentType node. Entity declarations and notations are not made * available. Entity reference expansions and default attribute additions do not occur. * * **This behavior is slightly different from the one in the specs**: * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. * - `publicId` and `systemId` contain the raw data including any possible quotes, * so they can always be serialized back to the original value * - `internalSubset` contains the raw string between `[` and `]` if present, * but is not parsed or validated in any form. * * @function DOMImplementation#createDocumentType * @param {string} qualifiedName * The {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified * name} of the document type to be created. * @param {string} [publicId] * The external subset public identifier. Stored verbatim including surrounding quotes. * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the value is non-empty and does not match the XML `PubidLiteral` production * (W3C DOM Parsing §3.2.1.3; XML 1.0 production [12]). Creation-time validation is not * enforced — deferred to a future breaking release. * @param {string} [systemId] * The external subset system identifier. Stored verbatim including surrounding quotes. * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the value is non-empty and does not match the XML `SystemLiteral` production * (W3C DOM Parsing §3.2.1.3; XML 1.0 production [11]). Creation-time validation is not * enforced — deferred to a future breaking release. * @param {string} [internalSubset] * The internal subset or an empty string if it is not present. Stored verbatim. * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the value contains `"]>"`. Creation-time validation is not enforced. * @returns {DocumentType} * A new {@link DocumentType} node with {@link Node#ownerDocument} set to null. * @throws {DOMException} * With code: * * - `INVALID_CHARACTER_ERR`: Raised if the specified qualified name is not an XML name * according to {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#XML XML 1.0}. * - `NAMESPACE_ERR`: Raised if the qualifiedName is malformed. * - `NOT_SUPPORTED_ERR`: May be raised if the implementation does not support the feature * "XML" and the language exposed through the Document does not support XML Namespaces (such * as {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#HTML40 HTML 4.01}). * @since DOM Level 2. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType * MDN * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living * Standard * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Level-3-Core-DOM-createDocType DOM * Level 3 Core * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM * Level 2 Core * @see https://github.com/xmldom/xmldom/blob/master/CHANGELOG.md#050 * @see https://www.w3.org/TR/DOM-Level-2-Core/#core-ID-Core-DocType-internalSubset * @prettierignore */ createDocumentType: function(qualifiedName, publicId, systemId, internalSubset) { validateQualifiedName(qualifiedName); var node = new DocumentType(PDC); node.name = qualifiedName; node.nodeName = qualifiedName; node.publicId = publicId || ""; node.systemId = systemId || ""; node.internalSubset = internalSubset || ""; node.childNodes = new NodeList(); return node; }, /** * Returns an HTML document, that might already have a basic DOM structure. * * __It behaves slightly different from the description in the living standard__: * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs are * omitted) * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. * * @param {string | false} [title] * A string containing the title to give the new HTML document. * @returns {Document} * The HTML document. * @since WHATWG Living Standard. * @see {@link #createDocument} * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument * @see https://dom.spec.whatwg.org/#html-document */ createHTMLDocument: function(title) { var doc = new Document(PDC, { contentType: MIME_TYPE.HTML }); doc.implementation = this; doc.childNodes = new NodeList(); if (title !== false) { doc.doctype = this.createDocumentType("html"); doc.doctype.ownerDocument = doc; doc.appendChild(doc.doctype); var htmlNode = doc.createElement("html"); doc.appendChild(htmlNode); var headNode = doc.createElement("head"); htmlNode.appendChild(headNode); if (typeof title === "string") { var titleNode = doc.createElement("title"); titleNode.appendChild(doc.createTextNode(title)); headNode.appendChild(titleNode); } htmlNode.appendChild(doc.createElement("body")); } return doc; } }; function Node(symbol) { checkSymbol(symbol); } Node.prototype = { /** * The first child of this node. * * @type {Node | null} */ firstChild: null, /** * The last child of this node. * * @type {Node | null} */ lastChild: null, /** * The previous sibling of this node. * * @type {Node | null} */ previousSibling: null, /** * The next sibling of this node. * * @type {Node | null} */ nextSibling: null, /** * The parent node of this node. * * @type {Node | null} */ parentNode: null, /** * The parent element of this node. * * @type {Element | null} */ get parentElement() { return this.parentNode && this.parentNode.nodeType === this.ELEMENT_NODE ? this.parentNode : null; }, /** * The child nodes of this node. * * @type {NodeList} */ childNodes: null, /** * The document object associated with this node. * * @type {Document | null} */ ownerDocument: null, /** * The value of this node. * * @type {string | null} */ nodeValue: null, /** * The namespace URI of this node. * * @type {string | null} */ namespaceURI: null, /** * The prefix of the namespace for this node. * * @type {string | null} */ prefix: null, /** * The local part of the qualified name of this node. * * @type {string | null} */ localName: null, /** * The baseURI is currently always `about:blank`, * since that's what happens when you create a document from scratch. * * @type {'about:blank'} */ baseURI: "about:blank", /** * Is true if this node is part of a document. * * @type {boolean} */ get isConnected() { var rootNode = this.getRootNode(); return rootNode && rootNode.nodeType === rootNode.DOCUMENT_NODE; }, /** * Checks whether `other` is an inclusive descendant of this node. * * @param {Node | null | undefined} other * The node to check. * @returns {boolean} * True if `other` is an inclusive descendant of this node; false otherwise. * @see https://dom.spec.whatwg.org/#dom-node-contains */ contains: function(other) { if (!other) return false; var parent = other; do { if (this === parent) return true; parent = parent.parentNode; } while (parent); return false; }, /** * @typedef GetRootNodeOptions * @property {boolean} [composed=false] */ /** * Searches for the root node of this node. * * **This behavior is slightly different from the in the specs**: * - ignores `options.composed`, since `ShadowRoot`s are unsupported, always returns root. * * @param {GetRootNodeOptions} [options] * @returns {Node} * Root node. * @see https://dom.spec.whatwg.org/#dom-node-getrootnode * @see https://dom.spec.whatwg.org/#concept-shadow-including-root */ getRootNode: function(options) { var parent = this; do { if (!parent.parentNode) { return parent; } parent = parent.parentNode; } while (parent); }, /** * Checks whether the given node is equal to this node. * * Two nodes are equal when they have the same type, defining characteristics (for the type), * and the same childNodes. The comparison is iterative to avoid stack overflows on * deeply-nested trees. Attribute nodes of each Element pair are also pushed onto the stack * and compared the same way. * * @param {Node} [otherNode] * @returns {boolean} * @see https://dom.spec.whatwg.org/#concept-node-equals * @see ../docs/walk-dom.md. */ isEqualNode: function(otherNode) { if (!otherNode) return false; var stack = [{ node: this, other: otherNode }]; while (stack.length > 0) { var pair = stack.pop(); var node = pair.node; var other = pair.other; if (node.nodeType !== other.nodeType) return false; switch (node.nodeType) { case node.DOCUMENT_TYPE_NODE: if (node.name !== other.name) return false; if (node.publicId !== other.publicId) return false; if (node.systemId !== other.systemId) return false; break; case node.ELEMENT_NODE: if (node.namespaceURI !== other.namespaceURI) return false; if (node.prefix !== other.prefix) return false; if (node.localName !== other.localName) return false; if (node.attributes.length !== other.attributes.length) return false; for (var i = 0; i < node.attributes.length; i++) { var attr2 = node.attributes.item(i); var otherAttr = other.getAttributeNodeNS(attr2.namespaceURI, attr2.localName); if (!otherAttr) return false; stack.push({ node: attr2, other: otherAttr }); } break; case node.ATTRIBUTE_NODE: if (node.namespaceURI !== other.namespaceURI) return false; if (node.localName !== other.localName) return false; if (node.value !== other.value) return false; break; case node.PROCESSING_INSTRUCTION_NODE: if (node.target !== other.target || node.data !== other.data) return false; break; case node.TEXT_NODE: case node.CDATA_SECTION_NODE: case node.COMMENT_NODE: if (node.data !== other.data) return false; break; } if (node.childNodes.length !== other.childNodes.length) return false; for (var i = node.childNodes.length - 1; i >= 0; i--) { stack.push({ node: node.childNodes[i], other: other.childNodes[i] }); } } return true; }, /** * Checks whether or not the given node is this node. * * @param {Node} [otherNode] */ isSameNode: function(otherNode) { return this === otherNode; }, /** * Inserts a node before a reference node as a child of this node. * * @param {Node} newChild * The new child node to be inserted. * @param {Node | null} refChild * The reference node before which newChild will be inserted. * @returns {Node} * The new child node successfully inserted. * @throws {DOMException} * Throws a DOMException if inserting the node would result in a DOM tree that is not * well-formed, or if `child` is provided but is not a child of `parent`. * See {@link _insertBefore} for more details. * @since Modified in DOM L2 */ insertBefore: function(newChild, refChild) { return _insertBefore(this, newChild, refChild); }, /** * Replaces an old child node with a new child node within this node. * * @param {Node} newChild * The new node that is to replace the old node. * If it already exists in the DOM, it is removed from its original position. * @param {Node} oldChild * The existing child node to be replaced. * @returns {Node} * Returns the replaced child node. * @throws {DOMException} * Throws a DOMException if replacing the node would result in a DOM tree that is not * well-formed, or if `oldChild` is not a child of `this`. * This can also occur if the pre-replacement validity assertion fails. * See {@link _insertBefore}, {@link Node.removeChild}, and * {@link assertPreReplacementValidityInDocument} for more details. * @see https://dom.spec.whatwg.org/#concept-node-replace */ replaceChild: function(newChild, oldChild) { _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument); if (oldChild) { this.removeChild(oldChild); } }, /** * Removes an existing child node from this node. * * @param {Node} oldChild * The child node to be removed. * @returns {Node} * Returns the removed child node. * @throws {DOMException} * Throws a DOMException if `oldChild` is not a child of `this`. * See {@link _removeChild} for more details. */ removeChild: function(oldChild) { return _removeChild(this, oldChild); }, /** * Appends a child node to this node. * * @param {Node} newChild * The child node to be appended to this node. * If it already exists in the DOM, it is removed from its original position. * @returns {Node} * Returns the appended child node. * @throws {DOMException} * Throws a DOMException if appending the node would result in a DOM tree that is not * well-formed, or if `newChild` is not a valid Node. * See {@link insertBefore} for more details. */ appendChild: function(newChild) { return this.insertBefore(newChild, null); }, /** * Determines whether this node has any child nodes. * * @returns {boolean} * Returns true if this node has any child nodes, and false otherwise. */ hasChildNodes: function() { return this.firstChild != null; }, /** * Creates a copy of the calling node. * * @param {boolean} deep * If true, the contents of the node are recursively copied. * If false, only the node itself (and its attributes, if it is an element) are copied. * @returns {Node} * Returns the newly created copy of the node. * @throws {DOMException} * May throw a DOMException if operations within {@link Element#setAttributeNode} or * {@link Node#appendChild} (which are potentially invoked in this method) do not meet their * specific constraints. * @see {@link cloneNode} */ cloneNode: function(deep) { return cloneNode(this.ownerDocument || this, this, deep); }, /** * Puts the specified node and all of its subtree into a "normalized" form. In a normalized * subtree, no text nodes in the subtree are empty and there are no adjacent text nodes. * * Specifically, this method merges any adjacent text nodes (i.e., nodes for which `nodeType` * is `TEXT_NODE`) into a single node with the combined data. It also removes any empty text * nodes. * * This method iterativly traverses all child nodes to normalize all descendent nodes within * the subtree. * * @throws {DOMException} * May throw a DOMException if operations within removeChild or appendData (which are * potentially invoked in this method) do not meet their specific constraints. * @since Modified in DOM Level 2 * @see {@link Node.removeChild} * @see {@link CharacterData.appendData} * @see ../docs/walk-dom.md. */ normalize: function() { walkDOM(this, null, { enter: function(node) { var child = node.firstChild; while (child) { var next = child.nextSibling; if (next !== null && next.nodeType === TEXT_NODE && child.nodeType === TEXT_NODE) { var tail = []; var sibling = next; while (sibling !== null && sibling.nodeType === TEXT_NODE) { tail.push(sibling.data); sibling = sibling.nextSibling; } var removed = child.nextSibling; while (removed !== sibling) { var following = removed.nextSibling; removed.parentNode = null; removed.previousSibling = null; removed.nextSibling = null; removed = following; } child.nextSibling = sibling; if (sibling !== null) { sibling.previousSibling = child; } else { node.lastChild = child; } child.appendData(tail.join("")); _onUpdateChild(node.ownerDocument, node); child = sibling; } else { child = next; } } return true; } }); }, /** * Checks whether the DOM implementation implements a specific feature and its version. * * @deprecated * Since `DOMImplementation.hasFeature` is deprecated and always returns true. * @param {string} feature * The package name of the feature to test. This is the same name that can be passed to the * method `hasFeature` on `DOMImplementation`. * @param {string} version * This is the version number of the package name to test. * @returns {boolean} * Returns true in all cases in the current implementation. * @since Introduced in DOM Level 2 * @see {@link DOMImplementation.hasFeature} */ isSupported: function(feature, version2) { return this.ownerDocument.implementation.hasFeature(feature, version2); }, /** * Look up the prefix associated to the given namespace URI, starting from this node. * **The default namespace declarations are ignored by this method.** * See Namespace Prefix Lookup for details on the algorithm used by this method. * * **This behavior is different from the in the specs**: * - no node type specific handling * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes * * @param {string | null} namespaceURI * The namespace URI for which to find the associated prefix. * @returns {string | null} * The associated prefix, if found; otherwise, null. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix * @see https://github.com/xmldom/xmldom/issues/322 * @prettierignore */ lookupPrefix: function(namespaceURI) { var el = this; while (el) { var map = el._nsMap; if (map) { for (var n in map) { if (hasOwn(map, n) && map[n] === namespaceURI) { return n; } } } el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode; } return null; }, /** * This function is used to look up the namespace URI associated with the given prefix, * starting from this node. * * **This behavior is different from the in the specs**: * - no node type specific handling * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes * * @param {string | null} prefix * The prefix for which to find the associated namespace URI. * @returns {string | null} * The associated namespace URI, if found; otherwise, null. * @since DOM Level 3 * @see https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespaceURI * @prettierignore */ lookupNamespaceURI: function(prefix) { var el = this; while (el) { var map = el._nsMap; if (map) { if (hasOwn(map, prefix)) { return map[prefix]; } } el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode; } return null; }, /** * Determines whether the given namespace URI is the default namespace. * * The function works by looking up the prefix associated with the given namespace URI. If no * prefix is found (i.e., the namespace URI is not registered in the namespace map of this * node or any of its ancestors), it returns `true`, implying the namespace URI is considered * the default. * * **This behavior is different from the in the specs**: * - no node type specific handling * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes * * @param {string | null} namespaceURI * The namespace URI to be checked. * @returns {boolean} * Returns true if the given namespace URI is the default namespace, false otherwise. * @since DOM Level 3 * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-isDefaultNamespace * @see https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace * @prettierignore */ isDefaultNamespace: function(namespaceURI) { var prefix = this.lookupPrefix(namespaceURI); return prefix == null; }, /** * Compares the reference node with a node with regard to their position in the document and * according to the document order. * * @param {Node} other * The node to compare the reference node to. * @returns {number} * Returns how the node is positioned relatively to the reference node according to the * bitmask. 0 if reference node and given node are the same. * @since DOM Level 3 * @see https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-compare * @see https://dom.spec.whatwg.org/#dom-node-comparedocumentposition */ compareDocumentPosition: function(other) { if (this === other) return 0; var node1 = other; var node2 = this; var attr1 = null; var attr2 = null; if (node1 instanceof Attr) { attr1 = node1; node1 = attr1.ownerElement; } if (node2 instanceof Attr) { attr2 = node2; node2 = attr2.ownerElement; if (attr1 && node1 && node2 === node1) { for (var i = 0, attr3; attr3 = node2.attributes[i]; i++) { if (attr3 === attr1) return DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + DocumentPosition.DOCUMENT_POSITION_PRECEDING; if (attr3 === attr2) return DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + DocumentPosition.DOCUMENT_POSITION_FOLLOWING; } } } if (!node1 || !node2 || node2.ownerDocument !== node1.ownerDocument) { return DocumentPosition.DOCUMENT_POSITION_DISCONNECTED + DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + (docGUID(node2.ownerDocument) > docGUID(node1.ownerDocument) ? DocumentPosition.DOCUMENT_POSITION_FOLLOWING : DocumentPosition.DOCUMENT_POSITION_PRECEDING); } if (attr2 && node1 === node2) { return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING; } if (attr1 && node1 === node2) { return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING; } var chain1 = []; var ancestor1 = node1.parentNode; while (ancestor1) { if (!attr2 && ancestor1 === node2) { return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING; } chain1.push(ancestor1); ancestor1 = ancestor1.parentNode; } chain1.reverse(); var chain2 = []; var ancestor2 = node2.parentNode; while (ancestor2) { if (!attr1 && ancestor2 === node1) { return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING; } chain2.push(ancestor2); ancestor2 = ancestor2.parentNode; } chain2.reverse(); var ca = commonAncestor(chain1, chain2); for (var n in ca.childNodes) { var child = ca.childNodes[n]; if (child === node2) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING; if (child === node1) return DocumentPosition.DOCUMENT_POSITION_PRECEDING; if (chain2.indexOf(child) >= 0) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING; if (chain1.indexOf(child) >= 0) return DocumentPosition.DOCUMENT_POSITION_PRECEDING; } return 0; } }; function _xmlEncoder(c) { return c == "<" && "<" || c == ">" && ">" || c == "&" && "&" || c == '"' && """ || "&#" + c.charCodeAt() + ";"; } copy(NodeType, Node); copy(NodeType, Node.prototype); copy(DocumentPosition, Node); copy(DocumentPosition, Node.prototype); function _visitNode(node, callback) { walkDOM(node, null, { enter: function(n) { return callback(n) ? walkDOM.STOP : true; } }); } function walkDOM(node, context, callbacks) { var stack = [{ node, context, phase: walkDOM.ENTER }]; while (stack.length > 0) { var frame2 = stack.pop(); if (frame2.phase === walkDOM.ENTER) { var childContext = callbacks.enter(frame2.node, frame2.context); if (childContext === walkDOM.STOP) { return walkDOM.STOP; } stack.push({ node: frame2.node, context: childContext, phase: walkDOM.EXIT }); if (childContext === null || childContext === void 0) { continue; } var child = frame2.node.lastChild; while (child) { stack.push({ node: child, context: childContext, phase: walkDOM.ENTER }); child = child.previousSibling; } } else { if (callbacks.exit) { callbacks.exit(frame2.node, frame2.context); } } } } walkDOM.STOP = /* @__PURE__ */ Symbol("walkDOM.STOP"); walkDOM.ENTER = 0; walkDOM.EXIT = 1; function Document(symbol, options) { checkSymbol(symbol); var opt = options || {}; this.ownerDocument = this; this.contentType = opt.contentType || MIME_TYPE.XML_APPLICATION; this.type = isHTMLMimeType(this.contentType) ? "html" : "xml"; } function _onAddAttribute(doc, el, newAttr) { doc && doc._inc++; var ns = newAttr.namespaceURI; if (ns === NAMESPACE.XMLNS) { el._nsMap[newAttr.prefix ? newAttr.localName : ""] = newAttr.value; } } function _onRemoveAttribute(doc, el, newAttr, remove) { doc && doc._inc++; var ns = newAttr.namespaceURI; if (ns === NAMESPACE.XMLNS) { delete el._nsMap[newAttr.prefix ? newAttr.localName : ""]; } } function _onUpdateChild(doc, parent, newChild) { if (doc && doc._inc) { doc._inc++; var childNodes = parent.childNodes; if (newChild && !newChild.nextSibling) { childNodes[childNodes.length++] = newChild; } else { var child = parent.firstChild; var i = 0; while (child) { childNodes[i++] = child; child = child.nextSibling; } childNodes.length = i; delete childNodes[childNodes.length]; } } } function _removeChild(parentNode, child) { if (parentNode !== child.parentNode) { throw new DOMException(DOMException.NOT_FOUND_ERR, "child's parent is not parent"); } var oldPreviousSibling = child.previousSibling; var oldNextSibling = child.nextSibling; if (oldPreviousSibling) { oldPreviousSibling.nextSibling = oldNextSibling; } else { parentNode.firstChild = oldNextSibling; } if (oldNextSibling) { oldNextSibling.previousSibling = oldPreviousSibling; } else { parentNode.lastChild = oldPreviousSibling; } _onUpdateChild(parentNode.ownerDocument, parentNode); child.parentNode = null; child.previousSibling = null; child.nextSibling = null; return child; } function hasValidParentNodeType(node) { return node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE); } function hasInsertableNodeType(node) { return node && (node.nodeType === Node.CDATA_SECTION_NODE || node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.DOCUMENT_TYPE_NODE || node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE || node.nodeType === Node.TEXT_NODE); } function isDocTypeNode(node) { return node && node.nodeType === Node.DOCUMENT_TYPE_NODE; } function isElementNode(node) { return node && node.nodeType === Node.ELEMENT_NODE; } function isTextNode(node) { return node && node.nodeType === Node.TEXT_NODE; } function isElementInsertionPossible(doc, child) { var parentChildNodes = doc.childNodes || []; if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) { return false; } var docTypeNode = find(parentChildNodes, isDocTypeNode); return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); } function isElementReplacementPossible(doc, child) { var parentChildNodes = doc.childNodes || []; function hasElementChildThatIsNotChild(node) { return isElementNode(node) && node !== child; } if (find(parentChildNodes, hasElementChildThatIsNotChild)) { return false; } var docTypeNode = find(parentChildNodes, isDocTypeNode); return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); } function assertPreInsertionValidity1to5(parent, node, child) { if (!hasValidParentNodeType(parent)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Unexpected parent node type " + parent.nodeType); } if (child && child.parentNode !== parent) { throw new DOMException(DOMException.NOT_FOUND_ERR, "child not in parent"); } if ( // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException. !hasInsertableNodeType(node) || // 5. If either `node` is a Text node and `parent` is a document, // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0 // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE) // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException. isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE ) { throw new DOMException( DOMException.HIERARCHY_REQUEST_ERR, "Unexpected node type " + node.nodeType + " for parent node type " + parent.nodeType ); } } function assertPreInsertionValidityInDocument(parent, node, child) { var parentChildNodes = parent.childNodes || []; var nodeChildNodes = node.childNodes || []; if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { var nodeChildElements = nodeChildNodes.filter(isElementNode); if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "More than one element or text in fragment"); } if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype"); } } if (isElementNode(node)) { if (!isElementInsertionPossible(parent, child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype"); } } if (isDocTypeNode(node)) { if (find(parentChildNodes, isDocTypeNode)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one doctype is allowed"); } var parentElementChild = find(parentChildNodes, isElementNode); if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can only be inserted before an element"); } if (!child && parentElementChild) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can not be appended since element is present"); } } } function assertPreReplacementValidityInDocument(parent, node, child) { var parentChildNodes = parent.childNodes || []; var nodeChildNodes = node.childNodes || []; if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { var nodeChildElements = nodeChildNodes.filter(isElementNode); if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "More than one element or text in fragment"); } if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype"); } } if (isElementNode(node)) { if (!isElementReplacementPossible(parent, child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype"); } } if (isDocTypeNode(node)) { let hasDoctypeChildThatIsNotChild = function(node2) { return isDocTypeNode(node2) && node2 !== child; }; if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one doctype is allowed"); } var parentElementChild = find(parentChildNodes, isElementNode); if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can only be inserted before an element"); } } } function _insertBefore(parent, node, child, _inDocumentAssertion) { assertPreInsertionValidity1to5(parent, node, child); if (parent.nodeType === Node.DOCUMENT_NODE) { (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child); } var cp = node.parentNode; if (cp) { cp.removeChild(node); } if (node.nodeType === DOCUMENT_FRAGMENT_NODE) { var newFirst = node.firstChild; if (newFirst == null) { return node; } var newLast = node.lastChild; } else { newFirst = newLast = node; } var pre = child ? child.previousSibling : parent.lastChild; newFirst.previousSibling = pre; newLast.nextSibling = child; if (pre) { pre.nextSibling = newFirst; } else { parent.firstChild = newFirst; } if (child == null) { parent.lastChild = newLast; } else { child.previousSibling = newLast; } do { newFirst.parentNode = parent; } while (newFirst !== newLast && (newFirst = newFirst.nextSibling)); _onUpdateChild(parent.ownerDocument || parent, parent, node); if (node.nodeType == DOCUMENT_FRAGMENT_NODE) { node.firstChild = node.lastChild = null; } return node; } Document.prototype = { /** * The implementation that created this document. * * @type DOMImplementation * @readonly */ implementation: null, nodeName: "#document", nodeType: DOCUMENT_NODE, /** * The DocumentType node of the document. * * @type DocumentType * @readonly */ doctype: null, documentElement: null, _inc: 1, insertBefore: function(newChild, refChild) { if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) { var child = newChild.firstChild; while (child) { var next = child.nextSibling; this.insertBefore(child, refChild); child = next; } return newChild; } _insertBefore(this, newChild, refChild); newChild.ownerDocument = this; if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) { this.documentElement = newChild; } return newChild; }, removeChild: function(oldChild) { var removed = _removeChild(this, oldChild); if (removed === this.documentElement) { this.documentElement = null; } return removed; }, replaceChild: function(newChild, oldChild) { _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument); newChild.ownerDocument = this; if (oldChild) { this.removeChild(oldChild); } if (isElementNode(newChild)) { this.documentElement = newChild; } }, /** * Imports a node from another document into this document, creating a new copy owned by this * document. The source node and its subtree are not modified. * * @param {Node} importedNode * The node to import. * @param {boolean} deep * If true, the contents of the node are recursively imported. * If false, only the node itself (and its attributes, if it is an element) are imported. * @returns {Node} * Returns the newly created import of the node. * @see {@link importNode} * @see {@link https://dom.spec.whatwg.org/#dom-document-importnode} */ importNode: function(importedNode, deep) { return importNode(this, importedNode, deep); }, // Introduced in DOM Level 2: getElementById: function(id) { var rtv = null; _visitNode(this.documentElement, function(node) { if (node.nodeType == ELEMENT_NODE) { if (node.getAttribute("id") == id) { rtv = node; return true; } } }); return rtv; }, /** * Creates a new `Element` that is owned by this `Document`. * In HTML Documents `localName` is the lower cased `tagName`, * otherwise no transformation is being applied. * When `contentType` implies the HTML namespace, it will be set as `namespaceURI`. * * __This implementation differs from the specification:__ - The provided name is not checked * against the `Name` production, * so no related error will be thrown. * - There is no interface `HTMLElement`, it is always an `Element`. * - There is no support for a second argument to indicate using custom elements. * * @param {string} tagName * @returns {Element} * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement * @see https://dom.spec.whatwg.org/#dom-document-createelement * @see https://dom.spec.whatwg.org/#concept-create-element */ createElement: function(tagName) { var node = new Element(PDC); node.ownerDocument = this; if (this.type === "html") { tagName = tagName.toLowerCase(); } if (hasDefaultHTMLNamespace(this.contentType)) { node.namespaceURI = NAMESPACE.HTML; } node.nodeName = tagName; node.tagName = tagName; node.localName = tagName; node.childNodes = new NodeList(); var attrs = node.attributes = new NamedNodeMap(); attrs._ownerElement = node; return node; }, /** * @returns {DocumentFragment} */ createDocumentFragment: function() { var node = new DocumentFragment(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); return node; }, /** * @param {string} data * @returns {Text} */ createTextNode: function(data) { var node = new Text(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.appendData(data); return node; }, /** * @param {string} data * @returns {Comment} * @see https://dom.spec.whatwg.org/#dom-document-createcomment * @see https://www.w3.org/TR/xml/#NT-Comment XML 1.0 production [15] * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.3 * * Note: no validation is performed at creation time. When the resulting document is * serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the comment data contains `--` anywhere, ends with `-`, or contains characters * outside the XML Char production (W3C DOM Parsing §3.2.1.3). Without that option the * data is emitted verbatim. */ createComment: function(data) { var node = new Comment(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.appendData(data); return node; }, /** * Returns a new CDATASection node whose data is `data`. * * __This implementation differs from the specification:__ - calling this method on an HTML * document does not throw `NotSupportedError`. * * @param {string} data * @returns {CDATASection} * @throws {DOMException} * With code `INVALID_CHARACTER_ERR` if `data` contains `"]]>"`. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createCDATASection * @see https://dom.spec.whatwg.org/#dom-document-createcdatasection */ createCDATASection: function(data) { if (data.indexOf("]]>") !== -1) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'data contains "]]>"'); } var node = new CDATASection(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.appendData(data); return node; }, /** * Returns a ProcessingInstruction node whose target is target and data is data. * * __This behavior is slightly different from the in the specs__: * - it does not do any input validation on the arguments and doesn't throw * "InvalidCharacterError". * * Note: When the resulting document is serialized with `requireWellFormed: true`, the * serializer throws `InvalidStateError` if `.target` is not a valid XML `NCName` (a `Name` * with no colon) or is an ASCII case-insensitive match for `"xml"`, or if `.data` contains * `?>` or characters outside the XML Char production (W3C DOM Parsing §3.2.1.7). Without that * option the target and data are emitted verbatim. * * @param {string} target * @param {string} data * @returns {ProcessingInstruction} * @see https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction * @see https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.7 */ createProcessingInstruction: function(target, data) { var node = new ProcessingInstruction(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.nodeName = node.target = target; node.nodeValue = node.data = data; return node; }, /** * Creates an `Attr` node that is owned by this document. * In HTML Documents `localName` is the lower cased `name`, * otherwise no transformation is being applied. * * __This implementation differs from the specification:__ - The provided name is not checked * against the `Name` production, * so no related error will be thrown. * * @param {string} name * @returns {Attr} * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute * @see https://dom.spec.whatwg.org/#dom-document-createattribute */ createAttribute: function(name) { if (!g.QName_exact.test(name)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'invalid character in name "' + name + '"'); } if (this.type === "html") { name = name.toLowerCase(); } return this._createAttribute(name); }, _createAttribute: function(name) { var node = new Attr(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.name = name; node.nodeName = name; node.localName = name; node.specified = true; return node; }, /** * Creates an EntityReference object. * The current implementation does not fill the `childNodes` with those of the corresponding * `Entity` * * The `name` is validated against the XML `Name` production at creation time; an invalid name * throws `InvalidCharacterError`. When the resulting node is serialized with * `requireWellFormed: true`, the serializer re-validates `nodeName` against the XML `Name` * production and throws `InvalidStateError` if a later `nodeName` mutation made it invalid; * without that option the name is emitted verbatim. * * __This implementation differs from the specification:__ xmldom does not expand entities — * the parser resolves entity references inline and never constructs `EntityReference` nodes, * so this method is the only producer. * * @deprecated * In DOM Level 4. * @param {string} name * The name of the entity to reference. No namespace well-formedness checks are performed. * @returns {EntityReference} * @throws {DOMException} * With code `INVALID_CHARACTER_ERR` when `name` is not a valid XML `Name`. * @throws {DOMException} * with code `NOT_SUPPORTED_ERR` when the document is of type `html` * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-392B75AE */ createEntityReference: function(name) { if (!g.Name_exact.test(name)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'not a valid xml name "' + name + '"'); } if (this.type === "html") { throw new DOMException("document is an html document", DOMExceptionName.NotSupportedError); } var node = new EntityReference(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.nodeName = name; return node; }, // Introduced in DOM Level 2: /** * @param {string} namespaceURI * @param {string} qualifiedName * @returns {Element} */ createElementNS: function(namespaceURI, qualifiedName) { var validated = validateAndExtract(namespaceURI, qualifiedName); var node = new Element(PDC); var attrs = node.attributes = new NamedNodeMap(); node.childNodes = new NodeList(); node.ownerDocument = this; node.nodeName = qualifiedName; node.tagName = qualifiedName; node.namespaceURI = validated[0]; node.prefix = validated[1]; node.localName = validated[2]; attrs._ownerElement = node; return node; }, // Introduced in DOM Level 2: /** * @param {string} namespaceURI * @param {string} qualifiedName * @returns {Attr} */ createAttributeNS: function(namespaceURI, qualifiedName) { var validated = validateAndExtract(namespaceURI, qualifiedName); var node = new Attr(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.nodeName = qualifiedName; node.name = qualifiedName; node.specified = true; node.namespaceURI = validated[0]; node.prefix = validated[1]; node.localName = validated[2]; return node; } }; _extends(Document, Node); function Element(symbol) { checkSymbol(symbol); this._nsMap = /* @__PURE__ */ Object.create(null); } Element.prototype = { nodeType: ELEMENT_NODE, /** * The attributes of this element. * * @type {NamedNodeMap | null} */ attributes: null, getQualifiedName: function() { return this.prefix ? this.prefix + ":" + this.localName : this.localName; }, _isInHTMLDocumentAndNamespace: function() { return this.ownerDocument.type === "html" && this.namespaceURI === NAMESPACE.HTML; }, /** * Implementaton of Level2 Core function hasAttributes. * * @returns {boolean} * True if attribute list is not empty. * @see https://www.w3.org/TR/DOM-Level-2-Core/#core-ID-NodeHasAttrs */ hasAttributes: function() { return !!(this.attributes && this.attributes.length); }, hasAttribute: function(name) { return !!this.getAttributeNode(name); }, /** * Returns element’s first attribute whose qualified name is `name`, and `null` * if there is no such attribute. * * @param {string} name * @returns {string | null} */ getAttribute: function(name) { var attr2 = this.getAttributeNode(name); return attr2 ? attr2.value : null; }, getAttributeNode: function(name) { if (this._isInHTMLDocumentAndNamespace()) { name = name.toLowerCase(); } return this.attributes.getNamedItem(name); }, /** * Sets the value of element’s first attribute whose qualified name is qualifiedName to value. * * @param {string} name * @param {string} value */ setAttribute: function(name, value) { if (this._isInHTMLDocumentAndNamespace()) { name = name.toLowerCase(); } var attr2 = this.getAttributeNode(name); if (attr2) { attr2.value = attr2.nodeValue = "" + value; } else { attr2 = this.ownerDocument._createAttribute(name); attr2.value = attr2.nodeValue = "" + value; this.setAttributeNode(attr2); } }, removeAttribute: function(name) { var attr2 = this.getAttributeNode(name); attr2 && this.removeAttributeNode(attr2); }, setAttributeNode: function(newAttr) { return this.attributes.setNamedItem(newAttr); }, setAttributeNodeNS: function(newAttr) { return this.attributes.setNamedItemNS(newAttr); }, removeAttributeNode: function(oldAttr) { return this.attributes.removeNamedItem(oldAttr.nodeName); }, //get real attribute name,and remove it by removeAttributeNode removeAttributeNS: function(namespaceURI, localName) { var old = this.getAttributeNodeNS(namespaceURI, localName); old && this.removeAttributeNode(old); }, hasAttributeNS: function(namespaceURI, localName) { return this.getAttributeNodeNS(namespaceURI, localName) != null; }, /** * Returns element’s attribute whose namespace is `namespaceURI` and local name is * `localName`, * or `null` if there is no such attribute. * * @param {string} namespaceURI * @param {string} localName * @returns {string | null} */ getAttributeNS: function(namespaceURI, localName) { var attr2 = this.getAttributeNodeNS(namespaceURI, localName); return attr2 ? attr2.value : null; }, /** * Sets the value of element’s attribute whose namespace is `namespaceURI` and local name is * `localName` to value. * * @param {string} namespaceURI * @param {string} qualifiedName * @param {string} value * @see https://dom.spec.whatwg.org/#dom-element-setattributens */ setAttributeNS: function(namespaceURI, qualifiedName, value) { var validated = validateAndExtract(namespaceURI, qualifiedName); var localName = validated[2]; var attr2 = this.getAttributeNodeNS(namespaceURI, localName); if (attr2) { attr2.value = attr2.nodeValue = "" + value; } else { attr2 = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); attr2.value = attr2.nodeValue = "" + value; this.setAttributeNode(attr2); } }, getAttributeNodeNS: function(namespaceURI, localName) { return this.attributes.getNamedItemNS(namespaceURI, localName); }, /** * Returns a LiveNodeList of all child elements which have **all** of the given class name(s). * * Returns an empty list if `classNames` is an empty string or only contains HTML white space * characters. * * Warning: This returns a live LiveNodeList. * Changes in the DOM will reflect in the array as the changes occur. * If an element selected by this array no longer qualifies for the selector, * it will automatically be removed. Be aware of this for iteration purposes. * * @param {string} classNames * Is a string representing the class name(s) to match; multiple class names are separated by * (ASCII-)whitespace. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname */ getElementsByClassName: function(classNames) { var classNamesSet = toOrderedSet(classNames); return new LiveNodeList(this, function(base) { var ls = []; if (classNamesSet.length > 0) { _visitNode(base, function(node) { if (node !== base && node.nodeType === ELEMENT_NODE) { var nodeClassNames = node.getAttribute("class"); if (nodeClassNames) { var matches = classNames === nodeClassNames; if (!matches) { var nodeClassNamesSet = toOrderedSet(nodeClassNames); matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet)); } if (matches) { ls.push(node); } } } }); } return ls; }); }, /** * Returns a LiveNodeList of elements with the given qualifiedName. * Searching for all descendants can be done by passing `*` as `qualifiedName`. * * All descendants of the specified element are searched, but not the element itself. * The returned list is live, which means it updates itself with the DOM tree automatically. * Therefore, there is no need to call `Element.getElementsByTagName()` * with the same element and arguments repeatedly if the DOM changes in between calls. * * When called on an HTML element in an HTML document, * `getElementsByTagName` lower-cases the argument before searching for it. * This is undesirable when trying to match camel-cased SVG elements (such as * ``) in an HTML document. * Instead, use `Element.getElementsByTagNameNS()`, * which preserves the capitalization of the tag name. * * `Element.getElementsByTagName` is similar to `Document.getElementsByTagName()`, * except that it only searches for elements that are descendants of the specified element. * * @param {string} qualifiedName * @returns {LiveNodeList} * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName * @see https://dom.spec.whatwg.org/#concept-getelementsbytagname */ getElementsByTagName: function(qualifiedName) { var isHTMLDocument = (this.nodeType === DOCUMENT_NODE ? this : this.ownerDocument).type === "html"; var lowerQualifiedName = qualifiedName.toLowerCase(); return new LiveNodeList(this, function(base) { var ls = []; _visitNode(base, function(node) { if (node === base || node.nodeType !== ELEMENT_NODE) { return; } if (qualifiedName === "*") { ls.push(node); } else { var nodeQualifiedName = node.getQualifiedName(); var matchingQName = isHTMLDocument && node.namespaceURI === NAMESPACE.HTML ? lowerQualifiedName : qualifiedName; if (nodeQualifiedName === matchingQName) { ls.push(node); } } }); return ls; }); }, getElementsByTagNameNS: function(namespaceURI, localName) { return new LiveNodeList(this, function(base) { var ls = []; _visitNode(base, function(node) { if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === "*" || node.namespaceURI === namespaceURI) && (localName === "*" || node.localName == localName)) { ls.push(node); } }); return ls; }); } }; Document.prototype.getElementsByClassName = Element.prototype.getElementsByClassName; Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; _extends(Element, Node); function Attr(symbol) { checkSymbol(symbol); this.namespaceURI = null; this.prefix = null; this.ownerElement = null; } Attr.prototype.nodeType = ATTRIBUTE_NODE; _extends(Attr, Node); function CharacterData(symbol) { checkSymbol(symbol); } CharacterData.prototype = { data: "", substringData: function(offset, count) { return this.data.substring(offset, offset + count); }, appendData: function(text) { text = this.data + text; this.nodeValue = this.data = text; this.length = text.length; }, insertData: function(offset, text) { this.replaceData(offset, 0, text); }, deleteData: function(offset, count) { this.replaceData(offset, count, ""); }, replaceData: function(offset, count, text) { var start = this.data.substring(0, offset); var end = this.data.substring(offset + count); text = start + text + end; this.nodeValue = this.data = text; this.length = text.length; } }; _extends(CharacterData, Node); function Text(symbol) { checkSymbol(symbol); } Text.prototype = { nodeName: "#text", nodeType: TEXT_NODE, splitText: function(offset) { var text = this.data; var newText = text.substring(offset); text = text.substring(0, offset); this.data = this.nodeValue = text; this.length = text.length; var newNode = this.ownerDocument.createTextNode(newText); if (this.parentNode) { this.parentNode.insertBefore(newNode, this.nextSibling); } return newNode; } }; _extends(Text, CharacterData); function Comment(symbol) { checkSymbol(symbol); } Comment.prototype = { nodeName: "#comment", nodeType: COMMENT_NODE }; _extends(Comment, CharacterData); function CDATASection(symbol) { checkSymbol(symbol); } CDATASection.prototype = { nodeName: "#cdata-section", nodeType: CDATA_SECTION_NODE }; _extends(CDATASection, Text); function DocumentType(symbol) { checkSymbol(symbol); } DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; _extends(DocumentType, Node); function Notation(symbol) { checkSymbol(symbol); } Notation.prototype.nodeType = NOTATION_NODE; _extends(Notation, Node); function Entity(symbol) { checkSymbol(symbol); } Entity.prototype.nodeType = ENTITY_NODE; _extends(Entity, Node); function EntityReference(symbol) { checkSymbol(symbol); } EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; _extends(EntityReference, Node); function DocumentFragment(symbol) { checkSymbol(symbol); } DocumentFragment.prototype.nodeName = "#document-fragment"; DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; _extends(DocumentFragment, Node); function ProcessingInstruction(symbol) { checkSymbol(symbol); } ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; _extends(ProcessingInstruction, CharacterData); function XMLSerializer() { } XMLSerializer.prototype.serializeToString = function(node, options) { return nodeSerializeToString.call(node, options); }; Node.prototype.toString = nodeSerializeToString; function nodeSerializeToString(options) { var opts; if (typeof options === "function") { opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: options }; } else if (options != null) { opts = { requireWellFormed: !!options.requireWellFormed, splitCDATASections: options.splitCDATASections !== false, nodeFilter: options.nodeFilter || null }; } else { opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: null }; } var buf = []; var refNode = this.nodeType === DOCUMENT_NODE && this.documentElement || this; var prefix = refNode.prefix; var uri = refNode.namespaceURI; if (uri && prefix == null) { var prefix = refNode.lookupPrefix(uri); if (prefix == null) { var visibleNamespaces = [ { namespace: uri, prefix: null } //{namespace:uri,prefix:''} ]; } } serializeToString(this, buf, visibleNamespaces, opts); return buf.join(""); } function needNamespaceDefine(node, isHTML, visibleNamespaces) { var prefix = node.prefix || ""; var uri = node.namespaceURI; if (!uri) { return false; } if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) { return false; } var i = visibleNamespaces.length; while (i--) { var ns = visibleNamespaces[i]; if (ns.prefix === prefix) { return ns.namespace !== uri; } } return true; } function addSerializedAttribute(buf, qualifiedName, value, requireWellFormed) { if (requireWellFormed && !g.QName_exact.test(qualifiedName)) { throw new DOMException( 'The attribute name "' + qualifiedName + '" is not a valid XML QName', DOMExceptionName.InvalidStateError ); } buf.push(" ", qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"'); } function serializeToString(node, buf, visibleNamespaces, opts) { if (!visibleNamespaces) { visibleNamespaces = []; } var nodeFilter = opts.nodeFilter; var requireWellFormed = opts.requireWellFormed; var splitCDATASections = opts.splitCDATASections; var doc = node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument; var isHTML = doc.type === "html"; walkDOM( node, { ns: visibleNamespaces }, { enter: function(n, ctx) { var namespaces = ctx.ns; if (nodeFilter) { n = nodeFilter(n); if (n) { if (typeof n == "string") { buf.push(n); return null; } } else { return null; } } switch (n.nodeType) { case ELEMENT_NODE: var attrs = n.attributes; var len = attrs.length; var nodeName = n.tagName; var prefixedNodeName = nodeName; if (!isHTML && !n.prefix && n.namespaceURI) { var defaultNS; for (var ai = 0; ai < attrs.length; ai++) { if (attrs.item(ai).name === "xmlns") { defaultNS = attrs.item(ai).value; break; } } if (!defaultNS) { for (var nsi = namespaces.length - 1; nsi >= 0; nsi--) { var nsEntry = namespaces[nsi]; if (nsEntry.prefix === "" && nsEntry.namespace === n.namespaceURI) { defaultNS = nsEntry.namespace; break; } } } if (defaultNS !== n.namespaceURI) { for (var nsi = namespaces.length - 1; nsi >= 0; nsi--) { var nsEntry = namespaces[nsi]; if (nsEntry.namespace === n.namespaceURI) { if (nsEntry.prefix) { prefixedNodeName = nsEntry.prefix + ":" + nodeName; } break; } } } } if (requireWellFormed && !g.QName_exact.test(prefixedNodeName)) { throw new DOMException( 'The element name "' + prefixedNodeName + '" is not a valid XML QName', DOMExceptionName.InvalidStateError ); } buf.push("<", prefixedNodeName); var childNamespaces = namespaces.slice(); for (var i = 0; i < len; i++) { var attr2 = attrs.item(i); if (attr2.prefix == "xmlns") { childNamespaces.push({ prefix: attr2.localName, namespace: attr2.value }); } else if (attr2.nodeName == "xmlns") { childNamespaces.push({ prefix: "", namespace: attr2.value }); } } for (var i = 0; i < len; i++) { var attr2 = attrs.item(i); if (needNamespaceDefine(attr2, isHTML, childNamespaces)) { var attrPrefix = attr2.prefix || ""; var uri = attr2.namespaceURI; addSerializedAttribute(buf, attrPrefix ? "xmlns:" + attrPrefix : "xmlns", uri, requireWellFormed); childNamespaces.push({ prefix: attrPrefix, namespace: uri }); } var filteredAttr = nodeFilter ? nodeFilter(attr2) : attr2; if (filteredAttr) { if (typeof filteredAttr === "string") { buf.push(filteredAttr); } else { addSerializedAttribute(buf, filteredAttr.name, filteredAttr.value, requireWellFormed); } } } if (nodeName === prefixedNodeName && needNamespaceDefine(n, isHTML, childNamespaces)) { var nodePrefix = n.prefix || ""; var uri = n.namespaceURI; addSerializedAttribute(buf, nodePrefix ? "xmlns:" + nodePrefix : "xmlns", uri, requireWellFormed); childNamespaces.push({ prefix: nodePrefix, namespace: uri }); } var canCloseTag = !n.firstChild; if (canCloseTag && (isHTML || n.namespaceURI === NAMESPACE.HTML)) { canCloseTag = isHTMLVoidElement(nodeName); } if (canCloseTag) { buf.push("/>"); return null; } buf.push(">"); if (isHTML && isHTMLRawTextElement(nodeName)) { var child = n.firstChild; while (child) { if (child.data) { buf.push(child.data); } else { serializeToString(child, buf, childNamespaces.slice(), opts); } child = child.nextSibling; } buf.push(""); return null; } return { ns: childNamespaces, tag: prefixedNodeName }; case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: if (requireWellFormed && n.nodeType === DOCUMENT_NODE && n.documentElement == null) { throw new DOMException("The Document has no documentElement", DOMExceptionName.InvalidStateError); } return { ns: namespaces }; case ATTRIBUTE_NODE: addSerializedAttribute(buf, n.name, n.value, requireWellFormed); return null; case TEXT_NODE: if (requireWellFormed && g.InvalidChar.test(n.data)) { throw new DOMException( "The Text node data contains characters outside the XML Char production", DOMExceptionName.InvalidStateError ); } buf.push(n.data.replace(/[<&>]/g, _xmlEncoder)); return null; case CDATA_SECTION_NODE: if (requireWellFormed && n.data.indexOf("]]>") !== -1) { throw new DOMException('The CDATASection data contains "]]>"', DOMExceptionName.InvalidStateError); } if (splitCDATASections) { buf.push(g.CDATA_START, n.data.replace(/]]>/g, "]]]]>"), g.CDATA_END); } else { buf.push(g.CDATA_START, n.data, g.CDATA_END); } return null; case COMMENT_NODE: if (requireWellFormed) { if (g.InvalidChar.test(n.data)) { throw new DOMException( "The comment node data contains characters outside the XML Char production", DOMExceptionName.InvalidStateError ); } if (n.data.indexOf("--") !== -1 || n.data[n.data.length - 1] === "-") { throw new DOMException( 'The comment node data contains "--" or ends with "-"', DOMExceptionName.InvalidStateError ); } } buf.push(g.COMMENT_START, n.data, g.COMMENT_END); return null; case DOCUMENT_TYPE_NODE: var pubid = n.publicId; var sysid = n.systemId; if (requireWellFormed) { if (!g.Name_exact.test(n.name)) { throw new DOMException( 'The doctype name "' + n.name + '" is not a valid XML Name', DOMExceptionName.InvalidStateError ); } if (pubid && !g.PubidLiteral_match.test(pubid)) { throw new DOMException("DocumentType publicId is not a valid PubidLiteral", DOMExceptionName.InvalidStateError); } if (sysid && sysid !== "." && !g.SystemLiteral_match.test(sysid)) { throw new DOMException("DocumentType systemId is not a valid SystemLiteral", DOMExceptionName.InvalidStateError); } if (n.internalSubset && n.internalSubset.indexOf("]>") !== -1) { throw new DOMException('DocumentType internalSubset contains "]>"', DOMExceptionName.InvalidStateError); } } buf.push(g.DOCTYPE_DECL_START, " ", n.name); if (pubid) { buf.push(" ", g.PUBLIC, " ", pubid); if (sysid && sysid !== ".") { buf.push(" ", sysid); } } else if (sysid && sysid !== ".") { buf.push(" ", g.SYSTEM, " ", sysid); } if (n.internalSubset) { buf.push(" [", n.internalSubset, "]"); } buf.push(">"); return null; case PROCESSING_INSTRUCTION_NODE: if (requireWellFormed) { if (!g.NCName_exact.test(n.target) || n.target.toLowerCase() === "xml") { throw new DOMException( 'The processing instruction target "' + n.target + '" is not a valid XML NCName or is reserved', DOMExceptionName.InvalidStateError ); } if (g.InvalidChar.test(n.data)) { throw new DOMException( "The ProcessingInstruction data contains characters outside the XML Char production", DOMExceptionName.InvalidStateError ); } if (n.data.indexOf("?>") !== -1) { throw new DOMException('The ProcessingInstruction data contains "?>"', DOMExceptionName.InvalidStateError); } } buf.push(""); return null; case ENTITY_REFERENCE_NODE: if (requireWellFormed && !g.Name_exact.test(n.nodeName)) { throw new DOMException( 'The entity reference name "' + n.nodeName + '" is not a valid XML Name', DOMExceptionName.InvalidStateError ); } buf.push("&", n.nodeName, ";"); return null; //case ENTITY_NODE: //case NOTATION_NODE: default: buf.push("??", n.nodeName); return null; } }, exit: function(n, childCtx) { if (childCtx && childCtx.tag) { buf.push(""); } } } ); } function importNode(doc, node, deep) { var destRoot; walkDOM(node, null, { enter: function(srcNode, destParent) { var destNode = srcNode.cloneNode(false); destNode.ownerDocument = doc; destNode.parentNode = null; if (destParent === null) { destRoot = destNode; } else { destParent.appendChild(destNode); } var shouldDeep = srcNode.nodeType === ATTRIBUTE_NODE || deep; return shouldDeep ? destNode : null; } }); return destRoot; } function cloneNode(doc, node, deep) { var destRoot; walkDOM(node, null, { enter: function(srcNode, destParent) { var destNode = new srcNode.constructor(PDC); for (var n in srcNode) { if (hasOwn(srcNode, n)) { var v = srcNode[n]; if (typeof v != "object") { if (v != destNode[n]) { destNode[n] = v; } } } } if (srcNode.childNodes) { destNode.childNodes = new NodeList(); } destNode.ownerDocument = doc; var shouldDeep = deep; switch (destNode.nodeType) { case ELEMENT_NODE: var attrs = srcNode.attributes; var attrs2 = destNode.attributes = new NamedNodeMap(); var len = attrs.length; attrs2._ownerElement = destNode; for (var i = 0; i < len; i++) { destNode.setAttributeNode(cloneNode(doc, attrs.item(i), true)); } break; case ATTRIBUTE_NODE: shouldDeep = true; } if (destParent !== null) { destParent.appendChild(destNode); } else { destRoot = destNode; } return shouldDeep ? destNode : null; } }); return destRoot; } function __set__(object, key, value) { object[key] = value; } function childrenRefresh(node) { var ls = []; var child = node.firstChild; while (child) { if (child.nodeType === ELEMENT_NODE) { ls.push(child); } child = child.nextSibling; } return ls; } try { if (Object.defineProperty) { Object.defineProperty(LiveNodeList.prototype, "length", { get: function() { _updateLiveList(this); return this.$$length; } }); Object.defineProperty(Node.prototype, "textContent", { get: function() { if (this.nodeType === ELEMENT_NODE || this.nodeType === DOCUMENT_FRAGMENT_NODE) { var buf = []; walkDOM(this, null, { enter: function(n) { if (n.nodeType === ELEMENT_NODE || n.nodeType === DOCUMENT_FRAGMENT_NODE) { return true; } if (n.nodeType === PROCESSING_INSTRUCTION_NODE || n.nodeType === COMMENT_NODE) { return null; } buf.push(n.nodeValue); } }); return buf.join(""); } return this.nodeValue; }, set: function(data) { switch (this.nodeType) { case ELEMENT_NODE: case DOCUMENT_FRAGMENT_NODE: while (this.firstChild) { this.removeChild(this.firstChild); } if (data || String(data)) { this.appendChild(this.ownerDocument.createTextNode(data)); } break; default: this.data = data; this.value = data; this.nodeValue = data; } } }); Object.defineProperty(CharacterData.prototype, "data", { get: function() { return this._data != null ? this._data : ""; }, set: function(v) { this._data = v; this.length = typeof v === "string" ? v.length : 0; } }); Object.defineProperty(CharacterData.prototype, "nodeValue", { get: function() { return this.data; }, set: function(v) { this.data = v; }, enumerable: true, configurable: true }); Object.defineProperty(Element.prototype, "children", { get: function() { return new LiveNodeList(this, childrenRefresh); } }); Object.defineProperty(Document.prototype, "children", { get: function() { return new LiveNodeList(this, childrenRefresh); } }); Object.defineProperty(DocumentFragment.prototype, "children", { get: function() { return new LiveNodeList(this, childrenRefresh); } }); __set__ = function(object, key, value) { object["$$" + key] = value; }; } } catch (e) { } exports._updateLiveList = _updateLiveList; exports.Attr = Attr; exports.CDATASection = CDATASection; exports.CharacterData = CharacterData; exports.Comment = Comment; exports.Document = Document; exports.DocumentFragment = DocumentFragment; exports.DocumentType = DocumentType; exports.DOMImplementation = DOMImplementation; exports.Element = Element; exports.Entity = Entity; exports.EntityReference = EntityReference; exports.LiveNodeList = LiveNodeList; exports.NamedNodeMap = NamedNodeMap; exports.Node = Node; exports.NodeList = NodeList; exports.Notation = Notation; exports.Text = Text; exports.ProcessingInstruction = ProcessingInstruction; exports.walkDOM = walkDOM; exports.XMLSerializer = XMLSerializer; } }); // node_modules/@xmldom/xmldom/lib/entities.js var require_entities = __commonJS({ "node_modules/@xmldom/xmldom/lib/entities.js"(exports) { "use strict"; init_define_L2W_CONFIG(); var freeze = require_conventions().freeze; exports.XML_ENTITIES = freeze({ amp: "&", apos: "'", gt: ">", lt: "<", quot: '"' }); exports.HTML_ENTITIES = freeze({ Aacute: "\xC1", aacute: "\xE1", Abreve: "\u0102", abreve: "\u0103", ac: "\u223E", acd: "\u223F", acE: "\u223E\u0333", Acirc: "\xC2", acirc: "\xE2", acute: "\xB4", Acy: "\u0410", acy: "\u0430", AElig: "\xC6", aelig: "\xE6", af: "\u2061", Afr: "\u{1D504}", afr: "\u{1D51E}", Agrave: "\xC0", agrave: "\xE0", alefsym: "\u2135", aleph: "\u2135", Alpha: "\u0391", alpha: "\u03B1", Amacr: "\u0100", amacr: "\u0101", amalg: "\u2A3F", AMP: "&", amp: "&", And: "\u2A53", and: "\u2227", andand: "\u2A55", andd: "\u2A5C", andslope: "\u2A58", andv: "\u2A5A", ang: "\u2220", ange: "\u29A4", angle: "\u2220", angmsd: "\u2221", angmsdaa: "\u29A8", angmsdab: "\u29A9", angmsdac: "\u29AA", angmsdad: "\u29AB", angmsdae: "\u29AC", angmsdaf: "\u29AD", angmsdag: "\u29AE", angmsdah: "\u29AF", angrt: "\u221F", angrtvb: "\u22BE", angrtvbd: "\u299D", angsph: "\u2222", angst: "\xC5", angzarr: "\u237C", Aogon: "\u0104", aogon: "\u0105", Aopf: "\u{1D538}", aopf: "\u{1D552}", ap: "\u2248", apacir: "\u2A6F", apE: "\u2A70", ape: "\u224A", apid: "\u224B", apos: "'", ApplyFunction: "\u2061", approx: "\u2248", approxeq: "\u224A", Aring: "\xC5", aring: "\xE5", Ascr: "\u{1D49C}", ascr: "\u{1D4B6}", Assign: "\u2254", ast: "*", asymp: "\u2248", asympeq: "\u224D", Atilde: "\xC3", atilde: "\xE3", Auml: "\xC4", auml: "\xE4", awconint: "\u2233", awint: "\u2A11", backcong: "\u224C", backepsilon: "\u03F6", backprime: "\u2035", backsim: "\u223D", backsimeq: "\u22CD", Backslash: "\u2216", Barv: "\u2AE7", barvee: "\u22BD", Barwed: "\u2306", barwed: "\u2305", barwedge: "\u2305", bbrk: "\u23B5", bbrktbrk: "\u23B6", bcong: "\u224C", Bcy: "\u0411", bcy: "\u0431", bdquo: "\u201E", becaus: "\u2235", Because: "\u2235", because: "\u2235", bemptyv: "\u29B0", bepsi: "\u03F6", bernou: "\u212C", Bernoullis: "\u212C", Beta: "\u0392", beta: "\u03B2", beth: "\u2136", between: "\u226C", Bfr: "\u{1D505}", bfr: "\u{1D51F}", bigcap: "\u22C2", bigcirc: "\u25EF", bigcup: "\u22C3", bigodot: "\u2A00", bigoplus: "\u2A01", bigotimes: "\u2A02", bigsqcup: "\u2A06", bigstar: "\u2605", bigtriangledown: "\u25BD", bigtriangleup: "\u25B3", biguplus: "\u2A04", bigvee: "\u22C1", bigwedge: "\u22C0", bkarow: "\u290D", blacklozenge: "\u29EB", blacksquare: "\u25AA", blacktriangle: "\u25B4", blacktriangledown: "\u25BE", blacktriangleleft: "\u25C2", blacktriangleright: "\u25B8", blank: "\u2423", blk12: "\u2592", blk14: "\u2591", blk34: "\u2593", block: "\u2588", bne: "=\u20E5", bnequiv: "\u2261\u20E5", bNot: "\u2AED", bnot: "\u2310", Bopf: "\u{1D539}", bopf: "\u{1D553}", bot: "\u22A5", bottom: "\u22A5", bowtie: "\u22C8", boxbox: "\u29C9", boxDL: "\u2557", boxDl: "\u2556", boxdL: "\u2555", boxdl: "\u2510", boxDR: "\u2554", boxDr: "\u2553", boxdR: "\u2552", boxdr: "\u250C", boxH: "\u2550", boxh: "\u2500", boxHD: "\u2566", boxHd: "\u2564", boxhD: "\u2565", boxhd: "\u252C", boxHU: "\u2569", boxHu: "\u2567", boxhU: "\u2568", boxhu: "\u2534", boxminus: "\u229F", boxplus: "\u229E", boxtimes: "\u22A0", boxUL: "\u255D", boxUl: "\u255C", boxuL: "\u255B", boxul: "\u2518", boxUR: "\u255A", boxUr: "\u2559", boxuR: "\u2558", boxur: "\u2514", boxV: "\u2551", boxv: "\u2502", boxVH: "\u256C", boxVh: "\u256B", boxvH: "\u256A", boxvh: "\u253C", boxVL: "\u2563", boxVl: "\u2562", boxvL: "\u2561", boxvl: "\u2524", boxVR: "\u2560", boxVr: "\u255F", boxvR: "\u255E", boxvr: "\u251C", bprime: "\u2035", Breve: "\u02D8", breve: "\u02D8", brvbar: "\xA6", Bscr: "\u212C", bscr: "\u{1D4B7}", bsemi: "\u204F", bsim: "\u223D", bsime: "\u22CD", bsol: "\\", bsolb: "\u29C5", bsolhsub: "\u27C8", bull: "\u2022", bullet: "\u2022", bump: "\u224E", bumpE: "\u2AAE", bumpe: "\u224F", Bumpeq: "\u224E", bumpeq: "\u224F", Cacute: "\u0106", cacute: "\u0107", Cap: "\u22D2", cap: "\u2229", capand: "\u2A44", capbrcup: "\u2A49", capcap: "\u2A4B", capcup: "\u2A47", capdot: "\u2A40", CapitalDifferentialD: "\u2145", caps: "\u2229\uFE00", caret: "\u2041", caron: "\u02C7", Cayleys: "\u212D", ccaps: "\u2A4D", Ccaron: "\u010C", ccaron: "\u010D", Ccedil: "\xC7", ccedil: "\xE7", Ccirc: "\u0108", ccirc: "\u0109", Cconint: "\u2230", ccups: "\u2A4C", ccupssm: "\u2A50", Cdot: "\u010A", cdot: "\u010B", cedil: "\xB8", Cedilla: "\xB8", cemptyv: "\u29B2", cent: "\xA2", CenterDot: "\xB7", centerdot: "\xB7", Cfr: "\u212D", cfr: "\u{1D520}", CHcy: "\u0427", chcy: "\u0447", check: "\u2713", checkmark: "\u2713", Chi: "\u03A7", chi: "\u03C7", cir: "\u25CB", circ: "\u02C6", circeq: "\u2257", circlearrowleft: "\u21BA", circlearrowright: "\u21BB", circledast: "\u229B", circledcirc: "\u229A", circleddash: "\u229D", CircleDot: "\u2299", circledR: "\xAE", circledS: "\u24C8", CircleMinus: "\u2296", CirclePlus: "\u2295", CircleTimes: "\u2297", cirE: "\u29C3", cire: "\u2257", cirfnint: "\u2A10", cirmid: "\u2AEF", cirscir: "\u29C2", ClockwiseContourIntegral: "\u2232", CloseCurlyDoubleQuote: "\u201D", CloseCurlyQuote: "\u2019", clubs: "\u2663", clubsuit: "\u2663", Colon: "\u2237", colon: ":", Colone: "\u2A74", colone: "\u2254", coloneq: "\u2254", comma: ",", commat: "@", comp: "\u2201", compfn: "\u2218", complement: "\u2201", complexes: "\u2102", cong: "\u2245", congdot: "\u2A6D", Congruent: "\u2261", Conint: "\u222F", conint: "\u222E", ContourIntegral: "\u222E", Copf: "\u2102", copf: "\u{1D554}", coprod: "\u2210", Coproduct: "\u2210", COPY: "\xA9", copy: "\xA9", copysr: "\u2117", CounterClockwiseContourIntegral: "\u2233", crarr: "\u21B5", Cross: "\u2A2F", cross: "\u2717", Cscr: "\u{1D49E}", cscr: "\u{1D4B8}", csub: "\u2ACF", csube: "\u2AD1", csup: "\u2AD0", csupe: "\u2AD2", ctdot: "\u22EF", cudarrl: "\u2938", cudarrr: "\u2935", cuepr: "\u22DE", cuesc: "\u22DF", cularr: "\u21B6", cularrp: "\u293D", Cup: "\u22D3", cup: "\u222A", cupbrcap: "\u2A48", CupCap: "\u224D", cupcap: "\u2A46", cupcup: "\u2A4A", cupdot: "\u228D", cupor: "\u2A45", cups: "\u222A\uFE00", curarr: "\u21B7", curarrm: "\u293C", curlyeqprec: "\u22DE", curlyeqsucc: "\u22DF", curlyvee: "\u22CE", curlywedge: "\u22CF", curren: "\xA4", curvearrowleft: "\u21B6", curvearrowright: "\u21B7", cuvee: "\u22CE", cuwed: "\u22CF", cwconint: "\u2232", cwint: "\u2231", cylcty: "\u232D", Dagger: "\u2021", dagger: "\u2020", daleth: "\u2138", Darr: "\u21A1", dArr: "\u21D3", darr: "\u2193", dash: "\u2010", Dashv: "\u2AE4", dashv: "\u22A3", dbkarow: "\u290F", dblac: "\u02DD", Dcaron: "\u010E", dcaron: "\u010F", Dcy: "\u0414", dcy: "\u0434", DD: "\u2145", dd: "\u2146", ddagger: "\u2021", ddarr: "\u21CA", DDotrahd: "\u2911", ddotseq: "\u2A77", deg: "\xB0", Del: "\u2207", Delta: "\u0394", delta: "\u03B4", demptyv: "\u29B1", dfisht: "\u297F", Dfr: "\u{1D507}", dfr: "\u{1D521}", dHar: "\u2965", dharl: "\u21C3", dharr: "\u21C2", DiacriticalAcute: "\xB4", DiacriticalDot: "\u02D9", DiacriticalDoubleAcute: "\u02DD", DiacriticalGrave: "`", DiacriticalTilde: "\u02DC", diam: "\u22C4", Diamond: "\u22C4", diamond: "\u22C4", diamondsuit: "\u2666", diams: "\u2666", die: "\xA8", DifferentialD: "\u2146", digamma: "\u03DD", disin: "\u22F2", div: "\xF7", divide: "\xF7", divideontimes: "\u22C7", divonx: "\u22C7", DJcy: "\u0402", djcy: "\u0452", dlcorn: "\u231E", dlcrop: "\u230D", dollar: "$", Dopf: "\u{1D53B}", dopf: "\u{1D555}", Dot: "\xA8", dot: "\u02D9", DotDot: "\u20DC", doteq: "\u2250", doteqdot: "\u2251", DotEqual: "\u2250", dotminus: "\u2238", dotplus: "\u2214", dotsquare: "\u22A1", doublebarwedge: "\u2306", DoubleContourIntegral: "\u222F", DoubleDot: "\xA8", DoubleDownArrow: "\u21D3", DoubleLeftArrow: "\u21D0", DoubleLeftRightArrow: "\u21D4", DoubleLeftTee: "\u2AE4", DoubleLongLeftArrow: "\u27F8", DoubleLongLeftRightArrow: "\u27FA", DoubleLongRightArrow: "\u27F9", DoubleRightArrow: "\u21D2", DoubleRightTee: "\u22A8", DoubleUpArrow: "\u21D1", DoubleUpDownArrow: "\u21D5", DoubleVerticalBar: "\u2225", DownArrow: "\u2193", Downarrow: "\u21D3", downarrow: "\u2193", DownArrowBar: "\u2913", DownArrowUpArrow: "\u21F5", DownBreve: "\u0311", downdownarrows: "\u21CA", downharpoonleft: "\u21C3", downharpoonright: "\u21C2", DownLeftRightVector: "\u2950", DownLeftTeeVector: "\u295E", DownLeftVector: "\u21BD", DownLeftVectorBar: "\u2956", DownRightTeeVector: "\u295F", DownRightVector: "\u21C1", DownRightVectorBar: "\u2957", DownTee: "\u22A4", DownTeeArrow: "\u21A7", drbkarow: "\u2910", drcorn: "\u231F", drcrop: "\u230C", Dscr: "\u{1D49F}", dscr: "\u{1D4B9}", DScy: "\u0405", dscy: "\u0455", dsol: "\u29F6", Dstrok: "\u0110", dstrok: "\u0111", dtdot: "\u22F1", dtri: "\u25BF", dtrif: "\u25BE", duarr: "\u21F5", duhar: "\u296F", dwangle: "\u29A6", DZcy: "\u040F", dzcy: "\u045F", dzigrarr: "\u27FF", Eacute: "\xC9", eacute: "\xE9", easter: "\u2A6E", Ecaron: "\u011A", ecaron: "\u011B", ecir: "\u2256", Ecirc: "\xCA", ecirc: "\xEA", ecolon: "\u2255", Ecy: "\u042D", ecy: "\u044D", eDDot: "\u2A77", Edot: "\u0116", eDot: "\u2251", edot: "\u0117", ee: "\u2147", efDot: "\u2252", Efr: "\u{1D508}", efr: "\u{1D522}", eg: "\u2A9A", Egrave: "\xC8", egrave: "\xE8", egs: "\u2A96", egsdot: "\u2A98", el: "\u2A99", Element: "\u2208", elinters: "\u23E7", ell: "\u2113", els: "\u2A95", elsdot: "\u2A97", Emacr: "\u0112", emacr: "\u0113", empty: "\u2205", emptyset: "\u2205", EmptySmallSquare: "\u25FB", emptyv: "\u2205", EmptyVerySmallSquare: "\u25AB", emsp: "\u2003", emsp13: "\u2004", emsp14: "\u2005", ENG: "\u014A", eng: "\u014B", ensp: "\u2002", Eogon: "\u0118", eogon: "\u0119", Eopf: "\u{1D53C}", eopf: "\u{1D556}", epar: "\u22D5", eparsl: "\u29E3", eplus: "\u2A71", epsi: "\u03B5", Epsilon: "\u0395", epsilon: "\u03B5", epsiv: "\u03F5", eqcirc: "\u2256", eqcolon: "\u2255", eqsim: "\u2242", eqslantgtr: "\u2A96", eqslantless: "\u2A95", Equal: "\u2A75", equals: "=", EqualTilde: "\u2242", equest: "\u225F", Equilibrium: "\u21CC", equiv: "\u2261", equivDD: "\u2A78", eqvparsl: "\u29E5", erarr: "\u2971", erDot: "\u2253", Escr: "\u2130", escr: "\u212F", esdot: "\u2250", Esim: "\u2A73", esim: "\u2242", Eta: "\u0397", eta: "\u03B7", ETH: "\xD0", eth: "\xF0", Euml: "\xCB", euml: "\xEB", euro: "\u20AC", excl: "!", exist: "\u2203", Exists: "\u2203", expectation: "\u2130", ExponentialE: "\u2147", exponentiale: "\u2147", fallingdotseq: "\u2252", Fcy: "\u0424", fcy: "\u0444", female: "\u2640", ffilig: "\uFB03", fflig: "\uFB00", ffllig: "\uFB04", Ffr: "\u{1D509}", ffr: "\u{1D523}", filig: "\uFB01", FilledSmallSquare: "\u25FC", FilledVerySmallSquare: "\u25AA", fjlig: "fj", flat: "\u266D", fllig: "\uFB02", fltns: "\u25B1", fnof: "\u0192", Fopf: "\u{1D53D}", fopf: "\u{1D557}", ForAll: "\u2200", forall: "\u2200", fork: "\u22D4", forkv: "\u2AD9", Fouriertrf: "\u2131", fpartint: "\u2A0D", frac12: "\xBD", frac13: "\u2153", frac14: "\xBC", frac15: "\u2155", frac16: "\u2159", frac18: "\u215B", frac23: "\u2154", frac25: "\u2156", frac34: "\xBE", frac35: "\u2157", frac38: "\u215C", frac45: "\u2158", frac56: "\u215A", frac58: "\u215D", frac78: "\u215E", frasl: "\u2044", frown: "\u2322", Fscr: "\u2131", fscr: "\u{1D4BB}", gacute: "\u01F5", Gamma: "\u0393", gamma: "\u03B3", Gammad: "\u03DC", gammad: "\u03DD", gap: "\u2A86", Gbreve: "\u011E", gbreve: "\u011F", Gcedil: "\u0122", Gcirc: "\u011C", gcirc: "\u011D", Gcy: "\u0413", gcy: "\u0433", Gdot: "\u0120", gdot: "\u0121", gE: "\u2267", ge: "\u2265", gEl: "\u2A8C", gel: "\u22DB", geq: "\u2265", geqq: "\u2267", geqslant: "\u2A7E", ges: "\u2A7E", gescc: "\u2AA9", gesdot: "\u2A80", gesdoto: "\u2A82", gesdotol: "\u2A84", gesl: "\u22DB\uFE00", gesles: "\u2A94", Gfr: "\u{1D50A}", gfr: "\u{1D524}", Gg: "\u22D9", gg: "\u226B", ggg: "\u22D9", gimel: "\u2137", GJcy: "\u0403", gjcy: "\u0453", gl: "\u2277", gla: "\u2AA5", glE: "\u2A92", glj: "\u2AA4", gnap: "\u2A8A", gnapprox: "\u2A8A", gnE: "\u2269", gne: "\u2A88", gneq: "\u2A88", gneqq: "\u2269", gnsim: "\u22E7", Gopf: "\u{1D53E}", gopf: "\u{1D558}", grave: "`", GreaterEqual: "\u2265", GreaterEqualLess: "\u22DB", GreaterFullEqual: "\u2267", GreaterGreater: "\u2AA2", GreaterLess: "\u2277", GreaterSlantEqual: "\u2A7E", GreaterTilde: "\u2273", Gscr: "\u{1D4A2}", gscr: "\u210A", gsim: "\u2273", gsime: "\u2A8E", gsiml: "\u2A90", Gt: "\u226B", GT: ">", gt: ">", gtcc: "\u2AA7", gtcir: "\u2A7A", gtdot: "\u22D7", gtlPar: "\u2995", gtquest: "\u2A7C", gtrapprox: "\u2A86", gtrarr: "\u2978", gtrdot: "\u22D7", gtreqless: "\u22DB", gtreqqless: "\u2A8C", gtrless: "\u2277", gtrsim: "\u2273", gvertneqq: "\u2269\uFE00", gvnE: "\u2269\uFE00", Hacek: "\u02C7", hairsp: "\u200A", half: "\xBD", hamilt: "\u210B", HARDcy: "\u042A", hardcy: "\u044A", hArr: "\u21D4", harr: "\u2194", harrcir: "\u2948", harrw: "\u21AD", Hat: "^", hbar: "\u210F", Hcirc: "\u0124", hcirc: "\u0125", hearts: "\u2665", heartsuit: "\u2665", hellip: "\u2026", hercon: "\u22B9", Hfr: "\u210C", hfr: "\u{1D525}", HilbertSpace: "\u210B", hksearow: "\u2925", hkswarow: "\u2926", hoarr: "\u21FF", homtht: "\u223B", hookleftarrow: "\u21A9", hookrightarrow: "\u21AA", Hopf: "\u210D", hopf: "\u{1D559}", horbar: "\u2015", HorizontalLine: "\u2500", Hscr: "\u210B", hscr: "\u{1D4BD}", hslash: "\u210F", Hstrok: "\u0126", hstrok: "\u0127", HumpDownHump: "\u224E", HumpEqual: "\u224F", hybull: "\u2043", hyphen: "\u2010", Iacute: "\xCD", iacute: "\xED", ic: "\u2063", Icirc: "\xCE", icirc: "\xEE", Icy: "\u0418", icy: "\u0438", Idot: "\u0130", IEcy: "\u0415", iecy: "\u0435", iexcl: "\xA1", iff: "\u21D4", Ifr: "\u2111", ifr: "\u{1D526}", Igrave: "\xCC", igrave: "\xEC", ii: "\u2148", iiiint: "\u2A0C", iiint: "\u222D", iinfin: "\u29DC", iiota: "\u2129", IJlig: "\u0132", ijlig: "\u0133", Im: "\u2111", Imacr: "\u012A", imacr: "\u012B", image: "\u2111", ImaginaryI: "\u2148", imagline: "\u2110", imagpart: "\u2111", imath: "\u0131", imof: "\u22B7", imped: "\u01B5", Implies: "\u21D2", in: "\u2208", incare: "\u2105", infin: "\u221E", infintie: "\u29DD", inodot: "\u0131", Int: "\u222C", int: "\u222B", intcal: "\u22BA", integers: "\u2124", Integral: "\u222B", intercal: "\u22BA", Intersection: "\u22C2", intlarhk: "\u2A17", intprod: "\u2A3C", InvisibleComma: "\u2063", InvisibleTimes: "\u2062", IOcy: "\u0401", iocy: "\u0451", Iogon: "\u012E", iogon: "\u012F", Iopf: "\u{1D540}", iopf: "\u{1D55A}", Iota: "\u0399", iota: "\u03B9", iprod: "\u2A3C", iquest: "\xBF", Iscr: "\u2110", iscr: "\u{1D4BE}", isin: "\u2208", isindot: "\u22F5", isinE: "\u22F9", isins: "\u22F4", isinsv: "\u22F3", isinv: "\u2208", it: "\u2062", Itilde: "\u0128", itilde: "\u0129", Iukcy: "\u0406", iukcy: "\u0456", Iuml: "\xCF", iuml: "\xEF", Jcirc: "\u0134", jcirc: "\u0135", Jcy: "\u0419", jcy: "\u0439", Jfr: "\u{1D50D}", jfr: "\u{1D527}", jmath: "\u0237", Jopf: "\u{1D541}", jopf: "\u{1D55B}", Jscr: "\u{1D4A5}", jscr: "\u{1D4BF}", Jsercy: "\u0408", jsercy: "\u0458", Jukcy: "\u0404", jukcy: "\u0454", Kappa: "\u039A", kappa: "\u03BA", kappav: "\u03F0", Kcedil: "\u0136", kcedil: "\u0137", Kcy: "\u041A", kcy: "\u043A", Kfr: "\u{1D50E}", kfr: "\u{1D528}", kgreen: "\u0138", KHcy: "\u0425", khcy: "\u0445", KJcy: "\u040C", kjcy: "\u045C", Kopf: "\u{1D542}", kopf: "\u{1D55C}", Kscr: "\u{1D4A6}", kscr: "\u{1D4C0}", lAarr: "\u21DA", Lacute: "\u0139", lacute: "\u013A", laemptyv: "\u29B4", lagran: "\u2112", Lambda: "\u039B", lambda: "\u03BB", Lang: "\u27EA", lang: "\u27E8", langd: "\u2991", langle: "\u27E8", lap: "\u2A85", Laplacetrf: "\u2112", laquo: "\xAB", Larr: "\u219E", lArr: "\u21D0", larr: "\u2190", larrb: "\u21E4", larrbfs: "\u291F", larrfs: "\u291D", larrhk: "\u21A9", larrlp: "\u21AB", larrpl: "\u2939", larrsim: "\u2973", larrtl: "\u21A2", lat: "\u2AAB", lAtail: "\u291B", latail: "\u2919", late: "\u2AAD", lates: "\u2AAD\uFE00", lBarr: "\u290E", lbarr: "\u290C", lbbrk: "\u2772", lbrace: "{", lbrack: "[", lbrke: "\u298B", lbrksld: "\u298F", lbrkslu: "\u298D", Lcaron: "\u013D", lcaron: "\u013E", Lcedil: "\u013B", lcedil: "\u013C", lceil: "\u2308", lcub: "{", Lcy: "\u041B", lcy: "\u043B", ldca: "\u2936", ldquo: "\u201C", ldquor: "\u201E", ldrdhar: "\u2967", ldrushar: "\u294B", ldsh: "\u21B2", lE: "\u2266", le: "\u2264", LeftAngleBracket: "\u27E8", LeftArrow: "\u2190", Leftarrow: "\u21D0", leftarrow: "\u2190", LeftArrowBar: "\u21E4", LeftArrowRightArrow: "\u21C6", leftarrowtail: "\u21A2", LeftCeiling: "\u2308", LeftDoubleBracket: "\u27E6", LeftDownTeeVector: "\u2961", LeftDownVector: "\u21C3", LeftDownVectorBar: "\u2959", LeftFloor: "\u230A", leftharpoondown: "\u21BD", leftharpoonup: "\u21BC", leftleftarrows: "\u21C7", LeftRightArrow: "\u2194", Leftrightarrow: "\u21D4", leftrightarrow: "\u2194", leftrightarrows: "\u21C6", leftrightharpoons: "\u21CB", leftrightsquigarrow: "\u21AD", LeftRightVector: "\u294E", LeftTee: "\u22A3", LeftTeeArrow: "\u21A4", LeftTeeVector: "\u295A", leftthreetimes: "\u22CB", LeftTriangle: "\u22B2", LeftTriangleBar: "\u29CF", LeftTriangleEqual: "\u22B4", LeftUpDownVector: "\u2951", LeftUpTeeVector: "\u2960", LeftUpVector: "\u21BF", LeftUpVectorBar: "\u2958", LeftVector: "\u21BC", LeftVectorBar: "\u2952", lEg: "\u2A8B", leg: "\u22DA", leq: "\u2264", leqq: "\u2266", leqslant: "\u2A7D", les: "\u2A7D", lescc: "\u2AA8", lesdot: "\u2A7F", lesdoto: "\u2A81", lesdotor: "\u2A83", lesg: "\u22DA\uFE00", lesges: "\u2A93", lessapprox: "\u2A85", lessdot: "\u22D6", lesseqgtr: "\u22DA", lesseqqgtr: "\u2A8B", LessEqualGreater: "\u22DA", LessFullEqual: "\u2266", LessGreater: "\u2276", lessgtr: "\u2276", LessLess: "\u2AA1", lesssim: "\u2272", LessSlantEqual: "\u2A7D", LessTilde: "\u2272", lfisht: "\u297C", lfloor: "\u230A", Lfr: "\u{1D50F}", lfr: "\u{1D529}", lg: "\u2276", lgE: "\u2A91", lHar: "\u2962", lhard: "\u21BD", lharu: "\u21BC", lharul: "\u296A", lhblk: "\u2584", LJcy: "\u0409", ljcy: "\u0459", Ll: "\u22D8", ll: "\u226A", llarr: "\u21C7", llcorner: "\u231E", Lleftarrow: "\u21DA", llhard: "\u296B", lltri: "\u25FA", Lmidot: "\u013F", lmidot: "\u0140", lmoust: "\u23B0", lmoustache: "\u23B0", lnap: "\u2A89", lnapprox: "\u2A89", lnE: "\u2268", lne: "\u2A87", lneq: "\u2A87", lneqq: "\u2268", lnsim: "\u22E6", loang: "\u27EC", loarr: "\u21FD", lobrk: "\u27E6", LongLeftArrow: "\u27F5", Longleftarrow: "\u27F8", longleftarrow: "\u27F5", LongLeftRightArrow: "\u27F7", Longleftrightarrow: "\u27FA", longleftrightarrow: "\u27F7", longmapsto: "\u27FC", LongRightArrow: "\u27F6", Longrightarrow: "\u27F9", longrightarrow: "\u27F6", looparrowleft: "\u21AB", looparrowright: "\u21AC", lopar: "\u2985", Lopf: "\u{1D543}", lopf: "\u{1D55D}", loplus: "\u2A2D", lotimes: "\u2A34", lowast: "\u2217", lowbar: "_", LowerLeftArrow: "\u2199", LowerRightArrow: "\u2198", loz: "\u25CA", lozenge: "\u25CA", lozf: "\u29EB", lpar: "(", lparlt: "\u2993", lrarr: "\u21C6", lrcorner: "\u231F", lrhar: "\u21CB", lrhard: "\u296D", lrm: "\u200E", lrtri: "\u22BF", lsaquo: "\u2039", Lscr: "\u2112", lscr: "\u{1D4C1}", Lsh: "\u21B0", lsh: "\u21B0", lsim: "\u2272", lsime: "\u2A8D", lsimg: "\u2A8F", lsqb: "[", lsquo: "\u2018", lsquor: "\u201A", Lstrok: "\u0141", lstrok: "\u0142", Lt: "\u226A", LT: "<", lt: "<", ltcc: "\u2AA6", ltcir: "\u2A79", ltdot: "\u22D6", lthree: "\u22CB", ltimes: "\u22C9", ltlarr: "\u2976", ltquest: "\u2A7B", ltri: "\u25C3", ltrie: "\u22B4", ltrif: "\u25C2", ltrPar: "\u2996", lurdshar: "\u294A", luruhar: "\u2966", lvertneqq: "\u2268\uFE00", lvnE: "\u2268\uFE00", macr: "\xAF", male: "\u2642", malt: "\u2720", maltese: "\u2720", Map: "\u2905", map: "\u21A6", mapsto: "\u21A6", mapstodown: "\u21A7", mapstoleft: "\u21A4", mapstoup: "\u21A5", marker: "\u25AE", mcomma: "\u2A29", Mcy: "\u041C", mcy: "\u043C", mdash: "\u2014", mDDot: "\u223A", measuredangle: "\u2221", MediumSpace: "\u205F", Mellintrf: "\u2133", Mfr: "\u{1D510}", mfr: "\u{1D52A}", mho: "\u2127", micro: "\xB5", mid: "\u2223", midast: "*", midcir: "\u2AF0", middot: "\xB7", minus: "\u2212", minusb: "\u229F", minusd: "\u2238", minusdu: "\u2A2A", MinusPlus: "\u2213", mlcp: "\u2ADB", mldr: "\u2026", mnplus: "\u2213", models: "\u22A7", Mopf: "\u{1D544}", mopf: "\u{1D55E}", mp: "\u2213", Mscr: "\u2133", mscr: "\u{1D4C2}", mstpos: "\u223E", Mu: "\u039C", mu: "\u03BC", multimap: "\u22B8", mumap: "\u22B8", nabla: "\u2207", Nacute: "\u0143", nacute: "\u0144", nang: "\u2220\u20D2", nap: "\u2249", napE: "\u2A70\u0338", napid: "\u224B\u0338", napos: "\u0149", napprox: "\u2249", natur: "\u266E", natural: "\u266E", naturals: "\u2115", nbsp: "\xA0", nbump: "\u224E\u0338", nbumpe: "\u224F\u0338", ncap: "\u2A43", Ncaron: "\u0147", ncaron: "\u0148", Ncedil: "\u0145", ncedil: "\u0146", ncong: "\u2247", ncongdot: "\u2A6D\u0338", ncup: "\u2A42", Ncy: "\u041D", ncy: "\u043D", ndash: "\u2013", ne: "\u2260", nearhk: "\u2924", neArr: "\u21D7", nearr: "\u2197", nearrow: "\u2197", nedot: "\u2250\u0338", NegativeMediumSpace: "\u200B", NegativeThickSpace: "\u200B", NegativeThinSpace: "\u200B", NegativeVeryThinSpace: "\u200B", nequiv: "\u2262", nesear: "\u2928", nesim: "\u2242\u0338", NestedGreaterGreater: "\u226B", NestedLessLess: "\u226A", NewLine: "\n", nexist: "\u2204", nexists: "\u2204", Nfr: "\u{1D511}", nfr: "\u{1D52B}", ngE: "\u2267\u0338", nge: "\u2271", ngeq: "\u2271", ngeqq: "\u2267\u0338", ngeqslant: "\u2A7E\u0338", nges: "\u2A7E\u0338", nGg: "\u22D9\u0338", ngsim: "\u2275", nGt: "\u226B\u20D2", ngt: "\u226F", ngtr: "\u226F", nGtv: "\u226B\u0338", nhArr: "\u21CE", nharr: "\u21AE", nhpar: "\u2AF2", ni: "\u220B", nis: "\u22FC", nisd: "\u22FA", niv: "\u220B", NJcy: "\u040A", njcy: "\u045A", nlArr: "\u21CD", nlarr: "\u219A", nldr: "\u2025", nlE: "\u2266\u0338", nle: "\u2270", nLeftarrow: "\u21CD", nleftarrow: "\u219A", nLeftrightarrow: "\u21CE", nleftrightarrow: "\u21AE", nleq: "\u2270", nleqq: "\u2266\u0338", nleqslant: "\u2A7D\u0338", nles: "\u2A7D\u0338", nless: "\u226E", nLl: "\u22D8\u0338", nlsim: "\u2274", nLt: "\u226A\u20D2", nlt: "\u226E", nltri: "\u22EA", nltrie: "\u22EC", nLtv: "\u226A\u0338", nmid: "\u2224", NoBreak: "\u2060", NonBreakingSpace: "\xA0", Nopf: "\u2115", nopf: "\u{1D55F}", Not: "\u2AEC", not: "\xAC", NotCongruent: "\u2262", NotCupCap: "\u226D", NotDoubleVerticalBar: "\u2226", NotElement: "\u2209", NotEqual: "\u2260", NotEqualTilde: "\u2242\u0338", NotExists: "\u2204", NotGreater: "\u226F", NotGreaterEqual: "\u2271", NotGreaterFullEqual: "\u2267\u0338", NotGreaterGreater: "\u226B\u0338", NotGreaterLess: "\u2279", NotGreaterSlantEqual: "\u2A7E\u0338", NotGreaterTilde: "\u2275", NotHumpDownHump: "\u224E\u0338", NotHumpEqual: "\u224F\u0338", notin: "\u2209", notindot: "\u22F5\u0338", notinE: "\u22F9\u0338", notinva: "\u2209", notinvb: "\u22F7", notinvc: "\u22F6", NotLeftTriangle: "\u22EA", NotLeftTriangleBar: "\u29CF\u0338", NotLeftTriangleEqual: "\u22EC", NotLess: "\u226E", NotLessEqual: "\u2270", NotLessGreater: "\u2278", NotLessLess: "\u226A\u0338", NotLessSlantEqual: "\u2A7D\u0338", NotLessTilde: "\u2274", NotNestedGreaterGreater: "\u2AA2\u0338", NotNestedLessLess: "\u2AA1\u0338", notni: "\u220C", notniva: "\u220C", notnivb: "\u22FE", notnivc: "\u22FD", NotPrecedes: "\u2280", NotPrecedesEqual: "\u2AAF\u0338", NotPrecedesSlantEqual: "\u22E0", NotReverseElement: "\u220C", NotRightTriangle: "\u22EB", NotRightTriangleBar: "\u29D0\u0338", NotRightTriangleEqual: "\u22ED", NotSquareSubset: "\u228F\u0338", NotSquareSubsetEqual: "\u22E2", NotSquareSuperset: "\u2290\u0338", NotSquareSupersetEqual: "\u22E3", NotSubset: "\u2282\u20D2", NotSubsetEqual: "\u2288", NotSucceeds: "\u2281", NotSucceedsEqual: "\u2AB0\u0338", NotSucceedsSlantEqual: "\u22E1", NotSucceedsTilde: "\u227F\u0338", NotSuperset: "\u2283\u20D2", NotSupersetEqual: "\u2289", NotTilde: "\u2241", NotTildeEqual: "\u2244", NotTildeFullEqual: "\u2247", NotTildeTilde: "\u2249", NotVerticalBar: "\u2224", npar: "\u2226", nparallel: "\u2226", nparsl: "\u2AFD\u20E5", npart: "\u2202\u0338", npolint: "\u2A14", npr: "\u2280", nprcue: "\u22E0", npre: "\u2AAF\u0338", nprec: "\u2280", npreceq: "\u2AAF\u0338", nrArr: "\u21CF", nrarr: "\u219B", nrarrc: "\u2933\u0338", nrarrw: "\u219D\u0338", nRightarrow: "\u21CF", nrightarrow: "\u219B", nrtri: "\u22EB", nrtrie: "\u22ED", nsc: "\u2281", nsccue: "\u22E1", nsce: "\u2AB0\u0338", Nscr: "\u{1D4A9}", nscr: "\u{1D4C3}", nshortmid: "\u2224", nshortparallel: "\u2226", nsim: "\u2241", nsime: "\u2244", nsimeq: "\u2244", nsmid: "\u2224", nspar: "\u2226", nsqsube: "\u22E2", nsqsupe: "\u22E3", nsub: "\u2284", nsubE: "\u2AC5\u0338", nsube: "\u2288", nsubset: "\u2282\u20D2", nsubseteq: "\u2288", nsubseteqq: "\u2AC5\u0338", nsucc: "\u2281", nsucceq: "\u2AB0\u0338", nsup: "\u2285", nsupE: "\u2AC6\u0338", nsupe: "\u2289", nsupset: "\u2283\u20D2", nsupseteq: "\u2289", nsupseteqq: "\u2AC6\u0338", ntgl: "\u2279", Ntilde: "\xD1", ntilde: "\xF1", ntlg: "\u2278", ntriangleleft: "\u22EA", ntrianglelefteq: "\u22EC", ntriangleright: "\u22EB", ntrianglerighteq: "\u22ED", Nu: "\u039D", nu: "\u03BD", num: "#", numero: "\u2116", numsp: "\u2007", nvap: "\u224D\u20D2", nVDash: "\u22AF", nVdash: "\u22AE", nvDash: "\u22AD", nvdash: "\u22AC", nvge: "\u2265\u20D2", nvgt: ">\u20D2", nvHarr: "\u2904", nvinfin: "\u29DE", nvlArr: "\u2902", nvle: "\u2264\u20D2", nvlt: "<\u20D2", nvltrie: "\u22B4\u20D2", nvrArr: "\u2903", nvrtrie: "\u22B5\u20D2", nvsim: "\u223C\u20D2", nwarhk: "\u2923", nwArr: "\u21D6", nwarr: "\u2196", nwarrow: "\u2196", nwnear: "\u2927", Oacute: "\xD3", oacute: "\xF3", oast: "\u229B", ocir: "\u229A", Ocirc: "\xD4", ocirc: "\xF4", Ocy: "\u041E", ocy: "\u043E", odash: "\u229D", Odblac: "\u0150", odblac: "\u0151", odiv: "\u2A38", odot: "\u2299", odsold: "\u29BC", OElig: "\u0152", oelig: "\u0153", ofcir: "\u29BF", Ofr: "\u{1D512}", ofr: "\u{1D52C}", ogon: "\u02DB", Ograve: "\xD2", ograve: "\xF2", ogt: "\u29C1", ohbar: "\u29B5", ohm: "\u03A9", oint: "\u222E", olarr: "\u21BA", olcir: "\u29BE", olcross: "\u29BB", oline: "\u203E", olt: "\u29C0", Omacr: "\u014C", omacr: "\u014D", Omega: "\u03A9", omega: "\u03C9", Omicron: "\u039F", omicron: "\u03BF", omid: "\u29B6", ominus: "\u2296", Oopf: "\u{1D546}", oopf: "\u{1D560}", opar: "\u29B7", OpenCurlyDoubleQuote: "\u201C", OpenCurlyQuote: "\u2018", operp: "\u29B9", oplus: "\u2295", Or: "\u2A54", or: "\u2228", orarr: "\u21BB", ord: "\u2A5D", order: "\u2134", orderof: "\u2134", ordf: "\xAA", ordm: "\xBA", origof: "\u22B6", oror: "\u2A56", orslope: "\u2A57", orv: "\u2A5B", oS: "\u24C8", Oscr: "\u{1D4AA}", oscr: "\u2134", Oslash: "\xD8", oslash: "\xF8", osol: "\u2298", Otilde: "\xD5", otilde: "\xF5", Otimes: "\u2A37", otimes: "\u2297", otimesas: "\u2A36", Ouml: "\xD6", ouml: "\xF6", ovbar: "\u233D", OverBar: "\u203E", OverBrace: "\u23DE", OverBracket: "\u23B4", OverParenthesis: "\u23DC", par: "\u2225", para: "\xB6", parallel: "\u2225", parsim: "\u2AF3", parsl: "\u2AFD", part: "\u2202", PartialD: "\u2202", Pcy: "\u041F", pcy: "\u043F", percnt: "%", period: ".", permil: "\u2030", perp: "\u22A5", pertenk: "\u2031", Pfr: "\u{1D513}", pfr: "\u{1D52D}", Phi: "\u03A6", phi: "\u03C6", phiv: "\u03D5", phmmat: "\u2133", phone: "\u260E", Pi: "\u03A0", pi: "\u03C0", pitchfork: "\u22D4", piv: "\u03D6", planck: "\u210F", planckh: "\u210E", plankv: "\u210F", plus: "+", plusacir: "\u2A23", plusb: "\u229E", pluscir: "\u2A22", plusdo: "\u2214", plusdu: "\u2A25", pluse: "\u2A72", PlusMinus: "\xB1", plusmn: "\xB1", plussim: "\u2A26", plustwo: "\u2A27", pm: "\xB1", Poincareplane: "\u210C", pointint: "\u2A15", Popf: "\u2119", popf: "\u{1D561}", pound: "\xA3", Pr: "\u2ABB", pr: "\u227A", prap: "\u2AB7", prcue: "\u227C", prE: "\u2AB3", pre: "\u2AAF", prec: "\u227A", precapprox: "\u2AB7", preccurlyeq: "\u227C", Precedes: "\u227A", PrecedesEqual: "\u2AAF", PrecedesSlantEqual: "\u227C", PrecedesTilde: "\u227E", preceq: "\u2AAF", precnapprox: "\u2AB9", precneqq: "\u2AB5", precnsim: "\u22E8", precsim: "\u227E", Prime: "\u2033", prime: "\u2032", primes: "\u2119", prnap: "\u2AB9", prnE: "\u2AB5", prnsim: "\u22E8", prod: "\u220F", Product: "\u220F", profalar: "\u232E", profline: "\u2312", profsurf: "\u2313", prop: "\u221D", Proportion: "\u2237", Proportional: "\u221D", propto: "\u221D", prsim: "\u227E", prurel: "\u22B0", Pscr: "\u{1D4AB}", pscr: "\u{1D4C5}", Psi: "\u03A8", psi: "\u03C8", puncsp: "\u2008", Qfr: "\u{1D514}", qfr: "\u{1D52E}", qint: "\u2A0C", Qopf: "\u211A", qopf: "\u{1D562}", qprime: "\u2057", Qscr: "\u{1D4AC}", qscr: "\u{1D4C6}", quaternions: "\u210D", quatint: "\u2A16", quest: "?", questeq: "\u225F", QUOT: '"', quot: '"', rAarr: "\u21DB", race: "\u223D\u0331", Racute: "\u0154", racute: "\u0155", radic: "\u221A", raemptyv: "\u29B3", Rang: "\u27EB", rang: "\u27E9", rangd: "\u2992", range: "\u29A5", rangle: "\u27E9", raquo: "\xBB", Rarr: "\u21A0", rArr: "\u21D2", rarr: "\u2192", rarrap: "\u2975", rarrb: "\u21E5", rarrbfs: "\u2920", rarrc: "\u2933", rarrfs: "\u291E", rarrhk: "\u21AA", rarrlp: "\u21AC", rarrpl: "\u2945", rarrsim: "\u2974", Rarrtl: "\u2916", rarrtl: "\u21A3", rarrw: "\u219D", rAtail: "\u291C", ratail: "\u291A", ratio: "\u2236", rationals: "\u211A", RBarr: "\u2910", rBarr: "\u290F", rbarr: "\u290D", rbbrk: "\u2773", rbrace: "}", rbrack: "]", rbrke: "\u298C", rbrksld: "\u298E", rbrkslu: "\u2990", Rcaron: "\u0158", rcaron: "\u0159", Rcedil: "\u0156", rcedil: "\u0157", rceil: "\u2309", rcub: "}", Rcy: "\u0420", rcy: "\u0440", rdca: "\u2937", rdldhar: "\u2969", rdquo: "\u201D", rdquor: "\u201D", rdsh: "\u21B3", Re: "\u211C", real: "\u211C", realine: "\u211B", realpart: "\u211C", reals: "\u211D", rect: "\u25AD", REG: "\xAE", reg: "\xAE", ReverseElement: "\u220B", ReverseEquilibrium: "\u21CB", ReverseUpEquilibrium: "\u296F", rfisht: "\u297D", rfloor: "\u230B", Rfr: "\u211C", rfr: "\u{1D52F}", rHar: "\u2964", rhard: "\u21C1", rharu: "\u21C0", rharul: "\u296C", Rho: "\u03A1", rho: "\u03C1", rhov: "\u03F1", RightAngleBracket: "\u27E9", RightArrow: "\u2192", Rightarrow: "\u21D2", rightarrow: "\u2192", RightArrowBar: "\u21E5", RightArrowLeftArrow: "\u21C4", rightarrowtail: "\u21A3", RightCeiling: "\u2309", RightDoubleBracket: "\u27E7", RightDownTeeVector: "\u295D", RightDownVector: "\u21C2", RightDownVectorBar: "\u2955", RightFloor: "\u230B", rightharpoondown: "\u21C1", rightharpoonup: "\u21C0", rightleftarrows: "\u21C4", rightleftharpoons: "\u21CC", rightrightarrows: "\u21C9", rightsquigarrow: "\u219D", RightTee: "\u22A2", RightTeeArrow: "\u21A6", RightTeeVector: "\u295B", rightthreetimes: "\u22CC", RightTriangle: "\u22B3", RightTriangleBar: "\u29D0", RightTriangleEqual: "\u22B5", RightUpDownVector: "\u294F", RightUpTeeVector: "\u295C", RightUpVector: "\u21BE", RightUpVectorBar: "\u2954", RightVector: "\u21C0", RightVectorBar: "\u2953", ring: "\u02DA", risingdotseq: "\u2253", rlarr: "\u21C4", rlhar: "\u21CC", rlm: "\u200F", rmoust: "\u23B1", rmoustache: "\u23B1", rnmid: "\u2AEE", roang: "\u27ED", roarr: "\u21FE", robrk: "\u27E7", ropar: "\u2986", Ropf: "\u211D", ropf: "\u{1D563}", roplus: "\u2A2E", rotimes: "\u2A35", RoundImplies: "\u2970", rpar: ")", rpargt: "\u2994", rppolint: "\u2A12", rrarr: "\u21C9", Rrightarrow: "\u21DB", rsaquo: "\u203A", Rscr: "\u211B", rscr: "\u{1D4C7}", Rsh: "\u21B1", rsh: "\u21B1", rsqb: "]", rsquo: "\u2019", rsquor: "\u2019", rthree: "\u22CC", rtimes: "\u22CA", rtri: "\u25B9", rtrie: "\u22B5", rtrif: "\u25B8", rtriltri: "\u29CE", RuleDelayed: "\u29F4", ruluhar: "\u2968", rx: "\u211E", Sacute: "\u015A", sacute: "\u015B", sbquo: "\u201A", Sc: "\u2ABC", sc: "\u227B", scap: "\u2AB8", Scaron: "\u0160", scaron: "\u0161", sccue: "\u227D", scE: "\u2AB4", sce: "\u2AB0", Scedil: "\u015E", scedil: "\u015F", Scirc: "\u015C", scirc: "\u015D", scnap: "\u2ABA", scnE: "\u2AB6", scnsim: "\u22E9", scpolint: "\u2A13", scsim: "\u227F", Scy: "\u0421", scy: "\u0441", sdot: "\u22C5", sdotb: "\u22A1", sdote: "\u2A66", searhk: "\u2925", seArr: "\u21D8", searr: "\u2198", searrow: "\u2198", sect: "\xA7", semi: ";", seswar: "\u2929", setminus: "\u2216", setmn: "\u2216", sext: "\u2736", Sfr: "\u{1D516}", sfr: "\u{1D530}", sfrown: "\u2322", sharp: "\u266F", SHCHcy: "\u0429", shchcy: "\u0449", SHcy: "\u0428", shcy: "\u0448", ShortDownArrow: "\u2193", ShortLeftArrow: "\u2190", shortmid: "\u2223", shortparallel: "\u2225", ShortRightArrow: "\u2192", ShortUpArrow: "\u2191", shy: "\xAD", Sigma: "\u03A3", sigma: "\u03C3", sigmaf: "\u03C2", sigmav: "\u03C2", sim: "\u223C", simdot: "\u2A6A", sime: "\u2243", simeq: "\u2243", simg: "\u2A9E", simgE: "\u2AA0", siml: "\u2A9D", simlE: "\u2A9F", simne: "\u2246", simplus: "\u2A24", simrarr: "\u2972", slarr: "\u2190", SmallCircle: "\u2218", smallsetminus: "\u2216", smashp: "\u2A33", smeparsl: "\u29E4", smid: "\u2223", smile: "\u2323", smt: "\u2AAA", smte: "\u2AAC", smtes: "\u2AAC\uFE00", SOFTcy: "\u042C", softcy: "\u044C", sol: "/", solb: "\u29C4", solbar: "\u233F", Sopf: "\u{1D54A}", sopf: "\u{1D564}", spades: "\u2660", spadesuit: "\u2660", spar: "\u2225", sqcap: "\u2293", sqcaps: "\u2293\uFE00", sqcup: "\u2294", sqcups: "\u2294\uFE00", Sqrt: "\u221A", sqsub: "\u228F", sqsube: "\u2291", sqsubset: "\u228F", sqsubseteq: "\u2291", sqsup: "\u2290", sqsupe: "\u2292", sqsupset: "\u2290", sqsupseteq: "\u2292", squ: "\u25A1", Square: "\u25A1", square: "\u25A1", SquareIntersection: "\u2293", SquareSubset: "\u228F", SquareSubsetEqual: "\u2291", SquareSuperset: "\u2290", SquareSupersetEqual: "\u2292", SquareUnion: "\u2294", squarf: "\u25AA", squf: "\u25AA", srarr: "\u2192", Sscr: "\u{1D4AE}", sscr: "\u{1D4C8}", ssetmn: "\u2216", ssmile: "\u2323", sstarf: "\u22C6", Star: "\u22C6", star: "\u2606", starf: "\u2605", straightepsilon: "\u03F5", straightphi: "\u03D5", strns: "\xAF", Sub: "\u22D0", sub: "\u2282", subdot: "\u2ABD", subE: "\u2AC5", sube: "\u2286", subedot: "\u2AC3", submult: "\u2AC1", subnE: "\u2ACB", subne: "\u228A", subplus: "\u2ABF", subrarr: "\u2979", Subset: "\u22D0", subset: "\u2282", subseteq: "\u2286", subseteqq: "\u2AC5", SubsetEqual: "\u2286", subsetneq: "\u228A", subsetneqq: "\u2ACB", subsim: "\u2AC7", subsub: "\u2AD5", subsup: "\u2AD3", succ: "\u227B", succapprox: "\u2AB8", succcurlyeq: "\u227D", Succeeds: "\u227B", SucceedsEqual: "\u2AB0", SucceedsSlantEqual: "\u227D", SucceedsTilde: "\u227F", succeq: "\u2AB0", succnapprox: "\u2ABA", succneqq: "\u2AB6", succnsim: "\u22E9", succsim: "\u227F", SuchThat: "\u220B", Sum: "\u2211", sum: "\u2211", sung: "\u266A", Sup: "\u22D1", sup: "\u2283", sup1: "\xB9", sup2: "\xB2", sup3: "\xB3", supdot: "\u2ABE", supdsub: "\u2AD8", supE: "\u2AC6", supe: "\u2287", supedot: "\u2AC4", Superset: "\u2283", SupersetEqual: "\u2287", suphsol: "\u27C9", suphsub: "\u2AD7", suplarr: "\u297B", supmult: "\u2AC2", supnE: "\u2ACC", supne: "\u228B", supplus: "\u2AC0", Supset: "\u22D1", supset: "\u2283", supseteq: "\u2287", supseteqq: "\u2AC6", supsetneq: "\u228B", supsetneqq: "\u2ACC", supsim: "\u2AC8", supsub: "\u2AD4", supsup: "\u2AD6", swarhk: "\u2926", swArr: "\u21D9", swarr: "\u2199", swarrow: "\u2199", swnwar: "\u292A", szlig: "\xDF", Tab: " ", target: "\u2316", Tau: "\u03A4", tau: "\u03C4", tbrk: "\u23B4", Tcaron: "\u0164", tcaron: "\u0165", Tcedil: "\u0162", tcedil: "\u0163", Tcy: "\u0422", tcy: "\u0442", tdot: "\u20DB", telrec: "\u2315", Tfr: "\u{1D517}", tfr: "\u{1D531}", there4: "\u2234", Therefore: "\u2234", therefore: "\u2234", Theta: "\u0398", theta: "\u03B8", thetasym: "\u03D1", thetav: "\u03D1", thickapprox: "\u2248", thicksim: "\u223C", ThickSpace: "\u205F\u200A", thinsp: "\u2009", ThinSpace: "\u2009", thkap: "\u2248", thksim: "\u223C", THORN: "\xDE", thorn: "\xFE", Tilde: "\u223C", tilde: "\u02DC", TildeEqual: "\u2243", TildeFullEqual: "\u2245", TildeTilde: "\u2248", times: "\xD7", timesb: "\u22A0", timesbar: "\u2A31", timesd: "\u2A30", tint: "\u222D", toea: "\u2928", top: "\u22A4", topbot: "\u2336", topcir: "\u2AF1", Topf: "\u{1D54B}", topf: "\u{1D565}", topfork: "\u2ADA", tosa: "\u2929", tprime: "\u2034", TRADE: "\u2122", trade: "\u2122", triangle: "\u25B5", triangledown: "\u25BF", triangleleft: "\u25C3", trianglelefteq: "\u22B4", triangleq: "\u225C", triangleright: "\u25B9", trianglerighteq: "\u22B5", tridot: "\u25EC", trie: "\u225C", triminus: "\u2A3A", TripleDot: "\u20DB", triplus: "\u2A39", trisb: "\u29CD", tritime: "\u2A3B", trpezium: "\u23E2", Tscr: "\u{1D4AF}", tscr: "\u{1D4C9}", TScy: "\u0426", tscy: "\u0446", TSHcy: "\u040B", tshcy: "\u045B", Tstrok: "\u0166", tstrok: "\u0167", twixt: "\u226C", twoheadleftarrow: "\u219E", twoheadrightarrow: "\u21A0", Uacute: "\xDA", uacute: "\xFA", Uarr: "\u219F", uArr: "\u21D1", uarr: "\u2191", Uarrocir: "\u2949", Ubrcy: "\u040E", ubrcy: "\u045E", Ubreve: "\u016C", ubreve: "\u016D", Ucirc: "\xDB", ucirc: "\xFB", Ucy: "\u0423", ucy: "\u0443", udarr: "\u21C5", Udblac: "\u0170", udblac: "\u0171", udhar: "\u296E", ufisht: "\u297E", Ufr: "\u{1D518}", ufr: "\u{1D532}", Ugrave: "\xD9", ugrave: "\xF9", uHar: "\u2963", uharl: "\u21BF", uharr: "\u21BE", uhblk: "\u2580", ulcorn: "\u231C", ulcorner: "\u231C", ulcrop: "\u230F", ultri: "\u25F8", Umacr: "\u016A", umacr: "\u016B", uml: "\xA8", UnderBar: "_", UnderBrace: "\u23DF", UnderBracket: "\u23B5", UnderParenthesis: "\u23DD", Union: "\u22C3", UnionPlus: "\u228E", Uogon: "\u0172", uogon: "\u0173", Uopf: "\u{1D54C}", uopf: "\u{1D566}", UpArrow: "\u2191", Uparrow: "\u21D1", uparrow: "\u2191", UpArrowBar: "\u2912", UpArrowDownArrow: "\u21C5", UpDownArrow: "\u2195", Updownarrow: "\u21D5", updownarrow: "\u2195", UpEquilibrium: "\u296E", upharpoonleft: "\u21BF", upharpoonright: "\u21BE", uplus: "\u228E", UpperLeftArrow: "\u2196", UpperRightArrow: "\u2197", Upsi: "\u03D2", upsi: "\u03C5", upsih: "\u03D2", Upsilon: "\u03A5", upsilon: "\u03C5", UpTee: "\u22A5", UpTeeArrow: "\u21A5", upuparrows: "\u21C8", urcorn: "\u231D", urcorner: "\u231D", urcrop: "\u230E", Uring: "\u016E", uring: "\u016F", urtri: "\u25F9", Uscr: "\u{1D4B0}", uscr: "\u{1D4CA}", utdot: "\u22F0", Utilde: "\u0168", utilde: "\u0169", utri: "\u25B5", utrif: "\u25B4", uuarr: "\u21C8", Uuml: "\xDC", uuml: "\xFC", uwangle: "\u29A7", vangrt: "\u299C", varepsilon: "\u03F5", varkappa: "\u03F0", varnothing: "\u2205", varphi: "\u03D5", varpi: "\u03D6", varpropto: "\u221D", vArr: "\u21D5", varr: "\u2195", varrho: "\u03F1", varsigma: "\u03C2", varsubsetneq: "\u228A\uFE00", varsubsetneqq: "\u2ACB\uFE00", varsupsetneq: "\u228B\uFE00", varsupsetneqq: "\u2ACC\uFE00", vartheta: "\u03D1", vartriangleleft: "\u22B2", vartriangleright: "\u22B3", Vbar: "\u2AEB", vBar: "\u2AE8", vBarv: "\u2AE9", Vcy: "\u0412", vcy: "\u0432", VDash: "\u22AB", Vdash: "\u22A9", vDash: "\u22A8", vdash: "\u22A2", Vdashl: "\u2AE6", Vee: "\u22C1", vee: "\u2228", veebar: "\u22BB", veeeq: "\u225A", vellip: "\u22EE", Verbar: "\u2016", verbar: "|", Vert: "\u2016", vert: "|", VerticalBar: "\u2223", VerticalLine: "|", VerticalSeparator: "\u2758", VerticalTilde: "\u2240", VeryThinSpace: "\u200A", Vfr: "\u{1D519}", vfr: "\u{1D533}", vltri: "\u22B2", vnsub: "\u2282\u20D2", vnsup: "\u2283\u20D2", Vopf: "\u{1D54D}", vopf: "\u{1D567}", vprop: "\u221D", vrtri: "\u22B3", Vscr: "\u{1D4B1}", vscr: "\u{1D4CB}", vsubnE: "\u2ACB\uFE00", vsubne: "\u228A\uFE00", vsupnE: "\u2ACC\uFE00", vsupne: "\u228B\uFE00", Vvdash: "\u22AA", vzigzag: "\u299A", Wcirc: "\u0174", wcirc: "\u0175", wedbar: "\u2A5F", Wedge: "\u22C0", wedge: "\u2227", wedgeq: "\u2259", weierp: "\u2118", Wfr: "\u{1D51A}", wfr: "\u{1D534}", Wopf: "\u{1D54E}", wopf: "\u{1D568}", wp: "\u2118", wr: "\u2240", wreath: "\u2240", Wscr: "\u{1D4B2}", wscr: "\u{1D4CC}", xcap: "\u22C2", xcirc: "\u25EF", xcup: "\u22C3", xdtri: "\u25BD", Xfr: "\u{1D51B}", xfr: "\u{1D535}", xhArr: "\u27FA", xharr: "\u27F7", Xi: "\u039E", xi: "\u03BE", xlArr: "\u27F8", xlarr: "\u27F5", xmap: "\u27FC", xnis: "\u22FB", xodot: "\u2A00", Xopf: "\u{1D54F}", xopf: "\u{1D569}", xoplus: "\u2A01", xotime: "\u2A02", xrArr: "\u27F9", xrarr: "\u27F6", Xscr: "\u{1D4B3}", xscr: "\u{1D4CD}", xsqcup: "\u2A06", xuplus: "\u2A04", xutri: "\u25B3", xvee: "\u22C1", xwedge: "\u22C0", Yacute: "\xDD", yacute: "\xFD", YAcy: "\u042F", yacy: "\u044F", Ycirc: "\u0176", ycirc: "\u0177", Ycy: "\u042B", ycy: "\u044B", yen: "\xA5", Yfr: "\u{1D51C}", yfr: "\u{1D536}", YIcy: "\u0407", yicy: "\u0457", Yopf: "\u{1D550}", yopf: "\u{1D56A}", Yscr: "\u{1D4B4}", yscr: "\u{1D4CE}", YUcy: "\u042E", yucy: "\u044E", Yuml: "\u0178", yuml: "\xFF", Zacute: "\u0179", zacute: "\u017A", Zcaron: "\u017D", zcaron: "\u017E", Zcy: "\u0417", zcy: "\u0437", Zdot: "\u017B", zdot: "\u017C", zeetrf: "\u2128", ZeroWidthSpace: "\u200B", Zeta: "\u0396", zeta: "\u03B6", Zfr: "\u2128", zfr: "\u{1D537}", ZHcy: "\u0416", zhcy: "\u0436", zigrarr: "\u21DD", Zopf: "\u2124", zopf: "\u{1D56B}", Zscr: "\u{1D4B5}", zscr: "\u{1D4CF}", zwj: "\u200D", zwnj: "\u200C" }); exports.entityMap = exports.HTML_ENTITIES; } }); // node_modules/@xmldom/xmldom/lib/sax.js var require_sax = __commonJS({ "node_modules/@xmldom/xmldom/lib/sax.js"(exports) { "use strict"; init_define_L2W_CONFIG(); var conventions = require_conventions(); var g = require_grammar(); var errors = require_errors(); var isHTMLEscapableRawTextElement = conventions.isHTMLEscapableRawTextElement; var isHTMLMimeType = conventions.isHTMLMimeType; var isHTMLRawTextElement = conventions.isHTMLRawTextElement; var hasOwn = conventions.hasOwn; var NAMESPACE = conventions.NAMESPACE; var ParseError = errors.ParseError; var DOMException = errors.DOMException; var S_TAG = 0; var S_ATTR = 1; var S_ATTR_SPACE = 2; var S_EQ = 3; var S_ATTR_NOQUOT_VALUE = 4; var S_ATTR_END = 5; var S_TAG_SPACE = 6; var S_TAG_CLOSE = 7; function XMLReader() { } XMLReader.prototype = { parse: function(source, defaultNSMap, entityMap) { var domBuilder = this.domBuilder; domBuilder.startDocument(); _copy(defaultNSMap, defaultNSMap = /* @__PURE__ */ Object.create(null)); parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler); domBuilder.endDocument(); } }; var ENTITY_REG = /&#?\w+;?/g; function parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) { var isHTML = isHTMLMimeType(domBuilder.mimeType); if (source.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) { errorHandler.warning("Unicode replacement character detected, source encoding issues?"); } function fixedFromCharCode(code) { if (code > 65535) { code -= 65536; var surrogate1 = 55296 + (code >> 10), surrogate2 = 56320 + (code & 1023); return String.fromCharCode(surrogate1, surrogate2); } else { return String.fromCharCode(code); } } function entityReplacer(a2) { var complete = a2[a2.length - 1] === ";" ? a2 : a2 + ";"; if (!isHTML && complete !== a2) { errorHandler.error("EntityRef: expecting ;"); return a2; } var match = g.Reference.exec(complete); if (!match || match[0].length !== complete.length) { errorHandler.error("entity not matching Reference production: " + a2); return a2; } var k = complete.slice(1, -1); if (hasOwn(entityMap, k)) { return entityMap[k]; } else if (k.charAt(0) === "#") { return fixedFromCharCode(parseInt(k.substring(1).replace("x", "0x"))); } else { errorHandler.error("entity not found:" + a2); return a2; } } function appendText(end2) { if (end2 > start) { var xt = source.substring(start, end2).replace(ENTITY_REG, entityReplacer); locator && position(start); domBuilder.characters(xt, 0, end2 - start); start = end2; } } var lineStart = 0; var lineEnd = 0; var linePattern = /\r\n?|\n|$/g; var locator = domBuilder.locator; function position(p, m) { while (p >= lineEnd && (m = linePattern.exec(source))) { lineStart = lineEnd; lineEnd = m.index + m[0].length; locator.lineNumber++; } locator.columnNumber = p - lineStart + 1; } var parseStack = [{ currentNSMap: defaultNSMapCopy }]; var unclosedTags = []; var start = 0; while (true) { try { var tagStart = source.indexOf("<", start); if (tagStart < 0) { if (!isHTML && unclosedTags.length > 0) { return errorHandler.fatalError("unclosed xml tag(s): " + unclosedTags.join(", ")); } if (!source.substring(start).match(/^\s*$/)) { var doc = domBuilder.doc; var text = doc.createTextNode(source.substring(start)); if (doc.documentElement) { return errorHandler.error("Extra content at the end of the document"); } doc.appendChild(text); domBuilder.currentElement = text; } return; } if (tagStart > start) { var fromSource = source.substring(start, tagStart); if (!isHTML && unclosedTags.length === 0) { fromSource = fromSource.replace(new RegExp(g.S_OPT.source, "g"), ""); fromSource && errorHandler.error("Unexpected content outside root element: '" + fromSource + "'"); } appendText(tagStart); } switch (source.charAt(tagStart + 1)) { case "/": var end = source.indexOf(">", tagStart + 2); var tagNameRaw = source.substring(tagStart + 2, end > 0 ? end : void 0); if (!tagNameRaw) { return errorHandler.fatalError("end tag name missing"); } var endTagNameStrict = g.reg("^", g.QName_group, g.S_OPT, "$"); var tagNameMatch = end > 0 && endTagNameStrict.exec(tagNameRaw); if (!tagNameMatch) { var leadingTagNameMatch = end > 0 && g.reg("^", g.QName_group).exec(tagNameRaw); if (isHTML && leadingTagNameMatch) { errorHandler.warning('end tag name contains invalid trailing characters: "' + tagNameRaw + '"'); tagNameMatch = leadingTagNameMatch; } else if ( // Backward compatibility, remove this whole `else if` arm in the next breaking release // (XML then falls through to the `fatalError` below, for a clean mode split: XML fatal, // HTML warning). A valid end-tag name followed by a line break and trailing content was // silently accepted while `reg` still used the `m` flag; re-adding `m` here matches exactly // those inputs, kept recoverable and reported. leadingTagNameMatch && new RegExp(endTagNameStrict.source, endTagNameStrict.flags + "m").test(tagNameRaw) ) { errorHandler.error('end tag name is followed by a line break and trailing content: "' + tagNameRaw + '"'); tagNameMatch = leadingTagNameMatch; } else { return errorHandler.fatalError('end tag name contains invalid characters: "' + tagNameRaw + '"'); } } if (!domBuilder.currentElement && !domBuilder.doc.documentElement) { return; } var currentTagName = unclosedTags[unclosedTags.length - 1] || domBuilder.currentElement.tagName || domBuilder.doc.documentElement.tagName || ""; if (currentTagName !== tagNameMatch[1]) { var tagNameLower = tagNameMatch[1].toLowerCase(); if (!isHTML || currentTagName.toLowerCase() !== tagNameLower) { return errorHandler.fatalError('Opening and ending tag mismatch: "' + currentTagName + '" != "' + tagNameRaw + '"'); } } var config = parseStack.pop(); unclosedTags.pop(); var localNSMap = config.localNSMap; domBuilder.endElement(config.uri, config.localName, currentTagName); if (localNSMap) { for (var prefix in localNSMap) { if (hasOwn(localNSMap, prefix)) { domBuilder.endPrefixMapping(prefix); } } } end++; break; // end element case "?": locator && position(tagStart); end = parseProcessingInstruction(source, tagStart, domBuilder, errorHandler); break; case "!": locator && position(tagStart); end = parseDoctypeCommentOrCData(source, tagStart, domBuilder, errorHandler, isHTML); break; default: locator && position(tagStart); var el = new ElementAttributes(); var currentNSMap = parseStack[parseStack.length - 1].currentNSMap; var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler, isHTML); var len = el.length; if (!el.closed) { if (isHTML && conventions.isHTMLVoidElement(el.tagName)) { el.closed = true; } else { unclosedTags.push(el.tagName); } } if (locator && len) { var locator2 = copyLocator(locator, {}); for (var i = 0; i < len; i++) { var a = el[i]; position(a.offset); a.locator = copyLocator(locator, {}); } domBuilder.locator = locator2; if (appendElement(el, domBuilder, currentNSMap)) { parseStack.push(el); } domBuilder.locator = locator; } else { if (appendElement(el, domBuilder, currentNSMap)) { parseStack.push(el); } } if (isHTML && !el.closed) { end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder); } else { end++; } } } catch (e) { if (e instanceof ParseError) { throw e; } else if (e instanceof DOMException) { return errorHandler.fatalError("Error constructing the DOM: " + e.name + ": " + e.message, e); } errorHandler.error("element parse error: " + e); end = -1; } if (end > start) { start = end; } else { appendText(Math.max(tagStart, start) + 1); } } } function copyLocator(f, t) { t.lineNumber = f.lineNumber; t.columnNumber = f.columnNumber; return t; } function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler, isHTML) { function addAttribute(qname, value2, startIndex) { if (hasOwn(el.attributeNames, qname)) { return errorHandler.fatalError("Attribute " + qname + " redefined"); } if (!isHTML && value2.indexOf("<") >= 0) { return errorHandler.fatalError("Unescaped '<' not allowed in attributes values"); } el.addValue( qname, // @see https://www.w3.org/TR/xml/#AVNormalize // since the xmldom sax parser does not "interpret" DTD the following is not implemented: // - recursive replacement of (DTD) entity references // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA value2.replace(/[\t\n\r]/g, " ").replace(ENTITY_REG, entityReplacer), startIndex ); } var attrName; var value; var p = ++start; var s = S_TAG; while (true) { var c = source.charAt(p); if (s === S_TAG && c === "<") { throw new Error("unexpected < in tag name: " + source.slice(start, p)); } switch (c) { case "=": if (s === S_ATTR) { attrName = source.slice(start, p); s = S_EQ; } else if (s === S_ATTR_SPACE) { s = S_EQ; } else { throw new Error("attribute equal must after attrName"); } break; case "'": case '"': if (s === S_EQ || s === S_ATTR) { if (s === S_ATTR) { errorHandler.warning('attribute value must after "="'); attrName = source.slice(start, p); } start = p + 1; p = source.indexOf(c, start); if (p > 0) { value = source.slice(start, p); addAttribute(attrName, value, start - 1); s = S_ATTR_END; } else { throw new Error("attribute value no end '" + c + "' match"); } } else if (s == S_ATTR_NOQUOT_VALUE) { value = source.slice(start, p); addAttribute(attrName, value, start); errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ")!!"); start = p + 1; s = S_ATTR_END; } else { throw new Error('attribute value must after "="'); } break; case "/": switch (s) { case S_TAG: el.setTagName(source.slice(start, p)); case S_ATTR_END: case S_TAG_SPACE: case S_TAG_CLOSE: s = S_TAG_CLOSE; el.closed = true; case S_ATTR_NOQUOT_VALUE: case S_ATTR: break; case S_ATTR_SPACE: el.closed = true; break; //case S_EQ: default: throw new Error("attribute invalid close char('/')"); } break; case "": errorHandler.error("unexpected end of input"); if (s == S_TAG) { el.setTagName(source.slice(start, p)); } return p; case ">": switch (s) { case S_TAG: el.setTagName(source.slice(start, p)); case S_ATTR_END: case S_TAG_SPACE: case S_TAG_CLOSE: break; //normal case S_ATTR_NOQUOT_VALUE: //Compatible state case S_ATTR: value = source.slice(start, p); if (value.slice(-1) === "/") { el.closed = true; value = value.slice(0, -1); } case S_ATTR_SPACE: if (s === S_ATTR_SPACE) { value = attrName; } if (s == S_ATTR_NOQUOT_VALUE) { errorHandler.warning('attribute "' + value + '" missed quot(")!'); addAttribute(attrName, value, start); } else { if (!isHTML) { errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!'); } addAttribute(value, value, start); } break; case S_EQ: if (!isHTML) { return errorHandler.fatalError(`AttValue: ' or " expected`); } } return p; /*xml space '\x20' | #x9 | #xD | #xA; */ case "\x80": c = " "; default: if (c <= " ") { switch (s) { case S_TAG: el.setTagName(source.slice(start, p)); s = S_TAG_SPACE; break; case S_ATTR: attrName = source.slice(start, p); s = S_ATTR_SPACE; break; case S_ATTR_NOQUOT_VALUE: var value = source.slice(start, p); errorHandler.warning('attribute "' + value + '" missed quot(")!!'); addAttribute(attrName, value, start); case S_ATTR_END: s = S_TAG_SPACE; break; } } else { switch (s) { //case S_TAG:void();break; //case S_ATTR:void();break; //case S_ATTR_NOQUOT_VALUE:void();break; case S_ATTR_SPACE: if (!isHTML) { errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!'); } addAttribute(attrName, attrName, start); start = p; s = S_ATTR; break; case S_ATTR_END: errorHandler.warning('attribute space is required"' + attrName + '"!!'); case S_TAG_SPACE: s = S_ATTR; start = p; break; case S_EQ: s = S_ATTR_NOQUOT_VALUE; start = p; break; case S_TAG_CLOSE: throw new Error("elements closed character '/' and '>' must be connected to"); } } } p++; } } function appendElement(el, domBuilder, currentNSMap) { var tagName = el.tagName; var localNSMap = null; var i = el.length; while (i--) { var a = el[i]; var qName = a.qName; var value = a.value; var nsp = qName.indexOf(":"); if (nsp > 0) { var prefix = a.prefix = qName.slice(0, nsp); var localName = qName.slice(nsp + 1); var nsPrefix = prefix === "xmlns" && localName; } else { localName = qName; prefix = null; nsPrefix = qName === "xmlns" && ""; } a.localName = localName; if (nsPrefix !== false) { if (localNSMap == null) { localNSMap = /* @__PURE__ */ Object.create(null); currentNSMap = Object.create(currentNSMap); } currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; a.uri = NAMESPACE.XMLNS; domBuilder.startPrefixMapping(nsPrefix, value); } } var i = el.length; while (i--) { a = el[i]; if (a.prefix) { if (a.prefix === "xml") { a.uri = NAMESPACE.XML; } if (a.prefix !== "xmlns") { a.uri = currentNSMap[a.prefix]; } } } var nsp = tagName.indexOf(":"); if (nsp > 0) { prefix = el.prefix = tagName.slice(0, nsp); localName = el.localName = tagName.slice(nsp + 1); } else { prefix = null; localName = el.localName = tagName; } var ns = el.uri = currentNSMap[prefix || ""]; domBuilder.startElement(ns, localName, tagName, el); if (el.closed) { domBuilder.endElement(ns, localName, tagName); if (localNSMap) { for (prefix in localNSMap) { if (hasOwn(localNSMap, prefix)) { domBuilder.endPrefixMapping(prefix); } } } } else { el.currentNSMap = currentNSMap; el.localNSMap = localNSMap; return true; } } function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) { var isEscapableRaw = isHTMLEscapableRawTextElement(tagName); if (isEscapableRaw || isHTMLRawTextElement(tagName)) { var closeTag = new RegExp("", "ig"); closeTag.lastIndex = elStartEnd; var match = closeTag.exec(source); var elEndStart = match ? match.index : -1; if (elEndStart < 0) { return elStartEnd + 1; } var text = source.substring(elStartEnd + 1, elEndStart); if (isEscapableRaw) { text = text.replace(ENTITY_REG, entityReplacer); } domBuilder.characters(text, 0, text.length); return elEndStart; } return elStartEnd + 1; } function _copy(source, target) { for (var n in source) { if (hasOwn(source, n)) { target[n] = source[n]; } } } function parseUtils(source, start) { var index = start; function char(n) { n = n || 0; return source.charAt(index + n); } function skip(n) { n = n || 1; index += n; } function skipBlanks() { var blanks = 0; while (index < source.length) { var c = char(); if (c !== " " && c !== "\n" && c !== " " && c !== "\r") { return blanks; } blanks++; skip(); } return -1; } function substringFromIndex() { return source.substring(index); } function substringStartsWith(text) { return source.substring(index, index + text.length) === text; } function substringStartsWithCaseInsensitive(text) { return source.substring(index, index + text.length).toUpperCase() === text.toUpperCase(); } function getMatch(args2) { var expr = g.reg("^", args2); var match = expr.exec(substringFromIndex()); if (match) { skip(match[0].length); return match[0]; } return null; } return { char, getIndex: function() { return index; }, getMatch, getSource: function() { return source; }, skip, skipBlanks, substringFromIndex, substringStartsWith, substringStartsWithCaseInsensitive }; } function parseDoctypeInternalSubset(p, errorHandler) { function parsePI(p2, errorHandler2) { var match = g.PI.exec(p2.substringFromIndex()); if (!match) { return errorHandler2.fatalError("processing instruction is not well-formed at position " + p2.getIndex()); } if (match[1].toLowerCase() === "xml") { return errorHandler2.fatalError( "xml declaration is only allowed at the start of the document, but found at position " + p2.getIndex() ); } p2.skip(match[0].length); return match[0]; } var source = p.getSource(); if (p.char() === "[") { p.skip(1); var intSubsetStart = p.getIndex(); while (p.getIndex() < source.length) { p.skipBlanks(); if (p.char() === "]") { var internalSubset = source.substring(intSubsetStart, p.getIndex()); p.skip(1); return internalSubset; } var current = null; if (p.char() === "<" && p.char(1) === "!") { switch (p.char(2)) { case "E": if (p.char(3) === "L") { current = p.getMatch(g.elementdecl); } else if (p.char(3) === "N") { current = p.getMatch(g.EntityDecl); } break; case "A": current = p.getMatch(g.AttlistDecl); break; case "N": current = p.getMatch(g.NotationDecl); break; case "-": current = p.getMatch(g.Comment); break; } } else if (p.char() === "<" && p.char(1) === "?") { current = parsePI(p, errorHandler); } else if (p.char() === "%") { current = p.getMatch(g.PEReference); } else { return errorHandler.fatalError("Error detected in Markup declaration"); } if (!current) { return errorHandler.fatalError("Error in internal subset at position " + p.getIndex()); } } return errorHandler.fatalError("doctype internal subset is not well-formed, missing ]"); } } function parseDoctypeCommentOrCData(source, start, domBuilder, errorHandler, isHTML) { var p = parseUtils(source, start); switch (isHTML ? p.char(2).toUpperCase() : p.char(2)) { case "-": var comment = p.getMatch(g.Comment); if (comment) { domBuilder.comment(comment, g.COMMENT_START.length, comment.length - g.COMMENT_START.length - g.COMMENT_END.length); return p.getIndex(); } else { return errorHandler.fatalError("comment is not well-formed at position " + p.getIndex()); } case "[": var cdata = p.getMatch(g.CDSect); if (cdata) { if (!isHTML && !domBuilder.currentElement) { return errorHandler.fatalError("CDATA outside of element"); } domBuilder.startCDATA(); domBuilder.characters(cdata, g.CDATA_START.length, cdata.length - g.CDATA_START.length - g.CDATA_END.length); domBuilder.endCDATA(); return p.getIndex(); } else { return errorHandler.fatalError("Invalid CDATA starting at position " + start); } case "D": { if (domBuilder.doc && domBuilder.doc.documentElement) { return errorHandler.fatalError("Doctype not allowed inside or after documentElement at position " + p.getIndex()); } if (isHTML ? !p.substringStartsWithCaseInsensitive(g.DOCTYPE_DECL_START) : !p.substringStartsWith(g.DOCTYPE_DECL_START)) { return errorHandler.fatalError("Expected " + g.DOCTYPE_DECL_START + " at position " + p.getIndex()); } p.skip(g.DOCTYPE_DECL_START.length); if (p.skipBlanks() < 1) { return errorHandler.fatalError("Expected whitespace after " + g.DOCTYPE_DECL_START + " at position " + p.getIndex()); } var doctype = { name: void 0, publicId: void 0, systemId: void 0, internalSubset: void 0 }; doctype.name = p.getMatch(g.Name); if (!doctype.name) return errorHandler.fatalError("doctype name missing or contains unexpected characters at position " + p.getIndex()); if (isHTML && doctype.name.toLowerCase() !== "html") { errorHandler.warning("Unexpected DOCTYPE in HTML document at position " + p.getIndex()); } p.skipBlanks(); if (p.substringStartsWith(g.PUBLIC) || p.substringStartsWith(g.SYSTEM)) { var match = g.ExternalID_match.exec(p.substringFromIndex()); if (!match) { return errorHandler.fatalError("doctype external id is not well-formed at position " + p.getIndex()); } if (match.groups.SystemLiteralOnly !== void 0) { doctype.systemId = match.groups.SystemLiteralOnly; } else { doctype.systemId = match.groups.SystemLiteral; doctype.publicId = match.groups.PubidLiteral; } p.skip(match[0].length); } else if (isHTML && p.substringStartsWithCaseInsensitive(g.SYSTEM)) { p.skip(g.SYSTEM.length); if (p.skipBlanks() < 1) { return errorHandler.fatalError("Expected whitespace after " + g.SYSTEM + " at position " + p.getIndex()); } doctype.systemId = p.getMatch(g.ABOUT_LEGACY_COMPAT_SystemLiteral); if (!doctype.systemId) { return errorHandler.fatalError( "Expected " + g.ABOUT_LEGACY_COMPAT + " in single or double quotes after " + g.SYSTEM + " at position " + p.getIndex() ); } } if (isHTML && doctype.systemId && !g.ABOUT_LEGACY_COMPAT_SystemLiteral.test(doctype.systemId)) { errorHandler.warning("Unexpected doctype.systemId in HTML document at position " + p.getIndex()); } if (!isHTML) { p.skipBlanks(); doctype.internalSubset = parseDoctypeInternalSubset(p, errorHandler); } p.skipBlanks(); if (p.char() !== ">") { return errorHandler.fatalError("doctype not terminated with > at position " + p.getIndex()); } p.skip(1); domBuilder.startDTD(doctype.name, doctype.publicId, doctype.systemId, doctype.internalSubset); domBuilder.endDTD(); return p.getIndex(); } default: return errorHandler.fatalError('Not well-formed XML starting with " 0) { return errorHandler.fatalError( "processing instruction at position " + start + " is an xml declaration which is only at the start of the document" ); } if (!g.XMLDecl.test(source.substring(start))) { return errorHandler.fatalError("xml declaration is not well-formed"); } } domBuilder.processingInstruction(match[1], match[2]); return start + match[0].length; } function ElementAttributes() { this.attributeNames = /* @__PURE__ */ Object.create(null); } ElementAttributes.prototype = { setTagName: function(tagName) { if (!g.QName_exact.test(tagName)) { throw new Error("invalid tagName:" + tagName); } this.tagName = tagName; }, addValue: function(qName, value, offset) { if (!g.QName_exact.test(qName)) { throw new Error("invalid attribute:" + qName); } this.attributeNames[qName] = this.length; this[this.length++] = { qName, value, offset }; }, length: 0, getLocalName: function(i) { return this[i].localName; }, getLocator: function(i) { return this[i].locator; }, getQName: function(i) { return this[i].qName; }, getURI: function(i) { return this[i].uri; }, getValue: function(i) { return this[i].value; } // ,getIndex:function(uri, localName)){ // if(localName){ // // }else{ // var qName = uri // } // }, // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))}, // getType:function(uri,localName){} // getType:function(i){}, }; exports.XMLReader = XMLReader; exports.parseUtils = parseUtils; exports.parseDoctypeCommentOrCData = parseDoctypeCommentOrCData; } }); // node_modules/@xmldom/xmldom/lib/dom-parser.js var require_dom_parser = __commonJS({ "node_modules/@xmldom/xmldom/lib/dom-parser.js"(exports) { "use strict"; init_define_L2W_CONFIG(); var conventions = require_conventions(); var dom = require_dom(); var errors = require_errors(); var entities = require_entities(); var sax = require_sax(); var DOMImplementation = dom.DOMImplementation; var hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace; var isHTMLMimeType = conventions.isHTMLMimeType; var isValidMimeType = conventions.isValidMimeType; var MIME_TYPE = conventions.MIME_TYPE; var NAMESPACE = conventions.NAMESPACE; var ParseError = errors.ParseError; var XMLReader = sax.XMLReader; function normalizeLineEndings(input) { return input.replace(/\r[\n\u0085]/g, "\n").replace(/[\r\u0085\u2028\u2029]/g, "\n"); } function DOMParser3(options) { options = options || {}; if (options.locator === void 0) { options.locator = true; } this.assign = options.assign || conventions.assign; this.domHandler = options.domHandler || DOMHandler; this.onError = options.onError || options.errorHandler; if (options.errorHandler && typeof options.errorHandler !== "function") { throw new TypeError("errorHandler object is no longer supported, switch to onError!"); } else if (options.errorHandler) { options.errorHandler("warning", "The `errorHandler` option has been deprecated, use `onError` instead!", this); } this.normalizeLineEndings = options.normalizeLineEndings || normalizeLineEndings; this.locator = !!options.locator; this.xmlns = this.assign(/* @__PURE__ */ Object.create(null), options.xmlns); } DOMParser3.prototype.parseFromString = function(source, mimeType) { if (!isValidMimeType(mimeType)) { throw new TypeError('DOMParser.parseFromString: the provided mimeType "' + mimeType + '" is not valid.'); } var defaultNSMap = this.assign(/* @__PURE__ */ Object.create(null), this.xmlns); var entityMap = entities.XML_ENTITIES; var defaultNamespace = defaultNSMap[""] || null; if (hasDefaultHTMLNamespace(mimeType)) { entityMap = entities.HTML_ENTITIES; defaultNamespace = NAMESPACE.HTML; } else if (mimeType === MIME_TYPE.XML_SVG_IMAGE) { defaultNamespace = NAMESPACE.SVG; } defaultNSMap[""] = defaultNamespace; defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML; var domBuilder = new this.domHandler({ mimeType, defaultNamespace, onError: this.onError }); var locator = this.locator ? {} : void 0; if (this.locator) { domBuilder.setDocumentLocator(locator); } var sax2 = new XMLReader(); sax2.errorHandler = domBuilder; sax2.domBuilder = domBuilder; var isXml = !conventions.isHTMLMimeType(mimeType); if (isXml && typeof source !== "string") { sax2.errorHandler.fatalError("source is not a string"); } sax2.parse(this.normalizeLineEndings(String(source)), defaultNSMap, entityMap); if (!domBuilder.doc.documentElement) { sax2.errorHandler.fatalError("missing root element"); } return domBuilder.doc; }; function DOMHandler(options) { var opt = options || {}; this.mimeType = opt.mimeType || MIME_TYPE.XML_APPLICATION; this.defaultNamespace = opt.defaultNamespace || null; this.cdata = false; this.currentElement = void 0; this.doc = void 0; this.locator = void 0; this.onError = opt.onError; } function position(locator, node) { node.lineNumber = locator.lineNumber; node.columnNumber = locator.columnNumber; } DOMHandler.prototype = { /** * Either creates an XML or an HTML document and stores it under `this.doc`. * If it is an XML document, `this.defaultNamespace` is used to create it, * and it will not contain any `childNodes`. * If it is an HTML document, it will be created without any `childNodes`. * * @see http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html */ startDocument: function() { var impl = new DOMImplementation(); this.doc = isHTMLMimeType(this.mimeType) ? impl.createHTMLDocument(false) : impl.createDocument(this.defaultNamespace, ""); }, startElement: function(namespaceURI, localName, qName, attrs) { var doc = this.doc; var el = doc.createElementNS(namespaceURI, qName || localName); var len = attrs.length; appendElement(this, el); this.currentElement = el; this.locator && position(this.locator, el); for (var i = 0; i < len; i++) { var namespaceURI = attrs.getURI(i); var value = attrs.getValue(i); var qName = attrs.getQName(i); var attr2 = doc.createAttributeNS(namespaceURI, qName); this.locator && position(attrs.getLocator(i), attr2); attr2.value = attr2.nodeValue = value; el.setAttributeNode(attr2); } }, endElement: function(namespaceURI, localName, qName) { this.currentElement = this.currentElement.parentNode; }, startPrefixMapping: function(prefix, uri) { }, endPrefixMapping: function(prefix) { }, processingInstruction: function(target, data) { var ins = this.doc.createProcessingInstruction(target, data); this.locator && position(this.locator, ins); appendElement(this, ins); }, ignorableWhitespace: function(ch, start, length2) { }, characters: function(chars, start, length2) { chars = _toString.apply(this, arguments); if (chars) { if (this.cdata) { var charNode = this.doc.createCDATASection(chars); } else { var charNode = this.doc.createTextNode(chars); } if (this.currentElement) { this.currentElement.appendChild(charNode); } else if (/^\s*$/.test(chars)) { this.doc.appendChild(charNode); } this.locator && position(this.locator, charNode); } }, skippedEntity: function(name) { }, endDocument: function() { this.doc.normalize(); }, /** * Stores the locator to be able to set the `columnNumber` and `lineNumber` * on the created DOM nodes. * * @param {Locator} locator */ setDocumentLocator: function(locator) { if (locator) { locator.lineNumber = 0; } this.locator = locator; }, //LexicalHandler comment: function(chars, start, length2) { chars = _toString.apply(this, arguments); var comm = this.doc.createComment(chars); this.locator && position(this.locator, comm); appendElement(this, comm); }, startCDATA: function() { this.cdata = true; }, endCDATA: function() { this.cdata = false; }, startDTD: function(name, publicId, systemId, internalSubset) { var impl = this.doc.implementation; if (impl && impl.createDocumentType) { var dt = impl.createDocumentType(name, publicId, systemId, internalSubset); this.locator && position(this.locator, dt); appendElement(this, dt); this.doc.doctype = dt; } }, reportError: function(level, message) { if (typeof this.onError === "function") { try { this.onError(level, message, this); } catch (e) { throw new ParseError("Reporting " + level + ' "' + message + '" caused ' + e, this.locator); } } else { console.error("[xmldom " + level + "] " + message, _locator(this.locator)); } }, /** * @see http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html */ warning: function(message) { this.reportError("warning", message); }, error: function(message) { this.reportError("error", message); }, /** * This function reports a fatal error and throws a ParseError. * * @param {string} message * - The message to be used for reporting and throwing the error. * @param {Error} [cause] * The error that caused this fatal error, preserved as the thrown `ParseError`'s `cause`. * @returns {never} * This function always throws an error and never returns a value. * @throws {ParseError} * Always throws a ParseError with the provided message. */ fatalError: function(message, cause) { this.reportError("fatalError", message); throw new ParseError(message, this.locator, cause); } }; function _locator(l) { if (l) { return "\n@#[line:" + l.lineNumber + ",col:" + l.columnNumber + "]"; } } function _toString(chars, start, length2) { if (typeof chars == "string") { return chars.substr(start, length2); } else { if (chars.length >= start + length2 || start) { return new java.lang.String(chars, start, length2) + ""; } return chars; } } "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace( /\w+/g, function(key) { DOMHandler.prototype[key] = function() { return null; }; } ); function appendElement(handler, node) { if (!handler.currentElement) { handler.doc.appendChild(node); } else { handler.currentElement.appendChild(node); } } function onErrorStopParsing(level) { if (level === "error") throw "onErrorStopParsing"; } function onWarningStopParsing() { throw "onWarningStopParsing"; } exports.__DOMHandler = DOMHandler; exports.DOMParser = DOMParser3; exports.normalizeLineEndings = normalizeLineEndings; exports.onErrorStopParsing = onErrorStopParsing; exports.onWarningStopParsing = onWarningStopParsing; } }); // node_modules/@xmldom/xmldom/lib/index.js var require_lib = __commonJS({ "node_modules/@xmldom/xmldom/lib/index.js"(exports) { "use strict"; init_define_L2W_CONFIG(); var conventions = require_conventions(); exports.assign = conventions.assign; exports.hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace; exports.isHTMLMimeType = conventions.isHTMLMimeType; exports.isValidMimeType = conventions.isValidMimeType; exports.MIME_TYPE = conventions.MIME_TYPE; exports.NAMESPACE = conventions.NAMESPACE; var errors = require_errors(); exports.DOMException = errors.DOMException; exports.DOMExceptionName = errors.DOMExceptionName; exports.ExceptionCode = errors.ExceptionCode; exports.ParseError = errors.ParseError; var dom = require_dom(); exports.Attr = dom.Attr; exports.CDATASection = dom.CDATASection; exports.CharacterData = dom.CharacterData; exports.Comment = dom.Comment; exports.Document = dom.Document; exports.DocumentFragment = dom.DocumentFragment; exports.DocumentType = dom.DocumentType; exports.DOMImplementation = dom.DOMImplementation; exports.Element = dom.Element; exports.Entity = dom.Entity; exports.EntityReference = dom.EntityReference; exports.LiveNodeList = dom.LiveNodeList; exports.NamedNodeMap = dom.NamedNodeMap; exports.Node = dom.Node; exports.NodeList = dom.NodeList; exports.Notation = dom.Notation; exports.ProcessingInstruction = dom.ProcessingInstruction; exports.Text = dom.Text; exports.XMLSerializer = dom.XMLSerializer; var domParser = require_dom_parser(); exports.DOMParser = domParser.DOMParser; exports.normalizeLineEndings = domParser.normalizeLineEndings; exports.onErrorStopParsing = domParser.onErrorStopParsing; exports.onWarningStopParsing = domParser.onWarningStopParsing; } }); // desktop/src/bin.ts init_define_L2W_CONFIG(); import { isSea } from "node:sea"; import { getCACertificates, setDefaultCACertificates } from "node:tls"; // desktop/src/cli.ts init_define_L2W_CONFIG(); import { readFile as readFile3, writeFile as writeFile4, mkdir as mkdir4 } from "node:fs/promises"; import { readFileSync as readFileSync3 } from "node:fs"; import { dirname as dirname5, join as join6, resolve as resolve4, basename as basename2, extname, sep as sep2 } from "node:path"; // desktop/src/convert-tex.ts init_define_L2W_CONFIG(); // docx/src/codec-node.ts init_define_L2W_CONFIG(); import { inflateRawSync, deflateRawSync } from "node:zlib"; var nodeZipCodec = { async inflateRaw(data) { return new Uint8Array(inflateRawSync(data)); }, async deflateRaw(data) { return new Uint8Array(deflateRawSync(data, { level: 9 })); } }; // desktop/src/convert-core.ts init_define_L2W_CONFIG(); // texdoc/src/tex-parse.ts init_define_L2W_CONFIG(); // parser/src/parser.ts init_define_L2W_CONFIG(); // parser/src/tokenizer.ts init_define_L2W_CONFIG(); var LETTER = /[A-Za-z]/; var DIGIT = /[0-9]/; function tokenize(source) { const tokens = []; let i = 0; const n = source.length; const push = (type, value, start, end) => { tokens.push({ type, value, start, end }); }; while (i < n) { const ch = source[i]; if (ch === " " || ch === " " || ch === "\n" || ch === "\r") { i++; continue; } if (ch === "%") { while (i < n && source[i] !== "\n") i++; continue; } if (ch === "\\") { const start = i; i++; if (i >= n) { push("command", "", start, i); break; } if (source[i] === "\\") { i++; push("newline", "\\\\", start, i); continue; } if (LETTER.test(source[i])) { let j = i; while (j < n && LETTER.test(source[j])) j++; const name2 = source.slice(i, j); i = j; push("command", name2, start, i); continue; } const name = source[i]; i++; push("command", name, start, i); continue; } if (ch === "{") { push("lbrace", "{", i, i + 1); i++; continue; } if (ch === "}") { push("rbrace", "}", i, i + 1); i++; continue; } if (ch === "[") { push("lbracket", "[", i, i + 1); i++; continue; } if (ch === "]") { push("rbracket", "]", i, i + 1); i++; continue; } if (ch === "^") { push("caret", "^", i, i + 1); i++; continue; } if (ch === "_") { push("underscore", "_", i, i + 1); i++; continue; } if (ch === "&") { push("ampersand", "&", i, i + 1); i++; continue; } if (DIGIT.test(ch)) { const start = i; let j = i; while (j < n && DIGIT.test(source[j])) j++; if (source[j] === "." && DIGIT.test(source[j + 1] ?? "")) { j++; while (j < n && DIGIT.test(source[j])) j++; } const value = source.slice(start, j); i = j; push("number", value, start, i); continue; } const codePoint = source.codePointAt(i); const charLen = codePoint > 65535 ? 2 : 1; push("char", source.slice(i, i + charLen), i, i + charLen); i += charLen; } push("eof", "", n, n); return tokens; } // parser/src/errors.ts init_define_L2W_CONFIG(); // parser/src/tokens.ts init_define_L2W_CONFIG(); function formatPosition(source, index) { let line3 = 1; let column = 1; const limit = Math.max(0, Math.min(index, source.length)); for (let i = 0; i < limit; i++) { if (source[i] === "\n") { line3++; column = 1; } else { column++; } } return { line: line3, column }; } // parser/src/errors.ts var LatexParseError = class extends Error { constructor(source, type, message, position, token, suggestion) { const { line: line3, column } = formatPosition(source, position); super(message); this.name = "LatexParseError"; this.details = { type, message, position, line: line3, column, token, suggestion }; } toDisplayString() { const { line: line3, column, message, token, suggestion } = this.details; const lines = [ "Unable to parse this expression.", `Line ${line3}, character ${column}`, message ]; if (token !== void 0) lines.push(`Unexpected token: ${token || ""}`); if (suggestion) lines.push(`Suggested fix: ${suggestion}`); return lines.join("\n"); } }; // domain/src/symbols.ts init_define_L2W_CONFIG(); var greekLower = { alpha: "\u03B1", beta: "\u03B2", gamma: "\u03B3", delta: "\u03B4", epsilon: "\u03F5", varepsilon: "\u03B5", zeta: "\u03B6", eta: "\u03B7", theta: "\u03B8", vartheta: "\u03D1", iota: "\u03B9", kappa: "\u03BA", lambda: "\u03BB", mu: "\u03BC", nu: "\u03BD", xi: "\u03BE", omicron: "\u03BF", pi: "\u03C0", varpi: "\u03D6", rho: "\u03C1", varrho: "\u03F1", sigma: "\u03C3", varsigma: "\u03C2", tau: "\u03C4", upsilon: "\u03C5", phi: "\u03C6", varphi: "\u03D5", chi: "\u03C7", psi: "\u03C8", omega: "\u03C9" }; var greekUpper = { Gamma: "\u0393", Delta: "\u0394", Theta: "\u0398", Lambda: "\u039B", Xi: "\u039E", Pi: "\u03A0", Sigma: "\u03A3", Upsilon: "\u03A5", Phi: "\u03A6", Psi: "\u03A8", Omega: "\u03A9" }; var operators = { pm: "\xB1", mp: "\u2213", times: "\xD7", div: "\xF7", cdot: "\u22C5", ast: "\u2217", star: "\u22C6", circ: "\u2218", bullet: "\u2219", oplus: "\u2295", ominus: "\u2296", otimes: "\u2297", oslash: "\u2298", odot: "\u2299", setminus: "\u2216", wedge: "\u2227", vee: "\u2228", cup: "\u222A", cap: "\u2229", amalg: "\u2A3F" }; var relations = { leq: "\u2264", le: "\u2264", geq: "\u2265", ge: "\u2265", neq: "\u2260", ne: "\u2260", approx: "\u2248", equiv: "\u2261", sim: "\u223C", simeq: "\u2243", cong: "\u2245", propto: "\u221D", parallel: "\u2225", perp: "\u22A5", in: "\u2208", notin: "\u2209", ni: "\u220B", subset: "\u2282", subseteq: "\u2286", supset: "\u2283", supseteq: "\u2287", sqsubseteq: "\u2291", sqsupseteq: "\u2292", prec: "\u227A", succ: "\u227B", ll: "\u226A", gg: "\u226B", asymp: "\u224D", doteq: "\u2250", // School notation: slanted inequalities (UK/Indian textbooks), the // negated relations amssymb names, and logic's turnstiles. leqslant: "\u2A7D", geqslant: "\u2A7E", nleq: "\u2270", ngeq: "\u2271", nless: "\u226E", ngtr: "\u226F", nsubseteq: "\u2288", nsupseteq: "\u2289", subsetneq: "\u228A", supsetneq: "\u228B", ncong: "\u2247", nsim: "\u2241", nparallel: "\u2226", nmid: "\u2224", nequiv: "\u2262", triangleq: "\u225C", backsim: "\u223D", approxeq: "\u224A", vdash: "\u22A2", models: "\u22A8" }; var arrows = { rightarrow: "\u2192", to: "\u2192", leftarrow: "\u2190", gets: "\u2190", leftrightarrow: "\u2194", Rightarrow: "\u21D2", Leftarrow: "\u21D0", Leftrightarrow: "\u21D4", mapsto: "\u21A6", longrightarrow: "\u27F6", longleftarrow: "\u27F5", // U+21BD, the harpoon pointing left with its barb down. This used to be // U+21C1, which points right — \rightharpoondown's glyph. rightleftharpoons: "\u21CC", rightharpoonup: "\u21C0", leftharpoondown: "\u21BD", leftharpoonup: "\u21BC", rightharpoondown: "\u21C1", leftrightharpoons: "\u21CB", uparrow: "\u2191", downarrow: "\u2193", nearrow: "\u2197", searrow: "\u2198", swarrow: "\u2199", nwarrow: "\u2196", // Logic (\implies, \iff) and the long and decorated arrows. implies: "\u27F9", impliedby: "\u27F8", iff: "\u27FA", Longrightarrow: "\u27F9", Longleftarrow: "\u27F8", Longleftrightarrow: "\u27FA", longleftrightarrow: "\u27F7", longmapsto: "\u27FC", hookrightarrow: "\u21AA", hookleftarrow: "\u21A9", twoheadrightarrow: "\u21A0", leadsto: "\u21DD", rightsquigarrow: "\u21DD", rightleftarrows: "\u21C4", leftrightarrows: "\u21C6", Uparrow: "\u21D1", Downarrow: "\u21D3", updownarrow: "\u2195", Updownarrow: "\u21D5" }; var misc = { infty: "\u221E", partial: "\u2202", nabla: "\u2207", forall: "\u2200", exists: "\u2203", nexists: "\u2204", emptyset: "\u2205", varnothing: "\u2205", ldots: "\u2026", cdots: "\u22EF", vdots: "\u22EE", ddots: "\u22F1", therefore: "\u2234", because: "\u2235", angle: "\u2220", top: "\u22A4", bot: "\u22A5", aleph: "\u2135", hbar: "\u210F", ell: "\u2113", Re: "\u211C", Im: "\u2111", wp: "\u2118", prime: "\u2032", surd: "\u221A", degree: "\xB0", hslash: "\u210F", imath: "\u0131", jmath: "\u0237", langle: "\u27E8", rangle: "\u27E9", lVert: "\u2016", rVert: "\u2016", Vert: "\u2016", vert: "|", mid: "\u2223", neg: "\xAC", lnot: "\xAC", checkmark: "\u2713", // Phase 3 (physics): Hermitian conjugate/adjoint dagger, d'Alembertian. dagger: "\u2020", ddagger: "\u2021", Box: "\u25A1", // Geometry, and the floor/ceiling brackets on their own (\left\lfloor // already worked; a bare \lfloor x \rfloor did not). triangle: "\u25B3", square: "\u25A1", blacksquare: "\u25A0", diamond: "\u22C4", measuredangle: "\u2221", sphericalangle: "\u2222", frown: "\u2322", smile: "\u2323", lfloor: "\u230A", rfloor: "\u230B", lceil: "\u2308", rceil: "\u2309", complement: "\u2201", mho: "\u2127", AA: "\xC5", beth: "\u2136", gimel: "\u2137", daleth: "\u2138", dots: "\u2026" }; function toClass(table, cls) { const out = {}; for (const [k, v] of Object.entries(table)) out[k] = { text: v, class: cls }; return out; } var SYMBOL_TABLE = { ...toClass(greekLower, "greek"), ...toClass(greekUpper, "greek"), ...toClass(operators, "operator"), ...toClass(relations, "operator"), ...toClass(arrows, "operator"), ...toClass(misc, "special") }; var NEGATED = { "=": "\u2260", "<": "\u226E", ">": "\u226F", "\u2264": "\u2270", "\u2265": "\u2271", "\u2261": "\u2262", "\u223C": "\u2241", "\u2243": "\u2244", "\u2245": "\u2247", "\u2248": "\u2249", "\u2208": "\u2209", "\u220B": "\u220C", "\u2282": "\u2284", "\u2283": "\u2285", "\u2286": "\u2288", "\u2287": "\u2289", "\u2223": "\u2224", "|": "\u2224", "\u2225": "\u2226", "\u22A2": "\u22AC", "\u22A8": "\u22AD", "\u227A": "\u2280", "\u227B": "\u2281", "\u2203": "\u2204", "\u2192": "\u219B", "\u2190": "\u219A", "\u2194": "\u21AE", "\u21D2": "\u21CF", "\u21D0": "\u21CD", "\u21D4": "\u21CE" }; var ESCAPED_CHAR_TABLE = { "%": "%", "$": "$", "#": "#", "&": "&", "_": "_", "{": "{", "}": "}", " ": " ", ",": " ", ";": " " }; // domain/src/functions.ts init_define_L2W_CONFIG(); var FUNCTION_NAMES = /* @__PURE__ */ new Set([ // trigonometric "sin", "cos", "tan", "cot", "sec", "csc", // inverse trigonometric "arcsin", "arccos", "arctan", "arccot", "arcsec", "arccsc", // hyperbolic "sinh", "cosh", "tanh", "coth", "sech", "csch", "arsinh", "arcosh", "artanh", // logs / exponential "log", "ln", "exp", // limit-style (stacked subscript, m:limLow, when only a bare subscript follows) "lim", "limsup", "liminf", "max", "min", "sup", "inf", // misc named operators "det", "gcd", "lcm", "dim", "ker", "deg", "arg", "hom", "Pr", "mod" ]); var LIMIT_STYLE_FUNCTIONS = /* @__PURE__ */ new Set([ "lim", "limsup", "liminf", "max", "min", "sup", "inf" ]); // domain/src/colors.ts init_define_L2W_CONFIG(); var XCOLOR = { red: "FF0000", green: "00FF00", blue: "0000FF", cyan: "00FFFF", magenta: "FF00FF", yellow: "FFFF00", black: "000000", white: "FFFFFF", gray: "808080", darkgray: "404040", lightgray: "BFBFBF", brown: "BF8040", lime: "BFFF00", olive: "808000", orange: "FF8000", pink: "FFBFBF", purple: "BF0040", teal: "008080", violet: "800080" }; function xcolorName(hex2) { const wanted = hex2.toUpperCase(); return Object.keys(XCOLOR).find((name) => XCOLOR[name] === wanted); } var CSS_COLORS = { red: "FF0000", green: "008000", blue: "0000FF", black: "000000", white: "FFFFFF", gray: "808080", grey: "808080", silver: "C0C0C0", orange: "FFA500", purple: "800080", teal: "008080", navy: "000080", maroon: "800000", olive: "808000", yellow: "FFFF00", cyan: "00FFFF", aqua: "00FFFF", magenta: "FF00FF", fuchsia: "FF00FF", pink: "FFC0CB", brown: "A52A2A", violet: "EE82EE", lime: "00FF00" }; function cssColorToHex(value) { const v = value.trim(); const short = /^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])$/.exec(v); if (short) return `${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`.toUpperCase(); const long = /^#([0-9a-fA-F]{6})$/.exec(v); if (long) return long[1].toUpperCase(); return CSS_COLORS[v.toLowerCase()] ?? null; } // domain/src/chemistry.ts init_define_L2W_CONFIG(); function parseChemicalFormula(source, raw, baseOffset) { const shifted = tokenize(raw).map((tk) => ({ ...tk, start: tk.start + baseOffset, end: tk.end + baseOffset })); let pos = 0; const peek = (o = 0) => shifted[Math.min(pos + o, shifted.length - 1)]; const adv = () => shifted[pos < shifted.length - 1 ? pos++ : pos]; const atEnd = () => peek().type === "eof"; function fail6(type, message, tok, suggestion) { throw new LatexParseError(source, type, message, tok.start, tok.value || void 0, suggestion); } function digitNode(tok) { return { kind: "symbol", class: "digit", text: tok.value, source: tok.value, start: tok.start, end: tok.end }; } function attachCharge(node, numberTok) { let text = numberTok ? numberTok.value : ""; let end = numberTok ? numberTok.end : node.end; const start = numberTok ? numberTok.start : peek().start; let sawSign = false; for (; ; ) { const s = peek(); if (s.type === "char" && (s.value === "+" || s.value === "-") && s.start === end) { text += s.value; end = s.end; sawSign = true; adv(); continue; } break; } if (!sawSign) return node; const sup = { kind: "symbol", class: "punct", text, source: text, start, end }; return { kind: "supsub", base: node, sup, start: node.start, end }; } function readSignedArg() { if (peek().type === "lbrace") { const open = adv(); let text = ""; let end = open.end; while (peek().type !== "rbrace" && !atEnd()) { const tk2 = peek(); if (tk2.type === "number" || tk2.type === "char" && (tk2.value === "+" || tk2.value === "-")) { text += tk2.value; end = tk2.end; adv(); } else { fail6( "unsupported-construct", `Only digits and +/- are supported inside an explicit ^{...} in \\ce{}, found "${tk2.value}".`, tk2, "Move anything else outside \\ce{}, or write the charge as plain digits/signs." ); } } if (peek().type !== "rbrace") fail6("unclosed-brace", "Missing closing '}' for ^{...} in \\ce{}.", peek(), "Add a matching '}'."); const close = adv(); return { text, start: open.start, end: close.end }; } const tk = peek(); if (tk.type === "number" || tk.type === "char" && (tk.value === "+" || tk.value === "-")) { adv(); let text = tk.value; let end = tk.end; while (peek().type === "char" && (peek().value === "+" || peek().value === "-") && peek().start === end) { const s = adv(); text += s.value; end = s.end; } return { text, start: tk.start, end }; } fail6("wrong-argument-count", "Expected a digit or +/- after ^ in \\ce{}.", tk); } function isBond(k) { const dash = peek(k); const next = peek(k + 1); if (!(dash.type === "char" && dash.value === "-" && next.start === dash.end)) return false; return next.type === "lbracket" || next.type === "char" && /^[A-Za-z(]$/.test(next.value); } function maybeSubscriptOrCharge(node) { let result = node; const n = peek(); if (n.start === result.end) { if (n.type === "number") { const p1 = peek(1); if (p1.type === "char" && (p1.value === "+" || p1.value === "-") && p1.start === n.end && !isBond(1)) { adv(); return attachCharge(result, n); } adv(); const sub = digitNode(n); result = { kind: "supsub", base: result, sub, start: result.start, end: n.end }; } else if (n.type === "char" && (n.value === "+" || n.value === "-") && !isBond(0)) { return attachCharge(result, void 0); } } const caret = peek(); if (caret.type === "caret" && caret.start === result.end) { adv(); const { text, start, end } = readSignedArg(); const sup = { kind: "symbol", class: "punct", text, source: text, start, end }; result = { kind: "supsub", base: result, sup, start: result.start, end }; } return result; } function parseLetterRun() { const first = adv(); let text = first.value; let end = first.end; while (peek().type === "char" && /[a-z]/.test(peek().value) && peek().start === end) { const t2 = adv(); text += t2.value; end = t2.end; } const node = { kind: "symbol", class: "letter", text, source: text, start: first.start, end }; return maybeSubscriptOrCharge(node); } function parseGroup(open) { const openTok = adv(); const close = open === "(" ? ")" : "]"; const isCloseTok = (tk) => open === "(" ? tk.type === "char" && tk.value === ")" : tk.type === "rbracket"; const children3 = []; while (!isCloseTok(peek()) && !atEnd()) { children3.push(parseAtomUnit()); } if (!isCloseTok(peek())) { fail6("unclosed-brace", `Missing closing '${close}' in \\ce{}.`, peek(), `Add a matching '${close}'.`); } const closeTok = adv(); const bodyRow = { kind: "row", children: children3, start: openTok.start, end: closeTok.end }; const delimited = { kind: "delimited", left: open, right: close, parts: [bodyRow], start: openTok.start, end: closeTok.end }; return maybeSubscriptOrCharge(delimited); } function matchesSeq(values) { for (let k = 0; k < values.length; k++) { const tk = peek(k); if (tk.type !== "char" || tk.value !== values[k]) return false; if (k > 0 && peek(k - 1).end !== tk.start) return false; } return true; } function consumeArrow(n, chr, kind) { const start = peek().start; let end = start; for (let k = 0; k < n; k++) { end = peek().end; adv(); } const conditions = []; while (conditions.length < 2 && peek().type === "lbracket" && peek().start === end) { const openTok = adv(); const condChildren = []; while (peek().type !== "rbracket" && !atEnd()) { const previous = condChildren[condChildren.length - 1]; if (previous && peek().start > previous.end) { condChildren.push({ kind: "spacing", size: "medium", start: previous.end, end: peek().start }); } condChildren.push(parseAtomUnit()); } if (peek().type !== "rbracket") { fail6("unclosed-brace", "Missing closing ']' for the reaction condition.", peek(), "Add a matching ']', e.g. \\ce{A ->[cat.] B}."); } const closeTok = adv(); conditions.push({ kind: "row", children: condChildren, start: openTok.start, end: closeTok.end }); end = closeTok.end; } const [above, below] = conditions; const node = { kind: "labeledarrow", arrow: kind, chr, above, below, start, end }; return node; } function tryParseArrow() { if (matchesSeq(["<", "<", "=", ">"])) { fail6( "unsupported-construct", "Asymmetric equilibrium arrows (favoring the reverse direction) are not supported \u2014 no distinct OMML glyph is available for them.", peek(), "Use a plain equilibrium arrow (<=>) instead." ); } if (matchesSeq(["<", "=", ">", ">"])) { fail6( "unsupported-construct", "Asymmetric equilibrium arrows (favoring the forward direction) are not supported \u2014 no distinct OMML glyph is available for them.", peek(), "Use a plain equilibrium arrow (<=>) instead." ); } if (matchesSeq(["<", "=", ">"])) return consumeArrow(3, "\u21CC", "xrightarrow"); if (matchesSeq(["-", ">"])) return consumeArrow(2, "\u2192", "xrightarrow"); if (matchesSeq(["<", "-"])) return consumeArrow(2, "\u2190", "xleftarrow"); return void 0; } function parseIsotope() { const start = peek().start; let presup; let presub; while (peek().type === "caret" || peek().type === "underscore") { const mark = adv(); const arg = readSignedArg(); const node = { kind: "symbol", class: "digit", text: arg.text, source: arg.text, start: arg.start, end: arg.end }; if (mark.type === "caret") { if (presup) fail6("wrong-argument-count", "An isotope has one mass number: there are two ^ here.", mark); presup = node; } else { if (presub) fail6("wrong-argument-count", "An isotope has one atomic number: there are two _ here.", mark); presub = node; } } const element = peek(); if (!(element.type === "char" && /[A-Za-z]/.test(element.value))) { fail6( "unsupported-construct", "An isotope's ^{mass} and _{number} have to be followed by an element symbol inside \\ce{}.", element, "Write it as \\ce{^{14}_{6}C}: the numbers, then the element." ); } const base = parseLetterRun(); return { kind: "prescript", base, presup, presub, start, end: base.end }; } function parseAtomUnit() { const arrow = tryParseArrow(); if (arrow) return arrow; const tk = peek(); if (tk.type === "char" && tk.value === "(") return parseGroup("("); if (tk.type === "lbracket") return parseGroup("["); if (tk.type === "char" && /[A-Za-z]/.test(tk.value)) return parseLetterRun(); if (tk.type === "number") { adv(); return digitNode(tk); } if (tk.type === "caret" || tk.type === "underscore") return parseIsotope(); if (tk.type === "char" && (tk.value === "+" || tk.value === "-")) { adv(); return { kind: "symbol", class: "punct", text: tk.value, source: tk.value, start: tk.start, end: tk.end }; } if (tk.type === "command") { adv(); if (tk.value in SYMBOL_TABLE) { const def = SYMBOL_TABLE[tk.value]; return { kind: "symbol", class: def.class, text: def.text, source: `\\${tk.value}`, start: tk.start, end: tk.end }; } if (tk.value in ESCAPED_CHAR_TABLE) { return { kind: "symbol", class: "punct", text: ESCAPED_CHAR_TABLE[tk.value], source: `\\${tk.value}`, start: tk.start, end: tk.end }; } fail6( "unknown-command", `Unknown command "\\${tk.value}" inside \\ce{}.`, tk, "Only simple named symbols (e.g. \\Delta, \\alpha) are supported inside \\ce{} \u2014 not compound commands like \\frac. Move those outside \\ce{}." ); } if (tk.type === "char") { adv(); const text = tk.value === "#" ? "\u2261" : tk.value; return { kind: "symbol", class: "punct", text, source: tk.value, start: tk.start, end: tk.end }; } fail6("unexpected-eof", "Unexpected end of \\ce{} content.", tk); } const children2 = []; while (!atEnd()) { children2.push(parseAtomUnit()); } return children2; } // parser/src/parser.ts var NARY_COMMANDS = { sum: "sum", prod: "prod", coprod: "coprod", int: "int", iint: "iint", iiint: "iiint", oint: "oint", iiiint: "iiiint", oiint: "oiint", oiiint: "oiiint", bigcup: "bigcup", bigcap: "bigcap", bigoplus: "bigoplus", bigotimes: "bigotimes", bigodot: "bigodot", biguplus: "biguplus", bigvee: "bigvee", bigwedge: "bigwedge", bigsqcup: "bigsqcup" }; var ACCENT_COMMANDS = { vec: "vec", hat: "hat", widehat: "hat", bar: "bar", overline: "bar", dot: "dot", ddot: "ddot", tilde: "tilde", widetilde: "tilde", check: "check", breve: "breve", overrightarrow: "overrightarrow", overleftarrow: "overleftarrow", // The line through A and B in geometry: an arrow head at both ends. overleftrightarrow: "overleftrightarrow", underline: "underline" }; var X_ARROW_COMMANDS = { xrightarrow: "\u27F6", xleftarrow: "\u27F5", xleftrightarrow: "\u27F7", xRightarrow: "\u27F9", xLeftarrow: "\u27F8", xLeftrightarrow: "\u27FA", xrightleftharpoons: "\u21CC", xleftrightharpoons: "\u21CB", xmapsto: "\u27FC", xhookrightarrow: "\u21AA", xhookleftarrow: "\u21A9" }; var STYLE_SWITCHES = /* @__PURE__ */ new Set(["displaystyle", "textstyle", "scriptstyle", "scriptscriptstyle"]); var SPACING_COMMANDS = { ",": "thin", ";": "medium", ":": "medium", "!": "thin", quad: "quad", qquad: "qquad", " ": "medium" }; var ROW_RULES = /* @__PURE__ */ new Set(["hline", "toprule", "midrule", "bottomrule"]); var MATRIX_ENV = { matrix: "matrix", pmatrix: "pmatrix", bmatrix: "bmatrix", Bmatrix: "Bmatrix", vmatrix: "vmatrix", Vmatrix: "Vmatrix" }; var ALIGN_ENV = { // `aligned`/`gathered` are align/gather for use *inside* an equation — // \left\{ \begin{aligned} ... \end{aligned} \right. is how a system of // equations with a brace is written. In OMML they are the same m:eqArr. aligned: true, gathered: false, // env name (after stripping a trailing "*") -> whether rows may contain an alignment "&" // // `split` is align's single-equation sibling: it only ever appears inside // an equation environment, and \begin{equation} already routes \begin // through parseEnvironment, so it needs nothing beyond this entry. It // inherits align's limitation exactly — see parseAlignBody and ir.ts // IrEqArr: rows render correctly but are not aligned at the `&`. align: true, gather: false, split: true }; var CANCEL_COMMANDS = { cancel: "forward", bcancel: "backward", xcancel: "cross" }; var GROUP_CHAR_COMMANDS = { overbrace: { pos: "top", chr: "\u23DE" }, underbrace: { pos: "bot", chr: "\u23DF" }, overparen: { pos: "top", chr: "\u23DC" }, overarc: { pos: "top", chr: "\u23DC" }, underparen: { pos: "bot", chr: "\u23DD" } }; var STACK_COMMANDS = { overset: "top", stackrel: "top", underset: "bot" }; var PAIRED_DELIMITER_COMMANDS = { abs: { left: "|", right: "|" }, norm: { left: "\u2016", right: "\u2016" }, ceil: { left: "\u2308", right: "\u2309" }, floor: { left: "\u230A", right: "\u230B" } }; var TEXT_FONT = { textbf: "mathbf", textit: "mathit", textsf: "mathsf", texttt: "mathtt" }; var FONT_VARIANT_COMMANDS = { mathbb: "mathbb", Bbb: "mathbb", mathcal: "mathcal", mathscr: "mathcal", mathfrak: "mathfrak", mathsf: "mathsf", mathtt: "mathtt", mathbf: "mathbf", boldsymbol: "boldsymbol", bm: "boldsymbol", mathit: "mathit", // \si{}/\unit{} (siunitx-style unit typesetting): upright text, but unlike // \mathrm the argument is a real nested parse, so exponents/fractions // inside a unit expression (\unit{m/s^2}) work. See docs/SUPPORTED_LATEX.md // for what siunitx features this does NOT replicate (per-unit macros like // \kg, \per, \square are not implemented — they throw unknown-command). si: "upright", unit: "upright" }; var DELIM_COMMAND_TO_CHAR = { "{": "{", "}": "}", langle: "\u27E8", rangle: "\u27E9", vert: "|", Vert: "\u2016", lVert: "\u2016", rVert: "\u2016", lfloor: "\u230A", rfloor: "\u230B", lceil: "\u2308", rceil: "\u2309" }; var isCommand = (t, name) => t.type === "command" && t.value === name; var isEnd = (t) => t.type === "command" && t.value === "end"; var isRight = (t) => t.type === "command" && t.value === "right"; var isMiddle = (t) => t.type === "command" && t.value === "middle"; var Parser = class _Parser { constructor(source) { this.source = source; this.pos = 0; this.nestingDepth = 0; this.tokens = tokenize(source); } /** Parses the entire source as one top-level expression (a Row). */ parse() { const row2 = this.parseRow((t) => t.type === "eof"); const eof = this.peek(); if (eof.type !== "eof") { throw this.err("unexpected-token", `Unexpected ${eof.type} "${eof.value}"`, eof, "Check for an unmatched closing brace or bracket."); } return row2; } // ---- token stream helpers ------------------------------------------------- peek(offset = 0) { const idx = Math.min(this.pos + offset, this.tokens.length - 1); return this.tokens[idx]; } advance() { const t = this.tokens[this.pos]; if (this.pos < this.tokens.length - 1) this.pos++; return t; } expect(type, context) { const t = this.peek(); if (t.type !== type) { throw this.err("unexpected-token", `Expected ${type} ${context}, found ${t.type === "eof" ? "end of input" : `"${t.value}"`}`, t); } return this.advance(); } err(type, message, at, suggestion) { return new LatexParseError(this.source, type, message, at.start, at.value || void 0, suggestion); } // ---- row / group parsing --------------------------------------------------- parseRow(stop) { const start = this.peek().start; const raw = []; while (!stop(this.peek()) && this.peek().type !== "eof") { raw.push(this.parseAtom(stop)); } const children2 = this.mergePrescripts(raw); const end = children2.length > 0 ? children2[children2.length - 1].end : start; return { kind: "row", children: children2, start, end }; } /** * Merges an empty-base SupSubNode (produced when `^`/`_` appears with no * preceding atom, e.g. bare "^2" or "{}^2") with the atom immediately * following it into a PrescriptNode — isotope notation like * {}^{14}_{6}C parses as [emptyBase^14_6, C] at the token level; this is * the one place that pair gets recognized and turned into a proper OMML * prescript (m:sPre) instead of two unrelated siblings. See ast.ts * PrescriptNode. */ mergePrescripts(children2) { const isEmptyBaseSupSub = (n) => n.kind === "supsub" && n.base.kind === "row" && n.base.children.length === 0; const out = []; for (let i = 0; i < children2.length; i++) { const c = children2[i]; const next = children2[i + 1]; if (isEmptyBaseSupSub(c) && next && !isEmptyBaseSupSub(next)) { const node = { kind: "prescript", base: next, presup: c.sup, presub: c.sub, start: c.start, end: next.end }; out.push(node); i++; continue; } out.push(c); } return out; } parseGroup() { const open = this.expect("lbrace", "to start a group"); const row2 = this.parseRow((t) => t.type === "rbrace"); if (this.peek().type !== "rbrace") { throw this.err( "unclosed-brace", "Missing closing brace.", this.peek(), "Add a matching '}' \u2014 every '{' needs a corresponding '}'." ); } const close = this.advance(); return { ...row2, start: open.start, end: close.end }; } /** One argument: a brace group, or (LaTeX shorthand) a single atom with no scripts attached. */ parseArgument() { const t = this.peek(); if (t.type === "lbrace") return this.parseGroup(); if (t.type === "eof") { throw this.err("unexpected-eof", "Expected an argument but reached the end of the input.", t, "Provide an argument, e.g. wrap it in braces: {...}"); } if (t.type === "number" && t.value.length > 1) { this.tokens.splice(this.pos, 1, { ...t, value: t.value[0], end: t.start + 1 }, { ...t, value: t.value.slice(1), start: t.start + 1 }); } return this.parseAtomCore((tk) => tk.type === "eof"); } parseOptionalArgument() { if (this.peek().type !== "lbracket") return void 0; this.advance(); const row2 = this.parseRow((t) => t.type === "rbracket"); if (this.peek().type !== "rbracket") { throw this.err("unclosed-brace", "Missing closing ']' for optional argument.", this.peek(), "Add a matching ']'."); } this.advance(); return row2; } readBracedIdentifier(context) { this.expect("lbrace", `after ${context}`); let name = ""; while (this.peek().type === "char" || this.peek().type === "number") { name += this.advance().value; } if (this.peek().type !== "rbrace") { throw this.err("unclosed-brace", `Missing closing brace for ${context} name.`, this.peek(), "Environment/command names must be plain letters, e.g. {pmatrix}."); } this.advance(); return name; } static { // ---- atoms ------------------------------------------------------------- /** * Guards against unbounded recursion from adversarial/malformed input — * e.g. `x` followed by tens of thousands of nested `^{...}` groups, which * would otherwise recurse through parseAtom -> attachScripts -> * parseArgument -> parseGroup -> parseRow -> parseAtom -> ... once per * nesting level until V8's real call stack overflows with an uncaught * RangeError (confirmed via a throwaway repro during Phase 6 hardening — * see docs/ARCHITECTURE.md "Phase 6 additions" and brief §20 "must be * safe for use with untrusted LaTeX"). This wraps parseAtom rather than * just parseAtomCore specifically so it stays "held open" through * attachScripts's own recursive descent into `^`/`_` arguments — a guard * that unwound before attachScripts ran wouldn't actually bound * `x^{y^{z^{...}}}`-style script chains, only e.g. `\frac{\frac{...}}` * chains that recurse before returning. MAX_NESTING_DEPTH is comfortably * below any real hand-written (or even generated) equation's nesting * depth — the deepest expression in this repo's 400+-expression test * corpus nests well under 20 levels — while staying far enough under * V8's actual stack limit (each nesting level here costs several parser * call frames, not one) to guarantee this throws a clean, structured * LatexParseError instead of a raw RangeError. */ this.MAX_NESTING_DEPTH = 200; } parseAtom(stop) { if (++this.nestingDepth > _Parser.MAX_NESTING_DEPTH) { const t = this.peek(); this.nestingDepth--; throw this.err( "too-deeply-nested", `This expression nests more than ${_Parser.MAX_NESTING_DEPTH} levels deep (fractions, scripts, radicals, groups, etc. inside one another).`, t, "Break the expression into smaller pieces, or check for a runaway/accidentally-repeated pattern." ); } try { const core = this.parseAtomCore(stop); return this.attachScripts(core); } finally { this.nestingDepth--; } } attachScripts(core) { let sup; let sub; const primes = []; let primesStart = 0; let primesEnd = 0; for (; ; ) { const t = this.peek(); if (t.type === "char" && t.value === "'") { if (sup) throw this.err("wrong-argument-count", "Double superscript: a prime (') after an explicit superscript is ambiguous. Write the prime first (x'^{2}) or group it, e.g. x^{2\\prime}.", t); if (primes.length === 0) primesStart = t.start; while (this.peek().type === "char" && this.peek().value === "'") { const p = this.advance(); primesEnd = p.end; primes.push({ kind: "symbol", class: "special", text: "\u2032", source: "'", start: p.start, end: p.end }); } continue; } if (t.type === "caret") { if (sup) throw this.err("wrong-argument-count", "Double superscript: use braces to group, e.g. x^{a^b}.", t); this.advance(); sup = this.parseArgument(); } else if (t.type === "underscore") { if (sub) throw this.err("wrong-argument-count", "Double subscript: use braces to group, e.g. x_{a_b}.", t); this.advance(); sub = this.parseArgument(); } else { break; } } if (primes.length > 0) { const children2 = sup ? [...primes, sup] : primes; const end = sup ? sup.end : primesEnd; sup = { kind: "row", children: children2, start: primesStart, end }; } if (!sup && !sub) return core; const node = { kind: "supsub", base: core, sup, sub, start: core.start, end: (sup ?? sub).end }; return node; } parseAtomCore(stop) { const t = this.peek(); if (t.type === "lbrace") return this.parseGroup(); if (t.type === "number") { this.advance(); const n = { kind: "symbol", class: "digit", text: t.value, source: t.value, start: t.start, end: t.end }; return n; } if (t.type === "lbracket") { this.advance(); const n = { kind: "symbol", class: "punct", text: "[", source: "[", start: t.start, end: t.end }; return n; } if (t.type === "rbracket") { this.advance(); const n = { kind: "symbol", class: "punct", text: "]", source: "]", start: t.start, end: t.end }; return n; } if (t.type === "char") { this.advance(); const letter = /[A-Za-z]/.test(t.value); const n = { kind: "symbol", class: letter ? "letter" : "punct", text: t.value, source: t.value, start: t.start, end: t.end }; return n; } if (t.type === "caret" || t.type === "underscore") { const empty = { kind: "row", children: [], start: t.start, end: t.start }; return empty; } if (t.type === "command") return this.parseCommand(t, stop); if (t.type === "ampersand" || t.type === "newline") { throw this.err("unexpected-token", `"${t.value}" is only valid inside a matrix or cases environment.`, t); } throw this.err("unexpected-eof", "Expected an expression but reached the end of the input.", t); } parseCommand(t, stop) { const name = t.value; this.advance(); if (STYLE_SWITCHES.has(name)) { const node = { kind: "row", children: [], start: t.start, end: t.end }; return node; } switch (name) { case "cfrac": if (this.peek().type === "lbracket") { throw this.err("unsupported-construct", "\\cfrac's [l]/[r] numerator alignment can't be shown in a Word equation.", this.peek(), "Write \\cfrac{...}{...} without the [l] or [r]."); } // falls through case "frac": case "dfrac": case "tfrac": { const numerator = this.parseArgument(); const denominator = this.parseArgument(); const node = { kind: "frac", numerator, denominator, start: t.start, end: denominator.end }; return node; } case "binom": case "dbinom": case "tbinom": { const top = this.parseArgument(); const bottom = this.parseArgument(); const node = { kind: "binom", top, bottom, start: t.start, end: bottom.end }; return node; } case "sqrt": { const index = this.parseOptionalArgument(); const radicand = this.parseArgument(); const node = { kind: "sqrt", radicand, index, start: t.start, end: radicand.end }; return node; } case "left": return this.parseLeftRight(t); case "right": throw this.err("unexpected-token", '"\\right" without a matching "\\left".', t, "Add a \\left before this delimiter."); case "middle": throw this.err("unexpected-token", '"\\middle" is only valid directly inside a \\left ... \\right pair.', t, "Move this \\middle| inside a \\left...\\right group, e.g. \\left(A\\middle|B\\right)."); case "begin": return this.parseEnvironment(t); case "end": throw this.err("unexpected-token", '"\\end" without a matching "\\begin".', t); case "text": case "mathrm": case "textrm": case "textnormal": case "textup": case "operatorname": { const raw = this.readRawGroup(); const node = { kind: "text", text: raw.text, start: t.start, end: raw.end }; return node; } // Styled text: the words as \text has them, in the matching font. case "textbf": case "textit": case "textsf": case "texttt": { const raw = this.readRawGroup(); const content = { kind: "text", text: raw.text, start: t.start, end: raw.end }; const variant = TEXT_FONT[name]; const node = { kind: "fontvariant", variant, content, start: t.start, end: raw.end }; return node; } case "tag": { const raw = this.readRawGroup(); const node = { kind: "tag", label: raw.text, start: t.start, end: raw.end }; return node; } case "pmod": { const arg = this.parseArgument(); const children2 = [ { kind: "text", text: " (mod ", start: t.start, end: t.start }, arg, { kind: "symbol", class: "punct", text: ")", source: ")", start: arg.end, end: arg.end } ]; const node = { kind: "row", children: children2, start: t.start, end: arg.end }; return node; } case "bmod": { const node = { kind: "text", text: " mod ", start: t.start, end: t.end }; return node; } // Dirac bra-ket notation (physics-package-style convenience macros). // Each builds a real OMML delimiter object (m:d) directly — a single // semantic unit, not separate delimiter+content symbols side by side. case "bra": { const arg = this.parseArgument(); const node = { kind: "delimited", left: "\u27E8", right: "|", parts: [arg], start: t.start, end: arg.end }; return node; } case "ket": { const arg = this.parseArgument(); const node = { kind: "delimited", left: "|", right: "\u27E9", parts: [arg], start: t.start, end: arg.end }; return node; } case "expval": { const arg = this.parseArgument(); const node = { kind: "delimited", left: "\u27E8", right: "\u27E9", parts: [arg], start: t.start, end: arg.end }; return node; } case "braket": case "ip": { const a = this.parseArgument(); const b = this.parseArgument(); const node = { kind: "delimited", left: "\u27E8", right: "\u27E9", parts: [a, b], sepChar: "|", start: t.start, end: b.end }; return node; } case "boxed": { const base = this.parseArgument(); const node = { kind: "boxed", base, start: t.start, end: base.end }; return node; } case "textcolor": case "color": { const color = this.readColor(t); const content = name === "textcolor" ? this.parseArgument() : this.parseRow(stop); const node = { kind: "color", color, content, start: t.start, end: Math.max(content.end, t.end) }; return node; } case "not": { const target = this.parseAtomCore(stop); const negated = target.kind === "symbol" ? NEGATED[target.text] : void 0; if (negated === void 0) { throw this.err( "unsupported-construct", "\\not can only negate a relation that has a crossed-out form, such as \\not=, \\not\\in or \\not\\subset.", t, "Word can't strike through an arbitrary symbol. Use the negated symbol itself, e.g. \\neq, \\notin, \\nleq." ); } const node = { kind: "symbol", class: "operator", text: negated, source: `\\not${target.source}`, start: t.start, end: target.end }; return node; } case "limits": case "nolimits": throw this.err("unexpected-token", `\\${name} has to come straight after a large operator (\\sum, \\int) or a function name (\\lim, \\det).`, t); case "hline": case "toprule": case "midrule": case "bottomrule": throw this.err( "unexpected-token", `\\${name} draws a line between the rows of an array or matrix, so it has to start a row.`, t, "Put it straight after \\\\ or \\begin{array}{...}, as in \\begin{array}{|c|c|} \\hline a & b \\\\ \\hline \\end{array}." ); // The physics package's shorthands, built from structures that already // exist: a derivative is a fraction, \vb is bold, \mel is a bra-ket. case "dv": case "pdv": return this.parseDerivative(t, name === "pdv"); case "dd": { const order = this.parseOptionalArgument(); const d = this.differential(false, order, t); if (this.peek().type !== "lbrace") return d; const arg = this.parseGroup(); const node = { kind: "row", children: [d, arg], start: t.start, end: arg.end }; return node; } case "vb": case "va": { const starred = this.peek().type === "char" && this.peek().value === "*"; if (starred) this.advance(); const content = this.parseArgument(); if (name === "va") { const node2 = { kind: "accent", accent: "vec", base: content, start: t.start, end: content.end }; return node2; } const node = { kind: "fontvariant", variant: starred ? "boldsymbol" : "mathbf", content, start: t.start, end: content.end }; return node; } case "grad": case "curl": case "divergence": case "laplacian": { const nabla = { kind: "symbol", class: "special", text: "\u2207", source: "\\nabla", start: t.start, end: t.end }; if (name === "grad") return nabla; if (name === "laplacian") { const two = { kind: "symbol", class: "digit", text: "2", source: "2", start: t.end, end: t.end }; const node2 = { kind: "supsub", base: nabla, sup: two, start: t.start, end: t.end }; return node2; } const op = name === "curl" ? { kind: "symbol", class: "operator", text: "\xD7", source: "\\times", start: t.end, end: t.end } : { kind: "symbol", class: "operator", text: "\u22C5", source: "\\cdot", start: t.end, end: t.end }; const node = { kind: "row", children: [nabla, op], start: t.start, end: t.end }; return node; } case "ev": { const arg = this.parseArgument(); const node = { kind: "delimited", left: "\u27E8", right: "\u27E9", parts: [arg], start: t.start, end: arg.end }; return node; } case "mel": { const a = this.parseArgument(); const op = this.parseArgument(); const b = this.parseArgument(); const node = { kind: "delimited", left: "\u27E8", right: "\u27E9", parts: [a, op, b], sepChar: "|", start: t.start, end: b.end }; return node; } case "ketbra": { const a = this.parseArgument(); const b = this.parseArgument(); const ket = { kind: "delimited", left: "|", right: "\u27E9", parts: [a], start: t.start, end: a.end }; const bra = { kind: "delimited", left: "\u27E8", right: "|", parts: [b], start: a.end, end: b.end }; const node = { kind: "row", children: [ket, bra], start: t.start, end: b.end }; return node; } default: break; } if (name in FONT_VARIANT_COMMANDS) { const content = this.parseArgument(); const node = { kind: "fontvariant", variant: FONT_VARIANT_COMMANDS[name], content, start: t.start, end: content.end }; return node; } if (name in ACCENT_COMMANDS) { const base = this.parseArgument(); const node = { kind: "accent", accent: ACCENT_COMMANDS[name], base, start: t.start, end: base.end }; return node; } if (name === "cancelto") { throw this.err( "unsupported-construct", "\\cancelto is not supported.", t, "OMML can strike a term through (\\cancel) but has no way to draw the arrow and target value \\cancelto adds. Write \\cancel{...} and put the value alongside." ); } if (name === "substack") { const rows = this.parseSubstackRows(t); const node = { kind: "matrix", matrixKind: "array", rows, columns: ["center"], start: t.start, end: this.tokens[Math.max(0, this.pos - 1)].end }; return node; } if (name in CANCEL_COMMANDS) { const base = this.parseArgument(); const node = { kind: "cancel", cancel: CANCEL_COMMANDS[name], base, start: t.start, end: base.end }; return node; } if (name in GROUP_CHAR_COMMANDS) { const base = this.parseArgument(); const { pos, chr } = GROUP_CHAR_COMMANDS[name]; const node = { kind: "groupchar", pos, chr, base, start: t.start, end: base.end }; return node; } if (name in STACK_COMMANDS) { const label = this.parseArgument(); const base = this.parseArgument(); const node = { kind: "stack", pos: STACK_COMMANDS[name], label, base, start: t.start, end: base.end }; return node; } if (name in PAIRED_DELIMITER_COMMANDS) { const pair = PAIRED_DELIMITER_COMMANDS[name]; if (this.peek().type === "char" && this.peek().value === "*") this.advance(); const arg = this.parseArgument(); const node = { kind: "delimited", left: pair.left, right: pair.right, parts: [arg], start: t.start, end: arg.end }; return node; } if (name in NARY_COMMANDS) { return this.parseNAry(t, name); } if (name in SPACING_COMMANDS) { const node = { kind: "spacing", size: SPACING_COMMANDS[name], start: t.start, end: t.end }; return node; } if (name in X_ARROW_COMMANDS) { const below = this.parseOptionalArgument(); const aboveArg = this.parseArgument(); const above = aboveArg.kind === "row" && aboveArg.children.length === 0 ? void 0 : aboveArg; const node = { kind: "labeledarrow", arrow: name, chr: X_ARROW_COMMANDS[name], above, below, start: t.start, end: aboveArg.end }; return node; } if (name === "ce") { const raw = this.readRawGroup(); const children2 = parseChemicalFormula(this.source, raw.text, raw.start); const content = { kind: "row", children: children2, start: raw.start, end: raw.end }; const node = { kind: "fontvariant", variant: "upright", content, start: t.start, end: raw.end }; return node; } if (name in SYMBOL_TABLE) { const def = SYMBOL_TABLE[name]; const node = { kind: "symbol", class: def.class, text: def.text, source: `\\${name}`, start: t.start, end: t.end }; return node; } if (name in ESCAPED_CHAR_TABLE) { const node = { kind: "symbol", class: "punct", text: ESCAPED_CHAR_TABLE[name], source: `\\${name}`, start: t.start, end: t.end }; return node; } if (FUNCTION_NAMES.has(name)) { const limits = this.readLimitsModifier(); const node = limits === void 0 ? { kind: "func", name, start: t.start, end: t.end } : { kind: "func", name, limits, start: t.start, end: this.tokens[Math.max(0, this.pos - 1)].end }; return node; } throw this.err( "unknown-command", `Unknown command "\\${name}".`, t, "Check the spelling, or see SUPPORTED_LATEX.md for the list of supported commands." ); } /** \limits or \nolimits straight after an operator: true, false, or undefined when neither is there. */ readLimitsModifier() { const p = this.peek(); if (isCommand(p, "limits")) { this.advance(); return true; } if (isCommand(p, "nolimits")) { this.advance(); return false; } return void 0; } /** * \color's and \textcolor's colour: an xcolor name ({red}), or a hex value * with the HTML model ([HTML]{1F77B4}). Returned as six upper-case hex digits. */ readColor(t) { let model; if (this.peek().type === "lbracket") { const open = this.advance(); model = ""; while (this.peek().type === "char" || this.peek().type === "number") model += this.advance().value; if (this.peek().type !== "rbracket") throw this.err("unclosed-brace", "Missing ']' after the colour model.", this.peek()); this.advance(); if (model.toUpperCase() !== "HTML") { throw this.err("unsupported-construct", `The colour model "${model}" is not supported.`, open, "Use a colour name, e.g. \\textcolor{red}{x}, or [HTML]{FF0000}."); } } const raw = this.readRawGroup(); const value = raw.text.trim(); const at = { type: "char", value, start: raw.start, end: raw.end }; if (model !== void 0) { if (!/^[0-9A-Fa-f]{6}$/.test(value)) throw this.err("unsupported-construct", `"${value}" is not a six-digit HTML colour.`, at, "Write it as six hex digits, e.g. [HTML]{1F77B4}."); return value.toUpperCase(); } const hex2 = XCOLOR[value]; if (hex2 === void 0) { throw this.err("unsupported-construct", `"${value}" is not a colour TeXConverter knows (after \\${t.value}).`, at, `Use one of ${Object.keys(XCOLOR).join(", ")} \u2014 or [HTML]{RRGGBB}.`); } return hex2; } /** * The upright d (or ∂) of a derivative, raised to `order` when there is * one: the d² in d²y/dx². */ differential(partial, order, at) { const d = partial ? { kind: "symbol", class: "special", text: "\u2202", source: "\\partial", start: at.start, end: at.end } : { kind: "text", text: "d", start: at.start, end: at.end }; if (!order) return d; const node = { kind: "supsub", base: d, sup: order, start: at.start, end: order.end }; return node; } /** * The physics package's \dv and \pdv, written out as the fraction they draw: * * \dv{x} d/dx \pdv{x} ∂/∂x * \dv{y}{x} dy/dx \pdv{f}{x} ∂f/∂x * \dv[2]{y}{x} d²y/dx² \pdv{f}{x}{y} ∂²f/∂x∂y */ parseDerivative(t, partial) { const order = this.parseOptionalArgument(); const first = this.parseArgument(); const second = this.peek().type === "lbrace" ? this.parseArgument() : void 0; const third = partial && second && this.peek().type === "lbrace" ? this.parseArgument() : void 0; const end = (third ?? second ?? first).end; const d = (o) => this.differential(partial, o, t); const row2 = (children2) => ({ kind: "row", children: children2, start: t.start, end }); const raised = (base, o) => o ? { kind: "supsub", base, sup: o, start: base.start, end: o.end } : base; let numerator; let denominator; if (third) { if (order) throw this.err("unsupported-construct", "A mixed partial derivative takes no [order]: \\pdv{f}{x}{y} is already second order.", t); const two = { kind: "symbol", class: "digit", text: "2", source: "2", start: t.start, end: t.start }; numerator = row2([d(two), first]); denominator = row2([d(), second, d(), third]); } else if (second) { numerator = row2([d(order), first]); denominator = row2([d(), raised(second, order)]); } else { numerator = d(order); denominator = row2([d(), raised(first, order)]); } const node = { kind: "frac", numerator, denominator, start: t.start, end }; return node; } parseNAry(t, name) { const op = NARY_COMMANDS[name]; const limits = this.readLimitsModifier(); let sub; let sup; for (; ; ) { const p = this.peek(); if (p.type === "underscore") { if (sub) throw this.err("wrong-argument-count", "Double subscript on a large operator.", p); this.advance(); sub = this.parseArgument(); } else if (p.type === "caret") { if (sup) throw this.err("wrong-argument-count", "Double superscript on a large operator.", p); this.advance(); sup = this.parseArgument(); } else { break; } } const operand = this.parseRow( (tok) => tok.type === "eof" || tok.type === "rbrace" || tok.type === "rbracket" || tok.type === "ampersand" || tok.type === "newline" || isEnd(tok) || isRight(tok) ); const node = limits === void 0 ? { kind: "nary", op, sub, sup, operand, start: t.start, end: operand.end } : { kind: "nary", op, sub, sup, operand, limits, start: t.start, end: operand.end }; return node; } /** * \left ... \right, optionally divided into multiple parts by * one or more \middle — e.g. \left\langle\psi\middle|\phi\right\rangle * for bra-ket notation, or \left(A\middle|B\right) for conditional * probability. OMML's m:d object has exactly one m:sepChr shared by every * internal divider, so every \middle inside a single \left...\right group * must use the same delimiter character; a mix throws a clear error rather * than silently dropping one of the dividers. */ parseLeftRight(t) { const left = this.parseDelimiterChar(); const stop = (tok) => isRight(tok) || isMiddle(tok) || tok.type === "eof"; const parts = [this.parseRow(stop)]; let sepChar; while (isMiddle(this.peek())) { const middleTok = this.advance(); const ch = this.parseDelimiterChar(); if (sepChar === void 0) { sepChar = ch; } else if (sepChar !== ch) { throw this.err( "unsupported-construct", `Multiple \\middle delimiters with different characters ("${sepChar}" and "${ch}") in the same \\left...\\right are not supported.`, middleTok, "OMML's delimiter object uses one separator character for the whole group \u2014 use the same delimiter for every \\middle here, e.g. \\middle| each time." ); } parts.push(this.parseRow(stop)); } if (!isRight(this.peek())) { throw this.err("unclosed-environment", "Missing \\right to match this \\left.", this.peek(), "Add a \\right."); } const rightTok = this.advance(); const right = this.parseDelimiterChar(); const node = { kind: "delimited", left, right, parts, sepChar, start: t.start, end: rightTok.end }; return node; } parseDelimiterChar() { const t = this.advance(); if (t.type === "lbracket") return "["; if (t.type === "rbracket") return "]"; if (t.type === "char") { if (t.value === ".") return ""; if ("()[]|".includes(t.value)) return t.value; throw this.err("invalid-delimiter", `"${t.value}" is not a valid \\left/\\right delimiter.`, t, "Use one of ( ) [ ] { } | \\langle \\rangle \\lfloor \\rfloor \\lceil \\rceil or . for none."); } if (t.type === "command" && t.value in DELIM_COMMAND_TO_CHAR) { return DELIM_COMMAND_TO_CHAR[t.value]; } throw this.err("invalid-delimiter", `Expected a delimiter after \\left/\\right, found "${t.value}".`, t); } parseEnvironment(t) { const name = this.readBracedIdentifier("\\begin"); const baseName = name.replace(/\*$/, ""); if (baseName === "array") { const spec = this.parseColumnSpec(); return this.parseMatrixBody(t, "array", name, spec.columns, spec.rules); } if (baseName in MATRIX_ENV) { return this.parseMatrixBody(t, MATRIX_ENV[baseName], name); } if (baseName === "cases") { return this.parseCasesBody(t, name); } if (baseName === "equation") { const row2 = this.parseRow((tok) => isEnd(tok) || tok.type === "eof"); this.consumeEnd(name); return { ...row2, start: t.start }; } if (baseName in ALIGN_ENV) { return this.parseAlignBody(t, name, ALIGN_ENV[baseName]); } if (baseName === "eqnarray") { throw this.err( "unsupported-construct", `The \\begin{${name}} environment is not supported yet.`, t, "eqnarray is deprecated even in LaTeX itself \u2014 use \\begin{align} instead, which is supported." ); } throw this.err("unsupported-construct", `Unknown or unsupported environment "\\begin{${name}}".`, t); } /** * Reads `\begin{array}`'s mandatory `{lcr}` column spec. * * Only l/c/r are representable: OMML's m:mPr describes column count and * justification and nothing else. It has no column-rule property, so a * `|` divider cannot be drawn, and no fixed-width column, so `p{3cm}` * has no meaning either. Every one of those throws naming the token it * choked on, rather than being dropped — an array silently missing its * rules is a different table from the one that was written, and the * whole point of this parser is that it never quietly changes the maths. */ /** * The `{a \\ b \\ c}` body of \substack, as one single-cell row each. * * Unlike a matrix body this has no `&`: substack is always one column, so * an ampersand is a mistake worth naming rather than a second column. */ parseSubstackRows(t) { if (this.peek().type !== "lbrace") { throw this.err("unexpected-token", "\\substack needs a braced group, as in \\substack{i tok.type === "newline" || tok.type === "rbrace" || tok.type === "ampersand" || tok.type === "eof"; for (; ; ) { const line3 = this.parseRow(stop); rows.push([line3]); const p = this.peek(); if (p.type === "newline") { this.advance(); continue; } if (p.type === "ampersand") { throw this.err("unexpected-token", '\\substack has a single column, so "&" has no meaning in it.', p, "Separate the lines with \\\\ instead."); } if (p.type === "rbrace") { this.advance(); break; } throw this.err("unclosed-brace", "Missing the closing brace of \\substack.", p); } return rows; } /** * Single `|` rules are supported — the augmented matrix [A | b] of linear * algebra. OMML's matrix has no column rules, so lower.ts draws one the way * Word users build it by hand: the matrix split at the rule into side-by-side * matrices inside one delimiter object, with | as its separator. A double * rule `||` has no such spelling and is refused. */ parseColumnSpec() { const raw = this.readRawGroup(); const columns = []; const rules = []; for (let i = 0; i < raw.text.length; i++) { const ch = raw.text[i]; if (ch === "l") { columns.push("left"); continue; } if (ch === "c") { columns.push("center"); continue; } if (ch === "r") { columns.push("right"); continue; } if (/\s/.test(ch)) continue; if (ch === "\\" && raw.text[i + 1] === "|") continue; const at = { type: "char", value: ch, start: raw.start + i, end: raw.start + i + 1 }; if (ch === "|") { if (rules[rules.length - 1] === columns.length) { throw this.err( "unsupported-construct", `Double column rules ("||") are not supported.`, at, "Word can draw a single line between matrix columns, not a double one. Use a single |." ); } rules.push(columns.length); continue; } if (ch === "p" || ch === "m" || ch === "b") { throw this.err( "unsupported-construct", `Fixed-width array columns ("${ch}{...}") are not supported.`, at, "OMML columns size to their content. Use l, c or r instead." ); } throw this.err( "unsupported-construct", `"${ch}" is not a supported array column specifier.`, at, "Only l, c and r are supported." ); } if (columns.length === 0) { throw this.err( "unsupported-construct", "\\begin{array} needs a column spec, such as {ccc}.", { type: "char", value: "", start: raw.start, end: raw.end }, "Write \\begin{array}{cc} for a two-column array." ); } return { columns, rules }; } consumeEnd(expectedName) { const endTok = this.peek(); if (!isEnd(endTok)) { throw this.err("unclosed-environment", `Missing \\end{${expectedName}}.`, endTok); } this.advance(); const closingName = this.readBracedIdentifier("\\end"); if (closingName !== expectedName) { throw this.err( "unclosed-environment", `\\begin{${expectedName}} does not match \\end{${closingName}}.`, endTok, `Change \\end{${closingName}} to \\end{${expectedName}}.` ); } } parseMatrixBody(t, kind, envName, columns, rules = []) { const rows = []; const hlines = []; let current = []; const cellStop = (tok) => tok.type === "ampersand" || tok.type === "newline" || isEnd(tok) || tok.type === "eof"; for (; ; ) { if (current.length === 0) { for (let p2 = this.peek(); p2.type === "command" && ROW_RULES.has(p2.value); p2 = this.peek()) { this.advance(); if (hlines[hlines.length - 1] !== rows.length) hlines.push(rows.length); } } const cell = this.parseRow(cellStop); current.push(cell); const p = this.peek(); if (p.type === "ampersand") { this.advance(); continue; } if (p.type === "newline") { this.advance(); rows.push(current); current = []; continue; } if (isEnd(p)) { const only = current.length === 1 ? current[0] : null; const empty = only !== null && only.kind === "row" && only.children.length === 0; if (!(empty && rows.length > 0 && hlines.includes(rows.length))) rows.push(current); this.consumeEnd(envName); break; } throw this.err("unclosed-environment", `Missing \\end{${envName}}.`, p); } const end = this.tokens[Math.max(0, this.pos - 1)].end; const lines = hlines.length === 0 ? {} : { hlines }; if (columns === void 0) return { kind: "matrix", matrixKind: kind, rows, ...lines, start: t.start, end }; return rules.length === 0 ? { kind: "matrix", matrixKind: kind, rows, columns, ...lines, start: t.start, end } : { kind: "matrix", matrixKind: kind, rows, columns, rules, ...lines, start: t.start, end }; } /** * \begin{align}/\begin{gather} body. See ast.ts AlignNode / ir.ts IrEqArr * for the real limitation this runs into: OMML's m:eqArr has no native * "align every row at a shared column" behavior the way LaTeX's align * does, so each row here is rendered as its own left-to-right content — * correct per-row, but not vertically aligned at the `&` across rows. */ parseAlignBody(t, envName, alignPoints) { const rows = []; let current = []; const cellStop = (tok) => tok.type === "ampersand" || tok.type === "newline" || isEnd(tok) || tok.type === "eof"; for (; ; ) { const cell = this.parseRow(cellStop); current.push(cell); const p = this.peek(); if (p.type === "ampersand") { if (!alignPoints) { throw this.err("unexpected-token", `"&" is not valid in \\begin{${envName}} \u2014 gather has no alignment points (that's what align is for).`, p); } this.advance(); continue; } if (p.type === "newline") { this.advance(); rows.push(current); current = []; continue; } if (isEnd(p)) { rows.push(current); this.consumeEnd(envName); break; } throw this.err("unclosed-environment", `Missing \\end{${envName}}.`, p); } return { kind: "align", rows, alignPoints, start: t.start, end: this.tokens[Math.max(0, this.pos - 1)].end }; } parseCasesBody(t, envName) { const rows = []; const cellStop = (tok) => tok.type === "ampersand" || tok.type === "newline" || isEnd(tok) || tok.type === "eof"; for (; ; ) { const expr = this.parseRow(cellStop); let condition; if (this.peek().type === "ampersand") { this.advance(); condition = this.parseRow(cellStop); } rows.push({ expr, condition }); const p = this.peek(); if (p.type === "newline") { this.advance(); continue; } if (isEnd(p)) { this.consumeEnd(envName); break; } throw this.err("unclosed-environment", `Missing \\end{${envName}}.`, p); } return { kind: "cases", rows, start: t.start, end: this.tokens[Math.max(0, this.pos - 1)].end }; } /** Reads a raw {...} group directly from source (preserving whitespace), for \text{...} etc. */ readRawGroup() { const open = this.expect("lbrace", "after \\text"); let depth = 1; let i = open.end; const src = this.source; const start = i; while (i < src.length && depth > 0) { if (src[i] === "{") depth++; else if (src[i] === "}") { depth--; if (depth === 0) break; } i++; } if (depth !== 0) { throw this.err("unclosed-brace", "Missing closing brace.", this.peek(), "Add a matching '}'."); } const text = src.slice(start, i); const closeIndex = i + 1; while (this.pos < this.tokens.length - 1 && this.tokens[this.pos].start < closeIndex) { this.pos++; } return { text, start, end: closeIndex }; } }; function parseLatex(source) { return new Parser(source).parse(); } // ir/src/lower.ts init_define_L2W_CONFIG(); // ir/src/variants.ts init_define_L2W_CONFIG(); function buildAlphabetMap(base, exceptions = {}) { const map = {}; for (let i = 0; i < 26; i++) { const upper = String.fromCharCode(65 + i); const lower2 = String.fromCharCode(97 + i); map[upper] = String.fromCodePoint(exceptions[upper] ?? base.upperStart + i); if (base.lowerStart !== void 0) { map[lower2] = String.fromCodePoint(exceptions[lower2] ?? base.lowerStart + i); } } if (base.digitStart !== void 0) { for (let d = 0; d <= 9; d++) map[String(d)] = String.fromCodePoint(base.digitStart + d); } return map; } var MATHBB_MAP = buildAlphabetMap( { upperStart: 120120, lowerStart: 120146, digitStart: 120792 }, { C: 8450, H: 8461, N: 8469, P: 8473, Q: 8474, R: 8477, Z: 8484 } ); var MATHCAL_MAP = buildAlphabetMap( { upperStart: 119964, lowerStart: 119990 }, { B: 8492, E: 8496, F: 8497, H: 8459, I: 8464, L: 8466, M: 8499, R: 8475, e: 8495, g: 8458, o: 8500 } ); var MATHFRAK_MAP = buildAlphabetMap( { upperStart: 120068, lowerStart: 120094 }, { C: 8493, H: 8460, I: 8465, R: 8476, Z: 8488 } ); var MATHSF_MAP = buildAlphabetMap({ upperStart: 120224, lowerStart: 120250, digitStart: 120802 }); var MATHTT_MAP = buildAlphabetMap({ upperStart: 120432, lowerStart: 120458, digitStart: 120822 }); var VARIANT_MAPS = { mathbb: MATHBB_MAP, mathcal: MATHCAL_MAP, mathfrak: MATHFRAK_MAP, mathsf: MATHSF_MAP, mathtt: MATHTT_MAP }; function transliterate(text, variant) { const map = VARIANT_MAPS[variant]; let out = ""; for (const ch of text) out += map[ch] ?? ch; return out; } // ir/src/lower.ts var NARY_CHAR = { sum: "\u2211", prod: "\u220F", coprod: "\u2210", int: "\u222B", iint: "\u222C", iiint: "\u222D", oint: "\u222E", iiiint: "\u2A0C", oiint: "\u222F", oiiint: "\u2230", bigcup: "\u22C3", bigcap: "\u22C2", bigoplus: "\u2A01", bigotimes: "\u2A02", bigodot: "\u2A00", biguplus: "\u2A04", bigvee: "\u22C1", bigwedge: "\u22C0", bigsqcup: "\u2A06" }; var UNDER_OVER_OPS = /* @__PURE__ */ new Set(["sum", "prod", "coprod", "bigcup", "bigcap", "bigoplus", "bigotimes", "bigodot", "biguplus", "bigvee", "bigwedge", "bigsqcup"]); var UNDER_OVER_CHARS = new Set([...UNDER_OVER_OPS].map((op) => NARY_CHAR[op])); var ACCENT_CHAR = { hat: "\u0302", tilde: "\u0303", dot: "\u0307", ddot: "\u0308", check: "\u030C", breve: "\u0306", vec: "\u20D7", overrightarrow: "\u20D7", overleftarrow: "\u20D6", overleftrightarrow: "\u20E1" }; var X_ARROW_CHAR = { xrightarrow: "\u27F6", xleftarrow: "\u27F5", xleftrightarrow: "\u27F7", xRightarrow: "\u27F9", xLeftarrow: "\u27F8", xLeftrightarrow: "\u27FA", xrightleftharpoons: "\u21CC", xleftrightharpoons: "\u21CB", xmapsto: "\u27FC", xhookrightarrow: "\u21AA", xhookleftarrow: "\u21A9" }; var SPACING_TEXT = { thin: "\u2009", medium: "\u2005", thick: "\u2004", quad: "\u2003", qquad: "\u2003\u2003" }; var recording = null; function remember(node, span) { if (recording !== null && span !== void 0 && !recording.has(node)) recording.set(node, span); } function row(children2) { return { kind: "row", children: children2 }; } function matrixFromCases(node) { return { kind: "matrix", rows: node.rows.map((r) => r.condition ? [lower(r.expr), lower(r.condition)] : [lower(r.expr)]), columns: ["left", "left"] }; } function matrixWithRules(rows, columns, rules, hlines) { const lines = hlines === void 0 ? {} : { hlines }; const width = columns.length; const inner = [...new Set(rules)].filter((r) => r > 0 && r < width).sort((a, b) => a - b); const bounds = [0, ...inner, width]; const parts = []; for (let k = 0; k < bounds.length - 1; k++) { const from = bounds[k]; const to = bounds[k + 1]; const slice = rows.map((r) => Array.from({ length: to - from }, (_, i) => r[from + i] ?? row([]))); const cols = columns.slice(from, to); parts.push(cols.every((c) => c === "center") ? { kind: "matrix", rows: slice, ...lines } : { kind: "matrix", rows: slice, columns: cols, ...lines }); } const left = rules.includes(0) ? "|" : ""; const right = rules.includes(width) ? "|" : ""; return parts.length === 1 ? { kind: "delimited", left, right, parts } : { kind: "delimited", left, right, parts, sepChar: "|" }; } var MATRIX_DELIMS = { matrix: { left: "", right: "" }, pmatrix: { left: "(", right: ")" }, bmatrix: { left: "[", right: "]" }, Bmatrix: { left: "{", right: "}" }, vmatrix: { left: "|", right: "|" }, Vmatrix: { left: "\u2016", right: "\u2016" }, // `array` draws no delimiters of its own; \left ... \right supplies them. array: { left: "", right: "" } }; function mapSymbols(node, f) { const out = mapSymbolsOnce(node, f); if (recording !== null) remember(out, recording.get(node)); return out; } function mapSymbolsOnce(node, f) { switch (node.kind) { case "symbol": return f(node); case "row": return { ...node, children: node.children.map((c) => mapSymbols(c, f)) }; case "frac": return { ...node, numerator: mapSymbols(node.numerator, f), denominator: mapSymbols(node.denominator, f) }; case "radical": return { ...node, radicand: mapSymbols(node.radicand, f), index: node.index ? mapSymbols(node.index, f) : void 0 }; case "supersub": return { ...node, base: mapSymbols(node.base, f), sup: node.sup ? mapSymbols(node.sup, f) : void 0, sub: node.sub ? mapSymbols(node.sub, f) : void 0 }; case "limlow": return { ...node, base: mapSymbols(node.base, f), lower: mapSymbols(node.lower, f) }; case "nary": return { ...node, sub: node.sub ? mapSymbols(node.sub, f) : void 0, sup: node.sup ? mapSymbols(node.sup, f) : void 0, operand: mapSymbols(node.operand, f) }; case "delimited": return { ...node, parts: node.parts.map((p) => mapSymbols(p, f)) }; case "matrix": return { ...node, rows: node.rows.map((r) => r.map((c) => mapSymbols(c, f))) }; case "accent": return { ...node, base: mapSymbols(node.base, f) }; case "borderbox": case "groupchar": return { ...node, base: mapSymbols(node.base, f) }; case "limupp": return { ...node, base: mapSymbols(node.base, f), upper: mapSymbols(node.upper, f) }; case "prescript": return { ...node, base: mapSymbols(node.base, f), presup: node.presup ? mapSymbols(node.presup, f) : void 0, presub: node.presub ? mapSymbols(node.presub, f) : void 0 }; case "eqarr": return { ...node, rows: node.rows.map((r) => mapSymbols(r, f)) }; case "labeledarrow": return { ...node, above: node.above ? mapSymbols(node.above, f) : void 0, below: node.below ? mapSymbols(node.below, f) : void 0 }; default: { const exhaustive = node; throw new Error(`Unhandled IR node in mapSymbols: ${JSON.stringify(exhaustive)}`); } } } function applyUnicodeVariant(node, variant) { return mapSymbols(node, (s) => ({ kind: "symbol", text: transliterate(s.text, variant), italic: false, bold: s.bold })); } function applyBold(node) { return mapSymbols(node, (s) => ({ ...s, bold: true })); } function applyColor(node, color) { return mapSymbols(node, (s) => s.color !== void 0 ? s : { ...s, color }); } function lower(ast) { const ir = lowerNode(ast); remember(ir, { start: ast.start, end: ast.end }); return ir; } function lowerNode(ast) { switch (ast.kind) { case "row": return row(ast.children.map(lower)); case "symbol": { const italic = ast.class === "letter" || ast.class === "greek"; return { kind: "symbol", text: ast.text, italic }; } case "text": return { kind: "symbol", text: ast.text, italic: false }; case "spacing": return { kind: "symbol", text: SPACING_TEXT[ast.size] ?? " ", italic: false }; case "func": return { kind: "symbol", text: ast.name, italic: false }; case "frac": return { kind: "frac", numerator: lower(ast.numerator), denominator: lower(ast.denominator), noBar: false }; case "binom": return { kind: "delimited", left: "(", right: ")", parts: [{ kind: "frac", numerator: lower(ast.top), denominator: lower(ast.bottom), noBar: true }] }; case "sqrt": return { kind: "radical", radicand: lower(ast.radicand), index: ast.index ? lower(ast.index) : void 0 }; case "supsub": { if (ast.base.kind === "func" && ast.sub && !ast.sup && (ast.base.limits ?? LIMIT_STYLE_FUNCTIONS.has(ast.base.name))) { return { kind: "limlow", base: lower(ast.base), lower: lower(ast.sub) }; } if (ast.base.kind === "groupchar") { const base = lower(ast.base); if (ast.base.pos === "top" && ast.sup && !ast.sub) { return { kind: "limupp", base, upper: lower(ast.sup) }; } if (ast.base.pos === "bot" && ast.sub && !ast.sup) { return { kind: "limlow", base, lower: lower(ast.sub) }; } } return { kind: "supersub", base: lower(ast.base), sup: ast.sup ? lower(ast.sup) : void 0, sub: ast.sub ? lower(ast.sub) : void 0 }; } case "nary": { const chr = NARY_CHAR[ast.op] ?? "\u2211"; return { kind: "nary", chr, sub: ast.sub ? lower(ast.sub) : void 0, sup: ast.sup ? lower(ast.sup) : void 0, operand: lower(ast.operand), limitLocation: ast.limits ?? UNDER_OVER_OPS.has(ast.op) ? "undOvr" : "subSup" }; } case "delimited": { const parts = ast.parts.map(lower); if (parts.length === 1 && ast.sepChar === void 0) { const only = parts[0].kind === "row" && parts[0].children.length === 1 ? parts[0].children[0] : parts[0]; if (only.kind === "delimited" && only.left === "" && only.right === "" && only.sepChar === "|") { return { kind: "delimited", left: ast.left, right: ast.right, parts: only.parts, sepChar: "|" }; } } return { kind: "delimited", left: ast.left, right: ast.right, parts, sepChar: ast.sepChar }; } case "matrix": { const delims = MATRIX_DELIMS[ast.matrixKind] ?? { left: "", right: "" }; const rows = ast.rows.map((r) => r.map(lower)); if (ast.rules && ast.rules.length > 0 && ast.columns) return matrixWithRules(rows, ast.columns, ast.rules, ast.hlines); const lines = ast.hlines === void 0 ? {} : { hlines: ast.hlines }; const inner = ast.columns === void 0 ? { kind: "matrix", rows, ...lines } : { kind: "matrix", rows, columns: ast.columns, ...lines }; if (!delims.left && !delims.right) return inner; return { kind: "delimited", left: delims.left, right: delims.right, parts: [inner] }; } case "cases": return { kind: "delimited", left: "{", right: "", parts: [matrixFromCases(ast)] }; case "cancel": return { kind: "borderbox", base: lower(ast.base), strikeBLTR: ast.cancel === "forward" || ast.cancel === "cross", strikeTLBR: ast.cancel === "backward" || ast.cancel === "cross" }; case "groupchar": return { kind: "groupchar", chr: ast.chr, pos: ast.pos, base: lower(ast.base) }; case "boxed": return { kind: "borderbox", base: lower(ast.base), boxed: true }; case "color": return applyColor(lower(ast.content), ast.color); case "stack": return ast.pos === "top" ? { kind: "limupp", base: lower(ast.base), upper: lower(ast.label) } : { kind: "limlow", base: lower(ast.base), lower: lower(ast.label) }; case "accent": { const base = lower(ast.base); if (ast.accent === "bar") return { kind: "accent", base, bar: true }; if (ast.accent === "underline") return { kind: "accent", base, bar: true, under: true }; return { kind: "accent", base, char: ACCENT_CHAR[ast.accent] ?? "\u0302" }; } case "unsupported": return { kind: "symbol", text: `[unsupported: ${ast.construct}]`, italic: false }; case "fontvariant": { const content = lower(ast.content); if (ast.variant === "mathbf") return applyBold(mapSymbols(content, (s) => ({ ...s, italic: false }))); if (ast.variant === "boldsymbol") return applyBold(content); if (ast.variant === "upright") return mapSymbols(content, (s) => ({ ...s, italic: false })); if (ast.variant === "mathit") return mapSymbols(content, (s) => ({ ...s, italic: true })); return applyUnicodeVariant(content, ast.variant); } case "prescript": return { kind: "prescript", base: lower(ast.base), presup: ast.presup ? lower(ast.presup) : void 0, presub: ast.presub ? lower(ast.presub) : void 0 }; case "align": { const rows = ast.rows.map((cells2) => row(cells2.map(lower))); return { kind: "eqarr", rows, justify: ast.alignPoints ? "left" : "center" }; } case "tag": return row([]); case "labeledarrow": { const chr = ast.chr ?? X_ARROW_CHAR[ast.arrow] ?? "\u27F6"; return { kind: "labeledarrow", chr, above: ast.above ? lower(ast.above) : void 0, below: ast.below ? lower(ast.below) : void 0 }; } default: { const exhaustive = ast; throw new Error(`Unhandled AST node: ${JSON.stringify(exhaustive)}`); } } } // graphics/src/index.ts init_define_L2W_CONFIG(); // graphics/src/errors.ts init_define_L2W_CONFIG(); var GraphicsError = class extends Error { constructor(details) { super(details.message); this.name = "GraphicsError"; this.details = details; } /** The message as the task pane and the CLI both show it. */ toDisplayString() { const parts = [this.details.message]; if (this.details.suggestion) parts.push(this.details.suggestion); return parts.join(" "); } }; function fail(type, message, position, token, suggestion) { throw new GraphicsError({ type, message, position, token, suggestion }); } // graphics/src/gfx-parse.ts init_define_L2W_CONFIG(); // graphics/src/tokenizer.ts init_define_L2W_CONFIG(); function readBalanced(source, start, open, close) { let depth = 0; let i = start; while (i < source.length) { const ch = source[i]; if (ch === "\\") { i += 2; continue; } if (ch === open) depth++; else if (ch === close) { depth--; if (depth === 0) return { raw: source.slice(start + 1, i), end: i + 1 }; } else if (open !== "{" && ch === "{") { const inner = readBalanced(source, i, "{", "}"); i = inner.end; continue; } i++; } fail("syntax", `Unclosed "${open}" \u2014 no matching "${close}".`, start, open); } function tokenizeGraphics(source) { const out = []; const ends = []; let i = 0; while (i < source.length) { while (ends.length < out.length) ends.push(i); const ch = source[i]; if (/\s/.test(ch)) { i++; continue; } if (ch === "%") { while (i < source.length && source[i] !== "\n") i++; continue; } if (ch === "\\") { const rest = source.slice(i + 1); const letters = /^[A-Za-z@]+/.exec(rest); if (letters && letters[0] === "foreach") { const loop = readForeach(source, i); out.push(loop.token); i = loop.end; continue; } if (letters) { out.push({ kind: "command", name: letters[0], at: i }); i += 1 + letters[0].length; continue; } const next = source[i + 1]; if (next === void 0) fail("syntax", "The source ends with a lone backslash.", i, "\\"); out.push({ kind: "command", name: next, at: i }); i += 2; continue; } if (ch === "[") { const { raw, end } = readBalanced(source, i, "[", "]"); out.push({ kind: "options", raw, at: i }); i = end; continue; } if (ch === "{") { const { raw, end } = readBalanced(source, i, "{", "}"); out.push({ kind: "group", raw, at: i }); i = end; continue; } if (ch === "(") { const { raw, end } = readBalanced(source, i, "(", ")"); out.push({ kind: "coord", raw, at: i }); i = end; continue; } if (ch === ";") { out.push({ kind: "semi", at: i }); i++; continue; } if (source.startsWith("..", i)) { out.push({ kind: "pathop", value: "..", at: i }); i += 2; continue; } if (source.startsWith("--", i)) { out.push({ kind: "pathop", value: "--", at: i }); i += 2; continue; } if (source.startsWith("|-", i) || source.startsWith("-|", i)) { out.push({ kind: "pathop", value: source.slice(i, i + 2), at: i }); i += 2; continue; } if (/[A-Za-z0-9_.+-]/.test(ch)) { const start = i; while (i < source.length && /[A-Za-z0-9_.+-]/.test(source[i])) { if (source.startsWith("--", i) || source.startsWith("-|", i)) break; i++; } if (i === start) i++; out.push({ kind: "word", value: source.slice(start, i), at: start }); continue; } fail("syntax", `"${ch}" has no meaning here.`, i, ch); } while (ends.length < out.length) ends.push(i); out.push({ kind: "eof", at: source.length }); ends.push(source.length); return out.map((t, k) => ({ ...t, end: ends[k] })); } function readForeach(source, start) { let i = start + "\\foreach".length; const header = /^([\s\S]*?)\bin\s*(?=\{)/.exec(source.slice(i)); if (!header) fail("syntax", "\\foreach needs \\x in {list}.", start, "foreach"); let variables = header[1]; let options = ""; const bracket = variables.indexOf("["); if (bracket >= 0) { const { raw } = readBalanced(variables, bracket, "[", "]"); options = raw; variables = variables.slice(0, bracket); } i += header[0].length; const list = readBalanced(source, i, "{", "}"); i = list.end; while (i < source.length && /\s/.test(source[i])) i++; let body; let bodyAt; if (source[i] === "{") { const group = readBalanced(source, i, "{", "}"); body = group.raw; bodyAt = i + 1; i = group.end; } else { bodyAt = i; let depth = 0; let j = i; for (; j < source.length; j++) { const ch = source[j]; if (ch === "\\") { j++; continue; } if (ch === "{" || ch === "[" || ch === "(") depth++; else if (ch === "}" || ch === "]" || ch === ")") depth--; else if (ch === ";" && depth === 0) break; } if (j >= source.length) fail("syntax", 'The \\foreach body is missing its closing ";".', start, "foreach"); body = source.slice(i, j + 1); i = j + 1; } return { token: { kind: "foreach", variables: variables.trim(), options, list: list.raw, body, bodyAt, at: start }, end: i }; } // graphics/src/options.ts init_define_L2W_CONFIG(); function parseOptions(raw, base = 0) { const entries = []; let depth = 0; let start = 0; const push = (text, at) => { const trimmed = text.trim(); if (trimmed.length === 0) return; const offset = at + (text.length - text.trimStart().length); const eq = splitOnFirstTopLevel(trimmed, "="); if (eq === null) { entries.push({ key: trimmed, at: base + offset }); return; } entries.push({ key: eq.before.trim(), value: eq.after.trim(), at: base + offset }); }; for (let i = 0; i < raw.length; i++) { const ch = raw[i]; if (ch === "\\") { i++; continue; } if (ch === "{" || ch === "[" || ch === "(") depth++; else if (ch === "}" || ch === "]" || ch === ")") depth--; else if (ch === "," && depth === 0) { push(raw.slice(start, i), start); start = i + 1; } } push(raw.slice(start), start); return entries; } function splitOnFirstTopLevel(text, sep3) { let depth = 0; for (let i = 0; i < text.length; i++) { const ch = text[i]; if (ch === "\\") { i++; continue; } if (ch === "{" || ch === "[" || ch === "(") depth++; else if (ch === "}" || ch === "]" || ch === ")") depth--; else if (ch === sep3 && depth === 0) { return { before: text.slice(0, i), after: text.slice(i + 1) }; } } return null; } function optionValue(options, key) { let found; for (const entry of options) if (entry.key === key) found = entry.value ?? ""; return found; } function optionAt(options, key) { return options.find((e) => e.key === key)?.at ?? 0; } function unbrace(value) { const trimmed = value.trim(); return trimmed.startsWith("{") && trimmed.endsWith("}") ? trimmed.slice(1, -1) : trimmed; } function rejectUnsupported(options, supported, context) { for (const entry of options) { if (!supported.has(entry.key)) { fail( "unsupported-option", `"${entry.key}" is not an option this build understands on ${context}.`, entry.at, entry.key, `Supported here: ${[...supported].sort().join(", ")}.` ); } } } // graphics/src/expr.ts init_define_L2W_CONFIG(); var CONSTANTS = { pi: Math.PI, e: Math.E }; var DEG = Math.PI / 180; var FUNCTIONS = { // DEGREES, not radians. This is pgfmath's convention, and following it is // not a preference: `\addplot {sin(x)}` over domain 0:6.28 is a nearly // flat line in real pgfplots and a full period in radians, and both are // perfectly plausible-looking plots. See `deg` below for the idiom that // gets a mathematical sine. sin: { arity: 1, apply: ([x]) => Math.sin(x * DEG) }, cos: { arity: 1, apply: ([x]) => Math.cos(x * DEG) }, tan: { arity: 1, apply: ([x]) => Math.tan(x * DEG) }, asin: { arity: 1, apply: ([x]) => Math.asin(x) / DEG }, acos: { arity: 1, apply: ([x]) => Math.acos(x) / DEG }, atan: { arity: 1, apply: ([x]) => Math.atan(x) / DEG }, atan2: { arity: 2, apply: ([y, x]) => Math.atan2(y, x) / DEG }, sinh: { arity: 1, apply: ([x]) => Math.sinh(x) }, cosh: { arity: 1, apply: ([x]) => Math.cosh(x) }, tanh: { arity: 1, apply: ([x]) => Math.tanh(x) }, exp: { arity: 1, apply: ([x]) => Math.exp(x) }, ln: { arity: 1, apply: ([x]) => Math.log(x) }, log10: { arity: 1, apply: ([x]) => Math.log10(x) }, log2: { arity: 1, apply: ([x]) => Math.log2(x) }, sqrt: { arity: 1, apply: ([x]) => Math.sqrt(x) }, abs: { arity: 1, apply: ([x]) => Math.abs(x) }, floor: { arity: 1, apply: ([x]) => Math.floor(x) }, ceil: { arity: 1, apply: ([x]) => Math.ceil(x) }, round: { arity: 1, apply: ([x]) => Math.round(x) }, min: { arity: 2, apply: ([a, b]) => Math.min(a, b) }, max: { arity: 2, apply: ([a, b]) => Math.max(a, b) }, mod: { arity: 2, apply: ([a, b]) => a % b }, // Radians -> degrees and back. Because the trig functions above take // degrees, `sin(deg(x))` is how a .tex file asks for the sine of x // radians, and it is a common sight for exactly that reason. deg: { arity: 1, apply: ([x]) => x / DEG }, rad: { arity: 1, apply: ([x]) => x * DEG } }; var PLOT_VARIABLES = ["x", "y", "z"]; function tokenizeExpr(source, base) { const out = []; let i = 0; while (i < source.length) { const ch = source[i]; if (/\s/.test(ch)) { i++; continue; } if (/[0-9.]/.test(ch)) { const start = i; while (i < source.length && /[0-9.]/.test(source[i])) i++; if (i < source.length && /[eE]/.test(source[i]) && /[0-9+-]/.test(source[i + 1] ?? "")) { i += 2; while (i < source.length && /[0-9]/.test(source[i])) i++; } const text = source.slice(start, i); const value = Number(text); if (!Number.isFinite(value)) { fail("unsupported-expression", `"${text}" is not a number.`, base + start, text); } out.push({ kind: "num", value, at: base + start }); continue; } if (/[A-Za-z_]/.test(ch) || ch === "\\" && /[A-Za-z]/.test(source[i + 1] ?? "")) { const start = i; i++; while (i < source.length && /[A-Za-z0-9_]/.test(source[i])) i++; out.push({ kind: "name", value: source.slice(start, i), at: base + start }); continue; } if ("+-*/^(),".includes(ch)) { out.push({ kind: "op", value: ch, at: base + i }); i++; continue; } fail("unsupported-expression", `"${ch}" has no meaning in a plot expression.`, base + i, ch); } out.push({ kind: "eof", at: base + source.length }); return out; } var ExprParser = class { constructor(toks, variables) { this.toks = toks; this.variables = variables; this.pos = 0; } peek() { return this.toks[this.pos]; } advance() { const t = this.toks[this.pos]; if (this.pos < this.toks.length - 1) this.pos++; return t; } isOp(value) { const t = this.peek(); return t.kind === "op" && t.value === value; } expectOp(value, context) { if (!this.isOp(value)) { const t = this.peek(); fail( "unsupported-expression", `Expected "${value}" ${context}.`, t.at, t.kind === "eof" ? void 0 : String(t.value) ); } this.advance(); } parse() { const node = this.expr(); const t = this.peek(); if (t.kind !== "eof") { fail( "unsupported-expression", `Unexpected "${String(t.value)}" after the end of the expression.`, t.at, String(t.value) ); } return node; } expr() { let left = this.term(); for (; ; ) { if (this.isOp("+") || this.isOp("-")) { const op = this.advance().value; left = { kind: "binary", op, left, right: this.term() }; continue; } return left; } } term() { let left = this.unary(); for (; ; ) { if (this.isOp("*") || this.isOp("/")) { const op = this.advance().value; left = { kind: "binary", op, left, right: this.unary() }; continue; } return left; } } unary() { if (this.isOp("-")) { this.advance(); return { kind: "unary", op: "-", operand: this.unary() }; } if (this.isOp("+")) { this.advance(); return this.unary(); } return this.power(); } power() { const base = this.atom(); if (this.isOp("^")) { this.advance(); return { kind: "binary", op: "^", left: base, right: this.unary() }; } return base; } atom() { const t = this.peek(); if (t.kind === "num") { this.advance(); return { kind: "number", value: t.value }; } if (t.kind === "op" && t.value === "(") { this.advance(); const inner = this.expr(); this.expectOp(")", "to close a bracketed group"); return inner; } if (t.kind === "name") { this.advance(); const name = t.value; if (this.isOp("(")) { this.advance(); const args2 = []; if (!this.isOp(")")) { args2.push(this.expr()); while (this.isOp(",")) { this.advance(); args2.push(this.expr()); } } this.expectOp(")", `to close the arguments of "${name}"`); const fn = FUNCTIONS[name]; if (fn === void 0) { fail( "unknown-command", `"${name}" is not a function this build can plot.`, t.at, name, `Available functions: ${Object.keys(FUNCTIONS).sort().join(", ")}.` ); } if (args2.length !== fn.arity) { fail( "unsupported-expression", `"${name}" takes ${fn.arity} argument${fn.arity === 1 ? "" : "s"}, not ${args2.length}.`, t.at, name ); } return { kind: "call", name, args: args2 }; } if (this.variables.includes(name)) return { kind: "variable", name }; if (CONSTANTS[name] !== void 0) return { kind: "number", value: CONSTANTS[name] }; fail( "unknown-command", `"${name}" is not a variable or constant this build knows.`, t.at, name, `Plot variables are ${this.variables.join(", ")}; constants are ${Object.keys(CONSTANTS).join(", ")}.` ); } fail( "unsupported-expression", t.kind === "eof" ? "The expression ended early." : `Unexpected "${t.value}" in a plot expression.`, t.at, t.kind === "eof" ? void 0 : String(t.value) ); } }; function parseExpr(source, base = 0, variables = PLOT_VARIABLES) { return new ExprParser(tokenizeExpr(source, base), variables).parse(); } function evaluate(node, env) { switch (node.kind) { case "number": return node.value; case "variable": { const value = env[node.name]; if (value === void 0) { fail("unsupported-expression", `"${node.name}" has no value in this plot.`, 0, node.name); } return value; } case "unary": return -evaluate(node.operand, env); case "binary": { const a = evaluate(node.left, env); const b = evaluate(node.right, env); switch (node.op) { case "+": return a + b; case "-": return a - b; case "*": return a * b; case "/": return a / b; case "^": return Math.pow(a, b); } } // eslint-disable-next-line no-fallthrough -- every case above returns case "call": return FUNCTIONS[node.name].apply(node.args.map((a) => evaluate(a, env))); } } function evaluateSource(source, env = {}, base = 0) { return evaluate(parseExpr(source, base), env); } var FUNCTION_NAMES2 = Object.keys(FUNCTIONS).sort(); // graphics/src/gfx-parse.ts var GRAPHICS_ENVIRONMENTS = /* @__PURE__ */ new Set(["tikzpicture", "tkzpicture", "circuitikz"]); var TKZ_PREFIX = "tkz"; var NO_OPTIONS = []; var GraphicsParser = class { constructor(toks) { this.toks = toks; this.pos = 0; /** Where the last token taken ends. */ this.lastEnd = 0; } peek(offset = 0) { return this.toks[Math.min(this.pos + offset, this.toks.length - 1)]; } advance() { const t = this.toks[this.pos]; if (this.pos < this.toks.length - 1) this.pos++; this.lastEnd = t.end ?? t.at; return t; } isCommand(name, offset = 0) { const t = this.peek(offset); return t.kind === "command" && t.name === name; } /** An `[...]` immediately here, or an empty list. */ takeOptions() { const t = this.peek(); if (t.kind !== "options") return NO_OPTIONS; this.advance(); return parseOptions(t.raw, t.at + 1); } /** The `{name}` after \begin or \end. */ environmentName(after, at) { const t = this.peek(); if (t.kind !== "group") { fail("syntax", `\\${after} must be followed by an environment name in braces.`, at, after); } this.advance(); return t.raw.trim(); } /** Consumes the trailing `;` a TikZ statement ends with. */ endStatement(command, at) { const t = this.peek(); if (t.kind === "semi") { this.advance(); return; } if (t.kind === "eof") { fail("syntax", `\\${command} is missing its closing ";".`, at, command); } fail( "unknown-command", `\\${command} has a part this build does not understand before its ";".`, t.at, tokenText(t) ); } /** * A picture, given either its body or the whole environment. * * Both forms arrive in practice — the document pipeline hands over what it * found between `\begin` and `\end`, while the task pane and the tests hand * over what the user typed. Recognising the wrapper here rather than * stripping it first is what keeps every error offset pointing into the * source the caller actually holds. */ /** Statements to the end of the tokens: a \foreach body. */ parseBody() { return this.parseStatements(null); } parsePicture() { const first = this.peek(); const second = this.peek(1); const wrapped = first.kind === "command" && first.name === "begin" && second.kind === "group" && GRAPHICS_ENVIRONMENTS.has(second.raw.trim()); if (!wrapped) { const options2 = this.takeOptions(); return { options: options2, statements: this.parseStatements(null) }; } const name = second.raw.trim(); this.advance(); this.advance(); const options = this.takeOptions(); const statements = this.parseStatements(name); const rest = this.peek(); if (rest.kind !== "eof") { fail("syntax", `There is content after \\end{${name}}.`, rest.at, tokenText(rest)); } return { options, statements }; } /** * Statements up to `\end{until}`, or to end of input when `until` is null. */ parseStatements(until) { const out = []; for (; ; ) { const t = this.peek(); if (t.kind === "eof") { if (until !== null) fail("syntax", `Missing \\end{${until}}.`, t.at, until); return out; } if (t.kind === "command" && t.name === "end") { if (until === null) { fail("syntax", "\\end with no matching \\begin.", t.at, "end"); } this.advance(); const name = this.environmentName("end", t.at); if (name !== until) { fail("syntax", `\\begin{${until}} is closed by \\end{${name}}.`, t.at, name); } return out; } if (t.kind === "foreach") { this.advance(); const loop = { start: t.at, end: this.lastEnd }; out.push(...expandForeach(t).map((s) => fromLoop(s, loop))); continue; } if (t.kind === "command" && (t.name === "usetikzlibrary" || t.name === "ctikzset")) { this.advance(); if (this.peek().kind === "group") this.advance(); if (this.peek().kind === "semi") this.advance(); continue; } const statement = this.parseStatement(); out.push({ ...statement, src: { start: t.at, end: this.lastEnd } }); } } parseStatement() { const t = this.peek(); if (t.kind !== "command") { fail("syntax", `Expected a command, found "${tokenText(t)}".`, t.at, tokenText(t)); } if (t.name === "begin") { this.advance(); const name = this.environmentName("begin", t.at); if (name === "axis") return this.parseAxis(t.at, 2); if (name === "scope") { const options = this.takeOptions(); return { kind: "scope", options, body: this.parseStatements("scope"), at: t.at }; } if (name === "axis3d" || name === "axis3D") { fail("unknown-command", `\\begin{${name}} is not a pgfplots environment; 3D plots use \\begin{axis} with \\addplot3.`, t.at, name); } fail( "unknown-command", `\\begin{${name}} is not an environment this build draws.`, t.at, name, "Supported inside a picture: axis, scope." ); } if (t.name === "coordinate") return this.parseCoordinate(); if (t.name === "tikzset") { this.advance(); const group = this.peek(); if (group.kind !== "group") fail("syntax", "\\tikzset needs its styles in braces.", t.at, "tikzset"); this.advance(); if (this.peek().kind === "semi") this.advance(); return { kind: "tikzset", options: parseOptions(group.raw, group.at + 1), at: t.at }; } if (t.name === "addplot") { return this.parseAddPlot(); } if (t.name === "draw" || t.name === "path" || t.name === "fill" || t.name === "filldraw") { return this.parseDraw(); } if (t.name === "node") { return this.parseNode(); } if (t.name.startsWith(TKZ_PREFIX)) { return this.parseTkz(); } fail( "unknown-command", `\\${t.name} is not a drawing command this build implements.`, t.at, t.name, "Supported: \\draw, \\fill, \\filldraw, \\path, \\node, \\coordinate, \\foreach, \\tikzset, \\addplot, and scope and axis environments." ); } parseAxis(at, dimensions) { const options = this.takeOptions(); const statements = this.parseStatements("axis"); const body = []; for (const statement of statements) { if (statement.kind === "axis") { fail("unsupported-option", "An axis cannot hold another axis.", statement.at, "axis"); } if (statement.kind === "tkz") { fail( "unknown-command", `\\${statement.name} is a tkz-euclide command, which cannot be used inside an axis.`, statement.at, statement.name ); } if (statement.kind === "coordinate" || statement.kind === "scope" || statement.kind === "tikzset") { fail( "unsupported-option", `${statement.kind === "coordinate" ? "\\coordinate" : statement.kind === "scope" ? "A scope" : "\\tikzset"} can't be used inside an axis in this build.`, statement.at, statement.kind, "Inside an axis, use \\addplot, \\draw and \\node." ); } body.push(statement); } const plots = body.filter((s) => s.kind === "addplot"); const anyThree = plots.some((p) => p.dimensions === 3); const anyTwo = plots.some((p) => p.dimensions === 2); if (anyThree && anyTwo) { fail("unsupported-option", "An axis cannot mix \\addplot and \\addplot3 in this build \u2014 the two need different axis frames.", at); } return { kind: "axis", options, body, dimensions: anyThree ? 3 : dimensions, at }; } parseAddPlot() { const command = this.advance(); const suffix = this.peek(); const dimensions = suffix.kind === "word" && suffix.value === "3" ? 3 : 2; if (dimensions === 3) this.advance(); const name = dimensions === 3 ? "addplot3" : command.name; const options = this.takeOptions(); let data; const t = this.peek(); if (t.kind === "word" && t.value === "coordinates") { this.advance(); const group = this.peek(); if (group.kind !== "group") { fail("syntax", "\\addplot coordinates must be followed by a braced list of points.", t.at, "coordinates"); } this.advance(); data = { kind: "coordinates", points: parseCoordinateList(group.raw, group.at + 1), at: group.at }; } else if (t.kind === "group") { this.advance(); data = { kind: "expression", source: t.raw, at: t.at + 1 }; } else if (t.kind === "coord") { this.advance(); data = parseParametric(t.raw, t.at + 1, name); } else if (t.kind === "word" && (t.value === "table" || t.value === "file")) { fail( "unsupported-option", `\\addplot ${t.value} reads data from outside the document, which this build cannot do.`, t.at, t.value, "Write the points inline with \\addplot coordinates {...}." ); } else { fail( "syntax", `\\${name} needs {an expression}, ({x}, {y}), or coordinates {...}.`, t.at, tokenText(t) ); } const closedCycle = this.isCommand("closedcycle"); if (closedCycle) this.advance(); this.endStatement(name, command.at); return { kind: "addplot", dimensions, options, data, closedCycle, at: command.at }; } /** `+` or `++` right before a coordinate. */ takeRelative() { const t = this.peek(); if (t.kind === "word" && (t.value === "+" || t.value === "++") && this.peek(1).kind === "coord") { this.advance(); return t.value; } return ""; } atCoordinate() { const t = this.peek(); return t.kind === "coord" || t.kind === "word" && (t.value === "+" || t.value === "++") && this.peek(1).kind === "coord"; } takeCoord(what, at) { const relative = this.takeRelative(); const t = this.peek(); if (t.kind !== "coord") fail("syntax", `${what} must be followed by a coordinate in brackets, like (1,2).`, at, what); this.advance(); return { coord: { raw: t.raw, at: t.at + 1 }, relative }; } /** Options straight after a word (`to[…]`, `circle[…]`), or none. */ optionsHere() { return this.peek().kind === "options" ? this.takeOptions() : NO_OPTIONS; } parseDraw() { const command = this.advance(); const options = this.takeOptions(); const parts = []; let op = "move"; for (; ; ) { const t = this.peek(); if (this.atCoordinate()) { const { coord, relative } = this.takeCoord("A path", t.at); parts.push({ kind: "point", op, coord, relative }); op = "move"; continue; } if (t.kind === "pathop") { this.advance(); if (t.value === "..") { parts.push(this.parseCurve(t.at)); op = "move"; continue; } if (op !== "move") fail("syntax", `Two path operators in a row ("${op}" then "${t.value}").`, t.at, t.value); op = t.value; continue; } if (t.kind !== "word") break; if (t.value === "cycle") { this.advance(); parts.push({ kind: "cycle", at: t.at }); op = "move"; continue; } if (t.value === "to") { this.advance(); const opts = this.optionsHere(); const { coord, relative } = this.takeCoord("to", t.at); parts.push({ kind: "to", options: opts, to: coord, relative, at: t.at }); continue; } if (t.value === "rectangle") { this.advance(); const { coord, relative } = this.takeCoord("rectangle", t.at); parts.push({ kind: "rectangle", to: coord, relative }); continue; } if (t.value === "grid") { this.advance(); const opts = this.optionsHere(); const { coord, relative } = this.takeCoord("grid", t.at); parts.push({ kind: "grid", options: opts, to: coord, relative, at: t.at }); continue; } if (t.value === "circle" || t.value === "ellipse") { this.advance(); const opts = this.optionsHere(); const sized = opts.some((o) => o.key === "radius" || o.key === "x radius" || o.key === "y radius"); const size = !sized && this.peek().kind === "coord" ? this.advance() : null; parts.push(size ? { kind: "circle", options: opts, radius: size.raw, radiusAt: size.at + 1, at: t.at } : { kind: "circle", options: opts, radius: null, at: t.at }); continue; } if (t.value === "arc") { this.advance(); const opts = this.optionsHere(); const spec = opts.length === 0 && this.peek().kind === "coord" ? this.advance() : null; parts.push(spec ? { kind: "arc", options: opts, spec: spec.raw, specAt: spec.at + 1, at: t.at } : { kind: "arc", options: opts, spec: null, at: t.at }); continue; } if (t.value === "plot") { this.advance(); const opts = this.optionsHere(); const next = this.peek(); if (next.kind === "word" && next.value === "coordinates") { this.advance(); const group = this.peek(); if (group.kind !== "group") fail("syntax", "plot coordinates must be followed by a braced list of points.", next.at, "coordinates"); this.advance(); parts.push({ kind: "plot", options: opts, op: op === "move" ? "move" : "--", data: { coordinates: parseCoordinateList(group.raw, group.at + 1) }, at: t.at }); } else if (next.kind === "coord") { this.advance(); const pair = parseParametric(next.raw, next.at + 1, "plot"); parts.push({ kind: "plot", options: opts, op: op === "move" ? "move" : "--", data: { x: pair.x.source, y: pair.y.source }, at: t.at }); } else { fail("syntax", "plot needs coordinates {\u2026} or ({x}, {y}).", t.at, "plot"); } op = "move"; continue; } if (t.value === "node") { this.advance(); let opts = this.optionsHere(); let name = null; if (this.peek().kind === "coord") name = this.advance().raw.trim(); if (this.peek().kind === "options") opts = [...opts, ...this.takeOptions()]; const text = this.peek(); if (text.kind !== "group") fail("syntax", "A node on a path needs its text in braces: node {text}.", t.at, "node"); this.advance(); parts.push({ kind: "node", options: opts, name, text: text.raw, textAt: text.at + 1, at: t.at }); continue; } if (t.value === "coordinate") { this.advance(); this.optionsHere(); const name = this.peek(); if (name.kind !== "coord") fail("syntax", "coordinate needs a name in brackets: coordinate (A).", t.at, "coordinate"); this.advance(); parts.push({ kind: "coordinate", name: name.raw.trim(), at: t.at }); continue; } if (t.value === "pic") { fail("unknown-command", "pic is not something this build draws.", t.at, "pic", "Mark an angle with an arc: (B) ++(0:0.5) arc (0:40:0.5)."); } break; } if (parts.length === 0) { fail("syntax", `\\${command.name} has no coordinates.`, command.at, command.name); } this.endStatement(command.name, command.at); return { kind: "draw", command: command.name, options, parts, at: command.at }; } /** After `..`: `controls (a) and (b) .. (c)`. */ parseCurve(at) { const word = this.peek(); if (!(word.kind === "word" && word.value === "controls")) fail("syntax", 'A curve is written ".. controls (a) and (b) .. (c)".', at, ".."); this.advance(); const first = this.takeCoord("controls", at); let second; const and = this.peek(); if (and.kind === "word" && and.value === "and") { this.advance(); second = this.takeCoord("and", and.at); } const dots = this.peek(); if (!(dots.kind === "pathop" && dots.value === "..")) fail("syntax", `A curve's control points end with "..", then the end point.`, at, ".."); this.advance(); const end = this.takeCoord("..", dots.at); return { kind: "curve", c1: first.coord, c1Relative: first.relative, ...second ? { c2: second.coord } : {}, c2Relative: second?.relative ?? "", to: end.coord, relative: end.relative, at }; } parseNode() { const command = this.advance(); let options = this.takeOptions(); let name = null; if (this.peek().kind === "coord") name = this.advance().raw.trim(); if (this.peek().kind === "options") options = [...options, ...this.takeOptions()]; let place = { raw: "0,0", at: command.at }; let placed = false; const at = this.peek(); if (at.kind === "word" && at.value === "at") { this.advance(); const coord = this.peek(); if (coord.kind !== "coord") fail("syntax", "\\node at must be followed by a coordinate.", at.at, "at"); this.advance(); place = { raw: coord.raw, at: coord.at + 1 }; placed = true; if (this.peek().kind === "options") options = [...options, ...this.takeOptions()]; } const text = this.peek(); if (text.kind !== "group") { fail("syntax", "\\node needs its text in braces.", at.at, "node"); } this.advance(); this.endStatement("node", command.at); return { kind: "node", options, name, at_: place, placed, text: text.raw, textAt: text.at + 1, at: command.at }; } parseCoordinate() { const command = this.advance(); this.takeOptions(); const name = this.peek(); if (name.kind !== "coord") fail("syntax", "\\coordinate needs a name: \\coordinate (A) at (1,2);", command.at, "coordinate"); this.advance(); const at = this.peek(); if (!(at.kind === "word" && at.value === "at")) fail("syntax", "\\coordinate needs a position: \\coordinate (A) at (1,2);", name.at, "coordinate"); this.advance(); const coord = this.peek(); if (coord.kind !== "coord") fail("syntax", "\\coordinate ... at must be followed by a coordinate.", at.at, "at"); this.advance(); this.endStatement("coordinate", command.at); return { kind: "coordinate", name: name.raw.trim(), at_: { raw: coord.raw, at: coord.at + 1 }, at: command.at }; } parseTkz() { const command = this.advance(); const options = this.takeOptions(); const args2 = []; for (; ; ) { const t = this.peek(); if (t.kind === "coord") { this.advance(); args2.push({ kind: "coord", raw: t.raw, at: t.at + 1 }); continue; } if (t.kind === "group") { this.advance(); args2.push({ kind: "group", raw: t.raw, at: t.at + 1 }); continue; } break; } if (this.peek().kind === "semi") this.advance(); return { kind: "tkz", name: command.name, options, args: args2, at: command.at }; } }; function tokenText(t) { switch (t.kind) { case "command": return `\\${t.name}`; case "options": return `[${t.raw}]`; case "group": return `{${t.raw}}`; case "coord": return `(${t.raw})`; case "pathop": case "word": return t.value; case "semi": return ";"; case "eof": return "end of input"; case "foreach": return "\\foreach"; } } function parseParametric(raw, base, command) { const parts = []; let depth = 0; let start = 0; for (let i = 0; i <= raw.length; i++) { const ch = raw[i]; if (ch === "{" || ch === "(") depth++; else if (ch === "}" || ch === ")") depth--; else if (ch === "," && depth === 0 || i === raw.length) { const text = raw.slice(start, i); const lead = text.length - text.trimStart().length; const trimmed = text.trim(); const braced2 = trimmed.startsWith("{") && trimmed.endsWith("}"); parts.push({ source: braced2 ? trimmed.slice(1, -1) : trimmed, at: base + start + lead + (braced2 ? 1 : 0) }); start = i + 1; } } if (parts.length !== 2 || parts.some((p) => p.source.trim() === "")) { fail( "syntax", `\\${command} (\u2026) is a parametric plot and needs exactly two expressions: ({x}, {y}).`, base, `(${raw})` ); } return { kind: "parametric", x: parts[0], y: parts[1], at: base - 1 }; } function parseCoordinateList(raw, base) { const out = []; let i = 0; while (i < raw.length) { const ch = raw[i]; if (/\s/.test(ch)) { i++; continue; } if (ch !== "(") { fail("bad-coordinate", `Expected a coordinate "(x,y)", found "${ch}".`, base + i, ch); } const close = raw.indexOf(")", i); if (close < 0) fail("bad-coordinate", "A coordinate is missing its closing bracket.", base + i, "("); out.push({ raw: raw.slice(i + 1, close), at: base + i + 1 }); i = close + 1; } if (out.length === 0) fail("bad-coordinate", "A coordinate list cannot be empty.", base, "coordinates"); return out; } var FOREACH_LIMIT = 2e3; var foreachRuns = 0; function loopNumber(n) { return String(Math.round(n * 1e9) / 1e9); } function foreachValues(list, at) { const items = []; let depth = 0; let start = 0; for (let i = 0; i <= list.length; i++) { const ch = list[i]; if (ch === "{" || ch === "(") depth++; else if (ch === "}" || ch === ")") depth--; else if (ch === "," && depth === 0 || i === list.length) { const item = list.slice(start, i).trim(); if (item) items.push(item.startsWith("{") && item.endsWith("}") ? item.slice(1, -1) : item); start = i + 1; } } const out = []; for (let i = 0; i < items.length; i++) { if (items[i] !== "...") { out.push(items[i]); continue; } const first = Number(items[i - 2] ?? items[i - 1]); const second = Number(items[i - 1]); const last = Number(items[i + 1]); if (i === 0 || !Number.isFinite(second) || !Number.isFinite(last) || !Number.isFinite(first)) { fail("syntax", 'In \\foreach, "..." goes between numbers: {1,...,5} or {0,0.5,...,2}.', at, "..."); } const step2 = i >= 2 && items[i - 2] !== void 0 && Number.isFinite(Number(items[i - 2])) ? second - first : last >= second ? 1 : -1; if (step2 === 0 || Math.sign(step2) !== Math.sign(last - second || step2)) fail("syntax", "This \\foreach range never reaches its end.", at, "..."); for (let v = second + step2; step2 > 0 ? v < last - 1e-9 : v > last + 1e-9; v += step2) { out.push(loopNumber(v)); if (out.length > FOREACH_LIMIT) break; } } return out; } function substitute(text, name, value) { return text.replace(new RegExp(`\\\\${name}(?![A-Za-z@])`, "g"), value); } function fromLoop(s, loop) { if (s.kind === "scope") return { ...s, src: loop, fromLoop: true, body: s.body.map((b) => fromLoop(b, loop)) }; if (s.kind === "axis") return { ...s, src: loop, fromLoop: true, body: s.body.map((b) => fromLoop(b, loop)) }; return { ...s, src: loop, fromLoop: true }; } function expandForeach(loop) { const names = loop.variables.split("/").map((v) => v.trim().replace(/^\\/, "")); if (names.some((n) => !/^[A-Za-z@]+$/.test(n))) fail("syntax", "\\foreach variables are written \\x, or \\x/\\y.", loop.at, loop.variables); const options = parseOptions(loop.options, loop.at); let count = null; const evaluations = []; for (const o of options) { if (o.key === "count" && o.value) { const m = /^\\([A-Za-z@]+)(?:\s+from\s+(-?\d+))?$/.exec(o.value.trim()); if (!m) fail("syntax", "count is written count=\\i (or count=\\i from 0).", o.at, o.value); count = { name: m[1], from: m[2] === void 0 ? 1 : Number(m[2]) }; } else if (o.key === "evaluate" && o.value) { const m = /^\\([A-Za-z@]+)\s+as\s+\\([A-Za-z@]+)\s+using\s+([\s\S]+)$/.exec(o.value.trim()); if (!m) fail("syntax", "evaluate is written evaluate=\\x as \\y using \\x*2.", o.at, o.value); evaluations.push({ from: m[1], name: m[2], using: m[3].trim() }); } else { fail("unsupported-option", `"${o.key}" is not a \\foreach option this build understands.`, o.at, o.key, "Supported: count, evaluate."); } } const out = []; foreachValues(loop.list, loop.at).forEach((item, index) => { if (++foreachRuns > FOREACH_LIMIT) fail("unsupported-option", `\\foreach would run more than ${FOREACH_LIMIT} times in one picture.`, loop.at, "foreach"); const parts = item.split("/").map((p) => p.trim()); let body = loop.body; const values = names.map((n, i) => [n, parts[Math.min(i, parts.length - 1)]]); if (count) values.push([count.name, String(count.from + index)]); for (const e of evaluations) { const input = values.find(([n]) => n === e.from)?.[1] ?? "0"; values.push([e.name, loopNumber(evaluateSource(substitute(e.using, e.from, `(${input})`).replace(/^\{|\}$/g, ""), {}, loop.at))]); } for (const [n, v] of [...values].sort((a, b) => b[0].length - a[0].length)) body = substitute(body, n, v); const tokens = tokenizeGraphics(body).map((t) => ({ ...t, at: t.at + loop.bodyAt })); out.push(...new GraphicsParser(tokens).parseBody()); }); return out; } function parseGraphics(source) { foreachRuns = 0; return new GraphicsParser(tokenizeGraphics(source)).parsePicture(); } // graphics/src/coords.ts init_define_L2W_CONFIG(); function boundsOf(points) { if (points.length === 0) return { minX: 0, minY: 0, maxX: 1, maxY: 1 }; let minX = Infinity; let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity; for (const p of points) { minX = Math.min(minX, p.x); minY = Math.min(minY, p.y); maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y); } if (maxX - minX < 1) { const mid = (minX + maxX) / 2; minX = mid - 0.5; maxX = mid + 0.5; } if (maxY - minY < 1) { const mid = (minY + maxY) / 2; minY = mid - 0.5; maxY = mid + 0.5; } return { minX, minY, maxX, maxY }; } // graphics/src/axis.ts init_define_L2W_CONFIG(); // graphics/src/label-text.ts init_define_L2W_CONFIG(); function segments(label) { const out = []; let i = 0; let literal = ""; while (i < label.length) { const ch = label[i]; if (ch === "\\" && label[i + 1] === "$") { literal += "$"; i += 2; continue; } if (ch === "$") { const close = label.indexOf("$", i + 1); if (close < 0) { literal += "$"; i++; continue; } if (literal.length > 0) { out.push({ math: false, text: literal }); literal = ""; } out.push({ math: true, text: label.slice(i + 1, close) }); i = close + 1; continue; } literal += ch; i++; } if (literal.length > 0) out.push({ math: false, text: literal }); return out; } function runsFromIr(node, baseline, offset) { switch (node.kind) { case "row": return node.children.flatMap((c) => runsFromIr(c, baseline, offset)); case "symbol": return node.text.length === 0 ? [] : [{ text: node.text, baseline, italic: node.italic }]; case "supersub": { if (baseline !== "normal") { fail( "unsupported-expression", "A label can raise or lower text once, but not a script on a script.", offset, void 0, "Simplify the label, or put the expression in the surrounding text instead." ); } const out = [...runsFromIr(node.base, "normal", offset)]; if (node.sub) out.push(...runsFromIr(node.sub, "sub", offset)); if (node.sup) out.push(...runsFromIr(node.sup, "sup", offset)); return out; } default: fail( "unsupported-expression", `A label cannot contain a ${describe(node.kind)} \u2014 a plot label is a single line of text.`, offset, node.kind, "Use a simpler label, or place the expression in the document text near the figure." ); } } function describe(kind) { switch (kind) { case "frac": return "fraction"; case "radical": return "radical"; case "matrix": return "matrix"; case "nary": return "large operator"; case "delimited": return "bracketed group"; case "accent": return "accented symbol"; default: return kind; } } function labelRuns(label, offset = 0) { const out = []; for (const segment of segments(label)) { if (!segment.math) { const command = /\\[A-Za-z]+/.exec(segment.text); if (command) { fail( "unknown-command", `${command[0]} in a label's text is not drawn: only plain text and $...$ maths are.`, offset, command[0], command[0] === "\\chemfig" ? "Draw a structure with \\chemfig on its own, or a reaction with \\schemestart ... \\schemestop, not inside a TikZ node." : "Write plain text, or put maths between $...$." ); } if (segment.text.length > 0) out.push({ text: segment.text, baseline: "normal", italic: false }); continue; } if (segment.text.trim().length === 0) continue; out.push(...runsFromIr(lower(parseLatex(segment.text)), "normal", offset)); } return out; } function textItem(label, options) { const item = { kind: "text", at: options.at, runs: labelRuns(label, options.offset ?? 0), anchor: options.anchor, baseline: options.baseline, fontSize: options.fontSize, color: options.color }; return options.rotate === void 0 ? item : { ...item, rotate: options.rotate }; } // graphics/src/axis.ts var PLOT_WIDTH = 360; var PLOT_HEIGHT = 260; var MARGIN = { top: 16, right: 16, bottom: 40, left: 48 }; var AXIS_WIDTH = PLOT_WIDTH + MARGIN.left + MARGIN.right; var AXIS_HEIGHT = PLOT_HEIGHT + MARGIN.top + MARGIN.bottom; var INNER_MARGIN = 12; var TITLE_ROOM = 22; function axisLayout(lines, hasTitle) { if (lines === "box" || lines === "left") { return { margin: MARGIN, plotWidth: PLOT_WIDTH, plotHeight: PLOT_HEIGHT }; } const margin = { top: hasTitle ? TITLE_ROOM : INNER_MARGIN, right: INNER_MARGIN, bottom: INNER_MARGIN, left: INNER_MARGIN }; return { margin, plotWidth: AXIS_WIDTH - margin.left - margin.right, plotHeight: AXIS_HEIGHT - margin.top - margin.bottom }; } var BOX_LAYOUT = axisLayout("box", false); var AXIS_COLOR = "#333333"; var GRID_COLOR = "#cccccc"; var LABEL_SIZE = 11; var TICK_SIZE = 10; var AXIS_STROKE = { color: AXIS_COLOR, width: 1 }; var GRID_STROKE = { color: GRID_COLOR, width: 0.6 }; var SUPPORTED_AXIS_OPTIONS = /* @__PURE__ */ new Set([ "xmin", "xmax", "ymin", "ymax", "zmin", "zmax", "xlabel", "ylabel", "zlabel", "title", "grid", "xtick", "ytick", "ztick", "width", "height", "view", "scale only axis", "axis lines", "axis line style", "enlargelimits", "samples", "domain" ]); function numberOption(options, key, fallback) { const raw = optionValue(options, key); if (raw === void 0 || raw.trim() === "") return fallback; return evaluateSource(unbrace(raw), {}, 0); } function readRange(options, axis, at, fallback) { const min = optionValue(options, `${axis}min`); const max = optionValue(options, `${axis}max`); if (min === void 0 || max === void 0) { if (fallback) return fallback; fail( "unsupported-option", `The axis does not give ${axis}min and ${axis}max, and this build does not infer limits from the data.`, at, `${axis}min`, `Add ${axis}min and ${axis}max to the axis options.` ); } const lo = numberOption(options, `${axis}min`, 0); const hi = numberOption(options, `${axis}max`, 1); if (!(hi > lo)) { fail("unsupported-option", `${axis}max must be greater than ${axis}min.`, at, `${axis}max`); } return { min: lo, max: hi }; } function buildFrame(x, y, layout = BOX_LAYOUT) { const { margin, plotWidth, plotHeight } = layout; const sx = plotWidth / (x.max - x.min); const sy = plotHeight / (y.max - y.min); const toDevice = (dx, dy) => ({ x: margin.left + (dx - x.min) * sx, // Device y grows downward; data y grows upward. y: margin.top + plotHeight - (dy - y.min) * sy }); const toData = (p) => ({ x: x.min + (p.x - margin.left) / sx, y: y.min + (margin.top + plotHeight - p.y) / sy }); const baselineValue = Math.min(Math.max(0, y.min), y.max); return { x, y, layout, toDevice, toData, baselineY: toDevice(x.min, baselineValue).y, baselineValue }; } function defaultTicks(range) { const span = range.max - range.min; const rough = span / 6; const magnitude = Math.pow(10, Math.floor(Math.log10(rough))); const step2 = [1, 2, 5, 10].map((m) => m * magnitude).find((s) => span / s <= 8) ?? magnitude * 10; const ticks = []; const first = Math.ceil(range.min / step2) * step2; for (let v = first; v <= range.max + step2 * 1e-9; v += step2) { ticks.push(Number(v.toFixed(10))); } return ticks; } function explicitTicks(options, key) { const raw = optionValue(options, key); if (raw === void 0) return null; const inner = unbrace(raw).trim(); if (inner === "" || inner === "\\empty") return []; return inner.split(",").map((part) => evaluateSource(part.trim())); } function ticksFor(options, range, key) { return explicitTicks(options, key) ?? defaultTicks(range); } function formatTick(value) { if (Object.is(value, -0)) return "0"; const rounded = Number(value.toFixed(6)); return String(rounded); } function readGrid(options, at) { const grid = optionValue(options, "grid"); if (grid === void 0) return "none"; const value = unbrace(grid).trim(); if (value === "none" || value === "false") return "none"; if (value === "major" || value === "" || value === "true") return "major"; if (value === "both" || value === "minor") return "both"; fail("unsupported-option", `grid=${value} is not supported; use none, major or both.`, at, value); } function readLines(options, at) { const raw = optionValue(options, "axis lines"); if (raw === void 0) return "box"; const value = unbrace(raw).trim(); if (value === "box") return "box"; if (value === "left") return "left"; if (value === "middle" || value === "center") return "middle"; if (value === "none") return "none"; fail("unsupported-option", `axis lines=${value} is not supported; use box, left, middle, center or none.`, at, value); } function readFrameOptions(options, at) { rejectUnsupported(options, SUPPORTED_AXIS_OPTIONS, "an axis"); return { grid: readGrid(options, at), lines: readLines(options, at) }; } function drawAxis(frame2, options, frameOptions, at) { if (frameOptions.lines === "middle" || frameOptions.lines === "none") { return drawInnerAxis(frame2, options, frameOptions, at); } const items = []; const xTicks = ticksFor(options, frame2.x, "xtick"); const yTicks = ticksFor(options, frame2.y, "ytick"); if (frameOptions.grid !== "none") { for (const value of xTicks) { const top = frame2.toDevice(value, frame2.y.max); const bottom = frame2.toDevice(value, frame2.y.min); items.push({ kind: "path", points: [top, bottom], closed: false, stroke: GRID_STROKE }); } for (const value of yTicks) { const left = frame2.toDevice(frame2.x.min, value); const right = frame2.toDevice(frame2.x.max, value); items.push({ kind: "path", points: [left, right], closed: false, stroke: GRID_STROKE }); } } if (frameOptions.lines === "left") { const origin = frame2.toDevice(frame2.x.min, frame2.y.min); const xEnd = frame2.toDevice(frame2.x.max, frame2.y.min); const yEnd = frame2.toDevice(frame2.x.min, frame2.y.max); items.push({ kind: "path", points: [origin, xEnd], closed: false, stroke: AXIS_STROKE }); items.push({ kind: "path", points: [origin, yEnd], closed: false, stroke: AXIS_STROKE }); items.push(axisArrow(origin, xEnd), axisArrow(origin, yEnd)); } else { const corners = [ frame2.toDevice(frame2.x.min, frame2.y.min), frame2.toDevice(frame2.x.max, frame2.y.min), frame2.toDevice(frame2.x.max, frame2.y.max), frame2.toDevice(frame2.x.min, frame2.y.max) ]; items.push({ kind: "path", points: corners, closed: true, stroke: AXIS_STROKE }); } for (const value of xTicks) { const base = frame2.toDevice(value, frame2.y.min); items.push({ kind: "path", points: [base, { x: base.x, y: base.y - 4 }], closed: false, stroke: AXIS_STROKE }); items.push({ kind: "text", at: { x: base.x, y: base.y + 6 }, runs: [{ text: formatTick(value), baseline: "normal", italic: false }], anchor: "middle", baseline: "top", fontSize: TICK_SIZE, color: AXIS_COLOR }); } for (const value of yTicks) { const base = frame2.toDevice(frame2.x.min, value); items.push({ kind: "path", points: [base, { x: base.x + 4, y: base.y }], closed: false, stroke: AXIS_STROKE }); items.push({ kind: "text", at: { x: base.x - 6, y: base.y }, runs: [{ text: formatTick(value), baseline: "normal", italic: false }], anchor: "end", baseline: "middle", fontSize: TICK_SIZE, color: AXIS_COLOR }); } const xLabel = optionValue(options, "xlabel"); if (xLabel !== void 0) { items.push( textItem(unbrace(xLabel), { at: { x: MARGIN.left + PLOT_WIDTH / 2, y: AXIS_HEIGHT - 6 }, anchor: "middle", baseline: "bottom", fontSize: LABEL_SIZE, color: AXIS_COLOR, offset: at }) ); } const yLabel = optionValue(options, "ylabel"); if (yLabel !== void 0) { items.push( textItem(unbrace(yLabel), { at: { x: 12, y: MARGIN.top + PLOT_HEIGHT / 2 }, anchor: "middle", baseline: "middle", fontSize: LABEL_SIZE, color: AXIS_COLOR, // Read bottom-to-top, as an axis label is. rotate: -90, offset: at }) ); } const title = optionValue(options, "title"); if (title !== void 0) { items.push( textItem(unbrace(title), { at: { x: MARGIN.left + PLOT_WIDTH / 2, y: 4 }, anchor: "middle", baseline: "top", fontSize: LABEL_SIZE + 1, color: AXIS_COLOR, offset: at }) ); } return items; } function axisArrow(from, to) { const dx = to.x - from.x; const dy = to.y - from.y; const length2 = Math.hypot(dx, dy) || 1; const ux = dx / length2; const uy = dy / length2; const size = 7; const half = 3; return { kind: "path", points: [ { x: to.x + ux * 2, y: to.y + uy * 2 }, { x: to.x - ux * size - uy * half, y: to.y - uy * size + ux * half }, { x: to.x - ux * size + uy * half, y: to.y - uy * size - ux * half } ], closed: true, fill: { color: AXIS_COLOR, opacity: 1 } }; } function crossing(range) { return Math.min(Math.max(0, range.min), range.max); } function drawInnerAxis(frame2, options, frameOptions, at) { const items = []; const xTicks = ticksFor(options, frame2.x, "xtick"); const yTicks = ticksFor(options, frame2.y, "ytick"); const { margin, plotWidth, plotHeight } = frame2.layout; const left = margin.left; const top = margin.top; const right = left + plotWidth; const bottom = top + plotHeight; if (frameOptions.grid !== "none") { for (const value of xTicks) { items.push({ kind: "path", points: [frame2.toDevice(value, frame2.y.max), frame2.toDevice(value, frame2.y.min)], closed: false, stroke: GRID_STROKE }); } for (const value of yTicks) { items.push({ kind: "path", points: [frame2.toDevice(frame2.x.min, value), frame2.toDevice(frame2.x.max, value)], closed: false, stroke: GRID_STROKE }); } } if (frameOptions.lines === "middle") { const x0 = crossing(frame2.x); const y0 = crossing(frame2.y); const axisY = frame2.toDevice(0, y0).y; const axisX = frame2.toDevice(x0, 0).x; const xFrom = { x: left, y: axisY }; const xTo = { x: right, y: axisY }; const yFrom = { x: axisX, y: bottom }; const yTo = { x: axisX, y: top }; items.push({ kind: "path", points: [xFrom, xTo], closed: false, stroke: AXIS_STROKE }); items.push({ kind: "path", points: [yFrom, yTo], closed: false, stroke: AXIS_STROKE }); items.push(axisArrow(xFrom, xTo), axisArrow(yFrom, yTo)); const xLabelsBelow = bottom - axisY > 16; const yLabelsLeft = axisX - left > 26; const throughOrigin = x0 === 0 && y0 === 0; const label = (text, p, anchor, baseline) => ({ kind: "text", at: p, runs: [{ text, baseline: "normal", italic: false }], anchor, baseline, fontSize: TICK_SIZE, color: AXIS_COLOR }); for (const value of xTicks) { const p = frame2.toDevice(value, y0); if (p.x > right - 10 || p.x < left + 2) continue; if (throughOrigin && value === 0) continue; items.push({ kind: "path", points: [{ x: p.x, y: p.y - 3 }, { x: p.x, y: p.y + 3 }], closed: false, stroke: AXIS_STROKE }); items.push(label(formatTick(value), { x: p.x, y: xLabelsBelow ? p.y + 5 : p.y - 5 }, "middle", xLabelsBelow ? "top" : "bottom")); } for (const value of yTicks) { const p = frame2.toDevice(x0, value); if (p.y < top + 10 || p.y > bottom - 2) continue; if (throughOrigin && value === 0) continue; items.push({ kind: "path", points: [{ x: p.x - 3, y: p.y }, { x: p.x + 3, y: p.y }], closed: false, stroke: AXIS_STROKE }); items.push(label(formatTick(value), { x: yLabelsLeft ? p.x - 5 : p.x + 5, y: p.y }, yLabelsLeft ? "end" : "start", "middle")); } if (throughOrigin) items.push(label("0", { x: axisX - 4, y: axisY + 4 }, "end", "top")); const xLabel = optionValue(options, "xlabel"); if (xLabel !== void 0) { items.push( textItem(unbrace(xLabel), { at: { x: right - 4, y: axisY - 6 }, anchor: "end", baseline: "bottom", fontSize: LABEL_SIZE, color: AXIS_COLOR, offset: at }) ); } const yLabel = optionValue(options, "ylabel"); if (yLabel !== void 0) { items.push( textItem(unbrace(yLabel), { at: { x: axisX + 8, y: top + 2 }, anchor: "start", baseline: "top", fontSize: LABEL_SIZE, color: AXIS_COLOR, offset: at }) ); } } const title = optionValue(options, "title"); if (title !== void 0) { items.push( textItem(unbrace(title), { at: { x: left + plotWidth / 2, y: 4 }, anchor: "middle", baseline: "top", fontSize: LABEL_SIZE + 1, color: AXIS_COLOR, offset: at }) ); } return items; } // graphics/src/addplot.ts init_define_L2W_CONFIG(); // graphics/src/style.ts init_define_L2W_CONFIG(); // graphics/src/colors.ts init_define_L2W_CONFIG(); var NAMED = { red: [255, 0, 0], green: [0, 255, 0], blue: [0, 0, 255], cyan: [0, 255, 255], magenta: [255, 0, 255], yellow: [255, 255, 0], black: [0, 0, 0], gray: [128, 128, 128], grey: [128, 128, 128], white: [255, 255, 255], darkgray: [64, 64, 64], lightgray: [191, 191, 191], brown: [191, 128, 64], lime: [191, 255, 0], olive: [128, 128, 0], orange: [255, 128, 0], pink: [255, 191, 191], purple: [191, 0, 64], teal: [0, 128, 128], violet: [128, 0, 128] }; var hex = (n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, "0"); function mix(a, b, percent) { const t = percent / 100; return `#${hex(a[0] * t + b[0] * (1 - t))}${hex(a[1] * t + b[1] * (1 - t))}${hex(a[2] * t + b[2] * (1 - t))}`; } function resolveColor(expression, at) { const text = expression.trim(); if (text.length === 0) fail("unsupported-option", "A colour was given with no value.", at); if (/^#[0-9a-fA-F]{6}$/.test(text)) return text.toLowerCase(); const rgb = /^\{?\s*rgb\s*,\s*255\s*:\s*red\s*,\s*(\d+)\s*;\s*green\s*,\s*(\d+)\s*;\s*blue\s*,\s*(\d+)\s*\}?$/.exec(text); if (rgb) return `#${hex(Number(rgb[1]))}${hex(Number(rgb[2]))}${hex(Number(rgb[3]))}`; const parts = text.split("!").map((p) => p.trim()); const base = NAMED[parts[0].toLowerCase()]; if (base === void 0) { fail( "unsupported-option", `"${parts[0]}" is not a colour this build knows.`, at, parts[0], `Known colours: ${Object.keys(NAMED).sort().join(", ")}.` ); } if (parts.length === 1) return `#${hex(base[0])}${hex(base[1])}${hex(base[2])}`; const percent = Number(parts[1]); if (!Number.isFinite(percent) || percent < 0 || percent > 100) { fail("unsupported-option", `"${parts[1]}" is not a percentage between 0 and 100.`, at, parts[1]); } const otherName = parts[2] ?? "white"; const other = NAMED[otherName.toLowerCase()]; if (other === void 0) { fail("unsupported-option", `"${otherName}" is not a colour this build knows.`, at, otherName); } if (parts.length > 3) { fail("unsupported-option", `The colour expression "${text}" is more complex than this build supports.`, at, text); } return mix(base, other, percent); } var COLOR_NAMES = Object.keys(NAMED).sort(); // graphics/src/style.ts var COLOR_NAME_SET = new Set(COLOR_NAMES); function isColorExpression(entry) { if (entry.value !== void 0) return false; if (/^#[0-9a-fA-F]{6}$/.test(entry.key)) return true; return COLOR_NAME_SET.has(entry.key.split("!")[0].trim().toLowerCase()); } function currentColor(options) { let color; const rest = []; for (const entry of options) { if (isColorExpression(entry)) color = resolveColor(entry.key, entry.at); else rest.push(entry); } return { color, rest }; } var NAMED_WIDTHS = [ ["ultra thin", 0.4], ["very thin", 0.6], ["thin", 0.8], ["semithick", 1], ["thick", 1.6], ["very thick", 2.4], ["ultra thick", 3.2] ]; var DEFAULT_LINE_WIDTH = 1.2; var WIDTH_OPTION_NAMES = NAMED_WIDTHS.map(([name]) => name); var DASH_OPTION_NAMES = ["solid", "dashed", "dotted", "densely dashed", "loosely dashed"]; function readLineWidth(options, fallback = DEFAULT_LINE_WIDTH) { let width = fallback; for (const entry of options) { const named = NAMED_WIDTHS.find(([name]) => name === entry.key); if (named) width = named[1]; } const explicit = optionValue(options, "line width"); if (explicit !== void 0) { const parsed = Number.parseFloat(unbrace(explicit)); if (!Number.isFinite(parsed) || parsed <= 0) { fail("unsupported-option", `line width="${explicit}" is not a positive length.`, optionAt(options, "line width"), explicit); } width = parsed; } return width; } function readDash(options) { let dash; for (const entry of options) { if (entry.key === "solid") dash = void 0; else if (entry.key === "dashed") dash = [4, 3]; else if (entry.key === "densely dashed") dash = [3, 1.5]; else if (entry.key === "loosely dashed") dash = [6, 4]; else if (entry.key === "dotted") dash = [1, 2]; } return dash; } function readStroke(options, defaultColor, drawn = true) { const raw = optionValue(options, "draw") ?? optionValue(options, "color"); if (raw !== void 0 && unbrace(raw).trim() === "none") return void 0; if (!drawn && raw === void 0) return void 0; const color = raw === void 0 || raw.trim() === "" ? defaultColor : resolveColor(unbrace(raw), optionAt(options, "draw")); const width = readLineWidth(options); const dash = readDash(options); return dash === void 0 ? { color, width } : { color, width, dash }; } function readOpacity(options, key) { const raw = optionValue(options, key); if (raw === void 0) return void 0; const value = Number(unbrace(raw)); if (!Number.isFinite(value) || value < 0 || value > 1) { fail("unsupported-option", `${key} must be between 0 and 1, not "${raw}".`, optionAt(options, key), raw); } return value; } function fillOpacity(options) { return readOpacity(options, "fill opacity") ?? readOpacity(options, "opacity"); } function readFill(options) { const raw = optionValue(options, "fill"); if (raw === void 0) return void 0; const text = unbrace(raw).trim(); if (text === "none") return void 0; const opacity = readOpacity(options, "fill opacity") ?? readOpacity(options, "opacity") ?? 1; return { color: resolveColor(text, optionAt(options, "fill")), opacity }; } var IMPLIED_FILL_OPACITY = 0.2; function impliedFill(options, color) { const opacity = readOpacity(options, "fill opacity") ?? readOpacity(options, "opacity") ?? IMPLIED_FILL_OPACITY; return { color, opacity }; } // graphics/src/addplot.ts var DEFAULT_SAMPLES = 50; var DEFAULT_MARK_SIZE = 3; var DEFAULT_PLOT_COLOR = "#1f4e9c"; var SUPPORTED_PLOT_OPTIONS = /* @__PURE__ */ new Set([ "domain", "samples", "fill", "draw", "color", "opacity", "fill opacity", "line width", "name path", "smooth", "only marks", "mark", "mark size", "variable", "unbounded coords", "restrict x to domain", "restrict y to domain", ...WIDTH_OPTION_NAMES, ...DASH_OPTION_NAMES ]); function readDomain(options, frame2) { return readInterval(options, "domain") ?? { from: frame2.x.min, to: frame2.x.max }; } function readInterval(options, key) { const raw = optionValue(options, key); if (raw === void 0) return void 0; const text = unbrace(raw).trim(); const at = optionAt(options, key); const parts = text.split(":"); if (parts.length !== 2) { fail("unsupported-option", `${key} must be written "from:to", not "${text}".`, at, text); } const from = Number(parts[0]); const to = Number(parts[1]); if (!Number.isFinite(from) || !Number.isFinite(to)) { fail("unsupported-option", `${key}="${text}" is not a pair of numbers.`, at, text); } if (to <= from) { fail("unsupported-option", `${key}="${text}" ends at or before it starts.`, at, text); } return { from, to }; } function readVariable(options) { const raw = optionValue(options, "variable"); if (raw === void 0) return "x"; const name = unbrace(raw).trim(); if (!/^\\?[A-Za-z]+$/.test(name)) { fail("unsupported-option", `variable must name a parameter, like \\t, not "${raw}".`, optionAt(options, "variable"), raw); } return name; } function readJump(options) { const raw = optionValue(options, "unbounded coords"); if (raw === void 0) return false; const value = unbrace(raw).trim(); if (value === "jump") return true; if (value === "discard") return false; fail("unsupported-option", `unbounded coords=${value} is not supported; use jump or discard.`, optionAt(options, "unbounded coords"), value); } function readMarkSize(options) { const raw = optionValue(options, "mark size"); if (raw === void 0) return DEFAULT_MARK_SIZE; const value = Number.parseFloat(unbrace(raw)); if (!Number.isFinite(value) || value <= 0 || value > 20) { fail("unsupported-option", `mark size="${raw}" is not a size between 0 and 20pt.`, optionAt(options, "mark size"), raw); } return value * 4 / 3; } function readSamples(options) { const raw = optionValue(options, "samples"); if (raw === void 0) return DEFAULT_SAMPLES; const at = optionAt(options, "samples"); const value = Number(unbrace(raw).trim()); if (!Number.isInteger(value) || value < 2) { fail("unsupported-option", `samples must be a whole number of at least 2, not "${raw}".`, at, raw); } if (value > 5e3) { fail("unsupported-option", `samples=${value} is beyond this build's limit of 5000.`, at, raw); } return value; } function readStyle(options, wantsFill) { const { color, rest } = currentColor(options); rejectUnsupported(rest, SUPPORTED_PLOT_OPTIONS, "\\addplot"); const markersOnly = rest.some((o) => o.key === "only marks"); const stroke = markersOnly ? void 0 : readStroke(rest, color ?? DEFAULT_PLOT_COLOR); const strokeColor = stroke?.color ?? color ?? DEFAULT_PLOT_COLOR; const fill = readFill(rest) ?? (wantsFill ? impliedFill(rest, strokeColor) : void 0); return { stroke, fill, markersOnly }; } function samplePoints(expr, from, to, samples) { const out = []; for (let i = 0; i < samples; i++) { const x = samples === 1 ? from : from + (to - from) * i / (samples - 1); out.push({ x, y: evaluate(expr, { x }) }); } return out; } function sampleParametric(node, frame2) { if (node.data.kind !== "parametric") throw new Error("not a parametric plot"); const variable = readVariable(node.options); const fx = parseExpr(node.data.x.source, node.data.x.at, [variable]); const fy = parseExpr(node.data.y.source, node.data.y.at, [variable]); const { from, to } = readDomain(node.options, frame2); const samples = readSamples(node.options); const out = []; for (let i = 0; i < samples; i++) { const t = from + (to - from) * i / (samples - 1); out.push({ x: evaluate(fx, { [variable]: t }), y: evaluate(fy, { [variable]: t }) }); } return out; } function readCoordinates(node) { if (node.data.kind !== "coordinates") throw new Error("not a coordinate plot"); return node.data.points.map((point) => { const parts = point.raw.replace(/^\s*axis cs:/, "").split(","); if (parts.length < 2) { fail("bad-coordinate", `"(${point.raw})" is not a coordinate pair.`, point.at, point.raw); } const x = Number(parts[0].trim()); const y = Number(parts[1].trim()); if (!Number.isFinite(x) || !Number.isFinite(y)) { fail("bad-coordinate", `"(${point.raw})" is not a pair of numbers.`, point.at, point.raw); } return { x, y }; }); } function finitePoints(points) { return points.filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y)); } function restrict(points, options) { const rx = readInterval(options, "restrict x to domain"); const ry = readInterval(options, "restrict y to domain"); if (!rx && !ry) return points; return points.map( (p) => rx && (p.x < rx.from || p.x > rx.to) || ry && (p.y < ry.from || p.y > ry.to) ? { x: p.x, y: NaN } : p ); } function runsOf(points, jump) { if (!jump) { const all = finitePoints(points); return all.length === 0 ? [] : [all]; } const runs = []; let current = []; for (const p of points) { if (Number.isFinite(p.x) && Number.isFinite(p.y)) { current.push(p); } else if (current.length > 0) { runs.push(current); current = []; } } if (current.length > 0) runs.push(current); return runs; } function drawPlot(node, frame2) { if (node.dimensions !== 2) { fail("unsupported-option", "\\addplot3 needs a 3-D axis; this plot is in a 2-D one.", node.at); } const style = readStyle(node.options, node.closedCycle); let data; if (node.data.kind === "expression") { const expr = parseExpr(node.data.source, node.data.at); const { from, to } = readDomain(node.options, frame2); data = samplePoints(expr, from, to, readSamples(node.options)); } else if (node.data.kind === "parametric") { data = sampleParametric(node, frame2); } else { data = readCoordinates(node); } const runs = runsOf(restrict(data, node.options), readJump(node.options)); if (runs.length === 0) { fail( "unsupported-expression", "The plot produced no drawable points \u2014 every sample was infinite or undefined.", node.at, void 0, "Check the domain: a function with an asymptote inside it has no value there." ); } if (style.markersOnly) { const size = readMarkSize(node.options); const color = currentColor(node.options).color ?? style.fill?.color ?? DEFAULT_PLOT_COLOR; return runs.flat().map((p) => ({ kind: "marker", at: frame2.toDevice(p.x, p.y), shape: "dot", size, fill: { color, opacity: 1 } })); } return runs.map((run3) => { const closing = node.closedCycle ? [ { x: run3[run3.length - 1].x, y: frame2.baselineValue }, { x: run3[0].x, y: frame2.baselineValue } ] : []; const points = [...run3, ...closing].map((p) => frame2.toDevice(p.x, p.y)); return { kind: "path", points, closed: node.closedCycle, ...style.stroke ? { stroke: style.stroke } : {}, ...style.fill ? { fill: style.fill } : {} }; }); } // graphics/src/clip.ts init_define_L2W_CONFIG(); var EPS = 1e-6; function inside(p, r) { return p.x >= r.left - EPS && p.x <= r.right + EPS && p.y >= r.top - EPS && p.y <= r.bottom + EPS; } function clipSegment(a, b, r) { const dx = b.x - a.x; const dy = b.y - a.y; let t0 = 0; let t1 = 1; const edges = [ [-dx, a.x - r.left], [dx, r.right - a.x], [-dy, a.y - r.top], [dy, r.bottom - a.y] ]; for (const [p, q] of edges) { if (Math.abs(p) < 1e-12) { if (q < -EPS) return null; continue; } const t = q / p; if (p < 0) { if (t > t1) return null; if (t > t0) t0 = t; } else { if (t < t0) return null; if (t < t1) t1 = t; } } const at = (t) => ({ x: a.x + dx * t, y: a.y + dy * t }); return [t0 === 0 ? a : at(t0), t1 === 1 ? b : at(t1)]; } function clipPolyline(points, r) { if (points.length === 1) return inside(points[0], r) ? [[points[0]]] : []; const runs = []; let current = []; for (let i = 0; i + 1 < points.length; i++) { const piece = clipSegment(points[i], points[i + 1], r); if (!piece) { if (current.length > 0) runs.push(current); current = []; continue; } const [from, to] = piece; const last = current[current.length - 1]; if (!last || last.x !== from.x || last.y !== from.y) { if (current.length > 0) runs.push(current); current = [from]; } current.push(to); if (to !== points[i + 1]) { runs.push(current); current = []; } } if (current.length > 0) runs.push(current); return runs.filter((run3) => run3.length >= 2); } function clipPolygon(points, r) { const lerpX = (a, b, x) => ({ x, y: a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x) }); const lerpY = (a, b, y) => ({ x: a.x + (b.x - a.x) * (y - a.y) / (b.y - a.y), y }); const edges = [ { keep: (p) => p.x >= r.left - EPS, cross: (a, b) => lerpX(a, b, r.left) }, { keep: (p) => p.x <= r.right + EPS, cross: (a, b) => lerpX(a, b, r.right) }, { keep: (p) => p.y >= r.top - EPS, cross: (a, b) => lerpY(a, b, r.top) }, { keep: (p) => p.y <= r.bottom + EPS, cross: (a, b) => lerpY(a, b, r.bottom) } ]; let out = [...points]; for (const edge of edges) { if (out.length === 0) break; const input = out; out = []; for (let i = 0; i < input.length; i++) { const current = input[i]; const previous = input[(i + input.length - 1) % input.length]; if (edge.keep(current)) { if (!edge.keep(previous)) out.push(edge.cross(previous, current)); out.push(current); } else if (edge.keep(previous)) { out.push(edge.cross(previous, current)); } } } return out; } function clipPath(item, r) { if (item.points.every((p) => inside(p, r))) return [item]; if (!item.closed) { return clipPolyline(item.points, r).map((points) => ({ ...item, points })); } const out = []; if (item.fill) { const polygon = clipPolygon(item.points, r); if (polygon.length >= 3) { const { stroke: _stroke, ...rest } = item; out.push({ ...rest, points: polygon }); } } if (item.stroke) { const ring = [...item.points, item.points[0]]; for (const points of clipPolyline(ring, r)) { const { fill: _fill, ...rest } = item; out.push({ ...rest, closed: false, points }); } } return out; } function clipToRect(items, r) { const out = []; for (const item of items) { switch (item.kind) { case "path": out.push(...clipPath(item, r)); break; case "marker": case "text": if (inside(item.at, r)) out.push(item); break; case "circle": case "arc": if (inside(item.center, r)) out.push(item); break; } } return out; } // graphics/src/to-svg.ts init_define_L2W_CONFIG(); var SCRIPT_SCALE = 0.72; var SUP_SHIFT = -0.42; var SUB_SHIFT = 0.28; var ASCENT = 0.8; var HALF_EX = 0.32; function num(value) { if (!Number.isFinite(value)) return "0"; const rounded = Number(value.toFixed(3)); return Object.is(rounded, -0) ? "0" : String(rounded); } function escapeXml(text) { return text.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); } function pointsAttr(points) { return points.map((p) => `${num(p.x)},${num(p.y)}`).join(" "); } function paintAttrs(item) { const attrs = []; if (item.fill) { attrs.push(`fill="${escapeXml(item.fill.color)}"`); if (item.fill.opacity !== 1) attrs.push(`fill-opacity="${num(item.fill.opacity)}"`); } else { attrs.push(`fill="none"`); } if (item.stroke) { attrs.push(`stroke="${escapeXml(item.stroke.color)}"`, `stroke-width="${num(item.stroke.width)}"`); if (item.stroke.dash && item.stroke.dash.length > 0) { attrs.push(`stroke-dasharray="${item.stroke.dash.map(num).join(" ")}"`); } } return attrs.join(" "); } function pathElement(item) { if (item.points.length === 0) return ""; const tag = item.closed ? "polygon" : "polyline"; return `<${tag} points="${pointsAttr(item.points)}" ${paintAttrs(item)}/>`; } function circleElement(item) { return ``; } function arcElement(item) { const at = (angle) => ({ x: item.center.x + item.radius * Math.cos(angle), y: item.center.y - item.radius * Math.sin(angle) }); const start = at(item.startAngle); const end = at(item.endAngle); const sweepAngle = item.endAngle - item.startAngle; const largeArc = Math.abs(sweepAngle) > Math.PI ? 1 : 0; const sweep = sweepAngle > 0 ? 0 : 1; if (Math.abs(sweepAngle) >= Math.PI * 2 - 1e-9) return circleElement({ ...item, kind: "circle" }); const d = `M ${num(start.x)} ${num(start.y)} A ${num(item.radius)} ${num(item.radius)} 0 ${largeArc} ${sweep} ${num(end.x)} ${num(end.y)}` + (item.fill ? ` L ${num(item.center.x)} ${num(item.center.y)} Z` : ""); return ``; } function markerElement(item) { const { x, y } = item.at; const r = item.size; switch (item.shape) { case "dot": return ``; case "circle": return ``; case "square": return ``; case "cross": { const stroke = paintAttrs({ stroke: item.stroke }); return ``; } } } function baselineY(item) { switch (item.baseline) { case "top": return item.at.y + item.fontSize * ASCENT; case "middle": return item.at.y + item.fontSize * HALF_EX; case "bottom": return item.at.y; } } function textElement(item) { if (item.runs.length === 0) return ""; const x = num(item.at.x); const y = num(baselineY(item)); let offset = 0; const spans = item.runs.map((run3) => { const target = run3.baseline === "sup" ? SUP_SHIFT : run3.baseline === "sub" ? SUB_SHIFT : 0; const dy = (target - offset) * item.fontSize; offset = target; const attrs2 = [`dy="${num(dy)}"`]; if (run3.baseline !== "normal") attrs2.push(`font-size="${num(item.fontSize * SCRIPT_SCALE)}"`); if (run3.italic) attrs2.push(`font-style="italic"`); return `${escapeXml(run3.text)}`; }); const attrs = [ `x="${x}"`, `y="${y}"`, `font-size="${num(item.fontSize)}"`, `fill="${escapeXml(item.color)}"`, `text-anchor="${item.anchor}"` ]; if (item.rotate !== void 0) attrs.push(`transform="rotate(${num(item.rotate)} ${x} ${y})"`); return `${spans.join("")}`; } function itemElement(item) { switch (item.kind) { case "path": return pathElement(item); case "circle": return circleElement(item); case "arc": return arcElement(item); case "text": return textElement(item); case "marker": return markerElement(item); } } function sceneToSvg(scene, options = {}) { const parts = []; parts.push( `` ); if (options.title !== void 0) parts.push(`${escapeXml(options.title)}`); if (scene.background !== void 0) { parts.push(``); } for (const item of scene.items) { const element = itemElement(item); if (element.length > 0) parts.push(element); } parts.push(``); return parts.join(""); } function svgToBytes(svg) { return new TextEncoder().encode(svg); } // graphics/src/chemfig.ts init_define_L2W_CONFIG(); var FONT = 13; var EM = FONT; var ATOM_SEP = 3 * EM; var BOND_OFFSET = 0.2 * EM; var DOUBLE_SEP = 0.25 * EM; var CRAM_WIDTH = 0.65 * EM; var HASH_STEP = 0.3 * EM; var BOND_WIDTH = 1.1; var CYCLE_RADIUS_COEFF = 0.75; var ANGLE_INCREMENT = 45; var INK = "#000000"; var PADDING = 10; var ARROW_LENGTH = 3 * EM; var ARROW_GAP = 1 * EM; var PLUS_GAP = 0.5 * EM; var LABEL_SEP = 0.3 * EM; var LABEL_FONT = 0.85 * FONT; var NAME_SEP = 0.7 * EM; var NAME_FONT = 0.9 * FONT; var HEAD_LENGTH = 0.55 * EM; var HEAD_HALF = 0.22 * EM; var EQUILIBRIUM_SEP = 0.18 * EM; var SCRIPT_SCALE2 = 0.72; var CAP_HALF = 0.34; var SUP_RISE = 0.3; var SUB_DROP = 0.25; var BOND_CHARS = /* @__PURE__ */ new Set(["-", "=", "~", "<", ">"]); var GROUP_STOPS = /* @__PURE__ */ new Set(["-", "=", "~", "<", ">", "(", ")", "*", "[", "]", "?", "!", "@"]); var SUPPORTED_BOND_OPTIONS = /* @__PURE__ */ new Set(["draw", "color", "line width", ...WIDTH_OPTION_NAMES, ...DASH_OPTION_NAMES]); var TEXT_SYMBOLS = { oplus: "\u2295", ominus: "\u2296", delta: "\u03B4", Delta: "\u0394", cdot: "\xB7", bullet: "\u2022", ",": "\u2009", " ": " ", "%": "%", "&": "&", "#": "#", textdegree: "\xB0", degree: "\xB0" }; var WIDTHS = { A: 0.7, B: 0.64, C: 0.66, D: 0.73, E: 0.6, F: 0.56, G: 0.72, H: 0.74, I: 0.34, J: 0.38, K: 0.7, L: 0.58, M: 0.88, N: 0.73, O: 0.75, P: 0.59, Q: 0.75, R: 0.66, S: 0.54, T: 0.62, U: 0.72, V: 0.7, W: 0.96, X: 0.7, Y: 0.68, Z: 0.6, a: 0.48, b: 0.53, c: 0.44, d: 0.53, e: 0.47, f: 0.32, g: 0.49, h: 0.55, i: 0.28, j: 0.28, k: 0.52, l: 0.28, m: 0.82, n: 0.55, o: 0.52, p: 0.53, q: 0.53, r: 0.38, s: 0.4, t: 0.33, u: 0.55, v: 0.5, w: 0.73, x: 0.5, y: 0.5, z: 0.44, " ": 0.25, "\u2009": 0.17, ".": 0.25, ",": 0.25, ":": 0.25, ";": 0.25, "'": 0.22, "(": 0.33, ")": 0.33, "[": 0.3, "]": 0.3, "-": 0.33, "\u2013": 0.5, "\u2014": 1, "+": 0.6, "\u2212": 0.6, "=": 0.6, "/": 0.4, "\xB0": 0.4, "\xB7": 0.25 }; function charWidth(ch) { return WIDTHS[ch] ?? (/\d/.test(ch) ? 0.5 : 0.6); } function runsWidth(runs, fontSize) { let em = 0; for (const run3 of runs) { const scale = run3.baseline === "normal" ? 1 : SCRIPT_SCALE2; for (const ch of run3.text) em += charWidth(ch) * scale; } return em * fontSize; } var EMPTY_BOUNDS = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; function include(b, x, y) { return { minX: Math.min(b.minX, x), minY: Math.min(b.minY, y), maxX: Math.max(b.maxX, x), maxY: Math.max(b.maxY, y) }; } function centredText(runs, at, fontSize) { return { kind: "text", at, runs, anchor: "middle", baseline: "middle", fontSize, color: INK }; } function textBounds(item) { const width = runsWidth(item.runs, item.fontSize); const left = item.anchor === "start" ? item.at.x : item.anchor === "end" ? item.at.x - width : item.at.x - width / 2; const sup = item.runs.some((r) => r.baseline === "sup"); const sub = item.runs.some((r) => r.baseline === "sub"); const baseline = item.baseline === "top" ? item.at.y + 0.8 * item.fontSize : item.baseline === "middle" ? item.at.y + 0.32 * item.fontSize : item.at.y; const top = baseline - (0.82 + (sup ? 0.2 : 0)) * item.fontSize; const bottom = baseline + (0.1 + (sub ? 0.18 : 0)) * item.fontSize; return { minX: left, minY: top, maxX: left + width, maxY: bottom }; } function boundsOfItems(items) { let b = EMPTY_BOUNDS; for (const item of items) { switch (item.kind) { case "path": for (const p of item.points) b = include(b, p.x, p.y); break; case "circle": case "arc": b = include(include(b, item.center.x - item.radius, item.center.y - item.radius), item.center.x + item.radius, item.center.y + item.radius); break; case "text": { const t = textBounds(item); b = include(include(b, t.minX, t.minY), t.maxX, t.maxY); break; } case "marker": b = include(b, item.at.x, item.at.y); break; } } return b; } function shiftItems(items, dx, dy) { const move = (p) => ({ x: p.x + dx, y: p.y + dy }); return items.map((shifted) => { const item = shifted.move ? { ...shifted, move: { ...shifted.move, origin: move(shifted.move.origin) } } : shifted; switch (item.kind) { case "path": return { ...item, points: item.points.map(move) }; case "circle": case "arc": return { ...item, center: move(item.center) }; case "text": case "marker": return { ...item, at: move(item.at) }; } }); } function textRuns(raw, at) { let out = ""; let i = 0; while (i < raw.length) { const ch = raw[i]; if (ch === "$") { const close = raw.indexOf("$", i + 1); if (close < 0) fail("syntax", "A $ in this label has no closing $.", at + i, "$"); out += raw.slice(i, close + 1); i = close + 1; continue; } if (ch === "\\") { const name = /^\\([A-Za-z]+|.)/.exec(raw.slice(i))?.[1]; if (name === void 0) fail("syntax", "A label can't end with a backslash.", at + i, "\\"); if (name === "$") { out += "\\$"; i += 2; continue; } if (name === "ce") { const group = readBalanced2(raw, i + 3, "{", "}", at); out += `$\\ce{${group.content}}$`; i = group.end; continue; } const symbol = TEXT_SYMBOLS[name]; if (symbol === void 0) { fail("unknown-command", `\\${name} can't be drawn in a chemistry label.`, at + i, name, "Write the label as plain text, with $\u2026$ for maths."); } out += symbol; i += 1 + name.length; continue; } if (raw.startsWith("---", i)) { out += "\u2014"; i += 3; continue; } if (raw.startsWith("--", i)) { out += "\u2013"; i += 2; continue; } if (ch === "~") out += "\xA0"; else if (ch !== "{" && ch !== "}") out += ch; i++; } return mergeRuns(labelRuns(out.replace(/[ \t\r\n]+/g, " ").replace(/^ | $/g, ""), at)); } function mergeRuns(runs) { const out = []; for (const raw of runs) { let run3 = raw.baseline === "normal" ? raw : { ...raw, text: raw.text.replace(/-/g, "\u2212") }; if (run3.italic && /^[Α-Ω]+$/.test(run3.text)) run3 = { ...run3, italic: false }; const last = out[out.length - 1]; if (last && last.baseline === run3.baseline && last.italic === run3.italic) out[out.length - 1] = { ...last, text: last.text + run3.text }; else if (run3.text.length > 0) out.push(run3); } return out; } function readBalanced2(source, from, open, close, base) { if (source[from] !== open) fail("syntax", `Expected "${open}" here.`, base + from, source[from]); let depth = 0; for (let i = from; i < source.length; i++) { const ch = source[i]; if (ch === "\\") { i++; continue; } if (ch === open) depth++; else if (ch === close) { depth--; if (depth === 0) return { content: source.slice(from + 1, i), end: i + 1 }; } } fail("syntax", `This "${open}" is never closed.`, base + from, open); } var LEWIS_KINDS = { ":": "pair", ".": "dot", "|": "bar", I: "box" }; var rad = (degrees) => degrees * Math.PI / 180; var normalise = (degrees) => (degrees % 360 + 360) % 360; var step = (from, degrees, length2) => ({ x: from.x + length2 * Math.cos(rad(degrees)), y: from.y - length2 * Math.sin(rad(degrees)) }); function departureAtom(group, degrees) { const a = normalise(degrees); return a < 90 || a > 270 ? Math.max(0, group.atoms.length - 1) : 0; } function arrivalAtom(count, degrees) { const a = normalise(degrees); return a > 90 && a < 270 ? Math.max(0, count - 1) : 0; } function atomPoint(group, index) { return group.centers[index] ?? group.at; } function placeGroup(atoms, hook, at) { if (atoms.length === 0) return { atoms, centers: [], at }; const centers = new Array(atoms.length); centers[hook] = at; for (let i = hook + 1; i < atoms.length; i++) { const before = centers[i - 1]; centers[i] = { x: before.x + atoms[i - 1].width / 2 + atoms[i].width / 2, y: at.y }; } for (let i = hook - 1; i >= 0; i--) { const after = centers[i + 1]; centers[i] = { x: after.x - atoms[i + 1].width / 2 - atoms[i].width / 2, y: at.y }; } return { atoms, centers, at }; } function clearance(atom, dir) { if (!atom) return 0; const up = (CAP_HALF + (atom.sup ? SUP_RISE : 0)) * EM; const down = (CAP_HALF + (atom.sub ? SUB_DROP : 0)) * EM; const tx = Math.abs(dir.x) > 1e-9 ? atom.width / 2 / Math.abs(dir.x) : Infinity; const ty = dir.y < -1e-9 ? up / -dir.y : dir.y > 1e-9 ? down / dir.y : Infinity; return Math.min(tx, ty) + BOND_OFFSET; } var LEWIS_GAP = 0.15 * EM; var DOT_RADIUS = 0.09 * EM; var PAIR_SPREAD = 0.32 * EM; var BAR_LENGTH = 0.6 * EM; var CHARGE_FONT = SCRIPT_SCALE2 * FONT; function decorationItems(atom, centre, decoration, beyond = 0) { const d = { x: Math.cos(rad(decoration.angle)), y: -Math.sin(rad(decoration.angle)) }; const across = { x: -d.y, y: d.x }; const up = (CAP_HALF + (atom.sup ? SUP_RISE : 0)) * EM; const down = (CAP_HALF + (atom.sub ? SUB_DROP : 0)) * EM; const tx = Math.abs(d.x) > 1e-9 ? atom.width / 2 / Math.abs(d.x) : Infinity; const ty = d.y < -1e-9 ? up / -d.y : d.y > 1e-9 ? down / d.y : Infinity; const edgeAt = Math.min(tx, ty) + LEWIS_GAP + beyond; const out = (more, side2 = 0) => ({ x: centre.x + d.x * (edgeAt + more) + across.x * side2, y: centre.y + d.y * (edgeAt + more) + across.y * side2 }); const ink = { color: INK, opacity: 1 }; const stroke = { color: INK, width: BOND_WIDTH }; switch (decoration.kind) { case "dot": return { items: [{ kind: "circle", center: out(DOT_RADIUS), radius: DOT_RADIUS, fill: ink }], reach: beyond + 2 * DOT_RADIUS + LEWIS_GAP }; case "pair": return { items: [-1, 1].map((s) => ({ kind: "circle", center: out(DOT_RADIUS, s * PAIR_SPREAD / 2), radius: DOT_RADIUS, fill: ink })), reach: beyond + 2 * DOT_RADIUS + LEWIS_GAP }; case "bar": return { items: [line(out(0, -BAR_LENGTH / 2), out(0, BAR_LENGTH / 2), stroke)], reach: beyond + LEWIS_GAP }; case "box": { const depth = 0.22 * EM; return { items: [{ kind: "path", points: [out(0, -BAR_LENGTH / 2), out(0, BAR_LENGTH / 2), out(depth, BAR_LENGTH / 2), out(depth, -BAR_LENGTH / 2)], closed: true, stroke }], reach: beyond + depth + LEWIS_GAP }; } case "text": { const text = centredText(decoration.runs, { x: 0, y: 0 }, CHARGE_FONT); const b = textBounds(text); const reachOut = Math.abs(d.x) * ((b.maxX - b.minX) / 2) + Math.abs(d.y) * ((b.maxY - b.minY) / 2); const c = out(reachOut); return { items: [{ ...text, at: { x: c.x - (b.minX + b.maxX) / 2, y: c.y - (b.minY + b.maxY) / 2 } }], reach: beyond + 2 * reachOut + LEWIS_GAP }; } } } var HOOK_BONDS = { "-": { kind: "single", reversed: false }, "=": { kind: "double", reversed: false }, "~": { kind: "triple", reversed: false }, ">": { kind: "wedge", reversed: false }, "<": { kind: "wedge", reversed: true }, ">:": { kind: "hashed", reversed: false }, "<:": { kind: "hashed", reversed: true }, ">|": { kind: "hollow", reversed: false }, "<|": { kind: "hollow", reversed: true } }; var line = (a, b, stroke) => ({ kind: "path", points: [a, b], closed: false, stroke }); function bondItems(spec, from, start, to, end, ringN) { const stroke = spec.stroke; if (!stroke) return []; const dx = end.x - start.x; const dy = end.y - start.y; const length2 = Math.hypot(dx, dy); if (length2 < 1e-9) return []; const u = { x: dx / length2, y: dy / length2 }; const s0 = clearance(from, u); const s1 = clearance(to, { x: -u.x, y: -u.y }); if (s0 + s1 >= length2) return []; const p0 = { x: start.x + u.x * s0, y: start.y + u.y * s0 }; const p1 = { x: end.x - u.x * s1, y: end.y - u.y * s1 }; const left = { x: u.y, y: -u.x }; const off = (p, d, along = 0) => ({ x: p.x + left.x * d + u.x * along, y: p.y + left.y * d + u.y * along }); switch (spec.kind) { case "single": return [line(p0, p1, stroke)]; case "triple": return [line(p0, p1, stroke), line(off(p0, DOUBLE_SEP), off(p1, DOUBLE_SEP), stroke), line(off(p0, -DOUBLE_SEP), off(p1, -DOUBLE_SEP), stroke)]; case "double": { const side2 = spec.side === 0 && ringN !== null ? 1 : spec.side; if (side2 === 0) { return [line(off(p0, DOUBLE_SEP / 2), off(p1, DOUBLE_SEP / 2), stroke), line(off(p0, -DOUBLE_SEP / 2), off(p1, -DOUBLE_SEP / 2), stroke)]; } const d = side2 === 1 ? DOUBLE_SEP : -DOUBLE_SEP; const trim = ringN === null ? 0 : DOUBLE_SEP * Math.tan(Math.PI / ringN); return [line(p0, p1, stroke), line(off(p0, d, from ? 0 : trim), off(p1, d, to ? 0 : -trim), stroke)]; } case "wedge": case "hashed": case "hollow": { const narrow = spec.reversed ? p1 : p0; const wide = spec.reversed ? p0 : p1; const half = CRAM_WIDTH / 2; if (spec.kind === "wedge") { const tip = stroke.width / 2; return [ { kind: "path", points: [off(narrow, tip), off(wide, half), off(wide, -half), off(narrow, -tip)], closed: true, fill: { color: stroke.color, opacity: 1 } } ]; } if (spec.kind === "hollow") { return [{ kind: "path", points: [narrow, off(wide, half), off(wide, -half)], closed: true, stroke }]; } const span = Math.hypot(wide.x - narrow.x, wide.y - narrow.y); const count = Math.max(2, Math.floor(span / HASH_STEP)); const items = []; for (let k = 1; k <= count; k++) { const t = k / count; const at = { x: narrow.x + (wide.x - narrow.x) * t, y: narrow.y + (wide.y - narrow.y) * t }; items.push(line(off(at, half * t), off(at, -half * t), { ...stroke, width: Math.min(stroke.width, 1) })); } return items; } } } function bondStroke(raw, at) { const options = parseOptions(raw, at); const { color, rest } = currentColor(options); rejectUnsupported(rest, SUPPORTED_BOND_OPTIONS, "a chemfig bond"); const stroke = readStroke(rest, color ?? INK); if (!stroke) return void 0; const width = rest.some((o) => o.key === "line width" || WIDTH_OPTION_NAMES.includes(o.key)) ? stroke.width : BOND_WIDTH; return { ...stroke, width }; } function onlyAnAtom(raw, at) { fail("syntax", "Put only the atom inside \\charge or \\lewis, and its bonds after the closing brace: \\charge{90=$\\oplus$}{N}(-H)-H, not \\charge{90=$\\oplus$}{N(-H)-H}.", at, raw.trim()); } function atomLabel(atoms) { let out = ""; for (const atom of atoms) { for (const run3 of mergeRuns(atom.runs)) out += run3.baseline === "normal" ? run3.text : `${run3.baseline === "sub" ? "_" : "^"}{${run3.text}}`; for (const d of atom.decorations ?? []) { if (d.kind !== "text") continue; const text = d.runs.map((r) => r.text).join(""); if (/[+⊕]/.test(text)) out += "^{+}"; else if (/[-−⊖]/.test(text)) out += "^{-}"; } } return out; } var MoleculeReader = class _MoleculeReader { constructor(src, base) { this.src = src; this.base = base; this.i = 0; this.items = []; /** What was drawn, as atoms and bonds. */ this.graph = { atoms: [], bonds: [] }; /** Hooks read with the atoms just read, placed by `placeHooks`. */ this.pending = []; /** The first atom given each hook name: later ones bond to it. */ this.hooks = /* @__PURE__ */ new Map(); /** Hook names that have bonded at least once. */ this.linked = /* @__PURE__ */ new Set(); } here() { return this.base + this.i; } skipSpace() { while (this.i < this.src.length && /\s/.test(this.src[this.i])) this.i++; } read() { this.skipSpace(); let defaultAngle = 0; if (this.src[this.i] === "[") defaultAngle = this.leadingAngle(0) ?? 0; const atoms = this.atoms(); const group = placeGroup(atoms, 0, { x: 0, y: 0 }); this.drawAtoms(group); this.placeHooks(group); this.sequence({ group, prev: defaultAngle, defaultAngle, atStart: true, fromRing: null }, null, null); const open = [...this.hooks.keys()].find((name) => !this.linked.has(name)); if (open !== void 0) fail("syntax", `The hook ?${open === "a" ? "" : `[${open}]`} is never closed: give the atom it bonds to the same hook.`, this.base, "?"); } /** * The hooks read with a group, now it is placed: the first atom with a * name is remembered, and each later one is bonded to it. */ placeHooks(group) { for (const hook of this.pending) { const atom = hook.atom < 0 ? void 0 : group.atoms[hook.atom]; const at = hook.atom < 0 ? group.at : atomPoint(group, hook.atom); const first = this.hooks.get(hook.name); if (first === void 0) { this.hooks.set(hook.name, { atom, at }); continue; } this.items.push(...bondItems(hook.spec, first.atom, first.at, atom, at, null)); this.graph.bonds.push({ from: first.at, to: at, kind: hook.spec.kind, reversed: hook.spec.reversed }); this.linked.add(hook.name); } this.pending = []; } /** `?`, `?[name]` or `?[name,bond,tikz]`, after the atom it marks. */ hook(atom) { const at = this.here(); this.i++; let fields = []; if (this.src[this.i] === "[") { const { content, end } = readBalanced2(this.src, this.i, "[", "]", this.base); this.i = end; fields = splitTopLevel(content, ","); } const name = (fields[0] ?? "").trim() || "a"; const code = (fields[1] ?? "").trim() || "-"; const bond = HOOK_BONDS[code]; if (bond === void 0) fail("unsupported-option", `"${code}" is not a bond a hook can draw: use -, =, ~, >, <, >:, <:, >| or <|.`, at, code); const tikz = fields.slice(2).join(","); const stroke = tikz.trim() === "" ? { color: INK, width: BOND_WIDTH } : bondStroke(tikz, at); this.pending.push({ name, spec: { ...bond, side: 0, stroke }, atom, at }); } /** `[angle]` opening a molecule or a branch: that sequence's default angle. */ leadingAngle(prev) { const at = this.i; const { content, end } = readBalanced2(this.src, this.i, "[", "]", this.base); this.i = end; const fields = splitFields(content); if (fields.slice(1).some((f) => f.trim() !== "")) { fail("unsupported-option", "Only an angle can be given at the start of a molecule here.", this.base + at, content); } return parseAngle(fields[0] ?? "", prev, this.base + at); } /** * A group is written as one line of text, so its letters sit at the font's * own spacing rather than at estimated widths. It is anchored at the outer * edge of the atom the bond reached, which keeps that atom over the bond * end however far the estimate is out. */ drawAtoms(group, hook = 0) { if (group.atoms.length === 0) return; this.graph.atoms.push({ at: group.centers[hook] ?? group.centers[0], centers: group.centers, label: atomLabel(group.atoms) }); const runs = mergeRuns(group.atoms.flatMap((a) => a.runs)); const last = group.atoms.length - 1; const y = group.centers[0].y; const fromEnd = hook === last && last > 0; const x = fromEnd ? group.centers[last].x + group.atoms[last].width / 2 : group.centers[0].x - group.atoms[0].width / 2; this.items.push({ ...centredText(runs, { x, y }, FONT), anchor: fromEnd ? "end" : "start" }); group.atoms.forEach((atom, i) => { const used = /* @__PURE__ */ new Map(); for (const decoration of atom.decorations ?? []) { const angle = normalise(decoration.angle); const drawn = decorationItems(atom, group.centers[i], decoration, used.get(angle) ?? 0); this.items.push(...drawn.items); used.set(angle, drawn.reach); } }); } sequence(cur, ring, close) { for (; ; ) { this.skipSpace(); const ch = this.src[this.i]; if (ch === void 0) { if (close !== null) fail("syntax", `A "(" is never closed.`, this.here(), "("); return; } if (ch === close) { this.i++; return; } if (ch === ")") fail("syntax", `This ")" closes nothing.`, this.here(), ")"); if (BOND_CHARS.has(ch)) this.bond(cur, ring); else if (ch === "(") { this.i++; this.branch(cur, ring); } else if (ch === "*") this.ring(cur, ring); else if (ch === "?") { this.hook(cur.group.atoms.length - 1); this.placeHooks(cur.group); } else if (ch === "!") fail("unknown-command", "Submolecules (!) are not supported.", this.here(), "!", "Write the group out in full."); else if (ch === "@") fail("unknown-command", "Named bonds and atoms (@{\u2026}) are not supported.", this.here(), "@"); else { const atom = /^[^-=~<>()*[\]?!@\s]+/.exec(this.src.slice(this.i))?.[0] ?? ch; const how = /\(\s*$/.test(this.src.slice(0, this.i)) ? `: a branch starts with its bond, as (-${atom}), not (${atom})` : ""; fail("syntax", `"${atom}" needs a bond before it, such as -, = or ~${how}.`, this.here(), ch); } } } bondSpec() { const at = this.here(); const c = this.src[this.i++]; let kind = "single"; let side2 = 0; let reversed = false; if (c === "=") { kind = "double"; if (this.src[this.i] === "^") { side2 = 1; this.i++; } else if (this.src[this.i] === "_") { side2 = 2; this.i++; } } else if (c === "~") kind = "triple"; else if (c === ">" || c === "<") { reversed = c === "<"; kind = "wedge"; if (this.src[this.i] === ":") { kind = "hashed"; this.i++; } else if (this.src[this.i] === "|") { kind = "hollow"; this.i++; } } if (this.src[this.i] === "#") fail("unsupported-option", "Bond offsets (#(\u2026)) are not supported.", this.here(), "#"); if (this.src[this.i] === "@") fail("unknown-command", "Named bonds (@{\u2026}) are not supported.", this.here(), "@"); let options = null; if (this.src[this.i] === "[") { const { content, end } = readBalanced2(this.src, this.i, "[", "]", this.base); options = content; this.i = end; } return { spec: { kind, side: side2, reversed, stroke: { color: INK, width: BOND_WIDTH } }, options, at }; } bond(cur, ring) { const { spec: plain, options, at } = this.bondSpec(); const fields = splitFields(options ?? ""); const spec = fields[4] !== void 0 && fields[4].trim() !== "" ? { ...plain, stroke: bondStroke(fields[4], at) } : plain; let angle; let length2 = 1; if (ring) { ring.count++; if (ring.count > ring.n) fail("syntax", `A ring of ${ring.n} has only ${ring.n} bonds.`, at); angle = cur.prev + 360 / ring.n + (ring.count === 1 ? ring.init : 0); } else { angle = parseAngle(fields[0] ?? "", cur.prev, at) ?? cur.defaultAngle; const coeff = (fields[1] ?? "").trim(); if (coeff !== "") { length2 = Number(coeff); if (!Number.isFinite(length2) || length2 <= 0) fail("unsupported-option", `"${coeff}" is not a bond length.`, at, coeff); } } const fromAtom = atomIndex(fields[2], cur.group.atoms.length, at) ?? departureAtom(cur.group, angle); const start = atomPoint(cur.group, fromAtom); let next; let toAtom; if (ring && ring.count === ring.n) { next = ring.hook; toAtom = ring.hookAtom; this.skipSpace(); if (this.i < this.src.length && this.src[this.i] !== ")") { fail("syntax", `Nothing can follow the last bond of a ring of ${ring.n}.`, this.here(), this.src[this.i]); } } else { const atoms = this.atoms(); toAtom = atomIndex(fields[3], atoms.length, at) ?? arrivalAtom(atoms.length, angle); next = placeGroup(atoms, toAtom, step(start, angle, ATOM_SEP * length2)); this.drawAtoms(next, toAtom); } this.items.push(...bondItems(spec, cur.group.atoms[fromAtom], start, next.atoms[toAtom], atomPoint(next, toAtom), ring ? ring.n : null)); if (spec.stroke) this.graph.bonds.push({ from: start, to: atomPoint(next, toAtom), kind: spec.kind, reversed: spec.reversed }); if (next !== ring?.hook) this.placeHooks(next); cur.group = next; cur.prev = angle; cur.atStart = false; cur.fromRing = null; } branch(cur, ring) { const inner = { ...cur }; if (ring) { inner.defaultAngle = ring.count === 0 ? cur.prev + 180 + ring.correction : cur.prev - 90 + 180 / ring.n; inner.fromRing = ring.n; } this.skipSpace(); if (this.src[this.i] === "[") { const angle = this.leadingAngle(inner.prev); if (angle !== void 0) { inner.defaultAngle = angle; inner.prev = angle; } } this.sequence(inner, null, ")"); } ring(cur, outer) { const at = this.here(); this.i++; const circle2 = this.src[this.i] === "*"; if (circle2) this.i++; if (this.src[this.i] === "[") fail("unsupported-option", "Options on a ring's circle are not supported.", this.here(), "["); const digits = /^\d+/.exec(this.src.slice(this.i))?.[0]; if (digits === void 0) fail("syntax", "A ring needs its size after the *, as in *6(\u2026).", this.here(), this.src[this.i]); const n = Number(digits); if (n < 3 || n > 12) fail("unsupported-option", `A ring of ${n} can't be drawn; use 3 to 12.`, at, digits); this.i += digits.length; this.skipSpace(); if (this.src[this.i] !== "(") fail("syntax", `A ring needs its bonds in brackets, as in *${n}(-=-=-=).`, this.here(), this.src[this.i]); this.i++; const lastRing = outer?.n ?? cur.fromRing; const correction = cur.atStart ? 180 / n : 0; const init = lastRing !== null ? 360 / lastRing - 180 : -180 / n - 90 + correction; const hookAtom = departureAtom(cur.group, cur.prev); const state = { n, hook: cur.group, hookAtom, init, correction, count: 0 }; const centre = step(atomPoint(cur.group, hookAtom), cur.prev + init + 180 / n + 90, ATOM_SEP / (2 * Math.sin(Math.PI / n))); this.sequence({ ...cur, fromRing: null }, state, ")"); if (circle2) { this.items.push({ kind: "circle", center: centre, radius: CYCLE_RADIUS_COEFF * ATOM_SEP / (2 * Math.tan(Math.PI / n)), stroke: { color: INK, width: BOND_WIDTH } }); } } /** An atom group, split into atoms at each capital letter; spaces are ignored, as chemfig ignores them. */ atoms() { const atoms = []; let runs = null; const push = () => { if (runs && runs.length > 0) atoms.push(makeAtom(runs)); runs = null; }; const append = (text, baseline) => { runs ??= []; const last = runs[runs.length - 1]; if (last && last.baseline === baseline) runs[runs.length - 1] = { ...last, text: last.text + text }; else runs.push({ text, baseline, italic: false }); }; while (this.i < this.src.length) { const ch = this.src[this.i]; if (ch === "?") { this.hook(runs ? atoms.length : atoms.length - 1); continue; } if (GROUP_STOPS.has(ch)) break; if (/\s/.test(ch)) { this.i++; continue; } if (ch === "{") { push(); const { content, end } = readBalanced2(this.src, this.i, "{", "}", this.base); const at = this.here(); this.i = end; for (const piece of scriptPieces(content, at)) append(piece.text, piece.baseline); push(); continue; } if (ch === "_" || ch === "^") { if (!runs) fail("syntax", `A ${ch === "_" ? "subscript" : "superscript"} needs an atom before it.`, this.here(), ch); this.i++; append(this.scriptToken(), ch === "_" ? "sub" : "sup"); continue; } if (ch === "\\") { const at = this.here(); const name = /^\\([A-Za-z]+|.)/.exec(this.src.slice(this.i))?.[1] ?? ""; if (/^(lewis|Lewis|charge|Charge)$/.test(name)) { push(); this.i += 1 + name.length; atoms.push(name.toLowerCase() === "lewis" ? this.lewis(at) : this.charge(at)); continue; } const symbol = TEXT_SYMBOLS[name]; if (symbol === void 0) { fail("unknown-command", `\\${name} can't be drawn in a chemfig atom.`, at, name, "Write the atom as letters, with _ and ^ for subscripts and charges."); } this.i += 1 + name.length; append(symbol, "normal"); continue; } if (/[A-Z]/.test(ch)) push(); append(ch, "normal"); this.i++; } push(); return atoms; } /** Options in [...] after \lewis or \charge: none are drawn, so any given are refused. */ noOptions(command) { this.skipSpace(); if (this.src[this.i] !== "[") return; const at = this.here(); const { content, end } = readBalanced2(this.src, this.i, "[", "]", this.base); if (content.trim() !== "") fail("unsupported-option", `Options on \\${command} are not supported.`, at, content, "Leave them out; the dots are drawn at chemfig's own size."); this.i = end; } /** `\lewis{0:2.4|6I,O}`: at each multiple of 45°, a pair, one electron, a line or a box. */ lewis(at) { this.noOptions("lewis"); this.skipSpace(); const groupAt = this.here() + 1; const { content, end } = readBalanced2(this.src, this.i, "{", "}", this.base); this.i = end; const comma = content.indexOf(","); if (comma < 0) fail("syntax", "\\lewis needs its places, a comma, then the atom: \\lewis{0:2:,O}.", at, "lewis"); const decorations = []; const spec = content.slice(0, comma).replace(/\s+/g, ""); for (let i = 0; i < spec.length; i += 2) { const place = spec[i]; const kind = LEWIS_KINDS[spec[i + 1] ?? ""]; if (!/[0-7]/.test(place)) fail("syntax", `"${place}" is not a place for \\lewis: give a digit 0 to 7, in steps of 45\xB0.`, groupAt, place); if (kind === void 0) fail("syntax", `Place ${place} in \\lewis needs :, ., | or I after it: ${place}: for a pair, ${place}. for one electron.`, groupAt, spec.slice(i, i + 2)); decorations.push({ angle: Number(place) * ANGLE_INCREMENT, kind }); } return this.decoratedAtom(content.slice(comma + 1), groupAt + comma + 1, decorations); } /** `\charge{90=$\oplus$,0=\:}{N}`: text or electrons at an angle (or north, south east, …) round an atom. */ charge(at) { this.noOptions("charge"); this.skipSpace(); const listAt = this.here() + 1; const list = readBalanced2(this.src, this.i, "{", "}", this.base); this.i = list.end; this.skipSpace(); const atomAt = this.here() + 1; if (this.src[this.i] !== "{") fail("syntax", "\\charge needs the atom after its list: \\charge{90=$\\oplus$}{N}.", at, "charge"); const atom = readBalanced2(this.src, this.i, "{", "}", this.base); this.i = atom.end; const decorations = []; let offset = 0; for (const entry of splitTopLevel(list.content, ",")) { const entryAt = listAt + offset; offset += entry.length + 1; if (entry.trim() === "") continue; const eq = entry.indexOf("="); if (eq < 0) fail("syntax", `"${entry.trim()}" needs a place and what goes there, as 90=$\\oplus$.`, entryAt, entry.trim()); const place = entry.slice(0, eq).trim(); if (place.includes("[")) fail("unsupported-option", "Options on a \\charge place are not supported.", entryAt, place); const angle = chargeAngle(place.replace(/:.*$/, "").trim(), entryAt); const what = entry.slice(eq + 1).trim(); const electrons = /^\\([:.|I])$/.exec(what)?.[1]; if (electrons !== void 0) decorations.push({ angle, kind: LEWIS_KINDS[electrons] }); else decorations.push({ angle, kind: "text", runs: textRuns(what, entryAt + eq + 1) }); } return this.decoratedAtom(atom.content, atomAt, decorations); } decoratedAtom(raw, at, decorations) { if (/^\s*\\(lewis|Lewis|charge|Charge)(?![A-Za-z])/.test(raw)) { const reader = new _MoleculeReader(raw, at); const inner = reader.atoms(); reader.skipSpace(); if (inner.length !== 1 || reader.i < raw.length || reader.pending.length > 0) onlyAnAtom(raw, at); return { ...inner[0], decorations: [...inner[0].decorations ?? [], ...decorations] }; } if ([...raw.replace(/[_^](\{[^}]*\}|\\[A-Za-z]+|.)/g, "")].some((ch) => GROUP_STOPS.has(ch))) onlyAnAtom(raw, at); const pieces = scriptPieces(raw.trim(), at); if (pieces.length === 0) fail("syntax", "There is no atom here to put electrons or a charge on.", at); return { ...makeAtom(pieces.map((p) => ({ text: p.text, baseline: p.baseline, italic: false }))), decorations }; } /** What follows _ or ^: one character, or a braced group. */ scriptToken() { const ch = this.src[this.i]; if (ch === void 0) fail("syntax", "A subscript or superscript is missing its text.", this.here()); if (ch === "{") { const at = this.here(); const { content, end } = readBalanced2(this.src, this.i, "{", "}", this.base); this.i = end; return plainText(content, at); } if (ch === "\\") { const name = /^\\([A-Za-z]+|.)/.exec(this.src.slice(this.i))?.[1] ?? ""; const symbol = TEXT_SYMBOLS[name]; if (symbol === void 0) fail("unknown-command", `\\${name} can't be drawn in a chemfig atom.`, this.here(), name); this.i += 1 + name.length; return symbol; } this.i++; return ch === "-" ? "\u2212" : ch; } }; function makeAtom(runs) { return { runs, width: runsWidth(runs, FONT), sub: runs.some((r) => r.baseline === "sub"), sup: runs.some((r) => r.baseline === "sup") }; } function scriptPieces(content, at) { const pieces = []; let i = 0; while (i < content.length) { const ch = content[i]; if (ch === "_" || ch === "^") { const next = content[i + 1]; if (next === void 0) fail("syntax", "A subscript or superscript is missing its text.", at + i); if (next === "{") { const group = readBalanced2(content, i + 1, "{", "}", at); pieces.push({ text: plainText(group.content, at + i), baseline: ch === "_" ? "sub" : "sup" }); i = group.end; } else { pieces.push({ text: next === "-" ? "\u2212" : next, baseline: ch === "_" ? "sub" : "sup" }); i += 2; } continue; } const start = i; while (i < content.length && content[i] !== "_" && content[i] !== "^") i++; pieces.push({ text: plainText(content.slice(start, i), at + start), baseline: "normal" }); } return pieces.filter((p) => p.text.length > 0); } function plainText(raw, at) { let out = ""; for (let i = 0; i < raw.length; i++) { const ch = raw[i]; if (ch === "\\") { const name = /^\\([A-Za-z]+|.)/.exec(raw.slice(i))?.[1] ?? ""; const symbol = TEXT_SYMBOLS[name]; if (symbol === void 0) fail("unknown-command", `\\${name} can't be drawn in a chemfig atom.`, at + i, name); out += symbol; i += name.length; } else if (ch === "-") out += "\u2212"; else if (ch !== "{" && ch !== "}" && !/\s/.test(ch)) out += ch; } return out; } function splitTopLevel(raw, sep3) { const parts = []; let depth = 0; let maths = false; let start = 0; for (let i = 0; i < raw.length; i++) { const ch = raw[i]; if (ch === "\\") i++; else if (ch === "$") maths = !maths; else if (ch === "{" || ch === "[") depth++; else if (ch === "}" || ch === "]") depth--; else if (ch === sep3 && depth === 0 && !maths) { parts.push(raw.slice(start, i)); start = i + 1; } } parts.push(raw.slice(start)); return parts; } var COMPASS = { east: 0, "north east": 45, north: 90, "north west": 135, west: 180, "south west": 225, south: 270, "south east": 315 }; function chargeAngle(place, at) { const compass = COMPASS[place.replace(/\s+/g, " ")]; if (compass !== void 0) return compass; const degrees = Number(place); if (place === "" || !Number.isFinite(degrees)) fail("unsupported-option", `"${place}" is not a place for a charge.`, at, place, "Give an angle, such as 90 for above or 0 for the right."); return degrees; } function splitFields(raw) { const fields = []; let depth = 0; let start = 0; for (let i = 0; i < raw.length; i++) { const ch = raw[i]; if (ch === "{" || ch === "[" || ch === "(") depth++; else if (ch === "}" || ch === "]" || ch === ")") depth--; else if (ch === "," && depth === 0 && fields.length < 4) { fields.push(raw.slice(start, i)); start = i + 1; } } fields.push(raw.slice(start)); return fields; } function parseAngle(raw, prev, at) { const text = raw.trim(); if (text === "") return void 0; const relative = text.startsWith("::"); const absolute = !relative && text.startsWith(":"); const value = Number(text.slice(relative ? 2 : absolute ? 1 : 0).trim()); if (!Number.isFinite(value)) fail("unsupported-option", `"${text}" is not a bond angle. Write [2], [:90] or [::30].`, at, text); return relative ? prev + value : absolute ? value : value * ANGLE_INCREMENT; } function atomIndex(raw, count, at) { const text = (raw ?? "").trim(); if (text === "" || count === 0) return void 0; const n = Number(text); if (!Number.isInteger(n) || n < 1 || n > Math.max(1, count)) fail("unsupported-option", `There is no atom ${text} in that group.`, at, text); return Math.min(n, count) - 1; } function moleculeBox(body, base) { const reader = new MoleculeReader(body, base); reader.read(); return { items: reader.items, bounds: boundsOfItems(reader.items) }; } function textBox(raw, at, fontSize) { const runs = textRuns(raw, at); if (runs.length === 0) return { items: [], bounds: { minX: 0, minY: 0, maxX: 0, maxY: 0 } }; const item = centredText(runs, { x: 0, y: 0 }, fontSize); return { items: [item], bounds: textBounds(item) }; } var ARROW_TYPES = /* @__PURE__ */ new Set(["->", "<-", "<->", "<=>"]); var SCHEME_COMMANDS = /^\\(chemfig|chemname|arrow|schemestart|schemestop|\+)(?![A-Za-z])/; var SchemeReader = class { constructor(src) { this.src = src; this.i = 0; this.items = []; } skipSpace() { while (this.i < this.src.length && /\s/.test(this.src[this.i])) this.i++; } read() { let text = ""; let textAt = 0; const flush = () => { if (text.trim() !== "") this.items.push({ kind: "compound", box: textBox(text, textAt, FONT) }); text = ""; }; while (this.i < this.src.length) { const command = SCHEME_COMMANDS.exec(this.src.slice(this.i))?.[1]; if (command === void 0) { if (text === "") textAt = this.i; if (this.src[this.i] === "\\") { const other = /^\\([A-Za-z]+|.)/.exec(this.src.slice(this.i))[0]; if (/^\\(subscheme|chemleft|chemright|chemup|chemdown|setchemfig|chemmove|chemabove|chembelow|lewis|charge|merge)$/.test(other)) { fail("unknown-command", `${other} is not supported in a scheme here.`, this.i, other.slice(1), "Write the scheme as compounds joined by \\arrow and \\+; branch with \\arrow(a--b) and \\arrow(@a--c)[-90]."); } } text += this.src[this.i]; this.i++; continue; } flush(); const at = this.i; this.i += command.length + 1; switch (command) { case "chemfig": case "chemname": this.i = at; this.items.push(this.compound()); break; case "+": this.skipBracedArgument(); this.items.push({ kind: "plus" }); break; case "arrow": this.items.push(this.arrow()); break; case "schemestart": case "schemestop": fail("syntax", `\\${command} can only open and close the whole scheme.`, at, command); } } flush(); } /** `\+{…}` takes optional spacings; the drawing uses its own. */ skipBracedArgument() { const save = this.i; this.skipSpace(); if (this.src[this.i] === "{") this.i = readBalanced2(this.src, this.i, "{", "}", 0).end; else this.i = save; } /** `\chemfig[…]{…}` or `\chemname[…]{compound}{name}`, at `this.i`. */ compound() { if (this.src.startsWith("\\chemname", this.i)) { this.i += "\\chemname".length; this.skipSpace(); if (this.src[this.i] === "[") this.i = readBalanced2(this.src, this.i, "[", "]", 0).end; this.skipSpace(); const inner = readBalanced2(this.src, this.i, "{", "}", 0); const innerAt = this.i + 1; this.i = inner.end; this.skipSpace(); const name = readBalanced2(this.src, this.i, "{", "}", 0); const nameAt = this.i + 1; this.i = name.end; const box = compoundBox(inner.content, innerAt); return { kind: "compound", box, name: textBox(name.content.replace(/\\\\/g, " "), nameAt, NAME_FONT) }; } this.i += "\\chemfig".length; this.skipSpace(); if (this.src[this.i] === "[") { const options = readBalanced2(this.src, this.i, "[", "]", 0); if (options.content.trim() !== "") { fail("unsupported-option", "Options on \\chemfig itself are not supported.", this.i, options.content, "Set angles on the bonds instead."); } this.i = options.end; } this.skipSpace(); const body = readBalanced2(this.src, this.i, "{", "}", 0); const bodyAt = this.i + 1; this.i = body.end; return { kind: "compound", box: moleculeBox(body.content, bodyAt) }; } /** `\arrow(a--b){type[above][below]}[angle,length]`. */ arrow() { this.skipSpace(); const ends = this.src[this.i] === "(" ? this.arrowEnds() : {}; this.skipSpace(); let type = "->"; let above; let below; if (this.src[this.i] === "{") { const spec = readBalanced2(this.src, this.i, "{", "}", 0); const specAt = this.i + 1; this.i = spec.end; const parsed = parseArrowSpec(spec.content, specAt); type = parsed.type; above = parsed.above; below = parsed.below; } let coeff = 1; let angle = 0; this.skipSpace(); if (this.src[this.i] === "[") { const optionsAt = this.i + 1; const options = readBalanced2(this.src, this.i, "[", "]", 0); this.i = options.end; const [angleText = "", length2 = "", ...style] = options.content.split(","); if (angleText.trim() !== "") { angle = Number(angleText.trim().replace(/^:+/, "")); if (!Number.isFinite(angle)) fail("unsupported-option", `"${angleText.trim()}" is not an arrow angle.`, optionsAt, angleText.trim(), "Give it in degrees, such as [-90]."); } if (style.join(",").trim() !== "") fail("unsupported-option", "Arrow styles are not supported here.", optionsAt, style.join(",")); if (length2.trim() !== "") { coeff = Number(length2.trim()); if (!Number.isFinite(coeff) || coeff <= 0) fail("unsupported-option", `"${length2.trim()}" is not an arrow length.`, optionsAt, length2.trim()); } } return { kind: "arrow", type, coeff, angle, ...ends, ...above ? { above } : {}, ...below ? { below } : {} }; } /** * `(a--b)` after \arrow: a names the compound the arrow leaves, b the one * it arrives at, and `@a` leaves a compound named earlier, which is how a * scheme branches. Either side may be empty. */ arrowEnds() { const at = this.i + 1; const group = readBalanced2(this.src, this.i, "(", ")", 0); this.i = group.end; const dash = group.content.indexOf("--"); if (dash < 0) fail("syntax", "Name an arrow's ends as (a--b).", at, group.content); const ends = {}; for (const [raw, offset] of [[group.content.slice(0, dash), 0], [group.content.slice(dash + 2), dash + 2]]) { const name = raw.trim(); if (name === "") continue; const nameAt = at + offset + raw.indexOf(name); if (name.includes(".")) { fail("unsupported-option", "Anchors on an arrow's ends are not supported.", nameAt, name, "Arrows meet each compound at its edge; leave out the .anchor."); } if (!/^@?[A-Za-z0-9_]+$/.test(name)) fail("syntax", `"${name}" is not a compound's name.`, nameAt, name, "Use letters and digits, such as (r--p1)."); if (offset === 0) { if (name.startsWith("@")) ends.from = { name: name.slice(1), at: nameAt }; else ends.names = { name, at: nameAt }; } else { if (name.startsWith("@")) { fail("unsupported-option", "An arrow can't arrive at a compound drawn already.", nameAt, name, "An arrow may leave a named compound (@a--b), not return to one."); } ends.arrives = name; } } return ends; } }; function compoundBox(raw, at) { const trimmed = raw.trim(); const chemfig = /^\\chemfig\s*(\[[^\]]*\])?\s*\{/.exec(trimmed); if (chemfig) { const lead = raw.length - raw.trimStart().length; if (chemfig[1] !== void 0 && chemfig[1].slice(1, -1).trim() !== "") { fail("unsupported-option", "Options on \\chemfig itself are not supported.", at + lead, chemfig[1], "Set angles on the bonds instead."); } const open = trimmed.indexOf("{", chemfig[0].length - 1); const body = readBalanced2(trimmed, open, "{", "}", at + lead); if (trimmed.slice(body.end).trim() !== "") fail("syntax", "A \\chemname holds one compound.", at + lead + body.end); return moleculeBox(body.content, at + lead + open + 1); } return textBox(raw, at, FONT); } function labelBox(raw, at) { if (raw.trim() === "") return void 0; if (/^\s*\\chemfig\b/.test(raw)) return compoundBox(raw, at); return textBox(raw, at, LABEL_FONT); } function parseArrowSpec(raw, at) { const typeEnd = raw.indexOf("["); const typeText = (typeEnd < 0 ? raw : raw.slice(0, typeEnd)).trim() || "->"; if (!ARROW_TYPES.has(typeText)) { fail("unsupported-option", `"${typeText}" is not an arrow this build draws.`, at, typeText, "Use ->, <-, <-> or <=>."); } const labels = []; let i = typeEnd < 0 ? raw.length : typeEnd; while (i < raw.length) { while (i < raw.length && /\s/.test(raw[i])) i++; if (i >= raw.length) break; const group = readBalanced2(raw, i, "[", "]", at); labels.push({ content: group.content, at: at + i + 1 }); i = group.end; } if (labels.length > 2 && labels.slice(2).some((l) => l.content.trim() !== "")) { fail("unsupported-option", "An arrow takes a label above and one below; label angles are not supported.", labels[2].at); } const above = labels[0] ? labelBox(labels[0].content, labels[0].at) : void 0; const below = labels[1] ? labelBox(labels[1].content, labels[1].at) : void 0; return { type: typeText, ...above ? { above } : {}, ...below ? { below } : {} }; } var frame = (origin, d, along, across) => ({ x: origin.x + d.x * along + d.y * across, y: origin.y + d.y * along - d.x * across }); function head(tip, d, stroke) { return { kind: "path", points: [tip, frame(tip, d, -HEAD_LENGTH, HEAD_HALF), frame(tip, d, -HEAD_LENGTH, -HEAD_HALF)], closed: true, fill: { color: stroke.color, opacity: 1 } }; } function harpoon(tip, d, stroke) { return { kind: "path", points: [tip, frame(tip, d, -HEAD_LENGTH, HEAD_HALF * 1.4)], closed: false, stroke }; } function arrowItems(type, start, d, length2) { const stroke = { color: INK, width: BOND_WIDTH }; const at = (along, across = 0) => frame(start, d, along, across); const back = { x: -d.x, y: -d.y }; const tuck = HEAD_LENGTH * 0.5; switch (type) { case "->": return [line(at(0), at(length2 - tuck), stroke), head(at(length2), d, stroke)]; case "<-": return [line(at(tuck), at(length2), stroke), head(at(0), back, stroke)]; case "<->": return [line(at(tuck), at(length2 - tuck), stroke), head(at(0), back, stroke), head(at(length2), d, stroke)]; case "<=>": return [ line(at(0, EQUILIBRIUM_SEP), at(length2, EQUILIBRIUM_SEP), stroke), harpoon(at(length2, EQUILIBRIUM_SEP), d, stroke), line(at(0, -EQUILIBRIUM_SEP), at(length2, -EQUILIBRIUM_SEP), stroke), harpoon(at(0, -EQUILIBRIUM_SEP), back, stroke) ]; } } function centreBox(box, cx, cy) { if (box.items.length === 0) return []; const bx = (box.bounds.minX + box.bounds.maxX) / 2; const by = (box.bounds.minY + box.bounds.maxY) / 2; return shiftItems(box.items, cx - bx, cy - by); } var widthOf = (box) => box && box.items.length > 0 ? box.bounds.maxX - box.bounds.minX : 0; var heightOf = (box) => box && box.items.length > 0 ? box.bounds.maxY - box.bounds.minY : 0; var reach = (halfW, halfH, d) => Math.abs(d.x) * halfW + Math.abs(d.y) * halfH; function side(p, d) { if (Math.abs(d.x) >= 0.5) return { x: Math.sign(d.x) * p.halfW, y: 0 }; return { x: 0, y: d.y > 0 ? p.halfH + p.nameDepth : -p.halfH }; } var around = (c, halfW, up, down) => ({ minX: c.x - halfW, maxX: c.x + halfW, minY: c.y - up, maxY: c.y + down }); var overlaps = (a, b) => a.minX < b.maxX + LABEL_SEP && b.minX < a.maxX + LABEL_SEP && a.minY < b.maxY + LABEL_SEP && b.minY < a.maxY + LABEL_SEP; function layoutScheme(items) { const out = []; const named = /* @__PURE__ */ new Map(); const placed = []; const taken = []; let last = null; let cursor = { x: 0, y: 0 }; let pending = null; let previous = null; const drawArrow = (size) => { const { item, start, d, length: asked } = pending; pending = null; const lift = item.type === "<=>" ? EQUILIBRIUM_SEP : 0; const labels = []; if (item.above && item.above.items.length > 0) labels.push({ box: item.above, side: 1 }); if (item.below && item.below.items.length > 0) labels.push({ box: item.below, side: -1 }); const layout = (length2) => { const placedLabels = labels.map(({ box, side: s }) => { const off = lift + LABEL_SEP + reach(widthOf(box) / 2, heightOf(box) / 2, { x: d.y, y: d.x }); const at = frame(start, d, length2 / 2, s * off); return { box, at, bounds: around(at, widthOf(box) / 2, heightOf(box) / 2, heightOf(box) / 2) }; }); const tip = frame(start, d, length2, 0); let centre = { x: tip.x + d.x * ARROW_GAP, y: tip.y + d.y * ARROW_GAP }; const boxes = placedLabels.map((l) => l.bounds); if (size) { const meets = side(size, { x: -d.x, y: -d.y }); centre = { x: centre.x - meets.x, y: centre.y - meets.y }; boxes.push(around(centre, size.halfW, size.halfH, size.halfH + size.nameDepth)); } return { length: length2, placedLabels, tip, centre, clear: !boxes.some((b) => taken.some((t) => overlaps(b, t))) }; }; let chosen = layout(asked); for (let extra = EM / 2; !chosen.clear && extra <= 20 * EM; extra += EM / 2) { const longer = layout(asked + extra); if (longer.clear) chosen = longer; } if (!chosen.clear) chosen = layout(asked); out.push(...arrowItems(item.type, start, d, chosen.length)); for (const l of chosen.placedLabels) { out.push(...centreBox(l.box, l.at.x, l.at.y)); taken.push(l.bounds); } cursor = chosen.tip; return chosen.centre; }; for (const item of items) { if (item.kind !== "compound" && pending) drawArrow(); if (item.kind === "compound") { const halfW = Math.max(widthOf(item.box), widthOf(item.name)) / 2; const halfH = heightOf(item.box) / 2; const nameDepth = item.name && item.name.items.length > 0 ? NAME_SEP + heightOf(item.name) : 0; const size = { halfW, halfH, nameDepth }; const arrives = pending?.item.arrives; const centre = pending ? drawArrow(size) : { x: cursor.x + (previous === "compound" ? PLUS_GAP * 2 : 0) + halfW, y: cursor.y }; const here = { cx: centre.x, cy: centre.y, ...size }; out.push(...centreBox(item.box, here.cx, here.cy)); taken.push(around(centre, halfW, halfH, halfH + nameDepth)); placed.push(item.name && item.name.items.length > 0 ? { at: here, name: item.name } : { at: here }); if (arrives) named.set(arrives, here); last = here; cursor = { x: here.cx + halfW, y: here.cy }; } else if (item.kind === "plus") { const from = previous === "arrow" ? { x: cursor.x + ARROW_GAP, y: cursor.y } : cursor; const runs = [{ text: "+", baseline: "normal", italic: false }]; const w = runsWidth(runs, FONT); out.push(centredText(runs, { x: from.x + PLUS_GAP + w / 2, y: from.y }, FONT)); cursor = { x: from.x + PLUS_GAP + w + PLUS_GAP, y: from.y }; } else { let from = last; if (item.from) { from = named.get(item.from.name) ?? null; if (!from) fail("syntax", `No compound before this arrow is named "${item.from.name}".`, item.from.at, `@${item.from.name}`, "Name it on an arrow that leaves it, as \\arrow(a--b)."); } if (item.names) { if (!from) fail("syntax", `There is no compound before this arrow to name "${item.names.name}".`, item.names.at, item.names.name); named.set(item.names.name, from); } const d = { x: Math.cos(rad(item.angle)), y: -Math.sin(rad(item.angle)) }; const leave = from ? { x: from.cx + side(from, d).x, y: from.cy + side(from, d).y } : cursor; const along = (box) => box && box.items.length > 0 ? reach(widthOf(box), heightOf(box), d) : 0; const length2 = Math.max(ARROW_LENGTH * item.coeff, along(item.above) + EM, along(item.below) + EM); pending = { item, start: frame(leave, d, ARROW_GAP, 0), d, length: length2 }; last = null; } previous = item.kind; } if (pending) drawArrow(); const rows = /* @__PURE__ */ new Map(); for (const p of placed) rows.set(Math.round(p.at.cy), [...rows.get(Math.round(p.at.cy)) ?? [], p]); for (const row2 of rows.values()) { const nameLine = Math.max(...row2.map((p) => p.at.cy + p.at.halfH)) + NAME_SEP + 0.5 * NAME_FONT; for (const p of row2) if (p.name) out.push(...centreBox(p.name, p.at.cx, nameLine)); } return out; } function isChemistrySource(source) { return /^\s*\\(chemfig|chemname|schemestart)(?![A-Za-z])/.test(source); } function chemistryToScene(source) { let body = source; const start = /^\s*\\schemestart(?![A-Za-z])/.exec(source); if (start) { const stop = source.lastIndexOf("\\schemestop"); if (stop < 0) fail("syntax", "\\schemestart has no \\schemestop.", start[0].length - "\\schemestart".length, "schemestart"); if (source.slice(stop + "\\schemestop".length).trim() !== "") { fail("syntax", "Nothing can follow \\schemestop.", stop + "\\schemestop".length); } body = " ".repeat(start[0].length) + source.slice(start[0].length, stop); } const reader = new SchemeReader(body); reader.read(); if (reader.items.length === 0) fail("syntax", "There is no structure to draw.", 0); const items = layoutScheme(reader.items); const b = boundsOfItems(items); if (!Number.isFinite(b.minX)) fail("syntax", "There is no structure to draw.", 0); return { width: b.maxX - b.minX + PADDING * 2, height: b.maxY - b.minY + PADDING * 2, items: shiftItems(items, PADDING - b.minX, PADDING - b.minY) }; } // graphics/src/tikz-draw.ts init_define_L2W_CONFIG(); // graphics/src/circuits.ts init_define_L2W_CONFIG(); var line2 = (points, weight = 1) => ({ points, closed: false, fill: "none", weight }); var shape = (points, fill) => ({ points, closed: true, fill, weight: 1 }); var P = (x, y) => ({ x, y }); function circle(cx, cy, r, steps = 40) { const out = []; for (let i = 0; i < steps; i++) out.push(P(cx + r * Math.cos(2 * Math.PI * i / steps), cy + r * Math.sin(2 * Math.PI * i / steps))); return out; } function arrowHead(tip, dx, dy, size = 0.13) { const n = Math.hypot(dx, dy) || 1; const [ux, uy] = [dx / n, dy / n]; return shape([tip, P(tip.x - ux * size - uy * size * 0.4, tip.y - uy * size + ux * size * 0.4), P(tip.x - ux * size + uy * size * 0.4, tip.y - uy * size - ux * size * 0.4)], "ink"); } function zigzag(half, amp, teeth = 6) { const pts = [P(-half, 0)]; const step2 = 2 * half / teeth; for (let i = 0; i < teeth; i++) pts.push(P(-half + (i + 0.5) * step2, i % 2 === 0 ? amp : -amp)); pts.push(P(half, 0)); return pts; } function round(r, inside2 = [], letters = []) { return { half: r, reach: r, shapes: [shape(circle(0, 0, r), "paper"), ...inside2], letters }; } function meter(letter) { return round(0.3, [], [{ text: letter, at: P(0, 0) }]); } function diode(filled) { return [shape([P(-0.2, -0.2), P(-0.2, 0.2), P(0.2, 0)], filled ? "ink" : "paper"), line2([P(0.2, -0.2), P(0.2, 0.2)])]; } var RESISTOR = { half: 0.45, reach: 0.15, shapes: [line2(zigzag(0.45, 0.15))] }; var BOX_RESISTOR = { half: 0.45, reach: 0.13, shapes: [shape([P(-0.45, -0.13), P(0.45, -0.13), P(0.45, 0.13), P(-0.45, 0.13)], "paper")] }; function inductor() { const pts = []; for (let k = 0; k < 4; k++) { const cx = -0.375 + 0.25 * k; for (let i = 0; i <= 12; i++) pts.push(P(cx - 0.125 * Math.cos(Math.PI * i / 12), 0.125 * Math.sin(Math.PI * i / 12))); } return { half: 0.5, reach: 0.15, shapes: [line2(pts)] }; } function cells(n) { const gap = 0.16; const shapes = []; const half = gap * (2 * n - 1) / 2; for (let i = 0; i < 2 * n; i++) { const x = -half + i * gap; const long = i % 2 === 1; shapes.push(line2([P(x, long ? -0.35 : -0.18), P(x, long ? 0.35 : 0.18)], long ? 1 : 2)); } if (n > 2) shapes.push({ ...line2([P(-half + gap * 1.5, 0), P(half - gap * 1.5, 0)]), weight: 1 }); return { half, reach: 0.35, shapes }; } function sineInside() { const pts = []; for (let i = 0; i <= 24; i++) pts.push(P(-0.2 + 0.4 * i / 24, 0.1 * Math.sin(2 * Math.PI * i / 24))); return line2(pts); } var SYMBOLS = { short: () => "short", open: () => "open", R: (f) => f.has("european") ? BOX_RESISTOR : RESISTOR, resistor: (f) => f.has("european") ? BOX_RESISTOR : RESISTOR, "american resistor": () => RESISTOR, "european resistor": () => BOX_RESISTOR, generic: () => BOX_RESISTOR, vR: () => ({ ...RESISTOR, reach: 0.35, shapes: [...RESISTOR.shapes, line2([P(-0.4, -0.3), P(0.3, 0.24)]), arrowHead(P(0.4, 0.32), 0.8, 0.62)] }), "variable resistor": () => SYMBOLS.vR(/* @__PURE__ */ new Set()), rheostat: () => SYMBOLS.vR(/* @__PURE__ */ new Set()), pR: () => ({ ...RESISTOR, reach: 0.5, shapes: [...RESISTOR.shapes, line2([P(0, 0.55), P(0, 0.3)]), arrowHead(P(0, 0.17), 0, -1)] }), potentiometer: () => SYMBOLS.pR(/* @__PURE__ */ new Set()), C: () => ({ half: 0.1, reach: 0.3, shapes: [line2([P(-0.1, -0.3), P(-0.1, 0.3)], 1.4), line2([P(0.1, -0.3), P(0.1, 0.3)], 1.4)] }), capacitor: () => SYMBOLS.C(/* @__PURE__ */ new Set()), L: () => inductor(), inductor: () => inductor(), "american inductor": () => inductor(), "cute inductor": () => inductor(), battery1: () => cells(1), cell: () => cells(1), battery: () => cells(2), battery2: () => cells(2), V: () => round(0.35, [], [{ text: "+", at: P(0.17, 0) }, { text: "\u2212", at: P(-0.17, 0) }]), "american voltage source": () => SYMBOLS.V(/* @__PURE__ */ new Set()), vsource: () => round(0.35, [line2([P(-0.35, 0), P(0.35, 0)])]), sV: () => round(0.35, [sineInside()]), vsourcesin: () => round(0.35, [sineInside()]), "sinusoidal voltage source": () => round(0.35, [sineInside()]), I: () => round(0.35, [line2([P(-0.2, 0), P(0.12, 0)]), arrowHead(P(0.22, 0), 1, 0)]), isource: () => SYMBOLS.I(/* @__PURE__ */ new Set()), "american current source": () => SYMBOLS.I(/* @__PURE__ */ new Set()), lamp: () => round(0.3, [line2([P(-0.21, -0.21), P(0.21, 0.21)]), line2([P(-0.21, 0.21), P(0.21, -0.21)])]), bulb: () => round(0.3, [line2([P(-0.21, -0.21), P(0.21, 0.21)]), line2([P(-0.21, 0.21), P(0.21, -0.21)])]), ammeter: () => meter("A"), voltmeter: () => meter("V"), ohmmeter: () => meter("\u03A9"), galvanometer: () => meter("G"), wattmeter: () => meter("W"), switch: () => ({ half: 0.3, reach: 0.25, shapes: [shape(circle(-0.25, 0, 0.05, 12), "paper"), shape(circle(0.25, 0, 0.05, 12), "paper"), line2([P(-0.25, 0), P(0.2, 0.25)])] }), nos: () => SYMBOLS.switch(/* @__PURE__ */ new Set()), spst: () => SYMBOLS.switch(/* @__PURE__ */ new Set()), "opening switch": () => SYMBOLS.switch(/* @__PURE__ */ new Set()), ncs: () => ({ half: 0.3, reach: 0.12, shapes: [shape(circle(-0.25, 0, 0.05, 12), "paper"), shape(circle(0.25, 0, 0.05, 12), "paper"), line2([P(-0.25, 0), P(0.27, 0.06)])] }), "closing switch": () => SYMBOLS.ncs(/* @__PURE__ */ new Set()), cspst: () => SYMBOLS.ncs(/* @__PURE__ */ new Set()), key: () => SYMBOLS.switch(/* @__PURE__ */ new Set()), D: () => ({ half: 0.2, reach: 0.2, shapes: diode(false) }), diode: () => ({ half: 0.2, reach: 0.2, shapes: diode(false) }), "D*": () => ({ half: 0.2, reach: 0.2, shapes: diode(true) }), "full diode": () => ({ half: 0.2, reach: 0.2, shapes: diode(true) }), led: () => ({ half: 0.2, reach: 0.45, shapes: [...diode(false), line2([P(-0.02, 0.25), P(0.12, 0.42)]), arrowHead(P(0.17, 0.48), 0.14, 0.17, 0.09), line2([P(0.12, 0.22), P(0.26, 0.39)]), arrowHead(P(0.31, 0.45), 0.14, 0.17, 0.09)] }), zD: () => ({ half: 0.2, reach: 0.2, shapes: [shape([P(-0.2, -0.2), P(-0.2, 0.2), P(0.2, 0)], "paper"), line2([P(0.12, -0.24), P(0.2, -0.2), P(0.2, 0.2), P(0.28, 0.24)])] }), zener: () => SYMBOLS.zD(/* @__PURE__ */ new Set()), fuse: () => ({ half: 0.3, reach: 0.1, shapes: [shape([P(-0.3, -0.1), P(0.3, -0.1), P(0.3, 0.1), P(-0.3, 0.1)], "paper"), line2([P(-0.3, 0), P(0.3, 0)])] }) }; var COMPONENT_NAMES = Object.keys(SYMBOLS); var LABEL_KEY = /^(l|a|v|i|i>|i<|i_|i\^|i>_|i>\^|i<_|i<\^|l_|l\^|a_|a\^|v_|v\^|v<|v>)$/; function componentIn(options) { const found = options.find((o) => o.key in SYMBOLS); if (!found) return null; return { name: found.key, label: found.value === void 0 || found.value === "" ? null : unbrace(found.value), rest: options.filter((o) => o !== found) }; } var OTHER_KEYS = /* @__PURE__ */ new Set(["color", "thick", "very thick", "thin", "line width", "invert", "mirror", "name", "n"]); function drawComponent(name, label, rest, from, to, flags, isTerminalKey) { const made = SYMBOLS[name](flags); const dx = to.x - from.x; const dy = to.y - from.y; const length2 = Math.hypot(dx, dy); const u = length2 === 0 ? P(1, 0) : P(dx / length2, dy / length2); let n = P(-u.y, u.x); if (rest.some((o) => o.key === "mirror")) n = P(-n.x, -n.y); const invert3 = rest.some((o) => o.key === "invert"); const mid = P((from.x + to.x) / 2, (from.y + to.y) / 2); for (const o of rest) { if (!LABEL_KEY.test(o.key) && !OTHER_KEYS.has(o.key) && !isTerminalKey(o.key)) { fail("unsupported-option", `"${o.key}" is not an option this build understands on a circuit component.`, o.at, o.key, "Supported: a label (R=$R$, l=\u2026, l_=\u2026, a=\u2026, v=\u2026, i=\u2026), terminals (*-*, o-o, -o), mirror, invert."); } } if (made === "open") return { open: true, bodyStart: from, bodyEnd: to, shapes: [], labels: [], letters: [] }; const symbol = made === "short" ? { half: 0, reach: 0, shapes: [] } : made; const k = symbol.half === 0 ? 1 : Math.min(1, length2 * 0.9 / (2 * symbol.half)); const flip = invert3 ? -1 : 1; const place = (p) => { const x = p.x * k * flip; const y = p.y * k; return P(mid.x + u.x * x + n.x * y, mid.y + u.y * x + n.y * y); }; const shapes = symbol.shapes.map((s) => ({ ...s, points: s.points.map(place) })); const letters = (symbol.letters ?? []).map((l) => ({ text: l.text, at: place(l.at) })); const labels = []; const reach2 = Math.max(symbol.reach * k, 0.05) + 0.08; const side2 = (under) => under ? P(-n.x, -n.y) : n; const text = (raw) => unbrace(raw); const add2 = (raw, under) => { const d = side2(under); labels.push({ text: text(raw), at: P(mid.x + d.x * reach2, mid.y + d.y * reach2), dir: d }); }; if (label) add2(label, false); for (const o of rest) { if (o.value === void 0) continue; if (o.key === "l" || o.key === "l^") add2(o.value, false); else if (o.key === "l_" || o.key === "a" || o.key === "a_") add2(o.value, true); else if (o.key === "a^") add2(o.value, false); else if (/^v/.test(o.key)) add2(o.value, o.key !== "v^"); } const current = rest.find((o) => /^i/.test(o.key) && o.value !== void 0); if (current) { const back = current.key.includes("<"); const under = current.key.includes("_"); const gap = Math.max(0, length2 / 2 - symbol.half * k); const along = symbol.half * k + (gap > 0.3 ? gap / 2 : 0.15); const tip = P(mid.x + u.x * along, mid.y + u.y * along); shapes.push(arrowHead(tip, back ? -u.x : u.x, back ? -u.y : u.y, 0.16)); const d = side2(under); labels.push({ text: text(current.value), at: P(tip.x + d.x * 0.12, tip.y + d.y * 0.12), dir: d }); } const ends = symbol.half * k; return { open: false, bodyStart: P(mid.x - u.x * ends, mid.y - u.y * ends), bodyEnd: P(mid.x + u.x * ends, mid.y + u.y * ends), shapes, labels, letters }; } function groundShapes(at) { const top = at.y - 0.2; return [line2([at, P(at.x, top)]), line2([P(at.x - 0.22, top), P(at.x + 0.22, top)]), line2([P(at.x - 0.14, top - 0.07), P(at.x + 0.14, top - 0.07)]), line2([P(at.x - 0.06, top - 0.14), P(at.x + 0.06, top - 0.14)])]; } function terminalShape(at, open) { return shape(circle(at.x, at.y, 0.06, 16), open ? "paper" : "ink"); } // graphics/src/tikz-draw.ts var IDENTITY = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }; var apply = (t, p) => ({ x: t.a * p.x + t.c * p.y + t.e, y: t.b * p.x + t.d * p.y + t.f }); var applyLinear = (t, p) => ({ x: t.a * p.x + t.c * p.y, y: t.b * p.x + t.d * p.y }); function compose(outer, inner) { return { a: outer.a * inner.a + outer.c * inner.b, b: outer.b * inner.a + outer.d * inner.b, c: outer.a * inner.c + outer.c * inner.d, d: outer.b * inner.c + outer.d * inner.d, e: outer.a * inner.e + outer.c * inner.f + outer.e, f: outer.b * inner.e + outer.d * inner.f + outer.f }; } function invert(t) { const det = t.a * t.d - t.b * t.c; if (Math.abs(det) < 1e-12) fail("unsupported-option", "A scale of 0 flattens the picture to nothing.", 0, "scale"); return { a: t.d / det, b: -t.b / det, c: -t.c / det, d: t.a / det, e: (t.c * t.f - t.d * t.e) / det, f: (t.b * t.e - t.a * t.f) / det }; } var translate = (x, y) => ({ ...IDENTITY, e: x, f: y }); var scaleBy = (x, y) => ({ ...IDENTITY, a: x, d: y }); function rotateBy(deg) { const r = deg * Math.PI / 180; return { a: Math.cos(r), b: Math.sin(r), c: -Math.sin(r), d: Math.cos(r), e: 0, f: 0 }; } var TRANSFORM_KEYS = /* @__PURE__ */ new Set(["shift", "xshift", "yshift", "rotate", "rotate around", "scale", "xscale", "yscale", "x", "y"]); function readTransform(options) { let t = IDENTITY; const rest = []; for (const o of options) { if (!TRANSFORM_KEYS.has(o.key) || o.value === void 0) { rest.push(o); continue; } const value = unbrace(o.value); switch (o.key) { case "shift": { const p = plainPoint(value, o.at); t = compose(t, translate(p.x, p.y)); break; } case "xshift": t = compose(t, translate(length(value, o.at, "pt"), 0)); break; case "yshift": t = compose(t, translate(0, length(value, o.at, "pt"))); break; case "rotate": t = compose(t, rotateBy(number(value, o.at, o.key))); break; case "rotate around": { const m = /^([^:]+):\s*\((.*)\)$/.exec(value); if (!m) fail("unsupported-option", "rotate around is written rotate around={30:(1,2)}.", o.at, o.key); const p = plainPoint(m[2], o.at); t = compose(t, compose(translate(p.x, p.y), compose(rotateBy(number(m[1], o.at, o.key)), translate(-p.x, -p.y)))); break; } case "scale": { const s = number(value, o.at, o.key); t = compose(t, scaleBy(s, s)); break; } case "xscale": t = compose(t, scaleBy(number(value, o.at, o.key), 1)); break; case "yscale": t = compose(t, scaleBy(1, number(value, o.at, o.key))); break; case "x": t = compose(t, scaleBy(length(value, o.at, "cm"), 1)); break; case "y": t = compose(t, scaleBy(1, length(value, o.at, "cm"))); break; } } return { transform: t, rest }; } var PT = 1 / 28.4527559; var UNITS = { cm: 1, mm: 0.1, pt: PT, bp: 2.54 / 72, in: 2.54, pc: 12 * PT, em: 10 * PT, ex: 4.3 * PT, px: 2.54 / 96 }; var PX_PER_CM = 37.8; function pgfmath(text) { return text.replace(/\s+r(?=\s*[)*/+\-,^]|\s*$)/g, "*57.29577951308232").replace(/\\pi\b/g, "pi"); } function number(raw, at, what, env = {}, variables = []) { const text = unbrace(raw).trim(); const direct = Number(text); if (text !== "" && Number.isFinite(direct)) return direct; let value; try { value = evaluate(parseExpr(pgfmath(text), at, variables), env); } catch { fail("bad-coordinate", `"${raw.trim()}" is not a number this build can read for ${what}.`, at, raw.trim()); } if (!Number.isFinite(value)) fail("bad-coordinate", `"${raw.trim()}" has no value for ${what}.`, at, raw.trim()); return value; } function length(raw, at, bare) { const text = unbrace(raw).trim(); const m = /^([-+]?(?:\d+\.?\d*|\.\d+))\s*(cm|mm|pt|bp|in|pc|em|ex|px)$/.exec(text); if (m) return Number(m[1]) * UNITS[m[2]]; const unit = /^(.*?)\s*\*?\s*(cm|mm|pt|bp|in|pc|em|ex|px)$/.exec(text); if (unit && unit[1] && !/[A-Za-z]$/.test(unit[1])) return number(unit[1], at, "a length") * UNITS[unit[2]]; return number(text, at, "a length") * (bare === "pt" ? PT : 1); } function splitTop(text, sep3 = ",") { const out = []; let depth = 0; let start = 0; for (let i = 0; i < text.length; i++) { const ch = text[i]; if (ch === "{" || ch === "(" || ch === "[") depth++; else if (ch === "}" || ch === ")" || ch === "]") depth--; else if (depth === 0 && text.startsWith(sep3, i)) { out.push(text.slice(start, i)); start = i + sep3.length; } } out.push(text.slice(start)); return out; } function plainPoint(raw, at) { const text = raw.trim().replace(/^\(|\)$/g, ""); const parts = splitTop(text); if (parts.length === 2) return { x: length(parts[0], at, "cm"), y: length(parts[1], at, "cm") }; const polar = splitTop(text, ":"); if (polar.length === 2) { const a = number(polar[0], at, "an angle") * Math.PI / 180; const r = length(polar[1], at, "cm"); return { x: r * Math.cos(a), y: r * Math.sin(a) }; } fail("bad-coordinate", `"(${text})" is not a coordinate this build can read.`, at, text); } var PLAIN_COORD = /^\s*-?(?:\d+\.?\d*|\.\d+)\s*,\s*-?(?:\d+\.?\d*|\.\d+)\s*$/; function plainCoord(c) { return PLAIN_COORD.test(c.raw) ? { start: c.at, end: c.at + c.raw.length, raw: c.raw } : null; } var PLAIN_RADIUS = /^\s*(?:\d+\.?\d*|\.\d+)\s*$/; var PLAIN_ARC = /^\s*-?(?:\d+\.?\d*|\.\d+)\s*:\s*-?(?:\d+\.?\d*|\.\d+)\s*:\s*(?:\d+\.?\d*|\.\d+)\s*$/; function pathCoords(parts) { const out = []; let here = -1; const circles = []; let circleCount = 0; const arcs = []; const rectangles = []; let rotate = "free"; let flip = true; const fixed = (mirror) => { rotate = "none"; flip = flip && mirror; }; const take = (c, relative) => { if (relative !== "") { here = -1; fixed(false); return true; } const plain = plainCoord(c); if (plain) out.push(plain); here = out.length - 1; return plain !== null; }; for (const part of parts) { let ok = true; switch (part.kind) { case "point": if (part.op === "|-" || part.op === "-|") fixed(true); ok = take(part.coord, part.relative); break; case "curve": ok = take(part.c1, part.c1Relative) && (!part.c2 || take(part.c2, part.c2Relative)) && take(part.to, part.relative); break; case "to": if (part.options.length > 0) fixed(false); ok = take(part.to, part.relative); break; case "rectangle": { const from = here; ok = take(part.to, part.relative); if (ok && from >= 0 && part.relative === "") rectangles.push({ from, to: out.length - 1 }); else fixed(false); break; } case "grid": if (rotate === "free") rotate = "quarter"; ok = take(part.to, part.relative); break; case "plot": ok = "coordinates" in part.data && part.data.coordinates.every((c) => take(c, "")); here = -1; break; case "circle": circleCount++; if (part.radius !== null && part.radiusAt !== void 0 && here >= 0 && PLAIN_RADIUS.test(part.radius)) { circles.push({ radius: { start: part.radiusAt, end: part.radiusAt + part.radius.length, raw: part.radius }, center: here }); } if (part.radius?.includes("and") || part.options.some((o) => o.key === "x radius" || o.key === "y radius")) fixed(true); break; case "arc": if (part.spec !== null && part.specAt !== void 0 && PLAIN_ARC.test(part.spec)) arcs.push({ start: part.specAt, end: part.specAt + part.spec.length, raw: part.spec }); else fixed(false); here = -1; break; default: break; } if (!ok) return null; } if (out.length === 0) return null; const placed = { coords: out, turns: { rotate, flip }, arcs, rectangles }; return circleCount === 1 && circles.length === 1 ? { ...placed, circle: circles[0] } : placed; } function traced(drawn, s, placed, transform, ctx) { if (!s.src) return [...drawn]; const move = placed && !s.fromLoop && !ctx.axis ? { ...placed, transform } : null; return drawn.map((d) => { const { textSrc, ...rest } = d; return { ...rest, src: s.src, ...move ? { move } : {}, ...textSrc && !s.fromLoop ? { textSrc } : {} }; }); } function newContext(pxPerUnit, axis) { return { store: /* @__PURE__ */ new Map(), nodes: /* @__PURE__ */ new Map(), styles: /* @__PURE__ */ new Map([["help lines", parseOptions("gray!70, very thin")]]), pxPerUnit, axis, flags: /* @__PURE__ */ new Set() }; } function expandStyles(options, ctx, depth = 0) { if (depth > 10) fail("unsupported-option", "These styles refer to each other in a loop.", options[0]?.at ?? 0, options[0]?.key); const out = []; for (const o of options) { const style = o.value === void 0 ? ctx.styles.get(o.key) : void 0; if (style) out.push(...expandStyles(style.map((s) => ({ ...s, at: o.at })), ctx, depth + 1)); else out.push(o); } return out; } var NODE_INHERITED = /* @__PURE__ */ new Set(["font", "text", "color", "inner sep"]); var CIRCUIT_STYLES = /* @__PURE__ */ new Set(["american", "european", "american resistors", "european resistors", "american voltages", "european voltages", "american currents", "european currents", "american inductors", "cute inductors", "american ports", "siunitx", "straight voltages", "nooldvoltagedirection", "RPvoltages", "EFvoltages"]); var IGNORED_SCOPE_KEYS = /* @__PURE__ */ new Set(["baseline", ">", "line cap", "line join", "every picture/.style", "transform shape"]); function enterScope(options, frame2, ctx) { const definitions = []; const used = []; for (const o of options) { const def = /^(.*?)\/\.(style|append style)$/.exec(o.key); if (def && o.value !== void 0) { const name = def[1].trim(); const body = parseOptions(unbrace(o.value), o.at + 1); if (name === "every node") definitions.push({ key: "__every node", value: o.value, at: o.at }); else ctx.styles.set(name, def[2] === "append style" ? [...ctx.styles.get(name) ?? [], ...body] : body); continue; } used.push(o); } const expanded = expandStyles(used, ctx); const { transform, rest } = readTransform(expanded); const inherited = []; const nodeStyle = []; for (const d of definitions) nodeStyle.push(...expandStyles(parseOptions(unbrace(d.value), d.at + 1), ctx)); const { color, rest: uncolored } = currentColor(rest); if (color !== void 0) { const entry = { key: "color", value: color, at: rest[0]?.at ?? 0 }; inherited.push(entry); nodeStyle.push(entry); } for (const o of uncolored) { if (IGNORED_SCOPE_KEYS.has(o.key)) continue; if (CIRCUIT_STYLES.has(o.key)) { if (o.key === "european" || o.key === "european resistors") ctx.flags.add("european"); if (o.key === "american" || o.key === "american resistors") ctx.flags.delete("european"); continue; } if (!DRAW_KEYS.has(o.key) && !NODE_KEYS.has(o.key) && !(o.value === void 0 && arrowKey(o.key))) { fail("unsupported-option", `"${o.key}" is not an option this build understands on a picture or scope.`, o.at, o.key, "Supported: scale, shift, rotate, xshift, yshift, styles (name/.style={\u2026}, every node/.style={\u2026}), and the options of \\draw."); } if (NODE_INHERITED.has(o.key)) nodeStyle.push(o); if (o.key !== "font" && o.key !== "inner sep" && o.key !== "text") inherited.push(o); } return { transform: compose(frame2.transform, transform), inherited: [...frame2.inherited, ...inherited], nodeStyle: [...frame2.nodeStyle, ...nodeStyle] }; } var ANCHORS = { center: [0, 0], base: [0, -0.3], "base west": [-1, -0.3], "base east": [1, -0.3], mid: [0, 0], text: [0, 0], north: [0, 1], south: [0, -1], east: [1, 0], west: [-1, 0], "north east": [1, 1], "north west": [-1, 1], "south east": [1, -1], "south west": [-1, -1] }; function borderPoint(box, dx, dy) { if (dx === 0 && dy === 0) return box.center; if (box.shape === "rectangle") { const s = Math.min(box.halfW / Math.abs(dx || 1e-12), box.halfH / Math.abs(dy || 1e-12)); return { x: box.center.x + dx * s, y: box.center.y + dy * s }; } const t = 1 / Math.sqrt((dx / box.halfW) ** 2 + (dy / box.halfH) ** 2); return { x: box.center.x + dx * t, y: box.center.y + dy * t }; } function anchorOf(box, anchor, at, raw) { const named = ANCHORS[anchor]; if (named) { if (box.shape === "rectangle") return { x: box.center.x + named[0] * box.halfW, y: box.center.y + named[1] * box.halfH }; const [x, y] = named; const n = Math.hypot(x, y) || 1; return borderPoint(box, x / n, y / n); } const angle = Number(anchor); if (Number.isFinite(angle)) return borderPoint(box, Math.cos(angle * Math.PI / 180), Math.sin(angle * Math.PI / 180)); fail("bad-coordinate", `"${anchor}" is not an anchor of a node.`, at, raw, "Anchors: north, south, east, west, north east, \u2026, center, or an angle like (A.30)."); } var Resolver = class { constructor(ctx, transform) { this.ctx = ctx; this.transform = transform; } /** A coordinate in canvas units. `current` is the path's current point, for `+` and `++`. */ resolve(coord, relative, current) { let text = coord.raw.trim(); if (this.ctx.axis) text = text.replace(/^axis cs:\s*/, ""); if (text === "") fail("bad-coordinate", "An empty coordinate.", coord.at, text); if (relative) { if (!current) fail("bad-coordinate", `"${relative}(${text})" needs a point before it to start from.`, coord.at, text); const offset = this.local(text, coord.at); return { p: add(current, applyLinear(this.transform, offset)), ref: null }; } if (text.startsWith("$") && text.endsWith("$")) { if (this.ctx.axis) fail("bad-coordinate", "Calculated coordinates ($\u2026$) can't be used inside an axis.", coord.at, text); return { p: this.calc(text.slice(1, -1), coord.at), ref: null }; } if (splitTop(text).length === 2 || splitTop(text, ":").length === 2) { if (this.ctx.axis && splitTop(text).length !== 2) { fail("bad-coordinate", `"(${coord.raw})" is not a point in the axis \u2014 write it as (axis cs:x,y).`, coord.at, coord.raw); } return { p: apply(this.transform, this.local(text, coord.at)), ref: null }; } if (this.ctx.axis) fail("bad-coordinate", `"(${coord.raw})" is not a point in the axis \u2014 write it as (axis cs:x,y).`, coord.at, coord.raw); if (!/^[A-Za-z][A-Za-z0-9_' .-]*$/.test(text)) fail("bad-coordinate", `"(${text})" is not a coordinate this build can read.`, coord.at, text); return this.named(text, coord.at); } /** `(x,y)` or `(a:r)` in the coordinates it's written in, before the transform. */ local(text, at) { const parts = splitTop(text); if (parts.length === 2) return { x: length(parts[0], at, "cm"), y: length(parts[1], at, "cm") }; const polar = splitTop(text, ":"); if (polar.length === 2) { const a = number(polar[0], at, "an angle") * Math.PI / 180; const radii = splitTop(polar[1], " and "); const rx = length(radii[0], at, "cm"); const ry = radii.length === 2 ? length(radii[1], at, "cm") : rx; return { x: rx * Math.cos(a), y: ry * Math.sin(a) }; } if (/^[A-Za-z]/.test(text)) fail("bad-coordinate", `"+(${text})" moves by an amount, which a name isn't.`, at, text); fail("bad-coordinate", `"(${text})" is not a coordinate this build can read.`, at, text); } named(text, at) { const node = this.ctx.nodes.get(text); if (node) return { p: node.center, ref: node }; const point = this.ctx.store.get(text); if (point) return { p: point, ref: null }; const dot = text.indexOf("."); if (dot > 0) { const box = this.ctx.nodes.get(text.slice(0, dot)); if (box) return { p: anchorOf(box, text.slice(dot + 1).trim(), at, text), ref: null }; const p = this.ctx.store.get(text.slice(0, dot)); if (p) return { p, ref: null }; } const known = [...this.ctx.nodes.keys(), ...this.ctx.store.keys()]; fail( "undefined-point", `The point "${text}" has not been defined.`, at, text, known.length === 0 ? "No points have been defined yet in this picture. Name one first: \\coordinate (A) at (1,2);" : `Points defined so far: ${known.join(", ")}.` ); } /** `$(A)!0.5!(B)$`, `$(A)+(1,0)$`, `$0.5*(A)+0.5*(B)$`. */ calc(text, at) { let i = 0; const skip = () => { while (i < text.length && /\s/.test(text[i])) i++; }; const coordinate = () => { skip(); if (text[i] !== "(") fail("bad-coordinate", `In $\u2026$, expected a coordinate in brackets.`, at, text); const { raw, end } = readBalanced(text, i, "(", ")"); i = end; const inner = raw.trim(); const p = splitTop(inner).length === 2 || splitTop(inner, ":").length === 2 ? apply(this.transform, this.local(inner, at)) : this.named(inner, at).p; skip(); if (text[i] === "!") { const close = text.indexOf("!", i + 1); if (close < 0) fail("bad-coordinate", "In $\u2026$, a partway point is written (A)!0.5!(B).", at, text); const amount = text.slice(i + 1, close).trim(); i = close + 1; const q = coordinate(); const d = { x: q.x - p.x, y: q.y - p.y }; if (/[a-z]$/.test(amount)) { const dist = length(amount, at, "cm"); const n = Math.hypot(d.x, d.y) || 1; return { x: p.x + d.x / n * dist, y: p.y + d.y / n * dist }; } const t = number(amount, at, "a partway amount"); return { x: p.x + d.x * t, y: p.y + d.y * t }; } return p; }; const term = () => { skip(); const factor = /^([-+]?(?:\d+\.?\d*|\.\d+))\s*\*/.exec(text.slice(i)); if (factor) { i += factor[0].length; const p = coordinate(); const k = Number(factor[1]); return { x: p.x * k, y: p.y * k }; } return coordinate(); }; let total = term(); for (; ; ) { skip(); const op = text[i]; if (op !== "+" && op !== "-") break; i++; const next = term(); total = op === "+" ? add(total, next) : { x: total.x - next.x, y: total.y - next.y }; } skip(); if (i < text.length) fail("bad-coordinate", `"$${text}$" is not a calculation this build can read.`, at, text); return total; } }; var add = (a, b) => ({ x: a.x + b.x, y: a.y + b.y }); var ARROW_NAMES = ["latex'", "latex", "Latex", "stealth'", "stealth", "Stealth", "to", "To", "Triangle", "triangle 45", "triangle 60", "triangle 90", "Straight Barb", "Classical TikZ Rightarrow", "Kite", "Computer Modern Rightarrow", "Rays"]; var DOT_NAMES = ["Circle", "circle", "o", "*", "Square", "Diamond"]; function tipSpec(spec) { let s = spec.trim(); if (s === "") return null; let arrows2 = 0; let bar = false; let dot = false; let open = false; while (s.length > 0) { if (s.startsWith("{")) { let inner; try { const r = readBalanced(s, 0, "{", "}"); inner = r.raw; s = s.slice(r.end).trim(); } catch { return void 0; } const name2 = inner.split("[")[0].trim(); if (ARROW_NAMES.includes(name2) || name2 === ">") arrows2++; else if (name2 === "Bar" || name2 === "|") bar = true; else if (DOT_NAMES.includes(name2)) [dot, open] = [true, open || name2 === "o"]; else return void 0; continue; } if (s.startsWith(">") || s.startsWith("<")) { arrows2++; s = s.slice(1); continue; } if (s.startsWith("|")) { bar = true; s = s.slice(1); continue; } const name = [...ARROW_NAMES, ...DOT_NAMES].sort((a, b) => b.length - a.length).find((n) => s.startsWith(n)); if (!name) return void 0; if (DOT_NAMES.includes(name)) [dot, open] = [true, open || name === "o"]; else arrows2++; s = s.slice(name.length).trim(); } return { arrows: arrows2, bar, dot, open }; } function arrowKey(key) { let depth = 0; for (let i = 0; i < key.length; i++) { const ch = key[i]; if (ch === "{" || ch === "[") depth++; else if (ch === "}" || ch === "]") depth--; else if (ch === "-" && depth === 0) { const start = tipSpec(key.slice(0, i)); const end = tipSpec(key.slice(i + 1)); if (start !== void 0 && end !== void 0) return { start, end }; } } return null; } var DRAW_KEYS = /* @__PURE__ */ new Set([ "draw", "color", "fill", "opacity", "fill opacity", "draw opacity", "line width", "pattern", "pattern color", "rounded corners", "sharp corners", "line cap", "line join", "shorten >", "shorten <", "decorate", "decoration", "postaction", "domain", "samples", "smooth", "smooth cycle", "tension", "variable", "step", "xstep", "ystep", "radius", "x radius", "y radius", "start angle", "end angle", "delta angle", ">", "font", "text", "every node/.style", "inner sep", "__every node", ...WIDTH_OPTION_NAMES, ...DASH_OPTION_NAMES ]); var DECORATIONS = ["zigzag", "coil", "snake", "brace", "border", "markings", "saw", "bumps"]; function readDecoration(raw, at) { if (raw === void 0) return null; const options = parseOptions(unbrace(raw), at); const name = options.find((o) => o.value === void 0 && DECORATIONS.includes(o.key))?.key; if (!name) { const first = options.find((o) => o.value === void 0 && o.key !== "mirror"); fail("unsupported-option", `"${first?.key ?? raw}" is not a decoration this build draws.`, at, first?.key, `Decorations: ${DECORATIONS.join(", ")}.`); } const len = (key, fallback) => { const v = optionValue(options, key); return v === void 0 ? fallback : length(v, optionAt(options, key), "pt"); }; const marks = []; for (const o of options) { if (o.key !== "mark" || o.value === void 0) continue; const m = /^at position\s+([-+]?[\d.]+)\s*(cm|mm|pt)?\s+with\s*\{\s*\\(arrow|arrowreversed)\s*(?:\[[^\]]*\])?\s*\{([^}]*)\}\s*\}$/.exec(unbrace(o.value).trim()); const between = /^between positions\s+([-+]?[\d.]+)\s+and\s+([-+]?[\d.]+)\s+step\s+([\d.]+)\s+with\s*\{\s*\\(arrow|arrowreversed)\s*(?:\[[^\]]*\])?\s*\{([^}]*)\}\s*\}$/.exec(unbrace(o.value).trim()); if (m) { const tip = m[4].trim(); const reversed = m[3] === "arrowreversed" !== (tip.startsWith("<") || tip === "latex reversed"); marks.push({ at: m[2] ? length(`${m[1]}${m[2]}`, o.at, "cm") : Number(m[1]), fixed: m[2] !== void 0, reversed }); } else if (between) { const reversed = between[4] === "arrowreversed" !== between[5].trim().startsWith("<"); for (let p = Number(between[1]); p <= Number(between[2]) + 1e-9 && marks.length < 50; p += Number(between[3]) || 1) marks.push({ at: p, fixed: false, reversed }); } else { fail("unsupported-option", "A marking is written mark=at position 0.5 with {\\arrow{>}}.", o.at, "mark"); } } return { name, amplitude: len("amplitude", name === "brace" ? 5 * PT : 2.5 * PT), segment: len("segment length", name === "border" ? 4 * PT : 10 * PT), aspect: Number(optionValue(options, "aspect") ?? 0.5), mirror: options.some((o) => o.key === "mirror"), raise: len("raise", 0), pre: len("pre length", 0), post: len("post length", 0), angle: Number(unbrace(optionValue(options, "angle") ?? "45")), marks }; } function cubic(p0, p1, p2, p3, steps = 24) { const out = []; for (let i = 1; i <= steps; i++) { const t = i / steps; const u = 1 - t; out.push({ x: u * u * u * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t * t * t * p3.x, y: u * u * u * p0.y + 3 * u * u * t * p1.y + 3 * u * t * t * p2.y + t * t * t * p3.y }); } return out; } function smoothThrough(points, closed, tension) { if (points.length < 3) return [...points]; const n = points.length; const at = (i) => closed ? points[(i + n) % n] : points[Math.max(0, Math.min(n - 1, i))]; const out = [points[0]]; const k = tension / 0.55 / 3; const segments2 = closed ? n : n - 1; for (let i = 0; i < segments2; i++) { const p0 = at(i - 1); const p1 = at(i); const p2 = at(i + 1); const p3 = at(i + 2); const c1 = { x: p1.x + (p2.x - p0.x) * k / 2, y: p1.y + (p2.y - p0.y) * k / 2 }; const c2 = { x: p2.x - (p3.x - p1.x) * k / 2, y: p2.y - (p3.y - p1.y) * k / 2 }; out.push(...cubic(p1, c1, c2, p2, 12)); } return out; } var PathBuilder = class { constructor(ctx, transform, resolver, options, nodeOptions) { this.ctx = ctx; this.transform = transform; this.resolver = resolver; this.options = options; this.nodeOptions = nodeOptions; this.pieces = []; this.labels = []; /** Circuit symbols, ground marks and terminals: drawn over the wire, in its colour. */ this.symbols = []; this.piece = null; /** Where the current loop began, for cycle: a symbol breaks the wire, not the loop. */ this.loopStart = null; this.current = null; /** The points the last operation added, for a node placed along it. */ this.last = []; this.inverse = invert(transform); } local(p) { return apply(this.inverse, p); } start(p, ref, newLoop = true) { if (newLoop) this.loopStart = p; this.piece = { points: [p], closed: false, startRef: ref, endRef: ref }; this.pieces.push(this.piece); this.current = p; this.last = [p]; } lineTo(points, ref) { if (!this.current) fail("syntax", "A path has to start at a point before it can go anywhere.", 0); if (!this.piece) this.start(this.current, null); const from = this.current; this.piece.points.push(...points); this.piece.endRef = ref; this.current = points[points.length - 1] ?? from; this.last = [from, ...points]; } need(what, at) { if (!this.current) fail("syntax", `${what} needs a point before it.`, at, what); return this.current; } run(parts, drawAt) { for (const part of parts) { switch (part.kind) { case "point": { const { p: target, ref } = this.resolver.resolve(part.coord, part.relative, this.current); if (part.op === "move") { this.start(target, ref); } else if (part.op === "--") { this.lineTo([target], ref); } else { const from = this.need(part.op, part.coord.at); const lf = this.local(from); const lt = this.local(target); const corner = apply(this.transform, part.op === "|-" ? { x: lf.x, y: lt.y } : { x: lt.x, y: lf.y }); this.lineTo([corner, target], ref); } if (part.relative === "+" && part.op !== "move") this.current = this.last[0] ?? this.current; break; } case "curve": { const from = this.need("A curve", part.at); const end = this.resolver.resolve(part.to, part.relative, from); const c1 = this.resolver.resolve(part.c1, part.c1Relative, from).p; const c2 = part.c2 ? this.resolver.resolve(part.c2, part.c2Relative, end.p).p : null; const [k1, k2] = c2 ? [c1, c2] : ( // One control point: the quadratic curve, as a cubic. [ { x: from.x + (c1.x - from.x) * 2 / 3, y: from.y + (c1.y - from.y) * 2 / 3 }, { x: end.p.x + (c1.x - end.p.x) * 2 / 3, y: end.p.y + (c1.y - end.p.y) * 2 / 3 } ] ); this.lineTo(cubic(from, k1, k2, end.p), end.ref); break; } case "to": { const from = this.need("to", part.at); const end = this.resolver.resolve(part.to, part.relative, from); const component = componentIn(expandStyles(part.options, this.ctx)); if (component) this.component(from, end.p, component); else this.lineTo(this.toCurve(from, end.p, part.options, part.at), end.ref); break; } case "rectangle": { const from = this.need("rectangle", 0); const end = this.resolver.resolve(part.to, part.relative, from).p; const a = this.local(from); const b = this.local(end); const corners = [a, { x: b.x, y: a.y }, b, { x: a.x, y: b.y }].map((p) => apply(this.transform, p)); this.pieces.push({ points: corners, closed: true, startRef: null, endRef: null }); this.piece = null; this.current = end; this.last = [from, end]; break; } case "grid": { const from = this.need("grid", part.at); const end = this.resolver.resolve(part.to, part.relative, from).p; this.grid(this.local(from), this.local(end), [...this.options, ...part.options], part.at); this.piece = null; this.current = end; break; } case "circle": { const centre = this.need(part.radius === null && part.options.length === 0 ? "circle" : "circle", part.at); const [rx, ry] = this.radii(part.radius, [...this.options, ...part.options], part.at); const c = this.local(centre); const points = []; const steps = 96; for (let i = 0; i < steps; i++) { const t = i / steps * 2 * Math.PI; points.push(apply(this.transform, { x: c.x + rx * Math.cos(t), y: c.y + ry * Math.sin(t) })); } this.pieces.push({ points, closed: true, startRef: null, endRef: null }); this.piece = null; this.last = [centre]; break; } case "arc": { const from = this.need("arc", part.at); const { start, end, rx, ry } = this.arcSpec(part.spec, [...this.options, ...part.options], part.at); const a0 = start * Math.PI / 180; const a1 = end * Math.PI / 180; const lf = this.local(from); const c = { x: lf.x - rx * Math.cos(a0), y: lf.y - ry * Math.sin(a0) }; const steps = Math.max(8, Math.ceil(Math.abs(end - start) / 3)); const points = []; for (let i = 1; i <= steps; i++) { const t = a0 + (a1 - a0) * i / steps; points.push(apply(this.transform, { x: c.x + rx * Math.cos(t), y: c.y + ry * Math.sin(t) })); } this.lineTo(points, null); break; } case "plot": { const points = this.plot(part); if (points.length === 0) break; if (part.op === "--" && this.current) this.lineTo(points, null); else { this.start(points[0], null); this.lineTo(points.slice(1), null); } if (part.options.some((o) => o.key === "smooth cycle") && this.piece) this.piece.closed = true; break; } case "node": this.node(part); break; case "coordinate": { const p = this.need("coordinate", part.at); this.ctx.store.set(part.name, p); break; } case "cycle": if (!this.piece) fail("syntax", "cycle has no path to close.", part.at, "cycle"); if (this.loopStart && this.piece.points[0] !== this.loopStart) { this.lineTo([this.loopStart], null); this.current = this.loopStart; this.piece = null; break; } this.piece.closed = true; this.piece.endRef = null; this.current = this.piece.points[0]; this.last = [this.piece.points[this.piece.points.length - 1], this.piece.points[0]]; this.piece = null; break; } } if (this.pieces.length === 0 && this.labels.length === 0 && !this.current) fail("syntax", "This path has no points.", drawAt); } toCurve(from, to, options, at) { const allowed = /* @__PURE__ */ new Set(["out", "in", "bend left", "bend right", "looseness", "relative"]); for (const o2 of options) { if (!allowed.has(o2.key)) fail("unsupported-option", `"${o2.key}" is not a to-path option this build understands.`, o2.at, o2.key, "Supported: out, in, bend left, bend right, looseness; or a circuit symbol: R, C, L, battery1, battery, V, sV, I, switch, ncs, lamp, ammeter, voltmeter, galvanometer, D, led, zD, fuse, vR, pR, short."); } const dir = Math.atan2(to.y - from.y, to.x - from.x) * 180 / Math.PI; let out = null; let into = null; const bendLeft = optionValue(options, "bend left"); const bendRight = optionValue(options, "bend right"); if (bendLeft !== void 0) { const b = bendLeft === "" ? 30 : number(bendLeft, at, "bend left"); out = dir + b; into = dir + 180 - b; } else if (bendRight !== void 0) { const b = bendRight === "" ? 30 : number(bendRight, at, "bend right"); out = dir - b; into = dir + 180 + b; } const o = optionValue(options, "out"); const i = optionValue(options, "in"); if (o !== void 0) out = number(o, at, "out"); if (i !== void 0) into = number(i, at, "in"); if (out === null && into === null) return [to]; out ??= dir; into ??= dir + 180; const looseness = Number(optionValue(options, "looseness") ?? 1); const d = Math.hypot(to.x - from.x, to.y - from.y) * 0.3915 * looseness; const rad2 = Math.PI / 180; return cubic( from, { x: from.x + d * Math.cos(out * rad2), y: from.y + d * Math.sin(out * rad2) }, { x: to.x + d * Math.cos(into * rad2), y: to.y + d * Math.sin(into * rad2) }, to ); } radii(raw, options, at) { if (raw !== null) { const parts = splitTop(raw, " and "); const rx2 = length(parts[0], at, "cm"); return [rx2, parts.length === 2 ? length(parts[1], at, "cm") : rx2]; } const r = optionValue(options, "radius"); const rx = optionValue(options, "x radius") ?? r; const ry = optionValue(options, "y radius") ?? r; if (rx === void 0 || ry === void 0) fail("syntax", "A circle needs a radius: circle (1) or circle[radius=1].", at, "circle"); return [length(rx, at, "cm"), length(ry, at, "cm")]; } arcSpec(spec, options, at) { if (spec !== null) { const parts = splitTop(spec, ":"); if (parts.length !== 3) fail("syntax", "An arc is written arc (start:end:radius), e.g. arc (0:90:1).", at, "arc"); const radii = splitTop(parts[2], " and "); const rx2 = length(radii[0], at, "cm"); return { start: number(parts[0], at, "an arc"), end: number(parts[1], at, "an arc"), rx: rx2, ry: radii.length === 2 ? length(radii[1], at, "cm") : rx2 }; } const startRaw = optionValue(options, "start angle"); const endRaw = optionValue(options, "end angle"); const deltaRaw = optionValue(options, "delta angle"); if (startRaw === void 0 && endRaw === void 0) fail("syntax", "An arc needs its angles: arc (0:90:1) or arc[start angle=0, end angle=90, radius=1].", at, "arc"); const start = startRaw !== void 0 ? number(startRaw, at, "start angle") : number(endRaw, at, "end angle") - number(deltaRaw ?? "0", at, "delta angle"); const end = endRaw !== void 0 ? number(endRaw, at, "end angle") : start + number(deltaRaw ?? "0", at, "delta angle"); const [rx, ry] = this.radii(null, options, at); return { start, end, rx, ry }; } grid(a, b, options, at) { const step2 = optionValue(options, "step"); const sx = length(optionValue(options, "xstep") ?? step2 ?? "1", at, "cm"); const sy = length(optionValue(options, "ystep") ?? step2 ?? "1", at, "cm"); if (sx <= 0 || sy <= 0) fail("unsupported-option", "A grid step must be more than 0.", at, "step"); const [x0, x1] = [Math.min(a.x, b.x), Math.max(a.x, b.x)]; const [y0, y1] = [Math.min(a.y, b.y), Math.max(a.y, b.y)]; if ((x1 - x0) / sx + (y1 - y0) / sy > 1e3) fail("unsupported-option", "This grid would have more than 1000 lines.", at, "grid"); const line3 = (p, q) => this.pieces.push({ points: [apply(this.transform, p), apply(this.transform, q)], closed: false, startRef: null, endRef: null }); for (let x = Math.ceil(x0 / sx - 1e-9) * sx; x <= x1 + 1e-9; x += sx) line3({ x, y: y0 }, { x, y: y1 }); for (let y = Math.ceil(y0 / sy - 1e-9) * sy; y <= y1 + 1e-9; y += sy) line3({ x: x0, y }, { x: x1, y }); } plot(part) { const options = [...this.options, ...part.options]; let points; if ("coordinates" in part.data) { points = part.data.coordinates.map((c) => this.resolver.resolve(c, "", null).p); } else { const variable = (unbrace(optionValue(options, "variable") ?? "\\x").replace(/^\\/, "") || "x").trim(); const domain = unbrace(optionValue(options, "domain") ?? "-5:5").split(":"); if (domain.length !== 2) fail("unsupported-option", "domain is written domain=a:b.", optionAt(options, "domain"), "domain"); const lo = number(domain[0], part.at, "domain"); const hi = number(domain[1], part.at, "domain"); const samples = Math.round(number(optionValue(options, "samples") ?? "25", part.at, "samples")); if (samples < 2 || samples > 5e3) fail("unsupported-option", "samples must be from 2 to 5000.", optionAt(options, "samples"), "samples"); const vars = [variable]; const own = (s) => pgfmath(unbrace(s).replace(new RegExp(`\\\\${variable}(?![A-Za-z])`, "g"), variable)); const fx = parseExpr(own(part.data.x), part.at, vars); const fy = parseExpr(own(part.data.y), part.at, vars); points = []; for (let i = 0; i < samples; i++) { const v = lo + (hi - lo) * i / (samples - 1); const x = evaluate(fx, { [variable]: v }); const y = evaluate(fy, { [variable]: v }); if (Number.isFinite(x) && Number.isFinite(y)) points.push(apply(this.transform, { x, y })); } } const smooth = options.some((o) => o.key === "smooth" || o.key === "smooth cycle"); if (!smooth) return points; const tension = Number(optionValue(options, "tension") ?? 0.55); return smoothThrough(points, options.some((o) => o.key === "smooth cycle"), tension); } /** A circuit symbol on the wire from `from` to `to`: wire, symbol, wire, and its labels. */ component(from, to, c) { const terminals = c.rest.filter((o) => o.value === void 0 && arrowKey(o.key)?.start !== void 0 && /^[*o]?-[*o]?$/.test(o.key)); const drawing = drawComponent(c.name, c.label, c.rest.filter((o) => !terminals.includes(o)), from, to, this.ctx.flags, (key) => /^[*o]?-[*o]?$/.test(key)); if (drawing.open) { this.start(to, null, false); } else { if (drawing.bodyStart.x !== from.x || drawing.bodyStart.y !== from.y) this.lineTo([drawing.bodyStart], null); this.symbols.push(...drawing.shapes); if (drawing.bodyEnd.x !== drawing.bodyStart.x || drawing.bodyEnd.y !== drawing.bodyStart.y) this.start(drawing.bodyEnd, null, false); this.lineTo([to], null); } this.last = [from, to]; for (const t of terminals) { const [a, b] = t.key.split("-"); if (a) this.symbols.push(terminalShape(from, a === "o")); if (b) this.symbols.push(terminalShape(to, b === "o")); } for (const l of drawing.labels) this.labels.push(...makeLabel(l.text, [...this.nodeOptions, { key: placementToward(l.dir), at: 0 }], l.at, null, 0, this.ctx, null)); for (const l of drawing.letters) { this.labels.push(...makeLabel(l.text, [...this.nodeOptions, { key: "font", value: "\\small", at: 0 }, { key: "inner sep", value: "0pt", at: 0 }], l.at, null, 0, this.ctx, null)); } } node(part) { const options = [...this.nodeOptions, ...expandStyles(part.options, this.ctx)]; if (options.some((o) => o.key === "ground" || o.key === "circ" || o.key === "ocirc")) { this.symbols.push(...circuitNode(options, this.need("node", part.at))); if (!part.text.trim()) return; } const pos = nodePosition(options); let anchor; let slope = null; if (pos === null || this.last.length < 2) { anchor = this.need("node", part.at); } else { const along = pointAlong(this.last, pos); anchor = along.p; slope = along.dir; } if (!options.some((o) => o.key === "sloped")) slope = null; const [label, ...extra] = makeLabel(part.text, options, anchor, part.name, part.at, this.ctx, slope); this.labels.push({ ...label, textSrc: { start: part.textAt, end: part.textAt + part.text.length } }, ...extra); } }; function placementToward(d) { const angle = Math.atan2(d.y, d.x) * 180 / Math.PI; const names = ["right", "above right", "above", "above left", "left", "below left", "below", "below right"]; return names[(Math.round(angle / 45) % 8 + 8) % 8]; } function circuitNode(options, at) { if (options.some((o) => o.key === "ground")) return groundShapes(at); return [terminalShape(at, options.some((o) => o.key === "ocirc"))]; } function nodePosition(options) { let pos = null; for (const o of options) { if (o.key === "midway") pos = 0.5; else if (o.key === "near start") pos = 0.25; else if (o.key === "near end") pos = 0.75; else if (o.key === "at start" || o.key === "very near start") pos = o.key === "at start" ? 0 : 0.125; else if (o.key === "at end" || o.key === "very near end") pos = o.key === "at end" ? 1 : 0.875; else if (o.key === "pos" && o.value !== void 0) pos = number(o.value, o.at, "pos"); } return pos; } function pointAlong(points, t) { const lengths = [0]; for (let i = 1; i < points.length; i++) lengths.push(lengths[i - 1] + Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y)); const total = lengths[lengths.length - 1]; const target = Math.max(0, Math.min(1, t)) * total; for (let i = 1; i < points.length; i++) { if (lengths[i] >= target - 1e-12) { const seg = lengths[i] - lengths[i - 1]; const u = seg === 0 ? 0 : (target - lengths[i - 1]) / seg; const a2 = points[i - 1]; const b2 = points[i]; return { p: { x: a2.x + (b2.x - a2.x) * u, y: a2.y + (b2.y - a2.y) * u }, dir: { x: b2.x - a2.x, y: b2.y - a2.y } }; } } const a = points[points.length - 2]; const b = points[points.length - 1]; return { p: b, dir: { x: b.x - a.x, y: b.y - a.y } }; } function clipToNodes(piece) { const inside2 = (box, p) => { const dx = (p.x - box.center.x) / (box.halfW || 1e-9); const dy = (p.y - box.center.y) / (box.halfH || 1e-9); return box.shape === "rectangle" ? Math.abs(dx) <= 1 && Math.abs(dy) <= 1 : dx * dx + dy * dy <= 1; }; const trim = (points, box) => { let i = 1; while (i < points.length && inside2(box, points[i])) i++; if (i >= points.length) return points; let a = points[i - 1]; let b = points[i]; for (let k = 0; k < 30; k++) { const m = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; if (inside2(box, m)) a = m; else b = m; } return [b, ...points.slice(i)]; }; if (piece.closed || piece.points.length < 2) return; if (piece.startRef) piece.points = trim(piece.points, piece.startRef); if (piece.endRef) piece.points = trim([...piece.points].reverse(), piece.endRef).reverse(); } var Measured = class { constructor(points) { this.points = points; this.lengths = [0]; for (let i = 1; i < points.length; i++) this.lengths.push(this.lengths[i - 1] + Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y)); } get total() { return this.lengths[this.lengths.length - 1]; } /** The point at distance `s`, and the unit tangent there. */ at(s) { const target = Math.max(0, Math.min(this.total, s)); let i = 1; while (i < this.points.length - 1 && this.lengths[i] < target) i++; const a = this.points[i - 1]; const b = this.points[i]; const seg = this.lengths[i] - this.lengths[i - 1]; const u = seg === 0 ? 0 : (target - this.lengths[i - 1]) / seg; const n = Math.hypot(b.x - a.x, b.y - a.y) || 1; return { p: { x: a.x + (b.x - a.x) * u, y: a.y + (b.y - a.y) * u }, t: { x: (b.x - a.x) / n, y: (b.y - a.y) / n } }; } /** The polyline from `s0` to `s1`. */ slice(s0, s1) { const out = [this.at(s0).p]; for (let i = 1; i < this.points.length - 1; i++) if (this.lengths[i] > s0 && this.lengths[i] < s1) out.push(this.points[i]); out.push(this.at(s1).p); return out; } }; function decoratePiece(points, d) { const path = new Measured(points); const total = path.total; if (total === 0) return [[...points]]; const s0 = Math.min(d.pre, total); const s1 = Math.max(s0, total - d.post); const middle = s1 - s0; const side2 = d.mirror ? -1 : 1; const offset = (s, along, across) => { const { p, t } = path.at(s); const n = { x: -t.y * side2, y: t.x * side2 }; return { x: p.x + t.x * along + n.x * (across + d.raise), y: p.y + t.y * along + n.y * (across + d.raise) }; }; const lead = s0 > 0 ? path.slice(0, s0) : [path.at(0).p]; const tail = s1 < total ? path.slice(s1, total) : [path.at(total).p]; const join7 = (mid) => [[...lead, ...mid, ...tail]]; const count = Math.max(1, Math.round(middle / d.segment)); const seg = middle / count; const A = d.amplitude; switch (d.name) { case "zigzag": case "saw": { const mid = []; for (let k = 0; k < count; k++) { const base = s0 + k * seg; if (d.name === "saw") mid.push(offset(base + seg, -seg, A), offset(base + seg, 0, 0)); else mid.push(offset(base + seg / 4, 0, A), offset(base + 3 * seg / 4, 0, -A)); } mid.push(path.at(s1).p); return join7(mid); } case "snake": case "bumps": { const mid = []; const steps = count * 16; for (let i = 0; i <= steps; i++) { const s = s0 + middle * i / steps; const phase = 2 * Math.PI * (s - s0) / seg; mid.push(offset(s, 0, d.name === "bumps" ? A * Math.abs(Math.sin(phase / 2)) : A * Math.sin(phase))); } return join7(mid); } case "coil": { const mid = []; const steps = count * 24; const back = Math.max(d.aspect * A, 1.3 * seg / (2 * Math.PI)); for (let i = 0; i <= steps; i++) { const theta = 2 * Math.PI * count * i / steps; mid.push(offset(s0 + middle * i / steps, back * (Math.cos(theta) - 1), A * Math.sin(theta))); } return join7(mid); } case "brace": { const a = path.at(s0).p; const b = path.at(s1).p; const t = { x: (b.x - a.x) / (middle || 1), y: (b.y - a.y) / (middle || 1) }; const n = { x: -t.y * side2, y: t.x * side2 }; const at = (u, h) => ({ x: a.x + t.x * u + n.x * (h + d.raise), y: a.y + t.y * u + n.y * (h + d.raise) }); const half = middle / 2; const r = Math.min(A / 2, half / 2); return [ [ at(0, 0), ...cubic(at(0, 0), at(0, r), at(r, A / 2), at(r * 1.5, A / 2), 8), at(half - r * 1.5, A / 2), ...cubic(at(half - r * 1.5, A / 2), at(half - r / 2, A / 2), at(half, A / 2), at(half, A), 8), ...cubic(at(half, A), at(half, A / 2), at(half + r / 2, A / 2), at(half + r * 1.5, A / 2), 8), at(middle - r * 1.5, A / 2), ...cubic(at(middle - r * 1.5, A / 2), at(middle - r, A / 2), at(middle, r), at(middle, 0), 8) ] ]; } case "border": { const ticks = []; const rad2 = d.angle * Math.PI / 180; const n = Math.max(1, Math.round(middle / d.segment)); for (let k = 0; k <= n; k++) { const s = s0 + middle * k / n; ticks.push([offset(s, 0, 0), offset(s, A * Math.cos(rad2), A * Math.sin(rad2))]); } return ticks; } default: return [[...points]]; } } function readPaint(options, command, defaultColor, at) { const { color, rest: uncolored } = currentColor(options); let start = null; let end = null; const rest = []; for (const o of uncolored) { const tips = o.value === void 0 ? arrowKey(o.key) : null; if (tips) { start = tips.start; end = tips.end; } else rest.push(o); } for (const o of rest) { if (!DRAW_KEYS.has(o.key)) { fail("unsupported-option", `"${o.key}" is not an option this build understands on \\${command}.`, o.at, o.key, `Supported here: arrow tips (->, <->, -latex, |<->|), ${[...DRAW_KEYS].filter((k) => !k.startsWith("__")).sort().join(", ")}.`); } } const drawn = command === "draw" || command === "filldraw" || rest.some((o) => o.key === "draw" && unbrace(o.value ?? "") !== "none"); const stroke = readStroke(rest, color ?? defaultColor, drawn); const explicit = readFill(rest); const patternRaw = optionValue(rest, "pattern"); const fill = explicit ?? ((command === "fill" || command === "filldraw") && patternRaw === void 0 ? { color: color ?? defaultColor, opacity: fillOpacity(rest) ?? 1 } : void 0); const PATTERNS = ["north east lines", "north west lines", "horizontal lines", "vertical lines", "crosshatch", "grid", "dots", "crosshatch dots"]; if (patternRaw !== void 0 && !PATTERNS.includes(unbrace(patternRaw))) { fail("unsupported-option", `pattern=${patternRaw} is not a pattern this build draws.`, optionAt(rest, "pattern"), patternRaw, `Patterns: ${PATTERNS.join(", ")}.`); } const patternColor = optionValue(rest, "pattern color"); const roundedRaw = optionValue(rest, "rounded corners"); const shorten = (key) => { const v = optionValue(rest, key); return v === void 0 ? 0 : length(v, optionAt(rest, key), "pt") * PX_PER_CM; }; let decorationRaw = optionValue(rest, "decoration"); let replace = rest.some((o) => o.key === "decorate"); const post = optionValue(rest, "postaction"); if (post !== void 0) { const inner = parseOptions(unbrace(post), optionAt(rest, "postaction") + 1); for (const o of inner) { if (o.key !== "decorate" && o.key !== "decoration") fail("unsupported-option", `"${o.key}" can't be used in postaction in this build.`, o.at, o.key, "postaction={decorate} draws a decoration as well as the path."); } if (inner.some((o) => o.key === "decorate")) replace = false; decorationRaw = optionValue(inner, "decoration") ?? decorationRaw; if (!inner.some((o) => o.key === "decorate")) decorationRaw = void 0; } else if (!replace) { decorationRaw = void 0; } const decoration = readDecoration(decorationRaw, optionAt(rest, "decoration") || at); const marks = decoration?.name === "markings" ? decoration.marks : []; return { paint: { ...stroke ? { stroke } : {}, ...fill ? { fill } : {}, ...patternRaw !== void 0 ? { pattern: { kind: unbrace(patternRaw), color: patternColor ? resolveColor(unbrace(patternColor), optionAt(rest, "pattern color")) : "#000000" } } : {}, start, end, shortenStart: shorten("shorten <"), shortenEnd: shorten("shorten >"), rounded: roundedRaw === void 0 ? 0 : (roundedRaw === "" ? 4 * PT : length(roundedRaw, optionAt(rest, "rounded corners"), "pt")) * PX_PER_CM, marks }, decoration: decoration && decoration.name !== "markings" ? decoration : null, replace: decoration?.name === "markings" ? false : replace }; } var DEFAULT_COLOR = "#000000"; var LABEL_COLOR = "#333333"; var NODE_FONT_SIZE = 12; function drawPath(node, ctx, frame2) { const own = expandStyles(node.options, ctx); const { transform, rest } = readTransform(own); const options = [...frame2.inherited, ...rest]; const t = compose(frame2.transform, transform); const { color } = currentColor(options); const nodeOptions = [...frame2.nodeStyle]; if (color !== void 0) nodeOptions.push({ key: "color", value: color, at: node.at }); for (const o of options) if (o.key === "font" || o.key === "text") nodeOptions.push(o); for (const o of options) if (o.key === "__every node" || o.key === "every node/.style") nodeOptions.push(...parseOptions(unbrace(o.value ?? ""), o.at)); const builder = new PathBuilder(ctx, t, new Resolver(ctx, t), options, nodeOptions); builder.run(node.parts, node.at); const { paint, decoration, replace } = readPaint(options, node.command, DEFAULT_COLOR, node.at); for (const piece of builder.pieces) clipToNodes(piece); const out = []; if (decoration) { const decorated = builder.pieces.flatMap((p) => decoratePiece(p.closed ? [...p.points, p.points[0]] : p.points, decoration)); const pieces = decorated.map((points) => ({ points, closed: false, startRef: null, endRef: null })); if (!replace) out.push({ kind: "shape", pieces: builder.pieces, paint }); const { fill: _fill, pattern: _pattern, ...line3 } = paint; out.push({ kind: "shape", pieces, paint: replace ? line3 : { ...line3, start: null, end: null, marks: [] } }); } else { out.push({ kind: "shape", pieces: builder.pieces, paint }); } out.push(...symbolShapes(builder.symbols, paint.stroke)); out.push(...builder.labels); return traced(out, node, pathCoords(node.parts), t, ctx); } var PLACEMENTS = { above: [0, 1], below: [0, -1], left: [-1, 0], right: [1, 0], "above left": [-1, 1], "above right": [1, 1], "below left": [-1, -1], "below right": [1, -1] }; var FONT_SIZES = [ ["tiny", 6.5], ["scriptsize", 8], ["footnotesize", 9.5], ["small", 10.5], ["normalsize", 12], ["large", 14], ["Large", 16.5], ["LARGE", 19.5], ["huge", 23], ["Huge", 27] ]; var NODE_KEYS = /* @__PURE__ */ new Set([ ...Object.keys(PLACEMENTS), "anchor", "color", "text", "draw", "fill", "opacity", "fill opacity", "draw opacity", "text opacity", "line width", "circle", "rectangle", "ellipse", "shape", "minimum size", "minimum width", "minimum height", "inner sep", "inner xsep", "inner ysep", "outer sep", "rounded corners", "font", "scale", "rotate", "xshift", "yshift", "align", "text width", "label", "midway", "near start", "near end", "at start", "at end", "very near start", "very near end", "pos", "sloped", "name", "transform shape", "text centered", "fill opacity", "ground", "circ", "ocirc", ...WIDTH_OPTION_NAMES, ...DASH_OPTION_NAMES ]); function nodeLines(text) { const plain = text.replace(/\\(?:textbf|textit|textrm|textsf|texttt|emph|mbox|text)\s*\{([^{}]*)\}/g, "$1").replace(/\\(?:bfseries|itshape|centering|raggedright|raggedleft|small|footnotesize|scriptsize|tiny|large|Large|normalsize)\b\s*/g, "").replace(/~/g, " "); return plain.split(/\\\\(?:\[[^\]]*\])?/).map((l) => l.trim()); } function makeLabel(text, options, anchor, name, at, ctx, slope) { const { color: current, rest } = currentColor(options); for (const o of rest) { if (!NODE_KEYS.has(o.key) && o.key !== "__every node" && o.key !== "every node/.style") { fail("unsupported-option", `"${o.key}" is not an option this build understands on a node.`, o.at, o.key, `Supported here: ${[...NODE_KEYS].sort().join(", ")}.`); } } const scale = Number(unbrace(optionValue(rest, "scale") ?? "1")) || 1; const font = optionValue(rest, "font") ?? ""; const sizeName = FONT_SIZES.filter(([n2]) => new RegExp(`\\\\${n2}(?![A-Za-z])`).test(font)).pop(); const fontSize = (sizeName ? sizeName[1] : NODE_FONT_SIZE) * scale; const lines = text.trim() === "" ? [] : nodeLines(text); let textW = 0; for (const line3 of lines) textW = Math.max(textW, runsWidth(labelRuns(line3, at), fontSize)); const textH = lines.length === 0 ? 0 : (lines.length - 1) * fontSize * 1.2 + fontSize; const sep3 = (key, fallback) => { const v = optionValue(rest, key); return v === void 0 ? fallback : length(v, optionAt(rest, key), "pt") * PX_PER_CM; }; const inner = sep3("inner sep", 3.33 * PT * PX_PER_CM); let halfW = textW / 2 + sep3("inner xsep", inner); let halfH = textH / 2 + sep3("inner ysep", inner); const shapeRaw = optionValue(rest, "shape"); const shape2 = shapeRaw !== void 0 ? ["circle", "ellipse", "rectangle"].includes(unbrace(shapeRaw)) ? unbrace(shapeRaw) : fail("unsupported-option", `shape=${shapeRaw} is not a node shape this build draws.`, optionAt(rest, "shape"), shapeRaw, "Shapes: rectangle, circle, ellipse.") : rest.some((o) => o.key === "circle") ? "circle" : rest.some((o) => o.key === "ellipse") ? "ellipse" : "rectangle"; const minSize = sep3("minimum size", 0); halfW = Math.max(halfW, sep3("minimum width", minSize) / 2); halfH = Math.max(halfH, sep3("minimum height", minSize) / 2); if (shape2 === "circle") halfW = halfH = Math.max(Math.hypot(halfW, halfH), minSize / 2); if (shape2 === "ellipse") { halfW *= Math.SQRT2; halfH *= Math.SQRT2; } let dir = [0, 0]; let gap = 0; for (const o of rest) { const p = PLACEMENTS[o.key]; if (p) { dir = p; if (o.value !== void 0 && /\bof\b/.test(o.value)) fail("unsupported-option", `${o.key}=${o.value} needs the positioning library, which this build doesn't have.`, o.at, o.key, "Give the node a position with at (x,y)."); gap = o.value === void 0 || o.value === "" ? 2 : length(o.value, o.at, "pt") * PX_PER_CM; } } const anchorRaw = optionValue(rest, "anchor"); if (anchorRaw !== void 0) { const a = ANCHORS[unbrace(anchorRaw)]; if (!a) fail("unsupported-option", `anchor=${anchorRaw} is not an anchor this build knows.`, optionAt(rest, "anchor"), anchorRaw, "Anchors: north, south, east, west, north east, \u2026, center."); dir = [-a[0], -a[1]]; gap = 0; } const n = Math.hypot(dir[0], dir[1]) || 1; let dxPx = dir[0] === 0 ? 0 : Math.sign(dir[0]) * (halfW + gap / n); let dyPx = dir[1] === 0 ? 0 : Math.sign(dir[1]) * (halfH + gap / n); const shiftX = optionValue(rest, "xshift"); const shiftY = optionValue(rest, "yshift"); if (shiftX !== void 0) dxPx += length(shiftX, optionAt(rest, "xshift"), "pt") * PX_PER_CM; if (shiftY !== void 0) dyPx += length(shiftY, optionAt(rest, "yshift"), "pt") * PX_PER_CM; const center = { x: anchor.x + dxPx / ctx.pxPerUnit.x, y: anchor.y + dyPx / ctx.pxPerUnit.y }; const textColor = optionValue(rest, "text") ?? optionValue(rest, "color"); const color = textColor !== void 0 && textColor !== "" ? resolveColor(unbrace(textColor), optionAt(rest, "text") || optionAt(rest, "color")) : current ?? LABEL_COLOR; const drawRaw = optionValue(rest, "draw"); const drawn = drawRaw !== void 0 && unbrace(drawRaw) !== "none"; const stroke = drawn ? readStroke(rest, current ?? DEFAULT_COLOR, true) : void 0; const fill = readFill(rest); const alignRaw = unbrace(optionValue(rest, "align") ?? "center"); const align = alignRaw === "left" ? "start" : alignRaw === "right" ? "end" : "middle"; const rounded = optionValue(rest, "rounded corners"); const nameOpt = optionValue(rest, "name"); const named = name ?? (nameOpt !== void 0 ? unbrace(nameOpt) : null); if (named) ctx.nodes.set(named, { center, halfW: halfW / ctx.pxPerUnit.x, halfH: halfH / ctx.pxPerUnit.y, shape: shape2 }); const label = { kind: "label", center, lines, align, fontSize, color, rotate: Number(unbrace(optionValue(rest, "rotate") ?? "0")) || 0, slope, textHalf: textW / 2, halfW, halfH, shape: shape2, rounded: rounded === void 0 ? 0 : (rounded === "" ? 4 * PT : length(rounded, optionAt(rest, "rounded corners"), "pt")) * PX_PER_CM, ...stroke ? { stroke } : {}, ...fill ? { fill } : {}, at }; const out = [label]; const extra = optionValue(rest, "label"); if (extra !== void 0) { const m = /^(?:\[([^\]]*)\])?\s*(?:(above left|above right|below left|below right|above|below|left|right|-?\d+(?:\.\d+)?)\s*:)?([\s\S]*)$/.exec(unbrace(extra)); const where = m?.[2] ?? "above"; const opts = parseOptions(m?.[1] ?? "", optionAt(rest, "label")); const angle = Number(where); const d = Number.isFinite(angle) ? [Math.cos(angle * Math.PI / 180), Math.sin(angle * Math.PI / 180)] : PLACEMENTS[where]; const box = { center, halfW: halfW / ctx.pxPerUnit.x, halfH: halfH / ctx.pxPerUnit.y, shape: shape2 }; const nd = Math.hypot(d[0], d[1]) || 1; const edge = borderPoint(box, d[0] / nd, d[1] / nd); const placement = Number.isFinite(angle) ? Math.abs(d[0]) < 0.38 ? d[1] > 0 ? "above" : "below" : Math.abs(d[1]) < 0.38 ? d[0] > 0 ? "right" : "left" : `${d[1] > 0 ? "above" : "below"} ${d[0] > 0 ? "right" : "left"}` : where; out.push(...makeLabel(m?.[3] ?? "", [{ key: placement, at }, ...opts], edge, null, at, ctx, null)); } return out; } function evaluateStatements(statements, ctx, frame2) { const out = []; for (const s of statements) { switch (s.kind) { case "draw": out.push(...drawPath(s, ctx, frame2)); break; case "node": out.push(...drawNode(s, ctx, frame2)); break; case "coordinate": { const p = new Resolver(ctx, frame2.transform).resolve(s.at_, "", null).p; ctx.store.set(s.name, p); break; } case "scope": out.push(...evaluateStatements(s.body, ctx, enterScope(s.options, frame2, ctx))); break; case "tikzset": enterScope(s.options, frame2, ctx); for (const o of s.options) { if (!/\/\.(style|append style)$/.test(o.key)) fail("unsupported-option", `\\tikzset only defines styles here ("${o.key}" isn't one).`, o.at, o.key, "Write name/.style={\u2026}, then use [name]."); } break; case "addplot": fail( "unknown-command", "\\addplot only works inside \\begin{axis}.", s.at, "addplot", "Wrap the plot in \\begin{axis}[xmin=\u2026,xmax=\u2026,ymin=\u2026,ymax=\u2026] \u2026 \\end{axis}." ); break; case "tkz": fail( "unknown-command", `\\${s.name} is a tkz-euclide command, which this build does not draw.`, s.at, s.name, "Draw the construction with \\draw and \\node instead." ); break; case "axis": fail("unsupported-option", "An axis cannot be combined with other drawing commands \u2014 they use different coordinate systems.", s.at); } } return out; } function symbolShapes(symbols, wire) { const ink = wire ?? { color: DEFAULT_COLOR, width: readLineWidth([]) }; return symbols.map((s) => ({ kind: "shape", pieces: [{ points: s.points, closed: s.closed, startRef: null, endRef: null }], paint: { stroke: { color: ink.color, width: ink.width * s.weight }, ...s.fill === "none" ? {} : { fill: { color: s.fill === "ink" ? ink.color : "#ffffff", opacity: 1 } }, start: null, end: null, shortenStart: 0, shortenEnd: 0, rounded: 0, marks: [] } })); } function drawNode(node, ctx, frame2) { const own = expandStyles(node.options, ctx); const { transform, rest } = readTransform(own.filter((o) => o.key !== "rotate")); const rotate = own.filter((o) => o.key === "rotate"); const t = compose(frame2.transform, transform); const anchor = new Resolver(ctx, t).resolve(node.at_, "", null).p; const everyNode = frame2.inherited.filter((o) => o.key === "__every node").flatMap((o) => parseOptions(unbrace(o.value ?? ""), o.at)); const options = [...frame2.nodeStyle, ...everyNode, ...rest, ...rotate]; const coords = node.placed ? plainCoord(node.at_) : null; const textSrc = { start: node.textAt, end: node.textAt + node.text.length }; const labelled = (opts) => { const [label, ...extra] = makeLabel(node.text, opts, anchor, node.name, node.at, ctx, null); return [{ ...label, textSrc }, ...extra]; }; const circuit = options.some((o) => o.key === "ground" || o.key === "circ" || o.key === "ocirc"); const drawn = !circuit ? labelled(options) : [...symbolShapes(circuitNode(options, anchor), void 0), ...node.text.trim() ? labelled(options.filter((o) => !["ground", "circ", "ocirc"].includes(o.key))) : []]; return traced(drawn, node, coords ? { coords: [coords], turns: { rotate: "free", flip: true }, arcs: [], rectangles: [] } : null, t, ctx); } function drawnPoints(drawn, ctx) { const out = []; for (const d of drawn) { if (d.kind === "shape") for (const piece of d.pieces) out.push(...piece.points); else { const w = d.halfW / ctx.pxPerUnit.x; const h = d.halfH / ctx.pxPerUnit.y; out.push(d.center); if (d.stroke || d.fill) out.push({ x: d.center.x - w, y: d.center.y - h }, { x: d.center.x + w, y: d.center.y + h }); } } return out; } var ARROW_MIN = 7; function arrowSize(stroke) { return Math.max(ARROW_MIN, (stroke?.width ?? 1) * 4.5); } function triangle(tip, ux, uy, size, color) { const half = size * 0.36; return { kind: "path", points: [tip, { x: tip.x - ux * size - uy * half, y: tip.y - uy * size + ux * half }, { x: tip.x - ux * size + uy * half, y: tip.y - uy * size - ux * half }], closed: true, fill: { color, opacity: 1 } }; } function circlePoints(c, rx, ry, steps = 48) { const out = []; for (let i = 0; i < steps; i++) { const t = i / steps * 2 * Math.PI; out.push({ x: c.x + rx * Math.cos(t), y: c.y + ry * Math.sin(t) }); } return out; } function tipItems(points, tip, stroke) { const color = stroke?.color ?? DEFAULT_COLOR; const size = arrowSize(stroke); const end = points[points.length - 1]; let from = points[points.length - 2]; for (let i = points.length - 2; i >= 0; i--) { from = points[i]; if (Math.hypot(end.x - from.x, end.y - from.y) >= size * 0.6) break; } const len = Math.hypot(end.x - from.x, end.y - from.y); if (len < 1e-9) return { items: [], trim: 0 }; const ux = (end.x - from.x) / len; const uy = (end.y - from.y) / len; const items = []; let trim = 0; for (let k = 0; k < tip.arrows; k++) { items.push(triangle({ x: end.x - ux * size * 0.7 * k, y: end.y - uy * size * 0.7 * k }, ux, uy, size, color)); trim = size * 0.6 + size * 0.7 * k; } if (tip.bar) { const h = size * 0.6; items.push({ kind: "path", points: [{ x: end.x - uy * h, y: end.y + ux * h }, { x: end.x + uy * h, y: end.y - ux * h }], closed: false, stroke: { color, width: stroke?.width ?? 1 } }); } if (tip.dot) { items.push({ kind: "path", points: circlePoints(end, size * 0.32, size * 0.32, 16), closed: true, fill: { color: tip.open ? "#ffffff" : color, opacity: 1 }, ...tip.open ? { stroke: { color, width: stroke?.width ?? 1 } } : {} }); trim = Math.max(trim, size * 0.2); } return { items, trim }; } function trimStart(points, amount) { if (amount <= 0 || points.length < 2) return [...points]; let left = amount; for (let i = 1; i < points.length; i++) { const a = points[i - 1]; const b = points[i]; const seg = Math.hypot(b.x - a.x, b.y - a.y); if (seg >= left) { const u = left / (seg || 1); return [{ x: a.x + (b.x - a.x) * u, y: a.y + (b.y - a.y) * u }, ...points.slice(i)]; } left -= seg; } return [points[points.length - 1]]; } var trimEnd = (points, amount) => trimStart([...points].reverse(), amount).reverse(); function roundCorners(points, closed, radius) { if (radius <= 0 || points.length < 3) return [...points]; const n = points.length; const out = []; for (let i = 0; i < n; i++) { const p = points[i]; const prev = closed ? points[(i - 1 + n) % n] : points[i - 1]; const next = closed ? points[(i + 1) % n] : points[i + 1]; if (!prev || !next) { out.push(p); continue; } const l1 = Math.hypot(p.x - prev.x, p.y - prev.y); const l2 = Math.hypot(next.x - p.x, next.y - p.y); const r = Math.min(radius, l1 / 2, l2 / 2); const turn = Math.abs(Math.atan2((p.x - prev.x) * (next.y - p.y) - (p.y - prev.y) * (next.x - p.x), (p.x - prev.x) * (next.x - p.x) + (p.y - prev.y) * (next.y - p.y))); if (r < 0.5 || turn < 0.15) { out.push(p); continue; } const a = { x: p.x + (prev.x - p.x) / l1 * r, y: p.y + (prev.y - p.y) / l1 * r }; const b = { x: p.x + (next.x - p.x) / l2 * r, y: p.y + (next.y - p.y) / l2 * r }; for (let k = 0; k <= 6; k++) { const t = k / 6; const u = 1 - t; out.push({ x: u * u * a.x + 2 * u * t * p.x + t * t * b.x, y: u * u * a.y + 2 * u * t * p.y + t * t * b.y }); } } return out; } function patternItems(polygon, kind, color) { const spacing = 4.3; const stroke = { color, width: 0.6 }; const items = []; if (kind === "dots" || kind === "crosshatch dots") { let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; for (const p of polygon) [x0, y0, x1, y1] = [Math.min(x0, p.x), Math.min(y0, p.y), Math.max(x1, p.x), Math.max(y1, p.y)]; for (let y = Math.ceil(y0 / spacing) * spacing; y <= y1; y += spacing) { for (let x = Math.ceil(x0 / spacing) * spacing + (kind === "crosshatch dots" && Math.round(y / spacing) % 2 ? spacing / 2 : 0); x <= x1; x += spacing) { if (insidePolygon(polygon, { x, y })) items.push({ kind: "marker", at: { x, y }, shape: "dot", size: 0.7, fill: { color, opacity: 1 } }); } } return items; } const directions = kind === "north east lines" ? [{ x: Math.SQRT1_2, y: -Math.SQRT1_2 }] : kind === "north west lines" ? [{ x: Math.SQRT1_2, y: Math.SQRT1_2 }] : kind === "horizontal lines" ? [{ x: 1, y: 0 }] : kind === "vertical lines" ? [{ x: 0, y: 1 }] : [{ x: 1, y: 0 }, { x: 0, y: 1 }]; for (const d of directions) { const n = { x: -d.y, y: d.x }; let lo = Infinity; let hi = -Infinity; for (const p of polygon) { const c = p.x * n.x + p.y * n.y; lo = Math.min(lo, c); hi = Math.max(hi, c); } for (let c = Math.ceil(lo / spacing) * spacing; c <= hi; c += spacing) { const ts = []; for (let i = 0; i < polygon.length; i++) { const a = polygon[i]; const b = polygon[(i + 1) % polygon.length]; const fa = a.x * n.x + a.y * n.y - c; const fb = b.x * n.x + b.y * n.y - c; if (fa < 0 !== fb < 0) { const u = fa / (fa - fb); const p = { x: a.x + (b.x - a.x) * u, y: a.y + (b.y - a.y) * u }; ts.push(p.x * d.x + p.y * d.y); } } ts.sort((p, q) => p - q); for (let k = 0; k + 1 < ts.length; k += 2) { const at = (t) => ({ x: n.x * c + d.x * t, y: n.y * c + d.y * t }); items.push({ kind: "path", points: [at(ts[k]), at(ts[k + 1])], closed: false, stroke }); } } } return items; } function insidePolygon(polygon, p) { let inside2 = false; for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { const a = polygon[i]; const b = polygon[j]; if (a.y > p.y !== b.y > p.y && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x) inside2 = !inside2; } return inside2; } function markItems(pieces, marks, stroke) { const all = pieces.flat(); if (all.length < 2) return []; const path = new Measured(all); const size = arrowSize(stroke); return marks.map((m) => { const s = m.fixed ? m.at < 0 ? path.total + m.at * PX_PER_CM : m.at * PX_PER_CM : m.at * path.total; const { p, t } = path.at(s); const [ux, uy] = m.reversed ? [-t.x, -t.y] : [t.x, t.y]; return triangle({ x: p.x + ux * size * 0.5, y: p.y + uy * size * 0.5 }, ux, uy, size, stroke?.color ?? DEFAULT_COLOR); }); } function renderDrawn(drawn, place) { const items = []; for (const d of drawn) { const from = items.length; renderOne(d, place, items); if (!d.src) continue; const move = d.move && deviceMove(d.move, place); for (let i = from; i < items.length; i++) { const item = items[i]; items[i] = { ...item, src: d.src, ...move ? { move } : {}, ...d.textSrc && item.kind === "text" ? { textSrc: d.textSrc } : {} }; } } return items; } function deviceMove(move, place) { const { transform, ...placed } = move; return { ...placed, ...deviceFrame(transform, place) }; } function deviceFrame(transform, place) { const o = place({ x: 0, y: 0 }); const ex = place(applyLinear(transform, { x: 1, y: 0 })); const ey = place(applyLinear(transform, { x: 0, y: 1 })); return { matrix: [ex.x - o.x, ex.y - o.y, ey.x - o.x, ey.y - o.y], origin: place(apply(transform, { x: 0, y: 0 })) }; } function renderOne(d, place, items) { { if (d.kind === "label") { items.push(...renderLabel(d, place)); return; } const { paint } = d; const pieces = d.pieces.filter((p) => p.points.length > 1).map((p) => ({ points: p.points.map(place), closed: p.closed })); if (pieces.length === 0) return; const first = pieces[0]; const last = pieces[pieces.length - 1]; const extra = []; if (paint.shortenStart > 0 && !first.closed) first.points = trimStart(first.points, paint.shortenStart); if (paint.shortenEnd > 0 && !last.closed) last.points = trimEnd(last.points, paint.shortenEnd); if (paint.end && !last.closed && last.points.length >= 2) { const { items: tip, trim } = tipItems(last.points, paint.end, paint.stroke); extra.push(...tip); last.points = trimEnd(last.points, trim); } if (paint.start && !first.closed && first.points.length >= 2) { const { items: tip, trim } = tipItems([...first.points].reverse(), paint.start, paint.stroke); extra.push(...tip); first.points = trimStart(first.points, trim); } for (const piece of pieces) { const points = roundCorners(piece.points, piece.closed, paint.rounded); if (paint.pattern) { if (paint.fill) items.push({ kind: "path", points, closed: true, fill: paint.fill }); items.push(...patternItems(points, paint.pattern.kind, paint.pattern.color)); if (paint.stroke) items.push({ kind: "path", points, closed: piece.closed, stroke: paint.stroke }); } else if (paint.stroke || paint.fill) { items.push({ kind: "path", points, closed: piece.closed, ...paint.stroke ? { stroke: paint.stroke } : {}, ...paint.fill ? { fill: paint.fill } : {} }); } } if (paint.stroke || paint.fill) items.push(...extra); if (paint.marks.length > 0) items.push(...markItems(pieces.map((p) => p.points), paint.marks, paint.stroke)); } } function renderLabel(d, place) { const c = place(d.center); const items = []; if (d.stroke || d.fill) { const outline = d.shape === "rectangle" ? roundCorners( [ { x: c.x - d.halfW, y: c.y - d.halfH }, { x: c.x + d.halfW, y: c.y - d.halfH }, { x: c.x + d.halfW, y: c.y + d.halfH }, { x: c.x - d.halfW, y: c.y + d.halfH } ], true, d.rounded ) : circlePoints(c, d.halfW, d.halfH); items.push({ kind: "path", points: outline, closed: true, ...d.stroke ? { stroke: d.stroke } : {}, ...d.fill ? { fill: d.fill } : {} }); } let rotate = -d.rotate; if (d.slope) { const a = place(d.center); const b = place({ x: d.center.x + d.slope.x, y: d.center.y + d.slope.y }); rotate = Math.atan2(b.y - a.y, b.x - a.x) * 180 / Math.PI; if (rotate > 90) rotate -= 180; if (rotate < -90) rotate += 180; } const lineH = d.fontSize * 1.2; const x = d.align === "start" ? c.x - d.textHalf : d.align === "end" ? c.x + d.textHalf : c.x; d.lines.forEach((line3, i) => { if (line3 === "") return; const item = { kind: "text", at: { x, y: c.y + (i - (d.lines.length - 1) / 2) * lineH }, runs: labelRuns(line3, d.at), anchor: d.align, baseline: "middle", fontSize: d.fontSize, color: d.color }; items.push(Math.abs(rotate) > 0.01 ? { ...item, rotate } : item); }); return items; } // graphics/src/svg-import.ts init_define_L2W_CONFIG(); var CM_PER_UNIT = 0.025; var PT_PER_UNIT = CM_PER_UNIT * 28.4528; var PX_PER_UNIT = CM_PER_UNIT * 37.8; // graphics/src/index.ts var UNIT = PX_PER_CM; var PICTURE_PADDING = 14; var ROOT = { transform: IDENTITY, inherited: [], nodeStyle: [] }; function axisScene(node) { if (node.dimensions === 3) { fail( "unknown-command", "\\addplot3 draws in three dimensions, which this build does not render.", node.at, "addplot3", "Plot the section you need as a 2-D figure." ); } const frameOptions = readFrameOptions(node.options, node.at); const x = readRange(node.options, "x", node.at); const y = readRange(node.options, "y", node.at); const layout = axisLayout(frameOptions.lines, optionValue(node.options, "title") !== void 0); const frame2 = buildFrame(x, y, layout); const origin = frame2.toDevice(0, 0); const ctx = newContext({ x: Math.abs(frame2.toDevice(1, 0).x - origin.x), y: Math.abs(frame2.toDevice(0, 1).y - origin.y) }, true); const place = (p) => frame2.toDevice(p.x, p.y); const contents = []; for (const statement of node.body) { if (statement.kind === "addplot") contents.push(...traceTo(drawPlot(statement, frame2), statement.src)); else contents.push(...renderDrawn(evaluateStatements([statement], ctx, ROOT), place)); } const box = { left: layout.margin.left, top: layout.margin.top, right: layout.margin.left + layout.plotWidth, bottom: layout.margin.top + layout.plotHeight }; return { width: AXIS_WIDTH, height: AXIS_HEIGHT, items: [...traceTo(drawAxis(frame2, node.options, frameOptions, node.at), node.src), ...clipToRect(contents, box)] }; } function traceTo(items, src) { return src ? items.map((i) => ({ ...i, src })) : [...items]; } function pictureScene(statements, pictureOptions) { const ctx = newContext({ x: UNIT, y: UNIT }, false); const picture = enterScope(pictureOptions, ROOT, ctx); const drawn = evaluateStatements(statements, ctx, picture); const bounds = boundsOf(drawnPoints(drawn, ctx)); const width = (bounds.maxX - bounds.minX) * UNIT + PICTURE_PADDING * 2; const height = (bounds.maxY - bounds.minY) * UNIT + PICTURE_PADDING * 2; const place = (p) => ({ x: PICTURE_PADDING + (p.x - bounds.minX) * UNIT, // Data y runs up, device y runs down. y: PICTURE_PADDING + (bounds.maxY - p.y) * UNIT }); return fitToLabels({ width, height, items: renderDrawn(drawn, place), frame: deviceFrame(picture.transform, place) }); } function fitToLabels(scene) { const ink = boundsOfItems(scene.items); if (!Number.isFinite(ink.minX)) return scene; const minX = Math.min(PICTURE_PADDING, ink.minX); const minY = Math.min(PICTURE_PADDING, ink.minY); const maxX = Math.max(scene.width - PICTURE_PADDING, ink.maxX); const maxY = Math.max(scene.height - PICTURE_PADDING, ink.maxY); const dx = PICTURE_PADDING - minX; const dy = PICTURE_PADDING - minY; return { width: maxX - minX + PICTURE_PADDING * 2, height: maxY - minY + PICTURE_PADDING * 2, items: dx === 0 && dy === 0 ? scene.items : shiftItems(scene.items, dx, dy), ...scene.frame ? { frame: { ...scene.frame, origin: { x: scene.frame.origin.x + dx, y: scene.frame.origin.y + dy } } } : {} }; } function tikzToScene(source) { const picture = parseGraphics(source); const axes = picture.statements.filter((s) => s.kind === "axis"); if (axes.length === 0) return pictureScene(picture.statements, picture.options); if (axes.length > 1) { fail("unsupported-option", "A picture with more than one axis is not supported.", axes[1].at, "axis"); } if (picture.statements.length > 1) { const other = picture.statements.find((s) => s.kind !== "axis"); fail( "unsupported-option", "An axis cannot be combined with other drawing commands \u2014 they use different coordinate systems.", other.at ); } return axisScene(axes[0]); } function figureToScene(source) { return isChemistrySource(source) ? chemistryToScene(source) : tikzToScene(source); } function figureToSvg(source, title) { return sceneToSvg(figureToScene(source), title === void 0 ? {} : { title }); } function figurePackages(source) { const packages = []; const chemistry = isChemistrySource(source) || /\\(chemfig|schemestart)(?![A-Za-z])/.test(source); const circuit = /\\begin\s*\{circuitikz\}|\bto\s*\[\s*(?:R|C|L|D\*?|V|I|sV|battery1?|battery2|cell|lamp|bulb|ammeter|voltmeter|galvanometer|ohmmeter|switch|nos|ncs|spst|cspst|led|zD|fuse|vR|pR|short|open|resistor|capacitor|inductor|diode|vsource|isource|key|rheostat|potentiometer)\b|node\s*\[\s*(?:ground|circ|ocirc)\b/.test(source); if (/\\begin\s*\{axis\}|\\addplot/.test(source)) packages.push("\\usepackage{pgfplots}", "\\pgfplotsset{compat=1.18}"); else if (circuit) packages.push("\\usepackage{circuitikz}"); else if (!chemistry) packages.push("\\usepackage{tikz}"); if (/pattern\s*=/.test(source)) packages.push("\\usetikzlibrary{patterns}"); if (/decorat/.test(source)) packages.push("\\usetikzlibrary{decorations.pathmorphing,decorations.pathreplacing,decorations.markings}"); if (/\$\s*\(/.test(source)) packages.push("\\usetikzlibrary{calc}"); if (chemistry) packages.push("\\usepackage{chemfig}"); if (/\\ce\s*\{/.test(source)) packages.push("\\usepackage{mhchem}"); return packages; } // docir/src/doc-ir.ts init_define_L2W_CONFIG(); function isDisplayMathParagraph(block) { if (block.kind !== "paragraph") return false; const meaningful = block.children.filter((c) => c.kind !== "eqnumber" && (c.kind !== "text" || c.text.trim() !== "")); return meaningful.length === 1 && meaningful[0].kind === "math"; } function* walkBlocks(blocks) { for (const block of blocks) { yield block; if (block.kind === "list") { for (const item of block.items) yield* walkBlocks(item.blocks ?? []); } else if (block.kind === "table") { for (const row2 of block.rows) for (const cell of row2.cells) yield* walkBlocks(cell.blocks); } } } function* walkInlines(blocks) { const fromInlines = function* (children2) { for (const child of children2) { yield child; if (child.kind === "link") yield* fromInlines(child.children); } }; for (const block of walkBlocks(blocks)) { switch (block.kind) { case "paragraph": case "heading": yield* fromInlines(block.children); break; case "list": for (const item of block.items) yield* fromInlines(item.children); break; case "table": break; } } } // texdoc/src/tex-parse.ts function stripComments(source) { let out = ""; let i = 0; while (i < source.length) { const ch = source[i]; if (ch === "\\" && i + 1 < source.length) { out += ch + source[i + 1]; i += 2; continue; } if (ch === "%") { let end = source.indexOf("\n", i); if (end < 0) return out; end += 1; while (end < source.length && (source[end] === " " || source[end] === " ")) end++; i = end; continue; } out += ch; i += 1; } return out; } function matchBrace(source, open, openChar = "{", closeChar = "}") { if (source[open] !== openChar) return -1; let depth = 0; for (let i = open; i < source.length; i++) { const ch = source[i]; if (ch === "\\") { i += 1; continue; } if (ch === openChar) depth += 1; else if (ch === closeChar) { depth -= 1; if (depth === 0) return i + 1; } } return -1; } var CHARACTER_COMMANDS = { textbackslash: "\\", textasciitilde: "~", textasciicircum: "^", ldots: "\u2026", dots: "\u2026", quad: " ", qquad: " ", " ": " ", ",": " ", ";": " " }; var SIMPLE_ESCAPES = /* @__PURE__ */ new Set(["%", "$", "&", "#", "_", "{", "}"]); function unescapeTexArgument(raw) { let out = ""; let i = 0; while (i < raw.length) { if (raw[i] === "\\") { const next = raw[i + 1]; if (next !== void 0 && SIMPLE_ESCAPES.has(next)) { out += next; i += 2; continue; } const command = /^\\(textbackslash|textasciitilde|textasciicircum)(?:\{\})?/.exec(raw.slice(i)); if (command !== null) { out += command[1] === "textbackslash" ? "\\" : command[1] === "textasciitilde" ? "~" : "^"; i += command[0].length; continue; } } out += raw[i]; i += 1; } return out; } var MATH_ENVIRONMENTS = /* @__PURE__ */ new Set([ "equation", "equation*", "align", "align*", "gather", "gather*", "displaymath", "eqnarray", "eqnarray*" ]); function equationNumber(name, body) { if (name.endsWith("*") || name === "displaymath") return []; const tag = /\\tag\*?\s*\{([^}]*)\}/.exec(body); if (tag !== null) return [{ kind: "eqnumber", tag: tag[1].trim() }]; if (/\\(nonumber|notag)\b/.test(body)) return []; return [{ kind: "eqnumber" }]; } var ROW_NUMBERED = /* @__PURE__ */ new Set(["align", "gather", "eqnarray"]); function topLevelLines(body) { const lines = []; let depth = 0; let start = 0; for (let i = 0; i < body.length; i++) { const c = body[i]; if (c === "\\") { if (body.startsWith("\\begin{", i)) depth++; else if (body.startsWith("\\end{", i)) depth--; else if (body[i + 1] === "\\" && depth === 0) { lines.push(body.slice(start, i)); start = i + 2; } i++; continue; } if (c === "{") depth++; else if (c === "}") depth--; } lines.push(body.slice(start)); if (lines.length > 1 && lines[lines.length - 1].trim() === "") lines.pop(); return lines; } function rowNumbers(body) { const lines = topLevelLines(body); if (lines.length < 2) return null; return lines.map((line3) => { if (/\\(nonumber|notag)\b/.test(line3)) return null; const labels = Array.from(line3.matchAll(/\\label\s*\{([^}]*)\}/g), (m) => m[1].trim()); const tag = /\\tag\*?\s*\{([^}]*)\}/.exec(line3); return tag === null ? { labels } : { tag: tag[1].trim(), labels }; }); } function withoutLineNumbering(whole) { return whole.replace(/\\label\s*\{[^}]*\}/g, "").replace(/\\tag\*?\s*\{[^}]*\}/g, "").replace(/\\(nonumber|notag)\b/g, ""); } function eqarrRows(ir) { const arr = ir.kind === "eqarr" ? ir : ir.kind === "row" && ir.children.length === 1 && ir.children[0].kind === "eqarr" ? ir.children[0] : null; return arr !== null && arr.kind === "eqarr" ? arr.rows.length : 0; } var SECTIONING = { part: 1, chapter: 1, section: 1, subsection: 2, subsubsection: 3, paragraph: 4, subparagraph: 5 }; var sectionLevel = (name) => SECTIONING[name.endsWith("*") ? name.slice(0, -1) : name]; var TEXT_STYLES = { textbf: "bold", bf: "bold", textit: "italic", emph: "italic", textsl: "italic", it: "italic", underline: "underline", uline: "underline" }; var IGNORED_COMMANDS = /* @__PURE__ */ new Set([ "maketitle", "tableofcontents", "listoffigures", "listoftables", "newpage", "clearpage", "cleardoublepage", "pagebreak", "noindent", "indent", "centering", "raggedright", "raggedleft", "small", "footnotesize", "large", "Large", "LARGE", "huge", "Huge", "normalsize", "hfill", "vfill", "hspace", "vspace", "bigskip", "medskip", "smallskip", "printbibliography", "bibliographystyle", "hline", "toprule", "midrule", "bottomrule", "protect", "linebreak", "nolinebreak", "sloppy", "frenchspacing" ]); var TRANSPARENT_ENVIRONMENTS = /* @__PURE__ */ new Set([ "document", "center", "flushleft", "flushright", "figure", "figure*", "table", "table*", "minipage", "small", "footnotesize", "abstract", "quote", "quotation", "sloppypar" ]); function readCommand(source, at, argLimit) { if (source[at] !== "\\") return null; const match = /^\\([A-Za-z]+\*?|.)/.exec(source.slice(at)); if (match === null) return null; const name = match[1]; let i = at + match[0].length; const optionals = []; const args2 = []; for (; ; ) { let j = i; let newlines = 0; while (j < source.length && /\s/.test(source[j])) { if (source[j] === "\n") newlines += 1; j += 1; } if (newlines > 1) break; if (source[j] === "[" && optionals.length + args2.length < argLimit) { const close = matchBrace(source, j, "[", "]"); if (close < 0) break; optionals.push(source.slice(j + 1, close - 1)); i = close; continue; } if (source[j] === "{" && args2.length < argLimit) { const close = matchBrace(source, j); if (close < 0) break; args2.push(source.slice(j + 1, close - 1)); i = close; continue; } break; } return { name, optionals, args: args2, end: i }; } function lengthInCm(length2) { const m = /^\s*([0-9]*\.?[0-9]+)\s*(cm|mm|in|pt|em|ex|\\textwidth|\\linewidth|\\columnwidth)\s*$/.exec(length2); if (m === null) return null; const cmPer = { cm: 1, mm: 0.1, in: 2.54, pt: 2.54 / 72.27, em: 0.39, ex: 0.17, "\\textwidth": 16.5, "\\linewidth": 16.5, "\\columnwidth": 16.5 }; return Math.round(Number(m[1]) * cmPer[m[2]] * 10) / 10; } var ARG_COUNTS = { href: 2, includegraphics: 1, footnote: 1, cite: 1, citep: 1, citet: 1, chemfig: 1, chemname: 2, label: 1, ref: 1, eqref: 1, pageref: 1, url: 1, texttt: 1, textrm: 1, textsc: 1, caption: 1, title: 1, author: 1, date: 1, documentclass: 1, usepackage: 1, input: 1, include: 1, bibliography: 1, multicolumn: 3, textsuperscript: 1, textsubscript: 1, chapter: 1, rule: 2, hspace: 1, vspace: 1 }; function argCountFor(name) { if (ARG_COUNTS[name] !== void 0) return ARG_COUNTS[name]; if (TEXT_STYLES[name] !== void 0) return 1; if (sectionLevel(name) !== void 0) return 1; return 0; } function mathOpenerAt(source, at) { if (source.startsWith("$$", at)) return { open: "$$", close: "$$", display: true }; if (source[at] === "$") return { open: "$", close: "$", display: false }; if (source.startsWith("\\(", at)) return { open: "\\(", close: "\\)", display: false }; if (source.startsWith("\\[", at)) return { open: "\\[", close: "\\]", display: true }; return null; } function findMathCloser(source, from, close) { let i = from; while (i < source.length) { if (source.startsWith(close, i)) return i; if (source[i] === "\\") { i += 2; continue; } i += 1; } return -1; } function trimBreaks(out) { for (; ; ) { const last = out[out.length - 1]; if (last?.kind === "break" && last.variant === "line" && last !== void 0) out.pop(); else if (last?.kind === "text" && last.text.trim() === "" && out.length > 1 && out[out.length - 2].kind === "break") out.pop(); else return; } } var TexParser = class { constructor(options) { this.options = options; this.warnings = []; this.citations = []; this.bibliographyFiles = []; this.footnotes = /* @__PURE__ */ new Map(); this.images = /* @__PURE__ */ new Map(); this.footnoteCounter = 0; this.figureCounter = 1; this.unknown = /* @__PURE__ */ new Set(); } note(message) { if (this.warnings.length < 200) this.warnings.push(message); } // -- inline -- /** * Turns a chunk of LaTeX with no block structure in it into inline nodes. */ inlines(source, style = {}) { const out = []; let text = ""; const flush = () => { if (text === "") return; const collapsed = text.replace(/[ \t\r\n]+/g, " "); if (collapsed !== "") out.push({ kind: "text", text: collapsed, ...style }); text = ""; }; let i = 0; while (i < source.length) { const ch = source[i]; if (ch === "$" || ch === "\\" && (source[i + 1] === "(" || source[i + 1] === "[")) { const math = this.readInlineMath(source, i); if (math !== null) { flush(); if (math.node.kind === "math" && math.node.display) trimBreaks(out); out.push(math.node); i = math.end; continue; } } if (ch === "{") { const close = matchBrace(source, i); if (close > 0) { flush(); out.push(...this.inlines(source.slice(i + 1, close - 1), style)); i = close; continue; } } if (ch === "\\") { const next = source[i + 1]; if (next !== void 0 && SIMPLE_ESCAPES.has(next)) { text += next; i += 2; continue; } if (next === "\\") { flush(); out.push({ kind: "break", variant: "line" }); i += 2; const bracket = source[i] === "[" ? matchBrace(source, i, "[", "]") : -1; if (bracket > 0) i = bracket; continue; } const command = readCommand(source, i, argCountFor(readCommand(source, i, 0)?.name ?? "")); if (command !== null && (command.name === "chemfig" || command.name === "chemname")) { const whole = source.slice(i, command.end); const image = this.drawnFigure(whole, `A \\${command.name}`); flush(); out.push(image ?? { kind: "text", text: whole }); i = command.end; continue; } if (command !== null) { const handled = this.inlineCommand(command, style); if (handled !== null) { flush(); out.push(...handled); i = command.end; continue; } const literal = CHARACTER_COMMANDS[command.name]; if (literal !== void 0) { text += literal; i = command.end; continue; } if (IGNORED_COMMANDS.has(command.name)) { i = command.end; continue; } if (!this.unknown.has(command.name)) { this.unknown.add(command.name); this.note(`\\${command.name} is not a command TeXConverter converts; its text was kept and the command dropped.`); } flush(); for (const arg of command.args) out.push(...this.inlines(arg, style)); i = command.end; continue; } } if (ch === "\n" && this.keepLines) { flush(); const last = out[out.length - 1]; if (last !== void 0 && last.kind !== "break" && !(last.kind === "math" && last.display)) out.push({ kind: "break", variant: "line" }); i += 1; continue; } if (ch === "~") { text += "\xA0"; i += 1; continue; } if (ch === "-" && source.startsWith("---", i)) { text += "\u2014"; i += 3; continue; } if (ch === "-" && source.startsWith("--", i)) { text += "\u2013"; i += 2; continue; } if (source.startsWith("``", i)) { text += "\u201C"; i += 2; continue; } if (source.startsWith("''", i)) { text += "\u201D"; i += 2; continue; } text += ch; i += 1; } flush(); trimBreaks(out); return out; } get keepLines() { return this.options.keepLineBreaks === true; } /** `$...$`, `$$...$$`, `\(...\)` or `\[...\]` starting at `at`. */ readInlineMath(source, at) { const opener = mathOpenerAt(source, at); if (opener === null) return null; const end = findMathCloser(source, at + opener.open.length, opener.close); if (end < 0) { this.note(`An unclosed ${opener.open} was left as text.`); return null; } const latex = source.slice(at + opener.open.length, end); const node = this.math(latex, opener.display); return node === null ? null : { node, end: end + opener.close.length }; } /** One equation, or null with a note if it does not parse. */ math(latex, display) { const trimmed = latex.trim(); if (trimmed === "") return null; try { return { kind: "math", ir: lower(parseLatex(trimmed)), display, source: trimmed }; } catch (e) { this.note(`An equation was left as text because it did not parse: ${e instanceof Error ? e.message : String(e)}`); return null; } } inlineCommand(command, style) { const { name, args: args2, optionals } = command; if ((name === "underline" || name === "uline") && /^\s*\\hspace\*?\s*\{[^}]*\}\s*$/.test(args2[0] ?? "")) { return [{ kind: "blank", widthCm: lengthInCm(/\{([^}]*)\}/.exec(args2[0])[1]) ?? 2.5 }]; } const styleKey = TEXT_STYLES[name]; if (styleKey !== void 0) { return this.inlines(args2[0] ?? "", { ...style, [styleKey]: true }); } switch (name) { case "texttt": case "textrm": case "textsc": return this.inlines(args2[0] ?? "", style); case "textsuperscript": case "textsubscript": { const script = name === "textsuperscript" ? "super" : "sub"; return this.inlines(args2[0] ?? "", style).map( (n) => n.kind === "text" ? { ...n, script } : n ); } case "href": return [{ kind: "link", href: unescapeTexArgument(args2[0] ?? ""), children: this.inlines(args2[1] ?? "", style) }]; case "url": { const href = unescapeTexArgument(args2[0] ?? ""); return [{ kind: "link", href, children: [{ kind: "text", text: href }] }]; } case "includegraphics": { const path = (args2[0] ?? "").trim(); if (path === "") return []; const node = { kind: "image", part: path }; const width = this.widthFromOptions(optionals[0] ?? ""); if (width !== null) node.widthEmu = width; return [node]; } case "footnote": { const id = String(++this.footnoteCounter); this.footnotes.set(id, [{ kind: "paragraph", children: this.inlines(args2[0] ?? "") }]); return [{ kind: "footnoteref", id }]; } case "cite": case "citep": case "citet": { const keys = (args2[0] ?? "").split(",").map((k) => k.trim()).filter((k) => k !== ""); for (const key of keys) if (!this.citations.includes(key)) this.citations.push(key); return [{ kind: "citation", keys }]; } case "label": return [{ kind: "label", id: (args2[0] ?? "").trim() }]; case "rule": { const width = (args2[0] ?? "").trim(); if (/^(?:[0-9.]*\s*)?\\(?:textwidth|linewidth|columnwidth|hsize)$/.test(width)) return [{ kind: "rule" }]; return [{ kind: "blank", widthCm: lengthInCm(width) ?? 2.5 }]; } case "hrule": return [{ kind: "rule" }]; case "hfill": return [{ kind: "fill" }]; case "newpage": case "clearpage": case "cleardoublepage": case "pagebreak": return [{ kind: "break", variant: "page" }]; case "ref": case "eqref": case "pageref": { const id = (args2[0] ?? "").trim(); return [{ kind: "ref", id, wrap: name === "eqref" ? "parentheses" : "none" }]; } case "input": case "include": case "bibliography": case "documentclass": case "usepackage": case "title": case "author": case "date": return []; default: return null; } } /** * `[width=0.8\textwidth]` and friends, as EMU. * * A fraction of \textwidth is resolved against a 6.5-inch text column, * which is what Word's default page gives you. That is an assumption, but * a stated one, and it beats dropping the size and letting a figure come * in at its pixel dimensions — a 2000px screenshot would arrive 20 inches * wide. */ widthFromOptions(options) { const EMU_PER_INCH2 = 914400; const TEXT_WIDTH_INCHES = 6.5; const relative = /width\s*=\s*([0-9.]+)\s*\\(?:textwidth|linewidth|columnwidth)/.exec(options); if (relative !== null) return Math.round(Number(relative[1]) * TEXT_WIDTH_INCHES * EMU_PER_INCH2); const absolute = /width\s*=\s*([0-9.]+)\s*(in|cm|mm|pt)\b/.exec(options); if (absolute !== null) { const value = Number(absolute[1]); const perUnit = { in: EMU_PER_INCH2, cm: EMU_PER_INCH2 / 2.54, mm: EMU_PER_INCH2 / 25.4, pt: EMU_PER_INCH2 / 72 }; return Math.round(value * perUnit[absolute[2]]); } return null; } // -- blocks -- blocks(source, depth = 0) { const out = []; let paragraph = ""; let continuing = false; const flush = () => { const joined = continuing; continuing = false; if (paragraph.trim() === "") { paragraph = ""; return; } const children2 = this.inlines(paragraph); if (children2.length > 0) out.push(joined ? { kind: "paragraph", children: children2, continues: true } : { kind: "paragraph", children: children2 }); paragraph = ""; }; let i = 0; while (i < source.length) { const blank = /^[ \t]*\n[ \t]*\n\s*/.exec(source.slice(i)); if (blank !== null) { flush(); continuing = false; i += blank[0].length; continue; } if (source[i] === "\\" && (source[i + 1] === "$" || source[i + 1] === "\\")) { paragraph += source.slice(i, i + 2); i += 2; continue; } const opener = mathOpenerAt(source, i); if (opener !== null) { const closer = findMathCloser(source, i + opener.open.length, opener.close); const dollarWhole = opener.open !== "$" || closer >= 0 && !/\n[ \t]*\n/.test(source.slice(i, closer)) && source.slice(i, closer).includes("\\begin{"); if (closer >= 0 && dollarWhole) { const end = closer + opener.close.length; paragraph += source.slice(i, end); i = end; continue; } } if (source[i] === "\\") { const peek = readCommand(source, i, 0); const name = peek?.name ?? ""; if (name === "begin") { const environment = readCommand(source, i, 1); const envName = environment?.args[0]?.trim() ?? ""; const region = this.environmentRegion(source, i, envName); if (region !== null) { const inParagraph = continuing || paragraph.trim() !== ""; flush(); const blocks = this.environment(envName, region.body, source.slice(i, region.end), depth); const only = blocks.length === 1 ? blocks[0] : null; const equation = only !== null && only.kind === "paragraph" && isDisplayMathParagraph({ ...only, children: only.children.filter((c) => c.kind !== "label") }) ? only : null; if (equation !== null && equation.kind === "paragraph") { out.push(inParagraph ? { ...equation, continues: true } : equation); continuing = true; } else { out.push(...blocks); continuing = false; } i = region.end; continue; } this.note(`\\begin{${envName}} has no matching \\end, so the rest of the file was read as text.`); } if (sectionLevel(name) !== void 0) { const command = readCommand(source, i, 1); if (command !== null) { flush(); const level = sectionLevel(name); out.push( name.endsWith("*") ? { kind: "heading", level, children: this.inlines(command.args[0] ?? ""), numbered: false } : { kind: "heading", level, children: this.inlines(command.args[0] ?? "") } ); i = command.end; continue; } } if (name === "caption") { const command = readCommand(source, i, 2); if (command !== null && command.args.length > 0) { flush(); out.push({ kind: "paragraph", align: "center", children: this.inlines(command.args[command.args.length - 1]) }); i = command.end; continue; } } if (name === "schemestart") { const scheme = this.scheme(source, i); if (scheme !== null) { flush(); out.push(...scheme.blocks); i = scheme.end; continue; } this.note("\\schemestart has no matching \\schemestop, so it was read as text."); } if (name === "input" || name === "include") { const command = readCommand(source, i, 1); if (command !== null) { flush(); out.push(...this.includeFile(command.args[0] ?? "", depth)); i = command.end; continue; } } if (name === "bibliography") { const command = readCommand(source, i, 1); if (command !== null) { for (const file of (command.args[0] ?? "").split(",")) { const trimmed = file.trim(); if (trimmed !== "") this.bibliographyFiles.push(trimmed); } i = command.end; continue; } } } paragraph += source[i]; i += 1; } flush(); return out; } /** The body and extent of `\begin{name}...\end{name}`, brace-matched for nesting. */ environmentRegion(source, at, name) { const begin = readCommand(source, at, 1); if (begin === null) return null; const openTag = `\\begin{${name}}`; const closeTag = `\\end{${name}}`; let depth = 1; let i = begin.end; while (i < source.length) { if (source.startsWith(openTag, i)) { depth += 1; i += openTag.length; continue; } if (source.startsWith(closeTag, i)) { depth -= 1; if (depth === 0) return { body: source.slice(begin.end, i), end: i + closeTag.length }; i += closeTag.length; continue; } i += 1; } return null; } environment(name, body, whole, depth) { if (MATH_ENVIRONMENTS.has(name)) { const labels = []; const withoutLabels = whole.replace(/\\label\s*\{([^}]*)\}/g, (_all, id) => { labels.push({ kind: "label", id: id.trim() }); return ""; }); const rows = ROW_NUMBERED.has(name) ? rowNumbers(body) : null; if (rows !== null) { const lines = this.math(withoutLineNumbering(whole), true); if (lines !== null && lines.kind === "math" && eqarrRows(lines.ir) === rows.length) { return [{ kind: "paragraph", children: [lines, { kind: "eqnumber", rows }] }]; } } const node = this.math(withoutLabels, true); if (node === null) return [{ kind: "paragraph", children: this.inlines(body) }]; return [{ kind: "paragraph", children: [...labels, node, ...equationNumber(name, body)] }]; } if (name === "itemize" || name === "enumerate" || name === "description") { const list = this.list(body, name === "enumerate"); const start = name === "enumerate" ? /^\s*\[[^\]]*?\bstart\s*=\s*(\d+)/.exec(body) : null; return [start !== null && list.kind === "list" && Number(start[1]) !== 1 ? { ...list, start: Number(start[1]) } : list]; } if (name === "tabular" || name === "array" || name === "tabularx" || name === "longtable") { return [this.table(body, name)]; } if (name === "verbatim" || name === "lstlisting" || name === "verbatim*") { return body.split(/\n/).filter((line3) => line3.trim() !== "").map((line3) => ({ kind: "paragraph", children: [{ kind: "text", text: line3 }] })); } if (GRAPHICS_ENVIRONMENTS.has(name)) { return this.figure(name, whole); } if (TRANSPARENT_ENVIRONMENTS.has(name)) { const inner = this.blocks(body, depth); if (name === "center") { return inner.map( (block) => block.kind === "paragraph" ? { ...block, align: "center" } : block.kind === "table" ? { ...block, align: "center" } : block ); } if (name === "flushright") { return inner.map((block) => block.kind === "paragraph" ? { ...block, align: "right" } : block); } return inner; } this.note(`\\begin{${name}} is not an environment TeXConverter converts; its contents were kept as ordinary paragraphs.`); return this.blocks(body, depth); } /** * A `tikzpicture` drawn to an SVG the document can carry. * * The source is kept on the node as well as the bytes. A picture is all * Word can show, but a picture is also all that would survive: without the * source the document comes back as `\includegraphics{figure1.svg}`, which * is neither the file that went in nor anything the author can edit again. * * A figure that cannot be drawn does NOT fail the document. One refused * figure in a hundred-page thesis is a note and a block of preserved * source; taking the whole conversion down over it would be a worse * outcome than the missing picture. */ figure(name, whole) { const image = this.drawnFigure(whole, `A \\begin{${name}}`); if (image === null) { return whole.split(/\n/).filter((line3) => line3.trim() !== "").map((line3) => ({ kind: "paragraph", children: [{ kind: "text", text: line3 }] })); } return [{ kind: "paragraph", children: [image] }]; } /** * Any figure source graphics/ draws — a tikzpicture, a `\chemfig` * structure, a `\schemestart` reaction — as a picture carrying that * source, or null (with a note) when it can't be drawn. */ drawnFigure(whole, what) { let svg; try { svg = figureToSvg(whole); } catch (e) { const reason = e instanceof GraphicsError ? e.toDisplayString() : e instanceof Error ? e.message : String(e); this.note(`${what} could not be drawn, so its source was kept as text: ${reason}`); return null; } const part = `word/media/figure${this.figureCounter++}.svg`; this.images.set(part, svgToBytes(svg)); return { kind: "image", part, source: { language: "tikz", tex: whole } }; } /** A reaction scheme: `\schemestart … \schemestop` at `at`, as its own paragraph. */ scheme(source, at) { const stop = source.indexOf("\\schemestop", at); if (stop < 0) return null; const end = stop + "\\schemestop".length; const whole = source.slice(at, end); const image = this.drawnFigure(whole, "A \\schemestart reaction"); const children2 = image === null ? [{ kind: "text", text: whole }] : [image]; return { blocks: [{ kind: "paragraph", align: "center", children: children2 }], end }; } /** * `\item`-separated content, with nested lists gathered. * * A nested `\begin{itemize}` inside an item is flattened to a deeper level * rather than kept as a block inside the item, because that is the shape * docir's DocList holds — the same shape Word writes, where nesting is an * integer on each paragraph rather than a structure. */ listItemContent(source) { const children2 = []; const blocks = []; let firstText = true; const appendText = (text) => { if (text.trim() === "") return; const inlines = this.inlines(text); if (inlines.length === 0) return; if (firstText) children2.push(...inlines); else blocks.push({ kind: "paragraph", children: inlines }); }; let i = 0; while (i < source.length) { const at = source.indexOf("\\begin{tabular", i); if (at < 0) { appendText(source.slice(i)); break; } appendText(source.slice(i, at)); const command = readCommand(source, at, 1); const name = command?.args[0]?.trim() ?? ""; if (command === null || !["tabular", "tabularx", "longtable"].includes(name)) { appendText(source.slice(at, at + 1)); i = at + 1; continue; } const region = this.environmentRegion(source, at, name); if (region === null) { appendText(source.slice(at, command.end)); i = command.end; continue; } blocks.push(this.table(region.body, name)); firstText = false; i = region.end; } return { children: children2, blocks }; } list(body, ordered, level = 0) { const items = []; const pieces = this.splitItems(body); for (const piece of pieces) { let rest = piece; const nested = []; for (; ; ) { const at = this.findNestedList(rest); if (at === null) break; const region = this.environmentRegion(rest, at.index, at.name); if (region === null) break; const inner = this.list(region.body, at.name === "enumerate", level + 1); if (inner.kind === "list") { for (const item of inner.items) nested.push(item); } rest = rest.slice(0, at.index) + rest.slice(region.end); } const content = this.listItemContent(rest.replace(/^\s+/, "")); if (content.children.length > 0 || content.blocks.length > 0 || nested.length === 0) { items.push({ level, children: content.children, ...content.blocks.length ? { blocks: content.blocks } : {} }); } items.push(...nested); } return { kind: "list", ordered, items }; } findNestedList(source) { for (const name of ["itemize", "enumerate", "description"]) { const index = source.indexOf(`\\begin{${name}}`); if (index >= 0) return { index, name }; } return null; } /** Splits an environment body on top-level `\item`, ignoring ones inside nested environments. */ splitItems(body) { const out = []; let depth = 0; let start = -1; let i = 0; while (i < body.length) { if (body.startsWith("\\begin{", i)) { depth += 1; i += 7; continue; } if (body.startsWith("\\end{", i)) { depth -= 1; i += 5; continue; } if (depth === 0 && body.startsWith("\\item", i) && !/[A-Za-z]/.test(body[i + 5] ?? "")) { if (start >= 0) out.push(body.slice(start, i)); i += 5; if (body[i] === "[") { const close = matchBrace(body, i, "[", "]"); if (close > 0) i = close; } start = i; continue; } i += 1; } if (start >= 0) out.push(body.slice(start)); return out; } table(body, name) { let rest = body; let spec = ""; for (let taken = 0; taken < (name === "tabularx" ? 2 : 1); taken++) { const open = rest.indexOf("{"); if (open < 0) break; const close = matchBrace(rest, open); if (close < 0) break; spec = rest.slice(open + 1, close - 1); rest = rest.slice(close); } const bordered = spec.includes("|"); const booktabs = /\\(?:toprule|bottomrule)\b/.test(rest); const rows = []; for (const rawRow of this.splitRows(rest)) { if (booktabs && rows.length > 0 && /^\s*(?:\[[^\]]*\])?\s*\\(?:midrule|cmidrule|hline)\b/.test(rawRow)) { rows[rows.length - 1] = { ...rows[rows.length - 1], ruleBelow: true }; } const cleaned = rawRow.replace(/\\(?:hline|toprule|midrule|bottomrule)\b/g, "").replace(/^\s*\[[^\]]*\]/, "").trim(); if (cleaned === "") continue; const cells2 = this.splitCells(cleaned).map((cell) => { const multi = /^\s*\\multicolumn\s*\{(\d+)\}/.exec(cell); if (multi !== null) { const command = readCommand(cell, cell.indexOf("\\multicolumn"), 3); return { span: Number(multi[1]), blocks: [{ kind: "paragraph", children: this.inlines(command?.args[2] ?? "") }] }; } return { span: 1, blocks: [{ kind: "paragraph", children: this.inlines(cell.trim()) }] }; }); rows.push({ cells: cells2, header: false }); } return booktabs ? { kind: "table", rows, bordered: false, booktabs: true } : { kind: "table", rows, bordered }; } /** Splits on `\\` that are not inside a nested environment or group. */ splitRows(body) { const out = []; let depth = 0; let start = 0; let i = 0; while (i < body.length) { const ch = body[i]; if (ch === "{") { depth += 1; i += 1; continue; } if (ch === "}") { depth -= 1; i += 1; continue; } if (depth === 0 && body.startsWith("\\\\", i)) { out.push(body.slice(start, i)); i += 2; if (body[i] === "[") { const close = matchBrace(body, i, "[", "]"); if (close > 0) i = close; } start = i; continue; } if (ch === "\\") { i += 2; continue; } i += 1; } out.push(body.slice(start)); return out; } /** Splits a row on `&`, respecting groups and escaped ampersands. */ splitCells(row2) { const out = []; let depth = 0; let start = 0; let i = 0; while (i < row2.length) { const ch = row2[i]; if (ch === "\\") { i += 2; continue; } if (ch === "{") depth += 1; else if (ch === "}") depth -= 1; else if (ch === "&" && depth === 0) { out.push(row2.slice(start, i)); start = i + 1; } i += 1; } out.push(row2.slice(start)); return out; } includeFile(path, depth) { const max = this.options.maxInputDepth ?? 8; if (depth >= max) { this.note(`\\input{${path}} was not followed \u2014 files are nested more than ${max} deep, which usually means a cycle.`); return []; } const resolve5 = this.options.resolveInput; if (resolve5 === void 0) { this.note(`\\input{${path}} was skipped \u2014 this converter was not given a way to read other files.`); return []; } const source = resolve5(path); if (source === null) { this.note(`\\input{${path}} was skipped \u2014 the file could not be read.`); return []; } return this.blocks(stripComments(source), depth + 1); } }; function splitPreambleAndBody(source) { const begin = source.indexOf("\\begin{document}"); if (begin < 0) return { preamble: "", body: source }; const end = source.lastIndexOf("\\end{document}"); const bodyStart = begin + "\\begin{document}".length; return { preamble: source.slice(0, begin), body: end > bodyStart ? source.slice(bodyStart, end) : source.slice(bodyStart) }; } function preambleValue(preamble, command) { const at = preamble.indexOf(`\\${command}`); if (at < 0) return void 0; const parsed = readCommand(preamble, at, 1); const value = parsed?.args[0]; return value === void 0 || value.trim() === "" ? void 0 : value.trim(); } function parseTexDocument(source, options = {}) { const cleaned = stripComments(source); const { preamble, body } = splitPreambleAndBody(cleaned); const snippet = !source.includes("\\begin{document}"); const parser = new TexParser({ ...options, keepLineBreaks: options.keepLineBreaks ?? snippet }); const blocks = parser.blocks(body); const documentClassRaw = preambleValue(preamble, "documentclass") ?? "article"; const title = preambleValue(preamble, "title"); const author = preambleValue(preamble, "author"); const result = { document: { blocks, footnotes: parser.footnotes, images: parser.images }, documentClass: documentClassRaw, bibliographyFiles: parser.bibliographyFiles, citations: parser.citations, warnings: parser.warnings }; if (title !== void 0) result.title = title; if (author !== void 0) result.author = author; return result; } // texdoc/src/bibtex.ts init_define_L2W_CONFIG(); function parseBibtex(source) { const entries = []; let i = 0; while (i < source.length) { const at = source.indexOf("@", i); if (at < 0) break; const header = /^@([A-Za-z]+)\s*[{(]\s*/.exec(source.slice(at)); if (header === null) { i = at + 1; continue; } const type = header[1].toLowerCase(); let cursor = at + header[0].length; if (type === "string" || type === "preamble" || type === "comment") { const end = matchDelimiter(source, at + header[0].length - 1); i = end < 0 ? at + 1 : end; continue; } const comma = source.indexOf(",", cursor); const closing = matchDelimiter(source, at + header[0].length - 1); if (closing < 0) { i = at + 1; continue; } if (comma < 0 || comma > closing) { i = closing; continue; } const key = source.slice(cursor, comma).trim(); cursor = comma + 1; const fields = {}; while (cursor < closing - 1) { const field = /^\s*([A-Za-z][A-Za-z0-9_-]*)\s*=\s*/.exec(source.slice(cursor, closing - 1)); if (field === null) break; const valueStart = cursor + field[0].length; const value = readFieldValue(source, valueStart, closing - 1); if (value === null) break; fields[field[1].toLowerCase()] = cleanValue(value.text); cursor = value.end; const next = /^\s*,/.exec(source.slice(cursor, closing - 1)); if (next === null) break; cursor += next[0].length; } if (key !== "") entries.push({ key, type, fields }); i = closing; } return entries; } function matchDelimiter(source, open) { const opener = source[open]; const closer = opener === "(" ? ")" : "}"; if (opener !== "{" && opener !== "(") return -1; let depth = 0; for (let i = open; i < source.length; i++) { const ch = source[i]; if (ch === opener) depth += 1; else if (ch === closer) { depth -= 1; if (depth === 0) return i + 1; } } return -1; } function readFieldValue(source, at, limit) { let i = at; while (i < limit && /\s/.test(source[i])) i++; const ch = source[i]; if (ch === "{") { const end = matchDelimiter(source, i); if (end < 0) return null; return { text: source.slice(i + 1, end - 1), end }; } if (ch === '"') { let depth = 0; for (let j = i + 1; j < limit; j++) { if (source[j] === "{") depth += 1; else if (source[j] === "}") depth -= 1; else if (source[j] === '"' && depth === 0) return { text: source.slice(i + 1, j), end: j + 1 }; } return null; } const bare = /^[^,}\n]*/.exec(source.slice(i, limit)); if (bare === null) return null; return { text: bare[0].trim(), end: i + bare[0].length }; } function cleanValue(raw) { return raw.replace(/[\s]+/g, " ").replace(/[{}]/g, "").replace(/\\&/g, "&").replace(/\\%/g, "%").replace(/\\_/g, "_").replace(/~/g, " ").trim(); } function formatAuthors(raw, style) { const authors = raw.split(/\s+and\s+/i).map((name) => name.trim()).filter((name) => name !== ""); if (authors.length === 0) return ""; const formatted = authors.map((name) => { const comma = name.indexOf(","); if (comma < 0) return name; const surname = name.slice(0, comma).trim(); const given = name.slice(comma + 1).trim(); return given === "" ? surname : `${given} ${surname}`; }); if (style === "ieee") { if (formatted.length === 1) return formatted[0]; return `${formatted.slice(0, -1).join(", ")} and ${formatted[formatted.length - 1]}`; } if (formatted.length === 1) return formatted[0]; if (formatted.length === 2) return `${formatted[0]} and ${formatted[1]}`; return `${formatted.slice(0, -1).join(", ")}, and ${formatted[formatted.length - 1]}`; } function formatEntry(entry, style = "plain") { const f = entry.fields; const parts = []; const authors = formatAuthors(f.author ?? f.editor ?? "", style); if (authors !== "") parts.push(authors); if (f.title !== void 0) parts.push(style === "ieee" ? `"${f.title}"` : f.title); switch (entry.type) { case "article": if (f.journal !== void 0) parts.push(f.journal); if (f.volume !== void 0) parts.push(f.number === void 0 ? `vol. ${f.volume}` : `vol. ${f.volume}, no. ${f.number}`); if (f.pages !== void 0) parts.push(`pp. ${f.pages.replace(/--?/g, "\u2013")}`); break; case "book": if (f.publisher !== void 0) parts.push(f.publisher); if (f.edition !== void 0) parts.push(`${f.edition} ed.`); break; case "inproceedings": case "conference": if (f.booktitle !== void 0) parts.push(`in ${f.booktitle}`); if (f.pages !== void 0) parts.push(`pp. ${f.pages.replace(/--?/g, "\u2013")}`); break; case "phdthesis": parts.push("Ph.D. thesis"); if (f.school !== void 0) parts.push(f.school); break; case "mastersthesis": parts.push("Master's thesis"); if (f.school !== void 0) parts.push(f.school); break; default: if (f.howpublished !== void 0) parts.push(f.howpublished); if (f.publisher !== void 0) parts.push(f.publisher); break; } if (f.year !== void 0) parts.push(f.year); if (f.doi !== void 0) parts.push(`doi:${f.doi}`); else if (f.url !== void 0) parts.push(f.url); const line3 = parts.join(", "); return line3.endsWith(".") ? line3 : `${line3}.`; } function buildBibliography(database, citedInOrder, style = "plain") { const byKey = new Map(database.map((entry) => [entry.key, entry])); const missing = []; const found = []; for (const key of citedInOrder) { const entry = byKey.get(key); if (entry === void 0) missing.push(key); else if (!found.includes(entry)) found.push(entry); } const entries = style === "unsrt" ? found : [...found].sort((a, b) => { const left = `${a.fields.author ?? a.fields.editor ?? ""}${a.fields.year ?? ""}`.toLowerCase(); const right = `${b.fields.author ?? b.fields.editor ?? ""}${b.fields.year ?? ""}`.toLowerCase(); return left.localeCompare(right) || a.key.localeCompare(b.key); }); const labels = /* @__PURE__ */ new Map(); entries.forEach((entry, index) => labels.set(entry.key, String(index + 1))); for (const key of missing) labels.set(key, key); return { entries, labels, missing }; } // texdoc/src/tex-emit.ts init_define_L2W_CONFIG(); // renderers/src/ir-to-latex.ts init_define_L2W_CONFIG(); // ir/src/ir.ts init_define_L2W_CONFIG(); function matrixColumnAligns(matrix) { const width = Math.max(1, ...matrix.rows.map((r) => r.length)); return Array.from({ length: width }, (_, i) => matrix.columns?.[i] ?? "center"); } // renderers/src/omml-parse.ts init_define_L2W_CONFIG(); var import_xmldom = __toESM(require_lib(), 1); var M_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"; var W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; var OmmlConversionError = class extends Error { constructor(message) { super(message); this.name = "OmmlConversionError"; } }; function fail2(message) { throw new OmmlConversionError(message); } function isMathElement(node) { return node && node.nodeType === 1 && node.namespaceURI === M_NS; } function childElements(el) { const out = []; for (let i = 0; i < el.childNodes.length; i++) { const n = el.childNodes[i]; if (isMathElement(n)) out.push(n); else if (n && n.nodeType === 1 && n.namespaceURI === W_NS && n.localName === "sdt") { for (let j = 0; j < n.childNodes.length; j++) { const part = n.childNodes[j]; if (part && part.nodeType === 1 && part.namespaceURI === W_NS && part.localName === "sdtContent") out.push(...childElements(part)); } } } return out; } function firstChild(el, localName) { return childElements(el).find((c) => c.localName === localName) ?? null; } function allChildren(el, localName) { return childElements(el).filter((c) => c.localName === localName); } function attrVal(el, name) { const attrs = el.attributes; if (!attrs) return null; for (let i = 0; i < attrs.length; i++) { const a = attrs[i]; if (a.localName === name) return a.value; } return null; } function propVal(parent, name) { const el = parent ? firstChild(parent, name) : null; if (!el) return null; const value = attrVal(el, "val"); return value !== null && value.length > 0 ? value : null; } function boolProp(parent, name, whenAbsent) { const el = parent ? firstChild(parent, name) : null; if (!el) return whenAbsent; const value = attrVal(el, "val"); if (value === null || value.length === 0) return true; return value === "1" || value === "true" || value === "on"; } function containerRow(parent, name) { const el = firstChild(parent, name); return el ? parseContainerAsRow(el) : { kind: "row", children: [] }; } function parseContainerAsRow(el) { const content = childElements(el).filter((c) => c.localName !== "argPr" && c.localName !== "ctrlPr"); return { kind: "row", children: content.map(parseNode) }; } var GREEK_RANGE = /[Ͱ-Ͽἀ-῿]/; function naturalItalic(ch) { return /[A-Za-z]/.test(ch) || GREEK_RANGE.test(ch); } function parseRun(el) { const text = allChildren(el, "t").map((t) => t.textContent ?? "").join(""); const rPr = firstChild(el, "rPr"); const styVal = propVal(rPr, "sty"); let italic; let bold = false; if (rPr && firstChild(rPr, "nor")) { const w = wordRunProps(el); bold = w.has("b"); italic = w.has("i"); } else if (styVal) { bold = styVal.includes("b"); italic = styVal.includes("i"); } else { italic = [...text].every((ch) => naturalItalic(ch)) && text.length > 0; } const color = runColor(el); const node = { kind: "symbol", text, italic, bold: bold || void 0 }; if (color !== void 0) node.color = color; return node; } function wordRunProps(run3) { const on = /* @__PURE__ */ new Set(); for (let i = 0; i < run3.childNodes.length; i++) { const rPr = run3.childNodes[i]; if (!rPr || rPr.nodeType !== 1 || rPr.namespaceURI !== W_NS || rPr.localName !== "rPr") continue; for (let j = 0; j < rPr.childNodes.length; j++) { const p = rPr.childNodes[j]; if (!p || p.nodeType !== 1 || p.namespaceURI !== W_NS) continue; const val2 = attrVal(p, "val"); if (val2 === null || !/^(0|false|off)$/.test(val2)) on.add(p.localName); } } return on; } function runColor(run3) { for (let i = 0; i < run3.childNodes.length; i++) { const rPr = run3.childNodes[i]; if (!rPr || rPr.nodeType !== 1 || rPr.namespaceURI !== W_NS || rPr.localName !== "rPr") continue; for (let j = 0; j < rPr.childNodes.length; j++) { const c = rPr.childNodes[j]; if (!c || c.nodeType !== 1 || c.namespaceURI !== W_NS || c.localName !== "color") continue; const value = attrVal(c, "val"); return value && /^[0-9A-Fa-f]{6}$/.test(value) ? value.toUpperCase() : void 0; } } return void 0; } function parseFrac(el) { const typeVal = propVal(firstChild(el, "fPr"), "type") ?? "bar"; return { kind: "frac", numerator: containerRow(el, "num"), denominator: containerRow(el, "den"), noBar: typeVal === "noBar" }; } function parseRadical(el) { const hidden = boolProp(firstChild(el, "radPr"), "degHide", false); const deg = firstChild(el, "deg"); const index = !hidden && deg && childElements(deg).length > 0 ? parseContainerAsRow(deg) : void 0; return { kind: "radical", radicand: containerRow(el, "e"), index }; } function parseSuperSub(el, _kind) { const sup = firstChild(el, "sup"); const sub = firstChild(el, "sub"); return { kind: "supersub", base: containerRow(el, "e"), sup: sup && childElements(sup).length > 0 ? parseContainerAsRow(sup) : void 0, sub: sub && childElements(sub).length > 0 ? parseContainerAsRow(sub) : void 0 }; } var DEFAULT_NARY_CHAR = "\u222B"; function parseNary(el) { const naryPr = firstChild(el, "naryPr"); const chr = propVal(naryPr, "chr") ?? DEFAULT_NARY_CHAR; const limitLocation = propVal(naryPr, "limLoc") ?? "subSup"; const subHidden = boolProp(naryPr, "subHide", false); const supHidden = boolProp(naryPr, "supHide", false); const sub = !subHidden ? firstChild(el, "sub") : null; const sup = !supHidden ? firstChild(el, "sup") : null; return { kind: "nary", chr, // A present-but-empty m:sub is not a subscript. Word writes one for an // operator with no lower limit rather than omitting the element, so // taking it at face value produced `\sum_{}` for a bare `\sum`. sub: sub && childElements(sub).length > 0 ? parseContainerAsRow(sub) : void 0, sup: sup && childElements(sup).length > 0 ? parseContainerAsRow(sup) : void 0, operand: containerRow(el, "e"), limitLocation: limitLocation === "undOvr" ? "undOvr" : "subSup" }; } var DELIM_CHAR_TO_LATEX = { "(": "(", ")": ")", "[": "[", "]": "]", "|": "|", "{": "\\{ ", "}": "\\} ", "\u27E8": "\\langle ", "\u27E9": "\\rangle ", "\u2016": "\\Vert ", "\u230A": "\\lfloor ", "\u230B": "\\rfloor ", "\u2308": "\\lceil ", "\u2309": "\\rceil ", "": "." }; function delimiterCharToLatex(ch) { const found = DELIM_CHAR_TO_LATEX[ch]; if (found === void 0) fail2(`Cannot represent delimiter character "${ch}" in LaTeX \\left...\\right.`); return found; } function parseDelimited(el) { const dPr = firstChild(el, "dPr"); const begChrEl = dPr ? firstChild(dPr, "begChr") : null; const endChrEl = dPr ? firstChild(dPr, "endChr") : null; const sepChrEl = dPr ? firstChild(dPr, "sepChr") : null; const left = begChrEl ? attrVal(begChrEl, "val") ?? "" : "("; const right = endChrEl ? attrVal(endChrEl, "val") ?? "" : ")"; const sepChar = sepChrEl ? attrVal(sepChrEl, "val") ?? void 0 : void 0; const parts = allChildren(el, "e"); const rows = parts.length > 0 ? parts.map(parseContainerAsRow) : [{ kind: "row", children: [] }]; return { kind: "delimited", left, right, parts: rows, sepChar }; } function parseFunc(el) { return { kind: "row", children: [...containerRow(el, "fName").children, ...containerRow(el, "e").children] }; } function parseBox(el) { return containerRow(el, "e"); } function parseMatrix(el) { const rows = allChildren(el, "mr").map((mr) => allChildren(mr, "e").map(parseContainerAsRow)); const columns = parseMatrixColumns(el); return columns === void 0 ? { kind: "matrix", rows } : { kind: "matrix", rows, columns }; } function parseMatrixColumns(el) { const mPr = firstChild(el, "mPr"); const mcs = mPr ? firstChild(mPr, "mcs") : null; if (!mcs) return void 0; const columns = []; for (const mc of allChildren(mcs, "mc")) { const pr = firstChild(mc, "mcPr"); const justification = propVal(pr, "mcJc") ?? "center"; if (justification === "inside" || justification === "outside") { fail2(`A matrix column justified "${justification}" has no LaTeX array equivalent \u2014 only left, center and right do.`); } const align = justification === "left" ? "left" : justification === "right" ? "right" : "center"; const count = Number.parseInt(propVal(pr, "count") ?? "1", 10); for (let i = 0; i < (Number.isFinite(count) && count > 0 ? count : 1); i++) columns.push(align); } return columns.some((c) => c !== "center") ? columns : void 0; } var DEFAULT_ACCENT_CHAR = "\u0302"; function parseAcc(el) { const chr = propVal(firstChild(el, "accPr"), "chr") ?? DEFAULT_ACCENT_CHAR; return { kind: "accent", base: containerRow(el, "e"), char: chr }; } function parseBar(el) { const pos = propVal(firstChild(el, "barPr"), "pos") ?? "bot"; if (pos === "bot") return { kind: "accent", base: containerRow(el, "e"), bar: true, under: true }; return { kind: "accent", base: containerRow(el, "e"), bar: true }; } function parsePrescript(el) { const base = containerRow(el, "e"); const sub = firstChild(el, "sub"); const sup = firstChild(el, "sup"); const presub = sub && childElements(sub).length > 0 ? parseContainerAsRow(sub) : void 0; const presup = sup && childElements(sup).length > 0 ? parseContainerAsRow(sup) : void 0; return { kind: "prescript", base, presub, presup }; } function parseEqArr(el) { const pr = firstChild(el, "eqArrPr"); const baseJc = pr ? firstChild(pr, "baseJc") : null; const justifyVal = baseJc ? attrVal(baseJc, "val") : "left"; const rows = allChildren(el, "e").map(parseContainerAsRow); return { kind: "eqarr", rows, justify: justifyVal === "center" ? "center" : "left" }; } var LABELED_ARROW_GLYPHS = /* @__PURE__ */ new Set(["\u27F6", "\u27F5", "\u27F7", "\u27F9", "\u27F8", "\u27FA", "\u21CC", "\u21CB", "\u27FC", "\u21AA", "\u21A9"]); function plainTextOf(el) { const children2 = childElements(el); if (children2.length === 0 || !children2.every((c) => c.localName === "r")) return null; return children2.map((r) => allChildren(r, "t").map((t) => t.textContent ?? "").join("")).join(""); } function parseLimLow(el, wrappedByLimUpp) { const baseEl = firstChild(el, "e"); const lim = firstChild(el, "lim"); if (!baseEl || !lim) fail2("m:limLow is missing m:e or m:lim."); const baseText = plainTextOf(baseEl); if (baseText !== null && LABELED_ARROW_GLYPHS.has(baseText)) { const above = wrappedByLimUpp ? parseLimUppLabel(wrappedByLimUpp.above) : void 0; return { kind: "labeledarrow", chr: baseText, below: parseContainerAsRow(lim), above }; } if (wrappedByLimUpp) { fail2(`m:limUpp wraps m:limLow, but the inner base "${baseText ?? "(complex content)"}" is not a recognized arrow glyph \u2014 cannot tell whether this is a labeled arrow.`); } return { kind: "limlow", base: parseContainerAsRow(baseEl), lower: parseContainerAsRow(lim) }; } function parseBorderBox(el) { const pr = firstChild(el, "borderBoxPr"); const hidden = ["hideTop", "hideBot", "hideLeft", "hideRight"].map((side2) => boolProp(pr, side2, false)); const boxed = hidden.every((h) => !h); if (!boxed && !hidden.every((h) => h)) { fail2("m:borderBox with only some of its borders drawn has no LaTeX equivalent \u2014 \\boxed draws all four."); } if (boolProp(pr, "strikeH", false) || boolProp(pr, "strikeV", false)) { fail2("m:borderBox with a horizontal or vertical strike has no \\cancel equivalent \u2014 \\cancel draws a diagonal."); } const strikeBLTR = boolProp(pr, "strikeBLTR", false); const strikeTLBR = boolProp(pr, "strikeTLBR", false); return boxed ? { kind: "borderbox", base: containerRow(el, "e"), strikeBLTR, strikeTLBR, boxed: true } : { kind: "borderbox", base: containerRow(el, "e"), strikeBLTR, strikeTLBR }; } var GROUP_CHAR_BRACES = { "\u23DE": "top", "\u23DF": "bot", "\u23DC": "top", "\u23DD": "bot" }; function parseGroupChar(el) { const pr = firstChild(el, "groupChrPr"); const chr = propVal(pr, "chr") ?? "\u23DE"; const braceSide = GROUP_CHAR_BRACES[chr]; if (braceSide === void 0) { fail2(`m:groupChr with the character "${chr}" has no LaTeX equivalent \u2014 only the braces \\overbrace (\u23DE), \\underbrace (\u23DF) and the arcs \\overparen (\u23DC), \\underparen (\u23DD) are supported.`); } const pos = propVal(pr, "pos") ?? "top"; if (pos !== braceSide) { fail2(`m:groupChr draws "${chr}" but places it at "${pos}" \u2014 LaTeX has no way to write a top brace underneath (or the reverse).`); } return { kind: "groupchar", chr, pos: braceSide, base: containerRow(el, "e") }; } function parseLimUppLabel(labelEl) { return parseContainerAsRow(labelEl); } function parseLimUpp(el) { const base = firstChild(el, "e"); const lim = firstChild(el, "lim"); if (!base || !lim) fail2("m:limUpp is missing m:e or m:lim."); const baseChildren = childElements(base); if (baseChildren.length === 1 && baseChildren[0].localName === "limLow") { const inner = baseChildren[0]; const innerBase = firstChild(inner, "e"); const innerText = innerBase ? plainTextOf(innerBase) : null; if (innerText !== null && LABELED_ARROW_GLYPHS.has(innerText)) { return parseLimLow(inner, { above: lim }); } } const baseText = plainTextOf(base); if (baseText !== null && LABELED_ARROW_GLYPHS.has(baseText)) { return { kind: "labeledarrow", chr: baseText, above: parseLimUppLabel(lim), below: void 0 }; } return { kind: "limupp", base: parseContainerAsRow(base), upper: parseLimUppLabel(lim) }; } function parseNode(el) { switch (el.localName) { case "r": return parseRun(el); case "f": return parseFrac(el); case "rad": return parseRadical(el); case "sSup": return parseSuperSub(el, "sSup"); case "sSub": return parseSuperSub(el, "sSub"); case "sSubSup": return parseSuperSub(el, "sSubSup"); case "nary": return parseNary(el); case "d": return parseDelimited(el); case "func": return parseFunc(el); case "box": return parseBox(el); case "m": return parseMatrix(el); case "acc": return parseAcc(el); case "bar": return parseBar(el); case "sPre": return parsePrescript(el); case "eqArr": return parseEqArr(el); case "limLow": return parseLimLow(el, false); case "limUpp": return parseLimUpp(el); case "borderBox": return parseBorderBox(el); case "groupChr": return parseGroupChar(el); default: return fail2(`"m:${el.localName}" is not a construct TeXConverter can convert back to LaTeX yet.`); } } function parseOoxml(ooxml) { const errors = []; const doc = new import_xmldom.DOMParser({ errorHandler: (level, msg) => { if (level === "error" || level === "fatalError") errors.push(String(msg)); } }).parseFromString(ooxml, "text/xml"); if (errors.length > 0) fail2(`The provided OOXML is not well-formed XML: ${errors.join("; ")}`); return doc; } function isDisplayEquation(oMathEl) { let node = oMathEl.parentNode; while (node) { if (isMathElement(node) && node.localName === "oMathPara") return true; node = node.parentNode; } return false; } function splitEquationRows(oMathEl) { const content = childElements(oMathEl).filter((c) => c.localName !== "ctrlPr"); if (content.length !== 1 || content[0].localName !== "eqArr") return null; const rows = allChildren(content[0], "e").map((e) => { const row2 = childElements(e).filter((c) => c.localName !== "argPr" && c.localName !== "ctrlPr"); const hash = row2.findIndex((c) => c.localName === "r" && allChildren(c, "t").map((t) => t.textContent ?? "").join("") === "#"); return hash < 0 ? { body: row2, number: null } : { body: row2.slice(0, hash), number: row2.slice(hash + 1) }; }); return rows.some((r) => r.number !== null) ? rows : null; } function numberDetails(number2) { let seq = false; let inInstruction = false; let text = ""; const bookmarks = []; const walk = (node) => { if (!node || node.nodeType !== 1) return; if (node.namespaceURI === W_NS && node.localName === "fldChar") { const type = attrVal(node, "fldCharType"); inInstruction = type === "begin"; return; } if (node.namespaceURI === W_NS && node.localName === "bookmarkStart") { const name = attrVal(node, "name"); if (name) bookmarks.push(name); return; } if (node.namespaceURI === M_NS && node.localName === "t" || node.namespaceURI === W_NS && node.localName === "instrText") { const value = node.textContent ?? ""; if (inInstruction) seq ||= /^\s*SEQ\b/i.test(value); else text += value; return; } for (let i = 0; i < node.childNodes.length; i++) walk(node.childNodes[i]); }; for (const el of number2) walk(el); return { seq, text: text.trim().replace(/^\((.*)\)$/, "$1"), bookmarks }; } function equationNumberOf(oMathEl) { const rows = splitEquationRows(oMathEl); if (rows === null || rows.length !== 1) return null; return numberDetails(rows[0].number); } function equationRowNumbersOf(oMathEl) { const rows = splitEquationRows(oMathEl); return rows === null ? null : rows.map((r) => r.number === null ? null : numberDetails(r.number)); } function oMathElementToIr(oMathEl) { const rows = splitEquationRows(oMathEl); if (rows !== null && rows.length === 1) return { kind: "row", children: rows[0].body.map(parseNode) }; if (rows !== null) return { kind: "eqarr", rows: rows.map((r) => ({ kind: "row", children: r.body.map(parseNode) })), justify: "left" }; return parseContainerAsRow(oMathEl); } // renderers/src/ir-to-latex.ts function fail3(message) { throw new OmmlConversionError(message); } var PREFERRED_COMMAND_FOR_GLYPH = { "\u2264": "leq", "\u2265": "geq", "\u2260": "neq", "\u2192": "to", "\u2190": "leftarrow", "\u2205": "emptyset", "\u210F": "hbar", "\xAC": "neg", "\u2016": "Vert", "\u27F9": "implies", "\u27F8": "impliedby", "\u27FA": "iff", "\u21DD": "leadsto", "\u2026": "ldots" }; var COMMAND_FOR_OPERATOR_GLYPH = Object.fromEntries( Object.entries(NARY_CHAR).map(([command, glyph]) => [glyph, command]) ); var X_ARROW_FOR_GLYPH = { "\u27F6": "xrightarrow", "\u27F5": "xleftarrow", "\u27F7": "xleftrightarrow", "\u27F9": "xRightarrow", "\u27F8": "xLeftarrow", "\u27FA": "xLeftrightarrow", "\u21CC": "xrightleftharpoons", "\u21CB": "xleftrightharpoons", "\u27FC": "xmapsto", "\u21AA": "xhookrightarrow", "\u21A9": "xhookleftarrow" }; function buildReverseSymbolMap() { const map = /* @__PURE__ */ new Map(); for (const [command, def] of Object.entries(SYMBOL_TABLE)) { if (!map.has(def.text)) map.set(def.text, command); } for (const [glyph, command] of Object.entries(COMMAND_FOR_OPERATOR_GLYPH)) { map.set(glyph, command); } for (const [glyph, command] of Object.entries(PREFERRED_COMMAND_FOR_GLYPH)) { map.set(glyph, command); } return map; } var REVERSE_SYMBOL_MAP = buildReverseSymbolMap(); function reverseChar(ch) { const command = REVERSE_SYMBOL_MAP.get(ch); if (command !== void 0) return `\\${command} `; if (ch === "\\" || ch === "{" || ch === "}" || ch === "%" || ch === "$" || ch === "#" || ch === "&" || ch === "_") { return `\\${ch}`; } return ch; } function reverseText(text) { return [...text].map(reverseChar).join(""); } function invert2(map) { const out = /* @__PURE__ */ new Map(); for (const [plain, glyph] of Object.entries(map)) out.set(glyph, plain); return out; } var REVERSE_VARIANT_MAPS = { mathbb: invert2(MATHBB_MAP), mathcal: invert2(MATHCAL_MAP), mathfrak: invert2(MATHFRAK_MAP), mathsf: invert2(MATHSF_MAP), mathtt: invert2(MATHTT_MAP) }; var GREEK_RANGE2 = /[Ͱ-Ͽἀ-῿]/; function naturalItalic2(ch) { return /[A-Za-z]/.test(ch) || GREEK_RANGE2.test(ch); } function italicIsMeaningless(ch) { return !naturalItalic2(ch) && REVERSE_SYMBOL_MAP.has(ch); } function matchesNaturalItalic(text, italic) { if (text.length === 0) return true; return [...text].every((ch) => naturalItalic2(ch) === italic || italicIsMeaningless(ch)); } function classifySymbolStyle(s) { const chars = [...s.text]; if (chars.length > 0 && !s.bold) { for (const variant of ["mathbb", "mathcal", "mathfrak", "mathsf", "mathtt"]) { const map = REVERSE_VARIANT_MAPS[variant]; if (chars.every((c) => map.has(c))) return { kind: "variant", variant, plainText: chars.map((c) => map.get(c)).join("") }; } } const bold = s.bold ?? false; if (matchesNaturalItalic(s.text, s.italic) && !/\s/.test(s.text)) return bold ? { kind: "boldsymbol" } : { kind: "plain" }; if (!s.italic) return bold ? { kind: "mathbf" } : { kind: "mathrm" }; if (!bold && !/\s/.test(s.text)) return { kind: "mathit" }; fail3( `Cannot represent this run ("${s.text}", italic=${s.italic}, bold=${bold}) in LaTeX \u2014 its styling doesn't match any of plain text, \\mathbf, \\boldsymbol, or \\mathrm.` ); } function styleSignature(style) { return style.kind === "variant" ? `variant:${style.variant}` : style.kind; } function wrapStyle(style, inner) { switch (style.kind) { case "variant": return `\\${style.variant}{${inner}}`; case "mathbf": return /\s/.test(inner) && !/[\\{}^_$&%#~]/.test(inner) ? `\\textbf{${inner}}` : `\\mathbf{${inner}}`; case "boldsymbol": return `\\boldsymbol{${inner}}`; case "mathrm": return `\\mathrm{${inner}}`; case "mathit": return `\\mathit{${inner}}`; case "plain": return inner; } } function wrapColor(color, inner) { if (color === void 0) return inner; const name = xcolorName(color); return name === void 0 ? `\\textcolor[HTML]{${color}}{${inner}}` : `\\textcolor{${name}}{${inner}}`; } function groupText(node, style) { if (style.kind === "variant") return style.plainText; if (style.kind === "mathrm") return node.text; return reverseText(node.text); } function mustStayWrapped(ch) { return naturalItalic2(ch) || /\s/.test(ch); } function splitUprightRun(text) { const pieces = []; let buf = ""; let bufWrapped = false; const flush = () => { if (buf === "") return; pieces.push(bufWrapped ? { style: { kind: "mathrm" }, text: buf } : { style: { kind: "plain" }, text: reverseText(buf) }); buf = ""; }; for (const ch of text) { const wrapped = mustStayWrapped(ch); if (buf !== "" && wrapped !== bufWrapped) flush(); bufWrapped = wrapped; buf += ch; } flush(); return pieces; } function symbolPieces(node) { const style = classifySymbolStyle(node); const pieces = style.kind !== "mathrm" ? [{ style, text: groupText(node, style) }] : splitUprightRun(node.text); return node.color === void 0 ? pieces : pieces.map((p) => ({ ...p, color: node.color })); } function emitGroup(style, text) { if (style.kind === "plain") return text; if (style.kind === "mathrm" && FUNCTION_NAMES.has(text)) return `\\${text} `; return wrapStyle(style, text); } function stringifyChildren(nodes) { const lastIndex = nodes.length - 1; let out = ""; let pendingStyle = null; let pendingColor; let pendingText = ""; const flush = () => { if (pendingStyle === null) return; out += wrapColor(pendingColor, emitGroup(pendingStyle, pendingText)); pendingStyle = null; pendingColor = void 0; pendingText = ""; }; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (node.kind !== "symbol") { flush(); out += node.kind === "nary" && i !== lastIndex ? `{${irToLatex(node)}}` : irToLatex(node); continue; } for (const piece of symbolPieces(node)) { if (pendingStyle !== null && styleSignature(pendingStyle) === styleSignature(piece.style) && pendingColor === piece.color) { pendingText += piece.text; } else { flush(); pendingStyle = piece.style; pendingColor = piece.color; pendingText = piece.text; } } } flush(); return out; } var COLUMN_SPEC_CHAR = { left: "l", center: "c", right: "r" }; var ACCENT_COMMAND_FOR_CHAR = { "\u0302": "hat", "\u0303": "tilde", "\u0307": "dot", "\u0308": "ddot", "\u030C": "check", "\u0306": "breve", "\u20D7": "vec", "\u20D6": "overleftarrow", "\u20E1": "overleftrightarrow" }; var GROUP_CHAR_COMMAND = { "\u23DE": "overbrace", "\u23DF": "underbrace", "\u23DC": "overparen", "\u23DD": "underparen" }; function groupCharCommand(chr) { const command = GROUP_CHAR_COMMAND[chr]; if (command === void 0) fail3(`Cannot represent the group character "${chr}" in LaTeX.`); return command; } var delimiterDepth = 0; function uprightFunctionName(node) { const parts = node.kind === "row" ? node.children : [node]; if (parts.length === 0 || !parts.every((p) => p.kind === "symbol" && !p.italic)) return null; const name = parts.map((p) => p.text).join(""); return FUNCTION_NAMES.has(name) ? name : null; } function ruledArrayLatex(node) { if (node.sepChar !== "|" || node.parts.length < 2) return null; const matrices = node.parts.map((p) => singleChild([p])); if (!matrices.every((m) => m !== null && m.kind === "matrix")) return null; const ms = matrices; const height = ms[0].rows.length; if (!ms.every((m) => m.rows.length === height)) return null; const spec = ms.map((m) => matrixColumnAligns(m).map((c) => COLUMN_SPEC_CHAR[c]).join("")).join("|"); const rows = []; for (let i = 0; i < height; i++) { rows.push(ms.flatMap((m) => { const width = matrixColumnAligns(m).length; return Array.from({ length: width }, (_, j) => m.rows[i][j] ? irToLatex(m.rows[i][j]) : ""); }).join(" & ")); } const body = withRowRules(rows, ms[0].hlines); const edgeRules = (node.left === "" || node.left === "|") && (node.right === "" || node.right === "|"); const array = (prefix, suffix) => `\\begin{array}{${prefix}${spec}${suffix}} ${body} \\end{array}`; if (edgeRules) return array(node.left === "|" ? "|" : "", node.right === "|" ? "|" : ""); return `\\left${delimiterCharToLatex(node.left)}${array("", "")}\\right${delimiterCharToLatex(node.right)}`; } function withRowRules(rows, hlines) { if (hlines === void 0 || hlines.length === 0) return rows.join(" \\\\ "); const out = rows.map((r, i) => hlines.includes(i) ? `\\hline ${r}` : r).join(" \\\\ "); return hlines.includes(rows.length) ? `${out} \\\\ \\hline` : out; } function braced(node) { const s = irToLatex(node); return `{${s}}`; } function singleChild(parts) { if (parts.length !== 1) return null; const part = parts[0]; if (part.kind === "row") return part.children.length === 1 ? part.children[0] : null; return part; } function irToLatex(node) { switch (node.kind) { case "row": return stringifyChildren(node.children); case "symbol": return stringifyChildren([node]); case "frac": { const cmd = node.noBar ? "binom" : "frac"; return `\\${cmd}${braced(node.numerator)}${braced(node.denominator)}`; } case "radical": return node.index ? `\\sqrt[${irToLatex(node.index)}]${braced(node.radicand)}` : `\\sqrt${braced(node.radicand)}`; case "supersub": { const baseLatex = irToLatex(node.base); let out = baseLatex.length === 0 ? "{}" : baseLatex; const fn = node.sub && !node.sup ? uprightFunctionName(node.base) : null; if (fn !== null && LIMIT_STYLE_FUNCTIONS.has(fn)) out = `\\${fn}\\nolimits`; if (node.sub) out += `_${braced(node.sub)}`; if (node.sup) out += `^${braced(node.sup)}`; return out; } case "limlow": { if (node.base.kind === "groupchar" && node.base.pos === "bot") { return `\\${groupCharCommand(node.base.chr)}${braced(node.base.base)}_${braced(node.lower)}`; } const name = uprightFunctionName(node.base); if (name === null) return `\\underset${braced(node.lower)}${braced(node.base)}`; return LIMIT_STYLE_FUNCTIONS.has(name) ? `\\${name}_${braced(node.lower)}` : `\\${name}\\limits_${braced(node.lower)}`; } case "limupp": if (node.base.kind === "groupchar" && node.base.pos === "top") { return `\\${groupCharCommand(node.base.chr)}${braced(node.base.base)}^${braced(node.upper)}`; } return `\\overset${braced(node.upper)}${braced(node.base)}`; case "groupchar": return `\\${groupCharCommand(node.chr)}${braced(node.base)}`; case "borderbox": { let inner; if (node.strikeBLTR && node.strikeTLBR) inner = `\\xcancel${braced(node.base)}`; else if (node.strikeTLBR) inner = `\\bcancel${braced(node.base)}`; else if (node.strikeBLTR) inner = `\\cancel${braced(node.base)}`; else inner = irToLatex(node.base); return node.boxed ? `\\boxed{${inner}}` : inner; } case "nary": { const command = COMMAND_FOR_OPERATOR_GLYPH[node.chr]; if (!command) fail3(`Cannot represent the operator "${node.chr}" as a LaTeX \\sum/\\int-style command.`); let out = `\\${command}`; const stacked = node.limitLocation === "undOvr"; if ((node.sub || node.sup) && stacked !== UNDER_OVER_CHARS.has(node.chr)) out += stacked ? "\\limits" : "\\nolimits"; if (node.sub) out += `_${braced(node.sub)}`; if (node.sup) out += `^${braced(node.sup)}`; return `${out} ${irToLatex(node.operand)}`; } case "delimited": { if (node.left === "(" && node.right === ")" && !node.sepChar) { const only = singleChild(node.parts); if (only && only.kind === "frac" && only.noBar) return irToLatex(only); } delimiterDepth++; try { const ruled = ruledArrayLatex(node); if (ruled !== null) return ruled; const left = delimiterCharToLatex(node.left); const right = delimiterCharToLatex(node.right); if (node.parts.length === 1) { return `\\left${left}${irToLatex(node.parts[0])}\\right${right}`; } if (!node.sepChar) fail3("A multi-part delimited group must have a separator character (\\middle)."); const sep3 = delimiterCharToLatex(node.sepChar).trim(); const middle = node.parts.map((p) => irToLatex(p)).join(`\\middle${sep3} `); return `\\left${left}${middle}\\right${right}`; } finally { delimiterDepth--; } } case "matrix": { const rows = withRowRules(node.rows.map((r) => r.map((cell) => irToLatex(cell)).join(" & ")), node.hlines); const aligns = matrixColumnAligns(node); if (aligns.some((c) => c !== "center") || node.hlines !== void 0 && node.hlines.length > 0) { const spec = aligns.map((c) => COLUMN_SPEC_CHAR[c]).join(""); return `\\begin{array}{${spec}} ${rows} \\end{array}`; } return `\\begin{matrix} ${rows} \\end{matrix}`; } case "accent": { if (node.bar) return node.under ? `\\underline${braced(node.base)}` : `\\bar${braced(node.base)}`; const command = ACCENT_COMMAND_FOR_CHAR[node.char ?? ""]; if (!command) fail3(`Cannot represent the combining accent character "${node.char}" as a LaTeX accent command.`); return `\\${command}${braced(node.base)}`; } case "prescript": { const sub = node.presub ? `_{${irToLatex(node.presub)}}` : ""; const sup = node.presup ? `^{${irToLatex(node.presup)}}` : ""; return `{}${sub}${sup}${irToLatex(node.base)}`; } case "eqarr": { const nested = delimiterDepth > 0; const envName = node.justify === "left" ? nested ? "aligned" : "align*" : nested ? "gathered" : "gather*"; const rows = node.rows.map((r) => irToLatex(r)).join(" \\\\ "); return `\\begin{${envName}} ${rows} \\end{${envName}}`; } case "labeledarrow": { const xCommand = X_ARROW_FOR_GLYPH[node.chr]; if (xCommand !== void 0) { const command2 = xCommand; const below = node.below ? `[${irToLatex(node.below)}]` : ""; const above = node.above ? braced(node.above) : "{}"; return `\\${command2}${below}${above}`; } const command = REVERSE_SYMBOL_MAP.get(node.chr); const glyph = command === void 0 ? node.chr : `\\${command}`; let out = node.below ? `\\underset${braced(node.below)}{${glyph}}` : glyph; if (node.above) out = `\\overset${braced(node.above)}{${out}}`; return out; } default: { const exhaustive = node; throw new OmmlConversionError(`Unhandled IR node in irToLatex: ${JSON.stringify(exhaustive)}`); } } } // texdoc/src/preamble.ts init_define_L2W_CONFIG(); function emptyFeatures() { return { images: false, links: false, tables: false, chemistry: false, units: false, unicode: false, colouredTables: false, tikz: false, pgfplots: false, chemfig: false, enumitem: false, booktabs: false }; } function sectioningCommands(documentClass) { const shared = ["section", "subsection", "subsubsection", "paragraph", "subparagraph"]; return documentClass === "article" ? shared : ["chapter", ...shared]; } function buildPreamble(features, options = {}) { if (options.customPreamble !== void 0) return options.customPreamble.trimEnd(); const documentClass = options.documentClass ?? "article"; const classOptions = [`${options.fontSize ?? 11}pt`, options.paper ?? "a4paper"].join(","); const lines = [`\\documentclass[${classOptions}]{${documentClass}}`]; lines.push("\\usepackage{amsmath}", "\\usepackage{amssymb}"); if (features.unicode) { lines.push("\\usepackage{iftex}", "\\ifTUTeX\\usepackage{fontspec}\\fi"); } if (features.chemistry) lines.push("\\usepackage{mhchem}"); if (features.units) lines.push("\\usepackage{siunitx}"); if (features.images) lines.push("\\usepackage{graphicx}"); if (features.tables) lines.push("\\usepackage{array}"); if (features.booktabs) lines.push("\\usepackage{booktabs}"); if (features.enumitem) lines.push("\\usepackage{enumitem}"); if (features.pgfplots) lines.push("\\usepackage{pgfplots}", "\\pgfplotsset{compat=1.18}"); else if (features.tikz) lines.push("\\usepackage{tikz}"); if (features.chemfig) lines.push("\\usepackage{chemfig}"); if (features.colouredTables) lines.push("\\usepackage[table]{xcolor}"); if (features.links) lines.push("\\usepackage{hyperref}"); return lines.join("\n"); } // texdoc/src/tex-emit.ts var TEXT_ESCAPES = { "\\": "\\textbackslash{}", "&": "\\&", "%": "\\%", $: "\\$", "#": "\\#", _: "\\_", "{": "\\{", "}": "\\}", "~": "\\textasciitilde{}", "^": "\\textasciicircum{}" }; var LIGATURE_CHARACTERS = /* @__PURE__ */ new Set(["-", "'", "`", ",", "<", ">"]); function escapeText(text) { let out = ""; let previous = ""; for (const ch of text) { if (ch === previous && LIGATURE_CHARACTERS.has(ch)) out += "{}"; out += TEXT_ESCAPES[ch] ?? ch; previous = ch; } return out; } var DISPLAY_ENVIRONMENTS = /^\s*\\begin\{(equation|align|gather|displaymath|multline|eqnarray)\*?\}/; function isDisplayEnvironment(latex) { return DISPLAY_ENVIRONMENTS.test(latex); } function escapeLabel(id) { return id.replace(/[\\{}%#$&~^]/g, ""); } function hasNonLatin1(text) { for (const ch of text) if (ch.codePointAt(0) > 255) return true; return false; } var Emitter = class { constructor(document2, options) { this.document = document2; this.options = options; this.features = emptyFeatures(); this.images = /* @__PURE__ */ new Map(); this.warnings = []; this.imageNames = /* @__PURE__ */ new Map(); this.imageCounter = options.imageStartIndex ?? 1; } // -- inline -- inline(nodes) { return nodes.map((n) => this.inlineOne(n)).join(""); } inlineOne(node) { switch (node.kind) { case "text": return this.text(node.text, node); case "math": return this.math(node.ir, node.display, node.source); case "link": { this.features.links = true; const label = this.inline(node.children); return `\\href{${escapeText(node.href)}}{${label}}`; } case "image": return this.image(node); case "break": return node.variant === "page" ? "\n\n\\newpage\n\n" : "\\\\\n"; case "rule": return "\\noindent\\rule{\\textwidth}{0.4pt}"; case "fill": return "\\hfill "; case "blank": return `\\underline{\\hspace{${node.widthCm}cm}}`; case "citation": return `\\cite{${node.keys.map((k) => escapeLabel(k)).join(",")}}`; case "label": return `\\label{${escapeLabel(node.id)}}`; case "eqnumber": return ""; case "ref": return node.wrap === "parentheses" ? `\\eqref{${escapeLabel(node.id)}}` : `\\ref{${escapeLabel(node.id)}}`; case "footnoteref": { const note = this.document.footnotes.get(node.id); if (note === void 0) return ""; const body = note.map((b) => this.block(b)).join(" ").trim(); return `\\footnote{${body}}`; } } } text(raw, style) { if (raw === "") return ""; if (hasNonLatin1(raw)) this.features.unicode = true; let out = escapeText(raw).replace(/\t/g, "\\quad{}"); if (style.script === "sub") out = `\\textsubscript{${out}}`; else if (style.script === "super") out = `\\textsuperscript{${out}}`; if (style.bold === true) out = `\\textbf{${out}}`; if (style.italic === true) out = `\\textit{${out}}`; if (style.underline === true) out = `\\underline{${out}}`; return out; } math(ir, display, source) { let latex; if (source !== void 0) { latex = source; } else { try { latex = irToLatex(ir); } catch (e) { const reason = e instanceof Error ? e.message : String(e); this.warnings.push(`An equation could not be written as LaTeX and was left as a marker: ${reason}`); return "\\textbf{[equation not converted]}"; } } if (latex.includes("\\ce{")) this.features.chemistry = true; if (/\\si\{|\\unit\{/.test(latex)) this.features.units = true; if (!display) return `$${latex}$`; return isDisplayEnvironment(latex) ? latex : `\\[${latex}\\]`; } image(node) { if (node.source?.language === "tikz") { const packages = figurePackages(node.source.tex).join("\n"); if (packages.includes("{pgfplots}")) this.features.pgfplots = true; if (packages.includes("{tikz}")) this.features.tikz = true; if (packages.includes("{chemfig}")) this.features.chemfig = true; if (packages.includes("{mhchem}")) this.features.chemistry = true; return node.source.tex; } this.features.images = true; const bytes = this.document.images.get(node.part); if (bytes === void 0) { this.warnings.push(`An image referenced ${node.part}, which is not in the document, and was skipped.`); return ""; } let path = this.imageNames.get(node.part); if (path === void 0) { const dot = node.part.lastIndexOf("."); const extension = dot < 0 ? ".png" : node.part.slice(dot); const folder = this.options.imageFolder ?? "images"; path = `${folder}/image${this.imageCounter++}${extension}`; this.imageNames.set(node.part, path); this.images.set(path, bytes); } const options = node.widthEmu !== void 0 ? `[width=${(node.widthEmu / 914400).toFixed(3)}in]` : ""; return `\\includegraphics${options}{${path}}`; } // -- blocks -- block(block) { switch (block.kind) { case "heading": return this.heading(block.level, this.inline(block.children), block.numbered !== false); case "paragraph": { const labelled = this.labelledDisplayEquation(block.children); if (labelled !== null) return labelled; const body = this.inline(block.children).trim(); if (body === "") return ""; if (block.align === "center") return `\\begin{center} ${body} \\end{center}`; if (block.align === "right") return `\\begin{flushright} ${body} \\end{flushright}`; return body; } case "list": return this.list(block.items, block.ordered, 0, block.start); case "table": return this.table(block); } } /** * A paragraph that is one display equation plus its number and labels. * * `\label` has to sit *inside* the equation environment. Outside it, LaTeX * attaches it to whatever counter was last stepped — usually the section — * so every `\ref` to it silently prints a section number instead of an * equation number. Nothing errors; the document is simply wrong. * * A numbered equation becomes a numbered environment even without a * label, so it keeps its number; a fixed one (Word's "#(3.1)") keeps it * as `\tag`. * * Returns null for any other shape, so the ordinary paragraph path runs. */ labelledDisplayEquation(children2) { const meaningful = children2.filter((c) => c.kind !== "text" || c.text.trim() !== ""); const labels = meaningful.filter((c) => c.kind === "label"); const number2 = meaningful.find((c) => c.kind === "eqnumber"); const rest = meaningful.filter((c) => c.kind !== "label" && c.kind !== "eqnumber"); if (labels.length === 0 && number2 === void 0 || rest.length !== 1) return null; const math = rest[0]; if (math.kind !== "math" || !math.display) return null; const latex = math.source ?? (() => { try { return irToLatex(math.ir); } catch { return null; } })(); if (latex === null) return null; if (number2?.rows !== void 0) { const lines = this.lineNumberedEquation(latex, number2.rows); if (lines !== null) return lines; } let tags = labels.map((l) => `\\label{${escapeLabel(l.id)}}`).join(""); if (number2?.tag !== void 0 && !/\\tag\b/.test(latex)) tags += `\\tag{${number2.tag}}`; const opening = /^\s*\\begin\{(equation|align|gather|multline|eqnarray)(\*?)\}/.exec(latex); if (opening !== null) { const name = opening[1]; const unstarred = opening[2] === "" ? latex : latex.replace(`\\begin{${name}*}`, `\\begin{${name}}`).replace(`\\end{${name}*}`, `\\end{${name}}`); return unstarred.replace(`\\begin{${name}}`, `\\begin{${name}}${tags}`); } return `\\begin{equation}${tags}${latex}\\end{equation}`; } /** * An aligned block numbered line by line, as an `align` (or the `gather` * or `eqnarray` it was) with each line's `\label`, `\tag` or `\nonumber` * at its end. Null when the lines don't match the numbers. */ lineNumberedEquation(latex, rows) { const env = /^\s*\\begin\{(align|gather|eqnarray|aligned|gathered)\*?\}([\s\S]*)\\end\{\1\*?\}\s*$/.exec(latex); if (env === null) return null; const lines = topLevelLines(env[2]); if (lines.length !== rows.length) return null; const name = env[1] === "aligned" ? "align" : env[1] === "gathered" ? "gather" : env[1]; const body = lines.map((line3, i) => { const row2 = rows[i]; const end = row2 === null ? "\\nonumber" : row2.labels.map((l) => `\\label{${escapeLabel(l)}}`).join("") + (row2.tag === void 0 ? "" : `\\tag{${row2.tag}}`); return `${line3.trim()}${end ? ` ${end}` : ""}`; }); return `\\begin{${name}} ${body.join(" \\\\\n")} \\end{${name}}`; } heading(level, body, numbered = true) { const commands = sectioningCommands(this.options.documentClass ?? "article"); const index = Math.min(level - 1, commands.length - 1); if (level - 1 > commands.length - 1) { this.warnings.push(`A Heading ${level} was written as \\${commands[index]}, the deepest level this document class has.`); } return `\\${commands[index]}${numbered ? "" : "*"}{${body}}`; } list(items, ordered, level, start) { const environment = ordered ? "enumerate" : "itemize"; const indent = " ".repeat(level); const from = ordered && start !== void 0 && start !== 1 ? `[start=${start}]` : ""; if (from) this.features.enumitem = true; const lines = [`${indent}\\begin{${environment}}${from}`]; for (let i = 0; i < items.length; i++) { const item = items[i]; if (item.level > level) { const start2 = i; while (i < items.length && items[i].level > level) i++; lines.push(this.list(items.slice(start2, i), ordered, level + 1)); i--; continue; } lines.push(`${indent} \\item ${this.inline(item.children)}`); for (const block of item.blocks ?? []) { if (block.kind === "table" && !block.bordered && block.booktabs !== true) lines.push(`${item.children.length > 0 ? "\\\\\n" : ""}${this.optionsTable(block)}`); else lines.push(this.block(block)); } } lines.push(`${indent}\\end{${environment}}`); return lines.join("\n"); } table(table) { const tabular = this.tabular(table); return table.align === "center" ? `\\begin{center} ${tabular} \\end{center}` : tabular; } tabular(table) { this.features.tables = true; const width = Math.max(1, ...table.rows.map((r) => r.cells.reduce((n, c) => n + c.span, 0))); if (table.booktabs === true && this.options.tableBorders !== true) return this.booktabs(table, width); const borders = this.options.tableBorders ?? table.bordered; const spec = borders ? `|${"l|".repeat(width)}` : "l".repeat(width); const lines = [`\\begin{tabular}{${spec}}`]; if (borders) lines.push("\\hline"); for (const row2 of table.rows) { const cells2 = row2.cells.map((cell) => { const body = cell.blocks.map((b) => this.block(b)).join(" ").trim(); return cell.span > 1 ? `\\multicolumn{${cell.span}}{${borders ? "|l|" : "l"}}{${body}}` : body; }); lines.push(`${cells2.join(" & ")} \\\\`); if (borders) lines.push("\\hline"); } lines.push("\\end{tabular}"); return lines.join("\n"); } /** A table of answer options under a question: as many equal columns as it has, across the item's width. */ optionsTable(table) { this.features.tables = true; const width = Math.max(1, ...table.rows.map((r) => r.cells.reduce((n, c) => n + c.span, 0))); const share = (Math.floor(96 / width) / 100).toFixed(2).replace(/^0/, "0"); const lines = [`\\begin{tabular}{@{}${`p{${share}\\linewidth}`.repeat(width)}@{}}`]; for (const row2 of table.rows) { const cells2 = row2.cells.map((cell) => { const body = cell.blocks.map((b) => this.block(b)).join(" ").trim(); return cell.span > 1 ? `\\multicolumn{${cell.span}}{l}{${body}}` : body; }); lines.push(`${cells2.join(" & ")} \\\\`); } lines.push("\\end{tabular}"); return lines.join("\n"); } /** Lines above and below, and under the rows that had one: booktabs. */ booktabs(table, width) { this.features.booktabs = true; const lines = [`\\begin{tabular}{${"l".repeat(width)}}`, "\\toprule"]; table.rows.forEach((row2, i) => { const cells2 = row2.cells.map((cell) => { const body = cell.blocks.map((b) => this.block(b)).join(" ").trim(); return cell.span > 1 ? `\\multicolumn{${cell.span}}{l}{${body}}` : body; }); lines.push(`${cells2.join(" & ")} \\\\`); if (row2.ruleBelow === true && i < table.rows.length - 1) lines.push("\\midrule"); }); lines.push("\\bottomrule", "\\end{tabular}"); return lines.join("\n"); } emit() { const dropEmpty = this.options.dropEmptyParagraphs ?? true; const body = []; for (const block of this.document.blocks) { const text = this.block(block); if (text === "" && dropEmpty) continue; if (block.kind === "paragraph" && block.continues === true && body.length > 0) body[body.length - 1] += ` ${text}`; else body.push(text); } const preamble = buildPreamble(this.features, this.options); const tex = `${preamble} \\begin{document} ${body.join("\n\n")} \\end{document} `; return { tex, images: this.images, warnings: this.warnings }; } }; function emitTexDocument(document2, options = {}) { return new Emitter(document2, options).emit(); } // docx/src/docx-write.ts init_define_L2W_CONFIG(); // renderers/src/omml.ts init_define_L2W_CONFIG(); var MC_JC = { left: "left", center: "center", right: "right" }; var M_NS2 = "http://schemas.openxmlformats.org/officeDocument/2006/math"; var W_NS2 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; function escapeXml2(text) { return text.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); } var MATH_FONT = ``; var CTRL_PR = ``; function run(text, italic, bold = false, color) { if (text.length === 0) return ""; const sty = bold ? italic ? "bi" : "b" : italic ? "i" : "p"; const font = color === void 0 ? MATH_FONT : MATH_FONT.replace("", ``); if (!italic && new RegExp("\\p{L}-\\p{L}", "u").test(text)) { const styled = bold ? font.replace("/>", "/>") : font; return `${styled}${escapeXml2(text)}`; } return `${font}${escapeXml2(text)}`; } function matrixRuleCells(node, cellRows) { const width = matrixColumnAligns(node).length; const hidden = `${CTRL_PR}`; const box = `${CTRL_PR}`; const cells2 = []; for (let j = 0; j < width; j++) { const column = cellRows.map((r) => `${r[j] ?? ""}`).join(""); const stack = `${CTRL_PR}${column}`; cells2.push(`${box}${hidden}${stack}`); } return cells2.join(""); } function renderIr(node) { switch (node.kind) { case "row": return node.children.map(renderIr).join(""); case "symbol": return run(node.text, node.italic, node.bold ?? false, node.color); case "frac": { const type = node.noBar ? "noBar" : "bar"; const num2 = argOrPlaceholder(node.numerator); const den = argOrPlaceholder(node.denominator); return `${CTRL_PR}${num2}${den}`; } case "radical": { const hide = node.index ? "0" : "1"; const deg = node.index ? renderIr(node.index) : ""; return `${CTRL_PR}${deg}${argOrPlaceholder(node.radicand)}`; } case "supersub": { const base = argOrPlaceholder(node.base); if (node.sup && node.sub) { return `${CTRL_PR}${base}${renderIr(node.sub)}${renderIr(node.sup)}`; } if (node.sup) { return `${CTRL_PR}${base}${renderIr(node.sup)}`; } if (node.sub) { return `${CTRL_PR}${base}${renderIr(node.sub)}`; } return base; } case "limlow": return `${CTRL_PR}${argOrPlaceholder(node.base)}${argOrPlaceholder(node.lower)}`; case "limupp": return `${CTRL_PR}${argOrPlaceholder(node.base)}${argOrPlaceholder(node.upper)}`; case "borderbox": { const strikes = (node.strikeBLTR ? `` : "") + (node.strikeTLBR ? `` : ""); const hidden = node.boxed ? "" : ``; const pr = `${hidden}${strikes}${CTRL_PR}`; return `${pr}${argOrPlaceholder(node.base)}`; } case "groupchar": { const pos = node.pos === "top" ? `` : ``; const vertJc = node.pos === "top" ? `` : ``; const pr = `${pos}${vertJc}${CTRL_PR}`; return `${pr}${argOrPlaceholder(node.base)}`; } case "nary": { const subHide = node.sub ? "" : ``; const supHide = node.sup ? "" : ``; const naryPr = `${subHide}${supHide}${CTRL_PR}`; const sub = node.sub ? `${renderIr(node.sub)}` : ""; const sup = node.sup ? `${renderIr(node.sup)}` : ""; return `${naryPr}${sub}${sup}${argOrPlaceholder(node.operand)}`; } case "delimited": { const sepChr = node.sepChar !== void 0 ? `` : ""; const dPr = `${sepChr}${CTRL_PR}`; const parts = node.parts.map((p) => `${argOrPlaceholder(p)}`).join(""); return `${dPr}${parts}`; } case "matrix": { const cellRows = node.rows.map((r) => r.map((cell) => `${argOrPlaceholder(cell)}`)); const ruled = node.hlines !== void 0 && node.hlines.length > 0; const ruleRow = ruled ? `${matrixRuleCells(node, cellRows)}` : ""; const rows = cellRows.map((cells2, i) => `${ruled && node.hlines.includes(i) ? ruleRow : ""}${cells2.join("")}`).join("") + (ruled && node.hlines.includes(cellRows.length) ? ruleRow : ""); const aligns = matrixColumnAligns(node); const groups = []; for (const align of aligns) { const last = groups[groups.length - 1]; if (last && last.align === align) last.count += 1; else groups.push({ align, count: 1 }); } const mcs = groups.map( (g) => `` ).join(""); const mPr = `${mcs}${CTRL_PR}`; return `${mPr}${rows}`; } case "accent": { const base = argOrPlaceholder(node.base); if (node.bar) { return `${CTRL_PR}${base}`; } return `${CTRL_PR}${base}`; } case "prescript": { const sub = node.presub ? `${renderIr(node.presub)}` : ""; const sup = node.presup ? `${renderIr(node.presup)}` : ""; return `${CTRL_PR}${sub}${sup}${argOrPlaceholder(node.base)}`; } case "eqarr": { const rows = node.rows.map((r) => `${argOrPlaceholder(r)}`).join(""); const pr = `${CTRL_PR}`; return `${pr}${rows}`; } case "labeledarrow": { let e = run(node.chr, false); if (node.below) { e = `${CTRL_PR}${e}${argOrPlaceholder(node.below)}`; } if (node.above) { e = `${CTRL_PR}${e}${argOrPlaceholder(node.above)}`; } return e; } default: { const exhaustive = node; throw new Error(`Unhandled IR node: ${JSON.stringify(exhaustive)}`); } } } function argOrPlaceholder(node) { const xml = renderIr(node); return xml.length > 0 ? xml : ``; } var FRAGMENT_NS = `xmlns:m="${M_NS2}" xmlns:w="${W_NS2}"`; function renderEquation(ir, options = {}) { const body = renderIr(ir); const oMath = `${body}`; const inner = options.display ? `${oMath}` : oMath; return inner.replace("", ``).replace(/^/, ``); } var SEQ_EQUATION = " SEQ Equation \\* ARABIC "; function renderNumberedEquation(ir, number2) { return numberedRows([{ body: renderIr(ir), number: number2 }]); } function renderRowNumberedEquation(ir, numbers) { const rows = ir.kind === "eqarr" ? ir.rows : [ir]; return numberedRows(rows.map((row2, i) => ({ body: renderIr(row2), number: numbers[i] ?? null }))); } function numberedRows(rows) { const cells2 = rows.map((r) => `${r.body}${r.number ? `${run("#", false)}${numberMarkup(r.number)}` : ""}`).join(""); const eqArr = `${CTRL_PR}${cells2}`; return `${eqArr}`; } function numberMarkup(number2) { const fieldRun = (inner) => `${MATH_FONT}${inner}`; const bookmarks = number2.bookmarks ?? []; const marked = bookmarks.map((b) => ``).join("") + run(number2.shown, false) + bookmarks.map((b) => ``).join(""); const label = number2.seq ? fieldRun(``) + fieldRun(`${escapeXml2(SEQ_EQUATION)}`) + fieldRun(``) + marked + fieldRun(``) : marked; return `${CTRL_PR}${label}`; } function bookmarkInsideEquation(omml, id, name) { const open = omml.indexOf(""); const close = omml.lastIndexOf(""); if (open < 0 || close < open) return omml; const start = open + "".length; return omml.slice(0, start) + `` + omml.slice(start, close) + `` + omml.slice(close); } function renderEquationRef(bookmark, shown, parentheses) { const text = (t) => `${escapeXml2(t)}`; const field = ` REF ${escapeXml2(bookmark)} \\h ` + text(shown) + ``; return parentheses ? `${text("(")}${field}${text(")")}` : field; } // word/src/metadata.ts init_define_L2W_CONFIG(); var CC_TAG_INLINE = "latex2word-equation"; var CC_TAG_DISPLAY = "latex2word-equation-display"; var CC_TAG_NUMBERED = "latex2word-eqn:"; var CC_TITLE_PREFIX = "latex2word:"; var CC_TITLE_TOO_LONG = "latex2word:(source too long to store)"; function readNumberTag(prefix, tag) { if (!tag?.startsWith(prefix)) return null; const rest = tag.slice(prefix.length); const colon = rest.lastIndexOf(":"); if (colon < 0) return null; const shown = rest.slice(0, colon); const bookmark = rest.slice(colon + 1); return shown.startsWith("=") ? { shown: shown.slice(1), bookmark, fixed: true } : { shown, bookmark }; } function isOwnTag(tag) { return tag === CC_TAG_INLINE || tag === CC_TAG_DISPLAY || readNumberTag(CC_TAG_NUMBERED, tag) !== null; } function isDisplayTag(tag) { return tag === CC_TAG_DISPLAY || readNumberTag(CC_TAG_NUMBERED, tag) !== null; } var SOURCE_NAMESPACE = "urn:texconverter:equations:1"; var SOURCE_BOOKMARK_PREFIX = "_TeXSrc"; function escapeXmlText(s) { return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); } function unescapeXmlText(s) { return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(parseInt(h, 16))).replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&/g, "&"); } function sourceStoreXml(records) { const items = [...records].map( ([bookmark, r]) => `${escapeXmlText(r.latex)}` ); return `${items.join("")}`; } function readSourceStore(xml) { const out = /* @__PURE__ */ new Map(); for (const m of xml.matchAll(/<(?:[\w.-]+:)?eq\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:[\w.-]+:)?eq>)/g)) { const attrs = m[1] ?? ""; const bookmark = /\bbookmark="([^"]*)"/.exec(attrs)?.[1]; if (bookmark === void 0 || bookmark === "") continue; const display = /\bdisplay="1"/.test(attrs); out.set(unescapeXmlText(bookmark), { latex: unescapeXmlText(m[2] ?? ""), display }); } return out; } function bookmarkName(id) { const cleaned = id.replace(/[^A-Za-z0-9_]/g, "_"); const prefixed = /^[A-Za-z]/.test(cleaned) ? cleaned : `L${cleaned}`; return prefixed.slice(0, 40); } // docx/src/opc.ts init_define_L2W_CONFIG(); var OpcError = class extends Error { constructor(message) { super(message); this.name = "OpcError"; } }; function fail4(message) { throw new OpcError(message); } var CONTENT_TYPES_PART = "[Content_Types].xml"; var CRC_TABLE = (() => { const table = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; table[n] = c >>> 0; } return table; })(); function crc32(data) { let c = 4294967295; for (let i = 0; i < data.length; i++) c = CRC_TABLE[(c ^ data[i]) & 255] ^ c >>> 8; return (c ^ 4294967295) >>> 0; } var SIG_LOCAL = 67324752; var SIG_CENTRAL = 33639248; var SIG_EOCD = 101010256; var SIG_EOCD64_LOCATOR = 117853008; var EOCD_MIN_SIZE = 22; var EOCD_MAX_SEARCH = 65535 + EOCD_MIN_SIZE; var FLAG_ENCRYPTED = 1; var METHOD_STORED = 0; var METHOD_DEFLATE = 8; var ZIP64_MARKER_32 = 4294967295; var ZIP64_MARKER_16 = 65535; function view(data) { return new DataView(data.buffer, data.byteOffset, data.byteLength); } function findEocd(data) { const dv = view(data); const earliest = Math.max(0, data.length - EOCD_MAX_SEARCH); for (let i = data.length - EOCD_MIN_SIZE; i >= earliest; i--) { if (dv.getUint32(i, true) === SIG_EOCD) return i; } return fail4("This file is not a zip archive \u2014 no end-of-central-directory record was found. A .docx is a zip; a .doc from Word 97-2003 is not, and neither is a file that only has the extension."); } function decodeName(bytes, utf8Flag) { void utf8Flag; return new TextDecoder("utf-8").decode(bytes); } function readCentralDirectory(data, eocd) { const dv = view(data); if (eocd >= 20 && dv.getUint32(eocd - 20, true) === SIG_EOCD64_LOCATOR) { fail4("This .docx uses the zip64 format, which TeXConverter does not read. Zip64 appears in archives over 4 GB or with more than 65,535 parts \u2014 if this is an ordinary document, re-saving it from Word will produce a plain zip."); } const entryCount = dv.getUint16(eocd + 10, true); const centralSize = dv.getUint32(eocd + 12, true); const centralOffset = dv.getUint32(eocd + 16, true); if (entryCount === ZIP64_MARKER_16 || centralSize === ZIP64_MARKER_32 || centralOffset === ZIP64_MARKER_32) { fail4("This .docx uses the zip64 format, which TeXConverter does not read."); } if (centralOffset + centralSize > data.length) { fail4("This .docx is truncated \u2014 its central directory extends past the end of the file."); } const entries = []; let cursor = centralOffset; for (let i = 0; i < entryCount; i++) { if (cursor + 46 > data.length || dv.getUint32(cursor, true) !== SIG_CENTRAL) { fail4(`This .docx is damaged \u2014 its central directory ends after ${i} of ${entryCount} entries.`); } const flags = dv.getUint16(cursor + 8, true); const method = dv.getUint16(cursor + 10, true); const crc = dv.getUint32(cursor + 16, true); const compressedSize = dv.getUint32(cursor + 20, true); const uncompressedSize = dv.getUint32(cursor + 24, true); const nameLen = dv.getUint16(cursor + 28, true); const extraLen = dv.getUint16(cursor + 30, true); const commentLen = dv.getUint16(cursor + 32, true); const localOffset = dv.getUint32(cursor + 42, true); const name = decodeName(data.subarray(cursor + 46, cursor + 46 + nameLen), (flags & 2048) !== 0); if ((flags & FLAG_ENCRYPTED) !== 0) { fail4(`"${name}" is encrypted. TeXConverter cannot open a password-protected document \u2014 remove the protection in Word first (File > Info > Protect Document).`); } if (compressedSize === ZIP64_MARKER_32 || uncompressedSize === ZIP64_MARKER_32 || localOffset === ZIP64_MARKER_32) { fail4(`"${name}" stores its size in a zip64 record, which TeXConverter does not read.`); } entries.push({ name, method, flags, crc, compressedSize, uncompressedSize, localOffset }); cursor += 46 + nameLen + extraLen + commentLen; } return entries; } function dataOffset(data, entry) { const dv = view(data); if (entry.localOffset + 30 > data.length || dv.getUint32(entry.localOffset, true) !== SIG_LOCAL) { fail4(`This .docx is damaged \u2014 "${entry.name}" has no local file header where its directory entry says it should.`); } const nameLen = dv.getUint16(entry.localOffset + 26, true); const extraLen = dv.getUint16(entry.localOffset + 28, true); return entry.localOffset + 30 + nameLen + extraLen; } async function readPackage(data, codec) { const entries = readCentralDirectory(data, findEocd(data)); const parts = /* @__PURE__ */ new Map(); for (const entry of entries) { if (entry.name.endsWith("/")) continue; const start = dataOffset(data, entry); const end = start + entry.compressedSize; if (end > data.length) { fail4(`This .docx is truncated \u2014 "${entry.name}" extends past the end of the file.`); } const raw = data.subarray(start, end); let content; if (entry.method === METHOD_STORED) { content = raw.slice(); } else if (entry.method === METHOD_DEFLATE) { content = await codec.inflateRaw(raw); } else { fail4(`"${entry.name}" is compressed with method ${entry.method}, which TeXConverter does not read \u2014 a .docx uses only stored (0) and deflate (8).`); } if (content.length !== entry.uncompressedSize || crc32(content) !== entry.crc) { fail4(`"${entry.name}" failed its checksum \u2014 this .docx is corrupt.`); } parts.set(entry.name, content); } return { parts }; } function dosDateTime(date) { const time = date.getHours() << 11 | date.getMinutes() << 5 | Math.floor(date.getSeconds() / 2) & 31; const day = date.getFullYear() - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate(); return { time, day }; } function concat(chunks) { const total = chunks.reduce((n, c) => n + c.length, 0); const out = new Uint8Array(total); let at = 0; for (const c of chunks) { out.set(c, at); at += c.length; } return out; } async function writePackage(pkg, codec, now = /* @__PURE__ */ new Date()) { const { time, day } = dosDateTime(now); const names = [...pkg.parts.keys()]; const ordered = names.includes(CONTENT_TYPES_PART) ? [CONTENT_TYPES_PART, ...names.filter((n) => n !== CONTENT_TYPES_PART)] : names; const chunks = []; const central = []; let offset = 0; for (const name of ordered) { const content = pkg.parts.get(name); const nameBytes = new TextEncoder().encode(name); const deflated = await codec.deflateRaw(content); const useDeflate = deflated.length < content.length; const body = useDeflate ? deflated : content; const method = useDeflate ? METHOD_DEFLATE : METHOD_STORED; const sum = crc32(content); const local = new Uint8Array(30); const lv = view(local); lv.setUint32(0, SIG_LOCAL, true); lv.setUint16(4, 20, true); lv.setUint16(6, 2048, true); lv.setUint16(8, method, true); lv.setUint16(10, time, true); lv.setUint16(12, day, true); lv.setUint32(14, sum, true); lv.setUint32(18, body.length, true); lv.setUint32(22, content.length, true); lv.setUint16(26, nameBytes.length, true); lv.setUint16(28, 0, true); chunks.push(local, nameBytes, body); const dir = new Uint8Array(46); const cv = view(dir); cv.setUint32(0, SIG_CENTRAL, true); cv.setUint16(4, 20, true); cv.setUint16(6, 20, true); cv.setUint16(8, 2048, true); cv.setUint16(10, method, true); cv.setUint16(12, time, true); cv.setUint16(14, day, true); cv.setUint32(16, sum, true); cv.setUint32(20, body.length, true); cv.setUint32(24, content.length, true); cv.setUint16(28, nameBytes.length, true); cv.setUint32(38, 420 << 16, true); cv.setUint32(42, offset, true); central.push(dir, nameBytes); offset += local.length + nameBytes.length + body.length; } const centralBytes = concat(central); const end = new Uint8Array(EOCD_MIN_SIZE); const ev = view(end); ev.setUint32(0, SIG_EOCD, true); ev.setUint16(8, ordered.length, true); ev.setUint16(10, ordered.length, true); ev.setUint32(12, centralBytes.length, true); ev.setUint32(16, offset, true); return concat([...chunks, centralBytes, end]); } function partText(pkg, name) { const bytes = pkg.parts.get(name); if (bytes === void 0) return null; const text = new TextDecoder("utf-8").decode(bytes); return text.charCodeAt(0) === 65279 ? text.slice(1) : text; } function requirePartText(pkg, name) { const text = partText(pkg, name); if (text === null) { fail4(`This file has no "${name}" part, so it is not a Word document. A .docx always contains one.`); } return text; } function partsUnder(pkg, prefix) { return [...pkg.parts.keys()].filter((n) => n.startsWith(prefix)); } // docx/src/docx-write.ts var EMU_PER_INCH = 914400; var DEFAULT_TEXT_WIDTH_EMU = Math.round(6.5 * EMU_PER_INCH); function intrinsicSize(bytes) { const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); if (bytes.length >= 24 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) { return { width: dv.getUint32(16, false), height: dv.getUint32(20, false) }; } if (bytes.length > 10 && bytes[0] === 71 && bytes[1] === 73 && bytes[2] === 70) { return { width: dv.getUint16(6, true), height: dv.getUint16(8, true) }; } if (bytes.length > 4 && bytes[0] === 255 && bytes[1] === 216) { let i = 2; while (i + 9 < bytes.length) { if (bytes[i] !== 255) { i += 1; continue; } const marker = bytes[i + 1]; if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) { i += 2; continue; } const length2 = dv.getUint16(i + 2, false); const isFrame = marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204; if (isFrame) return { height: dv.getUint16(i + 5, false), width: dv.getUint16(i + 7, false) }; if (length2 < 2) return null; i += 2 + length2; } } return null; } var CONTENT_TYPE_BY_EXTENSION = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", bmp: "image/bmp", tif: "image/tiff", tiff: "image/tiff", svg: "image/svg+xml", emf: "image/x-emf", wmf: "image/x-wmf" }; function extensionOf(path) { const dot = path.lastIndexOf("."); return dot < 0 ? "" : path.slice(dot + 1).toLowerCase(); } var REL_BASE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; var FIGURE_SOURCE_PREFIX = "latex2word:tikz\n"; var FIGURE_SOURCE_LIMIT = 8e3; function escapeXmlAttribute(text) { return escapeXml2(text).replace(/\r/g, " ").replace(/\n/g, " ").replace(/\t/g, " "); } var Writer = class { constructor(document2, options) { this.document = document2; this.options = options; this.warnings = []; this.relationships = []; this.media = /* @__PURE__ */ new Map(); this.imageRelIds = /* @__PURE__ */ new Map(); this.footnoteIds = /* @__PURE__ */ new Map(); this.nextRel = 1; this.imageCounter = 0; /** Numbering ids actually used, so numbering.xml only defines those. */ this.usedLists = { ordered: false, bullet: false }; /** Each numbered list's first number, in order: list n is w:num 2 + n. */ this.orderedStarts = []; /** How far a table is indented: under a list item's text, while writing that item's blocks. */ this.tableIndent = 0; /** Display equations' sources, by the bookmark inside each: the custom XML part written with the package. */ this.sources = /* @__PURE__ */ new Map(); /** * What each numbered equation shows, counted in document order before * anything is written, so a reference ahead of its equation already shows * the right number: Word recounts SEQ and REF fields only when it updates * them, and Word on the web and on iPad seldom does. */ this.numbers = /* @__PURE__ */ new Map(); /** What a reference to each label shows: its equation's number. */ this.labelNumbers = /* @__PURE__ */ new Map(); /** For an aligned block numbered line by line, what each line shows (null: no number). */ this.rowNumbers = /* @__PURE__ */ new Map(); this.nextId = options.firstId ?? 1; this.storeSource = options.storeSourceMetadata ?? true; this.countEquations(); } /** * What a `\cite{a,b}` prints. Supplied by the caller because the number * depends on the bibliography style and on everything else the document * cites; with no bibliography at all the keys themselves are printed, * which at least leaves the sentence readable. */ citationLabels(keys) { const labels = this.options.citationLabels; const rendered = keys.map((key) => labels?.get(key) ?? key); return `[${rendered.join(", ")}]`; } countEquations() { let count = 0; for (const block of walkBlocks(this.document.blocks)) { if (block.kind !== "paragraph") continue; const numbered = numberedEquation(block.children); if (numbered === null) continue; const rows = numbered.number.rows; if (rows !== void 0) { const shown2 = rows.map((row2) => row2 === null ? null : row2.tag ?? String(++count)); this.rowNumbers.set(numbered.number, shown2); rows.forEach((row2, i) => row2?.labels.forEach((label) => this.labelNumbers.set(label, shown2[i]))); continue; } const shown = numbered.number.tag ?? String(++count); this.numbers.set(numbered.number, shown); for (const label of numbered.labels) this.labelNumbers.set(label, shown); } } /** * A paragraph that is one display equation, with no content control: one * round it, round its paragraph or even inside it (Word moves it out when it * saves) makes Word lay the equation out as inline maths. Its source goes * in the custom XML part instead, through a bookmark inside it, as the task * pane does (word/src/metadata.ts). Null for any other paragraph. */ displayEquationParagraph(children2, props, marker = "") { const numbered = this.numberedParagraph(children2, props, marker); if (numbered !== null) return numbered; const meaningful = children2.filter((c) => c.kind !== "text" || c.text.trim() !== ""); const math = meaningful[0]; if (meaningful.length !== 1 || math?.kind !== "math" || !math.display) return null; return this.paragraph(marker + this.withSource(renderEquation(math.ir, { display: true }), math.source), props); } /** The hidden bookmark that marks a paragraph as continuing the one before (DocParagraph.continues). */ continuationMarker() { const id = this.nextId++; return ``; } /** A display equation with a bookmark inside it naming its stored source, when there is one to store. */ withSource(omml, source) { if (!this.storeSource || source === void 0) return omml; const id = this.nextId++; const name = `${SOURCE_BOOKMARK_PREFIX}${id}`; this.sources.set(name, { latex: source, display: true }); return bookmarkInsideEquation(omml, id, name); } /** * A paragraph that is a numbered display equation, written as Word numbers * one (renderNumberedEquation): the number at the right margin, a SEQ field * unless it is a \tag, and the equation's labels as bookmarks round it. */ numberedParagraph(children2, props, marker = "") { const numbered = numberedEquation(children2); if (numbered === null) return null; const { math, number: number2, labels } = numbered; if (number2.rows !== void 0) { const shown2 = this.rowNumbers.get(number2) ?? []; const numbers = number2.rows.map((row2, i) => { if (row2 === null) return null; const marks = row2.labels.map((label) => ({ id: this.nextId++, name: bookmarkName(label) })); if (marks.length === 0) marks.push({ id: this.nextId++, name: `_TeXEq${this.nextId}` }); return { shown: shown2[i] ?? "?", seq: row2.tag === void 0, bookmarks: marks }; }); const lines = math.ir.kind === "row" && math.ir.children.length === 1 ? math.ir.children[0] : math.ir; return this.paragraph(marker + this.withSource(renderRowNumberedEquation(lines, numbers), math.source), props); } const bookmarks = labels.map((label) => ({ id: this.nextId++, name: bookmarkName(label) })); if (bookmarks.length === 0) bookmarks.push({ id: this.nextId++, name: `_TeXEq${this.nextId}` }); const shown = this.numbers.get(number2) ?? "?"; const omml = renderNumberedEquation(math.ir, { shown, seq: number2.tag === void 0, bookmarks }); return this.paragraph(marker + this.withSource(omml, math.source), props); } relId(type, target, external = false) { const id = `rId${this.nextRel++}`; this.relationships.push(external ? { id, type, target, external } : { id, type, target }); return id; } // -- inline -- inlines(nodes) { return nodes.map((n) => this.inlineOne(n)).join(""); } inlineOne(node) { switch (node.kind) { case "text": return this.textRun(node); case "math": { const omml = renderEquation(node.ir, { display: node.display }); return this.storeSource ? wrapWithSource(omml, node.source, node.display) : omml; } case "link": { const id = this.relId(`${REL_BASE}/hyperlink`, node.href, true); return `${this.inlines(node.children)}`; } case "image": return this.image(node); case "break": return node.variant === "page" ? `` : ``; case "footnoteref": { const id = this.footnoteIds.get(node.id); if (id === void 0) return ""; return ``; } case "citation": return this.textRun({ kind: "text", text: this.citationLabels(node.keys) }); case "label": { const id = this.nextId++; return ``; } case "ref": return this.refField(node.id, node.wrap === "parentheses"); case "eqnumber": return ""; case "rule": return ""; case "fill": return ``; case "blank": return `${"\xA0".repeat(Math.max(4, Math.round(node.widthCm * BLANK_SPACES_PER_CM)))}`; } } textRun(node) { const props = []; if (node.bold === true) props.push(""); if (node.italic === true) props.push(""); if (node.underline === true) props.push(``); if (node.script === "sub") props.push(``); if (node.script === "super") props.push(``); const rPr = props.length > 0 ? `${props.join("")}` : ""; const pieces = node.text.split(" "); const body = pieces.map((piece, i) => (i === 0 ? "" : "") + (piece === "" ? "" : `${escapeXml2(piece)}`)).join(""); return `${rPr}${body}`; } /** * A REF field: a cross-reference Word recalculates, not a frozen number. * * The text between the field's "separate" and "end" is the cached result * Word shows until it next updates fields: the equation's number when the * label is a numbered equation's (counted by countEquations), and * otherwise the key, which a reader sees replaced as soon as fields * refresh. An \eqref's parentheses are outside the field (see * renderEquationRef). */ refField(id, parentheses) { return renderEquationRef(bookmarkName(id), this.labelNumbers.get(id) ?? id, parentheses); } image(node) { const bytes = this.document.images.get(node.part); if (bytes === void 0) { this.warnings.push(`The image "${node.part}" was referenced but its file was not available, so it was left out.`); return ""; } const extension = extensionOf(node.part) || "png"; if (CONTENT_TYPE_BY_EXTENSION[extension] === void 0) { this.warnings.push(`The image "${node.part}" is a .${extension}, which Word cannot embed, so it was left out.`); return ""; } if (extension === "svg") { this.warnings.push( `The image "${node.part}" is an SVG. It is embedded correctly for the package format, but Word needs a raster fallback alongside it, which this build does not yet write \u2014 expect a placeholder where the picture should be.` ); } let relId = this.imageRelIds.get(node.part); let target; if (relId === void 0) { const name = `image${++this.imageCounter}.${extension}`; target = `media/${name}`; this.media.set(`word/${target}`, bytes); relId = this.relId(`${REL_BASE}/image`, target); this.imageRelIds.set(node.part, relId); } const { cx, cy } = this.extentFor(node, bytes); const id = this.nextId++; const alt = node.alt ?? ""; const title = this.figureSource(node); return ``; } /** * The source a generated figure was drawn from, tagged so it can be read * back, or null when there is none. * * It rides on `wp:docPr/@title` — Word's "Title" field for a picture, which * is free text and which `@descr` (real alt text) must not be used for. The * tag prefix is what makes reading it back safe: a picture whose title a * person typed is not a figure this tool generated, and must not be turned * into one. */ figureSource(node) { if (node.source === void 0) return null; const encoded = `${FIGURE_SOURCE_PREFIX}${node.source.tex}`; if (encoded.length > FIGURE_SOURCE_LIMIT) { this.warnings.push( `A figure's source is ${encoded.length} characters, beyond the ${FIGURE_SOURCE_LIMIT} an attribute can safely hold, so the picture was written without it and cannot be edited as LaTeX after a round trip.` ); return null; } return encoded; } /** Both dimensions in EMU, deriving the missing one from the file's own aspect ratio. */ extentFor(node, bytes) { const intrinsic = intrinsicSize(bytes); const aspect = intrinsic === null || intrinsic.width === 0 ? 4 / 3 : intrinsic.width / intrinsic.height; if (node.widthEmu !== void 0 && node.heightEmu !== void 0) { return { cx: node.widthEmu, cy: node.heightEmu }; } if (node.widthEmu !== void 0) return { cx: node.widthEmu, cy: Math.round(node.widthEmu / aspect) }; if (node.heightEmu !== void 0) return { cx: Math.round(node.heightEmu * aspect), cy: node.heightEmu }; if (intrinsic !== null) { const cx2 = Math.min(Math.round(intrinsic.width / 96 * EMU_PER_INCH), DEFAULT_TEXT_WIDTH_EMU); return { cx: cx2, cy: Math.round(cx2 / aspect) }; } this.warnings.push("An image did not state its size and is not a format whose dimensions could be read; it was placed at four inches wide."); const cx = 4 * EMU_PER_INCH; return { cx, cy: Math.round(cx / aspect) }; } // -- blocks -- blocks(blocks) { return blocks.map((b) => this.block(b)).join(""); } block(block) { switch (block.kind) { case "heading": { const level = Math.min(Math.max(block.level, 1), 9); const id = block.numbered === false ? this.nextId++ : 0; const star = block.numbered === false ? `` : ""; return this.paragraph(star + this.inlines(block.children), ``); } case "paragraph": { if (block.children.some((c) => c.kind === "rule")) return this.ruledParagraphs(block); const props = []; if (block.align !== void 0 && block.align !== "left") { props.push(``); } return splitAtDisplayMath(block.children).map((children2, i) => { const marker = i > 0 || block.continues === true ? this.continuationMarker() : ""; return this.displayEquationParagraph(children2, props.join(""), marker) ?? this.paragraph(marker + this.inlines(children2), props.join("")); }).join(""); } case "list": return this.list(block.items, block.ordered, block.start); case "table": return this.table(block); } } /** * A paragraph holding \rule{\textwidth}: the text before each rule is a * paragraph with a line under it (a bottom border, full width, as LaTeX * draws it); a rule on its own is an empty paragraph with that line. */ ruledParagraphs(block) { const jc = block.align !== void 0 && block.align !== "left" ? `` : ""; const border = ``; const out = []; let run3 = []; const trimBreaks2 = (nodes) => { const copy = [...nodes]; while (copy.length > 0 && (copy[copy.length - 1].kind === "break" || copy[copy.length - 1].kind === "text" && copy[copy.length - 1].text.trim() === "")) copy.pop(); while (copy.length > 0 && (copy[0].kind === "break" || copy[0].kind === "text" && copy[0].text.trim() === "")) copy.shift(); return copy; }; for (const child of block.children) { if (child.kind !== "rule") { run3.push(child); continue; } out.push(this.paragraph(this.inlines(trimBreaks2(run3)), border + jc)); run3 = []; } const rest = trimBreaks2(run3); if (rest.length > 0) out.push(this.paragraph(this.inlines(rest), jc)); return out.join(""); } paragraph(content, props = "") { const pPr = props === "" ? "" : `${props}`; return `${pPr}${content}`; } list(items, ordered, start) { if (ordered) this.usedLists.ordered = true; else this.usedLists.bullet = true; let numId = 1; if (ordered) { this.orderedStarts.push(start ?? 1); numId = 2 + this.orderedStarts.length; } return items.map((item) => { const level = Math.min(item.level, 8); const props = ``; const outer = this.tableIndent; this.tableIndent = 720 * (level + 1); const inner = this.blocks(item.blocks ?? []); this.tableIndent = outer; return this.paragraph(this.inlines(item.children), props) + inner; }).join(""); } table(table) { const width = Math.max(1, ...table.rows.map((r) => r.cells.reduce((n, c) => n + c.span, 0))); const columnWidth = Math.floor(9360 / width); const booktabs = table.booktabs === true; const border = (side2) => table.bordered ? `` : booktabs && (side2 === "top" || side2 === "bottom") ? `` : ``; const tblPr = `` + (table.align === "center" ? `` : "") + (this.tableIndent > 0 && table.align !== "center" ? `` : "") + `${["top", "left", "bottom", "right", "insideH", "insideV"].map(border).join("")}`; const grid = `${``.repeat(width)}`; const rows = table.rows.map((row2) => { const trPr = row2.header ? `` : ""; const cells2 = row2.cells.map((cell) => { const span = cell.span > 1 ? `` : ""; const body = cell.blocks.length === 0 ? this.paragraph("") : this.blocks(cell.blocks); const withParagraph = body.includes("") || body.includes("` : ""; return `${span}${below}${withParagraph}`; }).join(""); return `${trPr}${cells2}`; }).join(""); return `${tblPr}${grid}${rows}${this.paragraph("")}`; } // -- parts -- documentPart() { let nextFootnote = 1; for (const id of this.document.footnotes.keys()) this.footnoteIds.set(id, ++nextFootnote); const body = this.blocks(this.document.blocks); const sectPr = ``; return xmlDeclaration( `${body}${sectPr}` ); } footnotesPart() { if (this.document.footnotes.size === 0) return null; const separators = ``; const notes = [...this.document.footnotes].map(([key, blocks]) => { const id = this.footnoteIds.get(key); const content = this.blocks(blocks) || this.paragraph(""); return `${content}`; }).join(""); return xmlDeclaration(`${separators}${notes}`); } relationshipsPart() { const entries = this.relationships.map( (rel) => `` ).join(""); return xmlDeclaration( `${entries}` ); } contentTypesPart(extraOverrides) { const extensions = /* @__PURE__ */ new Set(["rels", "xml"]); for (const name of this.media.keys()) extensions.add(extensionOf(name)); const defaults = [...extensions].map((extension) => { const type = extension === "rels" ? "application/vnd.openxmlformats-package.relationships+xml" : extension === "xml" ? "application/xml" : CONTENT_TYPE_BY_EXTENSION[extension]; return type === void 0 ? "" : ``; }).join(""); const overrides = [ ``, ``, ...extraOverrides ].join(""); return xmlDeclaration( `${defaults}${overrides}` ); } write() { const document2 = this.documentPart(); const footnotes = this.footnotesPart(); this.relId(`${REL_BASE}/styles`, "styles.xml"); const overrides = []; if (this.usedLists.ordered || this.usedLists.bullet) { this.relId(`${REL_BASE}/numbering`, "numbering.xml"); overrides.push( `` ); } if (footnotes !== null) { this.relId(`${REL_BASE}/footnotes`, "footnotes.xml"); overrides.push( `` ); } if (this.sources.size > 0) { this.relId(`${REL_BASE}/customXml`, "../customXml/item1.xml"); overrides.push(``); } const parts = /* @__PURE__ */ new Map(); const put = (name, text) => { parts.set(name, new TextEncoder().encode(text)); }; put(CONTENT_TYPES_PART, this.contentTypesPart(overrides)); put("_rels/.rels", ROOT_RELATIONSHIPS); put("word/document.xml", document2); put("word/_rels/document.xml.rels", this.relationshipsPart()); put("word/styles.xml", STYLES); if (this.usedLists.ordered || this.usedLists.bullet) put("word/numbering.xml", numbering(this.orderedStarts)); if (footnotes !== null) put("word/footnotes.xml", footnotes); if (this.sources.size > 0) { put("customXml/item1.xml", xmlDeclaration(sourceStoreXml(this.sources))); put("customXml/itemProps1.xml", CUSTOM_XML_PROPS); put("customXml/_rels/item1.xml.rels", CUSTOM_XML_RELS); } for (const [name, bytes] of this.media) parts.set(name, bytes); return { package: { parts }, warnings: this.warnings }; } }; function wrapWithSource(omml, source, display) { if (source === void 0 || source.length > 240) return omml; const tag = display ? "latex2word-equation-display" : "latex2word-equation"; return `${omml}`; } var CONTINUATION_PREFIX = "_TeXCont"; var UNNUMBERED_PREFIX = "_TeXStar"; function splitAtDisplayMath(children2) { const blank = (c) => c.kind === "text" && c.text.trim() === ""; const pieces = []; let current = []; const flush = () => { if (current.some((c) => !blank(c))) pieces.push(current); current = []; }; for (let i = 0; i < children2.length; i++) { const node = children2[i]; if (node.kind !== "math" || !node.display) { current.push(node); continue; } let start = current.length; while (start > 0 && (current[start - 1].kind === "label" || blank(current[start - 1]))) start--; const labels = current.splice(start).filter((c) => c.kind === "label"); flush(); const equation = [...labels, node]; while (i + 1 < children2.length && (children2[i + 1].kind === "eqnumber" || children2[i + 1].kind === "label")) equation.push(children2[++i]); pieces.push(equation); } flush(); return pieces.length === 0 ? [[...children2]] : pieces; } function numberedEquation(children2) { const meaningful = children2.filter((c) => c.kind !== "text" || c.text.trim() !== ""); const number2 = meaningful.find((c) => c.kind === "eqnumber"); if (number2 === void 0) return null; const rest = meaningful.filter((c) => c.kind !== "eqnumber" && c.kind !== "label"); if (rest.length !== 1 || rest[0].kind !== "math" || !rest[0].display) return null; const labels = meaningful.flatMap((c) => c.kind === "label" ? [c.id] : []); return { math: rest[0], number: number2, labels }; } var NAMESPACES = [ `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"`, `xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"`, `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"`, `xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"`, `xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"`, `xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"` ].join(" "); function xmlDeclaration(body) { return ` ${body}`; } var CUSTOM_XML_PROPS = xmlDeclaration( `` ); var CUSTOM_XML_RELS = xmlDeclaration( `` ); var ROOT_RELATIONSHIPS = xmlDeclaration( `` ); var STYLES = xmlDeclaration( `` + [1, 2, 3, 4, 5, 6, 7, 8, 9].map( (level) => `` ).join("") + `` ); var BULLET_LEVELS = [ { text: "\uF0B7", font: "Symbol" }, { text: "o", font: "Courier New" }, { text: "\uF0A7", font: "Wingdings" } ]; var ORDERED_FORMATS = ["decimal", "lowerLetter", "lowerRoman"]; var NUMBERING = xmlDeclaration( `` + [ { abstract: 1, bullet: true }, { abstract: 2, bullet: false } ].map( ({ abstract, bullet }) => `` + Array.from({ length: 9 }, (_unused, level) => { const indent = 720 * (level + 1); const marker = BULLET_LEVELS[level % BULLET_LEVELS.length]; return `` + (bullet ? `` : "") + ``; }).join("") + `` ).join("") + `` ); var BLANK_SPACES_PER_CM = 11.3; function numbering(orderedStarts) { const lists = orderedStarts.map( (start, i) => `` ).join(""); return NUMBERING.replace("", `${lists}`); } function documentToDocx(document2, options = {}) { return new Writer(document2, options).write(); } // docx/src/docx-read.ts init_define_L2W_CONFIG(); var W_NS3 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; var M_NS3 = "http://schemas.openxmlformats.org/officeDocument/2006/math"; var R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; var A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"; function isElement(node) { return node && node.nodeType === 1; } function children(el) { const out = []; for (let i = 0; i < el.childNodes.length; i++) { const n = el.childNodes[i]; if (isElement(n)) out.push(n); } return out; } function is(el, ns, name) { return el.namespaceURI === ns && el.localName === name; } function firstChild2(el, ns, name) { return children(el).find((c) => is(c, ns, name)) ?? null; } function firstDescendant(el, ns, name) { for (const child of children(el)) { if (is(child, ns, name)) return child; const deeper = firstDescendant(child, ns, name); if (deeper !== null) return deeper; } return null; } function attr(el, ns, name) { if (el === null) return null; const attrs = el.attributes; if (!attrs) return null; for (let i = 0; i < attrs.length; i++) { const a = attrs[i]; if (a.localName === name && (ns === null || a.namespaceURI === ns || a.namespaceURI === null)) return a.value; } return null; } function val(parent, name) { return attr(firstChild2(parent, W_NS3, name), W_NS3, "val"); } function onOff(parent, name) { if (parent === null) return false; const el = firstChild2(parent, W_NS3, name); if (el === null) return false; const v = attr(el, W_NS3, "val"); return v === null || !(v === "0" || v === "false" || v === "off"); } function textOf(el) { let out = ""; for (let i = 0; i < el.childNodes.length; i++) { const n = el.childNodes[i]; if (n.nodeType === 3 || n.nodeType === 4) out += n.data ?? ""; else if (isElement(n)) out += textOf(n); } return out; } function headingLevels(pkg) { const map = /* @__PURE__ */ new Map(); const xml = partText(pkg, "word/styles.xml"); if (xml === null) return map; let doc; try { doc = parseOoxml(xml); } catch { return map; } const root = doc.documentElement; if (root === null) return map; for (const style of children(root)) { if (!is(style, W_NS3, "style")) continue; const id = attr(style, W_NS3, "styleId"); if (id === null) continue; const name = (val(style, "name") ?? "").toLowerCase(); const match = /^heading\s*([1-9])$/.exec(name); if (match !== null) map.set(id, Number(match[1])); else if (name === "title") map.set(id, 0); } return map; } function numberingStarts(pkg) { const out = /* @__PURE__ */ new Map(); const xml = partText(pkg, "word/numbering.xml"); if (xml === null) return out; let root; try { root = parseOoxml(xml).documentElement; } catch { return out; } if (root === null) return out; const abstractStart = /* @__PURE__ */ new Map(); for (const node of children(root)) { if (!is(node, W_NS3, "abstractNum")) continue; const lvl = children(node).find((l) => is(l, W_NS3, "lvl") && (attr(l, W_NS3, "ilvl") ?? "0") === "0"); const start = Number(lvl === void 0 ? "1" : val(lvl, "start") ?? "1"); const id = attr(node, W_NS3, "abstractNumId"); if (id !== null && Number.isFinite(start)) abstractStart.set(id, start); } for (const node of children(root)) { if (!is(node, W_NS3, "num")) continue; const numId = attr(node, W_NS3, "numId"); if (numId === null) continue; let start = abstractStart.get(attr(firstChild2(node, W_NS3, "abstractNumId"), W_NS3, "val") ?? "") ?? 1; for (const override of children(node)) { if (!is(override, W_NS3, "lvlOverride") || (attr(override, W_NS3, "ilvl") ?? "0") !== "0") continue; const value = val(override, "startOverride"); if (value !== null && Number.isFinite(Number(value))) start = Number(value); } out.set(numId, start); } return out; } function numberingFormats(pkg) { const byNumId = /* @__PURE__ */ new Map(); const xml = partText(pkg, "word/numbering.xml"); if (xml === null) return byNumId; let doc; try { doc = parseOoxml(xml); } catch { return byNumId; } const root = doc.documentElement; if (root === null) return byNumId; const abstract = /* @__PURE__ */ new Map(); const numToAbstract = /* @__PURE__ */ new Map(); for (const node of children(root)) { if (is(node, W_NS3, "abstractNum")) { const id = attr(node, W_NS3, "abstractNumId"); if (id === null) continue; const levels = /* @__PURE__ */ new Map(); for (const lvl of children(node)) { if (!is(lvl, W_NS3, "lvl")) continue; const ilvl = Number(attr(lvl, W_NS3, "ilvl") ?? "0"); levels.set(ilvl, (val(lvl, "numFmt") ?? "decimal") !== "bullet"); } abstract.set(id, levels); } else if (is(node, W_NS3, "num")) { const numId = attr(node, W_NS3, "numId"); const abstractId = attr(firstChild2(node, W_NS3, "abstractNumId"), W_NS3, "val"); if (numId !== null && abstractId !== null) numToAbstract.set(numId, abstractId); } } for (const [numId, abstractId] of numToAbstract) { const levels = abstract.get(abstractId); if (levels !== void 0) byNumId.set(numId, levels); } return byNumId; } function relationships(pkg, partName) { const map = /* @__PURE__ */ new Map(); const slash = partName.lastIndexOf("/"); const relsName = `${partName.slice(0, slash)}/_rels/${partName.slice(slash + 1)}.rels`; const xml = partText(pkg, relsName); if (xml === null) return map; let doc; try { doc = parseOoxml(xml); } catch { return map; } const root = doc.documentElement; if (root === null) return map; for (const rel of children(root)) { const id = attr(rel, null, "Id"); const target = attr(rel, null, "Target"); if (id !== null && target !== null) map.set(id, target); } return map; } function resolveTarget(target, fromPart) { if (/^[a-z]+:/i.test(target)) return target; if (target.startsWith("/")) return target.slice(1); const base = fromPart.slice(0, fromPart.lastIndexOf("/")); const segments2 = `${base}/${target}`.split("/"); const out = []; for (const segment of segments2) { if (segment === "." || segment === "") continue; if (segment === "..") out.pop(); else out.push(segment); } return out.join("/"); } function markersIn(body) { const sources = /* @__PURE__ */ new Map(); const continuing = /* @__PURE__ */ new Set(); let pendingSource = null; let pendingContinuation = false; const walk = (el, paragraph) => { for (const child of children(el)) { if (is(child, W_NS3, "bookmarkStart")) { const name = attr(child, W_NS3, "name") ?? ""; if (name.startsWith(SOURCE_BOOKMARK_PREFIX)) pendingSource = name; else if (name.startsWith(CONTINUATION_PREFIX)) { if (paragraph !== null) continuing.add(paragraph); else pendingContinuation = true; } } else if (is(child, M_NS3, "oMath")) { const name = sourceBookmarkOf(child) ?? pendingSource; if (name !== null) sources.set(child, name); pendingSource = null; } else if (is(child, W_NS3, "p")) { if (pendingContinuation) continuing.add(child); pendingContinuation = false; walk(child, child); pendingSource = null; } else { walk(child, paragraph); } } }; walk(body, null); return { sources, continuing }; } function storedSources(pkg) { const out = /* @__PURE__ */ new Map(); for (const name of partsUnder(pkg, "customXml/")) { if (!/^customXml\/item\d+\.xml$/.test(name)) continue; const xml = partText(pkg, name); if (xml === null || !xml.includes(SOURCE_NAMESPACE)) continue; for (const [bookmark, record] of readSourceStore(xml)) out.set(bookmark, record); } return out; } function sourceBookmarkOf(el) { for (const child of children(el)) { if (is(child, W_NS3, "bookmarkStart")) { const name = attr(child, W_NS3, "name"); if (name !== null && name.startsWith(SOURCE_BOOKMARK_PREFIX)) return name; } const deeper = sourceBookmarkOf(child); if (deeper !== null) return deeper; } return null; } function referencedBookmarks(xml) { const found = /* @__PURE__ */ new Set(); for (const match of xml.matchAll(/REF\s+([A-Za-z0-9_]+)/g)) found.add(match[1]); return found; } function mergeText(inlines) { const out = []; for (const node of inlines) { const previous = out[out.length - 1]; if (node.kind === "text" && previous !== void 0 && previous.kind === "text" && previous.bold === node.bold && previous.italic === node.italic && previous.underline === node.underline && previous.script === node.script) { out[out.length - 1] = { ...previous, text: previous.text + node.text }; } else { out.push(node); } } return out.filter((n) => n.kind !== "text" || n.text !== ""); } function readRun(run3) { const props = firstChild2(run3, W_NS3, "rPr"); const bold = onOff(props, "b"); const italic = onOff(props, "i"); const underline = props !== null && firstChild2(props, W_NS3, "u") !== null && val(props, "u") !== "none"; const vertAlign = attr(props === null ? null : firstChild2(props, W_NS3, "vertAlign"), W_NS3, "val"); const script = vertAlign === "subscript" ? "sub" : vertAlign === "superscript" ? "super" : void 0; const style = (text) => { const node = { kind: "text", text }; if (bold) node.bold = true; if (italic) node.italic = true; if (underline) node.underline = true; if (script !== void 0) node.script = script; return node; }; const out = []; for (const child of children(run3)) { if (is(child, W_NS3, "t")) out.push(...answerBlanks(textOf(child), underline, style)); else if (is(child, W_NS3, "ptab") && attr(child, W_NS3, "alignment") === "right") out.push({ kind: "fill" }); else if (is(child, W_NS3, "tab")) out.push(style(" ")); else if (is(child, W_NS3, "noBreakHyphen")) out.push(style("-")); else if (is(child, W_NS3, "br")) { out.push({ kind: "break", variant: attr(child, W_NS3, "type") === "page" ? "page" : "line" }); } else if (is(child, W_NS3, "footnoteReference")) { const id = attr(child, W_NS3, "id"); if (id !== null) out.push({ kind: "footnoteref", id }); } } return out; } var SPACES_PER_CM = 11.3; var UNDERSCORES_PER_CM = 5.2; var halfCm = (cm) => Math.max(0.5, Math.round(cm * 2) / 2); function answerBlanks(text, underline, style) { if (underline && text.length >= 3 && /^[\s ]+$/.test(text)) return [{ kind: "blank", widthCm: halfCm(text.length / SPACES_PER_CM) }]; if (!/_{4,}/.test(text)) return [style(text)]; const out = []; let last = 0; for (const m of text.matchAll(/_{4,}/g)) { if (m.index > last) out.push(style(text.slice(last, m.index))); out.push({ kind: "blank", widthCm: halfCm(m[0].length / UNDERSCORES_PER_CM) }); last = m.index + m[0].length; } if (last < text.length) out.push(style(text.slice(last))); return out; } function readDrawing(drawing, ctx) { const blip = firstDescendant(drawing, A_NS, "blip"); const embed = attr(blip, R_NS, "embed"); if (embed === null) return null; const target = ctx.rels.get(embed); if (target === void 0) return null; const part = resolveTarget(target, ctx.relsFrom); const bytes = ctx.pkg.parts.get(part); if (bytes === void 0) return null; ctx.images.set(part, bytes); const node = { kind: "image", part }; const extent = firstDescendant(drawing, "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "extent"); const cx = attr(extent, null, "cx"); const cy = attr(extent, null, "cy"); if (cx !== null) node.widthEmu = Number(cx); if (cy !== null) node.heightEmu = Number(cy); const docPr = firstDescendant(drawing, "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "docPr"); const alt = attr(docPr, null, "descr"); if (alt !== null && alt !== "") node.alt = alt; const title = attr(docPr, null, "title"); if (title !== null && title.startsWith(FIGURE_SOURCE_PREFIX)) { node.source = { language: "tikz", tex: title.slice(FIGURE_SOURCE_PREFIX.length) }; } return node; } function storedSource(sdt) { const props = firstChild2(sdt, W_NS3, "sdtPr"); if (props === null) return null; const tag = attr(firstChild2(props, W_NS3, "tag"), W_NS3, "val"); if (!isOwnTag(tag)) return null; const title = attr(firstChild2(props, W_NS3, "alias"), W_NS3, "val") ?? ""; if (!title.startsWith(CC_TITLE_PREFIX) || title === CC_TITLE_TOO_LONG) return null; return { latex: title.slice(CC_TITLE_PREFIX.length), display: isDisplayTag(tag) }; } function readMath(oMath, ctx, outer) { ctx.equationIndex += 1; const index = ctx.equationIndex; const inner = children(oMath).find((c) => is(c, W_NS3, "sdt")); const bookmark = ctx.markers.sources.get(oMath) ?? null; const source = (inner === void 0 ? null : storedSource(inner)) ?? (bookmark === null ? void 0 : ctx.sources.get(bookmark)) ?? outer; try { const ir = oMathElementToIr(oMath); const display = isDisplayEquation(oMath) || source?.display === true; const node = { kind: "math", ir, display }; if (source !== null) node.source = source.latex; const kept = (names) => names.filter((name) => !name.startsWith("_") || ctx.referencedBookmarks.has(name)); const rows = equationRowNumbersOf(oMath); if (rows !== null && rows.length > 1) { const numbers = rows.map((row2) => row2 === null ? null : row2.seq ? { labels: kept(row2.bookmarks) } : { tag: row2.text, labels: kept(row2.bookmarks) }); return [node, { kind: "eqnumber", rows: numbers }]; } const number2 = equationNumberOf(oMath); if (number2 === null) return [node]; const labels = kept(number2.bookmarks).map((id) => ({ kind: "label", id })); return [...labels, node, number2.seq ? { kind: "eqnumber" } : { kind: "eqnumber", tag: number2.text }]; } catch (e) { if (!(e instanceof OmmlConversionError) || ctx.onUnsupported === "throw") throw e; ctx.skipped.push({ index, reason: e.message }); return []; } } function joinEquationRefs(out) { for (let i = 1; i + 1 < out.length; i++) { const before = out[i - 1]; const ref = out[i]; const after = out[i + 1]; if (ref.kind !== "ref" || ref.wrap !== "none" || before.kind !== "text" || after.kind !== "text") continue; if (!before.text.endsWith("(") || !after.text.startsWith(")")) continue; out[i - 1] = { ...before, text: before.text.slice(0, -1) }; out[i] = { ...ref, wrap: "parentheses" }; out[i + 1] = { ...after, text: after.text.slice(1) }; } return out.filter((n) => n.kind !== "text" || n.text !== ""); } function readField(siblings, start) { const fldChar = (el) => { for (const run3 of children(el)) { if (is(run3, W_NS3, "fldChar")) return attr(run3, W_NS3, "fldCharType"); } return null; }; if (!is(siblings[start], W_NS3, "r") || fldChar(siblings[start]) !== "begin") return null; let instruction = ""; for (let i = start + 1; i < siblings.length; i++) { const sibling = siblings[i]; if (!is(sibling, W_NS3, "r")) continue; const type = fldChar(sibling); if (type === "end") return { instruction: instruction.trim(), end: i }; if (type === "separate") continue; for (const run3 of children(sibling)) { if (is(run3, W_NS3, "instrText")) instruction += textOf(run3); } } return null; } function readInlines(parent, ctx, source = null) { const out = []; const siblings = children(parent); for (let index = 0; index < siblings.length; index++) { const child = siblings[index]; if (is(child, W_NS3, "bookmarkStart")) { const name = attr(child, W_NS3, "name"); if (name !== null && ctx.referencedBookmarks.has(name)) out.push({ kind: "label", id: name }); continue; } const field = readField(siblings, index); if (field !== null) { const ref = /^REF\s+(\S+)/i.exec(field.instruction); if (ref !== null) out.push({ kind: "ref", id: ref[1], wrap: "none" }); index = field.end; continue; } if (is(child, W_NS3, "r")) { out.push(...readRun(child)); for (const inRun of children(child)) { if (is(inRun, W_NS3, "drawing")) { const image = readDrawing(inRun, ctx); if (image !== null) out.push(image); } } } else if (is(child, W_NS3, "hyperlink")) { const id = attr(child, R_NS, "id"); const target = id === null ? null : ctx.rels.get(id); const inner = readInlines(child, ctx, source); if (target === void 0 || target === null) out.push(...inner); else out.push({ kind: "link", href: resolveTarget(target, ctx.relsFrom), children: inner }); } else if (is(child, M_NS3, "oMath")) { out.push(...readMath(child, ctx, source)); } else if (is(child, M_NS3, "oMathPara")) { for (const inner of children(child)) { if (!is(inner, M_NS3, "oMath")) continue; out.push(...readMath(inner, ctx, source)); } } else if (is(child, W_NS3, "sdt")) { const content = firstChild2(child, W_NS3, "sdtContent"); if (content !== null) out.push(...readInlines(content, ctx, storedSource(child) ?? source)); } else if (is(child, W_NS3, "ins") || is(child, W_NS3, "smartTag")) { out.push(...readInlines(child, ctx, source)); } } return joinEquationRefs(out); } function readParagraph(p, ctx) { const props = firstChild2(p, W_NS3, "pPr"); const inlines = mergeText(readInlines(p, ctx)); const styleId = props === null ? null : val(props, "pStyle"); const level = styleId === null ? void 0 : ctx.headings.get(styleId); if (level !== void 0 && level >= 1) { const unnumbered = children(p).some((c) => is(c, W_NS3, "bookmarkStart") && (attr(c, W_NS3, "name") ?? "").startsWith(UNNUMBERED_PREFIX)); return { block: unnumbered ? { kind: "heading", level, children: inlines, numbered: false } : { kind: "heading", level, children: inlines } }; } const numPr = props === null ? null : firstChild2(props, W_NS3, "numPr"); if (numPr !== null) { const numId = attr(firstChild2(numPr, W_NS3, "numId"), W_NS3, "val"); const ilvl = Number(attr(firstChild2(numPr, W_NS3, "ilvl"), W_NS3, "val") ?? "0"); if (numId !== null && numId !== "0") { const ordered = ctx.numbering.get(numId)?.get(ilvl) ?? true; return { block: { kind: "paragraph", children: inlines }, listKey: numId, listLevel: ilvl, listOrdered: ordered }; } } const align = props === null ? null : val(props, "jc"); const borders = props === null ? null : firstChild2(props, W_NS3, "pBdr"); const bottom = borders === null ? null : firstChild2(borders, W_NS3, "bottom"); const ruled = bottom !== null && !["none", "nil"].includes(attr(bottom, W_NS3, "val") ?? "none"); const hasContent = inlines.some((n) => n.kind !== "text" || n.text.trim() !== ""); const block = { kind: "paragraph", children: ruled ? hasContent ? [...inlines, { kind: "break", variant: "line" }, { kind: "rule" }] : [{ kind: "rule" }] : inlines }; if (align === "center" || align === "right" || align === "left") block.align = align; if (ctx.markers.continuing.has(p)) block.continues = true; return { block }; } function readTable(tbl, ctx) { const tblPr = firstChild2(tbl, W_NS3, "tblPr"); const borders = tblPr === null ? null : firstChild2(tblPr, W_NS3, "tblBorders"); const drawn = (b) => b !== null && !["none", "nil"].includes(attr(b, W_NS3, "val") ?? "none"); const side2 = (name) => drawn(borders === null ? null : firstChild2(borders, W_NS3, name)); const booktabs = side2("top") && side2("bottom") && !side2("insideH") && !side2("insideV") && !side2("left") && !side2("right"); const bordered = !booktabs && borders !== null && children(borders).some((b) => attr(b, W_NS3, "val") !== "none" && attr(b, W_NS3, "val") !== "nil"); const centred = tblPr !== null && val(tblPr, "jc") === "center"; const rows = []; for (const tr of children(tbl)) { if (!is(tr, W_NS3, "tr")) continue; const cells2 = []; for (const tc of children(tr)) { if (!is(tc, W_NS3, "tc")) continue; const tcPr = firstChild2(tc, W_NS3, "tcPr"); const span = Number(attr(tcPr === null ? null : firstChild2(tcPr, W_NS3, "gridSpan"), W_NS3, "val") ?? "1"); cells2.push({ blocks: readBlocks(tc, ctx), span: Number.isFinite(span) && span > 0 ? span : 1 }); } const trPr = firstChild2(tr, W_NS3, "trPr"); const lined = children(tr).filter((tc) => is(tc, W_NS3, "tc")).every((tc) => { const tcBorders = firstDescendant(firstChild2(tc, W_NS3, "tcPr") ?? tc, W_NS3, "tcBorders"); return drawn(tcBorders === null ? null : firstChild2(tcBorders, W_NS3, "bottom")); }); rows.push(booktabs && lined && cells2.length > 0 ? { cells: cells2, header: onOff(trPr, "tblHeader"), ruleBelow: true } : { cells: cells2, header: onOff(trPr, "tblHeader") }); } const table = { kind: "table", rows, bordered }; if (booktabs) table.booktabs = true; if (centred) table.align = "center"; return table; } function gatherLists(items, ctx) { const out = []; let pending = null; const flush = () => { if (pending === null) return; const shown = ctx.listCounts.get(pending.key) ?? 0; const start = (ctx.numberingStarts.get(pending.key) ?? 1) + shown; ctx.listCounts.set(pending.key, shown + pending.items.filter((item) => item.level === 0).length); out.push(pending.ordered && start !== 1 ? { kind: "list", ordered: true, items: pending.items, start } : { kind: "list", ordered: pending.ordered, items: pending.items }); pending = null; }; for (let index = 0; index < items.length; index++) { const info = items[index]; const next = items[index + 1]; if (pending !== null && info.listKey === void 0 && info.block.kind === "paragraph" && info.block.children.length === 0 && items[index - 1]?.block.kind === "table" && next?.listKey === pending.key) { continue; } if (info.listKey === void 0) { if (info.block.kind === "table" && pending !== null && pending.items.length > 0) { const last = pending.items.length - 1; const item = pending.items[last]; pending.items[last] = { ...item, blocks: [...item.blocks ?? [], info.block] }; continue; } flush(); out.push(info.block); continue; } const paragraph = info.block; if (pending !== null && pending.key !== info.listKey) flush(); if (pending === null) { pending = { key: info.listKey, ordered: info.listOrdered === true, items: [] }; } pending.items.push({ level: info.listLevel ?? 0, children: paragraph.children }); } flush(); return out; } function readBlocks(parent, ctx) { const paragraphs = []; for (const child of children(parent)) { if (is(child, W_NS3, "p")) { paragraphs.push(readParagraph(child, ctx)); } else if (is(child, W_NS3, "tbl")) { paragraphs.push({ block: readTable(child, ctx) }); } else if (is(child, W_NS3, "sdt")) { const content = firstChild2(child, W_NS3, "sdtContent"); if (content !== null) { for (const block of readBlocks(content, ctx)) paragraphs.push({ block }); } } } return gatherLists(paragraphs, ctx); } function readFootnotes(pkg, ctx) { const out = /* @__PURE__ */ new Map(); const xml = partText(pkg, "word/footnotes.xml"); if (xml === null) return out; let doc; try { doc = parseOoxml(xml); } catch { return out; } const root = doc.documentElement; if (root === null) return out; for (const note of children(root)) { if (!is(note, W_NS3, "footnote")) continue; const id = attr(note, W_NS3, "id"); if (id === null || Number(id) <= 0) continue; out.set(id, readBlocks(note, ctx)); } return out; } function docxToDocument(pkg, options = {}) { const documentPart = "word/document.xml"; const xml = requirePartText(pkg, documentPart); const doc = parseOoxml(xml); const root = doc.documentElement; if (root === null) throw new OmmlConversionError("word/document.xml is empty."); const body = firstChild2(root, W_NS3, "body"); if (body === null) throw new OmmlConversionError("word/document.xml has no , so there is nothing to convert."); const ctx = { pkg, headings: headingLevels(pkg), numbering: numberingFormats(pkg), numberingStarts: numberingStarts(pkg), listCounts: /* @__PURE__ */ new Map(), rels: relationships(pkg, documentPart), relsFrom: documentPart, images: /* @__PURE__ */ new Map(), skipped: [], onUnsupported: options.onUnsupportedEquation ?? "skip", referencedBookmarks: referencedBookmarks(xml), sources: storedSources(pkg), markers: markersIn(body), equationIndex: 0 }; const blocks = readBlocks(body, ctx); const footnotes = readFootnotes(pkg, ctx); return { document: { blocks, footnotes, images: ctx.images }, skipped: ctx.skipped }; } // texdoc/src/equation-text.ts init_define_L2W_CONFIG(); // renderers/src/convert.ts init_define_L2W_CONFIG(); // docir/src/detect-latex.ts init_define_L2W_CONFIG(); // word/src/scan.ts init_define_L2W_CONFIG(); var ENV_NAMES = ["equation*", "equation", "align*", "align", "gather*", "gather"]; function matchEnvOpener(text, i) { if (!text.startsWith("\\begin{", i)) return null; for (const name of ENV_NAMES) { const opener = `\\begin{${name}}`; if (text.startsWith(opener, i)) return { opener, name }; } return null; } function indexOfUnescaped(text, ch, from) { let idx = text.indexOf(ch, from); while (idx !== -1 && text[idx - 1] === "\\") { idx = text.indexOf(ch, idx + 1); } return idx; } function findSingleDollarClose(text, openIndex, mode) { const closeAt = indexOfUnescaped(text, "$", openIndex + 1); if (closeAt === -1) return -1; const inner = text.slice(openIndex + 1, closeAt); if (inner.length === 0) return -1; if (mode === "always") return closeAt; const firstChar = inner[0]; const lastChar = inner[inner.length - 1]; if (/\s/.test(firstChar)) return -1; if (/\s/.test(lastChar)) return -1; if (/\d/.test(firstChar) && !/^\d+(?:\.\d+)?$/.test(inner) && !/\d[A-Za-z\\]|[=^_\\{}]/.test(inner)) return -1; return closeAt; } function findLatexSpans(text, options = {}) { const singleDollarMode = options.singleDollarMode ?? "smart"; const spans = []; const n = text.length; let i = 0; while (i < n) { if (text[i] === "\\" && text[i + 1] === "$") { i += 2; continue; } const envMatch = matchEnvOpener(text, i); if (envMatch) { const closer = `\\end{${envMatch.name}}`; const closeAt = text.indexOf(closer, i + envMatch.opener.length); if (closeAt !== -1) { const end = closeAt + closer.length; const matchedText = text.slice(i, end); spans.push({ start: i, end, matchedText, latex: matchedText, display: true, delimiter: envMatch.name }); i = end; continue; } i += envMatch.opener.length; continue; } if (text.startsWith("$$", i)) { const closeAt = text.indexOf("$$", i + 2); if (closeAt !== -1) { const inner = text.slice(i + 2, closeAt); if (inner.trim().length > 0) { const end = closeAt + 2; spans.push({ start: i, end, matchedText: text.slice(i, end), latex: inner.trim(), display: true, delimiter: "$$" }); i = end; continue; } } i += 2; continue; } if (text.startsWith("\\[", i)) { const closeAt = text.indexOf("\\]", i + 2); if (closeAt !== -1) { const inner = text.slice(i + 2, closeAt); if (inner.trim().length > 0) { const end = closeAt + 2; spans.push({ start: i, end, matchedText: text.slice(i, end), latex: inner.trim(), display: true, delimiter: "\\[" }); i = end; continue; } } i += 2; continue; } if (text.startsWith("\\(", i)) { const closeAt = text.indexOf("\\)", i + 2); if (closeAt !== -1) { const inner = text.slice(i + 2, closeAt); if (inner.trim().length > 0) { const end = closeAt + 2; spans.push({ start: i, end, matchedText: text.slice(i, end), latex: inner.trim(), display: false, delimiter: "\\(" }); i = end; continue; } } i += 2; continue; } if (text[i] === "$" && singleDollarMode !== "never") { const closeAt = findSingleDollarClose(text, i, singleDollarMode); if (closeAt !== -1) { const end = closeAt + 1; const inner = text.slice(i + 1, closeAt); spans.push({ start: i, end, matchedText: text.slice(i, end), latex: inner.trim(), display: false, delimiter: "$" }); i = end; continue; } i += 1; continue; } i += 1; } return spans; } // docir/src/detect-latex.ts var Detector = class { constructor(singleDollarMode) { this.singleDollarMode = singleDollarMode; this.converted = 0; this.skippedAsCurrency = 0; this.rejected = []; } /** * How many more expressions this text would yield with the currency guard * off. Only computed in "smart" mode, where there is a guard to be off. */ countCurrencySkips(text, found) { if (this.singleDollarMode !== "smart") return 0; const starts = new Set(found.map((s) => s.start)); let extra = 0; for (const span of findLatexSpans(text, { singleDollarMode: "always" })) { if (starts.has(span.start)) continue; try { lower(parseLatex(span.latex)); extra++; } catch { } } return extra; } /** * Splits one text node into text and maths. * * Scanning per node rather than across the whole paragraph is deliberate: * docx-read.ts has already merged every adjacent run that shares * formatting, so a node boundary is a real change of formatting. An * expression that genuinely straddles one — half of it bold — is left * alone, which is the honest outcome: the document is saying those are two * differently-formatted things, and this pass does not overrule it. */ splitText(node) { const spans = findLatexSpans(node.text, { singleDollarMode: this.singleDollarMode }); this.skippedAsCurrency += this.countCurrencySkips(node.text, spans); if (spans.length === 0) return [node]; const out = []; let cursor = 0; for (const span of spans) { let ir; try { ir = lower(parseLatex(span.latex)); } catch (e) { this.rejected.push({ latex: span.latex, reason: e instanceof Error ? e.message : String(e) }); continue; } if (span.start > cursor) out.push({ ...node, text: node.text.slice(cursor, span.start) }); out.push({ kind: "math", ir, display: span.display, source: span.latex }); cursor = span.end; this.converted++; } if (cursor === 0) return [node]; if (cursor < node.text.length) out.push({ ...node, text: node.text.slice(cursor) }); return out; } inlines(nodes) { const out = []; for (const node of nodes) { if (node.kind === "text") out.push(...this.splitText(node)); else if (node.kind === "link") out.push({ ...node, children: this.inlines(node.children) }); else out.push(node); } return out; } blocks(blocks) { return blocks.map((block) => { switch (block.kind) { case "paragraph": case "heading": return { ...block, children: this.inlines(block.children) }; case "list": return { ...block, items: block.items.map((item) => ({ ...item, children: this.inlines(item.children), ...item.blocks === void 0 ? {} : { blocks: this.blocks(item.blocks) } })) }; case "table": return { ...block, rows: block.rows.map((row2) => ({ ...row2, cells: row2.cells.map((cell) => ({ ...cell, blocks: this.blocks(cell.blocks) })) })) }; } }); } }; function detectLatexInText(document2, options = {}) { if (options.enabled === false) return { document: document2, converted: 0, rejected: [], skippedAsCurrency: 0 }; const detector = new Detector(options.singleDollarMode ?? "smart"); const blocks = detector.blocks(document2.blocks); const footnotes = /* @__PURE__ */ new Map(); for (const [id, note] of document2.footnotes) footnotes.set(id, detector.blocks(note)); return { document: { blocks, footnotes, images: document2.images }, converted: detector.converted, rejected: detector.rejected, skippedAsCurrency: detector.skippedAsCurrency }; } // desktop/src/convert-core.ts async function docxToTex(bytes, codec, options = {}) { const pkg = await readPackage(bytes, codec); const { document: raw, skipped } = docxToDocument(pkg); const detected = detectLatexInText(raw, options.detectLatex); const document2 = detected.document; const emitted = emitTexDocument(document2, options); return { tex: emitted.tex, images: new Map(emitted.images), equationsConverted: [...walkInlines(document2.blocks)].filter((n) => n.kind === "math").length, equationsFromText: detected.converted, equationsSkipped: skipped, rejectedText: detected.rejected, skippedAsCurrency: detected.skippedAsCurrency, warnings: emitted.warnings, blocks: document2.blocks.length }; } var IMAGE_EXTENSIONS = ["", ".png", ".jpg", ".jpeg", ".pdf", ".eps", ".gif", ".svg"]; function attachImages(document2, resolve5, warnings) { if (resolve5 === void 0) return; for (const node of walkInlines(document2.blocks)) { if (node.kind !== "image" || document2.images.has(node.part)) continue; let found = null; for (const extension of IMAGE_EXTENSIONS) { found = resolve5(node.part + extension); if (found !== null) break; } if (found === null) warnings.push(`The image "${node.part}" could not be found, so it was left out.`); else document2.images.set(node.part, found); } } function bibliographyBlocks(entries, style, title) { if (entries.length === 0) return []; const blocks = [{ kind: "heading", level: 1, children: [{ kind: "text", text: title }] }]; entries.forEach((entry, index) => { blocks.push({ kind: "paragraph", children: [{ kind: "text", text: `[${index + 1}] ${formatEntry(entry, style)}` }] }); }); return blocks; } function bibliographyNames(source) { return [...source.matchAll(/\\(?:bibliography|addbibresource)\{([^}]*)\}/g)].flatMap((m) => m[1].split(",")).map((name) => name.trim()).filter((name) => name !== ""); } async function texToDocx(source, codec, options = {}) { const parsed = parseTexDocument(source, options); const warnings = [...parsed.warnings]; attachImages(parsed.document, options.resolveImage, warnings); const database = (options.bibSources ?? []).flatMap((text) => parseBibtex(text)); const bibliography = buildBibliography(database, parsed.citations, options.bibStyle ?? "plain"); for (const key of bibliography.missing) { warnings.push(`The citation "${key}" has no entry in the bibliography, so its key was printed instead of a number.`); } const latexText = options.mathAsLatex === true; const document2 = { ...parsed.document, footnotes: latexText ? new Map([...parsed.document.footnotes].map(([id, blocks]) => [id, mathAsLatexText(blocks)])) : parsed.document.footnotes, blocks: [ ...latexText ? mathAsLatexText(parsed.document.blocks) : parsed.document.blocks, ...bibliographyBlocks(bibliography.entries, options.bibStyle ?? "plain", options.bibliographyTitle ?? "References") ] }; const written = documentToDocx(document2, { ...options, citationLabels: bibliography.labels }); warnings.push(...written.warnings); return { bytes: await writePackage(written.package, codec), blocks: document2.blocks.length, equations: [...walkInlines(document2.blocks)].filter((n) => n.kind === "math").length, images: document2.images.size, citations: parsed.citations.length, missingCitations: bibliography.missing, warnings }; } function mathAsLatexText(blocks) { const inlines = (children2) => children2.flatMap((child) => { if (child.kind === "math") { const latex = (child.source ?? irToLatex(child.ir)).trim(); return [{ kind: "text", text: child.display ? `$$${latex}$$` : `$${latex}$` }]; } if (child.kind === "eqnumber") return []; if (child.kind === "link") return [{ ...child, children: inlines(child.children) }]; return [child]; }); return blocks.map((block) => { switch (block.kind) { case "paragraph": case "heading": return { ...block, children: inlines(block.children) }; case "list": return { ...block, items: block.items.map((item) => ({ ...item, children: inlines(item.children), ...item.blocks ? { blocks: mathAsLatexText(item.blocks) } : {} })) }; case "table": return { ...block, rows: block.rows.map((row2) => ({ ...row2, cells: row2.cells.map((cell) => ({ ...cell, blocks: mathAsLatexText(cell.blocks) })) })) }; } }); } // desktop/src/convert-tex.ts function convertTex(source, options = {}) { return texToDocx(source, nodeZipCodec, options); } // desktop/src/app.ts init_define_L2W_CONFIG(); import { spawn as spawn4, spawnSync as spawnSync3 } from "node:child_process"; import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs"; import { homedir as homedir2 } from "node:os"; import { basename, dirname as dirname4, join as join5, resolve as resolve3 } from "node:path"; // src/shared/config.ts init_define_L2W_CONFIG(); var FALLBACK = Object.freeze({ environment: "development", baseUrl: "https://localhost:3000", licenseServerUrl: null, licensePublicKeys: {}, isProduction: false, debug: true }); var CONFIG = typeof define_L2W_CONFIG_default === "object" && define_L2W_CONFIG_default !== null ? Object.freeze(define_L2W_CONFIG_default) : FALLBACK; // desktop/src/service.ts init_define_L2W_CONFIG(); import { createServer } from "node:http"; import { createReadStream } from "node:fs"; import { pipeline } from "node:stream/promises"; import { randomBytes, timingSafeEqual } from "node:crypto"; import { mkdir as mkdir2, writeFile as writeFile2, access } from "node:fs/promises"; import { dirname as dirname2, join as join2, resolve, sep } from "node:path"; // desktop/src/batch.ts init_define_L2W_CONFIG(); import { posix } from "node:path"; function normalizeDropPath(path) { const parts = path.replace(/\\/g, "/").split("/").filter((p) => p !== "" && p !== "."); if (parts.length === 0 || parts.includes("..")) return null; return parts.join("/"); } var decoder = new TextDecoder("utf-8"); var decode = (bytes) => decoder.decode(bytes); var stem = (path) => posix.basename(path).replace(/\.[^.]*$/, ""); var plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`; var DOCX = /\.docx$/i; var TEX = /\.(tex|latex)$/i; var BIB = /\.bib$/i; var isLockFile = (path) => posix.basename(path).startsWith("~$"); async function convertBatch(dropped, options = {}) { const files = /* @__PURE__ */ new Map(); for (const file of dropped) { const path = normalizeDropPath(file.path); if (path !== null && !isLockFile(path)) files.set(path, file.bytes); } const byLowerPath = new Map([...files.keys()].map((path) => [path.toLowerCase(), path])); const lookup = (dir, target) => { const joined = posix.normalize(posix.join(dir, target.replace(/\\/g, "/"))); if (joined.startsWith("../") || joined === "..") return null; return byLowerPath.get(joined.toLowerCase()) ?? null; }; const paths = [...files.keys()]; const docxPaths = paths.filter((p) => DOCX.test(p)); const texPaths = paths.filter((p) => TEX.test(p)); const outcomes = []; if (docxPaths.length === 0 && texPaths.length === 0) { return [{ input: "Dropped files", error: "Nothing to convert here: drop .docx or .tex files, or a folder that contains them." }]; } for (const path of docxPaths) { try { const result = await docxToTex(files.get(path), nodeZipCodec, { detectLatex: { singleDollarMode: options.singleDollarMode } }); const base = stem(path); const texName = `${base}.tex`; const out = /* @__PURE__ */ new Map(); let primary = texName; if (result.images.size === 0) { out.set(texName, new TextEncoder().encode(result.tex)); } else { primary = `${base}/${texName}`; out.set(primary, new TextEncoder().encode(result.tex)); for (const [image, bytes] of result.images) out.set(`${base}/${image}`, bytes); } const notes = [ ...result.equationsSkipped.map((s) => `Equation ${s.index} was left out: ${s.reason}`), ...result.rejectedText.map((r) => `Left as text: ${r.latex} \u2014 ${r.reason}`), ...result.skippedAsCurrency > 0 ? [`${plural(result.skippedAsCurrency, "expression")} starting with a digit were read as currency and left as text.`] : [], ...result.warnings ]; outcomes.push({ input: path, kind: "docx-to-tex", files: out, primary, summary: `${plural(result.blocks, "block")}, ${plural(result.equationsConverted, "equation")}` + (result.images.size > 0 ? `, ${plural(result.images.size, "image")}` : ""), notes }); } catch (e) { outcomes.push({ input: path, error: e instanceof Error ? e.message : String(e) }); } } const sources = new Map(texPaths.map((p) => [p, decode(files.get(p))])); let mains = texPaths.filter((p) => /\\documentclass\b/.test(sources.get(p))); if (mains.length === 0 && texPaths.length === 1) mains = texPaths; if (mains.length === 0 && texPaths.length > 1) { outcomes.push({ input: texPaths.join(", "), error: "None of these .tex files has \\documentclass, so there is no telling which is the document and which are its chapters." }); } const allBibs = paths.filter((p) => BIB.test(p)); for (const path of mains) { try { const source = sources.get(path); const dir = posix.dirname(path); const named = bibliographyNames(source).map((n) => lookup(dir, BIB.test(n) ? n : `${n}.bib`)).filter((p) => p !== null); const bibPaths = named.length > 0 ? named : allBibs; const report = await texToDocx(source, nodeZipCodec, { bibStyle: options.bibStyle, bibSources: bibPaths.map((p) => decode(files.get(p))), resolveInput: (target) => { const found = lookup(dir, target) ?? lookup(dir, `${target}.tex`); return found === null || found === path ? null : decode(files.get(found)); }, resolveImage: (target) => { const found = lookup(dir, target); return found === null ? null : files.get(found); } }); const docxName = `${stem(path)}.docx`; outcomes.push({ input: path, kind: "tex-to-docx", files: /* @__PURE__ */ new Map([[docxName, report.bytes]]), primary: docxName, summary: `${plural(report.blocks, "block")}, ${plural(report.equations, "equation")}` + (report.images > 0 ? `, ${plural(report.images, "image")}` : "") + (report.citations > 0 ? `, ${plural(report.citations, "work")} cited` : ""), notes: report.warnings }); } catch (e) { outcomes.push({ input: path, error: e instanceof Error ? e.message : String(e) }); } } return outcomes; } // desktop/src/account.ts init_define_L2W_CONFIG(); // src/shared/app-version.ts init_define_L2W_CONFIG(); var APP_VERSION = true ? "0.6.0-alpha" : "0.0.0-dev"; var APP_BUILD = true ? 341 : 0; var APP_DISTRIBUTION = typeof __APP_DISTRIBUTION__ === "string" && __APP_DISTRIBUTION__ === "store" ? "store" : "direct"; function versionLabel(version2 = APP_VERSION, build = APP_BUILD) { return build > 0 ? `${version2} (build ${build})` : version2; } // desktop/src/account.ts import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; // src/shared/license-client.ts init_define_L2W_CONFIG(); // src/shared/license-token.ts init_define_L2W_CONFIG(); var LICENSE_PREFIX = "L2W1"; var encoder = new TextEncoder(); function fromBase64url(input) { const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((input.length + 3) % 4)); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); return bytes; } function isClaims(value) { const c = value; return typeof c === "object" && c !== null && c.v === 1 && typeof c.kid === "string" && typeof c.sub === "string" && typeof c.dev === "string" && typeof c.lic === "string" && (c.plan === null || typeof c.plan === "string") && Array.isArray(c.ent) && c.ent.every((e) => typeof e === "string") && Array.isArray(c.base) && c.base.every((e) => typeof e === "string") && typeof c.iat === "number" && typeof c.exp === "number"; } function peekLicenseClaims(token) { const parts = token.split("."); if (parts.length !== 3 || parts[0] !== LICENSE_PREFIX) return void 0; try { const claims = JSON.parse(new TextDecoder().decode(fromBase64url(parts[1]))); return isClaims(claims) ? claims : void 0; } catch { return void 0; } } async function verifyLicense(token, keys, now) { if (typeof token !== "string" || token.length > 8192) return { ok: false, reason: "malformed" }; const parts = token.split("."); const claims = peekLicenseClaims(token); if (!claims) return { ok: false, reason: "malformed" }; const publicKey = Object.prototype.hasOwnProperty.call(keys, claims.kid) ? keys[claims.kid] : void 0; if (!publicKey) return { ok: false, reason: "unknown_key" }; let valid; try { const key = await crypto.subtle.importKey("raw", fromBase64url(publicKey), { name: "Ed25519" }, false, ["verify"]); valid = await crypto.subtle.verify({ name: "Ed25519" }, key, fromBase64url(parts[2]), encoder.encode(`${parts[0]}.${parts[1]}`)); } catch (e) { if (e instanceof Error && e.name === "NotSupportedError") return { ok: false, reason: "unsupported" }; return { ok: false, reason: "bad_signature" }; } if (!valid) return { ok: false, reason: "bad_signature" }; if (now >= claims.exp) return { ok: false, reason: "expired", claims }; return { ok: true, claims }; } // src/shared/sync-client.ts init_define_L2W_CONFIG(); var SyncHttpError = class extends Error { constructor(status, code, message) { super(message); this.status = status; this.code = code; this.name = "SyncHttpError"; } }; var STREAM_RETRY_MS = 5 * 6e4; // src/shared/license-client.ts var BASE_GRACE_MS = 30 * 24 * 60 * 60 * 1e3; var ACCOUNT_KEY = "latex2word.account.v1"; var DEVICE_ID_KEY = "latex2word.clientDeviceId.v1"; var LicenseServerError = class extends Error { constructor(status, code, message) { super(message); this.status = status; this.code = code; this.name = "LicenseServerError"; } }; var LicenseNetworkError = class extends Error { constructor(message = "Couldn't reach the TeXConverter server. Check your connection and try again.") { super(message); this.name = "LicenseNetworkError"; } }; var SIGNED_OUT = { state: "signed_out", granted: /* @__PURE__ */ new Set() }; function randomClientId() { const bytes = crypto.getRandomValues(new Uint8Array(16)); return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } function isStoredAccount(value) { const a = value; return typeof a === "object" && a !== null && a.v === 1 && typeof a.server === "string" && typeof a.session === "string" && typeof a.email === "string" && typeof a.license === "string" && typeof a.refreshAfter === "number"; } var LicenseClient = class _LicenseClient { constructor(options) { this.options = options; /** * Licences received from the server in this run. Trusted without a * signature check only where this runtime can't do Ed25519 at all — * they came straight from the server over HTTPS. */ this.fresh = /* @__PURE__ */ new Set(); this.serverUrl = options.serverUrl.replace(/\/+$/, ""); this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init)); this.now = options.now ?? Date.now; this.timeoutMs = options.timeoutMs ?? 15e3; } // ---- storage ------------------------------------------------------------- async account() { try { const raw = await this.options.store.get(ACCOUNT_KEY); if (!raw) return void 0; const parsed = JSON.parse(raw); return isStoredAccount(parsed) && parsed.server === this.serverUrl ? parsed : void 0; } catch { return void 0; } } async save(account) { await this.options.store.set(ACCOUNT_KEY, JSON.stringify(account)); } async forget() { try { await this.options.store.remove(ACCOUNT_KEY); } catch { } } /** * A random id this installation made up, so linking it again replaces its * old entry in the device list instead of taking another slot. Kept across * sign-outs; nothing about the machine goes into it. */ async clientDeviceId() { try { const existing = await this.options.store.get(DEVICE_ID_KEY); if (existing && /^[A-Za-z0-9_-]{8,100}$/.test(existing)) return existing; const created = randomClientId(); await this.options.store.set(DEVICE_ID_KEY, created); return created; } catch { return randomClientId(); } } // ---- HTTP ---------------------------------------------------------------- async request(method, path, body, session, timeoutMs = this.timeoutMs) { const headers = {}; if (body !== void 0) headers["content-type"] = "application/json"; if (session) headers.authorization = `Bearer ${session}`; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); let response; try { response = await this.fetchImpl(`${this.serverUrl}${path}`, { method, headers, body: body === void 0 ? void 0 : JSON.stringify(body), signal: controller.signal }); } catch { throw new LicenseNetworkError(); } finally { clearTimeout(timer); } let parsed; try { parsed = await response.json(); } catch { throw new LicenseNetworkError(`The TeXConverter server answered unexpectedly (HTTP ${response.status}).`); } return { status: response.status, body: parsed }; } static fail(response) { const code = typeof response.body?.code === "string" ? response.body.code : "error"; const message = typeof response.body?.error === "string" ? response.body.error : `Request failed (HTTP ${response.status}).`; return new LicenseServerError(response.status, code, message); } /** * A call to the API as this signed-in device, for what goes beyond the * licence: the AI tools (license-server/src/routes-ai.ts), and the * account's preferences and work (routes-sync.ts). The answer's body, or a * LicenseServerError carrying the server's code and message (401 * "unauthenticated" when nobody is signed in here). A 401 from the server * means this device was signed out elsewhere, so it's signed out here too. */ async callAsDevice(method, path, body, timeoutMs) { const account = await this.account(); if (!account) throw new LicenseServerError(401, "unauthenticated", "Sign in to your TeXConverter account first."); const response = await this.request(method, path, body, account.session, timeoutMs); if (response.status === 401) await this.forgetIf(account); if (response.status >= 400) throw _LicenseClient.fail(response); return response.body; } /** The account's event stream, as this device (sync-client.ts); a LicenseServerError if refused. */ async streamAsDevice(path, signal) { const account = await this.account(); if (!account) throw new LicenseServerError(401, "unauthenticated", "Sign in to your TeXConverter account first."); let response; try { response = await this.fetchImpl(`${this.serverUrl}${path}`, { headers: { authorization: `Bearer ${account.session}` }, signal }); } catch { throw new LicenseNetworkError(); } if (!response.ok || !response.body) { const parsed = await response.json().catch(() => ({})); if (response.status === 401) await this.forgetIf(account); throw _LicenseClient.fail({ status: response.status, body: parsed }); } return response.body; } /** * The account's preferences, work and changes, reached as this device: what * sync-client.ts, synced-storage.ts and work-store.ts are handed. */ syncTransport() { const asSync = (e) => e instanceof LicenseServerError ? new SyncHttpError(e.status, e.code, e.message) : e; return { call: async (method, path, body) => { try { return await this.callAsDevice(method, path, body); } catch (e) { throw asSync(e); } }, stream: async (path, signal) => { try { return await this.streamAsDevice(path, signal); } catch (e) { throw asSync(e); } } }; } /** Who is signed in here, to keep each account's synced things apart; null if nobody. */ async signedInEmail() { return (await this.account())?.email || null; } /** Forgets the account, unless another sign-in replaced it meanwhile. */ async forgetIf(account) { if ((await this.account())?.session === account.session) await this.forget(); } // ---- signing in ---------------------------------------------------------- /** Asks the server for a code to show. */ async startLink() { const { app, name, platform } = this.options.device; const response = await this.request("POST", "/v1/devices/link/start", { clientDeviceId: await this.clientDeviceId(), app, ...name ? { name: name.slice(0, 100) } : {}, ...platform ? { platform: platform.slice(0, 50) } : {} }); if (response.status !== 201) throw _LicenseClient.fail(response); const b = response.body; return { deviceCode: b.deviceCode, userCode: b.userCode, verificationUrl: b.verificationUrl, verificationUrlComplete: b.verificationUrlComplete, expiresAt: this.now() + b.expiresIn * 1e3, interval: b.interval }; } /** Asks once whether the code has been approved. On approval, this device is signed in. */ async pollLink(link) { const response = await this.request("POST", "/v1/devices/link/poll", { deviceCode: link.deviceCode }); const code = response.body?.code; if (response.status === 202) return "pending"; if (response.status === 429 && code === "slow_down") return "slow_down"; if (response.status === 410) return "expired"; if (response.status === 403 && code === "access_denied") return "denied"; if (response.status !== 200) throw _LicenseClient.fail(response); const b = response.body; this.fresh.add(b.license.token); await this.save({ v: 1, server: this.serverUrl, session: b.token, email: b.user?.email ?? "", name: b.user?.name ?? null, license: b.license.token, planName: b.license.planName ?? null, refreshAfter: b.license.refreshAfter }); return "approved"; } /** * Polls until the code is approved, declined or expires, or `signal` aborts. * Network hiccups while waiting are retried, not fatal: the person may be * halfway through signing in on the website. */ async waitForLink(link, options = {}) { const sleep = options.sleep ?? defaultSleep; let interval = Math.max(1, link.interval) * 1e3; for (; ; ) { if (options.signal?.aborted) return "cancelled"; if (this.now() >= link.expiresAt) return "expired"; await sleep(interval, options.signal); if (options.signal?.aborted) return "cancelled"; let result; try { result = await this.pollLink(link); } catch (e) { if (e instanceof LicenseNetworkError) continue; throw e; } if (result === "slow_down") interval += 5e3; else if (result !== "pending") return result; } } /** Signs this device out, here and (if reachable) on the server, which frees its slot. */ async signOut() { const account = await this.account(); await this.forget(); if (!account) return; try { await this.request("POST", "/v1/auth/logout", {}, account.session); } catch { } } // ---- what may be used ---------------------------------------------------- /** * What this device may use now. * * Answers from the stored licence where it can, and fetches a new one when * it is due — in the background while the stored one is still good, or * first when it isn't (`refresh: "force"` always fetches first). */ async status(options = {}) { const mode = options.refresh ?? "auto"; let account = await this.account(); if (!account) return SIGNED_OUT; if (mode === "force") { const refreshed = await this.refresh(account); if (refreshed === null) return SIGNED_OUT; if (refreshed) account = refreshed; } let checked = await this.check(account); if (checked.state !== "active" && mode === "auto") { const refreshed = await this.refresh(account); if (refreshed === null) return SIGNED_OUT; if (refreshed) checked = await this.check(refreshed); } else if (mode === "auto" && this.now() >= account.refreshAfter) { void this.refresh(account).catch(() => void 0); } return checked; } /** The stored licence, judged on its own. */ async check(account) { const now = this.now(); const who = { email: account.email, name: account.name, planName: account.planName }; const result = await verifyLicense(account.license, this.options.publicKeys, now); if (result.ok) return { state: "active", granted: new Set(result.claims.ent), expiresAt: result.claims.exp, ...who }; let claims; if (result.reason === "unsupported") { claims = peekLicenseClaims(account.license); if (claims && this.fresh.has(account.license) && now < claims.exp) { return { state: "active", granted: new Set(claims.ent), expiresAt: claims.exp, ...who }; } } else if (result.reason === "expired") { claims = result.claims; } if (claims && now < claims.exp + BASE_GRACE_MS) { return { state: "limited", granted: new Set(claims.base), expiresAt: claims.exp + BASE_GRACE_MS, ...who }; } return { state: "limited", granted: /* @__PURE__ */ new Set(), ...who }; } /** * Fetches a fresh licence. Resolves to the updated account; null if the * server says this device is signed out (and forgets it); undefined if the * server couldn't be reached or refused for another reason. */ refresh(account) { this.refreshing ??= (async () => { try { const { version: version2 } = this.options.device; const response = await this.request("POST", "/v1/license", version2 ? { appVersion: version2.slice(0, 60) } : {}, account.session); if (response.status === 401) { await this.forget(); return null; } if (response.status !== 200) return void 0; const license = response.body.license; this.fresh.add(license.token); const user = response.body.user; const updated = { ...account, ...user && typeof user.email === "string" ? { email: user.email, name: typeof user.name === "string" ? user.name : null } : {}, license: license.token, planName: license.planName ?? null, refreshAfter: license.refreshAfter }; await this.save(updated); return updated; } catch { return void 0; } finally { this.refreshing = void 0; } })(); return this.refreshing; } }; function defaultSleep(ms, signal) { return new Promise((resolve5) => { const timer = setTimeout(done, ms); function done() { clearTimeout(timer); signal?.removeEventListener("abort", done); resolve5(); } signal?.addEventListener("abort", done, { once: true }); }); } // desktop/src/account.ts var DOCUMENTS = "pack.documents"; var DIAGRAMS = "pack.diagrams"; var TABLES = "pack.tables"; var IMAGES = "core.image"; var AI = "pack.ai"; var PDF = "pack.pdf"; function accountFile(env = process.env, platform = process.platform) { if (platform === "win32") return join(env.APPDATA ?? join(homedir(), "AppData", "Roaming"), "LaTeX2Word", "account.json"); if (platform === "darwin") return join(homedir(), "Library", "Application Support", "LaTeX2Word", "account.json"); return join(env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "latex2word", "account.json"); } function fileStore(path) { const load = async () => { try { const parsed = JSON.parse(await readFile(path, "utf8")); return typeof parsed === "object" && parsed !== null ? parsed : {}; } catch { return {}; } }; const store = async (values) => { await mkdir(dirname(path), { recursive: true }); const temporary = `${path}.${process.pid}.tmp`; await writeFile(temporary, JSON.stringify(values), { mode: 384 }); await rename(temporary, path); }; return { async get(key) { const value = (await load())[key]; return typeof value === "string" ? value : null; }, async set(key, value) { await store({ ...await load(), [key]: value }); }, async remove(key) { const values = await load(); if (!(key in values)) return; delete values[key]; if (Object.keys(values).length === 0) await rm(path, { force: true }); else await store(values); } }; } var PLATFORM_NAMES = { win32: "Windows", darwin: "macOS", linux: "Linux" }; function clientApp(app, platform = process.platform) { const where = PLATFORM_NAMES[platform] ?? platform; return { app, name: `TeXConverter ${app === "desktop" ? "app" : "command line"} on ${where}`, platform, version: versionLabel() }; } function accountClient(app, options = {}) { if (!CONFIG.licenseServerUrl) return void 0; return new LicenseClient({ serverUrl: CONFIG.licenseServerUrl, publicKeys: CONFIG.licensePublicKeys, store: fileStore(options.path ?? accountFile()), device: clientApp(app), fetch: options.fetch }); } function diagramsRefusal(status) { if (status.granted.has(DIAGRAMS)) return null; if (status.state === "signed_out") return "Saving diagrams needs a TeXConverter account with a subject plan. Sign in first."; if (status.state === "limited") return "TeXConverter couldn't check your plan. Connect to the internet and try again."; return "Saving diagrams is part of every subject plan, which your account doesn't have yet."; } function tablesRefusal(status) { if (status.granted.has(TABLES)) return null; if (status.state === "signed_out") return "Saving statistics tables needs a TeXConverter account with a subject plan. Sign in first."; if (status.state === "limited") return "TeXConverter couldn't check your plan. Connect to the internet and try again."; return "Saving statistics tables is part of every subject plan, which your account doesn't have yet."; } function imagesRefusal(status) { if (status.granted.has(IMAGES)) return null; if (status.state === "signed_out") return "Saving an equation as a picture needs a TeXConverter account. It's free: sign in first."; if (status.state === "limited") return "TeXConverter couldn't check your plan. Connect to the internet and try again."; return "Saving an equation as a picture isn't included in your plan."; } function aiRefusal(status) { if (status.granted.has(AI)) return null; if (status.state === "signed_out") return "Create with AI needs a TeXConverter account. Sign in first."; if (status.state === "limited") return "TeXConverter couldn't check your plan. Connect to the internet and try again."; return "Create with AI in the app is part of every paid plan. On the free plan, it's on the TeXConverter website."; } function pdfRefusal(status) { if (status.granted.has(PDF) && status.granted.has(AI)) return null; if (status.state === "signed_out") return "PDF to LaTeX needs a TeXConverter account with a subject plan. Sign in first."; if (status.state === "limited") return "TeXConverter couldn't check your plan. Connect to the internet and try again."; return "PDF to LaTeX is part of every subject plan, which your account doesn't have yet."; } function documentsRefusal(status) { if (status.granted.has(DOCUMENTS)) return null; if (status.state === "signed_out") return "Converting whole files needs a TeXConverter account with the Documents pack. Sign in first."; if (status.state === "limited") return "TeXConverter couldn't check your plan. Connect to the internet and try again."; return "Converting whole files is part of the Documents pack, which your plan doesn't include. Every paid plan has it."; } // desktop/src/handwriting.ts init_define_L2W_CONFIG(); // renderers/src/mathml-parse.ts init_define_L2W_CONFIG(); var import_xmldom2 = __toESM(require_lib(), 1); // renderers/src/ir-to-mathml.ts init_define_L2W_CONFIG(); var MATHML_NS = "http://www.w3.org/1998/Math/MathML"; var ACCENT_SPACING_FORM = { "\u0302": "^", // hat "\u0303": "~", // tilde "\u0307": "\u02D9", // dot "\u0308": "\xA8", // ddot "\u030C": "\u02C7", // check "\u0306": "\u02D8", // breve "\u20D7": "\u2192", // vec "\u20D6": "\u2190", // overleftarrow "\u20E1": "\u2194" // overleftrightarrow }; var UNDERLINE_CHAR = "_"; var RELATION_BREAKS = /* @__PURE__ */ new Set([ "=", "\u2260", "<", ">", "\u2264", "\u2265", "\u2248", "\u2261", "\u223C", "\u2243", "\u2245", "\u221D", "\u226A", "\u226B", "\u2254", "\u2192", "\u2190", "\u2194", "\u21D2", "\u21D0", "\u21D4", "\u27F6", "\u27F5", "\u27F7", "\u27F9", "\u27F8", "\u27FA", "\u21A6", "\u27FC", "\u21CC", "\u21CB", "\u2208", "\u2209", "\u2282", "\u2283", "\u2286", "\u2287" ]); var BINARY_BREAKS = /* @__PURE__ */ new Set(["+", "-", "\u2212", "\xB1", "\u2213", "\xD7", "\xF7", "\xB7", "\u22C5", "\u222A", "\u2229", "\u2295", "\u2297", "\u2227", "\u2228"]); var BREAK_AFTER = /* @__PURE__ */ new Set([...RELATION_BREAKS, ...BINARY_BREAKS, ","]); // renderers/src/mathml-parse.ts function fail5(message) { throw new OmmlConversionError(message); } function isMathmlElement(node) { if (!node || node.nodeType !== 1) return false; const ns = node.namespaceURI; return ns === MATHML_NS || ns === null || ns === void 0; } function isFunctionApplication(el) { return nameOf(el) === "mo" && textOf2(el).trim() === "\u2061"; } function childElements2(el) { const out = []; for (let i = 0; i < el.childNodes.length; i++) { const n = el.childNodes[i]; if (isMathmlElement(n) && !isFunctionApplication(n)) out.push(n); } return out; } function attrVal2(el, name) { const attrs = el.attributes; if (!attrs) return null; for (let i = 0; i < attrs.length; i++) { const a = attrs[i]; if (a.localName === name) return a.value; } return null; } function nameOf(el) { return el.localName ?? ""; } function textOf2(el) { return el.textContent ?? ""; } var TOKEN_ELEMENTS = /* @__PURE__ */ new Set(["mi", "mn", "mo", "mtext", "ms", "mspace"]); var TRANSPARENT_ELEMENTS = /* @__PURE__ */ new Set(["mstyle", "mpadded", "semantics"]); var COMBINING_FORM = Object.fromEntries( Object.entries(ACCENT_SPACING_FORM).map(([combining, spacing]) => [spacing, combining]) ); var OVERLINE_CHARS = /* @__PURE__ */ new Set(["\u203E", "\u2015", "\xAF", "\u0304"]); function stylingOf(el, text) { const variant = attrVal2(el, "mathvariant"); if (variant !== null) { switch (variant) { case "italic": return { italic: true, bold: false }; case "bold": return { italic: false, bold: true }; case "bold-italic": return { italic: true, bold: true }; case "normal": return { italic: false, bold: false }; default: fail5(`mathvariant="${variant}" is not a style TeXConverter can represent \u2014 use the corresponding Unicode characters (as \\mathbb, \\mathcal and \\mathfrak produce) instead.`); } } const italic = nameOf(el) === "mi" && [...text].length === 1; return { italic, bold: false }; } function tokenToIr(el) { const name = nameOf(el); if (name === "mspace") { return { kind: "symbol", text: " ", italic: false }; } const text = textOf2(el); const { italic, bold } = stylingOf(el, text); const node = bold ? { kind: "symbol", text, italic, bold } : { kind: "symbol", text, italic }; const color = colorOf(el); if (color !== void 0) node.color = color; return node; } function colorOf(el) { const value = attrVal2(el, "mathcolor"); if (value === null) return void 0; const hex2 = cssColorToHex(value); if (hex2 === null) fail5(`mathcolor="${value}" is not a colour TeXConverter can read \u2014 use a #RRGGBB value or a common colour name.`); return hex2; } function contentOf(el) { return asRow(childElements2(el).map((c) => parseElement(c))); } function asRow(nodes) { if (nodes.length === 1) return nodes[0]; return { kind: "row", children: nodes }; } function expectChildren(el, count) { const kids = childElements2(el); if (kids.length !== count) { fail5(`<${nameOf(el)}> requires exactly ${count} child elements but has ${kids.length}.`); } return kids; } function isToken(el, name) { return nameOf(el) === name; } function singleChar(el) { if (!TOKEN_ELEMENTS.has(nameOf(el))) return null; const chars = [...textOf2(el).trim()]; return chars.length === 1 ? chars[0] : null; } var LARGE_OPERATORS = /* @__PURE__ */ new Set(["\u2211", "\u220F", "\u2210", "\u222B", "\u222C", "\u222D", "\u222E", "\u222F", "\u2230", "\u2A0C", "\u22C3", "\u22C2", "\u2A01", "\u2A02", "\u2A00", "\u2A04", "\u22C1", "\u22C0", "\u2A06"]); var ARROW_CHARS = /* @__PURE__ */ new Set(["\u27F6", "\u27F5", "\u2192", "\u2190", "\u21CC", "\u21C0", "\u21C1", "\u21BD", "\u21CB", "\u27F7", "\u27F9", "\u27F8", "\u27FA", "\u27FC", "\u21AA", "\u21A9"]); var UNDERLINE_CHARS = /* @__PURE__ */ new Set([UNDERLINE_CHAR, "\u0332"]); function isLargeOperator(el) { if (!isToken(el, "mo")) return false; if (attrVal2(el, "largeop") === "true") return true; const ch = singleChar(el); return ch !== null && LARGE_OPERATORS.has(ch); } function isArrowOperator(el) { if (!isToken(el, "mo")) return false; if (attrVal2(el, "stretchy") !== "true") return false; const ch = singleChar(el); return ch !== null && ARROW_CHARS.has(ch); } function accentMarkOf(el) { const ch = singleChar(el); if (ch === null) return null; if (COMBINING_FORM[ch] !== void 0) return COMBINING_FORM[ch]; if (ACCENT_SPACING_FORM[ch] !== void 0) return ch; return null; } function isOverline(el) { const ch = singleChar(el); return ch !== null && OVERLINE_CHARS.has(ch); } var GROUP_CHARS = { "\u23DE": "top", "\u23DF": "bot", "\u23DC": "top", "\u23DD": "bot" }; function groupCharOf(el) { const ch = singleChar(el); if (ch === null) return null; const pos = GROUP_CHARS[ch]; return pos === void 0 ? null : { chr: ch, pos }; } function parseUnderOver(el, under, over) { const kids = childElements2(el); const base = kids[0]; if (isLargeOperator(base)) { const chr = singleChar(base) ?? textOf2(base).trim(); const limitLocation = "undOvr"; return naryFrom(chr, under, over, limitLocation, { kind: "row", children: [] }); } if (isArrowOperator(base)) { const chr = singleChar(base) ?? textOf2(base).trim(); const node = { kind: "labeledarrow", chr }; if (over) node.above = parseElement(over); if (under) node.below = parseElement(under); return node; } if (over !== null && under === null) { const brace = groupCharOf(over); if (brace !== null) return { kind: "groupchar", chr: brace.chr, pos: brace.pos, base: parseElement(base) }; if (isOverline(over)) return { kind: "accent", base: parseElement(base), bar: true }; const mark = accentMarkOf(over); if (mark !== null) return { kind: "accent", base: parseElement(base), char: mark }; return { kind: "limupp", base: parseElement(base), upper: parseElement(over) }; } if (under !== null && over === null) { const brace = groupCharOf(under); if (brace !== null) return { kind: "groupchar", chr: brace.chr, pos: brace.pos, base: parseElement(base) }; const mark = singleChar(under); if (mark !== null && UNDERLINE_CHARS.has(mark)) return { kind: "accent", base: parseElement(base), bar: true, under: true }; return { kind: "limlow", base: parseElement(base), lower: parseElement(under) }; } fail5(` requires a large operator or an arrow as its base; found <${nameOf(base)}>.`); } function naryFrom(chr, sub, sup, limitLocation, operand) { const node = { kind: "nary", chr, operand, limitLocation }; if (sub) node.sub = parseElement(sub); if (sup) node.sup = parseElement(sup); return node; } var OPENING_FENCES = "([{\u27E8\u2308\u230A|\u2016\u2223"; var CLOSING_FENCES = ")]}\u27E9\u2309\u230B|\u2016\u2223"; function isExplicitFence(el) { return isToken(el, "mo") && attrVal2(el, "fence") === "true"; } function fenceCharOf(el, opening) { if (!isToken(el, "mo")) return null; if (attrVal2(el, "fence") === "true" && textOf2(el).trim() === "") return ""; const ch = singleChar(el); if (ch === null) return null; if (attrVal2(el, "fence") === "true") return ch; if (attrVal2(el, "stretchy") === "false") return null; return (opening ? OPENING_FENCES : CLOSING_FENCES).includes(ch) ? ch : null; } function tryDelimited(kids) { if (kids.length < 2) return null; const first = kids[0]; const last = kids[kids.length - 1]; let left = fenceCharOf(first, true); let right = fenceCharOf(last, false); let inner; if (left !== null && right !== null) { inner = kids.slice(1, -1); } else if (isExplicitFence(first) && left !== null) { right = ""; inner = kids.slice(1); } else if (isExplicitFence(last) && right !== null) { left = ""; inner = kids.slice(0, -1); } else { return null; } if (left === null || right === null) return null; const separators = []; const parts = [[]]; for (const kid of inner) { const sep3 = isToken(kid, "mo") && attrVal2(kid, "fence") === "true" ? singleChar(kid) : null; if (sep3 !== null) { separators.push(sep3); parts.push([]); } else { parts[parts.length - 1].push(parseElement(kid)); } } if (separators.length === 0) { return { kind: "delimited", left, right, parts: [asRow(parts[0])] }; } const sepChar = separators[0]; if (!separators.every((s) => s === sepChar)) { fail5("A delimited group divided by more than one kind of separator cannot be represented \u2014 OMML allows a single separator character per group."); } return { kind: "delimited", left, right, parts: parts.map((p) => asRow(p)), sepChar }; } function tryNary(kids) { if (kids.length === 0) return null; const head2 = kids[0]; const name = nameOf(head2); let chr = null; let sub = null; let sup = null; let limitLocation = "subSup"; if (isLargeOperator(head2)) { chr = singleChar(head2); } else if (["msub", "msup", "msubsup", "munder", "mover", "munderover"].includes(name)) { const inner = childElements2(head2); const base = inner[0]; if (base === void 0 || !isLargeOperator(base)) return null; chr = singleChar(base); limitLocation = name.startsWith("mu") || name === "mover" ? "undOvr" : "subSup"; if (name === "msub" || name === "munder") sub = inner[1] ?? null; else if (name === "msup" || name === "mover") sup = inner[1] ?? null; else { sub = inner[1] ?? null; sup = inner[2] ?? null; } } else { return null; } if (chr === null) return null; const operand = asRow(kids.slice(1).map((k) => parseElement(k))); return naryFrom(chr, sub, sup, limitLocation, operand); } function parseRow(kids) { const delimited = tryDelimited(kids); if (delimited !== null) return delimited; const nary = tryNary(kids); if (nary !== null) return nary; return asRow(kids.map((k) => parseElement(k))); } function parseTable(el) { const rows = childElements2(el).filter((r) => isToken(r, "mtr") || isToken(r, "mlabeledtr")); const cellRows = rows.map((r) => childElements2(r).filter((c) => isToken(c, "mtd")).map((c) => contentOf(c))); const align = attrVal2(el, "columnalign"); if ((align === "left" || align === "center") && cellRows.every((r) => r.length === 1)) { return { kind: "eqarr", rows: cellRows.map((r) => r[0]), justify: align }; } const columns = columnAlignments(align, Math.max(1, ...cellRows.map((r) => r.length))); return columns === void 0 ? { kind: "matrix", rows: cellRows } : { kind: "matrix", rows: cellRows, columns }; } function columnAlignments(align, width) { if (align === null || align === void 0) return void 0; const tokens = align.trim().split(/\s+/).filter((t) => t.length > 0); if (tokens.length === 0) return void 0; const columns = []; for (let i = 0; i < width; i++) { const token = tokens[Math.min(i, tokens.length - 1)]; columns.push(token === "left" ? "left" : token === "right" ? "right" : "center"); } return columns.some((c) => c !== "center") ? columns : void 0; } function parseMultiscripts(el) { const kids = childElements2(el); const split = kids.findIndex((k) => isToken(k, "mprescripts")); if (split < 0) { fail5(" without (postscript-style staggered indices) has no OMML equivalent \u2014 write the scripts as ordinary sub/superscripts."); } const base = kids[0]; if (base === void 0) fail5(" has no base."); const pre = kids.slice(split + 1); if (pre.length !== 2) { fail5(` takes prescripts in (sub, sup) pairs; found ${pre.length} after .`); } const node = { kind: "prescript", base: parseElement(base) }; if (!isToken(pre[0], "none")) node.presub = parseElement(pre[0]); if (!isToken(pre[1], "none")) node.presup = parseElement(pre[1]); return node; } function parseElement(el) { const name = nameOf(el); if (TOKEN_ELEMENTS.has(name)) return tokenToIr(el); if (TRANSPARENT_ELEMENTS.has(name)) { const color = colorOf(el); return color === void 0 ? contentOf(el) : applyColor(contentOf(el), color); } switch (name) { case "math": case "mrow": return parseRow(childElements2(el)); case "mfrac": { const [num2, den] = expectChildren(el, 2); const thickness = attrVal2(el, "linethickness"); const noBar = thickness === "0" || thickness === "0px" || thickness === "0pt"; return { kind: "frac", numerator: parseElement(num2), denominator: parseElement(den), noBar }; } case "msqrt": return { kind: "radical", radicand: contentOf(el) }; case "mroot": { const [radicand, index] = expectChildren(el, 2); return { kind: "radical", radicand: parseElement(radicand), index: parseElement(index) }; } case "msub": case "msup": case "msubsup": { const nary = tryNary([el]); if (nary !== null) return nary; const kids = expectChildren(el, name === "msubsup" ? 3 : 2); const base = parseElement(kids[0]); if (name === "msub") return { kind: "supersub", base, sub: parseElement(kids[1]) }; if (name === "msup") return { kind: "supersub", base, sup: parseElement(kids[1]) }; return { kind: "supersub", base, sub: parseElement(kids[1]), sup: parseElement(kids[2]) }; } case "munder": { const kids = expectChildren(el, 2); return parseUnderOver(el, kids[1], null); } case "mover": { const kids = expectChildren(el, 2); return parseUnderOver(el, null, kids[1]); } case "munderover": { const kids = expectChildren(el, 3); return parseUnderOver(el, kids[1], kids[2]); } case "mmultiscripts": return parseMultiscripts(el); case "mtable": return parseTable(el); case "menclose": { const notation = (attrVal2(el, "notation") ?? "longdiv").trim().split(/\s+/).filter((n) => n.length > 0); const strikeBLTR = notation.includes("updiagonalstrike"); const strikeTLBR = notation.includes("downdiagonalstrike"); const boxed = notation.includes("box"); const unsupported = notation.filter((n) => n !== "updiagonalstrike" && n !== "downdiagonalstrike" && n !== "box"); if (unsupported.length > 0) { fail5(` has no OMML equivalent \u2014 only box (\\boxed) and the diagonal strikes (the \\cancel family) are supported.`); } return boxed ? { kind: "borderbox", base: contentOf(el), strikeBLTR, strikeTLBR, boxed: true } : { kind: "borderbox", base: contentOf(el), strikeBLTR, strikeTLBR }; } case "mfenced": { const left = attrVal2(el, "open") ?? "("; const right = attrVal2(el, "close") ?? ")"; return { kind: "delimited", left, right, parts: [contentOf(el)] }; } default: return fail5(`"<${name}>" is not a MathML element TeXConverter can convert.`); } } function parseXml(xml) { const errors = []; const doc = new import_xmldom2.DOMParser({ errorHandler: (level, msg) => { if (level === "error" || level === "fatalError") errors.push(String(msg)); } }).parseFromString(xml, "text/xml"); if (errors.length > 0) fail5(`The provided MathML is not well-formed XML: ${errors.join("; ")}`); return doc; } function findMath(doc) { let found = null; const visit = (node) => { if (found !== null || !node) return; if (isMathmlElement(node) && node.localName === "math") { found = node; return; } for (let i = 0; i < node.childNodes.length; i++) visit(node.childNodes[i]); }; visit(doc.documentElement); return found; } function parseMathmlDetailed(xml) { const doc = parseXml(xml); const math = findMath(doc); if (math === null) fail5("No element found \u2014 this does not look like MathML."); return { ir: parseElement(math), display: attrVal2(math, "display") === "block" }; } function parseMathml(xml) { return parseMathmlDetailed(xml).ir; } // desktop/src/handwriting.ts var HandwritingError = class extends Error { constructor(reason, message) { super(message); this.reason = reason; this.name = "HandwritingError"; } }; function createHandwritingDesk(open) { let current; return { available: open !== void 0, async write(signal) { if (open === void 0) throw new HandwritingError("unavailable", "Online handwriting recognition isn't available in this build."); if (current) throw new HandwritingError("busy", "The handwriting panel is already open. Finish or close it first."); const abort = new AbortController(); current = abort; const onCallerGone = () => abort.abort(); signal?.addEventListener("abort", onCallerGone, { once: true }); let outcome; try { outcome = await open(abort.signal); } finally { signal?.removeEventListener("abort", onCallerGone); current = void 0; } if (outcome.kind === "cancelled") return { kind: "cancelled" }; try { return { kind: "inserted", latex: irToLatex(parseMathml(outcome.mathml)), mathml: outcome.mathml }; } catch (e) { throw new HandwritingError( "unreadable", `Windows recognised the handwriting, but TeXConverter couldn't read its answer: ${e instanceof Error ? e.message : String(e)}` ); } }, abort() { current?.abort(); } }; } // desktop/src/update.ts init_define_L2W_CONFIG(); import { createHash } from "node:crypto"; import { existsSync, renameSync, rmSync, writeFileSync } from "node:fs"; var UpdateError = class extends Error { }; function compareBuilds(currentBuild, downloads) { const latest = downloads.windows; if (currentBuild <= 0 || !latest || latest.build <= currentBuild) return { available: false, required: false }; return { available: true, required: downloads.minimumBuild > currentBuild }; } async function filesFromZip(zip, release) { if (zip.byteLength !== release.bytes) throw new UpdateError(`The download was ${zip.byteLength} bytes, not ${release.bytes}. Try again.`); const sha = createHash("sha256").update(zip).digest("hex"); if (sha !== release.sha256) throw new UpdateError("The download didn't match its checksum, so it wasn't installed. Try again."); let parts; try { parts = (await readPackage(zip, nodeZipCodec)).parts; } catch (e) { throw new UpdateError(`The download couldn't be opened (${e instanceof Error ? e.message : String(e)}).`); } const name = [...parts.keys()].find((n) => /(^|\/)TeXConverter\.exe$/i.test(n)); const exe = name === void 0 ? void 0 : parts.get(name); if (!exe) throw new UpdateError("The download has no TeXConverter.exe in it."); if (exe.byteLength < 2 || exe[0] !== 77 || exe[1] !== 90) throw new UpdateError("The TeXConverter.exe in the download isn't a Windows program."); const helperName = [...parts.keys()].find((n) => /(^|\/)TeXConverterHelper\.exe$/i.test(n)); const helper = helperName === void 0 ? void 0 : parts.get(helperName); return { exe, helper: helper && helper.byteLength >= 2 && helper[0] === 77 && helper[1] === 90 ? helper : null }; } var realExeFiles = { exists: existsSync, rename: renameSync, write: (path, data) => writeFileSync(path, data), remove: (path) => rmSync(path, { force: true }) }; var oldExePath = (exe) => `${exe}.old`; function replaceExe(exe, data, files = realExeFiles) { const old = oldExePath(exe); if (files.exists(old)) files.remove(old); try { files.rename(exe, old); } catch (e) { throw new UpdateError(`TeXConverter couldn't move itself aside to update (${e instanceof Error ? e.message : String(e)}). Download the new version from the website instead.`); } try { files.write(exe, data); } catch (e) { try { files.remove(exe); } catch { } try { files.rename(old, exe); } catch { throw new UpdateError(`The update couldn't be written, and the previous version is at ${old}. Rename it back to TeXConverter.exe, or download the app again.`); } throw new UpdateError(`The update couldn't be written (${e instanceof Error ? e.message : String(e)}); this version is still in place.`); } } function removeOldExe(exe, files = realExeFiles) { try { if (files.exists(oldExePath(exe))) files.remove(oldExePath(exe)); } catch { } } var HOUR = 36e5; function createUpdater(options) { const fetchImpl = options.fetch ?? fetch; const files = options.files ?? realExeFiles; const now = options.now ?? Date.now; const current = versionLabel(options.version, options.build); let downloads = null; let state = "idle"; let progress = null; let error = null; let checkedAt = null; let timer; let running = false; let checking = null; function status() { const { available, required } = downloads ? compareBuilds(options.build, downloads) : { available: false, required: false }; const latest = downloads?.windows ?? null; return { current, latest: latest ? { label: latest.label, notes: latest.notes, bytes: latest.bytes, build: latest.build } : null, available, required, canInstall: options.exe !== null && options.build > 0, state, progress, error, checkedAt }; } async function fetchDownloads() { const res = await fetchImpl(`${options.serverUrl}/v1/downloads`, { signal: AbortSignal.timeout(15e3) }); if (!res.ok) throw new UpdateError(`TeXConverter's server answered ${res.status}.`); const body = await res.json(); const w = body.windows; const windows = w && typeof w.url === "string" && Number.isInteger(w.build) && typeof w.sha256 === "string" ? w : null; return { windows, minimumBuild: Number(body.minimumBuild) || 0, updateCheckHours: Number(body.updateCheckHours) || 6 }; } function check() { if (state === "downloading" || state === "installing" || state === "restarting") return Promise.resolve(status()); checking ??= (async () => { state = "checking"; try { downloads = await fetchDownloads(); checkedAt = now(); error = null; } catch { } finally { state = "idle"; checking = null; } return status(); })(); return checking; } async function download(release) { const res = await fetchImpl(release.url, { signal: AbortSignal.timeout(30 * 6e4) }); if (!res.ok || !res.body) throw new UpdateError(`The download failed (${res.status}). Try again.`); const chunks = []; let received = 0; const reader = res.body.getReader(); for (; ; ) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); received += value.byteLength; if (received > release.bytes) { void reader.cancel(); throw new UpdateError("The download was bigger than it should be, so it wasn't installed."); } progress = release.bytes > 0 ? received / release.bytes : null; } const zip = new Uint8Array(received); let at = 0; for (const c of chunks) { zip.set(c, at); at += c.byteLength; } return zip; } async function install2() { if (state === "downloading" || state === "installing" || state === "restarting") return status(); if (options.exe === null || options.build <= 0) throw new UpdateError("This copy of TeXConverter can't update itself. Download the new version from the website."); await check(); const release = downloads?.windows; if (!release || !compareBuilds(options.build, downloads).available) throw new UpdateError("This is already the latest version."); error = null; try { state = "downloading"; progress = 0; const update = await filesFromZip(await download(release), release); state = "installing"; progress = null; replaceExe(options.exe, update.exe, files); try { options.afterReplace?.(options.exe, release.label, update.helper); } catch { } state = "restarting"; return status(); } catch (e) { state = "failed"; progress = null; error = e instanceof UpdateError ? e.message : `The update failed (${e instanceof Error ? e.message : String(e)}). Try again.`; throw e instanceof UpdateError ? e : new UpdateError(error); } } function schedule() { if (!running) return; const hours = Math.min(168, Math.max(1, downloads?.updateCheckHours ?? 6)); timer = setTimeout(() => { void check().finally(schedule); }, hours * HOUR); timer.unref?.(); } return { status, check, install: install2, start() { if (running) return; running = true; void check().finally(schedule); }, stop() { running = false; if (timer) clearTimeout(timer); timer = void 0; } }; } // desktop/src/service.ts var HANDWRITING_STATUS = { unavailable: 404, busy: 409, unreadable: 422 }; var MAX_BODY_BYTES = 256 * 1024 * 1024; var AI_TASKS = ["diagram", "equation", "photo", "figure", "edit", "page", "equations"]; var AI_TIMEOUT_MS = 12e4; var ID = "[A-Za-z0-9_-]{1,64}"; var ACCOUNT_ROUTES = [ ["GET", /^\/sync$/], ["GET", /^\/prefs$/], ["PATCH", /^\/prefs$/], ["GET", /^\/work$/], ["POST", /^\/work$/], ["PATCH", new RegExp(`^/work/${ID}$`)], ["DELETE", new RegExp(`^/work/${ID}$`)], ["GET", /^\/ai\/creations$/], ["POST", /^\/ai\/creations$/], ["GET", new RegExp(`^/ai/creations/${ID}/photo$`)], ["POST", new RegExp(`^/ai/creations/${ID}/(pin|remove|source)$`)] ]; function accountRoute(method, pathname) { if (!pathname.startsWith("/api/")) return null; const rest = pathname.slice("/api".length); return ACCOUNT_ROUTES.some(([m, path]) => m === method && path.test(rest)) ? `/v1${rest}` : null; } var HttpError = class extends Error { /** The licence server's code for a refusal it made, passed on so the page can act on it. */ constructor(status, message, code) { super(message); this.status = status; this.code = code; } }; function send(res, status, type, body, headers = {}) { res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", ...headers }); res.end(body); } var sendJson = (res, status, body) => send(res, status, "application/json; charset=utf-8", JSON.stringify(body)); async function readJson(req) { if (!(req.headers["content-type"] ?? "").startsWith("application/json")) { throw new HttpError(415, "Expected JSON."); } const chunks = []; let size = 0; for await (const chunk of req) { size += chunk.length; if (size > MAX_BODY_BYTES) throw new HttpError(413, "That is more than TeXConverter will take in one go. Convert fewer files at a time."); chunks.push(chunk); } try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { throw new HttpError(400, "The request was not valid JSON."); } } function sameToken(expected, given) { if (typeof given !== "string") return false; const a = Buffer.from(expected); const b = Buffer.from(given); return a.length === b.length && timingSafeEqual(a, b); } async function exists(path) { try { await access(path); return true; } catch { return false; } } async function freeName(dir, name) { const dot = name.lastIndexOf("."); const [base, extension] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""]; for (let n = 1; ; n++) { const candidate = n === 1 ? name : `${base} (${n})${extension}`; if (!await exists(join2(dir, candidate))) return candidate; } } function fileStem(name) { const stem2 = name.replace(/\.pdf$/i, "").replace(/[<>:"/\\|?*\u0000-\u001f]/g, " ").replace(/\s+/g, " ").trim().replace(/^[. ]+|[. ]+$/g, "").slice(0, 80).trim(); return /^(con|prn|aux|nul|com\d|lpt\d)$/i.test(stem2) || stem2 === "" ? "PDF" : stem2; } var PAGE_CSP = "default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"; async function startService(options) { const token = options.token ?? randomBytes(32).toString("hex"); const outputDir = resolve(options.outputDir); const written = /* @__PURE__ */ new Map(); let lastSeen = Date.now(); let port = 0; let signIn; let lastSignIn; const desk = options.desk ?? createHandwritingDesk(options.handwriting); async function accountInfo(fresh = false) { if (!options.account) return { enabled: false }; const status = await options.account.status(fresh ? { refresh: "force" } : void 0); return { enabled: true, state: status.state, email: status.email ?? null, planName: status.planName ?? null, documents: documentsRefusal(status), diagrams: diagramsRefusal(status), tables: tablesRefusal(status), images: imagesRefusal(status), ai: aiRefusal(status), pdf: pdfRefusal(status), signIn: signIn ? { userCode: signIn.link.userCode, url: signIn.link.verificationUrlComplete } : null, lastSignIn: lastSignIn ?? null }; } async function relayAi(method, path, body, timeoutMs = AI_TIMEOUT_MS) { const account = options.account; if (!account?.callAsDevice) throw new HttpError(404, "This build of TeXConverter has no AI tools."); try { return await account.callAsDevice(method, path, body, timeoutMs); } catch (e) { throw unreachable(e); } } function unreachable(e) { if (e instanceof LicenseServerError) return new HttpError(e.status, e.message, e.code); return new HttpError(502, "TeXConverter's server couldn't be reached. Check your internet connection and try again."); } async function relayEvents(res, search) { const account = options.account; if (!account?.streamAsDevice) throw new HttpError(404, "This build of TeXConverter has no account to follow."); const abort = new AbortController(); res.once("close", () => abort.abort()); let body; try { body = await account.streamAsDevice(`/v1/sync/events${search}`, abort.signal); } catch (e) { throw unreachable(e); } res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" }); res.flushHeaders(); const reader = body.getReader(); try { for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) res.write(chunk.value); } catch { } finally { abort.abort(); res.end(); } } async function startSignIn(account) { if (!signIn) { const current = { link: await account.startLink(), abort: new AbortController() }; signIn = current; lastSignIn = void 0; account.waitForLink(current.link, { signal: current.abort.signal }).then( (outcome) => lastSignIn = outcome, () => lastSignIn = "failed" ).finally(() => { if (signIn === current) signIn = void 0; }); options.openUrl?.(current.link.verificationUrlComplete); } return { userCode: signIn.link.userCode, url: signIn.link.verificationUrlComplete }; } const server = createServer((req, res) => { handle(req, res).catch((e) => { if (e instanceof HttpError) sendJson(res, e.status, e.code === void 0 ? { error: e.message } : { error: e.message, code: e.code }); else sendJson(res, 500, { error: e instanceof Error ? e.message : String(e) }); }); }); async function handle(req, res) { const hosts = [`127.0.0.1:${port}`, `localhost:${port}`]; if (!hosts.includes(req.headers.host ?? "")) throw new HttpError(421, "Wrong host."); const url = new URL(req.url ?? "/", `http://${req.headers.host}`); if (url.pathname === "/" && req.method === "GET") { send(res, 200, "text/html; charset=utf-8", options.html, { "Content-Security-Policy": PAGE_CSP }); return; } const model = req.method === "GET" ? /^\/ocr\/reader\/([^/]{1,60})\/([^/]{1,80})$/.exec(url.pathname) : null; if (model) { const path = options.reader?.file(model[1], model[2]); if (!path) throw new HttpError(404, "Not found."); res.writeHead(200, { "Content-Type": path.endsWith(".wasm") ? "application/wasm" : "application/octet-stream", // A version's files never change. "Cache-Control": "private, max-age=31536000, immutable", "X-Content-Type-Options": "nosniff", "Cross-Origin-Resource-Policy": "same-origin" }); await pipeline(createReadStream(path), res).catch(() => void 0); return; } if (!url.pathname.startsWith("/api/")) throw new HttpError(404, "Not found."); const origin2 = req.headers.origin; if (origin2 !== void 0 && !hosts.some((h) => origin2 === `http://${h}`)) throw new HttpError(403, "Wrong origin."); if (!sameToken(token, req.headers["x-l2w-token"])) throw new HttpError(401, "Missing or wrong token."); lastSeen = Date.now(); const job = req.method === "GET" ? /^\/api\/ai\/jobs\/([A-Za-z0-9_-]{1,64})$/.exec(url.pathname) : null; if (job) { sendJson(res, 200, await relayAi("GET", `/v1/ai/jobs/${job[1]}`)); return; } const method = req.method ?? "GET"; const upstream = accountRoute(method, url.pathname); if (upstream) { const body = method === "POST" || method === "PATCH" ? await readJson(req) : void 0; sendJson(res, 200, await relayAi(method, upstream + url.search, body, 3e4)); return; } switch (`${req.method} ${url.pathname}`) { case "GET /api/status": sendJson(res, 200, { version: options.version, environment: options.build?.environment ?? "production", server: options.build?.server ?? null, outputDir, shell: options.shell === void 0 ? "unavailable" : options.shell.installed() ? "installed" : "not-installed", handwriting: desk.available, help: Object.keys(options.help ?? {}), updates: options.updates !== void 0, // fresh=1: the page heard the plan change elsewhere. account: await accountInfo(url.searchParams.get("fresh") === "1") }); return; case "GET /api/sync/events": await relayEvents(res, url.search); return; case "GET /api/library": if (!options.library) throw new HttpError(404, "This build of TeXConverter has no library to fetch."); sendJson(res, 200, await options.library().catch(() => { throw new HttpError(502, "The library couldn't be fetched."); })); return; case "GET /api/ai": sendJson(res, 200, await relayAi("GET", "/v1/ai")); return; case "GET /api/ocr/reader": if (!options.reader) throw new HttpError(404, "This build of TeXConverter has no reader."); sendJson(res, 200, url.searchParams.get("fresh") === "1" ? await options.reader.refresh() : options.reader.status()); return; case "POST /api/ocr/reader/prepare": if (!options.reader) throw new HttpError(404, "This build of TeXConverter has no reader."); void options.reader.prepare(); sendJson(res, 200, options.reader.status()); return; case "POST /api/ai/diagram": case "POST /api/ai/equation": case "POST /api/ai/photo": case "POST /api/ai/figure": case "POST /api/ai/edit": case "POST /api/ai/page": case "POST /api/ai/equations": { const task = AI_TASKS.find((t) => url.pathname === `/api/ai/${t}`); sendJson(res, 200, await relayAi("POST", `/v1/ai/${task}`, await readJson(req))); return; } case "POST /api/ai/pages": sendJson(res, 200, await relayAi("POST", "/v1/ai/pages", await readJson(req))); return; // A photo from the phone (frontend/src/phone-photo.ts): start, wait for it, end. case "POST /api/ai/photo/qr": case "POST /api/ai/photo/qr/status": case "POST /api/ai/photo/qr/cancel": sendJson(res, 200, await relayAi("POST", url.pathname.replace(/^\/api\//, "/v1/"), await readJson(req), 3e4)); return; case "POST /api/account/signin": if (!options.account) throw new HttpError(404, "This build of TeXConverter has no accounts."); sendJson(res, 200, await startSignIn(options.account)); return; case "POST /api/account/cancel": signIn?.abort.abort(); res.writeHead(204).end(); return; case "POST /api/account/signout": if (!options.account) throw new HttpError(404, "This build of TeXConverter has no accounts."); await options.account.signOut(); res.writeHead(204).end(); return; case "POST /api/ping": res.writeHead(204).end(); return; case "POST /api/convert": sendJson(res, 200, await convert(await readJson(req))); return; case "POST /api/pdf/save": sendJson(res, 200, await savePdf(await readJson(req))); return; case "POST /api/open": { const body = await readJson(req); const path = typeof body.id === "string" ? written.get(body.id) : void 0; if (path === void 0) throw new HttpError(404, "TeXConverter did not write that file in this session."); options.openPath?.(path, body.reveal === true); res.writeHead(204).end(); return; } case "POST /api/install": { if (options.shell === void 0) throw new HttpError(404, "There is no shell integration on this system."); sendJson(res, 200, { done: await options.shell.install() }); return; } case "POST /api/handwrite": sendJson(res, 200, { latex: await handwrite() }); return; case "GET /api/update": sendJson(res, 200, updates().status()); return; case "POST /api/update/check": sendJson(res, 200, await updates().check()); return; case "POST /api/update/install": { let status; try { status = await updates().install(); } catch (e) { if (e instanceof UpdateError) throw new HttpError(409, e.message); throw e; } res.once("finish", () => void close()); sendJson(res, 200, status); return; } case "POST /api/help": { const body = await readJson(req); const help = options.help ?? {}; const page = typeof body.topic === "string" && Object.prototype.hasOwnProperty.call(help, body.topic) ? help[body.topic] : void 0; if (page === void 0) throw new HttpError(404, "There is no such help page."); options.openUrl?.(typeof page === "string" ? page : await page()); res.writeHead(204).end(); return; } case "POST /api/update/download": options.openUrl?.(updates().downloadPage); res.writeHead(204).end(); return; default: throw new HttpError(404, "Not found."); } } function updates() { if (!options.updates) throw new HttpError(404, "This build of TeXConverter doesn't update itself."); return options.updates; } async function handwrite() { try { const result = await desk.write(); return result.kind === "inserted" ? result.latex : null; } catch (e) { if (e instanceof HandwritingError) throw new HttpError(HANDWRITING_STATUS[e.reason], e.message); throw e; } } async function convert(body) { if (options.account) { const refusal = documentsRefusal(await options.account.status()); if (refusal !== null) throw new HttpError(403, refusal); } const request = body; if (!Array.isArray(request.files)) throw new HttpError(400, "Expected a list of files."); const dropped = request.files.map((f) => { if (typeof f?.path !== "string" || typeof f?.data !== "string") throw new HttpError(400, "Each file needs a path and base64 data."); return { path: f.path, bytes: new Uint8Array(Buffer.from(f.data, "base64")) }; }); const outcomes = await convertBatch(dropped, { bibStyle: request.options?.bibStyle, singleDollarMode: request.options?.singleDollarMode }); const results = []; for (const outcome of outcomes) { if ("error" in outcome) { results.push({ input: outcome.input, error: outcome.error }); continue; } const top = outcome.primary.split("/")[0]; const freeTop = await freeName(outputDir, top); let primaryPath = ""; for (const [relative, bytes] of outcome.files) { const target = resolve(outputDir, freeTop + relative.slice(top.length)); if (!target.startsWith(outputDir + sep)) throw new Error(`Refusing to write outside the output folder: ${relative}`); await mkdir2(dirname2(target), { recursive: true }); await writeFile2(target, bytes); if (relative === outcome.primary) primaryPath = target; } const id = randomBytes(12).toString("hex"); written.set(id, primaryPath); results.push({ input: outcome.input, kind: outcome.kind, output: primaryPath.slice(outputDir.length + 1), id, summary: outcome.summary, notes: outcome.notes }); } return { results }; } async function savePdf(body) { if (options.account) { const refusal = pdfRefusal(await options.account.status()); if (refusal !== null) throw new HttpError(403, refusal); } const request = body; if (typeof request.name !== "string" || typeof request.tex !== "string" || !Array.isArray(request.files)) { throw new HttpError(400, "Expected a name, the LaTeX and its figures."); } const figures = /* @__PURE__ */ new Map(); for (const f of request.files) { const path = typeof f?.path === "string" ? normalizeDropPath(f.path) : null; if (path === null || !path.startsWith("figures/") || typeof f.data !== "string") throw new HttpError(400, "Each figure needs a path under figures/ and base64 data."); figures.set(path, new Uint8Array(Buffer.from(f.data, "base64"))); } const base = fileStem(request.name); const folder = resolve(outputDir, await freeName(outputDir, base)); if (!folder.startsWith(outputDir + sep)) throw new HttpError(400, "That name can't be used for a folder."); await mkdir2(join2(folder, "figures"), { recursive: true }); for (const [path, bytes] of figures) await writeFile2(join2(folder, ...path.split("/")), bytes); const texPath = join2(folder, `${base}.tex`); await writeFile2(texPath, request.tex, "utf8"); const saved = (path) => { const id = randomBytes(12).toString("hex"); written.set(id, path); return { output: path.slice(outputDir.length + 1), id }; }; const result = { tex: saved(texPath), word: null, notes: [] }; if (request.word === true) { const refusal = options.account ? documentsRefusal(await options.account.status()) : null; if (refusal !== null) { result.notes.push(`No Word copy: ${refusal}`); } else { try { const report = await convertTex(request.tex, { resolveImage: (target) => figures.get(normalizeDropPath(target) ?? "") ?? null }); const docxPath = join2(folder, `${base}.docx`); await writeFile2(docxPath, report.bytes); result.word = saved(docxPath); result.notes.push(...report.warnings.slice(0, 50)); } catch (e) { result.notes.push(`The Word copy couldn't be made: ${e instanceof Error ? e.message : String(e)}`); } } } return result; } await new Promise((resolveListen, rejectListen) => { server.once("error", rejectListen); server.listen(options.port ?? 0, "127.0.0.1", () => { server.removeListener("error", rejectListen); resolveListen(); }); }); port = server.address().port; const origin = `http://127.0.0.1:${port}`; let resolveClosed; const closed = new Promise((r) => resolveClosed = r); let idleTimer; const close = async () => { if (idleTimer) clearInterval(idleTimer); desk.abort(); await new Promise((r) => { server.close(() => r()); server.closeAllConnections(); }); resolveClosed(); }; const idleMs = options.idleMs === void 0 ? 6e4 : options.idleMs; if (idleMs !== null) { idleTimer = setInterval(() => { if (Date.now() - lastSeen > idleMs) void close(); }, Math.min(idleMs, 5e3)); } return { origin, url: `${origin}/?t=${token}`, token, closed, close }; } // desktop/src/reader-models.ts init_define_L2W_CONFIG(); import { createHash as createHash2 } from "node:crypto"; import { createWriteStream } from "node:fs"; import { mkdir as mkdir3, readdir, readFile as readFile2, rename as rename2, rm as rm2, stat, utimes, writeFile as writeFile3 } from "node:fs/promises"; import { join as join3 } from "node:path"; import { Readable } from "node:stream"; import { pipeline as pipeline2 } from "node:stream/promises"; // src/shared/model-manifest.ts init_define_L2W_CONFIG(); var MANIFEST_PREFIX = "TCM1"; var MODEL_ENGINES = ["reader"]; var MODEL_VERSION_RE = /^[0-9A-Za-z][0-9A-Za-z.-]{0,59}$/; var MODEL_FILE_RE = /^[0-9A-Za-z][0-9A-Za-z._-]{0,79}$/; var MODEL_SHA256_RE = /^[0-9a-f]{64}$/; var encoder2 = new TextEncoder(); function isModelEngine(value) { return typeof value === "string" && MODEL_ENGINES.includes(value); } function isManifest(value) { const m = value; return typeof m === "object" && m !== null && m.v === 1 && isModelEngine(m.engine) && typeof m.version === "string" && MODEL_VERSION_RE.test(m.version) && typeof m.label === "string" && (m.kind === "own" || m.kind === "p2t" || m.kind === "pix2tex") && typeof m.runtime === "string" && typeof m.promotedAt === "number" && Array.isArray(m.files) && m.files.length > 0 && m.files.every( (f) => typeof f === "object" && f !== null && typeof f.name === "string" && MODEL_FILE_RE.test(f.name) && Number.isInteger(f.bytes) && f.bytes > 0 && typeof f.sha256 === "string" && MODEL_SHA256_RE.test(f.sha256) ) && new Set(m.files.map((f) => f.name)).size === m.files.length; } async function verifyManifest(token, keys) { if (typeof token !== "string" || token.length > 64 * 1024) return { ok: false, reason: "malformed" }; const parts = token.split("."); if (parts.length !== 4 || parts[0] !== MANIFEST_PREFIX) return { ok: false, reason: "malformed" }; const [, kid, payload, signature] = parts; let manifest; try { manifest = JSON.parse(new TextDecoder().decode(fromBase64url(payload))); } catch { return { ok: false, reason: "malformed" }; } if (!isManifest(manifest)) return { ok: false, reason: "malformed" }; const publicKey = Object.prototype.hasOwnProperty.call(keys, kid) ? keys[kid] : void 0; if (!publicKey) return { ok: false, reason: "unknown_key" }; let valid; try { const key = await crypto.subtle.importKey("raw", fromBase64url(publicKey), { name: "Ed25519" }, false, ["verify"]); valid = await crypto.subtle.verify({ name: "Ed25519" }, key, fromBase64url(signature), encoder2.encode(`${MANIFEST_PREFIX}.${kid}.${payload}`)); } catch (e) { if (e instanceof Error && e.name === "NotSupportedError") return { ok: false, reason: "unsupported" }; return { ok: false, reason: "bad_signature" }; } return valid ? { ok: true, manifest } : { ok: false, reason: "bad_signature" }; } // desktop/src/reader-models.ts var OFFER_FILE = "offer.json"; var READY_FILE = "ready.json"; var KEEP = 2; function readerDir(env = process.env, platform = process.platform, home = "") { if (platform === "win32") return join3(env.LOCALAPPDATA ?? join3(home || env.USERPROFILE || "", "AppData", "Local"), "LaTeX2Word", "ocr-models", "reader"); if (platform === "darwin") return join3(home || env.HOME || "", "Library", "Caches", "LaTeX2Word", "ocr-models", "reader"); return join3(env.XDG_CACHE_HOME ?? join3(home || env.HOME || "", ".cache"), "latex2word", "ocr-models", "reader"); } async function readerModels(options) { const doFetch = options.fetch ?? fetch; const dir = options.dir; let saved = null; const ready = /* @__PURE__ */ new Map(); let downloading = null; let failure = null; async function check(offer) { if (!offer.model) return { offer, manifest: null }; const verified = await verifyManifest(offer.model.manifest, options.publicKeys); return { offer, manifest: verified.ok ? verified.manifest : null }; } const onDevice = (f) => options.everyFile === true || !f.name.startsWith("hand_"); async function versionFolders() { const entries = await readdir(dir, { withFileTypes: true }).catch(() => []); return entries.filter((e) => e.isDirectory() && MODEL_VERSION_RE.test(e.name)).map((e) => e.name); } try { saved = await check(JSON.parse(await readFile2(join3(dir, OFFER_FILE), "utf8"))); } catch { saved = null; } for (const name of await versionFolders()) { try { const verified = await verifyManifest(await readFile2(join3(dir, name, READY_FILE), "utf8"), options.publicKeys); if (verified.ok && verified.manifest.version === name) ready.set(name, verified.manifest); } catch { } } function status() { const offer = saved?.offer; const manifest = saved?.manifest ?? null; const base = { offerAi: offer?.offerAi ?? false, unsureBelow: offer?.unsureBelow ?? 0.7, version: manifest?.version ?? null, label: manifest?.label ?? null, kind: manifest?.kind ?? null, bytes: 0, done: 0, reason: null, files: null }; if (!offer) return { ...base, state: "unavailable", reason: "TeXConverter hasn't been able to check for its reader yet. Connect to the internet once." }; if (!offer.enabled) return { ...base, state: "off" }; if (!manifest) return { ...base, state: "unavailable", reason: "This copy of TeXConverter couldn't check the reader it was offered, so it won't use it." }; if (manifest.runtime !== options.runtime) return { ...base, state: "unavailable", reason: "The reader on offer needs a newer TeXConverter. Update the app to use it." }; const bytes = manifest.files.filter(onDevice).reduce((n, f) => n + f.bytes, 0); if (ready.has(manifest.version)) return { ...base, state: "ready", bytes, done: bytes, files: `/ocr/reader/${manifest.version}/` }; if (downloading?.version === manifest.version) return { ...base, state: "downloading", bytes, done: downloading.done }; if (failure?.version === manifest.version) return { ...base, state: "failed", bytes, reason: failure.reason }; return { ...base, state: "absent", bytes }; } async function refresh() { let offer; try { const res = await doFetch(options.offerUrl ?? `${options.serverUrl}/v1/ocr/reader`, { headers: options.headers, signal: AbortSignal.timeout(8e3) }); if (!res.ok) return status(); offer = await res.json(); } catch { return status(); } const before = saved?.manifest?.version; saved = await check(offer); await mkdir3(dir, { recursive: true }); await writeFile3(join3(dir, OFFER_FILE), JSON.stringify(offer)); const now = saved.manifest?.version; if (now && now !== before && ready.has(now)) await utimes(join3(dir, now, READY_FILE), /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date()).catch(() => void 0); return status(); } async function download(manifest, token, base) { const folder = join3(dir, manifest.version); await mkdir3(folder, { recursive: true }); for (const f of manifest.files.filter(onDevice)) { const target = join3(folder, f.name); const partial = `${target}.partial`; const res = await doFetch(new URL(f.name, base).href, { signal: AbortSignal.timeout(30 * 6e4) }); if (!res.ok || !res.body) throw new Error(`TeXConverter's server didn't send ${f.name} (${res.status}).`); const hash = createHash2("sha256"); let size = 0; const counted = Readable.fromWeb(res.body).on("data", (chunk) => { hash.update(chunk); size += chunk.length; if (downloading) downloading.done += chunk.length; }); await pipeline2(counted, createWriteStream(partial)); if (size !== f.bytes || hash.digest("hex") !== f.sha256) { await rm2(partial, { force: true }); throw new Error(`${f.name} arrived damaged. Try again.`); } await rename2(partial, target); } await writeFile3(join3(folder, READY_FILE), token); ready.set(manifest.version, manifest); } async function prune(keep) { const others = []; for (const name of await versionFolders()) { if (name === keep) continue; const at = await stat(join3(dir, name, READY_FILE)).then((s) => s.mtimeMs, () => 0); others.push({ name, at }); } others.sort((a, b) => b.at - a.at); for (const o of others.filter((o2, i) => o2.at === 0 || i >= KEEP - 1)) { ready.delete(o.name); await rm2(join3(dir, o.name), { recursive: true, force: true }); } } function prepare() { const now = status(); if (now.state !== "absent" && now.state !== "failed") return downloading?.promise ?? Promise.resolve(now); const manifest = saved.manifest; const offer = saved.offer.model; failure = null; const promise = download(manifest, offer.manifest, offer.files).then(() => prune(manifest.version)).catch((e) => { failure = { version: manifest.version, reason: e instanceof Error ? e.message : String(e) }; }).then(() => { downloading = null; return status(); }); downloading = { version: manifest.version, bytes: now.bytes, done: 0, promise }; return promise; } function file(version2, name) { const manifest = ready.get(version2); if (!manifest?.files.some((f) => f.name === name && onDevice(f))) return null; return join3(dir, version2, name); } return { status, refresh, prepare, file }; } // ocr/src/local/runtime.ts init_define_L2W_CONFIG(); var ORT_VERSION = "1.30.0"; // desktop/src/shell.ts init_define_L2W_CONFIG(); import { spawnSync as spawnSync2, spawn as spawn2 } from "node:child_process"; import { copyFileSync, existsSync as existsSync2, mkdirSync, readFileSync, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs"; import { dirname as dirname3, join as join4, resolve as resolve2 } from "node:path"; // desktop/src/ink.ts init_define_L2W_CONFIG(); var INK_SCRIPT = String.raw` $ErrorActionPreference = 'Stop' Add-Type -ReferencedAssemblies System.Windows.Forms, System.Drawing -TypeDefinition @' using System; using System.Drawing; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Windows.Forms; // _IMathInputControlEvents, from micaut.dll's type library. [ComImport, Guid("683336B5-A47D-4358-96F9-875A472AE70A"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IMathInputControlEvents { [DispId(0)] void Insert([MarshalAs(UnmanagedType.BStr)] string recoResult); [DispId(1)] void Close(); [DispId(2)] void Paint(IntPtr hdc, int left, int top, int right, int bottom); [DispId(3)] void Clear(); } [ComVisible(true), ClassInterface(ClassInterfaceType.None)] public class TeXConverterInk : IMathInputControlEvents { [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindow(string cls, string title); [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h); [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags); [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, IntPtr pid); [DllImport("user32.dll")] static extern bool AttachThreadInput(uint attach, uint to, bool on); [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId(); // Windows lets only the program in front give the foreground away. The // panel is opened from the background (the helper serving Word, or the // app's server behind its browser tab), so it joins the front window's // input for a moment to be handed the focus, and the pen goes straight to it. static void BringToFront(IntPtr window) { uint front = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero); uint self = GetCurrentThreadId(); bool joined = front != 0 && front != self && AttachThreadInput(self, front, true); try { SetForegroundWindow(window); } finally { if (joined) AttachThreadInput(self, front, false); } } string result; public void Insert(string recoResult) { result = recoResult; Application.ExitThread(); } public void Close() { Application.ExitThread(); } public void Paint(IntPtr hdc, int left, int top, int right, int bottom) { } public void Clear() { } static object Call(object target, string name, params object[] args) { return target.GetType().InvokeMember(name, BindingFlags.InvokeMethod, null, target, args); } public static string Run(string caption) { object mic = Activator.CreateInstance(Type.GetTypeFromProgID("micaut.MathInputControl", true)); var sink = new TeXConverterInk(); IConnectionPoint point; Guid events = typeof(IMathInputControlEvents).GUID; ((IConnectionPointContainer)mic).FindConnectionPoint(ref events, out point); int cookie; point.Advise(sink, out cookie); try { Call(mic, "SetCaptionText", caption); Call(mic, "EnableAutoGrow", true); // Word's size, centred on the screen the user is working on. Rectangle area = Screen.FromPoint(Cursor.Position).WorkingArea; int width = Math.Min(780, area.Width - 40), height = Math.Min(500, area.Height - 40); int left = area.Left + (area.Width - width) / 2, top = area.Top + (area.Height - height) / 2; Call(mic, "SetPosition", left, top, left + width, top + height); Call(mic, "Show"); // The window is looked for until it appears (for up to 10 s), and the // panel counts as closed only once it has been seen and then hidden. IntPtr window = IntPtr.Zero; bool seen = false; int waited = 0; var watch = new Timer { Interval = 250 }; watch.Tick += (s, e) => { if (window == IntPtr.Zero) { window = FindWindow(null, caption); if (window != IntPtr.Zero) { // Above the browser or Word it was opened from, which otherwise // keeps the foreground and leaves the panel behind it. SetWindowPos(window, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040); BringToFront(window); } } if (window != IntPtr.Zero && IsWindowVisible(window)) seen = true; else if (seen || ++waited > 40) Application.ExitThread(); }; watch.Start(); Application.Run(); watch.Stop(); Call(mic, "Hide"); } finally { point.Unadvise(cookie); } return sink.result; } } '@ $mathml = [TeXConverterInk]::Run($env:TEXCONVERTER_INK_CAPTION) if ($mathml) { [Console]::Out.Write('MATHML ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($mathml))) } else { [Console]::Out.Write('CANCELLED') } `; function encodeCommand(script) { return Buffer.from(script, "utf16le").toString("base64"); } // desktop/src/taskbar.ts init_define_L2W_CONFIG(); import { spawn, spawnSync } from "node:child_process"; var APP_USER_MODEL_ID = "PureTechWithJoy.TeXConverter"; var PACKAGE_APP_ID = "TeXConverter"; var WINDOW_TITLE = "TeXConverter"; var TASKBAR_TYPE = String.raw` Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; using System.Text; public static class TeXConverterTaskbar { [StructLayout(LayoutKind.Sequential, Pack = 4)] struct PropertyKey { public Guid fmtid; public uint pid; } [StructLayout(LayoutKind.Explicit)] struct PropVariant { [FieldOffset(0)] public ushort vt; [FieldOffset(8)] public IntPtr p; } [ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IPropertyStore { int GetCount(out uint count); int GetAt(uint index, out PropertyKey key); int GetValue(ref PropertyKey key, out PropVariant value); int SetValue(ref PropertyKey key, ref PropVariant value); int Commit(); } [DllImport("shell32.dll")] static extern int SHGetPropertyStoreForWindow(IntPtr hwnd, ref Guid iid, out IPropertyStore store); [DllImport("shell32.dll", CharSet = CharSet.Unicode)] static extern int SHGetPropertyStoreFromParsingName(string path, IntPtr bindContext, int flags, ref Guid iid, out IPropertyStore store); delegate bool EnumProc(IntPtr hwnd, IntPtr data); [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc proc, IntPtr data); [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr hwnd); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr hwnd, StringBuilder text, int max); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr hwnd, StringBuilder name, int max); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid); [DllImport("user32.dll")] static extern bool IsIconic(IntPtr hwnd); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hwnd, int command); [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hwnd); [DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern int GetCurrentPackageFamilyName(ref uint length, StringBuilder name); // PKEY_AppUserModel_*: RelaunchCommand 2, RelaunchIconResource 3, RelaunchDisplayNameResource 4, ID 5. static readonly Guid AppUserModel = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"); static void Set(IPropertyStore store, uint pid, string text) { PropertyKey key = new PropertyKey(); key.fmtid = AppUserModel; key.pid = pid; PropVariant value = new PropVariant(); value.vt = 31; // VT_LPWSTR value.p = Marshal.StringToCoTaskMemUni(text); try { Marshal.ThrowExceptionForHR(store.SetValue(ref key, ref value)); } finally { Marshal.FreeCoTaskMem(value.p); } } /** The Store package's ID for its app named app, when this runs inside the package (as the app's children do); null outside one. */ public static string PackageAppId(string app) { uint length = 256; StringBuilder name = new StringBuilder(256); return GetCurrentPackageFamilyName(ref length, name) == 0 ? name.ToString() + "!" + app : null; } static bool IsAppWindow(IntPtr hwnd, string title) { if (!IsWindowVisible(hwnd)) return false; StringBuilder text = new StringBuilder(256); GetWindowText(hwnd, text, text.Capacity); if (text.ToString() != title) return false; StringBuilder name = new StringBuilder(256); GetClassName(hwnd, name, name.Capacity); if (name.ToString() != "Chrome_WidgetWin_1") return false; uint pid; GetWindowThreadProcessId(hwnd, out pid); try { string process = System.Diagnostics.Process.GetProcessById((int)pid).ProcessName.ToLowerInvariant(); return process == "msedge" || process == "chrome"; } catch { return false; } } /** Gives every open app window the ID; how many there were. */ public static int TagWindows(string title, string id, string command, string icon) { int tagged = 0; EnumWindows(delegate (IntPtr hwnd, IntPtr data) { if (!IsAppWindow(hwnd, title)) return true; Guid iid = typeof(IPropertyStore).GUID; IPropertyStore store; if (SHGetPropertyStoreForWindow(hwnd, ref iid, out store) != 0) return true; try { // The relaunch values before the ID: Windows reads them as the ID changes. // None for a package's ID: Windows starts a package's app itself. if (!String.IsNullOrEmpty(command)) { Set(store, 2, command); Set(store, 3, icon); Set(store, 4, title); } Set(store, 5, id); store.Commit(); tagged++; } catch { } finally { Marshal.ReleaseComObject(store); } return true; }, IntPtr.Zero); return tagged; } /** Brings the open app window to the front, restored if it was minimised; false when there is none. */ public static bool FocusWindow(string title) { IntPtr found = IntPtr.Zero; EnumWindows(delegate (IntPtr hwnd, IntPtr data) { if (!IsAppWindow(hwnd, title)) return true; found = hwnd; return false; }, IntPtr.Zero); if (found == IntPtr.Zero) return false; if (IsIconic(found)) ShowWindow(found, 9); // SW_RESTORE if (!SetForegroundWindow(found)) { // Windows lets a window be brought forward only by the program in use; // a tap of Alt makes this one that, as the person did just open it. keybd_event(0x12, 0, 0, UIntPtr.Zero); keybd_event(0x12, 0, 2, UIntPtr.Zero); // KEYEVENTF_KEYUP SetForegroundWindow(found); } return true; } /** Gives a saved .lnk the ID. */ public static void TagShortcut(string path, string id) { Guid iid = typeof(IPropertyStore).GUID; IPropertyStore store; Marshal.ThrowExceptionForHR(SHGetPropertyStoreFromParsingName(path, IntPtr.Zero, 2, ref iid, out store)); // GPS_READWRITE try { Set(store, 5, id); Marshal.ThrowExceptionForHR(store.Commit()); } finally { Marshal.ReleaseComObject(store); } } } '@ `; var TAG_WINDOW_SCRIPT = String.raw`${TASKBAR_TYPE} $id = [TeXConverterTaskbar]::PackageAppId($env:TEXCONVERTER_PACKAGE_APP) $relaunch = $null if (-not $id) { $id = $env:TEXCONVERTER_APP_ID; $relaunch = $env:TEXCONVERTER_RELAUNCH } $deadline = [DateTime]::UtcNow.AddSeconds(20) do { if ([TeXConverterTaskbar]::TagWindows($env:TEXCONVERTER_WINDOW_TITLE, $id, $relaunch, $env:TEXCONVERTER_ICON) -gt 0) { break } Start-Sleep -Milliseconds 100 } while ([DateTime]::UtcNow -lt $deadline) `; function tagWindowEnv(exe, launcher = exe) { return { TEXCONVERTER_WINDOW_TITLE: WINDOW_TITLE, TEXCONVERTER_APP_ID: APP_USER_MODEL_ID, // Used instead, with no relaunch values, when the app runs from the Store package. TEXCONVERTER_PACKAGE_APP: PACKAGE_APP_ID, // Quoted: the path may have spaces in it. No arguments: it opens as a double-click does. TEXCONVERTER_RELAUNCH: `"${launcher}"`, TEXCONVERTER_ICON: `${exe},0` }; } var POWERSHELL_FLAGS = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand"]; function tagAppWindow(exe, launcher = exe, spawnFn = (command, args2, o) => spawn(command, [...args2], { ...o, detached: true, stdio: "ignore" })) { const child = spawnFn("powershell.exe", [...POWERSHELL_FLAGS, encodeCommand(TAG_WINDOW_SCRIPT)], { windowsHide: true, env: { ...process.env, ...tagWindowEnv(exe, launcher) } }); child.on("error", () => void 0); child.unref(); } var FOCUS_WINDOW_SCRIPT = String.raw`${TASKBAR_TYPE} if ([TeXConverterTaskbar]::FocusWindow($env:TEXCONVERTER_WINDOW_TITLE)) { exit 0 } else { exit 1 } `; var runFocus = (command, args2, env) => spawnSync(command, [...args2], { windowsHide: true, stdio: "ignore", env, timeout: 15e3 }); function focusAppWindow(run3 = runFocus) { if (process.platform !== "win32") return false; return run3("powershell.exe", [...POWERSHELL_FLAGS, encodeCommand(FOCUS_WINDOW_SCRIPT)], { ...process.env, TEXCONVERTER_WINDOW_TITLE: WINDOW_TITLE }).status === 0; } // desktop/src/pe.ts init_define_L2W_CONFIG(); function optionalHeader(exe) { const view2 = new DataView(exe.buffer, exe.byteOffset, exe.byteLength); if (exe.byteLength < 64 || view2.getUint16(0, true) !== 23117) throw new Error("it is not a Windows executable (no MZ header)"); const pe = view2.getUint32(60, true); if (pe + 24 + 70 > exe.byteLength || view2.getUint32(pe, true) !== 17744) throw new Error("it is not a Windows executable (no PE header)"); const at = pe + 24; const magic = view2.getUint16(at, true); if (magic !== 267 && magic !== 523) throw new Error("its PE header is of an unknown kind"); return { view: view2, at, plus: magic === 523 }; } function subsystemOf(exe) { const { view: view2, at } = optionalHeader(exe); return view2.getUint16(at + 68, true); } function withoutConsole(exe) { const current = subsystemOf(exe); if (current !== 2 && current !== 3) throw new Error(`it is for an unexpected Windows subsystem (${current})`); const { at } = optionalHeader(exe); const out = exe.slice(); new DataView(out.buffer, out.byteOffset, out.byteLength).setUint16(at + 68, 2, true); return out; } // desktop/src/shell.ts var APP_NAME = "TeXConverter"; var EXE_NAME = "TeXConverter.exe"; var VERB = "LaTeX2Word.Convert"; var CLASSES = "HKCU\\Software\\Classes\\SystemFileAssociations"; var UNINSTALL_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\LaTeX2Word"; var RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"; var RUN_VALUE = "TeXConverterHelper"; var HELPER_EXE_NAME = "TeXConverterHelper.exe"; var DESKTOP_SHORTCUT_NAME = `${APP_NAME}.lnk`; function installPaths(env) { if (!env.LOCALAPPDATA || !env.APPDATA) throw new Error("LOCALAPPDATA and APPDATA are not set, so there is nowhere per-user to install to."); const installDir = join4(env.LOCALAPPDATA, "Programs", APP_NAME); return { installDir, exe: join4(installDir, EXE_NAME), helperExe: join4(installDir, HELPER_EXE_NAME), shortcut: join4(env.APPDATA, "Microsoft", "Windows", "Start Menu", "Programs", `${APP_NAME}.lnk`), windowProfile: join4(env.LOCALAPPDATA, APP_NAME, "Window") }; } function registryKeys() { return [`${CLASSES}\\.docx\\shell\\${VERB}`, `${CLASSES}\\.tex\\shell\\${VERB}`, UNINSTALL_KEY]; } function registryValues(paths, version2) { const values = []; const verbs = [ [".docx", "Convert to LaTeX (.tex)"], [".tex", "Convert to Word (.docx)"] ]; for (const [extension, label] of verbs) { const key = `${CLASSES}\\${extension}\\shell\\${VERB}`; values.push({ key, name: null, type: "REG_SZ", data: label }); values.push({ key, name: "Icon", type: "REG_SZ", data: `${paths.exe},0` }); values.push({ key: `${key}\\command`, name: null, type: "REG_SZ", data: `"${paths.exe}" open "%1"` }); } const uninstall2 = [ ["DisplayName", "REG_SZ", APP_NAME], ["DisplayVersion", "REG_SZ", version2], ["Publisher", "REG_SZ", APP_NAME], ["DisplayIcon", "REG_SZ", `${paths.exe},0`], ["InstallLocation", "REG_SZ", paths.installDir], ["UninstallString", "REG_SZ", `"${paths.exe}" uninstall`], ["NoModify", "REG_DWORD", "1"], ["NoRepair", "REG_DWORD", "1"] ]; for (const [name, type, data] of uninstall2) values.push({ key: UNINSTALL_KEY, name, type, data }); return values; } function regAddArgs(value) { return ["add", value.key, ...value.name === null ? ["/ve"] : ["/v", value.name], "/t", value.type, "/d", value.data, "/f"]; } function regDeleteArgs(key, value) { return value === void 0 ? ["delete", key, "/f"] : ["delete", key, "/v", value, "/f"]; } function helperRunValue(paths) { return { key: RUN_KEY, name: RUN_VALUE, type: "REG_SZ", data: `"${paths.helperExe}" helper` }; } function shippedHelper(paths, sourceExe, read = readIfThere) { if (resolve2(dirname3(sourceExe)).toLowerCase() === resolve2(paths.installDir).toLowerCase()) return null; const helper = read(join4(dirname3(sourceExe), HELPER_EXE_NAME)); return helper !== null && isWindowlessExe(helper) ? helper : null; } function isWindowlessExe(exe) { try { return subsystemOf(exe) === 2; } catch { return false; } } function readIfThere(path) { try { return readFileSync(path); } catch { return null; } } function stopHelperScript(paths) { return `Get-Process -Name 'TeXConverterHelper' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq ${psQuote(paths.helperExe)} } | Stop-Process -Force -ErrorAction SilentlyContinue`; } function psQuote(text) { return `'${text.replace(/'/g, "''")}'`; } function shortcutScript(paths, target = paths.exe) { return [ `$ErrorActionPreference = 'Stop'`, TASKBAR_TYPE, `$links = @(${psQuote(paths.shortcut)})`, `$desktop = [Environment]::GetFolderPath('Desktop')`, `if ($desktop) { $links += Join-Path $desktop ${psQuote(DESKTOP_SHORTCUT_NAME)} }`, // A pinned taskbar icon is a separate .lnk from the desktop and Start // Menu shortcuts. Refresh our existing pin in place so it cannot keep // pointing at an older install location after an upgrade. `$pinned = Join-Path $env:APPDATA 'MicrosoftInternet ExplorerQuick LaunchUser PinnedTaskBar'`, `try { if (Test-Path -LiteralPath $pinned) { foreach ($candidate in (Get-ChildItem -LiteralPath $pinned -Filter '*.lnk' -File)) { $existing = (New-Object -ComObject WScript.Shell).CreateShortcut($candidate.FullName); if ($existing.TargetPath -eq ${psQuote(paths.exe)} -or $existing.TargetPath -eq ${psQuote(paths.helperExe)}) { $links += $candidate.FullName } } } } catch { }`, `foreach ($link in $links) {`, ` $s = (New-Object -ComObject WScript.Shell).CreateShortcut($link)`, ` $s.TargetPath = ${psQuote(target)}`, // No arguments: it starts as a double-click does, opening the app window. ` $s.WindowStyle = 7`, ` $s.IconLocation = ${psQuote(`${paths.exe},0`)}`, ` $s.Description = 'Convert between Word documents and LaTeX'`, ` $s.Save()`, ` try { [TeXConverterTaskbar]::TagShortcut($link, ${psQuote(APP_USER_MODEL_ID)}) } catch { }`, `}`, // Let Explorer discard cached file and shortcut icons after replacement. `try { Add-Type -Namespace TeXConverter -Name ShellNotify -MemberDefinition '[System.Runtime.InteropServices.DllImport("shell32.dll")] public static extern void SHChangeNotify(int wEventId, uint uFlags, System.IntPtr dwItem1, System.IntPtr dwItem2);' -ErrorAction Stop; [TeXConverter.ShellNotify]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero) } catch { }` ].join("\n"); } function removeDesktopShortcutScript(paths) { return [ `$desktop = [Environment]::GetFolderPath('Desktop')`, `if (-not $desktop) { exit 1 }`, `$link = Join-Path $desktop ${psQuote(DESKTOP_SHORTCUT_NAME)}`, `if (-not (Test-Path -LiteralPath $link)) { exit 1 }`, `$target = (New-Object -ComObject WScript.Shell).CreateShortcut($link).TargetPath`, `if ($target -ne ${psQuote(paths.exe)} -and $target -ne ${psQuote(paths.helperExe)}) { exit 1 }`, `Remove-Item -LiteralPath $link -Force`, `exit 0` ].join("; "); } function powershellArgs(script) { return ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encodeCommand(script)]; } var defaultRunner = (command, args2) => { const result = spawnSync2(command, args2, { encoding: "utf8", windowsHide: true }); return { status: result.status, stderr: result.stderr ?? "" }; }; var launchDetached = (exe, args2) => { spawn2(exe, args2, { detached: true, stdio: "ignore", windowsHide: true }).on("error", () => void 0).unref(); }; function stopHelper(paths, run3) { run3("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", stopHelperScript(paths)]); } function setUpHelper(paths, run3 = defaultRunner, launch = launchDetached, shipped = null) { try { const helper = shipped !== null && isWindowlessExe(shipped) ? shipped : withoutConsole(readFileSync(paths.exe)); stopHelper(paths, run3); writeFileSync2(paths.helperExe, helper); const result = run3("reg", regAddArgs(helperRunValue(paths))); if (result.status !== 0) throw new Error(result.stderr.trim() || "the registry refused"); launch(paths.helperExe, ["helper"]); return "Set up handwriting for the Word add-in: a small helper starts with Windows, so Handwrite in Word opens Windows' handwriting panel"; } catch (e) { return `Handwriting from Word couldn't be set up (${e instanceof Error ? e.message : String(e)}); it works while this window is open, and everything else is in place.`; } } function requireWindows() { if (process.platform !== "win32") { throw new Error("The right-click menu and Start Menu entry are Windows-only for now. Use `texconverter app` or `texconverter convert` instead."); } } function isInstalled(paths, run3 = defaultRunner) { if (process.platform !== "win32" || !existsSync2(paths.exe)) return false; return run3("reg", ["query", UNINSTALL_KEY]).status === 0; } function install(paths, version2, sourceExe, run3 = defaultRunner, launch = launchDetached, helper = shippedHelper(paths, sourceExe)) { requireWindows(); const done = []; if (resolve2(sourceExe).toLowerCase() !== resolve2(paths.exe).toLowerCase()) { mkdirSync(paths.installDir, { recursive: true }); try { copyFileSync(sourceExe, paths.exe); } catch (e) { throw new Error(`Could not copy TeXConverter into ${paths.installDir} (${e instanceof Error ? e.message : String(e)}). If another copy is running, close it and try again.`); } done.push(`Installed to ${paths.installDir}`); } for (const value of registryValues(paths, version2)) { const result = run3("reg", regAddArgs(value)); if (result.status !== 0) throw new Error(`Could not write ${value.key}: ${result.stderr.trim()}`); } done.push("Added \u201CConvert to LaTeX\u201D to the right-click menu of .docx files, and \u201CConvert to Word\u201D to .tex files"); const helperLine = setUpHelper(paths, run3, launch, helper); mkdirSync(dirname3(paths.shortcut), { recursive: true }); const shortcut = run3("powershell.exe", powershellArgs(shortcutScript(paths, existsSync2(paths.helperExe) ? paths.helperExe : paths.exe))); if (shortcut.status === 0) done.push("Added TeXConverter to the Start Menu and the desktop"); else done.push(`The Start Menu and desktop icons could not be created (${shortcut.stderr.trim() || "no reason given"}); everything else is in place.`); done.push(helperLine); return done; } function uninstall(paths, runningExe, run3 = defaultRunner) { requireWindows(); const done = []; for (const key of registryKeys()) run3("reg", regDeleteArgs(key)); done.push("Removed the right-click menu entries"); run3("reg", regDeleteArgs(RUN_KEY, RUN_VALUE)); stopHelper(paths, run3); if (existsSync2(paths.helperExe)) done.push("Stopped the handwriting helper and removed it from sign-in"); if (existsSync2(paths.shortcut)) { rmSync2(paths.shortcut, { force: true }); done.push("Removed the Start Menu entry"); } if (run3("powershell.exe", powershellArgs(removeDesktopShortcutScript(paths))).status === 0) done.push("Removed the desktop icon"); try { rmSync2(paths.windowProfile, { recursive: true, force: true }); } catch { } if (existsSync2(paths.installDir)) { if (resolve2(dirname3(runningExe)).toLowerCase() === resolve2(paths.installDir).toLowerCase()) { spawn2("cmd.exe", ["/d", "/c", `ping 127.0.0.1 -n 3 >nul & rmdir /s /q "${paths.installDir}"`], { detached: true, stdio: "ignore", windowsHide: true, windowsVerbatimArguments: true }).unref(); } else { rmSync2(paths.installDir, { recursive: true, force: true }); } done.push(`Removed ${paths.installDir}`); } return done; } // desktop/src/bridge.ts init_define_L2W_CONFIG(); import { createServer as createServer2 } from "node:http"; // src/shared/desktop-bridge.ts init_define_L2W_CONFIG(); var BRIDGE_PORTS = [47815, 47816, 47817]; var BRIDGE_PROTOCOL = 1; var BRIDGE_HEADER = "X-TeXConverter-Bridge"; var HANDWRITING_CAPABILITY = "handwriting"; var SIGN_IN_CAPABILITY = "sign-in"; var USER_CODE_PATTERN = /^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/; function isCompatibleStatus(value) { if (typeof value !== "object" || value === null) return false; const v = value; return v.app === "texconverter" && v.protocol === BRIDGE_PROTOCOL && typeof v.version === "string" && Array.isArray(v.capabilities); } function bridgeOrigins(baseUrl) { return [new URL(baseUrl).origin]; } // desktop/src/bridge.ts var BridgeUnavailable = class extends Error { constructor(reason) { super(reason === "running" ? "Another copy of TeXConverter is already serving the Word add-in." : `The ports ${BRIDGE_PORTS.join(", ")} are all in use by other programs.`); this.reason = reason; this.name = "BridgeUnavailable"; } }; var FAILURE_STATUS = { unavailable: 404, busy: 409, unreadable: 422 }; var ALLOWED_REQUEST_HEADERS = [BRIDGE_HEADER.toLowerCase(), "content-type"]; function sendJson2(res, status, body, cors = {}) { res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", ...cors }); res.end(JSON.stringify(body)); } function corsFor(origin) { return { "Access-Control-Allow-Origin": origin, Vary: "Origin" }; } function preflightAllowed(method, requestHeaders) { if (method !== "GET" && method !== "POST") return false; const asked = (requestHeaders ?? "").split(",").map((h) => h.trim().toLowerCase()).filter((h) => h !== ""); return asked.every((h) => ALLOWED_REQUEST_HEADERS.includes(h)); } async function isOurBridge(port, fetchFn = fetch) { try { const res = await fetchFn(`http://127.0.0.1:${port}/v1/status`, { headers: { [BRIDGE_HEADER]: String(BRIDGE_PROTOCOL) }, signal: AbortSignal.timeout(1500) }); return res.ok && isCompatibleStatus(await res.json()); } catch { return false; } } async function startBridge(options) { const allowed = new Set(options.allowedOrigins); let port = 0; const status = () => ({ app: "texconverter", protocol: BRIDGE_PROTOCOL, version: options.version, capabilities: [...options.desk.available ? [HANDWRITING_CAPABILITY] : [], ...options.signIn ? [SIGN_IN_CAPABILITY] : []] }); let signingIn = false; async function signInWord(res, code, cors) { const signIn = options.signIn; if (code === null || !USER_CODE_PATTERN.test(code)) return sendJson2(res, 400, { error: "That isn't a sign-in code." }, cors); if (signingIn) return sendJson2(res, 409, { error: "TeXConverter is already asking about a sign-in. Answer it first." }, cors); signingIn = true; try { const email = await signIn.email(); if (email === null) return sendJson2(res, 409, { error: "The TeXConverter app isn't signed in any more. Sign in on the website instead." }, cors); const gone = new AbortController(); res.on("close", () => { if (!res.writableFinished) gone.abort(); }); if (!await signIn.confirm(email, gone.signal)) { if (!gone.signal.aborted) sendJson2(res, 403, { error: "The sign-in wasn't allowed on this computer." }, cors); return; } try { await signIn.approve(code); } catch (e) { return sendJson2(res, 502, { error: e instanceof Error ? e.message : String(e) }, cors); } sendJson2(res, 200, { ok: true }, cors); } finally { signingIn = false; } } async function handle(req, res) { const hosts = [`127.0.0.1:${port}`, `localhost:${port}`]; if (!hosts.includes(req.headers.host ?? "")) return sendJson2(res, 421, { error: "Wrong host." }); const origin = req.headers.origin; const fromAllowed = origin !== void 0 && allowed.has(origin); if (origin !== void 0 && !fromAllowed) return sendJson2(res, 403, { error: "This origin may not use TeXConverter." }); const cors = fromAllowed ? corsFor(origin) : {}; const path = new URL(req.url ?? "/", "http://127.0.0.1").pathname; if (req.method === "OPTIONS") { if (!fromAllowed || !preflightAllowed(req.headers["access-control-request-method"], req.headers["access-control-request-headers"])) { return sendJson2(res, 403, { error: "Not allowed." }); } res.writeHead(204, { ...cors, "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Headers": `${BRIDGE_HEADER}, Content-Type`, // Chrome's Private / Local Network Access: a public page reaching // loopback needs the server to say it expects that. "Access-Control-Allow-Private-Network": "true", "Access-Control-Max-Age": "600", "Cache-Control": "no-store" }); res.end(); return; } if (req.headers[BRIDGE_HEADER.toLowerCase()] === void 0) return sendJson2(res, 400, { error: `Missing ${BRIDGE_HEADER}.` }, cors); if (Number(req.headers["content-length"] ?? 0) > 0 || req.headers["transfer-encoding"] !== void 0) { return sendJson2(res, 413, { error: "The bridge takes no request body." }, cors); } switch (`${req.method} ${path}`) { case "GET /v1/status": return sendJson2(res, 200, status(), cors); case "POST /v1/handwrite": { if (!fromAllowed) return sendJson2(res, 403, { error: "Handwriting is for the TeXConverter add-in." }); const gone = new AbortController(); res.on("close", () => { if (!res.writableFinished) gone.abort(); }); try { const result = await options.desk.write(gone.signal); const body = result; if (!gone.signal.aborted) sendJson2(res, 200, body, cors); } catch (e) { if (e instanceof HandwritingError) return sendJson2(res, FAILURE_STATUS[e.reason], { error: e.message }, cors); throw e; } return; } case "GET /v1/account": { if (!fromAllowed || !options.signIn) return sendJson2(res, 403, { error: "The account is for the TeXConverter add-in." }, cors); const body = { email: await options.signIn.email() }; return sendJson2(res, 200, body, cors); } case "POST /v1/sign-in": { if (!fromAllowed || !options.signIn) return sendJson2(res, 403, { error: "Signing in is for the TeXConverter add-in." }, cors); return signInWord(res, new URL(req.url ?? "/", "http://127.0.0.1").searchParams.get("code"), cors); } default: return sendJson2(res, 404, { error: "Not found." }, cors); } } const server = createServer2((req, res) => { handle(req, res).catch((e) => { if (!res.headersSent) sendJson2(res, 500, { error: e instanceof Error ? e.message : String(e) }); else res.end(); }); }); server.headersTimeout = 1e4; server.requestTimeout = 15e3; let sawOurs = false; for (const candidate of options.ports ?? BRIDGE_PORTS) { const listened = await new Promise((resolve5, reject) => { const onError = (e) => { server.removeListener("listening", onListening); if (e.code === "EADDRINUSE" || e.code === "EACCES") resolve5(false); else reject(e); }; const onListening = () => { server.removeListener("error", onError); resolve5(true); }; server.once("error", onError); server.once("listening", onListening); server.listen(candidate, "127.0.0.1"); }); if (listened) { port = server.address().port; break; } if (await isOurBridge(candidate)) { sawOurs = true; break; } } if (port === 0) throw new BridgeUnavailable(sawOurs ? "running" : "ports-taken"); let resolveClosed; const closed = new Promise((r) => resolveClosed = r); server.on("close", () => resolveClosed()); return { port, closed, close: () => new Promise((resolve5) => { server.close(() => resolve5()); server.closeAllConnections(); }) }; } // desktop/src/confirm.ts init_define_L2W_CONFIG(); import { spawn as spawn3 } from "node:child_process"; var CONFIRM_SCRIPT = String.raw` Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.Application]::EnableVisualStyles() $owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; ShowInTaskbar = $false } $answer = [System.Windows.Forms.MessageBox]::Show($owner, $env:TEXCONVERTER_CONFIRM_TEXT, 'TeXConverter', 'YesNo', 'Question', 'Button2') $owner.Dispose() if ($answer -eq 'Yes') { [Console]::Out.Write('YES') } else { [Console]::Out.Write('NO') } `; function windowsConfirm(options = {}) { const run3 = options.spawnFn ?? ((command, args2, o) => spawn3(command, [...args2], o)); const timeoutMs = options.timeoutMs ?? 12e4; return (question, signal) => new Promise((resolve5) => { if (process.platform !== "win32" && options.spawnFn === void 0) return resolve5(false); const child = run3( "powershell.exe", ["-NoProfile", "-NonInteractive", "-STA", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encodeCommand(CONFIRM_SCRIPT)], { windowsHide: true, env: { ...process.env, TEXCONVERTER_CONFIRM_TEXT: question } } ); let stdout = ""; child.stdout?.on("data", (chunk) => stdout += chunk.toString("utf8")); const stop = () => void child.kill(); const timer = setTimeout(stop, timeoutMs); signal?.addEventListener("abort", stop, { once: true }); const done = (answer) => { clearTimeout(timer); signal?.removeEventListener("abort", stop); resolve5(answer); }; child.on("error", () => done(false)); child.on("close", () => done(!signal?.aborted && stdout.trim() === "YES")); }); } // src/shared/support.ts init_define_L2W_CONFIG(); var SUPPORT_EMAIL = "support@texconverter.com"; var SUPPORT_EMAIL_PATTERN = /^[^\s@<>"?&#]+@[^\s@<>"?&#]+\.[^\s@<>"?&#]+$/; // desktop/src/app.ts function freeOutputStem(dir, stem2, suffixes, exists2 = existsSync3) { for (let n = 1; ; n++) { const candidate = n === 1 ? stem2 : `${stem2} (${n})`; if (!suffixes.some((suffix) => exists2(join5(dir, candidate + suffix)))) return candidate; } } function detached(command, args2, verbatim = false) { spawn4(command, args2, { detached: true, stdio: "ignore", windowsHide: false, windowsVerbatimArguments: verbatim }).on("error", () => void 0).unref(); } function openPathWithSystem(path, reveal) { if (process.platform === "win32") { detached("explorer.exe", [reveal ? `/select,"${path}"` : `"${path}"`], true); } else if (process.platform === "darwin") { detached("open", reveal ? ["-R", path] : [path]); } else { detached("xdg-open", [reveal ? dirname4(path) : path]); } } function openUrl(url) { if (process.platform === "win32") detached("rundll32.exe", ["url.dll,FileProtocolHandler", url]); else if (process.platform === "darwin") detached("open", [url]); else detached("xdg-open", [url]); } var WINDOWLESS_ENV = "TEXCONVERTER_WINDOWLESS"; function appWindowBrowser(exists2 = existsSync3, env = process.env, platform = process.platform) { if (platform !== "win32") return null; const roots = [env["ProgramFiles(x86)"], env["ProgramFiles"], env["LOCALAPPDATA"]].filter((r) => typeof r === "string" && r !== ""); const candidates = [ ...roots.map((r) => join5(r, "Microsoft", "Edge", "Application", "msedge.exe")), ...roots.map((r) => join5(r, "Google", "Chrome", "Application", "chrome.exe")) ]; return candidates.find((path) => exists2(path)) ?? null; } function appWindowArgs(url, profile = null, size = [1200, 820]) { const own = profile === null ? [] : [`--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "--disable-sync", "--disable-features=msImplicitSignin"]; return [`--app=${url}`, `--window-size=${size[0]},${size[1]}`, ...own]; } function openAppWindow(url, options = {}) { const browser = options.browser === void 0 ? appWindowBrowser() : options.browser; if (!browser) return openUrl(url); if (options.taskbarExe !== void 0) tagAppWindow(options.taskbarExe, options.taskbarLauncher ?? options.taskbarExe); spawn4(browser, appWindowArgs(url, options.profile ?? null), { detached: true, stdio: "ignore" }).on("error", () => openUrl(url)).unref(); } function windowExe(exe, exists2 = existsSync3) { if (basename(exe).toLowerCase() !== HELPER_EXE_NAME.toLowerCase()) return exe; const main2 = join5(dirname4(exe), EXE_NAME); return exists2(main2) ? main2 : exe; } function launchWindowless(exe, args2, ipc = false) { const child = spawn4(exe, [...args2], { detached: true, windowsHide: true, stdio: ipc ? ["ignore", "ignore", "ignore", "ipc"] : "ignore", env: { ...process.env, [WINDOWLESS_ENV]: "1" } }); child.on("error", () => void 0); return child; } function relaunchWindowless(exe, timeoutMs = 3e4, args2 = []) { const child = launchWindowless(exe, args2, true); return new Promise((resolve5) => { let settled = false; const done = (code, error) => { if (settled) return; settled = true; clearTimeout(timer); if (child.connected) child.disconnect(); child.unref(); if (error === void 0) return resolve5(code); console.error(`texconverter: ${error}`); void waitForEnter("TeXConverter couldn't start.").then(() => resolve5(code)); }; const timer = setTimeout(() => done(0), timeoutMs); child.on("message", (reply) => "error" in reply ? done(1, reply.error) : done(0)); child.on("error", (e) => done(1, e.message)); child.on("exit", (code) => done(code ?? 1, "it stopped while starting.")); }); } function tellLauncher(reply) { const send2 = process.send?.bind(process); if (!send2 || !process.connected) return; send2(reply, () => { if (process.connected) process.disconnect?.(); }); } function documentsFolder() { if (process.platform === "win32") { const result = spawnSync3( "reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", "/v", "Personal"], { encoding: "utf8", windowsHide: true } ); const match = /Personal\s+REG_SZ\s+(.+)/.exec(result.stdout ?? ""); if (result.status === 0 && match) return match[1].trim(); } return join5(homedir2(), "Documents"); } function waitForEnter(message) { if (!process.stdin.isTTY) return Promise.resolve(); console.log(` ${message} Press Enter to close this window.`); return new Promise((resolve5) => { process.stdin.resume(); process.stdin.once("data", () => { process.stdin.pause(); resolve5(); }); }); } function windowsPaths() { if (process.platform !== "win32") return null; try { return installPaths(process.env); } catch { return null; } } function libraryFrom(serverUrl) { return async () => { const res = await fetch(`${serverUrl}/v1/library`, { signal: AbortSignal.timeout(8e3) }); if (!res.ok) throw new Error(`The licence server answered ${res.status}.`); return res.json(); }; } async function supportAddress(serverUrl) { if (!serverUrl) return SUPPORT_EMAIL; try { const res = await fetch(`${serverUrl}/v1/contact`, { signal: AbortSignal.timeout(5e3) }); const { supportEmail } = res.ok ? await res.json() : {}; return typeof supportEmail === "string" && SUPPORT_EMAIL_PATTERN.test(supportEmail) ? supportEmail : SUPPORT_EMAIL; } catch { return SUPPORT_EMAIL; } } function updaterFor(version2, isSea2, paths) { if (process.platform !== "win32" || !CONFIG.licenseServerUrl) return void 0; const exe = isSea2 ? process.execPath : null; return createUpdater({ serverUrl: CONFIG.licenseServerUrl, version: version2, build: APP_BUILD, exe, afterReplace: (replaced, label, helper) => { if (paths !== null && resolve3(replaced).toLowerCase() === resolve3(paths.exe).toLowerCase() && isInstalled(paths)) install(paths, label, replaced, void 0, void 0, helper); } }); } function uiStateFile(env = process.env, platform = process.platform) { return join5(dirname4(accountFile(env, platform)), "ui.json"); } function rememberedPort(file) { try { const port = JSON.parse(readFileSync2(file, "utf8")).port; return typeof port === "number" && Number.isInteger(port) && port >= 1024 && port <= 65535 ? port : 0; } catch { return 0; } } function rememberPort(file, port) { try { mkdirSync2(dirname4(file), { recursive: true }); writeFileSync3(file, JSON.stringify({ port })); } catch { } } async function startOnRememberedPort(options, file, start = startService) { const port = rememberedPort(file); let service; try { service = await start({ ...options, port }); } catch (e) { if (port === 0) throw e; service = await start({ ...options, port: 0 }); } const now = Number(new URL(service.origin).port); if (now !== port) rememberPort(file, now); return service; } function runningAppFile(env = process.env, platform = process.platform) { return join5(dirname4(accountFile(env, platform)), "running.json"); } function readRunningApp(file) { try { const url = new URL(String(JSON.parse(readFileSync2(file, "utf8")).url)); return url.protocol === "http:" && url.hostname === "127.0.0.1" && url.searchParams.has("t") ? url : null; } catch { return null; } } function recordRunningApp(file, url) { try { mkdirSync2(dirname4(file), { recursive: true }); writeFileSync3(file, JSON.stringify({ url })); } catch { } } function clearRunningApp(file, url) { try { if (readRunningApp(file)?.href === new URL(url).href) rmSync3(file, { force: true }); } catch { } } async function findRunningApp(file, fetchImpl = fetch) { const url = readRunningApp(file); if (url === null) return null; try { const res = await fetchImpl(`${url.origin}/api/status`, { headers: { "X-L2W-Token": url.searchParams.get("t") }, signal: AbortSignal.timeout(3e3) }); if (!res.ok) return null; const status = await res.json(); return typeof status.version === "string" ? url : null; } catch { return null; } } function handwritingDesk() { return createHandwritingDesk(void 0); } function signInQuestion(email) { return `Sign in TeXConverter for Word as ${email}? Word asked to use the account this computer's TeXConverter app is signed in to. Choose Yes only if you just asked for this in Word.`; } function bridgeSignIn(client = accountClient("desktop"), confirm = windowsConfirm()) { if (!client) return void 0; return { async email() { const status = await client.status({ refresh: "never" }); return status.state === "signed_out" ? null : status.email ?? null; }, confirm: (email, signal) => confirm(signInQuestion(email), signal), async approve(userCode) { await client.callAsDevice("POST", "/v1/devices/link/approve-from-desktop", { userCode }); } }; } function bridgeFor(version2, desk, signIn) { return startBridge({ version: version2, allowedOrigins: bridgeOrigins(CONFIG.baseUrl), desk, signIn }); } function bridgeUseful(desk, signIn) { return process.platform === "win32" && (desk.available || signIn !== void 0); } function backgroundHelper(paths, distribution = APP_DISTRIBUTION, exe = process.execPath, exists2 = existsSync3) { const helper = distribution === "store" ? join5(dirname4(exe), HELPER_EXE_NAME) : paths?.helperExe; return helper !== void 0 && exists2(helper) ? helper : null; } var STORE_MANAGED = "TeXConverter came from the Microsoft Store, so Windows looks after it: it's on the Start Menu, in each .docx and .tex file's Open with menu, and starts its helper at sign-in. Remove it in Settings \u2192 Apps."; async function serveWordAddIn(version2, desk, helper) { const signIn = bridgeSignIn(); if (!bridgeUseful(desk, signIn)) return void 0; if (helper !== null) { launchDetached(helper, ["helper"]); return void 0; } try { return await bridgeFor(version2, desk, signIn); } catch (e) { if (!(e instanceof BridgeUnavailable)) console.error(`The Word add-in can't reach this app: ${e instanceof Error ? e.message : String(e)}`); return void 0; } } async function runHelper(version2) { const desk = handwritingDesk(); const signIn = bridgeSignIn(); if (!bridgeUseful(desk, signIn)) return 0; let bridge; try { bridge = await bridgeFor(version2, desk, signIn); } catch (e) { if (e instanceof BridgeUnavailable) return 0; throw e; } const stop = () => void bridge.close(); process.once("SIGINT", stop); process.once("SIGTERM", stop); await bridge.closed; return 0; } async function runApp(version2, html, isSea2, account) { if (html === void 0) { console.error("texconverter: this build has no app window. Build it with `npm run build:cli` or `npm run build:desktop`."); return 1; } const paths = windowsPaths(); const store = APP_DISTRIBUTION === "store"; const taskbarExe = isSea2 && paths !== null ? !store && existsSync3(paths.exe) ? paths.exe : process.execPath : void 0; const windowOptions = { profile: paths?.windowProfile ?? null, taskbarExe, taskbarLauncher: taskbarExe !== void 0 && paths !== null && taskbarExe === paths.exe && existsSync3(paths.helperExe) ? paths.helperExe : taskbarExe }; const runningFile = runningAppFile(); const running = await findRunningApp(runningFile); if (running !== null) { if (!focusAppWindow()) openAppWindow(running.href, windowOptions); console.log("TeXConverter is already open; its window has been brought to the front."); tellLauncher({ ready: true }); return 0; } if (isSea2 && !store) removeOldExe(process.execPath); const desk = handwritingDesk(); let bridge = await serveWordAddIn(version2, desk, backgroundHelper(paths)); const shell = isSea2 && paths !== null && !store ? { // A newly downloaded build is not the installed build even when an // older TeXConverter is registered. Offer Install so its exe, // helper and existing desktop/Start Menu/taskbar shortcuts all get // replaced with the build that was just launched. installed: () => isInstalled(paths) && resolve3(process.execPath).toLowerCase() === resolve3(paths.exe).toLowerCase(), install: async () => { await bridge?.close(); bridge = void 0; return install(paths, version2, process.execPath); } } : void 0; const outputDir = join5(documentsFolder(), "TeXConverter"); const library = CONFIG.licenseServerUrl ? libraryFrom(CONFIG.licenseServerUrl) : void 0; const updater = store ? void 0 : updaterFor(version2, isSea2, paths); const updates = updater && { status: updater.status, check: updater.check, install: updater.install, downloadPage: `${CONFIG.baseUrl}/download.html#desktop` }; const build = { environment: CONFIG.environment, server: CONFIG.licenseServerUrl }; const help = { guide: `${CONFIG.baseUrl}/docs/desktop-and-cli.html`, latex: `${CONFIG.baseUrl}/docs/supported-latex.html`, faq: `${CONFIG.baseUrl}/docs/faq.html`, support: async () => `mailto:${await supportAddress(CONFIG.licenseServerUrl)}` }; const reader = CONFIG.licenseServerUrl ? await readerModels({ serverUrl: CONFIG.licenseServerUrl, publicKeys: CONFIG.licensePublicKeys, dir: readerDir(), runtime: ORT_VERSION }) : void 0; const service = await startOnRememberedPort({ html, version: version2, outputDir, openPath: openPathWithSystem, shell, account, openUrl, desk, library, updates, build, help, reader }, uiStateFile()); updater?.start(); console.log(`TeXConverter ${version2} is running, and should have opened in a window of its own.`); console.log(`If it did not, open this address: ${service.url} `); console.log(`Converted files are saved to ${outputDir}`); console.log(`Close this window, or the app's window, to quit.`); recordRunningApp(runningFile, service.url); openAppWindow(service.url, windowOptions); tellLauncher({ ready: true }); const stop = () => void service.close(); process.once("SIGINT", stop); process.once("SIGTERM", stop); await service.closed; clearRunningApp(runningFile, service.url); updater?.stop(); await bridge?.close(); if (updater?.status().state === "restarting") { console.log("Updated. Starting the new version\u2026"); if (process.env[WINDOWLESS_ENV]) launchWindowless(process.execPath, ["app"]).unref(); else detached(process.execPath, ["app"]); } return 0; } function runInstall(version2, isSea2, distribution = APP_DISTRIBUTION) { if (distribution === "store") { console.log(STORE_MANAGED); return 0; } if (!isSea2) { console.error("texconverter: install puts TeXConverter.exe on the right-click menu, so it has to be run from TeXConverter.exe. Build it with `npm run build:desktop`."); return 1; } const paths = windowsPaths(); if (paths === null) { console.error("texconverter: the right-click menu and Start Menu entry are Windows-only for now."); return 1; } try { for (const line3 of install(paths, version2, process.execPath)) console.log(` ${line3}`); console.log("\nDone. Right-click a .docx or .tex file to convert it, or open TeXConverter from the Start Menu or the desktop."); return 0; } catch (e) { console.error(`texconverter: ${e instanceof Error ? e.message : String(e)}`); return 1; } } function runUninstall(distribution = APP_DISTRIBUTION) { if (distribution === "store") { console.log(STORE_MANAGED); return 0; } const paths = windowsPaths(); if (paths === null) { console.error("texconverter: there is nothing installed to remove on this system."); return 1; } for (const line3 of uninstall(paths, process.execPath)) console.log(` ${line3}`); return 0; } // desktop/src/work.ts init_define_L2W_CONFIG(); // frontend/src/your-work.ts init_define_L2W_CONFIG(); var KIND_LABEL = { equation: "Equation", graph: "Graph", table: "Table", diagram: "Diagram", document: "Document" }; function creationEntry(c) { const diagram = c.task === "diagram"; const firstLine = c.source.split("\n").map((l) => l.trim()).find((l) => l && !l.startsWith("%") && !/^\\(begin|end)\{/.test(l)) ?? c.source.trim(); return { id: c.id, from: "creation", kind: diagram ? "diagram" : "equation", title: (firstLine.length > 80 ? `${firstLine.slice(0, 79)}\u2026` : firstLine) || (diagram ? "Diagram" : "Equation"), body: diagram ? { source: c.source } : { latex: c.source }, surface: "ai", at: c.updatedAt ?? c.createdAt, pinned: c.pinned }; } function workEntry(item) { return { id: item.id, from: "work", kind: item.kind, title: item.title || KIND_LABEL[item.kind], body: item.body, surface: item.surface, at: item.updatedAt, pinned: false }; } // desktop/src/work.ts async function accountWork(call) { const items = []; let page = await call("GET", "/v1/work?limit=500"); for (; ; ) { for (const item of page.items) { const at = items.findIndex((i) => i.id === item.id); if (at >= 0) items.splice(at, 1); if (!item.deleted) items.push(item); } if (!page.more) break; page = await call("GET", `/v1/work?since=${page.rev}&limit=500`); } const creations = (await call("GET", "/v1/ai/creations")).items; return [...items.map(workEntry), ...creations.map(creationEntry)].sort((a, b) => b.at - a.at); } var WHERE = { web: "website", word: "Word", desktop: "desktop app", ai: "Create with AI" }; function formatWorkList(entries, now = Date.now()) { if (entries.length === 0) return "Nothing in Your work yet. What you make on the website, in Word or in the app, signed in, is kept here."; const idWidth = Math.max(...entries.map((e) => e.id.length)); const lines = entries.map((e) => { const where = WHERE[e.surface] ?? e.surface; const kind = e.kind.padEnd(8); return `${e.id.padEnd(idWidth)} ${kind} ${e.pinned ? "* " : ""}${e.title} (${where}, ${ago(now - e.at)})`; }); return [...lines, "", 'Run "texconverter work get " to print one.'].join("\n"); } function ago(ms) { const minutes = Math.round(ms / 6e4); if (minutes < 1) return "just now"; if (minutes < 60) return `${minutes} min ago`; const hours = Math.round(minutes / 60); if (hours < 48) return `${hours} h ago`; return `${Math.round(hours / 24)} days ago`; } function workText(entry) { const body = entry.body ?? {}; if (entry.kind === "equation" && typeof body.latex === "string") return body.latex; if (entry.kind === "diagram" && typeof body.source === "string") return body.source; return JSON.stringify(entry.body, null, 2); } // desktop/src/cli.ts async function convertDocx(bytes, texPath, options = {}) { const result = await docxToTex(bytes, nodeZipCodec, options); const outDir = dirname5(texPath); const images = /* @__PURE__ */ new Map(); for (const [relative, content] of result.images) images.set(join6(outDir, relative), content); return { ...result, texPath, images }; } async function convertDocxFile(inputPath, options = {}) { const texPath = resolve4(options.output ?? swapExtension(inputPath, ".tex")); const report = await convertDocx(new Uint8Array(await readFile3(inputPath)), texPath, options); await mkdir4(dirname5(texPath), { recursive: true }); await writeFile4(texPath, report.tex, "utf8"); for (const [path, bytes] of report.images) { await mkdir4(dirname5(path), { recursive: true }); await writeFile4(path, bytes); } return report; } function swapExtension(path, extension) { const current = extname(path); return current === "" ? path + extension : path.slice(0, -current.length) + extension; } async function convertTexFile(inputPath, options = {}) { const source = await readFile3(inputPath, "utf8"); const base = dirname5(resolve4(inputPath)); const docxPath = resolve4(options.output ?? swapExtension(inputPath, ".docx")); const readRelative = (path) => { try { return readFileSync3(resolveWithin(base, path)); } catch { return null; } }; const bibSources = []; const explicit = options.bibFiles ?? bibliographyNames(source); for (const name of explicit) { const text = readRelative(name) ?? readRelative(`${name}.bib`); if (text !== null) bibSources.push(text.toString("utf8")); } const report = await convertTex(source, { ...options, bibSources, resolveInput: (path) => { const found = readRelative(path) ?? readRelative(`${path}.tex`); return found === null ? null : found.toString("utf8"); }, resolveImage: (path) => { const found = readRelative(path); return found === null ? null : new Uint8Array(found); } }); await mkdir4(dirname5(docxPath), { recursive: true }); await writeFile4(docxPath, report.bytes); return { ...report, docxPath }; } function resolveWithin(base, path) { const full = resolve4(base, path); if (full !== base && !full.startsWith(base + sep2)) { throw new Error(`"${path}" is outside the document's folder.`); } return full; } function directionFor(path) { const extension = extname(path).toLowerCase(); if (extension === ".docx") return "docx-to-tex"; if (extension === ".tex" || extension === ".latex") return "tex-to-docx"; return null; } function formatTexReport(report) { const lines = [ ` ${report.docxPath}`, ` ${report.blocks} blocks, ${report.equations} equations` + (report.images > 0 ? `, ${report.images} images` : "") + (report.citations > 0 ? `, ${report.citations} citations` : "") ]; for (const warning of report.warnings.slice(0, 10)) lines.push(` note: ${warning}`); if (report.warnings.length > 10) lines.push(` ...and ${report.warnings.length - 10} more notes`); return lines.join("\n"); } var DOCUMENT_CLASSES = /* @__PURE__ */ new Set(["article", "report", "book"]); function parseArgs(argv) { const args2 = [...argv]; const inputs = []; const options = {}; if (args2.length === 0) return { command: "help", inputs, options }; const first = args2[0]; if (first === "--help" || first === "-h" || first === "help") return { command: "help", inputs, options }; if (first === "--version" || first === "-v") return { command: "version", inputs, options }; if (first === "app" || first === "install" || first === "uninstall" || first === "login" || first === "logout" || first === "account" || first === "helper") { return { command: first, inputs, options }; } if (first === "open") { const rest = args2.slice(1); if (rest.length !== 1) return { command: "open", inputs, options, error: "open takes exactly one file." }; return { command: "open", inputs: rest, options }; } if (first === "work") { const rest = args2.slice(1); const sub = rest[0] ?? "list"; if (sub === "list" && rest.length <= 1) return { command: "work", inputs: ["list"], options }; if (sub === "get" && rest.length === 2) return { command: "work", inputs: rest, options }; return { command: "work", inputs, options, error: 'work takes "list", or "get" and an id from the list.' }; } let i = 0; if (first === "convert") i = 1; const need = (flag) => { const value = args2[++i]; if (value === void 0 || value.startsWith("-")) return null; return value; }; for (; i < args2.length; i++) { const arg = args2[i]; switch (arg) { case "-o": case "--output": { const value = need(arg); if (value === null) return { command: "convert", inputs, options, error: `${arg} needs a file path.` }; options.output = value; break; } case "--images": { const value = need(arg); if (value === null) return { command: "convert", inputs, options, error: "--images needs a folder name." }; options.imageFolder = value; break; } case "--image-start": { const value = need(arg); const n = Number(value); if (value === null || !Number.isInteger(n) || n < 0) { return { command: "convert", inputs, options, error: "--image-start needs a whole number." }; } options.imageStartIndex = n; break; } case "--class": { const value = need(arg); if (value === null || !DOCUMENT_CLASSES.has(value)) { return { command: "convert", inputs, options, error: `--class must be one of: ${[...DOCUMENT_CLASSES].join(", ")}.` }; } options.documentClass = value; break; } case "--font-size": { const value = need(arg); const n = Number(value); if (value === null || ![10, 11, 12].includes(n)) { return { command: "convert", inputs, options, error: "--font-size must be 10, 11 or 12." }; } options.fontSize = n; break; } case "--no-table-borders": options.tableBorders = false; break; case "--no-detect-latex": options.detectLatex = { enabled: false }; break; case "--bib": { const value = need(arg); if (value === null) return { command: "convert", inputs, options, error: "--bib needs a .bib file name." }; options.bibFiles = [...options.bibFiles ?? [], value]; break; } case "--bib-style": { const value = need(arg); if (value === null || !["plain", "unsrt", "ieee"].includes(value)) { return { command: "convert", inputs, options, error: "--bib-style must be plain, unsrt or ieee." }; } options.bibStyle = value; break; } case "--dollar": { const value = need(arg); if (value === null || !["smart", "always", "never"].includes(value)) { return { command: "convert", inputs, options, error: "--dollar must be smart, always or never." }; } options.detectLatex = { ...options.detectLatex, singleDollarMode: value }; break; } default: if (arg.startsWith("-")) return { command: "convert", inputs, options, error: `Unknown option "${arg}".` }; inputs.push(arg); } } if (inputs.length === 0) return { command: "convert", inputs, options, error: "No input file given." }; if (inputs.length > 1 && options.output !== void 0) { return { command: "convert", inputs, options, error: "--output names a single file, so it cannot be used with several inputs." }; } return { command: "convert", inputs, options }; } var USAGE = `texconverter \u2014 convert between Word documents and LaTeX Usage: texconverter convert [more ...] [options] texconverter app Open the TeXConverter window and drag files into it texconverter install Install TeXConverter: icons on the Start Menu and desktop, and "Convert to LaTeX" / "Convert to Word" on the right-click menu (Windows, TeXConverter.exe only) texconverter uninstall Remove them again texconverter helper Serve handwriting to the Word add-in, with no window (what install starts at sign-in; Windows only) texconverter login Sign in to your TeXConverter account on this computer texconverter logout Sign out on this computer texconverter account Show who is signed in here, and their plan texconverter work List Your work: what you made on the website, in Word, in the app and with AI, kept on your account texconverter work get Print one: an equation's LaTeX, a diagram's source, a graph or table as JSON The direction follows the file: a .docx becomes a .tex, a .tex becomes a .docx. Converting whole files is part of the Documents pack, in every paid plan. Options: -o, --output Where to write the result (default: alongside the input) --images Folder for extracted images (default: images) --image-start First number used in image filenames (default: 1) --class article | report | book (default: article) --font-size 10 | 11 | 12 (default: 11) --no-table-borders Never draw table rules, whatever the source did --no-detect-latex Leave $...$ typed in the text as literal text --dollar smart | always | never - how bare $...$ is read (default: smart, which skips things that look like currency) Converting a .tex: --bib A bibliography to draw references from (repeatable) --bib-style plain | unsrt | ieee (default: plain) --class, --font-size Ignored - the .tex states its own -h, --help Show this -v, --version Show the version Equations TeXConverter cannot represent are listed in the report and left out of the output, rather than the whole document being refused.`; function formatReport(report) { const lines = [ ` ${report.texPath}`, ` ${report.blocks} blocks, ${report.equationsConverted} equations converted` + (report.equationsFromText > 0 ? ` (${report.equationsFromText} recognised in the text)` : "") + (report.images.size > 0 ? `, ${report.images.size} images` : "") ]; if (report.equationsSkipped.length > 0) { lines.push(` ${report.equationsSkipped.length} equations could not be converted:`); for (const skip of report.equationsSkipped.slice(0, 10)) { lines.push(` equation ${skip.index}: ${skip.reason}`); } if (report.equationsSkipped.length > 10) { lines.push(` ...and ${report.equationsSkipped.length - 10} more`); } } if (report.skippedAsCurrency > 0) { lines.push( ` ${report.skippedAsCurrency} more expressions would convert with --dollar always; they were read as currency because they start with a digit` ); } if (report.rejectedText.length > 0) { lines.push(` ${report.rejectedText.length} spans looked like LaTeX but did not parse, and were left as text:`); for (const rejected of report.rejectedText.slice(0, 5)) { lines.push(` ${rejected.latex.length > 50 ? rejected.latex.slice(0, 49) + "\u2026" : rejected.latex}`); } if (report.rejectedText.length > 5) lines.push(` ...and ${report.rejectedText.length - 5} more`); } for (const warning of report.warnings.slice(0, 10)) lines.push(` note: ${warning}`); return lines.join("\n"); } async function documentsAllowed(client) { if (!client) return true; const refusal = documentsRefusal(await client.status()); if (refusal === null) return true; console.error(`texconverter: ${refusal}`); return false; } async function runLogin(client, open) { const current = await client.status(); if (current.state !== "signed_out") { console.log(`Already signed in as ${current.email}. Run "texconverter logout" first to switch accounts.`); return 0; } const link = await client.startLink(); console.log(`To sign in, open this page in your browser: ${link.verificationUrl} `); console.log(`Sign in there, and check it shows this code: ${link.userCode} `); open(link.verificationUrlComplete); console.log("Waiting for you to approve it... (Ctrl+C to stop)"); const abort = new AbortController(); const cancel = () => abort.abort(); process.once("SIGINT", cancel); let outcome; try { outcome = await client.waitForLink(link, { signal: abort.signal }); } finally { process.removeListener("SIGINT", cancel); } if (outcome === "denied") console.error("texconverter: the sign-in was declined on the website."); if (outcome === "expired") console.error('texconverter: the code expired before it was approved. Run "texconverter login" again.'); if (outcome === "cancelled") console.error("texconverter: stopped; not signed in."); if (outcome !== "approved") return 1; return runAccount(client); } async function runAccount(client) { const status = await client.status(); if (status.state === "signed_out") { console.log('Not signed in on this computer. Run "texconverter login".'); return 0; } console.log(`Signed in as ${status.email}${status.planName ? `, ${status.planName} plan` : ""}.`); if (status.state === "limited") console.log("Couldn't check the plan just now, so only free features are on until TeXConverter can reach its server."); console.log(documentsRefusal(status) ?? "Converting whole files: included."); return 0; } async function runWork(client, inputs) { if ((await client.status()).state === "signed_out") { console.error('texconverter: Your work is kept on your account. Run "texconverter login" first.'); return 1; } const entries = await accountWork((method, path) => client.callAsDevice(method, path)); if (inputs[0] !== "get") { console.log(formatWorkList(entries)); return 0; } const entry = entries.find((e) => e.id === inputs[1]); if (!entry) { console.error(`texconverter: there is nothing in Your work with the id ${inputs[1]}. Run "texconverter work" for the list.`); return 1; } console.log(workText(entry)); return 0; } async function runOpen(input, client) { let ok = true; let notes = 0; if (!await documentsAllowed(client)) { await waitForEnter("Open TeXConverter from the Start Menu to sign in, or to see your plan."); return 1; } try { const direction = directionFor(input); if (direction === null) throw new Error("not a .docx or a .tex, so there is no direction to convert it in."); const dir = dirname5(resolve4(input)); const stem2 = basename2(input, extname(input)); console.log(`${basename2(input)} ->`); if (direction === "docx-to-tex") { const out = freeOutputStem(dir, stem2, [".tex", "-images"]); const report = await convertDocxFile(input, { output: join6(dir, `${out}.tex`), imageFolder: `${out}-images` }); console.log(formatReport(report)); notes = report.warnings.length + report.equationsSkipped.length + report.rejectedText.length; openPathWithSystem(report.texPath, true); } else { const out = freeOutputStem(dir, stem2, [".docx"]); const report = await convertTexFile(input, { output: join6(dir, `${out}.docx`) }); console.log(formatTexReport(report)); notes = report.warnings.length; openPathWithSystem(report.docxPath, false); } } catch (e) { ok = false; console.error(`${basename2(input)}: ${e instanceof Error ? e.message : String(e)}`); } if (!ok || notes > 0) await waitForEnter(ok ? "Converted, with the notes above." : "Nothing was converted."); return ok ? 0 : 1; } async function main(argv, version2, host = {}) { const parsed = parseArgs(argv); if (parsed.command === "help") { console.log(USAGE); return 0; } if (parsed.command === "version") { console.log(version2); return 0; } if (parsed.error !== void 0) { console.error(`texconverter: ${parsed.error}`); console.error(`Run "texconverter --help" for usage.`); return 2; } const account = host.account ?? accountClient; if (parsed.command === "app") return runApp(version2, host.uiHtml, host.isSea === true, account("desktop")); if (parsed.command === "install") return runInstall(version2, host.isSea === true); if (parsed.command === "uninstall") return runUninstall(); if (parsed.command === "helper") return runHelper(version2); const client = account("cli"); if (parsed.command === "login" || parsed.command === "logout" || parsed.command === "account" || parsed.command === "work") { if (!client) { console.error("texconverter: this build of TeXConverter has no accounts; there is nothing to sign in to."); return 1; } try { if (parsed.command === "login") return await runLogin(client, host.openUrl ?? openUrl); if (parsed.command === "logout") { await client.signOut(); console.log("Signed out on this computer."); return 0; } if (parsed.command === "work") return await runWork(client, parsed.inputs); return await runAccount(client); } catch (e) { console.error(`texconverter: ${e instanceof Error ? e.message : String(e)}`); return 1; } } if (parsed.command === "open") return runOpen(parsed.inputs[0], client); if (!await documentsAllowed(client)) { console.error('Run "texconverter login" to sign in.'); return 1; } let failures = 0; for (const input of parsed.inputs) { const direction = directionFor(input); if (direction === null) { failures++; console.error(`${basename2(input)}: not a .docx or a .tex, so there is no direction to convert it in.`); continue; } try { console.log(`${basename2(input)} ->`); if (direction === "docx-to-tex") { console.log(formatReport(await convertDocxFile(input, parsed.options))); } else { console.log(formatTexReport(await convertTexFile(input, parsed.options))); } } catch (e) { failures++; console.error(`${basename2(input)}: ${e instanceof Error ? e.message : String(e)}`); } } return failures > 0 ? 1 : 0; } // desktop/src/bin.ts var version = true ? "0.6.0-alpha" : "0.0.0-dev"; var uiHtml = true ? '\n\n\n\n\nTeXConverter\n\n\n\n\n\n\n\n\n
\n \n\n
\n
\n

Convert files

\n

Whole documents, both ways: Word to LaTeX and LaTeX to Word, with their equations, graphs and diagrams.

\n
\n\n \n \n\n
\n \n \n
\n

Drop Word or LaTeX files here

\n

Or a whole folder: a .tex is converted together with the chapters, figures and .bib files beside it. Several files convert in one go.

\n
\n \n \n
\n \n \n
\n\n
\n Options\n
\n \n \n
\n
\n\n \n
    \n
    \n\n \n \n\n \n \n\n \n\n \n\n \n\n \n \n\n \n \n\n \n\n
    \n \n
    \n
    \n
    \n\n\n\n' : void 0; var sea = isSea(); setDefaultCACertificates([...getCACertificates("default"), ...getCACertificates("system")]); var args = process.argv.slice(2); var doubleClicked = sea && args.length === 0; var run2 = doubleClicked && process.platform === "win32" && !process.env[WINDOWLESS_ENV] ? relaunchWindowless(windowExe(process.execPath)) : main(doubleClicked ? ["app"] : args, version, { uiHtml, isSea: sea }); run2.then((code) => { process.exitCode = code; }).catch((e) => { const message = e instanceof Error ? e.message : String(e); console.error(`texconverter: ${message}`); tellLauncher({ error: message }); process.exitCode = 1; });