This commit is contained in:
yushulx
2018-02-08 10:33:29 +08:00
6086 changed files with 83073 additions and 165739 deletions

View File

@@ -256,7 +256,7 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat
#### I want to update a package to a new major version
Before making your change, please create a new subfolder with the current version e.g. `v2`, and copy existing files to it. You will need to:
If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to:
1. Update the relative paths in `tsconfig.json` as well as `tslint.json`.
2. Add path mapping rules to ensure that tests are running against the intended version.
@@ -279,7 +279,8 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
}
```
Please note that unless upgrading something backwards-compatible like `node`, all packages depending of the updated package need a path mapping to it, as well as packages depending on *those*.
If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version.
For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`;
transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).

View File

@@ -6,6 +6,12 @@
"sourceRepoURL": "https://github.com/betterwaysystems/packer",
"asOfVersion": "1.1.3"
},
{
"libraryName": "Ably Realtime and Rest client library",
"typingsPackageName": "ably",
"sourceRepoURL": "https://www.ably.io/",
"asOfVersion": "1.0.0"
},
{
"libraryName": "ag-grid",
"typingsPackageName": "ag-grid",
@@ -78,6 +84,12 @@
"sourceRepoURL": "https://github.com/AlexTeixeira/Askmethat-Rating",
"asOfVersion": "0.4.0"
},
{
"libraryName": "assertion-error",
"typingsPackageName": "assertion-error",
"sourceRepoURL": "https://github.com/chaijs/assertion-error",
"asOfVersion": "1.1.0"
},
{
"libraryName": "asyncblock",
"typingsPackageName": "asyncblock",
@@ -582,6 +594,12 @@
"sourceRepoURL": "https://github.com/panuhorsmalahti/gulp-tslint",
"asOfVersion": "4.2.0"
},
{
"libraryName": "gulp-typedoc",
"typingsPackageName": "gulp-typedoc",
"sourceRepoURL": "https://github.com/rogierschouten/gulp-typedoc",
"asOfVersion": "2.2.0"
},
{
"libraryName": "gulp-typescript",
"typingsPackageName": "gulp-typescript",
@@ -798,6 +816,12 @@
"sourceRepoURL": "https://linqjs.codeplex.com/",
"asOfVersion": "2.2.33"
},
{
"libraryName": "Linq4JS",
"typingsPackageName": "linq4js",
"sourceRepoURL": "https://github.com/morrisjdev/Linq4JS",
"asOfVersion": "2.1.8"
},
{
"libraryName": "LinqSharp",
"typingsPackageName": "linqsharp",
@@ -810,6 +834,12 @@
"sourceRepoURL": "https://github.com/localForage/localForage",
"asOfVersion": "0.0.34"
},
{
"libraryName": "localforage-cordovasqlitedriver",
"typingsPackageName": "localforage-cordovasqlitedriver",
"sourceRepoURL": "https://github.com/thgreasi/localForage-cordovaSQLiteDriver",
"asOfVersion": "1.5.0"
},
{
"libraryName": "lodash-decorators",
"typingsPackageName": "lodash-decorators",
@@ -912,6 +942,12 @@
"sourceRepoURL": "https://github.com/theoephraim/node-pg-migrate#readme",
"asOfVersion": "2.15.0"
},
{
"libraryName": "node-waves",
"typingsPackageName": "node-waves",
"sourceRepoURL": "http://fian.my.id/Waves",
"asOfVersion": "0.7.6"
},
{
"libraryName": "Normalizr",
"typingsPackageName": "normalizr",
@@ -1194,6 +1230,12 @@
"sourceRepoURL": "https://github.com/EnoF/rest-io",
"asOfVersion": "4.1.0"
},
{
"libraryName": "rollup",
"typingsPackageName": "rollup",
"sourceRepoURL": "https://github.com/rollup/rollup",
"asOfVersion": "0.54.0"
},
{
"libraryName": "route-recognizer",
"typingsPackageName": "route-recognizer",
@@ -1482,6 +1524,12 @@
"sourceRepoURL": "https://webgme.org",
"asOfVersion": "2.11.0"
},
{
"libraryName": "Webix UI",
"typingsPackageName": "webix",
"sourceRepoURL": "http://webix.com",
"asOfVersion": "5.1.1"
},
{
"libraryName": "wolfy87-eventemitter",
"typingsPackageName": "wolfy87-eventemitter",
@@ -1512,6 +1560,12 @@
"sourceRepoURL": "https://github.com/PeculiarVentures/xadesjs",
"asOfVersion": "2.0.2"
},
{
"libraryName": "xhr-mock",
"typingsPackageName": "xhr-mock",
"sourceRepoURL": "https://github.com/jameslnewell/xhr-mock#readme",
"asOfVersion": "2.0.0"
},
{
"libraryName": "xlsx",
"typingsPackageName": "xlsx",
@@ -1530,6 +1584,18 @@
"sourceRepoURL": "github.com/node-xmpp/node-xmpp/",
"asOfVersion": "1.2.0"
},
{
"libraryName": "xterm.js",
"typingsPackageName": "xterm",
"sourceRepoURL": "https://github.com/sourcelair/xterm.js/",
"asOfVersion": "3.0.0"
},
{
"libraryName": "yFiles for HTML",
"typingsPackageName": "yfiles",
"sourceRepoURL": "none",
"asOfVersion": "2.1.0"
},
{
"libraryName": "zetapush-js",
"typingsPackageName": "zetapush-js",

View File

@@ -5,7 +5,7 @@
import * as fs from 'fs';
import * as path from 'path';
const home = path.join(__dirname, '..');
const home = path.join(__dirname, "..", "types");
for (const dirName of fs.readdirSync(home)) {
if (dirName.startsWith(".") || dirName === "node_modules" || dirName === "scripts") {

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,253 +0,0 @@
import * as Ably from 'ably';
declare const console: { log(message: any): void };
const ApiKey = 'appId.keyId:secret';
const client = new Ably.Realtime(ApiKey);
const restClient = new Ably.Rest(ApiKey);
// Connection
// Successful connection:
client.connection.on('connected', () => {
// successful connection
});
// Failed connection:
client.connection.on('failed', () => {
// failed connection
});
// Subscribing to a channel
const channel = client.channels.get('test');
channel.subscribe(message => {
message.name; // 'greeting'
message.data; // 'Hello World!'
});
// Only certain events:
channel.subscribe('myEvent', message => {
message.name; // 'myEvent'
message.data; // 'myData'
});
// Publishing to a channel
// Publish a single message with name and data
channel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
channel.publish('greeting', 'Hello World!', err => {
if (err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
});
// Publish several messages at once
channel.publish([{name: 'greeting', data: 'Hello World!'}], () => { });
// Querying the History
channel.history((err, messagesPage) => {
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { nextPage; }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards'}, (err, messagesPage) => {
console.log(messagesPage.items.length);
});
// Presence on a channel
// Getting presence:
channel.presence.get(presenceSet => {
presenceSet; // array of PresenceMessages
});
// Note that presence#get on a realtime channel does not return a PaginatedResult, as the library maintains a local copy of the presence set.
// Entering (and leaving) the presence set:
channel.presence.enter('my status', err => {
// now I am entered
});
channel.presence.update('new status', err => {
// my presence data is updated
});
channel.presence.leave(null, err => {
// I've left the presence set
});
channel.presence.enterClient('myClientId', 'status', err => {
});
// and similiarly, updateClient and leaveClient
// Querying the Presence History
channel.presence.history((err, messagesPage) => { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Symmetrical end-to-end encrypted payloads on a channel
// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key.
// The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption
// Generate a random 256-bit key for demonstration purposes (in
// practice you need to create one and distribute it to clients yourselves)
Ably.Realtime.Crypto.generateRandomKey((err, key) => {
const channel = client.channels.get('channelName', { cipher: { key } });
channel.subscribe(message => {
message.name; // 'name is not encrypted'
message.data; // 'sensitive data is encrypted'
});
channel.publish('name is not encrypted', 'sensitive data is encrypted');
});
// You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect):
channel.setOptions({cipher: {key: '<KEY>'}}, () => {
// New encryption settings are in effect
});
// Using the REST API
const restChannel = restClient.channels.get('test');
// Publishing to a channel
// Publish a single message with name and data
restChannel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
restChannel.publish('greeting', 'Hello World!', err => {
if (err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
});
// Publish several messages at once
restChannel.publish([{name: 'greeting', data: 'Hello World!'}], () => {});
// Querying the History
restChannel.history((err, messagesPage) => {
messagesPage; // PaginatedResult
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => {}); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Presence on a channel
restChannel.presence.get((err, presencePage) => { // PaginatedResult
presencePage.items; // array of PresenceMessage
presencePage.items[0].data; // payload for first message
presencePage.items.length; // number of messages in the current page of members
presencePage.hasNext(); // true if there are further pages
presencePage.isLast(); // true if this page is the last page
presencePage.next(nextPage => {}); // retrieves the next page as PaginatedResult
});
// Querying the Presence History
restChannel.presence.history((err, messagesPage) => { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Generate Token and Token Request
// See https://www.ably.io/documentation/general/authentication for an explanation of Ably's authentication mechanism.
// Requesting a token:
client.auth.requestToken((err, tokenDetails) => {
// tokenDetails is instance of TokenDetails
// see https://www.ably.io/documentation/rest/authentication/#token-details for its properties
// Now we have the token, we can send it to someone who can instantiate a client with it:
const clientUsingToken = new Ably.Realtime(tokenDetails.token);
});
// requestToken can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.requestToken({}, {}, (err, tokenDetails) => { });
// Creating a token request (for example, on a server in response to a request by a client using the authCallback or authUrl mechanisms):
client.auth.createTokenRequest((err, tokenRequest) => {
// now send the tokenRequest back to the client, which will
// use it to request a token and connect to Ably
});
// createTokenRequest can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.createTokenRequest({}, {}, (err, tokenRequest) => { });
// Fetching your application's stats
client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as PaginatedResult
statsPage.items; // array of Stats
statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
statsPage.items.length; // number of stats in the current page of history
statsPage.hasNext(); // true if there are wrther pages
statsPage.isLast(); // true if this page is the last page
statsPage.next((nextPage) => {}); // retrieves the next page as PaginatedResult
});
// Fetching the Ably service time
client.time({}, (err, time) => {}); // time is in ms since epoch
// Getting decoded Message objects from JSON
const messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]);
console.log(messages[0].id);
const message = Ably.Rest.Message.fromEncoded({ id: 'foo' });
console.log(message.id);
// Getting decoded PresenceMessage objects from JSON
const presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]);
console.log(presenceMessages[0].action);
const presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' });
console.log(presenceMessage.action);

473
types/ably/index.d.ts vendored
View File

@@ -1,473 +0,0 @@
// Type definitions for Ably Realtime and Rest client library 0.9
// Project: https://www.ably.io/
// Definitions by: Ably <https://github.com/ably>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export namespace ablyLib {
namespace ChannelState {
type INITIALIZED = 'initialized';
type ATTACHING = 'attaching';
type ATTACHED = "attached";
type DETACHING = "detaching";
type DETACHED = "detached";
type SUSPENDED = "suspended";
type FAILED = "failed";
}
type ChannelState = ChannelState.FAILED | ChannelState.INITIALIZED | ChannelState.SUSPENDED | ChannelState.ATTACHED | ChannelState.ATTACHING | ChannelState.DETACHED | ChannelState.DETACHING;
namespace ConnectionState {
type INITIALIZED = "initialized";
type CONNECTING = "connecting";
type CONNECTED = "connected";
type DISCONNECTED = "disconnected";
type SUSPENDED = "suspended";
type CLOSING = "closing";
type CLOSED = "closed";
type FAILED = "failed";
}
type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED |
ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED;
namespace ConnectionEvent {
type INITIALIZED = "initialized";
type CONNECTING = "connecting";
type CONNECTED = "connected";
type DISCONNECTED = "disconnected";
type SUSPENDED = "suspended";
type CLOSING = "closing";
type CLOSED = "closed";
type FAILED = "failed";
type UPDATE = "update";
}
type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED |
ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE;
namespace PresenceAction {
type ABSENT = "absent";
type PRESENT = "present";
type ENTER = "enter";
type LEAVE = "leave";
type UPDATE = "update";
}
type PresenceAction = PresenceAction.ABSENT | PresenceAction.PRESENT | PresenceAction.ENTER | PresenceAction.LEAVE | PresenceAction.UPDATE;
namespace StatsIntervalGranularity {
type MINUTE = "minute";
type HOUR = "hour";
type DAY = "day";
type MONTH = "month";
}
type StatsIntervalGranularity = StatsIntervalGranularity.MINUTE | StatsIntervalGranularity.HOUR | StatsIntervalGranularity.DAY | StatsIntervalGranularity.MONTH;
namespace HTTPMethods {
type POST = "POST";
type GET = "GET";
}
type HTTPMethods = HTTPMethods.GET | HTTPMethods.POST;
// Interfaces
interface ClientOptions extends AuthOptions {
/**
* When true will automatically connect to Ably when library is instanced. This is true by default
*/
autoConnect?: boolean;
/**
* Optional clientId that can be used to specify the identity for this client. In most cases
* it is preferable to instead specift a clientId in the token issued to this client.
*/
clientId?: string;
defaultTokenParams?: TokenParams;
/**
* When true, messages published on channels by this client will be echoed back to this client.
* This is true by default
*/
echoMessages?: boolean;
/**
* Use this only if you have been provided a dedicated environment by Ably
*/
environment?: string;
/**
* Logger configuration
*/
log?: LogInfo;
port?: number;
/**
* When true, messages will be queued whilst the connection is disconnected. True by default.
*/
queueMessages?: boolean;
restHost?: string;
realtimeHost?: string;
fallbackHosts?: string[];
/**
* Can be used to explicitly recover a connection.
* See https://www.ably.io/documentation/realtime/connection#connection-state-recovery
*/
recover?: standardCallback | string;
/**
* Use a non-secure connection connection. By default, a TLS connection is used to connect to Ably
*/
tls?: boolean;
tlsPort?: number;
/**
* When true, the more efficient MsgPack binary encoding is used.
* When false, JSON text encoding is used.
*/
useBinaryProtocol?: boolean;
}
interface AuthOptions {
/**
* A function which is called when a new token is required.
* The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically
* by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object.
*/
authCallback?(data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void): void;
authHeaders?: { [index: string]: string };
authMethod?: HTTPMethods;
authParams?: { [index: string]: string };
/**
* A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format).
*/
authUrl?: string;
key?: string;
queryTime?: boolean;
token?: TokenDetails | string;
tokenDetails?: TokenDetails;
useTokenAuth?: boolean;
}
interface TokenParams {
capability?: string;
clientId?: string;
nonce?: string;
timestamp?: number;
ttl?: number;
}
interface CipherParams {
algorithm: string;
key: any;
keyLength: number;
mode: string;
}
interface ErrorInfo {
code: number;
message: string;
statusCode: number;
}
interface StatsMessageCount {
count: number;
data: number;
}
interface StatsMessageTypes {
all: StatsMessageCount;
messages: StatsMessageCount;
presence: StatsMessageCount;
}
interface StatsRequestCount {
failed: number;
refused: number;
succeeded: number;
}
interface StatsResourceCount {
mean: number;
min: number;
opened: number;
peak: number;
refused: number;
}
interface StatsConnectionTypes {
all: StatsResourceCount;
plain: StatsResourceCount;
tls: StatsResourceCount;
}
interface StatsMessageTraffic {
all: StatsMessageTypes;
realtime: StatsMessageTypes;
rest: StatsMessageTypes;
webhook: StatsMessageTypes;
}
interface TokenDetails {
capability: string;
clientId?: string;
expires: number;
issued: number;
token: string;
}
interface TokenRequest {
capability: string;
clientId?: string;
keyName: string;
mac: string;
nonce: string;
timestamp: number;
ttl?: number;
}
interface ChannelOptions {
cipher: any;
}
interface RestPresenceHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
}
interface RestPresenceParams {
limit?: number;
clientId?: string;
connectionId?: string;
}
interface RealtimePresenceParams {
waitForSync?: boolean;
clientId?: string;
connectionId?: string;
}
interface RealtimePresenceHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
untilAttach?: boolean;
}
interface LogInfo {
/**
* A number controlling the verbosity of the output. Valid values are: 0 (no logs), 1 (errors only),
* 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
*/
level?: number;
/**
* A function to handle each line of log output. If handler is not specified, console.log is used.
*/
handler?(...args: any[]): void;
}
interface ChannelEvent {
state: ChannelState;
}
interface ChannelStateChange {
current: ChannelState;
previous: ChannelState;
reason?: ErrorInfo;
resumed: boolean;
}
interface ConnectionStateChange {
current: ConnectionState;
previous: ConnectionState;
reason?: ErrorInfo;
retryIn?: number;
}
// Common Listeners
type paginatedResultCallback<T> = (error: ErrorInfo, results: PaginatedResult<T>) => void;
type standardCallback = (error: ErrorInfo, results: any) => void;
type messageCallback<T> = (message: T) => void;
type errorCallback = (error: ErrorInfo) => void;
type channelEventCallback = (channelEvent: ChannelEvent, changeStateChange: ChannelStateChange) => void;
type connectionEventCallback = (connectionEvent: ConnectionEvent, connectionStateChange: ConnectionStateChange) => void;
type timeCallback = (error: ErrorInfo, time: number) => void;
type realtimePresenceGetCallback = (error: ErrorInfo, messages: PresenceMessage[]) => void;
type tokenDetailsCallback = (error: ErrorInfo, Results: TokenDetails) => void;
type tokenRequestCallback = (error: ErrorInfo, Results: TokenRequest) => void;
type fromEncoded<T> = (JsonObject: any, channelOptions?: ChannelOptions) => T;
type fromEncodedArray<T> = (JsonArray: any[], channelOptions?: ChannelOptions) => T[];
// Internal Classes
class EventEmitter<T> {
on: (eventOrCallback: string | T, callback?: T) => void;
once: (eventOrCallback: string | T, callback?: T) => void;
off: (eventOrCallback?: string | T, callback?: T) => void;
}
// Classes
class Auth {
clientId: string;
authorize: (tokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void;
createTokenRequest: (tokenParams?: TokenParams | tokenRequestCallback, authOptions?: AuthOptions | tokenRequestCallback, callback?: tokenRequestCallback) => void;
requestToken: (TokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void;
}
class Presence {
get: (params: RestPresenceParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
history: (params: RestPresenceHistoryParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
}
class RealtimePresence {
syncComplete: () => boolean;
get: (Params: realtimePresenceGetCallback | RealtimePresenceParams, callback?: realtimePresenceGetCallback) => void;
history: (ParamsOrCallback: RealtimePresenceHistoryParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
subscribe: (presenceOrCallback: PresenceAction | messageCallback<PresenceMessage>, listener?: messageCallback<PresenceMessage>) => void;
unsubscribe: (presence?: PresenceAction, listener?: messageCallback<PresenceMessage>) => void;
enter: (data?: errorCallback | any, callback?: errorCallback) => void;
update: (data?: errorCallback | any, callback?: errorCallback) => void;
leave: (data?: errorCallback | any, callback?: errorCallback) => void;
enterClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
updateClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
leaveClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
}
class Channel {
name: string;
presence: Presence;
history: (paramsOrCallback?: RestPresenceHistoryParams | paginatedResultCallback<Message>, callback?: paginatedResultCallback<Message>) => void;
publish: (messagesOrName: any, messagedataOrCallback?: errorCallback | any, callback?: errorCallback) => void;
}
class RealtimeChannel extends EventEmitter<channelEventCallback> {
name: string;
errorReason: ErrorInfo;
state: ChannelState;
presence: RealtimePresence;
attach: (callback?: standardCallback) => void;
detach: (callback?: standardCallback) => void;
history: (paramsOrCallback?: RealtimePresenceHistoryParams | paginatedResultCallback<Message>, callback?: paginatedResultCallback<Message>) => void;
subscribe: (eventOrCallback: messageCallback<Message> | string, listener?: messageCallback<Message>) => void;
unsubscribe: (eventOrCallback?: messageCallback<Message> | string, listener?: messageCallback<Message>) => void;
publish: (messagesOrName: any, messageDataOrCallback?: errorCallback | any, callback?: errorCallback) => void;
setOptions: (options: any, callback?: errorCallback) => void;
}
class Channels<T> {
get: (name: string, channelOptions?: ChannelOptions) => T;
release: (name: string) => void;
}
class Message {
constructor();
static fromEncoded: fromEncoded<Message>;
static fromEncodedArray: fromEncodedArray<Message>;
clientId: string;
connectionId: string;
data: any;
encoding: string;
extras: any;
id: string;
name: string;
timestamp: number;
}
interface MessageStatic {
fromEncoded: fromEncoded<Message>;
fromEncodedArray: fromEncodedArray<Message>;
}
class PresenceMessage {
constructor();
static fromEncoded: fromEncoded<PresenceMessage>;
static fromEncodedArray: fromEncodedArray<PresenceMessage>;
action: PresenceAction;
clientId: string;
connectionId: string;
data: any;
encoding: string;
id: string;
timestamp: number;
}
interface PresenceMessageStatic {
fromEncoded: fromEncoded<PresenceMessage>;
fromEncodedArray: fromEncodedArray<PresenceMessage>;
}
interface Crypto {
generateRandomKey(callback: (error: ErrorInfo, key: string) => void): void;
}
class Connection extends EventEmitter<connectionEventCallback> {
errorReason: ErrorInfo;
id: string;
key: string;
recoveryKey: string;
serial: number;
state: ConnectionState;
close: () => void;
connect: () => void;
ping: (callback?: (error: ErrorInfo, responseTime: number) => void) => void;
}
class Stats {
all: StatsMessageTypes;
apiRequests: StatsRequestCount;
channels: StatsResourceCount;
connections: StatsConnectionTypes;
inbound: StatsMessageTraffic;
intervalId: string;
outbound: StatsMessageTraffic;
persisted: StatsMessageTypes;
tokenRequests: StatsRequestCount;
}
class PaginatedResult<T> {
items: T[];
first: (results: paginatedResultCallback<T>) => void;
next: (results: paginatedResultCallback<T>) => void;
current: (results: paginatedResultCallback<T>) => void;
hasNext: () => boolean;
isLast: () => boolean;
}
class HttpPaginatedResponse extends PaginatedResult<any> {
items: string[];
statusCode: number;
success: boolean;
errorCode: number;
errorMessage: string;
headers: any;
}
}
export class Rest {
constructor(options: ablyLib.ClientOptions | string);
static Crypto: ablyLib.Crypto;
static Message: ablyLib.MessageStatic;
static PresenceMessage: ablyLib.PresenceMessageStatic;
auth: ablyLib.Auth;
channels: ablyLib.Channels<ablyLib.Channel>;
request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void;
stats: (paramsOrCallback?: ablyLib.paginatedResultCallback<ablyLib.Stats> | any, callback?: ablyLib.paginatedResultCallback<ablyLib.Stats>) => void;
time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void;
}
export class Realtime {
constructor(options: ablyLib.ClientOptions | string);
static Crypto: ablyLib.Crypto;
static Message: ablyLib.MessageStatic;
static PresenceMessage: ablyLib.PresenceMessageStatic;
auth: ablyLib.Auth;
channels: ablyLib.Channels<ablyLib.RealtimeChannel>;
clientId: string;
connection: ablyLib.Connection;
request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void;
stats: (paramsOrCallback?: ablyLib.paginatedResultCallback<ablyLib.Stats> | any, callback?: ablyLib.paginatedResultCallback<ablyLib.Stats>) => void;
close: () => void;
connect: () => void;
time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void;
}

View File

@@ -1,6 +0,0 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-any-union": false
}
}

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp,
Responses, Transactions } from 'actions-on-google';
import * as express from 'express';
import express = require('express');
function testActionsSdk(request: express.Request, response: express.Response) {
const app = new ActionsSdkApp({request, response});

View File

@@ -263,8 +263,8 @@ export interface UserName {
* User's permissioned device location.
*/
export interface DeviceLocation {
/** {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
coordinates: object;
/** Coordinates: {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
coordinates: Coordinates;
/** Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
address: string;
/** Zip code. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */
@@ -273,6 +273,16 @@ export interface DeviceLocation {
city: string;
}
/**
* Coordinates containing latitude and longitude
*/
export interface Coordinates {
/** Latitude coordinate. */
latitude: number;
/** Longitude coordinate. */
longitude: number;
}
/**
* User object.
*/

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
@@ -25,4 +26,4 @@
"transactions.d.ts",
"actions-on-google-tests.ts"
]
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -0,0 +1,44 @@
const collectionToArray = <T>(col: any) => { // tslint:disable-line no-unnecessary-generics
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787925(v=vs.85).aspx
(() => {
const enumUsers = (label: string) => {
const volume = new ActiveXObject('Microsoft.DiskQuota');
volume.Initialize(label, true);
collectionToArray<DiskQuotaTypeLibrary.DIDiskQuotaUser>(volume).forEach(x => {
// Use the QuotaUser object to retrieve or set one or more of the user's disk quota properties
});
};
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787916(v=vs.85).aspx
(() => {
const volume = new ActiveXObject('Microsoft.DiskQuota');
volume.Initialize('MYDISK', true);
ActiveXObject.on(volume, 'OnUserNameChanged', ['pUser'], p => {
// Code to handle the event.
});
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787904(v=vs.85).aspx
(() => {
const dqc = new ActiveXObject('Microsoft.DiskQuota');
dqc.Initialize('MYDISK', true);
const findName = (name: string) => {
try {
return dqc.FindUser(name);
} catch { }
try {
return dqc.FindUser(dqc.TranslateLogonNameToSID(name));
} catch { }
};
})();

152
types/activex-diskquota/index.d.ts vendored Normal file
View File

@@ -0,0 +1,152 @@
// Type definitions for DiskQuotaTypeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.5
declare namespace DiskQuotaTypeLibrary {
// tslint:disable-next-line no-const-enum
const enum AccountStatusConstants {
dqAcctDeleted = 2,
dqAcctInvalid = 3,
dqAcctResolved = 0,
dqAcctUnavailable = 1,
dqAcctUnknown = 4,
dqAcctUnresolved = 5,
}
// tslint:disable-next-line no-const-enum
const enum QuotaStateConstants {
dqStateDisable = 0,
dqStateEnforce = 2,
dqStateTrack = 1,
}
// tslint:disable-next-line no-const-enum
const enum UserNameResolutionConstants {
dqResolveAsync = 2,
dqResolveNone = 0,
dqResolveSync = 1,
}
/** Automation interface for DiskQuotaUser */
class DIDiskQuotaUser {
private 'DiskQuotaTypeLibrary.DIDiskQuotaUser_typekey': DIDiskQuotaUser;
private constructor();
/** Name of user's account container */
readonly AccountContainerName: string;
/** Status of user's account */
readonly AccountStatus: AccountStatusConstants;
/** User's display name */
readonly DisplayName: string;
/** Unique ID number */
readonly ID: number;
/** Invalidate data cached in user object */
Invalidate(): void;
/** User's logon account name */
readonly LogonName: string;
/** User's quota limit (bytes) */
QuotaLimit: number;
/** User's quota limit (text) */
readonly QuotaLimitText: string;
/** User's quota warning threshold (bytes) */
QuotaThreshold: number;
/** User's quota warning threshold (text) */
readonly QuotaThresholdText: string;
/** Quota charged to user (bytes) */
readonly QuotaUsed: number;
/** Quota charged to user (text) */
readonly QuotaUsedText: string;
}
/** Microsoft Disk Quota */
class DiskQuotaControl {
private 'DiskQuotaTypeLibrary.DiskQuotaControl_typekey': DiskQuotaControl;
private constructor();
/** Add a user quota entry by Name */
AddUser(LogonName: string): DIDiskQuotaUser;
/** Default quota limit applied to new volume users (byte value) */
DefaultQuotaLimit: number;
/** Default quota limit applied to new volume users (text string) */
readonly DefaultQuotaLimitText: string;
/** Default warning threshold applied to new volume users (byte value) */
DefaultQuotaThreshold: number;
/** Default warning threshold applied to new volume users (text string) */
readonly DefaultQuotaThresholdText: string;
/** Delete a user quota entry */
DeleteUser(pUser: DIDiskQuotaUser): void;
/** Find a user quota entry by Name */
FindUser(LogonName: string): DIDiskQuotaUser;
/** Promote a user quota entry to the head of the name resolution queue */
GiveUserNameResolutionPriority(pUser: DIDiskQuotaUser): void;
/** Initialize the quota control object for a specified volume */
Initialize(path: string, bReadWrite: boolean): void;
/** Invalidate the cache of user name information */
InvalidateSidNameCache(): void;
/** Write event log entry when user exceeds quota limit */
LogQuotaLimit: boolean;
/** Write event log entry when user exceeds quota warning threshold */
LogQuotaThreshold: boolean;
/** Indicates if quota information is out of date */
readonly QuotaFileIncomplete: boolean;
/** Indicates if quota information is being rebuilt */
readonly QuotaFileRebuilding: boolean;
/** State of the volume's disk quota system */
QuotaState: QuotaStateConstants;
/** Terminate the user name resolution thread */
ShutdownNameResolution(): void;
/** Translates a user logon name to a security ID */
TranslateLogonNameToSID(LogonName: string): string;
/** Control the resolution of user Security IDs to user Names */
UserNameResolution: UserNameResolutionConstants;
}
}
interface ActiveXObject {
on(
obj: DiskQuotaTypeLibrary.DiskQuotaControl, event: 'OnUserNameChanged', argNames: ['pUser'], handler: (
this: DiskQuotaTypeLibrary.DiskQuotaControl, parameter: {readonly pUser: DiskQuotaTypeLibrary.DIDiskQuotaUser}) => void): void;
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
}
interface ActiveXObjectNameMap {
'Microsoft.DiskQuota': DiskQuotaTypeLibrary.DiskQuotaControl;
}
interface EnumeratorConstructor {
new(col: DiskQuotaTypeLibrary.DiskQuotaControl): Enumerator<DiskQuotaTypeLibrary.DIDiskQuotaUser>;
}
interface SafeArray<T = any> {
_brand: SafeArray<T>;
}

View File

@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"activex-diskquota-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -0,0 +1,730 @@
/// <reference types="activex-iwshruntimelibrary" />
const collectionToArray = <T>(col: { Item(index: any): T } | SafeArray<T>) => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
const dict = new ActiveXObject('Scripting.Dictionary');
items.forEach((x, index) => dict.Add(index, x));
return dict.Items() as SafeArray<T>;
};
const VB = {
InputBox: (prompt: string): string => ''
};
const getServer = () => {
const server = new ActiveXObject('FaxComEx.FaxServer');
server.Connect('');
return server;
};
(() => {
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693376(v=vs.85).aspx
const server = new ActiveXObject('FaxComEx.FaxServer');
const document = new ActiveXObject('FaxComEx.FaxDocument');
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692919(v=vs.85).aspx
server.Connect('');
server.Connect('computername');
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693502(v=vs.85).aspx
(() => {
const getInitializedDevice = () => {
const ret = getServer().GetDevices().ItemById(1);
ret.ReceiveMode = FAXCOMEXLib.FAX_DEVICE_RECEIVE_MODE_ENUM.fdrmAUTO_ANSWER;
ret.RingsBeforeAnswer = 5;
ret.SendEnabled = true;
return ret;
};
// saving configuration
let device = getInitializedDevice();
device.Save();
// abandoning changes to configuration, using the Refresh method
device = getInitializedDevice();
device.Refresh();
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693502(v=vs.85).aspx
(() => {
const incomingJob = getServer().Folders.IncomingQueue.GetJobs().Item(1);
incomingJob.Refresh();
const currentPage = incomingJob.CurrentPage;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692922(v=vs.85).aspx
(() => {
const server = getServer();
WScript.Echo(`Server information:
API Version: ${server.APIVersion}
Debug: ${server.Debug}
Build and version: ${server.MajorBuild}.${server.MinorBuild}.${server.MajorVersion}.${server.MinorVersion}
Server name: ${server.ServerName}`);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693455(v=vs.85).aspx
(() => {
const activity = getServer().Activity;
activity.Refresh();
WScript.Echo(`
${activity.IncomingMessages} incoming messages
${activity.OutgoingMessages} outgoing messages
${activity.RoutingMessages} routing messages
${activity.QueuedMessages} queued messages`);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693400(v=vs.85).aspx
(() => {
const device = getServer().GetDevices().Item(1);
device.CSID = 'Accounts payable';
device.Description = 'Primary fax device';
device.ReceiveMode = FAXCOMEXLib.FAX_DEVICE_RECEIVE_MODE_ENUM.fdrmAUTO_ANSWER;
device.RingsBeforeAnswer = 5;
device.SendEnabled = true;
device.TSID = 'Accounts payable';
device.Save();
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692985(v=vs.85).aspx
(() => {
const devices = getServer().GetDevices();
WScript.Echo(`This server has ${devices.Count} fax devices`);
for (let i = 1; i <= devices.Count; i++) {
WScript.Echo(`Device ID for device number ${i} is ${devices.Item(i).Id}`);
}
collectionToArray(devices).forEach(device => {
device.Refresh();
WScript.Echo(`
Device name: ${device.DeviceName}
Provider unique name: ${device.ProviderUniqueName}
Powered off: ${device.PoweredOff}
Receiving now: ${device.ReceivingNow}
Ringing now: ${device.RingingNow}
Sending now: ${device.SendingNow}`);
const routingMethods = new VBArray(device.UsedRoutingMethods).toArray();
routingMethods.forEach((guid, index) => {
WScript.Echo(`Method number ${index} = ${guid}`);
});
device.UseRoutingMethod(routingMethods[0], false);
device.Save();
});
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693486(v=vs.85).aspx
(() => {
const outputRuleInfo = (rule: FAXCOMEXLib.FaxOutboundRoutingRule, index?: number) => {
WScript.Echo(`
Outbound routing rule number: ${index || 'unknown'}
Area code: ${rule.AreaCode}
Country/region code: ${rule.CountryCode}
Device ID: ${rule.DeviceId}
Group name: ${rule.GroupName}
Status: ${rule.Status}
Is device used: ${rule.UseDevice}`
.trim());
};
const server = getServer();
const device = server.GetDevices().Item(1);
const id = device.Id;
const rules = server.OutboundRouting.GetRules();
const outboundRoutingRules = server.OutboundRouting.GetRules();
WScript.Echo(`There are ${outboundRoutingRules.Count} outbound routing rules on this server.`);
collectionToArray(outboundRoutingRules).forEach((rule, index) => {
rule.Refresh();
outputRuleInfo(rule, index);
if (!rule.UseDevice) { return; }
if (VB.InputBox('Do you want to change the device for this rule (Y/N)?') === 'Y') {
const newDeviceID = parseInt(VB.InputBox('Enter new device ID'), 10);
rule.DeviceId = newDeviceID;
rule.Save();
}
});
const msg = `
Do you want to:
1) display an item based on its country/region and area code,
2) remove an item based on its country/region and area code,
3) remove an item based on its item number, or
4) add a rule?
Input 1, 2, 3, 4, or 0 to exit
`.trim();
const result = parseInt(VB.InputBox(msg), 10);
let countryCode: number;
let areaCode: number;
let itemNumber: number;
let rule: FAXCOMEXLib.FaxOutboundRoutingRule;
switch (result) {
case 1:
countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10);
areaCode = parseInt(VB.InputBox('Enter the area code'), 10);
rule = outboundRoutingRules.ItemByCountryAndArea(countryCode, areaCode);
outputRuleInfo(rule);
break;
case 2:
countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10);
areaCode = parseInt(VB.InputBox('Enter the area code'), 10);
outboundRoutingRules.RemoveByCountryAndArea(countryCode, areaCode);
break;
case 3:
itemNumber = parseInt(VB.InputBox('Enter the item number'), 10);
outboundRoutingRules.Remove(itemNumber);
break;
case 4:
countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10);
areaCode = parseInt(VB.InputBox('Enter the area code'), 10);
rule = outboundRoutingRules.Add(countryCode, areaCode, true, '', id);
break;
default:
return;
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693408(v=vs.85).aspx
(() => {
const server = getServer();
const outboundRouting = server.OutboundRouting;
const outboundRoutingGroups = outboundRouting.GetGroups();
const groupName = VB.InputBox('Provide a name for the outbound routing group');
const outboundRoutingGroup = outboundRoutingGroups.Add(groupName);
const devices = collectionToArray(server.GetDevices());
// add the devices to the routing group
devices.forEach(device => outboundRoutingGroup.DeviceIds.Add(device.Id));
// move the last device to the top of the order
outboundRoutingGroup.DeviceIds.SetOrder(devices[devices.length - 1].Id, 1);
// display the number of devices, and the device ID of the first device,to confirm its location in the order
const msg = `
Number of devices: ${outboundRoutingGroup.DeviceIds.Count}
ID of first device: ${outboundRoutingGroup.DeviceIds.Item(1)}
`.trim();
WScript.Echo(msg);
// remove the first device
outboundRoutingGroup.DeviceIds.Remove(1);
WScript.Echo(`There are now ${outboundRoutingGroups.Count} routing groups on the server`);
collectionToArray(outboundRoutingGroups).forEach((routingGroup, index) => {
const msg = `
Routing group number: ${index}
Outbound routing group name: ${routingGroup.Name}
Device status: ${routingGroup.Status}
`.trim();
});
// allow user to remove a routing group
if (VB.InputBox('Do you want to remove a routing group (Y/N)?') === 'N') { return; }
const itemNumber = VB.InputBox('Enter the item number for the group you want to remove');
outboundRoutingGroups.Remove(itemNumber);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa964960(v=vs.85).aspx
(() => {
const accountSet = getServer().FaxAccountSet;
const accounts = collectionToArray(accountSet.GetAccounts());
WScript.Echo(`Number of accounts: ${accounts.length}`);
accounts.forEach(account => WScript.Echo(account.AccountName));
const accountName = VB.InputBox('Enter an account name');
accountSet.AddAccount(accountName);
accountSet.RemoveAccount(accountName);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692952(v=vs.85).aspx
(() => {
const incomingJobs = collectionToArray(getServer().Folders.IncomingQueue.GetJobs());
WScript.Echo(`There are ${incomingJobs.length} jobs in the incoming queue.`);
const n = parseInt(VB.InputBox('Input the number of a job for which you want information'), 10);
const job = incomingJobs[n - 1];
WScript.Echo(`
Available operations: ${job.AvailableOperations}
Caller ID: ${job.CallerId}
CSID: ${job.CSID}
Current page: ${job.CurrentPage}
Device ID: ${job.DeviceId}
Extended status: ${job.ExtendedStatus}
Extended status code: ${job.ExtendedStatusCode}
Job ID: ${job.Id}
Job type: ${job.JobType}
Retries: ${job.Retries}
Routing information: ${job.RoutingInformation}
Size: ${job.Size}
Status: ${job.Status}
Transmission start: ${new Date(job.TransmissionStart)}
Transmission end: ${new Date(job.TransmissionEnd)}
TSID: ${job.TSID}
`.trim());
if (VB.InputBox('Cancel this fax (Y/N)?') === 'Y') {
job.Cancel();
}
if (VB.InputBox('Open this fax (Y/N)?') === 'Y') {
const fileName = VB.InputBox('Enter path to save');
job.CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692914(v=vs.85).aspx
(() => {
const server = new ActiveXObject('FaxComEx.FaxServer');
server.Connect('');
const outgoingQueue = server.Folders.OutgoingQueue;
outgoingQueue.AgeLimit = 2;
outgoingQueue.AllowPersonalCoverPages = true;
outgoingQueue.Blocked = false;
outgoingQueue.Paused = false;
outgoingQueue.Branding = true;
outgoingQueue.DiscountRateStart = new Date(0, 0, 0, 0).getVarDate();
outgoingQueue.DiscountRateStart = new Date(0, 0, 0, 1).getVarDate();
outgoingQueue.UseDeviceTSID = true;
outgoingQueue.Save();
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693393(v=vs.85).aspx
(() => {
const outgoingQueue = getServer().Folders.OutgoingQueue;
outgoingQueue.Refresh();
WScript.Echo(`There are ${outgoingQueue.GetJobs().Count} faxes in the outgoing queue`);
const inputResult = VB.InputBox('Which fax should be displayed (item number or job name)?');
const itemNumber = parseInt(inputResult, 10);
const job =
isNaN(itemNumber) ?
outgoingQueue.GetJob(inputResult) :
outgoingQueue.GetJobs().Item(itemNumber);
WScript.Echo(`
Available operations: ${job.AvailableOperations}
Broadcast receipts grouped? ${job.GroupBroadcastReceipts}
CSID: ${job.CSID}
Current page: ${job.CurrentPage}
Device ID: ${job.DeviceId}
Document name: ${job.DocumentName}
Extended status: ${job.ExtendedStatus}
Extended status code: ${job.ExtendedStatusCode}
Job ID: ${job.Id}
Original scheduled time: ${new Date(job.OriginalScheduledTime)}
Pages: ${job.Pages}
Priority: ${job.Priority}
Receipt type: ${job.ReceiptType}
`.trim());
const fileName = VB.InputBox('Enter path to save');
job.CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
const answer = VB.InputBox(`
Do you want to:
(C) cancel
(P) pause
(R) restart
(E) resume
the job?
`.trim());
switch (answer) {
case 'C':
job.Cancel();
break;
case 'P':
job.Pause();
break;
case 'R':
job.Restart();
break;
case 'E':
job.Resume();
break;
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692936(v=vs.85).aspx
(() => {
const document = new ActiveXObject('FaxComEx.FaxDocument');
document.Body = 'C:\\docs\\body.txt';
document.DocumentName = 'My First Fax';
document.Priority = FAXCOMEXLib.FAX_PRIORITY_TYPE_ENUM.fptHIGH;
document.Recipients.Add('12225550100', 'Bud');
document.AttachFaxToReceipt = true;
document.CoverPageType = FAXCOMEXLib.FAX_COVERPAGE_TYPE_ENUM.fcptSERVER;
document.Note = 'Here is the info you requested';
document.ReceiptAddress = 'someone@example.com';
document.ReceiptType = FAXCOMEXLib.FAX_RECEIPT_TYPE_ENUM.frtMAIL;
document.ScheduleType = FAXCOMEXLib.FAX_SCHEDULE_TYPE_ENUM.fstSPECIFIC_TIME;
document.ScheduleTime = new Date(0, 0, 0, 16, 35, 47).getVarDate();
document.Subject = 'Today\'s fax';
// set sender properties
const sender = document.Sender;
sender.Title = 'Mr.';
sender.Name = 'Bob';
sender.City = 'Cleveland Heights';
sender.State = 'Ohio';
sender.Company = 'Microsoft';
sender.Country = 'USA';
sender.Email = 'someone@microsoft.com';
sender.FaxNumber = '12165555554';
sender.HomePhone = '12165555555';
sender.OfficeLocation = 'Downtown';
sender.OfficePhone = '12165555553';
sender.StreetAddress = '123 Main Street';
sender.TSID = 'Office fax machine';
sender.ZipCode = '44118';
sender.BillingCode = '23A54';
sender.Department = 'Accts Payable';
sender.SaveDefaultSender();
const server = getServer();
const jobID = document.ConnectedSubmit(server);
WScript.Echo(`The job ID is ${jobID}`);
server.Disconnect();
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693479(v=vs.85).aspx
(() => {
const document = new ActiveXObject('FaxComEx.FaxDocument');
document.Body = 'C:\\docs\\body.txt';
document.DocumentName = 'My First Fax';
const recipients = document.Recipients;
recipients.Add('12225550105', 'H');
recipients.Add('12225550104', 'N');
recipients.Add('12225550103', 'G');
WScript.Echo(`Number of recipients: ${recipients.Count}`);
collectionToArray(recipients).forEach((recipient, index) =>
WScript.Echo(`Recipient number ${index}: ${recipient.Name}, ${recipient.FaxNumber}`)
);
document.Sender.LoadDefaultSender();
document.GroupBroadcastReceipts = true;
const jobIDs = document.Submit('');
collectionToArray(jobIDs).forEach(jobID => WScript.Echo(`The job ID is ${jobID}`));
while (recipients.Count > 0) {
recipients.Remove(1);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa964962(v=vs.85).aspx
(() => {
const server = getServer();
const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10);
server.CurrentAccount.Folders.IncomingArchive.Refresh();
const messageIterator = server.Folders.IncomingArchive.GetMessages(prefetchCount);
messageIterator.MoveFirst();
for (let i = 1; i <= prefetchCount; i++) {
if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; }
const message = messageIterator.Message as FAXCOMEXLib.FaxIncomingMessage;
if (messageIterator.AtEOF) {
WScript.Echo(`End of file reached`);
return;
}
if (!message.WasReAssigned) {
if (VB.InputBox('Message not reassigned. Reassign (Y/N)?') === 'Y') {
message.Subject = 'Reassigning message';
message.SenderName = 'Test user';
message.Recipients = VB.InputBox('Enter username, e.g. Domain\\UserName');
message.SenderFaxNumber = '1234';
message.ReAssign();
}
}
messageIterator.MoveNext();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693402(v=vs.85).aspx
(() => {
const server = getServer();
const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10);
server.Folders.OutgoingArchive.Refresh();
const messageIterator = server.Folders.OutgoingArchive.GetMessages(prefetchCount);
messageIterator.MoveFirst();
for (let i = 1; i <= prefetchCount; i++) {
if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; }
if (messageIterator.AtEOF) {
WScript.Echo(`End of file reached`);
return;
}
const message = messageIterator.Message as FAXCOMEXLib.FaxOutgoingMessage;
const fileName = VB.InputBox('Enter path to save');
message.CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
WScript.Echo(`Message information:
CSID: ${message.CSID}
Device name: ${message.DeviceName}
Document name: ${message.DocumentName}
Message ID: ${message.Id}
Original scheduled time: ${new Date(message.OriginalScheduledTime)}
Pages: ${message.Pages}
Recipient fax number: ${message.Recipient.FaxNumber}
Retries: ${message.Retries}
Sender name: ${message.Sender.Name}
Size: ${message.Size}
Subject: ${message.Subject}
Submission ID: ${message.SubmissionId}
Submission time: ${new Date(message.SubmissionTime)}
Transmission end time: ${new Date(message.TransmissionEnd)}
Transmission start time: ${new Date(message.TransmissionStart)}
TSID: ${message.TSID}`);
if (VB.InputBox('Delete this fax from the archive (Y/N)?') === 'Y') {
message.Delete();
}
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693472(v=vs.85).aspx
(() => {
const server = getServer();
const outgoingArchive = server.Folders.OutgoingArchive;
WScript.Echo(`
Age limit: ${outgoingArchive.AgeLimit}
Archive folder: ${outgoingArchive.ArchiveFolder}
High quota mark: ${outgoingArchive.HighQuotaWaterMark}
Low quota water mark: ${outgoingArchive.LowQuotaWaterMark}
Size high: ${outgoingArchive.SizeHigh}
Size low: ${outgoingArchive.SizeLow}
Size quota warning: ${outgoingArchive.SizeQuotaWarning}
Is archive used? ${outgoingArchive.UseArchive}`.trim()
);
const newLimit = VB.InputBox('Set new age limit (enter empty value or Cancel to leave unchanged');
if (newLimit) {
outgoingArchive.AgeLimit = parseInt(newLimit, 10);
}
const messageID = VB.InputBox('Retrieve a message by ID (enter an empty value or press Cancel to exit');
if (messageID) {
const fileName = VB.InputBox('Enter path to save');
outgoingArchive.GetMessage(messageID).CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
}
})();
(() => {
const server = getServer();
const messageIterator = server.Folders.OutgoingArchive.GetMessages();
if (messageIterator.AtEOF) { return; }
messageIterator.MoveFirst();
while (!messageIterator.AtEOF) {
const message = messageIterator.Message;
WScript.Echo(`
Document name: ${message.DocumentName}
ID: ${message.Id}
Transmission end: ${new Date(message.TransmissionEnd)}
Transmission start: ${new Date(message.TransmissionStart)}
`.trim());
messageIterator.MoveNext();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692976(v=vs.85).aspx
(() => {
const server = getServer();
const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10);
server.Folders.IncomingArchive.Refresh();
const messageIterator = server.Folders.IncomingArchive.GetMessages(prefetchCount);
messageIterator.MoveFirst();
for (let i = 1; i <= prefetchCount; i++) {
if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; }
const message = messageIterator.Message as FAXCOMEXLib.FaxIncomingMessage;
if (messageIterator.AtEOF) {
WScript.Echo(`End of file reached`);
return;
}
const fileName = VB.InputBox('Enter path to save TIFF file');
message.CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
messageIterator.MoveNext();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693406(v=vs.85).aspx
(() => {
const server = getServer();
const incomingArchive = server.Folders.IncomingArchive;
incomingArchive.Refresh();
WScript.Echo(`
High quota water mark: ${incomingArchive.HighQuotaWaterMark}
Low quota water mark: ${incomingArchive.LowQuotaWaterMark}
Archive folder: ${incomingArchive.ArchiveFolder}
Age limit: ${incomingArchive.AgeLimit}
Size high: ${incomingArchive.SizeHigh}
Size low: ${incomingArchive.SizeLow}
Is size quota warning on? ${incomingArchive.SizeQuotaWarning}
Is archive used? ${incomingArchive.UseArchive}
`.trim());
incomingArchive.AgeLimit = 4;
incomingArchive.Save();
const messageID = VB.InputBox('Message ID to retrieve information? (Leave empty, or Cancel, to exit)');
if (messageID === '') { return; }
const message = incomingArchive.GetMessage(messageID);
WScript.Echo(`
Caller ID: ${message.CallerId}
CSID: ${message.CSID}
Device name: ${message.DeviceName}
Message ID: ${message.Id}
Number of pages: ${message.Pages}
Retries: ${message.Retries}
Routing information: ${message.RoutingInformation}
Size: ${message.Size}
Transmission start: ${new Date(message.TransmissionStart)}
Transmission end: ${new Date(message.TransmissionEnd)}
TSID: ${message.TSID}
`.trim());
if (VB.InputBox('Delete this message from the archive (Y/N)?') === 'Y') {
message.Delete();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693401(v=vs.85).aspx
(() => {
const server = getServer();
const loggingOptions = server.LoggingOptions;
const activityLogging = loggingOptions.ActivityLogging;
const eventLogging = loggingOptions.EventLogging;
activityLogging.Refresh();
activityLogging.LogIncoming = true;
activityLogging.LogOutgoing = true;
activityLogging.Save();
eventLogging.Refresh();
eventLogging.GeneralEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMED;
eventLogging.InboundEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMAX;
eventLogging.InitEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMAX;
eventLogging.OutboundEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllNONE;
eventLogging.Save();
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693387(v=vs.85).aspx
(() => {
const server = getServer();
const receiptOptions = server.ReceiptOptions;
receiptOptions.Refresh();
WScript.Echo(`
Allowed receipt types: ${receiptOptions.AllowedReceipts}
Authentication types: ${receiptOptions.AuthenticationType}
SMTP port: ${receiptOptions.SMTPPort}
SMTP sender: ${receiptOptions.SMTPSender}
SMTP server: ${receiptOptions.SMTPSender}
Use for inbound routing? ${receiptOptions.UseForInboundRouting}
`.trim());
receiptOptions.AllowedReceipts = FAXCOMEXLib.FAX_RECEIPT_TYPE_ENUM.frtMAIL;
receiptOptions.AuthenticationType = FAXCOMEXLib.FAX_SMTP_AUTHENTICATION_TYPE_ENUM.fsatBASIC;
receiptOptions.SMTPPort = 25;
receiptOptions.SMTPSender = 'someone@example.com';
receiptOptions.SMTPServer = 'My SMTP Server';
receiptOptions.UseForInboundRouting = true;
receiptOptions.Save();
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693462(v=vs.85).aspx
(() => {
const server = getServer();
collectionToArray(server.GetDeviceProviders()).forEach((provider, index) => {
WScript.Echo(`
Debug: ${provider.Debug}
Name: ${provider.FriendlyName}
Image name: ${provider.ImageName}
Init error code: ${provider.InitErrorCode}
Build and version: ${provider.MajorBuild}.${provider.MajorVersion}.${provider.MinorBuild}.${provider.MinorVersion}
Status: ${provider.Status}
TAPI provider: ${provider.TapiProviderName}
Unique name: ${provider.UniqueName}
`.trim());
new VBArray(provider.DeviceIds).toArray().forEach(id => WScript.Echo(id));
});
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693437(v=vs.85).aspx -- for a fax device
(() => {
const server = getServer();
const device = server.GetDevices().Item(1);
const deviceProperty = toSafeArray(1, 2, 3);
const propertyName = '{B1F944B9-9A16-45d1-933A-4060A4871AB0}';
device.SetExtensionProperty(propertyName, deviceProperty);
new VBArray(device.GetExtensionProperty(propertyName)).toArray().forEach(x => WScript.Echo(x));
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693437(v=vs.85).aspx -- for a fax device
(() => {
const server = getServer();
const serverProperty = toSafeArray(4, 2, 3);
const propertyName = `{AC7D0DEE-B6E5-4a44-AF45-835C58CB44D2}`;
server.SetExtensionProperty(propertyName, serverProperty);
new VBArray(server.GetExtensionProperty(propertyName)).toArray().forEach(x => WScript.Echo(x));
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693013(v=vs.85).aspx
(() => {
const server = getServer();
ActiveXObject.on(server, 'OnOutgoingJobAdded', ['pFaxServer', 'bstrJobId'], prm => WScript.Echo('New job added to queue'));
ActiveXObject.on(server, 'OnOutgoingJobChanged', ['pFaxServer', 'bstrJobId', 'pJobStatus'], prm => {
const status = prm.pJobStatus;
WScript.Echo(`
Available operations: ${status.AvailableOperations}
Caller ID: ${status.CallerId}
CSID: ${status.CSID}
Current page: ${status.CurrentPage}
Device ID: ${status.DeviceId}
Extended status: ${status.ExtendedStatus}
Extended status code: ${status.ExtendedStatusCode}
Job type: ${status.JobType}
Pages: ${status.Pages}
Retries: ${status.Retries}
Routing information: ${status.RoutingInformation}
Scheduled time: ${new Date(status.ScheduledTime)}
Size: ${status.Size}
Status: ${status.Status}
Transmission start: ${new Date(status.TransmissionStart)}
TSID: ${status.TSID}
`.trim());
try {
WScript.Echo(`Transmission end: ${new Date(status.TransmissionEnd)}`);
} catch {}
});
ActiveXObject.on(server, 'OnServerShutDown', ['pFaxServer'], prm => WScript.Echo('The local fax server has been shut down'));
server.ListenToServerEvents(
FAXCOMEXLib.FAX_SERVER_EVENTS_TYPE_ENUM.fsetFXSSVC_ENDED +
FAXCOMEXLib.FAX_SERVER_EVENTS_TYPE_ENUM.fsetOUT_QUEUE
);
})();

2053
types/activex-faxcomexlib/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"activex-faxcomexlib-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -0,0 +1,49 @@
const wshn = new ActiveXObject('WScript.Network');
// https://msdn.microsoft.com/en-us/library/s6wt333f(v=vs.84).aspx
// https://msdn.microsoft.com/en-us/library/wck0hkd7(v=vs.84).aspx
// https://msdn.microsoft.com/en-us/library/tte130y1(v=vs.84).aspx
// https://msdn.microsoft.com/en-us/library/3fxhka75(v=vs.84).aspx
(() => {
WScript.Echo('Domain = ' + wshn.UserDomain);
WScript.Echo('Computer Name = ' + wshn.ComputerName);
WScript.Echo('User Name = ' + wshn.UserName);
})();
// https://msdn.microsoft.com/en-us/library/zsdh7hkb(v=vs.84).aspx
wshn.AddWindowsPrinterConnection('\\\\printserv\\DefaultPrinter');
// https://msdn.microsoft.com/en-us/library/kxsdca3c(v=vs.84).aspx
wshn.AddPrinterConnection("LPT1", "\\\\Server\\Print1");
// https://msdn.microsoft.com/en-us/library/t9zt39at(v=vs.84).aspx
// https://msdn.microsoft.com/en-us/library/zhds6k80(v=vs.84).aspx
(() => {
const drives = wshn.EnumNetworkDrives();
const printers = wshn.EnumPrinterConnections();
WScript.Echo("Network drive mappings:");
for (let i = 0; i < drives.length; i += 2) {
WScript.Echo(`Drive ${drives.Item(i)} = ${drives.Item(i + 1)}`);
}
WScript.Echo('');
WScript.Echo("Network printer mappings:");
for (let i = 0; i < printers.length; i += 2) {
WScript.Echo(`Port ${printers.Item(i)} = ${printers.Item(i + 1)}`);
}
})();
// https://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx
wshn.MapNetworkDrive('E:', '\\\\Server\\Public');
// https://msdn.microsoft.com/en-us/library/d16d7wbf(v=vs.84).aspx
wshn.RemoveNetworkDrive('E:');
// https://msdn.microsoft.com/en-us/library/tsbh2yy7(v=vs.84).aspx
wshn.RemovePrinterConnection('\\\\PRN-CORP1\\B41-4523-A', true, true);
// https://msdn.microsoft.com/en-us/library/2ccwwdct(v=vs.84).aspx
(() => {
const printerPath = "\\\\research\\library1";
wshn.AddWindowsPrinterConnection(printerPath);
wshn.SetDefaultPrinter(printerPath);
})();

View File

@@ -0,0 +1,247 @@
// Type definitions for Windows Script Host Object Model - IWshRuntimeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/9bbdkx3k(v=vs.84).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
declare namespace IWshRuntimeLibrary {
// tslint:disable-next-line no-const-enum
const enum ButtonType {
OK,
OKCancel,
AbortRetryIgnore,
YesNoCancel,
YesNo,
RetryCancel,
CancelTryagainContinue
}
// tslint:disable-next-line no-const-enum
const enum IconType {
Stop = 16,
QuestionMark = 32,
ExclamationMakr = 48,
InformationMark = 64,
}
// tslint:disable-next-line no-const-enum
const enum PopupType {
SecondButtonDefault = 256,
ThirdButtonDefault = 512,
Modal = 4096,
RightJustified = 524288,
RTL = 1048576,
}
// tslint:disable-next-line no-const-enum
const enum PopupSelection {
NoButton = -1,
OK = 1,
Cancel = 2,
Abort = 3,
Retry = 4,
Ignore = 5,
Yes = 6,
No = 7,
TryAgain = 10,
Continue = 11,
}
// tslint:disable-next-line no-const-enum
const enum WshExecStatus {
WshFailed = 2,
WshFinished = 1,
WshRunning = 0,
}
// tslint:disable-next-line no-const-enum
const enum WshWindowStyle {
WshHide = 0,
WshMaximizedFocus = 3,
WshMinimizedFocus = 2,
WshMinimizedNoFocus = 6,
WshNormalFocus = 1,
WshNormalNoFocus = 4,
}
class TextStream {
private 'IWshRuntimeLibrary.TextStream_typekey': TextStream;
private constructor();
readonly AtEndOfLine: boolean;
readonly AtEndOfStream: boolean;
Close(): void;
readonly Column: number;
readonly Line: number;
Read(Characters: number): string;
ReadAll(): string;
ReadLine(): string;
Skip(Characters: number): void;
SkipLine(): void;
Write(Text: string): void;
WriteBlankLines(Lines: number): void;
/** @param string [Text=''] */
WriteLine(Text?: string): void;
}
/** Generic Collection Object */
class WshCollection {
private 'IWshRuntimeLibrary.WshCollection_typekey': WshCollection;
private constructor();
Count(): number;
Item(Index: any): any;
readonly length: number;
}
/** Environment Variables Collection Object */
class WshEnvironment {
private 'IWshRuntimeLibrary.WshEnvironment_typekey': WshEnvironment;
private constructor();
Count(): number;
Item(Name: string): string;
readonly length: number;
Remove(Name: string): void;
}
/** WSHExec object */
class WshExec {
private 'IWshRuntimeLibrary.WshExec_typekey': WshExec;
private constructor();
readonly ExitCode: number;
readonly ProcessID: number;
readonly Status: WshExecStatus;
readonly StdErr: TextStream;
readonly StdIn: TextStream;
readonly StdOut: TextStream;
Terminate(): void;
}
/** Network Object */
class WshNetwork {
private 'IWshRuntimeLibrary.WshNetwork_typekey': WshNetwork;
private constructor();
/**
* Adds a remote MS-DOS-based printer connection to your computer system.
* @param LocalName Local name to assign to the connected printer.
* @param RemoteName Name of the remote printer.
* @param UpdateProfile [false] Whether the printer mapping is stored in the current user's profile.
*
* If you are mapping a remote printer using the profile of someone other than current user, you can specify _UserName_ and _Password_.
*/
AddPrinterConnection(LocalName: string, RemoteName: string, UpdateProfile?: boolean, UserName?: string, Password?: string): void;
/**
* @param string Path to printer connection
* @param string [DriverName='']
* @param string [Port='LPT1']
*
* Unlike the **AddPrinterConnection** method, this method allows you to create a printer connection without directing it to a specific port, such as LPT1.
*/
AddWindowsPrinterConnection(PrinterName: string, DriverName?: string, Port?: string): void;
readonly ComputerName: string;
EnumNetworkDrives(): WshCollection;
EnumPrinterConnections(): WshCollection;
/**
* Adds a remote MS-DOS-based printer connection to your computer system.
* @param LocalName Name by which the mapped drive will be known locally
* @param RemoteName Share's UNC name (\\xxx\yyy)
* @param UpdateProfile [false] Whether the printer mapping is stored in the current user's profile.
*
* If you are mapping a network drive using the profile of someone other than current user, you can specify _UserName_ and _Password_.
*/
MapNetworkDrive(LocalName: string, RemoteName: string, UpdateProfile?: boolean, UserName?: string, Password?: string): void;
readonly Organization: string;
/**
* Removes a shared network drive from your computer system
* @param Name Name of the mapped drive you want to remove. This will be the drive letter if the drive has a mapping between a local name (drive letter) and a remote name (UNC name);
* it will be the UNC path if there is no such mapping
* @param Force [false] Remove the connections even if the resource is in use
* @param UpdateProfile [false] Remove the mapping from the user's profile
*/
RemoveNetworkDrive(Name: string, Force?: any, UpdateProfile?: any): void;
/**
* Removes a shared network printer connection from your computer system
* @param Name Name that identifies the printer. Can be a UNC name (in the form `\\xxx\yyy`) or a local name (such as `LPT1`)
* @param Force [false] Remove printer connection even if a user is still connected
* @param UpdateProfile [false] Remove the printer connection from the user's profile
*
* The **RemovePrinterConnection** method removes both Windows and MS-DOS based printer connections. If the printer was connected using the method **AddPrinterConnection**,
* _Name_ must be the printer's local name. If the printer was connected using the **AddWindowsPrinterConnection** method or was added manually (using the Add Printer wizard),
* then _Name_ must be the printer's UNC name.
*/
RemovePrinterConnection(Name: string, Force?: any, UpdateProfile?: any): void;
SetDefaultPrinter(Name: string): void;
readonly Site: string;
readonly UserDomain: string;
readonly UserName: string;
readonly UserProfile: string;
}
/** Shell Object */
class WshShell {
private 'IWshRuntimeLibrary.WshShell_typekey': WshShell;
private constructor();
AppActivate(App: any, Wait?: any): boolean;
CreateShortcut(PathLink: string): any;
CurrentDirectory: string;
Environment(Type?: any): WshEnvironment;
Exec(Command: string): WshExec;
ExpandEnvironmentStrings(Src: string): string;
/** @param string [Target=''] */
LogEvent(Type: any, Message: string, Target?: string): boolean;
Popup(Text: any, SecondsToWait?: number, Title?: string, Type?: ButtonType | IconType | PopupType): PopupSelection;
RegDelete(Name: string): void;
RegRead(Name: string): any;
RegWrite(Name: string, Value: any, Type?: any): void;
Run(Command: string, WindowStyle?: any, WaitOnReturn?: any): number;
SendKeys(Keys: string, Wait?: any): void;
readonly SpecialFolders: WshCollection;
}
/** Shortcut Object */
class WshShortcut {
private 'IWshRuntimeLibrary.WshShortcut_typekey': WshShortcut;
private constructor();
Arguments: string;
Description: string;
readonly FullName: string;
Hotkey: string;
IconLocation: string;
Load(PathLink: string): void;
readonly RelativePath: string;
Save(): void;
TargetPath: string;
WindowStyle: number;
WorkingDirectory: string;
}
/** URLShortcut Object */
class WshURLShortcut {
private 'IWshRuntimeLibrary.WshURLShortcut_typekey': WshURLShortcut;
private constructor();
readonly FullName: string;
Load(PathLink: string): void;
Save(): void;
TargetPath: string;
}
}
interface ActiveXObject {
set(obj: IWshRuntimeLibrary.WshEnvironment, propertyName: 'Item', parameterTypes: [string], newValue: string): void;
new <K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
}
interface ActiveXObjectNameMap {
'WScript.Network': IWshRuntimeLibrary.WshNetwork;
'WScript.Shell': IWshRuntimeLibrary.WshShell;
}
interface EnumeratorConstructor {
new(col: IWshRuntimeLibrary.WshCollection): Enumerator;
new(col: IWshRuntimeLibrary.WshEnvironment): Enumerator<string>;
}

View File

@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"activex-iwshruntimelibrary-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,8 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false],
"ban-types": false,
"no-const-enum": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-unnecessary-qualifier": false

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false
}
}

View File

@@ -0,0 +1,12 @@
// https://msdn.microsoft.com/en-us/library/aa752044(v=vs.85).aspx
(() => {
const ie = new ActiveXObject('InternetExplorer.Application');
ie.Navigate('http://contoso.com');
ie.Visible = true;
})();
let obj1 = new ActiveXObject('ShellNameSpace.ShellNameSpace');
let obj2 = new ActiveXObject('Shell.UIHelper');
let obj3 = new ActiveXObject('Shell.Explorer');

1577
types/activex-shdocvw/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}

View File

@@ -1,10 +1,8 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
@@ -19,6 +17,6 @@
},
"files": [
"index.d.ts",
"xhr-mock-tests.ts"
"activex-shdocvw-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -0,0 +1,489 @@
/// <reference types="activex-iwshruntimelibrary" />
const shell = new ActiveXObject('Shell.Application');
const getWindowsFolder = () => shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfWINDOWS);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537735(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
if (!folder) { return; }
const folderItem = folder.ParseName('system.ini');
if (!folderItem) { return; }
shell.AddToRecent(folderItem.Path);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774065(v=vs.85).aspx
(() => {
const folder = shell.BrowseForFolder(0, 'Example', 0, Shell32.ShellSpecialFolderConstants.ssfWINDOWS);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537736(v=vs.85).aspx
const canStartStop = shell.CanStartStopService('service name');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774069(v=vs.85).aspx
shell.ControlPanelItem('desk.cpl');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774073(v=vs.85).aspx
shell.Explore('C:\\');
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537737(v=vs.85).aspx
const explorerPolicy = shell.ExplorerPolicy('ValueName');
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537739(v=vs.85).aspx
const settingValue = shell.GetSetting(Shell32.SettingKey.SSF_SHOWALLOBJECTS);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537740(v=vs.85).aspx
const processorLevel = shell.GetSystemInformation('ProcessorLevel');
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537741(v=vs.85).aspx
const isRestricted = shell.IsRestricted('system', 'undockwithoutlogon');
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537742(v=vs.85).aspx
const isServiceRunning = shell.IsServiceRunning('Themes');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774086(v=vs.85).aspx
shell.Open(Shell32.ShellSpecialFolderConstants.ssfWINDOWS);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537743(v=vs.85).aspx
shell.ServiceStart('Messenger', true);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537744(v=vs.85).aspx
shell.ServiceStop('Messenger', true);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537745(v=vs.85).aspx
shell.ShellExecute("notepad.exe", "", "", "open", Shell32.ShellExecuteShow.Normal);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537746(v=vs.85).aspx?cs-save-lang=1&cs-lang=jscript#code-snippet-1
shell.ShowBrowserBar(Shell32.ExplorerBarCLSID.Favorites, true);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774107(v=vs.85).aspx
const wshShell = new ActiveXObject('WScript.Shell');
wshShell.Popup(shell.Windows().Count);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787866(v=vs.85).aspx
shell.NameSpace(`c:\\windows`)!.CopyHere('c:\\autoexec.bat');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx
(() => {
const folder = shell.NameSpace('c:\\windows');
const folderItem = folder ? folder.ParseName('clock.avi') : undefined;
if (folder && folderItem) {
const info = folder.GetDetailsOf(folderItem, Shell32.FileSystemDetails.Type);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787874(v=vs.85).aspx
shell.NameSpace('c:\\windows')!.MoveHere('c:\\temp.txt', Shell32.FileOperationFlag.FOF_NOCONFIRMATION);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787876(v=vs.85).aspx
shell.NameSpace('c:\\')!.NewFolder('TestFolder');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787858(v=vs.85).aspx
(() => {
const folder = shell.NameSpace("\\\\server\\share\\folder");
const offlineStatus = folder ? folder.OfflineStatus : undefined;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787880(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS);
WScript.Echo(folder!.ParentFolder.Title);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787860(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787816(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787850(v=vs.85).aspx
(() => {
const folder = shell.NameSpace('C:\\WINDOWS');
const folderItem = folder ? folder.Self : undefined;
if (folderItem) {
const verbs = folderItem.Verbs();
folderItem.InvokeVerb();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787812(v=vs.85).aspx
(() => {
const parentFolder = getWindowsFolder();
const folderItem = parentFolder ? parentFolder.ParseName('system32') : undefined;
const folder = folderItem ? folderItem.GetFolder : undefined;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787814(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787824(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS);
const folderItem = folder ? folder.ParseName('Internet Explorer.lnk') : undefined;
if (folderItem && folderItem.IsLink) {
const link = folderItem.GetLink;
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787818(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787819(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787821(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.Self : undefined;
if (folderItem) {
const isBrowsable = folderItem.IsBrowsable;
const isFileSystem = folderItem.IsFileSystem;
const isFolder = folderItem.IsFolder;
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787825(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder!.ParseName('notepad.exe');
if (folderItem) {
const oldDate = folderItem.ModifyDate;
folderItem.ModifyDate = new Date(1900, 1, 1, 18, 5).getVarDate();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787827(v=vs.85).aspx
(() => {
const rootFolder = shell.NameSpace('C:\\');
const folderItem = rootFolder ? rootFolder.ParseName('autoexec.bat') : undefined;
if (folderItem) {
const oldName = folderItem.Name;
folderItem.Name = 'test.bat';
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787829(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.Self : undefined;
const parent = folderItem ? folderItem.Parent : undefined;
if (parent) {
WScript.Echo('Got parent object');
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787844(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.Self : undefined;
const path = folderItem ? folderItem.Path : '';
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787846(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder!.ParseName('notepad.exe');
const size = folderItem ? folderItem.Size : undefined;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787848(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
if (folder) {
WScript.Echo(folder.Self.Type);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787798(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItems = folder ? folder.Items() : undefined;
const count = folderItems ? folderItems.Count : undefined;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787794(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfDRIVES);
if (folder) {
folder.Items().InvokeVerbEx();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774170(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774174(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS);
const verbs = folder ? folder.Self.Verbs() : undefined;
if (verbs) {
const verb = verbs.Item(0);
WScript.Echo(verb.Name);
verb.DoIt();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787787(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
if (folder) {
const folderItems = folder.Items();
WScript.Echo(folderItems.Count);
folderItems.Filter(Shell32.ShellFolderEnumerationFlags.SHCONTF_NONFOLDERS, '*.txt');
WScript.Echo(folderItems.Count);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787791(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774162(v=vs.85).aspx
(() => {
const echoFirstVerbName = (folder: Shell32.Folder3 | null) => {
if (!folder) { return; }
const verbs = folder.Items().Verbs;
WScript.Echo(verbs.Item(0).Name);
};
let folder = getWindowsFolder();
echoFirstVerbName(folder);
folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS);
echoFirstVerbName(folder);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774158(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS);
if (folder) {
const verbs = folder.Self.Verbs();
WScript.Echo(verbs.Count);
}
})();
const getIELink = () => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS);
const folderItem = folder ? folder.ParseName('Internet Explorer.lnk') : undefined;
return {
link: folderItem ? folderItem.GetLink : undefined,
folderItem
};
};
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773990(v=vs.85).aspx
(() => {
const { link, folderItem } = getIELink();
if (link && folderItem) {
WScript.Echo(link.GetIconLocation(folderItem.Path));
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773996(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
link.Resolve(Shell32.ShellLinkResolveFlags.NoUI);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773998(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
link.Description = 'New Description';
link.Save();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774002(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
link.SetIconLocation(link.Path, 1);
link.Save();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773986(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.Arguments);
link.Arguments = '/s';
link.Save();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773988(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.Description);
link.Description = 'Test';
link.Save();
}
})();
const parseHotkey = (hotkey: number) => {
// missing implementation
return {
shift: false,
ctrl: false,
alt: false,
extended: false,
hotkey
};
};
const buildHotkey = (hotkey: number, shift: boolean = false, ctrl: boolean = false, alt: boolean = false, extended: boolean = false) => {
// missing implementation
return 0;
};
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773992(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
const { hotkey } = parseHotkey(link.Hotkey);
WScript.Echo(hotkey);
link.Hotkey = buildHotkey(4);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773994(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.Path);
link.Path = 'C:\\Program Files\\IE\\IEXPLORE.EXE';
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774006(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.ShowCommand);
link.ShowCommand = Shell32.LinkShowWindowState.Normal;
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774008(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.WorkingDirectory);
link.WorkingDirectory = '';
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774115(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
const target = link.Target;
if (target) {
WScript.Echo(target.Size);
}
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774055(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.ParseName('notepad.exe') : undefined;
if (folderItem) {
WScript.Echo(folderItem.ExtendedProperty('infotip'));
}
const wordDoc = shell.NameSpace('C:\\')!.ParseName('test.doc');
if (wordDoc) {
const FMTID_SummaryInfo = "{F29F85E0-4FF9-1068-AB91-08002B27B3D9}";
const PID_TITLE = "2";
const PID_AUTHOR = "4";
const SCID_TITLE = `${FMTID_SummaryInfo} ${PID_TITLE}`;
const SCID_AUTHOR = `${FMTID_SummaryInfo} ${PID_AUTHOR}`;
const docTitle = wordDoc.ExtendedProperty(SCID_TITLE);
const docAuthor = wordDoc.ExtendedProperty(SCID_AUTHOR);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774057(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.ParseName('notepad.exe') : undefined;
if (folderItem) {
folderItem.InvokeVerbEx("open", "c:\\autoexec.bat");
}
})();
const collectionToArray = <T>(col: any): T[] => { // tslint:disable-line no-unnecessary-generics
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
interface String {
endsWith(searchString: string, length?: number): boolean;
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
};
}
// shell.Windows() includes items other than Explorer windows, such as Internet Explorer tabs
const getExplorerWindows = () =>
collectionToArray<SHDocVw.InternetExplorer>(shell.Windows())
.filter(x => x.FullName.toLowerCase().endsWith('explorer.exe'));
const getFolderViews = () =>
getExplorerWindows()
.map(x => x.Document as Shell32.ShellFolderView);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774045(v=vs.85).aspx
(() => {
getFolderViews().forEach(x =>
ActiveXObject.on(x, 'SelectionChanged', function(this: Shell32.ShellFolderView) {
WScript.Echo(`Selection change in ${this.Folder.Title} -- count: ${this.SelectedItems().Count}`);
})
);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773970(v=vs.85).aspx
WScript.Echo(shell.Windows().Item().Path);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773969(v=vs.85).aspx
WScript.Echo(shell.Windows().Count);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774043(v=vs.85).aspx
(() => {
getFolderViews().forEach(x =>
WScript.Echo(`${x.Folder.Title} -- ${x.SelectedItems().Count} selected items`)
);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774047(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774022(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774053(v=vs.85).aspx
(() => {
const folderView = getExplorerWindows()[0].Document as Shell32.ShellFolderView;
const folder = folderView.Folder;
if (folder) {
const folderItem = folder.Self;
folderView.SelectItem(folder.Self, Shell32.ShellFolderViewSelectItem.Focus);
}
WScript.Echo(folderView.ViewOptions);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774020(v=vs.85).aspx
(() => {
const folderView = getExplorerWindows()[0].Document as Shell32.ShellFolderView;
const focusedItem = folderView.FocusedItem;
if (focusedItem) {
WScript.Echo(`Focused item in first Excplorer window -- ${focusedItem.Path}`);
}
})();
(() => {
const router = new ActiveXObject('Shell.FolderView');
const folder = getFolderViews()[0];
router.SetFolderView(folder);
ActiveXObject.on(router, 'EnumDone', () => WScript.Echo('Current folder view was finisehd enumerating'));
ActiveXObject.on(router, 'SelectionChanged', () => WScript.Echo('Selection changed in current folder view'));
// the folder view monitored by the ShellFolderViewOC object can be changed via SetFolderView without disconnecting and reconnecting the handlers
})();

1016
types/activex-shell/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}

View File

@@ -1,9 +1,8 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
@@ -18,6 +17,6 @@
},
"files": [
"index.d.ts",
"ably-tests.ts"
"activex-shell-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}

View File

@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -14,10 +14,11 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"add-zero-tests.ts"
]
}
}

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -14,7 +14,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",

View File

@@ -110,6 +110,8 @@ declare namespace adone {
export function require(path: string): object;
export const package: object;
export function sprintf(format: string, ...args: any[]): string;
namespace I {
interface Runtime {
term: object; // TODO

View File

@@ -1,5 +1,275 @@
declare namespace adone {
namespace application {
function run(app: object, ignoreArgs?: boolean): Promise<void>;
namespace I {
type ArgumentType = ((x: string, index: number) => any) | RegExp;
interface ArgumentInfo {
name: string | string[];
action?: "store"
| "store_const"
| "store_true"
| "store_false"
| "append"
| "count"
| "set";
nargs?: number | "+" | "*" | "?"
type?: ArgumentType | ArgumentType[];
verify?: (args: any, opts: any) => boolean; // TODO
required?: boolean;
description?: string;
help?: string;
holder?: string | string[];
appendDefaultMessage?: boolean;
appendChoicesHelpMessage?: boolean;
default?: any;
enabled?: boolean;
}
interface Group {
name: string;
description?: string;
}
interface MainCommandInfo {
arguments?: Array<ArgumentInfo | string>;
options?: Array<ArgumentInfo | string>;
description?: string;
optionsGroups?: Group[];
blindMode?: boolean;
match?: (name: string) => boolean;
handler?: (args: object, opts: object) => void;
}
interface CommandInfo extends MainCommandInfo {
name?: string | string[];
group?: string;
}
interface ApplicationInfo {
name?: string;
description?: string;
subsystems?: SubsystemInfo[];
commandsGroups?: Group[]
}
interface SubsystemInfo {
name: string;
description?: string;
subsystem: string;
transpile?: boolean;
group?: string;
}
}
function DSubsystem(info?: I.ApplicationInfo): (...args: any[]) => void;
function DApplication(info?: I.ApplicationInfo): (...args: any[]) => void;
function DCliCommand(info?: I.CommandInfo): (...args: any[]) => void;
function DMainCliCommand(info?: I.MainCommandInfo): (...args: any[]) => void;
namespace I {
interface LoadSubsystemOptions {
name?: string,
description?: string,
group?: string,
transpile?: boolean
}
interface CommonAddSubsystemInfo {
name?: string,
useFilename?: boolean
description?: string,
group?: string,
configureArgs?: any[]
transpile?: boolean,
bind?: boolean | string
}
interface AddSubsystemInfo extends CommonAddSubsystemInfo {
subsystem: Subsystem | string,
}
interface SysInfo {
name: string;
description: string;
group: string;
configureArgs: any[];
instance: Subsystem;
path: string | null;
}
interface SysInfoWithPath extends SysInfo {
path: string;
}
interface SysInfoNoPath extends SysInfo {
path: null;
}
interface AddSubsystemsFromOptions extends CommonAddSubsystemInfo {
filter?: string[] | ((file: string) => boolean | Promise<boolean>)
}
}
class Subsystem extends event.AsyncEmitter {
constructor(options?: { name?: string });
readonly name?: string;
readonly root?: Subsystem;
setRoot(root: Subsystem): void;
readonly parent?: Subsystem;
readonly state: number;
readonly isOwned: boolean;
setState(state: number): void;
waitForState(expectedState: number, timeout?: number): Promise<void>;
configure(): void;
initialize(): void;
uninitialize(): void;
configureSubsystems(): Promise<void>;
uninitializeSubsystems(): Promise<void>;
reinitializeSubsystems(): Promise<void>;
configureSubsystem(name: string): Promise<void>;
loadSubsystem(subsystem: string | Subsystem, options?: I.LoadSubsystemOptions): Promise<void>;
unloadSubsystem(name: string): Promise<void>;
initializeSubsystem(name: string): Promise<void>;
uninitializeSubsystem(name: string): Promise<void>;
reinitializeSubsystem(name: string): Promise<void>;
getSubsystem(name: string): Subsystem;
hasSubsystem(name: string): boolean;
hasSubsystems(): boolean;
addSubsystem(info: I.AddSubsystemInfo & { subsystem: Subsystem }): I.SysInfoNoPath;
addSubsystem(info: I.AddSubsystemInfo & { subsystem: string }): I.SysInfoWithPath;
addSubsystemsFrom(path: string, options?: I.AddSubsystemsFromOptions): I.SysInfoWithPath;
instantiateSubsystem(subsystem: string | Subsystem, options?: {
transpile?: boolean
}): Subsystem;
deleteSubsystem(name: string, force?: boolean): void;
getSubsystemInfo(name: string): I.SysInfo;
getSubsystems(): I.SysInfo[];
}
namespace I {
interface ReportOptions {
events?: string;
signal?: string;
filename?: string;
directory?: string;
}
}
class Application extends Subsystem {
readonly isMain: boolean;
main(): void;
enableReport(opts?: I.ReportOptions): void;
reportEnabled(): boolean;
run(): Promise<void>;
exit(code?: number): Promise<void>;
exitOnSignal(...names: string[]): void;
removeProcesshandlers(): void;
_uncaughtException(err: any): void;
_unhandledRejection(reson: any, p: Promise<any>): void;
_rejectionHandled(p: Promise<any>): void;
_signalExit(sigName: string): void;
}
namespace I {
interface Command {
// ?
}
interface Argument {
// ?
}
interface PositionalArgument extends Argument {
// ?
}
interface OptionalArgument extends Argument {
// ?
}
interface DefineCommandFromSubsystemOptions {
name?: string;
description?: string;
group?: string;
subsystem: string | Subsystem;
configureArgs?: any[];
lazily?: boolean;
transpile?: boolean;
}
}
class CliApplication extends Application {
run(options?: { ignoreArgs?: boolean }): Promise<void>;
getVersion(): Promise<string | undefined>;
exposeCliInterface(ctxId?: string): void;
readonly mainCommand: I.Command;
defineMainCommand(schema: I.MainCommandInfo): this;
defineArguments(schema: I.MainCommandInfo): this;
defineCommand(schema: I.CommandInfo): I.Command;
defineCommandFromSubsystem(options?: I.DefineCommandFromSubsystemOptions): void;
defineOption(schema: I.ArgumentInfo): void;
defineOptionsGroup(schema: I.Group): void;
defineCommandsGroup(schema: I.Group): void;
option(path: string, options?: { value?: boolean }): any;
}
function run(app: Application, ignoreArgs?: boolean): Promise<void>;
function runCli(app: CliApplication, ignoreArgs?: boolean): Promise<void>;
}
}

View File

@@ -448,7 +448,7 @@ declare namespace adone {
isCompressed(): boolean;
}
interface ZipFile<StringType> extends event.EventEmitter {
interface ZipFile<StringType> extends event.Emitter {
/**
* true until close() is called; then it's false
*/

View File

@@ -38,7 +38,7 @@ declare namespace adone {
proxyExcludedKeys: string[];
}
type PossibleTypes = util.I.PossibleTypes | "array";
type PossibleTypes = meta.I.PossibleTypes | "array";
type UseFunction = (fn: () => void) => assertion;
@@ -53,18 +53,10 @@ declare namespace adone {
* Throws an AssertionError, like node.js
*/
fail(actual?: any, expected?: any, message?: string, operator?: any): void;
/**
* Asserts that value is truthy
*/
isOk(value: any, message?: string): void;
/**
* Asserts that value is truthy
*/
ok(value: any, message?: string): void;
/**
* Asserts that value is falsy
*/
isNotOk(value: any, message?: string): void;
/**
* Asserts that value is falsy
*/
@@ -104,51 +96,51 @@ declare namespace adone {
/**
* Asserts that value > above
*/
isAbove(value: any, above: any, message?: string): void;
above(value: any, above: any, message?: string): void;
/**
* Asserts that value >= atLeast
*/
isAtLeast(value: any, atLeast: any, message?: string): void;
atLeast(value: any, atLeast: any, message?: string): void;
/**
* Asserts that value < below
*/
isBelow(value: any, below: any, message?: string): void;
below(value: any, below: any, message?: string): void;
/**
* Asserts that value <= atMost
*/
isAtMost(value: any, atMost: any, message?: string): void;
atMost(value: any, atMost: any, message?: string): void;
/**
* Asserts that value is true
*/
isTrue(value: any, message?: string): void;
true(value: any, message?: string): void;
/**
* Asserts that value is not true
*/
isNotTrue(value: any, message?: string): void;
notTrue(value: any, message?: string): void;
/**
* Asserts that value is false
*/
isFalse(value: any, message?: string): void;
false(value: any, message?: string): void;
/**
* Asserts that value is not false
*/
isNotFalse(value: any, message?: string): void;
notFalse(value: any, message?: string): void;
/**
* Asserts that value is null
*/
isNull(value: any, message?: string): void;
null(value: any, message?: string): void;
/**
* Asserts that valus is not null
*/
isNotNull(value: any, message?: string): void;
notNull(value: any, message?: string): void;
/**
* Asserts that value is NaN
*/
isNaN(value: any, message?: string): void;
NaN(value: any, message?: string): void;
/**
* Asserts that value is not NaN
*/
isNotNaN(value: any, message?: string): void;
NotNaN(value: any, message?: string): void;
/**
* Asserts that value is neither null nor undefined
*/
@@ -160,63 +152,63 @@ declare namespace adone {
/**
* Asserts that value is undefined
*/
isUndefined(value: any, message?: string): void;
undefined(value: any, message?: string): void;
/**
* Asserts that value is not undefined
*/
isDefined(value: any, message?: string): void;
defined(value: any, message?: string): void;
/**
* Asserts that value is a function
*/
isFunction(value: any, message?: string): void;
function(value: any, message?: string): void;
/**
* Asserts that value is not a function
*/
isNotFunction(value: any, message?: string): void;
notFunction(value: any, message?: string): void;
/**
* Asserts that value is an object of type Object
*/
isObject(value: any, message?: string): void;
object(value: any, message?: string): void;
/**
* Asserts that value is not an object of type Object
*/
isNotObject(value: any, message?: string): void;
notObject(value: any, message?: string): void;
/**
* Asserts that value is an array
*/
isArray(value: any, message?: string): void;
array(value: any, message?: string): void;
/**
* Asserts that value is not an array
*/
isNotArray(value: any, message?: string): void;
notArray(value: any, message?: string): void;
/**
* Asserts that value is a string
*/
isString(value: any, message?: string): void;
string(value: any, message?: string): void;
/**
* Asserts that value is not a string
*/
isNotString(value: any, message?: string): void;
notString(value: any, message?: string): void;
/**
* Asserts that value is a number
*/
isNumber(value: any, message?: string): void;
number(value: any, message?: string): void;
/**
* Asserts that value is not a number
*/
isNotNumber(value: any, message?: string): void;
notNumber(value: any, message?: string): void;
/**
* Asserts that value is a finite number
*/
isFinite(value: any, message?: string): void;
finite(value: any, message?: string): void;
/**
* Asserts that value is a boolean
*/
isBoolean(value: any, message?: string): void;
boolean(value: any, message?: string): void;
/**
* Asserts that value is not a boolean
*/
isNotBoolean(value: any, message?: string): void;
notBoolean(value: any, message?: string): void;
/**
* Asserts that value's type is `type`
*/
@@ -562,66 +554,34 @@ declare namespace adone {
* Throws an error if value is truthy
*/
ifError(value: any): void;
/**
* Asserts that object is extensible
*/
isExtensible(object: object, message?: string): void;
/**
* Asserts that object is extensible
*/
extensible(object: object, message?: string): void;
/**
* Asserts that object is not extensible
*/
isNotExtensible(object: object, message?: string): void;
/**
* Asserts that object is not extensible
*/
notExtensible(object: object, message?: string): void;
/**
* Asserts that object is sealed
*/
isSealed(object: object, message?: string): void;
/**
* Asserts that object is sealed
*/
sealed(object: object, message?: string): void;
/**
* Asserts that object is not sealed
*/
isNotSealed(object: object, message?: string): void;
/**
* Asserts that object is not sealed
*/
notSealed(object: object, message?: string): void;
/**
* Asserts that object is frozen
*/
isFrozen(object: object, message?: string): void;
/**
* Asserts that object is frozen
*/
frozen(object: object, message?: string): void;
/**
* Asserts that object is not frozen
*/
isNotFrozen(object: object, message?: string): void;
/**
* Asserts that object is not frozen
*/
notFrozen(object: object, message?: string): void;
/**
* Asserts that value is empty
*/
isEmpty(value: any, message?: string): void;
/**
* Asserts that value is empty
*/
empty(value: any, message?: string): void;
/**
* Asserts that value is not empty
*/
isNotEmpty(value: any, message?: string): void;
/**
* Asserts that value is not empty
*/
@@ -710,43 +670,43 @@ declare namespace adone {
/**
* Asserts that the target is non-strictly equal to true
*/
ok: this;
ok(): this;
/**
* Asserts that the target is true
*/
true: this;
true(): this;
/**
* Asserts that the target is false
*/
false: this;
false(): this;
/**
* Asserts that the target is null
*/
null: this;
null(): this;
/**
* Asserts that the target is undefined
*/
undefined: this;
undefined(): this;
/**
* Asserts that the target is NaN
*/
NaN: this;
NaN(): this;
/**
* Asserts that the target is neither null nor undefined
*/
exist: this;
exist(): this;
/**
* Asserts that the target is empty
*/
empty: this;
empty(): this;
/**
* Asserts that the target is an arguments object
*/
arguments: this;
arguments(): this;
/**
* Asserts that the target is an arguments object
*/
Arguments: this;
Arguments(): this;
/**
* Asserts that the target is strictly equal to value(===)
*/
@@ -976,26 +936,26 @@ declare namespace adone {
/**
* Asserts that the target is extensible
*/
extensible: this;
extensible(): this;
/**
* Asserts that the target is sealed
*/
sealed: this;
sealed(): this;
/**
* Asserts that the target is frozen
*/
frozen: this;
frozen(): this;
/**
* Asserts that the target is a finite number
*/
finite: this;
finite(): this;
}
interface MockAssertions extends Assertion {
/**
* Asserts that the spy has been called
*/
called: this;
called(): this;
/**
* Asserts that the spy has been called n times
*/
@@ -1003,15 +963,15 @@ declare namespace adone {
/**
* Asserts that the spy has been called once
*/
calledOnce: this;
calledOnce(): this;
/**
* Asserts that the spy has been called twice
*/
calledTwice: this;
calledTwice(): this;
/**
* Asserts that the spy has been been called with `new`
*/
calledThrice: this;
calledThrice(): this;
/**
* Asserts that the spy has been called before anotherSpy
*/
@@ -1059,7 +1019,7 @@ declare namespace adone {
}
}
class AssertionError extends x.Exception {
class AssertionError extends exception.Exception {
constructor(message?: string, props?: object, ssf?: object)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,44 @@
declare namespace adone.collection {
/**
* Respresetns a data structure which is a combination of an array and a set.
* Adding a new member is O(1), testing for membership is O(1),
* and finding the index of an element is O(1).
*/
class ArraySet<T = any> {
/**
* The number of unique items in this ArraySet.
* If duplicates have been added, than those do not count towards the size.
*/
readonly length: number;
/**
* Adds the given value to this set.
*
* @param allowDuplicates Whether to allow duplicates in the set, false by default
*/
add(value: T, allowDuplicates?: boolean): this;
/**
* Checks whether the given value is a member of the set
*/
has(value: T): boolean;
/**
* Returns the index of the given element.
* If the value is not present it will return -1
*/
indexOf(value: T): number;
/**
* Converts the set to an array
*/
toArray(): T[];
/**
* Creates an ArraySet from the given iterable object
*
* @param allowDuplicates Whether to allow duplicates in the set, false by default
*/
static from<T>(iterable: Iterable<T>, allowDuplicates?: boolean): ArraySet<T>;
}
}

View File

@@ -0,0 +1,12 @@
declare namespace adone.collection {
/**
* Represents an asynchronous queue, each pop is a promise
* that is resolved with an existing element or an element that will be pushed in the future
*/
class AsyncQueue<T = any> extends Queue<T, Promise<T>> {
/**
* Returns a promise that will be resolved with an existing element or an element that will be pushed in the future
*/
pop(): Promise<T>;
}
}

View File

@@ -0,0 +1,48 @@
declare namespace adone.collection {
/**
* Represents an AVL tree, a self-balancing binary search tree
*/
class AVLTree<K = any, V = any> {
constructor(options?: I.BinarySearchTree.ConstructorOptions<K, V, AVLTree<K, V>>);
/**
* Checks whether the tree is an avl tree
*/
checkIsAVLT(): void;
/**
* Inserts a new key/value
*/
insert(key: K, value: V): void;
/**
* Deletes the given key/value from the tree
*/
delete(key: K, value?: V): void;
/**
* Returns the of keys in the tree
*/
getNumberOFKeys(): number;
/**
* Searches the given key in the tree
*/
search(key: K): V[];
/**
* Returns all the values from the given key bounds
*/
betweenBounds(query: I.BinarySearchTree.Query<K>): V[];
/**
* Executed the given callback for each node from left to right
*/
executeOnEveryNode(fn: (tree: AVLTree<K, V>) => void): void;
/**
* Prints the tree
*/
prettyPrint(printDate?: boolean, spacing?: string): void;
}
}

View File

@@ -0,0 +1,110 @@
declare namespace adone.collection {
namespace I.BinarySearchTree {
interface ConstructorOptions<K, V, Tree> {
/**
* The parent tree
*/
parent?: Tree;
/**
* Value to keep in this node
*/
value?: V;
/**
* WHether the values must be unique, false by default.
* If false you can store many values for same keys, otherwise only one
*/
unique?: boolean;
/**
* Custom keys comparator, by default if a > b => -1, a < b -1, a === b => 0
*/
compareKeys?(a: K, b: K): number;
/**
* Function that defines whether 2 values are the same, by default a === b
*/
checkValueEquality?(a: V, b: V): boolean;
}
interface Query<K> {
$lt?: K;
$lte?: K;
$gt?: K;
$gte?: K;
}
}
/**
* Represents a binary search tree
*/
class BinarySearchTree<K = any, V = any> {
constructor(options?: I.BinarySearchTree.ConstructorOptions<K, V, BinarySearchTree<K, V>>);
/**
* Returns the max descendant tree
*/
getMaxKeyDescendant(): BinarySearchTree<K, V>;
/**
* Returns the maximum key
*/
getMaxKey(): K;
/**
* Returns the min descendant tree
*/
getMinKeyDescendant(): BinarySearchTree<K, V>;
/**
* Returns the minumum key
*/
getMinKey(): K;
/**
* Traverses the tree and calls the given function for each node
*/
checkAllNodesFullfillCondition(test: (key: K, value: V) => void): void;
/**
* Checks whether the tree is a binary search tree
*/
checkIsBST(): void;
/**
* Returns the of keys in the tree
*/
getNumberOfKeys(): number;
/**
* Inserts a new key/value
*/
insert(key: K, value: V): void;
/**
* Searches the given key in the tree
*/
search(key: K): V[];
/**
* Returns all the values from the given key bounds
*/
betweenBounds(query: I.BinarySearchTree.Query<K>): V[];
/**
* Deletes the given key/value from the tree
*/
delete(key: K, value?: V): void;
/**
* Executed the given callback for each node from left to right
*/
executeOnEveryNode(fn: (tree: BinarySearchTree<K, V>) => void): void;
/**
* Prints the tree
*/
prettyPrint(printData?: boolean, spacing?: string): void;
}
}

View File

@@ -0,0 +1,92 @@
declare namespace adone.collection {
namespace I.BufferList {
type Appendable = Buffer | BufferList | string | number | Array<Buffer | BufferList | string | number>;
}
/**
* Represents a Node.js Buffer list collector, reader and streamer with callback/promise interface support
*/
class BufferList extends std.stream.Duplex implements PromiseLike<Buffer> {
/**
* Creates a new buffer list
*/
constructor();
/**
* Creates a new buffer list and initiates with the given value
*/
constructor(buffer: I.BufferList.Appendable);
/**
* Creates a new buffer list and subscribes the given callback on the end/error event
*/
constructor(callback: (err: any, data: Buffer) => void);
/**
* Adds an additional buffer or BufferList to the internal list
*/
append(buf: I.BufferList.Appendable): this;
/**
* Ends the stream
*/
end(chunk?: Buffer): void;
end(chunk?: () => void): void;
/**
* Returns the byte at the specified index
*/
get(idx: number): number;
/**
* Returns a new Buffer object containing the bytes within the range specified.
*/
slice(start?: number, end?: number): Buffer;
/**
* Copies the content of the list in the dest buffer
* starting from destStart and containing the bytes within the range specified with srcStart to srcEnd
*
* @param dstStart writes from this position
* @param srcStart reads bytes from this position
* @param srcEnd read bytes to this position
*/
copy<T extends Buffer = Buffer>(dst: T, dstStart?: number, srcStart?: number, srcEnd?: number): T;
/**
* Returns a new BufferList object containing the bytes within the range specified.
* No copies will be performed. All buffers in the result share memory with the original list.
*
* @param start slice from
* @param end slice to
*/
shallowSlice(start?: number, end?: number): BufferList;
/**
* Return a string representation of the buffer
*/
toString(encoding?: fs.I.Encoding, start?: number, end?: number): string;
/**
* Shifts bytes off the start of the list
*/
consume(bytes: number): this;
/**
* Performs a shallow-copy of the list.
*/
duplicate(): BufferList;
/**
* Destroys the stream
*/
destroy(): void;
then<T1 = Buffer, T2 = never>(
onfulfilled?: ((value: Buffer) => T1 | PromiseLike<T1>) | null,
onrejected?: ((reason: any) => T2 | PromiseLike<T2>) | null
): PromiseLike<T1 | T2>;
catch<T>(onrejected?: ((reason: any) => T | PromiseLike<T>) | null): PromiseLike<T | Buffer>;
}
}

View File

@@ -0,0 +1,892 @@
declare namespace adone.collection {
namespace I {
type Long = math.Long;
type Longable = math.I.Longable;
namespace ByteArray {
interface Varint32 {
value: number;
length: number;
}
interface Varint64 {
value: Long;
length: number;
}
interface String {
string: string;
length: number;
}
type Wrappable = string | ByteArray | Buffer | Uint8Array | ArrayBuffer;
type Metrics = "b" | "c";
}
}
/**
* Represents an array of bytes, enhanced Node.js Buffer
*/
class ByteArray {
readonly woffset: number;
readonly roffset: number;
readonly buffer: Buffer;
readonly noAssert: boolean;
/**
* Constructs a new ByteArray
*
* @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64)
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
constructor(capacity?: number, noAssert?: boolean);
/**
* Reads a BitSet as an array of booleans.
*
* @param offset Offset to read from. Will use and increase offset by length if omitted.
*/
readBitSet(offset?: number): boolean[];
/**
* Reads the specified number of bytes.
*
* @param length Number of bytes to read
* @param offset Offset to read from. Will use and increase offset by length if omitted.
*/
read(length: number, offset?: number): ByteArray;
/**
* Reads an 8bit signed integer
*
* @param offset Offset to read from
*/
readInt8(offset?: number): number;
/**
* Reads an 8bit unsigned integer
*
* @param offset Offset to read from
*/
readUInt8(offset?: number): number;
/**
* Reads a 16bit signed le integer
*
* @param offset Offset to read from
*/
readInt16LE(offset?: number): number;
/**
* Reads a 16bit unsigned le integer
*
* @param offset Offset to read from
*/
readUInt16LE(offset?: number): number;
/**
* Reads a 16bit signed be integer
*
* @param offset Offset to read from
*/
readInt16BE(offset?: number): number;
/**
* Reads a 16bit unsigned be integer
*
* @param offset Offset to read from
*/
readUInt16BE(offset?: number): number;
/**
* Reads a 32bit signed le integer
*
* @param offset Offset to read from
*/
readInt32LE(offset?: number): number;
/**
* Reads a 32bit unsigned le integer
*
* @param offset Offset to read from
*/
readUInt32LE(offset?: number): number;
/**
* Reads a 32bit signed be integer
*
* @param offset Offset to read from
*/
readInt32BE(offset?: number): number;
/**
* Reads a 32bit unsigned be integer
*
* @param offset Offset to read from
*/
readUInt32BE(offset?: number): number;
/**
* Reads a 64bit signed le integer as math.Long
*
* @param offset Offset to read from
*/
readInt64LE(offset?: number): math.Long;
/**
* Reads a 64bit unsigned le integer as math.Long
*
* @param offset Offset to read from
*/
readUInt64LE(offset?: number): math.Long;
/**
* Reads a 64bit signed be integer as math.Long
*
* @param offset Offset to read from
*/
readInt64BE(offset?: number): math.Long;
/**
* Reads a 64bit unsigned be integer as math.Long
*
* @param offset Offset to read from
*/
readUInt64BE(offset?: number): math.Long;
/**
* Reads a 32bit le float
*
* @param offset Offset to read from
*/
readFloatLE(offset?: number): number;
/**
* Reads a 32bit be float
*
* @param offset Offset to read from
*/
readFloatBE(offset?: number): number;
/**
* Reads a 64bit le float
*
* @param offset Offset to read from
*/
readDoubleLE(offset?: number): number;
/**
* Reads a 64bit be float
*
* @param offset Offset to read from
*/
readDoubleBE(offset?: number): number;
/**
* Appends some data to this ByteArray.
* This will overwrite any contents behind the specified offset up to the appended data's length.
*
* @param source The source write from
* @param offset Offset to write at
* @param length length to read from the source
* @param encoding encoding to use for wrapping the source in bytearray
*/
write(source: I.ByteArray.Wrappable, offset?: number, length?: number, encoding?: string): this;
/**
* Writes the array as a bitset.
* @param value Array of booleans to write
*/
writeBitSet(value: number[]): this;
/**
* Writes the array as a bitset.
* @param value Array of booleans to write
* @param offset Offset to write at
*/
writeBitSet(value: number[], offset: number): number;
/**
* Writes a buffer at the given offset
* @param buf Buffer to write
* @param offset Offset to write at
*/
writeBuffer(buf: Buffer, offset?: number): this;
/**
* Writes an 8bit signed integer
*
* @param offset Offset to write at
*/
writeInt8(value: number, offset?: number): this;
/**
* Writes an 8bit unsigned integer
*
* @param offset Offset to write at
*/
writeUInt8(value: number, offset?: number): this;
/**
* Writes a 16bit signed le integer
*
* @param offset Offset to write at
*/
writeInt16LE(value: number, offset?: number): this;
/**
* Writes a 16bit signed be integer
*
* @param offset Offset to write at
*/
writeInt16BE(value: number, offset?: number): this;
/**
* Writes a 16bit unsigned le integer
*
* @param offset Offset to write at
*/
writeUInt16LE(value: number, offset?: number): this;
/**
* Writes a 16bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt16BE(value: number, offset?: number): this;
/**
* Writes a 32bit signed le integer
*
* @param offset Offset to write at
*/
writeInt32LE(value: number, offset?: number): this;
/**
* Writes a 32bit signed be integer
*
* @param offset Offset to write at
*/
writeInt32BE(value: number, offset?: number): this;
/**
* Writes a 32bit unsigned le integer
*
* @param offset Offset to write at
*/
writeUInt32LE(value: number, offset?: number): this;
/**
* Writes a 32bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt32BE(value: number, offset?: number): this;
/**
* Writes a 64bit signed le long integer
*
* @param offset Offset to write at
*/
writeInt64LE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit signed be long integer
*
* @param offset Offset to write at
*/
writeInt64BE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit unsigned le long integer
*
* @param offset Offset to write at
*/
writeUInt64LE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit unsigned be long integer
*
* @param offset Offset to write at
*/
writeUInt64BE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 32bit le float
*
* @param offset Offset to write at
*/
writeFloatLE(value: number, offset?: number): this;
/**
* Writes a 32bit be float
*
* @param offset Offset to write at
*/
writeFloatBE(value: number, offset?: number): this;
/**
* Writes a 64bit le float
*
* @param offset Offset to write at
*/
writeDoubleLE(value: number, offset?: number): this;
/**
* Writes a 64bit be float
*
* @param offset Offset to write at
*/
writeDoubleBE(value: number, offset?: number): this;
/**
* Writes a 32bit base 128 variable-length integer
*/
writeVarint32(value: number): this;
/**
* Writes a 32bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint32(value: number, offset: number): number;
/**
* Writes a zig-zag encoded 32bit base 128 variable-length integer
*/
writeVarint32ZigZag(value: number): this;
/**
* Writes a zig-zag encoded 32bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint32ZigZag(value: number, offset: number): number;
/**
* Reads a 32bit base 128 variable-length integer
*/
readVarint32(): number;
/**
* Reads a 32bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint32(offset: number): I.ByteArray.Varint32;
/**
* Reads a zig-zag encoded 32bit base 128 variable-length integer
*/
readVarint32ZigZag(): number;
/**
* Reads a zig-zag encoded 32bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint32ZigZag(offset: number): I.ByteArray.Varint32;
/**
* Writes a 64bit base 128 variable-length integer
*/
writeVarint64(value: math.Long | string | number): this;
/**
* Writes a 64bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint64(value: math.Long | string | number, offset: number): number;
/**
* Writes a zig-zag encoded 64bit base 128 variable-length integer
*/
writeVarint64ZigZag(value: math.Long | string | number): this;
/**
* Writes a zig-zag encoded 64bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint64ZigZag(value: math.Long | string | number, offset: number): number;
/**
* Reads a 64bit base 128 variable-length integer
*/
readVarint64(): I.Long;
/**
* Reads a 64bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint64(offset: number): I.ByteArray.Varint64;
/**
* Reads a zig-zag encoded 64bit base 128 variable-length integer
*/
readVarint64ZigZag(): math.Long;
/**
* Reads a zig-zag encoded 64bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint64ZigZag(offset: number): I.ByteArray.Varint64;
/**
* Writes a NULL-terminated UTF8 encoded string.
* For this to work the specified string must not contain any NULL characters itself
*/
writeCString(str: string): this;
/**
* Writes a NULL-terminated UTF8 encoded string.
* For this to work the specified string must not contain any NULL characters itself
*
* @param offset Offset to write at
*/
writeCString(str: string, offset: number): number;
/**
* Reads a NULL-terminated UTF8 encoded string.
* For this to work the string read must not contain any NULL characters itself
*/
readCString(): string;
/**
* Reads a NULL-terminated UTF8 encoded string.
* For this to work the string read must not contain any NULL characters itself
*
* @param offset Offset to read from
*/
readCString(offset: number): I.ByteArray.String;
/**
* Writes an UTF8 encoded string
*/
writeString(str: string): this;
/**
* Writes an UTF8 encoded string
*
* @param offset Offset to write at
*/
writeString(str: string, offset: number): number;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c")
*/
readString(length: number, metrics?: I.ByteArray.Metrics): string;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c")
* @param offset Offset to read from
*/
readString(length: number, metrics: I.ByteArray.Metrics, offset: number): I.ByteArray.String;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param offset Offset to read from
*/
readString(length: number, offset: number): I.ByteArray.String;
/**
* Writes a length as varint32 prefixed UTF8 encoded string
*/
writeVString(str: string): this;
/**
* Writes a length as varint32 prefixed UTF8 encoded string
*
* @param offset Offset to read from
*/
writeVString(str: string, offset: number): number;
/**
* Reads a length as varint32 prefixed UTF8 encoded string
*/
readVString(): string;
/**
* Reads a length as varint32 prefixed UTF8 encoded string
*
* @param offset Offset to read from
*/
readVString(offset: number): I.ByteArray.String;
/**
* Appends this ByteArray's contents to another ByteArray.
* This will overwrite any contents behind the specified offset up to the length of this ByteArray's data
*
* @param offset Offset to append to
*/
appendTo(target: ByteArray, offset?: number): this;
/**
* Enables or disables assertions of argument types and offsets.
* Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid
*/
assert(assert?: boolean): this;
/**
* Gets the capacity of this ByteArray's backing buffer
*/
capacity(): number;
/**
* Clears this ByteArray's offsets by setting offset to 0 and limit to the backing buffer's capacity
*/
clear(): this;
/**
* Creates a cloned instance of this ByteArray,
* preset with this ByteArray's values for offset, markedOffset and limit
*
* @param copy Whether to copy the backing buffer or to return another view on the same, false by default
*/
clone(copy?: boolean): ByteArray;
/**
* Compacts this ByteArray to be backed by a buffer of its contents' length.
* Will set offset = 0 and limit = capacity and adapt markedOffset to the same relative position if set
*
* @param begin Offset to start at, buffer offset by default
* @param end Offset to end at, buffer limit by default
*/
compact(begin?: number, end?: number): this;
/**
* Creates a copy of this ByteArray's contents.
*
* @param begin Begin offset, buffer offset by default
* @param end End offset, buffer limit by default
*/
copy(begin?: number, end?: number): ByteArray;
/**
* Copies this ByteArray's contents to another ByteArray.
*
* @param targetOffset Offset to copy to. Will use and increase the target's offset by the number of bytes copied if omitted
* @param sourceOffset Offset to start copying from. Will use and increase offset by the number of bytes copied if omitted
* @param sourceLimit Offset to end copying from, defaults to the buffer limit
*/
copyTo(target: ByteArray, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ByteArray;
/**
* Makes sure that this ByteArray is backed by a ByteArray#buffer of at least the specified capacity.
* If the current capacity is exceeded, it will be doubled.
* If double the current capacity is less than the required capacity, the required capacity will be used instead
*/
ensureCapacity(capacity: number): this;
/**
* Overwrites this ByteArray's contents with the specified value.
*
* @param value Byte value to fill with. If given as a string, the first character is used
* @param begin Begin offset. Will use and increase offset by the number of bytes written if omitted. defaults to offset
* @param end End offset, defaults to limit.
*/
fill(value: string | number, begin?: number, end?: number): this;
/**
* Makes this ByteArray ready for a new sequence of write or relative read operations.
* Sets limit = offset and offset = 0.
* Make sure always to flip a ByteArray when all relative read or write operations are complete
*/
flip(): this;
/**
* Marks an offset on this ByteArray to be used later
*
* @param offset Offset to mark. Defaults to offset.
*/
mark(offset?: number): this;
/**
* Prepends some data to this ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param source Data to prepend
* @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted.
*/
prepend(source: I.ByteArray.Wrappable, offset: number): this;
/**
* Prepends some data to this ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param source Data to prepend
* @param encoding Encoding if data is a string
* @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted.
*/
prepend(source: I.ByteArray.Wrappable, encoding?: string, offset?: number): this;
/**
* Prepends this ByteArray to another ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param offset Offset to prepend at
*/
prependTo(target: ByteArray, offset?: number): this;
/**
* Gets the number of remaining readable bytes
*/
remaining(): number;
/**
* Resets this ByteArray's offset.
* If an offset has been marked through mark before, offset will be set to markedOffset, which will then be discarded.
* If no offset has been marked, sets offset = 0
*/
reset(): this;
/**
* Resizes this ByteArray to be backed by a buffer of at least the given capacity.
* Will do nothing if already that large or larger.
*
* @param capacity Capacity required
*/
resize(capacity: number): this;
/**
* Reverses this ByteArray's contents.
*
* @param begin Offset to start at, defaults to offset
* @param end Offset to end at, defaults to limit
*/
reverse(begin?: number, end?: number): this;
/**
* Skips the next length bytes. This will just advance
*/
skip(length: number): this;
/**
* Slices this ByteArray by creating a cloned instance with offset = begin and limit = end
*
* @param begin Begin offset, defaults to offset
* @param end End offset, defaults to limit
*/
slice(begin?: number, end?: number): ByteArray;
/**
* Returns a copy of the backing buffer that contains this ByteArray's contents.
*
* @param forceCopy If true returns a copy, otherwise returns a view referencing the same memory if possible, false by default
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer;
/**
* Returns a raw buffer compacted to contain this ByteArray's contents
*/
toArrayBuffer(): ArrayBuffer;
/**
* Converts the ByteArray's contents to a string
*
* @param encoding Output encoding
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toString(encoding?: string, begin?: number, end?: number): string;
/**
* Encodes this ByteArray's contents to a base64 encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBase64(begin?: number, end?: number): string;
/**
* Encodes this ByteArray to a binary encoded string, that is using only characters 0x00-0xFF as bytes
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBinary(begin?: number, end?: number): string;
/**
* Encodes this ByteArray to a hex encoded string with marked offsets
*
* @param columns If true returns two columns hex + ascii, defaults to false
*/
toDebug(columns?: boolean): string;
/**
* Encodes this ByteArray's contents to a hex encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toHex(begin?: number, end?: number): string;
/**
* Encodes this ByteArray's contents to an UTF8 encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toUTF8(begin?: number, end?: number): string;
static accessor(): typeof Buffer;
/**
* Allocates a new ByteArray backed by a buffer of the specified capacity.
*
* @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64)
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static allocate(capacity?: number, noAssert?: boolean): ByteArray;
/**
* Concatenates multiple ByteArrays into one
*
* @param encoding Encoding for strings
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static concat(buffers: I.ByteArray.Wrappable[], encoding?: string, noAssert?: boolean): ByteArray;
static type(): typeof Buffer;
/**
* Wraps a buffer or a string.
* Sets the allocated ByteArray's offset to 0 and its limit to the length of the wrapped data
*
* @param encoding Encoding for strings
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static wrap(buffer: I.ByteArray.Wrappable, encoding?: string, noAssert?: boolean): ByteArray;
/**
* Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer
*/
static calculateVarint32(value: number): number;
/**
* Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding
*/
static zigZagEncode32(n: number): number;
/**
* Decodes a zigzag encoded signed 32bit integer
*/
static zigZagDecode32(n: number): number;
/**
* Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer
*/
static calculateVarint64(value: number | string): number;
/**
* Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding
*/
static zigZagEncode64(value: number | string | I.Long): I.Long;
/**
* Decodes a zigzag encoded signed 64bit integer.
*/
static zigZagDecode64(value: number | string | I.Long): I.Long;
/**
* Calculates the number of UTF8 characters of a string.
* JavaScript itself uses UTF-16,
* so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF
*/
static calculateUTF8Chars(str: string): number;
/**
* Calculates the number of UTF8 bytes of a string.
*/
static calculateString(str: string): number;
/**
* Decodes a base64 encoded string to a ByteArray
*/
static fromBase64(str: string): ByteArray;
/**
* Encodes a binary string to base64 like window.btoa does
*/
static btoa(str: string): string;
/**
* Decodes a base64 encoded string to binary like window.atob does
*/
static atob(b64: string): string;
/**
* Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteArray
*/
static fromBinary(str: string): ByteArray;
/**
* Decodes a hex encoded string with marked offsets to a ByteArray
*/
static fromDebug(str: string, noAssert?: boolean): ByteArray;
/**
* Decodes a hex encoded string to a ByteArray
*/
static fromHex(str: string, noAssert?: boolean): ByteArray;
/**
* Decodes an UTF8 encoded string to a ByteArray
*/
static fromUTF8(str: string, noAssert?: boolean): ByteArray;
/**
* Default initial capacity
*/
static DEFAULT_CAPACITY: number;
/**
* Default no assertions flag
*/
static DEFAULT_NOASSERT: boolean;
/**
* Maximum number of bytes required to store a 32bit base 128 variable-length integer
*/
static MAX_VARINT32_BYTES: number;
/**
* Maximum number of bytes required to store a 64bit base 128 variable-length integer
*/
static MAX_VARINT64_BYTES: number;
/**
* Metrics representing number of UTF8 characters. Evaluates to `c`.
*/
static METRICS_CHARS: string;
/**
* Metrics representing number of bytes. Evaluates to `b`.
*/
static METRICS_BYTES: string;
}
}

View File

@@ -0,0 +1,9 @@
declare namespace adone.collection {
/**
* Represents a Map that has a default values factory object or function.
* Each get of non-existent key goes through the factory
*/
class DefaultMap<K = string, V = any> extends Map<K, V> {
constructor(factory?: ((key: K) => V) | { [key: string]: V }, iterable?: Iterable<[K, V]>);
}
}

View File

@@ -0,0 +1,61 @@
declare namespace adone.collection {
/**
* Represents a faster LRU cache but with less functionality
*/
class FastLRU<K = any, V = any> {
/**
* @param size Cache size, unlimited by default
*/
constructor(size?: number, options?: {
/**
* Function that is called when a value is deleted
*/
dispose?(key: K, value: V): void
});
/**
* The actual size of the cache
*/
readonly size: number;
/**
* Gets the value by the given key
*/
get(key: K): V | undefined;
/**
* Sets a new value for the given key
*/
set(key: K, value: V): void;
/**
* Deletes the given key from the cache
*/
delete(key: K): boolean;
/**
* Checks whether the cache has an element with the given key
*/
has(key: K): boolean;
/**
* Returns the keys iterator
*/
keys(): IterableIterator<K>;
/**
* Returns the values iterator
*/
values(): IterableIterator<V>;
/**
* Returns the entries iterator
*/
entries(): IterableIterator<[K, V]>;
/**
* Clears the cache
*/
clear(): void;
}
}

View File

@@ -0,0 +1,28 @@
/// <reference path="./array_set.d.ts" />
/// <reference path="./async_queue.d.ts" />
/// <reference path="./avl_tree.d.ts" />
/// <reference path="./binary_search_tree.d.ts" />
/// <reference path="./buffer_list.d.ts" />
/// <reference path="./byte_array.d.ts" />
/// <reference path="./default_map.d.ts" />
/// <reference path="./fast_lru.d.ts" />
/// <reference path="./linked_list.d.ts" />
/// <reference path="./lru.d.ts" />
/// <reference path="./map_cache.d.ts" />
/// <reference path="./ns_cache.d.ts" />
/// <reference path="./priority_queue.d.ts" />
/// <reference path="./queue.d.ts" />
/// <reference path="./rb_tree.d.ts" />
/// <reference path="./refcounted_cache.d.ts" />
/// <reference path="./set.d.ts" />
/// <reference path="./stack.d.ts" />
/// <reference path="./timedout_map.d.ts" />
declare namespace adone {
/**
* Data structures
*/
namespace collection {
//
}
}

View File

@@ -0,0 +1,150 @@
declare namespace adone.collection {
namespace I.LinkedList {
/**
* Represents the node of a linked list
*/
interface Node<T> {
/**
* The next node
*/
next?: Node<T>;
/**
* The previous node
*/
prev?: Node<T>;
/**
* The value this node contains
*/
value: T;
}
}
/**
* Represents a linked list
*/
class LinkedList<T = any> {
/**
* The maximum length of the list
*/
readonly maxLength: number;
/**
* Current length of the list
*/
readonly length: number;
/**
* Whether the list is autoresizable
*/
readonly autoresize: boolean;
/**
* @param maxLength Maximum length of the linked list
*/
constructor(maxLength?: number);
/**
* Whether the list is full
*/
readonly full: boolean;
/**
* Whether the list is empty
*/
readonly empty: boolean;
/**
* Resizes the list
*/
resize(newLength: number): this;
/**
* Adds a new node to the end
*
* @returns Added node
*/
push(value: T): I.LinkedList.Node<T>;
/**
* Removes the last node, returns undefined if the list is empty
*/
pop(): T | undefined;
/**
* Removes the first node, returns undefined if the list is empty
*/
shift(): T | undefined;
/**
* Inserts a new node at the beginning of the list
*
* @returns Added node
*/
unshift(value: T): I.LinkedList.Node<T>;
/**
* Moves the given node to the end of the list
*/
pushNode(node: I.LinkedList.Node<T>): void;
/**
* Moved the given node to the beginning of the list
*/
unshiftNode(node: I.LinkedList.Node<T>): void;
/**
* Removes the given node from the list
*/
removeNode(node: I.LinkedList.Node<T>): void;
/**
* Clears the list
*
* @param strong Whether to reset all the node's values
*/
clear(strong?: boolean): void;
/**
* Convers the list to an array
*/
toArray(): T[];
/**
* The first element of the list
*/
readonly front: T;
/**
* The last element of the list
*/
readonly back: T;
/**
* Returns an iterator over the list elements
*/
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns the next node for the given node
*/
nextNode(node: I.LinkedList.Node<T>): I.LinkedList.Node<T>;
/**
* Maps this linked list to a new one using the given function
*/
map<R>(fn: (value: T, index: number) => R): LinkedList<R>;
/**
* Invokes the given callback for each value from the beginning to the end (much faster than for-of).
* If the given function returns false it stops iterating.
*/
forEach(callback: (value: T, index: number) => void | boolean): void;
/**
* Default length of a new created linked list
*/
static DEFAULT_LENGTH: number;
}
}

213
types/adone/glosses/collections/lru.d.ts vendored Normal file
View File

@@ -0,0 +1,213 @@
declare namespace adone.collection {
namespace I.LRU {
type LengthCalculator<K, V> = (value: V, key: K) => number;
interface ConstructorOptions<K, V> {
/**
* The maximum size of the cache, checked by applying the length function to all values in the cache.
* Default is Infinity
*/
max?: number;
/**
* Maximum age in ms. Items are not pro-actively pruned out as they age,
* but if you try to get an item that is too old,
* it'll drop it and return undefined instead of giving it to you
*/
maxAge?: number;
/**
* Function that is used to calculate the length of stored items
*/
length?: LengthCalculator<K, V>;
/**
* Function that is called on items when they are dropped from the cache
*/
dispose?(key: K, value: V): void;
/**
* Whether to return the stale value before deleting it
*/
stale?: boolean;
/**
* Dispose will only be called when a key falls out of the cache, not when it is overwritten
*/
noDisposeOnSet?: boolean;
}
interface SerializedEntry<K, V> {
/**
* key
*/
key: K;
/**
* value
*/
value: V;
/**
* when it becomes expired
*/
e: number;
}
interface Entry<K, V> {
/**
* key
*/
key: K;
/**
* value
*/
value: V;
/**
* entry length
*/
length: number;
/**
* Timestamp when the entry was created
*/
now: number;
/**
* Maximum live time
*/
maxAge: number;
}
}
/**
* Represent an LRU cache
*/
class LRU<K = any, V = any> {
/**
* Creates an LRU cache of the given size
*/
constructor(max: number);
/**
* Creates an LRU cache with the given options
*/
constructor(options?: I.LRU.ConstructorOptions<K, V>);
/**
* The length of the cache, setter resizes the cache
*/
max: number;
/**
* stale setting
*/
allowStale: boolean;
/**
* maxAge setting
*/
maxAge: number;
/**
* length setting
*/
lengthCalculator: I.LRU.LengthCalculator<K, V>;
/**
* Total length of objects in cache taking into account length options function
*/
readonly length: number;
/**
* Total quantity of objects currently in cache.
* Note, that stale items are returned as part of this item count.
*/
readonly itemCount: number;
/**
* Iterates over all the keys in the cache, in reverse recent-ness order. (ie, less recently used items are iterated over first.)
*/
rforEach<T = any>(fn: (this: T, value: V, key: K, cache: LRU<K, V>) => void, thisp?: T): void;
/**
* Iterates over all the keys in the cache, in order of recent-ness
*/
forEach<T = any>(fn: (this: T, value: V, key: K, cache: LRU<K, V>) => void, thisp?: T): void;
/**
* Returns an array of the keys in the cache
*/
keys(): K[];
/**
* Returns an array of the values in the cache
*/
values(): V[];
/**
* Clears the cache entirely, throwing away all values
*/
reset(): void;
/**
* Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`
*/
dump(): Array<I.LRU.SerializedEntry<K, V>>;
/**
* Returns an internal lru list of entries
*/
dumpLru(): LinkedList<I.LRU.Entry<K, V>>;
/**
* @param opts std.util.inspect options
*/
inspect(opts?: object): string;
/**
* Sets a new value for the given key. Updates the "recently used"-ness of the key
*
* @param maxAge maxAge option specific for this key
* @returns Whether the key was set
*/
set(key: K, value: V, maxAge?: number): boolean;
/**
* Check if a key is in the cache, without updating the recent-ness or deleting it for being stale
*/
has(key: K): boolean;
/**
* Gets the value of the given key. Updates the "recently used"-ness of the key
*/
get(key: K): V | undefined;
/**
* Returns the key value without updating the "recently used"-ness of the key
*/
peek(key: K): V | undefined;
/**
* Deletes the less recently used element
*/
pop(): I.LRU.Entry<K, V>;
/**
* Deletes a key out of the cache
*/
del(key: K): void;
/**
* Loads another cache entries array, obtained with sourceCache.dump(), into the cache.
* The destination cache is reset before loading new entries
*/
load(arr: Array<I.LRU.SerializedEntry<K, V>>): void;
/**
* Manually iterates over the entire cache proactively pruning old entries
*/
prune(): void;
}
}

View File

@@ -0,0 +1,13 @@
declare namespace adone.collection {
class MapCache<T = any> {
has(key: string): boolean;
get(key: string): T;
set(key: string, value: T): void;
delete(key: string): void;
clear(): void;
}
}

Some files were not shown because too many files have changed in this diff Show More