vlayer-web-proof
Version:
It is a npm package for vlayer web proof mechanism. It uses native rust bindings for maximum efficiency.
166 lines (165 loc) ⢠7.43 kB
JavaScript
;
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());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.callNativeWebProof = callNativeWebProof;
exports.callNativeSimpleWebProof = callNativeSimpleWebProof;
exports.isNativeBindingLoaded = isNativeBindingLoaded;
exports.getNativeBindingInfo = getNativeBindingInfo;
const types_1 = require("./types");
const node_module_1 = __importDefault(require("node:module"));
let nativeBinding;
let bindingLoadAttempts = 0;
let bindingLoadError = null;
const MAX_BINDING_LOAD_ATTEMPTS = 3;
// Detect environment at runtime
function getRequireFunction() {
if (typeof require !== 'undefined') {
// CJS environment
return require;
}
// ESM environment
try {
const { createRequire } = node_module_1.default;
return createRequire(process.cwd() + '/package.json');
}
catch (_a) {
throw new Error('Cannot create require function in this environment');
}
}
function loadNativeBinding() {
if (nativeBinding) {
return nativeBinding;
}
if (bindingLoadError && bindingLoadAttempts >= MAX_BINDING_LOAD_ATTEMPTS) {
throw bindingLoadError;
}
const bindingPaths = [
'../../vlayer-web-proof.linux-x64-gnu.node',
'../vlayer-web-proof.linux-x64-gnu.node',
'./vlayer-web-proof.linux-x64-gnu.node',
'../../../vlayer-web-proof.linux-x64-gnu.node'
];
let lastError;
const requireFn = getRequireFunction();
for (const path of bindingPaths) {
try {
nativeBinding = requireFn(path);
bindingLoadError = null;
return nativeBinding;
}
catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
}
}
bindingLoadAttempts++;
if (bindingLoadAttempts >= MAX_BINDING_LOAD_ATTEMPTS) {
bindingLoadError = new Error(`Failed to load native binding. This package requires a native Rust component.\n` +
`Please check the following:\n` +
`1. Is your operating system supported? (Linux x64, macOS, Windows)\n` +
`2. Is the package installed correctly?\n` +
`3. Are the required system dependencies available?\n\n` +
`Detailed error: ${(lastError === null || lastError === void 0 ? void 0 : lastError.message) || 'Unknown error'}`);
throw bindingLoadError;
}
throw lastError || new Error('Failed to load native binding');
}
function validateNativeBinding(binding) {
if (!binding) {
throw new Error('Failed to load native binding');
}
if (typeof binding.generateWebProof !== 'function') {
throw new Error('Native binding missing: generateWebProof function not found');
}
if (typeof binding.generateSimpleWebProof !== 'function') {
throw new Error('Native binding missing: generateSimpleWebProof function not found');
}
}
function callNativeWebProof(request) {
return __awaiter(this, void 0, void 0, function* () {
try {
const binding = loadNativeBinding();
validateNativeBinding(binding);
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error(`Web proof generation timed out after ${types_1.DEFAULT_CONFIG.TIMEOUT_MS}ms`));
}, types_1.DEFAULT_CONFIG.TIMEOUT_MS);
});
const proofPromise = binding.generateWebProof({
url: request.url,
host: request.host,
notaryUrl: request.notary_url,
method: request.method,
headers: Array.from(request.headers),
data: request.data,
maxSentData: request.max_sent_data ? Number(request.max_sent_data) : undefined,
maxRecvData: request.max_recv_data ? Number(request.max_recv_data) : undefined,
});
const result = yield Promise.race([proofPromise, timeoutPromise]);
if (!result || typeof result !== 'object') {
throw new Error('Invalid response format from native binding');
}
return result;
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown native error';
if (errorMessage.includes('Failed to load native binding')) {
return {
success: false,
error: `ā ${errorMessage}\n\nš” Solution suggestions:\n- Reinstall the package: npm uninstall vlayer-web-proof && npm install vlayer-web-proof\n- Check your Node.js version (>=18.0.0 required)\n- Verify operating system support`
};
}
return {
success: false,
error: `Web proof generation failed: ${errorMessage}`
};
}
});
}
function callNativeSimpleWebProof(notaryHost, notaryPort, url) {
return __awaiter(this, void 0, void 0, function* () {
try {
const binding = loadNativeBinding();
validateNativeBinding(binding);
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error(`Simple web proof generation timed out after ${types_1.DEFAULT_CONFIG.TIMEOUT_MS}ms`));
}, types_1.DEFAULT_CONFIG.TIMEOUT_MS);
});
const proofPromise = binding.generateSimpleWebProof(notaryHost, notaryPort, url);
const result = yield Promise.race([proofPromise, timeoutPromise]);
if (!result || typeof result !== 'string') {
throw new Error('Invalid response format from native binding - string expected');
}
return result;
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown native error';
if (errorMessage.includes('Failed to load native binding')) {
throw new Error(`ā ${errorMessage}\n\nš” Try reinstalling the package: npm install vlayer-web-proof`);
}
throw new Error(`Simple web proof generation failed: ${errorMessage}`);
}
});
}
function isNativeBindingLoaded() {
return !!nativeBinding;
}
function getNativeBindingInfo() {
return {
loaded: !!nativeBinding,
attempts: bindingLoadAttempts,
error: (bindingLoadError === null || bindingLoadError === void 0 ? void 0 : bindingLoadError.message) || null,
supportedPlatforms: ['linux-x64', 'darwin-x64', 'darwin-arm64', 'win32-x64']
};
}