Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

protoscript

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

protoscript - npm Package Compare versions

Comparing version 0.0.11 to 0.0.12

runtime/well-known-types/any.pb.d.ts

189

cli/core.js

@@ -1,10 +0,1 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { spawnSync } from "child_process";

@@ -41,49 +32,48 @@ import { existsSync, mkdirSync } from "fs";

}
function getConfig() {
return __awaiter(this, void 0, void 0, function* () {
const projectRoot = process.cwd();
const defaultConfig = {
root: projectRoot,
exclude: [],
dest: ".",
language: existsSync(join(projectRoot, "tsconfig.json"))
? "typescript"
: "javascript",
json: {},
typescript: {},
};
const configFilePath = getConfigFilePath();
let userConfig = {};
if (configFilePath) {
logger.info(`Using configuration file at '${configFilePath}'.`);
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
userConfig = (yield import(configFilePath)).default;
}
catch (e) {
logger.error(`Failed to parse configuration file.`);
console.log(e);
process.exit(1);
}
const unknownKeys = Object.keys(userConfig).filter((key) => !(key in defaultConfig));
if (unknownKeys.length) {
logger.warn(`Found unknown configuration options: ${unknownKeys
.map((k) => `'${k}'`)
.join(", ")}.`);
}
async function getConfig() {
const projectRoot = process.cwd();
const defaultConfig = {
root: projectRoot,
exclude: [],
dest: ".",
language: existsSync(join(projectRoot, "tsconfig.json"))
? "typescript"
: "javascript",
json: {},
typescript: {},
};
const configFilePath = getConfigFilePath();
let userConfig = {};
if (configFilePath) {
logger.info(`Using configuration file at '${configFilePath}'.`);
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
userConfig = (await import(configFilePath)).default;
}
return Object.assign(Object.assign({}, defaultConfig), userConfig);
});
catch (e) {
logger.error(`Failed to parse configuration file.`);
console.log(e);
process.exit(1);
}
const unknownKeys = Object.keys(userConfig).filter((key) => !(key in defaultConfig));
if (unknownKeys.length) {
logger.warn(`Found unknown configuration options: ${unknownKeys
.map((k) => `'${k}'`)
.join(", ")}.`);
}
}
return {
...defaultConfig,
...userConfig,
};
}
export function main(opts) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
initLogger((_b = (_a = opts.logger) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : "ProtoScript");
const config = yield getConfig();
const excludes = config.exclude.map((pattern) => RegExp(pattern));
const protos = findFiles(config.root, ".proto")
.map((filepath) => relative(config.root, filepath))
.filter((file) => !excludes.some((exclude) => exclude.exec(file)));
if (!commandIsInPath("protoc")) {
logger.error(`Could not find the protobuf compiler. Please make sure 'protoc' is installed and in your '$PATH'.
export async function main(opts) {
initLogger(opts.logger?.name ?? "ProtoScript");
const config = await getConfig();
const excludes = config.exclude.map((pattern) => RegExp(pattern));
const protos = findFiles(config.root, ".proto")
.map((filepath) => relative(config.root, filepath))
.filter((file) => !excludes.some((exclude) => exclude.exec(file)));
if (!commandIsInPath("protoc")) {
logger.error(`Could not find the protobuf compiler. Please make sure 'protoc' is installed and in your '$PATH'.

@@ -102,18 +92,18 @@ MacOS:

`);
process.exit(1);
process.exit(1);
}
if (protos.length === 0) {
logger.info("No '.proto' files found.");
process.exit(0);
}
try {
const destination = config.dest === "." ? "." : resolve(config.dest);
if (!existsSync(destination)) {
logger.info(`Created destination folder '${destination}'.`);
mkdirSync(destination, { recursive: true });
}
if (protos.length === 0) {
logger.info("No '.proto' files found.");
process.exit(0);
}
try {
const destination = config.dest === "." ? "." : resolve(config.dest);
if (!existsSync(destination)) {
logger.info(`Created destination folder '${destination}'.`);
mkdirSync(destination, { recursive: true });
}
process.chdir(config.root);
const protoExt = config.language === "typescript" ? "pb.ts" : "pb.js";
const protosBeforeCompile = Object.fromEntries(findFiles(destination, protoExt).map((file) => [file, checksum(file)]));
const protoc = spawnSync(`\
process.chdir(config.root);
const protoExt = config.language === "typescript" ? "pb.ts" : "pb.js";
const protosBeforeCompile = Object.fromEntries(findFiles(destination, protoExt).map((file) => [file, checksum(file)]));
const protoc = spawnSync(`\
protoc \

@@ -124,39 +114,38 @@ --plugin=protoc-gen-protoscript=${opts.compiler.path} \

${config.json.emitFieldsWithDefaultValues
? "--protoscript_opt=json=emitFieldsWithDefaultValues"
: ""} \
? "--protoscript_opt=json=emitFieldsWithDefaultValues"
: ""} \
${config.json.useProtoFieldName
? "--protoscript_opt=json=useProtoFieldName"
: ""} \
? "--protoscript_opt=json=useProtoFieldName"
: ""} \
${config.typescript.emitDeclarationOnly
? "--protoscript_opt=typescript=emitDeclarationOnly"
: ""} \
? "--protoscript_opt=typescript=emitDeclarationOnly"
: ""} \
${protos.join(" ")}
`, { shell: true, encoding: "utf8" });
if (protoc.stderr) {
onCliError(protoc.stderr, (_c = protoc.status) !== null && _c !== void 0 ? _c : 1);
}
const protosAfterCompile = findFiles(destination, protoExt).map((file) => [
file,
checksum(file),
]);
const created = protosAfterCompile.filter((file) => !protosBeforeCompile[file[0]]);
const updated = protosAfterCompile.filter((file) => protosBeforeCompile[file[0]] && protosBeforeCompile[file[0]] !== file[1]);
const unchanged = protosAfterCompile.filter((file) => protosBeforeCompile[file[0]] === file[1]);
logger.info("\n");
if (created.length > 0) {
console.info(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Created:\n${created.map((f) => ` - ${f[0]}`).join("\n")}\n`);
}
if (updated.length > 0) {
console.info(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Updated:\n${updated.map((f) => ` - ${f[0]}`).join("\n")}\n`);
}
console.info(`${created.length} ${pluralize("file", created.length)} created, ${updated.length} ${pluralize("file", updated.length)} updated, ${unchanged.length} ${pluralize("file", unchanged.length)} unchanged. ${protos.length} ${pluralize("file", protos.length)} found.`);
if (protoc.stderr) {
onCliError(protoc.stderr, protoc.status ?? 1);
}
catch (error) {
onCliError(error, 1);
const protosAfterCompile = findFiles(destination, protoExt).map((file) => [
file,
checksum(file),
]);
const created = protosAfterCompile.filter((file) => !protosBeforeCompile[file[0]]);
const updated = protosAfterCompile.filter((file) => protosBeforeCompile[file[0]] && protosBeforeCompile[file[0]] !== file[1]);
const unchanged = protosAfterCompile.filter((file) => protosBeforeCompile[file[0]] === file[1]);
logger.info("\n");
if (created.length > 0) {
console.info(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Created:\n${created.map((f) => ` - ${f[0]}`).join("\n")}\n`);
}
});
if (updated.length > 0) {
console.info(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Updated:\n${updated.map((f) => ` - ${f[0]}`).join("\n")}\n`);
}
console.info(`${created.length} ${pluralize("file", created.length)} created, ${updated.length} ${pluralize("file", updated.length)} updated, ${unchanged.length} ${pluralize("file", unchanged.length)} unchanged. ${protos.length} ${pluralize("file", protos.length)} found.`);
}
catch (error) {
onCliError(error, 1);
}
}

@@ -12,3 +12,3 @@ import { readdirSync, readFileSync, statSync } from "fs";

}
catch (_a) {
catch {
return false;

@@ -15,0 +15,0 @@ }

@@ -9,5 +9,4 @@ import { processTypes } from "../utils.js";

types.forEach((node) => {
var _a;
const name = node.content.name;
if ((_a = node.content.comments) === null || _a === void 0 ? void 0 : _a.leading) {
if (node.content.comments?.leading) {
result += printComments(node.content.comments.leading);

@@ -23,3 +22,3 @@ }

node.content.fields.forEach(({ name: fieldName, tsType, repeated, optional, comments, map }) => {
if (comments === null || comments === void 0 ? void 0 : comments.leading) {
if (comments?.leading) {
result += printComments(comments.leading);

@@ -280,3 +279,3 @@ }

node.content.values.forEach(({ name, comments }) => {
if (comments === null || comments === void 0 ? void 0 : comments.leading) {
if (comments?.leading) {
result += printComments(comments.leading);

@@ -543,3 +542,3 @@ }

node.content.values.forEach(({ name, comments }) => {
if (comments === null || comments === void 0 ? void 0 : comments.leading) {
if (comments?.leading) {
result += printComments(comments.leading);

@@ -640,3 +639,3 @@ }

};
IMPORT_TRACKER = Object.assign({}, DEFAULT_IMPORT_TRACKER);
IMPORT_TRACKER = { ...DEFAULT_IMPORT_TRACKER };
const ast = processTypes(fileDescriptorProto, identifierTable, config.isTS);

@@ -649,4 +648,4 @@ const { imports, types } = ast;

const plugs = plugins.map((plugin) => plugin({ ast, config }));
const pluginImports = plugs.map((p) => p === null || p === void 0 ? void 0 : p.imports).filter(Boolean);
const pluginServices = plugs.map((p) => p === null || p === void 0 ? void 0 : p.services).filter(Boolean);
const pluginImports = plugs.map((p) => p?.imports).filter(Boolean);
const pluginServices = plugs.map((p) => p?.services).filter(Boolean);
const hasTypes = types.length > 0;

@@ -653,0 +652,0 @@ const hasSerializer = !config.typescript.emitDeclarationOnly &&

import PluginPb from "google-protobuf/google/protobuf/compiler/plugin_pb.js";
import { generate } from "./autogenerate/index.js";
import { getProtobufTSFileName, buildIdentifierTable, getProtobufJSFileName, } from "./utils.js";
import { getProtobufTSFileName, buildIdentifierTable, getProtobufJSFileName, KNOWN_TYPES, } from "./utils.js";
import { format } from "prettier";

@@ -8,5 +8,4 @@ import { deserializeConfig } from "../cli/utils.js";

export function compile(input, plugins = []) {
var _a;
const request = CodeGeneratorRequest.deserializeBinary(input);
const options = deserializeConfig((_a = request.getParameter()) !== null && _a !== void 0 ? _a : "");
const options = deserializeConfig(request.getParameter() ?? "");
const isTypescript = options.language === "typescript";

@@ -27,2 +26,5 @@ const response = new CodeGeneratorResponse();

}
if (!process.env.GENERATE_KNOWN_TYPES && KNOWN_TYPES.includes(name)) {
return;
}
const protobufTs = generate(fileDescriptorProto, identifierTable, options, plugins);

@@ -29,0 +31,0 @@ writeFile(isTypescript ? getProtobufTSFileName(name) : getProtobufJSFileName(name), protobufTs);

@@ -20,2 +20,3 @@ import type { CodeGeneratorRequest } from "google-protobuf/google/protobuf/compiler/plugin_pb.js";

export declare function getProtobufJSFileName(protoFileName: string): string;
export declare const KNOWN_TYPES: string[];
/**

@@ -22,0 +23,0 @@ * [namespacedIdentifier, file, package, publicImport]

@@ -31,3 +31,2 @@ import { dirname, relative } from "path";

export function getDescriptor(field, identifierTable, fileDescriptorProto) {
var _a, _b, _c, _d, _e, _f;
const repeated = field.getLabel() === FieldDescriptorProto.Label.LABEL_REPEATED;

@@ -113,3 +112,3 @@ const optional = field.hasProto3Optional() || field.hasOneofIndex();

case FieldDescriptorProto.Type.TYPE_ENUM: {
const _type = (_a = field.getTypeName()) !== null && _a !== void 0 ? _a : "";
const _type = field.getTypeName() ?? "";
const name = removePackagePrefix(_type, identifierTable, fileDescriptorProto);

@@ -152,3 +151,3 @@ return {

case FieldDescriptorProto.Type.TYPE_GROUP: {
const name = (_b = field.getName()) !== null && _b !== void 0 ? _b : "";
const name = field.getName() ?? "";
console.error(`Groups are not supported. Found group ${name}`);

@@ -158,7 +157,8 @@ return undefined;

case FieldDescriptorProto.Type.TYPE_MESSAGE: {
const _type = (_c = field.getTypeName()) !== null && _c !== void 0 ? _c : "";
const _type = field.getTypeName() ?? "";
const name = removePackagePrefix(_type, identifierTable, fileDescriptorProto);
/* eslint-disable */
const isMap = (_f = (_e = ((_d = identifierTable.find(({ namespacedIdentifier }) => _type === namespacedIdentifier)) === null || _d === void 0 ? void 0 : _d.descriptorProto)
.getOptions()) === null || _e === void 0 ? void 0 : _e.getMapEntry()) !== null && _f !== void 0 ? _f : false;
const isMap = (identifierTable.find(({ namespacedIdentifier }) => _type === namespacedIdentifier)?.descriptorProto)
.getOptions()
?.getMapEntry() ?? false;
/* eslint-enable */

@@ -293,2 +293,15 @@ if (isMap) {

}
export const KNOWN_TYPES = [
"google/protobuf/any.proto",
"google/protobuf/api.proto",
"google/protobuf/descriptor.proto",
"google/protobuf/duration.proto",
"google/protobuf/empty.proto",
"google/protobuf/field_mask.proto",
"google/protobuf/source_context.proto",
"google/protobuf/struct.proto",
"google/protobuf/timestamp.proto",
"google/protobuf/type.proto",
"google/protobuf/wrappers.proto",
];
function applyNamespace(namespacing, name, { removeLeadingPeriod } = {

@@ -310,3 +323,2 @@ removeLeadingPeriod: false,

request.getProtoFileList().forEach((fileDescriptorProto) => {
var _a;
const protoFilePath = fileDescriptorProto.getName();

@@ -316,3 +328,3 @@ if (!protoFilePath) {

}
const _package = (_a = fileDescriptorProto.getPackage()) !== null && _a !== void 0 ? _a : "";
const _package = fileDescriptorProto.getPackage() ?? "";
function addEntry(namespacing, name, descriptorProto) {

@@ -375,3 +387,3 @@ table.push({

.map((row) => {
const newRow = Object.assign({}, row);
const newRow = { ...row };
newRow.file = protoFilePath;

@@ -399,6 +411,5 @@ newRow.publicImport = row.file;

function getImportForIdentifier(identifier, identifiers, fileDescriptorProto, isTS) {
var _a, _b, _c;
const dep = getIdentifierEntryFromTable(identifier, identifiers, fileDescriptorProto);
const sourceFile = (_a = fileDescriptorProto.getName()) !== null && _a !== void 0 ? _a : "";
const dependencyImportPath = (_b = dep.publicImport) !== null && _b !== void 0 ? _b : dep.file;
const sourceFile = fileDescriptorProto.getName() ?? "";
const dependencyImportPath = dep.publicImport ?? dep.file;
const importPath = relative(dirname(sourceFile),

@@ -417,4 +428,7 @@ /*

: getProtobufJSFileName(dependencyImportPath));
const path = getImportPath(importPath);
const dependencyIdentifier = (_c = identifier.split(".").pop()) !== null && _c !== void 0 ? _c : "";
let path = getImportPath(importPath);
if (KNOWN_TYPES.includes(dependencyImportPath)) {
path = "protoscript";
}
const dependencyIdentifier = identifier.split(".").pop() ?? "";
return { identifier: dependencyIdentifier, path };

@@ -442,3 +456,2 @@ }

export function processTypes(fileDescriptorProto, identifierTable, isTS) {
var _a;
const typeFile = {

@@ -476,9 +489,6 @@ packageName: fileDescriptorProto.getPackage(),

}),
values: node.getValueList().map((value) => {
var _a, _b;
return ({
name: (_a = value.getName()) !== null && _a !== void 0 ? _a : "",
value: (_b = value.getNumber()) !== null && _b !== void 0 ? _b : 0,
});
}),
values: node.getValueList().map((value) => ({
name: value.getName() ?? "",
value: value.getNumber() ?? 0,
})),
};

@@ -488,3 +498,2 @@ return opts;

function getMessage(namespacing, node) {
var _a, _b;
let name = node.getName();

@@ -495,3 +504,3 @@ if (!name) {

}
const isMap = (_b = (_a = node.getOptions()) === null || _a === void 0 ? void 0 : _a.getMapEntry()) !== null && _b !== void 0 ? _b : false;
const isMap = node.getOptions()?.getMapEntry() ?? false;
name = isMap ? name.slice(0, name.lastIndexOf("Entry")) : name;

@@ -507,3 +516,2 @@ const opts = {

.map((value) => {
var _a, _b, _c, _d;
const descriptor = getDescriptor(value, identifierTable, fileDescriptorProto);

@@ -516,5 +524,11 @@ if (!descriptor) {

_type === FieldDescriptorProto.Type.TYPE_ENUM) {
processIdentifier((_a = value.getTypeName()) !== null && _a !== void 0 ? _a : "");
processIdentifier(value.getTypeName() ?? "");
}
return Object.assign({ name: camelCase((_b = value.getName()) !== null && _b !== void 0 ? _b : ""), protoName: (_c = value.getName()) !== null && _c !== void 0 ? _c : "", jsonName: value.getJsonName(), index: (_d = value.getNumber()) !== null && _d !== void 0 ? _d : 0 }, descriptor);
return {
name: camelCase(value.getName() ?? ""),
protoName: value.getName() ?? "",
jsonName: value.getJsonName(),
index: value.getNumber() ?? 0,
...descriptor,
};
})

@@ -576,22 +590,20 @@ .filter(isNotBlank),

});
typeFile.services = fileDescriptorProto.getServiceList().map((service) => {
var _a;
return ({
name: (_a = service.getName()) !== null && _a !== void 0 ? _a : "",
methods: service.getMethodList().map((method) => {
var _a, _b, _c, _d, _e;
processIdentifier((_a = method.getInputType()) !== null && _a !== void 0 ? _a : "");
processIdentifier((_b = method.getOutputType()) !== null && _b !== void 0 ? _b : "");
return {
name: (_c = method.getName()) !== null && _c !== void 0 ? _c : "",
input: removePackagePrefix((_d = method.getInputType()) !== null && _d !== void 0 ? _d : "", identifierTable, fileDescriptorProto),
output: removePackagePrefix((_e = method.getOutputType()) !== null && _e !== void 0 ? _e : "", identifierTable, fileDescriptorProto),
};
}),
});
});
typeFile.services = fileDescriptorProto.getServiceList().map((service) => ({
name: service.getName() ?? "",
methods: service.getMethodList().map((method) => {
processIdentifier(method.getInputType() ?? "");
processIdentifier(method.getOutputType() ?? "");
return {
name: method.getName() ?? "",
input: removePackagePrefix(method.getInputType() ?? "", identifierTable, fileDescriptorProto),
output: removePackagePrefix(method.getOutputType() ?? "", identifierTable, fileDescriptorProto),
};
}),
}));
// add comments
const comments = (_a = fileDescriptorProto
.getSourceCodeInfo()) === null || _a === void 0 ? void 0 : _a.getLocationList().filter((x) => x.hasLeadingComments() || x.hasTrailingComments());
comments === null || comments === void 0 ? void 0 : comments.forEach((comment) => {
const comments = fileDescriptorProto
.getSourceCodeInfo()
?.getLocationList()
.filter((x) => x.hasLeadingComments() || x.hasTrailingComments());
comments?.forEach((comment) => {
const content = {

@@ -598,0 +610,0 @@ leading: comment.getLeadingComments(),

export { BinaryReader } from "./runtime/reader.js";
export { BinaryWriter } from "./runtime/writer.js";
export { decodeBase64Bytes, encodeBase64Bytes } from "./runtime/json.js";
export * from "./runtime/well-known-types/index.js";
export declare type ByteSource = ArrayBuffer | Uint8Array | number[] | string;
export type { UserConfig as Config } from "./cli/core.js";
export { BinaryReader } from "./runtime/reader.js";
export { BinaryWriter } from "./runtime/writer.js";
export { decodeBase64Bytes, encodeBase64Bytes } from "./runtime/json.js";
export * from "./runtime/well-known-types/index.js";
{
"name": "protoscript",
"version": "0.0.11",
"version": "0.0.12",
"description": "A Protobuf runtime and code generation tool for JavaScript and TypeScript",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -59,4 +59,3 @@ /* eslint-disable @typescript-eslint/no-unsafe-argument */

endDelimited_(bookmark) {
var _a;
const oldLength = (_a = bookmark.pop()) !== null && _a !== void 0 ? _a : 0;
const oldLength = bookmark.pop() ?? 0;
let messageLength = this.totalLength_ + this.encoder_.length() - oldLength;

@@ -63,0 +62,0 @@ assert(messageLength >= 0);

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc