Socket
Socket
Sign inDemoInstall

@mongosh/async-rewriter2

Package Overview
Dependencies
Maintainers
11
Versions
80
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mongosh/async-rewriter2 - npm Package Compare versions

Comparing version 0.10.1 to 0.11.0

lib/error-codes.d.ts

18

lib/async-writer-babel.d.ts
import * as babel from '@babel/core';
import * as BabelTypes from '@babel/types';
declare type WrapState = {
movedStatements: babel.types.Statement[];
functionDeclarations: babel.types.FunctionDeclaration[];
hasFinishedMoving: boolean;
variables: string[];
addedCompletionRecords: boolean;
completionRecordId: babel.types.Identifier;
};
export declare const wrapAsFunctionPlugin: ({ types: t }: {
types: typeof BabelTypes;
}) => babel.PluginObj<WrapState>;
export declare const makeMaybeAsyncFunctionPlugin: ({ types: t }: {
types: typeof BabelTypes;
}) => babel.PluginObj<{
file: babel.types.File;
}>;
export default class AsyncWriter {

@@ -24,2 +7,1 @@ step(code: string, plugins: babel.PluginItem[]): string;

}
export {};

441

lib/async-writer-babel.js

@@ -25,423 +25,7 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.makeMaybeAsyncFunctionPlugin = exports.wrapAsFunctionPlugin = void 0;
const babel = __importStar(require("@babel/core"));
const runtime_support_nocov_1 = __importDefault(require("./runtime-support.nocov"));
exports.wrapAsFunctionPlugin = ({ types: t }) => {
function asNodeKey(v) { return v; }
const excludeFromCompletion = asNodeKey(Symbol('excludedFromCompletion'));
return {
pre() {
this.movedStatements = [];
this.functionDeclarations = [];
this.hasFinishedMoving = false;
this.addedCompletionRecords = false;
this.variables = [];
},
visitor: {
Statement(path) {
if (this.hasFinishedMoving)
return;
if (path.isDeclaration() && !path.getFunctionParent()) {
if (path.isVariableDeclaration()) {
if (path.parentPath.isProgram() || path.node.kind === 'var') {
const asAssignments = [];
for (const decl of path.node.declarations) {
this.variables.push(decl.id.name);
if (decl.init !== null) {
const expr = t.assignmentExpression('=', decl.id, decl.init);
if (path.node.kind !== 'var') {
Object.assign(expr, { [excludeFromCompletion]: true });
}
asAssignments.push(t.expressionStatement(expr));
}
}
if (path.parentPath.isProgram()) {
this.movedStatements.push(...asAssignments);
path.remove();
}
else {
path.replaceWithMultiple(asAssignments);
}
return;
}
}
else if (path.isFunctionDeclaration()) {
this.functionDeclarations.push(path.node);
if (path.node.id) {
path.replaceWith(t.expressionStatement(path.node.id));
}
else {
path.remove();
}
return;
}
else if (path.isClassDeclaration() && path.parentPath.isProgram()) {
this.variables.push(path.node.id.name);
this.movedStatements.push(t.expressionStatement(t.assignmentExpression('=', path.node.id, t.classExpression(path.node.id, path.node.superClass, path.node.body))));
path.replaceWith(t.expressionStatement(path.node.id));
return;
}
}
if (path.parentPath.isProgram()) {
this.movedStatements.push(path.node);
}
},
Program: {
enter(path) {
if (path.node.directives.length === 1 &&
path.node.directives[0].value.type === 'DirectiveLiteral') {
path.replaceWith(t.program([
t.expressionStatement(t.stringLiteral(path.node.directives[0].value.value))
]));
}
},
exit(path) {
if (this.hasFinishedMoving)
return;
this.hasFinishedMoving = true;
this.completionRecordId = path.scope.generateUidIdentifier('cr');
this.movedStatements.unshift(t.variableDeclaration('var', [t.variableDeclarator(this.completionRecordId)]));
path.replaceWith(t.program([
...this.variables.map(v => t.variableDeclaration('var', [t.variableDeclarator(t.identifier(v))])),
...this.functionDeclarations,
t.expressionStatement(t.callExpression(t.arrowFunctionExpression([], t.blockStatement(this.movedStatements)), []))
]));
}
},
BlockStatement: {
exit(path) {
if (!this.hasFinishedMoving)
return;
if (!path.parentPath.isArrowFunctionExpression())
return;
if (path.parentPath.getFunctionParent())
return;
if (this.addedCompletionRecords)
return;
this.addedCompletionRecords = true;
const records = path.getCompletionRecords();
for (const record of records) {
if (record.isExpressionWrapper() && !record.node.expression[excludeFromCompletion]) {
record.replaceWith(t.expressionStatement(t.assignmentExpression('=', this.completionRecordId, record.node.expression)));
}
}
path.replaceWith(t.blockStatement([
...path.node.body,
t.returnStatement(this.completionRecordId)
]));
}
}
}
};
};
exports.makeMaybeAsyncFunctionPlugin = ({ types: t }) => {
function asNodeKey(v) { return v; }
const isGeneratedInnerFunction = asNodeKey(Symbol('isGeneratedInnerFunction'));
const isGeneratedHelper = asNodeKey(Symbol('isGeneratedHelper'));
const isOriginalBody = asNodeKey(Symbol('isOriginalBody'));
const isAlwaysSyncFunction = asNodeKey(Symbol('isAlwaysSyncFunction'));
const identifierGroupKey = '@@mongosh.identifierGroup';
const symbolConstructor = babel.template.expression(`
Object.getOwnPropertySymbols(Array.prototype)[0].constructor
`)();
const syntheticPromiseSymbolTemplate = babel.template.statement(`
const SP_IDENTIFIER = SYMBOL_CONSTRUCTOR.for("@@mongosh.syntheticPromise");
`);
const markSyntheticPromiseTemplate = babel.template.statement(`
function MSP_IDENTIFIER(p) {
return Object.defineProperty(p, SP_IDENTIFIER, {
value: true
});
}
`);
const isSyntheticPromiseTemplate = babel.template.statement(`
function ISP_IDENTIFIER(p) {
return p && p[SP_IDENTIFIER];
}
`);
const assertNotSyntheticPromiseTemplate = babel.template.statement(`
function ANSP_IDENTIFIER(p, s) {
if (p && p[SP_IDENTIFIER]) {
throw new Error('Result of expression "' + s + '" cannot be used in this context');
}
return p;
}
`);
const asyncTryCatchWrapperTemplate = babel.template.expression(`
async () => {
try {
ORIGINAL_CODE;
} catch (err) {
if (FUNCTION_STATE_IDENTIFIER === "sync") {
SYNC_RETURN_VALUE_IDENTIFIER = err;
FUNCTION_STATE_IDENTIFIER = "threw";
} else throw err;
} finally {
if (FUNCTION_STATE_IDENTIFIER !== "threw") FUNCTION_STATE_IDENTIFIER = "returned";
}
}
`);
const wrapperFunctionTemplate = babel.template.statements(`
let FUNCTION_STATE_IDENTIFIER = "sync",
SYNC_RETURN_VALUE_IDENTIFIER,
EXPRESSION_HOLDER_IDENTIFIER;
const ASYNC_RETURN_VALUE_IDENTIFIER = (ASYNC_TRY_CATCH_WRAPPER)();
if (FUNCTION_STATE_IDENTIFIER === "returned")
return SYNC_RETURN_VALUE_IDENTIFIER;
else if (FUNCTION_STATE_IDENTIFIER === "threw")
throw SYNC_RETURN_VALUE_IDENTIFIER;
FUNCTION_STATE_IDENTIFIER = "async";
return MSP_IDENTIFIER(ASYNC_RETURN_VALUE_IDENTIFIER);
`);
const awaitSyntheticPromiseTemplate = babel.template.expression(`(
ORIGINAL_SOURCE,
EXPRESSION_HOLDER = NODE,
ISP_IDENTIFIER(EXPRESSION_HOLDER) ? await EXPRESSION_HOLDER : EXPRESSION_HOLDER
)`, {
allowAwaitOutsideFunction: true
});
const assertNotSyntheticExpressionTemplate = babel.template.expression(`
ANSP_IDENTIFIER(NODE, ORIGINAL_SOURCE)
`);
const rethrowTemplate = babel.template.statement(`
try {
ORIGINAL_CODE;
} catch (err) {
throw err;
}
`);
const demangleErrorTemplate = babel.template.statement(String.raw `
function DE_IDENTIFIER(err) {
if (Object.prototype.toString.call(err) === '[object Error]' &&
err.message.includes('\ufeff')) {
err.message = err.message.replace(/\(\s*"\ufeff(.+?)\ufeff"\s*,(?:[^\(]|\([^\)]*\))*\)/g, '$1');
}
return err;
}
`, { placeholderPattern: false, placeholderWhitelist: new Set(['DE_IDENTIFIER']) });
const returnValueWrapperTemplate = babel.template.expression(`(
SYNC_RETURN_VALUE_IDENTIFIER = NODE,
FUNCTION_STATE_IDENTIFIER === 'async' ? SYNC_RETURN_VALUE_IDENTIFIER : null
)`);
return {
pre(file) {
this.file = file;
},
visitor: {
BlockStatement(path) {
var _a, _b, _c, _d, _e, _f;
if (!path.parentPath.isFunction())
return;
if (path.parentPath.getData(identifierGroupKey))
return;
if (path.parentPath.node[isGeneratedInnerFunction])
return;
if (path.parentPath.node[isGeneratedHelper])
return;
const originalSource = path.parent.start !== undefined ?
this.file.code.slice(path.parent.start, path.parent.end) :
'function () { [unknown code] }';
const encodedOriginalSource = [...originalSource].map(char => char.charCodeAt(0).toString(16).padStart(4, '0')).join('');
const originalSourceNode = t.expressionStatement(t.stringLiteral(`<async_rewriter>${encodedOriginalSource}</>`));
const existingIdentifiers = (_a = path.findParent(path => !!path.getData(identifierGroupKey))) === null || _a === void 0 ? void 0 : _a.getData(identifierGroupKey);
const functionState = path.scope.generateUidIdentifier('fs');
const synchronousReturnValue = path.scope.generateUidIdentifier('srv');
const asynchronousReturnValue = path.scope.generateUidIdentifier('arv');
const expressionHolder = path.scope.generateUidIdentifier('ex');
const markSyntheticPromise = (_b = existingIdentifiers === null || existingIdentifiers === void 0 ? void 0 : existingIdentifiers.markSyntheticPromise) !== null && _b !== void 0 ? _b : path.scope.generateUidIdentifier('msp');
const isSyntheticPromise = (_c = existingIdentifiers === null || existingIdentifiers === void 0 ? void 0 : existingIdentifiers.isSyntheticPromise) !== null && _c !== void 0 ? _c : path.scope.generateUidIdentifier('isp');
const assertNotSyntheticPromise = (_d = existingIdentifiers === null || existingIdentifiers === void 0 ? void 0 : existingIdentifiers.assertNotSyntheticPromise) !== null && _d !== void 0 ? _d : path.scope.generateUidIdentifier('ansp');
const syntheticPromiseSymbol = (_e = existingIdentifiers === null || existingIdentifiers === void 0 ? void 0 : existingIdentifiers.syntheticPromiseSymbol) !== null && _e !== void 0 ? _e : path.scope.generateUidIdentifier('sp');
const demangleError = (_f = existingIdentifiers === null || existingIdentifiers === void 0 ? void 0 : existingIdentifiers.demangleError) !== null && _f !== void 0 ? _f : path.scope.generateUidIdentifier('de');
const identifiersGroup = {
functionState,
synchronousReturnValue,
asynchronousReturnValue,
expressionHolder,
markSyntheticPromise,
isSyntheticPromise,
assertNotSyntheticPromise,
syntheticPromiseSymbol,
demangleError
};
path.parentPath.setData(identifierGroupKey, identifiersGroup);
const commonHelpers = existingIdentifiers ? [] : [
Object.assign(syntheticPromiseSymbolTemplate({
SP_IDENTIFIER: syntheticPromiseSymbol,
SYMBOL_CONSTRUCTOR: symbolConstructor
}), { [isGeneratedHelper]: true }),
];
const promiseHelpers = existingIdentifiers ? [] : [
...commonHelpers,
Object.assign(markSyntheticPromiseTemplate({
MSP_IDENTIFIER: markSyntheticPromise,
SP_IDENTIFIER: syntheticPromiseSymbol
}), { [isGeneratedHelper]: true }),
Object.assign(isSyntheticPromiseTemplate({
ISP_IDENTIFIER: isSyntheticPromise,
SP_IDENTIFIER: syntheticPromiseSymbol
}), { [isGeneratedHelper]: true }),
Object.assign(demangleErrorTemplate({
DE_IDENTIFIER: demangleError
}), { [isGeneratedHelper]: true })
];
const syncFnHelpers = [
...commonHelpers,
Object.assign(assertNotSyntheticPromiseTemplate({
ANSP_IDENTIFIER: assertNotSyntheticPromise,
SP_IDENTIFIER: syntheticPromiseSymbol
}), { [isGeneratedHelper]: true })
];
if (path.parentPath.node.async) {
path.replaceWith(t.blockStatement([
originalSourceNode,
...promiseHelpers,
rethrowTemplate({
ORIGINAL_CODE: path.node.body
})
]));
return;
}
if (path.parentPath.node.generator ||
(path.parentPath.isClassMethod() &&
path.parentPath.node.key.type === 'Identifier' &&
path.parentPath.node.key.name === 'constructor')) {
Object.assign(path.parentPath.node, { [isAlwaysSyncFunction]: true });
path.replaceWith(t.blockStatement([
originalSourceNode,
...syncFnHelpers,
rethrowTemplate({
ORIGINAL_CODE: path.node.body
})
]));
return;
}
const asyncTryCatchWrapper = Object.assign(asyncTryCatchWrapperTemplate({
FUNCTION_STATE_IDENTIFIER: functionState,
SYNC_RETURN_VALUE_IDENTIFIER: synchronousReturnValue,
ORIGINAL_CODE: Object.assign(path.node, { [isOriginalBody]: true })
}), { [isGeneratedInnerFunction]: true });
const wrapperFunction = wrapperFunctionTemplate({
FUNCTION_STATE_IDENTIFIER: functionState,
SYNC_RETURN_VALUE_IDENTIFIER: synchronousReturnValue,
ASYNC_RETURN_VALUE_IDENTIFIER: asynchronousReturnValue,
EXPRESSION_HOLDER_IDENTIFIER: expressionHolder,
MSP_IDENTIFIER: markSyntheticPromise,
ASYNC_TRY_CATCH_WRAPPER: asyncTryCatchWrapper
});
path.replaceWith(t.blockStatement([
originalSourceNode,
...promiseHelpers,
...wrapperFunction
]));
},
Expression: {
enter(path) {
if (path.parentPath.isArrowFunctionExpression() && path.key === 'body') {
path.replaceWith(t.blockStatement([
t.returnStatement(path.node)
]));
}
},
exit(path) {
if (!path.getFunctionParent())
return;
if (!path.getFunctionParent().node.async &&
!path.getFunctionParent().node[isAlwaysSyncFunction])
return;
let identifierGroup;
if (path.getFunctionParent().node[isGeneratedInnerFunction]) {
if (!path.findParent(path => path.isFunction() || !!path.node[isOriginalBody]).node[isOriginalBody]) {
return;
}
identifierGroup = path.getFunctionParent().getFunctionParent().getData(identifierGroupKey);
if (path.parentPath.isReturnStatement() && !path.node[isGeneratedHelper]) {
path.replaceWith(Object.assign(returnValueWrapperTemplate({
SYNC_RETURN_VALUE_IDENTIFIER: identifierGroup.synchronousReturnValue,
FUNCTION_STATE_IDENTIFIER: identifierGroup.functionState,
NODE: path.node
}), { [isGeneratedHelper]: true }));
return;
}
}
else {
identifierGroup = path.getFunctionParent().getData(identifierGroupKey);
}
if (path.find(path => path.isFunction() || !!path.node[isGeneratedHelper]).node[isGeneratedHelper]) {
return;
}
if (path.parentPath.isCallExpression() &&
path.key === 'callee' &&
(path.isMemberExpression() || (path.isIdentifier() && path.node.name === 'eval'))) {
return;
}
if (path.parentPath.isAssignmentExpression() && path.key === 'left')
return;
if (path.parentPath.isUpdateExpression())
return;
if (path.isLiteral() ||
path.isArrayExpression() ||
path.isObjectExpression() ||
path.isFunctionExpression() ||
path.isArrowFunctionExpression() ||
path.isClassExpression() ||
path.isAssignmentExpression() ||
path.isBinaryExpression() ||
path.isConditionalExpression() ||
path.isLogicalExpression() ||
path.isSequenceExpression() ||
path.isParenthesizedExpression() ||
path.isUnaryExpression() ||
path.isSuper() ||
path.isAwaitExpression() ||
path.parentPath.isAwaitExpression()) {
return;
}
const { expressionHolder, isSyntheticPromise, assertNotSyntheticPromise } = identifierGroup;
const prettyOriginalString = limitStringLength(path.node.start !== undefined ?
this.file.code.slice(path.node.start, path.node.end) :
'<unknown>', 24);
if (!path.getFunctionParent().node.async) {
path.replaceWith(Object.assign(assertNotSyntheticExpressionTemplate({
ORIGINAL_SOURCE: t.stringLiteral(prettyOriginalString),
NODE: path.node,
ANSP_IDENTIFIER: assertNotSyntheticPromise
}), { [isGeneratedHelper]: true }));
return;
}
const originalSource = t.stringLiteral('\ufeff' + prettyOriginalString + '\ufeff');
path.replaceWith(Object.assign(awaitSyntheticPromiseTemplate({
ORIGINAL_SOURCE: originalSource,
EXPRESSION_HOLDER: expressionHolder,
ISP_IDENTIFIER: isSyntheticPromise,
NODE: path.node
}), { [isGeneratedHelper]: true }));
}
},
CatchClause: {
exit(path) {
var _a;
if (path.node[isGeneratedHelper] || !path.node.param || path.node.param.type !== 'Identifier')
return;
const existingIdentifiers = (_a = path.findParent(path => !!path.getData(identifierGroupKey))) === null || _a === void 0 ? void 0 : _a.getData(identifierGroupKey);
if (!existingIdentifiers)
return;
path.replaceWith(Object.assign(t.catchClause(path.node.param, t.blockStatement([
t.expressionStatement(t.assignmentExpression('=', path.node.param, t.callExpression(existingIdentifiers.demangleError, [path.node.param]))),
path.node.body
])), { [isGeneratedHelper]: true }));
}
}
}
};
};
function limitStringLength(input, maxLength) {
if (input.length <= maxLength)
return input;
return input.slice(0, (maxLength - 5) * 0.7) +
' ... ' +
input.slice(input.length - (maxLength - 5) * 0.3);
}
const wrap_as_iife_1 = __importDefault(require("./stages/wrap-as-iife"));
const transform_maybe_await_1 = __importDefault(require("./stages/transform-maybe-await"));
const error_codes_1 = require("./error-codes");
class AsyncWriter {

@@ -464,4 +48,9 @@ step(code, plugins) {

]);
code = this.step(code, [exports.wrapAsFunctionPlugin]);
code = this.step(code, [exports.makeMaybeAsyncFunctionPlugin]);
code = this.step(code, [wrap_as_iife_1.default]);
code = this.step(code, [
[
transform_maybe_await_1.default,
{ customErrorBuilder: babel.types.identifier('MongoshAsyncWriterError') }
]
]);
return code;

@@ -475,6 +64,14 @@ }

runtimeSupportCode() {
return this.process(runtime_support_nocov_1.default);
return this.process(`
class MongoshAsyncWriterError extends Error {
constructor(message, codeIdentifier) {
const code = (${JSON.stringify(error_codes_1.AsyncRewriterErrors)})[codeIdentifier];
super(\`[\${code}] \${message}\`);
this.code = code;
}
}
${runtime_support_nocov_1.default}`);
}
}
exports.default = AsyncWriter;
//# sourceMappingURL=async-writer-babel.js.map

@@ -259,2 +259,21 @@ 'use strict';

};
const origArraySort = Array.prototype.sort;
Array.prototype.sort = function (compareFn) {
return origArraySort.call(this, compareFn ? function (...args) {
return [...(function* () {
yield compareFn(...args);
})()][0];
} : undefined);
};
const origTypedArraySort = TypedArray.prototype.sort;
TypedArray.prototype.sort = function (compareFn) {
return origTypedArraySort.call(this, compareFn ? function (...args) {
return [...(function* () {
yield compareFn(...args);
})()][0];
} : undefined);
};
Array.prototype.flatMap = function (...args) {
return Array.prototype.map.call(this, ...args).flat();
};
TypedArray.prototype.reduce = Array.prototype.reduce;

@@ -261,0 +280,0 @@ TypedArray.prototype.reduceRight = Array.prototype.reduceRight;

{
"name": "@mongosh/async-rewriter2",
"version": "0.10.1",
"version": "0.11.0",
"description": "MongoDB Shell Async Rewriter Package",

@@ -40,3 +40,3 @@ "main": "./lib/index.js",

},
"gitHead": "dacbc9f140616f656058c26c1a0a6bc349721187"
"gitHead": "3f9e4337ee20219985800d99923a4903a21bfa5a"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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