fix support with webpack{4,5} in browser environment

added missing .js extension to the imports
split index
use browser field in package json
This commit is contained in:
Sebastian 2021-06-17 12:40:42 -03:00
parent 46f3fcbbfb
commit 1c7423dbad
No known key found for this signature in database
GPG Key ID: BE4FF68352439FC1
17 changed files with 200 additions and 103 deletions

View File

@ -29,9 +29,13 @@
"lib/" "lib/"
], ],
"main": "./dist/taler-wallet-core.js", "main": "./dist/taler-wallet-core.js",
"module": "./lib/index.js", "browser": {
"./dist/taler-wallet-core.js": "./dist/taler-wallet-core.browser.js",
"./lib/index.node.js": "./lib/index.browser.js"
},
"module": "./lib/index.node.js",
"type": "module", "type": "module",
"types": "./lib/index.d.ts", "types": "./lib/index.node.d.ts",
"devDependencies": { "devDependencies": {
"@ava/typescript": "^1.1.1", "@ava/typescript": "^1.1.1",
"@gnu-taler/pogen": "workspace:*", "@gnu-taler/pogen": "workspace:*",

View File

@ -6,8 +6,8 @@ import builtins from "builtin-modules";
import pkg from "./package.json"; import pkg from "./package.json";
import sourcemaps from 'rollup-plugin-sourcemaps'; import sourcemaps from 'rollup-plugin-sourcemaps';
export default { const nodeEntryPoint = {
input: "lib/index.js", input: "lib/index.node.js",
output: { output: {
file: pkg.main, file: pkg.main,
format: "cjs", format: "cjs",
@ -32,3 +32,34 @@ export default {
], ],
} }
const browserEntryPoint = {
input: "lib/index.browser.js",
output: {
file: pkg.browser[pkg.main],
format: "cjs",
sourcemap: true,
},
external: builtins,
plugins: [
nodeResolve({
preferBuiltins: true,
}),
sourcemaps(),
commonjs({
include: [/node_modules/, /dist/],
extensions: [".js"],
ignoreGlobal: false,
sourceMap: true,
}),
json(),
],
}
export default [
nodeEntryPoint,
browserEntryPoint
]

View File

@ -5,16 +5,6 @@
// Implementation derived from TweetNaCl version 20140427. // Implementation derived from TweetNaCl version 20140427.
// See for details: http://tweetnacl.cr.yp.to/ // See for details: http://tweetnacl.cr.yp.to/
import * as mod from "module";
let require: any;
if (typeof require !== "function" && mod.default && mod.default.createRequire) {
// We need this require function to synchronously
// import the "crypto" module in the CSPRNG initialization.
require = mod.default.createRequire(import.meta.url);
}
const gf = function (init: number[] = []): Float64Array { const gf = function (init: number[] = []): Float64Array {
const r = new Float64Array(16); const r = new Float64Array(16);
if (init) for (let i = 0; i < init.length; i++) r[i] = init[i]; if (init) for (let i = 0; i < init.length; i++) r[i] = init[i];
@ -2806,10 +2796,6 @@ function checkArrayTypes(...args: Uint8Array[]): void {
} }
} }
function cleanup(arr: Uint8Array): void {
for (let i = 0; i < arr.length; i++) arr[i] = 0;
}
export function randomBytes(n: number): Uint8Array { export function randomBytes(n: number): Uint8Array {
const b = new Uint8Array(n); const b = new Uint8Array(n);
randombytes(b, n); randombytes(b, n);
@ -3031,35 +3017,3 @@ export function secretbox_open(
return m.subarray(crypto_secretbox_ZEROBYTES); return m.subarray(crypto_secretbox_ZEROBYTES);
} }
function initPRNG() {
// Initialize PRNG if environment provides CSPRNG.
// If not, methods calling randombytes will throw.
// @ts-ignore-error
const cr = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
if (cr && cr.getRandomValues) {
// Browsers.
const QUOTA = 65536;
setPRNG(function (x: Uint8Array, n: number) {
let i;
const v = new Uint8Array(n);
for (i = 0; i < n; i += QUOTA) {
cr.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
}
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
} else if (typeof require !== "undefined") {
// Node.js.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cr = require("crypto");
if (cr && cr.randomBytes) {
setPRNG(function (x: Uint8Array, n: number) {
const v = cr.randomBytes(n);
for (let i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
}
}
}
initPRNG();

View File

@ -45,7 +45,7 @@ import {
MakeSyncSignatureRequest, MakeSyncSignatureRequest,
} from "@gnu-taler/taler-util"; } from "@gnu-taler/taler-util";
import { AmountJson, Amounts } from "@gnu-taler/taler-util"; import { AmountJson, Amounts } from "@gnu-taler/taler-util";
import * as timer from "../../util/timer"; import * as timer from "../../util/timer.js";
import { import {
encodeCrock, encodeCrock,
decodeCrock, decodeCrock,
@ -63,9 +63,9 @@ import {
setupRefreshTransferPub, setupRefreshTransferPub,
setupTipPlanchet, setupTipPlanchet,
setupWithdrawPlanchet, setupWithdrawPlanchet,
} from "../talerCrypto"; } from "../talerCrypto.js";
import { randomBytes } from "../primitives/nacl-fast"; import { randomBytes } from "../primitives/nacl-fast.js";
import { kdf } from "../primitives/kdf"; import { kdf } from "../primitives/kdf.js";
import { Timestamp, timestampTruncateToSecond } from "@gnu-taler/taler-util"; import { Timestamp, timestampTruncateToSecond } from "@gnu-taler/taler-util";
import { Logger } from "@gnu-taler/taler-util"; import { Logger } from "@gnu-taler/taler-util";

View File

@ -17,10 +17,10 @@
/** /**
* Imports * Imports
*/ */
import { CryptoWorkerFactory } from "./cryptoApi"; import { CryptoWorkerFactory } from "./cryptoApi.js";
import { CryptoWorker } from "./cryptoWorker"; import { CryptoWorker } from "./cryptoWorker.js";
import os from "os"; import os from "os";
import { CryptoImplementation } from "./cryptoImplementation"; import { CryptoImplementation } from "./cryptoImplementation.js";
import { Logger } from "@gnu-taler/taler-util"; import { Logger } from "@gnu-taler/taler-util";
const logger = new Logger("nodeThreadWorker.ts"); const logger = new Logger("nodeThreadWorker.ts");

View File

@ -14,10 +14,10 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/ */
import { CryptoImplementation } from "./cryptoImplementation"; import { CryptoImplementation } from "./cryptoImplementation.js";
import { CryptoWorkerFactory } from "./cryptoApi"; import { CryptoWorkerFactory } from "./cryptoApi.js";
import { CryptoWorker } from "./cryptoWorker"; import { CryptoWorker } from "./cryptoWorker.js";
/** /**
* The synchronous crypto worker produced by this factory doesn't run in the * The synchronous crypto worker produced by this factory doesn't run in the

View File

@ -24,13 +24,13 @@ import {
HttpRequestLibrary, HttpRequestLibrary,
HttpRequestOptions, HttpRequestOptions,
HttpResponse, HttpResponse,
} from "../util/http"; } from "../util/http.js";
import { RequestThrottler } from "../util/RequestThrottler"; import { RequestThrottler } from "../util/RequestThrottler.js";
import Axios, { AxiosResponse } from "axios"; import Axios, { AxiosResponse } from "axios";
import { OperationFailedError, makeErrorDetails } from "../errors"; import { OperationFailedError, makeErrorDetails } from "../errors.js";
import { URL } from "../util/url"; import { URL } from "../util/url.js";
import { Logger } from "@gnu-taler/taler-util"; import { Logger } from "@gnu-taler/taler-util";
import { bytesToString } from "../crypto/talerCrypto"; import { bytesToString } from "../crypto/talerCrypto.js";
import { TalerErrorCode } from "@gnu-taler/taler-util"; import { TalerErrorCode } from "@gnu-taler/taler-util";
const logger = new Logger("NodeHttpLib.ts"); const logger = new Logger("NodeHttpLib.ts");

View File

@ -27,12 +27,12 @@ import {
BridgeIDBFactory, BridgeIDBFactory,
shimIndexedDB, shimIndexedDB,
} from "@gnu-taler/idb-bridge"; } from "@gnu-taler/idb-bridge";
import { openTalerDatabase } from "../db"; import { openTalerDatabase } from "../db.js";
import { HttpRequestLibrary } from "../util/http"; import { HttpRequestLibrary } from "../util/http.js";
import { NodeThreadCryptoWorkerFactory } from "../crypto/workers/nodeThreadWorker"; import { NodeThreadCryptoWorkerFactory } from "../crypto/workers/nodeThreadWorker.js";
import { NodeHttpLib } from "./NodeHttpLib"; import { NodeHttpLib } from "./NodeHttpLib.js";
import { Logger } from "@gnu-taler/taler-util"; import { Logger } from "@gnu-taler/taler-util";
import { SynchronousCryptoWorkerFactory } from "../crypto/workers/synchronousWorker"; import { SynchronousCryptoWorkerFactory } from "../crypto/workers/synchronousWorker.js";
import type { IDBFactory } from "@gnu-taler/idb-bridge"; import type { IDBFactory } from "@gnu-taler/idb-bridge";
import { WalletNotification } from "@gnu-taler/taler-util"; import { WalletNotification } from "@gnu-taler/taler-util";
import { InternalWalletState } from "../common.js"; import { InternalWalletState } from "../common.js";

View File

@ -0,0 +1,72 @@
/*
This file is part of TALER
(C) 2019 GNUnet e.V.
TALER is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
TALER is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
export * from "./index.js";
import { setPRNG } from './crypto/primitives/nacl-fast.js';
// export default API;
function cleanup(arr: Uint8Array): void {
for (let i = 0; i < arr.length; i++) arr[i] = 0;
}
// Initialize PRNG if environment provides CSPRNG.
// If not, methods calling randombytes will throw.
// @ts-ignore-error
const cr = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
const QUOTA = 65536;
setPRNG(function (x: Uint8Array, n: number) {
let i;
const v = new Uint8Array(n);
for (i = 0; i < n; i += QUOTA) {
cr.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
}
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
// function initPRNG() {
// // Initialize PRNG if environment provides CSPRNG.
// // If not, methods calling randombytes will throw.
// // @ts-ignore-error
// const cr = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
// if (cr && cr.getRandomValues) {
// // Browsers.
// const QUOTA = 65536;
// setPRNG(function (x: Uint8Array, n: number) {
// let i;
// const v = new Uint8Array(n);
// for (i = 0; i < n; i += QUOTA) {
// cr.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
// }
// for (i = 0; i < n; i++) x[i] = v[i];
// cleanup(v);
// });
// } else if (typeof require !== "undefined") {
// // Node.js.
// // eslint-disable-next-line @typescript-eslint/no-var-requires
// const cr = require("crypto");
// if (cr && cr.randomBytes) {
// setPRNG(function (x: Uint8Array, n: number) {
// const v = cr.randomBytes(n);
// for (let i = 0; i < n; i++) x[i] = v[i];
// cleanup(v);
// });
// }
// }
// }
// initPRNG();

View File

@ -0,0 +1,43 @@
/*
This file is part of TALER
(C) 2019 GNUnet e.V.
TALER is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
TALER is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
export * from "./index.js";
// Utils for using the wallet under node
export { NodeHttpLib } from "./headless/NodeHttpLib.js";
export {
getDefaultNodeWallet,
DefaultNodeWalletArgs,
} from "./headless/helpers.js";
import { setPRNG } from './crypto/primitives/nacl-fast.js';
import cr from 'crypto';
function cleanup(arr: Uint8Array): void {
for (let i = 0; i < arr.length; i++) arr[i] = 0;
}
// Initialize PRNG if environment provides CSPRNG.
// If not, methods calling randombytes will throw.
if (cr && cr.randomBytes) {
setPRNG(function (x: Uint8Array, n: number) {
const v = cr.randomBytes(n);
for (let i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
}
export * from "./crypto/workers/nodeThreadWorker.js";

View File

@ -27,19 +27,12 @@ export * from "./util/promiseUtils.js";
export * from "./util/query.js"; export * from "./util/query.js";
export * from "./util/http.js"; export * from "./util/http.js";
// Utils for using the wallet under node
export { NodeHttpLib } from "./headless/NodeHttpLib.js";
export {
getDefaultNodeWallet,
DefaultNodeWalletArgs,
} from "./headless/helpers.js";
export * from "./versions.js"; export * from "./versions.js";
export * from "./db.js"; export * from "./db.js";
// Crypto and crypto workers // Crypto and crypto workers
export * from "./crypto/workers/nodeThreadWorker.js"; // export * from "./crypto/workers/nodeThreadWorker.js";
export { CryptoImplementation } from "./crypto/workers/cryptoImplementation.js"; export { CryptoImplementation } from "./crypto/workers/cryptoImplementation.js";
export type { CryptoWorker } from "./crypto/workers/cryptoWorker.js"; export type { CryptoWorker } from "./crypto/workers/cryptoWorker.js";
export { CryptoWorkerFactory, CryptoApi } from "./crypto/workers/cryptoApi.js"; export { CryptoWorkerFactory, CryptoApi } from "./crypto/workers/cryptoApi.js";

View File

@ -50,7 +50,7 @@ import {
BackupExchangeDetails, BackupExchangeDetails,
} from "@gnu-taler/taler-util"; } from "@gnu-taler/taler-util";
import { InternalWalletState } from "../../common.js"; import { InternalWalletState } from "../../common.js";
import { provideBackupState, getWalletBackupState } from "./state"; import { provideBackupState, getWalletBackupState } from "./state.js";
import { Amounts, getTimestampNow } from "@gnu-taler/taler-util"; import { Amounts, getTimestampNow } from "@gnu-taler/taler-util";
import { import {
CoinSourceType, CoinSourceType,
@ -60,7 +60,7 @@ import {
ProposalStatus, ProposalStatus,
WALLET_BACKUP_STATE_KEY, WALLET_BACKUP_STATE_KEY,
} from "../../db.js"; } from "../../db.js";
import { encodeCrock, stringToBytes, getRandomBytes } from "../../index.js"; import { encodeCrock, stringToBytes, getRandomBytes } from "../../crypto/talerCrypto.js";
import { canonicalizeBaseUrl, canonicalJson } from "@gnu-taler/taler-util"; import { canonicalizeBaseUrl, canonicalJson } from "@gnu-taler/taler-util";
export async function exportBackup( export async function exportBackup(

View File

@ -46,9 +46,9 @@ import {
WireInfo, WireInfo,
WalletStoresV1, WalletStoresV1,
} from "../../db.js"; } from "../../db.js";
import { PayCoinSelection } from "../../util/coinSelection"; import { PayCoinSelection } from "../../util/coinSelection.js";
import { j2s } from "@gnu-taler/taler-util"; import { j2s } from "@gnu-taler/taler-util";
import { checkDbInvariant, checkLogicInvariant } from "../../util/invariants"; import { checkDbInvariant, checkLogicInvariant } from "../../util/invariants.js";
import { Logger } from "@gnu-taler/taler-util"; import { Logger } from "@gnu-taler/taler-util";
import { initRetryInfo } from "../../util/retries.js"; import { initRetryInfo } from "../../util/retries.js";
import { InternalWalletState } from "../../common.js"; import { InternalWalletState } from "../../common.js";

View File

@ -53,7 +53,7 @@ import {
Logger, Logger,
getDurationRemaining, getDurationRemaining,
} from "@gnu-taler/taler-util"; } from "@gnu-taler/taler-util";
import { encodeCrock, getRandomBytes } from "../crypto/talerCrypto"; import { encodeCrock, getRandomBytes } from "../crypto/talerCrypto.js";
import { import {
PayCoinSelection, PayCoinSelection,
CoinCandidateSelection, CoinCandidateSelection,

View File

@ -27,7 +27,7 @@ import {
timestampCmp, timestampCmp,
Logger, Logger,
} from "@gnu-taler/taler-util"; } from "@gnu-taler/taler-util";
import { URL } from "./url"; import { URL } from "./url.js";
const logger = new Logger("RequestThrottler.ts"); const logger = new Logger("RequestThrottler.ts");

View File

@ -66,7 +66,7 @@ import {
WithdrawTestBalanceRequest, WithdrawTestBalanceRequest,
WithdrawUriInfoResponse, WithdrawUriInfoResponse,
} from "@gnu-taler/taler-util"; } from "@gnu-taler/taler-util";
import { AddBackupProviderRequest, BackupInfo } from "./operations/backup"; import { AddBackupProviderRequest, BackupInfo } from "./operations/backup/index.js";
import { PendingOperationsResponse } from "./pending-types.js"; import { PendingOperationsResponse } from "./pending-types.js";
export enum WalletApiOperation { export enum WalletApiOperation {

View File

@ -43,65 +43,65 @@ import {
getBackupRecovery, getBackupRecovery,
loadBackupRecovery, loadBackupRecovery,
runBackupCycle, runBackupCycle,
} from "./operations/backup"; } from "./operations/backup/index.js";
import { exportBackup } from "./operations/backup/export"; import { exportBackup } from "./operations/backup/export.js";
import { getBalances } from "./operations/balance"; import { getBalances } from "./operations/balance.js";
import { import {
createDepositGroup, createDepositGroup,
processDepositGroup, processDepositGroup,
trackDepositGroup, trackDepositGroup,
} from "./operations/deposits"; } from "./operations/deposits.js";
import { import {
makeErrorDetails, makeErrorDetails,
OperationFailedAndReportedError, OperationFailedAndReportedError,
OperationFailedError, OperationFailedError,
} from "./errors"; } from "./errors.js";
import { import {
acceptExchangeTermsOfService, acceptExchangeTermsOfService,
getExchangeDetails, getExchangeDetails,
updateExchangeFromUrl, updateExchangeFromUrl,
} from "./operations/exchanges"; } from "./operations/exchanges.js";
import { import {
confirmPay, confirmPay,
preparePayForUri, preparePayForUri,
processDownloadProposal, processDownloadProposal,
processPurchasePay, processPurchasePay,
} from "./operations/pay"; } from "./operations/pay.js";
import { getPendingOperations } from "./operations/pending"; import { getPendingOperations } from "./operations/pending.js";
import { processRecoupGroup } from "./operations/recoup"; import { processRecoupGroup } from "./operations/recoup.js";
import { import {
autoRefresh, autoRefresh,
createRefreshGroup, createRefreshGroup,
processRefreshGroup, processRefreshGroup,
} from "./operations/refresh"; } from "./operations/refresh.js";
import { import {
abortFailedPayWithRefund, abortFailedPayWithRefund,
applyRefund, applyRefund,
processPurchaseQueryRefund, processPurchaseQueryRefund,
} from "./operations/refund"; } from "./operations/refund.js";
import { import {
createReserve, createReserve,
createTalerWithdrawReserve, createTalerWithdrawReserve,
getFundingPaytoUris, getFundingPaytoUris,
processReserve, processReserve,
} from "./operations/reserves"; } from "./operations/reserves.js";
import { InternalWalletState } from "./common"; import { InternalWalletState } from "./common.js";
import { import {
runIntegrationTest, runIntegrationTest,
testPay, testPay,
withdrawTestBalance, withdrawTestBalance,
} from "./operations/testing"; } from "./operations/testing.js";
import { acceptTip, prepareTip, processTip } from "./operations/tip"; import { acceptTip, prepareTip, processTip } from "./operations/tip.js";
import { import {
deleteTransaction, deleteTransaction,
getTransactions, getTransactions,
retryTransaction, retryTransaction,
} from "./operations/transactions"; } from "./operations/transactions.js";
import { import {
getExchangeWithdrawalInfo, getExchangeWithdrawalInfo,
getWithdrawalDetailsForUri, getWithdrawalDetailsForUri,
processWithdrawGroup, processWithdrawGroup,
} from "./operations/withdraw"; } from "./operations/withdraw.js";
import { import {
AuditorTrustRecord, AuditorTrustRecord,
CoinSourceType, CoinSourceType,
@ -147,7 +147,7 @@ import {
RefreshReason, RefreshReason,
} from "@gnu-taler/taler-util"; } from "@gnu-taler/taler-util";
import { AmountJson, Amounts } from "@gnu-taler/taler-util"; import { AmountJson, Amounts } from "@gnu-taler/taler-util";
import { assertUnreachable } from "./util/assertUnreachable"; import { assertUnreachable } from "./util/assertUnreachable.js";
import { Logger } from "@gnu-taler/taler-util"; import { Logger } from "@gnu-taler/taler-util";
import { setWalletDeviceId } from "./operations/backup/state.js"; import { setWalletDeviceId } from "./operations/backup/state.js";
import { WalletCoreApiClient } from "./wallet-api-types.js"; import { WalletCoreApiClient } from "./wallet-api-types.js";