diff --git a/types/actions-on-google/NOTICE b/types/actions-on-google/NOTICE new file mode 100644 index 0000000000..262b08db36 --- /dev/null +++ b/types/actions-on-google/NOTICE @@ -0,0 +1,13 @@ +License Notices: + +The API definitions are from Actions on Google reference site [1] and actions-on-google library [2]. +The actions-on-google library is licensed under the Apache 2.0 License [3]. + +The code documentation is reproduced from work created and shared by Google [4] +and used according to terms described in the Creative Commons 3.0 Attribution License [5]. + +[1] https://developers.google.com/actions/ +[2] https://github.com/actions-on-google/actions-on-google-nodejs +[3] http://www.apache.org/licenses/LICENSE-2.0 +[4] https://developers.google.com/readme/policies/ +[5] http://creativecommons.org/licenses/by/3.0/ diff --git a/types/actions-on-google/actions-on-google-tests.ts b/types/actions-on-google/actions-on-google-tests.ts new file mode 100644 index 0000000000..e57e1e8d98 --- /dev/null +++ b/types/actions-on-google/actions-on-google-tests.ts @@ -0,0 +1,33 @@ +import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp, + Responses, Transactions } from 'actions-on-google'; +import * as express from 'express'; + +function testActionsSdk(request: express.Request, response: express.Response) { + const app = new ActionsSdkApp({request, response}); + const actionMap = new Map(); + actionMap.set(app.StandardIntents.MAIN, () => { + const richResponse: Responses.RichResponse = app.buildRichResponse() + .addSimpleResponse('Hello world') + .addSuggestions(['foo', 'bar']); + app.ask(richResponse); + }); + app.handleRequest(actionMap); +} + +function testDialogflow(request: express.Request, response: express.Response) { + const app = new DialogflowApp({request, response}); + const actionMap = new Map(); + actionMap.set(app.StandardIntents.MAIN, () => { + const order: Transactions.Order = app.buildOrder('foo'); + app.askForTransactionDecision(order, { + type: app.Transactions.PaymentType.PAYMENT_CARD, + displayName: 'VISA-1234', + deliveryAddressRequired: true + }); + }); + app.handleRequest(actionMap); +} + +const expressApp = express(); +expressApp.get('/actionssdk', testActionsSdk); +expressApp.get('/dialogflow', testDialogflow); diff --git a/types/actions-on-google/actions-sdk-app.d.ts b/types/actions-on-google/actions-sdk-app.d.ts new file mode 100644 index 0000000000..8de0de0cfb --- /dev/null +++ b/types/actions-on-google/actions-sdk-app.d.ts @@ -0,0 +1,390 @@ +import * as express from 'express'; + +import { AssistantApp } from './assistant-app'; +import { Carousel, List, RichResponse, SimpleResponse } from './response-builder'; + +// --------------------------------------------------------------------------- +// Actions SDK support +// --------------------------------------------------------------------------- + +export interface ActionsSdkAppOptions { + /** Express HTTP request object. */ + request: express.Request; + /** Express HTTP response object. */ + response: express.Response; + /** Function callback when session starts. */ + sessionStarted?(): any; +} + +/** + * This is the class that handles the conversation API directly from Assistant, + * providing implementation for all the methods available in the API. + */ +export class ActionsSdkApp extends AssistantApp { + /** + * Constructor for ActionsSdkApp object. + * To be used in the Actions SDK HTTP endpoint logic. + * + * @example + * const ActionsSdkApp = require('actions-on-google').ActionsSdkApp; + * const app = new ActionsSdkApp({request: request, response: response, + * sessionStarted:sessionStarted}); + * + * @actionssdk + */ + constructor(options: ActionsSdkAppOptions); + + /** + * Validates whether request is from Assistant through signature verification. + * Uses Google-Auth-Library to verify authorization token against given + * Google Cloud Project ID. Auth token is given in request header with key, + * "Authorization". + * + * @example + * const app = new ActionsSdkApp({request, response}); + * app.isRequestFromAssistant('nodejs-cloud-test-project-1234') + * .then(() => { + * app.ask('Hey there, thanks for stopping by!'); + * }) + * .catch(err => { + * response.status(400).send(); + * }); + * + * @param projectId Google Cloud Project ID for the Assistant app. + * @return Promise resolving with google-auth-library LoginTicket + * if request is from a valid source, otherwise rejects with the error reason + * for an invalid token. + * @actionssdk + */ + isRequestFromAssistant(projectId: string): Promise; + + /** + * Gets the request Conversation API version. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const apiVersion = app.getApiVersion(); + * + * @return Version value or null if no value. + * @actionssdk + */ + getApiVersion(): string; + + /** + * Gets the user's raw input query. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * app.tell('You said ' + app.getRawInput()); + * + * @return User's raw query or null if no value. + * @actionssdk + */ + getRawInput(): string; + + /** + * Gets previous JSON dialog state that the app sent to Assistant. + * Alternatively, use the app.data field to store JSON values between requests. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const dialogState = app.getDialogState(); + * + * @return JSON object provided to the Assistant in the previous + * user turn or {} if no value. + * @actionssdk + */ + getDialogState(): any; + + /** + * Gets the "versionLabel" specified inside the Action Package. + * Used by app to do version control. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const actionVersionLabel = app.getActionVersionLabel(); + * + * @return The specified version label or null if unspecified. + * @actionssdk + */ + getActionVersionLabel(): string; + + /** + * Gets the unique conversation ID. It's a new ID for the initial query, + * and stays the same until the end of the conversation. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const conversationId = app.getConversationId(); + * + * @return Conversation ID or null if no value. + * @actionssdk + */ + getConversationId(): string; + + /** + * Get the current intent. Alternatively, using a handler Map with + * {@link AssistantApp#handleRequest|handleRequest}, the client library will + * automatically handle the incoming intents. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function responseHandler (app) { + * const intent = app.getIntent(); + * switch (intent) { + * case app.StandardIntents.MAIN: + * const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say anything.'); + * app.ask(inputPrompt); + * break; + * + * case app.StandardIntents.TEXT: + * app.tell('You said ' + app.getRawInput()); + * break; + * } + * } + * + * app.handleRequest(responseHandler); + * + * @return Intent id or null if no value. + * @actionssdk + */ + getIntent(): string; + + /** + * Get the argument value by name from the current intent. If the argument + * is not a text argument, the entire argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @param argName Name of the argument. + * @return Argument value matching argName + * or null if no matching argument. + * @actionssdk + */ + getArgument(argName: string): string; + + /** + * Returns the option key user chose from options response. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * function optionPicked (app) { + * app.ask('You picked ' + app.getSelectedOption()); + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, pickOption); + * actionMap.set(app.StandardIntents.OPTION, optionPicked); + * + * app.handleRequest(actionMap); + * + * @return Option key of selected item. Null if no option selected or + * if current intent is not OPTION intent. + * @actionssdk + */ + getSelectedOption(): string; + + /** + * Asks to collect user's input; all user's queries need to be sent to + * the app. + * {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * @param inputPrompt Holding initial and + * no-input prompts. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by App. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + ask(inputPrompt: object | SimpleResponse | RichResponse, dialogState?: object): express.Response | null; + + /** + * Asks to collect user's input with a list. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcomeIntent (app) { + * app.askWithlist('Which of these looks good?', + * app.buildList('List title') + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, welcomeIntent); + * actionMap.set(app.StandardIntents.OPTION, optionIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt Holding initial and + * no-input prompts. Cannot contain basic card. + * @param list List built with {@link AssistantApp#buildList|buildList}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + askWithList(inputPrompt: object | SimpleResponse | RichResponse, list: List, dialogState?: object): express.Response | null; + + /** + * Asks to collect user's input with a carousel. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcomeIntent (app) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel() + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, welcomeIntent); + * actionMap.set(app.StandardIntents.OPTION, optionIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt Holding initial and + * no-input prompts. Cannot contain basic card. + * @param carousel Carousel built with + * {@link AssistantApp#buildCarousel|buildCarousel}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + askWithCarousel(inputPrompt: object | SimpleResponse | RichResponse, carousel: Carousel, dialogState?: object): express.Response | null; + + /** + * Tells Assistant to render the speech response and close the mic. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * @param textToSpeech Final response. + * Spoken response can be SSML. + * @return The HTTP response that is sent back to Assistant. + * @actionssdk + */ + tell(textToSpeech: string | SimpleResponse | RichResponse): express.Response | null; + + /** + * Builds the {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object} + * from initial prompt and no-input prompts. + * + * The App needs one initial prompt to start the conversation. If there is no user response, + * the App re-opens the mic and renders the no-input prompts three times + * (one for each no-input prompt that was configured) to help the user + * provide the right response. + * + * Note: we highly recommend app to provide all the prompts required here in order to ensure a + * good user experience. + * + * @example + * const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say a number.', + * ['Say any number', 'Pick a number', 'What is the number?']); + * app.ask(inputPrompt); + * + * @param isSsml Indicates whether the text to speech is SSML or not. + * @param initialPrompt The initial prompt the App asks the user. + * @param noInputs Array of re-prompts when the user does not respond (max 3). + * @return. + * @actionssdk + */ + buildInputPrompt(isSsml: boolean, initialPrompt: string, noInputs?: string[]): object; +} diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts new file mode 100644 index 0000000000..d33f447a2e --- /dev/null +++ b/types/actions-on-google/assistant-app.d.ts @@ -0,0 +1,1316 @@ +import * as express from 'express'; + +import { BasicCard, Carousel, List, OptionItem, RichResponse } from './response-builder'; +import { ActionPaymentTransactionConfig, Cart, GooglePaymentTransactionConfig, LineItem, + Location, Order, OrderUpdate, TransactionDecision, TransactionValues } from './transactions'; + +/** + * List of standard intents that the app provides. + * @actionssdk + * @dialogflow + */ +export enum StandardIntents { + /** + * App fires MAIN intent for queries like [talk to $app]. + */ + MAIN, + /** + * App fires TEXT intent when action issues ask intent. + */ + TEXT, + /** + * App fires PERMISSION intent when action invokes askForPermission. + */ + PERMISSION, + /** + * App fires OPTION intent when user chooses from options provided. + */ + OPTION, + /** + * App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. + */ + TRANSACTION_REQUIREMENTS_CHECK, + /** + * App fires DELIVERY_ADDRESS intent when action asks for delivery address. + */ + DELIVERY_ADDRESS, + /** + * App fires TRANSACTION_DECISION intent when action asks for transaction decision. + */ + TRANSACTION_DECISION, + /** + * App fires CONFIRMATION intent when requesting affirmation from user. + */ + CONFIRMATION, + /** + * App fires DATETIME intent when requesting date/time from user. + */ + DATETIME, + /** + * App fires SIGN_IN intent when requesting sign-in from user. + */ + SIGN_IN, + /** + * App fires NO_INPUT intent when user doesn't provide input. + */ + NO_INPUT, + /** + * App fires CANCEL intent when user exits app mid-dialog. + */ + CANCEL, + /** + * App fires NEW_SURFACE intent when requesting handoff to a new surface from user. + */ + NEW_SURFACE, +} + +/** + * List of supported permissions the app supports. + * @actionssdk + * @dialogflow + */ +export enum SupportedPermissions { + /** + * The user's name as defined in the + * {@link https://developers.google.com/actions/reference/conversation#UserProfile|UserProfile object} + */ + NAME, + /** + * The location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + DEVICE_PRECISE_LOCATION, + /** + * City and zipcode corresponding to the location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + DEVICE_COARSE_LOCATION, +} + +/** + * List of built-in argument names. + * @actionssdk + * @dialogflow + */ +export enum BuiltInArgNames { + /** + * Permission granted argument. + */ + PERMISSION_GRANTED, + /** + * Option selected argument. + */ + OPTION, + /** + * Transaction requirements check result argument. + */ + TRANSACTION_REQ_CHECK_RESULT, + /** + * Delivery address value argument. + */ + DELIVERY_ADDRESS_VALUE, + /** + * Transactions decision argument. + */ + TRANSACTION_DECISION_VALUE, + /** + * Confirmation argument. + */ + CONFIRMATION, + /** + * DateTime argument. + */ + DATETIME, + /** + * Sign in status argument. + */ + SIGN_IN, + /** + * Reprompt count for consecutive NO_INPUT intents. + */ + REPROMPT_COUNT, + /** + * Flag representing finality of NO_INPUT intent. + */ + IS_FINAL_REPROMPT, + /** + * New surface value argument. + */ + NEW_SURFACE, +} + +/** + * List of possible conversation stages, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ +export enum ConversationStages { + /** + * Unspecified conversation state. + */ + UNSPECIFIED, + /** + * A new conversation. + */ + NEW, + /** + * An active (ongoing) conversation. + */ + ACTIVE, +} + +/** + * List of surface capabilities supported by the app. + * @actionssdk + * @dialogflow + */ +export enum SurfaceCapabilities { + /** + * The ability to output audio. + */ + AUDIO_OUTPUT, + /** + * The ability to output on a screen + */ + SCREEN_OUTPUT, +} + +/** + * List of possible user input types. + * @actionssdk + * @dialogflow + */ +export enum InputTypes { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * Input given by touch. + */ + TOUCH, + /** + * Input given by voice (spoken). + */ + VOICE, + /** + * Input given by keyboard (typed). + */ + KEYBOARD +} + +/** + * List of possible sign in result status values. + * @actionssdk + * @dialogflow + */ +export enum SignInStatus { + /** + * Unknown status. + */ + UNSPECIFIED, + /** + * User successfully completed the account linking. + */ + OK, + /** + * Cancelled or dismissed account linking. + */ + CANCELLED, + /** + * System or network error. + */ + ERROR +} + +/** + * User provided date/time info. + */ +export interface DateTime { + date: { + year: number; + month: number; + day: number; + }; + time: { + hours: number; + minutes: number; + seconds: number; + nanos: number; + }; +} + +/** + * User's permissioned name info. + */ +export interface UserName { + /** User's display name. */ + displayName: string; + /** User's given name. */ + givenName: string; + /** User's family name. */ + familyName: string; +} + +/** + * User's permissioned device location. + */ +export interface DeviceLocation { + /** {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ + coordinates: object; + /** Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ + address: string; + /** Zip code. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */ + zipCode: string; + /** Device city. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */ + city: string; +} + +/** + * User object. + */ +export interface User { + /** Random string ID for Google user. */ + userId: string; + /** User name information. Null if not requested with {@link AssistantApp#askForPermission|askForPermission(SupportedPermissions.NAME)}. */ + userName: UserName; + /** Unique Oauth2 token. Only available with account linking. */ + accessToken: string; +} + +/** + * Actions on Google Surface. + */ +export interface Surface { + /** Capabilities of the surface. */ + capabilities: Capability[]; +} + +/** + * Surface capability. + */ +export interface Capability { + /** Name of the capability. */ + name: string; +} + +/** + * The Actions on Google client library AssistantApp base class. + * + * This class contains the methods that are shared between platforms to support the conversation API + * protocol from Assistant. It also exports the 'State' class as a helper to represent states by + * name. + */ +export class AssistantApp { + /** + * The session state. + */ + state: string; + + /** + * The session data in JSON format. + */ + data: object; + + /** + * List of standard intents that the app provides. + * @actionssdk + * @dialogflow + */ + readonly StandardIntents: typeof StandardIntents; + + /** + * List of supported permissions the app supports. + * @actionssdk + * @dialogflow + */ + readonly SupportedPermissions: typeof SupportedPermissions; + + /** + * List of built-in argument names. + * @actionssdk + * @dialogflow + */ + readonly BuiltInArgNames: typeof BuiltInArgNames; + + /** + * List of possible conversation stages, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ + readonly ConversationStages: typeof ConversationStages; + + /** + * List of surface capabilities supported by the app. + * @actionssdk + * @dialogflow + */ + readonly SurfaceCapabilities: typeof SurfaceCapabilities; + + /** + * List of possible user input types. + * @actionssdk + * @dialogflow + */ + readonly InputTypes: typeof InputTypes; + + /** + * List of possible sign in result status values. + * @actionssdk + * @dialogflow + */ + readonly SignInStatus: typeof SignInStatus; + + /** + * Values related to supporting {@link Transactions}. + */ + readonly Transactions: typeof TransactionValues; + + // --------------------------------------------------------------------------- + // Public APIs + // --------------------------------------------------------------------------- + + /** + * Handles the incoming Assistant request using a handler or Map of handlers. + * Each handler can be a function callback or Promise. + * + * @example + * // Actions SDK + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * // Dialogflow + * const app = new DialogflowApp({request: req, response: res}); + * const NAME_ACTION = 'make_name'; + * const COLOR_ARGUMENT = 'color'; + * const NUMBER_ARGUMENT = 'number'; + * + * function makeName (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * const color = app.getArgument(COLOR_ARGUMENT); + * app.tell('Alright, your silly name is ' + + * color + ' ' + number + + * '! I hope you like it. See you next time.'); + * } + * + * const actionMap = new Map(); + * actionMap.set(NAME_ACTION, makeName); + * app.handleRequest(actionMap); + * + * @param handler The handler (or Map of handlers) for the request. + * @actionssdk + * @dialogflow + */ + handleRequest(handler: ((app: AssistantApp) => any) | (Map any>)): void; + + /** + * Equivalent to {@link AssistantApp#askForPermission|askForPermission}, + * but allows you to prompt the user for more than one permission at once. + * + * Notes: + * + * * The order in which you specify the permission prompts does not matter - + * it is controlled by the Assistant to provide a consistent user experience. + * * The user will be able to either accept all permissions at once, or none. + * If you wish to allow them to selectively accept one or other, make several + * dialog turns asking for each permission independently with askForPermission. + * * Asking for DEVICE_COARSE_LOCATION and DEVICE_PRECISE_LOCATION at once is + * equivalent to just asking for DEVICE_PRECISE_LOCATION + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const GET_RIDE_ACTION = 'get_ride'; + * + * function requestPermission (app) { + * const permission = [ + * app.SupportedPermissions.NAME, + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION + * ]; + * app.askForPermissions('To pick you up', permissions); + * } + * + * function sendRide (app) { + * if (app.isPermissionGranted()) { + * const displayName = app.getUserName().displayName; + * const address = app.getDeviceLocation().address; + * app.tell('I will tell your driver to pick up ' + displayName + + * ' at ' + address); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not figure out where to pick you up.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(GET_RIDE_ACTION, sendRide); + * app.handleRequest(actionMap); + * + * @param context Context why the permission is being asked; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param permissions Array of permissions App supports, each of + * which comes from AssistantApp.SupportedPermissions. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return A response is sent to Assistant to ask for the user's permission; for any + * invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForPermissions(context: string, permissions: string[], dialogState?: object): express.Response | null; + + /** + * Checks whether user is in transactable state. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const TXN_REQ_COMPLETE = 'txn.req.complete'; + * + * let transactionConfig = { + * deliveryAddressRequired: false, + * type: app.Transactions.PaymentType.BANK, + * displayName: 'Checking-1234' + * }; + * function welcomeIntent (app) { + * app.askForTransactionRequirements(transactionConfig); + * } + * + * function txnReqCheck (app) { + * if (app.getTransactionRequirementsResult() === app.Transactions.ResultType.OK) { + * // continue cart building flow + * } else { + * // don't continue cart building + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(TXN_REQ_COMPLETE, txnReqCheck); + * app.handleRequest(actionMap); + * + * @param + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. Optional if order has no payment or + * delivery. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForTransactionRequirements(transactionConfig?: ActionPaymentTransactionConfig | GooglePaymentTransactionConfig, dialogState?: object): express.Response | null; + + /** + * Asks user to confirm transaction information. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const TXN_COMPLETE = 'txn.complete'; + * + * let transactionConfig = { + * deliveryAddressRequired: false, + * type: app.Transactions.PaymentType.BANK, + * displayName: 'Checking-1234' + * }; + * + * let order = app.buildOrder(); + * // fill order cart + * + * function welcomeIntent (app) { + * app.askForTransaction(order, transactionConfig); + * } + * + * function txnComplete (app) { + * // respond with order update + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(TXN_COMPLETE, txnComplete); + * app.handleRequest(actionMap); + * + * @param order Order built with buildOrder(). + * @param + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return HTTP response + * @dialogflow + */ + askForTransactionDecision(order: Order, transactionConfig: ActionPaymentTransactionConfig | GooglePaymentTransactionConfig, dialogState?: object): express.Response | null; + + /** + * Asks the Assistant to guide the user to grant a permission. For example, + * if you want your app to get access to the user's name, you would invoke + * the askForPermission method with a context containing the reason for the request, + * and the AssistantApp.SupportedPermissions.NAME permission. With this, the Assistant will ask + * the user, in your agent's voice, the following: '[Context with reason for the request], + * I'll just need to get your name from Google, is that OK?'. + * + * Once the user accepts or denies the request, the Assistant will fire another intent: + * assistant.intent.action.PERMISSION with a boolean argument: AssistantApp.BuiltInArgNames.PERMISSION_GRANTED + * and, if granted, the information that you requested. + * + * Read more: + * + * * {@link https://developers.google.com/actions/reference/conversation#ExpectedIntent|Supported Permissions} + * * Check if the permission has been granted with {@link AssistantApp#isPermissionGranted|isPermissionsGranted} + * * {@link AssistantApp#getDeviceLocation|getDeviceLocation} + * * {@link AssistantApp#getUserName|getUserName} + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const GET_RIDE_ACTION = 'get_ride'; + * + * function requestPermission (app) { + * const permission = app.SupportedPermissions.NAME; + * app.askForPermission('To pick you up', permission); + * } + * + * function sendRide (app) { + * if (app.isPermissionGranted()) { + * const displayName = app.getUserName().displayName; + * app.tell('I will tell your driver to pick up ' + displayName); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not figure out who to pick up.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(GET_RIDE_ACTION, sendRide); + * app.handleRequest(actionMap); + * + * @param context Context why permission is asked; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param permission One of the permissions Assistant supports, each of + * which comes from AssistantApp.SupportedPermissions. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return A response is sent to the Assistant to ask for the user's permission; + * for any invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForPermission(context: string, permission: string, dialogState?: object): express.Response | null; + + /** + * Returns true if the request follows a previous request asking for + * permission from the user and the user granted the permission(s). Otherwise, + * false. Use with {@link AssistantApp#askForPermissions|askForPermissions}. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * // or + * const app = new DialogflowApp({request: request, response: response}); + * app.askForPermissions("To get you a ride", [ + * app.SupportedPermissions.NAME, + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION + * ]); + * // ... + * // In response handler for subsequent intent: + * if (app.isPermissionGranted()) { + * // Use the requested permission(s) to get the user a ride + * } + * + * @return true if permissions granted. + * @dialogflow + * @actionssdk + */ + isPermissionGranted(): boolean; + + /** + * Asks user for delivery address. + * + * @example + * // For DialogflowApp: + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const DELIVERY_INTENT = 'delivery.address'; + * + * function welcomeIntent (app) { + * app.askForDeliveryAddress('To make sure I can deliver to you'); + * } + * + * function addressIntent (app) { + * const postalCode = app.getDeliveryAddress().postalAddress.postalCode; + * if (isInDeliveryZone(postalCode)) { + * app.tell('Great looks like you\'re in our delivery area!'); + * } else { + * app.tell('I\'m sorry it looks like we can\'t deliver to you.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DELIVERY_INTENT, addressIntent); + * app.handleRequest(actionMap); + * + * // For ActionsSdkApp: + * const app = new ActionsSdkApp({request, response}); + * const WELCOME_INTENT = app.StandardIntents.MAIN; + * const DELIVERY_INTENT = app.StandardIntents.DELIVERY_ADDRESS; + * + * function welcomeIntent (app) { + * app.askForDeliveryAddress('To make sure I can deliver to you'); + * } + * + * function addressIntent (app) { + * const postalCode = app.getDeliveryAddress().postalAddress.postalCode; + * if (isInDeliveryZone(postalCode)) { + * app.tell('Great looks like you\'re in our delivery area!'); + * } else { + * app.tell('I\'m sorry it looks like we can\'t deliver to you.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DELIVERY_INTENT, addressIntent); + * app.handleRequest(actionMap); + * + * @param reason Reason given to user for asking delivery address. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForDeliveryAddress(reason: string, dialogState?: object): express.Response | null; + + /** + * Asks user for a confirmation. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const CONFIRMATION = 'confirmation'; + * + * function welcomeIntent (app) { + * app.askForConfirmation('Are you sure you want to do that?'); + * } + * + * function confirmation (app) { + * if (app.getUserConfirmation()) { + * app.tell('Great! I\'m glad you want to do it!'); + * } else { + * app.tell('That\'s okay. Let\'s not do it now.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(CONFIRMATION, confirmation); + * app.handleRequest(actionMap); + * + * @param prompt The confirmation prompt presented to the user to + * query for an affirmative or negative response. If undefined or null, + * Google will use a generic yes/no prompt. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForConfirmation(prompt?: string, dialogState?: object): express.Response | null; + + /** + * Asks user for a timezone-agnostic date and time. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const DATETIME = 'datetime'; + * + * function welcomeIntent (app) { + * app.askForDateTime('When do you want to come in?', + * 'Which date works best for you?', + * 'What time of day works best for you?'); + * } + * + * function datetime (app) { + * app.tell({speech: 'Great see you at your appointment!', + * displayText: 'Great, we will see you on ' + * + app.getDateTime().date.month + * + '/' + app.getDateTime().date.day + * + ' at ' + app.getDateTime().time.hours + * + (app.getDateTime().time.minutes || '')}); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DATETIME, datetime); + * app.handleRequest(actionMap); + * + * @param initialPrompt The initial prompt used to ask for a + * date and time. If undefined or null, Google will use a generic + * prompt. + * @param datePrompt The prompt used to specifically ask for the + * date if not provided by user. If undefined or null, Google will use a + * generic prompt. + * @param timePrompt The prompt used to specifically ask for the + * time if not provided by user. If undefined or null, Google will use a + * generic prompt. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForDateTime(initialPrompt?: string, datePrompt?: string, timePrompt?: string, dialogState?: object): express.Response | null; + + /** + * Hands the user off to a web sign in flow. App sign in and OAuth credentials + * are set in the {@link https://console.actions.google.com|Actions Console}. + * Retrieve the access token in subsequent intents using + * app.getUser().accessToken. + * + * Note: Currently this API requires enabling the app for Transactions APIs. + * To do this, fill out the App Info section of the Actions Console project + * and check the box indicating the use of Transactions under "Privacy and + * consent". + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SIGN_IN = 'sign.in'; + * + * function welcomeIntent (app) { + * app.askForSignIn(); + * } + * + * function signIn (app) { + * if (app.getSignInStatus() === app.SignInstatus.OK) { + * let accessToken = app.getUser().accessToken; + * app.ask('Great, thanks for signing in!'); + * } else { + * app.ask('I won\'t be able to save your data, but let\'s continue!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SIGN_IN, signIn); + * app.handleRequest(actionMap); + * + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForSignIn(dialogState?: object): express.Response | null; + + /** + * Requests the user to switch to another surface during the conversation. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SHOW_IMAGE = 'show.image'; + * + * function welcomeIntent (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * showPicture(app); + * } else if (app.hasAvailableSurfaceCapabilities(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askForNewSurface('To show you an image', + * 'Check out this image', + * [app.SurfaceCapabilities.SCREEN_OUTPUT] + * ); + * } else { + * app.tell('This part of the app only works on screen devices. Sorry about that'); + * } + * } + * + * function showImage (app) { + * if (!app.isNewSurface()) { + * app.tell('Ok, I understand. You don't want to see pictures. Bye'); + * } else { + * showPicture(app, pictureType); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param context Context why new surface is requested; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param notificationTitle Title of the notification appearing on + * new surface device. + * @param capabilities The list of capabilities required in + * the surface. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return HTTP response. + * @dialogflow + * @actionssdk + */ + askForNewSurface(context: string, notificationTitle: string, capabilities: SurfaceCapabilities[], dialogState?: object): express.Response | null; + + /** + * Gets the {@link User} object. + * The user object contains information about the user, including + * a string identifier and personal information (requires requesting permissions, + * see {@link AssistantApp#askForPermissions|askForPermissions}). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * // or + * const app = new ActionsSdkApp({request: request, response: response}); + * const userId = app.getUser().userId; + * + * @return Null if no value. + * @actionssdk + * @dialogflow + */ + getUser(): User; + + /** + * If granted permission to user's name in previous intent, returns user's + * display name, family name, and given name. If name info is unavailable, + * returns null. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const SAY_NAME_ACTION = 'get_name'; + * + * function requestPermission (app) { + * const permission = app.SupportedPermissions.NAME; + * app.askForPermission('To know who you are', permission); + * } + * + * function sayName (app) { + * if (app.isPermissionGranted()) { + * app.tell('Your name is ' + app.getUserName().displayName)); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not get your name.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(SAY_NAME_ACTION, sayName); + * app.handleRequest(actionMap); + * @return Null if name permission is not granted. + * @actionssdk + * @dialogflow + */ + getUserName(): UserName; + + /** + * Gets the user locale. Returned string represents the regional language + * information of the user set in their Assistant settings. + * For example, 'en-US' represents US English. + * + * @example + * const app = new DialogflowApp({request, response}); + * const locale = app.getUserLocale(); + * + * @return User's locale, e.g. 'en-US'. Null if no locale given. + * @actionssdk + * @dialogflow + */ + getUserLocale(): string; + + /** + * If granted permission to device's location in previous intent, returns device's + * location (see {@link AssistantApp#askForPermissions|askForPermissions}). + * If device info is unavailable, returns null. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * // or + * const app = new ActionsSdkApp({request: req, response: res}); + * app.askForPermission("To get you a ride", + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION); + * // ... + * // In response handler for permissions fallback intent: + * if (app.isPermissionGranted()) { + * sendCarTo(app.getDeviceLocation().coordinates); + * } + * + * @return Null if location permission is not granted. + * @actionssdk + * @dialogflow + */ + getDeviceLocation(): DeviceLocation; + + /** + * Gets type of input used for this request. + * @return One of AssistantApp.InputTypes. + * Null if no input type given. + * @dialogflow + * @actionssdk + */ + getInputType(): number | string; + + /** + * Get the argument value by name from the current intent. + * If the argument is included in originalRequest, and is not a text argument, + * the entire argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param argName Name of the argument. + * @return Argument value matching argName + * or null if no matching argument. + * @dialogflow + * @actionssdk + */ + getArgumentCommon(argName: string): object; + + /** + * Gets transactability of user. Only use after calling + * askForTransactionRequirements. Null if no result given. + * + * @return One of Transactions.ResultType. + * @dialogflow + * @actionssdk + */ + getTransactionRequirementsResult(): string; + + /** + * Gets order delivery address. Only use after calling askForDeliveryAddress. + * + * @return Delivery address information. Null if user + * denies permission, or no address given. + * @dialogflow + * @actionssdk + */ + getDeliveryAddress(): Location; + + /** + * Gets transaction decision information. Only use after calling + * askForTransactionDecision. + * + * @return Transaction decision data. Returns object with + * userDecision only if user declines. userDecision will be one of + * Transactions.ConfirmationDecision. Null if no decision given. + * @dialogflow + * @actionssdk + */ + getTransactionDecision(): TransactionDecision; + + /** + * Gets confirmation decision. Use after askForConfirmation. + * + * @return False if user replied with negative response. Null if no user + * confirmation decision given. + * @dialogflow + * @actionssdk + */ + getUserConfirmation(): boolean | null; + + /** + * Gets user provided date and time. Use after askForDateTime. + * + * @return Date and time given by the user. Null if no user + * date and time given. + * @dialogflow + * @actionssdk + */ + getDateTime(): DateTime; + + /** + * Gets status of user sign in request. + * + * @return Result of user sign in request. One of + * DialogflowApp.SignInStatus or ActionsSdkApp.SignInStatus + * Null if no sign in status. + * @dialogflow + * @actionssdk + */ + getSignInStatus(): string; + + /** + * Returns true if user device has a given surface capability. + * + * @param requestedCapability Must be one of {@link SurfaceCapabilities}. + * @return True if user device has the given capability. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const DESCRIBE_SOMETHING = 'DESCRIBE_SOMETHING'; + * + * function describe (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.tell(richResponseWithBasicCard); + * } else { + * app.tell('Let me tell you about ...'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(DESCRIBE_SOMETHING, describe); + * app.handleRequest(actionMap); + * + * @dialogflow + * @actionssdk + */ + hasSurfaceCapability(requestedCapability: SurfaceCapabilities): boolean; + + /** + * Gets surface capabilities of user device. + * + * @return Supported surface capabilities, as defined in + * AssistantApp.SurfaceCapabilities. + * @dialogflow + * @actionssdk + */ + getSurfaceCapabilities(): string[]; + + /** + * Returns the set of other available surfaces for the user. + * + * @return Empty if no available surfaces. + * @actionssdk + * @dialogflow + */ + getAvailableSurfaces(): Surface[]; + + /** + * Returns true if user has an available surface which includes all given + * capabilities. Available surfaces capabilities may exist on surfaces other + * than that used for an ongoing conversation. + * + * @param capabilities Must be one of + * {@link SurfaceCapabilities}. + * @return True if user has a capability available on some surface. + * + * @dialogflow + * @actionssdk + */ + hasAvailableSurfaceCapabilities(capabilities: SurfaceCapabilities | SurfaceCapabilities[]): boolean; + + /** + * Returns the result of the AskForNewSurface helper. + * + * @return True if user has triggered conversation on a new device + * following the NEW_SURFACE intent. + * @actionssdk + * @dialogflow + */ + isNewSurface(): boolean; + + /** + * Returns true if the app is being tested in sandbox mode. Enable sandbox + * mode in the (Actions console)[console.actions.google.com] to test + * transactions. + * + * @return True if app is being used in Sandbox mode. + * @dialogflow + * @actionssdk + */ + isInSandbox(): boolean; + + /** + * Returns the number of subsequent reprompts related to silent input from the + * user. This should be used along with the NO_INPUT intent to reprompt the + * user for input in cases where the Google Assistant could not pick up any + * speech. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcome (app) { + * app.ask('Welcome to your app!'); + * } + * + * function noInput (app) { + * if (app.getRepromptCount() === 0) { + * app.ask(`What was that?`); + * } else if (app.getRepromptCount() === 1) { + * app.ask(`Sorry I didn't catch that. Could you repeat yourself?`); + * } else if (app.isFinalReprompt()) { + * app.tell(`Okay let's try this again later.`); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, welcome); + * actionMap.set(app.StandardIntents.NO_INPUT, noInput); + * app.handleRequest(actionMap); + * + * @return The current reprompt count. Null if no reprompt count + * available (e.g. not in the NO_INPUT intent). + * @dialogflow + * @actionssdk + */ + getRepromptCount(): number; + + /** + * Returns true if it is the final reprompt related to silent input from the + * user. This should be used along with the NO_INPUT intent to give the final + * response to the user after multiple silences and should be an app.tell + * which ends the conversation. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcome (app) { + * app.ask('Welcome to your app!'); + * } + * + * function noInput (app) { + * if (app.getRepromptCount() === 0) { + * app.ask(`What was that?`); + * } else if (app.getRepromptCount() === 1) { + * app.ask(`Sorry I didn't catch that. Could you repeat yourself?`); + * } else if (app.isFinalReprompt()) { + * app.tell(`Okay let's try this again later.`); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, welcome); + * actionMap.set(app.StandardIntents.NO_INPUT, noInput); + * app.handleRequest(actionMap); + * + * @return True if in a NO_INPUT intent and this is the final turn + * of dialog. + * @dialogflow + * @actionssdk + */ + isFinalReprompt(): boolean; + + // --------------------------------------------------------------------------- + // Response Builders + // --------------------------------------------------------------------------- + + /** + * Constructs RichResponse with chainable property setters. + * + * @param richResponse RichResponse to clone. + * @return Constructed RichResponse. + */ + buildRichResponse(richResponse?: RichResponse): RichResponse; + + /** + * Constructs BasicCard with chainable property setters. + * + * @param bodyText Body text of the card. Can be set using setTitle + * instead. + * @return Constructed BasicCard. + */ + buildBasicCard(bodyText?: string): BasicCard; + + /** + * Constructs List with chainable property setters. + * + * @param title A title to set for a new List. + * @return Constructed List. + */ + buildList(title?: string): List; + + /** + * Constructs Carousel with chainable property setters. + * + * @return Constructed Carousel. + */ + buildCarousel(): Carousel; + + /** + * Constructs OptionItem with chainable property setters. + * + * @param key A unique key to identify this option. This key will + * be returned as an argument in the resulting actions.intent.OPTION + * intent. + * @param synonyms A list of synonyms which the user may + * use to identify this option instead of the option key. + * @return Constructed OptionItem. + */ + buildOptionItem(key?: string, synonyms?: string | string[]): OptionItem; + + // --------------------------------------------------------------------------- + // Transaction Builders + // --------------------------------------------------------------------------- + + /** + * Constructs Order with chainable property setters. + * + * @param orderId Unique identifier for the order. + * @return Constructed Order. + */ + buildOrder(orderId: string): Order; + + /** + * Constructs Cart with chainable property setters. + * + * @param cartId Unique identifier for the cart. + * @return Constructed Cart. + */ + buildCart(cartId?: string): Cart; + + /** + * Constructs LineItem with chainable property setters. + * Because of a previous bug, the parameters are swapped compared to + * the LineItem constructor to prevent a breaking change. + * + * @param name Name of the line item. + * @param id Unique identifier for the item. + * @return Constructed LineItem. + */ + buildLineItem(name: string, id: string): LineItem; + + /** + * Constructs OrderUpdate with chainable property setters. + * + * @param orderId Unique identifier of the order. + * @param isGoogleOrderId True if the order ID is provided by + * Google. False if the order ID is app provided. + * @return Constructed OrderUpdate. + */ + buildOrderUpdate(orderId: string, isGoogleOrderId: boolean): OrderUpdate; +} diff --git a/types/actions-on-google/dialogflow-app.d.ts b/types/actions-on-google/dialogflow-app.d.ts new file mode 100644 index 0000000000..ab768241c2 --- /dev/null +++ b/types/actions-on-google/dialogflow-app.d.ts @@ -0,0 +1,571 @@ +import * as express from 'express'; + +import { AssistantApp } from './assistant-app'; +import { Carousel, List, RichResponse, SimpleResponse } from './response-builder'; + +// --------------------------------------------------------------------------- +// Dialogflow support +// --------------------------------------------------------------------------- + +/** + * Dialogflow {@link https://dialogflow.com/docs/concept-contexts|Context}. + */ +export interface Context { + /** Full name of the context. */ + name: string; + /** + * Parameters carried within this context. + * See {@link https://dialogflow.com/docs/concept-actions#section-extracting-values-from-contexts|here}. + */ + parameters: object; + /** Remaining number of intents */ + lifespan: number; +} + +export interface DialogflowAppOptions { + /** Express HTTP request object. */ + request: express.Request; + /** Express HTTP response object. */ + response: express.Response; + /** + * Function callback when session starts. + * Only called if webhook is enabled for welcome/triggering intents, and + * called from Web Simulator or Google Home device (i.e., not Dialogflow simulator). + */ + sessionStarted?(): any; +} + +/** + * This is the class that handles the communication with Dialogflow's fulfillment API. + */ +export class DialogflowApp extends AssistantApp { + /** + * Constructor for DialogflowApp object. + * To be used in the Dialogflow fulfillment webhook logic. + * + * @example + * const DialogflowApp = require('actions-on-google').DialogflowApp; + * const app = new DialogflowApp({request: request, response: response, + * sessionStarted:sessionStarted}); + * + * @dialogflow + */ + constructor(options: DialogflowAppOptions); + + /** + * @deprecated + * Verifies whether the request comes from Dialogflow. + * + * @param key The header key specified by the developer in the + * Dialogflow Fulfillment settings of the app. + * @param value The private value specified by the developer inside the + * fulfillment header. + * @return True if the request comes from Dialogflow. + * @dialogflow + */ + isRequestFromApiAi(key: string, value: string): boolean; + + /** + * Verifies whether the request comes from Dialogflow. + * + * @param key The header key specified by the developer in the + * Dialogflow Fulfillment settings of the app. + * @param value The private value specified by the developer inside the + * fulfillment header. + * @return True if the request comes from Dialogflow. + * @dialogflow + */ + isRequestFromDialogflow(key: string, value: string): boolean; + + /** + * Get the current intent. Alternatively, using a handler Map with + * {@link AssistantApp#handleRequest|handleRequest}, + * the client library will automatically handle the incoming intents. + * 'Intent' in the Dialogflow context translates into the current action. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * + * function responseHandler (app) { + * const intent = app.getIntent(); + * switch (intent) { + * case WELCOME_INTENT: + * app.ask('Welcome to action snippets! Say a number.'); + * break; + * + * case NUMBER_INTENT: + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * break; + * } + * } + * + * app.handleRequest(responseHandler); + * + * @return Intent id or null if no value (action name). + * @dialogflow + */ + getIntent(): string; + + /** + * Get the argument value by name from the current intent. If the argument + * is included in originalRequest, and is not a text argument, the entire + * argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param argName Name of the argument. + * @return Argument value matching argName + * or null if no matching argument. + * @dialogflow + */ + getArgument(argName: string): object; + + /** + * Get the context argument value by name from the current intent. Context + * arguments include parameters collected in previous intents during the + * lifespan of the given context. If the context argument has an original + * value, usually representing the underlying entity value, that will be given + * as part of the return object. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * const OUT_CONTEXT = 'output_context'; + * const NUMBER_ARG = 'myNumberArg'; + * + * function welcomeIntent (app) { + * const parameters = {}; + * parameters[NUMBER_ARG] = '42'; + * app.setContext(OUT_CONTEXT, 1, parameters); + * app.ask('Welcome to action snippets! Ask me for your number.'); + * } + * + * function numberIntent (app) { + * const number = app.getContextArgument(OUT_CONTEXT, NUMBER_ARG); + * // number === { value: 42 } + * app.tell('Your number is ' + number.value); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param contextName Name of the context. + * @param argName Name of the argument. + * @return Object containing value property and optional original + * property matching context argument. Null if no matching argument. + * @dialogflow + */ + getContextArgument(contextName: string, argName: string): object; + + /** + * Returns the RichResponse constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function tellFact (app) { + * let fact = 'Google was founded in 1998'; + * + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.ask(app.getIncomingRichResponse().addSimpleResponse('Here\'s a ' + + * 'fact for you. ' + fact + ' Which one do you want to hear about ' + + * 'next, Google\'s history or headquarters?')); + * } else { + * app.ask('Here\'s a fact for you. ' + fact + ' Which one ' + + * 'do you want to hear about next, Google\'s history or headquarters?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('tell.fact', tellFact); + * + * app.handleRequest(actionMap); + * + * @return RichResponse created in Dialogflow. If no RichResponse was + * created, an empty RichResponse is returned. + * @dialogflow + */ + getIncomingRichResponse(): RichResponse; + + /** + * Returns the List constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithList('Which of these looks good?', + * app.getIncomingList().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * + * app.handleRequest(actionMap); + * + * @return List created in Dialogflow. If no List was created, an empty + * List is returned. + * @dialogflow + */ + getIncomingList(): List; + + /** + * Returns the Carousel constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.getIncomingCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * + * app.handleRequest(actionMap); + * + * @return Carousel created in Dialogflow. If no Carousel was created, + * an empty Carousel is returned. + * @dialogflow + */ + getIncomingCarousel(): Carousel; + + /** + * Returns the option key user chose from options response. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.getIncomingCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * function optionPicked (app) { + * app.ask('You picked ' + app.getSelectedOption()); + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * actionMap.set('option.picked', optionPicked); + * + * app.handleRequest(actionMap); + * + * @return Option key of selected item. Null if no option selected or + * if current intent is not OPTION intent. + * @dialogflow + */ + getSelectedOption(): string; + + /** + * Asks to collect the user's input. + * {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}. + * + * NOTE: Due to a bug, if you specify the no-input prompts, + * the mic is closed after the 3rd prompt, so you should use the 3rd prompt + * for a bye message until the bug is fixed. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.', + * ['Say any number', 'Pick a number', 'We can stop here. See you soon.']); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt The input prompt + * response. + * @param noInputs Array of re-prompts when the user does not respond (max 3). + * @return HTTP response. + * @dialogflow + */ + ask(inputPrompt: string | SimpleResponse | RichResponse, noInputs?: string[]): express.Response | null; + + /** + * Asks to collect the user's input with a list. + * + * @example + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const OPTION_INTENT = 'option.select'; + * + * function welcomeIntent (app) { + * app.askWithList('Which of these looks good?', + * app.buildList('List title') + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Title of First List Item'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Title of Second List Item'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(OPTION_INTENT, optionIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt The input prompt + * response. + * @param.list List built with {@link AssistantApp#buildList|buildList} + * @return HTTP response. + * @dialogflow + */ + askWithList(inputPrompt: string | RichResponse | SimpleResponse, list: List): express.Response | null; + + /** + * Asks to collect the user's input with a carousel. + * + * @example + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const OPTION_INTENT = 'option.select'; + * + * function welcomeIntent (app) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel() + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(OPTION_INTENT, optionIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt The input prompt + * response. + * @param carousel Carousel built with + * {@link AssistantApp#buildCarousel|buildCarousel}. + * @return HTTP response. + * @dialogflow + */ + askWithCarousel(inputPrompt: string | RichResponse | SimpleResponse, carousel: Carousel): express.Response | null; + + /** + * Tells the Assistant to render the speech response and close the mic. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param speechResponse Final response. + * Spoken response can be SSML. + * @return The response that is sent back to Assistant. + * @dialogflow + */ + tell(speechResponse: string | SimpleResponse | RichResponse): express.Response | null; + + /** + * Set a new context for the current intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param name Name of the context. Dialogflow converts to lowercase. + * @param [lifespan=1] Context lifespan. + * @param parameters Context JSON parameters. + * @return Null if the context name is not defined. + * @dialogflow + */ + setContext(name: string, lifespan?: number, parameters?: any): null | undefined; + + /** + * Returns the incoming contexts for this intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * let contexts = app.getContexts(); + * // contexts === [{ + * // name: 'number', + * // lifespan: 0, + * // parameters: { + * // myNumber: '23', + * // myNumber.original: '23' + * // } + * // }] + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @return Empty if no active contexts. + * @dialogflow + */ + getContexts(): Context[]; + + /** + * Returns the incoming context by name for this intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * let context = app.getContext(CONTEXT_NUMBER); + * // context === { + * // name: 'number', + * // lifespan: 0, + * // parameters: { + * // myNumber: '23', + * // myNumber.original: '23' + * // } + * // } + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param name The name of the Context to retrieve. + * @return Context value matching name + * or null if no matching context. + * @dialogflow + */ + getContext(name: string): object; + + /** + * Gets the user's raw input query. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * app.tell('You said ' + app.getRawInput()); + * + * @return User's raw query or null if no value. + * @dialogflow + */ + getRawInput(): string; +} diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts new file mode 100644 index 0000000000..5f7baba3b8 --- /dev/null +++ b/types/actions-on-google/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for actions-on-google 1.5 +// Project: https://github.com/actions-on-google/actions-on-google-nodejs +// Definitions by: Joel Hegg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/** + * The Actions on Google client library. + * https://developers.google.com/actions/ + */ + +import * as Transactions from './transactions'; +import * as Responses from './response-builder'; + +export { AssistantApp } from './assistant-app'; +export { ActionsSdkApp, ActionsSdkAppOptions } from './actions-sdk-app'; +export { DialogflowApp, DialogflowAppOptions } from './dialogflow-app'; +export { Transactions }; +export { Responses }; +// Backwards compatibility +export { AssistantApp as Assistant } from './assistant-app'; +export { ActionsSdkApp as ActionsSdkAssistant } from './actions-sdk-app'; +export { DialogflowApp as ApiAiAssistant } from './dialogflow-app'; +export { DialogflowApp as ApiAiApp } from './dialogflow-app'; diff --git a/types/actions-on-google/response-builder.d.ts b/types/actions-on-google/response-builder.d.ts new file mode 100644 index 0000000000..1e11984551 --- /dev/null +++ b/types/actions-on-google/response-builder.d.ts @@ -0,0 +1,386 @@ +/** + * A collection of response builders. + */ + +import { OrderUpdate } from './transactions'; + +/** + * Simple Response type. + */ +export interface SimpleResponse { + /** Speech to be spoken to user. SSML allowed. */ + speech: string; + /** Optional text to be shown to user */ + displayText?: string; +} + +/** + * Suggestions to show with response. + */ +export interface Suggestion { + /** Text of the suggestion. */ + title: string; +} + +/** + * Link Out Suggestion. Used in rich response as a suggestion chip which, when + * selected, links out to external URL. + */ +export interface LinkOutSuggestion { + /** Text shown on the suggestion chip. */ + title: string; + /** String URL to open. */ + url: string; +} + +/** + * Image type shown on visual elements. + */ +export interface Image { + /** Image source URL. */ + url: string; + /** Text to replace for image for accessibility. */ + accessibilityText: string; + /** Width of the image. */ + width: number; + /** Height of the image. */ + height: number; +} + +/** + * Basic Card Button. Shown below basic cards. Open a URL when selected. + */ +export interface Button { + /** Text shown on the button. */ + title: string; + /** Action to take when selected. */ + openUrlAction: { + /** String URL to open. */ + url: string; + }; +} + +/** + * Option info. Provides unique identifier for a given OptionItem. + */ +export interface OptionInfo { + /** Unique string ID for this option. */ + key: string; + /** Synonyms that can be used by the user to indicate this option if they do not use the key. */ + synonyms: string[]; +} + +/** + * Class for initializing and constructing Rich Responses with chainable interface. + */ +export class RichResponse { + /** + * Constructor for RichResponse. Accepts optional RichResponse to clone. + * + * @param richResponse Optional RichResponse to clone. + */ + constructor(richResponse?: RichResponse); + + /** + * Ordered list of either SimpleResponse objects or BasicCard objects. + * First item must be SimpleResponse. There can be at most one card. + */ + items: Array; + + /** + * Ordered list of text suggestions to display. Optional. + */ + suggestions: Suggestion[]; + + /** + * Link Out Suggestion chip for this rich response. Optional. + */ + linkOutSuggestion?: LinkOutSuggestion; + + /** + * Adds a SimpleResponse to list of items. + * + * @param simpleResponse Simple response to present to + * user. If just a string, display text will not be set. + * @return Returns current constructed RichResponse. + */ + addSimpleResponse(simpleResponse: string | SimpleResponse): RichResponse; + + /** + * Adds a BasicCard to list of items. + * + * @param basicCard Basic card to include in response. + * @return Returns current constructed RichResponse. + */ + addBasicCard(basicCard: BasicCard): RichResponse; + + /** + * Adds a single suggestion or list of suggestions to list of items. + * + * @param suggestions Either a single string suggestion + * or list of suggestions to add. + * @return Returns current constructed RichResponse. + */ + addSuggestions(suggestions: string | string[]): RichResponse; + + /** + * Returns true if the given suggestion text is valid to be added to the suggestion list. A valid + * text string is not longer than 25 characters. + * @param suggestionText Text to validate as suggestion. + * @return True if the text is valid, false otherwise.s + */ + isValidSuggestionText(suggestionText: string): boolean; + + /** + * Sets the suggestion link for this rich response. + * + * @param destinationName Name of the link out destination. + * @param suggestionUrl - String URL to open when suggestion is used. + * @return Returns current constructed RichResponse. + */ + addSuggestionLink(destinationName: string, suggestionUrl: string): RichResponse; + + /** + * Adds an order update to this response. Use after a successful transaction + * decision to confirm the order. + * + * @param orderUpdate OrderUpdate object to add. + * @return Returns current constructed RichResponse. + */ + addOrderUpdate(orderUpdate: OrderUpdate): RichResponse; +} + +/** + * Class for initializing and constructing Basic Cards with chainable interface. + */ +export class BasicCard { + /** + * Constructor for BasicCard. Accepts optional BasicCard to clone. + * + * @param basicCard Optional BasicCard to clone. + */ + constructor(basicCard?: BasicCard); + + /** + * Title of the card. Optional. + */ + title?: string; + + /** + * Body text to show on the card. Required, unless image is present. + */ + formattedText: string; + + /** + * Subtitle of the card. Optional. + */ + subtitle?: string; + + /** + * Image to show on the card. Optional. + */ + image?: Image; + + /** + * Ordered list of buttons to show below card. Optional. + */ + buttons: Button[]; + + /** + * Sets the title for this Basic Card. + * + * @param title Title to show on card. + * @return Returns current constructed BasicCard. + */ + setTitle(title: string): BasicCard; + + /** + * Sets the subtitle for this Basic Card. + * + * @param subtitle Subtitle to show on card. + * @return Returns current constructed BasicCard. + */ + setSubtitle(subtitle: string): BasicCard; + + /** + * Sets the body text for this Basic Card. + * + * @param bodyText Body text to show on card. + * @return Returns current constructed BasicCard. + */ + setBodyText(bodyText: string): BasicCard; + + /** + * Sets the image for this Basic Card. + * + * @param url Image source URL. + * @param accessibilityText Text to replace for image for + * accessibility. + * @param width Width of the image. + * @param height Height of the image. + * @return Returns current constructed BasicCard. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): BasicCard; + + /** + * Adds a button below card. + * + * @param text Text to show on button. + * @param url URL to open when button is selected. + * @return Returns current constructed BasicCard. + */ + addButton(text: string, url: string): BasicCard; +} + +/** + * Class for initializing and constructing Lists with chainable interface. + */ +export class List { + /** + * Constructor for List. Accepts optional List to clone, string title, or + * list of items to copy. + * + * @param list Either a list to clone, a title + * to set for a new List, or an array of OptionItem to initialize a new + * list. + */ + constructor(list?: List | string | OptionItem[]); + + /** + * Title of the list. Optional. + */ + title?: string; + + /** + * List of 2-20 items to show in this list. Required. + */ + items: OptionItem[]; + + /** + * Sets the title for this List. + * + * @param title Title to show on list. + * @return Returns current constructed List. + */ + setTitle(title: string): List; + + /** + * Adds a single item or list of items to the list. + * + * @param optionItems OptionItems to add. + * @return Returns current constructed List. + */ + addItems(optionItems: OptionItem | OptionItem[]): List; +} + +/** + * Class for initializing and constructing Carousel with chainable interface. + */ +export class Carousel { + /** + * Constructor for Carousel. Accepts optional Carousel to clone or list of + * items to copy. + * + * @param carousel Either a carousel to clone + * or an array of OptionItem to initialize a new carousel + */ + constructor(carousel?: Carousel | OptionItem[]); + + /** + * List of 2-20 items to show in this carousel. Required. + */ + items: OptionItem[]; + + /** + * Adds a single item or list of items to the carousel. + * + * @param optionItems OptionItems to add. + * @return Returns current constructed Carousel. + */ + addItems(optionItems: OptionItem | OptionItem[]): Carousel; +} + +/** + * Class for initializing and constructing Option Items with chainable interface. + */ +export class OptionItem { + /** + * Constructor for OptionItem. Accepts optional OptionItem to clone. + * + * @param optionItem Optional OptionItem to clone. + */ + constructor(optionItem?: OptionItem); + + /** + * Option info of the option item. Required. + */ + optionInfo: OptionInfo; + + /** + * Title of the option item. Required. + */ + title: string; + + /** + * Description text of the item. Optional. + */ + description?: string; + + /** + * Image to show on item. Optional. + */ + image?: Image; + + /** + * Sets the title for this Option Item. + * + * @param title Title to show on item. + * @return Returns current constructed OptionItem. + */ + setTitle(title: string): OptionItem; + + /** + * Sets the description for this Option Item. + * + * @param description Description to show on item. + * @return Returns current constructed OptionItem. + */ + setDescription(description: string): OptionItem; + + /** + * Sets the image for this Option Item. + * + * @param url Image source URL. + * @param accessibilityText Text to replace for image for + * accessibility. + * @param width Width of the image. + * @param height Height of the image. + * @return Returns current constructed OptionItem. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): OptionItem; + + /** + * Sets the key for the OptionInfo of this Option Item. This will be returned + * as an argument in the resulting actions.intent.OPTION intent. + * + * @param key Key to uniquely identify this item. + * @return Returns current constructed OptionItem. + */ + setKey(key: string): OptionItem; + + /** + * Adds a single synonym or list of synonyms to item. + * + * @param synonyms Either a single string synonyms + * or list of synonyms to add. + * @return Returns current constructed OptionItem. + */ + addSynonyms(synonyms: string | string[]): OptionItem; +} + +/** + * Check if given text contains SSML. + * @param text Text to check. + * @return True if text contains SSML, false otherwise. + */ +export function isSsml(text: string): boolean; diff --git a/types/actions-on-google/transactions.d.ts b/types/actions-on-google/transactions.d.ts new file mode 100644 index 0000000000..8cc26165db --- /dev/null +++ b/types/actions-on-google/transactions.d.ts @@ -0,0 +1,1023 @@ +/** + * A collection of Transaction related constants, utility functions, and + * builders. + */ + +import { Image } from './response-builder'; + +/** + * Price type. + */ +export interface Price { + /** One of Transaction.PriceType. */ + type: PriceType; + amount: { + /** Currency code of price. */ + currencyCode: string; + /** Unit count of price. */ + units: number; + /** Partial unit count of price. */ + nanos?: number; + }; +} + +/** + * Order rejection info. + */ +export interface RejectionInfo { + /** One of Transaction.RejectionType. */ + type: RejectionType; + /** Reason for the order rejection. */ + reason: string; +} + +/** + * Order receipt info. + */ +export interface ReceiptInfo { + /** Action provided order ID. Used when the order has been received by the integrator. */ + confirmedActionOrderId: string; +} + +/** + * Order cancellation info. + */ +export interface CancellationInfo { + /** Reason for the cancellation. */ + reason: string; +} + +/** + * Order transit info. + */ +export interface TransitInfo { + /** UTC timestamp of the transit update. */ + updatedTime: { + /** Seconds since Unix epoch. */ + seconds: number; + /** Partial seconds since Unix epoch. */ + nanos?: number; + }; +} + +/** + * Order fulfillment info. + */ +export interface FulfillmentInfo { + /** UTC timestamp of the fulfillment update. */ + deliveryTime: { + /** Seconds since Unix epoch. */ + seconds: number; + /** Partial seconds since Unix epoch. */ + nanos?: number; + }; +} + +/** + * Order return info. + */ +export interface ReturnInfo { + /** Reason for the return. */ + reason: string; +} + +/** + * Transaction config for transactions not involving a Google provided + * payment instrument. + */ +export interface ActionPaymentTransactionConfig { + /** True if delivery address is required for the transaction. */ + deliveryAddressRequired: boolean; + /** One of Transactions.PaymentType. */ + type: PaymentType; + /** The name of the instrument displayed on receipt. For example, for card payment, could be "VISA-1234". */ + displayName: string; + customerInfoOptions?: CustomerInfoOptions; +} + +/** + * Transaction config for transactions involving a Google provided payment + * instrument. + */ +export interface GooglePaymentTransactionConfig { + /** True if delivery address is required for the transaction. */ + deliveryAddressRequired: boolean; + /** Tokenization parameters provided by payment gateway. */ + tokenizationParameters: object; + /** List of accepted card networks. Must be any number of Transactions.CardNetwork. */ + cardNetworks: CardNetwork[]; + /** True if prepaid cards are not allowed for transaction. */ + prepaidCardDisallowed: boolean; + customerInfoOptions?: CustomerInfoOptions; +} + +/** + * Customer information requested as part of the transaction + */ +export interface CustomerInfoOptions { + customerInfoProperties: string[]; +} + +/** + * Generic Location type. + */ +export interface Location { + postalAddress: { + regionCode: string; + languageCode: string; + postalCode: string; + administrativeArea: string; + locality: string; + addressLines: string[]; + recipients: string; + }; + phoneNumber: string; + notes: string; +} + +/** + * Decision and order information returned when calling getTransactionDecision(). + */ +export interface TransactionDecision { + /** One of Transactions.ConfirmationDecision. */ + userDecision: ConfirmationDecision; + checkResult: { + /** One of Transactions.ResultType. */ + resultType: ResultType; + }; + order: { + /** The proposed order used in the transaction decision. */ + finalOrder: Order; + /** Order ID assigned by Google. */ + googleOrderId: string; + /** User visible order ID set in proposed order. */ + actionOrderId: string; + orderDate: { + seconds: string; + nanos: number; + }; + paymentInfo: object; + customerInfo: { + /** Customer email. */ + email: string; + }; + }; + /** + * The delivery address if user requested. + * Will appear if userDecision is Transactions.DELIVERY_ADDRESS_UPDATED. + */ + deliveryAddress: Location; +} + +/** + * Values related to supporting transactions + */ +export const TransactionValues: { + /** List of transaction card networks available when paying with Google. */ + readonly CardNetwork: typeof CardNetwork; + /** List of possible item types. */ + readonly ItemType: typeof ItemType; + /** List of price types. */ + readonly PriceType: typeof PriceType; + /** List of possible item types. */ + readonly PaymentType: typeof PaymentType; + /** List of customer information properties that can be requested. */ + readonly CustomerInfoProperties: typeof CustomerInfoProperties; + /** List of possible order confirmation user decisions */ + readonly ConfirmationDecision: typeof ConfirmationDecision; + /** List of possible order states. */ + readonly OrderState: typeof OrderState; + /** List of possible actions to take on the order. */ + readonly OrderAction: typeof OrderAction; + /** List of possible types of order rejection. */ + readonly RejectionType: typeof RejectionType; + /** List of possible order state objects. */ + readonly OrderStateInfo: typeof OrderStateInfo; + /** List of possible order transaction requirements check result types. */ + readonly ResultType: typeof ResultType; + /** List of possible user decisions to give delivery address. */ + readonly DeliveryAddressDecision: typeof DeliveryAddressDecision; + /** List of possible order location types. */ + readonly LocationType: typeof LocationType; + /** List of possible order time types. */ + readonly TimeType: typeof TimeType; +}; + +/** + * List of transaction card networks available when paying with Google. + */ +export enum CardNetwork { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * American Express. + */ + AMEX, + /** + * Discover. + */ + DISCOVER, + /** + * Master Card. + */ + MASTERCARD, + /** + * Visa. + */ + VISA, + /** + * JCB. + */ + JCB +} + +/** + * List of possible item types. + */ +export enum ItemType { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * Regular. + */ + REGULAR, + /** + * Tax. + */ + TAX, + /** + * Discount + */ + DISCOUNT, + /** + * Gratuity + */ + GRATUITY, + /** + * Delivery + */ + DELIVERY, + /** + * Subtotal + */ + SUBTOTAL, + /** + * Fee. For everything else, there's fee. + */ + FEE +} + +/** + * List of price types. + */ +export enum PriceType { + /** + * Unknown. + */ + UNKNOWN, + /** + * Estimate. + */ + ESTIMATE, + /** + * Actual. + */ + ACTUAL +} + +/** + * List of possible item types. + */ +export enum PaymentType { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * Payment card. + */ + PAYMENT_CARD, + /** + * Bank. + */ + BANK, + /** + * Loyalty program. + */ + LOYALTY_PROGRAM, + /** + * On order fulfillment, such as cash on delivery. + */ + ON_FULFILLMENT, + /** + * Gift card. + */ + GIFT_CARD +} + +/** + * List of customer information properties that can be requested. + */ +export enum CustomerInfoProperties { + EMAIL +} + +/** + * List of possible order confirmation user decisions + */ +export enum ConfirmationDecision { + /** + * Order was approved by user. + */ + ACCEPTED, + /** + * Order was declined by user. + */ + REJECTED, + /** + * Order was not declined, but the delivery address was updated during + * confirmation. + */ + DELIVERY_ADDRESS_UPDATED, + /** + * Order was not declined, but the cart was updated during confirmation. + */ + CART_CHANGE_REQUESTED +} + +/** + * List of possible order states. + */ +export enum OrderState { + /** + * Order was rejected. + */ + REJECTED, + /** + * Order was confirmed by integrator and is active. + */ + CONFIRMED, + /** + * User cancelled the order. + */ + CANCELLED, + /** + * Order is being delivered. + */ + IN_TRANSIT, + /** + * User performed a return. + */ + RETURNED, + /** + * User received what was ordered. + */ + FULFILLED +} + +/** + * List of possible actions to take on the order. + */ +export enum OrderAction { + /** + * View details. + */ + VIEW_DETAILS, + /** + * Modify order. + */ + MODIFY, + /** + * Cancel order. + */ + CANCEL, + /** + * Return order. + */ + RETURN, + /** + * Exchange order. + */ + EXCHANGE, + /** + * Email. + */ + EMAIL, + /** + * Call. + */ + CALL, + /** + * Reorder. + */ + REORDER, + /** + * Review. + */ + REVIEW +} + +/** + * List of possible types of order rejection. + */ +export enum RejectionType { + /** + * Unknown + */ + UNKNOWN, + /** + * Payment was declined. + */ + PAYMENT_DECLINED +} + +/** + * List of possible order state objects. + */ +export enum OrderStateInfo { + /** + * Information about order rejection. Used with {@link RejectionInfo}. + */ + REJECTION, + /** + * Information about order receipt. Used with {@link ReceiptInfo}. + */ + RECEIPT, + /** + * Information about order cancellation. Used with {@link CancellationInfo}. + */ + CANCELLATION, + /** + * Information about in-transit order. Used with {@link TransitInfo}. + */ + IN_TRANSIT, + /** + * Information about order fulfillment. Used with {@link FulfillmentInfo}. + */ + FULFILLMENT, + /** + * Information about order return. Used with {@link ReturnInfo}. + */ + RETURN +} + +/** + * List of possible order transaction requirements check result types. + */ +export enum ResultType { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * OK to continue transaction. + */ + OK, + /** + * User is expected to take action, e.g. enable payments, to continue + * transaction. + */ + USER_ACTION_REQUIRED, + /** + * Transactions are not supported on current device/surface. + */ + ASSISTANT_SURFACE_NOT_SUPPORTED, + /** + * Transactions are not supported for current region/country. + */ + REGION_NOT_SUPPORTED +} + +/** + * List of possible user decisions to give delivery address. + */ +export enum DeliveryAddressDecision { + /** + * Unknown. + */ + UNKNOWN, + /** + * User granted delivery address. + */ + ACCEPTED, + /** + * User denied to give delivery address. + */ + REJECTED +} + +/** + * List of possible order location types. + */ +export enum LocationType { + /** + * Unknown. + */ + UNKNOWN, + /** + * Delivery location for an order. + */ + DELIVERY, + /** + * Business location of order provider. + */ + BUSINESS, + /** + * Origin of the order. + */ + ORIGIN, + /** + * Destination of the order. + */ + DESTINATION +} + +/** + * List of possible order time types. + */ +export enum TimeType { + /** + * Unknown. + */ + UNKNOWN, + /** + * Date of delivery for the order. + */ + DELIVERY_DATE, + /** + * Estimated Time of Arrival for order. + */ + ETA, + /** + * Reservation time. + */ + RESERVATION_SLOT +} + +/** + * Class for initializing and constructing Order with chainable interface. + */ +export class Order { + /** + * Constructor for Order. + * + * @param orderId Unique identifier for the order. + */ + constructor(orderId: string); + + /** + * ID for the order. Required. + */ + id: string; + + /** + * Cart for the order. + */ + cart?: Cart; + + /** + * Items not held in the order cart. + */ + otherItems: LineItem[]; + + /** + * Image for the order. + */ + image?: Image; + + /** + * TOS for the order. + */ + termsOfServiceUrl?: string; + + /** + * Total price for the order. + */ + totalPrice?: Price; + + /** + * Extensions for this order. Used for vertical-specific order attributes, + * like times and locations. + */ + extension?: object; + + /** + * Set the cart for this order. + * + * @param cart Cart for this order. + * @return Returns current constructed Order. + */ + setCart(cart: Cart): Order; + + /** + * Adds a single item or list of items to the non-cart items list. + * + * @param items Line Items to add. + * @return Returns current constructed Order. + */ + addOtherItems(items: LineItem | LineItem[]): Order; + + /** + * Sets the image for this order. + * + * @param url Image source URL. + * @param accessibilityText Text to replace for image for + * accessibility. + * @param width Width of the image. + * @param height Height of the image. + * @return Returns current constructed Order. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): Order; + + /** + * Set the TOS for this order. + * + * @param url String URL of the TOS. + * @return Returns current constructed Order. + */ + setTermsOfService(url: string): Order; + + /** + * Sets the total price for this order. + * + * @param priceType One of TransactionValues.PriceType. + * @param currencyCode Currency code of price. + * @param units Unit count of price. + * @param nanos Partial unit count of price. + * @return Returns current constructed Order. + */ + setTotalPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): Order; + + /** + * Adds an associated location to the order. Up to 2 locations can be added. + * + * @param type One of TransactionValues.LocationType. + * @param location Location to add. + * @return Returns current constructed Order. + */ + addLocation(type: LocationType, location: Location): Order; + + /** + * Sets an associated time to the order. + * + * @param type One of TransactionValues.TimeType. + * @param time Time to add. Time should be ISO 8601 representation + * of time value. Could be date, datetime, or duration. + * @return Returns current constructed Order. + */ + setTime(type: TimeType, time: string): Order; +} + +/** + * Class for initializing and constructing Cart with chainable interface. + */ +export class Cart { + /** + * Constructor for Cart. + * + * @param cartId Optional unique identifier for the cart. + */ + constructor(cartId?: string); + + /** + * ID for the cart. Optional. + */ + id?: string; + + /** + * Merchant providing the cart. + */ + merchant?: object; + + /** + * Optional notes about the cart. + */ + notes?: string; + + /** + * Items held in the order cart. + */ + lineItems: LineItem[]; + + /** + * Non-line items. + */ + otherItems: LineItem[]; + + /** + * Set the merchant for this cart. + * + * @param id Merchant ID. + * @param name Name of the merchant. + * @return Returns current constructed Cart. + */ + setMerchant(id: string, name: string): Cart; + + /** + * Set the notes for this cart. + * + * @param notes Notes. + * @return Returns current constructed Cart. + */ + setNotes(notes: string): Cart; + + /** + * Adds a single item or list of items to the cart. + * + * @param items Line Items to add. + * @return Returns current constructed Cart. + */ + addLineItems(items: LineItem | LineItem[]): Cart; + + /** + * Adds a single item or list of items to the non-items list of this cart. + * + * @param items Line Items to add. + * @return Returns current constructed Cart. + */ + addOtherItems(items: LineItem | LineItem[]): Cart; +} + +/** + * Class for initializing and constructing LineItem with chainable interface. + */ +export class LineItem { + /** + * Constructor for LineItem. + * + * @param lineItemId Unique identifier for the item. + * @param name Name of the item. + */ + constructor(lineItemId: string, name: string); + + /** + * Item ID. + */ + id: string; + + /** + * Name of the item. + */ + name: string; + + /** + * Item price. + */ + price?: Price; + + /** + * Sublines for current item. Only valid if item type is REGULAR. + */ + subLines?: Array; + + /** + * Image of the item. + */ + image?: Image; + + /** + * Type of the item. One of TransactionValues.ItemType. + */ + type?: ItemType; + + /** + * Quantity of the item. + */ + quantity?: number; + + /** + * Description for the item. + */ + description?: string; + + /** + * Offer ID for the item. + */ + offerId?: string; + + /** + * Adds a single item or list of items or notes to the sublines. Only valid + * if item type is REGULAR. + * + * @param items Sublines to add. + * @return Returns current constructed LineItem. + */ + addSublines(items: string | LineItem | Array): LineItem; + + /** + * Sets the image for this item. + * + * @param url Image source URL. + * @param accessibilityText Text to replace for image for + * accessibility. + * @param width Width of the image. + * @param height Height of the image. + * @return Returns current constructed LineItem. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): LineItem; + + /** + * Sets the price of this item. + * + * @param priceType One of TransactionValues.PriceType. + * @param currencyCode Currency code of price. + * @param units Unit count of price. + * @param nanos Partial unit count of price. + * @return Returns current constructed LineItem. + */ + setPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): LineItem; + + /** + * Set the type of the item. + * + * @param type Type of the item. One of TransactionValues.ItemType. + * @return Returns current constructed LineItem. + */ + setType(type: ItemType): LineItem; + + /** + * Set the quantity of the item. + * + * @param quantity Quantity of the item. + * @return Returns current constructed LineItem. + */ + setQuantity(quantity: number): LineItem; + + /** + * Set the description of the item. + * + * @param description Description of the item. + * @return Returns current constructed LineItem. + */ + setDescription(description: string): LineItem; + + /** + * Set the Offer ID of the item. + * + * @param offerId Offer ID of the item. + * @return Returns current constructed LineItem. + */ + setOfferId(offerId: string): LineItem; +} + +/** + * Class for initializing and constructing OrderUpdate with chainable interface. + */ +export class OrderUpdate { + /** + * Constructor for OrderUpdate. + * + * @param orderId Unique identifier of the order. + * @param isGoogleOrderId True if the order ID is provided by + * Google. False if the order ID is app provided. + */ + constructor(orderId: string, isGoogleOrderId: boolean); + + /** + * Google provided identifier of the order. + */ + googleOrderId?: string; + + /** + * App provided identifier of the order. + */ + actionOrderId?: string; + + /** + * State of the order. + */ + orderState?: object; + + /** + * Updates for items in the order. Mapped by item id to state or price. + */ + lineItemUpdates: object; + + /** + * UTC timestamp of the order update. + */ + updateTime?: object; + + /** + * Actionable items presented to the user to manage the order. + */ + orderManagementActions: object[]; + + /** + * Notification content to the user for the order update. + */ + userNotification?: object; + + /** + * Updated total price of the order. + */ + totalPrice?: Price; + + /** + * Set the Google provided order ID of the order. + * + * @param orderId Google provided order ID. + * @return Returns current constructed OrderUpdate. + */ + setGoogleOrderId(orderId: string): OrderUpdate; + + /** + * Set the Action provided order ID of the order. + * + * @param orderId Action provided order ID. + * @return Returns current constructed OrderUpdate. + */ + setActionOrderId(orderId: string): OrderUpdate; + + /** + * Set the state of the order. + * + * @param state One of TransactionValues.OrderState. + * @param label Label for the order state. + * @return Returns current constructed OrderUpdate. + */ + setOrderState(state: OrderState, label: string): OrderUpdate; + + /** + * Set the update time of the order. + * + * @param seconds Seconds since Unix epoch. + * @param nanos Partial time units. + * @return Returns current constructed OrderUpdate. + */ + setUpdateTime(seconds: number, nanos?: number): OrderUpdate; + + /** + * Set the user notification content of the order update. + * + * @param title Title of the notification. + * @param text Text of the notification. + * @return Returns current constructed OrderUpdate. + */ + setUserNotification(title: string, text: object): OrderUpdate; + + /** + * Sets the total price for this order. + * + * @param priceType One of TransactionValues.PriceType. + * @param currencyCode Currency code of price. + * @param units Unit count of price. + * @param nanos Partial unit count of price. + * @return Returns current constructed OrderUpdate. + */ + setTotalPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): OrderUpdate; + + /** + * Adds an actionable item for the user to manage the order. + * + * @param type One of TransactionValues.OrderActions. + * @param label Button label. + * @param url URL to open when button is clicked. + * @return Returns current constructed OrderUpdate. + */ + addOrderManagementAction(type: OrderAction, label: string, url: string): OrderUpdate; + + /** + * Adds a single price update for a particular line item in the order. + * + * @param itemId Line item ID for the order item updated. + * @param priceType One of TransactionValues.PriceType. + * @param currencyCode Currency code of new price. + * @param units Unit count of new price. + * @param nanos Partial unit count of new price. + * @param reason Reason for the price change. Required unless a + * reason for this line item change was already declared in + * addLineItemStateUpdate. + * @return Returns current constructed OrderUpdate. + */ + addLineItemPriceUpdate(itemId: string, priceType: PriceType, currencyCode: string, units: number, nanos?: number, reason?: string): OrderUpdate; + + /** + * Adds a single state update for a particular line item in the order. + * + * @param itemId Line item ID for the order item updated. + * @param state One of TransactionValues.OrderState. + * @param label Label for the new item state. + * @param reason Reason for the price change. This will overwrite + * any reason given in addLineitemPriceUpdate. + * @return Returns current constructed OrderUpdate. + */ + addLineItemStateUpdate(itemId: string, state: OrderState, label: string, reason?: string): OrderUpdate; + + /** + * Sets some extra information about the order. Takes an order update info + * type, and any accompanying data. This should only be called once per + * order update. + * + * @param type One of TransactionValues.OrderStateInfo. + * @param data Proper Object matching the data necessary for the info + * type. For instance, for the TransactionValues.OrderStateInfo.RECEIPT info + * type, use the {@link ReceiptInfo} data type. + * @return Returns current constructed OrderUpdate. + */ + setInfo(type: string, data: object): OrderUpdate; +} diff --git a/types/actions-on-google/tsconfig.json b/types/actions-on-google/tsconfig.json new file mode 100644 index 0000000000..6682b5c194 --- /dev/null +++ b/types/actions-on-google/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "assistant-app.d.ts", + "actions-sdk-app.d.ts", + "dialogflow-app.d.ts", + "response-builder.d.ts", + "transactions.d.ts", + "actions-on-google-tests.ts" + ] +} diff --git a/types/actions-on-google/tslint.json b/types/actions-on-google/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/actions-on-google/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index 18f57af4ff..0db2ab0002 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -137,11 +137,11 @@ export interface AtomEnvironment { // Managing the Atom Window /** Open a new Atom window using the given options. */ - open(params: { + open(params?: { pathsToOpen: ReadonlyArray, - newWindow: boolean, - devMode: boolean, - safeMode: boolean, + newWindow?: boolean, + devMode?: boolean, + safeMode?: boolean, }): void; /** Close the current window. */ @@ -270,15 +270,18 @@ export interface CommandRegistry { }): CompositeDisposable; /** Find all registered commands matching a query. */ - findCommands(params: { target: Node }): Array<{ + findCommands(params: { target: string|Node }): Array<{ name: string, displayName: string, description?: string, tags?: string[], }>; - /** Simulate the dispatch of a command on a DOM node. */ - dispatch(target: Node, commandName: string): void; + /** + * Simulate the dispatch of a command on a DOM node. + * @return Whether or not there was a matching command for the target. + */ + dispatch(target: Node, commandName: string): boolean; /** Invoke the given callback before dispatching a command event. */ onWillDispatch(callback: (event: CommandEvent) => void): Disposable; @@ -1092,10 +1095,10 @@ export class Point { export class Range { // Properties /** A Point representing the start of the Range. */ - start: PointLike; + start: Point; /** A Point representing the end of the Range. */ - end: PointLike; + end: Point; // Construction /** Convert any range-compatible object to a Range. */ @@ -1114,7 +1117,7 @@ export class Range { negate(): Range; // Serialization and Deserialization - /** Returns a plain javascript object representation of the range. */ + /** Returns a plain javascript object representation of the Range. */ serialize(): number[][]; // Range Details @@ -4710,7 +4713,7 @@ export class TextBuffer { destroyed: boolean; /** Create a new buffer backed by the given file path. */ - static load(source: string, params?: BufferLoadOptions): Promise; + static load(filePath: string, params?: BufferLoadOptions): Promise; /** * Create a new buffer backed by the given file path. For better performance, @@ -4737,6 +4740,9 @@ export class TextBuffer { shouldDestroyOnFileDelete?(): boolean }); + /** Returns a plain javascript object representation of the TextBuffer. */ + serialize(options?: { markerLayers?: boolean, history?: boolean }): object; + /** Returns the unique identifier for this buffer. */ getId(): string; diff --git a/types/babel-webpack-plugin/babel-webpack-plugin-tests.ts b/types/babel-webpack-plugin/babel-webpack-plugin-tests.ts new file mode 100644 index 0000000000..89b8efc6e6 --- /dev/null +++ b/types/babel-webpack-plugin/babel-webpack-plugin-tests.ts @@ -0,0 +1,10 @@ +import BabelWebpackPlugin = require('babel-webpack-plugin'); + +new BabelWebpackPlugin(); +new BabelWebpackPlugin({}); +new BabelWebpackPlugin({ + test: /\.js$/, + presets: ['es2015'], + sourceMaps: false, + compact: false +}); diff --git a/types/babel-webpack-plugin/index.d.ts b/types/babel-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..3f16d154ac --- /dev/null +++ b/types/babel-webpack-plugin/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for babel-webpack-plugin 0.1 +// Project: https://github.com/simlrh/babel-webpack-plugin +// Definitions by: Jed Fox +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin } from 'webpack'; +import { TransformOptions } from 'babel-core'; + +export = BabelWebpackPlugin; + +declare class BabelWebpackPlugin extends Plugin { + constructor(options?: BabelWebpackPlugin.Options); +} + +declare namespace BabelWebpackPlugin { + type Matcher = RegExp | string | Array; + interface Options extends TransformOptions { + test?: Matcher; + include?: Matcher; + exclude?: Matcher; + } +} diff --git a/types/babel-webpack-plugin/tsconfig.json b/types/babel-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..3e73343283 --- /dev/null +++ b/types/babel-webpack-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "babel-webpack-plugin-tests.ts" + ] +} diff --git a/types/babel-webpack-plugin/tslint.json b/types/babel-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index ef9e8b0675..c2ae788396 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -78,7 +78,7 @@ interface Size { } declare namespace Chart { - type ChartType = 'line' | 'bar' | 'radar' | 'doughnut' | 'polarArea' | 'bubble'; + type ChartType = 'line' | 'bar' | 'radar' | 'doughnut' | 'polarArea' | 'bubble' | 'pie'; type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'; diff --git a/types/clean-webpack-plugin/clean-webpack-plugin-tests.ts b/types/clean-webpack-plugin/clean-webpack-plugin-tests.ts new file mode 100644 index 0000000000..6d60f36d51 --- /dev/null +++ b/types/clean-webpack-plugin/clean-webpack-plugin-tests.ts @@ -0,0 +1,17 @@ +import CleanWebpackPlugin = require('clean-webpack-plugin'); + +const paths = [ + 'path', + 'glob/**/*.js', +]; + +new CleanWebpackPlugin(paths); +new CleanWebpackPlugin(paths, 'root-directory'); +new CleanWebpackPlugin(paths, {}); +new CleanWebpackPlugin(paths, { + root: 'root-directory', + verbose: true, + dry: true, + watch: true, + exclude: ['a, b'], +}); diff --git a/types/clean-webpack-plugin/index.d.ts b/types/clean-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..7fc45cc3e4 --- /dev/null +++ b/types/clean-webpack-plugin/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for clean-webpack-plugin 0.1 +// Project: https://github.com/johnagan/clean-webpack-plugin +// Definitions by: Jed Fox +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack'; + +export = CleanWebpackPlugin; + +declare class CleanWebpackPlugin extends Plugin { + /** + * @param paths A glob or array of globs to delete + */ + constructor(paths: string | ReadonlyArray, options?: string | CleanWebpackPlugin.Options); +} + +declare namespace CleanWebpackPlugin { + interface Options { + /** + * Absolute path to your webpack root folder (paths appended to this) + * Default: root of your package + */ + root?: string; + /** + * Write logs to the console. + */ + verbose?: boolean; + /** + * Set to `true` to emulate deletion without actually removing any files. + */ + dry?: boolean; + /** + * If true, remove files on recompile. + */ + watch?: boolean; + /** + * Instead of removing whole path recursively, + * remove all path's content with exclusion of provided immediate children. + * Good for not removing shared files from build directories. + */ + exclude?: ReadonlyArray; + /** + * Allow the plugin to clean folders outside of the webpack root + */ + allowExternal?: boolean; + } +} diff --git a/types/clean-webpack-plugin/tsconfig.json b/types/clean-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..2f342b4d42 --- /dev/null +++ b/types/clean-webpack-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clean-webpack-plugin-tests.ts" + ] +} diff --git a/types/clean-webpack-plugin/tslint.json b/types/clean-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clean-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cors/cors-tests.ts b/types/cors/cors-tests.ts index f43b9ee153..83975549c7 100644 --- a/types/cors/cors-tests.ts +++ b/types/cors/cors-tests.ts @@ -2,7 +2,7 @@ import express = require('express'); import cors = require('cors'); -var app = express(); +const app = express(); app.use(cors()); app.use(cors({ maxAge: 100, @@ -28,6 +28,9 @@ app.use(cors({ app.use(cors({ origin: /example\.com$/ })); +app.use(cors({ + origin: [/example\.com$/, 'http://example.com'] +})); app.use(cors({ origin: ['http://example.com', 'http://fakeurl.com'] })); @@ -37,7 +40,7 @@ app.use(cors({ app.use(cors({ origin: (requestOrigin, cb) => { try { - var allow = requestOrigin.indexOf('.edu') !== -1; + const allow = requestOrigin.indexOf('.edu') !== -1; cb(null, allow); } catch (err) { cb(err); diff --git a/types/cors/index.d.ts b/types/cors/index.d.ts index 0a99217f1f..ab8ba2ed2d 100644 --- a/types/cors/index.d.ts +++ b/types/cors/index.d.ts @@ -16,7 +16,7 @@ type CustomOrigin = ( declare namespace e { interface CorsOptions { - origin?: boolean | string | RegExp | string[] | RegExp[] | CustomOrigin; + origin?: boolean | string | RegExp | (string | RegExp)[] | CustomOrigin; methods?: string | string[]; allowedHeaders?: string | string[]; exposedHeaders?: string | string[]; diff --git a/types/cson/cson-tests.ts b/types/cson/cson-tests.ts index e5bdc67069..8d196e33c7 100644 --- a/types/cson/cson-tests.ts +++ b/types/cson/cson-tests.ts @@ -13,7 +13,7 @@ console.log('cson.createJSONString => %s', data); data = cson.createCSONString({hello: 'world'}); console.log('cson.createCSONString => %s', data); -var obj: Object = cson.parse(data); +var obj = cson.parse(data); console.log('cson.parse => %s', JSON.stringify(obj)); obj = cson.parseCSONString(data); diff --git a/types/cson/index.d.ts b/types/cson/index.d.ts index 72b985a82d..3366283721 100644 --- a/types/cson/index.d.ts +++ b/types/cson/index.d.ts @@ -5,27 +5,27 @@ // Create Strings -export declare function stringify(data: Object, opts?: Object, indent?: any): string; -export declare function createCSONString(data: Object, opts?: Object, next?: any): string; -export declare function createJSONString(data: Object, opts?: Object, next?: any): string; -export declare function createString(data: Object, opts?: Object, next?: any): string; +export declare function stringify(data: any, opts?: Object, indent?: any): string; +export declare function createCSONString(data: any, opts?: Object, next?: any): string; +export declare function createJSONString(data: any, opts?: Object, next?: any): string; +export declare function createString(data: any, opts?: Object, next?: any): string; // Parse Strings -export declare function parse(data: string, opts?: Object, next?: any): Object; -export declare function parseCSONString(data: string, opts?: Object, next?: any): Object; -export declare function parseJSONString(data: string, opts?: Object, next?: any): Object; -export declare function parseCSString(data: string, opts?: Object, next?: any): Object; -export declare function parseJSString(data: string, opts?: Object, next?: any): Object; -export declare function parseString(data: string, opts?: Object, next?: any): Object; +export declare function parse(data: string, opts?: Object, next?: any): any; +export declare function parseCSONString(data: string, opts?: Object, next?: any): any; +export declare function parseJSONString(data: string, opts?: Object, next?: any): any; +export declare function parseCSString(data: string, opts?: Object, next?: any): any; +export declare function parseJSString(data: string, opts?: Object, next?: any): any; +export declare function parseString(data: string, opts?: Object, next?: any): any; // Parse Files -export declare function load(filePath: string, opts?: Object, next?: any): Object; -export declare function parseCSONFile(filePath: string, opts?: Object, next?: any): Object; -export declare function parseJSONFile(filePath: string, opts?: Object, next?: any): Object; -export declare function parseCSFile(filePath: string, opts?: Object, next?: any): Object; -export declare function parseJSFile(filePath: string, opts?: Object, next?: any): Object; +export declare function load(filePath: string, opts?: Object, next?: any): any; +export declare function parseCSONFile(filePath: string, opts?: Object, next?: any): any; +export declare function parseJSONFile(filePath: string, opts?: Object, next?: any): any; +export declare function parseCSFile(filePath: string, opts?: Object, next?: any): any; +export declare function parseJSFile(filePath: string, opts?: Object, next?: any): any; // Require Files -export declare function requireCSFile(filePath: string, opts?: Object, next?: any): Object; -export declare function requireJSFile(filePath: string, opts?: Object, next?: any): Object; -export declare function requireFile(filePath: string, opts?: Object, next?: any): Object; +export declare function requireCSFile(filePath: string, opts?: Object, next?: any): any; +export declare function requireJSFile(filePath: string, opts?: Object, next?: any): any; +export declare function requireFile(filePath: string, opts?: Object, next?: any): any; diff --git a/types/google-apps-script-oauth2/google-apps-script-oauth2-tests.ts b/types/google-apps-script-oauth2/google-apps-script-oauth2-tests.ts new file mode 100644 index 0000000000..ca6d874fa4 --- /dev/null +++ b/types/google-apps-script-oauth2/google-apps-script-oauth2-tests.ts @@ -0,0 +1,32 @@ +// Examples from https://github.com/googlesamples/apps-script-oauth2 + +/** + * Create the OAuth2 service. + */ +function getDriveService() { + return OAuth2.createService('drive') + .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth') + .setTokenUrl('https://accounts.google.com/o/oauth2/token') + .setClientId('xxx') + .setClientSecret('yyy') + .setCallbackFunction('authCallback') + .setPropertyStore(PropertiesService.getUserProperties()) + .setScope('https://www.googleapis.com/auth/drive') + .setParam('login_hint', Session.getActiveUser().getEmail()) + .setParam('access_type', 'offline') + .setParam('approval_prompt', 'force') + ; +} + +/** + * Handle the callback. + */ +function authCallback(request: any) { + const driveService = getDriveService(); + const isAuthorized = driveService.handleCallback(request); + if (isAuthorized) { + Logger.log('success'); + } else { + Logger.log('denied'); + } +} diff --git a/types/google-apps-script-oauth2/index.d.ts b/types/google-apps-script-oauth2/index.d.ts new file mode 100644 index 0000000000..d5d9022849 --- /dev/null +++ b/types/google-apps-script-oauth2/index.d.ts @@ -0,0 +1,197 @@ +// Type definitions for google-apps-script-oauth2 24.0 +// Project: https://github.com/googlesamples/apps-script-oauth2 +// Definitions by: dhayab +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +declare namespace GoogleAppsScriptOAuth2 { + interface OAuth2 { + /** + * The supported locations for passing the state parameter. + */ + STATE_PARAMETER_LOCATION: typeof StateParameterLocation; + /** + * The supported formats for the returned OAuth2 token. + */ + TOKEN_FORMAT: typeof TokenFormat; + /** + * Creates a new OAuth2 service with the name specified. + * It's usually best to create and configure your service once at the start of your script, + * and then reference them during the different phases of the authorization flow. + */ + createService(serviceName: string): OAuth2Service; + /** + * Returns the redirect URI that will be used for a given script. + * Often this URI needs to be entered into a configuration screen of your OAuth provider. + */ + getRedirectUri(scriptId: string): string; + } + + interface OAuth2Service { + /** + * Gets an access token for this service. + * This token can be used in HTTP requests to the service's endpoint. + * This method will throw an error if the user's access was not granted or has expired. + */ + getAccessToken(): string; + /** + * Gets the authorization URL. + * The first step in getting an OAuth2 token is to have the user visit this URL + * and approve the authorization request. The user will then be redirected back to your + * application using callback function name specified, so that the flow may continue. + */ + getAuthorizationUrl(): string; + /** + * Gets the last error that occurred this execution when trying to + * automatically refresh or generate an access token. + */ + getLastError(): any; + /** + * Returns the redirect URI that will be used for this service. + * Often this URI needs to be entered into a configuration screen of your OAuth provider. + */ + getRedirectUri(): string; + /** + * Gets the token from the service's property store or cache. + */ + getToken(): object | null; + /** + * Completes the OAuth2 flow using the request data passed in to the callback function. + */ + handleCallback(callbackRequest: object): boolean; + /** + * Determines if the service has access (has been authorized and hasn't expired). + * If offline access was granted and the previous token has expired this method attempts + * to generate a new token. + */ + hasAccess(): boolean; + /** + * Refreshes a token that has expired. + * This is only possible if offline access was requested when the token was authorized. + */ + refresh(): void; + /** + * Resets the service, removing access and requiring the service to be re-authorized. + */ + reset(): void; + /** + * Sets the service's authorization base URL (required). + * For Google services this URL should be `https://accounts.google.com/o/oauth2/auth`. + */ + setAuthorizationBaseUrl(authorizationBaseUrl: string): OAuth2Service; + /** + * Sets the cache to use when persisting credentials (optional). + * Using a cache will reduce the need to read from the property store and may increase + * performance. In most cases this should be a private cache, but a public cache may be + * appropriate if you want to share access across users. + */ + setCache(cache: GoogleAppsScript.Cache.Cache): OAuth2Service; + /** + * Sets the name of the authorization callback function (required). + * This is the function that will be called when the user completes the authorization flow + * on the service provider's website. The callback accepts a request parameter, which + * should be passed to this service's `handleCallback()` method to complete the process. + */ + setCallbackFunction(callbackFunctionName: string): OAuth2Service; + /** + * Sets the client ID to use for the OAuth flow (required). + * You can create client IDs in the "Credentials" section of a Google Developers Console + * project. Although you can use any project with this library, it may be convinient to use + * the project that was created for your script. These projects are not visible if you + * visit the console directly, but you can access it by click on the menu item + * "Resources > Advanced Google services" in the Script Editor, and then click on the link + * "Google Developers Console" in the resulting dialog. + */ + setClientId(clientId: string): OAuth2Service; + /** + * Sets the client secret to use for the OAuth flow (required). + * See the documentation for `setClientId()` for more information on how to create client IDs and secrets. + */ + setClientSecret(clientSecret: string): OAuth2Service; + /** + * Sets number of minutes that a token obtained through Service Account authorization should be valid. Default: 60 minutes. + */ + setExpirationMinutes(expirationMinutes: string): OAuth2Service; + /** + * Sets the issuer (iss) value to use for Service Account authorization. + * If not set the client ID will be used instead. + */ + setIssuer(issuer: string): OAuth2Service; + /** + * Sets an additional parameter to use when constructing the authorization URL (optional). + * See the documentation for your service provider for information on what parameter values they support. + */ + setParam(name: string, value: string): OAuth2Service; + /** + * Sets the private key to use for Service Account authorization. + */ + setPrivateKey(privateKey: string): OAuth2Service; + /** + * Sets the property store to use when persisting credentials (required). + * In most cases this should be user properties, but document or script properties may be appropriate + * if you want to share access across users. + */ + setPropertyStore(propertyStore: GoogleAppsScript.Properties.Properties): OAuth2Service; + /** + * Sets the scope or scopes to request during the authorization flow (optional). + * If the scope value is an array it will be joined using the separator before being sent to the server, + * which is is a space character by default. + */ + setScope(scope: string | string[], separator?: string): OAuth2Service; + /** + * Sets the subject (sub) value to use for Service Account authorization. + */ + setSubject(subject: string): OAuth2Service; + /** + * Sets the format of the returned token. Default: `OAuth2.TOKEN_FORMAT.JSON`. + */ + setTokenFormat(tokenFormat: TokenFormat): OAuth2Service; + /** + * Sets the additional HTTP headers that should be sent when retrieving or refreshing the access token. + */ + setTokenHeaders(tokenHeaders: { [key: string]: string }): OAuth2Service; + /** + * Sets an additional function to invoke on the payload of the access token request. + */ + setTokenPayloadHandler(tokenHandler: (tokenPayload: TokenPayload) => object): OAuth2Service; + /** + * Sets the service's token URL (required). + * For Google services this URL should be `https://accounts.google.com/o/oauth2/token`. + */ + setTokenUrl(tokenUrl: string): OAuth2Service; + } + + enum StateParameterLocation { + /** + * Pass the state parameter in the authorization URL. + */ + AUTHORIZATION_URL, + /** + * Pass the state token in the redirect URL, as a workaround for APIs that don't support the state parameter. + */ + REDIRECT_URL, + } + + enum TokenFormat { + /** + * JSON format, for example `{"access_token": "..."}`. + */ + JSON, + /** + * Form URL-encoded, for example `access_token=...`. + */ + FORM_URL_ENCODED, + } + + interface TokenPayload { + code: string; + client_id: string; + client_secret: string; + redirect_uri: string; + grant_type: string; + } +} + +declare var OAuth2: GoogleAppsScriptOAuth2.OAuth2; diff --git a/types/google-apps-script-oauth2/tsconfig.json b/types/google-apps-script-oauth2/tsconfig.json new file mode 100644 index 0000000000..bc09dd70b9 --- /dev/null +++ b/types/google-apps-script-oauth2/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "google-apps-script-oauth2-tests.ts" + ] +} diff --git a/types/google-apps-script-oauth2/tslint.json b/types/google-apps-script-oauth2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-apps-script-oauth2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google.picker/index.d.ts b/types/google.picker/index.d.ts index 0341811917..11397695a2 100644 --- a/types/google.picker/index.d.ts +++ b/types/google.picker/index.d.ts @@ -146,6 +146,9 @@ declare namespace google { // For photo uploads, controls whether per-photo selection (as opposed to per-album) selection is enabled. SIMPLE_UPLOAD_ENABLED: string; + + // Whether Team Drive items should be included in results. + SUPPORT_TEAM_DRIVES: string; }; export var ViewId:{ diff --git a/types/highlight.js/index.d.ts b/types/highlight.js/index.d.ts index 7ae5d613fe..d691811b47 100644 --- a/types/highlight.js/index.d.ts +++ b/types/highlight.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for highlight.js v9.1.0 +// Type definitions for highlight.js v9.12 // Project: https://github.com/isagalaev/highlight.js // Definitions by: Niklas Mollenhauer , Jeremy Hull // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,7 +9,7 @@ declare namespace hljs name: string, value: string, ignore_illegals?: boolean, - continuation?: boolean) : IHighlightResult; + continuation?: ICompiledMode) : IHighlightResult; export function highlightAuto( value: string, languageSubset?: string[]) : IAutoHighlightResult; @@ -154,6 +154,6 @@ declare namespace hljs } } -declare module 'highlight.js' { - export = hljs; -} \ No newline at end of file + +export = hljs; +export as namespace hljs; diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 18b3db361a..1b8d137094 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -8,6 +8,7 @@ // Allan Lukwago // Ika // Waseem Dahman +// Jamie Mason // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -240,7 +241,7 @@ declare namespace jest { } interface ExpectExtendMap { - [key: string]: (this: MatcherUtils, received: any, actual: any) => { message(): string, pass: boolean }; + [key: string]: (this: MatcherUtils, received: any, ...actual: any[]) => { message(): string, pass: boolean }; } interface SnapshotSerializerOptions { diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index d2b4d95a0e..aca5021f1b 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -259,6 +259,12 @@ describe('Extending extend', () => { () => `expected ${received} ${pass ? 'not ' : ''} to be ${actual}`; return { message, pass }; }, + toBeVariadicMatcher(received: any, floor: number, ceiling: number) { + const pass = received >= floor && received <= ceiling; + const message = + () => `expected ${received} ${pass ? 'not ' : ''} to be within range ${floor}-${ceiling}`; + return { message, pass }; + }, toBeTest(received: any, actual: any) { this.utils.ensureNoExpected(received); this.utils.ensureActualIsNumber(received); diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 02ac767427..6dbc08245a 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1,6 +1,13 @@ -// Type definitions for joi v10.4.2 +// Type definitions for joi v13.0.1 // Project: https://github.com/hapijs/joi -// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers , Gael Magnan de Bornier , Rytis Alekna , Pavel Ivanov , Youngrok Kim +// Definitions by: Bart van der Schoor +// Laurence Dougal Myers +// Christopher Glantschnig +// David Broder-Rodgers +// Gael Magnan de Bornier +// Rytis Alekna +// Pavel Ivanov +// Youngrok Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -88,7 +95,7 @@ export interface EmailOptions { /** * Specifies a list of acceptable TLDs. */ - tldWhitelist?: string[] | Object; + tldWhitelist?: string[] | object; /** * Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email. */ @@ -161,7 +168,7 @@ export interface ValidationError extends Error, JoiObject { export interface ValidationErrorItem { message: string; type: string; - path: string; + path: string[]; options?: ValidationOptions; context?: Context; } @@ -195,6 +202,8 @@ export type Schema = AnySchema export interface AnySchema extends JoiObject { + schemaType?: Types | string; + /** * Validates a value using the schema and options. */ @@ -270,7 +279,7 @@ export interface AnySchema extends JoiObject { /** * Attaches metadata to the key. */ - meta(meta: Object): this; + meta(meta: object): this; /** * Annotates the key with an example value, must be valid. @@ -346,7 +355,7 @@ export interface AnySchema extends JoiObject { * an instance of `Error` - the override error. * a `function(errors)`, taking an array of errors as argument, where it must either: * return a `string` - substitutes the error message with this text - * return a single `object` or an `Array` of it, where: + * return a single ` object` or an `Array` of it, where: * `type` - optional parameter providing the type of the error (eg. `number.min`). * `message` - optional parameter if `template` is provided, containing the text of the error. * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. @@ -384,6 +393,8 @@ export interface Description { export interface Context { [key: string]: any; + key?: string; + label?: string; } export interface State { @@ -455,7 +466,7 @@ export interface NumberSchema extends AnySchema { /** * Specifies the maximum number of decimal places where: - * limit - the maximum number of decimal places allowed. + * @param limit - the maximum number of decimal places allowed. */ precision(limit: number): this; @@ -497,6 +508,18 @@ export interface StringSchema extends AnySchema { max(limit: number, encoding?: string): this; max(limit: Reference, encoding?: string): this; + /** + * Specifies whether the string.max() limit should be used as a truncation. + * @param enabled - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value. + */ + truncate(enabled?: boolean): this; + + /** + * Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized. + * @param form - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this; + /** * Requires the number to be a credit card number (Using Lunh Algorithm). */ @@ -554,7 +577,7 @@ export interface StringSchema extends AnySchema { * Requires the string value to be a valid GUID. */ guid(options?: GuidOptions): this; - + /** * Alias for `guid` -- Requires the string value to be a valid GUID */ @@ -651,6 +674,7 @@ export interface ArraySchema extends AnySchema { } export interface ObjectSchema extends AnySchema { + /** * Sets the allowed object keys. */ @@ -888,7 +912,7 @@ export type ExtensionBoundSchema = Schema & { export interface Rules

{ name: string; - params?: ObjectSchema | { [key in keyof P]: SchemaLike; }; + params?: ObjectSchema | {[key in keyof P]: SchemaLike; }; setup?(this: ExtensionBoundSchema, params: P): Schema | void; validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): Err | R; description?: string | ((params: P) => string); @@ -965,10 +989,15 @@ export function string(): StringSchema; /** * Generates a type that will match one of the provided alternative schemas */ -export function alternatives(): AlternativesSchema; export function alternatives(types: SchemaLike[]): AlternativesSchema; export function alternatives(...types: SchemaLike[]): AlternativesSchema; +/** + * Alias for `alternatives` + */ +export function alt(types: SchemaLike[]): AlternativesSchema; +export function alt(...types: SchemaLike[]): AlternativesSchema; + /** * Generates a placeholder schema for a schema that you would provide with the fn. * Supports the same methods of the any() type. @@ -1030,7 +1059,140 @@ export function reach(schema: ObjectSchema, path: string): T; */ export function extend(extention: Extension): any; +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +import * as Module from 'joi'; +export type Root = typeof Module; +export type DefaultsFunction = (root: Schema) => Schema; + +/** + * Creates a new Joi instance that will apply defaults onto newly created schemas + * through the use of the fn function that takes exactly one argument, the schema being created. + * + * @param fn - The function must always return a schema, even if untransformed. + */ +export function defaults(fn: DefaultsFunction): Root; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +// Below are undocumented APIs. use at your own risk +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + /** * Returns a plain object representing the schema's rules and properties */ export function describe(schema: Schema): Description; + +/** +* Whitelists a value +*/ +export function allow(value: any, ...values: any[]): Schema; +export function allow(values: any[]): Schema; + +/** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ +export function valid(value: any, ...values: any[]): Schema; +export function valid(values: any[]): Schema; +export function only(value: any, ...values: any[]): Schema; +export function only(values: any[]): Schema; +export function equal(value: any, ...values: any[]): Schema; +export function equal(values: any[]): Schema; + +/** + * Blacklists a value + */ +export function invalid(value: any, ...values: any[]): Schema; +export function invalid(values: any[]): Schema; +export function disallow(value: any, ...values: any[]): Schema; +export function disallow(values: any[]): Schema; +export function not(value: any, ...values: any[]): Schema; +export function not(values: any[]): Schema; + +/** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ +export function required(): Schema; + +/** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ +export function optional(): Schema; + +/** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ +export function forbidden(): Schema; + +/** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ +export function strip(): Schema; + +/** + * Annotates the key + */ +export function description(desc: string): Schema; + +/** + * Annotates the key + */ +export function notes(notes: string): Schema; +export function notes(notes: string[]): Schema; + +/** + * Annotates the key + */ +export function tags(notes: string): Schema; +export function tags(notes: string[]): Schema; + +/** + * Attaches metadata to the key. + */ +export function meta(meta: object): Schema; + +/** + * Annotates the key with an example value, must be valid. + */ +export function example(value: any): Schema; + +/** + * Annotates the key with an unit name. + */ +export function unit(name: string): Schema; + +/** + * Overrides the global validate() options for the current key and any sub-key. + */ +export function options(options: ValidationOptions): Schema; + +/** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ +export function strict(isStrict?: boolean): Schema; + +/** + * Returns a new type that is the result of adding the rules of one type to another. + */ +export function concat(schema: T): T; + +/** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ +export function when(ref: string, options: WhenOptions): AlternativesSchema; +export function when(ref: Reference, options: WhenOptions): AlternativesSchema; + +/** + * Overrides the key name in error messages. + */ +export function label(name: string): Schema; + +/** + * Outputs the original untouched value instead of the casted value. + */ +export function raw(isRaw?: boolean): Schema; + +/** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ +export function empty(schema?: any): Schema; diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 4f49a69b3f..96d91a72b9 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -136,13 +136,13 @@ var validErrFunc: Joi.ValidationErrorFunction; validErrItem = { message: str, type: str, - path: str + path: [str] }; validErrItem = { message: str, type: str, - path: str, + path: [str], options: validOpts, context: obj }; @@ -773,6 +773,10 @@ strSchema = strSchema.isoDate(); strSchema = strSchema.lowercase(); strSchema = strSchema.uppercase(); strSchema = strSchema.trim(); +strSchema = strSchema.truncate(); +strSchema = strSchema.truncate(false); +strSchema = strSchema.normalize(); +strSchema = strSchema.normalize('NFKC'); namespace common { strSchema = strSchema.allow(x); @@ -830,6 +834,13 @@ schema = Joi.alternatives().try(schema, schema); schema = Joi.alternatives(schemaArr); schema = Joi.alternatives(schema, anySchema, boolSchema); +schema = Joi.alt(); +schema = Joi.alt().try(schemaArr); +schema = Joi.alt().try(schema, schema); + +schema = Joi.alt(schemaArr); +schema = Joi.alt(schema, anySchema, boolSchema); + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = Joi.lazy(() => schema) @@ -844,14 +855,14 @@ namespace validate_tests { Joi.validate(value, schema, validOpts, (err, value) => { x = value; str = err.message; - str = err.details[0].path; + str = err.details[0].path[0]; str = err.details[0].message; str = err.details[0].type; }); Joi.validate(value, schema, (err, value) => { x = value; str = err.message; - str = err.details[0].path; + str = err.details[0].path.join('.'); str = err.details[0].message; str = err.details[0].type; }); @@ -950,3 +961,120 @@ const Joi3 = Joi.extend({ }, ], }); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +const defaultsJoi = Joi.defaults((schema) => { + switch (schema.schemaType) { + case 'string': + return schema.allow(''); + case 'object': + return (schema as Joi.ObjectSchema).min(1); + default: + return schema; + } +}); + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); diff --git a/types/joi/tsconfig.json b/types/joi/tsconfig.json index f6b8f170dc..57e6c47881 100644 --- a/types/joi/tsconfig.json +++ b/types/joi/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "joi-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/joi/v10/index.d.ts b/types/joi/v10/index.d.ts new file mode 100644 index 0000000000..372975ed9e --- /dev/null +++ b/types/joi/v10/index.d.ts @@ -0,0 +1,1178 @@ +// Type definitions for joi v10.6.0 +// Project: https://github.com/hapijs/joi +// Definitions by: Bart van der Schoor +// Laurence Dougal Myers +// Christopher Glantschnig +// David Broder-Rodgers +// Gael Magnan de Bornier +// Rytis Alekna +// Pavel Ivanov +// Youngrok Kim +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +// TODO express type of Schema in a type-parameter (.default, .valid, .example etc) + +export type Types = 'any' | 'alternatives' | 'array' | 'boolean' | 'binary' | 'date' | 'function' | 'lazy' | 'number' | 'object' | 'string'; + +export type LanguageOptions = string | false | null | { + [key: string]: LanguageOptions; +}; + +export type LanguageRootOptions = { + root?: string; + key?: string; + messages?: { wrapArrays?: boolean; }; +} & Partial> & { [key: string]: LanguageOptions; }; + +export interface ValidationOptions { + /** + * when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true. + */ + abortEarly?: boolean; + /** + * when true, attempts to cast values to the required types (e.g. a string to a number). Defaults to true. + */ + convert?: boolean; + /** + * when true, allows object to contain unknown keys which are ignored. Defaults to false. + */ + allowUnknown?: boolean; + /** + * when true, ignores unknown keys with a function value. Defaults to false. + */ + skipFunctions?: boolean; + /** + * remove unknown elements from objects and arrays. Defaults to false + * - when true, all unknown elements will be removed + * - when an object: + * - arrays - set to true to remove unknown items from arrays. + * - objects - set to true to remove unknown keys from objects + */ + stripUnknown?: boolean | { arrays?: boolean; objects?: boolean }; + /** + * overrides individual error messages. Defaults to no override ({}). + */ + language?: LanguageRootOptions; + /** + * sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'. Defaults to 'optional'. + */ + presence?: 'optional' | 'required' | 'forbidden'; + /** + * provides an external data set to be used in references + */ + context?: Context; + /** + * when true, do not apply default values. Defaults to false. + */ + noDefaults?: boolean; +} + +export interface RenameOptions { + /** + * if true, does not delete the old key name, keeping both the new and old keys in place. Defaults to false. + */ + alias?: boolean; + /** + * if true, allows renaming multiple keys to the same destination where the last rename wins. Defaults to false. + */ + multiple?: boolean; + /** + * if true, allows renaming a key over an existing key. Defaults to false. + */ + override?: boolean; + /** + * if true, skip renaming of a key if it's undefined. Defaults to false. + */ + ignoreUndefined?: boolean; +} + +export interface EmailOptions { + /** + * Numerical threshold at which an email address is considered invalid + */ + errorLevel?: number | boolean; + /** + * Specifies a list of acceptable TLDs. + */ + tldWhitelist?: string[] | Object; + /** + * Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email. + */ + minDomainAtoms?: number; +} + +export interface IpOptions { + /** + * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture + */ + version?: string | string[]; + /** + * Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden + */ + cidr?: string; +} + +export type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5' + +export interface GuidOptions { + version: GuidVersions[] | GuidVersions; +} + +export interface UriOptions { + /** + * Specifies one or more acceptable Schemes, should only include the scheme name. + * Can be an Array or String (strings are automatically escaped for use in a Regular Expression). + */ + scheme?: string | RegExp | Array; +} + +export interface WhenOptions { + /** + * the required condition joi type. + */ + is: SchemaLike; + /** + * the alternative schema type if the condition is true. Required if otherwise is missing. + */ + then?: SchemaLike; + /** + * the alternative schema type if the condition is false. Required if then is missing + */ + otherwise?: SchemaLike; +} + +export interface ReferenceOptions { + separator?: string; + contextPrefix?: string; +} + +export interface IPOptions { + version?: Array; + cidr?: string +} + +export interface JoiObject { + isJoi: boolean; +} + +export interface ValidationError extends Error, JoiObject { + details: ValidationErrorItem[]; + annotate(): string; + _object: any; +} + +export interface ValidationErrorItem { + message: string; + type: string; + path: string; + options?: ValidationOptions; + context?: Context; +} + +export interface ValidationErrorFunction { + (errors: ValidationErrorItem[]): string | ValidationErrorItem | ValidationErrorItem[] | Error; +} + +export interface ValidationResult { + error: ValidationError; + value: T; +} + +export type SchemaLike = string | number | boolean | object | null | Schema | SchemaMap; + +export interface SchemaMap { + [key: string]: SchemaLike | SchemaLike[]; +} + +export type Schema = AnySchema + | ArraySchema + | AlternativesSchema + | BinarySchema + | BooleanSchema + | DateSchema + | FunctionSchema + | NumberSchema + | ObjectSchema + | StringSchema + | LazySchema; + +export interface AnySchema extends JoiObject { + + /** + * Validates a value using the schema and options. + */ + validate(value: T): ValidationResult; + validate(value: T, options: ValidationOptions): ValidationResult; + validate(value: T, callback: (err: ValidationError, value: T) => R): R; + validate(value: T, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; + + /** + * Whitelists a value + */ + allow(...values: any[]): this; + allow(values: any[]): this; + + /** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ + valid(...values: any[]): this; + valid(values: any[]): this; + only(...values: any[]): this; + only(values: any[]): this; + equal(...values: any[]): this; + equal(values: any[]): this; + + /** + * Blacklists a value + */ + invalid(...values: any[]): this; + invalid(values: any[]): this; + disallow(...values: any[]): this; + disallow(values: any[]): this; + not(...values: any[]): this; + not(values: any[]): this; + + /** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ + required(): this; + exist(): this; + + /** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ + optional(): this; + + /** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ + forbidden(): this; + + /** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ + strip(): this; + + /** + * Annotates the key + */ + description(desc: string): this; + + /** + * Annotates the key + */ + notes(notes: string): this; + notes(notes: string[]): this; + + /** + * Annotates the key + */ + tags(notes: string): this; + tags(notes: string[]): this; + + /** + * Attaches metadata to the key. + */ + meta(meta: object): this; + + /** + * Annotates the key with an example value, must be valid. + */ + example(value: any): this; + + /** + * Annotates the key with an unit name. + */ + unit(name: string): this; + + /** + * Overrides the global validate() options for the current key and any sub-key. + */ + options(options: ValidationOptions): this; + + /** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ + strict(isStrict?: boolean): this; + + /** + * Sets a default value if the original value is undefined. + * @param value - the value. + * value supports references. + * value may also be a function which returns the default value. + * If value is specified as a function that accepts a single parameter, that parameter will be a context + * object that can be used to derive the resulting value. This clones the object however, which incurs some + * overhead so if you don't need access to the context define your method so that it does not accept any + * parameters. + * Without any value, default has no effect, except for object that will then create nested defaults + * (applying inner defaults of that object). + * + * Note that if value is an object, any changes to the object after default() is called will change the + * reference and any future assignment. + * + * Additionally, when specifying a method you must either have a description property on your method or the + * second parameter is required. + */ + default(value: any, description?: string): this; + default(): this; + + /** + * Returns a new type that is the result of adding the rules of one type to another. + */ + concat(schema: this): this; + + /** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + + /** + * Overrides the key name in error messages. + */ + label(name: string): this; + + /** + * Outputs the original untouched value instead of the casted value. + */ + raw(isRaw?: boolean): this; + + /** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ + empty(schema?: SchemaLike): this; + + /** + * Overrides the default joi error with a custom error if the rule fails where: + * @param err - can be: + * an instance of `Error` - the override error. + * a `function(errors)`, taking an array of errors as argument, where it must either: + * return a `string` - substitutes the error message with this text + * return a single ` object` or an `Array` of it, where: + * `type` - optional parameter providing the type of the error (eg. `number.min`). + * `message` - optional parameter if `template` is provided, containing the text of the error. + * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. + * `context` - optional parameter, to provide context to your error if you are using the `template`. + * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors. + * + * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the + * normal joi error properties. If validation fails and another error is found before the error + * override, that error will be returned and the override will be ignored (unless the `abortEarly` + * option has been set to `false`). + */ + error?(err: Error | ValidationErrorFunction): this; + + /** + * Returns a plain object representing the schema's rules and properties + */ + describe(): Description; +} + +export interface Description { + type?: Types | string; + label?: string; + description?: string; + flags?: object; + notes?: string[]; + tags?: string[]; + meta?: any[]; + example?: any[]; + valids?: any[]; + invalids?: any[]; + unit?: string; + options?: ValidationOptions; + [key: string]: any; +} + +export interface Context { + [key: string]: any; +} + +export interface State { + key?: string; + path?: string; + parent?: any; + reference?: any; +} + +export interface BooleanSchema extends AnySchema { + + /** + * Allows for additional values to be considered valid booleans by converting them to true during validation. + * Accepts a value or an array of values. String comparisons are by default case insensitive, + * see boolean.insensitive() to change this behavior. + * @param values - strings, numbers or arrays of them + */ + truthy(...values: Array): this; + + /** + * Allows for additional values to be considered valid booleans by converting them to false during validation. + * Accepts a value or an array of values. String comparisons are by default case insensitive, + * see boolean.insensitive() to change this behavior. + * @param values - strings, numbers or arrays of them + */ + falsy(...values: Array): this; + + /** + * Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion + * (when not in strict() mode) to be matched in a case insensitive manner. + * @param enabled + */ + insensitive(enabled?: boolean): this; +} + +export interface NumberSchema extends AnySchema { + /** + * Specifies the minimum value. + * It can also be a reference to another field. + */ + min(limit: number): this; + min(limit: Reference): this; + + /** + * Specifies the maximum value. + * It can also be a reference to another field. + */ + max(limit: number): this; + max(limit: Reference): this; + + /** + * Specifies that the value must be greater than limit. + * It can also be a reference to another field. + */ + greater(limit: number): this; + greater(limit: Reference): this; + + /** + * Specifies that the value must be less than limit. + * It can also be a reference to another field. + */ + less(limit: number): this; + less(limit: Reference): this; + + /** + * Requires the number to be an integer (no floating point). + */ + integer(): this; + + /** + * Specifies the maximum number of decimal places where: + * @param limit - the maximum number of decimal places allowed. + */ + precision(limit: number): this; + + /** + * Specifies that the value must be a multiple of base. + */ + multiple(base: number): this; + + /** + * Requires the number to be positive. + */ + positive(): this; + + /** + * Requires the number to be negative. + */ + negative(): this; +} + +export interface StringSchema extends AnySchema { + /** + * Allows the value to match any whitelist of blacklist item in a case insensitive comparison. + */ + insensitive(): this; + + /** + * Specifies the minimum number string characters. + * @param limit - the minimum number of string characters required. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + min(limit: number, encoding?: string): this; + min(limit: Reference, encoding?: string): this; + + /** + * Specifies the maximum number of string characters. + * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + max(limit: number, encoding?: string): this; + max(limit: Reference, encoding?: string): this; + + + /** + * Specifies whether the string.max() limit should be used as a truncation. + * @param enabled - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value. + */ + truncate(enabled?: boolean): this; + + /** + * Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized. + * @param form - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this; + + /** + * Requires the number to be a credit card number (Using Lunh Algorithm). + */ + creditCard(): this; + + /** + * Specifies the exact string length required + * @param limit - the required string length. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + length(limit: number, encoding?: string): this; + length(limit: Reference, encoding?: string): this; + + /** + * Defines a regular expression rule. + * @param pattern - a regular expression object the string value must match against. + * @param name - optional name for patterns (useful with multiple patterns). Defaults to 'required'. + */ + regex(pattern: RegExp, name?: string): this; + + /** + * Replace characters matching the given pattern with the specified replacement string where: + * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. + * @param replacement - the string that will replace the pattern. + */ + replace(pattern: RegExp, replacement: string): this; + replace(pattern: string, replacement: string): this; + + /** + * Requires the string value to only contain a-z, A-Z, and 0-9. + */ + alphanum(): this; + + /** + * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _. + */ + token(): this; + + /** + * Requires the string value to be a valid email address. + */ + email(options?: EmailOptions): this; + + /** + * Requires the string value to be a valid ip address. + */ + ip(options?: IpOptions): this; + + /** + * Requires the string value to be a valid RFC 3986 URI. + */ + uri(options?: UriOptions): this; + + /** + * Requires the string value to be a valid GUID. + */ + guid(options?: GuidOptions): this; + + /** + * Alias for `guid` -- Requires the string value to be a valid GUID + */ + uuid(options?: GuidOptions): this; + + /** + * Requires the string value to be a valid hexadecimal string. + */ + hex(): this; + + /** + * Requires the string value to be a valid hostname as per RFC1123. + */ + hostname(): this; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + isoDate(): this; + + /** + * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase. + */ + lowercase(): this; + + /** + * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase. + */ + uppercase(): this; + + /** + * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed. + */ + trim(): this; +} + +export interface ArraySchema extends AnySchema { + /** + * Allow this array to be sparse. + * enabled can be used with a falsy value to go back to the default behavior. + */ + sparse(enabled?: any): this; + + /** + * Allow single values to be checked against rules as if it were provided as an array. + * enabled can be used with a falsy value to go back to the default behavior. + */ + single(enabled?: any): this; + + /** + * List the types allowed for the array values. + * type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item in the array. + * If a type is .forbidden() then it cannot appear in the array. + * Required items can be added multiple times to signify that multiple items must be found. + * Errors will contain the number of items that didn't match. + * Any unmatched item having a label will be mentioned explicitly. + * + * @param type - a joi schema object to validate each array item against. + */ + items(...types: SchemaLike[]): this; + items(types: SchemaLike[]): this; + + /** + * Lists the types in sequence order for the array values where: + * @param type - a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item with the same index position in the array. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly. + */ + ordered(...types: SchemaLike[]): this; + ordered(types: SchemaLike[]): this; + + /** + * Specifies the minimum number of items in the array. + */ + min(limit: number): this; + + /** + * Specifies the maximum number of items in the array. + */ + max(limit: number): this; + + /** + * Specifies the exact number of items in the array. + */ + length(limit: number): this; + + /** + * Requires the array values to be unique. + * Be aware that a deep equality is performed on elements of the array having a type of object, + * a performance penalty is to be expected for this kind of operation. + */ + unique(comparator?: string): this; + unique(comparator?: (a: T, b: T) => boolean): this; +} + +export interface ObjectSchema extends AnySchema { + + /** + * Sets the allowed object keys. + */ + keys(schema?: SchemaMap): this; + + /** + * Specifies the minimum number of keys in the object. + */ + min(limit: number): this; + + /** + * Specifies the maximum number of keys in the object. + */ + max(limit: number): this; + + /** + * Specifies the exact number of keys in the object. + */ + length(limit: number): this; + + /** + * Specify validation rules for unknown keys matching a pattern. + */ + pattern(regex: RegExp, schema: SchemaLike): this; + + /** + * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. + * @param peers - the key names of which if one present, all are required. peers can be a single string value, + * an array of string values, or each peer provided as an argument. + */ + and(...peers: string[]): this; + and(peers: string[]): this; + + /** + * Defines a relationship between keys where not all peers can be present at the same time. + * @param peers - the key names of which if one present, the others may not all be present. + * peers can be a single string value, an array of string values, or each peer provided as an argument. + */ + nand(...peers: string[]): this; + nand(peers: string[]): this; + + /** + * Defines a relationship between keys where one of the peers is required (and more than one is allowed). + */ + or(...peers: string[]): this; + or(peers: string[]): this; + + /** + * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: + */ + xor(...peers: string[]): this; + xor(peers: string[]): this; + + /** + * Requires the presence of other keys whenever the specified key is present. + */ + with(key: string, peers: string): this; + with(key: string, peers: string[]): this; + + /** + * Forbids the presence of other keys whenever the specified is present. + */ + without(key: string, peers: string): this; + without(key: string, peers: string[]): this; + + /** + * Renames a key to another name (deletes the renamed key). + */ + rename(from: string, to: string, options?: RenameOptions): this; + + /** + * Verifies an assertion where. + */ + assert(ref: string, schema: SchemaLike, message?: string): this; + assert(ref: Reference, schema: SchemaLike, message?: string): this; + + /** + * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). + */ + unknown(allow?: boolean): this; + + /** + * Requires the object to be an instance of a given constructor. + * + * @param constructor - the constructor function that the object must be an instance of. + * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. + */ + type(constructor: Function, name?: string): this; + + /** + * Sets the specified children to required. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } }); + * var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d'); + * + * Note that in this example '' means the current object, a is not required but b is, as well as c and d. + */ + requiredKeys(children: string[]): this; + requiredKeys(...children: string[]): this; + + /** + * Sets the specified children to optional. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * The behavior is exactly the same as requiredKeys. + */ + optionalKeys(children: string[]): this; + optionalKeys(...children: string[]): this; +} + +export interface BinarySchema extends AnySchema { + /** + * Sets the string encoding format if a string input is converted to a buffer. + */ + encoding(encoding: string): this; + + /** + * Specifies the minimum length of the buffer. + */ + min(limit: number): this; + + /** + * Specifies the maximum length of the buffer. + */ + max(limit: number): this; + + /** + * Specifies the exact length of the buffer: + */ + length(limit: number): this; +} + +export interface DateSchema extends AnySchema { + + /** + * Specifies the oldest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + min(date: Date): this; + min(date: number): this; + min(date: string): this; + min(date: Reference): this; + + /** + * Specifies the latest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + max(date: Date): this; + max(date: number): this; + max(date: string): this; + max(date: Reference): this; + + /** + * Specifies the allowed date format: + * @param format - string or array of strings that follow the moment.js format. + */ + format(format: string): this; + format(format: string[]): this; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + iso(): this; + + /** + * Requires the value to be a timestamp interval from Unix Time. + * @param type - the type of timestamp (allowed values are unix or javascript [default]) + */ + timestamp(type?: 'javascript' | 'unix'): this; +} + +export interface FunctionSchema extends AnySchema { + + /** + * Specifies the arity of the function where: + * @param n - the arity expected. + */ + arity(n: number): this; + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + minArity(n: number): this; + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + maxArity(n: number): this; + + /** + * Requires the function to be a Joi reference. + */ + ref(): this; +} + +export interface AlternativesSchema extends AnySchema { + try(types: SchemaLike[]): this; + try(...types: SchemaLike[]): this; + when(ref: string, options: WhenOptions): this; + when(ref: Reference, options: WhenOptions): this; +} + +export interface LazySchema extends AnySchema { + +} + +export interface Reference extends JoiObject { + (value: any, validationOptions: ValidationOptions): any; + isContext: boolean; + key: string; + path: string; + toString(): string; +} + +export type ExtensionBoundSchema = Schema & { + /** + * Creates a joi error object. + * Used in conjunction with custom rules. + * @param type - the type of rule to create the error for. + * @param context - provide properties that will be available in the `language` templates. + * @param state - should the context passed into the `validate` function in a custom rule + * @param options - should the context passed into the `validate` function in a custom rule + */ + createError(type: string, context: Context, state: State, options: ValidationOptions): Err; +} + +export interface Rules

{ + name: string; + params?: ObjectSchema | {[key in keyof P]: SchemaLike; }; + setup?(this: ExtensionBoundSchema, params: P): Schema | void; + validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): Err | R; + description?: string | ((params: P) => string); +} + +export interface Extension { + name: string; + base?: Schema; + language?: LanguageOptions; + coerce?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R; + pre?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R; + describe?(this: Schema, description: Description): Description; + rules?: Rules[]; +} + +export interface Err extends JoiObject { + toString(): string; +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +/** + * Current version of the joi package. + */ +export const version: string; + +/** + * Generates a schema object that matches any data type. + */ +export function any(): AnySchema; + +/** + * Generates a schema object that matches an array data type. + */ +export function array(): ArraySchema; + +/** + * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool(). + */ +export function bool(): BooleanSchema; + +export function boolean(): BooleanSchema; + +/** + * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers). + */ +export function binary(): BinarySchema; + +/** + * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds). + */ +export function date(): DateSchema; + +/** + * Generates a schema object that matches a function type. + */ +export function func(): FunctionSchema; + +/** + * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers). + */ +export function number(): NumberSchema; + +/** + * Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). + */ +export function object(schema?: SchemaMap): ObjectSchema; + +/** + * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow(''). + */ +export function string(): StringSchema; + +/** + * Generates a type that will match one of the provided alternative schemas + */ +export function alternatives(types: SchemaLike[]): AlternativesSchema; +export function alternatives(...types: SchemaLike[]): AlternativesSchema; + +/** + * Alias for `alternatives` + */ +export function alt(types: SchemaLike[]): AlternativesSchema; +export function alt(...types: SchemaLike[]): AlternativesSchema; + +/** + * Generates a placeholder schema for a schema that you would provide with the fn. + * Supports the same methods of the any() type. + * This is mostly useful for recursive schemas + */ +export function lazy(cb: () => Schema): LazySchema; + +/** + * Validates a value using the given schema and options. + */ +export function validate(value: T, schema: SchemaLike): ValidationResult; +export function validate(value: T, schema: SchemaLike, callback: (err: ValidationError, value: T) => R): R; + +export function validate(value: T, schema: SchemaLike, options: ValidationOptions): ValidationResult; +export function validate(value: T, schema: SchemaLike, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; + +/** + * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). + */ +export function compile(schema: SchemaLike): Schema; +export function compile(schema: SchemaLike): T; + +/** + * Validates a value against a schema and throws if validation fails. + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ +export function assert(value: any, schema: SchemaLike, message?: string | Error): void; + +/** + * Validates a value against a schema, returns valid object, and throws if validation fails where: + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ +export function attempt(value: T, schema: SchemaLike, message?: string | Error): T; + +/** + * Generates a reference to the value of the named key. + */ +export function ref(key: string, options?: ReferenceOptions): Reference; + +/** + * Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages. + */ +export function isRef(ref: any): ref is Reference; + +/** + * Get a sub-schema of an existing schema based on a path. Path separator is a dot (.). + */ +export function reach(schema: ObjectSchema, path: string): Schema; +export function reach(schema: ObjectSchema, path: string): T; + +/** + * Creates a new Joi instance customized with the extension(s) you provide included. + */ +export function extend(extention: Extension): any; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +// Below are undocumented APIs. use at your own risk +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +/** + * Returns a plain object representing the schema's rules and properties + */ +export function describe(schema: Schema): Description; + +/** +* Whitelists a value +*/ +export function allow(value: any, ...values: any[]): Schema; +export function allow(values: any[]): Schema; + +/** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ +export function valid(value: any, ...values: any[]): Schema; +export function valid(values: any[]): Schema; +export function only(value: any, ...values: any[]): Schema; +export function only(values: any[]): Schema; +export function equal(value: any, ...values: any[]): Schema; +export function equal(values: any[]): Schema; + +/** + * Blacklists a value + */ +export function invalid(value: any, ...values: any[]): Schema; +export function invalid(values: any[]): Schema; +export function disallow(value: any, ...values: any[]): Schema; +export function disallow(values: any[]): Schema; +export function not(value: any, ...values: any[]): Schema; +export function not(values: any[]): Schema; + +/** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ +export function required(): Schema; + +/** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ +export function optional(): Schema; + +/** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ +export function forbidden(): Schema; + +/** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ +export function strip(): Schema; + +/** + * Annotates the key + */ +export function description(desc: string): Schema; + +/** + * Annotates the key + */ +export function notes(notes: string): Schema; +export function notes(notes: string[]): Schema; + +/** + * Annotates the key + */ +export function tags(notes: string): Schema; +export function tags(notes: string[]): Schema; + +/** + * Attaches metadata to the key. + */ +export function meta(meta: object): Schema; + +/** + * Annotates the key with an example value, must be valid. + */ +export function example(value: any): Schema; + +/** + * Annotates the key with an unit name. + */ +export function unit(name: string): Schema; + +/** + * Overrides the global validate() options for the current key and any sub-key. + */ +export function options(options: ValidationOptions): Schema; + +/** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ +export function strict(isStrict?: boolean): Schema; + +/** + * Returns a new type that is the result of adding the rules of one type to another. + */ +export function concat(schema: T): T; + +/** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ +export function when(ref: string, options: WhenOptions): AlternativesSchema; +export function when(ref: Reference, options: WhenOptions): AlternativesSchema; + +/** + * Overrides the key name in error messages. + */ +export function label(name: string): Schema; + +/** + * Outputs the original untouched value instead of the casted value. + */ +export function raw(isRaw?: boolean): Schema; + +/** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ +export function empty(schema?: any): Schema; diff --git a/types/joi/v10/joi-tests.ts b/types/joi/v10/joi-tests.ts new file mode 100644 index 0000000000..226abb3a7f --- /dev/null +++ b/types/joi/v10/joi-tests.ts @@ -0,0 +1,1016 @@ +import Joi = require('joi'); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var x: any = null; +var value: any = null; +var num: number = 0; +var str: string = ''; +var bool: boolean = false; +var exp: RegExp = null; +var obj: object = null; +var date: Date = null; +var err: Error = null; +var func: Function = null; + +var anyArr: any[] = []; +var numArr: number[] = []; +var strArr: string[] = []; +var boolArr: boolean[] = []; +var expArr: RegExp[] = []; +var objArr: object[] = []; +var errArr: Error[] = []; +var funcArr: Function[] = []; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schema: Joi.Schema = null; +var schemaLike: Joi.SchemaLike = null; + +var anySchema: Joi.AnySchema = null; +var numSchema: Joi.NumberSchema = null; +var strSchema: Joi.StringSchema = null; +var arrSchema: Joi.ArraySchema = null; +var boolSchema: Joi.BooleanSchema = null; +var binSchema: Joi.BinarySchema = null; +var dateSchema: Joi.DateSchema = null; +var funcSchema: Joi.FunctionSchema = null; +var objSchema: Joi.ObjectSchema = null; +var altSchema: Joi.AlternativesSchema = null; + +var schemaArr: Joi.Schema[] = []; + +var ref: Joi.Reference = null; +var description: Joi.Description = null; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validOpts: Joi.ValidationOptions = null; + +validOpts = { abortEarly: bool }; +validOpts = { convert: bool }; +validOpts = { allowUnknown: bool }; +validOpts = { skipFunctions: bool }; +validOpts = { stripUnknown: bool }; +validOpts = { stripUnknown: { arrays: bool } }; +validOpts = { stripUnknown: { objects: bool } }; +validOpts = { stripUnknown: { arrays: bool, objects: bool } }; +validOpts = { presence: 'optional' || 'required' || 'forbidden' }; +validOpts = { context: obj }; +validOpts = { noDefaults: bool }; +validOpts = { + language: { + root: str, + key: str, + messages: { wrapArrays: bool }, + string: { base: str }, + number: { base: str }, + object: { + base: false, + children: { childRule: str } + }, + customType: { + customRule: str + } + } +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var renOpts: Joi.RenameOptions = null; + +renOpts = { alias: bool }; +renOpts = { multiple: bool }; +renOpts = { override: bool }; +renOpts = { ignoreUndefined: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var emailOpts: Joi.EmailOptions = null; + +emailOpts = { errorLevel: num }; +emailOpts = { errorLevel: bool }; +emailOpts = { tldWhitelist: strArr }; +emailOpts = { tldWhitelist: obj }; +emailOpts = { minDomainAtoms: num }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var ipOpts: Joi.IpOptions = null; + +ipOpts = { version: str }; +ipOpts = { version: strArr }; +ipOpts = { cidr: str }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var uriOpts: Joi.UriOptions = null; + +uriOpts = { scheme: str }; +uriOpts = { scheme: exp }; +uriOpts = { scheme: strArr }; +uriOpts = { scheme: expArr }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var whenOpts: Joi.WhenOptions = null; + +whenOpts = { is: x }; +whenOpts = { is: schema, then: schema }; +whenOpts = { is: schema, otherwise: schema }; +whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var refOpts: Joi.ReferenceOptions = null; + +refOpts = { separator: str }; +refOpts = { contextPrefix: str }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validErr: Joi.ValidationError = null; +var validErrItem: Joi.ValidationErrorItem; +var validErrFunc: Joi.ValidationErrorFunction; + +validErrItem = { + message: str, + type: str, + path: str +}; + +validErrItem = { + message: str, + type: str, + path: str, + options: validOpts, + context: obj +}; + +validErrFunc = errs => errs; +validErrFunc = errs => errs[0]; +validErrFunc = errs => 'Some error'; +validErrFunc = errs => err; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = anySchema; +schema = numSchema; +schema = strSchema; +schema = arrSchema; +schema = boolSchema; +schema = binSchema; +schema = dateSchema; +schema = funcSchema; +schema = objSchema; + +anySchema = anySchema; +anySchema = numSchema; +anySchema = strSchema; +anySchema = arrSchema; +anySchema = boolSchema; +anySchema = binSchema; +anySchema = dateSchema; +anySchema = funcSchema; +anySchema = objSchema; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schemaMap: Joi.SchemaMap = null; + +schemaMap = { + a: numSchema, + b: strSchema +}; +schemaMap = { + a: numSchema, + b: { + b1: strSchema, + b2: anySchema + } +}; +schemaMap = { + a: numSchema, + b: [ + { b1: strSchema }, + { b2: anySchema } + ], + c: arrSchema, + d: schemaLike +}; +schemaMap = { + a: 1, + b: { + b1: '1', + b2: 2 + }, + c: [ + { c1: true }, + { c2: null } + ] +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +anySchema = Joi.any(); + +namespace common { + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.only(x); + anySchema = anySchema.only(x, x); + anySchema = anySchema.only([x, x, x]); + anySchema = anySchema.equal(x); + anySchema = anySchema.equal(x, x); + anySchema = anySchema.equal([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + anySchema = anySchema.disallow(x); + anySchema = anySchema.disallow(x, x); + anySchema = anySchema.disallow([x, x, x]); + anySchema = anySchema.not(x); + anySchema = anySchema.not(x, x); + anySchema = anySchema.not([x, x, x]); + + anySchema = anySchema.default(); + anySchema = anySchema.default(x); + anySchema = anySchema.default(x, str); + + anySchema = anySchema.required(); + anySchema = anySchema.optional(); + anySchema = anySchema.forbidden(); + anySchema = anySchema.strip(); + + anySchema = anySchema.description(str); + anySchema = anySchema.notes(str); + anySchema = anySchema.notes(strArr); + anySchema = anySchema.tags(str); + anySchema = anySchema.tags(strArr); + + anySchema = anySchema.meta(obj); + anySchema = anySchema.example(obj); + anySchema = anySchema.unit(str); + + anySchema = anySchema.options(validOpts); + anySchema = anySchema.strict(); + anySchema = anySchema.strict(bool); + anySchema = anySchema.concat(x); + + altSchema = anySchema.when(str, whenOpts); + altSchema = anySchema.when(ref, whenOpts); + + anySchema = anySchema.label(str); + anySchema = anySchema.raw(); + anySchema = anySchema.raw(bool); + anySchema = anySchema.empty(); + anySchema = anySchema.empty(str); + anySchema = anySchema.empty(anySchema); + + anySchema = anySchema.error(err); + anySchema = anySchema.error(validErrFunc); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +arrSchema = Joi.array(); + +arrSchema = arrSchema.sparse(); +arrSchema = arrSchema.sparse(bool); +arrSchema = arrSchema.single(); +arrSchema = arrSchema.single(bool); +arrSchema = arrSchema.ordered(anySchema); +arrSchema = arrSchema.ordered(anySchema, numSchema, strSchema, arrSchema, boolSchema, binSchema, dateSchema, funcSchema, objSchema, schemaLike); +arrSchema = arrSchema.ordered(schemaMap); +arrSchema = arrSchema.ordered([schemaMap, schemaMap, schemaLike]); +arrSchema = arrSchema.min(num); +arrSchema = arrSchema.max(num); +arrSchema = arrSchema.length(num); +arrSchema = arrSchema.unique(); +arrSchema = arrSchema.unique((a, b) => a.test === b.test); +arrSchema = arrSchema.unique('customer.id'); + + +arrSchema = arrSchema.items(numSchema); +arrSchema = arrSchema.items(numSchema, strSchema, schemaLike); +arrSchema = arrSchema.items([numSchema, strSchema, schemaLike]); +arrSchema = arrSchema.items(schemaMap); +arrSchema = arrSchema.items(schemaMap, schemaMap, schemaLike); +arrSchema = arrSchema.items([schemaMap, schemaMap, schemaLike]); + +// - - - - - - - - + +namespace common_copy_paste { + // use search & replace from any + arrSchema = arrSchema.allow(x); + arrSchema = arrSchema.allow(x, x); + arrSchema = arrSchema.allow([x, x, x]); + arrSchema = arrSchema.valid(x); + arrSchema = arrSchema.valid(x, x); + arrSchema = arrSchema.valid([x, x, x]); + arrSchema = arrSchema.only(x); + arrSchema = arrSchema.only(x, x); + arrSchema = arrSchema.only([x, x, x]); + arrSchema = arrSchema.equal(x); + arrSchema = arrSchema.equal(x, x); + arrSchema = arrSchema.equal([x, x, x]); + arrSchema = arrSchema.invalid(x); + arrSchema = arrSchema.invalid(x, x); + arrSchema = arrSchema.invalid([x, x, x]); + arrSchema = arrSchema.disallow(x); + arrSchema = arrSchema.disallow(x, x); + arrSchema = arrSchema.disallow([x, x, x]); + arrSchema = arrSchema.not(x); + arrSchema = arrSchema.not(x, x); + arrSchema = arrSchema.not([x, x, x]); + + arrSchema = arrSchema.default(x); + + arrSchema = arrSchema.required(); + arrSchema = arrSchema.optional(); + arrSchema = arrSchema.forbidden(); + + arrSchema = arrSchema.description(str); + arrSchema = arrSchema.notes(str); + arrSchema = arrSchema.notes(strArr); + arrSchema = arrSchema.tags(str); + arrSchema = arrSchema.tags(strArr); + + arrSchema = arrSchema.meta(obj); + arrSchema = arrSchema.example(obj); + arrSchema = arrSchema.unit(str); + + arrSchema = arrSchema.options(validOpts); + arrSchema = arrSchema.strict(); + arrSchema = arrSchema.concat(x); + + altSchema = arrSchema.when(str, whenOpts); + altSchema = arrSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +boolSchema = Joi.bool(); +boolSchema = Joi.boolean(); + +namespace common_copy_paste { + boolSchema = boolSchema.allow(x); + boolSchema = boolSchema.allow(x, x); + boolSchema = boolSchema.allow([x, x, x]); + boolSchema = boolSchema.valid(x); + boolSchema = boolSchema.valid(x, x); + boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.only(x); + boolSchema = boolSchema.only(x, x); + boolSchema = boolSchema.only([x, x, x]); + boolSchema = boolSchema.equal(x); + boolSchema = boolSchema.equal(x, x); + boolSchema = boolSchema.equal([x, x, x]); + boolSchema = boolSchema.invalid(x); + boolSchema = boolSchema.invalid(x, x); + boolSchema = boolSchema.invalid([x, x, x]); + boolSchema = boolSchema.disallow(x); + boolSchema = boolSchema.disallow(x, x); + boolSchema = boolSchema.disallow([x, x, x]); + boolSchema = boolSchema.not(x); + boolSchema = boolSchema.not(x, x); + boolSchema = boolSchema.not([x, x, x]); + + boolSchema = boolSchema.default(x); + + boolSchema = boolSchema.required(); + boolSchema = boolSchema.optional(); + boolSchema = boolSchema.forbidden(); + + boolSchema = boolSchema.description(str); + boolSchema = boolSchema.notes(str); + boolSchema = boolSchema.notes(strArr); + boolSchema = boolSchema.tags(str); + boolSchema = boolSchema.tags(strArr); + + boolSchema = boolSchema.meta(obj); + boolSchema = boolSchema.example(obj); + boolSchema = boolSchema.unit(str); + + boolSchema = boolSchema.options(validOpts); + boolSchema = boolSchema.strict(); + boolSchema = boolSchema.concat(x); + + boolSchema = boolSchema.truthy(str); + boolSchema = boolSchema.truthy(num); + boolSchema = boolSchema.truthy(strArr); + boolSchema = boolSchema.truthy(numArr); + boolSchema = boolSchema.truthy(str, str); + boolSchema = boolSchema.truthy(strArr, str); + boolSchema = boolSchema.truthy(str, strArr); + boolSchema = boolSchema.truthy(strArr, strArr); + boolSchema = boolSchema.falsy(str); + boolSchema = boolSchema.falsy(num); + boolSchema = boolSchema.falsy(strArr); + boolSchema = boolSchema.falsy(numArr); + boolSchema = boolSchema.falsy(str, str); + boolSchema = boolSchema.falsy(strArr, str); + boolSchema = boolSchema.falsy(str, strArr); + boolSchema = boolSchema.falsy(strArr, strArr); + boolSchema = boolSchema.insensitive(bool); + + altSchema = boolSchema.when(str, whenOpts); + altSchema = boolSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +binSchema = Joi.binary(); + +binSchema = binSchema.encoding(str); +binSchema = binSchema.min(num); +binSchema = binSchema.max(num); +binSchema = binSchema.length(num); + +namespace common { + binSchema = binSchema.allow(x); + binSchema = binSchema.allow(x, x); + binSchema = binSchema.allow([x, x, x]); + binSchema = binSchema.valid(x); + binSchema = binSchema.valid(x, x); + binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.only(x); + binSchema = binSchema.only(x, x); + binSchema = binSchema.only([x, x, x]); + binSchema = binSchema.equal(x); + binSchema = binSchema.equal(x, x); + binSchema = binSchema.equal([x, x, x]); + binSchema = binSchema.invalid(x); + binSchema = binSchema.invalid(x, x); + binSchema = binSchema.invalid([x, x, x]); + binSchema = binSchema.disallow(x); + binSchema = binSchema.disallow(x, x); + binSchema = binSchema.disallow([x, x, x]); + binSchema = binSchema.not(x); + binSchema = binSchema.not(x, x); + binSchema = binSchema.not([x, x, x]); + + binSchema = binSchema.default(x); + + binSchema = binSchema.required(); + binSchema = binSchema.optional(); + binSchema = binSchema.forbidden(); + + binSchema = binSchema.description(str); + binSchema = binSchema.notes(str); + binSchema = binSchema.notes(strArr); + binSchema = binSchema.tags(str); + binSchema = binSchema.tags(strArr); + + binSchema = binSchema.meta(obj); + binSchema = binSchema.example(obj); + binSchema = binSchema.unit(str); + + binSchema = binSchema.options(validOpts); + binSchema = binSchema.strict(); + binSchema = binSchema.concat(x); + + altSchema = binSchema.when(str, whenOpts); + altSchema = binSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +dateSchema = Joi.date(); + +dateSchema = dateSchema.min(date); +dateSchema = dateSchema.max(date); + +dateSchema = dateSchema.min(str); +dateSchema = dateSchema.max(str); + +dateSchema = dateSchema.min(num); +dateSchema = dateSchema.max(num); + +dateSchema = dateSchema.min(ref); +dateSchema = dateSchema.max(ref); + +dateSchema = dateSchema.format(str); +dateSchema = dateSchema.format(strArr); + +dateSchema = dateSchema.iso(); + +dateSchema = dateSchema.timestamp(); +dateSchema = dateSchema.timestamp('javascript'); +dateSchema = dateSchema.timestamp('unix'); + +namespace common { + dateSchema = dateSchema.allow(x); + dateSchema = dateSchema.allow(x, x); + dateSchema = dateSchema.allow([x, x, x]); + dateSchema = dateSchema.valid(x); + dateSchema = dateSchema.valid(x, x); + dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.only(x); + dateSchema = dateSchema.only(x, x); + dateSchema = dateSchema.only([x, x, x]); + dateSchema = dateSchema.equal(x); + dateSchema = dateSchema.equal(x, x); + dateSchema = dateSchema.equal([x, x, x]); + dateSchema = dateSchema.invalid(x); + dateSchema = dateSchema.invalid(x, x); + dateSchema = dateSchema.invalid([x, x, x]); + dateSchema = dateSchema.disallow(x); + dateSchema = dateSchema.disallow(x, x); + dateSchema = dateSchema.disallow([x, x, x]); + dateSchema = dateSchema.not(x); + dateSchema = dateSchema.not(x, x); + dateSchema = dateSchema.not([x, x, x]); + + dateSchema = dateSchema.default(x); + + dateSchema = dateSchema.required(); + dateSchema = dateSchema.optional(); + dateSchema = dateSchema.forbidden(); + + dateSchema = dateSchema.description(str); + dateSchema = dateSchema.notes(str); + dateSchema = dateSchema.notes(strArr); + dateSchema = dateSchema.tags(str); + dateSchema = dateSchema.tags(strArr); + + dateSchema = dateSchema.meta(obj); + dateSchema = dateSchema.example(obj); + dateSchema = dateSchema.unit(str); + + dateSchema = dateSchema.options(validOpts); + dateSchema = dateSchema.strict(); + dateSchema = dateSchema.concat(x); + + altSchema = dateSchema.when(str, whenOpts); + altSchema = dateSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +funcSchema = Joi.func(); + +funcSchema = funcSchema.arity(num); +funcSchema = funcSchema.minArity(num); +funcSchema = funcSchema.maxArity(num); +funcSchema = funcSchema.ref(); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +numSchema = Joi.number(); + +numSchema = numSchema.min(num); +numSchema = numSchema.min(ref); +numSchema = numSchema.max(num); +numSchema = numSchema.max(ref); +numSchema = numSchema.greater(num); +numSchema = numSchema.greater(ref); +numSchema = numSchema.less(num); +numSchema = numSchema.less(ref); +numSchema = numSchema.integer(); +numSchema = numSchema.precision(num); +numSchema = numSchema.multiple(num); +numSchema = numSchema.positive(); +numSchema = numSchema.negative(); + +namespace common { + numSchema = numSchema.allow(x); + numSchema = numSchema.allow(x, x); + numSchema = numSchema.allow([x, x, x]); + numSchema = numSchema.valid(x); + numSchema = numSchema.valid(x, x); + numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.only(x); + numSchema = numSchema.only(x, x); + numSchema = numSchema.only([x, x, x]); + numSchema = numSchema.equal(x); + numSchema = numSchema.equal(x, x); + numSchema = numSchema.equal([x, x, x]); + numSchema = numSchema.invalid(x); + numSchema = numSchema.invalid(x, x); + numSchema = numSchema.invalid([x, x, x]); + numSchema = numSchema.disallow(x); + numSchema = numSchema.disallow(x, x); + numSchema = numSchema.disallow([x, x, x]); + numSchema = numSchema.not(x); + numSchema = numSchema.not(x, x); + numSchema = numSchema.not([x, x, x]); + + numSchema = numSchema.default(x); + + numSchema = numSchema.required(); + numSchema = numSchema.optional(); + numSchema = numSchema.forbidden(); + + numSchema = numSchema.description(str); + numSchema = numSchema.notes(str); + numSchema = numSchema.notes(strArr); + numSchema = numSchema.tags(str); + numSchema = numSchema.tags(strArr); + + numSchema = numSchema.meta(obj); + numSchema = numSchema.example(obj); + numSchema = numSchema.unit(str); + + numSchema = numSchema.options(validOpts); + numSchema = numSchema.strict(); + numSchema = numSchema.concat(x); + + altSchema = numSchema.when(str, whenOpts); + altSchema = numSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +objSchema = Joi.object(); +objSchema = Joi.object(schemaMap); + +objSchema = objSchema.keys(); +objSchema = objSchema.keys(schemaMap); + +objSchema = objSchema.min(num); +objSchema = objSchema.max(num); +objSchema = objSchema.length(num); + +objSchema = objSchema.pattern(exp, schema); +objSchema = objSchema.pattern(exp, schemaLike); + +objSchema = objSchema.and(str); +objSchema = objSchema.and(str, str); +objSchema = objSchema.and(str, str, str); +objSchema = objSchema.and(strArr); + +objSchema = objSchema.nand(str); +objSchema = objSchema.nand(str, str); +objSchema = objSchema.nand(str, str, str); +objSchema = objSchema.nand(strArr); + +objSchema = objSchema.or(str); +objSchema = objSchema.or(str, str); +objSchema = objSchema.or(str, str, str); +objSchema = objSchema.or(strArr); + +objSchema = objSchema.xor(str); +objSchema = objSchema.xor(str, str); +objSchema = objSchema.xor(str, str, str); +objSchema = objSchema.xor(strArr); + +objSchema = objSchema.with(str, str); +objSchema = objSchema.with(str, strArr); + +objSchema = objSchema.without(str, str); +objSchema = objSchema.without(str, strArr); + +objSchema = objSchema.rename(str, str); +objSchema = objSchema.rename(str, str, renOpts); + +objSchema = objSchema.assert(str, schema); +objSchema = objSchema.assert(str, schema, str); +objSchema = objSchema.assert(ref, schema); +objSchema = objSchema.assert(ref, schema, str); + +objSchema = objSchema.unknown(); +objSchema = objSchema.unknown(bool); + +objSchema = objSchema.type(func); +objSchema = objSchema.type(func, str); + +objSchema = objSchema.requiredKeys(str); +objSchema = objSchema.requiredKeys(str, str); +objSchema = objSchema.requiredKeys(strArr); + +objSchema = objSchema.optionalKeys(str); +objSchema = objSchema.optionalKeys(str, str); +objSchema = objSchema.optionalKeys(strArr); + +namespace common { + objSchema = objSchema.allow(x); + objSchema = objSchema.allow(x, x); + objSchema = objSchema.allow([x, x, x]); + objSchema = objSchema.valid(x); + objSchema = objSchema.valid(x, x); + objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.only(x); + objSchema = objSchema.only(x, x); + objSchema = objSchema.only([x, x, x]); + objSchema = objSchema.equal(x); + objSchema = objSchema.equal(x, x); + objSchema = objSchema.equal([x, x, x]); + objSchema = objSchema.invalid(x); + objSchema = objSchema.invalid(x, x); + objSchema = objSchema.invalid([x, x, x]); + objSchema = objSchema.disallow(x); + objSchema = objSchema.disallow(x, x); + objSchema = objSchema.disallow([x, x, x]); + objSchema = objSchema.not(x); + objSchema = objSchema.not(x, x); + objSchema = objSchema.not([x, x, x]); + + objSchema = objSchema.default(x); + + objSchema = objSchema.required(); + objSchema = objSchema.optional(); + objSchema = objSchema.forbidden(); + + objSchema = objSchema.description(str); + objSchema = objSchema.notes(str); + objSchema = objSchema.notes(strArr); + objSchema = objSchema.tags(str); + objSchema = objSchema.tags(strArr); + + objSchema = objSchema.meta(obj); + objSchema = objSchema.example(obj); + objSchema = objSchema.unit(str); + + objSchema = objSchema.options(validOpts); + objSchema = objSchema.strict(); + objSchema = objSchema.concat(x); + + altSchema = objSchema.when(str, whenOpts); + altSchema = objSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +strSchema = Joi.string(); + +strSchema = strSchema.insensitive(); +strSchema = strSchema.min(num); +strSchema = strSchema.min(num, str); +strSchema = strSchema.min(ref); +strSchema = strSchema.min(ref, str); +strSchema = strSchema.max(num); +strSchema = strSchema.max(num, str); +strSchema = strSchema.max(ref); +strSchema = strSchema.max(ref, str); +strSchema = strSchema.creditCard(); +strSchema = strSchema.length(num); +strSchema = strSchema.length(num, str); +strSchema = strSchema.length(ref); +strSchema = strSchema.length(ref, str); +strSchema = strSchema.regex(exp); +strSchema = strSchema.regex(exp, str); +strSchema = strSchema.replace(exp, str); +strSchema = strSchema.replace(str, str); +strSchema = strSchema.alphanum(); +strSchema = strSchema.token(); +strSchema = strSchema.email(); +strSchema = strSchema.email(emailOpts); +strSchema = strSchema.ip(); +strSchema = strSchema.ip(ipOpts); +strSchema = strSchema.uri(); +strSchema = strSchema.uri(uriOpts); +strSchema = strSchema.guid(); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: 'uuidv4' }); +strSchema = strSchema.hex(); +strSchema = strSchema.hostname(); +strSchema = strSchema.isoDate(); +strSchema = strSchema.lowercase(); +strSchema = strSchema.uppercase(); +strSchema = strSchema.trim(); +strSchema = strSchema.truncate(); +strSchema = strSchema.truncate(false); +strSchema = strSchema.normalize(); +strSchema = strSchema.normalize('NFKC'); + +namespace common { + strSchema = strSchema.allow(x); + strSchema = strSchema.allow(x, x); + strSchema = strSchema.allow([x, x, x]); + strSchema = strSchema.valid(x); + strSchema = strSchema.valid(x, x); + strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.only(x); + strSchema = strSchema.only(x, x); + strSchema = strSchema.only([x, x, x]); + strSchema = strSchema.equal(x); + strSchema = strSchema.equal(x, x); + strSchema = strSchema.equal([x, x, x]); + strSchema = strSchema.invalid(x); + strSchema = strSchema.invalid(x, x); + strSchema = strSchema.invalid([x, x, x]); + strSchema = strSchema.disallow(x); + strSchema = strSchema.disallow(x, x); + strSchema = strSchema.disallow([x, x, x]); + strSchema = strSchema.not(x); + strSchema = strSchema.not(x, x); + strSchema = strSchema.not([x, x, x]); + + strSchema = strSchema.default(x); + + strSchema = strSchema.required(); + strSchema = strSchema.optional(); + strSchema = strSchema.forbidden(); + + strSchema = strSchema.description(str); + strSchema = strSchema.notes(str); + strSchema = strSchema.notes(strArr); + strSchema = strSchema.tags(str); + strSchema = strSchema.tags(strArr); + + strSchema = strSchema.meta(obj); + strSchema = strSchema.example(obj); + strSchema = strSchema.unit(str); + + strSchema = strSchema.options(validOpts); + strSchema = strSchema.strict(); + strSchema = strSchema.concat(x); + + altSchema = strSchema.when(str, whenOpts); + altSchema = strSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.alternatives(); +schema = Joi.alternatives().try(schemaArr); +schema = Joi.alternatives().try(schema, schema); + +schema = Joi.alternatives(schemaArr); +schema = Joi.alternatives(schema, anySchema, boolSchema); + +schema = Joi.alt(); +schema = Joi.alt().try(schemaArr); +schema = Joi.alt().try(schema, schema); + +schema = Joi.alt(schemaArr); +schema = Joi.alt(schema, anySchema, boolSchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.lazy(() => schema) + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +namespace validate_tests { + { + Joi.validate(value, obj); + Joi.validate(value, schema); + Joi.validate(value, schema, validOpts); + Joi.validate(value, schema, validOpts, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; + }); + Joi.validate(value, schema, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; + }); + // variant + Joi.validate(num, schema, validOpts, (err, value) => { + num = value; + }); + + // plain opts + Joi.validate(value, {}); + } + + { + let value = { username: 'example', password: 'example' }; + let schema = Joi.object().keys({ + username: Joi.string().max(255).required(), + password: Joi.string().regex(/^[a-zA-Z0-9]{3,255}$/).required(), + }); + let returnValue: Joi.ValidationResult; + + returnValue = schema.validate(value); + value = schema.validate(value, (err, value) => value); + + returnValue = Joi.validate(value, schema); + returnValue = Joi.validate(value, obj); + value = Joi.validate(value, obj, (err, value) => value); + value = Joi.validate(value, schema, (err, value) => value); + + returnValue = Joi.validate(value, schema, validOpts); + returnValue = Joi.validate(value, obj, validOpts); + value = Joi.validate(value, obj, validOpts, (err, value) => value); + value = Joi.validate(value, schema, validOpts, (err, value) => value); + + returnValue = schema.validate(value); + returnValue = schema.validate(value, validOpts); + value = schema.validate(value, (err, value) => value); + value = schema.validate(value, validOpts, (err, value) => value); + } +} + + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.compile(obj); +schema = Joi.compile(schemaMap); + +Joi.assert(obj, schema); +Joi.assert(obj, schema, str); +Joi.assert(obj, schema, err); +Joi.assert(obj, schemaLike); + +Joi.attempt(obj, schema); +Joi.attempt(obj, schema, str); +Joi.attempt(obj, schema, err); +Joi.attempt(obj, schemaLike); + +ref = Joi.ref(str, refOpts); +ref = Joi.ref(str); + +Joi.isRef(ref); + +description = Joi.describe(schema); +description = schema.describe(); + +schema = Joi.reach(objSchema, ''); + +const Joi2 = Joi.extend({ name: '', base: schema }); + +const Joi3 = Joi.extend({ + base: Joi.string(), + name: 'string', + language: { + asd: 'must be exactly asd(f)', + }, + pre(value, state, options) { + return value; + }, + describe(description) { + return description; + }, + rules: [ + { + name: 'asd', + params: { + allowF: Joi.boolean().default(false), + }, + setup(params) { + const fIsAllowed = params.allowF; + }, + validate(params, value, state, options) { + if (value === 'asd' || params.allowF && value === 'asdf') { + return value; + } + return this.createError('asd', { v: value }, state, options); + }, + }, + ], +}); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); diff --git a/types/joi/v10/tsconfig.json b/types/joi/v10/tsconfig.json new file mode 100644 index 0000000000..1bd530aff0 --- /dev/null +++ b/types/joi/v10/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "joi": [ + "joi/v10" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "joi-tests.ts" + ] +} diff --git a/types/leaflet.polylinemeasure/index.d.ts b/types/leaflet.polylinemeasure/index.d.ts new file mode 100644 index 0000000000..ea647b1266 --- /dev/null +++ b/types/leaflet.polylinemeasure/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for leaflet.polylinemeasure 1.0 +// Project: https://github.com/ppete2/Leaflet.PolylineMeasure#readme +// Definitions by: Rinat Sultanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as L from 'leaflet'; + +declare module 'leaflet' { + namespace Control { + interface PolylineMeasure extends Control { + new (options?: PolylineMeasureOptions): any; + } + + interface PolylineMeasureOptions { + position?: string; + unit?: string; + measureControlTitleOn?: string; + measureControlTitleOff?: string; + measureControlLabel?: string; + measureControlClasses?: any[]; + backgroundColor?: string; + cursor?: string; + clearMeasurementsOnStop?: boolean; + showMeasurementsClearControl?: boolean; + clearControlTitle?: string; + clearControlLabel?: string; + clearControlClasses?: any[]; + showUnitControl?: boolean; + tempLine?: any; + fixedLine?: any; + startCircle?: any; + intermedCircle?: any; + currentCircle?: any; + endCircle?: any; + } + } + + namespace control { + function polylineMeasure(options?: Control.PolylineMeasureOptions): Control.PolylineMeasure; + } +} diff --git a/types/leaflet.polylinemeasure/leaflet.polylinemeasure-tests.ts b/types/leaflet.polylinemeasure/leaflet.polylinemeasure-tests.ts new file mode 100644 index 0000000000..c659a77b1c --- /dev/null +++ b/types/leaflet.polylinemeasure/leaflet.polylinemeasure-tests.ts @@ -0,0 +1,11 @@ +import * as L from 'leaflet'; +import 'leaflet.polylinemeasure'; + +const map = L.map('map', {center: L.latLng(43.24209, 76.87743), zoom: 15}); + +L.tileLayer("http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", { + subdomains: ['a', 'b', 'c'], + attribution: '© OpenStreetMap' +}).addTo(map); + +L.control.polylineMeasure().addTo(map); diff --git a/types/leaflet.polylinemeasure/tsconfig.json b/types/leaflet.polylinemeasure/tsconfig.json new file mode 100644 index 0000000000..b1db5e086d --- /dev/null +++ b/types/leaflet.polylinemeasure/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "DOM" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "leaflet.polylinemeasure-tests.ts" + ] +} diff --git a/types/leaflet.polylinemeasure/tslint.json b/types/leaflet.polylinemeasure/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/leaflet.polylinemeasure/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/notyf/index.d.ts b/types/notyf/index.d.ts new file mode 100644 index 0000000000..25607add44 --- /dev/null +++ b/types/notyf/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for notyf 2.0 +// Project: https://github.com/caroso1222/notyf +// Definitions by: Pavel Gurov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + delay?: number; + alertIcon?: string; + confirmIcon?: string; +} + +declare class Notyf { + constructor(options?: Options); + + alert(text: string): void; + confirm(text: string): void; +} +export = Notyf; diff --git a/types/notyf/notyf-tests.ts b/types/notyf/notyf-tests.ts new file mode 100644 index 0000000000..add8338465 --- /dev/null +++ b/types/notyf/notyf-tests.ts @@ -0,0 +1,11 @@ +import Notyf = require("notyf"); + +const options = { + delay: 1000, + alertIcon: 'fa fa-bell', + confirmIcon: 'fa fa-exclamation' +}; + +const notyf = new Notyf(options); +notyf.alert('Danger!'); +notyf.confirm('Success!'); diff --git a/types/notyf/tsconfig.json b/types/notyf/tsconfig.json new file mode 100644 index 0000000000..9cf78d162a --- /dev/null +++ b/types/notyf/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "notyf-tests.ts" + ] +} diff --git a/types/notyf/tslint.json b/types/notyf/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/notyf/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts new file mode 100644 index 0000000000..488ad668d9 --- /dev/null +++ b/types/pubnub/index.d.ts @@ -0,0 +1,183 @@ +// Type definitions for pubnub 4.0 +// Project: https://github.com/pubnub/javascript +// Definitions by: bitbankinc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration + +declare class Pubnub { + constructor(config: Pubnub.PubnubConfig); + + setAuthKey(authKey: string): void; + + setFilterExpression(filterExpression: string): void; + + getFilterExpression(): string; + + publish( + params: Pubnub.PublishParameters, + callback: (status: any, response: Pubnub.PublishResponse) => void + ): void; + + publish( + params: Pubnub.PublishParameters + ): Promise; + + fire( + params: Pubnub.FireParameters, + callback: (status: any, response: Pubnub.PublishResponse) => void + ): void; + + fire( + params: Pubnub.FireParameters + ): Promise; + + subscribe(params: Pubnub.SubscribeParameters): void; + + unsubscribe(params: Pubnub.UnsubscribeParameters): void; + + unsubscribeAll(): void; + + addListener(params: Pubnub.ListenerParameters): void; + + removeListener(params: Pubnub.ListenerParameters): void; + + hereNow( + params: Pubnub.HereNowParameters, + callback: (status: any, response: Pubnub.HereNowResponse) => void + ): void; + + hereNow( + params: Pubnub.HereNowParameters + ): Promise; + + whereNow( + params: {uuid: string}, + callback: (status: Pubnub.WhereNowStatus, response: Pubnub.WhereNowResponse) => void + ): void; +} + +declare namespace Pubnub { + interface PubnubConfig { + subscribeKey: string; + publishKey?: string; + cipherKey?: string; + authKey?: string; + logVerbosity?: boolean; + uuid?: string; + ssl?: boolean; + origin?: string; + presenceTimeout?: number; + heartbeatInterval?: number; + restore?: boolean; + keepAlive?: boolean; + keepAliveSettings?: { + keepAliveMsecs?: number; + freeSocketKeepAliveTimeout?: number; + timeout?: number; + maxSockets?: number; + maxFreeSockets?: number; + }; + suppressLeaveEvents?: boolean; + secretKey?: string; + } + + interface PubnubData { + actualChannel: string; + channel: string; + message: any; + } + + interface StatusEvent { + category: string; + operation: string; + affectedChannels: string[]; + subscribedChannels: string[]; + affectedChannelGroups: string[]; + lastTimetoken: number | string; + currentTimetoken: number | string; + } + + // publish + interface PublishParameters { + message: any; + channel: string; + storeInHistory?: boolean; + sendByPost?: boolean; + meta?: any; + ttl?: number; + } + + interface PublishResponse { + timetoken: number; + } + + // fire + interface FireParameters { + message: any; + channel: string; + sendByPost?: boolean; + meta?: any; + } + + // subscribe + interface SubscribeParameters { + channels?: string[]; + channelGroups?: string[]; + withPresence?: boolean; + timetoken?: number; + } + + // unsubscribe + interface UnsubscribeParameters { + channels?: string[]; + channelGroups?: string[]; + } + + // addListener + interface ListenerParameters { + status?: (statusEvent: StatusEvent) => void; + message?: (data: PubnubData) => void; + presence?: (presenceEvent: any) => void; + } + + // hereNow + interface HereNowParameters { + channels?: string[]; + channelGroups?: string[]; + includeUUIDs?: boolean; + includeState?: boolean; + } + + interface HereNowResponse { + totalChannels: number; + totalOccupancy: number; + channels: {[channel: string]: any}; + } + + // whereNow + interface WhereNowStatus { + error: boolean; + operation: string; + statusCode: number; + } + + interface WhereNowResponse { + channels: string[]; + } + + // setState + interface SetStateParameters { + channels?: string[]; + channelGroups?: string[]; + state?: any; + } + + // getState + interface GetStateParameters { + uuid?: string; + channels?: string[]; + channelGroups?: string[]; + } +} + +export default Pubnub; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts new file mode 100644 index 0000000000..291fc035fe --- /dev/null +++ b/types/pubnub/pubnub-tests.ts @@ -0,0 +1,51 @@ +import Pubnub from 'pubnub'; + +const console = { + log: (params: any) => {} +}; + +const config: Pubnub.PubnubConfig = { + subscribeKey: '', + publishKey: '', + secretKey: '', + ssl: true, + authKey: '' +}; + +const pubnub = new Pubnub(config); + +pubnub.setAuthKey('myAuthenKey'); + +// publish with callback +pubnub.publish({channel: 'channel-1', message: {data: 1}}, (status, response) => { + /* + * Do something + */ + console.log(response.timetoken); +}); + +// publish promise +pubnub.publish({channel: 'channel-1', message: {data: 1}}).then((response) => { + /* + * Do something + */ + console.log(response.timetoken); +}); + +pubnub.subscribe({channels: ['channel-1']}); + +pubnub.addListener({ + status: statusEvent => { + if (statusEvent.category === "PNConnectedCategory") { + console.log(statusEvent.category); + } + }, + message: message => { + // handle message + }, + presence: presenceEvent => { + // handle presence + } +}); + +pubnub.unsubscribe({channels: ['channel-1']}); diff --git a/types/pubnub/tsconfig.json b/types/pubnub/tsconfig.json new file mode 100644 index 0000000000..fab1a92335 --- /dev/null +++ b/types/pubnub/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pubnub-tests.ts" + ] +} diff --git a/types/pubnub/tslint.json b/types/pubnub/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pubnub/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 151f69d70f..8479c100a1 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -96,6 +96,25 @@ export interface Cookie { sameSite: "Strict" | "Lax"; } +export interface DeleteCookie { + name: string; + url?: string; + domain?: string; + path?: string; + secure?: boolean; +} + +export interface SetCookie { + name: string; + value: string; + domain?: string; + path?: string; + expires?: number; + httpOnly?: boolean; + secure?: boolean; + sameSite?: "Strict" | "Lax"; +} + export interface Viewport { width: number; height: number; @@ -359,15 +378,7 @@ export interface Page extends FrameBase { close(): Promise; content(): Promise; cookies(...urls: string[]): Promise; - deleteCookie( - ...cookies: Array<{ - name: string; - url?: string; - domain?: string; - path?: string; - secure?: boolean; - }> - ): Promise; + deleteCookie(...cookies: DeleteCookie[]): Promise; emulate(options: Partial): Promise; emulateMedia(mediaType: 'screen' | 'print' | null): Promise; evaluateHandle( @@ -398,7 +409,7 @@ export interface Page extends FrameBase { screenshot(options?: ScreenshotOptions): Promise; select(selector: string, ...values: string[]): Promise; setContent(html: string): Promise; - setCookie(...cookies: Cookie[]): Promise; + setCookie(...cookies: SetCookie[]): Promise; setExtraHTTPHeaders(headers: Headers): Promise; setJavaScriptEnabled(enabled: boolean): Promise; setRequestInterceptionEnabled(value: boolean): Promise; diff --git a/types/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts index 19c9274cae..e124d12f5f 100644 --- a/types/qlik-engineapi/index.d.ts +++ b/types/qlik-engineapi/index.d.ts @@ -4060,7 +4060,7 @@ declare namespace EngineAPI { /** * Identifier and type of the dimension. */ - qDim: INxLibraryMeasureDef; + qDim: INxLibraryDimensionDef; /** * Cardinal and tags related to the dimension. @@ -4106,7 +4106,7 @@ declare namespace EngineAPI { * * @returns - A promise GenericDimension. */ - getDimension(): Promise; + getDimension(): Promise; /** * Returns the type and identifier of the object. @@ -6087,7 +6087,7 @@ declare namespace EngineAPI { * @returns - Information about the measure. * >> This parameter is mandatory. */ - getMeasure(): Promise; + getMeasure(): Promise; /** * Shows the properties of an object. @@ -6879,12 +6879,6 @@ declare namespace EngineAPI { qSignature: string; } - interface IQOptions { - qBookmarkId: string; - - qExpires: number; - } - interface IQDownloadInfo { /** * URL of the generated QVF @@ -7104,14 +7098,6 @@ declare namespace EngineAPI { */ exportApp(qTargetPath: string, qSrcAppId: string, qIds: string[]): Promise; - /** - * Reduce an app in the memory to the current selection of a specified bookmark - * and make it as http download available. - * @params - optional qOptions - * @returns - A Promise of qDownloadInfo - */ - exportReducedData(qOptions?: IQOptions): Promise; - /** * Returns the handle of the current app. * diff --git a/types/react-calendar-heatmap/index.d.ts b/types/react-calendar-heatmap/index.d.ts new file mode 100644 index 0000000000..f15ff887ca --- /dev/null +++ b/types/react-calendar-heatmap/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for react-calendar-heatmap 1.6 +// Project: https://github.com/patientslikeme/react-calendar-heatmap +// Definitions by: Keisuke Kan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from 'react'; + +export interface Props { + classForValue?: (value: any) => any; + endDate?: string | number | Date; + gutterSize?: number; + horizontal?: boolean; + monthLabels?: string[]; + numDays?: number; + onClick?: (value: any) => void; + onMouseLeave?: (e: any, value: any) => void; + onMouseOver?: (e: any, value: any) => void; + showMonthLabels?: boolean; + showOutOfRangeDays?: boolean; + showWeekdayLabels?: boolean; + startDate?: string | number | Date; + titleForValue?: (value: any) => any; + tooltipDataAttrs?: object; + transformDayElement?: (rect: any, value: any, index: number) => any; + values: any[]; + weekdayLabels?: string[]; +} + +export default class ReactCalendarHeatmap extends React.Component {} diff --git a/types/react-calendar-heatmap/react-calendar-heatmap-tests.tsx b/types/react-calendar-heatmap/react-calendar-heatmap-tests.tsx new file mode 100644 index 0000000000..4e807ddfcd --- /dev/null +++ b/types/react-calendar-heatmap/react-calendar-heatmap-tests.tsx @@ -0,0 +1,16 @@ +import * as React from 'react'; +import CalendarHeatmap from 'react-calendar-heatmap'; + +export default function() { + return ( + + ); +} diff --git a/types/react-calendar-heatmap/tsconfig.json b/types/react-calendar-heatmap/tsconfig.json new file mode 100644 index 0000000000..f605aa4478 --- /dev/null +++ b/types/react-calendar-heatmap/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-calendar-heatmap-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-calendar-heatmap/tslint.json b/types/react-calendar-heatmap/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-calendar-heatmap/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-ga/index.d.ts b/types/react-ga/index.d.ts index 56d9715ed1..d1d7eccc53 100644 --- a/types/react-ga/index.d.ts +++ b/types/react-ga/index.d.ts @@ -25,6 +25,8 @@ export interface GaOptions { legacyHistoryImport?: boolean; allowLinker?: boolean; userId?: string; + language?: string; + hostName?: string; } export interface InitializeOptions { diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index 91eea3851c..86f4bf0bd8 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -68,8 +68,8 @@ export { Pagination, PaginationProps } from ' export { PaginationItem, PaginationItemProps } from './lib/PaginationItem'; export { PaginationLink, PaginationLinkProps } from './lib/PaginationLink'; export { Popover, PopoverProps } from './lib/Popover'; -export { PopoverContent, PopoverContentProps } from './lib/PopoverContent'; -export { PopoverTitle, PopoverTitleProps } from './lib/PopoverTitle'; +export { PopoverBody, PopoverBodyProps } from './lib/PopoverBody'; +export { PopoverHeader, PopoverHeaderProps } from './lib/PopoverHeader'; export { Progress, ProgressProps } from './lib/Progress'; export { Row, RowProps } from './lib/Row'; export { TabContent, TabContentProps } from './lib/TabContent'; diff --git a/types/reactstrap/lib/PopoverBody.d.ts b/types/reactstrap/lib/PopoverBody.d.ts new file mode 100644 index 0000000000..de2d61f5e2 --- /dev/null +++ b/types/reactstrap/lib/PopoverBody.d.ts @@ -0,0 +1,10 @@ +import { CSSModule } from '../index'; + +export interface PopoverBodyProps { + tag?: React.ReactType; + className?: string; + cssModule?: CSSModule; +} + +export const PopoverBody: React.StatelessComponent; +export default PopoverBody; diff --git a/types/reactstrap/lib/PopoverContent.d.ts b/types/reactstrap/lib/PopoverContent.d.ts deleted file mode 100644 index ea72f4dfb4..0000000000 --- a/types/reactstrap/lib/PopoverContent.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { CSSModule } from '../index'; - -export interface PopoverContentProps { - tag?: React.ReactType; - className?: string; - cssModule?: CSSModule; -} - -export const PopoverContent: React.StatelessComponent; -export default PopoverContent; diff --git a/types/reactstrap/lib/PopoverHeader.d.ts b/types/reactstrap/lib/PopoverHeader.d.ts new file mode 100644 index 0000000000..7f38988391 --- /dev/null +++ b/types/reactstrap/lib/PopoverHeader.d.ts @@ -0,0 +1,10 @@ +import { CSSModule } from '../index'; + +export interface PopoverHeaderProps { + tag?: React.ReactType; + className?: string; + cssModule?: CSSModule; +} + +export const PopoverHeader: React.StatelessComponent; +export default PopoverHeader; diff --git a/types/reactstrap/lib/PopoverTitle.d.ts b/types/reactstrap/lib/PopoverTitle.d.ts deleted file mode 100644 index 9711058424..0000000000 --- a/types/reactstrap/lib/PopoverTitle.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { CSSModule } from '../index'; - -export interface PopoverTitleProps { - tag?: React.ReactType; - className?: string; - cssModule?: CSSModule; -} - -export const PopoverTitle: React.StatelessComponent; -export default PopoverTitle; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 4886d712eb..352fbe8ac3 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -62,8 +62,8 @@ import { PaginationItem, PaginationLink, Popover, - PopoverContent, - PopoverTitle, + PopoverBody, + PopoverHeader, Progress, TabPane, UncontrolledButtonDropdown, @@ -2480,8 +2480,8 @@ class Example85 extends React.Component { Launch Popover - Popover Title - Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. + Popover Title + Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. ); @@ -2511,8 +2511,8 @@ class PopoverItem extends React.Component { {this.props.item.text} - Popover Title - Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. + Popover Title + Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. ); diff --git a/types/resourcejs/index.d.ts b/types/resourcejs/index.d.ts new file mode 100644 index 0000000000..bb4bffa197 --- /dev/null +++ b/types/resourcejs/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for resourcejs 1.9 +// Project: https://github.com/travist/resourcejs +// Definitions by: Shaun Luttin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import express = require("express"); +import mongoose = require("mongoose"); + +export = resourcejs; + +declare function resourcejs( + app: express.Application, + route: string, + modelName: string, + model: mongoose.Model): resourcejs.ResourceEndpoint; + +declare namespace resourcejs { + type HttpHandler = (req: Request, res: Response, next: express.NextFunction) => void; + + type MethodBuild = (options?: T) => ResourceEndpoint; + + interface RestOptions extends HttpMethodOptions { + beforePut?: HttpHandler; + beforePatch?: HttpHandler; + beforePost?: HttpHandler; + beforeIndex?: HttpHandler; + beforeGet?: HttpHandler; + afterPut?: HttpHandler; + afterPatch?: HttpHandler; + afterPost?: HttpHandler; + afterIndex?: HttpHandler; + afterGet?: HttpHandler; + } + + interface VirtualOptions extends HttpMethodOptions { + path?: string; + } + + interface HttpMethodOptions { + before?: HttpHandler; + after?: HttpHandler; + } + + /** + * We manually generated this interface by looking an resource like this: + * const resource = Resource(app, route, name, model); + * console.log(resource); + */ + interface ResourceEndpoint { + model: mongoose.Model; + modelName: string; + name: string; + route: string; + methods: string[]; + __swagger: any; + register: ( + app: express.Application, + method: string, + path: string, + callback: (...args: any[]) => any, + last: (...args: any[]) => any, + options: object) => any; + + respond: HttpHandler; + setResponse: HttpHandler; + getMethodOptions: (method: string, options: object) => object; + rest: MethodBuild; + getParamQuery: (req: Request, name: string) => any; + getFindQuery: (req: Request) => object; + index: MethodBuild; + get: MethodBuild; + virtual: MethodBuild; + post: MethodBuild; + put: MethodBuild; + patch: MethodBuild; + delete: MethodBuild; + swagger: MethodBuild; + } + + interface Request extends express.Request { + skipResource: boolean; + noResponse: boolean; + query: any; + countQuery: any; + modelQuery: any; + skipDelete: boolean; + } + + interface Response extends express.Response { + resource: Resource; + } + + interface Resource { + status: number; + error: Error; + item: mongoose.Document | mongoose.Document[]; + } + + interface Error { + message: string; + path: string; + name: string; + errors: Error[]; + } +} diff --git a/types/resourcejs/resourcejs-tests.ts b/types/resourcejs/resourcejs-tests.ts new file mode 100644 index 0000000000..b3d2604933 --- /dev/null +++ b/types/resourcejs/resourcejs-tests.ts @@ -0,0 +1,19 @@ +import express = require("express"); +import resourcejs = require("resourcejs"); +import mongoose = require("mongoose"); + +const app = express(); +const route = "the-route"; +const resourceName = "the-resource-name"; + +const schema = new mongoose.Schema({}); +const model = mongoose.model(resourceName, schema); + +resourcejs(app, route, resourceName, model) + .get() + .post() + .delete() + .put() + .patch() + .index() + .rest(); diff --git a/types/resourcejs/tsconfig.json b/types/resourcejs/tsconfig.json new file mode 100644 index 0000000000..ca71c00a1a --- /dev/null +++ b/types/resourcejs/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "resourcejs-tests.ts" + ] +} diff --git a/types/resourcejs/tslint.json b/types/resourcejs/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/resourcejs/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/swig-email-templates/index.d.ts b/types/swig-email-templates/index.d.ts index 26b5944053..8297b022b6 100644 --- a/types/swig-email-templates/index.d.ts +++ b/types/swig-email-templates/index.d.ts @@ -1,20 +1,30 @@ -// Type definitions for swig-email-templates +// Type definitions for swig-email-templates 5.0 // Project: https://github.com/andrewrk/swig-email-templates // Definitions by: Adam Babcock +// Satana Charuwichitratana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 -/// +/// import swig = require('swig'); -interface SwigRender { - (file: string, context: T, callback: (err: any, html: string, text: string) => any): any; -} +type SwigRender = (file: string, context: T, callback: (err: any, html: string, text: string) => any) => any; interface SwigEmailTemplatesOptions extends swig.SwigOptions { root?: string; + juice?: any; + rewriteUrl?: (href: string) => string; + rewrite?: ($: JQueryStatic) => void; } -declare function init(options: SwigEmailTemplatesOptions, cb: (err: any, render: SwigRender) => any): any; -export = init; +declare class EmailTemplates { + constructor(options?: SwigEmailTemplatesOptions); + generateText(templatePath: string, context: any, html: string, cb: (error: any, text: string | null) => void): void; + generateSubject(templatePath: string, context: any, cb: (error: any, text: string | null) => void): void; + rewriteUrls($: JQueryStatic, rewrite: (href: string) => void): void; + render(templatePath: string, context: any, cb: (error: any, inlinedHTML?: string, text?: string, subject?: string) => void): void; +} + +export = EmailTemplates; diff --git a/types/swig-email-templates/swig-email-templates-tests.ts b/types/swig-email-templates/swig-email-templates-tests.ts index de396909a6..1103ab9019 100644 --- a/types/swig-email-templates/swig-email-templates-tests.ts +++ b/types/swig-email-templates/swig-email-templates-tests.ts @@ -1,15 +1,15 @@ +import EmailTemplates = require('swig-email-templates'); +import jQuery = require('jquery'); -import emailTemplates = require('swig-email-templates'); +const templates = new EmailTemplates(); +const withOptions = new EmailTemplates({ root: '' }); -var options = { - root: "root" -}; +templates.generateText('templatePath', {}, 'html', () => {}); +templates.generateSubject('templatePath', {}, () => {}); +templates.rewriteUrls(jQuery, () => {}); +templates.render('templatePath', {}, () => {}); -emailTemplates(options, function(err, render) { - var context = { - meatballCount: 9001, - }; - render('meatball-sandwich.html', context, function(err, html, text) { - // send html/text email - }); -}); +withOptions.generateText('templatePath', {}, 'html', () => {}); +withOptions.generateSubject('templatePath', {}, () => { }); +withOptions.rewriteUrls(jQuery, () => {}); +withOptions.render('templatePath', {}, () => {}); diff --git a/types/swig-email-templates/tsconfig.json b/types/swig-email-templates/tsconfig.json index b25f125136..987a6f629a 100644 --- a/types/swig-email-templates/tsconfig.json +++ b/types/swig-email-templates/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "swig-email-templates-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swig-email-templates/tslint.json b/types/swig-email-templates/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/swig-email-templates/tslint.json +++ b/types/swig-email-templates/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/vuex-i18n/index.d.ts b/types/vuex-i18n/index.d.ts new file mode 100644 index 0000000000..2332ef4436 --- /dev/null +++ b/types/vuex-i18n/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for vuex-i18n 1.7 +// Project: https://github.com/dkfbasel/vuex-i18n +// Definitions by: Cedric Kemp +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import _Vue, { PluginObject } from "vue"; + +declare module "vue/types/vue" { + interface Vue { + $i18n: Ii18n; + } + + interface VueConstructor { + i18n: Ii18n; + } +} + +export interface Translations { + [key: string]: string; +} + +export interface Ii18n { + /** get the current locale */ + locale(): string; + + /** set the current locale (i.e. 'de', 'en') */ + set(locale: string): void; + + /** + * add locale translation to the storage. this will extend existing information + * (i.e. 'de', {'message': 'Eine Nachricht'}) + */ + add(locale: string, translations: Translations): void; + + /** + * replace locale translations in the storage. this will remove all previous + * locale information for the specified locale + */ + replace(locale: string, translations: Translations): void; + + /** + * remove the given locale from the store + */ + remove(locale: string): void; + + /** + * set a fallback locale if translation for current locale does not exist + */ + fallback(locale: string): void; + + /** + * get localized string from store. note that we pass the arguments passed + * to the function directly to the translateInLanguage function + */ + translate(key: string, options: any, pluralization?: number): string | undefined; + + /** + * get localized string from store. note that we pass the arguments passed + * to the function directly to the translateInLanguage function + */ + translate(key: string, defaultValue: string, options: any, pluralization?: number): string | undefined; + + /** + * get localized string from store in a given language if available. + */ + translateIn(locale: string, key: string, options: any, pluralization?: number): string | undefined; + + /** + * get localized string from store in a given language if available. + */ + translateIn(locale: string, key: string, defaultValue: string, options: any, pluralization?: number): string | undefined; + + /** + * check if the given locale translations are present in the store + */ + localeExists(locale: string): boolean; + + /** + * check if the given key is available in the current or fallback locale + */ + keyExists(key: string): boolean; +} + +declare const _default: { + plugin: PluginObject; +}; + +export default _default; diff --git a/types/vuex-i18n/package.json b/types/vuex-i18n/package.json new file mode 100644 index 0000000000..f180048358 --- /dev/null +++ b/types/vuex-i18n/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "vue": ">=2.0.0", + "vuex": ">=2.0.0" + } +} diff --git a/types/vuex-i18n/tsconfig.json b/types/vuex-i18n/tsconfig.json new file mode 100644 index 0000000000..9f8f6eb2fd --- /dev/null +++ b/types/vuex-i18n/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "types": [], + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "noEmit": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vuex-i18n-tests.ts" + ] +} \ No newline at end of file diff --git a/types/vuex-i18n/tslint.json b/types/vuex-i18n/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/vuex-i18n/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/vuex-i18n/vuex-i18n-tests.ts b/types/vuex-i18n/vuex-i18n-tests.ts new file mode 100644 index 0000000000..218bd12ccf --- /dev/null +++ b/types/vuex-i18n/vuex-i18n-tests.ts @@ -0,0 +1,41 @@ +// load vue and vuex instance +import Vue from "vue"; +import { Store } from "vuex"; + +// load vuex i18n module +import vuexI18n from "vuex-i18n"; + +// initialize the vuex store using the vuex module. note that you can change the +// name of the module if you wish +const store = new Store({}); + +// initialize the internationalization plugin on the vue instance. note that +// the store must be passed to the plugin. the plugin will then generate some +// helper functions for components (i.e. this.$i18n.set, this.$t) and on the vue +// instance (i.e. Vue.i18n.set). +Vue.use(vuexI18n.plugin, store); + +// please note that you must specify the name of the vuex module if it is +// different from i18n. i.e. Vue.use(vuexI18n.plugin, store, "myName") + +// add some translations (could also be loaded from a separate file) +// note that it is possible to use placeholders. translations can also be +// structured as object trees and will automatically be flattened by the the +// plugin +const translationsEn = { + content: "This is some {type} content" +}; + +// translations can be kept in separate files for each language +// i.e. resources/i18n/de.json. +const translationsDe = { + "My nice title": "Ein schöner Titel", + content: "Dies ist ein toller Inhalt" +}; + +// add translations directly to the application +Vue.i18n.add("en", translationsEn); +Vue.i18n.add("de", translationsDe); + +// set the start locale to use +Vue.i18n.set("en"); diff --git a/types/wtfnode/index.d.ts b/types/wtfnode/index.d.ts new file mode 100644 index 0000000000..a33af419c3 --- /dev/null +++ b/types/wtfnode/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for wtfnode 0.5 +// Project: https://github.com/myndzi/wtfnode +// Definitions by: Piotr Roszatycki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function dump(): void; +export function init(): void; diff --git a/types/wtfnode/tsconfig.json b/types/wtfnode/tsconfig.json new file mode 100644 index 0000000000..429ee54cb7 --- /dev/null +++ b/types/wtfnode/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "wtfnode-tests.ts" + ] +} diff --git a/types/wtfnode/tslint.json b/types/wtfnode/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/wtfnode/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/wtfnode/wtfnode-tests.ts b/types/wtfnode/wtfnode-tests.ts new file mode 100644 index 0000000000..a87800aee5 --- /dev/null +++ b/types/wtfnode/wtfnode-tests.ts @@ -0,0 +1,4 @@ +import * as wtf from 'wtfnode'; + +wtf.init(); +wtf.dump();