feat(ui): finalize E-TIB modernization with footer redesign, video optimization, and TS fixes

Former-commit-id: 67ac02c8404cc66893fdf97308574701cca6000c
This commit is contained in:
2026-05-07 10:43:20 +02:00
parent f2fdea96ec
commit 5439df72ea
3712 changed files with 932332 additions and 1867 deletions

View File

@@ -0,0 +1,217 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var picocolors = require('picocolors');
var jsTokens = require('js-tokens');
var helperValidatorIdentifier = require('@babel/helper-validator-identifier');
function isColorSupported() {
return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported
);
}
const compose = (f, g) => v => f(g(v));
function buildDefs(colors) {
return {
keyword: colors.cyan,
capitalized: colors.yellow,
jsxIdentifier: colors.yellow,
punctuator: colors.yellow,
number: colors.magenta,
string: colors.green,
regex: colors.magenta,
comment: colors.gray,
invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
gutter: colors.gray,
marker: compose(colors.red, colors.bold),
message: compose(colors.red, colors.bold),
reset: colors.reset
};
}
const defsOn = buildDefs(picocolors.createColors(true));
const defsOff = buildDefs(picocolors.createColors(false));
function getDefs(enabled) {
return enabled ? defsOn : defsOff;
}
const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
const BRACKET = /^[()[\]{}]$/;
let tokenize;
const JSX_TAG = /^[a-z][\w-]*$/i;
const getTokenType = function (token, offset, text) {
if (token.type === "name") {
const tokenValue = token.value;
if (helperValidatorIdentifier.isKeyword(tokenValue) || helperValidatorIdentifier.isStrictReservedWord(tokenValue, true) || sometimesKeywords.has(tokenValue)) {
return "keyword";
}
if (JSX_TAG.test(tokenValue) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
return "jsxIdentifier";
}
const firstChar = String.fromCodePoint(tokenValue.codePointAt(0));
if (firstChar !== firstChar.toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
};
tokenize = function* (text) {
let match;
while (match = jsTokens.default.exec(text)) {
const token = jsTokens.matchToToken(match);
yield {
type: getTokenType(token, match.index, text),
value: token.value
};
}
};
function highlight(text) {
if (text === "") return "";
const defs = getDefs(true);
let highlighted = "";
for (const {
type,
value
} of tokenize(text)) {
if (type in defs) {
highlighted += value.split(NEWLINE$1).map(str => defs[type](str)).join("\n");
} else {
highlighted += value;
}
}
return highlighted;
}
let deprecationWarningShown = false;
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts, startLineBaseZero) {
const startLoc = Object.assign({
column: 0,
line: -1
}, loc.start);
const endLoc = Object.assign({}, startLoc, loc.end);
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line - startLineBaseZero;
const startColumn = startLoc.column;
const endLine = endLoc.line - startLineBaseZero;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start,
end,
markerLines
};
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
const startLineBaseZero = (opts.startLine || 1) - 1;
const defs = getDefs(shouldHighlight);
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts, startLineBaseZero);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end + startLineBaseZero).length;
const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number + startLineBaseZero}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} |`;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + defs.message(opts.message);
}
}
return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
} else {
return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (shouldHighlight) {
return defs.reset(frame);
} else {
return frame;
}
}
function index (rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
const location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}
exports.codeFrameColumns = codeFrameColumns;
exports.default = index;
exports.highlight = highlight;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,32 @@
{
"name": "@babel/code-frame",
"version": "7.29.0",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-code-frame",
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-code-frame"
},
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-validator-identifier": "^7.28.5",
"js-tokens": "^4.0.0",
"picocolors": "^1.1.1"
},
"devDependencies": {
"charcodes": "^0.2.0",
"import-meta-resolve": "^4.1.0",
"strip-ansi": "^4.0.0"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}

View File

@@ -0,0 +1 @@
../../../@babel+helper-validator-identifier@7.28.5/node_modules/@babel/helper-validator-identifier

View File

@@ -0,0 +1 @@
../../js-tokens@4.0.0/node_modules/js-tokens

View File

@@ -0,0 +1 @@
../../picocolors@1.1.1/node_modules/picocolors

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isIdentifierChar = isIdentifierChar;
exports.isIdentifierName = isIdentifierName;
exports.isIdentifierStart = isIdentifierStart;
let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088f\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5c\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdc-\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7dc\ua7f1-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
let nonASCIIidentifierChars = "\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1add\u1ae0-\u1aeb\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65";
const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
function isInAstralSet(code, set) {
let pos = 0x10000;
for (let i = 0, length = set.length; i < length; i += 2) {
pos += set[i];
if (pos > code) return false;
pos += set[i + 1];
if (pos >= code) return true;
}
return false;
}
function isIdentifierStart(code) {
if (code < 65) return code === 36;
if (code <= 90) return true;
if (code < 97) return code === 95;
if (code <= 122) return true;
if (code <= 0xffff) {
return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
}
return isInAstralSet(code, astralIdentifierStartCodes);
}
function isIdentifierChar(code) {
if (code < 48) return code === 36;
if (code < 58) return true;
if (code < 65) return false;
if (code <= 90) return true;
if (code < 97) return code === 95;
if (code <= 122) return true;
if (code <= 0xffff) {
return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
}
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
}
function isIdentifierName(name) {
let isFirst = true;
for (let i = 0; i < name.length; i++) {
let cp = name.charCodeAt(i);
if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {
const trail = name.charCodeAt(++i);
if ((trail & 0xfc00) === 0xdc00) {
cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
}
}
if (isFirst) {
isFirst = false;
if (!isIdentifierStart(cp)) {
return false;
}
} else if (!isIdentifierChar(cp)) {
return false;
}
}
return !isFirst;
}
//# sourceMappingURL=identifier.js.map

View File

@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isIdentifierChar", {
enumerable: true,
get: function () {
return _identifier.isIdentifierChar;
}
});
Object.defineProperty(exports, "isIdentifierName", {
enumerable: true,
get: function () {
return _identifier.isIdentifierName;
}
});
Object.defineProperty(exports, "isIdentifierStart", {
enumerable: true,
get: function () {
return _identifier.isIdentifierStart;
}
});
Object.defineProperty(exports, "isKeyword", {
enumerable: true,
get: function () {
return _keyword.isKeyword;
}
});
Object.defineProperty(exports, "isReservedWord", {
enumerable: true,
get: function () {
return _keyword.isReservedWord;
}
});
Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictBindOnlyReservedWord;
}
});
Object.defineProperty(exports, "isStrictBindReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictBindReservedWord;
}
});
Object.defineProperty(exports, "isStrictReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictReservedWord;
}
});
var _identifier = require("./identifier.js");
var _keyword = require("./keyword.js");
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isKeyword = isKeyword;
exports.isReservedWord = isReservedWord;
exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
exports.isStrictBindReservedWord = isStrictBindReservedWord;
exports.isStrictReservedWord = isStrictReservedWord;
const reservedWords = {
keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
strictBind: ["eval", "arguments"]
};
const keywords = new Set(reservedWords.keyword);
const reservedWordsStrictSet = new Set(reservedWords.strict);
const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
function isReservedWord(word, inModule) {
return inModule && word === "await" || word === "enum";
}
function isStrictReservedWord(word, inModule) {
return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
}
function isStrictBindOnlyReservedWord(word) {
return reservedWordsStrictBindSet.has(word);
}
function isStrictBindReservedWord(word, inModule) {
return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
}
function isKeyword(word) {
return keywords.has(word);
}
//# sourceMappingURL=keyword.js.map

View File

@@ -0,0 +1,31 @@
{
"name": "@babel/helper-validator-identifier",
"version": "7.28.5",
"description": "Validate identifier/keywords name",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-validator-identifier"
},
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "./lib/index.js",
"exports": {
".": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
},
"./package.json": "./package.json"
},
"devDependencies": {
"@unicode/unicode-17.0.0": "^1.6.10",
"charcodes": "^0.2.0"
},
"engines": {
"node": ">=6.9.0"
},
"author": "The Babel Team (https://babel.dev/team)",
"type": "commonjs"
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
module.exports = require("./color.cjs").default;

View File

@@ -0,0 +1,58 @@
{
"name": "@img/colour",
"version": "1.1.0",
"description": "The ESM-only 'color' package made compatible for use with CommonJS runtimes",
"license": "MIT",
"main": "index.cjs",
"types": "index.d.ts",
"exports": {
".": {
"types": "./index.d.ts",
"require": "./index.cjs",
"default": "./index.cjs"
},
"./package.json": "./package.json"
},
"authors": [
"Heather Arthur <fayearthur@gmail.com>",
"Josh Junon <josh@junon.me>",
"Maxime Thirouin",
"Dyma Ywanov <dfcreative@gmail.com>",
"LitoMore (https://github.com/LitoMore)"
],
"engines": {
"node": ">=18"
},
"files": [
"color.cjs",
"index.d.ts"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/lovell/colour.git"
},
"type": "commonjs",
"keywords": [
"color",
"colour",
"cjs",
"commonjs"
],
"scripts": {
"build:cjs": "esbuild node_modules/color/index.js --bundle --platform=node --outfile=color.cjs",
"build:dts": "dts-bundle-generator ./dts-src.ts -o index.d.ts --project tsconfig.build.json --external-inlines color --external-inlines color-convert --export-referenced-types=false",
"build": "npm run build:cjs && npm run build:dts",
"test": "node --test"
},
"devDependencies": {
"color": "5.0.3",
"color-convert": "3.1.3",
"color-name": "2.1.0",
"color-string": "2.1.4",
"dts-bundle-generator": "^9.5.1",
"esbuild": "^0.27.3"
}
}

View File

@@ -0,0 +1,40 @@
{
"name": "@img/sharp-darwin-arm64",
"version": "0.34.5",
"description": "Prebuilt sharp for use with macOS 64-bit ARM",
"author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com",
"repository": {
"type": "git",
"url": "git+https://github.com/lovell/sharp.git",
"directory": "npm/darwin-arm64"
},
"license": "Apache-2.0",
"funding": {
"url": "https://opencollective.com/libvips"
},
"preferUnplugged": true,
"optionalDependencies": {
"@img/sharp-libvips-darwin-arm64": "1.2.4"
},
"files": [
"lib"
],
"publishConfig": {
"access": "public"
},
"type": "commonjs",
"exports": {
"./sharp.node": "./lib/sharp-darwin-arm64.node",
"./package": "./package.json"
},
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"os": [
"darwin"
],
"cpu": [
"arm64"
]
}

View File

@@ -0,0 +1 @@
../../../@img+sharp-libvips-darwin-arm64@1.2.4/node_modules/@img/sharp-libvips-darwin-arm64

View File

@@ -0,0 +1,46 @@
# `@img/sharp-libvips-darwin-arm64`
Prebuilt libvips and dependencies for use with sharp on macOS 64-bit ARM.
## Licensing
This software contains third-party libraries
used under the terms of the following licences:
| Library | Used under the terms of |
|---------------|-----------------------------------------------------------------------------------------------------------|
| aom | BSD 2-Clause + [Alliance for Open Media Patent License 1.0](https://aomedia.org/license/patent-license/) |
| cairo | Mozilla Public License 2.0 |
| cgif | MIT Licence |
| expat | MIT Licence |
| fontconfig | [fontconfig Licence](https://gitlab.freedesktop.org/fontconfig/fontconfig/blob/main/COPYING) (BSD-like) |
| freetype | [freetype Licence](https://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/FTL.TXT) (BSD-like) |
| fribidi | LGPLv3 |
| glib | LGPLv3 |
| harfbuzz | MIT Licence |
| highway | Apache-2.0 License, BSD 3-Clause |
| lcms | MIT Licence |
| libarchive | BSD 2-Clause |
| libexif | LGPLv3 |
| libffi | MIT Licence |
| libheif | LGPLv3 |
| libimagequant | [BSD 2-Clause](https://github.com/lovell/libimagequant/blob/main/COPYRIGHT) |
| libnsgif | MIT Licence |
| libpng | [libpng License](https://github.com/pnggroup/libpng/blob/master/LICENSE) |
| librsvg | LGPLv3 |
| libspng | [BSD 2-Clause, libpng License](https://github.com/randy408/libspng/blob/master/LICENSE) |
| libtiff | [libtiff License](https://gitlab.com/libtiff/libtiff/blob/master/LICENSE.md) (BSD-like) |
| libvips | LGPLv3 |
| libwebp | New BSD License |
| libxml2 | MIT Licence |
| mozjpeg | [zlib License, IJG License, BSD-3-Clause](https://github.com/mozilla/mozjpeg/blob/master/LICENSE.md) |
| pango | LGPLv3 |
| pixman | MIT Licence |
| proxy-libintl | LGPLv3 |
| zlib-ng | [zlib Licence](https://github.com/zlib-ng/zlib-ng/blob/develop/LICENSE.md) |
Use of libraries under the terms of the LGPLv3 is via the
"any later version" clause of the LGPLv2 or LGPLv2.1.
Please report any errors or omissions via
https://github.com/lovell/sharp-libvips/issues/new

View File

@@ -0,0 +1,220 @@
/* glibconfig.h
*
* This is a generated file. Please modify 'glibconfig.h.in'
*/
#ifndef __GLIBCONFIG_H__
#define __GLIBCONFIG_H__
#include <glib/gmacros.h>
#include <limits.h>
#include <float.h>
#define GLIB_HAVE_ALLOCA_H
#define GLIB_STATIC_COMPILATION 1
#define GOBJECT_STATIC_COMPILATION 1
#define GIO_STATIC_COMPILATION 1
#define GMODULE_STATIC_COMPILATION 1
#define GI_STATIC_COMPILATION 1
#define G_INTL_STATIC_COMPILATION 1
#define FFI_STATIC_BUILD 1
/* Specifies that GLib's g_print*() functions wrap the
* system printf functions. This is useful to know, for example,
* when using glibc's register_printf_function().
*/
#define GLIB_USING_SYSTEM_PRINTF
G_BEGIN_DECLS
#define G_MINFLOAT FLT_MIN
#define G_MAXFLOAT FLT_MAX
#define G_MINDOUBLE DBL_MIN
#define G_MAXDOUBLE DBL_MAX
#define G_MINSHORT SHRT_MIN
#define G_MAXSHORT SHRT_MAX
#define G_MAXUSHORT USHRT_MAX
#define G_MININT INT_MIN
#define G_MAXINT INT_MAX
#define G_MAXUINT UINT_MAX
#define G_MINLONG LONG_MIN
#define G_MAXLONG LONG_MAX
#define G_MAXULONG ULONG_MAX
typedef signed char gint8;
typedef unsigned char guint8;
typedef signed short gint16;
typedef unsigned short guint16;
#define G_GINT16_MODIFIER "h"
#define G_GINT16_FORMAT "hi"
#define G_GUINT16_FORMAT "hu"
typedef signed int gint32;
typedef unsigned int guint32;
#define G_GINT32_MODIFIER ""
#define G_GINT32_FORMAT "i"
#define G_GUINT32_FORMAT "u"
#define G_HAVE_GINT64 1 /* deprecated, always true */
G_GNUC_EXTENSION typedef signed long long gint64;
G_GNUC_EXTENSION typedef unsigned long long guint64;
#define G_GINT64_CONSTANT(val) (G_GNUC_EXTENSION (val##LL))
#define G_GUINT64_CONSTANT(val) (G_GNUC_EXTENSION (val##ULL))
#define G_GINT64_MODIFIER "ll"
#define G_GINT64_FORMAT "lli"
#define G_GUINT64_FORMAT "llu"
#define GLIB_SIZEOF_VOID_P 8
#define GLIB_SIZEOF_LONG 8
#define GLIB_SIZEOF_SIZE_T 8
#define GLIB_SIZEOF_SSIZE_T 8
typedef signed long gssize;
typedef unsigned long gsize;
#define G_GSIZE_MODIFIER "l"
#define G_GSSIZE_MODIFIER "l"
#define G_GSIZE_FORMAT "lu"
#define G_GSSIZE_FORMAT "li"
#define G_MAXSIZE G_MAXULONG
#define G_MINSSIZE G_MINLONG
#define G_MAXSSIZE G_MAXLONG
typedef gint64 goffset;
#define G_MINOFFSET G_MININT64
#define G_MAXOFFSET G_MAXINT64
#define G_GOFFSET_MODIFIER G_GINT64_MODIFIER
#define G_GOFFSET_FORMAT G_GINT64_FORMAT
#define G_GOFFSET_CONSTANT(val) G_GINT64_CONSTANT(val)
#define G_POLLFD_FORMAT "%d"
#define GPOINTER_TO_INT(p) ((gint) (glong) (p))
#define GPOINTER_TO_UINT(p) ((guint) (gulong) (p))
#define GINT_TO_POINTER(i) ((gpointer) (glong) (i))
#define GUINT_TO_POINTER(u) ((gpointer) (gulong) (u))
typedef signed long gintptr;
typedef unsigned long guintptr;
#define G_GINTPTR_MODIFIER "l"
#define G_GINTPTR_FORMAT "li"
#define G_GUINTPTR_FORMAT "lu"
#define GLIB_MAJOR_VERSION 2
#define GLIB_MINOR_VERSION 86
#define GLIB_MICRO_VERSION 1
#define G_OS_UNIX
#define G_VA_COPY va_copy
#define G_HAVE_ISO_VARARGS 1
/* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi
* is passed ISO vararg support is turned off, and there is no work
* around to turn it on, so we unconditionally turn it off.
*/
#if __GNUC__ == 2 && __GNUC_MINOR__ == 95
# undef G_HAVE_ISO_VARARGS
#endif
#define G_HAVE_GROWING_STACK 0
#ifndef _MSC_VER
# define G_HAVE_GNUC_VARARGS 1
#endif
#if defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590)
#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))
#elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550)
#define G_GNUC_INTERNAL __hidden
#elif defined (__GNUC__) && defined (G_HAVE_GNUC_VISIBILITY)
#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))
#else
#define G_GNUC_INTERNAL
#endif
#define G_THREADS_ENABLED
#define G_THREADS_IMPL_POSIX
#define G_ATOMIC_LOCK_FREE
#define GINT16_TO_LE(val) ((gint16) (val))
#define GUINT16_TO_LE(val) ((guint16) (val))
#define GINT16_TO_BE(val) ((gint16) GUINT16_SWAP_LE_BE (val))
#define GUINT16_TO_BE(val) (GUINT16_SWAP_LE_BE (val))
#define GINT32_TO_LE(val) ((gint32) (val))
#define GUINT32_TO_LE(val) ((guint32) (val))
#define GINT32_TO_BE(val) ((gint32) GUINT32_SWAP_LE_BE (val))
#define GUINT32_TO_BE(val) (GUINT32_SWAP_LE_BE (val))
#define GINT64_TO_LE(val) ((gint64) (val))
#define GUINT64_TO_LE(val) ((guint64) (val))
#define GINT64_TO_BE(val) ((gint64) GUINT64_SWAP_LE_BE (val))
#define GUINT64_TO_BE(val) (GUINT64_SWAP_LE_BE (val))
#define GLONG_TO_LE(val) ((glong) GINT64_TO_LE (val))
#define GULONG_TO_LE(val) ((gulong) GUINT64_TO_LE (val))
#define GLONG_TO_BE(val) ((glong) GINT64_TO_BE (val))
#define GULONG_TO_BE(val) ((gulong) GUINT64_TO_BE (val))
#define GINT_TO_LE(val) ((gint) GINT32_TO_LE (val))
#define GUINT_TO_LE(val) ((guint) GUINT32_TO_LE (val))
#define GINT_TO_BE(val) ((gint) GINT32_TO_BE (val))
#define GUINT_TO_BE(val) ((guint) GUINT32_TO_BE (val))
#define GSIZE_TO_LE(val) ((gsize) GUINT64_TO_LE (val))
#define GSSIZE_TO_LE(val) ((gssize) GINT64_TO_LE (val))
#define GSIZE_TO_BE(val) ((gsize) GUINT64_TO_BE (val))
#define GSSIZE_TO_BE(val) ((gssize) GINT64_TO_BE (val))
#define G_BYTE_ORDER G_LITTLE_ENDIAN
#define GLIB_SYSDEF_POLLIN =1
#define GLIB_SYSDEF_POLLOUT =4
#define GLIB_SYSDEF_POLLPRI =2
#define GLIB_SYSDEF_POLLHUP =16
#define GLIB_SYSDEF_POLLERR =8
#define GLIB_SYSDEF_POLLNVAL =32
/* No way to disable deprecation warnings for macros, so only emit deprecation
* warnings on platforms where usage of this macro is broken */
#if defined(__APPLE__) || defined(_MSC_VER) || defined(__CYGWIN__)
#define G_MODULE_SUFFIX "so" GLIB_DEPRECATED_MACRO_IN_2_76
#else
#define G_MODULE_SUFFIX "so"
#endif
typedef int GPid;
#define G_PID_FORMAT "i"
#define GLIB_SYSDEF_AF_UNIX 1
#define GLIB_SYSDEF_AF_INET 2
#define GLIB_SYSDEF_AF_INET6 30
#define GLIB_SYSDEF_MSG_OOB 1
#define GLIB_SYSDEF_MSG_PEEK 2
#define GLIB_SYSDEF_MSG_DONTROUTE 4
#define G_DIR_SEPARATOR '/'
#define G_DIR_SEPARATOR_S "/"
#define G_SEARCHPATH_SEPARATOR ':'
#define G_SEARCHPATH_SEPARATOR_S ":"
#undef G_HAVE_FREE_SIZED
G_END_DECLS
#endif /* __GLIBCONFIG_H__ */

View File

@@ -0,0 +1 @@
module.exports = __dirname;

View File

@@ -0,0 +1,36 @@
{
"name": "@img/sharp-libvips-darwin-arm64",
"version": "1.2.4",
"description": "Prebuilt libvips and dependencies for use with sharp on macOS 64-bit ARM",
"author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com",
"repository": {
"type": "git",
"url": "git+https://github.com/lovell/sharp-libvips.git",
"directory": "npm/darwin-arm64"
},
"license": "LGPL-3.0-or-later",
"funding": {
"url": "https://opencollective.com/libvips"
},
"preferUnplugged": true,
"publishConfig": {
"access": "public"
},
"files": [
"lib",
"versions.json"
],
"type": "commonjs",
"exports": {
"./lib": "./lib/index.js",
"./package": "./package.json",
"./versions": "./versions.json"
},
"os": [
"darwin"
],
"cpu": [
"arm64"
]
}

View File

@@ -0,0 +1,30 @@
{
"aom": "3.13.1",
"archive": "3.8.2",
"cairo": "1.18.4",
"cgif": "0.5.0",
"exif": "0.6.25",
"expat": "2.7.3",
"ffi": "3.5.2",
"fontconfig": "2.17.1",
"freetype": "2.14.1",
"fribidi": "1.0.16",
"glib": "2.86.1",
"harfbuzz": "12.1.0",
"heif": "1.20.2",
"highway": "1.3.0",
"imagequant": "2.4.1",
"lcms": "2.17",
"mozjpeg": "0826579",
"pango": "1.57.0",
"pixman": "0.46.4",
"png": "1.6.50",
"proxy-libintl": "0.5",
"rsvg": "2.61.2",
"spng": "0.7.4",
"tiff": "4.7.1",
"vips": "8.17.3",
"webp": "1.6.0",
"xml2": "2.15.1",
"zlib-ng": "2.2.5"
}

View File

@@ -0,0 +1,16 @@
/**
* @typedef {import('hast-util-to-jsx-runtime').Fragment} Fragment
* @typedef {import('hast-util-to-jsx-runtime').Jsx} Jsx
* @typedef {import('hast-util-to-jsx-runtime').JsxDev} JsxDev
* @typedef {import('./lib/util/resolve-evaluate-options.js').UseMdxComponents} UseMdxComponents
* @typedef {import('./lib/compile.js').CompileOptions} CompileOptions
* @typedef {import('./lib/core.js').ProcessorOptions} ProcessorOptions
* @typedef {import('./lib/util/resolve-evaluate-options.js').EvaluateOptions} EvaluateOptions
* @typedef {import('./lib/util/resolve-evaluate-options.js').RunOptions} RunOptions
*/
export {compile, compileSync} from './lib/compile.js'
export {createProcessor} from './lib/core.js'
export {evaluate, evaluateSync} from './lib/evaluate.js'
export {nodeTypes} from './lib/node-types.js'
export {run, runSync} from './lib/run.js'

View File

@@ -0,0 +1,57 @@
/**
* @import {Compatible, VFile} from 'vfile'
* @import {ProcessorOptions} from './core.js'
*/
/**
* @typedef {Omit<ProcessorOptions, 'format'>} CoreProcessorOptions
* Core configuration.
*
* @typedef ExtraOptions
* Extra configuration.
* @property {'detect' | 'md' | 'mdx' | null | undefined} [format='detect']
* Format of `file` (default: `'detect'`).
*
* @typedef {CoreProcessorOptions & ExtraOptions} CompileOptions
* Configuration for `compile`.
*
* `CompileOptions` is the same as `ProcessorOptions` with the exception that
* the `format` option supports a `'detect'` value, which is the default.
* The `'detect'` format means to use `'md'` for files with an extension in
* `mdExtensions` and `'mdx'` otherwise.
*/
import {resolveFileAndOptions} from './util/resolve-file-and-options.js'
import {createProcessor} from './core.js'
/**
* Compile MDX to JS.
*
* @param {Readonly<Compatible>} vfileCompatible
* MDX document to parse.
* @param {Readonly<CompileOptions> | null | undefined} [compileOptions]
* Compile configuration (optional).
* @return {Promise<VFile>}
* Promise to compiled file.
*/
export function compile(vfileCompatible, compileOptions) {
const {file, options} = resolveFileAndOptions(vfileCompatible, compileOptions)
return createProcessor(options).process(file)
}
/**
* Synchronously compile MDX to JS.
*
* When possible please use the async `compile`.
*
* @param {Readonly<Compatible>} vfileCompatible
* MDX document to parse.
* @param {Readonly<CompileOptions> | null | undefined} [compileOptions]
* Compile configuration (optional).
* @return {VFile}
* Compiled file.
*/
export function compileSync(vfileCompatible, compileOptions) {
const {file, options} = resolveFileAndOptions(vfileCompatible, compileOptions)
return createProcessor(options).processSync(file)
}

View File

@@ -0,0 +1,237 @@
/**
* @import {Program} from 'estree-jsx'
* @import {Root} from 'mdast'
* @import {Options as RehypeRecmaOptions} from 'rehype-recma'
* @import {Options as RemarkRehypeOptions} from 'remark-rehype'
* @import {SourceMapGenerator} from 'source-map'
* @import {PluggableList, Processor} from 'unified'
*/
/**
* @typedef ProcessorOptions
* Configuration for `createProcessor`.
* @property {typeof SourceMapGenerator | null | undefined} [SourceMapGenerator]
* Add a source map (object form) as the `map` field on the resulting file
* (optional).
* @property {URL | string | null | undefined} [baseUrl]
* Use this URL as `import.meta.url` and resolve `import` and `export … from`
* relative to it (optional, example: `import.meta.url`).
* @property {boolean | null | undefined} [development=false]
* Whether to add extra info to error messages in generated code and use the
* development automatic JSX runtime (`Fragment` and `jsxDEV` from
* `/jsx-dev-runtime`) (default: `false`);
* when using the webpack loader (`@mdx-js/loader`) or the Rollup integration
* (`@mdx-js/rollup`) through Vite, this is automatically inferred from how
* you configure those tools.
* @property {RehypeRecmaOptions['elementAttributeNameCase']} [elementAttributeNameCase='react']
* Casing to use for attribute names (default: `'react'`);
* HTML casing is for example `class`, `stroke-linecap`, `xml:lang`;
* React casing is for example `className`, `strokeLinecap`, `xmlLang`;
* for JSX components written in MDX, the author has to be aware of which
* framework they use and write code accordingly;
* for AST nodes generated by this project, this option configures it
* @property {'md' | 'mdx' | null | undefined} [format='mdx']
* format of the file (default: `'mdx'`);
* `'md'` means treat as markdown and `'mdx'` means treat as MDX.
* @property {boolean | null | undefined} [jsx=false]
* Whether to keep JSX (default: `false`);
* the default is to compile JSX away so that the resulting file is
* immediately runnable.
* @property {string | null | undefined} [jsxImportSource='react']
* Place to import automatic JSX runtimes from (default: `'react'`);
* when in the `automatic` runtime, this is used to define an import for
* `Fragment`, `jsx`, `jsxDEV`, and `jsxs`.
* @property {'automatic' | 'classic' | null | undefined} [jsxRuntime='automatic']
* JSX runtime to use (default: `'automatic'`);
* the automatic runtime compiles to `import _jsx from
* '$importSource/jsx-runtime'\n_jsx('p')`;
* the classic runtime compiles to calls such as `h('p')`.
*
* > 👉 **Note**: support for the classic runtime is deprecated and will
* > likely be removed in the next major version.
* @property {ReadonlyArray<string> | null | undefined} [mdExtensions]
* List of markdown extensions, with dot (default: `['.md', '.markdown', …]`);
* affects integrations.
* @property {ReadonlyArray<string> | null | undefined} [mdxExtensions]
* List of MDX extensions, with dot (default: `['.mdx']`);
* affects integrations.
* @property {'function-body' | 'program' | null | undefined} [outputFormat='program']
* Output format to generate (default: `'program'`);
* in most cases `'program'` should be used, it results in a whole program;
* internally `evaluate` uses `'function-body'` to compile to
* code that can be passed to `run`;
* in some cases, you might want what `evaluate` does in separate steps, such
* as when compiling on the server and running on the client.
* @property {string | null | undefined} [pragma='React.createElement']
* Pragma for JSX, used in the classic runtime as an identifier for function
* calls: `<x />` to `React.createElement('x')` (default:
* `'React.createElement'`);
* when changing this, you should also define `pragmaFrag` and
* `pragmaImportSource` too.
*
* > 👉 **Note**: support for the classic runtime is deprecated and will
* > likely be removed in the next major version.
* @property {string | null | undefined} [pragmaFrag='React.Fragment']
* Pragma for fragment symbol, used in the classic runtime as an identifier
* for unnamed calls: `<>` to `React.createElement(React.Fragment)` (default:
* `'React.Fragment'`);
* when changing this, you should also define `pragma` and
* `pragmaImportSource` too.
*
* > 👉 **Note**: support for the classic runtime is deprecated and will
* > likely be removed in the next major version.
* @property {string | null | undefined} [pragmaImportSource='react']
* Where to import the identifier of `pragma` from, used in the classic
* runtime (default: `'react'`);
* to illustrate, when `pragma` is `'a.b'` and `pragmaImportSource` is `'c'`
* the following will be generated: `import a from 'c'` and things such as
* `a.b('h1', {})`.
* when changing this, you should also define `pragma` and `pragmaFrag` too.
*
* > 👉 **Note**: support for the classic runtime is deprecated and will
* > likely be removed in the next major version.
* @property {string | null | undefined} [providerImportSource]
* Place to import a provider from (optional, example: `'@mdx-js/react'`);
* normally its used for runtimes that support context (React, Preact), but
* it can be used to inject components into the compiled code;
* the module must export and identifier `useMDXComponents` which is called
* without arguments to get an object of components (`MDXComponents` from
* `mdx/types.js`).
* @property {PluggableList | null | undefined} [recmaPlugins]
* List of recma plugins (optional).
* @property {PluggableList | null | undefined} [remarkPlugins]
* List of remark plugins (optional).
* @property {PluggableList | null | undefined} [rehypePlugins]
* List of rehype plugins (optional).
* @property {Readonly<RemarkRehypeOptions> | null | undefined} [remarkRehypeOptions]
* Options to pass to `remark-rehype` (optional);
* in particular, you might want to pass configuration for footnotes if your
* content is not in English;
* the option `allowDangerousHtml` will always be set to `true` and the MDX
* nodes (see `nodeTypes`) are passed through.
* @property {RehypeRecmaOptions['stylePropertyNameCase']} [stylePropertyNameCase='dom']
* Casing to use for property names in `style` objects (default: `'dom'`);
* CSS casing is for example `background-color` and `-webkit-line-clamp`;
* DOM casing is for example `backgroundColor` and `WebkitLineClamp`;
* for JSX components written in MDX, the author has to be aware of which
* framework they use and write code accordingly;
* for AST nodes generated by this project, this option configures it
* @property {boolean | null | undefined} [tableCellAlignToStyle=true]
* Turn obsolete `align` properties on `td` and `th` into CSS `style`
* properties (default: `true`).
*/
import {unreachable} from 'devlop'
import recmaBuildJsx from 'recma-build-jsx'
import recmaJsx from 'recma-jsx'
import recmaStringify from 'recma-stringify'
import rehypeRecma from 'rehype-recma'
import remarkMdx from 'remark-mdx'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import {unified} from 'unified'
import {recmaBuildJsxTransform} from './plugin/recma-build-jsx-transform.js'
import {recmaDocument} from './plugin/recma-document.js'
import {recmaJsxRewrite} from './plugin/recma-jsx-rewrite.js'
import {rehypeRemoveRaw} from './plugin/rehype-remove-raw.js'
import {remarkMarkAndUnravel} from './plugin/remark-mark-and-unravel.js'
import {nodeTypes} from './node-types.js'
const removedOptions = [
'compilers',
'filepath',
'hastPlugins',
'mdPlugins',
'skipExport',
'wrapExport'
]
let warned = false
/**
* Create a processor to compile markdown or MDX to JavaScript.
*
* > **Note**: `format: 'detect'` is not allowed in `ProcessorOptions`.
*
* @param {Readonly<ProcessorOptions> | null | undefined} [options]
* Configuration (optional).
* @return {Processor<Root, Program, Program, Program, string>}
* Processor.
*/
export function createProcessor(options) {
const settings = options || {}
let index = -1
while (++index < removedOptions.length) {
const key = removedOptions[index]
if (key in settings) {
unreachable(
'Unexpected removed option `' +
key +
'`; see <https://mdxjs.com/migrating/v2/> on how to migrate'
)
}
}
// @ts-expect-error: throw an error for a runtime value which is not allowed
// by the types.
if (settings.format === 'detect') {
unreachable(
"Unexpected `format: 'detect'`, which is not supported by `createProcessor`, expected `'mdx'` or `'md'`"
)
}
if (
(settings.jsxRuntime === 'classic' ||
settings.pragma ||
settings.pragmaFrag ||
settings.pragmaImportSource) &&
!warned
) {
warned = true
console.warn(
"Unexpected deprecated option `jsxRuntime: 'classic'`, `pragma`, `pragmaFrag`, or `pragmaImportSource`; see <https://mdxjs.com/migrating/v3/> on how to migrate"
)
}
const pipeline = unified().use(remarkParse)
if (settings.format !== 'md') {
pipeline.use(remarkMdx)
}
const remarkRehypeOptions = settings.remarkRehypeOptions || {}
pipeline
.use(remarkMarkAndUnravel)
.use(settings.remarkPlugins || [])
.use(remarkRehype, {
...remarkRehypeOptions,
allowDangerousHtml: true,
passThrough: [...(remarkRehypeOptions.passThrough || []), ...nodeTypes]
})
.use(settings.rehypePlugins || [])
if (settings.format === 'md') {
pipeline.use(rehypeRemoveRaw)
}
pipeline
// @ts-expect-error: `Program` is close enough to a `Node`,
// but type inference has trouble with it and bridges.
.use(rehypeRecma, settings)
.use(recmaDocument, settings)
.use(recmaJsxRewrite, settings)
if (!settings.jsx) {
pipeline.use(recmaBuildJsx, settings).use(recmaBuildJsxTransform, settings)
}
pipeline
.use(recmaJsx)
.use(recmaStringify, settings)
.use(settings.recmaPlugins || [])
// @ts-expect-error: TS doesnt get the plugins we added with if-statements.
return pipeline
}

View File

@@ -0,0 +1,69 @@
/**
* @import {MDXModule} from 'mdx/types.js'
* @import {Compatible} from 'vfile'
* @import {EvaluateOptions} from './util/resolve-evaluate-options.js'
*/
import {resolveEvaluateOptions} from './util/resolve-evaluate-options.js'
import {compile, compileSync} from './compile.js'
import {run, runSync} from './run.js'
/**
* Compile and run MDX.
*
* When you trust your content, `evaluate` can work.
* When possible, use `compile`, write to a file, and then run with Node or use
* one of the integrations.
*
* > ☢️ **Danger**: its called **evaluate** because it `eval`s JavaScript.
*
* ###### Notes
*
* Compiling (and running) MDX takes time.
*
* If you are live-rendering a string of MDX that often changes using a virtual
* DOM based framework (such as React), one performance improvement is to call
* the `MDXContent` component yourself.
* The reason is that the `evaluate` creates a new function each time, which
* cannot be diffed:
*
* ```diff
* const {default: MDXContent} = await evaluate('…')
*
* -<MDXContent {...props} />
* +MDXContent(props)
* ```
*
* @param {Readonly<Compatible>} file
* MDX document to parse.
* @param {Readonly<EvaluateOptions>} options
* Configuration (**required**).
* @return {Promise<MDXModule>}
* Promise to a module;
* the result is an object with a `default` field set to the component;
* anything else that was exported is available too.
*/
export async function evaluate(file, options) {
const {compiletime, runtime} = resolveEvaluateOptions(options)
return run(await compile(file, compiletime), runtime)
}
/**
* Compile and run MDX, synchronously.
*
* When possible please use the async `evaluate`.
*
* > ☢️ **Danger**: its called **evaluate** because it `eval`s JavaScript.
*
* @param {Readonly<Compatible>} file
* MDX document to parse.
* @param {Readonly<EvaluateOptions>} options
* Configuration (**required**).
* @return {MDXModule}
* Module.
*/
export function evaluateSync(file, options) {
const {compiletime, runtime} = resolveEvaluateOptions(options)
return runSync(compileSync(file, compiletime), runtime)
}

View File

@@ -0,0 +1,11 @@
/**
* List of node types made by `mdast-util-mdx`, which have to be passed
* through untouched from the mdast tree to the hast tree.
*/
export const nodeTypes = /** @type {const} */ ([
'mdxFlowExpression',
'mdxJsxFlowElement',
'mdxJsxTextElement',
'mdxTextExpression',
'mdxjsEsm'
])

View File

@@ -0,0 +1,80 @@
/**
* @import {Program} from 'estree-jsx'
*/
/**
* @typedef Options
* Configuration for internal plugin `recma-build-jsx-transform`.
* @property {'function-body' | 'program' | null | undefined} [outputFormat='program']
* Whether to keep the import of the automatic runtime or get it from
* `arguments[0]` instead (default: `'program'`).
*/
import {specifiersToDeclarations} from '../util/estree-util-specifiers-to-declarations.js'
import {toIdOrMemberExpression} from '../util/estree-util-to-id-or-member-expression.js'
/**
* Plugin to change the tree after compiling JSX away.
*
* @param {Readonly<Options> | null | undefined} [options]
* Configuration (optional).
* @returns
* Transform.
*/
export function recmaBuildJsxTransform(options) {
/* c8 ignore next -- always given in `@mdx-js/mdx` */
const {outputFormat} = options || {}
/**
* @param {Program} tree
* Tree.
* @returns {undefined}
* Nothing.
*/
return function (tree) {
// Remove the pragma comment that we injected ourselves as it is no longer
// needed.
if (tree.comments) {
tree.comments = tree.comments.filter(function (d) {
return !d.data?._mdxIsPragmaComment
})
}
// When compiling to a function body, replace the import that was just
// generated, and get `jsx`, `jsxs`, and `Fragment` from `arguments[0]`
// instead.
if (outputFormat === 'function-body') {
let index = 0
// Skip directives: JS currently only has `use strict`, but Acorn allows
// arbitrary ones.
// Practically things like `use client` could be used?
while (index < tree.body.length) {
const child = tree.body[index]
if ('directive' in child && child.directive) {
index++
} else {
break
}
}
const declaration = tree.body[index]
if (
declaration &&
declaration.type === 'ImportDeclaration' &&
typeof declaration.source.value === 'string' &&
/\/jsx-(dev-)?runtime$/.test(declaration.source.value)
) {
tree.body[index] = {
type: 'VariableDeclaration',
kind: 'const',
declarations: specifiersToDeclarations(
declaration.specifiers,
toIdOrMemberExpression(['arguments', 0])
)
}
}
}
}
}

View File

@@ -0,0 +1,915 @@
/**
* @import {
CallExpression,
Directive,
ExportAllDeclaration,
ExportDefaultDeclaration,
ExportNamedDeclaration,
ExportSpecifier,
Expression,
FunctionDeclaration,
Identifier,
ImportDeclaration,
ImportDefaultSpecifier,
ImportExpression,
ImportSpecifier,
JSXElement,
JSXFragment,
Literal,
ModuleDeclaration,
Node,
Program,
Property,
SimpleLiteral,
SpreadElement,
Statement,
VariableDeclarator
* } from 'estree-jsx'
* @import {VFile} from 'vfile'
* @import {ProcessorOptions} from '../core.js'
*/
import {ok as assert} from 'devlop'
import {createVisitors} from 'estree-util-scope'
import {walk} from 'estree-walker'
import {positionFromEstree} from 'unist-util-position-from-estree'
import {stringifyPosition} from 'unist-util-stringify-position'
import {create} from '../util/estree-util-create.js'
import {declarationToExpression} from '../util/estree-util-declaration-to-expression.js'
import {isDeclaration} from '../util/estree-util-is-declaration.js'
import {specifiersToDeclarations} from '../util/estree-util-specifiers-to-declarations.js'
import {toIdOrMemberExpression} from '../util/estree-util-to-id-or-member-expression.js'
/**
* Wrap the estree in `MDXContent`.
*
* @param {Readonly<ProcessorOptions>} options
* Configuration.
* @returns
* Transform.
*/
export function recmaDocument(options) {
const baseUrl = options.baseUrl || undefined
const baseHref = typeof baseUrl === 'object' ? baseUrl.href : baseUrl
const outputFormat = options.outputFormat || 'program'
const pragma =
options.pragma === undefined ? 'React.createElement' : options.pragma
const pragmaFrag =
options.pragmaFrag === undefined ? 'React.Fragment' : options.pragmaFrag
const pragmaImportSource = options.pragmaImportSource || 'react'
const jsxImportSource = options.jsxImportSource || 'react'
const jsxRuntime = options.jsxRuntime || 'automatic'
/**
* @param {Program} tree
* Tree.
* @param {VFile} file
* File.
* @returns {undefined}
* Nothing.
*/
return function (tree, file) {
/** @type {Array<[string, string] | string>} */
const exportedValues = []
/** @type {Array<Directive | ModuleDeclaration | Statement>} */
const replacement = []
let exportAllCount = 0
/** @type {ExportDefaultDeclaration | ExportSpecifier | undefined} */
let layout
/** @type {boolean | undefined} */
let content
/** @type {Node} */
let child
if (jsxRuntime === 'classic' && pragmaFrag) {
injectPragma(tree, '@jsxFrag', pragmaFrag)
}
if (jsxRuntime === 'classic' && pragma) {
injectPragma(tree, '@jsx', pragma)
}
if (jsxRuntime === 'automatic' && jsxImportSource) {
injectPragma(tree, '@jsxImportSource', jsxImportSource)
}
if (jsxRuntime) {
injectPragma(tree, '@jsxRuntime', jsxRuntime)
}
if (jsxRuntime === 'classic' && pragmaImportSource) {
if (!pragma) {
throw new Error(
'Missing `pragma` in classic runtime with `pragmaImportSource`'
)
}
handleEsm({
type: 'ImportDeclaration',
specifiers: [
{
type: 'ImportDefaultSpecifier',
local: {type: 'Identifier', name: pragma.split('.')[0]}
}
],
attributes: [],
source: {type: 'Literal', value: pragmaImportSource}
})
}
// Find the `export default`, the JSX expression, and leave the rest
// (import/exports) as they are.
for (child of tree.body) {
// ```tsx
// export default properties => <>{properties.children}</>
// ```
//
// Treat it as an inline layout declaration.
if (child.type === 'ExportDefaultDeclaration') {
if (layout) {
file.fail(
'Unexpected duplicate layout, expected a single layout (previous: ' +
stringifyPosition(positionFromEstree(layout)) +
')',
{
ancestors: [tree, child],
place: positionFromEstree(child),
ruleId: 'duplicate-layout',
source: 'recma-document'
}
)
}
layout = child
replacement.push({
type: 'VariableDeclaration',
kind: 'const',
declarations: [
{
type: 'VariableDeclarator',
id: {type: 'Identifier', name: 'MDXLayout'},
init: isDeclaration(child.declaration)
? declarationToExpression(child.declaration)
: child.declaration
}
]
})
}
// ```tsx
// export {a, b as c} from 'd'
// ```
else if (child.type === 'ExportNamedDeclaration' && child.source) {
// Cast because always simple.
const source = /** @type {SimpleLiteral} */ (child.source)
// Remove `default` or `as default`, but not `default as`, specifier.
child.specifiers = child.specifiers.filter(function (specifier) {
if (
specifier.exported.type === 'Identifier' &&
specifier.exported.name === 'default'
) {
if (layout) {
file.fail(
'Unexpected duplicate layout, expected a single layout (previous: ' +
stringifyPosition(positionFromEstree(layout)) +
')',
{
ancestors: [tree, child, specifier],
place: positionFromEstree(child),
ruleId: 'duplicate-layout',
source: 'recma-document'
}
)
}
layout = specifier
// Make it just an import: `import MDXLayout from '…'`.
/** @type {Array<ImportDefaultSpecifier | ImportSpecifier>} */
const specifiers = []
// Default as default / something else as default.
if (
specifier.local.type === 'Identifier' &&
specifier.local.name === 'default'
) {
specifiers.push({
type: 'ImportDefaultSpecifier',
local: {type: 'Identifier', name: 'MDXLayout'}
})
} else {
/** @type {ImportSpecifier} */
const importSpecifier = {
type: 'ImportSpecifier',
imported: specifier.local,
local: {type: 'Identifier', name: 'MDXLayout'}
}
create(specifier.local, importSpecifier)
specifiers.push(importSpecifier)
}
/** @type {Literal} */
const from = {type: 'Literal', value: source.value}
create(source, from)
/** @type {ImportDeclaration} */
const declaration = {
type: 'ImportDeclaration',
specifiers,
attributes: [],
source: from
}
create(specifier, declaration)
handleEsm(declaration)
return false
}
return true
})
// If there are other things imported, keep it.
if (child.specifiers.length > 0) {
handleExport(child)
}
}
// ```tsx
// export {a, b as c}
// export * from 'a'
// ```
else if (
child.type === 'ExportNamedDeclaration' ||
child.type === 'ExportAllDeclaration'
) {
handleExport(child)
} else if (child.type === 'ImportDeclaration') {
handleEsm(child)
} else if (
child.type === 'ExpressionStatement' &&
(child.expression.type === 'JSXElement' ||
child.expression.type === 'JSXFragment')
) {
content = true
replacement.push(
...createMdxContent(child.expression, outputFormat, Boolean(layout))
)
} else {
// This catch-all branch is because plugins might add other things.
// Normally, we only have import/export/jsx, but just add whatevers
// there.
replacement.push(child)
}
}
// If there was no JSX content at all, add an empty function.
if (!content) {
replacement.push(
...createMdxContent(undefined, outputFormat, Boolean(layout))
)
}
exportedValues.push(['MDXContent', 'default'])
if (outputFormat === 'function-body') {
replacement.push({
type: 'ReturnStatement',
argument: {
type: 'ObjectExpression',
properties: [
...Array.from({length: exportAllCount}).map(
/**
* @param {undefined} _
* Nothing.
* @param {number} index
* Index.
* @returns {SpreadElement}
* Node.
*/
function (_, index) {
return {
type: 'SpreadElement',
argument: {
type: 'Identifier',
name: '_exportAll' + (index + 1)
}
}
}
),
...exportedValues.map(function (d) {
/** @type {Property} */
const property = {
type: 'Property',
kind: 'init',
method: false,
computed: false,
shorthand: typeof d === 'string',
key: {
type: 'Identifier',
name: typeof d === 'string' ? d : d[1]
},
value: {
type: 'Identifier',
name: typeof d === 'string' ? d : d[0]
}
}
return property
})
]
}
})
}
tree.body = replacement
let usesImportMetaUrlVariable = false
let usesResolveDynamicHelper = false
if (baseHref || outputFormat === 'function-body') {
walk(tree, {
enter(node) {
if (
(node.type === 'ExportAllDeclaration' ||
node.type === 'ExportNamedDeclaration' ||
node.type === 'ImportDeclaration') &&
node.source
) {
// We never hit this branch when generating function bodies, as
// statements are already compiled away into import expressions.
assert(baseHref, 'unexpected missing `baseHref` in branch')
let value = node.source.value
// The literal source for statements can only be string.
assert(typeof value === 'string', 'expected string source')
// Resolve a specifier.
// This is the same as `_resolveDynamicMdxSpecifier`, which has to
// be injected to work with expressions at runtime, but as we have
// `baseHref` at compile time here and statements are static
// strings, we can do it now.
try {
// To do: next major: use `URL.canParse`.
// eslint-disable-next-line no-new
new URL(value)
// Fine: a full URL.
} catch {
if (
value.startsWith('/') ||
value.startsWith('./') ||
value.startsWith('../')
) {
value = new URL(value, baseHref).href
} else {
// Fine: are bare specifier.
}
}
/** @type {SimpleLiteral} */
const replacement = {type: 'Literal', value}
create(node.source, replacement)
node.source = replacement
return
}
if (node.type === 'ImportExpression') {
usesResolveDynamicHelper = true
/** @type {CallExpression} */
const replacement = {
type: 'CallExpression',
callee: {type: 'Identifier', name: '_resolveDynamicMdxSpecifier'},
arguments: [node.source],
optional: false
}
node.source = replacement
return
}
// To do: add support for `import.meta.resolve`.
if (
node.type === 'MemberExpression' &&
'object' in node &&
node.object.type === 'MetaProperty' &&
node.property.type === 'Identifier' &&
node.object.meta.name === 'import' &&
node.object.property.name === 'meta' &&
node.property.name === 'url'
) {
usesImportMetaUrlVariable = true
/** @type {Identifier} */
const replacement = {type: 'Identifier', name: '_importMetaUrl'}
create(node, replacement)
this.replace(replacement)
}
}
})
}
if (usesResolveDynamicHelper) {
if (!baseHref) {
usesImportMetaUrlVariable = true
}
tree.body.push(
resolveDynamicMdxSpecifier(
baseHref
? {type: 'Literal', value: baseHref}
: {type: 'Identifier', name: '_importMetaUrl'}
)
)
}
if (usesImportMetaUrlVariable) {
assert(
outputFormat === 'function-body',
'expected `function-body` when using dynamic url injection'
)
tree.body.unshift(...createImportMetaUrlVariable())
}
/**
* @param {ExportAllDeclaration | ExportNamedDeclaration} node
* Export node.
* @returns {undefined}
* Nothing.
*/
function handleExport(node) {
if (node.type === 'ExportNamedDeclaration') {
// ```tsx
// export function a() {}
// export class A {}
// export var a = 1
// ```
if (node.declaration) {
const visitors = createVisitors()
// Walk the top-level scope.
walk(node, {
enter(node) {
visitors.enter(node)
if (
node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression'
) {
this.skip()
visitors.exit(node)
}
},
leave: visitors.exit
})
exportedValues.push(...visitors.scopes[0].defined)
}
// ```tsx
// export {a, b as c}
// export {a, b as c} from 'd'
// ```
for (child of node.specifiers) {
if (child.exported.type === 'Identifier') {
exportedValues.push(child.exported.name)
/* c8 ignore next 5 -- to do: <https://github.com/mdx-js/mdx/issues/2536> */
} else {
// Must be string.
assert(typeof child.exported.value === 'string')
exportedValues.push(child.exported.value)
}
}
}
handleEsm(node)
}
/**
* @param {ExportAllDeclaration | ExportNamedDeclaration | ImportDeclaration} node
* Export or import node.
* @returns {undefined}
* Nothing.
*/
function handleEsm(node) {
/** @type {ModuleDeclaration | Statement | undefined} */
let replace
/** @type {Expression} */
let init
if (outputFormat === 'function-body') {
if (
// Always have a source:
node.type === 'ImportDeclaration' ||
node.type === 'ExportAllDeclaration' ||
// Source optional:
(node.type === 'ExportNamedDeclaration' && node.source)
) {
// We always have a source, but types say they can be missing.
assert(node.source, 'expected `node.source` to be defined')
// ```
// import 'a'
// //=> await import('a')
// import a from 'b'
// //=> const {default: a} = await import('b')
// export {a, b as c} from 'd'
// //=> const {a, c: b} = await import('d')
// export * from 'a'
// //=> const _exportAll0 = await import('a')
// ```
/** @type {ImportExpression} */
const argument = {type: 'ImportExpression', source: node.source}
create(node, argument)
init = {type: 'AwaitExpression', argument}
if (
(node.type === 'ImportDeclaration' ||
node.type === 'ExportNamedDeclaration') &&
node.specifiers.length === 0
) {
replace = {type: 'ExpressionStatement', expression: init}
} else {
replace = {
type: 'VariableDeclaration',
kind: 'const',
declarations:
node.type === 'ExportAllDeclaration'
? [
{
type: 'VariableDeclarator',
id: {
type: 'Identifier',
name: '_exportAll' + ++exportAllCount
},
init
}
]
: specifiersToDeclarations(node.specifiers, init)
}
}
} else if (node.declaration) {
replace = node.declaration
} else {
/** @type {Array<VariableDeclarator>} */
const declarators = []
for (const specifier of node.specifiers) {
// `id` can only be an identifier,
// so we ignore literal.
if (
specifier.exported.type === 'Identifier' &&
specifier.local.type === 'Identifier' &&
specifier.local.name !== specifier.exported.name
) {
declarators.push({
type: 'VariableDeclarator',
id: specifier.exported,
init: specifier.local
})
}
}
if (declarators.length > 0) {
replace = {
type: 'VariableDeclaration',
kind: 'const',
declarations: declarators
}
}
}
} else {
replace = node
}
if (replace) {
replacement.push(replace)
}
}
}
/**
* @param {Readonly<Expression> | undefined} content
* Content.
* @param {'function-body' | 'program'} outputFormat
* Output format.
* @param {boolean | undefined} [hasInternalLayout=false]
* Whether theres an internal layout (default: `false`).
* @returns {Array<ExportDefaultDeclaration | FunctionDeclaration>}
* Functions.
*/
function createMdxContent(content, outputFormat, hasInternalLayout) {
/** @type {JSXElement} */
const element = {
type: 'JSXElement',
openingElement: {
type: 'JSXOpeningElement',
name: {type: 'JSXIdentifier', name: 'MDXLayout'},
attributes: [
{
type: 'JSXSpreadAttribute',
argument: {type: 'Identifier', name: 'props'}
}
],
selfClosing: false
},
closingElement: {
type: 'JSXClosingElement',
name: {type: 'JSXIdentifier', name: 'MDXLayout'}
},
children: [
{
type: 'JSXElement',
openingElement: {
type: 'JSXOpeningElement',
name: {type: 'JSXIdentifier', name: '_createMdxContent'},
attributes: [
{
type: 'JSXSpreadAttribute',
argument: {type: 'Identifier', name: 'props'}
}
],
selfClosing: true
},
closingElement: null,
children: []
}
]
}
let result = /** @type {Expression} */ (element)
if (!hasInternalLayout) {
result = {
type: 'ConditionalExpression',
test: {type: 'Identifier', name: 'MDXLayout'},
consequent: result,
alternate: {
type: 'CallExpression',
callee: {type: 'Identifier', name: '_createMdxContent'},
arguments: [{type: 'Identifier', name: 'props'}],
optional: false
}
}
}
let argument =
// Cast because TS otherwise does not think `JSXFragment`s are expressions.
/** @type {Readonly<Expression> | Readonly<JSXFragment>} */ (
content || {type: 'Identifier', name: 'undefined'}
)
// Unwrap a fragment of a single element.
if (
argument.type === 'JSXFragment' &&
argument.children.length === 1 &&
argument.children[0].type === 'JSXElement'
) {
argument = argument.children[0]
}
let awaitExpression = false
walk(argument, {
enter(node) {
if (
node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression'
) {
return this.skip()
}
if (
node.type === 'AwaitExpression' ||
/* c8 ignore next 2 -- can only occur in a function (which then can
* only be async, so skipped it) */
(node.type === 'ForOfStatement' && node.await)
) {
awaitExpression = true
}
}
})
/** @type {FunctionDeclaration} */
const declaration = {
type: 'FunctionDeclaration',
id: {type: 'Identifier', name: 'MDXContent'},
params: [
{
type: 'AssignmentPattern',
left: {type: 'Identifier', name: 'props'},
right: {type: 'ObjectExpression', properties: []}
}
],
body: {
type: 'BlockStatement',
body: [{type: 'ReturnStatement', argument: result}]
}
}
return [
{
type: 'FunctionDeclaration',
async: awaitExpression,
id: {type: 'Identifier', name: '_createMdxContent'},
params: [{type: 'Identifier', name: 'props'}],
body: {
type: 'BlockStatement',
body: [
{
type: 'ReturnStatement',
// Cast because TS doesnt think `JSXFragment` is an expression.
// eslint-disable-next-line object-shorthand
argument: /** @type {Expression} */ (argument)
}
]
}
},
outputFormat === 'program'
? {type: 'ExportDefaultDeclaration', declaration}
: declaration
]
}
}
/**
* @param {Program} tree
* @param {string} name
* @param {string} value
* @returns {undefined}
*/
function injectPragma(tree, name, value) {
tree.comments?.unshift({
type: 'Block',
value: name + ' ' + value,
data: {_mdxIsPragmaComment: true}
})
}
/**
* @param {Expression} importMetaUrl
* @returns {FunctionDeclaration}
*/
function resolveDynamicMdxSpecifier(importMetaUrl) {
return {
type: 'FunctionDeclaration',
id: {type: 'Identifier', name: '_resolveDynamicMdxSpecifier'},
generator: false,
async: false,
params: [{type: 'Identifier', name: 'd'}],
body: {
type: 'BlockStatement',
body: [
{
type: 'IfStatement',
test: {
type: 'BinaryExpression',
left: {
type: 'UnaryExpression',
operator: 'typeof',
prefix: true,
argument: {type: 'Identifier', name: 'd'}
},
operator: '!==',
right: {type: 'Literal', value: 'string'}
},
consequent: {
type: 'ReturnStatement',
argument: {type: 'Identifier', name: 'd'}
},
alternate: null
},
// To do: use `URL.canParse` when widely supported (see commented
// out code below).
{
type: 'TryStatement',
block: {
type: 'BlockStatement',
body: [
{
type: 'ExpressionStatement',
expression: {
type: 'NewExpression',
callee: {type: 'Identifier', name: 'URL'},
arguments: [{type: 'Identifier', name: 'd'}]
}
},
{
type: 'ReturnStatement',
argument: {type: 'Identifier', name: 'd'}
}
]
},
handler: {
type: 'CatchClause',
param: null,
body: {type: 'BlockStatement', body: []}
},
finalizer: null
},
// To do: use `URL.canParse` when widely supported.
// {
// type: 'IfStatement',
// test: {
// type: 'CallExpression',
// callee: toIdOrMemberExpression(['URL', 'canParse']),
// arguments: [{type: 'Identifier', name: 'd'}],
// optional: false
// },
// consequent: {
// type: 'ReturnStatement',
// argument: {type: 'Identifier', name: 'd'}
// },
// alternate: null
// },
{
type: 'IfStatement',
test: {
type: 'LogicalExpression',
left: {
type: 'LogicalExpression',
left: {
type: 'CallExpression',
callee: toIdOrMemberExpression(['d', 'startsWith']),
arguments: [{type: 'Literal', value: '/'}],
optional: false
},
operator: '||',
right: {
type: 'CallExpression',
callee: toIdOrMemberExpression(['d', 'startsWith']),
arguments: [{type: 'Literal', value: './'}],
optional: false
}
},
operator: '||',
right: {
type: 'CallExpression',
callee: toIdOrMemberExpression(['d', 'startsWith']),
arguments: [{type: 'Literal', value: '../'}],
optional: false
}
},
consequent: {
type: 'ReturnStatement',
argument: {
type: 'MemberExpression',
object: {
type: 'NewExpression',
callee: {type: 'Identifier', name: 'URL'},
arguments: [{type: 'Identifier', name: 'd'}, importMetaUrl]
},
property: {type: 'Identifier', name: 'href'},
computed: false,
optional: false
}
},
alternate: null
},
{
type: 'ReturnStatement',
argument: {type: 'Identifier', name: 'd'}
}
]
}
}
}
/**
* @returns {Array<Statement>}
*/
function createImportMetaUrlVariable() {
return [
{
type: 'VariableDeclaration',
declarations: [
{
type: 'VariableDeclarator',
id: {type: 'Identifier', name: '_importMetaUrl'},
init: toIdOrMemberExpression(['arguments', 0, 'baseUrl'])
}
],
kind: 'const'
},
{
type: 'IfStatement',
test: {
type: 'UnaryExpression',
operator: '!',
prefix: true,
argument: {type: 'Identifier', name: '_importMetaUrl'}
},
consequent: {
type: 'ThrowStatement',
argument: {
type: 'NewExpression',
callee: {type: 'Identifier', name: 'Error'},
arguments: [
{
type: 'Literal',
value:
'Unexpected missing `options.baseUrl` needed to support `export … from`, `import`, or `import.meta.url` when generating `function-body`'
}
]
}
},
alternate: null
}
]
}

View File

@@ -0,0 +1,620 @@
/**
* @import {
Expression,
Function as EstreeFunction,
Identifier,
ImportSpecifier,
JSXElement,
ModuleDeclaration,
ObjectPattern,
Program,
Property,
SpreadElement,
Statement,
VariableDeclarator
* } from 'estree-jsx'
* @import {Scope} from 'estree-util-scope'
* @import {VFile} from 'vfile'
* @import {ProcessorOptions} from '../core.js'
*/
/**
* @typedef StackEntry
* Entry.
* @property {Array<string>} components
* Used components.
* @property {Map<string, string>} idToInvalidComponentName
* Map of JSX identifiers which cannot be used as JS identifiers, to valid JS identifiers.
* @property {Readonly<EstreeFunction>} node
* Function.
* @property {Array<string>} objects
* Identifiers of used objects (such as `x` in `x.y`).
* @property {Record<string, {node: Readonly<JSXElement>, component: boolean}>} references
* Map of JSX identifiers for components and objects, to where they were first used.
* @property {Array<string>} tags
* Tag names.
*/
import {name as isIdentifierName} from 'estree-util-is-identifier-name'
import {createVisitors} from 'estree-util-scope'
import {walk} from 'estree-walker'
import {stringifyPosition} from 'unist-util-stringify-position'
import {positionFromEstree} from 'unist-util-position-from-estree'
import {specifiersToDeclarations} from '../util/estree-util-specifiers-to-declarations.js'
import {toBinaryAddition} from '../util/estree-util-to-binary-addition.js'
import {
toIdOrMemberExpression,
toJsxIdOrMemberExpression
} from '../util/estree-util-to-id-or-member-expression.js'
/**
* A plugin that rewrites JSX in functions to accept components as
* `props.components` (when the function is called `_createMdxContent`), or from
* a provider (if there is one).
* It also makes sure that any undefined components are defined: either from
* received components or as a function that throws an error.
*
* @param {Readonly<ProcessorOptions>} options
* Configuration (optional).
* @returns
* Transform.
*/
export function recmaJsxRewrite(options) {
const {development, outputFormat, providerImportSource} = options
/**
* @param {Program} tree
* Tree.
* @param {VFile} file
* File.
* @returns {undefined}
* Nothing.
*/
return function (tree, file) {
const visitors = createVisitors()
/** @type {Array<StackEntry>} */
const functionStack = []
let importProvider = false
let createErrorHelper = false
walk(tree, {
enter(node) {
visitors.enter(node)
if (
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression'
) {
functionStack.push({
components: [],
idToInvalidComponentName: new Map(),
node,
objects: [],
references: {},
tags: []
})
// `MDXContent` only ever contains `MDXLayout`.
if (
isNamedFunction(node, 'MDXContent') &&
!inScope(visitors.scopes, 'MDXLayout')
) {
functionStack[0].components.push('MDXLayout')
}
}
const functionInfo = functionStack[0]
if (
!functionInfo ||
(!isNamedFunction(functionInfo.node, '_createMdxContent') &&
!providerImportSource)
) {
return
}
if (node.type === 'JSXElement') {
let name = node.openingElement.name
// `<x.y>`, `<Foo.Bar>`, `<x.y.z>`.
if (name.type === 'JSXMemberExpression') {
/** @type {Array<string>} */
const ids = []
// Find the left-most identifier.
while (name.type === 'JSXMemberExpression') {
ids.unshift(name.property.name)
name = name.object
}
ids.unshift(name.name)
const fullId = ids.join('.')
const id = name.name
const isInScope = inScope(visitors.scopes, id)
if (
!Object.hasOwn(functionInfo.references, fullId) &&
(!isInScope ||
// If the parent scope is `_createMdxContent`, then this
// references a component we can add a check statement for.
(functionStack.length === 1 &&
functionStack[0].node.type === 'FunctionDeclaration' &&
isNamedFunction(functionStack[0].node, '_createMdxContent')))
) {
functionInfo.references[fullId] = {component: true, node}
}
if (!functionInfo.objects.includes(id) && !isInScope) {
functionInfo.objects.push(id)
}
}
// `<xml:thing>`.
else if (name.type === 'JSXNamespacedName') {
// Ignore namespaces.
}
// If the name is a valid ES identifier, and it doesnt start with a
// lowercase letter, its a component.
// For example, `$foo`, `_bar`, `Baz` are all component names.
// But `foo` and `b-ar` are tag names.
else if (isIdentifierName(name.name) && !/^[a-z]/.test(name.name)) {
const id = name.name
if (!inScope(visitors.scopes, id)) {
// No need to add an error for an undefined layout — we use an
// `if` later.
if (
id !== 'MDXLayout' &&
!Object.hasOwn(functionInfo.references, id)
) {
functionInfo.references[id] = {component: true, node}
}
if (!functionInfo.components.includes(id)) {
functionInfo.components.push(id)
}
}
} else if (node.data && node.data._mdxExplicitJsx) {
// Do not turn explicit JSX into components from `_components`.
// As in, a given `h1` component is used for `# heading` (next case),
// but not for `<h1>heading</h1>`.
} else {
const id = name.name
if (!functionInfo.tags.includes(id)) {
functionInfo.tags.push(id)
}
/** @type {Array<number | string>} */
let jsxIdExpression = ['_components', id]
if (isIdentifierName(id) === false) {
let invalidComponentName =
functionInfo.idToInvalidComponentName.get(id)
if (invalidComponentName === undefined) {
invalidComponentName = `_component${functionInfo.idToInvalidComponentName.size}`
functionInfo.idToInvalidComponentName.set(
id,
invalidComponentName
)
}
jsxIdExpression = [invalidComponentName]
}
node.openingElement.name =
toJsxIdOrMemberExpression(jsxIdExpression)
if (node.closingElement) {
node.closingElement.name =
toJsxIdOrMemberExpression(jsxIdExpression)
}
}
}
},
leave(node) {
visitors.exit(node)
/** @type {Array<Property | SpreadElement>} */
const defaults = []
/** @type {Array<string>} */
const actual = []
/** @type {Array<Expression>} */
const parameters = []
/** @type {Array<VariableDeclarator>} */
const declarations = []
if (
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression'
) {
const functionInfo = functionStack[functionStack.length - 1]
/** @type {string} */
let name
for (name of functionInfo.tags.sort()) {
defaults.push({
type: 'Property',
kind: 'init',
key: isIdentifierName(name)
? {type: 'Identifier', name}
: {type: 'Literal', value: name},
value: {type: 'Literal', value: name},
method: false,
shorthand: false,
computed: false
})
}
actual.push(...functionInfo.components)
for (name of functionInfo.objects) {
// In some cases, a component is used directly (`<X>`) but its also
// used as an object (`<X.Y>`).
if (!actual.includes(name)) {
actual.push(name)
}
}
actual.sort()
/** @type {Array<Statement>} */
const statements = []
if (
defaults.length > 0 ||
actual.length > 0 ||
functionInfo.idToInvalidComponentName.size > 0
) {
if (providerImportSource) {
importProvider = true
parameters.push({
type: 'CallExpression',
callee: {type: 'Identifier', name: '_provideComponents'},
arguments: [],
optional: false
})
}
// Accept `components` as a prop if this is the `MDXContent` or
// `_createMdxContent` function.
if (
isNamedFunction(functionInfo.node, 'MDXContent') ||
isNamedFunction(functionInfo.node, '_createMdxContent')
) {
parameters.push(toIdOrMemberExpression(['props', 'components']))
}
if (defaults.length > 0 || parameters.length > 1) {
for (const parameter of parameters) {
defaults.push({type: 'SpreadElement', argument: parameter})
}
}
// If were getting components from several sources, merge them.
/** @type {Expression} */
let componentsInit =
defaults.length > 0
? {type: 'ObjectExpression', properties: defaults}
: // If were only getting components from `props.components`,
// make sure its defined.
{
type: 'LogicalExpression',
operator: '||',
left: parameters[0],
right: {type: 'ObjectExpression', properties: []}
}
/** @type {ObjectPattern | undefined} */
let componentsPattern
// Add components to scope.
// For `['MyComponent', 'MDXLayout']` this generates:
// ```tsx
// const {MyComponent, wrapper: MDXLayout} = _components
// ```
// Note that MDXLayout is special as its taken from
// `_components.wrapper`.
if (actual.length > 0) {
componentsPattern = {
type: 'ObjectPattern',
properties: actual.map(function (name) {
return {
type: 'Property',
kind: 'init',
key: {
type: 'Identifier',
name: name === 'MDXLayout' ? 'wrapper' : name
},
value: {type: 'Identifier', name},
method: false,
shorthand: name !== 'MDXLayout',
computed: false
}
})
}
}
if (functionInfo.tags.length > 0) {
declarations.push({
type: 'VariableDeclarator',
id: {type: 'Identifier', name: '_components'},
init: componentsInit
})
componentsInit = {type: 'Identifier', name: '_components'}
}
if (isNamedFunction(functionInfo.node, '_createMdxContent')) {
for (const [id, componentName] of [
...functionInfo.idToInvalidComponentName
].sort(function ([a], [b]) {
return a.localeCompare(b)
})) {
// For JSX IDs that cant be represented as JavaScript IDs (as in,
// those with dashes, such as `custom-element`), generate a
// separate variable that is a valid JS ID (such as `_component0`),
// and takes it from components:
// `const _component0 = _components['custom-element']`
declarations.push({
type: 'VariableDeclarator',
id: {
type: 'Identifier',
name: componentName
},
init: {
type: 'MemberExpression',
object: {type: 'Identifier', name: '_components'},
property: {type: 'Literal', value: id},
computed: true,
optional: false
}
})
}
}
if (componentsPattern) {
declarations.push({
type: 'VariableDeclarator',
id: componentsPattern,
init: componentsInit
})
}
if (declarations.length > 0) {
statements.push({
type: 'VariableDeclaration',
kind: 'const',
declarations
})
}
}
/** @type {string} */
let key
// Add partials (so for `x.y.z` itd generate `x` and `x.y` too).
for (key in functionInfo.references) {
if (Object.hasOwn(functionInfo.references, key)) {
const parts = key.split('.')
let index = 0
while (++index < parts.length) {
const partial = parts.slice(0, index).join('.')
if (!Object.hasOwn(functionInfo.references, partial)) {
functionInfo.references[partial] = {
component: false,
node: functionInfo.references[key].node
}
}
}
}
}
const references = Object.keys(functionInfo.references).sort()
let index = -1
while (++index < references.length) {
const id = references[index]
const info = functionInfo.references[id]
const place = stringifyPosition(positionFromEstree(info.node))
/** @type {Array<Expression>} */
const parameters = [
{type: 'Literal', value: id},
{type: 'Literal', value: info.component}
]
createErrorHelper = true
if (development && place) {
parameters.push({type: 'Literal', value: place})
}
statements.push({
type: 'IfStatement',
test: {
type: 'UnaryExpression',
operator: '!',
prefix: true,
argument: toIdOrMemberExpression(id.split('.'))
},
consequent: {
type: 'ExpressionStatement',
expression: {
type: 'CallExpression',
callee: {type: 'Identifier', name: '_missingMdxReference'},
arguments: parameters,
optional: false
}
},
alternate: undefined
})
}
if (statements.length > 0) {
// Arrow functions with an implied return:
if (node.body.type !== 'BlockStatement') {
node.body = {
type: 'BlockStatement',
body: [{type: 'ReturnStatement', argument: node.body}]
}
}
node.body.body.unshift(...statements)
}
functionStack.pop()
}
}
})
// If a provider is used (and can be used), import it.
if (importProvider && providerImportSource) {
tree.body.unshift(
createImportProvider(providerImportSource, outputFormat)
)
}
// If potentially missing components are used.
if (createErrorHelper) {
/** @type {Array<Expression>} */
const message = [
{type: 'Literal', value: 'Expected '},
{
type: 'ConditionalExpression',
test: {type: 'Identifier', name: 'component'},
consequent: {type: 'Literal', value: 'component'},
alternate: {type: 'Literal', value: 'object'}
},
{type: 'Literal', value: ' `'},
{type: 'Identifier', name: 'id'},
{
type: 'Literal',
value:
'` to be defined: you likely forgot to import, pass, or provide it.'
}
]
/** @type {Array<Identifier>} */
const parameters = [
{type: 'Identifier', name: 'id'},
{type: 'Identifier', name: 'component'}
]
if (development) {
message.push({
type: 'ConditionalExpression',
test: {type: 'Identifier', name: 'place'},
consequent: toBinaryAddition([
{type: 'Literal', value: '\nIts referenced in your code at `'},
{type: 'Identifier', name: 'place'},
{
type: 'Literal',
value: (file.path ? '` in `' + file.path : '') + '`'
}
]),
alternate: {type: 'Literal', value: ''}
})
parameters.push({type: 'Identifier', name: 'place'})
}
tree.body.push({
type: 'FunctionDeclaration',
id: {type: 'Identifier', name: '_missingMdxReference'},
generator: false,
async: false,
params: parameters,
body: {
type: 'BlockStatement',
body: [
{
type: 'ThrowStatement',
argument: {
type: 'NewExpression',
callee: {type: 'Identifier', name: 'Error'},
arguments: [toBinaryAddition(message)]
}
}
]
}
})
}
if (outputFormat === 'function-body') {
tree.body.unshift({
type: 'ExpressionStatement',
expression: {type: 'Literal', value: 'use strict'},
directive: 'use strict'
})
}
}
}
/**
* @param {string} providerImportSource
* Provider source.
* @param {'function-body' | 'program' | null | undefined} outputFormat
* Format.
* @returns {ModuleDeclaration | Statement}
* Node.
*/
function createImportProvider(providerImportSource, outputFormat) {
/** @type {Array<ImportSpecifier>} */
const specifiers = [
{
type: 'ImportSpecifier',
imported: {type: 'Identifier', name: 'useMDXComponents'},
local: {type: 'Identifier', name: '_provideComponents'}
}
]
return outputFormat === 'function-body'
? {
type: 'VariableDeclaration',
kind: 'const',
declarations: specifiersToDeclarations(
specifiers,
toIdOrMemberExpression(['arguments', 0])
)
}
: {
type: 'ImportDeclaration',
specifiers,
attributes: [],
source: {type: 'Literal', value: providerImportSource}
}
}
/**
* @param {Readonly<EstreeFunction>} node
* Node.
* @param {string} name
* Name.
* @returns {boolean}
* Whether `node` is a named function with `name`.
*/
function isNamedFunction(node, name) {
return Boolean(node && 'id' in node && node.id && node.id.name === name)
}
/**
* @param {Array<Scope>} scopes
* Scope.
* @param {string} id
* Identifier.
* @returns {boolean}
* Whether `id` is in `scope`.
*/
function inScope(scopes, id) {
let index = scopes.length
while (index--) {
const scope = scopes[index]
if (scope.defined.includes(id)) {
return true
}
}
return false
}

View File

@@ -0,0 +1,31 @@
/**
* @import {Root} from 'hast'
*/
import {visit} from 'unist-util-visit'
/**
* A tiny plugin that removes raw HTML.
*
* This is needed if the format is `md` and `rehype-raw` was not used to parse
* dangerous HTML into nodes.
*
* @returns
* Transform.
*/
export function rehypeRemoveRaw() {
/**
* @param {Root} tree
* Tree.
* @returns {undefined}
* Nothing.
*/
return function (tree) {
visit(tree, 'raw', function (_, index, parent) {
if (parent && typeof index === 'number') {
parent.children.splice(index, 1)
return index
}
})
}
}

View File

@@ -0,0 +1,114 @@
/**
* @import {Root, RootContent} from 'mdast'
*/
import {collapseWhiteSpace} from 'collapse-white-space'
import {walk} from 'estree-walker'
import {visit} from 'unist-util-visit'
/**
* A tiny plugin that unravels `<p><h1>x</h1></p>` but also
* `<p><Component /></p>` (so it has no knowledge of “HTML”).
*
* It also marks JSX as being explicitly JSX, so when a user passes a `h1`
* component, it is used for `# heading` but not for `<h1>heading</h1>`.
*
* @returns
* Transform.
*/
export function remarkMarkAndUnravel() {
/**
* @param {Root} tree
* Tree.
* @returns {undefined}
* Nothing.
*/
return function (tree) {
visit(tree, function (node, index, parent) {
let offset = -1
let all = true
let oneOrMore = false
if (parent && typeof index === 'number' && node.type === 'paragraph') {
const children = node.children
while (++offset < children.length) {
const child = children[offset]
if (
child.type === 'mdxJsxTextElement' ||
child.type === 'mdxTextExpression'
) {
oneOrMore = true
} else if (
child.type === 'text' &&
collapseWhiteSpace(child.value, {style: 'html', trim: true}) === ''
) {
// Empty.
} else {
all = false
break
}
}
if (all && oneOrMore) {
offset = -1
/** @type {Array<RootContent>} */
const newChildren = []
while (++offset < children.length) {
const child = children[offset]
if (child.type === 'mdxJsxTextElement') {
// @ts-expect-error: mutate because it is faster; content model is fine.
child.type = 'mdxJsxFlowElement'
}
if (child.type === 'mdxTextExpression') {
// @ts-expect-error: mutate because it is faster; content model is fine.
child.type = 'mdxFlowExpression'
}
if (
child.type === 'text' &&
/^[\t\r\n ]+$/.test(String(child.value))
) {
// Empty.
} else {
newChildren.push(child)
}
}
parent.children.splice(index, 1, ...newChildren)
return index
}
}
if (
node.type === 'mdxJsxFlowElement' ||
node.type === 'mdxJsxTextElement'
) {
const data = node.data || (node.data = {})
data._mdxExplicitJsx = true
}
if (
(node.type === 'mdxFlowExpression' ||
node.type === 'mdxTextExpression' ||
node.type === 'mdxjsEsm') &&
node.data &&
node.data.estree
) {
walk(node.data.estree, {
enter(node) {
if (node.type === 'JSXElement') {
const data = node.data || (node.data = {})
data._mdxExplicitJsx = true
}
}
})
}
})
}
}

View File

@@ -0,0 +1,44 @@
/**
* @import {MDXModule} from 'mdx/types.js'
* @import {RunOptions} from './util/resolve-evaluate-options.js'
*/
/** @type {new (code: string, ...args: Array<unknown>) => Function} **/
const AsyncFunction = Object.getPrototypeOf(run).constructor
/**
* Run code compiled with `outputFormat: 'function-body'`.
*
* > ☢️ **Danger**: this `eval`s JavaScript.
*
* @param {{toString(): string}} code
* JavaScript function body to run.
* @param {RunOptions} options
* Configuration (**required**).
* @return {Promise<MDXModule>}
* Promise to a module;
* the result is an object with a `default` field set to the component;
* anything else that was exported is available too.
*/
export async function run(code, options) {
return new AsyncFunction(String(code))(options)
}
/**
* Run code, synchronously.
*
* When possible please use the async `run`.
*
* > ☢️ **Danger**: this `eval`s JavaScript.
*
* @param {{toString(): string}} code
* JavaScript function body to run.
* @param {RunOptions} options
* Configuration (**required**).
* @return {MDXModule}
* Module.
*/
export function runSync(code, options) {
// eslint-disable-next-line no-new-func
return new Function(String(code))(options)
}

View File

@@ -0,0 +1,29 @@
/**
* @import {Node} from 'estree-jsx'
*/
// Fix to show references to above types in VS Code.
''
/**
* @param {Readonly<Node>} from
* Node to take from.
* @param {Node} to
* Node to add to.
* @returns {undefined}
* Nothing.
*/
export function create(from, to) {
/** @type {Array<keyof Node>} */
const fields = ['start', 'end', 'loc', 'range']
let index = -1
while (++index < fields.length) {
const field = fields[index]
if (field in from) {
// @ts-expect-error: assume theyre settable.
to[field] = from[field]
}
}
}

View File

@@ -0,0 +1,33 @@
/**
* @import {
Declaration,
Expression,
MaybeNamedClassDeclaration,
MaybeNamedFunctionDeclaration
* } from 'estree-jsx'
*/
import {ok as assert} from 'devlop'
/**
* Turn a declaration into an expression.
*
* Doesnt work for variable declarations, but thats fine for our use case
* because currently were using this utility for export default declarations,
* which cant contain variable declarations.
*
* @param {Readonly<Declaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration>} declaration
* Declaration.
* @returns {Expression}
* Expression.
*/
export function declarationToExpression(declaration) {
if (declaration.type === 'FunctionDeclaration') {
return {...declaration, type: 'FunctionExpression'}
}
// This is currently an internal utility so the next shouldnt happen or a
// maintainer is making a mistake.
assert(declaration.type === 'ClassDeclaration', 'unexpected node type')
return {...declaration, type: 'ClassExpression'}
}

View File

@@ -0,0 +1,27 @@
/**
* @import {
Declaration,
MaybeNamedClassDeclaration,
MaybeNamedFunctionDeclaration,
Node
* } from 'estree-jsx'
*/
// Fix to show references to above types in VS Code.
''
/**
* Check if `node` is a declaration.
*
* @param {Readonly<MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration | Node>} node
* Node to check.
* @returns {node is Declaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration}
* Whether `node` is a declaration.
*/
export function isDeclaration(node) {
return Boolean(
node.type === 'FunctionDeclaration' ||
node.type === 'ClassDeclaration' ||
node.type === 'VariableDeclaration'
)
}

View File

@@ -0,0 +1,104 @@
/**
* @import {
AssignmentProperty,
ExportSpecifier,
Expression,
Identifier,
ImportDefaultSpecifier,
ImportNamespaceSpecifier,
ImportSpecifier,
Literal,
VariableDeclarator
* } from 'estree-jsx'
*/
import {ok as assert} from 'devlop'
import {create} from './estree-util-create.js'
/**
* @param {ReadonlyArray<Readonly<ExportSpecifier> | Readonly<ImportDefaultSpecifier> | Readonly<ImportNamespaceSpecifier> | Readonly<ImportSpecifier>>} specifiers
* Specifiers.
* @param {Readonly<Expression>} init
* Initializer.
* @returns {Array<VariableDeclarator>}
* Declarations.
*/
export function specifiersToDeclarations(specifiers, init) {
let index = -1
/** @type {Array<VariableDeclarator>} */
const declarations = []
/** @type {Array<ExportSpecifier | ImportDefaultSpecifier | ImportSpecifier>} */
const otherSpecifiers = []
// Can only be one according to JS syntax.
/** @type {ImportNamespaceSpecifier | undefined} */
let importNamespaceSpecifier
while (++index < specifiers.length) {
const specifier = specifiers[index]
if (specifier.type === 'ImportNamespaceSpecifier') {
importNamespaceSpecifier = specifier
} else {
otherSpecifiers.push(specifier)
}
}
if (importNamespaceSpecifier) {
/** @type {VariableDeclarator} */
const declarator = {
type: 'VariableDeclarator',
id: importNamespaceSpecifier.local,
init
}
create(importNamespaceSpecifier, declarator)
declarations.push(declarator)
}
declarations.push({
type: 'VariableDeclarator',
id: {
type: 'ObjectPattern',
properties: otherSpecifiers.map(function (specifier) {
/** @type {Identifier | Literal} */
let key =
specifier.type === 'ImportSpecifier'
? specifier.imported
: specifier.type === 'ExportSpecifier'
? specifier.exported
: {type: 'Identifier', name: 'default'}
let value = specifier.local
// Switch them around if were exporting.
if (specifier.type === 'ExportSpecifier') {
value = key
key = specifier.local
}
// To do: what to do about literals?
// `const { a: 'b' } = c()` does not work?
assert(value.type === 'Identifier')
/** @type {AssignmentProperty} */
const property = {
type: 'Property',
kind: 'init',
shorthand:
key.type === 'Identifier' &&
value.type === 'Identifier' &&
key.name === value.name,
method: false,
computed: false,
key,
value
}
create(specifier, property)
return property
})
},
init: importNamespaceSpecifier
? {type: 'Identifier', name: importNamespaceSpecifier.local.name}
: init
})
return declarations
}

View File

@@ -0,0 +1,25 @@
/**
* @import {Expression} from 'estree-jsx'
*/
import {ok as assert} from 'devlop'
/**
* @param {ReadonlyArray<Expression>} expressions
* Expressions.
* @returns {Expression}
* Addition.
*/
export function toBinaryAddition(expressions) {
let index = -1
/** @type {Expression | undefined} */
let left
while (++index < expressions.length) {
const right = expressions[index]
left = left ? {type: 'BinaryExpression', left, operator: '+', right} : right
}
assert(left, 'expected non-empty `expressions` to be passed')
return left
}

View File

@@ -0,0 +1,73 @@
/**
* @import {
Identifier,
JSXIdentifier,
JSXMemberExpression,
Literal,
MemberExpression
* } from 'estree-jsx'
*/
import {ok as assert} from 'devlop'
import {name as isIdentifierName} from 'estree-util-is-identifier-name'
/**
* @param {ReadonlyArray<number | string>} ids
* Identifiers (example: `['list', 0]).
* @returns {Identifier | MemberExpression}
* Identifier or member expression.
*/
export function toIdOrMemberExpression(ids) {
let index = -1
/** @type {Identifier | Literal | MemberExpression | undefined} */
let object
while (++index < ids.length) {
const name = ids[index]
/** @type {Identifier | Literal} */
const id =
typeof name === 'string' && isIdentifierName(name)
? {type: 'Identifier', name}
: {type: 'Literal', value: name}
object = object
? {
type: 'MemberExpression',
object,
property: id,
computed: id.type === 'Literal',
optional: false
}
: id
}
assert(object, 'expected non-empty `ids` to be passed')
assert(object.type !== 'Literal', 'expected identifier as left-most value')
return object
}
/**
* @param {ReadonlyArray<number | string>} ids
* Identifiers (example: `['list', 0]).
* @returns {JSXIdentifier | JSXMemberExpression}
* Identifier or member expression.
*/
export function toJsxIdOrMemberExpression(ids) {
let index = -1
/** @type {JSXIdentifier | JSXMemberExpression | undefined} */
let object
while (++index < ids.length) {
const name = ids[index]
assert(
typeof name === 'string' && isIdentifierName(name, {jsx: true}),
'expected valid jsx identifier, not `' + name + '`'
)
/** @type {JSXIdentifier} */
const id = {type: 'JSXIdentifier', name}
object = object ? {type: 'JSXMemberExpression', object, property: id} : id
}
assert(object, 'expected non-empty `ids` to be passed')
return object
}

View File

@@ -0,0 +1,6 @@
import markdownExtensions from 'markdown-extensions'
export const md = markdownExtensions.map(function (d) {
return '.' + d
})
export const mdx = ['.mdx']

View File

@@ -0,0 +1,87 @@
/**
* @import {Fragment, Jsx, JsxDev} from 'hast-util-to-jsx-runtime'
* @import {MDXComponents} from 'mdx/types.js'
* @import {CompileOptions} from '../compile.js'
*/
/**
* @typedef {EvaluateProcessorOptions & RunOptions} EvaluateOptions
* Configuration for `evaluate`.
*
* @typedef {Omit<CompileOptions, 'baseUrl' | 'jsx' | 'jsxImportSource' | 'jsxRuntime' | 'outputFormat' | 'pragma' | 'pragmaFrag' | 'pragmaImportSource' | 'providerImportSource'> } EvaluateProcessorOptions
* Compile configuration without JSX options for evaluation.
*
* @typedef RunOptions
* Configuration to run compiled code.
*
* `Fragment`, `jsx`, and `jsxs` are used when the code is compiled in
* production mode (`development: false`).
* `Fragment` and `jsxDEV` are used when compiled in development mode
* (`development: true`).
* `useMDXComponents` is used when the code is compiled with
* `providerImportSource: '#'` (the exact value of this compile option
* doesnt matter).
* @property {URL | string | null | undefined} [baseUrl]
* Use this URL as `import.meta.url` and resolve `import` and `export … from`
* relative to it (optional, example: `import.meta.url`);
* this option can also be given at compile time in `CompileOptions`;
* you should pass this (likely at runtime), as you might get runtime errors
* when using `import.meta.url` / `import` / `export … from ` otherwise.
* @property {Fragment} Fragment
* Symbol to use for fragments (**required**).
* @property {Jsx | null | undefined} [jsx]
* Function to generate an element with static children in production mode.
* @property {JsxDev | null | undefined} [jsxDEV]
* Function to generate an element in development mode.
* @property {Jsx | null | undefined} [jsxs]
* Function to generate an element with dynamic children in production mode.
* @property {UseMdxComponents | null | undefined} [useMDXComponents]
* Function to get components from context.
*
* @callback UseMdxComponents
* Get components from context.
* @returns {MDXComponents}
* Current components.
*/
// Fix to show references to above types in VS Code.
''
/**
* Split compiletime options from runtime options.
*
* @param {Readonly<EvaluateOptions> | null | undefined} options
* Configuration.
* @returns {{compiletime: CompileOptions, runtime: RunOptions}}
* Split options.
*/
export function resolveEvaluateOptions(options) {
const {
Fragment,
baseUrl,
development,
jsx,
jsxDEV,
jsxs,
useMDXComponents,
...rest
} = options || {}
if (!Fragment) throw new Error('Expected `Fragment` given to `evaluate`')
if (development) {
if (!jsxDEV) throw new Error('Expected `jsxDEV` given to `evaluate`')
} else {
if (!jsx) throw new Error('Expected `jsx` given to `evaluate`')
if (!jsxs) throw new Error('Expected `jsxs` given to `evaluate`')
}
return {
compiletime: {
...rest,
development,
outputFormat: 'function-body',
providerImportSource: useMDXComponents ? '#' : undefined
},
runtime: {Fragment, baseUrl, jsx, jsxDEV, jsxs, useMDXComponents}
}
}

View File

@@ -0,0 +1,53 @@
/**
* @import {Compatible} from 'vfile'
* @import {CompileOptions} from '../compile.js'
* @import {ProcessorOptions} from '../core.js'
*/
import {VFile} from 'vfile'
import {md} from './extnames.js'
/**
* Create a file and options from a given `vfileCompatible` and options that
* might contain `format: 'detect'`.
*
* @param {Readonly<Compatible>} vfileCompatible
* File.
* @param {Readonly<CompileOptions> | null | undefined} [options]
* Configuration (optional).
* @returns {{file: VFile, options: ProcessorOptions}}
* File and options.
*/
export function resolveFileAndOptions(vfileCompatible, options) {
const file = looksLikeAVFile(vfileCompatible)
? vfileCompatible
: new VFile(vfileCompatible)
const {format, ...rest} = options || {}
return {
file,
options: {
format:
format === 'md' || format === 'mdx'
? format
: file.extname && (rest.mdExtensions || md).includes(file.extname)
? 'md'
: 'mdx',
...rest
}
}
}
/**
* @param {Readonly<Compatible> | null | undefined} [value]
* Thing.
* @returns {value is VFile}
* Check.
*/
function looksLikeAVFile(value) {
return Boolean(
value &&
typeof value === 'object' &&
'message' in value &&
'messages' in value
)
}

View File

@@ -0,0 +1,108 @@
{
"name": "@mdx-js/mdx",
"version": "3.1.1",
"description": "MDX compiler",
"license": "MIT",
"keywords": [
"jsx",
"markdown",
"mdx",
"remark"
],
"homepage": "https://mdxjs.com",
"repository": {
"type": "git",
"url": "https://github.com/mdx-js/mdx",
"directory": "packages/mdx/"
},
"bugs": "https://github.com/mdx-js/mdx/issues",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
},
"author": "John Otander <johnotander@gmail.com> (https://johno.com)",
"contributors": [
"John Otander <johnotander@gmail.com> (https://johno.com)",
"Tim Neutkens <tim@vercel.com>",
"Matija Marohnić <matija.marohnic@gmail.com>",
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"JounQin <admin@1stg.me> (https://www.1stg.me)",
"Christian Murphy <christian.murphy.42@gmail.com>"
],
"type": "module",
"sideEffects": false,
"exports": {
".": "./index.js",
"./internal-create-format-aware-processors": "./lib/util/create-format-aware-processors.js",
"./internal-extnames-to-regex": "./lib/util/extnames-to-regex.js"
},
"files": [
"lib/",
"index.d.ts.map",
"index.d.ts",
"index.js"
],
"dependencies": {
"@types/estree": "^1.0.0",
"@types/estree-jsx": "^1.0.0",
"@types/hast": "^3.0.0",
"@types/mdx": "^2.0.0",
"acorn": "^8.0.0",
"collapse-white-space": "^2.0.0",
"devlop": "^1.0.0",
"estree-util-is-identifier-name": "^3.0.0",
"estree-util-scope": "^1.0.0",
"estree-walker": "^3.0.0",
"hast-util-to-jsx-runtime": "^2.0.0",
"markdown-extensions": "^2.0.0",
"recma-build-jsx": "^1.0.0",
"recma-jsx": "^1.0.0",
"recma-stringify": "^1.0.0",
"rehype-recma": "^1.0.0",
"remark-mdx": "^3.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.0.0",
"source-map": "^0.7.0",
"unified": "^11.0.0",
"unist-util-position-from-estree": "^2.0.0",
"unist-util-stringify-position": "^4.0.0",
"unist-util-visit": "^5.0.0",
"vfile": "^6.0.0"
},
"scripts": {
"test": "npm run test-coverage",
"test-api": "node --conditions development --enable-source-maps test/index.js",
"test-coverage": "c8 --100 --reporter lcov npm run test-api"
},
"xo": {
"overrides": [
{
"files": [
"test/**/*.js"
],
"rules": {
"no-restricted-globals": "off"
}
},
{
"files": [
"**/*.ts"
],
"rules": {
"@typescript-eslint/array-type": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/consistent-type-definitions": "off"
}
}
],
"prettier": true,
"rules": {
"complexity": "off",
"logical-assignment-operators": "off",
"max-depth": "off",
"n/file-extension-in-import": "off",
"unicorn/prefer-at": "off",
"unicorn/prefer-code-point": "off"
}
}
}

View File

@@ -0,0 +1 @@
../../collapse-white-space@2.1.0/node_modules/collapse-white-space

View File

@@ -0,0 +1 @@
../../devlop@1.1.0/node_modules/devlop

View File

@@ -0,0 +1 @@
../../estree-util-is-identifier-name@3.0.0/node_modules/estree-util-is-identifier-name

View File

@@ -0,0 +1 @@
../../estree-util-scope@1.0.0/node_modules/estree-util-scope

View File

@@ -0,0 +1 @@
../../estree-walker@3.0.3/node_modules/estree-walker

View File

@@ -0,0 +1 @@
../../markdown-extensions@2.0.0/node_modules/markdown-extensions

View File

@@ -0,0 +1 @@
../../recma-build-jsx@1.0.0/node_modules/recma-build-jsx

View File

@@ -0,0 +1 @@
../../recma-jsx@1.0.1_acorn@8.16.0/node_modules/recma-jsx

View File

@@ -0,0 +1 @@
../../recma-stringify@1.0.0/node_modules/recma-stringify

View File

@@ -0,0 +1 @@
../../rehype-recma@1.0.0/node_modules/rehype-recma

View File

@@ -0,0 +1 @@
../../remark-mdx@3.1.1/node_modules/remark-mdx

View File

@@ -0,0 +1 @@
../../remark-parse@11.0.0/node_modules/remark-parse

View File

@@ -0,0 +1 @@
../../remark-rehype@11.1.2/node_modules/remark-rehype

View File

@@ -0,0 +1 @@
../../unified@11.0.5/node_modules/unified

View File

@@ -0,0 +1 @@
../../unist-util-position-from-estree@2.0.0/node_modules/unist-util-position-from-estree

View File

@@ -0,0 +1 @@
../../unist-util-stringify-position@4.0.0/node_modules/unist-util-stringify-position

View File

@@ -0,0 +1 @@
../../unist-util-visit@5.1.0/node_modules/unist-util-visit

View File

@@ -0,0 +1 @@
../../vfile@6.0.3/node_modules/vfile

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,36 @@
{
"name": "@next/env",
"version": "16.1.6",
"keywords": [
"react",
"next",
"next.js",
"dotenv"
],
"description": "Next.js dotenv file loading",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "packages/next-env"
},
"author": "Next.js Team <support@vercel.com>",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"dev": "ncc build ./index.ts -w -o dist/",
"prebuild:source": "node ../../scripts/rm.mjs dist",
"types": "tsc --declaration --emitDeclarationOnly --declarationDir dist",
"build:source": "ncc build ./index.ts -o ./dist/ --minify --no-cache --no-source-map-register",
"build": "pnpm build:source && pnpm types",
"prepublishOnly": "cd ../../ && turbo run build"
},
"devDependencies": {
"@vercel/ncc": "0.34.0",
"dotenv": "16.3.1",
"dotenv-expand": "10.0.0"
}
}

View File

@@ -0,0 +1,72 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextAPI = void 0;
const NoopContextManager_1 = require("../context/NoopContextManager");
const global_utils_1 = require("../internal/global-utils");
const diag_1 = require("./diag");
const API_NAME = 'context';
const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager();
/**
* Singleton object which represents the entry point to the OpenTelemetry Context API
*
* @since 1.0.0
*/
class ContextAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
constructor() { }
/** Get the singleton instance of the Context API */
static getInstance() {
if (!this._instance) {
this._instance = new ContextAPI();
}
return this._instance;
}
/**
* Set the current context manager.
*
* @returns true if the context manager was successfully registered, else false
*/
setGlobalContextManager(contextManager) {
return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance());
}
/**
* Get the currently active context
*/
active() {
return this._getContextManager().active();
}
/**
* Execute a function with an active context
*
* @param context context to be active during function execution
* @param fn function to execute in a context
* @param thisArg optional receiver to be used for calling fn
* @param args optional arguments forwarded to fn
*/
with(context, fn, thisArg, ...args) {
return this._getContextManager().with(context, fn, thisArg, ...args);
}
/**
* Bind a context to a target function or event emitter
*
* @param context context to bind to the event emitter or function. Defaults to the currently active context
* @param target function or event emitter to bind
*/
bind(context, target) {
return this._getContextManager().bind(context, target);
}
_getContextManager() {
return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER;
}
/** Disable and remove the global context manager */
disable() {
this._getContextManager().disable();
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
}
exports.ContextAPI = ContextAPI;
//# sourceMappingURL=context.js.map

View File

@@ -0,0 +1,84 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagAPI = void 0;
const ComponentLogger_1 = require("../diag/ComponentLogger");
const logLevelLogger_1 = require("../diag/internal/logLevelLogger");
const types_1 = require("../diag/types");
const global_utils_1 = require("../internal/global-utils");
const API_NAME = 'diag';
/**
* Singleton object which represents the entry point to the OpenTelemetry internal
* diagnostic API
*
* @since 1.0.0
*/
class DiagAPI {
/** Get the singleton instance of the DiagAPI API */
static instance() {
if (!this._instance) {
this._instance = new DiagAPI();
}
return this._instance;
}
/**
* Private internal constructor
* @private
*/
constructor() {
function _logProxy(funcName) {
return function (...args) {
const logger = (0, global_utils_1.getGlobal)('diag');
// shortcut if logger not set
if (!logger)
return;
return logger[funcName](...args);
};
}
// Using self local variable for minification purposes as 'this' cannot be minified
const self = this;
// DiagAPI specific functions
const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => {
var _a, _b, _c;
if (logger === self) {
// There isn't much we can do here.
// Logging to the console might break the user application.
// Try to log to self. If a logger was previously registered it will receive the log.
const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation');
self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
return false;
}
if (typeof optionsOrLogLevel === 'number') {
optionsOrLogLevel = {
logLevel: optionsOrLogLevel,
};
}
const oldLogger = (0, global_utils_1.getGlobal)('diag');
const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger);
// There already is an logger registered. We'll let it know before overwriting it.
if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : '<failed to generate stacktrace>';
oldLogger.warn(`Current logger will be overwritten from ${stack}`);
newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
}
return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true);
};
self.setLogger = setLogger;
self.disable = () => {
(0, global_utils_1.unregisterGlobal)(API_NAME, self);
};
self.createComponentLogger = (options) => {
return new ComponentLogger_1.DiagComponentLogger(options);
};
self.verbose = _logProxy('verbose');
self.debug = _logProxy('debug');
self.info = _logProxy('info');
self.warn = _logProxy('warn');
self.error = _logProxy('error');
}
}
exports.DiagAPI = DiagAPI;
//# sourceMappingURL=diag.js.map

View File

@@ -0,0 +1,50 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetricsAPI = void 0;
const NoopMeterProvider_1 = require("../metrics/NoopMeterProvider");
const global_utils_1 = require("../internal/global-utils");
const diag_1 = require("./diag");
const API_NAME = 'metrics';
/**
* Singleton object which represents the entry point to the OpenTelemetry Metrics API
*/
class MetricsAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
constructor() { }
/** Get the singleton instance of the Metrics API */
static getInstance() {
if (!this._instance) {
this._instance = new MetricsAPI();
}
return this._instance;
}
/**
* Set the current global meter provider.
* Returns true if the meter provider was successfully registered, else false.
*/
setGlobalMeterProvider(provider) {
return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance());
}
/**
* Returns the global meter provider.
*/
getMeterProvider() {
return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER;
}
/**
* Returns a meter from the global meter provider.
*/
getMeter(name, version, options) {
return this.getMeterProvider().getMeter(name, version, options);
}
/** Remove the global meter provider */
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
}
exports.MetricsAPI = MetricsAPI;
//# sourceMappingURL=metrics.js.map

View File

@@ -0,0 +1,80 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PropagationAPI = void 0;
const global_utils_1 = require("../internal/global-utils");
const NoopTextMapPropagator_1 = require("../propagation/NoopTextMapPropagator");
const TextMapPropagator_1 = require("../propagation/TextMapPropagator");
const context_helpers_1 = require("../baggage/context-helpers");
const utils_1 = require("../baggage/utils");
const diag_1 = require("./diag");
const API_NAME = 'propagation';
const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator();
/**
* Singleton object which represents the entry point to the OpenTelemetry Propagation API
*
* @since 1.0.0
*/
class PropagationAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
constructor() {
this.createBaggage = utils_1.createBaggage;
this.getBaggage = context_helpers_1.getBaggage;
this.getActiveBaggage = context_helpers_1.getActiveBaggage;
this.setBaggage = context_helpers_1.setBaggage;
this.deleteBaggage = context_helpers_1.deleteBaggage;
}
/** Get the singleton instance of the Propagator API */
static getInstance() {
if (!this._instance) {
this._instance = new PropagationAPI();
}
return this._instance;
}
/**
* Set the current propagator.
*
* @returns true if the propagator was successfully registered, else false
*/
setGlobalPropagator(propagator) {
return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance());
}
/**
* Inject context into a carrier to be propagated inter-process
*
* @param context Context carrying tracing data to inject
* @param carrier carrier to inject context into
* @param setter Function used to set values on the carrier
*/
inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) {
return this._getGlobalPropagator().inject(context, carrier, setter);
}
/**
* Extract context from a carrier
*
* @param context Context which the newly created context will inherit from
* @param carrier Carrier to extract context from
* @param getter Function used to extract keys from a carrier
*/
extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) {
return this._getGlobalPropagator().extract(context, carrier, getter);
}
/**
* Return a list of all fields which may be used by the propagator.
*/
fields() {
return this._getGlobalPropagator().fields();
}
/** Remove the global propagator */
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
_getGlobalPropagator() {
return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
}
}
exports.PropagationAPI = PropagationAPI;
//# sourceMappingURL=propagation.js.map

View File

@@ -0,0 +1,70 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceAPI = void 0;
const global_utils_1 = require("../internal/global-utils");
const ProxyTracerProvider_1 = require("../trace/ProxyTracerProvider");
const spancontext_utils_1 = require("../trace/spancontext-utils");
const context_utils_1 = require("../trace/context-utils");
const diag_1 = require("./diag");
const API_NAME = 'trace';
/**
* Singleton object which represents the entry point to the OpenTelemetry Tracing API
*
* @since 1.0.0
*/
class TraceAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
constructor() {
this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider();
this.wrapSpanContext = spancontext_utils_1.wrapSpanContext;
this.isSpanContextValid = spancontext_utils_1.isSpanContextValid;
this.deleteSpan = context_utils_1.deleteSpan;
this.getSpan = context_utils_1.getSpan;
this.getActiveSpan = context_utils_1.getActiveSpan;
this.getSpanContext = context_utils_1.getSpanContext;
this.setSpan = context_utils_1.setSpan;
this.setSpanContext = context_utils_1.setSpanContext;
}
/** Get the singleton instance of the Trace API */
static getInstance() {
if (!this._instance) {
this._instance = new TraceAPI();
}
return this._instance;
}
/**
* Set the current global tracer.
*
* @returns true if the tracer provider was successfully registered, else false
*/
setGlobalTracerProvider(provider) {
const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance());
if (success) {
this._proxyTracerProvider.setDelegate(provider);
}
return success;
}
/**
* Returns the global tracer provider.
*/
getTracerProvider() {
return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider;
}
/**
* Returns a tracer from the global tracer provider.
*/
getTracer(name, version) {
return this.getTracerProvider().getTracer(name, version);
}
/** Remove the global tracer provider */
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider();
}
}
exports.TraceAPI = TraceAPI;
//# sourceMappingURL=trace.js.map

View File

@@ -0,0 +1,52 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0;
const context_1 = require("../api/context");
const context_2 = require("../context/context");
/**
* Baggage key
*/
const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key');
/**
* Retrieve the current baggage from the given context
*
* @param {Context} Context that manage all context values
* @returns {Baggage} Extracted baggage from the context
*/
function getBaggage(context) {
return context.getValue(BAGGAGE_KEY) || undefined;
}
exports.getBaggage = getBaggage;
/**
* Retrieve the current baggage from the active/current context
*
* @returns {Baggage} Extracted baggage from the context
*/
function getActiveBaggage() {
return getBaggage(context_1.ContextAPI.getInstance().active());
}
exports.getActiveBaggage = getActiveBaggage;
/**
* Store a baggage in the given context
*
* @param {Context} Context that manage all context values
* @param {Baggage} baggage that will be set in the actual context
*/
function setBaggage(context, baggage) {
return context.setValue(BAGGAGE_KEY, baggage);
}
exports.setBaggage = setBaggage;
/**
* Delete the baggage stored in the given context
*
* @param {Context} Context that manage all context values
*/
function deleteBaggage(context) {
return context.deleteValue(BAGGAGE_KEY);
}
exports.deleteBaggage = deleteBaggage;
//# sourceMappingURL=context-helpers.js.map

View File

@@ -0,0 +1,44 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaggageImpl = void 0;
class BaggageImpl {
constructor(entries) {
this._entries = entries ? new Map(entries) : new Map();
}
getEntry(key) {
const entry = this._entries.get(key);
if (!entry) {
return undefined;
}
return Object.assign({}, entry);
}
getAllEntries() {
return Array.from(this._entries.entries());
}
setEntry(key, entry) {
const newBaggage = new BaggageImpl(this._entries);
newBaggage._entries.set(key, entry);
return newBaggage;
}
removeEntry(key) {
const newBaggage = new BaggageImpl(this._entries);
newBaggage._entries.delete(key);
return newBaggage;
}
removeEntries(...keys) {
const newBaggage = new BaggageImpl(this._entries);
for (const key of keys) {
newBaggage._entries.delete(key);
}
return newBaggage;
}
clear() {
return new BaggageImpl();
}
}
exports.BaggageImpl = BaggageImpl;
//# sourceMappingURL=baggage-impl.js.map

View File

@@ -0,0 +1,12 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.baggageEntryMetadataSymbol = void 0;
/**
* Symbol used to make BaggageEntryMetadata an opaque type
*/
exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata');
//# sourceMappingURL=symbol.js.map

View File

@@ -0,0 +1,41 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.baggageEntryMetadataFromString = exports.createBaggage = void 0;
const diag_1 = require("../api/diag");
const baggage_impl_1 = require("./internal/baggage-impl");
const symbol_1 = require("./internal/symbol");
const diag = diag_1.DiagAPI.instance();
/**
* Create a new Baggage with optional entries
*
* @param entries An array of baggage entries the new baggage should contain
*/
function createBaggage(entries = {}) {
return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries)));
}
exports.createBaggage = createBaggage;
/**
* Create a serializable BaggageEntryMetadata object from a string.
*
* @param str string metadata. Format is currently not defined by the spec and has no special meaning.
*
* @since 1.0.0
*/
function baggageEntryMetadataFromString(str) {
if (typeof str !== 'string') {
diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);
str = '';
}
return {
__TYPE__: symbol_1.baggageEntryMetadataSymbol,
toString() {
return str;
},
};
}
exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString;
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,16 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.context = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const context_1 = require("./api/context");
/**
* Entrypoint for context API
* @since 1.0.0
*/
exports.context = context_1.ContextAPI.getInstance();
//# sourceMappingURL=context-api.js.map

View File

@@ -0,0 +1,27 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopContextManager = void 0;
const context_1 = require("./context");
class NoopContextManager {
active() {
return context_1.ROOT_CONTEXT;
}
with(_context, fn, thisArg, ...args) {
return fn.call(thisArg, ...args);
}
bind(_context, target) {
return target;
}
enable() {
return this;
}
disable() {
return this;
}
}
exports.NoopContextManager = NoopContextManager;
//# sourceMappingURL=NoopContextManager.js.map

View File

@@ -0,0 +1,52 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ROOT_CONTEXT = exports.createContextKey = void 0;
/**
* Get a key to uniquely identify a context value
*
* @since 1.0.0
*/
function createContextKey(description) {
// The specification states that for the same input, multiple calls should
// return different keys. Due to the nature of the JS dependency management
// system, this creates problems where multiple versions of some package
// could hold different keys for the same property.
//
// Therefore, we use Symbol.for which returns the same key for the same input.
return Symbol.for(description);
}
exports.createContextKey = createContextKey;
class BaseContext {
/**
* Construct a new context which inherits values from an optional parent context.
*
* @param parentContext a context from which to inherit values
*/
constructor(parentContext) {
// for minification
const self = this;
self._currentContext = parentContext ? new Map(parentContext) : new Map();
self.getValue = (key) => self._currentContext.get(key);
self.setValue = (key, value) => {
const context = new BaseContext(self._currentContext);
context._currentContext.set(key, value);
return context;
};
self.deleteValue = (key) => {
const context = new BaseContext(self._currentContext);
context._currentContext.delete(key);
return context;
};
}
}
/**
* The root context is used as the default parent context when there is no active context
*
* @since 1.0.0
*/
exports.ROOT_CONTEXT = new BaseContext();
//# sourceMappingURL=context.js.map

View File

@@ -0,0 +1,20 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.diag = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const diag_1 = require("./api/diag");
/**
* Entrypoint for Diag API.
* Defines Diagnostic handler used for internal diagnostic logging operations.
* The default provides a Noop DiagLogger implementation which may be changed via the
* diag.setLogger(logger: DiagLogger) function.
*
* @since 1.0.0
*/
exports.diag = diag_1.DiagAPI.instance();
//# sourceMappingURL=diag-api.js.map

View File

@@ -0,0 +1,47 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagComponentLogger = void 0;
const global_utils_1 = require("../internal/global-utils");
/**
* Component Logger which is meant to be used as part of any component which
* will add automatically additional namespace in front of the log message.
* It will then forward all message to global diag logger
* @example
* const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });
* cLogger.debug('test');
* // @opentelemetry/instrumentation-http test
*/
class DiagComponentLogger {
constructor(props) {
this._namespace = props.namespace || 'DiagComponentLogger';
}
debug(...args) {
return logProxy('debug', this._namespace, args);
}
error(...args) {
return logProxy('error', this._namespace, args);
}
info(...args) {
return logProxy('info', this._namespace, args);
}
warn(...args) {
return logProxy('warn', this._namespace, args);
}
verbose(...args) {
return logProxy('verbose', this._namespace, args);
}
}
exports.DiagComponentLogger = DiagComponentLogger;
function logProxy(funcName, namespace, args) {
const logger = (0, global_utils_1.getGlobal)('diag');
// shortcut if logger not set
if (!logger) {
return;
}
return logger[funcName](namespace, ...args);
}
//# sourceMappingURL=ComponentLogger.js.map

View File

@@ -0,0 +1,73 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagConsoleLogger = exports._originalConsoleMethods = void 0;
const consoleMap = [
{ n: 'error', c: 'error' },
{ n: 'warn', c: 'warn' },
{ n: 'info', c: 'info' },
{ n: 'debug', c: 'debug' },
{ n: 'verbose', c: 'trace' },
];
// Save original console methods at module load time, before any instrumentation
// can wrap them. This ensures DiagConsoleLogger calls the unwrapped originals.
// Exported for testing only — not part of the public API.
exports._originalConsoleMethods = {};
if (typeof console !== 'undefined') {
const keys = [
'error',
'warn',
'info',
'debug',
'trace',
'log',
];
for (const key of keys) {
// eslint-disable-next-line no-console
if (typeof console[key] === 'function') {
// eslint-disable-next-line no-console
exports._originalConsoleMethods[key] = console[key];
}
}
}
/**
* A simple Immutable Console based diagnostic logger which will output any messages to the Console.
* If you want to limit the amount of logging to a specific level or lower use the
* {@link createLogLevelDiagLogger}
*
* @since 1.0.0
*/
class DiagConsoleLogger {
constructor() {
function _consoleFunc(funcName) {
return function (...args) {
// Prefer original (pre-instrumentation) methods saved at module load time.
let theFunc = exports._originalConsoleMethods[funcName];
// Some environments only expose the console when the F12 developer console is open
if (typeof theFunc !== 'function') {
theFunc = exports._originalConsoleMethods['log'];
}
// Fall back in case console was not available at module load time but became available later.
if (typeof theFunc !== 'function' && console) {
// eslint-disable-next-line no-console
theFunc = console[funcName];
if (typeof theFunc !== 'function') {
// eslint-disable-next-line no-console
theFunc = console.log;
}
}
if (typeof theFunc === 'function') {
return theFunc.apply(console, args);
}
};
}
for (let i = 0; i < consoleMap.length; i++) {
this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);
}
}
}
exports.DiagConsoleLogger = DiagConsoleLogger;
//# sourceMappingURL=consoleLogger.js.map

View File

@@ -0,0 +1,34 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLogLevelDiagLogger = void 0;
const types_1 = require("../types");
function createLogLevelDiagLogger(maxLevel, logger) {
if (maxLevel < types_1.DiagLogLevel.NONE) {
maxLevel = types_1.DiagLogLevel.NONE;
}
else if (maxLevel > types_1.DiagLogLevel.ALL) {
maxLevel = types_1.DiagLogLevel.ALL;
}
// In case the logger is null or undefined
logger = logger || {};
function _filterFunc(funcName, theLevel) {
const theFunc = logger[funcName];
if (typeof theFunc === 'function' && maxLevel >= theLevel) {
return theFunc.bind(logger);
}
return function () { };
}
return {
error: _filterFunc('error', types_1.DiagLogLevel.ERROR),
warn: _filterFunc('warn', types_1.DiagLogLevel.WARN),
info: _filterFunc('info', types_1.DiagLogLevel.INFO),
debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG),
verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE),
};
}
exports.createLogLevelDiagLogger = createLogLevelDiagLogger;
//# sourceMappingURL=logLevelLogger.js.map

View File

@@ -0,0 +1,33 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagLogLevel = void 0;
/**
* Defines the available internal logging levels for the diagnostic logger, the numeric values
* of the levels are defined to match the original values from the initial LogLevel to avoid
* compatibility/migration issues for any implementation that assume the numeric ordering.
*/
var DiagLogLevel;
(function (DiagLogLevel) {
/** Diagnostic Logging level setting to disable all logging (except and forced logs) */
DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE";
/** Identifies an error scenario */
DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR";
/** Identifies a warning scenario */
DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN";
/** General informational log message */
DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO";
/** General debug log message */
DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG";
/**
* Detailed trace level logging should only be used for development, should only be set
* in a development environment.
*/
DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE";
/** Used to set the logging level to include all logging */
DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL";
})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {}));
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1,71 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0;
var utils_1 = require("./baggage/utils");
Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } });
// Context APIs
var context_1 = require("./context/context");
Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function () { return context_1.createContextKey; } });
Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } });
// Diag APIs
var consoleLogger_1 = require("./diag/consoleLogger");
Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } });
var types_1 = require("./diag/types");
Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function () { return types_1.DiagLogLevel; } });
// Metrics APIs
var NoopMeter_1 = require("./metrics/NoopMeter");
Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } });
var Metric_1 = require("./metrics/Metric");
Object.defineProperty(exports, "ValueType", { enumerable: true, get: function () { return Metric_1.ValueType; } });
// Propagation APIs
var TextMapPropagator_1 = require("./propagation/TextMapPropagator");
Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } });
Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } });
var ProxyTracer_1 = require("./trace/ProxyTracer");
Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } });
// TODO: Remove ProxyTracerProvider export in the next major version.
var ProxyTracerProvider_1 = require("./trace/ProxyTracerProvider");
Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } });
var SamplingResult_1 = require("./trace/SamplingResult");
Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } });
var span_kind_1 = require("./trace/span_kind");
Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return span_kind_1.SpanKind; } });
var status_1 = require("./trace/status");
Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return status_1.SpanStatusCode; } });
var trace_flags_1 = require("./trace/trace_flags");
Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function () { return trace_flags_1.TraceFlags; } });
var utils_2 = require("./trace/internal/utils");
Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function () { return utils_2.createTraceState; } });
var spancontext_utils_1 = require("./trace/spancontext-utils");
Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } });
Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } });
Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } });
var invalid_span_constants_1 = require("./trace/invalid-span-constants");
Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } });
Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } });
Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } });
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const context_api_1 = require("./context-api");
Object.defineProperty(exports, "context", { enumerable: true, get: function () { return context_api_1.context; } });
const diag_api_1 = require("./diag-api");
Object.defineProperty(exports, "diag", { enumerable: true, get: function () { return diag_api_1.diag; } });
const metrics_api_1 = require("./metrics-api");
Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return metrics_api_1.metrics; } });
const propagation_api_1 = require("./propagation-api");
Object.defineProperty(exports, "propagation", { enumerable: true, get: function () { return propagation_api_1.propagation; } });
const trace_api_1 = require("./trace-api");
Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return trace_api_1.trace; } });
// Default export.
exports.default = {
context: context_api_1.context,
diag: diag_api_1.diag,
metrics: metrics_api_1.metrics,
propagation: propagation_api_1.propagation,
trace: trace_api_1.trace,
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,60 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0;
const version_1 = require("../version");
const semver_1 = require("./semver");
const major = version_1.VERSION.split('.')[0];
const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
const _global = (typeof globalThis === 'object'
? globalThis
: typeof self === 'object'
? self
: typeof window === 'object'
? window
: typeof global === 'object'
? global
: {});
function registerGlobal(type, instance, diag, allowOverride = false) {
var _a;
const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
version: version_1.VERSION,
});
if (!allowOverride && api[type]) {
// already registered an API of this type
const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
diag.error(err.stack || err.message);
return false;
}
if (api.version !== version_1.VERSION) {
// All registered APIs must be of the same version exactly
const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`);
diag.error(err.stack || err.message);
return false;
}
api[type] = instance;
diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);
return true;
}
exports.registerGlobal = registerGlobal;
function getGlobal(type) {
var _a, _b;
const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) {
return;
}
return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
}
exports.getGlobal = getGlobal;
function unregisterGlobal(type, diag) {
diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);
const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
if (api) {
delete api[type];
}
}
exports.unregisterGlobal = unregisterGlobal;
//# sourceMappingURL=global-utils.js.map

View File

@@ -0,0 +1,111 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCompatible = exports._makeCompatibilityCheck = void 0;
const version_1 = require("../version");
const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
/**
* Create a function to test an API version to see if it is compatible with the provided ownVersion.
*
* The returned function has the following semantics:
* - Exact match is always compatible
* - Major versions must match exactly
* - 1.x package cannot use global 2.x package
* - 2.x package cannot use global 1.x package
* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API
* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects
* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3
* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor
* - Patch and build tag differences are not considered at this time
*
* @param ownVersion version which should be checked against
*/
function _makeCompatibilityCheck(ownVersion) {
const acceptedVersions = new Set([ownVersion]);
const rejectedVersions = new Set();
const myVersionMatch = ownVersion.match(re);
if (!myVersionMatch) {
// we cannot guarantee compatibility so we always return noop
return () => false;
}
const ownVersionParsed = {
major: +myVersionMatch[1],
minor: +myVersionMatch[2],
patch: +myVersionMatch[3],
prerelease: myVersionMatch[4],
};
// if ownVersion has a prerelease tag, versions must match exactly
if (ownVersionParsed.prerelease != null) {
return function isExactmatch(globalVersion) {
return globalVersion === ownVersion;
};
}
function _reject(v) {
rejectedVersions.add(v);
return false;
}
function _accept(v) {
acceptedVersions.add(v);
return true;
}
return function isCompatible(globalVersion) {
if (acceptedVersions.has(globalVersion)) {
return true;
}
if (rejectedVersions.has(globalVersion)) {
return false;
}
const globalVersionMatch = globalVersion.match(re);
if (!globalVersionMatch) {
// cannot parse other version
// we cannot guarantee compatibility so we always noop
return _reject(globalVersion);
}
const globalVersionParsed = {
major: +globalVersionMatch[1],
minor: +globalVersionMatch[2],
patch: +globalVersionMatch[3],
prerelease: globalVersionMatch[4],
};
// if globalVersion has a prerelease tag, versions must match exactly
if (globalVersionParsed.prerelease != null) {
return _reject(globalVersion);
}
// major versions must match
if (ownVersionParsed.major !== globalVersionParsed.major) {
return _reject(globalVersion);
}
if (ownVersionParsed.major === 0) {
if (ownVersionParsed.minor === globalVersionParsed.minor &&
ownVersionParsed.patch <= globalVersionParsed.patch) {
return _accept(globalVersion);
}
return _reject(globalVersion);
}
if (ownVersionParsed.minor <= globalVersionParsed.minor) {
return _accept(globalVersion);
}
return _reject(globalVersion);
};
}
exports._makeCompatibilityCheck = _makeCompatibilityCheck;
/**
* Test an API version to see if it is compatible with this API.
*
* - Exact match is always compatible
* - Major versions must match exactly
* - 1.x package cannot use global 2.x package
* - 2.x package cannot use global 1.x package
* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API
* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects
* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3
* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor
* - Patch and build tag differences are not considered at this time
*
* @param version version of the API requesting an instance of the global API
*/
exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION);
//# sourceMappingURL=semver.js.map

View File

@@ -0,0 +1,17 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.metrics = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const metrics_1 = require("./api/metrics");
/**
* Entrypoint for metrics API
*
* @since 1.3.0
*/
exports.metrics = metrics_1.MetricsAPI.getInstance();
//# sourceMappingURL=metrics-api.js.map

View File

@@ -0,0 +1,18 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueType = void 0;
/**
* The Type of value. It describes how the data is reported.
*
* @since 1.3.0
*/
var ValueType;
(function (ValueType) {
ValueType[ValueType["INT"] = 0] = "INT";
ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE";
})(ValueType = exports.ValueType || (exports.ValueType = {}));
//# sourceMappingURL=Metric.js.map

View File

@@ -0,0 +1,118 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0;
/**
* NoopMeter is a noop implementation of the {@link Meter} interface. It reuses
* constant NoopMetrics for all of its methods.
*/
class NoopMeter {
constructor() { }
/**
* @see {@link Meter.createGauge}
*/
createGauge(_name, _options) {
return exports.NOOP_GAUGE_METRIC;
}
/**
* @see {@link Meter.createHistogram}
*/
createHistogram(_name, _options) {
return exports.NOOP_HISTOGRAM_METRIC;
}
/**
* @see {@link Meter.createCounter}
*/
createCounter(_name, _options) {
return exports.NOOP_COUNTER_METRIC;
}
/**
* @see {@link Meter.createUpDownCounter}
*/
createUpDownCounter(_name, _options) {
return exports.NOOP_UP_DOWN_COUNTER_METRIC;
}
/**
* @see {@link Meter.createObservableGauge}
*/
createObservableGauge(_name, _options) {
return exports.NOOP_OBSERVABLE_GAUGE_METRIC;
}
/**
* @see {@link Meter.createObservableCounter}
*/
createObservableCounter(_name, _options) {
return exports.NOOP_OBSERVABLE_COUNTER_METRIC;
}
/**
* @see {@link Meter.createObservableUpDownCounter}
*/
createObservableUpDownCounter(_name, _options) {
return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
}
/**
* @see {@link Meter.addBatchObservableCallback}
*/
addBatchObservableCallback(_callback, _observables) { }
/**
* @see {@link Meter.removeBatchObservableCallback}
*/
removeBatchObservableCallback(_callback) { }
}
exports.NoopMeter = NoopMeter;
class NoopMetric {
}
exports.NoopMetric = NoopMetric;
class NoopCounterMetric extends NoopMetric {
add(_value, _attributes) { }
}
exports.NoopCounterMetric = NoopCounterMetric;
class NoopUpDownCounterMetric extends NoopMetric {
add(_value, _attributes) { }
}
exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric;
class NoopGaugeMetric extends NoopMetric {
record(_value, _attributes) { }
}
exports.NoopGaugeMetric = NoopGaugeMetric;
class NoopHistogramMetric extends NoopMetric {
record(_value, _attributes) { }
}
exports.NoopHistogramMetric = NoopHistogramMetric;
class NoopObservableMetric {
addCallback(_callback) { }
removeCallback(_callback) { }
}
exports.NoopObservableMetric = NoopObservableMetric;
class NoopObservableCounterMetric extends NoopObservableMetric {
}
exports.NoopObservableCounterMetric = NoopObservableCounterMetric;
class NoopObservableGaugeMetric extends NoopObservableMetric {
}
exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric;
class NoopObservableUpDownCounterMetric extends NoopObservableMetric {
}
exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric;
exports.NOOP_METER = new NoopMeter();
// Synchronous instruments
exports.NOOP_COUNTER_METRIC = new NoopCounterMetric();
exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric();
exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();
exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();
// Asynchronous instruments
exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();
exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();
exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();
/**
* Create a no-op Meter
*
* @since 1.3.0
*/
function createNoopMeter() {
return exports.NOOP_METER;
}
exports.createNoopMeter = createNoopMeter;
//# sourceMappingURL=NoopMeter.js.map

View File

@@ -0,0 +1,20 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0;
const NoopMeter_1 = require("./NoopMeter");
/**
* An implementation of the {@link MeterProvider} which returns an impotent Meter
* for all calls to `getMeter`
*/
class NoopMeterProvider {
getMeter(_name, _version, _options) {
return NoopMeter_1.NOOP_METER;
}
}
exports.NoopMeterProvider = NoopMeterProvider;
exports.NOOP_METER_PROVIDER = new NoopMeterProvider();
//# sourceMappingURL=NoopMeterProvider.js.map

View File

@@ -0,0 +1,17 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.propagation = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const propagation_1 = require("./api/propagation");
/**
* Entrypoint for propagation API
*
* @since 1.0.0
*/
exports.propagation = propagation_1.PropagationAPI.getInstance();
//# sourceMappingURL=propagation-api.js.map

View File

@@ -0,0 +1,23 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTextMapPropagator = void 0;
/**
* No-op implementations of {@link TextMapPropagator}.
*/
class NoopTextMapPropagator {
/** Noop inject function does nothing */
inject(_context, _carrier) { }
/** Noop extract function does nothing and returns the input context */
extract(context, _carrier) {
return context;
}
fields() {
return [];
}
}
exports.NoopTextMapPropagator = NoopTextMapPropagator;
//# sourceMappingURL=NoopTextMapPropagator.js.map

View File

@@ -0,0 +1,36 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0;
/**
* @since 1.0.0
*/
exports.defaultTextMapGetter = {
get(carrier, key) {
if (carrier == null) {
return undefined;
}
return carrier[key];
},
keys(carrier) {
if (carrier == null) {
return [];
}
return Object.keys(carrier);
},
};
/**
* @since 1.0.0
*/
exports.defaultTextMapSetter = {
set(carrier, key, value) {
if (carrier == null) {
return;
}
carrier[key] = value;
},
};
//# sourceMappingURL=TextMapPropagator.js.map

View File

@@ -0,0 +1,17 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const trace_1 = require("./api/trace");
/**
* Entrypoint for trace API
*
* @since 1.0.0
*/
exports.trace = trace_1.TraceAPI.getInstance();
//# sourceMappingURL=trace-api.js.map

View File

@@ -0,0 +1,58 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NonRecordingSpan = void 0;
const invalid_span_constants_1 = require("./invalid-span-constants");
/**
* The NonRecordingSpan is the default {@link Span} that is used when no Span
* implementation is available. All operations are no-op including context
* propagation.
*/
class NonRecordingSpan {
constructor(spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) {
this._spanContext = spanContext;
}
// Returns a SpanContext.
spanContext() {
return this._spanContext;
}
// By default does nothing
setAttribute(_key, _value) {
return this;
}
// By default does nothing
setAttributes(_attributes) {
return this;
}
// By default does nothing
addEvent(_name, _attributes) {
return this;
}
addLink(_link) {
return this;
}
addLinks(_links) {
return this;
}
// By default does nothing
setStatus(_status) {
return this;
}
// By default does nothing
updateName(_name) {
return this;
}
// By default does nothing
end(_endTime) { }
// isRecording always returns false for NonRecordingSpan.
isRecording() {
return false;
}
// By default does nothing
recordException(_exception, _time) { }
}
exports.NonRecordingSpan = NonRecordingSpan;
//# sourceMappingURL=NonRecordingSpan.js.map

View File

@@ -0,0 +1,68 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTracer = void 0;
const context_1 = require("../api/context");
const context_utils_1 = require("../trace/context-utils");
const NonRecordingSpan_1 = require("./NonRecordingSpan");
const spancontext_utils_1 = require("./spancontext-utils");
const contextApi = context_1.ContextAPI.getInstance();
/**
* No-op implementations of {@link Tracer}.
*/
class NoopTracer {
// startSpan starts a noop span.
startSpan(name, options, context = contextApi.active()) {
const root = Boolean(options === null || options === void 0 ? void 0 : options.root);
if (root) {
return new NonRecordingSpan_1.NonRecordingSpan();
}
const parentFromContext = context && (0, context_utils_1.getSpanContext)(context);
if (isSpanContext(parentFromContext) &&
(0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) {
return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext);
}
else {
return new NonRecordingSpan_1.NonRecordingSpan();
}
}
startActiveSpan(name, arg2, arg3, arg4) {
let opts;
let ctx;
let fn;
if (arguments.length < 2) {
return;
}
else if (arguments.length === 2) {
fn = arg2;
}
else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
}
else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
const span = this.startSpan(name, opts, parentContext);
const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span);
return contextApi.with(contextWithSpanSet, fn, undefined, span);
}
}
exports.NoopTracer = NoopTracer;
function isSpanContext(spanContext) {
return (spanContext !== null &&
typeof spanContext === 'object' &&
'spanId' in spanContext &&
typeof spanContext['spanId'] === 'string' &&
'traceId' in spanContext &&
typeof spanContext['traceId'] === 'string' &&
'traceFlags' in spanContext &&
typeof spanContext['traceFlags'] === 'number');
}
//# sourceMappingURL=NoopTracer.js.map

View File

@@ -0,0 +1,21 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTracerProvider = void 0;
const NoopTracer_1 = require("./NoopTracer");
/**
* An implementation of the {@link TracerProvider} which returns an impotent
* Tracer for all calls to `getTracer`.
*
* All operations are no-op.
*/
class NoopTracerProvider {
getTracer(_name, _version, _options) {
return new NoopTracer_1.NoopTracer();
}
}
exports.NoopTracerProvider = NoopTracerProvider;
//# sourceMappingURL=NoopTracerProvider.js.map

View File

@@ -0,0 +1,46 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyTracer = void 0;
const NoopTracer_1 = require("./NoopTracer");
const NOOP_TRACER = new NoopTracer_1.NoopTracer();
/**
* Proxy tracer provided by the proxy tracer provider
*
* @since 1.0.0
*/
class ProxyTracer {
constructor(provider, name, version, options) {
this._provider = provider;
this.name = name;
this.version = version;
this.options = options;
}
startSpan(name, options, context) {
return this._getTracer().startSpan(name, options, context);
}
startActiveSpan(_name, _options, _context, _fn) {
const tracer = this._getTracer();
return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
}
/**
* Try to get a tracer from the proxy tracer provider.
* If the proxy tracer provider has no delegate, return a noop tracer.
*/
_getTracer() {
if (this._delegate) {
return this._delegate;
}
const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
if (!tracer) {
return NOOP_TRACER;
}
this._delegate = tracer;
return this._delegate;
}
}
exports.ProxyTracer = ProxyTracer;
//# sourceMappingURL=ProxyTracer.js.map

View File

@@ -0,0 +1,46 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyTracerProvider = void 0;
const ProxyTracer_1 = require("./ProxyTracer");
const NoopTracerProvider_1 = require("./NoopTracerProvider");
const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider();
/**
* Tracer provider which provides {@link ProxyTracer}s.
*
* Before a delegate is set, tracers provided are NoOp.
* When a delegate is set, traces are provided from the delegate.
* When a delegate is set after tracers have already been provided,
* all tracers already provided will use the provided delegate implementation.
*
* @deprecated This will be removed in the next major version.
* @since 1.0.0
*/
class ProxyTracerProvider {
/**
* Get a {@link ProxyTracer}
*/
getTracer(name, version, options) {
var _a;
return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options));
}
getDelegate() {
var _a;
return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
}
/**
* Set the delegate tracer provider
*/
setDelegate(delegate) {
this._delegate = delegate;
}
getDelegateTracer(name, version, options) {
var _a;
return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
}
}
exports.ProxyTracerProvider = ProxyTracerProvider;
//# sourceMappingURL=ProxyTracerProvider.js.map

View File

@@ -0,0 +1,33 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamplingDecision = void 0;
/**
* @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*
* @since 1.0.0
*/
var SamplingDecision;
(function (SamplingDecision) {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {}));
//# sourceMappingURL=SamplingResult.js.map

View File

@@ -0,0 +1,71 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0;
const context_1 = require("../context/context");
const NonRecordingSpan_1 = require("./NonRecordingSpan");
const context_2 = require("../api/context");
/**
* span key
*/
const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN');
/**
* Return the span if one exists
*
* @param context context to get span from
*/
function getSpan(context) {
return context.getValue(SPAN_KEY) || undefined;
}
exports.getSpan = getSpan;
/**
* Gets the span from the current context, if one exists.
*/
function getActiveSpan() {
return getSpan(context_2.ContextAPI.getInstance().active());
}
exports.getActiveSpan = getActiveSpan;
/**
* Set the span on a context
*
* @param context context to use as parent
* @param span span to set active
*/
function setSpan(context, span) {
return context.setValue(SPAN_KEY, span);
}
exports.setSpan = setSpan;
/**
* Remove current span stored in the context
*
* @param context context to delete span from
*/
function deleteSpan(context) {
return context.deleteValue(SPAN_KEY);
}
exports.deleteSpan = deleteSpan;
/**
* Wrap span context in a NoopSpan and set as span in a new
* context
*
* @param context context to set active span on
* @param spanContext span context to be wrapped
*/
function setSpanContext(context, spanContext) {
return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext));
}
exports.setSpanContext = setSpanContext;
/**
* Get the span context of the span if it exists.
*
* @param context context to get values from
*/
function getSpanContext(context) {
var _a;
return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();
}
exports.getSpanContext = getSpanContext;
//# sourceMappingURL=context-utils.js.map

View File

@@ -0,0 +1,94 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceStateImpl = void 0;
const tracestate_validators_1 = require("./tracestate-validators");
const MAX_TRACE_STATE_ITEMS = 32;
const MAX_TRACE_STATE_LEN = 512;
const LIST_MEMBERS_SEPARATOR = ',';
const LIST_MEMBER_KEY_VALUE_SPLITTER = '=';
/**
* TraceState must be a class and not a simple object type because of the spec
* requirement (https://www.w3.org/TR/trace-context/#tracestate-field).
*
* Here is the list of allowed mutations:
* - New key-value pair should be added into the beginning of the list
* - The value of any key can be updated. Modified keys MUST be moved to the
* beginning of the list.
*/
class TraceStateImpl {
constructor(rawTraceState) {
this._internalState = new Map();
if (rawTraceState)
this._parse(rawTraceState);
}
set(key, value) {
// TODO: Benchmark the different approaches(map vs list) and
// use the faster one.
const traceState = this._clone();
if (traceState._internalState.has(key)) {
traceState._internalState.delete(key);
}
traceState._internalState.set(key, value);
return traceState;
}
unset(key) {
const traceState = this._clone();
traceState._internalState.delete(key);
return traceState;
}
get(key) {
return this._internalState.get(key);
}
serialize() {
return (Array.from(this._internalState.keys())
// Use reduceRight() because keys are stored in reverse insertion order.
.reduceRight((agg, key) => {
agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));
return agg;
}, [])
.join(LIST_MEMBERS_SEPARATOR));
}
_parse(rawTraceState) {
if (rawTraceState.length > MAX_TRACE_STATE_LEN)
return;
this._internalState = rawTraceState
.split(LIST_MEMBERS_SEPARATOR)
// Use reduceRight() so new keys (.set(...)) will be placed at the beginning
.reduceRight((agg, part) => {
const listMember = part.trim(); // Optional Whitespace (OWS) handling
const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
if (i !== -1) {
const key = listMember.slice(0, i);
const value = listMember.slice(i + 1, part.length);
if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) {
agg.set(key, value);
}
else {
// TODO: Consider to add warning log
}
}
return agg;
}, new Map());
// Because of the reverse() requirement, trunc must be done after map is created
if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {
this._internalState = new Map(Array.from(this._internalState.entries())
.reverse() // Use reverse same as original tracestate parse chain
.slice(0, MAX_TRACE_STATE_ITEMS));
}
}
// @ts-expect-error TS6133 Accessed in tests only.
_keys() {
return Array.from(this._internalState.keys()).reverse();
}
_clone() {
const traceState = new TraceStateImpl();
traceState._internalState = new Map(this._internalState);
return traceState;
}
}
exports.TraceStateImpl = TraceStateImpl;
//# sourceMappingURL=tracestate-impl.js.map

View File

@@ -0,0 +1,35 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateValue = exports.validateKey = void 0;
const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';
const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;
const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;
const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);
const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
/**
* Key is opaque string up to 256 characters printable. It MUST begin with a
* lowercase letter, and can only contain lowercase letters a-z, digits 0-9,
* underscores _, dashes -, asterisks *, and forward slashes /.
* For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the
* vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.
* see https://www.w3.org/TR/trace-context/#key
*/
function validateKey(key) {
return VALID_KEY_REGEX.test(key);
}
exports.validateKey = validateKey;
/**
* Value is opaque string up to 256 characters printable ASCII RFC0020
* characters (i.e., the range 0x20 to 0x7E) except comma , and =.
*/
function validateValue(value) {
return (VALID_VALUE_BASE_REGEX.test(value) &&
!INVALID_VALUE_COMMA_EQUAL_REGEX.test(value));
}
exports.validateValue = validateValue;
//# sourceMappingURL=tracestate-validators.js.map

View File

@@ -0,0 +1,16 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTraceState = void 0;
const tracestate_impl_1 = require("./tracestate-impl");
/**
* @since 1.1.0
*/
function createTraceState(rawTraceState) {
return new tracestate_impl_1.TraceStateImpl(rawTraceState);
}
exports.createTraceState = createTraceState;
//# sourceMappingURL=utils.js.map

Some files were not shown because too many files have changed in this diff Show More