fix compiler warnings

This commit is contained in:
Florian Dold 2016-09-12 20:25:56 +02:00
parent e3cc9c59bc
commit 8852857347
16 changed files with 161 additions and 137 deletions

View File

@ -9,7 +9,7 @@ interface System {
config: any; config: any;
newModule(obj: Object): any; newModule(obj: Object): any;
normalizeSync(name: string): string; normalizeSync(name: string): string;
set(moduleName: string, module: any) set(moduleName: string, module: any): void;
} }

View File

@ -33,7 +33,7 @@ export interface EmscFunGen {
export declare namespace Module { export declare namespace Module {
var cwrap: EmscFunGen; var cwrap: EmscFunGen;
function _free(ptr: number); function _free(ptr: number): void;
function _malloc(n: number): number; function _malloc(n: number): number;
@ -41,9 +41,10 @@ export declare namespace Module {
function getValue(ptr: number, type: string, noSafe?: boolean): number; function getValue(ptr: number, type: string, noSafe?: boolean): number;
function setValue(ptr: number, value: number, type: string, noSafe?: boolean); function setValue(ptr: number, value: number, type: string,
noSafe?: boolean): void;
function writeStringToMemory(s: string, function writeStringToMemory(s: string,
buffer: number, buffer: number,
dontAddNull?: boolean); dontAddNull?: boolean): void;
} }

View File

@ -24,14 +24,14 @@ document.addEventListener(
declare var i18n: any; declare var i18n: any;
const JedModule = window["Jed"]; const JedModule: any = (window as any)["Jed"];
var jed; var jed: any;
class PluralNumber { class PluralNumber {
n: number; n: number;
constructor(n) { constructor(n: number) {
this.n = n; this.n = n;
} }
@ -62,7 +62,7 @@ function init () {
/** Convert template strings to a msgid */ /** Convert template strings to a msgid */
function toI18nString(strings) { function toI18nString(strings: string[]) {
let str = ""; let str = "";
for (let i = 0; i < strings.length; i++) { for (let i = 0; i < strings.length; i++) {
str += strings[i]; str += strings[i];
@ -75,7 +75,7 @@ function toI18nString(strings) {
/** Use the first number in values to determine plural form */ /** Use the first number in values to determine plural form */
function getPluralValue (values) { function getPluralValue (values: any) {
let n = null; let n = null;
for (let i = 0; i < values.length; i++) { for (let i = 0; i < values.length; i++) {
if ("number" === typeof values[i] || values[i] instanceof PluralNumber) { if ("number" === typeof values[i] || values[i] instanceof PluralNumber) {
@ -88,11 +88,11 @@ function getPluralValue (values) {
} }
var i18n = <any>function i18n(strings, ...values) { var i18n = <any>function i18n(strings: string[], ...values: any[]) {
init(); init();
if ("object" !== typeof jed) { if ("object" !== typeof jed) {
// Fallback implementation in case i18n lib is not there // Fallback implementation in case i18n lib is not there
return String.raw(strings, ...values); return String.raw(strings as any, ...values);
} }
let str = toI18nString (strings); let str = toI18nString (strings);
@ -109,11 +109,11 @@ i18n.strings = {};
* Interpolate i18nized values with arbitrary objects. * Interpolate i18nized values with arbitrary objects.
* @return Array of strings/objects. * @return Array of strings/objects.
*/ */
i18n.parts = function(strings, ...values) { i18n.parts = function(strings: string[], ...values: any[]) {
init(); init();
if ("object" !== typeof jed) { if ("object" !== typeof jed) {
// Fallback implementation in case i18n lib is not there // Fallback implementation in case i18n lib is not there
let parts = []; let parts: string[] = [];
for (let i = 0; i < strings.length; i++) { for (let i = 0; i < strings.length; i++) {
parts.push(strings[i]); parts.push(strings[i]);
@ -127,7 +127,7 @@ i18n.parts = function(strings, ...values) {
let str = toI18nString (strings); let str = toI18nString (strings);
let n = getPluralValue (values); let n = getPluralValue (values);
let tr = jed.ngettext(str, str, n).split(/%(\d+)\$s/); let tr = jed.ngettext(str, str, n).split(/%(\d+)\$s/);
let parts = []; let parts: string[] = [];
for (let i = 0; i < tr.length; i++) { for (let i = 0; i < tr.length; i++) {
if (0 == i % 2) { if (0 == i % 2) {
parts.push(tr[i]); parts.push(tr[i]);
@ -144,7 +144,7 @@ i18n.parts = function(strings, ...values) {
* Pluralize based on first numeric parameter in the template. * Pluralize based on first numeric parameter in the template.
* @todo The plural argument is used for extraction by pogen.js * @todo The plural argument is used for extraction by pogen.js
*/ */
i18n.pluralize = function (singular, plural) { i18n.pluralize = function (singular: any, plural: any) {
return singular; return singular;
}; };
@ -154,4 +154,4 @@ i18n.pluralize = function (singular, plural) {
*/ */
i18n.number = function (n : number) { i18n.number = function (n : number) {
return new PluralNumber (n); return new PluralNumber (n);
} };

View File

@ -25,18 +25,39 @@
*/ */
export namespace Checkable { export namespace Checkable {
export function SchemaError(message) {
type Path = (number|string)[];
interface SchemaErrorConstructor {
new (err: string): SchemaError;
}
interface SchemaError {
name: string;
message: string;
}
interface Prop {
propertyKey: any;
checker: any;
type: any;
elementChecker?: any;
elementProp?: any;
}
export let SchemaError = (function SchemaError(message: string) {
this.name = 'SchemaError'; this.name = 'SchemaError';
this.message = message; this.message = message;
this.stack = (<any>new Error()).stack; this.stack = (<any>new Error()).stack;
} }) as any as SchemaErrorConstructor;
SchemaError.prototype = new Error; SchemaError.prototype = new Error;
let chkSym = Symbol("checkable"); let chkSym = Symbol("checkable");
function checkNumber(target, prop, path): any { function checkNumber(target: any, prop: Prop, path: Path): any {
if ((typeof target) !== "number") { if ((typeof target) !== "number") {
throw new SchemaError(`expected number for ${path}`); throw new SchemaError(`expected number for ${path}`);
} }
@ -44,7 +65,7 @@ export namespace Checkable {
} }
function checkString(target, prop, path): any { function checkString(target: any, prop: Prop, path: Path): any {
if (typeof target !== "string") { if (typeof target !== "string") {
throw new SchemaError(`expected string for ${path}, got ${typeof target} instead`); throw new SchemaError(`expected string for ${path}, got ${typeof target} instead`);
} }
@ -52,7 +73,7 @@ export namespace Checkable {
} }
function checkAnyObject(target, prop, path): any { function checkAnyObject(target: any, prop: Prop, path: Path): any {
if (typeof target !== "object") { if (typeof target !== "object") {
throw new SchemaError(`expected (any) object for ${path}, got ${typeof target} instead`); throw new SchemaError(`expected (any) object for ${path}, got ${typeof target} instead`);
} }
@ -60,12 +81,12 @@ export namespace Checkable {
} }
function checkAny(target, prop, path): any { function checkAny(target: any, prop: Prop, path: Path): any {
return target; return target;
} }
function checkList(target, prop, path): any { function checkList(target: any, prop: Prop, path: Path): any {
if (!Array.isArray(target)) { if (!Array.isArray(target)) {
throw new SchemaError(`array expected for ${path}, got ${typeof target} instead`); throw new SchemaError(`array expected for ${path}, got ${typeof target} instead`);
} }
@ -77,7 +98,7 @@ export namespace Checkable {
} }
function checkOptional(target, prop, path): any { function checkOptional(target: any, prop: Prop, path: Path): any {
console.assert(prop.propertyKey); console.assert(prop.propertyKey);
prop.elementChecker(target, prop.elementChecker(target,
prop.elementProp, prop.elementProp,
@ -86,7 +107,7 @@ export namespace Checkable {
} }
function checkValue(target, prop, path): any { function checkValue(target: any, prop: Prop, path: Path): any {
let type = prop.type; let type = prop.type;
if (!type) { if (!type) {
throw Error(`assertion failed (prop is ${JSON.stringify(prop)})`); throw Error(`assertion failed (prop is ${JSON.stringify(prop)})`);
@ -123,8 +144,8 @@ export namespace Checkable {
} }
export function Class(target) { export function Class(target: any) {
target.checked = (v) => { target.checked = (v: any) => {
return checkValue(v, { return checkValue(v, {
propertyKey: "(root)", propertyKey: "(root)",
type: target, type: target,
@ -135,7 +156,7 @@ export namespace Checkable {
} }
export function Value(type) { export function Value(type: any) {
if (!type) { if (!type) {
throw Error("Type does not exist yet (wrong order of definitions?)"); throw Error("Type does not exist yet (wrong order of definitions?)");
} }
@ -152,7 +173,7 @@ export namespace Checkable {
} }
export function List(type) { export function List(type: any) {
let stub = {}; let stub = {};
type(stub, "(list-element)"); type(stub, "(list-element)");
let elementProp = mkChk(stub).props[0]; let elementProp = mkChk(stub).props[0];
@ -174,7 +195,7 @@ export namespace Checkable {
} }
export function Optional(type) { export function Optional(type: any) {
let stub = {}; let stub = {};
type(stub, "(optional-element)"); type(stub, "(optional-element)");
let elementProp = mkChk(stub).props[0]; let elementProp = mkChk(stub).props[0];
@ -230,7 +251,7 @@ export namespace Checkable {
} }
function mkChk(target) { function mkChk(target: any) {
let chk = target[chkSym]; let chk = target[chkSym];
if (!chk) { if (!chk) {
chk = {props: []}; chk = {props: []};

View File

@ -27,9 +27,10 @@ import {Denomination} from "./types";
import {Offer} from "./wallet"; import {Offer} from "./wallet";
import {CoinWithDenom} from "./wallet"; import {CoinWithDenom} from "./wallet";
import {PayCoinInfo} from "./types"; import {PayCoinInfo} from "./types";
type RegistryEntry = {resolve: any; reject: any};
export class CryptoApi { export class CryptoApi {
private nextRpcId: number = 1; private nextRpcId: number = 1;
private rpcRegistry = {}; private rpcRegistry: {[n: number]: RegistryEntry} = {};
private cryptoWorker: Worker; private cryptoWorker: Worker;
@ -52,14 +53,14 @@ export class CryptoApi {
} }
private registerRpcId(resolve, reject): number { private registerRpcId(resolve: any, reject: any): number {
let id = this.nextRpcId++; let id = this.nextRpcId++;
this.rpcRegistry[id] = {resolve, reject}; this.rpcRegistry[id] = {resolve, reject};
return id; return id;
} }
private doRpc<T>(methodName: string, ...args): Promise<T> { private doRpc<T>(methodName: string, ...args: any[]): Promise<T> {
return new Promise<T>((resolve, reject) => { return new Promise<T>((resolve, reject) => {
let msg = { let msg = {
operation: methodName, operation: methodName,

View File

@ -28,6 +28,7 @@ import {Offer} from "./wallet";
import {CoinWithDenom} from "./wallet"; import {CoinWithDenom} from "./wallet";
import {CoinPaySig} from "./types"; import {CoinPaySig} from "./types";
import {Denomination} from "./types"; import {Denomination} from "./types";
import {Amount} from "./emscriptif";
export function main(worker: Worker) { export function main(worker: Worker) {
@ -43,7 +44,7 @@ export function main(worker: Worker) {
if (typeof msg.data.operation != "string") { if (typeof msg.data.operation != "string") {
console.error("RPC operation must be string"); console.error("RPC operation must be string");
} }
let f = RpcFunctions[msg.data.operation]; let f = (RpcFunctions as any)[msg.data.operation];
if (!f) { if (!f) {
console.error(`unknown operation: '${msg.data.operation}'`); console.error(`unknown operation: '${msg.data.operation}'`);
return; return;
@ -156,7 +157,7 @@ namespace RpcFunctions {
} }
export function rsaUnblind(sig, bk, pk): string { export function rsaUnblind(sig: string, bk: string, pk: string): string {
let denomSig = native.rsaUnblind(native.RsaSignature.fromCrock(sig), let denomSig = native.rsaUnblind(native.RsaSignature.fromCrock(sig),
native.RsaBlindingKeySecret.fromCrock(bk), native.RsaBlindingKeySecret.fromCrock(bk),
native.RsaPublicKey.fromCrock(pk)); native.RsaPublicKey.fromCrock(pk));
@ -170,11 +171,11 @@ namespace RpcFunctions {
*/ */
export function signDeposit(offer: Offer, export function signDeposit(offer: Offer,
cds: CoinWithDenom[]): PayCoinInfo { cds: CoinWithDenom[]): PayCoinInfo {
let ret = []; let ret: PayCoinInfo = [];
let amountSpent = native.Amount.getZero(cds[0].coin.currentAmount.currency); let amountSpent = native.Amount.getZero(cds[0].coin.currentAmount.currency);
let amountRemaining = new native.Amount(offer.contract.amount); let amountRemaining = new native.Amount(offer.contract.amount);
for (let cd of cds) { for (let cd of cds) {
let coinSpend; let coinSpend: Amount;
if (amountRemaining.value == 0 && amountRemaining.fraction == 0) { if (amountRemaining.value == 0 && amountRemaining.fraction == 0) {
break; break;

View File

@ -15,6 +15,7 @@
*/ */
"use strict"; "use strict";
import Dictionary = _.Dictionary;
/** /**
* Declarations and helpers for * Declarations and helpers for
@ -83,27 +84,27 @@ export function openTalerDb(): Promise<IDBDatabase> {
} }
export function exportDb(db): Promise<any> { export function exportDb(db: IDBDatabase): Promise<any> {
let dump = { let dump = {
name: db.name, name: db.name,
version: db.version, version: db.version,
stores: {} stores: {} as Dictionary<any>,
}; };
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let tx = db.transaction(db.objectStoreNames); let tx = db.transaction(db.objectStoreNames);
tx.addEventListener("complete", (e) => { tx.addEventListener("complete", () => {
resolve(dump); resolve(dump);
}); });
for (let i = 0; i < db.objectStoreNames.length; i++) { for (let i = 0; i < db.objectStoreNames.length; i++) {
let name = db.objectStoreNames[i]; let name = db.objectStoreNames[i];
let storeDump = {}; let storeDump = {} as Dictionary<any>;
dump.stores[name] = storeDump; dump.stores[name] = storeDump;
let store = tx.objectStore(name) let store = tx.objectStore(name)
.openCursor() .openCursor()
.addEventListener("success", (e) => { .addEventListener("success", (e: Event) => {
let cursor = e.target.result; let cursor = (e.target as any).result;
if (cursor) { if (cursor) {
storeDump[cursor.key] = cursor.value; storeDump[cursor.key] = cursor.value;
cursor.continue(); cursor.continue();

View File

@ -36,11 +36,11 @@ const GNUNET_SYSERR = -1;
let Module = EmscWrapper.Module; let Module = EmscWrapper.Module;
let getEmsc: EmscWrapper.EmscFunGen = (...args) => Module.cwrap.apply(null, let getEmsc: EmscWrapper.EmscFunGen = (...args: any[]) => Module.cwrap.apply(null,
args); args);
var emsc = { var emsc = {
free: (ptr) => Module._free(ptr), free: (ptr: number) => Module._free(ptr),
get_value: getEmsc('TALER_WR_get_value', get_value: getEmsc('TALER_WR_get_value',
'number', 'number',
['number']), ['number']),
@ -164,13 +164,12 @@ enum RandomQuality {
abstract class ArenaObject { abstract class ArenaObject {
private _nativePtr: number; private _nativePtr: number | undefined = undefined;
arena: Arena; arena: Arena;
abstract destroy(): void; abstract destroy(): void;
constructor(arena?: Arena) { constructor(arena?: Arena) {
this.nativePtr = null;
if (!arena) { if (!arena) {
if (arenaStack.length == 0) { if (arenaStack.length == 0) {
throw Error("No arena available") throw Error("No arena available")
@ -192,9 +191,9 @@ abstract class ArenaObject {
} }
free() { free() {
if (this.nativePtr !== undefined) { if (this.nativePtr) {
emsc.free(this.nativePtr); emsc.free(this.nativePtr);
this.nativePtr = undefined; this._nativePtr = undefined;
} }
} }
@ -212,21 +211,22 @@ abstract class ArenaObject {
this._nativePtr = n; this._nativePtr = n;
} }
set nativePtr(v) { set nativePtr(v: number) {
this.setNative(v); this.setNative(v);
} }
get nativePtr() { get nativePtr() {
return this.getNative(); return this.getNative();
} }
} }
interface Arena { interface Arena {
put(obj: ArenaObject): void; put(obj: ArenaObject): void;
destroy(): void; destroy(): void;
} }
class DefaultArena implements Arena { class DefaultArena implements Arena {
heap: Array<ArenaObject>; heap: Array<ArenaObject>;
@ -234,7 +234,7 @@ class DefaultArena implements Arena {
this.heap = []; this.heap = [];
} }
put(obj) { put(obj: ArenaObject) {
this.heap.push(obj); this.heap.push(obj);
} }
@ -269,7 +269,7 @@ class SyncArena extends DefaultArena {
super(); super();
} }
pub(obj) { pub(obj: ArenaObject) {
super.put(obj); super.put(obj);
if (!this.isScheduled) { if (!this.isScheduled) {
this.schedule(); this.schedule();
@ -308,14 +308,12 @@ export class Amount extends ArenaObject {
} }
destroy() { destroy() {
if (this.nativePtr != 0) { super.free();
emsc.free(this.nativePtr);
}
} }
static getZero(currency: string, a?: Arena): Amount { static getZero(currency: string, a?: Arena): Amount {
let am = new Amount(null, a); let am = new Amount(undefined, a);
let r = emsc.amount_get_zero(currency, am.getNative()); let r = emsc.amount_get_zero(currency, am.getNative());
if (r != GNUNET_OK) { if (r != GNUNET_OK) {
throw Error("invalid currency"); throw Error("invalid currency");
@ -442,7 +440,7 @@ abstract class PackedArenaObject extends ArenaObject {
} }
alloc() { alloc() {
if (this.nativePtr === null) { if (!this.nativePtr) {
this.nativePtr = emscAlloc.malloc(this.size()); this.nativePtr = emscAlloc.malloc(this.size());
} }
} }
@ -466,7 +464,7 @@ abstract class PackedArenaObject extends ArenaObject {
b = (b + 256) % 256; b = (b + 256) % 256;
bytes.push("0".concat(b.toString(16)).slice(-2)); bytes.push("0".concat(b.toString(16)).slice(-2));
} }
let lines = []; let lines: string[] = [];
for (let i = 0; i < bytes.length; i += 8) { for (let i = 0; i < bytes.length; i += 8) {
lines.push(bytes.slice(i, i + 8).join(",")); lines.push(bytes.slice(i, i + 8).join(","));
} }
@ -482,7 +480,7 @@ export class AmountNbo extends PackedArenaObject {
toJson(): any { toJson(): any {
let a = new DefaultArena(); let a = new DefaultArena();
let am = new Amount(null, a); let am = new Amount(undefined, a);
am.fromNbo(this); am.fromNbo(this);
let json = am.toJson(); let json = am.toJson();
a.destroy(); a.destroy();
@ -508,7 +506,7 @@ export class EddsaPrivateKey extends PackedArenaObject {
return obj; return obj;
} }
static fromCrock: (string) => EddsaPrivateKey; static fromCrock: (s: string) => EddsaPrivateKey;
} }
mixinStatic(EddsaPrivateKey, fromCrock); mixinStatic(EddsaPrivateKey, fromCrock);
@ -521,7 +519,7 @@ function fromCrock(s: string) {
} }
function mixin(obj, method, name?: string) { function mixin(obj: any, method: any, name?: string) {
if (!name) { if (!name) {
name = method.name; name = method.name;
} }
@ -532,7 +530,7 @@ function mixin(obj, method, name?: string) {
} }
function mixinStatic(obj, method, name?: string) { function mixinStatic(obj: any, method: any, name?: string) {
if (!name) { if (!name) {
name = method.name; name = method.name;
} }
@ -595,7 +593,7 @@ export class RsaBlindingKeySecret extends PackedArenaObject {
return o; return o;
} }
static fromCrock: (string) => RsaBlindingKeySecret; static fromCrock: (s: string) => RsaBlindingKeySecret;
} }
mixinStatic(RsaBlindingKeySecret, fromCrock); mixinStatic(RsaBlindingKeySecret, fromCrock);
@ -622,9 +620,9 @@ export class ByteArray extends PackedArenaObject {
return this.allocatedSize; return this.allocatedSize;
} }
constructor(desiredSize: number, init: number, a?: Arena) { constructor(desiredSize: number, init?: number, a?: Arena) {
super(a); super(a);
if (init === undefined || init === null) { if (init === undefined) {
this.nativePtr = emscAlloc.malloc(desiredSize); this.nativePtr = emscAlloc.malloc(desiredSize);
} else { } else {
this.nativePtr = init; this.nativePtr = init;
@ -642,7 +640,7 @@ export class ByteArray extends PackedArenaObject {
let hstr = emscAlloc.malloc(s.length + 1); let hstr = emscAlloc.malloc(s.length + 1);
Module.writeStringToMemory(s, hstr); Module.writeStringToMemory(s, hstr);
let decodedLen = Math.floor((s.length * 5) / 8); let decodedLen = Math.floor((s.length * 5) / 8);
let ba = new ByteArray(decodedLen, null, a); let ba = new ByteArray(decodedLen, undefined, a);
let res = emsc.string_to_data(hstr, s.length, ba.nativePtr, decodedLen); let res = emsc.string_to_data(hstr, s.length, ba.nativePtr, decodedLen);
emsc.free(hstr); emsc.free(hstr);
if (res != GNUNET_OK) { if (res != GNUNET_OK) {
@ -899,11 +897,11 @@ interface Encodeable {
encode(arena?: Arena): ByteArray; encode(arena?: Arena): ByteArray;
} }
function makeEncode(encodeFn) { function makeEncode(encodeFn: any) {
function encode(arena?: Arena) { function encode(arena?: Arena) {
let ptr = emscAlloc.malloc(PTR_SIZE); let ptr = emscAlloc.malloc(PTR_SIZE);
let len = encodeFn(this.getNative(), ptr); let len = encodeFn(this.getNative(), ptr);
let res = new ByteArray(len, null, arena); let res = new ByteArray(len, undefined, arena);
res.setNative(Module.getValue(ptr, '*')); res.setNative(Module.getValue(ptr, '*'));
emsc.free(ptr); emsc.free(ptr);
return res; return res;

View File

@ -24,7 +24,7 @@
import {AmountJson} from "./types"; import {AmountJson} from "./types";
export function substituteFulfillmentUrl(url: string, vars) { export function substituteFulfillmentUrl(url: string, vars: any) {
url = url.replace("${H_contract}", vars.H_contract); url = url.replace("${H_contract}", vars.H_contract);
url = url.replace("${$}", "$"); url = url.replace("${$}", "$");
return url; return url;
@ -42,7 +42,7 @@ export function amountToPretty(amount: AmountJson): string {
* *
* See http://api.taler.net/wallet.html#general * See http://api.taler.net/wallet.html#general
*/ */
export function canonicalizeBaseUrl(url) { export function canonicalizeBaseUrl(url: string) {
let x = new URI(url); let x = new URI(url);
if (!x.protocol()) { if (!x.protocol()) {
x.protocol("https"); x.protocol("https");
@ -54,10 +54,10 @@ export function canonicalizeBaseUrl(url) {
} }
export function parsePrettyAmount(pretty: string): AmountJson { export function parsePrettyAmount(pretty: string): AmountJson|undefined {
const res = /([0-9]+)(.[0-9]+)?\s*(\w+)/.exec(pretty); const res = /([0-9]+)(.[0-9]+)?\s*(\w+)/.exec(pretty);
if (!res) { if (!res) {
return null; return undefined;
} }
return { return {
value: parseInt(res[1], 10), value: parseInt(res[1], 10),

View File

@ -66,19 +66,19 @@ export class BrowserHttpLib {
} }
postJson(url: string|uri.URI, body) { postJson(url: string|uri.URI, body: any) {
return this.req("post", url, {req: JSON.stringify(body)}); return this.req("post", url, {req: JSON.stringify(body)});
} }
postForm(url: string|uri.URI, form) { postForm(url: string|uri.URI, form: any) {
return this.req("post", url, {req: form}); return this.req("post", url, {req: form});
} }
} }
export class RequestException { export class RequestException {
constructor(detail) { constructor(detail: any) {
} }
} }

View File

@ -392,5 +392,5 @@ export interface CheckRepurchaseResult {
export interface Notifier { export interface Notifier {
notify(); notify(): void;
} }

View File

@ -26,11 +26,11 @@
import MithrilComponent = _mithril.MithrilComponent; import MithrilComponent = _mithril.MithrilComponent;
import {substituteFulfillmentUrl} from "../lib/wallet/helpers"; import {substituteFulfillmentUrl} from "../lib/wallet/helpers";
import m from "mithril"; import m from "mithril";
import {Contract} from "../lib/wallet/types"; import {Contract, AmountJson} from "../lib/wallet/types";
"use strict"; "use strict";
function prettyAmount(amount) { function prettyAmount(amount: AmountJson) {
let v = amount.value + amount.fraction / 1e6; let v = amount.value + amount.fraction / 1e6;
return `${v.toFixed(2)} ${amount.currency}`; return `${v.toFixed(2)} ${amount.currency}`;
} }
@ -40,7 +40,7 @@ const Details = {
controller() { controller() {
return {collapsed: m.prop(true)}; return {collapsed: m.prop(true)};
}, },
view(ctrl, contract: Contract) { view(ctrl: any, contract: Contract) {
if (ctrl.collapsed()) { if (ctrl.collapsed()) {
return m("div", [ return m("div", [
m("button.linky", { m("button.linky", {
@ -71,11 +71,11 @@ export function main() {
let offer = JSON.parse(query.offer); let offer = JSON.parse(query.offer);
console.dir(offer); console.dir(offer);
let contract = offer.contract; let contract = offer.contract;
let error = null; let error: string|null = null;
let payDisabled = true; let payDisabled = true;
var Contract = { var Contract = {
view(ctrl) { view(ctrl: any) {
return [ return [
m("p", m("p",
i18n.parts`${m("strong", contract.merchant.name)} i18n.parts`${m("strong", contract.merchant.name)}

View File

@ -41,10 +41,10 @@ import {getReserveCreationInfo} from "../lib/wallet/wxApi";
*/ */
class DelayTimer { class DelayTimer {
ms: number; ms: number;
f; f: () => void;
timerId: number = null; timerId: number|undefined = undefined;
constructor(ms: number, f) { constructor(ms: number, f: () => void) {
this.f = f; this.f = f;
this.ms = ms; this.ms = ms;
} }
@ -58,7 +58,7 @@ class DelayTimer {
} }
stop() { stop() {
if (this.timerId !== null) { if (this.timerId != undefined) {
window.clearTimeout(this.timerId); window.clearTimeout(this.timerId);
} }
} }
@ -67,11 +67,10 @@ class DelayTimer {
class Controller { class Controller {
url = m.prop<string>(); url = m.prop<string>();
statusString = null; statusString: string | null = null;
isValidExchange = false; isValidExchange = false;
reserveCreationInfo: ReserveCreationInfo = null; reserveCreationInfo?: ReserveCreationInfo;
private timer: DelayTimer; private timer: DelayTimer;
private request: XMLHttpRequest;
amount: AmountJson; amount: AmountJson;
callbackUrl: string; callbackUrl: string;
wtTypes: string[]; wtTypes: string[];
@ -97,7 +96,7 @@ class Controller {
private update() { private update() {
this.timer.stop(); this.timer.stop();
const doUpdate = () => { const doUpdate = () => {
this.reserveCreationInfo = null; this.reserveCreationInfo = undefined;
if (!this.url()) { if (!this.url()) {
this.statusString = i18n`Error: URL is empty`; this.statusString = i18n`Error: URL is empty`;
m.redraw(true); m.redraw(true);
@ -126,7 +125,7 @@ class Controller {
.catch((e) => { .catch((e) => {
console.log("get exchange info rejected"); console.log("get exchange info rejected");
if (e.hasOwnProperty("httpStatus")) { if (e.hasOwnProperty("httpStatus")) {
this.statusString = `Error: request failed with status ${this.request.status}`; this.statusString = `Error: request failed with status ${e.httpStatus}`;
} else if (e.hasOwnProperty("errorResponse")) { } else if (e.hasOwnProperty("errorResponse")) {
let resp = e.errorResponse; let resp = e.errorResponse;
this.statusString = `Error: ${resp.error} (${resp.hint})`; this.statusString = `Error: ${resp.error} (${resp.hint})`;
@ -143,11 +142,7 @@ class Controller {
reset() { reset() {
this.isValidExchange = false; this.isValidExchange = false;
this.statusString = null; this.statusString = null;
this.reserveCreationInfo = null; this.reserveCreationInfo = undefined;
if (this.request) {
this.request.abort();
this.request = null;
}
} }
confirmReserve(rci: ReserveCreationInfo, confirmReserve(rci: ReserveCreationInfo,
@ -155,7 +150,7 @@ class Controller {
amount: AmountJson, amount: AmountJson,
callback_url: string) { callback_url: string) {
const d = {exchange, amount}; const d = {exchange, amount};
const cb = (rawResp) => { const cb = (rawResp: any) => {
if (!rawResp) { if (!rawResp) {
throw Error("empty response"); throw Error("empty response");
} }
@ -195,8 +190,8 @@ class Controller {
} }
function view(ctrl: Controller): any { function view(ctrl: Controller): any {
let controls = []; let controls: any[] = [];
let mx = (x, ...args) => controls.push(m(x, ...args)); let mx = (x: any, ...args: any[]) => controls.push(m(x, ...args));
mx("p", mx("p",
i18n.parts`You are about to withdraw ${m("strong", amountToPretty( i18n.parts`You are about to withdraw ${m("strong", amountToPretty(
@ -210,8 +205,8 @@ function view(ctrl: Controller): any {
} }
function viewSimple(ctrl: Controller) { function viewSimple(ctrl: Controller) {
let controls = []; let controls: any[] = [];
let mx = (x, ...args) => controls.push(m(x, ...args)); let mx = (x: any, ...args: any[]) => controls.push(m(x, ...args));
if (ctrl.statusString) { if (ctrl.statusString) {
mx("p", "Error: ", ctrl.statusString); mx("p", "Error: ", ctrl.statusString);
@ -221,9 +216,9 @@ function viewSimple(ctrl: Controller) {
} }
}, "advanced options"); }, "advanced options");
} }
else if (ctrl.reserveCreationInfo) { else if (ctrl.reserveCreationInfo != undefined) {
mx("button.accept", { mx("button.accept", {
onclick: () => ctrl.confirmReserve(ctrl.reserveCreationInfo, onclick: () => ctrl.confirmReserve(ctrl.reserveCreationInfo!,
ctrl.url(), ctrl.url(),
ctrl.amount, ctrl.amount,
ctrl.callbackUrl), ctrl.callbackUrl),
@ -249,11 +244,11 @@ function viewSimple(ctrl: Controller) {
function viewComplex(ctrl: Controller) { function viewComplex(ctrl: Controller) {
let controls = []; let controls: any[] = [];
let mx = (x, ...args) => controls.push(m(x, ...args)); let mx = (x: any, ...args: any[]) => controls.push(m(x, ...args));
mx("button.accept", { mx("button.accept", {
onclick: () => ctrl.confirmReserve(ctrl.reserveCreationInfo, onclick: () => ctrl.confirmReserve(ctrl.reserveCreationInfo!,
ctrl.url(), ctrl.url(),
ctrl.amount, ctrl.amount,
ctrl.callbackUrl), ctrl.callbackUrl),
@ -314,8 +309,8 @@ function viewComplex(ctrl: Controller) {
function renderReserveCreationDetails(rci: ReserveCreationInfo) { function renderReserveCreationDetails(rci: ReserveCreationInfo) {
let denoms = rci.selectedDenoms; let denoms = rci.selectedDenoms;
let countByPub = {}; let countByPub: {[s: string]: number} = {};
let uniq = []; let uniq: Denomination[] = [];
denoms.forEach((x: Denomination) => { denoms.forEach((x: Denomination) => {
let c = countByPub[x.denom_pub] || 0; let c = countByPub[x.denom_pub] || 0;
@ -358,7 +353,7 @@ function renderReserveCreationDetails(rci: ReserveCreationInfo) {
function getSuggestedExchange(currency: string): Promise<string> { function getSuggestedExchange(currency: string): Promise<string> {
// TODO: make this request go to the wallet backend // TODO: make this request go to the wallet backend
// Right now, this is a stub. // Right now, this is a stub.
const defaultExchange = { const defaultExchange: {[s: string]: string} = {
"KUDOS": "https://exchange.demo.taler.net", "KUDOS": "https://exchange.demo.taler.net",
"PUDOS": "https://exchange.test.taler.net", "PUDOS": "https://exchange.test.taler.net",
}; };

View File

@ -21,30 +21,33 @@
* @author Florian Dold * @author Florian Dold
*/ */
function replacer(match, pIndent, pKey, pVal, pEnd) { function replacer(match: string, pIndent: string, pKey: string, pVal: string,
pEnd: string) {
var key = '<span class=json-key>'; var key = '<span class=json-key>';
var val = '<span class=json-value>'; var val = '<span class=json-value>';
var str = '<span class=json-string>'; var str = '<span class=json-string>';
var r = pIndent || ''; var r = pIndent || '';
if (pKey) if (pKey) {
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: '; r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
if (pVal) }
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>'; if (pVal) {
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
}
return r + (pEnd || ''); return r + (pEnd || '');
} }
function prettyPrint(obj) { function prettyPrint(obj: any) {
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg; var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
return JSON.stringify(obj, null, 3) return JSON.stringify(obj, null as any, 3)
.replace(/&/g, '&amp;').replace(/\\"/g, '&quot;') .replace(/&/g, '&amp;').replace(/\\"/g, '&quot;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;') .replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(jsonLine, replacer); .replace(jsonLine, replacer);
} }
document.addEventListener("DOMContentLoaded", (e) => { document.addEventListener("DOMContentLoaded", () => {
chrome.runtime.sendMessage({type:'dump-db'}, (resp) => { chrome.runtime.sendMessage({type: 'dump-db'}, (resp) => {
document.getElementById('dump').innerHTML = prettyPrint(resp); document.getElementById('dump').innerHTML = prettyPrint(resp);
}); });
}); });

View File

@ -29,12 +29,15 @@
"use strict"; "use strict";
import {substituteFulfillmentUrl} from "../lib/wallet/helpers"; import {substituteFulfillmentUrl} from "../lib/wallet/helpers";
import BrowserClickedEvent = chrome.browserAction.BrowserClickedEvent;
import {Wallet} from "../lib/wallet/wallet";
import {AmountJson} from "../lib/wallet/types";
declare var m: any; declare var m: any;
declare var i18n: any; declare var i18n: any;
function onUpdateNotification(f) { function onUpdateNotification(f: () => void) {
let port = chrome.runtime.connect({name: "notifications"}); let port = chrome.runtime.connect({name: "notifications"});
port.onMessage.addListener((msg, port) => { port.onMessage.addListener((msg, port) => {
f(); f();
@ -56,7 +59,7 @@ export function main() {
console.log("this is popup"); console.log("this is popup");
function makeTab(target, name) { function makeTab(target: string, name: string) {
let cssClass = ""; let cssClass = "";
if (target == m.route()) { if (target == m.route()) {
cssClass = "active"; cssClass = "active";
@ -79,8 +82,8 @@ namespace WalletNavBar {
} }
function openInExtension(element, isInitialized) { function openInExtension(element: HTMLAnchorElement, isInitialized: boolean) {
element.addEventListener("click", (e) => { element.addEventListener("click", (e: Event) => {
chrome.tabs.create({ chrome.tabs.create({
"url": element.href "url": element.href
}); });
@ -94,7 +97,7 @@ namespace WalletBalance {
} }
class Controller { class Controller {
myWallet; myWallet: any;
gotError = false; gotError = false;
constructor() { constructor() {
@ -128,7 +131,7 @@ namespace WalletBalance {
if (!wallet) { if (!wallet) {
throw Error("Could not retrieve wallet"); throw Error("Could not retrieve wallet");
} }
let listing = _.map(wallet, x => m("p", formatAmount(x))); let listing = _.map(wallet, (x: any) => m("p", formatAmount(x)));
if (listing.length > 0) { if (listing.length > 0) {
return listing; return listing;
} }
@ -141,13 +144,13 @@ namespace WalletBalance {
} }
function formatTimestamp(t) { function formatTimestamp(t: number) {
let x = new Date(t); let x = new Date(t);
return x.toLocaleString(); return x.toLocaleString();
} }
function formatAmount(amount) { function formatAmount(amount: AmountJson) {
let v = amount.value + amount.fraction / 1e6; let v = amount.value + amount.fraction / 1e6;
return `${v.toFixed(2)} ${amount.currency}`; return `${v.toFixed(2)} ${amount.currency}`;
} }
@ -158,7 +161,7 @@ function abbrevKey(s: string) {
} }
function retryPayment(url, contractHash) { function retryPayment(url: string, contractHash: string) {
return function() { return function() {
chrome.tabs.create({ chrome.tabs.create({
"url": substituteFulfillmentUrl(url, "url": substituteFulfillmentUrl(url,
@ -168,7 +171,7 @@ function retryPayment(url, contractHash) {
} }
function formatHistoryItem(historyItem) { function formatHistoryItem(historyItem: any) {
const d = historyItem.detail; const d = historyItem.detail;
const t = historyItem.timestamp; const t = historyItem.timestamp;
console.log("hist item", historyItem); console.log("hist item", historyItem);
@ -210,7 +213,7 @@ namespace WalletHistory {
} }
class Controller { class Controller {
myHistory; myHistory: any;
gotError = false; gotError = false;
constructor() { constructor() {
@ -287,7 +290,7 @@ var WalletDebug = {
}; };
function openExtensionPage(page) { function openExtensionPage(page: string) {
return function() { return function() {
chrome.tabs.create({ chrome.tabs.create({
"url": chrome.extension.getURL(page) "url": chrome.extension.getURL(page)
@ -296,7 +299,7 @@ function openExtensionPage(page) {
} }
function openTab(page) { function openTab(page: string) {
return function() { return function() {
chrome.tabs.create({ chrome.tabs.create({
"url": page "url": page

View File

@ -1,9 +1,9 @@
import * as Emsc from '../../lib/wallet/emscriptif'; import * as Emsc from '../../lib/wallet/emscriptif';
declare var HttpMockLib; declare var HttpMockLib: any;
export function declareTests(assert, context, it) { export function declareTests(assert: any, context: any, it: any) {
it("calls native emscripten code", function() { it("calls native emscripten code", function() {
let x = new Emsc.Amount({value: 42, fraction: 42, currency: "EUR"}); let x = new Emsc.Amount({value: 42, fraction: 42, currency: "EUR"});