8986ea02568055672e1beddb78d7e5aed90251028babf76ed1d8d56afb5edf35 package.json

This commit is contained in:
GitHub Workflow 2026-10-07 13:11:50 +00:00
commit 274b2ad738
68749 changed files with 3469508 additions and 0 deletions

1
.bin/acorn Symbolic link
View file

@ -0,0 +1 @@
../acorn/bin/acorn

1
.bin/cssesc Symbolic link
View file

@ -0,0 +1 @@
../cssesc/bin/cssesc

1
.bin/esbuild Symbolic link
View file

@ -0,0 +1 @@
../esbuild/bin/esbuild

1
.bin/eslint Symbolic link
View file

@ -0,0 +1 @@
../eslint/bin/eslint.js

1
.bin/js-yaml Symbolic link
View file

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
.bin/json5 Symbolic link
View file

@ -0,0 +1 @@
../json5/lib/cli.js

1
.bin/loose-envify Symbolic link
View file

@ -0,0 +1 @@
../loose-envify/cli.js

1
.bin/nanoid Symbolic link
View file

@ -0,0 +1 @@
../nanoid/bin/nanoid.cjs

1
.bin/node-which Symbolic link
View file

@ -0,0 +1 @@
../which/bin/node-which

1
.bin/resolve Symbolic link
View file

@ -0,0 +1 @@
../resolve/bin/resolve

1
.bin/rimraf Symbolic link
View file

@ -0,0 +1 @@
../rimraf/bin.js

1
.bin/sass Symbolic link
View file

@ -0,0 +1 @@
../sass/sass.js

1
.bin/semver Symbolic link
View file

@ -0,0 +1 @@
../semver/bin/semver.js

1
.bin/stylelint Symbolic link
View file

@ -0,0 +1 @@
../stylelint/bin/stylelint.mjs

6697
.package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

50
.package.json Normal file
View file

@ -0,0 +1,50 @@
{
"name": "anaconda-webui",
"description": "Scaffolding for a cockpit module",
"type": "module",
"main": "index.js",
"author": "",
"license": "LGPL-2.1",
"scripts": {
"watch": "ESBUILD_WATCH=true ./build.js",
"build": "./build.js",
"eslint": "eslint --ext .js --ext .jsx src/",
"eslint:fix": "eslint --fix --ext .js --ext .jsx src/",
"stylelint": "stylelint 'src/**/*{.css,scss}'",
"stylelint:fix": "stylelint --fix 'src/**/*{.css,scss}'"
},
"devDependencies": {
"esbuild": "0.28.2",
"esbuild-plugin-copy": "2.1.1",
"esbuild-sass-plugin": "3.7.0",
"eslint": "8.57.0",
"eslint-config-standard": "17.1.0",
"eslint-config-standard-jsx": "11.0.0",
"eslint-config-standard-react": "13.0.0",
"eslint-plugin-import": "2.31.0",
"eslint-plugin-jsx-a11y": "6.10.2",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "6.6.0",
"eslint-plugin-react": "7.37.5",
"eslint-plugin-react-hooks": "4.6.2",
"eslint-plugin-simple-import-sort": "^12.0.0",
"eslint-plugin-sort-destructure-keys": "^2.0.0",
"gettext-parser": "8.0.0",
"sass": "1.98.0",
"stylelint": "17.14.1",
"stylelint-config-recommended-scss": "17.0.1",
"stylelint-config-standard-scss": "17.0.0",
"stylelint-formatter-pretty": "4.0.1"
},
"dependencies": {
"@patternfly/patternfly": "6.6.1",
"@patternfly/react-core": "6.6.1",
"@patternfly/react-table": "6.6.1",
"dequal": "2.0.3",
"luxon": "^3.6.1",
"react": "18.3.1",
"react-dom": "18.3.1",
"stacktrace-js": "2.0.2",
"throttle-debounce": "5.0.2"
}
}

22
@babel/code-frame/LICENSE Normal file
View file

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,19 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/babel-code-frame) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
or using yarn:
```sh
yarn add @babel/code-frame --dev
```

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

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,32 @@
{
"name": "@babel/code-frame",
"version": "7.29.7",
"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.29.7",
"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,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,19 @@
# @babel/helper-validator-identifier
> Validate identifier/keywords name
See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/babel-helper-validator-identifier) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-validator-identifier
```
or using yarn:
```sh
yarn add @babel/helper-validator-identifier
```

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

File diff suppressed because one or more lines are too long

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 @@
{"version":3,"names":["_identifier","require","_keyword"],"sources":["../src/index.ts"],"sourcesContent":["export {\n isIdentifierName,\n isIdentifierChar,\n isIdentifierStart,\n} from \"./identifier.ts\";\nexport {\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"./keyword.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,WAAA,GAAAC,OAAA;AAKA,IAAAC,QAAA,GAAAD,OAAA","ignoreList":[]}

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 @@
{"version":3,"names":["reservedWords","keyword","strict","strictBind","keywords","Set","reservedWordsStrictSet","reservedWordsStrictBindSet","isReservedWord","word","inModule","isStrictReservedWord","has","isStrictBindOnlyReservedWord","isStrictBindReservedWord","isKeyword"],"sources":["../src/keyword.ts"],"sourcesContent":["const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n"],"mappings":";;;;;;;;;;AAAA,MAAMA,aAAa,GAAG;EACpBC,OAAO,EAAE,CACP,OAAO,EACP,MAAM,EACN,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,EACT,IAAI,EACJ,MAAM,EACN,SAAS,EACT,KAAK,EACL,UAAU,EACV,IAAI,EACJ,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,KAAK,EACL,KAAK,EACL,OAAO,EACP,OAAO,EACP,MAAM,EACN,KAAK,EACL,MAAM,EACN,OAAO,EACP,OAAO,EACP,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,MAAM,EACN,OAAO,EACP,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,MAAM,EACN,QAAQ,CACT;EACDC,MAAM,EAAE,CACN,YAAY,EACZ,WAAW,EACX,KAAK,EACL,SAAS,EACT,SAAS,EACT,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,OAAO,CACR;EACDC,UAAU,EAAE,CAAC,MAAM,EAAE,WAAW;AAClC,CAAC;AACD,MAAMC,QAAQ,GAAG,IAAIC,GAAG,CAACL,aAAa,CAACC,OAAO,CAAC;AAC/C,MAAMK,sBAAsB,GAAG,IAAID,GAAG,CAACL,aAAa,CAACE,MAAM,CAAC;AAC5D,MAAMK,0BAA0B,GAAG,IAAIF,GAAG,CAACL,aAAa,CAACG,UAAU,CAAC;AAK7D,SAASK,cAAcA,CAACC,IAAY,EAAEC,QAAiB,EAAW;EACvE,OAAQA,QAAQ,IAAID,IAAI,KAAK,OAAO,IAAKA,IAAI,KAAK,MAAM;AAC1D;AAOO,SAASE,oBAAoBA,CAACF,IAAY,EAAEC,QAAiB,EAAW;EAC7E,OAAOF,cAAc,CAACC,IAAI,EAAEC,QAAQ,CAAC,IAAIJ,sBAAsB,CAACM,GAAG,CAACH,IAAI,CAAC;AAC3E;AAMO,SAASI,4BAA4BA,CAACJ,IAAY,EAAW;EAClE,OAAOF,0BAA0B,CAACK,GAAG,CAACH,IAAI,CAAC;AAC7C;AAOO,SAASK,wBAAwBA,CACtCL,IAAY,EACZC,QAAiB,EACR;EACT,OACEC,oBAAoB,CAACF,IAAI,EAAEC,QAAQ,CAAC,IAAIG,4BAA4B,CAACJ,IAAI,CAAC;AAE9E;AAEO,SAASM,SAASA,CAACN,IAAY,EAAW;EAC/C,OAAOL,QAAQ,CAACQ,GAAG,CAACH,IAAI,CAAC;AAC3B","ignoreList":[]}

View file

@ -0,0 +1,31 @@
{
"name": "@babel/helper-validator-identifier",
"version": "7.29.7",
"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"
}

View file

@ -0,0 +1,41 @@
# @bufbuild/protobuf
This package provides the runtime library for the [protoc-gen-es](https://www.npmjs.com/package/@bufbuild/protoc-gen-es)
code generator plugin.
## Protocol Buffers for ECMAScript
A complete implementation of [Protocol Buffers](https://protobuf.dev/) in TypeScript,
suitable for web browsers, Node.js, Deno, and Bun, created by [Buf](https://buf.build).
**Protobuf-ES** is a solid, modern alternative to existing Protobuf implementations for the JavaScript ecosystem. It
provides a comprehensive plugin framework and decouples the base types from RPC functionality.
Some additional features:
- Generates pure TypeScript
- Plain message objects, no getters/setters
- Reflection, registries, and custom options
- 100% conformant against the official Protobuf test suite
- Standard plugin-based generation, works with the Buf CLI as well as `protoc`
- Write your own code generators with [@bufbuild/protoplugin](https://www.npmjs.com/package/@bufbuild/protoplugin)
- Pairs with [@connectrpc/connect](https://www.npmjs.com/package/@connectrpc/connect) for RPC and [@bufbuild/protovalidate](https://www.npmjs.com/package/@bufbuild/protovalidate) for validation
## Installation
```bash
npm install @bufbuild/protobuf
```
## Documentation
To learn how to work with `@bufbuild/protobuf`, check out the docs for the [Runtime API](https://protobufes.com/guides/messages/)
and the [generated code](https://protobufes.com/reference/generated-code/).
Official documentation for the Protobuf-ES project can be found at [protobufes.com](https://protobufes.com/).
For more information on Buf, check out the official [Buf documentation](https://buf.build/docs/).
## Examples
A complete code example can be found in the **Protobuf-ES** repo [here](https://github.com/bufbuild/protobuf-es/tree/main/packages/protobuf-example).

View file

@ -0,0 +1,6 @@
import type { MessageShape } from "./types.js";
import { type DescMessage } from "./descriptors.js";
/**
* Create a deep copy of a message, including extensions and unknown fields.
*/
export declare function clone<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>): MessageShape<Desc>;

View file

@ -0,0 +1,66 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.clone = clone;
const descriptors_js_1 = require("./descriptors.js");
const reflect_js_1 = require("./reflect/reflect.js");
const guard_js_1 = require("./reflect/guard.js");
/**
* Create a deep copy of a message, including extensions and unknown fields.
*/
function clone(schema, message) {
return cloneReflect((0, reflect_js_1.reflect)(schema, message)).message;
}
function cloneReflect(i) {
const o = (0, reflect_js_1.reflect)(i.desc);
for (const f of i.fields) {
if (!i.isSet(f)) {
continue;
}
switch (f.fieldKind) {
case "list":
const list = o.get(f);
for (const item of i.get(f)) {
list.add(cloneSingular(f, item));
}
break;
case "map":
const map = o.get(f);
for (const entry of i.get(f).entries()) {
map.set(entry[0], cloneSingular(f, entry[1]));
}
break;
default: {
o.set(f, cloneSingular(f, i.get(f)));
break;
}
}
}
const unknown = i.getUnknown();
if (unknown && unknown.length > 0) {
o.setUnknown([...unknown]);
}
return o;
}
function cloneSingular(field, value) {
if (field.message !== undefined && (0, guard_js_1.isReflectMessage)(value)) {
return cloneReflect(value);
}
if (field.scalar == descriptors_js_1.ScalarType.BYTES && value instanceof Uint8Array) {
// @ts-expect-error T cannot extend Uint8Array in practice
return value.slice();
}
return value;
}

View file

@ -0,0 +1 @@
export { boot } from "../codegenv2/boot.js";

View file

@ -0,0 +1,18 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.boot = void 0;
var boot_js_1 = require("../codegenv2/boot.js");
Object.defineProperty(exports, "boot", { enumerable: true, get: function () { return boot_js_1.boot; } });

View file

@ -0,0 +1,10 @@
import type { DescFile } from "../descriptors.js";
import type { GenEnum } from "./types.js";
import type { JsonValue } from "../json-value.js";
export { tsEnum } from "../codegenv2/enum.js";
/**
* Hydrate an enum descriptor.
*
* @private
*/
export declare function enumDesc<Shape extends number, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenEnum<Shape, JsonType>;

View file

@ -0,0 +1,31 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.tsEnum = void 0;
exports.enumDesc = enumDesc;
var enum_js_1 = require("../codegenv2/enum.js");
Object.defineProperty(exports, "tsEnum", { enumerable: true, get: function () { return enum_js_1.tsEnum; } });
/**
* Hydrate an enum descriptor.
*
* @private
*/
function enumDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.enums[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedEnums[e];
}

View file

@ -0,0 +1,9 @@
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenExtension } from "./types.js";
/**
* Hydrate an extension descriptor.
*
* @private
*/
export declare function extDesc<Extendee extends Message, Value>(file: DescFile, path: number, ...paths: number[]): GenExtension<Extendee, Value>;

View file

@ -0,0 +1,28 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.extDesc = extDesc;
/**
* Hydrate an extension descriptor.
*
* @private
*/
function extDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.extensions[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedExtensions[e];
}

View file

@ -0,0 +1 @@
export { fileDesc } from "../codegenv2/file.js";

View file

@ -0,0 +1,18 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileDesc = void 0;
var file_js_1 = require("../codegenv2/file.js");
Object.defineProperty(exports, "fileDesc", { enumerable: true, get: function () { return file_js_1.fileDesc; } });

View file

@ -0,0 +1,10 @@
export * from "../codegenv2/boot.js";
export * from "../codegenv2/embed.js";
export * from "./enum.js";
export * from "./extension.js";
export * from "./file.js";
export * from "./message.js";
export * from "./service.js";
export * from "./symbols.js";
export * from "../codegenv2/scalar.js";
export * from "./types.js";

View file

@ -0,0 +1,39 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("../codegenv2/boot.js"), exports);
__exportStar(require("../codegenv2/embed.js"), exports);
__exportStar(require("./enum.js"), exports);
__exportStar(require("./extension.js"), exports);
__exportStar(require("./file.js"), exports);
__exportStar(require("./message.js"), exports);
__exportStar(require("./service.js"), exports);
__exportStar(require("./symbols.js"), exports);
__exportStar(require("../codegenv2/scalar.js"), exports);
__exportStar(require("./types.js"), exports);

View file

@ -0,0 +1,10 @@
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenMessage } from "./types.js";
import type { JsonValue } from "../json-value.js";
/**
* Hydrate a message descriptor.
*
* @private
*/
export declare function messageDesc<Shape extends Message, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenMessage<Shape, JsonType>;

View file

@ -0,0 +1,24 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.messageDesc = messageDesc;
/**
* Hydrate a message descriptor.
*
* @private
*/
function messageDesc(file, path, ...paths) {
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]);
}

View file

@ -0,0 +1,8 @@
import type { GenService, GenServiceMethods } from "./types.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a service descriptor.
*
* @private
*/
export declare function serviceDesc<T extends GenServiceMethods>(file: DescFile, path: number, ...paths: number[]): GenService<T>;

View file

@ -0,0 +1,27 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceDesc = serviceDesc;
/**
* Hydrate a service descriptor.
*
* @private
*/
function serviceDesc(file, path, ...paths) {
if (paths.length > 0) {
throw new Error();
}
return file.services[path];
}

View file

@ -0,0 +1,140 @@
/**
* @private
*/
export declare const packageName = "@bufbuild/protobuf";
/**
* @private
*/
export declare const wktPublicImportPaths: Readonly<Record<string, string>>;
/**
* @private
*/
export declare const symbols: {
readonly codegen: {
readonly boot: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/boot.js";
readonly from: string;
};
readonly fileDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/file.js";
readonly from: string;
};
readonly enumDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/enum.js";
readonly from: string;
};
readonly extDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/extension.js";
readonly from: string;
};
readonly messageDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/message.js";
readonly from: string;
};
readonly serviceDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/service.js";
readonly from: string;
};
readonly tsEnum: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../../codegenv1/enum.js";
readonly from: string;
};
readonly GenFile: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenEnum: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenExtension: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenMessage: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
readonly GenService: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../../codegenv1/types.js";
readonly from: string;
};
};
readonly isMessage: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../is-message.js";
readonly from: "@bufbuild/protobuf";
};
readonly Message: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../types.js";
readonly from: "@bufbuild/protobuf";
};
readonly create: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../create.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../from-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../to-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly protoInt64: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../proto-int64.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonValue: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonObject: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly UnknownEnum: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../types.js";
readonly from: "@bufbuild/protobuf";
};
};

View file

@ -0,0 +1,59 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.symbols = exports.wktPublicImportPaths = exports.packageName = void 0;
const symbols_js_1 = require("../codegenv2/symbols.js");
/**
* @private
*/
exports.packageName = symbols_js_1.packageName;
/**
* @private
*/
exports.wktPublicImportPaths = {
"google/protobuf/compiler/plugin.proto": exports.packageName + "/wkt",
"google/protobuf/any.proto": exports.packageName + "/wkt",
"google/protobuf/api.proto": exports.packageName + "/wkt",
"google/protobuf/cpp_features.proto": exports.packageName + "/wkt",
"google/protobuf/descriptor.proto": exports.packageName + "/wkt",
"google/protobuf/duration.proto": exports.packageName + "/wkt",
"google/protobuf/empty.proto": exports.packageName + "/wkt",
"google/protobuf/field_mask.proto": exports.packageName + "/wkt",
"google/protobuf/go_features.proto": exports.packageName + "/wkt",
"google/protobuf/java_features.proto": exports.packageName + "/wkt",
"google/protobuf/source_context.proto": exports.packageName + "/wkt",
"google/protobuf/struct.proto": exports.packageName + "/wkt",
"google/protobuf/timestamp.proto": exports.packageName + "/wkt",
"google/protobuf/type.proto": exports.packageName + "/wkt",
"google/protobuf/wrappers.proto": exports.packageName + "/wkt",
};
/**
* @private
*/
// biome-ignore format: want this to read well
exports.symbols = Object.assign(Object.assign({}, symbols_js_1.symbols), { codegen: {
boot: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/boot.js", from: exports.packageName + "/codegenv1" },
fileDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/file.js", from: exports.packageName + "/codegenv1" },
enumDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/enum.js", from: exports.packageName + "/codegenv1" },
extDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/extension.js", from: exports.packageName + "/codegenv1" },
messageDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/message.js", from: exports.packageName + "/codegenv1" },
serviceDesc: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/service.js", from: exports.packageName + "/codegenv1" },
tsEnum: { typeOnly: false, bootstrapWktFrom: "../../codegenv1/enum.js", from: exports.packageName + "/codegenv1" },
GenFile: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenEnum: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenExtension: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenMessage: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
GenService: { typeOnly: true, bootstrapWktFrom: "../../codegenv1/types.js", from: exports.packageName + "/codegenv1" },
} });

View file

@ -0,0 +1,79 @@
import type { Message } from "../types.js";
import type { DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescService } from "../descriptors.js";
import type { JsonValue } from "../json-value.js";
/**
* Describes a protobuf source file.
*
* @private
*/
export type GenFile = DescFile;
/**
* Describes a message declaration in a protobuf source file.
*
* This type is identical to DescMessage, but carries additional type
* information.
*
* @private
*/
export type GenMessage<RuntimeShape extends Message, JsonType = JsonValue> = Omit<DescMessage, "field" | "typeName"> & {
field: Record<MessageFieldNames<RuntimeShape>, DescField>;
typeName: RuntimeShape["$typeName"];
} & brandv1<RuntimeShape, JsonType>;
/**
* Describes an enumeration in a protobuf source file.
*
* This type is identical to DescEnum, but carries additional type
* information.
*
* @private
*/
export type GenEnum<RuntimeShape extends number, JsonType extends JsonValue = JsonValue> = Omit<DescEnum, "value"> & {
value: Record<RuntimeShape, DescEnumValue>;
} & brandv1<RuntimeShape, JsonType>;
/**
* Describes an extension in a protobuf source file.
*
* This type is identical to DescExtension, but carries additional type
* information.
*
* @private
*/
export type GenExtension<Extendee extends Message = Message, RuntimeShape = unknown> = DescExtension & brandv1<Extendee, RuntimeShape>;
/**
* Describes a service declaration in a protobuf source file.
*
* This type is identical to DescService, but carries additional type
* information.
*
* @private
*/
export type GenService<RuntimeShape extends GenServiceMethods> = Omit<DescService, "method"> & {
method: {
[K in keyof RuntimeShape]: RuntimeShape[K] & DescMethod;
};
};
/**
* @private
*/
export type GenServiceMethods = Record<string, Pick<DescMethod, "input" | "output" | "methodKind">>;
type brandv1<A, B = unknown> = {
/**
* @internal
*/
readonly $codegenv1: {
a: A;
b: B;
};
};
/**
* Union of the property names of all fields, including oneof members.
* For an anonymous message (no generated message shape), it's simply a string.
*/
type MessageFieldNames<T extends Message> = Message extends T ? string : Exclude<keyof {
[P in keyof T as P extends ("$typeName" | "$unknown") ? never : T[P] extends Oneof<infer K> ? K : P]-?: true;
}, number | symbol>;
type Oneof<K extends string> = {
case: K | undefined;
value?: unknown;
};
export {};

View file

@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });

View file

@ -0,0 +1,63 @@
import type { DescriptorProto_ExtensionRange, FieldDescriptorProto_Label, FieldDescriptorProto_Type, FieldOptions_OptionRetention, FieldOptions_OptionTargetType, FieldOptions_EditionDefault, EnumValueDescriptorProto, FileDescriptorProto } from "../wkt/google/protobuf/descriptor_pb.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a file descriptor for google/protobuf/descriptor.proto from a plain
* object.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export declare function boot(boot: FileDescriptorProtoBoot): DescFile;
/**
* An object literal for initializing the message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export type FileDescriptorProtoBoot = {
name: "google/protobuf/descriptor.proto";
package: "google.protobuf";
messageType: DescriptorProtoBoot[];
enumType: EnumDescriptorProtoBoot[];
};
export type DescriptorProtoBoot = {
name: string;
field?: FieldDescriptorProtoBoot[];
nestedType?: DescriptorProtoBoot[];
enumType?: EnumDescriptorProtoBoot[];
extensionRange?: Pick<DescriptorProto_ExtensionRange, "start" | "end">[];
};
export type FieldDescriptorProtoBoot = {
name: string;
number: number;
label?: FieldDescriptorProto_Label;
type: FieldDescriptorProto_Type;
typeName?: string;
extendee?: string;
defaultValue?: string;
options?: FieldOptionsBoot;
};
export type FieldOptionsBoot = {
packed?: boolean;
deprecated?: boolean;
retention?: FieldOptions_OptionRetention;
targets?: FieldOptions_OptionTargetType[];
editionDefaults?: FieldOptions_EditionDefaultBoot[];
};
export type FieldOptions_EditionDefaultBoot = Pick<FieldOptions_EditionDefault, "edition" | "value">;
export type EnumDescriptorProtoBoot = {
name: string;
value: EnumValueDescriptorProtoBoot[];
};
export type EnumValueDescriptorProtoBoot = Pick<EnumValueDescriptorProto, "name" | "number">;
/**
* Creates the message google.protobuf.FileDescriptorProto from an object literal.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
export declare function bootFileDescriptorProto(init: FileDescriptorProtoBoot): FileDescriptorProto;

View file

@ -0,0 +1,105 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.boot = boot;
exports.bootFileDescriptorProto = bootFileDescriptorProto;
const restore_json_names_js_1 = require("./restore-json-names.js");
const registry_js_1 = require("../registry.js");
/**
* Hydrate a file descriptor for google/protobuf/descriptor.proto from a plain
* object.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
function boot(boot) {
const root = bootFileDescriptorProto(boot);
root.messageType.forEach(restore_json_names_js_1.restoreJsonNames);
const reg = (0, registry_js_1.createFileRegistry)(root, () => undefined);
// biome-ignore lint/style/noNonNullAssertion: non-null assertion because we just created the registry from the file we look up
return reg.getFile(root.name);
}
/**
* Creates the message google.protobuf.FileDescriptorProto from an object literal.
*
* See createFileDescriptorProtoBoot() for details.
*
* @private
*/
function bootFileDescriptorProto(init) {
const proto = Object.create({
syntax: "",
edition: 0,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FileDescriptorProto", dependency: [], publicDependency: [], weakDependency: [], optionDependency: [], service: [], extension: [] }, init), { messageType: init.messageType.map(bootDescriptorProto), enumType: init.enumType.map(bootEnumDescriptorProto) }));
}
function bootDescriptorProto(init) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const proto = Object.create({
visibility: 0,
});
return Object.assign(proto, {
$typeName: "google.protobuf.DescriptorProto",
name: init.name,
field: (_b = (_a = init.field) === null || _a === void 0 ? void 0 : _a.map(bootFieldDescriptorProto)) !== null && _b !== void 0 ? _b : [],
extension: [],
nestedType: (_d = (_c = init.nestedType) === null || _c === void 0 ? void 0 : _c.map(bootDescriptorProto)) !== null && _d !== void 0 ? _d : [],
enumType: (_f = (_e = init.enumType) === null || _e === void 0 ? void 0 : _e.map(bootEnumDescriptorProto)) !== null && _f !== void 0 ? _f : [],
extensionRange: (_h = (_g = init.extensionRange) === null || _g === void 0 ? void 0 : _g.map((e) => (Object.assign({ $typeName: "google.protobuf.DescriptorProto.ExtensionRange" }, e)))) !== null && _h !== void 0 ? _h : [],
oneofDecl: [],
reservedRange: [],
reservedName: [],
});
}
function bootFieldDescriptorProto(init) {
const proto = Object.create({
label: 1,
typeName: "",
extendee: "",
defaultValue: "",
oneofIndex: 0,
jsonName: "",
proto3Optional: false,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FieldDescriptorProto" }, init), { options: init.options ? bootFieldOptions(init.options) : undefined }));
}
function bootFieldOptions(init) {
var _a, _b, _c;
const proto = Object.create({
ctype: 0,
packed: false,
jstype: 0,
lazy: false,
unverifiedLazy: false,
deprecated: false,
weak: false,
debugRedact: false,
retention: 0,
});
return Object.assign(proto, Object.assign(Object.assign({ $typeName: "google.protobuf.FieldOptions" }, init), { targets: (_a = init.targets) !== null && _a !== void 0 ? _a : [], editionDefaults: (_c = (_b = init.editionDefaults) === null || _b === void 0 ? void 0 : _b.map((e) => (Object.assign({ $typeName: "google.protobuf.FieldOptions.EditionDefault" }, e)))) !== null && _c !== void 0 ? _c : [], uninterpretedOption: [] }));
}
function bootEnumDescriptorProto(init) {
const proto = Object.create({
visibility: 0,
});
return Object.assign(proto, {
$typeName: "google.protobuf.EnumDescriptorProto",
name: init.name,
reservedName: [],
reservedRange: [],
value: init.value.map((e) => (Object.assign({ $typeName: "google.protobuf.EnumValueDescriptorProto" }, e))),
});
}

View file

@ -0,0 +1,43 @@
import type { DescEnum, DescExtension, DescMessage, DescService } from "../descriptors.js";
import { type FileDescriptorProto } from "../wkt/google/protobuf/descriptor_pb.js";
import type { FileDescriptorProtoBoot } from "./boot.js";
type EmbedUnknown = {
bootable: false;
proto(): FileDescriptorProto;
base64(): string;
};
type EmbedDescriptorProto = Omit<EmbedUnknown, "bootable"> & {
bootable: true;
boot(): FileDescriptorProtoBoot;
};
/**
* Create necessary information to embed a file descriptor in
* generated code.
*
* @private
*/
export declare function embedFileDesc(file: FileDescriptorProto): EmbedUnknown | EmbedDescriptorProto;
/**
* Compute the path to a message, enumeration, extension, or service in a
* file descriptor.
*
* @private
*/
export declare function pathInFileDesc(desc: DescMessage | DescEnum | DescExtension | DescService): number[];
/**
* The file descriptor for google/protobuf/descriptor.proto cannot be embedded
* in serialized form, since it is required to parse itself.
*
* This function takes an instance of the message, and returns a plain object
* that can be hydrated to the message again via bootFileDescriptorProto().
*
* This function only works with a message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto, and only supports features that are
* relevant for the specific use case. For example, it discards file options,
* reserved ranges and reserved names, and field options that are unused in
* descriptor.proto.
*
* @private
*/
export declare function createFileDescriptorProtoBoot(proto: FileDescriptorProto): FileDescriptorProtoBoot;
export {};

View file

@ -0,0 +1,244 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.embedFileDesc = embedFileDesc;
exports.pathInFileDesc = pathInFileDesc;
exports.createFileDescriptorProtoBoot = createFileDescriptorProtoBoot;
const names_js_1 = require("../reflect/names.js");
const fields_js_1 = require("../fields.js");
const base64_encoding_js_1 = require("../wire/base64-encoding.js");
const to_binary_js_1 = require("../to-binary.js");
const clone_js_1 = require("../clone.js");
const descriptor_pb_js_1 = require("../wkt/google/protobuf/descriptor_pb.js");
/**
* Create necessary information to embed a file descriptor in
* generated code.
*
* @private
*/
function embedFileDesc(file) {
const embed = {
bootable: false,
proto() {
const stripped = (0, clone_js_1.clone)(descriptor_pb_js_1.FileDescriptorProtoSchema, file);
(0, fields_js_1.clearField)(stripped, descriptor_pb_js_1.FileDescriptorProtoSchema.field.dependency);
(0, fields_js_1.clearField)(stripped, descriptor_pb_js_1.FileDescriptorProtoSchema.field.sourceCodeInfo);
stripped.messageType.map(stripJsonNames);
return stripped;
},
base64() {
const bytes = (0, to_binary_js_1.toBinary)(descriptor_pb_js_1.FileDescriptorProtoSchema, this.proto());
return (0, base64_encoding_js_1.base64Encode)(bytes, "std_raw");
},
};
return file.name == "google/protobuf/descriptor.proto"
? Object.assign(Object.assign({}, embed), { bootable: true, boot() {
return createFileDescriptorProtoBoot(this.proto());
} }) : embed;
}
function stripJsonNames(d) {
for (const f of d.field) {
if (f.jsonName === (0, names_js_1.protoCamelCase)(f.name)) {
(0, fields_js_1.clearField)(f, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.jsonName);
}
}
for (const n of d.nestedType) {
stripJsonNames(n);
}
}
/**
* Compute the path to a message, enumeration, extension, or service in a
* file descriptor.
*
* @private
*/
function pathInFileDesc(desc) {
if (desc.kind == "service") {
return [desc.file.services.indexOf(desc)];
}
const parent = desc.parent;
if (parent == undefined) {
switch (desc.kind) {
case "enum":
return [desc.file.enums.indexOf(desc)];
case "message":
return [desc.file.messages.indexOf(desc)];
case "extension":
return [desc.file.extensions.indexOf(desc)];
}
}
function findPath(cur) {
const nested = [];
for (let parent = cur.parent; parent;) {
const idx = parent.nestedMessages.indexOf(cur);
nested.unshift(idx);
cur = parent;
parent = cur.parent;
}
nested.unshift(cur.file.messages.indexOf(cur));
return nested;
}
const path = findPath(parent);
switch (desc.kind) {
case "extension":
return [...path, parent.nestedExtensions.indexOf(desc)];
case "message":
return [...path, parent.nestedMessages.indexOf(desc)];
case "enum":
return [...path, parent.nestedEnums.indexOf(desc)];
}
}
/**
* The file descriptor for google/protobuf/descriptor.proto cannot be embedded
* in serialized form, since it is required to parse itself.
*
* This function takes an instance of the message, and returns a plain object
* that can be hydrated to the message again via bootFileDescriptorProto().
*
* This function only works with a message google.protobuf.FileDescriptorProto
* for google/protobuf/descriptor.proto, and only supports features that are
* relevant for the specific use case. For example, it discards file options,
* reserved ranges and reserved names, and field options that are unused in
* descriptor.proto.
*
* @private
*/
function createFileDescriptorProtoBoot(proto) {
var _a;
assert(proto.name == "google/protobuf/descriptor.proto");
assert(proto.package == "google.protobuf");
assert(!proto.dependency.length);
assert(!proto.publicDependency.length);
assert(!proto.weakDependency.length);
assert(!proto.optionDependency.length);
assert(!proto.service.length);
assert(!proto.extension.length);
assert(proto.sourceCodeInfo === undefined);
assert(proto.syntax == "" || proto.syntax == "proto2");
assert(!((_a = proto.options) === null || _a === void 0 ? void 0 : _a.features)); // we're dropping file options
assert(proto.edition === descriptor_pb_js_1.Edition.EDITION_UNKNOWN);
return {
name: proto.name,
package: proto.package,
messageType: proto.messageType.map(createDescriptorBoot),
enumType: proto.enumType.map(createEnumDescriptorBoot),
};
}
function createDescriptorBoot(proto) {
assert(proto.extension.length == 0);
assert(!proto.oneofDecl.length);
assert(!proto.options);
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.DescriptorProtoSchema.field.visibility));
const b = {
name: proto.name,
};
if (proto.field.length) {
b.field = proto.field.map(createFieldDescriptorBoot);
}
if (proto.nestedType.length) {
b.nestedType = proto.nestedType.map(createDescriptorBoot);
}
if (proto.enumType.length) {
b.enumType = proto.enumType.map(createEnumDescriptorBoot);
}
if (proto.extensionRange.length) {
b.extensionRange = proto.extensionRange.map((r) => {
assert(!r.options);
return { start: r.start, end: r.end };
});
}
return b;
}
function createFieldDescriptorBoot(proto) {
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.name));
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.number));
assert((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.type));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.oneofIndex));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.jsonName) ||
proto.jsonName === (0, names_js_1.protoCamelCase)(proto.name));
const b = {
name: proto.name,
number: proto.number,
type: proto.type,
};
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.label)) {
b.label = proto.label;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.typeName)) {
b.typeName = proto.typeName;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.extendee)) {
b.extendee = proto.extendee;
}
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldDescriptorProtoSchema.field.defaultValue)) {
b.defaultValue = proto.defaultValue;
}
if (proto.options) {
b.options = createFieldOptionsBoot(proto.options);
}
return b;
}
function createFieldOptionsBoot(proto) {
const b = {};
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.ctype));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.packed)) {
b.packed = proto.packed;
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.jstype));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.lazy));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.unverifiedLazy));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.deprecated)) {
b.deprecated = proto.deprecated;
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.weak));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.debugRedact));
if ((0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.retention)) {
b.retention = proto.retention;
}
if (proto.targets.length) {
b.targets = proto.targets;
}
if (proto.editionDefaults.length) {
b.editionDefaults = proto.editionDefaults.map((d) => ({
value: d.value,
edition: d.edition,
}));
}
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.features));
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.FieldOptionsSchema.field.uninterpretedOption));
return b;
}
function createEnumDescriptorBoot(proto) {
assert(!proto.options);
assert(!(0, fields_js_1.isFieldSet)(proto, descriptor_pb_js_1.EnumDescriptorProtoSchema.field.visibility));
return {
name: proto.name,
value: proto.value.map((v) => {
assert(!v.options);
return {
name: v.name,
number: v.number,
};
}),
};
}
/**
* Assert that condition is truthy or throw error.
*/
function assert(condition) {
if (!condition) {
throw new Error();
}
}

View file

@ -0,0 +1,29 @@
import type { DescEnum, DescFile } from "../descriptors.js";
import type { GenEnum } from "./types.js";
import type { JsonValue } from "../json-value.js";
/**
* Hydrate an enum descriptor.
*
* @private
*/
export declare function enumDesc<Shape extends number, JsonType extends JsonValue = JsonValue>(file: DescFile, path: number, ...paths: number[]): GenEnum<Shape, JsonType>;
/**
* Construct a TypeScript enum object at runtime from a descriptor.
*
* The returned object is identical to a transpiled TS enum and includes the
* reverse mapping, see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
*/
export declare function tsEnum(desc: DescEnum): {
[key: number]: string;
[k: string]: string | number;
};
/**
* Construct an object enum at runtime from a descriptor.
*
* The returned object is a record of enum value name to integer value. It's
* a subset of transpiled TS enums - it does not include the reverse mapping,
* and only supports lookup by value name.
*/
export declare function objEnum(desc: DescEnum): {
[key: string]: number;
};

View file

@ -0,0 +1,58 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.enumDesc = enumDesc;
exports.tsEnum = tsEnum;
exports.objEnum = objEnum;
/**
* Hydrate an enum descriptor.
*
* @private
*/
function enumDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.enums[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedEnums[e];
}
/**
* Construct a TypeScript enum object at runtime from a descriptor.
*
* The returned object is identical to a transpiled TS enum and includes the
* reverse mapping, see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
*/
function tsEnum(desc) {
const enumObject = {};
for (const value of desc.values) {
enumObject[value.localName] = value.number;
enumObject[value.number] = value.localName;
}
return enumObject;
}
/**
* Construct an object enum at runtime from a descriptor.
*
* The returned object is a record of enum value name to integer value. It's
* a subset of transpiled TS enums - it does not include the reverse mapping,
* and only supports lookup by value name.
*/
function objEnum(desc) {
const enumObject = {};
for (const value of desc.values) {
enumObject[value.localName] = value.number;
}
return enumObject;
}

View file

@ -0,0 +1,9 @@
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenExtension } from "./types.js";
/**
* Hydrate an extension descriptor.
*
* @private
*/
export declare function extDesc<Extendee extends Message, Value>(file: DescFile, path: number, ...paths: number[]): GenExtension<Extendee, Value>;

View file

@ -0,0 +1,28 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.extDesc = extDesc;
/**
* Hydrate an extension descriptor.
*
* @private
*/
function extDesc(file, path, ...paths) {
if (paths.length == 0) {
return file.extensions[path];
}
const e = paths.pop(); // we checked length above
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedExtensions[e];
}

View file

@ -0,0 +1,7 @@
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a file descriptor.
*
* @private
*/
export declare function fileDesc(b64: string, imports?: DescFile[]): DescFile;

View file

@ -0,0 +1,35 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileDesc = fileDesc;
const base64_encoding_js_1 = require("../wire/base64-encoding.js");
const descriptor_pb_js_1 = require("../wkt/google/protobuf/descriptor_pb.js");
const registry_js_1 = require("../registry.js");
const restore_json_names_js_1 = require("./restore-json-names.js");
const from_binary_js_1 = require("../from-binary.js");
/**
* Hydrate a file descriptor.
*
* @private
*/
function fileDesc(b64, imports) {
var _a;
const root = (0, from_binary_js_1.fromBinary)(descriptor_pb_js_1.FileDescriptorProtoSchema, (0, base64_encoding_js_1.base64Decode)(b64));
root.messageType.forEach(restore_json_names_js_1.restoreJsonNames);
root.dependency = (_a = imports === null || imports === void 0 ? void 0 : imports.map((f) => f.proto.name)) !== null && _a !== void 0 ? _a : [];
const reg = (0, registry_js_1.createFileRegistry)(root, (protoFileName) => imports === null || imports === void 0 ? void 0 : imports.find((f) => f.proto.name === protoFileName));
// biome-ignore lint/style/noNonNullAssertion: non-null assertion because we just created the registry from the file we look up
return reg.getFile(root.name);
}

View file

@ -0,0 +1,10 @@
export * from "./boot.js";
export * from "./embed.js";
export * from "./enum.js";
export * from "./extension.js";
export * from "./file.js";
export * from "./message.js";
export * from "./service.js";
export * from "./symbols.js";
export * from "./scalar.js";
export * from "./types.js";

View file

@ -0,0 +1,39 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./boot.js"), exports);
__exportStar(require("./embed.js"), exports);
__exportStar(require("./enum.js"), exports);
__exportStar(require("./extension.js"), exports);
__exportStar(require("./file.js"), exports);
__exportStar(require("./message.js"), exports);
__exportStar(require("./service.js"), exports);
__exportStar(require("./symbols.js"), exports);
__exportStar(require("./scalar.js"), exports);
__exportStar(require("./types.js"), exports);

View file

@ -0,0 +1,15 @@
import type { Message } from "../types.js";
import type { DescFile } from "../descriptors.js";
import type { GenMessage } from "./types.js";
/**
* Hydrate a message descriptor.
*
* @private
*/
export declare function messageDesc<Shape extends Message, Opt extends {
jsonType?: unknown;
validType?: unknown;
} = {
jsonType: undefined;
validType: undefined;
}>(file: DescFile, path: number, ...paths: number[]): GenMessage<Shape, Opt>;

View file

@ -0,0 +1,24 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.messageDesc = messageDesc;
/**
* Hydrate a message descriptor.
*
* @private
*/
function messageDesc(file, path, ...paths) {
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]);
}

View file

@ -0,0 +1,5 @@
import type { DescriptorProto } from "../wkt/google/protobuf/descriptor_pb.js";
/**
* @private
*/
export declare function restoreJsonNames(message: DescriptorProto): void;

View file

@ -0,0 +1,29 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.restoreJsonNames = restoreJsonNames;
const names_js_1 = require("../reflect/names.js");
const unsafe_js_1 = require("../reflect/unsafe.js");
/**
* @private
*/
function restoreJsonNames(message) {
for (const f of message.field) {
if (!(0, unsafe_js_1.unsafeIsSetExplicit)(f, "jsonName")) {
f.jsonName = (0, names_js_1.protoCamelCase)(f.name);
}
}
message.nestedType.forEach(restoreJsonNames);
}

View file

@ -0,0 +1,9 @@
import { ScalarType } from "../descriptors.js";
/**
* Return the TypeScript type (as a string) for the given scalar type.
*/
export declare function scalarTypeScriptType(scalar: ScalarType, longAsString: boolean): "string" | "boolean" | "bigint" | "bigint | string" | "Uint8Array" | "number";
/**
* Return the JSON type (as a string) for the given scalar type.
*/
export declare function scalarJsonType(scalar: ScalarType): "string" | "boolean" | "number" | `number | "NaN" | "Infinity" | "-Infinity"`;

View file

@ -0,0 +1,67 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.scalarTypeScriptType = scalarTypeScriptType;
exports.scalarJsonType = scalarJsonType;
const descriptors_js_1 = require("../descriptors.js");
/**
* Return the TypeScript type (as a string) for the given scalar type.
*/
function scalarTypeScriptType(scalar, longAsString) {
switch (scalar) {
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.INT64:
return longAsString ? "string" : "bigint";
case descriptors_js_1.ScalarType.BYTES:
return "Uint8Array";
default:
return "number";
}
}
/**
* Return the JSON type (as a string) for the given scalar type.
*/
function scalarJsonType(scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
return `number | "NaN" | "Infinity" | "-Infinity"`;
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.INT64:
return "string";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
return "number";
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.BYTES:
return "string";
}
}

View file

@ -0,0 +1,8 @@
import type { GenService, GenServiceMethods } from "./types.js";
import type { DescFile } from "../descriptors.js";
/**
* Hydrate a service descriptor.
*
* @private
*/
export declare function serviceDesc<T extends GenServiceMethods>(file: DescFile, path: number, ...paths: number[]): GenService<T>;

View file

@ -0,0 +1,27 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceDesc = serviceDesc;
/**
* Hydrate a service descriptor.
*
* @private
*/
function serviceDesc(file, path, ...paths) {
if (paths.length > 0) {
throw new Error();
}
return file.services[path];
}

View file

@ -0,0 +1,158 @@
/**
* @private
*/
export declare const packageName = "@bufbuild/protobuf";
/**
* @private
*
* A map from Protobuf file path to import path for the well-known types.
*
* All well-known files are exported as subpaths from @bufbuild/protobuf/wkt,
* but have been historically exported from a barrel. For backwards-compatibility,
* the existing barrel exports are maintained.
*
* For convenience, generated code continues to import from the barrel for
* commonly used WKT, and only generates the full subpath import for files
* that are rarely used.
*
* All well-known files must be listed here. New files should import from the
* full subpath.
*/
export declare const wktPublicImportPaths: Readonly<Record<string, string>>;
/**
* @private
*/
export declare const symbols: {
readonly isMessage: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../is-message.js";
readonly from: "@bufbuild/protobuf";
};
readonly Message: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../types.js";
readonly from: "@bufbuild/protobuf";
};
readonly create: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../create.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../from-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly fromBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../from-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toBinary: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../to-binary.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJson: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly toJsonString: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../to-json.js";
readonly from: "@bufbuild/protobuf";
};
readonly protoInt64: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../proto-int64.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonValue: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly JsonObject: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../json-value.js";
readonly from: "@bufbuild/protobuf";
};
readonly UnknownEnum: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../types.js";
readonly from: "@bufbuild/protobuf";
};
readonly codegen: {
readonly boot: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../codegenv2/boot.js";
readonly from: string;
};
readonly fileDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../codegenv2/file.js";
readonly from: string;
};
readonly enumDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../codegenv2/enum.js";
readonly from: string;
};
readonly extDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../codegenv2/extension.js";
readonly from: string;
};
readonly messageDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../codegenv2/message.js";
readonly from: string;
};
readonly serviceDesc: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../codegenv2/service.js";
readonly from: string;
};
readonly tsEnum: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../codegenv2/enum.js";
readonly from: string;
};
readonly objEnum: {
readonly typeOnly: false;
readonly bootstrapWktFrom: "../codegenv2/enum.js";
readonly from: string;
};
readonly GenFile: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../codegenv2/types.js";
readonly from: string;
};
readonly GenEnum: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../codegenv2/types.js";
readonly from: string;
};
readonly GenExtension: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../codegenv2/types.js";
readonly from: string;
};
readonly GenMessage: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../codegenv2/types.js";
readonly from: string;
};
readonly GenService: {
readonly typeOnly: true;
readonly bootstrapWktFrom: "../codegenv2/types.js";
readonly from: string;
};
};
};

View file

@ -0,0 +1,93 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.symbols = exports.wktPublicImportPaths = exports.packageName = void 0;
/**
* @private
*/
exports.packageName = "@bufbuild/protobuf";
const legacyWktBarrel = exports.packageName + "/wkt";
/**
* @private
*
* A map from Protobuf file path to import path for the well-known types.
*
* All well-known files are exported as subpaths from @bufbuild/protobuf/wkt,
* but have been historically exported from a barrel. For backwards-compatibility,
* the existing barrel exports are maintained.
*
* For convenience, generated code continues to import from the barrel for
* commonly used WKT, and only generates the full subpath import for files
* that are rarely used.
*
* All well-known files must be listed here. New files should import from the
* full subpath.
*/
exports.wktPublicImportPaths = {
"google/protobuf/compiler/plugin.proto": legacyWktBarrel,
"google/protobuf/any.proto": legacyWktBarrel,
"google/protobuf/api.proto": exports.packageName + "/wkt/google/protobuf/api_pb.js",
"google/protobuf/c_sharp_features.proto": exports.packageName + "/wkt/google/protobuf/c_sharp_features_pb.js",
"google/protobuf/cpp_features.proto": exports.packageName + "/wkt/google/protobuf/cpp_features_pb.js",
"google/protobuf/cpp_file_options.proto": exports.packageName + "/wkt/google/protobuf/cpp_file_options_pb.js",
"google/protobuf/cpp_options.proto": exports.packageName + "/wkt/google/protobuf/cpp_options_pb.js",
"google/protobuf/descriptor.proto": legacyWktBarrel,
"google/protobuf/duration.proto": legacyWktBarrel,
"google/protobuf/empty.proto": legacyWktBarrel,
"google/protobuf/field_mask.proto": legacyWktBarrel,
"google/protobuf/go_features.proto": exports.packageName + "/wkt/google/protobuf/go_features_pb.js",
"google/protobuf/java_features.proto": exports.packageName + "/wkt/google/protobuf/java_features_pb.js",
"google/protobuf/json_enumvalue_options.proto": exports.packageName + "/wkt/google/protobuf/json_enumvalue_options_pb.js",
"google/protobuf/json_options.proto": exports.packageName + "/wkt/google/protobuf/json_options_pb.js",
"google/protobuf/source_context.proto": exports.packageName + "/wkt/google/protobuf/source_context_pb.js",
"google/protobuf/struct.proto": legacyWktBarrel,
"google/protobuf/timestamp.proto": legacyWktBarrel,
"google/protobuf/type.proto": exports.packageName + "/wkt/google/protobuf/type_pb.js",
"google/protobuf/wrappers.proto": legacyWktBarrel,
};
/**
* @private
*/
// biome-ignore format: want this to read well
exports.symbols = {
isMessage: { typeOnly: false, bootstrapWktFrom: "../is-message.js", from: exports.packageName },
Message: { typeOnly: true, bootstrapWktFrom: "../types.js", from: exports.packageName },
create: { typeOnly: false, bootstrapWktFrom: "../create.js", from: exports.packageName },
fromJson: { typeOnly: false, bootstrapWktFrom: "../from-json.js", from: exports.packageName },
fromJsonString: { typeOnly: false, bootstrapWktFrom: "../from-json.js", from: exports.packageName },
fromBinary: { typeOnly: false, bootstrapWktFrom: "../from-binary.js", from: exports.packageName },
toBinary: { typeOnly: false, bootstrapWktFrom: "../to-binary.js", from: exports.packageName },
toJson: { typeOnly: false, bootstrapWktFrom: "../to-json.js", from: exports.packageName },
toJsonString: { typeOnly: false, bootstrapWktFrom: "../to-json.js", from: exports.packageName },
protoInt64: { typeOnly: false, bootstrapWktFrom: "../proto-int64.js", from: exports.packageName },
JsonValue: { typeOnly: true, bootstrapWktFrom: "../json-value.js", from: exports.packageName },
JsonObject: { typeOnly: true, bootstrapWktFrom: "../json-value.js", from: exports.packageName },
UnknownEnum: { typeOnly: true, bootstrapWktFrom: "../types.js", from: exports.packageName },
codegen: {
boot: { typeOnly: false, bootstrapWktFrom: "../codegenv2/boot.js", from: exports.packageName + "/codegenv2" },
fileDesc: { typeOnly: false, bootstrapWktFrom: "../codegenv2/file.js", from: exports.packageName + "/codegenv2" },
enumDesc: { typeOnly: false, bootstrapWktFrom: "../codegenv2/enum.js", from: exports.packageName + "/codegenv2" },
extDesc: { typeOnly: false, bootstrapWktFrom: "../codegenv2/extension.js", from: exports.packageName + "/codegenv2" },
messageDesc: { typeOnly: false, bootstrapWktFrom: "../codegenv2/message.js", from: exports.packageName + "/codegenv2" },
serviceDesc: { typeOnly: false, bootstrapWktFrom: "../codegenv2/service.js", from: exports.packageName + "/codegenv2" },
tsEnum: { typeOnly: false, bootstrapWktFrom: "../codegenv2/enum.js", from: exports.packageName + "/codegenv2" },
objEnum: { typeOnly: false, bootstrapWktFrom: "../codegenv2/enum.js", from: exports.packageName + "/codegenv2" },
GenFile: { typeOnly: true, bootstrapWktFrom: "../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenEnum: { typeOnly: true, bootstrapWktFrom: "../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenExtension: { typeOnly: true, bootstrapWktFrom: "../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenMessage: { typeOnly: true, bootstrapWktFrom: "../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
GenService: { typeOnly: true, bootstrapWktFrom: "../codegenv2/types.js", from: exports.packageName + "/codegenv2" },
},
};

View file

@ -0,0 +1,85 @@
import type { Message } from "../types.js";
import type { DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescService } from "../descriptors.js";
import type { JsonValue } from "../json-value.js";
/**
* Describes a protobuf source file.
*
* @private
*/
export type GenFile = DescFile;
/**
* Describes a message declaration in a protobuf source file.
*
* This type is identical to DescMessage, but carries additional type
* information.
*
* @private
*/
export type GenMessage<RuntimeShape extends Message, Opt extends {
jsonType?: unknown;
validType?: unknown;
} = {
jsonType?: unknown;
validType?: unknown;
}> = Omit<DescMessage, "field" | "typeName"> & {
field: Record<MessageFieldNames<RuntimeShape>, DescField>;
typeName: RuntimeShape["$typeName"];
} & brandv2<RuntimeShape, Opt>;
/**
* Describes an enumeration in a protobuf source file.
*
* This type is identical to DescEnum, but carries additional type
* information.
*
* @private
*/
export type GenEnum<RuntimeShape extends number, JsonType extends JsonValue = JsonValue> = Omit<DescEnum, "value"> & {
value: Record<RuntimeShape, DescEnumValue>;
} & brandv2<RuntimeShape, JsonType>;
/**
* Describes an extension in a protobuf source file.
*
* This type is identical to DescExtension, but carries additional type
* information.
*
* @private
*/
export type GenExtension<Extendee extends Message = Message, RuntimeShape = unknown> = DescExtension & brandv2<Extendee, RuntimeShape>;
/**
* Describes a service declaration in a protobuf source file.
*
* This type is identical to DescService, but carries additional type
* information.
*
* @private
*/
export type GenService<RuntimeShape extends GenServiceMethods> = Omit<DescService, "method"> & {
method: {
[K in keyof RuntimeShape]: RuntimeShape[K] & DescMethod;
};
};
/**
* @private
*/
export type GenServiceMethods = Record<string, Pick<DescMethod, "input" | "output" | "methodKind">>;
type brandv2<A, B = unknown> = {
/**
* @internal
*/
readonly $codegenv2: {
a: A;
b: B;
};
};
/**
* Union of the property names of all fields, including oneof members.
* For an anonymous message (no generated message shape), it's simply a string.
*/
type MessageFieldNames<T extends Message> = Message extends T ? string : Exclude<keyof {
[P in keyof T as P extends ("$typeName" | "$unknown") ? never : T[P] extends Oneof<infer K> ? K : P]-?: true;
}, number | symbol>;
type Oneof<K extends string> = {
case: K | undefined;
value?: unknown;
};
export {};

View file

@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });

View file

@ -0,0 +1,9 @@
import { type DescMessage } from "./descriptors.js";
import type { MessageInitShape, MessageShape } from "./types.js";
/**
* Create a new message instance.
*
* The second argument is an optional initializer object, where all fields are
* optional.
*/
export declare function create<Desc extends DescMessage>(schema: Desc, init?: MessageInitShape<Desc>): MessageShape<Desc>;

View file

@ -0,0 +1,297 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = create;
const is_message_js_1 = require("./is-message.js");
const descriptors_js_1 = require("./descriptors.js");
const scalar_js_1 = require("./reflect/scalar.js");
const guard_js_1 = require("./reflect/guard.js");
const unsafe_js_1 = require("./reflect/unsafe.js");
const wrappers_js_1 = require("./wkt/wrappers.js");
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name = $number;
const EDITION_PROTO3 = 999;
// bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name = $number;
const EDITION_PROTO2 = 998;
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name = $number;
const IMPLICIT = 2;
/**
* Create a new message instance.
*
* The second argument is an optional initializer object, where all fields are
* optional.
*/
function create(schema, init) {
if ((0, is_message_js_1.isMessage)(init, schema)) {
return init;
}
return compiledCreate(schema)(init);
}
const compiledCreates = new WeakMap();
/**
* Return the compiled create function for a message, compiling it on first use. */
function compiledCreate(desc) {
let compiled = compiledCreates.get(desc);
if (compiled === undefined) {
compiled = compileCreate(desc);
compiledCreates.set(desc, compiled);
}
return compiled;
}
/** Singular field: scalar, enum, or message. */
const INIT_SINGULAR = 0;
/** List field: a zero message has a fresh empty array. */
const INIT_LIST = 1;
/** Map field: a zero message has a fresh empty object. */
const INIT_MAP = 2;
/** Oneof group: the ADT is always stored, cases convert by case name. */
const INIT_ONEOF = 3;
/* Compile the create function for this message type. */
function compileCreate(desc) {
const typeName = desc.typeName;
const { properties, prototype } = compileInitMessage(desc);
return (init) => {
let message;
if (prototype !== undefined) {
message = Object.create(prototype);
message.$typeName = typeName;
}
else {
message = { $typeName: typeName };
}
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
const name = property.name;
const initValue = init === null || init === void 0 ? void 0 : init[name];
switch (property.kind) {
case INIT_SINGULAR:
if (initValue != null) {
message[name] =
property.convert !== undefined
? property.convert(initValue)
: initValue;
}
else if (property.constant !== undefined) {
message[name] = property.constant;
}
break;
case INIT_LIST:
message[name] =
property.convert !== undefined && Array.isArray(initValue)
? initValue.map(property.convert)
: (initValue !== null && initValue !== void 0 ? initValue : []);
break;
case INIT_MAP:
// Object.create(null) would be desirable for the fresh map, but is
// unsupported by React:
// https://react.dev/reference/react/use-server#serializable-parameters-and-return-values
if (property.convert === undefined || !(0, guard_js_1.isObject)(initValue)) {
message[name] = initValue !== null && initValue !== void 0 ? initValue : {};
}
else {
const converted = {};
const keys = Object.keys(initValue);
for (let k = 0; k < keys.length; k++) {
(0, unsafe_js_1.setOwn)(converted, keys[k], property.convert(initValue[keys[k]]));
}
message[name] = converted;
}
break;
case INIT_ONEOF: {
const oneofValue = initValue;
if ((oneofValue === null || oneofValue === void 0 ? void 0 : oneofValue.case) != null) {
const convert = property.convert.get(oneofValue.case);
if (convert !== undefined) {
message[name] = {
case: oneofValue.case,
value: convert(oneofValue.value),
};
break;
}
}
message[name] = { case: undefined };
break;
}
}
}
return message;
};
}
/**
* Classify every member once, so that creating a message is a walk over a
* compact list instead of a walk over the descriptor.
*/
function compileInitMessage(desc) {
var _a, _b;
const properties = [];
const prototype = {};
const usePrototype = needsPrototypeChain(desc);
for (const member of desc.members) {
const name = member.localName;
if (member.kind == "oneof") {
properties.push({
name,
kind: INIT_ONEOF,
constant: undefined,
convert: compileConvertOneof(member),
});
continue;
}
switch (member.fieldKind) {
case "message": {
// Singular message fields are absent from a zero message.
properties.push({
name,
kind: INIT_SINGULAR,
constant: undefined,
convert: compileConvertMessage(member),
});
break;
}
case "list": {
properties.push({
name,
kind: INIT_LIST,
constant: undefined,
convert: member.listKind == "message"
? ((_a = compileConvertMessage(member)) !== null && _a !== void 0 ? _a : ((value) => value))
: member.scalar == descriptors_js_1.ScalarType.BYTES
? toU8Arr
: undefined,
});
break;
}
case "map": {
properties.push({
name,
kind: INIT_MAP,
constant: undefined,
convert: member.mapKind == "message"
? ((_b = compileConvertMessage(member)) !== null && _b !== void 0 ? _b : ((value) => value))
: member.scalar == descriptors_js_1.ScalarType.BYTES
? toU8Arr
: undefined,
});
break;
}
default: {
const zeroValue = createZeroValue(member);
properties.push({
name,
kind: INIT_SINGULAR,
constant: member.presence == IMPLICIT ? zeroValue : undefined,
convert: member.fieldKind == "scalar" && member.scalar == descriptors_js_1.ScalarType.BYTES
? toU8Arr
: undefined,
});
if (usePrototype) {
prototype[name] = zeroValue;
}
break;
}
}
}
return {
properties,
prototype: usePrototype ? prototype : undefined,
};
}
/**
* Compile the conversion of each case of a oneof group, keyed by case name.
*/
function compileConvertOneof(oneof) {
const converters = new Map();
for (const field of oneof.fields) {
let convert;
if (field.fieldKind == "message") {
convert = compileConvertMessage(field);
}
else if (field.fieldKind == "scalar" &&
field.scalar == descriptors_js_1.ScalarType.BYTES) {
convert = toU8Arr;
}
converters.set(field.localName, convert !== null && convert !== void 0 ? convert : ((value) => value));
}
return converters;
}
/**
* Compile the conversion of an init value for a message field, a message
* list item, or a message map value. Returns undefined if values are used
* as-is.
*/
function compileConvertMessage(field) {
if (field.fieldKind == "message" &&
!field.oneof &&
(0, wrappers_js_1.isWrapperDesc)(field.message)) {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
return field.message.fields[0].scalar == descriptors_js_1.ScalarType.BYTES
? toU8Arr
: undefined;
}
if (field.message.typeName == "google.protobuf.Struct" &&
field.parent.typeName !== "google.protobuf.Value") {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
return undefined;
}
const messageDesc = field.message;
// Resolved on first use, not here: the message type can be this very field's
// parent, whose create function is still being compiled.
let compiled;
return (value) => {
if (!(0, guard_js_1.isObject)(value) || (0, is_message_js_1.isMessage)(value, messageDesc)) {
return value;
}
compiled !== null && compiled !== void 0 ? compiled : (compiled = compiledCreate(messageDesc));
return compiled(value);
};
}
// converts any ArrayLike<number> to Uint8Array if necessary.
function toU8Arr(value) {
return Array.isArray(value) ? new Uint8Array(value) : value;
}
/**
* Do we need the prototype chain to track field presence?
*/
function needsPrototypeChain(desc) {
switch (desc.file.edition) {
case EDITION_PROTO3:
// proto3 always uses implicit presence, we never need the prototype chain.
return false;
case EDITION_PROTO2:
// proto2 never uses implicit presence, we always need the prototype chain.
return true;
default:
// If a message uses scalar or enum fields with explicit presence, we need
// the prototype chain to track presence. This rule does not apply to fields
// in a oneof group - they use a different mechanism to track presence.
return desc.fields.some((f) => f.presence != IMPLICIT && f.fieldKind != "message" && !f.oneof);
}
}
/**
* Returns the zero value for a scalar or enum field. Scalar and enum fields
* can have default values.
*/
function createZeroValue(field) {
const defaultValue = field.getDefaultValue();
if (defaultValue !== undefined) {
return field.fieldKind == "scalar" && field.longAsString
? defaultValue.toString()
: defaultValue;
}
return field.fieldKind == "scalar"
? (0, scalar_js_1.scalarZeroValue)(field.scalar, field.longAsString)
: field.enum.values[0].number;
}

View file

@ -0,0 +1,638 @@
import type { DescriptorProto, Edition, EnumDescriptorProto, EnumValueDescriptorProto, FeatureSet_FieldPresence, FieldDescriptorProto, FileDescriptorProto, MethodDescriptorProto, MethodOptions_IdempotencyLevel, OneofDescriptorProto, ServiceDescriptorProto } from "./wkt/google/protobuf/descriptor_pb.js";
import type { ScalarValue } from "./reflect/scalar.js";
export type SupportedEdition = Extract<Edition, typeof Edition.EDITION_PROTO2 | typeof Edition.EDITION_PROTO3 | typeof Edition.EDITION_2023 | typeof Edition.EDITION_2024 | typeof Edition.EDITION_2026>;
type SupportedFieldPresence = Extract<FeatureSet_FieldPresence, typeof FeatureSet_FieldPresence.EXPLICIT | typeof FeatureSet_FieldPresence.IMPLICIT | typeof FeatureSet_FieldPresence.LEGACY_REQUIRED>;
/**
* Scalar value types. This is a subset of field types declared by protobuf
* enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
* are omitted, but the numerical values are identical.
*/
export declare enum ScalarType {
DOUBLE = 1,
FLOAT = 2,
INT64 = 3,
UINT64 = 4,
INT32 = 5,
FIXED64 = 6,
FIXED32 = 7,
BOOL = 8,
STRING = 9,
BYTES = 12,
UINT32 = 13,
SFIXED32 = 15,
SFIXED64 = 16,
SINT32 = 17,// Uses ZigZag encoding.
SINT64 = 18
}
/**
* A union of all descriptors, discriminated by a `kind` property.
*/
export type AnyDesc = DescFile | DescEnum | DescEnumValue | DescMessage | DescField | DescExtension | DescOneof | DescService | DescMethod;
/**
* Describes a protobuf source file.
*/
export interface DescFile {
readonly kind: "file";
/**
* The edition of the protobuf file. Will be EDITION_PROTO2 for syntax="proto2",
* EDITION_PROTO3 for syntax="proto3";
*/
readonly edition: SupportedEdition;
/**
* The name of the file, excluding the .proto suffix.
* For a protobuf file `foo/bar.proto`, this is `foo/bar`.
*/
readonly name: string;
/**
* Files imported by this file.
*/
readonly dependencies: DescFile[];
/**
* Top-level enumerations declared in this file.
* Note that more enumerations might be declared within message declarations.
*/
readonly enums: DescEnum[];
/**
* Top-level messages declared in this file.
* Note that more messages might be declared within message declarations.
*/
readonly messages: DescMessage[];
/**
* Top-level extensions declared in this file.
* Note that more extensions might be declared within message declarations.
*/
readonly extensions: DescExtension[];
/**
* Services declared in this file.
*/
readonly services: DescService[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: FileDescriptorProto;
toString(): string;
}
/**
* Describes an enumeration in a protobuf source file.
*/
export interface DescEnum {
readonly kind: "enum";
/**
* The fully qualified name of the enumeration. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the enumeration, as declared in the protobuf source.
*/
readonly name: string;
/**
* The file this enumeration was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this enumeration was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* Enumerations can be open or closed.
* See https://protobuf.dev/programming-guides/enum/
*/
readonly open: boolean;
/**
* Values declared for this enumeration.
*/
readonly values: DescEnumValue[];
/**
* All values of this enum by their number.
*/
readonly value: Record<number, DescEnumValue>;
/**
* A prefix shared by all enum values.
* For example, `my_enum_` for `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`
*/
readonly sharedPrefix?: string | undefined;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: EnumDescriptorProto;
toString(): string;
}
/**
* Describes an individual value of an enumeration in a protobuf source file.
*/
export interface DescEnumValue {
readonly kind: "enum_value";
/**
* The name of the enumeration value, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the value in a TypeScript enum.
*/
readonly localName: string;
/**
* The enumeration this value belongs to.
*/
readonly parent: DescEnum;
/**
* The numeric enumeration value, as specified in the protobuf source.
*/
readonly number: number;
/**
* The name of the enumeration value in JSON.
*/
readonly jsonName: string;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: EnumValueDescriptorProto;
toString(): string;
}
/**
* Describes a message declaration in a protobuf source file.
*/
export interface DescMessage {
readonly kind: "message";
/**
* The fully qualified name of the message. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the message, as specified in the protobuf source.
*/
readonly name: string;
/**
* The file this message was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this message was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* Fields declared for this message, including fields declared in a oneof
* group.
*/
readonly fields: DescField[];
/**
* All fields of this message by their "localName".
*/
readonly field: Record<string, DescField>;
/**
* Oneof groups declared for this message.
* This does not include synthetic oneofs for proto3 optionals.
*/
readonly oneofs: DescOneof[];
/**
* Standalone fields and oneof groups for this message, ordered by
* their appearance in the protobuf source.
*/
readonly members: (DescField | DescOneof)[];
/**
* Enumerations declared within the message, if any.
*/
readonly nestedEnums: DescEnum[];
/**
* Messages declared within the message, if any.
* This does not include synthetic messages like map entries.
*/
readonly nestedMessages: DescMessage[];
/**
* Extensions declared within the message, if any.
*/
readonly nestedExtensions: DescExtension[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: DescriptorProto;
toString(): string;
}
/**
* Describes a field declaration in a protobuf source file.
*/
export type DescField = (descFieldScalar & descFieldCommon) | (descFieldList & descFieldCommon) | (descFieldMessage & descFieldCommon) | (descFieldEnum & descFieldCommon) | (descFieldMap & descFieldCommon);
type descFieldCommon = descFieldAndExtensionShared & {
readonly kind: "field";
/**
* The message this field is declared on.
*/
readonly parent: DescMessage;
/**
* A safe and idiomatic name for the field as a property in ECMAScript.
*/
readonly localName: string;
};
/**
* Describes an extension in a protobuf source file.
*/
export type DescExtension = (Omit<descFieldScalar, "oneof"> & descExtensionCommon) | (Omit<descFieldEnum, "oneof"> & descExtensionCommon) | (Omit<descFieldMessage, "oneof"> & descExtensionCommon) | (descFieldList & descExtensionCommon);
type descExtensionCommon = descFieldAndExtensionShared & {
readonly kind: "extension";
/**
* The fully qualified name of the extension.
*/
readonly typeName: string;
/**
* The file this extension was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this extension was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* The message that this extension extends.
*/
readonly extendee: DescMessage;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
};
interface descFieldAndExtensionShared {
/**
* The field name, as specified in the protobuf source
*/
readonly name: string;
/**
* The field number, as specified in the protobuf source.
*/
readonly number: number;
/**
* The field name in JSON.
*/
readonly jsonName: string;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* Presence of the field.
* See https://protobuf.dev/programming-guides/field_presence/
*/
readonly presence: SupportedFieldPresence;
/**
* Whether to reject invalid UTF-8 when reading this field from the binary
* wire format. Reflects the resolved `utf8_validation` feature: true for
* VERIFY (proto3 and editions 2023+ default), false for NONE (proto2
* default).
*/
readonly utf8Validation: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: FieldDescriptorProto;
/**
* Get the edition features for this protobuf element.
*/
toString(): string;
}
type descFieldSingularCommon = {
/**
* The `oneof` group this field belongs to, if any.
*
* This does not include synthetic oneofs for proto3 optionals.
*/
readonly oneof: DescOneof | undefined;
};
type descFieldScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly fieldKind: "scalar";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: T;
/**
* By default, 64-bit integral types (int64, uint64, sint64, fixed64,
* sfixed64) are represented with BigInt.
*
* If the field option `jstype = JS_STRING` is set, this property
* is true, and 64-bit integral types are represented with String.
*/
readonly longAsString: boolean;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): ScalarValue<T> | undefined;
} & descFieldSingularCommon : never;
type descFieldMessage = {
readonly fieldKind: "message";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: DescMessage;
/**
* Encode the message delimited (a.k.a. proto2 group encoding), or
* length-prefixed?
*/
readonly delimitedEncoding: boolean;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): undefined;
} & descFieldSingularCommon;
type descFieldEnum = {
readonly fieldKind: "enum";
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: DescEnum;
/**
* Return the default value specified in the protobuf source.
*/
getDefaultValue(): number | undefined;
} & descFieldSingularCommon;
type descFieldList = (descFieldListScalar & descFieldListCommon) | (descFieldListEnum & descFieldListCommon) | (descFieldListMessage & descFieldListCommon);
type descFieldListCommon = {
readonly fieldKind: "list";
/**
* Pack this repeated field? Only valid for repeated enum fields, and
* for repeated scalar fields except BYTES and STRING.
*/
readonly packed: boolean;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
};
type descFieldListScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly listKind: "scalar";
/**
* The enum list element type.
*/
readonly enum: undefined;
/**
* The message list element type.
*/
readonly message: undefined;
/**
* Scalar list element type.
*/
readonly scalar: T;
/**
* By default, 64-bit integral types (int64, uint64, sint64, fixed64,
* sfixed64) are represented with BigInt.
*
* If the field option `jstype = JS_STRING` is set, this property
* is true, and 64-bit integral types are represented with String.
*/
readonly longAsString: boolean;
} : never;
type descFieldListEnum = {
readonly listKind: "enum";
/**
* The enum list element type.
*/
readonly enum: DescEnum;
/**
* The message list element type.
*/
readonly message: undefined;
/**
* Scalar list element type.
*/
readonly scalar: undefined;
};
type descFieldListMessage = {
readonly listKind: "message";
/**
* The enum list element type.
*/
readonly enum: undefined;
/**
* The message list element type.
*/
readonly message: DescMessage;
/**
* Scalar list element type.
*/
readonly scalar: undefined;
/**
* Encode the message delimited (a.k.a. proto2 group encoding), or
* length-prefixed?
*/
readonly delimitedEncoding: boolean;
};
type descFieldMap = (descFieldMapScalar & descFieldMapCommon) | (descFieldMapEnum & descFieldMapCommon) | (descFieldMapMessage & descFieldMapCommon);
type descFieldMapCommon<T extends ScalarType = ScalarType> = T extends Exclude<ScalarType, ScalarType.FLOAT | ScalarType.DOUBLE | ScalarType.BYTES> ? {
readonly fieldKind: "map";
/**
* The scalar map key type.
*/
readonly mapKey: T;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: undefined;
/**
* Encode the map entry message delimited (a.k.a. proto2 group encoding),
* or length-prefixed? As of Edition 2023, this is always false for map fields,
* and also applies to map values, if they are messages.
*/
readonly delimitedEncoding: false;
} : never;
type descFieldMapScalar<T extends ScalarType = ScalarType> = T extends T ? {
readonly mapKind: "scalar";
/**
* The enum map value type.
*/
readonly enum: undefined;
/**
* The message map value type.
*/
readonly message: undefined;
/**
* Scalar map value type.
*/
readonly scalar: T;
} : never;
type descFieldMapEnum = {
readonly mapKind: "enum";
/**
* The enum map value type.
*/
readonly enum: DescEnum;
/**
* The message map value type.
*/
readonly message: undefined;
/**
* Scalar map value type.
*/
readonly scalar: undefined;
};
type descFieldMapMessage = {
readonly mapKind: "message";
/**
* The enum map value type.
*/
readonly enum: undefined;
/**
* The message map value type.
*/
readonly message: DescMessage;
/**
* Scalar map value type.
*/
readonly scalar: undefined;
};
/**
* Describes a oneof group in a protobuf source file.
*/
export interface DescOneof {
readonly kind: "oneof";
/**
* The name of the oneof group, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the oneof group as a property in ECMAScript.
*/
readonly localName: string;
/**
* The message this oneof group was declared in.
*/
readonly parent: DescMessage;
/**
* The fields declared in this oneof group.
*/
readonly fields: DescField[];
/**
* Marked as deprecated in the protobuf source.
* Note that oneof groups cannot be marked as deprecated, this property
* only exists for consistency and will always be false.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: OneofDescriptorProto;
toString(): string;
}
/**
* Describes a service declaration in a protobuf source file.
*/
export interface DescService {
readonly kind: "service";
/**
* The fully qualified name of the service. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the service, as specified in the protobuf source.
*/
readonly name: string;
/**
* The file this service was declared in.
*/
readonly file: DescFile;
/**
* The RPCs this service declares.
*/
readonly methods: DescMethod[];
/**
* All methods of this service by their "localName".
*/
readonly method: Record<string, DescMethod>;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: ServiceDescriptorProto;
toString(): string;
}
/**
* Describes an RPC declaration in a protobuf source file.
*/
export interface DescMethod {
readonly kind: "rpc";
/**
* The name of the RPC, as specified in the protobuf source.
*/
readonly name: string;
/**
* A safe and idiomatic name for the RPC as a method in ECMAScript.
*/
readonly localName: string;
/**
* The parent service.
*/
readonly parent: DescService;
/**
* One of the four available method types.
*/
readonly methodKind: "unary" | "server_streaming" | "client_streaming" | "bidi_streaming";
/**
* The message type for requests.
*/
readonly input: DescMessage;
/**
* The message type for responses.
*/
readonly output: DescMessage;
/**
* The idempotency level declared in the protobuf source, if any.
*/
readonly idempotency: MethodOptions_IdempotencyLevel;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: MethodDescriptorProto;
toString(): string;
}
/**
* Comments on an element in a protobuf source file.
*/
export interface DescComments {
readonly leadingDetached: readonly string[];
readonly leading?: string | undefined;
readonly trailing?: string | undefined;
readonly sourcePath: readonly number[];
}
export {};

View file

@ -0,0 +1,53 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScalarType = void 0;
/**
* Scalar value types. This is a subset of field types declared by protobuf
* enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
* are omitted, but the numerical values are identical.
*/
var ScalarType;
(function (ScalarType) {
// 0 is reserved for errors.
// Order is weird for historical reasons.
ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE";
ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT";
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
// negative values are likely.
ScalarType[ScalarType["INT64"] = 3] = "INT64";
ScalarType[ScalarType["UINT64"] = 4] = "UINT64";
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
// negative values are likely.
ScalarType[ScalarType["INT32"] = 5] = "INT32";
ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64";
ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32";
ScalarType[ScalarType["BOOL"] = 8] = "BOOL";
ScalarType[ScalarType["STRING"] = 9] = "STRING";
// Tag-delimited aggregate.
// Group type is deprecated and not supported in proto3. However, Proto3
// implementations should still be able to parse the group wire format and
// treat group fields as unknown fields.
// TYPE_GROUP = 10,
// TYPE_MESSAGE = 11, // Length-delimited aggregate.
// New in version 2.
ScalarType[ScalarType["BYTES"] = 12] = "BYTES";
ScalarType[ScalarType["UINT32"] = 13] = "UINT32";
// TYPE_ENUM = 14,
ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32";
ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64";
ScalarType[ScalarType["SINT32"] = 17] = "SINT32";
ScalarType[ScalarType["SINT64"] = 18] = "SINT64";
})(ScalarType || (exports.ScalarType = ScalarType = {}));

View file

@ -0,0 +1,46 @@
import type { MessageShape } from "./types.js";
import { type DescMessage } from "./descriptors.js";
import type { Registry } from "./registry.js";
interface EqualsOptions {
/**
* A registry to look up extensions, and messages packed in Any.
*
* @private Experimental API, does not follow semantic versioning.
*/
registry: Registry;
/**
* Unpack google.protobuf.Any before comparing.
* If a type is not in the registry, comparison falls back to comparing the
* fields of Any.
*
* @private Experimental API, does not follow semantic versioning.
*/
unpackAny?: boolean;
/**
* Consider extensions when comparing.
*
* @private Experimental API, does not follow semantic versioning.
*/
extensions?: boolean;
/**
* Consider unknown fields when comparing.
* The registry is used to distinguish between extensions, and unknown fields
* caused by schema changes.
*
* @private Experimental API, does not follow semantic versioning.
*/
unknown?: boolean;
}
/**
* Compare two messages of the same type for equality.
*
* Fields are compared one by one, but only when set: a field set in one message
* but not the other makes them unequal, while fields set in both are compared
* by value. Extensions and unknown fields are disregarded by default.
*
* Float and double values are compared with IEEE semantics: NaN does not equal
* NaN, and -0 equals 0 (with the exception for singular fields with implicit
* presence: -0 is set, +0 is unset).
*/
export declare function equals<Desc extends DescMessage>(schema: Desc, a: MessageShape<Desc>, b: MessageShape<Desc>, options?: EqualsOptions): boolean;
export {};

View file

@ -0,0 +1,209 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.equals = equals;
const scalar_js_1 = require("./reflect/scalar.js");
const reflect_js_1 = require("./reflect/reflect.js");
const descriptors_js_1 = require("./descriptors.js");
const index_js_1 = require("./wkt/index.js");
const extensions_js_1 = require("./extensions.js");
/**
* Compare two messages of the same type for equality.
*
* Fields are compared one by one, but only when set: a field set in one message
* but not the other makes them unequal, while fields set in both are compared
* by value. Extensions and unknown fields are disregarded by default.
*
* Float and double values are compared with IEEE semantics: NaN does not equal
* NaN, and -0 equals 0 (with the exception for singular fields with implicit
* presence: -0 is set, +0 is unset).
*/
function equals(schema, a, b, options) {
if (a.$typeName != schema.typeName || b.$typeName != schema.typeName) {
return false;
}
if (a === b) {
return true;
}
return reflectEquals((0, reflect_js_1.reflect)(schema, a), (0, reflect_js_1.reflect)(schema, b), options);
}
function reflectEquals(a, b, opts) {
if (a.desc.typeName === "google.protobuf.Any" && (opts === null || opts === void 0 ? void 0 : opts.unpackAny) == true) {
return anyUnpackedEquals(a.message, b.message, opts);
}
for (const f of a.fields) {
if (!fieldEquals(f, a, b, opts)) {
return false;
}
}
if ((opts === null || opts === void 0 ? void 0 : opts.unknown) == true && !unknownEquals(a, b, opts.registry)) {
return false;
}
if ((opts === null || opts === void 0 ? void 0 : opts.extensions) == true && !extensionsEquals(a, b, opts)) {
return false;
}
return true;
}
// TODO(tstamm) add an option to consider NaN equal to NaN?
function fieldEquals(f, a, b, opts) {
if (!a.isSet(f) && !b.isSet(f)) {
return true;
}
if (!a.isSet(f) || !b.isSet(f)) {
return false;
}
switch (f.fieldKind) {
case "scalar":
return (0, scalar_js_1.scalarEquals)(f.scalar, a.get(f), b.get(f));
case "enum":
return a.get(f) === b.get(f);
case "message":
return reflectEquals(a.get(f), b.get(f), opts);
case "map": {
// TODO(tstamm) can't we compare sizes first?
const mapA = a.get(f);
const mapB = b.get(f);
const keys = [];
for (const k of mapA.keys()) {
if (!mapB.has(k)) {
return false;
}
keys.push(k);
}
for (const k of mapB.keys()) {
if (!mapA.has(k)) {
return false;
}
}
for (const key of keys) {
const va = mapA.get(key);
const vb = mapB.get(key);
if (va === vb) {
continue;
}
switch (f.mapKind) {
case "enum":
return false;
case "message":
if (!reflectEquals(va, vb, opts)) {
return false;
}
break;
case "scalar":
if (!(0, scalar_js_1.scalarEquals)(f.scalar, va, vb)) {
return false;
}
break;
}
}
break;
}
case "list": {
const listA = a.get(f);
const listB = b.get(f);
if (listA.size != listB.size) {
return false;
}
for (let i = 0; i < listA.size; i++) {
const va = listA.get(i);
const vb = listB.get(i);
if (va === vb) {
continue;
}
switch (f.listKind) {
case "enum":
return false;
case "message":
if (!reflectEquals(va, vb, opts)) {
return false;
}
break;
case "scalar":
if (!(0, scalar_js_1.scalarEquals)(f.scalar, va, vb)) {
return false;
}
break;
}
}
break;
}
}
return true;
}
function anyUnpackedEquals(a, b, opts) {
if (a.typeUrl !== b.typeUrl) {
return false;
}
const unpackedA = (0, index_js_1.anyUnpack)(a, opts.registry);
const unpackedB = (0, index_js_1.anyUnpack)(b, opts.registry);
if (unpackedA && unpackedB) {
const schema = opts.registry.getMessage(unpackedA.$typeName);
if (schema) {
return equals(schema, unpackedA, unpackedB, opts);
}
}
return (0, scalar_js_1.scalarEquals)(descriptors_js_1.ScalarType.BYTES, a.value, b.value);
}
function unknownEquals(a, b, registry) {
function getTrulyUnknown(msg, registry) {
var _a;
const u = (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : [];
return registry
? u.filter((uf) => !registry.getExtensionFor(msg.desc, uf.no))
: u;
}
const unknownA = getTrulyUnknown(a, registry);
const unknownB = getTrulyUnknown(b, registry);
if (unknownA.length != unknownB.length) {
return false;
}
for (let i = 0; i < unknownA.length; i++) {
const a = unknownA[i];
const b = unknownB[i];
if (a.no != b.no) {
return false;
}
if (a.wireType != b.wireType) {
return false;
}
if (!(0, scalar_js_1.scalarEquals)(descriptors_js_1.ScalarType.BYTES, a.data, b.data)) {
return false;
}
}
return true;
}
function extensionsEquals(a, b, opts) {
function getSetExtensions(msg, registry) {
var _a;
return ((_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : [])
.map((uf) => registry.getExtensionFor(msg.desc, uf.no))
.filter((e) => e != undefined)
.filter((e, index, arr) => arr.indexOf(e) === index);
}
const extensionsA = getSetExtensions(a, opts.registry);
const extensionsB = getSetExtensions(b, opts.registry);
if (extensionsA.length != extensionsB.length ||
extensionsA.some((e) => !extensionsB.includes(e))) {
return false;
}
for (const extension of extensionsA) {
const [containerA, field] = (0, extensions_js_1.createExtensionContainer)(extension, (0, extensions_js_1.getExtension)(a.message, extension));
const [containerB] = (0, extensions_js_1.createExtensionContainer)(extension, (0, extensions_js_1.getExtension)(b.message, extension));
if (!fieldEquals(field, containerA, containerB, opts)) {
return false;
}
}
return true;
}

View file

@ -0,0 +1,60 @@
import type { AnyDesc, DescEnum, DescEnumValue, DescExtension, DescField, DescFile, DescMessage, DescMethod, DescOneof, DescService } from "./descriptors.js";
import type { BinaryReadOptions } from "./from-binary.js";
import type { ReflectMessage } from "./reflect/reflect-types.js";
import type { Extendee, ExtensionValueShape } from "./types.js";
import type { EnumOptions, EnumValueOptions, FieldOptions, FileOptions, MessageOptions, MethodOptions, OneofOptions, ServiceOptions } from "./wkt/google/protobuf/descriptor_pb.js";
/**
* Retrieve an extension value from a message.
*
* The function never returns undefined. Use hasExtension() to check whether an
* extension is set. If the extension is not set, this function returns the
* default value (if one was specified in the protobuf source), or the zero value
* (for example `0` for numeric types, `[]` for repeated extension fields, and
* an empty message instance for message fields).
*
* Extensions are stored as unknown fields on a message. To mutate an extension
* value, make sure to store the new value with setExtension() after mutating.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function getExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc, options?: Partial<BinaryReadOptions>): ExtensionValueShape<Desc>;
/**
* Set an extension value on a message. If the message already has a value for
* this extension, the value is replaced.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function setExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc, value: ExtensionValueShape<Desc>): void;
/**
* Remove an extension value from a message.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function clearExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc): void;
/**
* Check whether an extension is set on a message.
*/
export declare function hasExtension<Desc extends DescExtension>(message: Extendee<Desc>, extension: Desc): boolean;
/**
* Check whether an option is set on a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls hasExtension().
*/
export declare function hasOption<Ext extends DescExtension, Desc extends DescForOptionExtension<Ext>>(element: Desc, option: Ext): boolean;
/**
* Retrieve an option value from a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls getExtension(). Same as getExtension(), this
* function never returns undefined.
*/
export declare function getOption<Ext extends DescExtension, Desc extends DescForOptionExtension<Ext>>(element: Desc, option: Ext): ExtensionValueShape<Ext>;
type DescForOptionExtension<Ext extends DescExtension> = Extendee<Ext> extends FileOptions ? DescFile : Extendee<Ext> extends EnumOptions ? DescEnum : Extendee<Ext> extends EnumValueOptions ? DescEnumValue : Extendee<Ext> extends MessageOptions ? DescMessage : Extendee<Ext> extends MessageOptions ? DescEnum : Extendee<Ext> extends FieldOptions ? DescField | DescExtension : Extendee<Ext> extends OneofOptions ? DescOneof : Extendee<Ext> extends ServiceOptions ? DescService : Extendee<Ext> extends EnumOptions ? DescEnum : Extendee<Ext> extends MethodOptions ? DescMethod : AnyDesc;
/**
* @private
*/
export declare function createExtensionContainer<Desc extends DescExtension>(extension: Desc, value?: ExtensionValueShape<Desc>): [ReflectMessage, DescField, () => ExtensionValueShape<Desc>];
export {};

View file

@ -0,0 +1,168 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.getExtension = getExtension;
exports.setExtension = setExtension;
exports.clearExtension = clearExtension;
exports.hasExtension = hasExtension;
exports.hasOption = hasOption;
exports.getOption = getOption;
exports.createExtensionContainer = createExtensionContainer;
const create_js_1 = require("./create.js");
const from_binary_js_1 = require("./from-binary.js");
const reflect_js_1 = require("./reflect/reflect.js");
const scalar_js_1 = require("./reflect/scalar.js");
const to_binary_js_1 = require("./to-binary.js");
const binary_encoding_js_1 = require("./wire/binary-encoding.js");
const wrappers_js_1 = require("./wkt/wrappers.js");
/**
* Retrieve an extension value from a message.
*
* The function never returns undefined. Use hasExtension() to check whether an
* extension is set. If the extension is not set, this function returns the
* default value (if one was specified in the protobuf source), or the zero value
* (for example `0` for numeric types, `[]` for repeated extension fields, and
* an empty message instance for message fields).
*
* Extensions are stored as unknown fields on a message. To mutate an extension
* value, make sure to store the new value with setExtension() after mutating.
*
* If the extension does not extend the given message, an error is raised.
*/
function getExtension(message, extension, options) {
assertExtendee(extension, message);
const ufs = filterUnknownFields(message.$unknown, extension);
const [container, field, get] = createExtensionContainer(extension);
const ctx = (0, from_binary_js_1.makeReadContext)(options);
for (const uf of ufs) {
(0, from_binary_js_1.readField)(container, new binary_encoding_js_1.BinaryReader(uf.data), field, uf.wireType, ctx);
}
return get();
}
/**
* Set an extension value on a message. If the message already has a value for
* this extension, the value is replaced.
*
* If the extension does not extend the given message, an error is raised.
*/
function setExtension(message, extension, value) {
var _a;
assertExtendee(extension, message);
const ufs = ((_a = message.$unknown) !== null && _a !== void 0 ? _a : []).filter((uf) => uf.no !== extension.number);
const [container, field] = createExtensionContainer(extension, value);
const writer = new binary_encoding_js_1.BinaryWriter();
(0, to_binary_js_1.writeField)(writer, { writeUnknownFields: true }, container, field);
const reader = new binary_encoding_js_1.BinaryReader(writer.finish());
while (reader.pos < reader.len) {
const [no, wireType] = reader.tag();
const data = reader.skip(wireType, no);
ufs.push({ no, wireType, data });
}
message.$unknown = ufs;
}
/**
* Remove an extension value from a message.
*
* If the extension does not extend the given message, an error is raised.
*/
function clearExtension(message, extension) {
assertExtendee(extension, message);
if (message.$unknown === undefined) {
return;
}
message.$unknown = message.$unknown.filter((uf) => uf.no !== extension.number);
}
/**
* Check whether an extension is set on a message.
*/
function hasExtension(message, extension) {
var _a;
return (extension.extendee.typeName === message.$typeName &&
!!((_a = message.$unknown) === null || _a === void 0 ? void 0 : _a.find((uf) => uf.no === extension.number)));
}
/**
* Check whether an option is set on a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls hasExtension().
*/
function hasOption(element, option) {
const message = element.proto.options;
if (!message) {
return false;
}
return hasExtension(message, option);
}
/**
* Retrieve an option value from a descriptor.
*
* Options are extensions to the `google.protobuf.*Options` messages defined in
* google/protobuf/descriptor.proto. This function gets the option message from
* the descriptor, and calls getExtension(). Same as getExtension(), this
* function never returns undefined.
*/
function getOption(element, option) {
const message = element.proto.options;
if (!message) {
const [, , get] = createExtensionContainer(option);
return get();
}
return getExtension(message, option);
}
function filterUnknownFields(unknownFields, extension) {
if (unknownFields === undefined)
return [];
if (extension.fieldKind === "enum" || extension.fieldKind === "scalar") {
// singular scalar fields do not merge, we pick the last
for (let i = unknownFields.length - 1; i >= 0; --i) {
if (unknownFields[i].no == extension.number) {
return [unknownFields[i]];
}
}
return [];
}
return unknownFields.filter((uf) => uf.no === extension.number);
}
/**
* @private
*/
function createExtensionContainer(extension, value) {
const localName = extension.typeName;
const field = Object.assign(Object.assign({}, extension), { kind: "field", parent: extension.extendee, localName });
const desc = Object.assign(Object.assign({}, extension.extendee), { fields: [field], members: [field], oneofs: [] });
const container = (0, create_js_1.create)(desc, value !== undefined ? { [localName]: value } : undefined);
return [
(0, reflect_js_1.reflect)(desc, container),
field,
() => {
const value = container[localName];
if (value === undefined) {
// biome-ignore lint/style/noNonNullAssertion: Only message fields are undefined, rest will have a zero value.
const desc = extension.message;
if ((0, wrappers_js_1.isWrapperDesc)(desc)) {
return (0, scalar_js_1.scalarZeroValue)(desc.fields[0].scalar, desc.fields[0].longAsString);
}
return (0, create_js_1.create)(desc);
}
return value;
},
];
}
function assertExtendee(extension, message) {
if (extension.extendee.typeName != message.$typeName) {
throw new Error(`extension ${extension.typeName} can only be applied to message ${extension.extendee.typeName}`);
}
}

View file

@ -0,0 +1,23 @@
import type { MessageShape } from "./types.js";
import type { DescField, DescMessage } from "./descriptors.js";
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
export declare function isFieldSet<Desc extends DescMessage>(message: MessageShape<Desc>, field: DescField): boolean;
/**
* Resets the field, so that isFieldSet() will return false.
*/
export declare function clearField<Desc extends DescMessage>(message: MessageShape<Desc>, field: DescField): void;

View file

@ -0,0 +1,45 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFieldSet = isFieldSet;
exports.clearField = clearField;
const unsafe_js_1 = require("./reflect/unsafe.js");
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
function isFieldSet(message, field) {
return (field.parent.typeName == message.$typeName && (0, unsafe_js_1.unsafeIsSet)(message, field));
}
/**
* Resets the field, so that isFieldSet() will return false.
*/
function clearField(message, field) {
if (field.parent.typeName == message.$typeName) {
(0, unsafe_js_1.unsafeClear)(message, field);
}
}

View file

@ -0,0 +1,48 @@
import { type DescField, type DescMessage } from "./descriptors.js";
import type { MessageShape } from "./types.js";
import type { ReflectMessage } from "./reflect/index.js";
import { BinaryReader, WireType } from "./wire/binary-encoding.js";
/**
* Options for parsing binary data.
*/
export interface BinaryReadOptions {
/**
* Retain unknown fields during parsing? The default behavior is to retain
* unknown fields and include them in the serialized output.
*
* For more details see https://developers.google.com/protocol-buffers/docs/proto3#unknowns
*/
readUnknownFields: boolean;
/**
* The maximum depth of nested messages to parse. If a message nests deeper
* than this limit, parsing fails with an error instead of exhausting the
* call stack. Defaults to 100.
*/
recursionLimit: number;
}
interface BinaryReadContext extends BinaryReadOptions {
depth: number;
}
/**
* @private Only exported for getExtension()
*/
export declare function makeReadContext(options?: Partial<BinaryReadOptions>): BinaryReadContext;
/**
* Parse serialized binary data.
*/
export declare function fromBinary<Desc extends DescMessage>(schema: Desc, bytes: Uint8Array, options?: Partial<BinaryReadOptions>): MessageShape<Desc>;
/**
* Parse from binary data, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
export declare function mergeFromBinary<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, bytes: Uint8Array, options?: Partial<BinaryReadOptions>): MessageShape<Desc>;
/**
* @private Only exported for getExtension()
*/
export declare function readField(message: ReflectMessage, reader: BinaryReader, field: DescField, wireType: WireType, ctx: BinaryReadContext): void;
export {};

View file

@ -0,0 +1,418 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeReadContext = makeReadContext;
exports.fromBinary = fromBinary;
exports.mergeFromBinary = mergeFromBinary;
exports.readField = readField;
const descriptors_js_1 = require("./descriptors.js");
const scalar_js_1 = require("./reflect/scalar.js");
const error_js_1 = require("./reflect/error.js");
const unsafe_js_1 = require("./reflect/unsafe.js");
const message_js_1 = require("./reflect/message.js");
const create_js_1 = require("./create.js");
const binary_encoding_js_1 = require("./wire/binary-encoding.js");
const varint_js_1 = require("./wire/varint.js");
/**
* @private Only exported for getExtension()
*/
function makeReadContext(options) {
return Object.assign(Object.assign({ readUnknownFields: true, recursionLimit: 100 }, options), { depth: 0 });
}
/**
* Parse serialized binary data.
*/
function fromBinary(schema, bytes, options) {
const message = (0, create_js_1.create)(schema);
compiledReader(schema).read(message, new binary_encoding_js_1.BinaryReader(bytes), makeReadContext(options), bytes.byteLength);
return message;
}
/**
* Parse from binary data, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
function mergeFromBinary(schema, target, bytes, options) {
if (target.$typeName !== schema.typeName &&
schema.fields.length > 0) {
throw new error_js_1.FieldError(schema.fields[0], `cannot use ${schema.fields[0]} with message ${target.$typeName}`, "ForeignFieldError");
}
compiledReader(schema).read(target, new binary_encoding_js_1.BinaryReader(bytes), makeReadContext(options), bytes.byteLength);
return target;
}
const compiledReaders = new WeakMap();
/**
* Return the compiled decoder for a message, compiling it on first use.
*/
function compiledReader(desc) {
let compiled = compiledReaders.get(desc);
if (compiled === undefined) {
compiled = compileMessage(desc);
}
return compiled;
}
function compileMessage(desc) {
const descString = String(desc);
const fieldReaders = new Map();
const compiled = {
read: compileMessageReader(descString, fieldReaders),
readGroup: compileGroupReader(descString, fieldReaders),
};
// Register before compiling fields, so that recursive message types
// resolve to this instance instead of compiling endlessly.
compiledReaders.set(desc, compiled);
for (const field of desc.fields) {
fieldReaders.set(field.number, compileFieldReader(field));
}
return compiled;
}
/**
* Create a decoder for a length-prefixed message body, dispatching wire
* records to the compiled field decoders by field number.
*/
function compileMessageReader(descString, fieldReaders) {
return (message, reader, ctx, length) => {
var _a;
if (++ctx.depth > ctx.recursionLimit) {
throw new Error(`cannot decode ${descString} from binary: maximum recursion depth of ${ctx.recursionLimit} reached`);
}
const end = reader.pos + length;
const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
while (reader.pos < end) {
const [fieldNo, wireType] = reader.tag();
const fieldReader = fieldReaders.get(fieldNo);
if (fieldReader === undefined) {
// Use remaining recursion budget for skipping nested groups
const data = reader.skip(wireType, fieldNo, ctx.recursionLimit - ctx.depth);
if (ctx.readUnknownFields) {
unknownFields.push({ no: fieldNo, wireType, data });
}
continue;
}
fieldReader(message, reader, ctx, wireType);
}
if (unknownFields.length > 0) {
message.$unknown = unknownFields;
}
ctx.depth--;
};
}
/**
* Create a decoder for a message with the delimited encoding (group),
* reading until the EndGroup tag, like compileMessageReader.
*/
function compileGroupReader(descString, fieldReaders) {
return (message, reader, ctx, fieldNo) => {
var _a;
if (++ctx.depth > ctx.recursionLimit) {
throw new Error(`cannot decode ${descString} from binary: maximum recursion depth of ${ctx.recursionLimit} reached`);
}
let recordFieldNo;
let wireType;
const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
while (reader.pos < reader.len) {
[recordFieldNo, wireType] = reader.tag();
if (wireType == binary_encoding_js_1.WireType.EndGroup) {
break;
}
const fieldReader = fieldReaders.get(recordFieldNo);
if (fieldReader === undefined) {
// Use remaining recursion budget for skipping nested groups
const data = reader.skip(wireType, recordFieldNo, ctx.recursionLimit - ctx.depth);
if (ctx.readUnknownFields) {
unknownFields.push({ no: recordFieldNo, wireType, data });
}
continue;
}
fieldReader(message, reader, ctx, wireType);
}
if (wireType != binary_encoding_js_1.WireType.EndGroup || recordFieldNo !== fieldNo) {
throw new Error("invalid end group tag");
}
if (unknownFields.length > 0) {
message.$unknown = unknownFields;
}
ctx.depth--;
};
}
/**
* @private Only exported for getExtension()
*/
function readField(message, reader, field, wireType, ctx) {
compileFieldReader(field)(message[unsafe_js_1.unsafeLocal], reader, ctx, wireType);
}
function compileFieldReader(field) {
switch (field.fieldKind) {
case "scalar":
return compileScalarFieldReader(field);
case "enum":
return compileEnumFieldReader(field);
case "message":
return compileMessageFieldReader(field);
case "list":
return compileListFieldReader(field);
case "map":
return compileMapFieldReader(field);
}
}
function compileScalarFieldReader(field) {
const readScalar = compileScalarReader(field.scalar, field.utf8Validation, field.longAsString);
const localName = field.localName;
if (field.oneof) {
const oneofLocalName = field.oneof.localName;
return (message, reader) => {
message[oneofLocalName] = {
case: localName,
value: readScalar(reader),
};
};
}
return (message, reader) => {
message[localName] = readScalar(reader);
};
}
function compileEnumFieldReader(field) {
var _a;
const localName = field.localName;
const oneofLocalName = (_a = field.oneof) === null || _a === void 0 ? void 0 : _a.localName;
if (field.enum.open) {
if (oneofLocalName !== undefined) {
return (message, reader) => {
message[oneofLocalName] = { case: localName, value: reader.int32() };
};
}
return (message, reader) => {
message[localName] = reader.int32();
};
}
// Closed enums: unknown values are stored as unknown fields.
const values = field.enum.values;
const fieldNo = field.number;
return (message, reader, ctx, wireType) => {
var _a;
const val = reader.int32();
if (values.some((v) => v.number === val)) {
if (oneofLocalName !== undefined) {
message[oneofLocalName] = { case: localName, value: val };
}
else {
message[localName] = val;
}
}
else if (ctx.readUnknownFields) {
const bytes = [];
(0, varint_js_1.varint32write)(val, bytes);
const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
unknownFields.push({
no: fieldNo,
wireType,
data: new Uint8Array(bytes),
});
message.$unknown = unknownFields;
}
};
}
function compileMessageFieldReader(field) {
const localName = field.localName;
const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
const readChild = compileChildReader(field);
if (field.oneof) {
const oneofLocalName = field.oneof.localName;
return (message, reader, ctx) => {
const oneof = message[oneofLocalName];
const child = toMessage(oneof.case === localName ? oneof.value : undefined);
readChild(child, reader, ctx);
message[oneofLocalName] = { case: localName, value: toLocal(child) };
};
}
return (message, reader, ctx) => {
const child = toMessage(message[localName]);
readChild(child, reader, ctx);
message[localName] = toLocal(child);
};
}
/**
* Compile a decoder for the wire format of a message field, honoring the
* delimited encoding of the field.
*/
function compileChildReader(field) {
const compiledChild = compiledReader(field.message);
if (field.delimitedEncoding) {
const fieldNo = field.number;
return (child, reader, ctx) => compiledChild.readGroup(child, reader, ctx, fieldNo);
}
return (child, reader, ctx) => compiledChild.read(child, reader, ctx, reader.uint32());
}
function compileListFieldReader(field) {
const localName = field.localName;
if (field.listKind == "message") {
const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
const readChild = compileChildReader(field);
return (message, reader, ctx) => {
const child = toMessage(undefined);
readChild(child, reader, ctx);
message[localName].push(toLocal(child));
};
}
const scalarType = field.listKind == "enum" ? descriptors_js_1.ScalarType.INT32 : field.scalar;
const longAsString = field.listKind == "scalar" ? field.longAsString : false;
const readScalar = compileScalarReader(scalarType, field.utf8Validation, longAsString);
const packedPossible = scalarType != descriptors_js_1.ScalarType.STRING && scalarType != descriptors_js_1.ScalarType.BYTES;
return (message, reader, ctx, wireType) => {
const items = message[localName];
if (wireType == binary_encoding_js_1.WireType.LengthDelimited && packedPossible) {
const end = reader.uint32() + reader.pos;
while (reader.pos < end) {
items.push(readScalar(reader));
}
}
else {
items.push(readScalar(reader));
}
};
}
function compileMapFieldReader(field) {
const localName = field.localName;
const readKey = compileScalarReader(field.mapKey, field.utf8Validation, false);
const keyZero = (0, scalar_js_1.scalarZeroValue)(field.mapKey, false);
let readValue;
let valueDefault;
switch (field.mapKind) {
case "scalar": {
const scalar = field.scalar;
const readScalar = compileScalarReader(scalar, field.utf8Validation, false);
readValue = (reader) => readScalar(reader);
// Bytes zero values are created per entry, so that entries do not share
// one instance.
if (scalar == descriptors_js_1.ScalarType.BYTES) {
valueDefault = () => new Uint8Array(0);
}
else {
const zero = (0, scalar_js_1.scalarZeroValue)(scalar, false);
valueDefault = () => zero;
}
break;
}
case "enum": {
const zero = field.enum.values[0].number;
readValue = (reader) => reader.int32();
valueDefault = () => zero;
break;
}
case "message": {
const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
const readChild = compiledReader(field.message).read;
// A repeated value field within one entry merges into the previous
// value, like any other singular message field.
readValue = (reader, ctx, existing) => {
const child = toMessage(existing);
readChild(child, reader, ctx, reader.uint32());
return toLocal(child);
};
valueDefault = () => toLocal(toMessage(undefined));
break;
}
}
return (message, reader, ctx) => {
const record = message[localName];
let key;
let val;
// Read the length of the map entry, which is a varint.
const len = reader.uint32();
// Calculate end AFTER advancing reader.pos (above), so that reader.pos is
// at the start of the map entry.
const end = reader.pos + len;
while (reader.pos < end) {
// Map entries have the key in field 1, and the value in field 2.
const [fieldNo] = reader.tag();
switch (fieldNo) {
case 1:
key = readKey(reader);
break;
case 2:
val = readValue(reader, ctx, val);
break;
}
}
if (key === undefined) {
key = keyZero;
}
if (val === undefined) {
val = valueDefault();
}
// Map keys may be booleans, numbers, or bigints. Object keys are strings, so
// they are converted implicitly. setOwn() is needed because a key can be
// "__proto__".
(0, unsafe_js_1.setOwn)(record, key, val);
};
}
/**
* Returns a reader for a scalar value. For 64-bit integers, BinaryReader
* already returns the local representation (bigint or string), so, unlike in
* the reflection layer, no validation is needed here.
*/
function compileScalarReader(type, utf8Validation, longAsString) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return (reader) => reader.string(utf8Validation);
case descriptors_js_1.ScalarType.BOOL:
return (reader) => reader.bool();
case descriptors_js_1.ScalarType.DOUBLE:
return (reader) => reader.double();
case descriptors_js_1.ScalarType.FLOAT:
return (reader) => reader.float();
case descriptors_js_1.ScalarType.INT32:
return (reader) => reader.int32();
case descriptors_js_1.ScalarType.INT64:
if (longAsString) {
return (reader) => String(reader.int64());
}
return (reader) => reader.int64();
case descriptors_js_1.ScalarType.UINT64:
if (longAsString) {
return (reader) => String(reader.uint64());
}
return (reader) => reader.uint64();
case descriptors_js_1.ScalarType.FIXED64:
if (longAsString) {
return (reader) => String(reader.fixed64());
}
return (reader) => reader.fixed64();
case descriptors_js_1.ScalarType.BYTES:
return (reader) => reader.bytes();
case descriptors_js_1.ScalarType.FIXED32:
return (reader) => reader.fixed32();
case descriptors_js_1.ScalarType.SFIXED32:
return (reader) => reader.sfixed32();
case descriptors_js_1.ScalarType.SFIXED64:
if (longAsString) {
return (reader) => String(reader.sfixed64());
}
return (reader) => reader.sfixed64();
case descriptors_js_1.ScalarType.SINT64:
if (longAsString) {
return (reader) => String(reader.sint64());
}
return (reader) => reader.sint64();
case descriptors_js_1.ScalarType.UINT32:
return (reader) => reader.uint32();
case descriptors_js_1.ScalarType.SINT32:
return (reader) => reader.sint32();
}
}

View file

@ -0,0 +1,78 @@
import { type DescEnum, type DescMessage } from "./descriptors.js";
import type { JsonValue } from "./json-value.js";
import type { Registry } from "./registry.js";
import type { EnumJsonType, EnumShape, MessageShape } from "./types.js";
/**
* Options for parsing JSON data.
*/
export interface JsonReadOptions {
/**
* Ignore unknown fields: Proto3 JSON parser should reject unknown fields
* by default. This option ignores unknown fields in parsing, as well as
* unrecognized enum string representations.
*/
ignoreUnknownFields: boolean;
/**
* This option is required to read `google.protobuf.Any` and extensions
* from JSON format.
*/
registry?: Registry | undefined;
/**
* The maximum depth of nested messages to parse. If a message nests deeper
* than this limit, parsing fails with an error instead of exhausting the
* call stack. Defaults to 100.
*/
recursionLimit: number;
}
/**
* Parse a message from a JSON string.
*
* Duplicate keys are rejected.
*/
export declare function fromJsonString<Desc extends DescMessage>(schema: Desc, json: string, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON string, merging fields into the target.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*
* Duplicate keys in the JSON are rejected, as in `fromJsonString`.
*/
export declare function mergeFromJsonString<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, json: string, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON value.
*
* Duplicate keys are rejected, but a value parsed by JSON.parse has already
* dropped duplicates (the last one wins). Use `fromJsonString` for strict
* duplicate-key checking.
*/
export declare function fromJson<Desc extends DescMessage>(schema: Desc, json: JsonValue, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parse a message from a JSON value, merging fields into the target.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*
* Duplicate keys are rejected as in `fromJson`; use `mergeFromJsonString`
* for strict checking.
*/
export declare function mergeFromJson<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, json: JsonValue, options?: Partial<JsonReadOptions>): MessageShape<Desc>;
/**
* Parses an enum value from JSON.
*/
export declare function enumFromJson<Desc extends DescEnum>(descEnum: Desc, json: EnumJsonType<Desc>): EnumShape<Desc>;
/**
* Is the given value a JSON enum value?
*
* For an enum value with a custom JSON name set with the option
* `(pb.enumvalue.json).string`, this function only returns true for the
* custom name, while fromJson() and enumFromJson() also accept the Protobuf
* name.
*/
export declare function isEnumJson<Desc extends DescEnum>(descEnum: Desc, value: unknown): value is EnumJsonType<Desc>;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,19 @@
export * from "./types.js";
export * from "./is-message.js";
export * from "./create.js";
export * from "./clone.js";
export * from "./descriptors.js";
export * from "./equals.js";
export * from "./fields.js";
export * from "./registry.js";
export type { JsonValue, JsonObject } from "./json-value.js";
export { toBinary } from "./to-binary.js";
export type { BinaryWriteOptions } from "./to-binary.js";
export { fromBinary, mergeFromBinary } from "./from-binary.js";
export type { BinaryReadOptions } from "./from-binary.js";
export * from "./to-json.js";
export * from "./from-json.js";
export * from "./merge.js";
export { hasExtension, getExtension, setExtension, clearExtension, hasOption, getOption, } from "./extensions.js";
export * from "./proto-int64.js";
export * from "./unknown-enum.js";

View file

@ -0,0 +1,55 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOption = exports.hasOption = exports.clearExtension = exports.setExtension = exports.getExtension = exports.hasExtension = exports.mergeFromBinary = exports.fromBinary = exports.toBinary = void 0;
__exportStar(require("./types.js"), exports);
__exportStar(require("./is-message.js"), exports);
__exportStar(require("./create.js"), exports);
__exportStar(require("./clone.js"), exports);
__exportStar(require("./descriptors.js"), exports);
__exportStar(require("./equals.js"), exports);
__exportStar(require("./fields.js"), exports);
__exportStar(require("./registry.js"), exports);
var to_binary_js_1 = require("./to-binary.js");
Object.defineProperty(exports, "toBinary", { enumerable: true, get: function () { return to_binary_js_1.toBinary; } });
var from_binary_js_1 = require("./from-binary.js");
Object.defineProperty(exports, "fromBinary", { enumerable: true, get: function () { return from_binary_js_1.fromBinary; } });
Object.defineProperty(exports, "mergeFromBinary", { enumerable: true, get: function () { return from_binary_js_1.mergeFromBinary; } });
__exportStar(require("./to-json.js"), exports);
__exportStar(require("./from-json.js"), exports);
__exportStar(require("./merge.js"), exports);
var extensions_js_1 = require("./extensions.js");
Object.defineProperty(exports, "hasExtension", { enumerable: true, get: function () { return extensions_js_1.hasExtension; } });
Object.defineProperty(exports, "getExtension", { enumerable: true, get: function () { return extensions_js_1.getExtension; } });
Object.defineProperty(exports, "setExtension", { enumerable: true, get: function () { return extensions_js_1.setExtension; } });
Object.defineProperty(exports, "clearExtension", { enumerable: true, get: function () { return extensions_js_1.clearExtension; } });
Object.defineProperty(exports, "hasOption", { enumerable: true, get: function () { return extensions_js_1.hasOption; } });
Object.defineProperty(exports, "getOption", { enumerable: true, get: function () { return extensions_js_1.getOption; } });
__exportStar(require("./proto-int64.js"), exports);
__exportStar(require("./unknown-enum.js"), exports);

View file

@ -0,0 +1,7 @@
import type { MessageShape } from "./types.js";
import type { DescMessage } from "./descriptors.js";
/**
* Determine whether the given `arg` is a message.
* If `desc` is set, determine whether `arg` is this specific message.
*/
export declare function isMessage<Desc extends DescMessage>(arg: unknown, schema?: Desc): arg is MessageShape<Desc>;

View file

@ -0,0 +1,33 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isMessage = isMessage;
/**
* Determine whether the given `arg` is a message.
* If `desc` is set, determine whether `arg` is this specific message.
*/
function isMessage(arg, schema) {
const isMessage = arg !== null &&
typeof arg == "object" &&
"$typeName" in arg &&
typeof arg.$typeName == "string";
if (!isMessage) {
return false;
}
if (schema === undefined) {
return true;
}
return schema.typeName === arg.$typeName;
}

View file

@ -0,0 +1,16 @@
/**
* Represents any possible JSON value:
* - number
* - string
* - boolean
* - null
* - object (with any JSON value as property)
* - array (with any JSON value as element)
*/
export type JsonValue = number | string | boolean | null | JsonObject | JsonValue[];
/**
* Represents a JSON object.
*/
export type JsonObject = {
[k: string]: JsonValue;
};

View file

@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });

View file

@ -0,0 +1,13 @@
import type { MessageShape } from "./types.js";
import type { DescMessage } from "./descriptors.js";
/**
* Merge message `source` into message `target`, following Protobuf semantics.
*
* This is the same as serializing the source message, then deserializing it
* into the target message via `mergeFromBinary()`, with one difference:
* While serialization will create a copy of all values, `merge()` will copy
* the reference for `bytes` and messages.
*
* Also see https://protobuf.com/docs/language-spec#merging-protobuf-messages
*/
export declare function merge<Desc extends DescMessage>(schema: Desc, target: MessageShape<Desc>, source: MessageShape<Desc>): void;

View file

@ -0,0 +1,70 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.merge = merge;
const reflect_js_1 = require("./reflect/reflect.js");
/**
* Merge message `source` into message `target`, following Protobuf semantics.
*
* This is the same as serializing the source message, then deserializing it
* into the target message via `mergeFromBinary()`, with one difference:
* While serialization will create a copy of all values, `merge()` will copy
* the reference for `bytes` and messages.
*
* Also see https://protobuf.com/docs/language-spec#merging-protobuf-messages
*/
function merge(schema, target, source) {
reflectMerge((0, reflect_js_1.reflect)(schema, target), (0, reflect_js_1.reflect)(schema, source));
}
function reflectMerge(target, source) {
var _a;
var _b;
const sourceUnknown = source.message.$unknown;
if (sourceUnknown !== undefined && sourceUnknown.length > 0) {
(_a = (_b = target.message).$unknown) !== null && _a !== void 0 ? _a : (_b.$unknown = []);
target.message.$unknown.push(...sourceUnknown);
}
for (const f of target.fields) {
if (!source.isSet(f)) {
continue;
}
switch (f.fieldKind) {
case "scalar":
case "enum":
target.set(f, source.get(f));
break;
case "message":
if (target.isSet(f)) {
reflectMerge(target.get(f), source.get(f));
}
else {
target.set(f, source.get(f));
}
break;
case "list":
const list = target.get(f);
for (const e of source.get(f)) {
list.add(e);
}
break;
case "map":
const map = target.get(f);
for (const [k, v] of source.get(f)) {
map.set(k, v);
}
break;
}
}
}

View file

@ -0,0 +1,4 @@
{
"type": "commonjs",
"sideEffects": false
}

View file

@ -0,0 +1,98 @@
/**
* Int64Support for the current environment.
*/
export declare const protoInt64: Int64Support;
/**
* We use the `bigint` primitive to represent 64-bit integral types. If bigint
* is unavailable, we fall back to a string representation, which means that
* all values typed as `bigint` will actually be strings.
*
* If your code is intended to run in an environment where bigint may be
* unavailable, it must handle both the bigint and the string representation.
* For presenting values, this is straight-forward with implicit or explicit
* conversion to string:
*
* ```ts
* let el = document.createElement("span");
* el.innerText = message.int64Field; // assuming a protobuf int64 field
*
* console.log(`int64: ${message.int64Field}`);
*
* let str: string = message.int64Field.toString();
* ```
*
* If you need to manipulate 64-bit integral values and are sure the values
* can be safely represented as an IEEE-754 double precision number, you can
* convert to a JavaScript Number:
*
* ```ts
* console.log(message.int64Field.toString())
* let num = Number(message.int64Field);
* num = num + 1;
* message.int64Field = protoInt64.parse(num);
* ```
*
* If you need to manipulate 64-bit integral values that are outside the
* range of safe representation as a JavaScript Number, we recommend you
* use a third party library, for example the npm package "long":
*
* ```ts
* // convert the field value to a Long
* const bits = protoInt64.enc(message.int64Field);
* const longValue = Long.fromBits(bits.lo, bits.hi);
*
* // perform arithmetic
* const longResult = longValue.subtract(1);
*
* // set the result in the field
* message.int64Field = protoInt64.dec(longResult.low, longResult.high);
*
* // Assuming int64Field contains 9223372036854775807:
* console.log(message.int64Field); // 9223372036854775806
* ```
*/
interface Int64Support {
/**
* 0n if bigint is available, "0" if unavailable.
*/
readonly zero: bigint;
/**
* Is bigint available?
*/
readonly supported: boolean;
/**
* Parse a signed 64-bit integer.
* Returns a bigint if available, a string otherwise.
*/
parse(value: string | number | bigint): bigint;
/**
* Parse an unsigned 64-bit integer.
* Returns a bigint if available, a string otherwise.
*/
uParse(value: string | number | bigint): bigint;
/**
* Convert a signed 64-bit integral value to a two's complement.
*/
enc(value: string | number | bigint): {
lo: number;
hi: number;
};
/**
* Convert an unsigned 64-bit integral value to a two's complement.
*/
uEnc(value: string | number | bigint): {
lo: number;
hi: number;
};
/**
* Convert a two's complement to a signed 64-bit integral value.
* Returns a bigint if available, a string otherwise.
*/
dec(lo: number, hi: number): bigint;
/**
* Convert a two's complement to an unsigned 64-bit integral value.
* Returns a bigint if available, a string otherwise.
*/
uDec(lo: number, hi: number): bigint;
}
export {};

View file

@ -0,0 +1,131 @@
"use strict";
// Copyright 2021-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.protoInt64 = void 0;
const varint_js_1 = require("./wire/varint.js");
/**
* Int64Support for the current environment.
*/
exports.protoInt64 = makeInt64Support();
function makeInt64Support() {
const dv = new DataView(new ArrayBuffer(8));
// note that Safari 14 implements BigInt, but not the DataView methods
const ok = typeof BigInt === "function" &&
typeof dv.getBigInt64 === "function" &&
typeof dv.getBigUint64 === "function" &&
typeof dv.setBigInt64 === "function" &&
typeof dv.setBigUint64 === "function" &&
(!!globalThis.Deno ||
!!globalThis.Bun ||
typeof process != "object" ||
typeof process.env != "object" ||
process.env.BUF_BIGINT_DISABLE !== "1");
if (ok) {
const MIN = BigInt("-9223372036854775808");
const MAX = BigInt("9223372036854775807");
const UMIN = BigInt("0");
const UMAX = BigInt("18446744073709551615");
return {
zero: BigInt(0),
supported: true,
parse(value) {
const bi = typeof value == "bigint" ? value : BigInt(value);
if (bi > MAX || bi < MIN) {
throw new Error(`invalid int64: ${value}`);
}
return bi;
},
uParse(value) {
const bi = typeof value == "bigint" ? value : BigInt(value);
if (bi > UMAX || bi < UMIN) {
throw new Error(`invalid uint64: ${value}`);
}
return bi;
},
enc(value) {
dv.setBigInt64(0, this.parse(value), true);
return {
lo: dv.getInt32(0, true),
hi: dv.getInt32(4, true),
};
},
uEnc(value) {
dv.setBigInt64(0, this.uParse(value), true);
return {
lo: dv.getInt32(0, true),
hi: dv.getInt32(4, true),
};
},
dec(lo, hi) {
dv.setInt32(0, lo, true);
dv.setInt32(4, hi, true);
return dv.getBigInt64(0, true);
},
uDec(lo, hi) {
dv.setInt32(0, lo, true);
dv.setInt32(4, hi, true);
return dv.getBigUint64(0, true);
},
};
}
return {
zero: "0",
supported: false,
parse(value) {
if (typeof value != "string") {
value = value.toString();
}
assertInt64String(value);
return value;
},
uParse(value) {
if (typeof value != "string") {
value = value.toString();
}
assertUInt64String(value);
return value;
},
enc(value) {
if (typeof value != "string") {
value = value.toString();
}
assertInt64String(value);
return (0, varint_js_1.int64FromString)(value);
},
uEnc(value) {
if (typeof value != "string") {
value = value.toString();
}
assertUInt64String(value);
return (0, varint_js_1.int64FromString)(value);
},
dec(lo, hi) {
return (0, varint_js_1.int64ToString)(lo, hi);
},
uDec(lo, hi) {
return (0, varint_js_1.uInt64ToString)(lo, hi);
},
};
}
function assertInt64String(value) {
if (!/^-?[0-9]+$/.test(value)) {
throw new Error("invalid int64: " + value);
}
}
function assertUInt64String(value) {
if (!/^[0-9]+$/.test(value)) {
throw new Error("invalid uint64: " + value);
}
}

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