Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(shell-api): add test and note about runtime independence MONGOSH-1975 #2312

Merged
merged 3 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/service-provider-core/src/textencoder-polyfill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ if (
typeof TextEncoder !== 'function'
) {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
Object.assign(Function('return this')(), textEncodingPolyfill());
const global =
(typeof globalThis === 'object' &&
globalThis?.Object === Object &&
globalThis) ||
Function('return this')();
Object.assign(global, textEncodingPolyfill());
}

// Basic encoder/decoder polyfill for java-shell environment (see above)
Expand Down
5 changes: 5 additions & 0 deletions packages/shell-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# @mongosh/shell-api

Provides the runtime-independent classes that make up the MongoDB Shell API,
such as `Database`, `Collection`, etc., and the global objects and APIs
available to shell users, such as `db`, `rs`, `sh`, `console`, `print()`, etc.
6 changes: 3 additions & 3 deletions packages/shell-api/src/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,11 +397,11 @@ interface Signatures {
// object instead of a global list, or even more radical changes
// such as removing the concept of signatures altogether.
const signaturesGlobalIdentifier = '@@@mdb.signatures@@@';
if (!(global as any)[signaturesGlobalIdentifier]) {
(global as any)[signaturesGlobalIdentifier] = {};
if (!(globalThis as any)[signaturesGlobalIdentifier]) {
(globalThis as any)[signaturesGlobalIdentifier] = {};
}

const signatures: Signatures = (global as any)[signaturesGlobalIdentifier];
const signatures: Signatures = (globalThis as any)[signaturesGlobalIdentifier];
signatures.Document = { type: 'Document', attributes: {} };
export { signatures };

Expand Down
89 changes: 89 additions & 0 deletions packages/shell-api/src/runtime-independence.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// This test verifies that shell-api only uses standard JS features.
import fsSync from 'fs';
import vm from 'vm';
import { createRequire } from 'module';
import { expect } from 'chai';
import sinon from 'ts-sinon';

describe('Runtime independence', function () {
it('Can run using exclusively JS standard features', async function () {
const entryPoint = require.resolve('../');

const context = vm.createContext(Object.create(null), {
codeGeneration: {
strings: false,
wasm: false,
},
});

// These are all used Node.js modules that are somewhat easily polyfill-able
// for other environments, but which we should still ideally remove in the
// long run (and definitely not add anything here).
// Guaranteed bonusly for anyone who removes a package from this list!
const allowedNodeBuiltins = ['crypto', 'util', 'events', 'path'];
// Our TextDecoder/TextEncoder polyfills require this, unfortunately.
context.Buffer = Buffer;
// lodash used by mongodb-redact used by @mongosh/history requires this Node.js-ism.
// Let's get rid of it: https://github.com/mongodb-js/devtools-shared/pull/497
addaleax marked this conversation as resolved.
Show resolved Hide resolved
vm.runInContext('globalThis.global = globalThis;', context);

// Small CJS implementation, without __dirname or __filename
const cache = Object.create(null);
const absolutePathRequire = (absolutePath: string) => {
absolutePath = fsSync.realpathSync(absolutePath);
if (cache[absolutePath]) return cache[absolutePath];
const module = (cache[absolutePath] = { exports: {} });
const localRequire = (specifier: string) => {
if (allowedNodeBuiltins.includes(specifier)) return require(specifier);
return absolutePathRequire(
createRequire(absolutePath).resolve(specifier)
).exports;
};
const source = fsSync.readFileSync(absolutePath, 'utf8');
const fn = vm.runInContext(
`(function(module, exports, require) {\n${source}\n})`,
context,
{
filename: `IN_CONTEXT:${absolutePath}`,
}
);
fn(module, module.exports, localRequire);
return module;
};

// service-provider-core injects a dummy polyfill for TextDecoder/TextEncoder
absolutePathRequire(require.resolve('@mongosh/service-provider-core'));
const shellApi =
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
absolutePathRequire(entryPoint).exports as typeof import('./');

// Verify that `shellApi` is generally usable.
const sp = { platform: 'CLI', close: sinon.spy() };
const evaluationListener = { onExit: sinon.spy() };
const instanceState = new shellApi.ShellInstanceState(sp as any);
instanceState.setEvaluationListener(evaluationListener);
expect(instanceState.initialServiceProvider).to.equal(sp);
const bsonObj = instanceState.shellBson.ISODate(
'2025-01-09T20:43:51+01:00'
);
expect(bsonObj.toISOString()).to.equal('2025-01-09T19:43:51.000Z');
expect(bsonObj instanceof Date).to.equal(false);
expect(Object.prototype.toString.call(bsonObj)).to.equal(
Object.prototype.toString.call(new Date())
);

try {
await instanceState.shellApi.exit();
expect.fail('missed exception');
} catch (err: any) {
expect(err.message).to.include('.onExit listener returned');
expect(err.stack).to.include('IN_CONTEXT');
expect(err instanceof Error).to.equal(false);
expect(Object.prototype.toString.call(err)).to.equal(
Object.prototype.toString.call(new Error())
);
}
expect(sp.close).to.have.been.calledOnce;
expect(evaluationListener.onExit).to.have.been.calledOnce;
});
});
Loading