diff --git a/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.104.x-/react-common_v3.x.x.js b/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.104.x-v0.200.x/react-common_v3.x.x.js similarity index 100% rename from definitions/npm/@apollo/react-common_v3.x.x/flow_v0.104.x-/react-common_v3.x.x.js rename to definitions/npm/@apollo/react-common_v3.x.x/flow_v0.104.x-v0.200.x/react-common_v3.x.x.js diff --git a/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.104.x-/test_react-common_v3.x.x.js b/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.104.x-v0.200.x/test_react-common_v3.x.x.js similarity index 100% rename from definitions/npm/@apollo/react-common_v3.x.x/flow_v0.104.x-/test_react-common_v3.x.x.js rename to definitions/npm/@apollo/react-common_v3.x.x/flow_v0.104.x-v0.200.x/test_react-common_v3.x.x.js diff --git a/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.201.x-/react-common_v3.x.x.js b/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.201.x-/react-common_v3.x.x.js new file mode 100644 index 0000000000..d23fb244d5 --- /dev/null +++ b/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.201.x-/react-common_v3.x.x.js @@ -0,0 +1,1050 @@ +declare module '@apollo/react-common' { + import type { Node } from 'react'; + + /* start utils */ + declare export type Record = { + [key: $Keys]: U, + ..., + }; + /* end utils */ + + /* start graphql */ + declare export type DocumentNode = any; + declare export type ExecutionResult = { + data?: T, + extensions?: { [string]: any, ... }, + errors?: any[], + ... + }; + declare export type GraphQLError = any; + declare export type VariableDefinitionNode = any; + /* end graphql */ + + /* start context */ + declare export type ApolloContextValue = { + client?: ApolloClient, + renderPromises?: Record, + ... + }; + + declare export type ApolloProviderProps = { + client: ApolloClient, + children: Node | Node[] | null, + ... + }; + + declare export class ApolloProvider extends React$Component< + ApolloProviderProps + > { + childContextTypes: { + client: ApolloClient, + operations: Map< + string, + { + query: DocumentNode, + variables: any, + ... + } + >, + ... + }; + getChildContext(): { + client: ApolloClient, + operations: Map< + string, + { + query: DocumentNode, + variables: any, + ... + } + >, + ... + }; + } + + declare export function getApolloContext(): T; + + declare export interface ApolloConsumerProps { + children: (client: ApolloClient) => Node; + } + + declare export class ApolloConsumer extends React$Component {} + declare export function resetApolloContext(): void; + + /* end context */ + + /* start parser */ + declare export type DocumentType = 'Query' | 'Mutation' | 'Subscription'; + + declare export type IDocumentDefinition = { + type: DocumentType, + name: string, + variables: $ReadOnlyArray , + ... + }; + + declare export function operationName(type: DocumentType): string; + + declare export function parser(document: DocumentNode): IDocumentDefinition; + /* end parser */ + + /* start operation types */ + declare export type OperationVariables = Record; + + declare export type Context = Record; + + /* Query types */ + declare export type BaseQueryOptions = { + ssr?: boolean, + variables?: TVariables, + fetchPolicy?: FetchPolicy, + errorPolicy?: ErrorPolicy, + pollInterval?: number, + client?: ApolloClient, + notifyOnNetworkStatusChange?: boolean, + context?: Context, + partialRefetch?: boolean, + returnPartialData?: boolean, + ... + }; + + declare export type QueryFunctionOptions< + TData, + TVariables + > = BaseQueryOptions & { + displayName?: string, + skip?: boolean, + onCompleted?: (data: TData) => void, + onError?: (error: ApolloError) => void, + ... + }; + + declare export type ObservableQueryFields = { + startPolling: $PropertyType< + ObservableQuery, + 'startPolling' + >, + stopPolling: $PropertyType< + ObservableQuery, + 'stopPolling' + >, + subscribeToMore: $PropertyType< + ObservableQuery, + 'subscribeToMore' + >, + updateQuery: $PropertyType< + ObservableQuery, + 'updateQuery' + >, + refetch: $PropertyType, 'refetch'>, + variables: $PropertyType, 'variables'>, + fetchMore: (( + fetchMoreOptions: FetchMoreQueryOptions & + FetchMoreOptions + ) => Promise>) & + (( + fetchMoreOptions: { + query?: DocumentNode, + ... + } & FetchMoreQueryOptions & + FetchMoreOptions + ) => Promise>), + ... + }; + + declare export type QueryResult = ObservableQueryFields< + TData, + TVariables + > & { + client: ApolloClient, + data: ?TData, + error?: ApolloError, + loading: boolean, + networkStatus: NetworkStatusRaw, + called: boolean, + ... + }; + + /* Mutation types */ + declare export type RefetchQueriesFunction = ( + ...args: any[] + ) => Array; + + declare export type BaseMutationOptions = { + variables?: TVariables, + optimisticResponse?: TData | ((vars: TVariables) => TData), + refetchQueries?: Array | RefetchQueriesFunction, + awaitRefetchQueries?: boolean, + errorPolicy?: ErrorPolicy, + update?: MutationUpdaterFn, + client?: ApolloClient, + notifyOnNetworkStatusChange?: boolean, + context?: Context, + onCompleted?: (data: TData) => void, + onError?: (error: ApolloError) => void, + fetchPolicy?: FetchPolicy, + ignoreResults?: boolean, + ... + }; + + declare export type MutationFunctionOptions = { + variables?: TVariables, + optimisticResponse?: TData | ((vars: TVariables | { ... }) => TData), + refetchQueries?: Array | RefetchQueriesFunction, + awaitRefetchQueries?: boolean, + update?: MutationUpdaterFn, + context?: Context, + fetchPolicy?: FetchPolicy, + ... + }; + + declare export type MutationResult = { + data?: TData, + error?: ApolloError, + loading: boolean, + called: boolean, + client?: ApolloClient, + ... + }; + + declare export type MutationFetchResult< + TData = Record, + C = Record, + E = Record + > = ExecutionResult & { + extensions?: E, + context?: C, + ... + }; + + declare export type MutationFunction = ( + options?: MutationFunctionOptions + ) => Promise>; + + /* Subscription types */ + declare export type OnSubscriptionDataOptions = { + client: ApolloClient, + subscriptionData: SubscriptionResult, + ... + }; + + declare export type BaseSubscriptionOptions = { + variables?: TVariables, + fetchPolicy?: FetchPolicy, + shouldResubscribe?: + | boolean + | ((options: BaseSubscriptionOptions) => boolean), + client?: ApolloClient, + onSubscriptionData?: (options: OnSubscriptionDataOptions) => any, + onSubscriptionComplete?: () => void, + ... + }; + + declare export type SubscriptionResult = { + loading: boolean, + data?: TData, + error?: ApolloError, + ... + }; + /* end operation types */ + + /* start apollo-client types */ + + declare class ObservableQuery< + T, + V = { [key: string]: any, ... } + > extends Observable> { + options: WatchQueryOptions; + queryId: string; + variables: V; + isCurrentlyPolling: boolean; + shouldSubscribe: boolean; + isTornDown: boolean; + scheduler: QueryScheduler; + queryManager: QueryManager; + observers: Observer>[]; + subscriptionHandles: SubscriptionLINK[]; + lastResult: ApolloQueryResult; + lastError: ApolloError; + lastVariables: V; + constructor(data: { + scheduler: QueryScheduler, + options: WatchQueryOptions, + shouldSubscribe?: boolean, + ... + }): this; + result(): Promise>; + currentResult(): ApolloCurrentResult; + getLastResult(): ApolloQueryResult; + getLastError(): ApolloError; + resetLastResults(): void; + refetch(variables?: V): Promise>; + fetchMore( + fetchMoreOptions: FetchMoreQueryOptions & FetchMoreOptions + ): Promise>; + subscribeToMore(options: SubscribeToMoreOptions): () => void; + setOptions( + opts: ModifiableWatchQueryOptions + ): Promise>; + setVariables( + variables: V, + tryFetch?: boolean, + fetchResults?: boolean + ): Promise>; + updateQuery( + mapFn: (previousQueryResult: any, options: UpdateQueryOptions) => any + ): void; + stopPolling(): void; + startPolling(pollInterval: number): void; + } + + declare class QueryManager { + scheduler: QueryScheduler; + link: ApolloLink; + mutationStore: MutationStore; + queryStore: QueryStore; + dataStore: DataStore; + constructor({ + link: ApolloLink, + queryDeduplication?: boolean, + store: DataStore, + onBroadcast?: () => void, + ssrMode?: boolean, + ... + }): this; + mutate(options: MutationOptions<>): Promise>; + fetchQuery( + queryId: string, + options: WatchQueryOptions, + fetchType?: FetchType, + fetchMoreForQueryId?: string + ): Promise>; + queryListenerForObserver( + queryId: string, + options: WatchQueryOptions, + observer: Observer> + ): QueryListener; + watchQuery( + options: WatchQueryOptions, + shouldSubscribe?: boolean + ): ObservableQuery; + query(options: WatchQueryOptions): Promise>; + generateQueryId(): string; + stopQueryInStore(queryId: string): void; + addQueryListener(queryId: string, listener: QueryListener): void; + updateQueryWatch( + queryId: string, + document: DocumentNode, + options: WatchQueryOptions + ): void; + addFetchQueryPromise( + requestId: number, + promise: Promise>, + resolve: (result: ApolloQueryResult) => void, + reject: (error: Error) => void + ): void; + removeFetchQueryPromise(requestId: number): void; + addObservableQuery( + queryId: string, + observableQuery: ObservableQuery + ): void; + removeObservableQuery(queryId: string): void; + clearStore(): Promise; + resetStore(): Promise[]>; + } + + declare class QueryStore { + getStore(): { + [queryId: string]: QueryStoreValue, + ..., + }; + get(queryId: string): QueryStoreValue; + initQuery(query: { + queryId: string, + document: DocumentNode, + storePreviousVariables: boolean, + variables: any, + isPoll: boolean, + isRefetch: boolean, + metadata: any, + fetchMoreForQueryId: string | void, + ... + }): void; + markQueryResult( + queryId: string, + result: ExecutionResult<>, + fetchMoreForQueryId: string | void + ): void; + markQueryError( + queryId: string, + error: Error, + fetchMoreForQueryId: string | void + ): void; + markQueryResultClient(queryId: string, complete: boolean): void; + stopQuery(queryId: string): void; + reset(observableQueryIds: string[]): void; + } + + declare class QueryScheduler { + inFlightQueries: { + [queryId: string]: WatchQueryOptions, + ..., + }; + registeredQueries: { + [queryId: string]: WatchQueryOptions, + ..., + }; + intervalQueries: { + [interval: number]: string[], + ..., + }; + queryManager: QueryManager; + constructor({ + queryManager: QueryManager, + ssrMode?: boolean, + ... + }): this; + checkInFlight(queryId: string): ?boolean; + fetchQuery( + queryId: string, + options: WatchQueryOptions, + fetchType: FetchType + ): Promise>; + startPollingQuery( + options: WatchQueryOptions, + queryId: string, + listener?: QueryListener + ): string; + stopPollingQuery(queryId: string): void; + fetchQueriesOnInterval(interval: number): void; + addQueryOnInterval( + queryId: string, + queryOptions: WatchQueryOptions + ): void; + registerPollingQuery( + queryOptions: WatchQueryOptions + ): ObservableQuery; + markMutationError(mutationId: string, error: Error): void; + reset(): void; + } + + declare class DataStore { + constructor(initialCache: ApolloCache): this; + getCache(): ApolloCache; + markQueryResult( + result: ExecutionResult<>, + document: DocumentNode, + variables: any, + fetchMoreForQueryId: string | void, + ignoreErrors?: boolean + ): void; + markSubscriptionResult( + result: ExecutionResult<>, + document: DocumentNode, + variables: any + ): void; + markMutationInit(mutation: { + mutationId: string, + document: DocumentNode, + variables: any, + updateQueries: { + [queryId: string]: QueryWithUpdater, + ..., + }, + update: ((proxy: DataProxy, mutationResult: any) => void) | void, + optimisticResponse: any, + ... + }): void; + markMutationResult(mutation: { + mutationId: string, + result: ExecutionResult<>, + document: DocumentNode, + variables: any, + updateQueries: { + [queryId: string]: QueryWithUpdater, + ..., + }, + update: ((proxy: DataProxy, mutationResult: any) => void) | void, + ... + }): void; + markMutationComplete({ + mutationId: string, + optimisticResponse?: any, + ... + }): void; + markUpdateQueryResult( + document: DocumentNode, + variables: any, + newResult: any + ): void; + reset(): Promise; + } + + declare export type QueryWithUpdater = { + updater: MutationQueryReducer, + query: QueryStoreValue, + ... + }; + + declare export interface MutationStoreValue { + mutationString: string; + variables: any; + loading: boolean; + error: Error | null; + } + + declare class MutationStore { + getStore(): { + [mutationId: string]: MutationStoreValue, + ..., + }; + get(mutationId: string): MutationStoreValue; + initMutation( + mutationId: string, + mutationString: string, + variables: any + ): void; + } + + declare export interface FetchMoreOptions { + updateQuery: ( + previousQueryResult: TData, + options: { + fetchMoreResult?: TData, + variables: TVariables, + ... + } + ) => TData; + } + + declare export interface UpdateQueryOptions { + variables?: any; + } + + declare export type ApolloCurrentResult = { + data: T | { ... }, + errors?: Array, + loading: boolean, + networkStatus: NetworkStatusRaw, + error?: ApolloError, + partial?: boolean, + ... + }; + + declare export type ModifiableWatchQueryOptions = { + variables?: { + [key: string]: any, + ..., + }, + pollInterval?: number, + fetchPolicy?: FetchPolicy, + errorPolicy?: ErrorPolicy, + fetchResults?: boolean, + notifyOnNetworkStatusChange?: boolean, + ... + }; + + declare export type WatchQueryOptions = { + ...$Exact, + query: DocumentNode, + metadata?: any, + context?: any, + ... + }; + + declare export type RefetchQueryDescription = Array< + string | PureQueryOptions + >; + + declare export interface MutationBaseOptions< + T = { + [key: string]: any, + ..., + } + > { + optimisticResponse?: any; + updateQueries?: MutationQueryReducersMap; + optimisticResponse?: any; + refetchQueries?: + | ((result: ExecutionResult<>) => RefetchQueryDescription) + | RefetchQueryDescription; + update?: MutationUpdaterFn; + errorPolicy?: ErrorPolicy; + variables?: any; + } + + declare export type FetchPolicy = + | 'cache-first' + | 'cache-and-network' + | 'network-only' + | 'cache-only' + | 'no-cache' + | 'standby'; + + declare export type ErrorPolicy = 'none' | 'ignore' | 'all'; + + declare export interface FetchMoreQueryOptions { + variables: $Shape; + } + + declare export type SubscribeToMoreOptions< + TData, + TSubscriptionData, + TSubscriptionVariables = void + > = { + document?: DocumentNode, + variables?: TSubscriptionVariables, + updateQuery?: ( + previousResult: TData, + result: { + subscriptionData: { + data?: TSubscriptionData, + ... + }, + variables: TSubscriptionVariables, + ... + } + ) => TData, + onError?: (error: Error) => void, + ... + }; + + declare export type MutationUpdaterFn = ( + proxy: DataProxy, + mutationResult: FetchResult + ) => void; + + declare export type NetworkStatusRaw = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + + declare export class NetworkStatus { + [NetworkStatusRaw]: string; + string: NetworkStatusRaw; + } + + declare export type QueryListener = ( + queryStoreValue: QueryStoreValue, + newData?: any + ) => void; + + declare export type QueryStoreValue = { + document: DocumentNode, + variables: any, + previousVariables: any, + networkStatus: NetworkStatusRaw, + networkError: Error | null, + graphQLErrors: GraphQLError[], + metadata: any, + ... + }; + + declare export type PureQueryOptions = { + query: DocumentNode, + variables?: { + [key: string]: any, + ..., + }, + ... + }; + + declare export type ApolloQueryResult = { + data: T, + errors?: Array, + loading: boolean, + networkStatus: NetworkStatusRaw, + stale: boolean, + ... + }; + + declare export type FetchType = 1 | 2 | 3; + + declare export type MutationQueryReducer = ( + previousResult: { + [key: string]: any, + ..., + }, + options: { + mutationResult: FetchResult, + queryName: string | void, + queryVariables: { + [key: string]: any, + ..., + }, + ... + } + ) => { + [key: string]: any, + ..., + }; + + declare export type MutationQueryReducersMap< + T = { + [key: string]: any, + ..., + } + > = { + [queryName: string]: MutationQueryReducer, + ..., + }; + + declare class $ApolloError extends Error { + message: string; + graphQLErrors: Array; + networkError: Error | null; + extraInfo: any; + constructor(info: ErrorConstructor): this; + } + declare export type ApolloError = $ApolloError; + + declare export interface ErrorConstructor { + graphQLErrors?: Array; + networkError?: Error | null; + errorMessage?: string; + extraInfo?: any; + } + + declare export interface DefaultOptions { + +watchQuery?: ModifiableWatchQueryOptions; + +query?: ModifiableWatchQueryOptions; + +mutate?: MutationBaseOptions<>; + } + + declare export type ApolloClientOptions = { + link: ApolloLink, + cache: ApolloCache, + ssrMode?: boolean, + ssrForceFetchDelay?: number, + connectToDevTools?: boolean, + queryDeduplication?: boolean, + defaultOptions?: DefaultOptions, + ... + }; + + declare class ApolloClient { + link: ApolloLink; + store: DataStore; + cache: ApolloCache; + queryManager: QueryManager; + disableNetworkFetches: boolean; + version: string; + queryDeduplication: boolean; + defaultOptions: DefaultOptions; + devToolsHookCb: any; + proxy: ApolloCache | void; + ssrMode: boolean; + resetStoreCallbacks: Array<() => Promise>; + constructor(options: ApolloClientOptions): this; + watchQuery(options: WatchQueryOptions): ObservableQuery; + query(options: WatchQueryOptions): Promise>; + mutate(options: MutationOptions): Promise>; + subscribe(options: SubscriptionOptions): Observable; + readQuery(options: DataProxyReadQueryOptions): T | null; + readFragment( + options: DataProxyReadFragmentOptions + ): TData | null; + writeQuery( + options: DataProxyWriteQueryOptions + ): void; + writeFragment( + options: DataProxyWriteFragmentOptions + ): void; + writeData(options: DataProxyWriteDataOptions): void; + __actionHookForDevTools(cb: () => any): void; + __requestRaw(payload: GraphQLRequest): Observable>; + initQueryManager(): void; + resetStore(): Promise> | null>; + onResetStore(cb: () => Promise): () => void; + reFetchObservableQueries( + includeStandby?: boolean + ): Promise[]> | Promise; + extract(optimistic?: boolean): TCacheShape; + restore(serializedState: TCacheShape): ApolloCache; + } + + /* apollo-link types */ + declare class ApolloLink { + constructor(request?: RequestHandler): this; + static empty(): ApolloLink; + static from(links: Array): ApolloLink; + static split( + test: (op: Operation) => boolean, + left: ApolloLink | RequestHandler, + right: ApolloLink | RequestHandler + ): ApolloLink; + static execute( + link: ApolloLink, + operation: GraphQLRequest + ): Observable>; + split( + test: (op: Operation) => boolean, + left: ApolloLink | RequestHandler, + right: ApolloLink | RequestHandler + ): ApolloLink; + concat(next: ApolloLink | RequestHandler): ApolloLink; + request( + operation: Operation, + forward?: NextLink + ): Observable> | null; + } + + declare export interface GraphQLRequest { + query: DocumentNode; + variables?: { + [key: string]: any, + ..., + }; + operationName?: string; + context?: { + [key: string]: any, + ..., + }; + extensions?: { + [key: string]: any, + ..., + }; + } + + declare export interface Operation { + query: DocumentNode; + variables: { + [key: string]: any, + ..., + }; + operationName: string; + extensions: { + [key: string]: any, + ..., + }; + setContext: (context: { + [key: string]: any, + ..., + }) => { + [key: string]: any, + ..., + }; + getContext: () => { + [key: string]: any, + ..., + }; + toKey: () => string; + } + + declare export type FetchResult< + C = { + [key: string]: any, + ..., + }, + E = { + [key: string]: any, + ..., + } + > = ExecutionResult & { + extension?: E, + context?: C, + ... + }; + + declare export type NextLink = ( + operation: Operation + ) => Observable>; + + declare export type RequestHandler = ( + operation: Operation, + forward?: NextLink + ) => Observable> | null; + + declare class Observable { + subscribe( + observerOrNext: ((value: T) => void) | ZenObservableObserver, + error?: (error: any) => void, + complete?: () => void + ): ZenObservableSubscription; + forEach(fn: (value: T) => void): Promise; + map(fn: (value: T) => R): Observable; + filter(fn: (value: T) => boolean): Observable; + reduce( + fn: (previousValue: R | T, currentValue: T) => R | T, + initialValue?: R | T + ): Observable; + flatMap(fn: (value: T) => ZenObservableObservableLike): Observable; + from( + observable: Observable | ZenObservableObservableLike | Array + ): Observable; + of(...args: Array): Observable; + } + + declare export interface Observer { + start?: (subscription: SubscriptionLINK) => any; + next?: (value: T) => void; + error?: (errorValue: any) => void; + complete?: () => void; + } + + declare export interface SubscriptionLINK { + closed: boolean; + unsubscribe(): void; + } + + declare export interface ZenObservableSubscriptionObserver { + closed: boolean; + next(value: T): void; + error(errorValue: any): void; + complete(): void; + } + + declare export interface ZenObservableSubscription { + closed: boolean; + unsubscribe(): void; + } + + declare export interface ZenObservableObserver { + start?: (subscription: ZenObservableSubscription) => any; + next?: (value: T) => void; + error?: (errorValue: any) => void; + complete?: () => void; + } + + declare export type ZenObservableSubscriber = ( + observer: ZenObservableSubscriptionObserver + ) => void | (() => void) | SubscriptionLINK; + + declare export interface ZenObservableObservableLike { + subscribe?: ZenObservableSubscriber; + } + /* apollo-link types */ + + /* apollo-cache types */ + declare class ApolloCache { + read(query: CacheReadOptions): T | null; + write(write: CacheWriteOptions): void; + diff(query: CacheDiffOptions): CacheDiffResult; + watch(watch: CacheWatchOptions): () => void; + evict(query: CacheEvictOptions): CacheEvictionResult; + reset(): Promise; + restore(serializedState: TSerialized): ApolloCache; + extract(optimistic?: boolean): TSerialized; + removeOptimistic(id: string): void; + performTransaction(transaction: Transaction): void; + recordOptimisticTransaction( + transaction: Transaction, + id: string + ): void; + transformDocument(document: DocumentNode): DocumentNode; + transformForLink(document: DocumentNode): DocumentNode; + readQuery( + options: DataProxyReadQueryOptions, + optimistic?: boolean + ): QueryType | null; + readFragment( + options: DataProxyReadFragmentOptions, + optimistic?: boolean + ): FragmentType | null; + writeQuery( + options: CacheWriteQueryOptions + ): void; + writeFragment( + options: CacheWriteFragmentOptions + ): void; + writeData(options: CacheWriteDataOptions): void; + } + + declare export type Transaction = (c: ApolloCache) => void; + + declare export type CacheWatchCallback = (newData: any) => void; + + declare export interface CacheEvictionResult { + success: boolean; + } + + declare export interface CacheReadOptions extends DataProxyReadQueryOptions { + rootId?: string; + previousResult?: any; + optimistic: boolean; + } + + declare export interface CacheWriteOptions extends DataProxyReadQueryOptions { + dataId: string; + result: any; + } + + declare export interface CacheDiffOptions extends CacheReadOptions { + returnPartialData?: boolean; + } + + declare export interface CacheWatchOptions extends CacheReadOptions { + callback: CacheWatchCallback; + } + + declare export interface CacheEvictOptions extends DataProxyReadQueryOptions { + rootId?: string; + } + + declare export type CacheDiffResult = DataProxyDiffResult; + declare export type CacheWriteQueryOptions< + TData, + TVariables + > = DataProxyWriteQueryOptions; + declare export type CacheWriteFragmentOptions< + TData, + TVariables + > = DataProxyWriteFragmentOptions; + declare export type CacheWriteDataOptions< + TData + > = DataProxyWriteDataOptions; + + declare export interface DataProxyReadQueryOptions { + query: DocumentNode; + variables?: TVariables; + } + + declare export interface DataProxyReadFragmentOptions { + id: string; + fragment: DocumentNode; + fragmentName?: string; + variables?: TVariables; + } + + declare export interface DataProxyWriteQueryOptions { + data: TData; + query: DocumentNode; + variables?: TVariables; + } + + declare export interface DataProxyWriteFragmentOptions { + data: TData; + id: string; + fragment: DocumentNode; + fragmentName?: string; + variables?: TVariables; + } + + declare export interface DataProxyWriteDataOptions { + data: TData; + id?: string; + } + + declare export type DataProxyDiffResult = { + result?: T, + complete?: boolean, + ... + }; + + declare export interface DataProxy { + readQuery( + options: DataProxyReadQueryOptions, + optimistic?: boolean + ): QueryType | null; + readFragment( + options: DataProxyReadFragmentOptions, + optimistic?: boolean + ): FragmentType | null; + writeQuery( + options: DataProxyWriteQueryOptions + ): void; + writeFragment( + options: DataProxyWriteFragmentOptions + ): void; + writeData(options: DataProxyWriteDataOptions): void; + } + /* End apollo-cache types */ + /* end apollo-client types */ +} diff --git a/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.201.x-/test_react-common_v3.x.x.js b/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.201.x-/test_react-common_v3.x.x.js new file mode 100644 index 0000000000..afe610790e --- /dev/null +++ b/definitions/npm/@apollo/react-common_v3.x.x/flow_v0.201.x-/test_react-common_v3.x.x.js @@ -0,0 +1,119 @@ +// @flow + +import * as React from 'react'; +import { it, describe } from 'flow-typed-test'; +import { + ApolloProvider, + ApolloConsumer, + parser, + operationName, + type DocumentType, + type IDocumentDefinition +} from '@apollo/react-common'; + +const gql = (strings, ...args) => {}; // graphql-tag stub + +const query = gql` + { + foo + } +`; +const mutation = gql` + mutation { + foo + } +`; + +type Hero = { + name: string, + id: string, + appearsIn: string[], + friends: Hero[], + ... +}; + +const HERO_QUERY = gql` + query GetCharacter($episode: String!, $offset: Int) { + hero(episode: $episode, offset: $offset) { + name + id + friends { + name + id + appearsIn + } + } + } +`; + +describe('', () => { + it('works when passed client', () => { + // $FlowExpectedError Should be an instance of ApolloClient + const client = {}; + +
+ ; + }); + + it('raises an error when not passed a client', () => { + // $FlowExpectedError ApolloProvider requires client prop + +
+ ; + }); + + it('raises an error when not passed children', () => { + // Should be an instance of ApolloClient + const client = {}; + + // $FlowExpectedError ApolloProvider requires client prop + ; + }); +}); + +describe('', () => { + it('passes ApolloClient to the consumer children', () => { + + {client => { + const onClick = () => { + client.resetStore(); + client.query({ query: HERO_QUERY }); + client.readQuery({ + query: HERO_QUERY, + variables: { episode: 'episode' }, + }); + // $FlowExpectedError doSomethingElse is not a method of ApolloClient + client.doSomethingElse(); + }; + return ; + }} + ; + }); +}); + +describe('parser', () => { + it('returns IDocumentDefinition', () => { + const document = {}; + + const result = parser({}); + + (result: IDocumentDefinition); + // $FlowExpectedError + (result: number); + }) +}) + +describe('operationName', () => { + it('works', () => { + const result = operationName('Query'); + + (result: string); + // $FlowExpectedError + (result: number); + }) + + it('requires DocumentType', () => { + // $FlowExpectedError must be a DocumentType + const result = operationName('foo'); + }) +}) diff --git a/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.104.x-/react-hooks_v3.x.x.js b/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.104.x-v0.200.x/react-hooks_v3.x.x.js similarity index 100% rename from definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.104.x-/react-hooks_v3.x.x.js rename to definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.104.x-v0.200.x/react-hooks_v3.x.x.js diff --git a/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.104.x-/test_react-hooks_v3.x.x.js b/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.104.x-v0.200.x/test_react-hooks_v3.x.x.js similarity index 100% rename from definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.104.x-/test_react-hooks_v3.x.x.js rename to definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.104.x-v0.200.x/test_react-hooks_v3.x.x.js diff --git a/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.201.x-/react-hooks_v3.x.x.js b/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.201.x-/react-hooks_v3.x.x.js new file mode 100644 index 0000000000..66ae3284e1 --- /dev/null +++ b/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.201.x-/react-hooks_v3.x.x.js @@ -0,0 +1,1046 @@ +declare module '@apollo/react-hooks' { + import type { ComponentType, Element, Node } from 'react'; + + /* start graphql types */ + declare export type DocumentNode = any; + declare export type GraphQLError = any; + /* end graphql types */ + + /* start @apollo/react-common types */ + declare export type ApolloProviderProps = {| + client: ApolloClient, + children: Node | Node[] | null, + |}; + + declare export class ApolloProvider extends React$Component< + ApolloProviderProps + > { + childContextTypes: {| + client: ApolloClient, + operations: Map< + string, + {| + query: DocumentNode, + variables: any, + |} + >, + |}; + getChildContext(): {| + client: ApolloClient, + operations: Map< + string, + {| + query: DocumentNode, + variables: any, + |} + >, + |}; + } + + declare export interface ApolloConsumerProps { + children: (client: ApolloClient) => Node; + } + + declare export class ApolloConsumer extends React$Component {} + + declare export function getApolloContext(): T; + declare export function resetApolloContext(): void; + /* end @apollo/react-common types */ + + /* start @apollo/react-hooks types */ + declare export type Record = {| [key: $Keys]: U |}; + + declare export function useQuery( + query: DocumentNode, + options?: QueryHookOptions + ): QueryResult; + + declare export function useLazyQuery( + query: DocumentNode, + options?: LazyQueryHookOptions + ): [ + (options?: QueryLazyOptions) => void, + QueryResult + ]; + + declare export function useSubscription( + query: DocumentNode, + options?: SubscriptionHookOptions + ): QueryResult; + + declare export function useMutation( + query: DocumentNode, + options?: MutationHookOptions + ): MutationTuple; + + declare export function useApolloClient(): ApolloClient; + + declare export class RenderPromises { + registerSSRObservable( + observable: ObservableQuery, + props: QueryOptions + ): void; + addQueryPromise( + queryInstance: QueryData, + finish: () => Node + ): Node; + hasPromises(): boolean; + consumeAndAwaitPromises(): Promise; + } + + declare export class QueryData { + execute(): QueryResult; + executeLazy(): QueryTuple; + fetchData(): Promise> | boolean; + afterExecute({| lazy?: boolean |}): any; + cleanup(): void; + getOptions(): any; + } + + /* Common types */ + declare export type CommonOptions = {| + ...TOptions, + client?: ApolloClient, + |}; + + /* Query types */ + declare export type QueryOptions = {| + ...QueryFunctionOptions, + children?: (result: QueryResult) => Node, + query: DocumentNode, + |}; + + declare export type QueryHookOptions = {| + ...QueryFunctionOptions, + query?: DocumentNode, + |}; + + declare export type LazyQueryHookOptions = {| + ...$Diff, {| skip: any |}>, + query?: DocumentNode, + |}; + + declare export type QueryPreviousData = {| + client?: ApolloClient, + query?: DocumentNode, + observableQueryOptions?: any, + result?: ApolloQueryResult | null, + loading?: boolean, + options?: QueryOptions, + |}; + + declare export type QueryCurrentObservable = {| + query?: ObservableQuery | null, + subscription?: ZenObservableSubscription, + |}; + + declare export type QueryLazyOptions = {| + variables?: TVariables, + context?: Context, + |}; + + declare export type QueryTuple = [ + (options?: QueryLazyOptions) => void, + QueryResult + ]; + + /* Mutation types */ + declare export type MutationHookOptions = {| + ...BaseMutationOptions, + mutation?: DocumentNode, + |}; + + declare export type MutationOptions = {| + ...BaseMutationOptions, + mutation: DocumentNode, + |}; + + declare export type MutationTuple = [ + ( + options?: MutationFunctionOptions + ) => Promise>, + MutationResult + ]; + + /* Subscription types */ + declare export type SubscriptionHookOptions = {| + ...BaseSubscriptionOptions, + subscription?: DocumentNode, + |}; + + declare export type SubscriptionOptions = {| + ...BaseSubscriptionOptions, + subscription: DocumentNode, + children?: + | null + | ((result: SubscriptionResult) => Element | null), + |}; + + declare export type SubscriptionCurrentObservable = {| + query?: Observable, + subscription?: ZenObservableSubscription, + |}; + + /* Common types */ + declare export type OperationVariables = Record; + + declare export type Context = Record; + + declare export type ExecutionResult = {| + data?: T, + extensions?: Record, + errors?: GraphQLError[], + |}; + + /* Query types */ + declare export type BaseQueryOptions = {| + ssr?: boolean, + variables?: TVariables, + fetchPolicy?: FetchPolicy, + errorPolicy?: ErrorPolicy, + pollInterval?: number, + client?: ApolloClient, + notifyOnNetworkStatusChange?: boolean, + context?: Context, + partialRefetch?: boolean, + returnPartialData?: boolean, + |}; + + declare export type QueryFunctionOptions = {| + ...BaseQueryOptions, + displayName?: string, + skip?: boolean, + onCompleted?: (data: TData) => void, + onError?: (error: ApolloError) => void, + |}; + + declare export type ObservableQueryFields = {| + startPolling: $PropertyType< + ObservableQuery, + 'startPolling' + >, + stopPolling: $PropertyType< + ObservableQuery, + 'stopPolling' + >, + subscribeToMore: $PropertyType< + ObservableQuery, + 'subscribeToMore' + >, + updateQuery: $PropertyType< + ObservableQuery, + 'updateQuery' + >, + refetch: $PropertyType, 'refetch'>, + variables: $PropertyType, 'variables'>, + fetchMore: ((fetchMoreOptions: {| + ...$Exact>, + ...$Exact>, + |}) => Promise>) & + ((fetchMoreOptions: {| + query?: DocumentNode, + ...$Exact>, + ...$Exact>, + |}) => Promise>), + |}; + + declare export type QueryResult = {| + ...ObservableQueryFields, + client: ApolloClient, + data: ?TData, + error?: ApolloError, + loading: boolean, + networkStatus: NetworkStatus, + called: boolean, + |}; + + /* Mutation types */ + declare export type RefetchQueriesFunction = ( + ...args: any[] + ) => Array; + + declare export type BaseMutationOptions = {| + variables?: TVariables, + optimisticResponse?: TData | ((vars: TVariables) => TData), + refetchQueries?: Array | RefetchQueriesFunction, + awaitRefetchQueries?: boolean, + errorPolicy?: ErrorPolicy, + update?: MutationUpdaterFn, + client?: ApolloClient, + notifyOnNetworkStatusChange?: boolean, + context?: Context, + onCompleted?: (data: TData) => void, + onError?: (error: ApolloError) => void, + fetchPolicy?: FetchPolicy, + ignoreResults?: boolean, + |}; + + declare export type MutationFunctionOptions = {| + variables?: TVariables, + optimisticResponse?: TData | ((vars: TVariables | {||}) => TData), + refetchQueries?: Array | RefetchQueriesFunction, + awaitRefetchQueries?: boolean, + update?: MutationUpdaterFn, + context?: Context, + fetchPolicy?: FetchPolicy, + |}; + + declare export type MutationResult = {| + data?: TData, + error?: ApolloError, + loading: boolean, + called: boolean, + client?: ApolloClient, + |}; + + declare export type MutationFetchResult< + TData = Record, + C = Record, + E = Record + > = {| + ...ExecutionResult, + extensions?: E, + context?: C, + |}; + + declare export type MutationFunction = ( + options?: MutationFunctionOptions + ) => Promise>; + + /* Subscription types */ + declare export type OnSubscriptionDataOptions = {| + client: ApolloClient, + subscriptionData: SubscriptionResult, + |}; + + declare export type BaseSubscriptionOptions = {| + variables?: TVariables, + skip?: boolean, + fetchPolicy?: FetchPolicy, + shouldResubscribe?: + | boolean + | ((options: BaseSubscriptionOptions) => boolean), + client?: ApolloClient, + onSubscriptionData?: (options: OnSubscriptionDataOptions) => any, + onSubscriptionComplete?: () => void, + |}; + + declare export type SubscriptionResult = {| + loading: boolean, + data?: TData, + error?: ApolloError, + |}; + + /* end @apollo/react-hooks types */ + + /* start apollo-client types */ + + declare class ObservableQuery< + T, + V = { [key: string]: any, ... } + > extends Observable> { + options: WatchQueryOptions; + queryId: string; + variables: V; + isCurrentlyPolling: boolean; + shouldSubscribe: boolean; + isTornDown: boolean; + scheduler: QueryScheduler; + queryManager: QueryManager; + observers: Observer>[]; + subscriptionHandles: SubscriptionLINK[]; + lastResult: ApolloQueryResult; + lastError: ApolloError; + lastVariables: V; + constructor(data: {| + scheduler: QueryScheduler, + options: WatchQueryOptions, + shouldSubscribe?: boolean, + |}): this; + result(): Promise>; + currentResult(): ApolloCurrentResult; + getLastResult(): ApolloQueryResult; + getLastError(): ApolloError; + resetLastResults(): void; + refetch(variables?: V): Promise>; + fetchMore(fetchMoreOptions: {| + ...$Exact>, + ...$Exact>, + |}): Promise>; + subscribeToMore(options: SubscribeToMoreOptions): () => void; + setOptions( + opts: ModifiableWatchQueryOptions + ): Promise>; + setVariables( + variables: V, + tryFetch?: boolean, + fetchResults?: boolean + ): Promise>; + updateQuery( + mapFn: (previousQueryResult: any, options: UpdateQueryOptions) => any + ): void; + stopPolling(): void; + startPolling(pollInterval: number): void; + } + + declare class QueryManager { + scheduler: QueryScheduler; + link: ApolloLink; + mutationStore: MutationStore; + queryStore: QueryStore; + dataStore: DataStore; + constructor({| + link: ApolloLink, + queryDeduplication?: boolean, + store: DataStore, + onBroadcast?: () => void, + ssrMode?: boolean, + |}): this; + mutate(options: MutationOptions): Promise>; + fetchQuery( + queryId: string, + options: WatchQueryOptions, + fetchType?: FetchType, + fetchMoreForQueryId?: string + ): Promise>; + queryListenerForObserver( + queryId: string, + options: WatchQueryOptions, + observer: Observer> + ): QueryListener; + watchQuery( + options: WatchQueryOptions, + shouldSubscribe?: boolean + ): ObservableQuery; + query(options: WatchQueryOptions): Promise>; + generateQueryId(): string; + stopQueryInStore(queryId: string): void; + addQueryListener(queryId: string, listener: QueryListener): void; + updateQueryWatch( + queryId: string, + document: DocumentNode, + options: WatchQueryOptions + ): void; + addFetchQueryPromise( + requestId: number, + promise: Promise>, + resolve: (result: ApolloQueryResult) => void, + reject: (error: Error) => void + ): void; + removeFetchQueryPromise(requestId: number): void; + addObservableQuery( + queryId: string, + observableQuery: ObservableQuery + ): void; + removeObservableQuery(queryId: string): void; + clearStore(): Promise; + resetStore(): Promise[]>; + } + + declare class QueryStore { + getStore(): {| [queryId: string]: QueryStoreValue |}; + get(queryId: string): QueryStoreValue; + initQuery(query: {| + queryId: string, + document: DocumentNode, + storePreviousVariables: boolean, + variables: any, + isPoll: boolean, + isRefetch: boolean, + metadata: any, + fetchMoreForQueryId: string | void, + |}): void; + markQueryResult( + queryId: string, + result: ExecutionResult<>, + fetchMoreForQueryId: string | void + ): void; + markQueryError( + queryId: string, + error: Error, + fetchMoreForQueryId: string | void + ): void; + markQueryResultClient(queryId: string, complete: boolean): void; + stopQuery(queryId: string): void; + reset(observableQueryIds: string[]): void; + } + + declare class QueryScheduler { + inFlightQueries: {| [queryId: string]: WatchQueryOptions |}; + registeredQueries: {| [queryId: string]: WatchQueryOptions |}; + intervalQueries: {| [interval: number]: string[] |}; + queryManager: QueryManager; + constructor({| + queryManager: QueryManager, + ssrMode?: boolean, + |}): this; + checkInFlight(queryId: string): ?boolean; + fetchQuery( + queryId: string, + options: WatchQueryOptions, + fetchType: FetchType + ): Promise>; + startPollingQuery( + options: WatchQueryOptions, + queryId: string, + listener?: QueryListener + ): string; + stopPollingQuery(queryId: string): void; + fetchQueriesOnInterval(interval: number): void; + addQueryOnInterval( + queryId: string, + queryOptions: WatchQueryOptions + ): void; + registerPollingQuery( + queryOptions: WatchQueryOptions + ): ObservableQuery; + markMutationError(mutationId: string, error: Error): void; + reset(): void; + } + + declare class DataStore { + constructor(initialCache: ApolloCache): this; + getCache(): ApolloCache; + markQueryResult( + result: ExecutionResult<>, + document: DocumentNode, + variables: any, + fetchMoreForQueryId: string | void, + ignoreErrors?: boolean + ): void; + markSubscriptionResult( + result: ExecutionResult<>, + document: DocumentNode, + variables: any + ): void; + markMutationInit(mutation: {| + mutationId: string, + document: DocumentNode, + variables: any, + updateQueries: {| [queryId: string]: QueryWithUpdater |}, + update: ((proxy: DataProxy, mutationResult: any) => void) | void, + optimisticResponse: any, + |}): void; + markMutationResult(mutation: {| + mutationId: string, + result: ExecutionResult<>, + document: DocumentNode, + variables: any, + updateQueries: {| [queryId: string]: QueryWithUpdater |}, + update: ((proxy: DataProxy, mutationResult: any) => void) | void, + |}): void; + markMutationComplete({| + mutationId: string, + optimisticResponse?: any, + |}): void; + markUpdateQueryResult( + document: DocumentNode, + variables: any, + newResult: any + ): void; + reset(): Promise; + } + + declare export type QueryWithUpdater = {| + updater: MutationQueryReducer, + query: QueryStoreValue, + |}; + + declare export interface MutationStoreValue { + mutationString: string; + variables: any; + loading: boolean; + error: Error | null; + } + + declare class MutationStore { + getStore(): {| [mutationId: string]: MutationStoreValue |}; + get(mutationId: string): MutationStoreValue; + initMutation( + mutationId: string, + mutationString: string, + variables: any + ): void; + } + + declare export type FetchMoreOptions = { + updateQuery: ( + previousQueryResult: TData, + options: {| + fetchMoreResult?: TData, + variables: TVariables, + |} + ) => TData, + }; + + declare export interface UpdateQueryOptions { + variables?: any; + } + + declare export type ApolloCurrentResult = {| + data: T | {||}, + errors?: Array, + loading: boolean, + networkStatus: NetworkStatus, + error?: ApolloError, + partial?: boolean, + |}; + + declare export type ModifiableWatchQueryOptions = {| + variables?: {| [key: string]: any |}, + pollInterval?: number, + fetchPolicy?: FetchPolicy, + errorPolicy?: ErrorPolicy, + fetchResults?: boolean, + notifyOnNetworkStatusChange?: boolean, + |}; + + declare export type WatchQueryOptions = {| + ...$Exact, + query: DocumentNode, + metadata?: any, + context?: any, + |}; + + declare export type RefetchQueryDescription = Array< + string | PureQueryOptions + >; + + declare export interface MutationBaseOptions< + T = { + [key: string]: any, + ..., + } + > { + optimisticResponse?: any; + updateQueries?: MutationQueryReducersMap; + optimisticResponse?: any; + refetchQueries?: + | ((result: ExecutionResult<>) => RefetchQueryDescription) + | RefetchQueryDescription; + update?: MutationUpdaterFn; + errorPolicy?: ErrorPolicy; + variables?: any; + } + + declare export type FetchPolicy = + | 'cache-first' + | 'cache-and-network' + | 'network-only' + | 'cache-only' + | 'no-cache' + | 'standby'; + + declare export type ErrorPolicy = 'none' | 'ignore' | 'all'; + + declare export type FetchMoreQueryOptions = { + variables: $Shape, + }; + + declare export type SubscribeToMoreOptions< + TData, + TSubscriptionData, + TSubscriptionVariables = void + > = {| + document?: DocumentNode, + variables?: TSubscriptionVariables, + updateQuery?: ( + previousResult: TData, + result: {| + subscriptionData: {| data?: TSubscriptionData |}, + variables: TSubscriptionVariables, + |} + ) => TData, + onError?: (error: Error) => void, + |}; + + declare export type MutationUpdaterFn = ( + proxy: DataProxy, + mutationResult: FetchResult + ) => void; + + declare export type NetworkStatus = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + + declare export type QueryListener = ( + queryStoreValue: QueryStoreValue, + newData?: any + ) => void; + + declare export type QueryStoreValue = {| + document: DocumentNode, + variables: any, + previousVariables: any, + networkStatus: NetworkStatus, + networkError: Error | null, + graphQLErrors: GraphQLError[], + metadata: any, + |}; + + declare export type PureQueryOptions = {| + query: DocumentNode, + variables?: {| [key: string]: any |}, + |}; + + declare export type ApolloQueryResult = {| + data: T, + errors?: Array, + loading: boolean, + networkStatus: NetworkStatus, + stale: boolean, + |}; + + declare export type FetchType = 1 | 2 | 3; + + declare export type MutationQueryReducer = ( + previousResult: {| [key: string]: any |}, + options: {| + mutationResult: FetchResult, + queryName: string | void, + queryVariables: {| [key: string]: any |}, + |} + ) => {| [key: string]: any |}; + + declare export type MutationQueryReducersMap< + T = { + [key: string]: any, + ..., + } + > = {| [queryName: string]: MutationQueryReducer |}; + + declare class $ApolloError extends Error { + message: string; + graphQLErrors: Array; + networkError: Error | null; + extraInfo: any; + constructor(info: ErrorConstructor): this; + } + declare export type ApolloError = $ApolloError; + + declare export interface ErrorConstructor { + graphQLErrors?: Array; + networkError?: Error | null; + errorMessage?: string; + extraInfo?: any; + } + + declare export interface DefaultOptions { + +watchQuery?: ModifiableWatchQueryOptions; + +query?: ModifiableWatchQueryOptions; + +mutate?: MutationBaseOptions<>; + } + + declare export type ApolloClientOptions = {| + link: ApolloLink, + cache: ApolloCache, + ssrMode?: boolean, + ssrForceFetchDelay?: number, + connectToDevTools?: boolean, + queryDeduplication?: boolean, + defaultOptions?: DefaultOptions, + |}; + + declare class ApolloClient { + link: ApolloLink; + store: DataStore; + cache: ApolloCache; + queryManager: QueryManager; + disableNetworkFetches: boolean; + version: string; + queryDeduplication: boolean; + defaultOptions: DefaultOptions; + devToolsHookCb: any; + proxy: ApolloCache | void; + ssrMode: boolean; + resetStoreCallbacks: Array<() => Promise>; + constructor(options: ApolloClientOptions): this; + watchQuery(options: WatchQueryOptions): ObservableQuery; + query(options: WatchQueryOptions): Promise>; + mutate(options: MutationOptions): Promise>; + subscribe(options: SubscriptionOptions): Observable; + readQuery(options: DataProxyReadQueryOptions): T | null; + readFragment( + options: DataProxyReadFragmentOptions + ): TData | null; + writeQuery( + options: DataProxyWriteQueryOptions + ): void; + writeFragment( + options: DataProxyWriteFragmentOptions + ): void; + writeData(options: DataProxyWriteDataOptions): void; + __actionHookForDevTools(cb: () => any): void; + __requestRaw(payload: GraphQLRequest): Observable>; + initQueryManager(): void; + resetStore(): Promise> | null>; + onResetStore(cb: () => Promise): () => void; + reFetchObservableQueries( + includeStandby?: boolean + ): Promise[]> | Promise; + extract(optimistic?: boolean): TCacheShape; + restore(serializedState: TCacheShape): ApolloCache; + } + + /* apollo-link types */ + declare class ApolloLink { + constructor(request?: RequestHandler): this; + static empty(): ApolloLink; + static from(links: Array): ApolloLink; + static split( + test: (op: Operation) => boolean, + left: ApolloLink | RequestHandler, + right: ApolloLink | RequestHandler + ): ApolloLink; + static execute( + link: ApolloLink, + operation: GraphQLRequest + ): Observable>; + split( + test: (op: Operation) => boolean, + left: ApolloLink | RequestHandler, + right: ApolloLink | RequestHandler + ): ApolloLink; + concat(next: ApolloLink | RequestHandler): ApolloLink; + request( + operation: Operation, + forward?: NextLink + ): Observable> | null; + } + + declare export interface GraphQLRequest { + query: DocumentNode; + variables?: {| [key: string]: any |}; + operationName?: string; + context?: {| [key: string]: any |}; + extensions?: {| [key: string]: any |}; + } + + declare export interface Operation { + query: DocumentNode; + variables: {| [key: string]: any |}; + operationName: string; + extensions: {| [key: string]: any |}; + setContext: (context: {| [key: string]: any |}) => {| [key: string]: any |}; + getContext: () => {| [key: string]: any |}; + toKey: () => string; + } + + declare export type FetchResult< + C = {| + [key: string]: any, + |}, + E = {| + [key: string]: any, + |} + > = {| + ...ExecutionResult, + extension?: E, + context?: C, + |}; + + declare export type NextLink = ( + operation: Operation + ) => Observable>; + + declare export type RequestHandler = ( + operation: Operation, + forward?: NextLink + ) => Observable> | null; + + declare class Observable { + subscribe( + observerOrNext: ((value: T) => void) | ZenObservableObserver, + error?: (error: any) => void, + complete?: () => void + ): ZenObservableSubscription; + forEach(fn: (value: T) => void): Promise; + map(fn: (value: T) => R): Observable; + filter(fn: (value: T) => boolean): Observable; + reduce( + fn: (previousValue: R | T, currentValue: T) => R | T, + initialValue?: R | T + ): Observable; + flatMap(fn: (value: T) => ZenObservableObservableLike): Observable; + from( + observable: Observable | ZenObservableObservableLike | Array + ): Observable; + of(...args: Array): Observable; + } + + declare export interface Observer { + start?: (subscription: SubscriptionLINK) => any; + next?: (value: T) => void; + error?: (errorValue: any) => void; + complete?: () => void; + } + + declare export interface SubscriptionLINK { + closed: boolean; + unsubscribe(): void; + } + + declare export interface ZenObservableSubscriptionObserver { + closed: boolean; + next(value: T): void; + error(errorValue: any): void; + complete(): void; + } + + declare export interface ZenObservableSubscription { + closed: boolean; + unsubscribe(): void; + } + + declare export interface ZenObservableObserver { + start?: (subscription: ZenObservableSubscription) => any; + next?: (value: T) => void; + error?: (errorValue: any) => void; + complete?: () => void; + } + + declare export type ZenObservableSubscriber = ( + observer: ZenObservableSubscriptionObserver + ) => void | (() => void) | SubscriptionLINK; + + declare export interface ZenObservableObservableLike { + subscribe?: ZenObservableSubscriber; + } + /* apollo-link types */ + + /* apollo-cache types */ + declare class ApolloCache { + read(query: CacheReadOptions): T | null; + write(write: CacheWriteOptions): void; + diff(query: CacheDiffOptions): CacheDiffResult; + watch(watch: CacheWatchOptions): () => void; + evict(query: CacheEvictOptions): CacheEvictionResult; + reset(): Promise; + restore(serializedState: TSerialized): ApolloCache; + extract(optimistic?: boolean): TSerialized; + removeOptimistic(id: string): void; + performTransaction(transaction: Transaction): void; + recordOptimisticTransaction( + transaction: Transaction, + id: string + ): void; + transformDocument(document: DocumentNode): DocumentNode; + transformForLink(document: DocumentNode): DocumentNode; + readQuery( + options: DataProxyReadQueryOptions, + optimistic?: boolean + ): QueryType | null; + readFragment( + options: DataProxyReadFragmentOptions, + optimistic?: boolean + ): FragmentType | null; + writeQuery( + options: CacheWriteQueryOptions + ): void; + writeFragment( + options: CacheWriteFragmentOptions + ): void; + writeData(options: CacheWriteDataOptions): void; + } + + declare export type Transaction = (c: ApolloCache) => void; + + declare export type CacheWatchCallback = (newData: any) => void; + + declare export interface CacheEvictionResult { + success: boolean; + } + + declare export interface CacheReadOptions + extends DataProxyReadQueryOptions { + rootId?: string; + previousResult?: any; + optimistic: boolean; + } + + declare export interface CacheWriteOptions + extends DataProxyReadQueryOptions { + dataId: string; + result: any; + } + + declare export interface CacheDiffOptions extends CacheReadOptions { + returnPartialData?: boolean; + } + + declare export interface CacheWatchOptions extends CacheReadOptions { + callback: CacheWatchCallback; + } + + declare export interface CacheEvictOptions + extends DataProxyReadQueryOptions { + rootId?: string; + } + + declare export type CacheDiffResult = DataProxyDiffResult; + declare export type CacheWriteQueryOptions< + TData, + TVariables + > = DataProxyWriteQueryOptions; + declare export type CacheWriteFragmentOptions< + TData, + TVariables + > = DataProxyWriteFragmentOptions; + declare export type CacheWriteDataOptions< + TData + > = DataProxyWriteDataOptions; + + declare export interface DataProxyReadQueryOptions { + query: DocumentNode; + variables?: D; + } + + declare export interface DataProxyReadFragmentOptions { + id: string; + fragment: DocumentNode; + fragmentName?: string; + variables?: TVariables; + } + + declare export interface DataProxyWriteQueryOptions { + data: TData; + query: DocumentNode; + variables?: TVariables; + } + + declare export interface DataProxyWriteFragmentOptions { + data: TData; + id: string; + fragment: DocumentNode; + fragmentName?: string; + variables?: TVariables; + } + + declare export interface DataProxyWriteDataOptions { + data: TData; + id?: string; + } + + declare export type DataProxyDiffResult = {| + result?: T, + complete?: boolean, + |}; + + declare export interface DataProxy { + readQuery( + options: DataProxyReadQueryOptions, + optimistic?: boolean + ): QueryType | null; + readFragment( + options: DataProxyReadFragmentOptions, + optimistic?: boolean + ): FragmentType | null; + writeQuery( + options: DataProxyWriteQueryOptions + ): void; + writeFragment( + options: DataProxyWriteFragmentOptions + ): void; + writeData(options: DataProxyWriteDataOptions): void; + } + /* End apollo-cache types */ + /* end apollo-client types */ +} diff --git a/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.201.x-/test_react-hooks_v3.x.x.js b/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.201.x-/test_react-hooks_v3.x.x.js new file mode 100644 index 0000000000..cde25e5fbb --- /dev/null +++ b/definitions/npm/@apollo/react-hooks_v3.x.x/flow_v0.201.x-/test_react-hooks_v3.x.x.js @@ -0,0 +1,143 @@ +// @flow +import * as React from 'react'; +import { it, describe } from 'flow-typed-test'; +import { + useQuery, + useMutation, + useSubscription, + useLazyQuery, + useApolloClient, +} from '@apollo/react-hooks'; + +const gql = (strings, ...args) => {}; // graphql-tag stub + +const query = gql` + { + foo + } +`; +const mutation = gql` + mutation { + foo + } +`; + +type Hero = { + name: string, + id: string, + appearsIn: string[], + friends: Hero[], + ... +}; + +type IQuery = { + foo: string, + bar: string, + ... +}; + +describe('useQuery hook', () => { + type Data = { + a: string, + b: string, + ... + }; + type Variables = { + c: string, + ... + }; + const result = useQuery('test'); + + const { data, loading, error } = result; + it('handles data correctly', () => { + if (data) { + const a: string = data.a; + // $FlowExpectedError + const b: number = data.b; + } + }); + it('handles loading state correctly', () => { + if (error) { + (error.message: string); + (error.graphQLErrors: Array); + // $FlowExpectedError + (error.graphQLErrors: string); + (error.networkError: Error | null); + const extraInfo = error.extraInfo; + } + }); + it('handles error state correctly', () => { + (loading: boolean); + // $FlowExpectedError + (loading: string); + }); +}); + +describe('useMutation hook', () => { + type TData = {| + a: string, + b: string, + |}; + type TVariables = {| + c: string, + |}; + const [mutation, result] = useMutation('test'); + + const { data, loading, error } = result; + it('handles data correctly', () => { + if (data) { + const a: string = data.a; + // $FlowExpectedError + const b: number = data.b; + } + }); + it('handles variables correctly', async () => { + // $FlowExpectedError + const mutationResult = await mutation({ + variables: { + c: 'test', + }, + }); + if (mutationResult.data) { + (mutationResult.data.a: string); + (mutationResult.data.b: string); + (mutationResult.data.b: number); + } + // $FlowExpectedError + mutation('', {}); + // $FlowExpectedError + mutation('', { + variables: { + c: 5, + }, + }); + }); + it('handles loading state correctly', () => { + if (error) { + (error.message: string); + (error.graphQLErrors: Array); + // $FlowExpectedError + (error.graphQLErrors: string); + (error.networkError: Error | null); + const extraInfo = error.extraInfo; + } + }); + it('handles error state correctly', () => { + (loading: boolean); + // $FlowExpectedError + (loading: string); + }); + it('can manually update the cache after a mutation using update on the mutation function', async () => { + const mutationResult = await mutation({ + variables: { + c: 'test' + }, + update: cache => { + cache.readQuery({ query: 'test' }) + cache.readQuery({ query: 'test' }) + // $FlowExpectedError + cache.readQuery({ query: 'test' }) + } + }); + }) +}); diff --git a/definitions/npm/@koa/cors_v3.x.x/flow_v0.53.x-/cors_v3.x.x.js b/definitions/npm/@koa/cors_v3.x.x/flow_v0.201.x-/cors_v3.x.x.js similarity index 100% rename from definitions/npm/@koa/cors_v3.x.x/flow_v0.53.x-/cors_v3.x.x.js rename to definitions/npm/@koa/cors_v3.x.x/flow_v0.201.x-/cors_v3.x.x.js diff --git a/definitions/npm/@koa/cors_v3.x.x/flow_v0.53.x-v0.200.x/cors_v3.x.x.js b/definitions/npm/@koa/cors_v3.x.x/flow_v0.53.x-v0.200.x/cors_v3.x.x.js new file mode 100644 index 0000000000..a176faa585 --- /dev/null +++ b/definitions/npm/@koa/cors_v3.x.x/flow_v0.53.x-v0.200.x/cors_v3.x.x.js @@ -0,0 +1,19 @@ +declare module '@koa/cors' { + declare type Middleware = ( + ctx: any, + next: () => Promise + ) => Promise | void; + declare type Options = $Shape<{| + // TODO better support the "function" use case. + // This is a bit painful to type this object from scratch. + origin: string | ((ctx: any) => string | Promise), + allowMethods: string | string[], + exposeHeaders: string | string[], + allowHeaders: string | string[], + maxAge: string | number, + credentials: boolean, + keepHeadersOnError: boolean, + |}>; + + declare module.exports: (options?: Options) => Middleware; +} diff --git a/definitions/npm/@koa/router_v8.0.x/flow_v0.84.x-/router_v8.0.x.js b/definitions/npm/@koa/router_v8.0.x/flow_v0.201.x-/router_v8.0.x.js similarity index 100% rename from definitions/npm/@koa/router_v8.0.x/flow_v0.84.x-/router_v8.0.x.js rename to definitions/npm/@koa/router_v8.0.x/flow_v0.201.x-/router_v8.0.x.js diff --git a/definitions/npm/@koa/router_v8.0.x/flow_v0.84.x-v0.200.x/router_v8.0.x.js b/definitions/npm/@koa/router_v8.0.x/flow_v0.84.x-v0.200.x/router_v8.0.x.js new file mode 100644 index 0000000000..492286504c --- /dev/null +++ b/definitions/npm/@koa/router_v8.0.x/flow_v0.84.x-v0.200.x/router_v8.0.x.js @@ -0,0 +1,119 @@ +declare module "@koa/router" { + declare type Middleware = ( + ctx: any, + next: () => Promise + ) => Promise | void; + + declare type ParamMiddleware = ( + param: string, + ctx: any, + next: () => Promise + ) => Promise | void; + + declare class Router { + constructor(opts?: $Shape<{| + +prefix: string, + +sensitive: boolean, + +strict: boolean, + +methods: Array, + |}>): Router; + + get( + name: string, + route: string | string[], + handler: Middleware + ): this; + get( + route: string | string[], + ...middleware: Array + ): this; + + patch( + name: string, + route: string | string[], + handler: Middleware + ): this; + patch( + route: string | string[], + ...middleware: Array + ): this; + + post( + name: string, + route: string | string[], + handler: Middleware + ): this; + post( + route: string | string[], + ...middleware: Array + ): this; + + put( + name: string, + route: string | string[], + handler: Middleware + ): this; + put( + route: string | string[], + ...middleware: Array + ): this; + + delete( + name: string, + route: string | string[], + handler: Middleware + ): this; + delete( + route: string | string[], + ...middleware: Array + ): this; + + del( + name: string, + route: string | string[], + handler: Middleware + ): this; + del( + route: string | string[], + ...middleware: Array + ): this; + + all( + name: string, + route: string | string[], + handler: Middleware + ): this; + all( + route: string | string[], + ...middleware: Array + ): this; + + use(...middleware: Array): this; + use( + path: string | Array, + ...middleware: Array + ): this; + + prefix(prefix: string): this; + + routes(): Middleware; + + allowedMethods(options?: $Shape<{| + +throw: boolean, + +notImplemented: () => any, + +methodNotAllowed: () => any, + |}>): Middleware; + + param(param: string, middleware: ParamMiddleware): this; + + redirect(source: string, destination: string, code?: number): this; + + route(name: string): any | false; + + url(name: string, params: { ... }, options?: {| query: { ... } | string |}): string | Error; + + static url(path: string, params: { ... }): string; + } + + declare module.exports: typeof Router; +} diff --git a/definitions/npm/@reach/router_v1.1.x/flow_v0.104.x-/router_v1.1.x.js b/definitions/npm/@reach/router_v1.1.x/flow_v0.104.x-v0.200.x/router_v1.1.x.js similarity index 100% rename from definitions/npm/@reach/router_v1.1.x/flow_v0.104.x-/router_v1.1.x.js rename to definitions/npm/@reach/router_v1.1.x/flow_v0.104.x-v0.200.x/router_v1.1.x.js diff --git a/definitions/npm/@reach/router_v1.1.x/flow_v0.104.x-/test_router_v1.1.x.js b/definitions/npm/@reach/router_v1.1.x/flow_v0.104.x-v0.200.x/test_router_v1.1.x.js similarity index 100% rename from definitions/npm/@reach/router_v1.1.x/flow_v0.104.x-/test_router_v1.1.x.js rename to definitions/npm/@reach/router_v1.1.x/flow_v0.104.x-v0.200.x/test_router_v1.1.x.js diff --git a/definitions/npm/@reach/router_v1.1.x/flow_v0.201.x-/router_v1.1.x.js b/definitions/npm/@reach/router_v1.1.x/flow_v0.201.x-/router_v1.1.x.js new file mode 100644 index 0000000000..aa9a184020 --- /dev/null +++ b/definitions/npm/@reach/router_v1.1.x/flow_v0.201.x-/router_v1.1.x.js @@ -0,0 +1,135 @@ +// @flow + +declare module '@reach/router' { + declare type DomLocation = typeof location & {| state?: any |}; + + declare export type NavigateFn = ( + to: string, + options?: NavigateOptions<{...}> + ) => void; + + declare export var navigate: NavigateFn; + + declare export type HistoryListener = () => void; + + declare export type HistoryUnlistener = () => void; + + declare export interface History { + location: string; + transitioning: boolean; + listen: (listener: HistoryListener) => HistoryUnlistener; + navigate: NavigateFn; + } + + declare export interface HistorySource { + location: DomLocation; + addEventListener(name: string, listener: (event: Event) => void): void; + removeEventListener(name: string, listener: (event: Event) => void): void; + + history: { + state: any, + pushState(state: any, title: string, uri: string): void, + replaceState(state: any, title: string, uri: string): void, + ... + }; + } + + declare export interface NavigateOptions { + state?: State; + replace?: boolean; + } + + declare type CommonRouteProps = {| + children?: React$Node, + location?: DomLocation, + navigate?: NavigateFn, + uri?: string, + |}; + + declare export type DefaultRouteProps = { + ...CommonRouteProps, + default: boolean, + ... + }; + + declare export type RouteProps = { + ...CommonRouteProps, + path: string, + ... + }; + + declare export type LocationProviderRenderFn = (context: {| + location: DomLocation, + navigate: NavigateFn, + |}) => React$Node; + + declare export var Router: React$StatelessFunctionalComponent<{| + children?: React$Node, + basepath?: string, + primary?: boolean, + location?: DomLocation, + |}>; + + declare export type LinkProps = { + ...$Shape, + children: React$Node, + innerRef?: React$Ref, + getProps?: (props: { + isCurrent: boolean, + isPartiallyCurrent: boolean, + href: string, + location: DomLocation, + ... + }) => {...}, + state?: State, + to?: string, + replace?: boolean, + // remove href, as it's ignored by the router + href?: empty, + ... + }; + + declare export var Link: { (props: LinkProps): React$Node, ... }; + + declare export var Redirect: React$StatelessFunctionalComponent<{| + from?: string, + to: string, + noThrow?: boolean, + state?: any + |}>; + + declare export type MatchProps = {| + path: string, + children: (props: {| + match: null | {| uri: string, path: string, ...$Exact |}, + location: DomLocation, + navigate: NavigateFn, + |}) => React$Node, + |}; + + declare export var Match: { (props: MatchProps): React$Node, ... }; + + declare export var Location: React$StatelessFunctionalComponent<{| + children: LocationProviderRenderFn, + |}>; + + declare export class LocationProvider extends React$Component<{| + history: History, + children?: React$Node | LocationProviderRenderFn, + |}> {} + + declare export var ServerLocation: React$StatelessFunctionalComponent<{| + url: string, + children?: React$Node, + |}>; + + declare export function createHistory(source: HistorySource): History; + + declare export function createMemorySource( + initialPath: string + ): HistorySource; + + declare export function isRedirect(error: any): $Exact<{ uri: string, ... }>; + + declare export function redirectTo(uri: string): void; +} diff --git a/definitions/npm/@reach/router_v1.1.x/flow_v0.201.x-/test_router_v1.1.x.js b/definitions/npm/@reach/router_v1.1.x/flow_v0.201.x-/test_router_v1.1.x.js new file mode 100644 index 0000000000..cb986ee09a --- /dev/null +++ b/definitions/npm/@reach/router_v1.1.x/flow_v0.201.x-/test_router_v1.1.x.js @@ -0,0 +1,273 @@ +// @flow +import * as React from 'react'; + +import { + Router, + Link, + Redirect, + Match, + navigate, + Location, + LocationProvider, + ServerLocation, + createHistory, + createMemorySource, + isRedirect, + redirectTo, + type MatchProps, + type LinkProps, +} from '@reach/router'; + +import type { DefaultRouteProps, RouteProps } from '@reach/router'; + +import { it, describe } from 'flow-typed-test'; + +describe('@reach/router', () => { + describe('Router', () => { + it('works', () => { + +
+ ; + }); + + it('raises error', () => { + // $FlowExpectedError - basepath must be a string + ; + // $FlowExpectedError - primary must be a boolean + ; + // $FlowExpectedError - children must be a React$Node + {Array}; + }); + }); + + describe('DefaultRoute', () => { + const DefaultRoute = (props: DefaultRouteProps) =>
; + + it('works', () => { + ; + +
+ ; + }); + + it('raises error', () => { + // $FlowExpectedError - default must be a boolean + ; + // $FlowExpectedError - children must be a React$Node + {Array}; + }); + }); + + describe('Route', () => { + const Route = (props: RouteProps) =>
; + + it('works', () => { + ; + ; + ; + ; + +
+ ; + }); + + it('raises error', () => { + // $FlowExpectedError - path must be a string + ; + // $FlowExpectedError - children must be a React$Node + {Array}; + }); + }); + + describe('Link', () => { + it('works', () => { + +
+ ; + }); + + it('raises error', () => { + // $FlowExpectedError - children must be a React$Node + {Array}; + // $FlowExpectedError - to must be a string + ; + // $FlowExpectedError - href isn't available + ; + }); + }); + + describe('Redirect', () => { + it('works', () => { + ; + ; + ; + ; + }); + + it('raises error', () => { + // $FlowExpectedError - from must be a string + ; + // $FlowExpectedError - to must be a string + ; + // $FlowExpectedError - noThrow must be a boolean + ; + }); + }); + + describe('Match', () => { + it('works', () => { + + {props => + props.match ?
Hot {props.match.item}
:
Uncool
+ } +
; + }); + + it('raises error', () => { + // $FlowExpectedError - children must be a function + +
+ ; + }); + + describe('generic magic', () => { + type Params = { + articleId: string, + commentId: string, + ... + }; + + /* + In the future (https://github.com/facebook/flow/issues/7672) we can use this syntax: + + > + {props => { + if (props.match) { + (props.match.articleId: string); + } + }} + ; + + But now you need to create a wrapper with a type definition: + + */ + const MatchItem = (props: MatchProps) => Match(props); + + it('should define more pure type for match prop', () => { + + {props => { + if (props.match) { + (props.match.articleId: string); + (props.match.commentId: string); + + // $FlowExpectedError - `match` is exact type + (props.match.abc: number); + // $FlowExpectedError - `articleId` prop must be string + (props.match.articleId: boolean); + + return
Cool
; + } + + return
Uncool
; + }} +
; + }); + }); + }); + + describe('navigate', () => { + it('works', () => { + navigate('/'); + navigate('/', { state: {}, redirect: true }); + }); + + it('raises error', () => { + // $FlowExpectedError - first param must be a string + navigate({}); + }); + }); + + describe('Location', () => { + it('works', () => { + {props =>
}; + }); + + it('raises error', () => { + // $FlowExpectedError - children must be a function + +
+ ; + }); + }); + + describe('LocationProvider', () => { + it('works', () => { + const history = createHistory(window); + + +
Alright, we've established some location context
+
; + }); + + it('raises error', () => { + // $FlowExpectedError - history must be an instance of History + +
Alright, we've established some location context
+
; + }); + }); + + describe('ServerLocation', () => { + it('works', () => { + +
+ ; + }); + + it('raises error', () => { + // $FlowExpectedError - url must be a string + +
+ ; + }); + }); + + describe('createHistory', () => { + it('works', () => { + createHistory(window); + }); + + it('raises error', () => { + // $FlowExpectedError - first param must implements HistorySource + createHistory({}); + }); + }); + + describe('createMemorySource', () => { + it('works', () => { + createMemorySource('/starting/url'); + }); + + it('raises error', () => { + // $FlowExpectedError - first param must be a string + createMemorySource({}); + }); + }); + + describe('isRedirect', () => { + it('works', () => { + isRedirect({}); + }); + }); + + describe('redirectTo', () => { + it('works', () => { + redirectTo('/'); + }); + + it('raises error', () => { + // $FlowExpectedError - first param must be a string + redirectTo({}); + }); + }); +}); diff --git a/definitions/npm/@react-navigation/core_v3.x.x/flow_v0.104.x-/core_v3.x.x.js b/definitions/npm/@react-navigation/core_v3.x.x/flow_v0.104.x-v0.200.x/core_v3.x.x.js similarity index 100% rename from definitions/npm/@react-navigation/core_v3.x.x/flow_v0.104.x-/core_v3.x.x.js rename to definitions/npm/@react-navigation/core_v3.x.x/flow_v0.104.x-v0.200.x/core_v3.x.x.js diff --git a/definitions/npm/@react-navigation/core_v3.x.x/flow_v0.201.x-/core_v3.x.x.js b/definitions/npm/@react-navigation/core_v3.x.x/flow_v0.201.x-/core_v3.x.x.js new file mode 100644 index 0000000000..406b7a7ea4 --- /dev/null +++ b/definitions/npm/@react-navigation/core_v3.x.x/flow_v0.201.x-/core_v3.x.x.js @@ -0,0 +1,948 @@ +// @flow + +declare module '@react-navigation/core' { + + //--------------------------------------------------------------------------- + // SECTION 1: IDENTICAL TYPE DEFINITIONS + // This section is identical across all React Navigation libdefs and contains + // shared definitions. We wish we could make it DRY and import from a shared + // definition, but that isn't yet possible. + //--------------------------------------------------------------------------- + + /** + * SECTION 1A + * We start with some definitions that we have copy-pasted from React Native + * source files. + */ + + // This is a bastardization of the true StyleObj type located in + // react-native/Libraries/StyleSheet/StyleSheetTypes. We unfortunately can't + // import that here, and it's too lengthy (and consequently too brittle) to + // copy-paste here either. + declare type StyleObj = + | null + | void + | number + | false + | '' + | $ReadOnlyArray + | { [name: string]: any, ... }; + declare type ViewStyleProp = StyleObj; + declare type TextStyleProp = StyleObj; + declare type AnimatedViewStyleProp = StyleObj; + declare type AnimatedTextStyleProp = StyleObj; + + /** + * SECTION 1B + * The following are type declarations for core types necessary for every + * React Navigation libdef. + */ + + /** + * Navigation State + Action + */ + + declare export type NavigationParams = { [key: string]: mixed, ... }; + + declare export type NavigationBackAction = {| + type: 'Navigation/BACK', + key?: ?string, + |}; + declare export type NavigationInitAction = {| + type: 'Navigation/INIT', + params?: NavigationParams, + |}; + declare export type NavigationNavigateAction = {| + type: 'Navigation/NAVIGATE', + routeName: string, + params?: NavigationParams, + + // The action to run inside the sub-router + action?: NavigationNavigateAction, + + key?: string, + |}; + declare export type NavigationSetParamsAction = {| + type: 'Navigation/SET_PARAMS', + + // The key of the route where the params should be set + key: string, + + // The new params to merge into the existing route params + params: NavigationParams, + |}; + + declare export type NavigationPopAction = {| + +type: 'Navigation/POP', + +n?: number, + +immediate?: boolean, + |}; + declare export type NavigationPopToTopAction = {| + +type: 'Navigation/POP_TO_TOP', + +immediate?: boolean, + +key?: string, + |}; + declare export type NavigationPushAction = {| + +type: 'Navigation/PUSH', + +routeName: string, + +params?: NavigationParams, + +action?: NavigationNavigateAction, + +key?: string, + |}; + declare export type NavigationResetAction = {| + type: 'Navigation/RESET', + index: number, + key?: ?string, + actions: Array, + |}; + declare export type NavigationReplaceAction = {| + +type: 'Navigation/REPLACE', + +key: string, + +routeName: string, + +params?: NavigationParams, + +action?: NavigationNavigateAction, + |}; + declare export type NavigationCompleteTransitionAction = {| + +type: 'Navigation/COMPLETE_TRANSITION', + +key?: string, + +toChildKey?: string, + |}; + + declare export type NavigationOpenDrawerAction = {| + +type: 'Navigation/OPEN_DRAWER', + +key?: string, + |}; + declare export type NavigationCloseDrawerAction = {| + +type: 'Navigation/CLOSE_DRAWER', + +key?: string, + |}; + declare export type NavigationToggleDrawerAction = {| + +type: 'Navigation/TOGGLE_DRAWER', + +key?: string, + |}; + declare export type NavigationDrawerOpenedAction = {| + +type: 'Navigation/DRAWER_OPENED', + +key?: string, + |}; + declare export type NavigationDrawerClosedAction = {| + +type: 'Navigation/DRAWER_CLOSED', + +key?: string, + |}; + + declare export type NavigationJumpToAction = {| + +type: 'Navigation/JUMP_TO'; + +preserveFocus: boolean, + +routeName: string, + +key?: string, + +params?: NavigationParams, + |}; + + declare export type NavigationAction = + | NavigationBackAction + | NavigationInitAction + | NavigationNavigateAction + | NavigationSetParamsAction + | NavigationPopAction + | NavigationPopToTopAction + | NavigationPushAction + | NavigationResetAction + | NavigationReplaceAction + | NavigationCompleteTransitionAction + | NavigationOpenDrawerAction + | NavigationCloseDrawerAction + | NavigationToggleDrawerAction + | NavigationDrawerOpenedAction + | NavigationDrawerClosedAction + | NavigationJumpToAction; + + /** + * NavigationState is a tree of routes for a single navigator, where each + * child route may either be a NavigationScreenRoute or a + * NavigationRouterRoute. NavigationScreenRoute represents a leaf screen, + * while the NavigationRouterRoute represents the state of a child navigator. + * + * NOTE: NavigationState is a state tree local to a single navigator and + * its child navigators (via the routes field). + * If we're in navigator nested deep inside the app, the state will only be + * the state for that navigator. + * The state for the root navigator of our app represents the whole navigation + * state for the whole app. + */ + declare export type NavigationState = { + /** + * Index refers to the active child route in the routes array. + */ + index: number, + routes: Array, + isTransitioning?: bool, + ... + }; + + declare export type NavigationRoute = + | NavigationLeafRoute + | NavigationStateRoute; + + declare export type NavigationLeafRoute = {| + /** + * React's key used by some navigators. No need to specify these manually, + * they will be defined by the router. + */ + key: string, + /** + * For example 'Home'. + * This is used as a key in a route config when creating a navigator. + */ + routeName: string, + /** + * Path is an advanced feature used for deep linking and on the web. + */ + path?: string, + /** + * Params passed to this route when navigating to it, + * e.g. `{ car_id: 123 }` in a route that displays a car. + */ + params?: NavigationParams, + |}; + + declare export type NavigationStateRoute = {| + ...NavigationLeafRoute, + ...$Exact, + |}; + + /** + * Router + */ + + declare export type NavigationScreenProps = { [key: string]: mixed, ... }; + + declare export type NavigationScreenOptionsGetter = ( + navigation: NavigationScreenProp, + screenProps: ?NavigationScreenProps, + theme: SupportedThemes, + ) => Options; + + declare export type NavigationRouter = { + /** + * The reducer that outputs the new navigation state for a given action, + * with an optional previous state. When the action is considered handled + * but the state is unchanged, the output state is null. + */ + getStateForAction: (action: NavigationAction, lastState: ?State) => ?State, + /** + * Maps a URI-like string to an action. This can be mapped to a state + * using `getStateForAction`. + */ + getActionForPathAndParams: ( + path: string, + params?: NavigationParams + ) => ?NavigationAction, + getPathAndParamsForState: ( + state: State + ) => { + path: string, + params?: NavigationParams, + ... + }, + getComponentForRouteName: (routeName: string) => NavigationComponent, + getComponentForState: (state: State) => NavigationComponent, + /** + * Gets the screen navigation options for a given screen. + * + * For example, we could get the config for the 'Foo' screen when the + * `navigation.state` is: + * + * {routeName: 'Foo', key: '123'} + */ + getScreenOptions: NavigationScreenOptionsGetter, + ... + }; + + declare export type NavigationScreenOptions = { title?: string, ... }; + + declare export type SupportedThemes = 'light' | 'dark'; + + declare export type NavigationScreenConfigProps = $Shape<{| + navigation: NavigationScreenProp, + screenProps: NavigationScreenProps, + theme: SupportedThemes, + |}>; + + declare export type NavigationScreenConfig = + | Options + | (({| + ...NavigationScreenConfigProps, + navigationOptions: Options, + |}) => Options); + + declare export type NavigationComponent = + | NavigationScreenComponent + | NavigationNavigator; + + declare interface withOptionalNavigationOptions { + navigationOptions?: NavigationScreenConfig; + } + + declare export type NavigationScreenComponent< + Route: NavigationRoute, + Options: {...}, + Props: NavigationNavigatorProps, + > = React$ComponentType & + withOptionalNavigationOptions; + + declare interface withRouter { + router: NavigationRouter; + } + + declare export type NavigationNavigator< + State: NavigationState, + Options: {...}, + Props: NavigationNavigatorProps, + > = React$ComponentType & + withRouter & + withOptionalNavigationOptions; + + declare type _NavigationRouteConfigCore = {| + navigationOptions?: NavigationScreenConfig, + params?: NavigationParams, + path?: string, + |}; + declare export type NavigationRouteConfig = + | NavigationComponent + | {| ..._NavigationRouteConfigCore, screen: NavigationComponent |} + | {| ..._NavigationRouteConfigCore, getScreen: () => NavigationComponent |}; + + declare export type NavigationRouteConfigMap = { [routeName: string]: NavigationRouteConfig, ... }; + + /** + * Navigator Prop + */ + + declare export type NavigationDispatch = ( + action: NavigationAction + ) => boolean; + + declare export type EventType = + | 'willFocus' + | 'didFocus' + | 'willBlur' + | 'didBlur' + | 'action'; + + declare export type NavigationEventPayload = {| + type: EventType, + action: NavigationAction, + state: NavigationState, + lastState: ?NavigationState, + |}; + + declare export type NavigationEventCallback = ( + payload: NavigationEventPayload + ) => void; + + declare export type NavigationEventSubscription = {| remove: () => void |}; + + declare export type NavigationScreenProp<+S> = { + +state: S, + dispatch: NavigationDispatch, + addListener: ( + eventName: string, + callback: NavigationEventCallback + ) => NavigationEventSubscription, + getParam: ( + paramName: ParamName, + fallback?: $ElementType< + $PropertyType< + {| + ...{| params: {...} |}, + ...$Exact, + |}, + 'params' + >, + ParamName + > + ) => $ElementType< + $PropertyType< + {| + ...{| params: {...} |}, + ...$Exact, + |}, + 'params' + >, + ParamName + >, + dangerouslyGetParent: () => ?NavigationScreenProp, + isFocused: () => boolean, + goBack: (routeKey?: ?string) => boolean, + dismiss: () => boolean, + navigate: ( + routeName: + | string + | { + routeName: string, + params?: NavigationParams, + action?: NavigationNavigateAction, + key?: string, + ... + }, + params?: NavigationParams, + action?: NavigationNavigateAction + ) => boolean, + setParams: (newParams: NavigationParams) => boolean, + ... + }; + + declare export type NavigationNavigatorProps = $Shape<{ + navigation: NavigationScreenProp, + screenProps?: NavigationScreenProps, + navigationOptions?: O, + theme?: SupportedThemes | 'no-preference', + detached?: boolean, + ... + }>; + + /** + * Navigation container + */ + + declare export type NavigationContainer< + State: NavigationState, + Options: {...}, + Props: NavigationContainerProps, + > = React$ComponentType & + withRouter & + withOptionalNavigationOptions; + + declare export type NavigationContainerProps = $Shape<{ + uriPrefix?: string | RegExp, + onNavigationStateChange?: ?( + NavigationState, + NavigationState, + NavigationAction + ) => void, + navigation?: NavigationScreenProp, + persistenceKey?: ?string, + renderLoadingExperimental?: React$ComponentType<{...}>, + screenProps?: NavigationScreenProps, + navigationOptions?: O, + ... + }>; + + /** + * NavigationDescriptor + */ + + declare export type NavigationDescriptor = { + key: string, + state: NavigationRoute, + navigation: NavigationScreenProp, + getComponent: () => NavigationComponent, + ... + }; + + declare export type NavigationDescriptorMap = { + [key: string]: NavigationDescriptor, + ... + }; + + //--------------------------------------------------------------------------- + // SECTION 2: SHARED TYPE DEFINITIONS + // This section too is copy-pasted, but it's not identical across all React + // Navigation libdefs. We pick out bits and pieces that we need. + //--------------------------------------------------------------------------- + + /** + * SECTION 2A + * We start with definitions we have copy-pasted, either from in-package + * types, other Flow libdefs, or from TypeScript types somewhere. + */ + + // This is copied from + // react-native/Libraries/Animated/src/nodes/AnimatedInterpolation.js + declare type ExtrapolateType = 'extend' | 'identity' | 'clamp'; + declare type InterpolationConfigType = { + inputRange: Array, + outputRange: Array | Array, + easing?: (input: number) => number, + extrapolate?: ExtrapolateType, + extrapolateLeft?: ExtrapolateType, + extrapolateRight?: ExtrapolateType, + ... + }; + declare class AnimatedInterpolation { + interpolate(config: InterpolationConfigType): AnimatedInterpolation; + } + + // This is copied from + // react-native/Libraries/Animated/src/animations/Animation.js + declare type EndResult = { finished: boolean, ... }; + declare type EndCallback = (result: EndResult) => void; + declare class Animation { + start( + fromValue: number, + onUpdate: (value: number) => void, + onEnd: ?EndCallback, + previousAnimation: ?Animation, + animatedValue: AnimatedValue, + ): void; + stop(): void; + } + + // This is vaguely copied from + // react-native/Libraries/Animated/src/nodes/AnimatedTracking.js + declare class AnimatedTracking { + constructor( + value: AnimatedValue, + parent: any, + animationClass: any, + animationConfig: Object, + callback?: ?EndCallback, + ): void; + update(): void; + } + + // This is vaguely copied from + // react-native/Libraries/Animated/src/nodes/AnimatedValue.js + declare type ValueListenerCallback = (state: { value: number, ... }) => void; + declare class AnimatedValue { + constructor(value: number): void; + setValue(value: number): void; + setOffset(offset: number): void; + flattenOffset(): void; + extractOffset(): void; + addListener(callback: ValueListenerCallback): string; + removeListener(id: string): void; + removeAllListeners(): void; + stopAnimation(callback?: ?(value: number) => void): void; + resetAnimation(callback?: ?(value: number) => void): void; + interpolate(config: InterpolationConfigType): AnimatedInterpolation; + animate(animation: Animation, callback: ?EndCallback): void; + stopTracking(): void; + track(tracking: AnimatedTracking): void; + } + + /** + * SECTION 2B + * The following are the actually useful definitions in Section 2, that are + * used below in section 3, but also in other libdefs. + */ + + declare export type NavigationPathsConfig = { [routeName: string]: string, ... }; + + /** + * SafeAreaView + */ + + declare type _SafeAreaViewForceInsetValue = 'always' | 'never' | number; + declare type _SafeAreaViewInsets = $Shape<{| + top: _SafeAreaViewForceInsetValue, + bottom: _SafeAreaViewForceInsetValue, + left: _SafeAreaViewForceInsetValue, + right: _SafeAreaViewForceInsetValue, + vertical: _SafeAreaViewForceInsetValue, + horizontal: _SafeAreaViewForceInsetValue, + |}>; + + /** + * Interpolation + */ + + declare export type NavigationStackInterpolatorProps = $Shape<{| + layout: NavigationStackLayout, + scene: NavigationStackScene, + scenes: NavigationStackScene[], + position: AnimatedInterpolation, + navigation: NavigationStackProp, + mode?: HeaderMode, + shadowEnabled?: boolean, + cardOverlayEnabled?: boolean, + |}>; + + declare type _InterpolationResult = { [key: string]: mixed, ... }; + declare export type NavigationStackInterpolator = + (props: NavigationStackInterpolatorProps) => _InterpolationResult; + + /** + * Header + */ + + declare export type HeaderMode = 'float' | 'screen' | 'none'; + + declare export type HeaderProps = {| + layout: NavigationStackLayout, + scene: NavigationStackScene, + scenes: NavigationStackScene[], + position: AnimatedInterpolation, + navigation: NavigationStackProp, + mode: HeaderMode, + leftInterpolator?: NavigationStackInterpolator, + titleInterpolator?: NavigationStackInterpolator, + rightInterpolator?: NavigationStackInterpolator, + backgroundInterpolator?: NavigationStackInterpolator, + layoutPreset: 'left' | 'center', + transitionPreset?: 'fade-in-place' | 'uikit', + backTitleVisible?: boolean, + isLandscape: boolean, + |}; + + /** + * StackRouter + */ + + declare export type NavigationStackProp<+S> = + & NavigationScreenProp + & { + pop: (n?: number, params?: {| immediate?: boolean |}) => boolean, + popToTop: (params?: {| immediate?: boolean |}) => boolean, + push: ( + routeName: string, + params?: NavigationParams, + action?: NavigationNavigateAction + ) => boolean, + replace: ( + routeName: string, + params?: NavigationParams, + action?: NavigationNavigateAction + ) => boolean, + reset: (actions: NavigationAction[], index: number) => boolean, + ... + }; + + declare type _HeaderBackButtonProps = {| + disabled?: boolean, + onPress: () => void, + pressColorAndroid?: string, + tintColor?: ?string, + backImage?: React$ComponentType<{ + tintColor: string, + title?: ?string, + ... + }>, + title?: ?string, + truncatedTitle?: ?string, + backTitleVisible?: boolean, + allowFontScaling?: boolean, + titleStyle?: ?TextStyleProp, + headerLayoutPreset: 'left' | 'center', + width?: ?number, + scene: NavigationStackScene, + |}; + + declare export type NavigationStackScreenOptions = NavigationScreenOptions & { + header?: ?(React$Node | (HeaderProps => React$Node)), + headerTransparent?: boolean, + headerTitle?: (props: { children: ?string, ... }) => React$Node | React$Node, + headerTitleStyle?: AnimatedTextStyleProp, + headerTitleAllowFontScaling?: boolean, + headerTintColor?: string, + headerLeft?: ((props: _HeaderBackButtonProps) => React$Node) | React$Node, + headerBackTitle?: ?string, + headerBackImage?: (props: {| + tintColor?: string, + title?: ?string, + |}) => React$Node, + headerTruncatedBackTitle?: string, + headerBackTitleStyle?: TextStyleProp, + headerPressColorAndroid?: string, + headerRight?: React$Node, + headerStyle?: ViewStyleProp, + headerForceInset?: _SafeAreaViewInsets, + headerBackground?: React$Node | React$ElementType, + gesturesEnabled?: boolean, + gestureResponseDistance?: {| + vertical?: number, + horizontal?: number, + |}, + gestureDirection?: 'default' | 'inverted', + ... + }; + + declare export type NavigationStackRouterConfig = {| + initialRouteName?: string, + initialRouteParams?: NavigationParams, + paths?: NavigationPathsConfig, + navigationOptions?: NavigationScreenConfig, + defaultNavigationOptions?: NavigationScreenConfig, + initialRouteKey?: string, + |}; + + /** + * Stack Gestures, Animations, and Interpolators + */ + + declare export type NavigationStackLayout = { + height: AnimatedValue, + initHeight: number, + initWidth: number, + isMeasured: boolean, + width: AnimatedValue, + ... + }; + + declare export type NavigationStackScene = { + index: number, + isActive: boolean, + isStale: boolean, + key: string, + route: NavigationRoute, + descriptor: ?NavigationDescriptor, + ... + }; + + /** + * SwitchRouter + */ + + declare export type NavigationSwitchRouterConfig = {| + initialRouteName?: string, + initialRouteParams?: NavigationParams, + paths?: NavigationPathsConfig, + navigationOptions?: NavigationScreenConfig, + defaultNavigationOptions?: NavigationScreenConfig, + // todo: type these as the real route names rather than 'string' + order?: string[], + // Does the back button cause the router to switch to the initial tab + backBehavior?: 'none' | 'initialRoute' | 'history' | 'order', // defaults `initialRoute` + resetOnBlur?: boolean, + |}; + + /** + * TabRouter + */ + + declare export type NavigationTabProp<+S> = + & NavigationScreenProp + & { jumpTo: (routeName: string, key?: string) => void, ... }; + + declare export type NavigationTabRouterConfig = NavigationSwitchRouterConfig; + + declare export type NavigationTabScreenOptions = { + ...$Exact, + tabBarLabel?: React$Node, + tabBarVisible?: boolean, + tabBarAccessibilityLabel?: string, + tabBarTestID?: string, + tabBarIcon?: + | React$Node + | ((props: {| + focused: boolean, + tintColor?: string, + horizontal?: boolean, + |}) => React$Node), + tabBarOnPress?: (props: {| + navigation: NavigationTabProp, + defaultHandler: () => void, + |}) => void, + tabBarOnLongPress?: (props: {| + navigation: NavigationTabProp, + defaultHandler: () => void, + |}) => void, + ... + }; + + //--------------------------------------------------------------------------- + // SECTION 3: UNIQUE TYPE DEFINITIONS + // This section normally contains exported types that are not present in any + // other React Navigation libdef. But the main react-navigation libdef doesn't + // have any, so it's empty here. + //--------------------------------------------------------------------------- + + //--------------------------------------------------------------------------- + // SECTION 4: EXPORTED MODULE + // This is the only section that types exports. Other sections export types, + // but this section types the module's exports. + //--------------------------------------------------------------------------- + + declare export var StateUtils: { + get: (state: NavigationState, key: string) => ?NavigationRoute, + indexOf: (state: NavigationState, key: string) => number, + has: (state: NavigationState, key: string) => boolean, + push: (state: NavigationState, route: NavigationRoute) => NavigationState, + pop: (state: NavigationState) => NavigationState, + jumpToIndex: (state: NavigationState, index: number) => NavigationState, + jumpTo: (state: NavigationState, key: string) => NavigationState, + back: (state: NavigationState) => NavigationState, + forward: (state: NavigationState) => NavigationState, + replaceAt: ( + state: NavigationState, + key: string, + route: NavigationRoute + ) => NavigationState, + replaceAtIndex: ( + state: NavigationState, + index: number, + route: NavigationRoute + ) => NavigationState, + reset: ( + state: NavigationState, + routes: Array, + index?: number + ) => NavigationState, + ... + }; + + declare export function getNavigation( + router: NavigationRouter, + state: State, + dispatch: NavigationDispatch, + actionSubscribers: Set, + getScreenProps: () => {...}, + getCurrentNavigation: () => ?NavigationScreenProp + ): NavigationScreenProp; + + declare type _NavigationView> = React$ComponentType<{ + descriptors: NavigationDescriptorMap, + navigation: N, + navigationConfig: any, + ... + }>; + declare export function createNavigator>( + view: _NavigationView, + router: NavigationRouter, + navigatorConfig?: NavigatorConfig + ): NavigationNavigator; + + declare export var NavigationContext: React$Context< + ?NavigationScreenProp, + >; + declare export var NavigationProvider: $PropertyType; + declare export var NavigationConsumer: $PropertyType; + + declare type _SwitchNavigatorConfig = NavigationSwitchRouterConfig; + declare export function createSwitchNavigator( + routeConfigs: NavigationRouteConfigMap, + config?: _SwitchNavigatorConfig + ): NavigationNavigator; + + declare export var ThemeContext: React$Context; + declare export var ThemeProvider: $PropertyType; + declare export var ThemeConsumer: $PropertyType; + declare export var ThemeColors: { [theme: SupportedThemes]: { [key: string]: string, ... }, ... }; + declare export function useTheme(): SupportedThemes; + + declare export var NavigationActions: {| + BACK: 'Navigation/BACK', + INIT: 'Navigation/INIT', + NAVIGATE: 'Navigation/NAVIGATE', + SET_PARAMS: 'Navigation/SET_PARAMS', + back: (payload?: {| key?: ?string |}) => NavigationBackAction, + init: (payload?: {| params?: NavigationParams |}) => NavigationInitAction, + navigate: (payload: {| + routeName: string, + params?: ?NavigationParams, + action?: ?NavigationNavigateAction, + key?: string, + |}) => NavigationNavigateAction, + setParams: (payload: {| + key: string, + params: NavigationParams, + |}) => NavigationSetParamsAction, + |}; + + declare export var StackActions: {| + POP: 'Navigation/POP', + POP_TO_TOP: 'Navigation/POP_TO_TOP', + PUSH: 'Navigation/PUSH', + RESET: 'Navigation/RESET', + REPLACE: 'Navigation/REPLACE', + COMPLETE_TRANSITION: 'Navigation/COMPLETE_TRANSITION', + pop: (payload: {| + n?: number, + immediate?: boolean, + |}) => NavigationPopAction, + popToTop: (payload: {| + immediate?: boolean, + key?: string, + |}) => NavigationPopToTopAction, + push: (payload: {| + routeName: string, + params?: NavigationParams, + action?: NavigationNavigateAction, + key?: string, + |}) => NavigationPushAction, + reset: (payload: {| + index: number, + key?: ?string, + actions: Array, + |}) => NavigationResetAction, + replace: (payload: {| + key?: string, + routeName: string, + params?: NavigationParams, + action?: NavigationNavigateAction, + |}) => NavigationReplaceAction, + completeTransition: (payload: {| + key?: string, + toChildKey?: string, + |}) => NavigationCompleteTransitionAction, + |}; + + declare export var SwitchActions: {| + JUMP_TO: 'Navigation/JUMP_TO', + jumpTo: (payload: {| + routeName: string, + key?: string, + params?: NavigationParams, + |}) => NavigationJumpToAction, + |}; + + declare export function StackRouter( + routeConfigs: NavigationRouteConfigMap, + stackConfig?: NavigationStackRouterConfig + ): NavigationRouter; + + declare export function TabRouter( + routeConfigs: NavigationRouteConfigMap, + config?: NavigationTabRouterConfig + ): NavigationRouter; + + declare export function SwitchRouter( + routeConfigs: NavigationRouteConfigMap, + stackConfig?: NavigationSwitchRouterConfig + ): NavigationRouter; + + declare export function getActiveChildNavigationOptions< + State: NavigationState, + Options: {...} + >( + navigation: NavigationScreenProp, + screenProps?: NavigationScreenProps, + theme?: SupportedThemes, + ): Options; + + declare type _SceneViewProps = { + component: React$ComponentType<{ + screenProps: ?NavigationScreenProps, + navigation: NavigationScreenProp, + ... + }>, + screenProps: ?NavigationScreenProps, + navigation: NavigationScreenProp, + ... + }; + declare export var SceneView: React$ComponentType<_SceneViewProps>; + + declare type _NavigationEventsProps = { + navigation?: NavigationScreenProp, + onWillFocus?: NavigationEventCallback, + onDidFocus?: NavigationEventCallback, + onWillBlur?: NavigationEventCallback, + onDidBlur?: NavigationEventCallback, + ... + }; + declare export var NavigationEvents: React$ComponentType< + _NavigationEventsProps + >; + + declare export function withNavigation>( + Component: ComponentType + ): React$ComponentType< + $Diff< + React$ElementConfig, + {| navigation: NavigationScreenProp |} + > + >; + declare export function withNavigationFocus>( + Component: ComponentType + ): React$ComponentType<$Diff, {| isFocused: ?boolean |}>>; + +} diff --git a/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.104.x-/react-ui_v1.x.x.js b/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.104.x-v0.200.x/react-ui_v1.x.x.js similarity index 100% rename from definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.104.x-/react-ui_v1.x.x.js rename to definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.104.x-v0.200.x/react-ui_v1.x.x.js diff --git a/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.104.x-/test_react-ui_v1.x.x.js b/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.104.x-v0.200.x/test_react-ui_v1.x.x.js similarity index 100% rename from definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.104.x-/test_react-ui_v1.x.x.js rename to definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.104.x-v0.200.x/test_react-ui_v1.x.x.js diff --git a/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.201.x-/react-ui_v1.x.x.js b/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.201.x-/react-ui_v1.x.x.js new file mode 100644 index 0000000000..40a7384481 --- /dev/null +++ b/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.201.x-/react-ui_v1.x.x.js @@ -0,0 +1,2835 @@ +/* @flow */ +/* eslint-disable max-len */ + +type InputEventHandler = (event: SyntheticInputEvent) => void; + +type FocusEventHandler = (event: SyntheticFocusEvent) => void; + +type MouseEventHandler = (event: SyntheticMouseEvent) => void; + +type KeyboardEventHandler = ( + event: SyntheticKeyboardEvent, +) => void; + +type InputSize = 'small' | 'medium' | 'large'; +type InputAlign = 'left' | 'center' | 'right'; +type InputType = 'password' | 'text'; +type IconType = React$Node | (() => React$Node); + +type AnyObject = { + +[key: string]: T, + ..., +}; + +type _Theme = AnyObject; + +type _InputProps = { + leftIcon?: IconType, + rightIcon?: IconType, + error?: boolean, + warning?: boolean, + borderless?: boolean, + align?: InputAlign, + mask?: ?string, + maskChar?: ?string, + formatChars?: AnyObject, + alwaysShowMask?: boolean, + size?: InputSize, + onChange?: ( + event: SyntheticKeyboardEvent, + value: string, + ) => void, + onMouseEnter?: MouseEventHandler, + onMouseLeave?: MouseEventHandler, + onMouseOver?: MouseEventHandler, + type?: InputType, + value?: string, + capture?: boolean, + prefix?: React$Node, + suffix?: React$Node, + mainInGroup?: boolean, + selectAllOnFocus?: boolean, + onUnexpectedInput?: () => void, + ... +}; + +type _MenuItemState = null | 'hover' | 'selected' | void; + +declare class _MenuItem extends React$Component<_MenuItemProps> { + static __MENU_ITEM__: boolean; + static __MENU_HEADER__: boolean; +} + +type _InputVisibilityState = {| + blinking: boolean, + focused: boolean, +|}; + +type _InputState = {| + ...$Exact<_InputVisibilityState>, + polyfillPlaceholder: boolean, +|}; + +type Style = AnyObject; + +declare class _Input extends React$Component<_InputProps, _InputState> { + focus(): void; + blur(): void; + blink(): void; + setSelectionRange(start: number, end: number): void; + selectAll: () => void; +} + +type _MenuProps = {| + children: React$Node, + hasShadow?: boolean, + maxHeight?: number | string, + onItemClick?: () => void, + width?: number | string, + preventWindowScroll?: boolean, +|}; + +type _MenuState = {| + highlightedIndex: number, +|}; + +declare class _Menu extends React$Component<_MenuProps, _MenuState> { + up(): void; + down(): void; + enter(event: SyntheticEvent): boolean; + reset(): void; + highlightItem(index: number): void; +} + +type InputLikeTextProps = {| + ...$Exact<_InputProps>, + children?: React$Node, + innerRef?: (el: HTMLElement | null) => void, + onFocus?: FocusEventHandler, + onBlur?: FocusEventHandler, +|}; + +type InputLikeTextState = {| + ...$Exact<_InputVisibilityState>, +|}; + +declare class _InputLikeText extends React$Component< + InputLikeTextProps, + InputLikeTextState, +> { + focus(): void; + blur(): void; + blink(): void; +} + +type _CalendarDateShape = {| + year: number, + month: number, + date: number, +|}; + +declare class _MenuHeader extends React$Component<_MenuHeaderProps> { + static __MENU_HEADER__: boolean; +} + +type MenuSeparatorProps = {||}; + +declare class _MenuSeparator extends React$Component {} + +type _ButtonSize = 'small' | 'medium' | 'large'; +type _ButtonType = 'button' | 'submit' | 'reset'; +type _ButtonArrow = boolean | 'left'; +type _ButtonUse = 'default' | 'primary' | 'success' | 'danger' | 'pay' | 'link'; + +type _PopupMenuCaptionProps = {| + opened: boolean, + openMenu: (firstItemShouldBeSelected?: boolean) => void, + closeMenu: (restoreFocus?: boolean) => void, + toggleMenu: () => void, +|}; + +type _PopupMenuProps = {| + children?: React$Node, + menuMaxHeight?: number | string, + menuWidth?: number | string, + caption: React$Node | ((props: _PopupMenuCaptionProps) => React$Node), + positions?: $ReadOnlyArray, + onChangeMenuState?: (isOpened: boolean, restoreFocus: boolean) => void, + popupHasPin?: boolean, + popupMargin?: number, + popupPinOffset?: number, + type?: 'dropdown' | 'tooltip', + disableAnimations: boolean, +|}; + +type _PopupPosition = + | 'top left' + | 'top center' + | 'top right' + | 'right top' + | 'right middle' + | 'right bottom' + | 'bottom left' + | 'bottom center' + | 'bottom right' + | 'left top' + | 'left middle' + | 'left bottom'; + +type _SyntheticRadioEvent = {| + target: {| + id: ?string, + name: ?string, + checked: ?boolean, + disabled: ?boolean, + value: T, + |}, +|}; + +type _TokenColorName = string; + +type _TokenColors = {| + idle: _TokenColorName, + active?: _TokenColorName, +|}; + +type _TokenProps = {| + colors?: _TokenColors, + isActive?: boolean, + error?: boolean, + warning?: boolean, +|}; + +type _MenuHeaderProps = {| + children: React$Node, + _enableIconPadding?: ?boolean, +|}; + +type _MenuItemProps = {| + _enableIconPadding?: boolean, + alkoLink?: boolean, + comment?: React$Node, + disabled?: boolean, + // eslint-disable-next-line flowtype/no-weak-types + icon?: React$Element, + loose?: boolean, + state?: _MenuItemState, + onClick?: MouseEventHandler, + children?: React$Node | ((state: _MenuItemState) => React$Node), + target?: string, + title?: string, + href?: string, + onMouseEnter?: MouseEventHandler, + onMouseLeave?: MouseEventHandler, + // eslint-disable-next-line flowtype/no-weak-types + component?: React$ComponentType, +|}; + +type _CurrencyInputState = {| + formatted: string, + selection: Selection, + focused: boolean, +|}; + +declare class _CurrencyInput extends React$Component< + _CurrencyInputProps, + _CurrencyInputState, +> { + focus: () => void; + blur: () => void; +} + +type _CurrencyInputProps = { + value: ?number, + fractionDigits?: ?number, + signed?: boolean, + onChange: ( + e: { + target: {| + value: ?number, + |}, + ... + }, + value: ?number, + ) => void, + onSubmit?: () => void, + ... +}; + +type _SpinnerType = 'mini' | 'normal' | 'big'; + +type _SpinnerProps = {| + caption?: React$Node, + dimmed?: boolean, + type?: _SpinnerType, +|}; + +type _MAP = {| + circle: string, + baseline: string, + warning: string, + ok: string, + gear: string, + user: string, + wait: string, + clear: string, + grid: string, + money: string, + 'help-circle': string, + kebab: string, +|}; + +type _IconProps = {| + name: $Keys<_MAP>, + color: string, +|}; + +type _ComboBoxItem = {| + value: string | number, + label: string, +|}; + +type _FiasLocale = {| + modalTitle: string, + modalButtonOk: string, + modalButtonCancel: string, + + addressFill: string, + addressEdit: string, + addressNotVerified: string, + addressNotFound: string, + addressFillParentOrSearch: string, + addressSelectItemFromList: string, + + searchNotFound: string, + searchPlaceholder: string, + + regionLabel: string, + regionNotFound: string, + regionPlaceholder: string, + + districtLabel: string, + districtNotFound: string, + districtPlaceholder: string, + + cityLabel: string, + cityNotFound: string, + cityPlaceholder: string, + + intracityareaLabel: string, + intracityareaNotFound: string, + intracityareaPlaceholder: string, + + settlementLabel: string, + settlementNotFound: string, + settlementPlaceholder: string, + + planningstructureLabel: string, + planningstructureNotFound: string, + planningstructurePlaceholder: string, + + streetLabel: string, + streetNotFound: string, + streetFillBefore: string, + streetPlaceholder: string, + + steadLabel: string, + steadNotFound: string, + steadFillBefore: string, + steadPlaceholder: string, + + houseLabel: string, + houseNotFound: string, + houseFillBefore: string, + housePlaceholder: string, + + roomLabel: string, + roomNotFound: string, + roomFillBefore: string, + roomPlaceholder: string, + + postalcodeLabel: string, + postalcodePlaceholder: string, + postalcodeNotFound: string, + postalcodeNotValid: string, + postalcodeReplace: string, + + foreignAddressLabel: string, + foreignAddressPlaceholder: string, + + countryLabel: string, + countryPlaceholder: string, +|}; + +type _LogotypeLocale = {| + suffix: string, + prefix: string, +|}; + +type _ComboBoxLocale = {| + notFound: string, + errorNetworkButton: string, + errorNetworkMessage: string, +|}; + +type InternalDateOrder = 'DMY' | 'YMD' | 'MDY'; + +type InternalDateSeparator = '/' | '.' | '-' | ' '; + +type InternalDateFirstDayWeek = 0 | 1 | 2; + +type InternalDateDayWeek = 1 | 2 | 3 | 4 | 5 | 6 | 7; + +type InternalDateLocaleSet = {| + order: InternalDateOrder, + separator: InternalDateSeparator, + firstDayWeek: InternalDateFirstDayWeek, + notWorkingDays: $ReadOnlyArray, +|}; + +type _DatePickerLocale = {| + ...$Exact, + today: string, + months: $ReadOnlyArray, +|}; + +type _PagingLocale = {| + forward: string, +|}; + +type _SelectLocale = {| + placeholder: React$Node, +|}; + +type _SpinnerLocale = {| + loading: React$Node, +|}; + +type _TokenInputLocale = {| + addButtonComment: string, + addButtonTitle: string, +|}; + +type _TopBarLocale = {| + logout: string, + cabinetTitle: string, + cabinetSettings: string, + cabinetCertificates: string, + cabinetServices: string, +|}; + +declare module '@skbkontur/react-ui/Autocomplete' { + declare export type AutocompleteProps = { + ...$Exact<_InputProps>, + renderItem?: (item: string) => React$Node, + source?: + | $ReadOnlyArray + | ((patter: string) => Promise<$ReadOnlyArray>), + disablePortal?: boolean, + hasShadow?: boolean, + menuAlign?: 'left' | 'right', + menuMaxHeight?: number | string, + menuWidth?: number | string, + preventWindowScroll?: boolean, + onChange: ( + event: { + target: { + value: string, + ... + }, + ... + }, + value: string, + ) => void, + onBlur?: () => void, + size?: $PropertyType<_InputProps, 'size'>, + value: string, + ... + }; + + declare export type AutocompleteState = {| + items: void | null | $ReadOnlyArray, + selected: number, + |}; + + declare export default class Autocomplete extends React$Component< + AutocompleteProps, + AutocompleteState, + > { + focus(): void; + blur(): void; + } +} + +declare module '@skbkontur/react-ui/Button' { + declare export type ButtonSize = _ButtonSize; + declare export type ButtonType = _ButtonType; + declare export type ButtonArrow = _ButtonArrow; + declare export type ButtonUse = _ButtonUse; + + declare export type ButtonProps = {| + _noPadding?: boolean, + _noRightPadding?: boolean, + active?: boolean, + align?: string, + arrow?: ButtonArrow, + autoFocus?: boolean, + borderless?: boolean, + checked?: boolean, + children?: React$Node, + corners?: number, + disabled?: boolean, + disableFocus?: boolean, + error?: boolean, + focused?: boolean, + // eslint-disable-next-line flowtype/no-weak-types + icon?: React$Element, + loading?: boolean, + narrow?: boolean, + onBlur?: FocusEventHandler, + onClick?: MouseEventHandler, + onFocus?: FocusEventHandler, + onKeyDown?: KeyboardEventHandler, + onMouseEnter?: MouseEventHandler, + onMouseLeave?: MouseEventHandler, + onMouseOver?: MouseEventHandler, + size?: ButtonSize, + type?: ButtonType, + use?: ButtonUse, + visuallyFocused?: boolean, + warning?: boolean, + width?: number | string, + |}; + + declare export type ButtonState = {| + focusedByTab: boolean, + |}; + + declare export default class Button extends React$Component< + ButtonProps, + ButtonState, + > { + static TOP_LEFT: number; + static TOP_RIGHT: number; + static BOTTOM_RIGHT: number; + static BOTTOM_LEFT: number; + + focus(): void; + blur(): void; + } +} + +declare module '@skbkontur/react-ui/Calendar' { + declare class DayCellViewModel { + static create( + date: number, + month: number, + year: number, + isWeekend: boolean, + ): DayCellViewModel; + + date: number; + month: number; + year: number; + isWeekend: boolean; + } + + declare class MonthViewModel { + static create: (month: number, year: number) => MonthViewModel; + + +daysCount: number; + +offset: number; + +month: number; + +year: number; + +height: number; + +days: $ReadOnlyArray; + + isLastInYear: boolean; + isFirstInYear: boolean; + } + + declare export type CalendarDateShape = _CalendarDateShape; + + declare export type CalendarProps = {| + initialMonth?: number, + initialYear?: number, + onSelect?: (date: CalendarDateShape) => void, + value?: ?CalendarDateShape, + maxDate?: CalendarDateShape, + minDate?: CalendarDateShape, + isHoliday?: ( + day: CalendarDateShape & { + isWeekend: boolean, + ... + }, + ) => boolean, + |}; + + declare export type CalendarState = {| + scrollPosition: number, + months: $ReadOnlyArray, + today: CalendarDateShape, + scrollDirection: number, + scrollTarget: number, + |}; + + declare export default class Calendar extends React$Component< + CalendarProps, + CalendarState, + > { + scrollToMonth(month: number, year: number): void; + } +} + +declare module '@skbkontur/react-ui/Center' { + declare export type HorizontalAlign = 'left' | 'center' | 'right'; + + declare export type CenterProps = { + align?: HorizontalAlign, + style?: Style, + ... + }; + + declare export type CenterState = {||}; + + declare export default class Center extends React$Component< + CenterProps, + CenterState, + > {} +} + +declare module '@skbkontur/react-ui/Checkbox' { + declare export type CheckboxProps = { + children?: React$Node, + error?: boolean, + warning?: boolean, + onMouseEnter?: MouseEventHandler, + onMouseLeave?: MouseEventHandler, + onMouseOver?: MouseEventHandler, + onChange?: ( + event: SyntheticKeyboardEvent, + value: boolean, + ) => void, + initialIndeterminate?: boolean, + ... + }; + + declare export type CheckboxState = {| + focusedByTab: boolean, + indeterminate: boolean, + |}; + + declare export default class Checkbox extends React$Component< + CheckboxProps, + CheckboxState, + > { + focus(): void; + blur(): void; + setIndeterminate: () => void; + resetIndeterminate: () => void; + } +} + +declare module '@skbkontur/react-ui/ComboBox' { + declare export type ComboBoxItem = _ComboBoxItem; + + declare export type ComboBoxProps = {| + align?: 'left' | 'center' | 'right', + autocomplete?: boolean, + autoFocus?: boolean, + borderless?: boolean, + disablePortal?: boolean, + disabled?: boolean, + error?: boolean, + getItems?: (query: string) => Promise<$ReadOnlyArray>, + itemToValue?: (item: T) => string | number, + maxLength?: number, + drawArrow?: boolean, + menuAlign?: 'left' | 'right', + onBlur?: () => void, + onChange?: ( + event: { + target: { + value: T, + ... + }, + ... + }, + item: T, + ) => void, + onFocus?: () => void, + // eslint-disable-next-line flowtype/no-weak-types + onInputChange?: (query: string) => any, + onUnexpectedInput?: (query: string) => void | null | T, + placeholder?: string, + renderItem?: (item: T, state?: _MenuItemState) => React$Node, + renderNotFound?: () => React$Node, + renderTotalCount?: (found: number, total: number) => React$Node, + renderValue?: (item: T) => React$Node, + totalCount?: number, + value?: ?T, + valueToString?: (item: T) => string, + size?: 'small' | 'medium' | 'large', + warning?: boolean, + width?: string | number, + maxMenuHeight?: number | string, + |}; + + declare export default class ComboBox< + T = ComboBoxItem, + > extends React$Component> { + focus(): void; + search(query?: string): void; + open(): void; + close(): void; + selectInputText(): void; + reset(): void; + } +} + +declare module '@skbkontur/react-ui/ComboBoxOld' { + declare export type ComboBoxOldProps = {| + autoFocus?: boolean, + borderless?: boolean, + debounceInterval?: number, + disablePortal?: boolean, + disabled?: boolean, + error?: boolean, + info?: mixed | ((value: mixed) => mixed), + menuAlign?: 'left' | 'right', + openButton?: boolean, + placeholder?: string, + recover?: boolean | (() => mixed), + renderItem?: (value: mixed, info: mixed, state: mixed) => mixed, + renderNotFound?: string | (() => mixed), + renderTotalCount?: (foundCount: number, totalCount: number) => mixed, + renderValue?: (value: mixed, info: mixed) => mixed, + valueToString?: (value: mixed, info: mixed) => mixed, + source: (query: string) => mixed, + value?: mixed, + warning?: boolean, + width?: number | string, + onBlur?: () => mixed, + onChange?: (event: mixed, value: mixed) => mixed, + onClose?: () => mixed, + onFocus?: () => mixed, + onInputChange?: (value: string) => mixed, + onInputKeyDown?: () => mixed, + onMouseEnter?: () => mixed, + onMouseLeave?: () => mixed, + onMouseOver?: () => mixed, + onOpen?: () => mixed, + |}; + + declare export type ComboBoxOldState = {||}; + + declare export default class ComboBoxOld extends React$Component< + ComboBoxOldProps, + ComboBoxOldState, + > {} +} + +declare module '@skbkontur/react-ui/CurrencyInput' { + declare export type Selection = {| + start: number, + end: number, + direction: SelectionDirection, + |}; + + declare export type SelectionDirection = 'forward' | 'backward' | 'none'; + + declare export type CurrencyInputProps = _CurrencyInputProps; + + declare export type CurrencyInputState = _CurrencyInputState; + + declare export default typeof _CurrencyInput; +} + +declare module '@skbkontur/react-ui/CurrencyLabel' { + declare export type CurrencyLabelProps = {| + fractionDigits?: number, + value: number, + currencySymbol?: React$Node | null, + |}; + + declare var CurrencyLabel: React$ComponentType; + + declare export default typeof CurrencyLabel; +} + +declare module '@skbkontur/react-ui/CustomComboBox' { + declare export type Action = + | { + type: 'ValueChange', + value: T, + keepFocus: boolean, + ... + } + | { + type: 'TextChange', + value: string, + ... + } + | { + type: 'KeyPress', + event: SyntheticKeyboardEvent, + ... + } + | { + type: 'DidUpdate', + prevProps: CustomComboBoxProps, + prevState: CustomComboBoxState, + ... + } + | { + type: 'Mount', + ... + } + | { + type: 'Focus', + ... + } + | { + type: 'InputClick', + ... + } + | { + type: 'Blur', + ... + } + | { + type: 'Reset', + ... + } + | { + type: 'Open', + ... + } + | { + type: 'Close', + ... + } + | { + type: 'Search', + query: string, + ... + }; + + declare export type CustomComboBoxProps = {| + align?: 'left' | 'center' | 'right', + autoFocus?: boolean, + borderless?: boolean, + disablePortal?: boolean, + disabled?: boolean, + error?: boolean, + maxLength?: number, + menuAlign?: 'left' | 'right', + openButton?: boolean, + onMouseEnter?: (e: SyntheticMouseEvent) => void, + onMouseOver?: (e: SyntheticMouseEvent) => void, + onMouseLeave?: (e: SyntheticMouseEvent) => void, + placeholder?: string, + size?: 'small' | 'medium' | 'large', + totalCount?: number, + value?: ?T, + warning?: boolean, + width?: string | number, + maxMenuHeight?: number | string, + renderNotFound?: () => React$Node, + renderTotalCount?: (found: number, total: number) => React$Node, + renderItem: (item: T, state?: _MenuItemState) => React$Node, + renderValue: (value: T) => React$Node, + valueToString: (value: T) => string, + itemToValue: (item: T) => string | number, + |}; + + declare export type CustomComboBoxState = {| + editing: boolean, + loading: boolean, + opened: boolean, + textValue: string, + items: ?$ReadOnlyArray, + |}; + + declare export type Effect = ( + dispatch: (x0: Action) => void, + getState: () => CustomComboBoxState, + getProps: () => CustomComboBoxProps, + getInstance: () => CustomComboBox, + ) => void; + + declare export type Reducer = ( + state: CustomComboBoxState, + props: CustomComboBoxProps, + action: Action, + ) => + | CustomComboBoxState + | [CustomComboBoxState, $ReadOnlyArray>]; + + declare export type Props = { + reducer: Reducer, + ... + } & CustomComboBoxProps; + + declare var DefaultState: {| + editing: boolean, + items: null, + loading: boolean, + opened: boolean, + textValue: string, + |}; + + // eslint-disable-next-line flowtype/no-weak-types + declare export default class CustomComboBox extends React$Component< + Props, + CustomComboBoxState, + > { + // eslint-disable-next-line flowtype/no-weak-types + state: CustomComboBoxState; + input: ?_Input; + menu: ?_Menu; + inputLikeText: ?_InputLikeText; + + focus: () => void; + selectInputText: () => void; + blur: () => void; + search(query?: string): void; + open(): void; + close(): void; + reset(): void; + } +} + +declare module '@skbkontur/react-ui/DateInput' { + declare var DateInputConfig: {| + polyfillInput: boolean, + |}; + + declare var DateParts: {| + Date: number, + Month: number, + Year: number, + All: number, + |}; + + declare export type DateInputState = {| + selected: number | null, + editingCharIndex: number, + date: string | null, + month: string | null, + year: string | null, + minDate: ?_CalendarDateShape, + maxDate: ?_CalendarDateShape, + notify: boolean, + |}; + + declare export type DateInputProps = {| + value?: string, + error?: boolean, + warning?: boolean, + disabled?: boolean, + minDate?: ?string, + maxDate?: ?string, + width?: string | number, + withIcon?: boolean, + size?: 'small' | 'large' | 'medium', + onBlur?: (x0: SyntheticFocusEvent) => void, + onFocus?: (x0: SyntheticFocusEvent) => void, + onChange?: ( + x0: {| + target: {| + value: string, + |}, + |}, + x1: string, + ) => void, + onKeyDown?: (x0: SyntheticKeyboardEvent) => void, + |}; + + declare export type DateInputSetStateCallBack = ( + prevState: $ReadOnly, + props?: DateInputProps, + ) => DateInputState | null; + + declare export default class DateInput extends React$Component< + DateInputProps, + DateInputState, + > { + blur(): void; + focus(): void; + blink(): void; + } +} + +declare module '@skbkontur/react-ui/DatePicker' { + declare export type DatePickerProps = {| + autoFocus?: boolean, + disabled?: boolean, + enableTodayLink?: boolean, + error?: boolean, + minDate?: T, + maxDate?: T, + menuAlign?: 'left' | 'right', + size?: 'small' | 'medium' | 'large', + value: T | null, + warning?: boolean, + width?: number | string, + onBlur?: () => void, + onChange: ( + e: {| + target: {| + value: T, + |}, + |}, + v: T, + ) => void, + onFocus?: () => void, + /* eslint-disable flowtype/no-weak-types */ + onKeyDown?: (e: SyntheticKeyboardEvent) => void, + onMouseEnter?: (e: SyntheticMouseEvent) => void, + onMouseLeave?: (e: SyntheticMouseEvent) => void, + onMouseOver?: (e: SyntheticMouseEvent) => void, + /* eslint-enable flowtype/no-weak-types */ + isHoliday?: (day: T, isWeekend: boolean) => boolean, + |}; + + declare export type DatePickerState = {| + opened: boolean, + |}; + + declare export type DatePickerValue = string; + + declare export default class DatePicker extends React$Component< + DatePickerProps, + DatePickerState, + > { + static validate: (value: string | null | void) => boolean; + + blur(): void; + focus(): void; + close(): void; + } +} + +declare module '@skbkontur/react-ui/DatePickerOld' { + declare export type DatePickerOldProps = {| + autoFocus?: boolean, + className?: string, + disabled?: boolean, + error?: boolean, + maxYear?: number, + minYear?: number, + menuAlign?: 'left' | 'right', + onBlur?: () => void, + onChange?: ( + e: {| + target: {| + value: Date, + |}, + |}, + value: Date, + ) => void, + onFocus?: () => void, + onInput?: InputEventHandler, + onKeyDown?: KeyboardEventHandler, + onKeyPress?: KeyboardEventHandler, + onKeyUp?: KeyboardEventHandler, + onMouseEnter?: MouseEventHandler, + onMouseLeave?: MouseEventHandler, + onMouseOver?: MouseEventHandler, + onUnexpectedInput?: (value: string) => void, + placeholder?: string, + size?: 'small' | 'medium' | 'large', + value?: Date | string, + warning?: boolean, + width?: number | string, + withMask?: boolean, + |}; + + declare export type DatePickerOldState = {||}; + + declare export default class DatePicker extends React$Component< + DatePickerOldProps, + DatePickerOldState, + > {} +} + +declare module '@skbkontur/react-ui/DateSelect' { + declare var MONTHS: $ReadOnlyArray; + + declare export type DateSelectProps = {| + disabled?: boolean | null, + onChange: (value: number) => void, + type?: 'month' | 'year', + value: number, + width?: number | string, + minValue?: number, + maxValue?: number, + |}; + + declare export type DateSelectState = {| + botCapped: boolean, + current: ?number, + height: number, + opened: boolean, + pos: number, + top: number, + topCapped: boolean, + nodeTop: number, + |}; + + declare export default class DateSelect extends React$Component< + DateSelectProps, + DateSelectState, + > { + open: () => void; + close: () => void; + } +} + +declare module '@skbkontur/react-ui/Dropdown' { + declare export type DropdownProps = {| + caption: React$Node, + // eslint-disable-next-line flowtype/no-weak-types + icon?: React$Element, + width?: number | string, + // eslint-disable-next-line flowtype/no-weak-types + _renderButton?: (params: any) => React$Node, + disablePortal?: boolean, + disabled?: boolean, + error?: boolean, + warning?: boolean, + maxMenuHeight?: number, + menuAlign?: 'left' | 'right', + menuWidth?: number | string, + size?: _ButtonSize, + use?: _ButtonUse, + onClose?: () => void, + onOpen?: () => void, + children?: React$Node, + onMouseEnter?: MouseEventHandler, + onMouseLeave?: MouseEventHandler, + onMouseOver?: MouseEventHandler, + |}; + + declare export default class Dropdown extends React$Component { + static Header: typeof _MenuHeader; + static MenuItem: typeof _MenuItem; + static Separator: typeof _MenuSeparator; + + open(): void; + close(): void; + } +} + +declare module '@skbkontur/react-ui/DropdownContainer/DropdownContainer' { + declare export type DropdownMenuProps = {| + menuMaxHeight?: string | number, + menuWidth?: string | number, + caption: $PropertyType<_PopupMenuProps, 'caption'>, + onOpen?: () => void, + onClose?: () => void, + disableAnimations?: boolean, + children?: React$Node, + header?: React$Node, + footer?: React$Node, + positions?: $ReadOnlyArray<_PopupPosition>, + |}; + + declare export default class DropdownMenu extends React$Component {} +} + +declare module '@skbkontur/react-ui/DropdownMenu' { + declare export type DropdownMenuProps = {| + menuMaxHeight?: string | number, + menuWidth?: string | number, + caption: $PropertyType<_PopupMenuProps, 'caption'>, + onOpen?: () => void, + onClose?: () => void, + disableAnimations?: boolean, + children?: React$Node, + header?: React$Node, + footer?: React$Node, + positions?: $ReadOnlyArray<_PopupPosition>, + |}; + + declare export default class DropdownMenu extends React$Component {} +} + +declare module '@skbkontur/react-ui/Fias' { + declare class FiasData { + static isAddressObject: (data: FiasObject) => boolean; + static isStead: (data: FiasObject) => boolean; + static isHouse: (data: FiasObject) => boolean; + + data: FiasObject; + } + + declare class AddressElement { + type: Fields; + name: string; + data?: ?FiasData; + + +isFederalCity: boolean; + +verifiableData: $Shape; + + getText(withoutType?: boolean): string; + isTypeMatchField: (field: Fields) => boolean; + } + + declare export type FiasId = string; + + declare export type FiasEntity = {| + id: string, + fiasId: FiasId, + parentFiasId?: FiasId, + |}; + + declare export type AddressObject = {| + ...$Exact, + name: string, + abbreviation: string, + code: string, + |}; + + declare export type Stead = {| + ...$Exact, + number: string, + liveStatus: LiveStatuses, + |}; + + declare export type House = {| + ...$Exact, + estateStatus: EstateStatuses, + structureStatus: StructureStatuses, + number?: string, + structureNumber?: string, + buildingNumber?: string, + |}; + + declare export type Room = {| + ...$Exact, + flatNumber: string, + flatType: number, + liveStatus: LiveStatuses, + |}; + + declare export type EstateStatuses = 'Hold' | 'House' | 'HouseHold' | 'None'; + + declare export type StructureStatuses = + | 'Structure' + | 'Construction' + | 'Liter' + | 'None'; + + declare export type LiveStatuses = 'active' | 'inactive'; + + declare export type FiasObject = AddressObject | Stead | House | Room; + + declare export type Fields = + | 'region' + | 'district' + | 'city' + | 'intracityarea' + | 'settlement' + | 'planningstructure' + | 'street' + | 'stead' + | 'house' + | 'room'; + + declare export type ExtraFields = 'postalcode'; + + declare export type AddressFields = { + [key: Fields]: ?AddressElement, + ..., + }; + + declare export type FiasValue = {| + address?: AddressValue, + addressString?: string, + addressErrors?: AddressErrors, + fiasId?: FiasId, + |}; + + declare export type AddressValue = {| + [key: Fields]: void | {| + name: string, + data?: FiasObject, + |}, + |}; + + declare export type AddressResponse = {| + [key: Fields]: void | FiasObject, + |}; + + declare export type SearchResponse = $ReadOnlyArray; + + declare export type VerifyResponse = $ReadOnlyArray<{| + address: AddressResponse, + isValid: boolean, + invalidLevel?: string, + |}>; + + declare export type AddressErrors = { + [key: Fields]: void | string, + ..., + }; + + declare export type FormValidation = 'Error' | 'Warning' | 'None'; + + declare export type SearchOptions = {| + fiasId?: FiasId, + searchText?: string, + field?: Fields, + parentFiasId?: FiasId, + limit?: number, + fullAddress?: boolean, + directParent?: boolean, + |}; + + declare export type APIProvider = {| + search: (options: SearchOptions) => Promise>, + verify: (address: AddressValue) => Promise>, + |}; + + declare export type APIResult = {| + success: boolean, + data?: Data, + error?: Error, + |}; + + declare export type FetchFn = ( + uri: string, + options: {| + method?: 'GET' | 'POST', + body?: string, + |}, + ) => Promise; + + declare export type FetchResponse = {| + ok: boolean, + status: number, + statusText: string, + // eslint-disable-next-line flowtype/no-weak-types + json: () => Promise, + |}; + + declare export type FieldsSettings = {| + [field: Fields | ExtraFields]: {| + visible?: boolean, + |} | void, + |}; + + declare export type FiasCountry = {| + shortName: string, + fullName: string, + code: string, + |}; + + declare class Address { + static ALL_FIELDS: $ReadOnlyArray; + static VERIFIABLE_FIELDS: $ReadOnlyArray; + static FULL_ADDRESS_SEARCH_FIELDS: $ReadOnlyArray; + static ALL_PARENTS_SEARCH_FIELDS: $ReadOnlyArray; + static createFromResponse: (response: AddressResponse) => Address; + static createFromAddressValue: (addressValue: AddressValue) => Address; + static verify: ( + address: Address, + response: $ReadOnlyArray<{| + address: AddressResponse, + isValid: boolean, + invalidLevel?: string | void, + |}>, + notVerifiedMessage: string, + ) => Address; + static getParentFields: (field: Fields) => $ReadOnlyArray; + static filterVisibleFields: ( + fields: {| [key: Fields]: any |}, + fieldsSettings: FieldsSettings, + ) => {| [key: Fields]: any |}; + static getChildFields: (field: Fields) => $ReadOnlyArray; + static removeFiasData: ( + address: Address, + fields: $ReadOnlyArray, + ) => Address; + static getAddress: ( + api: APIProvider, + value?: FiasValue, + fieldsSettings?: FieldsSettings, + ) => Promise
; + + +isEmpty: boolean; + +hasErrors: boolean; + + fields: AddressFields; + errors: AddressErrors; + + hasError(field: Fields): boolean; + getError(field: Fields): string | void; + getAddressErrors: () => {| + region?: string | void, + district?: string | void, + city?: string | void, + intracityarea?: string | void, + settlement?: string | void, + planningstructure?: string | void, + street?: string | void, + stead?: string | void, + house?: string | void, + room?: string | void, + |}; + getText: ( + minField?: Fields | void, + skipTypes?: boolean, + connector?: string, + ) => string; + isAllowedToFill: (field: ?Fields) => boolean; + isAllowedToSearchFullAddress: (field?: Fields | void) => boolean; + isAllowedToSearchThroughChildrenOfDirectParent: ( + field?: Fields | void, + ) => boolean; + hasOnlyIndirectParent: (field: ?Fields) => boolean; + getClosestParentFiasId: (field?: Fields | void) => string | void; + getFiasId: () => string; + getAddressValue: () => AddressValue; + getValue: (withPostalCode?: boolean) => FiasValue; + convertForVerification: () => { ... }; + } + + declare export type FiasLocale = _FiasLocale; + + declare export type FiasProps = {| + value?: FiasValue, + error?: boolean, + warning?: boolean, + feedback?: string, + showAddressText?: boolean, + label?: string, + // eslint-disable-next-line flowtype/no-weak-types + icon?: React$Element, + readonly?: boolean, + baseUrl?: string, + api?: APIProvider, + onInit?: (value: FiasValue) => void, + onChange?: (value: FiasValue) => void, + onClose?: () => void, + search?: boolean, + limit?: number, + locale?: FiasLocale, + formValidation?: FormValidation, + allowNotVerified?: boolean, + version?: string, + |}; + + declare export type FiasState = {| + opened: boolean, + address: Address, + locale: FiasLocale, + |}; + + declare export default class Fias extends React$Component< + FiasProps, + FiasState, + > {} +} + +declare module '@skbkontur/react-ui/FxInput' { + declare export type FxInputProps = { + auto?: boolean, + type?: 'currency' | $PropertyType<_InputProps, 'type'>, + onRestore?: () => void, + onChange: + | $PropertyType<_CurrencyInputProps, 'onChange'> + | $PropertyType<_InputProps, 'onChange'>, + value?: string | number, + refInput?: (element: _CurrencyInput | _Input | null) => void, + ... + }; + + declare export type FxInputDefaultProps = {| + width: $PropertyType, + type: $PropertyType, + |}; + + declare export default class FxInput extends React$Component { + focus: () => void; + blur: () => void; + } +} + +declare module '@skbkontur/react-ui/Gapped' { + declare export type GappedProps = {| + gap?: number, + verticalAlign?: string | number, + vertical?: boolean, + children: React$Node, + |}; + + declare export default class Gapped extends React$Component {} +} + +declare module '@skbkontur/react-ui/Group' { + declare export type GroupProps = {| + width?: string | number, + |}; + + declare export type GroupChildProps = {| + mainInGroup?: boolean, + width?: string | number, + corners?: number, + |}; + + declare export default class Group extends React$Component {} +} + +declare module '@skbkontur/react-ui/HideBodyVerticalScroll' { + declare export default class HideBodyVerticalScroll extends React$Component<{||}> { + static hash: string; + } +} + +declare module '@skbkontur/react-ui/Hint' { + declare export type HintProps = {| + children?: React$Node, + manual?: boolean, + maxWidth?: string | number, + opened?: boolean, + pos?: + | 'top' + | 'right' + | 'bottom' + | 'left' + | 'top left' + | 'top center' + | 'top right' + | 'bottom left' + | 'bottom center' + | 'bottom right' + | 'left top' + | 'left middle' + | 'left bottom' + | 'right top' + | 'right middle' + | 'right bottom', + text: React$Node, + disableAnimations?: boolean, + useWrapper?: boolean, + onMouseEnter?: ( + event: SyntheticMouseEvent | MouseEvent, + ) => void, + onMouseLeave?: ( + event: SyntheticMouseEvent | MouseEvent, + ) => void, + |}; + + declare export type HintState = {| + opened: boolean, + |}; + + declare export default class Hint extends React$Component< + HintProps, + HintState, + > {} +} + +declare module '@skbkontur/react-ui/Icon/20px' { + declare export type MAP = _MAP; + + declare export type IconProps = _IconProps; + + declare export default class Icon extends React$Component { + static getAllNames(): $ReadOnlyArray; + } +} + +declare module '@skbkontur/react-ui/IgnoreLayerClick' { + declare export type IgnoreLayerClickProps = {| + children: React$Node, + active: boolean, + |}; + + declare export default class IgnoreLayerClick extends React$Component {} +} + +declare module '@skbkontur/react-ui/Input' { + declare export type InputSize = 'small' | 'medium' | 'large'; + declare export type InputAlign = 'left' | 'center' | 'right'; + declare export type InputType = 'password' | 'text'; + declare export type IconType = React$Node | (() => React$Node); + + declare export type InputProps = _InputProps; + + declare export type InputVisibilityState = _InputVisibilityState; + + declare export type InputState = _InputState; + + declare export default typeof _Input; +} + +declare module '@skbkontur/react-ui/Kebab' { + declare export type KebabProps = {| + disabled?: boolean, + onClose: () => void, + onOpen: () => void, + size?: 'small' | 'medium' | 'large', + positions?: $ReadOnlyArray<_PopupPosition>, + menuMaxHeight?: number | string, + disableAnimations?: boolean, + children?: React$Node, + |}; + + declare export type KebabState = {| + anchor: ?HTMLElement, + focusedByTab: boolean, + opened: boolean, + |}; + + declare export default class Kebab extends React$Component< + KebabProps, + KebabState, + > {} +} + +declare module '@skbkontur/react-ui/Kladr' { + declare export type PlaceDescription = {| + code: string, + fiasGuid: string, + name: string, + abbreviation: string, + isError: boolean, + |}; + + declare export type Address = { + region: PlaceDescription, + district: PlaceDescription, + city: PlaceDescription, + settlement: PlaceDescription, + street: PlaceDescription, + index: string, + okato: string, + house: string, + building: string, + room: string, + ... + }; + + declare export type KladrValue = {| + address: Address, + |}; + + declare export type KladrProps = {| + error?: string, + title: string, + value: any, + warning?: string, + onChange?: (event: any, value: KladrValue) => void, + |}; + + declare export type KladrState = {| + opened: boolean, + |}; + + declare export default class Kladr extends React$Component< + KladrProps, + KladrState, + > {} +} + +declare module '@skbkontur/react-ui/Link' { + declare export type LinkProps = { + disabled?: boolean, + href?: string, + // eslint-disable-next-line flowtype/no-weak-types + icon?: React$Element, + use?: 'default' | 'success' | 'danger' | 'grayed', + _button?: boolean, + _buttonOpened?: boolean, + tabIndex?: number, + onClick?: MouseEventHandler, + ... + }; + + declare export type LinkState = {| + focusedByTab: boolean, + |}; + + declare export default class Link extends React$Component< + LinkProps, + LinkState, + > { + // eslint-disable-next-line flowtype/no-weak-types + static __ADAPTER__: any; + } +} + +declare module '@skbkontur/react-ui/Loader' { + declare export type LoaderProps = {| + children?: React$Node, + active: boolean, + caption?: $PropertyType<_SpinnerProps, 'caption'>, + className?: string, + type?: 'mini' | 'normal' | 'big', + |}; + + declare export type LoaderState = {| + isStickySpinner: boolean, + spinnerStyle?: Style, + |}; + + declare export default class Loader extends React$Component< + LoaderProps, + LoaderState, + > {} +} + +declare module '@skbkontur/react-ui/LocaleProvider' { + declare export type LocaleControls = {| + Fias?: $Shape<_FiasLocale>, + TopBar?: $Shape<_TopBarLocale>, + Select?: $Shape<_SelectLocale>, + Paging?: $Shape<_PagingLocale>, + Spinner?: $Shape<_SpinnerLocale>, + ComboBox?: $Shape<_ComboBoxLocale>, + Logotype?: $Shape<_LogotypeLocale>, + TokenInput?: $Shape<_TokenInputLocale>, + DatePicker?: $Shape<_DatePickerLocale>, + |}; + + declare export type LocaleProviderProps = {| + locale?: LocaleControls, + langCode?: 'ru_RU' | 'en_GB', + children?: React$Node, + |}; + + declare var LocaleConsumer: React$ComponentType; + + declare export default class LocaleProvider extends React$Component {} +} + +declare module '@skbkontur/react-ui/Logotype' { + declare export type LogotypeLocale = _LogotypeLocale; + + declare export type LogotypeProps = {| + color?: string, + // eslint-disable-next-line flowtype/no-weak-types + component?: React$ComponentType | string, + href?: string, + suffix?: string, + textColor?: string, + withWidget?: boolean, + locale?: LogotypeLocale, + |}; + + declare export default class Logotype extends React$Component {} +} + +declare module '@skbkontur/react-ui/Menu/Menu' { + declare export type MenuProps = _MenuProps; + + declare export type MenuState = _MenuState; + + declare export default typeof _Menu; +} + +declare module '@skbkontur/react-ui/MenuHeader' { + declare export type MenuHeaderProps = _MenuHeaderProps; + + declare export default typeof _MenuHeader; +} + +declare module '@skbkontur/react-ui/MenuItem' { + declare export type MenuItemState = _MenuItemState; + + declare export type MenuItemElement = HTMLAnchorElement | HTMLSpanElement; + + declare export type MenuItemProps = _MenuItemProps; + + declare export default typeof _MenuItem; +} + +declare module '@skbkontur/react-ui/MenuSeparator' { + declare export type MenuSeparatorProps = {||}; + + declare export default typeof _MenuSeparator; +} + +declare module '@skbkontur/react-ui/Modal' { + declare export type HeaderProps = {| + close?: boolean, + sticky?: boolean, + children?: React$Node, + |}; + + declare function isHeader(child: React$Node): boolean; + + declare class Header extends React$Component {} + + declare export type BodyProps = {| + children?: React$Node, + |}; + + declare class Body extends React$Component {} + + declare export type FooterProps = {| + panel?: boolean, + sticky?: boolean, + children?: React$Node, + |}; + + declare function isFooter(child: React$Node): boolean; + + declare class Footer extends React$Component {} + + declare export type ModalProps = {| + children?: React$Node, + disableClose?: boolean, + alignTop?: boolean, + ignoreBackgroundClick?: boolean, + noClose?: boolean, + width?: number | string, + onClose?: () => void, + |}; + + declare export type ModalState = {| + stackPosition: number, + horizontalScroll: boolean, + clickTrapHeight?: string | number, + |}; + + declare export default class Modal extends React$Component< + ModalProps, + ModalState, + > { + static Header: typeof Header; + static Body: typeof Body; + static Footer: typeof Footer; + } +} + +declare module '@skbkontur/react-ui/ModalStack' { + declare export default class ModalStack { + // eslint-disable-next-line flowtype/no-weak-types + static add( + component: React$Component, + onChange: (stack: $ReadOnlyArray>) => void, + ): any; + // eslint-disable-next-line flowtype/no-weak-types + static remove(component: React$Component): void; + } +} + +declare module '@skbkontur/react-ui/Paging' { + declare export type ItemComponentProps = {| + active: boolean, + children?: React$Node, + className: string, + onClick: () => void, + pageNumber: number | 'forward', + tabIndex: number, + |}; + + declare export type PagingProps = {| + activePage: number, + component?: React$ComponentType, + onPageChange: (pageNumber: number) => void, + pagesCount: number, + disabled?: boolean, + strings?: {| + forward: string, + |}, + withoutNavigationHint?: boolean, + caption?: string, + useGlobalListener?: boolean, + |}; + + declare export type PagingState = {| + focusedByTab: boolean, + focusedItem: ?ItemType, + keyboardControl: boolean, + |}; + + declare export type ItemType = number | '.' | 'forward'; + + declare export default class Paging extends React$Component< + PagingProps, + PagingState, + > { + static isForward(pageNumber: number | 'forward'): boolean; + } +} + +declare module '@skbkontur/react-ui/PasswordInput' { + declare export type PasswordInputProps = {| + ...$Exact<_InputProps>, + detectCapsLock?: boolean, + |}; + + declare export type PasswordInputState = {| + visible: boolean, + capsLockEnabled?: boolean | null, + |}; + + declare export type InputProps = {| + ...$Exact, + onKeyDown: (event: SyntheticKeyboardEvent) => void, + onKeyPress: (event: SyntheticKeyboardEvent) => void, + rightIcon: () => React$Node, + |}; + + declare export default class PasswordInput extends React$Component< + PasswordInputProps, + PasswordInputState, + > { + focus: () => void; + } +} + +declare module '@skbkontur/react-ui/PerformanceMetrics/PerformanceMetrics' { + declare export type PerformanceMetricsProps = {| + componentsA: React$Element, + componentsB: React$Element, + |}; + + declare export function PerformanceMetrics( + props: PerformanceMetricsProps, + ): React$Node; +} + +declare module '@skbkontur/react-ui/Popup' { + declare export type PopupPosition = _PopupPosition; + + declare var PopupPositions: $ReadOnlyArray; + + declare export type PopupHandlerProps = {| + onMouseEnter?: ( + event: SyntheticMouseEvent | MouseEvent, + ) => void, + onMouseLeave?: ( + event: SyntheticMouseEvent | MouseEvent, + ) => void, + onClick?: (event: SyntheticMouseEvent | MouseEvent) => void, + onFocus?: (event: SyntheticFocusEvent | FocusEvent) => void, + onBlur?: (event: SyntheticFocusEvent | FocusEvent) => void, + onOpen?: () => void, + |}; + + declare export type PopupProps = {| + ...$Exact, + anchorElement: React$Node | HTMLElement, + backgroundColor?: string, + borderColor?: string, + children: React$Node | (() => React$Node), + hasPin: boolean, + hasShadow: boolean, + disableAnimations: boolean, + margin: number, + maxWidth: number | string, + opened: boolean, + pinOffset: number, + pinSize: number, + popupOffset: number, + positions: $ReadOnlyArray, + onCloseRequest?: () => void, + |}; + + declare export type PopupLocation = {| + coordinates: {| + left: number, + top: number, + |}, + position: string, + |}; + + declare export type PopupState = {| + location: ?PopupLocation, + |}; + + declare export default class Popup extends React$Component< + PopupProps, + PopupState, + > {} +} + +declare module '@skbkontur/react-ui/Radio' { + declare export type SyntheticRadioEvent = _SyntheticRadioEvent; + + declare export type RadioProps = { + error?: boolean, + warning?: boolean, + focused?: boolean, + pressed?: boolean, + hovered?: boolean, + active?: boolean, + onChange?: (event: SyntheticRadioEvent, value: T) => void, + onMouseEnter?: (event: SyntheticRadioEvent) => void, + onMouseLeave?: (event: SyntheticRadioEvent) => void, + onMouseOver?: (event: SyntheticRadioEvent) => void, + value: T, + ... + }; + + declare export default class Radio extends React$Component> { + focus(): void; + blur(): void; + } +} + +declare module '@skbkontur/react-ui/RadioGroup' { + declare export type PreventProps = {| + children?: React$Node, + |}; + + declare class Prevent extends React$Component {} + + declare export type ItemType = T | [T, React$Node]; + + declare export type RadioGroupProps = {| + defaultValue?: T, + value?: T, + items?: $ReadOnlyArray>, + name?: string, + disabled?: boolean, + warning?: boolean, + error?: boolean, + inline?: boolean, + children?: React$Node, + width?: string | number, + renderItem?: (itemValue: T, data: React$Node) => React$Node, + onChange?: (event: _SyntheticRadioEvent, value: T) => any, + onMouseLeave?: () => any, + onMouseOver?: () => any, + onMouseEnter?: () => any, + |}; + + declare export type RadioGroupState = {| + activeItem?: T, + |}; + + declare function renderItem(_value: any, data: React$Node): React$Node; + + declare export default class RadioGroup extends React$Component< + RadioGroupProps, + RadioGroupState, + > { + static Prevent: typeof Prevent; + + focus(): void; + } +} + +declare module '@skbkontur/react-ui/RenderContainer' { + declare export type RenderContainerProps = {| + anchor?: React$Node, + |}; + + declare export default class RenderContainer extends React$Component { + static lastId: number; + } +} + +declare module '@skbkontur/react-ui/RenderLayer' { + declare export type RenderLayerProps = {| + children: React$Node, + onClickOutside?: (e: Event) => void, + onFocusOutside?: (e: Event) => void, + active?: boolean, + |}; + + declare export default class RenderLayer extends React$Component {} +} + +declare module '@skbkontur/react-ui/ScrollContainer' { + declare export type ScrollContainerProps = {| + invert?: boolean, + maxHeight?: string | number, + preventWindowScroll?: boolean, + |}; + + declare export type ScrollContainerState = {| + scrollActive: boolean, + hover: boolean, + scrolling: boolean, + scrollSize: number, + scrollPos: number, + |}; + + declare export default class ScrollContainer extends React$Component< + ScrollContainerProps, + ScrollContainerState, + > { + scrollTo(element: HTMLElement): void; + scrollToTop(): void; + scrollToBottom(): void; + } +} + +declare module '@skbkontur/react-ui/Select' { + declare class Item extends React$Component<{| + children?: React$Node, + |}> {} + + declare export type ButtonParams = {| + disabled?: boolean, + label: React$Node, + onClick: () => void, + onKeyDown: (event: SyntheticKeyboardEvent) => void, + opened: boolean, + isPlaceholder: boolean, + |}; + + declare export type SelectProps = {| + // eslint-disable-next-line flowtype/no-weak-types + _icon?: React$Element, + _renderButton?: (params: ButtonParams) => React$Node, + defaultValue?: TValue, + // eslint-disable-next-line flowtype/no-weak-types + diadocLinkIcon?: React$Element, + disablePortal?: boolean, + disabled?: boolean, + error?: boolean, + filterItem?: (value: TValue, item: TItem, pattern: string) => boolean, + // eslint-disable-next-line flowtype/no-weak-types + items?: $ReadOnlyArray< + [TValue, TItem] | TItem | React$Element | (() => React$Element), + >, + maxMenuHeight?: number, + maxWidth?: string | number, + menuAlign?: 'left' | 'right', + menuWidth?: string | number, + onChange?: ( + e: {| + target: {| + value: TValue, + |}, + |}, + value: TValue, + ) => void, + onClose?: () => void, + onMouseEnter?: (e: SyntheticMouseEvent) => void, + onMouseLeave?: (e: SyntheticMouseEvent) => void, + onMouseOver?: (e: SyntheticMouseEvent) => void, + onOpen?: () => void, + placeholder?: React$Node, + renderItem?: (value: TValue, item?: TItem) => React$Node, + renderValue?: (value: TValue, item?: TItem) => React$Node, + areValuesEqual?: (value1: TValue, value2: TValue) => boolean, + search?: boolean, + value?: TValue, + width?: number | string, + warning?: boolean, + use?: _ButtonUse, + size?: _ButtonSize, + onFocus?: FocusEventHandler, + onBlur?: FocusEventHandler, + |}; + + declare export type SelectState = {| + opened: boolean, + searchPattern?: string, + value: ?TValue, + |}; + + declare function renderValue(value: any, item: any): any; + declare function renderItem(value: any, item: any): any; + declare function areValuesEqual(value1: any, value2: any): boolean; + declare function filterItem(value: any, item: any, pattern: string): boolean; + + declare export default class Select< + TValue = { ... }, + TItem = { ... }, + > extends React$Component, SelectState> { + static Item: typeof Item; + static SEP: () => React$Node; + static static: ( + element: + | string + | number + | boolean + | { ... } + | React$Element + | React$Node + | React$Portal + | (() => React$Node) + | null + | void, + ) => { ... } | null | void; + open: () => void; + close: () => void; + focus(): void; + } +} + +declare module '@skbkontur/react-ui/SidePage' { + declare export type Props = {| + children?: React$Node, + |}; + + declare class SidePageContainer extends React$Component {} + + declare export type SidePageHeaderProps = {| + children?: React$Node | ((fixed: boolean) => React$Node), + |}; + + declare class SidePageHeader extends React$Component { + renderClose(): React$Node; + } + + declare export type SidePageFooterProps = {| + children?: React$Node | ((fixed: boolean) => React$Node), + context?: SidePageContextType, + panel?: boolean, + |}; + + declare class SidePageFooter extends React$Component { + update: () => void; + } + + declare var SidePageFooterWithContext: ( + props: SidePageFooterProps, + ) => React$Node; + + declare export type SidePageContextType = {| + requestClose: () => void, + width: number | string, + updateLayout: () => void, + footerRef: (ref: SidePageFooter | null) => void, + |}; + + declare var SidePageContext: React$Context; + + declare var withContext: ( + BaseComponent: React$ComponentType< + P & {| + context?: SidePageContextType | void, + |}, + >, + ) => (props: P) => React$Node; + + declare export type SidePageBodyProps = {| + children?: React$Node, + context?: SidePageContextType, + |}; + + declare class SidePageBody extends React$Component {} + + declare var SidePageBodyWithContext: (props: SidePageBodyProps) => React$Node; + + declare export type SidePageProps = {| + blockBackground?: boolean, + disableClose?: boolean, + ignoreBackgroundClick?: boolean, + width?: number, + onClose?: () => void, + fromLeft?: boolean, + disableAnimations?: boolean, + children?: React$Node, + |}; + + declare export type SidePageState = {| + stackPosition?: number, + hasMargin?: boolean, + hasShadow?: boolean, + hasBackground?: boolean, + |}; + + declare export default class SidePage extends React$Component< + SidePageProps, + SidePageState, + > { + static Header: typeof SidePageHeader; + static Body: typeof SidePageBody; + static Footer: typeof SidePageFooter; + static Container: typeof SidePageContainer; + + updateLayout: () => void; + } +} + +declare module '@skbkontur/react-ui/Spinner' { + declare var types: AnyObject; + + declare var sizeMaps: AnyObject< + | {| + height: number, + width: number, + viewBox: void, + strokeWidth: number, + |} + | {| + height: number, + width: number, + viewBox: string, + strokeWidth: number, + |}, + >; + + declare function svgAnimateSupport(): boolean; + + declare var _default: {| + types: AnyObject, + sizeMaps: AnyObject< + | {| + height: number, + width: number, + viewBox: void, + strokeWidth: number, + |} + | {| + height: number, + width: number, + viewBox: string, + strokeWidth: number, + |}, + >, + svgAnimateSupport: typeof svgAnimateSupport, + |}; + + declare var SpinnerConfig: {| + hasSvgAnimationSupport: boolean, + |}; + + declare export type SpinnerType = _SpinnerType; + + declare export type SpinnerProps = _SpinnerProps; + + declare export default class Spinner extends React$Component { + static Types: typeof types; + } +} + +declare module '@skbkontur/react-ui/Sticky' { + declare export type StickyProps = {| + side: 'top' | 'bottom', + offset?: number, + getStop?: () => ?HTMLElement, + children?: React$Node | ((fixed: boolean) => React$Node), + allowChildWithMargins?: boolean, + |}; + + declare export type StickyState = {| + fixed: boolean, + height: number, + left: number | string, + width: number | string, + stopped: boolean, + relativeTop: number, + |}; + + declare export default class Sticky extends React$Component< + StickyProps, + StickyState, + > {} +} + +declare module '@skbkontur/react-ui/Switcher' { + declare export type SwitcherProps = {| + items: $ReadOnlyArray, + value?: string, + onChange?: ( + event: {| + target: {| + value: string, + |}, + |}, + value: string, + ) => void, + label?: string, + error?: boolean, + |}; + + declare export type SwitcherState = {| + focusedIndex: ?number, + |}; + + declare export type SwitcherItem = {| + label: string, + value: string, + |}; + + declare export default class Switcher extends React$Component< + SwitcherProps, + SwitcherState, + > {} +} + +declare module '@skbkontur/react-ui/Tabs' { + declare export type TabIndicators = {| + error: boolean, + warning: boolean, + success: boolean, + primary: boolean, + disabled: boolean, + |}; + + declare export type TabProps = {| + children?: React$Node, + // eslint-disable-next-line flowtype/no-weak-types + component?: React$ComponentType | string, + href?: string, + id?: string, + onClick?: (event: SyntheticMouseEvent) => void, + onKeyDown?: (event: SyntheticKeyboardEvent) => void, + disabled?: boolean, + error?: boolean, + warning?: boolean, + success?: boolean, + primary?: boolean, + style?: Style, + |}; + + declare export type TabContext = {| + activeTab: string, + // eslint-disable-next-line flowtype/no-weak-types + addTab: (id: string, getNode: () => any) => void, + notifyUpdate: () => void, + removeTab: (id: string) => void, + shiftFocus: (fromTab: string, delta: number) => void, + switchTab: (id: string) => void, + vertical: boolean, + |}; + + declare export type TabState = {| + focusedByKeyboard: boolean, + |}; + + declare class Tab extends React$Component { + // eslint-disable-next-line flowtype/no-weak-types + getUnderlyingNode: () => ?React$Element; + } + + declare export type TabsProps = {| + children?: React$Node, + indicatorClassName?: string, + onChange?: ( + ev: {| + target: {| + value: string, + |}, + |}, + value: string, + ) => void, + value: string, + vertical?: boolean, + width?: number | string, + |}; + + declare export type TabsState = {| + tabs: $ReadOnlyArray<{| + getNode: () => Tab | null, + id: string, + |}>, + |}; + + declare export default class Tabs extends React$Component< + TabsProps, + TabsState, + > { + static Tab: typeof Tab; + } +} + +declare module '@skbkontur/react-ui/Textarea' { + declare var TextareaAdapter: {| + getValue(inst: Textarea): string | number | $ReadOnlyArray | void, + setValue(inst: Textarea, value: string): void, + |}; + + declare export type TextareaProps = { + error?: boolean, + warning?: boolean, + disabled?: boolean, + autoResize?: boolean, + rows?: number, + maxRows?: string | number, + resize?: string, + width?: string | number, + onChange?: ( + event: SyntheticInputEvent, + value: string, + ) => void, + selectAllOnFocus?: boolean, + ... + }; + + declare export type TextareaState = {| + polyfillPlaceholder: boolean, + rows: number | string, + |}; + + declare export default class Textarea extends React$Component< + TextareaProps, + TextareaState, + > { + static __ADAPTER__: typeof TextareaAdapter; + + focus(): void; + blur(): void; + setSelectionRange: (start: number, end: number) => void; + selectAll: () => void; + } +} + +declare module '@skbkontur/react-ui/ThemeConsumer' { + declare export type Theme = _Theme; + + declare var ThemeConsumer: React$ComponentType; + + declare export default typeof ThemeConsumer; +} + +declare module '@skbkontur/react-ui/ThemeProvider' { + declare export type Theme = _Theme; + + declare export type ITheme = Theme; + + declare export type IThemeIn = Theme; + + declare export type ThemeProviderProps = {| + children: React$Node, + value: Theme, + |}; + + declare export default class ThemeProvider extends React$Component {} +} + +declare module '@skbkontur/react-ui/ThemeShowcase/ThemeShowcase' { + declare export type ShowcaseProps = {| + isDebugMode?: boolean, + |}; + + declare export type ShowcaseState = {| + selectedVariable?: _ComboBoxItem, + |}; + + declare export default class ThemeShowcase extends React$Component< + ShowcaseProps, + ShowcaseState, + > {} +} + +declare module '@skbkontur/react-ui/Toast' { + declare export type ToastViewProps = {| + children?: string, + action?: ?{| + label: string, + handler: () => void, + |}, + onClose?: () => void, + onMouseEnter?: () => void, + onMouseLeave?: () => void, + |}; + + declare class ToastView extends React$Component {} + + declare export type Action = {| + label: string, + handler: () => void, + |}; + + declare export type ToastState = {| + notification: ?string, + action: ?Action, + id: number, + |}; + + declare export type ToastProps = {| + onPush?: (notification: string, action?: Action) => void, + onClose?: (notification: string, action?: Action) => void, + |}; + + declare export default class Toast extends React$Component< + ToastProps, + ToastState, + > { + static push(notification: string, action?: Action): void; + static close(): void; + + _toast: ?ToastView; + push(notification: string, action?: Action): void; + close: () => void; + } +} + +declare module '@skbkontur/react-ui/Toggle' { + declare export type ToggleProps = {| + checked?: boolean, + defaultChecked?: boolean, + disabled?: boolean, + onChange?: (value: boolean) => void, + changeEventHandler?: InputEventHandler, + warning?: boolean, + error?: boolean, + loading?: boolean, + autoFocus?: boolean, + onFocus?: FocusEventHandler, + onBlur?: FocusEventHandler, + color?: string, + |}; + + declare export type ToggleState = {| + checked?: boolean, + focusByTab?: boolean, + |}; + + declare export default class Toggle extends React$Component< + ToggleProps, + ToggleState, + > { + focus: () => void; + } +} + +declare module '@skbkontur/react-ui/Token' { + declare export type TokenColorName = _TokenColorName; + + declare export type TokenColors = _TokenColors; + + declare export type TokenActions = {| + onClick?: MouseEventHandler, + onRemove?: MouseEventHandler, + |}; + + declare export type TokenProps = _TokenProps; + + declare var Token: React$ComponentType<{| + ...$Exact, + ...$Exact, + |}>; + + declare export default typeof Token; +} + +declare module '@skbkontur/react-ui/TokenInput' { + declare export type TokenInputType = 0 | 1 | 2; + + declare export type TokenInputProps = {| + selectedItems: $ReadOnlyArray, + onChange: (items: $ReadOnlyArray) => void, + autoFocus?: boolean, + type?: TokenInputType, + getItems?: (query: string) => Promise<$ReadOnlyArray>, + hideMenuIfEmptyInputValue?: boolean, + renderItem: (item: T, state: _MenuItemState) => React$Node | void, + renderValue: (item: T) => React$Node, + renderNotFound: () => React$Node, + valueToItem: (item: string) => T, + placeholder?: string, + delimiters?: $ReadOnlyArray, + error?: boolean, + warning?: boolean, + disabled?: boolean, + width: string | number, + renderTokenComponent?: ( + token: (props?: $Shape<_TokenProps>) => React$Node, + value?: T, + ) => React$Node, + |}; + + declare export type TokenInputState = {| + autocompleteItems?: $ReadOnlyArray, + activeTokens: $ReadOnlyArray, + inFocus?: boolean, + inputValue: string, + inputValueWidth: number, + preventBlur?: boolean, + loading?: boolean, + |}; + + declare export default class TokenInput extends React$Component< + TokenInputProps, + TokenInputState, + > {} +} + +declare module '@skbkontur/react-ui/Tooltip' { + declare export type TooltipTrigger = + | 'hover' + | 'click' + | 'focus' + | 'opened' + | 'closed' + | 'hoverAnchor'; + + declare export type TooltipProps = {| + anchorElement?: HTMLElement, + children?: React$Node, + className?: string, + closeButton?: boolean, + render?: ?() => React$Node, + pos: _PopupPosition, + trigger: TooltipTrigger, + onCloseClick?: MouseEventHandler, + onCloseRequest?: () => void, + allowedPositions?: $ReadOnlyArray<_PopupPosition>, + disableAnimations?: boolean, + useWrapper?: boolean, + |}; + + declare export type TooltipState = {| + opened: boolean, + |}; + + declare export default class Tooltip extends React$Component< + TooltipProps, + TooltipState, + > { + static closeDelay: number; + + renderContent: () => React$Node; + renderCloseButton(): React$Node; + } +} + +declare module '@skbkontur/react-ui/TooltipMenu' { + declare export type TooltipMenuChildType = React$Element< + React$ComponentType<_MenuItemProps | {||} | _MenuHeaderProps>, + >; + + declare export type TooltipMenuProps = {| + children?: TooltipMenuChildType | $ReadOnlyArray, + menuMaxHeight?: number | string, + menuWidth?: number | string, + caption: $PropertyType<_PopupMenuProps, 'caption'>, + positions?: $ReadOnlyArray, + disableAnimations: boolean, + |}; + + declare export default class TooltipMenu extends React$Component {} +} + +declare module '@skbkontur/react-ui/TopBar' { + declare class Logout extends React$Component {} + + declare export type UserProps = {| + userName: string, + cabinetUrl?: string, + |}; + + declare class User extends React$Component {} + + declare export type ButtonParams = {| + disabled?: boolean, + label: React$Node, + onClick: () => void, + onKeyDown: (event: SyntheticKeyboardEvent) => void, + opened: boolean, + |}; + + declare export type TopBarDropdownProps = {| + icon?: $PropertyType<_IconProps, 'name'>, + minWidth?: string | number | null, + use?: 'danger' | 'pay' | 'default', + label: React$Node, + onOpen?: () => void, + onClose?: () => void, + |}; + + declare class TopBarDropdown extends React$Component {} + + declare export type OrganizationsProps = {| + caption: React$Node, + comment?: ?string, + |}; + + declare export type OrganizationsState = {| + captionWhiteSpace: string, + minWidth: ?number, + |}; + + declare class Organizations extends React$Component< + OrganizationsProps, + OrganizationsState, + > {} + + declare class Divider extends React$Component<{||}> {} + + declare class Icon extends React$Component<_IconProps> { + static getAllNames(): $ReadOnlyArray; + } + + declare export type ItemProps = {| + _onClick?: (event: SyntheticMouseEvent) => void, + _onKeyDown?: (event: SyntheticKeyboardEvent) => void, + active?: boolean, + children?: React$Node, + className?: string, + icon?: $PropertyType<_IconProps, 'name'>, + iconOnly?: boolean, + minWidth?: string | number, + use?: 'danger' | 'pay' | 'default', + tabIndex?: number, + |}; + + declare class Item extends React$Component {} + + declare export type IconName = $PropertyType<_IconProps, 'name'>; + + declare export type ButtonItemProps = {| + ...$Exact, + active?: boolean, + children?: React$Node, + className?: string, + icon?: IconName, + iconOnly?: boolean, + minWidth?: string | number, + onClick?: () => void, + onKeyDown?: (event: SyntheticKeyboardEvent) => void, + use?: 'danger' | 'pay' | 'default', + |}; + + declare class ButtonItem extends React$Component {} + + declare export type TopBarProps = {| + children?: React$Node, + color?: string, + cabinetUrl?: string, + leftItems?: $ReadOnlyArray, + logoComponent?: React$ComponentType | string, + logoHref?: string, + maxWidth?: string | number, + noMargin?: boolean, + noShadow?: boolean, + noWidget?: boolean, + onLogout?: () => void, + rightItems?: $ReadOnlyArray, + suffix?: string, + userName?: string, + |}; + + declare export type TopBarDefaultProps = {| + maxWidth: string | number, + rightItems: $ReadOnlyArray, + |}; + + declare export type TopBarStartProps = {| + children?: React$Node, + |}; + + declare export type TopBarEndProps = {| + children?: React$Node, + |}; + + declare export default class TopBar extends React$Component { + static Divider: typeof Divider; + static Item: typeof ButtonItem; + static Dropdown: typeof TopBarDropdown; + static OrganizationsDropdown: typeof Organizations; + static Start: React$ComponentType; + static End: React$ComponentType; + static ItemStatic: typeof Item; + static User: typeof User; + static Logout: typeof Logout; + } +} + +declare module '@skbkontur/react-ui/ZIndex' { + declare export type ZIndexProps = { + delta: number, + render?: boolean, + className?: string, + ... + }; + + declare export default class ZIndex extends React$Component {} +} diff --git a/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.201.x-/test_react-ui_v1.x.x.js b/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.201.x-/test_react-ui_v1.x.x.js new file mode 100644 index 0000000000..0137c11a3a --- /dev/null +++ b/definitions/npm/@skbkontur/react-ui_v1.x.x/flow_v0.201.x-/test_react-ui_v1.x.x.js @@ -0,0 +1,13 @@ +/* @flow */ +import * as React from 'react'; +import { it, describe } from 'flow-typed-test'; +import Button from '@skbkontur/react-ui/Button'; + +describe('react-ui', () => { + it('controls prop types', () => { + ; + + // $FlowExpectedError + ; + }); +}); diff --git a/definitions/npm/apollo-client_v2.x.x/flow_v0.104.x-/apollo-client_v2.x.x.js b/definitions/npm/apollo-client_v2.x.x/flow_v0.104.x-v0.200.x/apollo-client_v2.x.x.js similarity index 100% rename from definitions/npm/apollo-client_v2.x.x/flow_v0.104.x-/apollo-client_v2.x.x.js rename to definitions/npm/apollo-client_v2.x.x/flow_v0.104.x-v0.200.x/apollo-client_v2.x.x.js diff --git a/definitions/npm/apollo-client_v2.x.x/flow_v0.201.x-/apollo-client_v2.x.x.js b/definitions/npm/apollo-client_v2.x.x/flow_v0.201.x-/apollo-client_v2.x.x.js new file mode 100644 index 0000000000..d9b02b68ea --- /dev/null +++ b/definitions/npm/apollo-client_v2.x.x/flow_v0.201.x-/apollo-client_v2.x.x.js @@ -0,0 +1,745 @@ +declare module "apollo-client" { + /** + * Types From graphql + * graphql types are maintained in the graphql-js repo + */ + declare type DocumentNode = any; + declare type ExecutionResult = { + data?: T, + extensions?: { [string]: any, ... }, + errors?: any[], + ... + }; + declare type GraphQLError = any; + /** End From graphql */ + + declare type OperationVariables = { [key: string]: any, ... }; + + declare export function print(ast: any): string; + + declare export class ObservableQuery extends Observable< + ApolloQueryResult + > { + options: WatchQueryOptions; + queryId: string; + variables: { [key: string]: any, ... }; + isCurrentlyPolling: boolean; + shouldSubscribe: boolean; + isTornDown: boolean; + scheduler: QueryScheduler; + queryManager: QueryManager; + observers: Observer>[]; + subscriptionHandles: SubscriptionLINK[]; + lastResult: ApolloQueryResult; + lastError: ApolloError; + lastVariables: { [key: string]: any, ... }; + + constructor(data: { + scheduler: QueryScheduler, + options: WatchQueryOptions, + shouldSubscribe?: boolean, + ... + }): this; + + result(): Promise>; + currentResult(): ApolloCurrentResult; + getLastResult(): ApolloQueryResult; + getLastError(): ApolloError; + resetLastResults(): void; + refetch(variables?: any): Promise>; + fetchMore( + fetchMoreOptions: FetchMoreQueryOptions & FetchMoreOptions + ): Promise>; + subscribeToMore(options: SubscribeToMoreOptions): () => void; + setOptions( + opts: ModifiableWatchQueryOptions + ): Promise>; + setVariables( + variables: any, + tryFetch?: boolean, + fetchResults?: boolean + ): Promise>; + updateQuery( + mapFn: (previousQueryResult: any, options: UpdateQueryOptions) => any + ): void; + stopPolling(): void; + startPolling(pollInterval: number): void; + } + + declare class QueryManager { + scheduler: QueryScheduler; + link: ApolloLink; + mutationStore: MutationStore; + queryStore: QueryStore; + dataStore: DataStore; + + constructor({ + link: ApolloLink, + queryDeduplication?: boolean, + store: DataStore, + onBroadcast?: () => void, + ssrMode?: boolean, + ... + }): this; + + mutate(options: MutationOptions<>): Promise>; + fetchQuery( + queryId: string, + options: WatchQueryOptions, + fetchType?: FetchType, + fetchMoreForQueryId?: string + ): Promise>; + queryListenerForObserver( + queryId: string, + options: WatchQueryOptions, + observer: Observer> + ): QueryListener; + watchQuery( + options: WatchQueryOptions, + shouldSubscribe?: boolean + ): ObservableQuery; + query(options: WatchQueryOptions): Promise>; + generateQueryId(): string; + stopQueryInStore(queryId: string): void; + addQueryListener(queryId: string, listener: QueryListener): void; + updateQueryWatch( + queryId: string, + document: DocumentNode, + options: WatchQueryOptions + ): void; + addFetchQueryPromise( + requestId: number, + promise: Promise>, + resolve: (result: ApolloQueryResult) => void, + reject: (error: Error) => void + ): void; + removeFetchQueryPromise(requestId: number): void; + addObservableQuery( + queryId: string, + observableQuery: ObservableQuery + ): void; + removeObservableQuery(queryId: string): void; + clearStore(): Promise; + resetStore(): Promise[]>; + } + + declare class QueryStore { + getStore(): { [queryId: string]: QueryStoreValue, ... }; + get(queryId: string): QueryStoreValue; + initQuery(query: { + queryId: string, + document: DocumentNode, + storePreviousVariables: boolean, + variables: Object, + isPoll: boolean, + isRefetch: boolean, + metadata: any, + fetchMoreForQueryId: string | void, + ... + }): void; + markQueryResult( + queryId: string, + result: ExecutionResult<>, + fetchMoreForQueryId: string | void + ): void; + markQueryError( + queryId: string, + error: Error, + fetchMoreForQueryId: string | void + ): void; + markQueryResultClient(queryId: string, complete: boolean): void; + stopQuery(queryId: string): void; + reset(observableQueryIds: string[]): void; + } + + declare class QueryScheduler { + inFlightQueries: { [queryId: string]: WatchQueryOptions, ... }; + registeredQueries: { [queryId: string]: WatchQueryOptions, ... }; + intervalQueries: { [interval: number]: string[], ... }; + queryManager: QueryManager; + constructor({ + queryManager: QueryManager, + ssrMode?: boolean, + ... + }): this; + checkInFlight(queryId: string): ?boolean; + fetchQuery( + queryId: string, + options: WatchQueryOptions, + fetchType: FetchType + ): Promise>; + startPollingQuery( + options: WatchQueryOptions, + queryId: string, + listener?: QueryListener + ): string; + stopPollingQuery(queryId: string): void; + fetchQueriesOnInterval(interval: number): void; + addQueryOnInterval( + queryId: string, + queryOptions: WatchQueryOptions + ): void; + registerPollingQuery( + queryOptions: WatchQueryOptions + ): ObservableQuery; + markMutationError(mutationId: string, error: Error): void; + reset(): void; + } + + declare class DataStore { + constructor(initialCache: ApolloCache): this; + getCache(): ApolloCache; + markQueryResult( + result: ExecutionResult<>, + document: DocumentNode, + variables: any, + fetchMoreForQueryId: string | void, + ignoreErrors?: boolean + ): void; + markSubscriptionResult( + result: ExecutionResult<>, + document: DocumentNode, + variables: any + ): void; + markMutationInit(mutation: { + mutationId: string, + document: DocumentNode, + variables: any, + updateQueries: { [queryId: string]: QueryWithUpdater, ... }, + update: ((proxy: DataProxy, mutationResult: Object) => void) | void, + optimisticResponse: Object | Function | void, + ... + }): void; + markMutationResult(mutation: { + mutationId: string, + result: ExecutionResult<>, + document: DocumentNode, + variables: any, + updateQueries: { [queryId: string]: QueryWithUpdater, ... }, + update: ((proxy: DataProxy, mutationResult: Object) => void) | void, + ... + }): void; + markMutationComplete({ + mutationId: string, + optimisticResponse?: any, + ... + }): void; + markUpdateQueryResult( + document: DocumentNode, + variables: any, + newResult: any + ): void; + reset(): Promise; + } + + declare type QueryWithUpdater = { + updater: MutationQueryReducer, + query: QueryStoreValue, + ... + }; + + declare interface MutationStoreValue { + mutationString: string; + variables: Object; + loading: boolean; + error: Error | null; + } + + declare class MutationStore { + getStore(): { [mutationId: string]: MutationStoreValue, ... }; + get(mutationId: string): MutationStoreValue; + initMutation( + mutationId: string, + mutationString: string, + variables: Object | void + ): void; + } + + declare export interface FetchMoreOptions { + updateQuery: ( + previousQueryResult: TData, + options: { + fetchMoreResult?: TData, + variables: TVariables, + ... + } + ) => TData; + } + + declare export interface UpdateQueryOptions { + variables?: Object; + } + + declare export type ApolloCurrentResult = { + data: T | {...}, + errors?: Array, + loading: boolean, + networkStatus: NetworkStatusRaw, + error?: ApolloError, + partial?: boolean, + ... + }; + + declare export type ModifiableWatchQueryOptions = { + variables?: { [key: string]: any, ... }, + pollInterval?: number, + fetchPolicy?: FetchPolicy, + errorPolicy?: ErrorPolicy, + fetchResults?: boolean, + notifyOnNetworkStatusChange?: boolean, + ... + } + + declare export type WatchQueryOptions = { + ...$Exact, + query: DocumentNode, + metadata?: any, + context?: any, + ... + } + + declare type RefetchQueryDescription = Array; + + declare interface MutationBaseOptions { + optimisticResponse?: Object | Function; + updateQueries?: MutationQueryReducersMap; + optimisticResponse?: Object; + refetchQueries?: + | ((result: ExecutionResult<>) => RefetchQueryDescription) + | RefetchQueryDescription; + update?: MutationUpdaterFn; + errorPolicy?: ErrorPolicy; + variables?: any; + } + + declare export type MutationOperation = (options: MutationBaseOptions) => Promise> + + declare export interface MutationOptions + extends MutationBaseOptions { + mutation: DocumentNode; + context?: any; + fetchPolicy?: FetchPolicy; + } + + declare export type SubscriptionOptions = { + query: DocumentNode, + variables?: { [key: string]: any, ... }, + ... + } + + declare export type FetchPolicy = + | "cache-first" + | "cache-and-network" + | "network-only" + | "cache-only" + | "no-cache" + | "standby"; + + declare export type ErrorPolicy = "none" | "ignore" | "all"; + + declare export interface FetchMoreQueryOptions { + variables: $Shape; + } + + declare export type SubscribeToMoreOptions< + TData, + TSubscriptionData, + TSubscriptionVariables = void + > = { + document?: DocumentNode, + variables?: TSubscriptionVariables, + updateQuery?: ( + previousResult: TData, + result: { + subscriptionData: { data?: TSubscriptionData, ... }, + variables: TSubscriptionVariables, + ... + } + ) => TData, + onError?: (error: Error) => void, + ... + }; + + declare export type MutationUpdaterFn = ( + proxy: DataProxy, + mutationResult: FetchResult + ) => void; + + declare export type NetworkStatusRaw = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + + declare export class NetworkStatus { + [NetworkStatusRaw]: string, + string: NetworkStatusRaw, + } + + declare export type QueryListener = ( + queryStoreValue: QueryStoreValue, + newData?: any + ) => void; + + declare export type QueryStoreValue = { + document: DocumentNode, + variables: Object, + previousVariables: Object | null, + networkStatus: NetworkStatusRaw, + networkError: Error | null, + graphQLErrors: GraphQLError[], + metadata: any, + ... + }; + + declare export type PureQueryOptions = { + query: DocumentNode, + variables?: { [key: string ]: any, ... }, + ... + }; + + declare export type ApolloQueryResult = { + data: T, + errors?: Array, + loading: boolean, + networkStatus: NetworkStatusRaw, + stale: boolean, + ... + }; + + declare export type FetchType = 1 | 2 | 3; + + declare export type MutationQueryReducer = ( + previousResult: { [key: string]: any, ... }, + options: { + mutationResult: FetchResult, + queryName: string | void, + queryVariables: { [key: string]: any, ... }, + ... + } + ) => { [key: string]: any, ... }; + + declare export type MutationQueryReducersMap = { [queryName: string]: MutationQueryReducer, ... }; + + declare export class ApolloError extends Error { + message: string; + graphQLErrors: Array; + networkError: Error | null; + extraInfo: any; + constructor(info: ErrorConstructor): this; + } + + declare interface ErrorConstructor { + graphQLErrors?: Array; + networkError?: Error | null; + errorMessage?: string; + extraInfo?: any; + } + + declare interface DefaultOptions { + +watchQuery?: ModifiableWatchQueryOptions; + +query?: ModifiableWatchQueryOptions; + +mutate?: MutationBaseOptions<>; + } + + declare export type ApolloClientOptions = { + link: ApolloLink, + cache: ApolloCache, + ssrMode?: boolean, + ssrForceFetchDelay?: number, + connectToDevTools?: boolean, + queryDeduplication?: boolean, + defaultOptions?: DefaultOptions, + ... + }; + + declare export class ApolloClient { + link: ApolloLink; + store: DataStore; + cache: ApolloCache; + queryManager: QueryManager; + disableNetworkFetches: boolean; + version: string; + queryDeduplication: boolean; + defaultOptions: DefaultOptions; + devToolsHookCb: Function; + proxy: ApolloCache | void; + ssrMode: boolean; + resetStoreCallbacks: Array<() => Promise>; + + constructor(options: ApolloClientOptions): this; + watchQuery(options: WatchQueryOptions): ObservableQuery; + query(options: WatchQueryOptions): Promise>; + mutate(options: MutationOptions): Promise>; + subscribe(options: SubscriptionOptions): Observable; + readQuery(options: DataProxyReadQueryOptions): T | null; + readFragment(options: DataProxyReadFragmentOptions): T | null; + writeQuery(options: DataProxyWriteQueryOptions): void; + writeFragment(options: DataProxyWriteFragmentOptions): void; + writeData(options: DataProxyWriteDataOptions): void; + __actionHookForDevTools(cb: () => any): void; + __requestRaw(payload: GraphQLRequest): Observable>; + initQueryManager(): void; + resetStore(): Promise> | null>; + onResetStore(cb: () => Promise): () => void; + reFetchObservableQueries( + includeStandby?: boolean + ): Promise[]> | Promise; + extract(optimistic?: boolean): TCacheShape; + restore(serializedState: TCacheShape): ApolloCache; + } + + declare export default typeof ApolloClient; + + /* apollo-link types */ + declare export class ApolloLink { + constructor(request?: RequestHandler): this; + + static empty(): ApolloLink; + static from(links: Array): ApolloLink; + static split( + test: (op: Operation) => boolean, + left: ApolloLink | RequestHandler, + right: ApolloLink | RequestHandler + ): ApolloLink; + static execute( + link: ApolloLink, + operation: GraphQLRequest + ): Observable>; + + split( + test: (op: Operation) => boolean, + left: ApolloLink | RequestHandler, + right: ApolloLink | RequestHandler + ): ApolloLink; + + concat(next: ApolloLink | RequestHandler): ApolloLink; + + request( + operation: Operation, + forward?: NextLink + ): Observable> | null; + } + + declare interface GraphQLRequest { + query: DocumentNode; + variables?: { [key: string]: any, ... }; + operationName?: string; + context?: { [key: string]: any, ... }; + extensions?: { [key: string]: any, ... }; + } + + declare interface Operation { + query: DocumentNode; + variables: { [key: string]: any, ... }; + operationName: string; + extensions: { [key: string]: any, ... }; + setContext: (context: { [key: string]: any, ... }) => { [key: string]: any, ... }; + getContext: () => { [key: string]: any, ... }; + toKey: () => string; + } + + declare export type FetchResult< + C = { [key: string]: any, ... }, + E = { [key: string]: any, ... } + > = ExecutionResult & { + extension?: E, + context?: C, + ... + }; + + declare type NextLink = (operation: Operation) => Observable>; + + declare type RequestHandler = ( + operation: Operation, + forward?: NextLink + ) => Observable> | null; + + declare class Observable { + subscribe( + observerOrNext: ((value: T) => void) | ZenObservableObserver, + error?: (error: any) => void, + complete?: () => void + ): ZenObservableSubscription; + + forEach(fn: (value: T) => void): Promise; + + map(fn: (value: T) => R): Observable; + + filter(fn: (value: T) => boolean): Observable; + + reduce( + fn: (previousValue: R | T, currentValue: T) => R | T, + initialValue?: R | T + ): Observable; + + flatMap(fn: (value: T) => ZenObservableObservableLike): Observable; + + from( + observable: Observable | ZenObservableObservableLike | Array + ): Observable; + + of(...args: Array): Observable; + } + + declare interface Observer { + start?: (subscription: SubscriptionLINK) => any; + next?: (value: T) => void; + error?: (errorValue: any) => void; + complete?: () => void; + } + + declare interface SubscriptionLINK { + closed: boolean; + unsubscribe(): void; + } + + declare interface ZenObservableSubscriptionObserver { + closed: boolean; + next(value: T): void; + error(errorValue: any): void; + complete(): void; + } + + declare interface ZenObservableSubscription { + closed: boolean; + unsubscribe(): void; + } + + declare interface ZenObservableObserver { + start?: (subscription: ZenObservableSubscription) => any; + next?: (value: T) => void; + error?: (errorValue: any) => void; + complete?: () => void; + } + + declare type ZenObservableSubscriber = ( + observer: ZenObservableSubscriptionObserver + ) => void | (() => void) | SubscriptionLINK; + + declare interface ZenObservableObservableLike { + subscribe?: ZenObservableSubscriber; + } + /* apollo-link types */ + + /* apollo-cache types */ + declare export class ApolloCache { + read(query: CacheReadOptions): T | null; + write(write: CacheWriteOptions): void; + diff(query: CacheDiffOptions): CacheDiffResult; + watch(watch: CacheWatchOptions): () => void; + evict(query: CacheEvictOptions): CacheEvictionResult; + reset(): Promise; + + restore(serializedState: TSerialized): ApolloCache; + extract(optimistic?: boolean): TSerialized; + + removeOptimistic(id: string): void; + + performTransaction(transaction: Transaction): void; + recordOptimisticTransaction( + transaction: Transaction, + id: string + ): void; + + transformDocument(document: DocumentNode): DocumentNode; + transformForLink(document: DocumentNode): DocumentNode; + + readQuery( + options: DataProxyReadQueryOptions, + optimistic?: boolean + ): QueryType | null; + readFragment( + options: DataProxyReadFragmentOptions, + optimistic?: boolean + ): FragmentType | null; + writeQuery(options: CacheWriteQueryOptions): void; + writeFragment(options: CacheWriteFragmentOptions): void; + writeData(options: CacheWriteDataOptions): void; + } + + declare type Transaction = (c: ApolloCache) => void; + + declare type CacheWatchCallback = (newData: any) => void; + + declare interface CacheEvictionResult { + success: boolean; + } + + declare interface CacheReadOptions extends DataProxyReadQueryOptions { + rootId?: string; + previousResult?: any; + optimistic: boolean; + } + + declare interface CacheWriteOptions extends DataProxyReadQueryOptions { + dataId: string; + result: any; + } + + declare interface CacheDiffOptions extends CacheReadOptions { + returnPartialData?: boolean; + } + + declare interface CacheWatchOptions extends CacheReadOptions { + callback: CacheWatchCallback; + } + + declare interface CacheEvictOptions extends DataProxyReadQueryOptions { + rootId?: string; + } + + declare type CacheDiffResult = DataProxyDiffResult; + declare type CacheWriteQueryOptions = DataProxyWriteQueryOptions; + declare type CacheWriteFragmentOptions = DataProxyWriteFragmentOptions; + declare type CacheWriteDataOptions = DataProxyWriteDataOptions; + declare type CacheReadFragmentOptions = DataProxyReadFragmentOptions; + + declare interface DataProxyReadQueryOptions { + query: DocumentNode; + variables?: any; + } + + declare interface DataProxyReadFragmentOptions { + id: string; + fragment: DocumentNode; + fragmentName?: string; + variables?: any; + } + + declare interface DataProxyWriteQueryOptions { + data: any; + query: DocumentNode; + variables?: any; + } + + declare interface DataProxyWriteFragmentOptions { + data: any; + id: string; + fragment: DocumentNode; + fragmentName?: string; + variables?: any; + } + + declare interface DataProxyWriteDataOptions { + data: any; + id?: string; + } + + declare type DataProxyDiffResult = { + result?: T, + complete?: boolean, + ... + }; + + declare interface DataProxy { + readQuery( + options: DataProxyReadQueryOptions, + optimistic?: boolean + ): QueryType | null; + readFragment( + options: DataProxyReadFragmentOptions, + optimistic?: boolean + ): FragmentType | null; + writeQuery(options: DataProxyWriteQueryOptions): void; + writeFragment(options: DataProxyWriteFragmentOptions): void; + writeData(options: DataProxyWriteDataOptions): void; + } + /* End apollo-cache types */ +} diff --git a/definitions/npm/axios_v0.19.x/flow_v0.104.x-/axios_v0.19.x.js b/definitions/npm/axios_v0.19.x/flow_v0.104.x-v0.200.x/axios_v0.19.x.js similarity index 100% rename from definitions/npm/axios_v0.19.x/flow_v0.104.x-/axios_v0.19.x.js rename to definitions/npm/axios_v0.19.x/flow_v0.104.x-v0.200.x/axios_v0.19.x.js diff --git a/definitions/npm/axios_v0.19.x/flow_v0.104.x-/test_axios_v0.19.x.js b/definitions/npm/axios_v0.19.x/flow_v0.104.x-v0.200.x/test_axios_v0.19.x.js similarity index 100% rename from definitions/npm/axios_v0.19.x/flow_v0.104.x-/test_axios_v0.19.x.js rename to definitions/npm/axios_v0.19.x/flow_v0.104.x-v0.200.x/test_axios_v0.19.x.js diff --git a/definitions/npm/axios_v0.20.x/flow_v0.83.x-/axios_v0.20.x.js b/definitions/npm/axios_v0.19.x/flow_v0.201.x-/axios_v0.19.x.js similarity index 100% rename from definitions/npm/axios_v0.20.x/flow_v0.83.x-/axios_v0.20.x.js rename to definitions/npm/axios_v0.19.x/flow_v0.201.x-/axios_v0.19.x.js diff --git a/definitions/npm/axios_v0.20.x/flow_v0.83.x-/test_axios_v0.20.x.js b/definitions/npm/axios_v0.19.x/flow_v0.201.x-/test_axios_v0.19.x.js similarity index 100% rename from definitions/npm/axios_v0.20.x/flow_v0.83.x-/test_axios_v0.20.x.js rename to definitions/npm/axios_v0.19.x/flow_v0.201.x-/test_axios_v0.19.x.js diff --git a/definitions/npm/axios_v0.21.x/flow_v0.83.x-/axios_v0.21.x.js b/definitions/npm/axios_v0.20.x/flow_v0.201.x-/axios_v0.20.x.js similarity index 100% rename from definitions/npm/axios_v0.21.x/flow_v0.83.x-/axios_v0.21.x.js rename to definitions/npm/axios_v0.20.x/flow_v0.201.x-/axios_v0.20.x.js diff --git a/definitions/npm/axios_v0.21.x/flow_v0.83.x-/test_axios_v0.21.x.js b/definitions/npm/axios_v0.20.x/flow_v0.201.x-/test_axios_v0.20.x.js similarity index 100% rename from definitions/npm/axios_v0.21.x/flow_v0.83.x-/test_axios_v0.21.x.js rename to definitions/npm/axios_v0.20.x/flow_v0.201.x-/test_axios_v0.20.x.js diff --git a/definitions/npm/axios_v0.22.x/flow_v0.83.x-/axios_v0.22.x.js b/definitions/npm/axios_v0.20.x/flow_v0.83.x-v0.200.x/axios_v0.20.x.js similarity index 100% rename from definitions/npm/axios_v0.22.x/flow_v0.83.x-/axios_v0.22.x.js rename to definitions/npm/axios_v0.20.x/flow_v0.83.x-v0.200.x/axios_v0.20.x.js diff --git a/definitions/npm/axios_v0.22.x/flow_v0.83.x-/test_axios_v0.22.x.js b/definitions/npm/axios_v0.20.x/flow_v0.83.x-v0.200.x/test_axios_v0.20.x.js similarity index 100% rename from definitions/npm/axios_v0.22.x/flow_v0.83.x-/test_axios_v0.22.x.js rename to definitions/npm/axios_v0.20.x/flow_v0.83.x-v0.200.x/test_axios_v0.20.x.js diff --git a/definitions/npm/axios_v0.23.x/flow_v0.83.x-/axios_v0.23.x.js b/definitions/npm/axios_v0.21.x/flow_v0.201.x-/axios_v0.21.x.js similarity index 100% rename from definitions/npm/axios_v0.23.x/flow_v0.83.x-/axios_v0.23.x.js rename to definitions/npm/axios_v0.21.x/flow_v0.201.x-/axios_v0.21.x.js diff --git a/definitions/npm/axios_v0.23.x/flow_v0.83.x-/test_axios_v0.23.x.js b/definitions/npm/axios_v0.21.x/flow_v0.201.x-/test_axios_v0.21.x.js similarity index 100% rename from definitions/npm/axios_v0.23.x/flow_v0.83.x-/test_axios_v0.23.x.js rename to definitions/npm/axios_v0.21.x/flow_v0.201.x-/test_axios_v0.21.x.js diff --git a/definitions/npm/axios_v0.24.x/flow_v0.83.x-/axios_v0.24.x.js b/definitions/npm/axios_v0.21.x/flow_v0.83.x-v0.200.x/axios_v0.21.x.js similarity index 100% rename from definitions/npm/axios_v0.24.x/flow_v0.83.x-/axios_v0.24.x.js rename to definitions/npm/axios_v0.21.x/flow_v0.83.x-v0.200.x/axios_v0.21.x.js diff --git a/definitions/npm/axios_v0.24.x/flow_v0.83.x-/test_axios_v0.24.x.js b/definitions/npm/axios_v0.21.x/flow_v0.83.x-v0.200.x/test_axios_v0.21.x.js similarity index 100% rename from definitions/npm/axios_v0.24.x/flow_v0.83.x-/test_axios_v0.24.x.js rename to definitions/npm/axios_v0.21.x/flow_v0.83.x-v0.200.x/test_axios_v0.21.x.js diff --git a/definitions/npm/axios_v0.25.x/flow_v0.83.x-/axios_v0.25.x.js b/definitions/npm/axios_v0.22.x/flow_v0.201.x-/axios_v0.22.x.js similarity index 100% rename from definitions/npm/axios_v0.25.x/flow_v0.83.x-/axios_v0.25.x.js rename to definitions/npm/axios_v0.22.x/flow_v0.201.x-/axios_v0.22.x.js diff --git a/definitions/npm/axios_v0.25.x/flow_v0.83.x-/test_axios_v0.25.x.js b/definitions/npm/axios_v0.22.x/flow_v0.201.x-/test_axios_v0.22.x.js similarity index 100% rename from definitions/npm/axios_v0.25.x/flow_v0.83.x-/test_axios_v0.25.x.js rename to definitions/npm/axios_v0.22.x/flow_v0.201.x-/test_axios_v0.22.x.js diff --git a/definitions/npm/axios_v0.26.x/flow_v0.83.x-/axios_v0.26.x.js b/definitions/npm/axios_v0.22.x/flow_v0.83.x-v0.200.x/axios_v0.22.x.js similarity index 100% rename from definitions/npm/axios_v0.26.x/flow_v0.83.x-/axios_v0.26.x.js rename to definitions/npm/axios_v0.22.x/flow_v0.83.x-v0.200.x/axios_v0.22.x.js diff --git a/definitions/npm/axios_v0.26.x/flow_v0.83.x-/test_axios_v0.26.x.js b/definitions/npm/axios_v0.22.x/flow_v0.83.x-v0.200.x/test_axios_v0.22.x.js similarity index 100% rename from definitions/npm/axios_v0.26.x/flow_v0.83.x-/test_axios_v0.26.x.js rename to definitions/npm/axios_v0.22.x/flow_v0.83.x-v0.200.x/test_axios_v0.22.x.js diff --git a/definitions/npm/axios_v0.23.x/flow_v0.201.x-/axios_v0.23.x.js b/definitions/npm/axios_v0.23.x/flow_v0.201.x-/axios_v0.23.x.js new file mode 100644 index 0000000000..9125c9be4e --- /dev/null +++ b/definitions/npm/axios_v0.23.x/flow_v0.201.x-/axios_v0.23.x.js @@ -0,0 +1,222 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare class Cancel { + constructor(message?: string): Cancel; + message: string; + } + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v0.23.x/flow_v0.201.x-/test_axios_v0.23.x.js b/definitions/npm/axios_v0.23.x/flow_v0.201.x-/test_axios_v0.23.x.js new file mode 100644 index 0000000000..d463de4954 --- /dev/null +++ b/definitions/npm/axios_v0.23.x/flow_v0.201.x-/test_axios_v0.23.x.js @@ -0,0 +1,455 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); diff --git a/definitions/npm/axios_v0.23.x/flow_v0.83.x-v0.200.x/axios_v0.23.x.js b/definitions/npm/axios_v0.23.x/flow_v0.83.x-v0.200.x/axios_v0.23.x.js new file mode 100644 index 0000000000..9125c9be4e --- /dev/null +++ b/definitions/npm/axios_v0.23.x/flow_v0.83.x-v0.200.x/axios_v0.23.x.js @@ -0,0 +1,222 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare class Cancel { + constructor(message?: string): Cancel; + message: string; + } + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v0.23.x/flow_v0.83.x-v0.200.x/test_axios_v0.23.x.js b/definitions/npm/axios_v0.23.x/flow_v0.83.x-v0.200.x/test_axios_v0.23.x.js new file mode 100644 index 0000000000..d463de4954 --- /dev/null +++ b/definitions/npm/axios_v0.23.x/flow_v0.83.x-v0.200.x/test_axios_v0.23.x.js @@ -0,0 +1,455 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); diff --git a/definitions/npm/axios_v0.24.x/flow_v0.201.x-/axios_v0.24.x.js b/definitions/npm/axios_v0.24.x/flow_v0.201.x-/axios_v0.24.x.js new file mode 100644 index 0000000000..9125c9be4e --- /dev/null +++ b/definitions/npm/axios_v0.24.x/flow_v0.201.x-/axios_v0.24.x.js @@ -0,0 +1,222 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare class Cancel { + constructor(message?: string): Cancel; + message: string; + } + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v0.24.x/flow_v0.201.x-/test_axios_v0.24.x.js b/definitions/npm/axios_v0.24.x/flow_v0.201.x-/test_axios_v0.24.x.js new file mode 100644 index 0000000000..d463de4954 --- /dev/null +++ b/definitions/npm/axios_v0.24.x/flow_v0.201.x-/test_axios_v0.24.x.js @@ -0,0 +1,455 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); diff --git a/definitions/npm/axios_v0.24.x/flow_v0.83.x-v0.200.x/axios_v0.24.x.js b/definitions/npm/axios_v0.24.x/flow_v0.83.x-v0.200.x/axios_v0.24.x.js new file mode 100644 index 0000000000..9125c9be4e --- /dev/null +++ b/definitions/npm/axios_v0.24.x/flow_v0.83.x-v0.200.x/axios_v0.24.x.js @@ -0,0 +1,222 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare class Cancel { + constructor(message?: string): Cancel; + message: string; + } + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v0.24.x/flow_v0.83.x-v0.200.x/test_axios_v0.24.x.js b/definitions/npm/axios_v0.24.x/flow_v0.83.x-v0.200.x/test_axios_v0.24.x.js new file mode 100644 index 0000000000..d463de4954 --- /dev/null +++ b/definitions/npm/axios_v0.24.x/flow_v0.83.x-v0.200.x/test_axios_v0.24.x.js @@ -0,0 +1,455 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); diff --git a/definitions/npm/axios_v0.25.x/flow_v0.201.x-/axios_v0.25.x.js b/definitions/npm/axios_v0.25.x/flow_v0.201.x-/axios_v0.25.x.js new file mode 100644 index 0000000000..9125c9be4e --- /dev/null +++ b/definitions/npm/axios_v0.25.x/flow_v0.201.x-/axios_v0.25.x.js @@ -0,0 +1,222 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare class Cancel { + constructor(message?: string): Cancel; + message: string; + } + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v0.25.x/flow_v0.201.x-/test_axios_v0.25.x.js b/definitions/npm/axios_v0.25.x/flow_v0.201.x-/test_axios_v0.25.x.js new file mode 100644 index 0000000000..d463de4954 --- /dev/null +++ b/definitions/npm/axios_v0.25.x/flow_v0.201.x-/test_axios_v0.25.x.js @@ -0,0 +1,455 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); diff --git a/definitions/npm/axios_v0.25.x/flow_v0.83.x-v0.200.x/axios_v0.25.x.js b/definitions/npm/axios_v0.25.x/flow_v0.83.x-v0.200.x/axios_v0.25.x.js new file mode 100644 index 0000000000..9125c9be4e --- /dev/null +++ b/definitions/npm/axios_v0.25.x/flow_v0.83.x-v0.200.x/axios_v0.25.x.js @@ -0,0 +1,222 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare class Cancel { + constructor(message?: string): Cancel; + message: string; + } + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v0.25.x/flow_v0.83.x-v0.200.x/test_axios_v0.25.x.js b/definitions/npm/axios_v0.25.x/flow_v0.83.x-v0.200.x/test_axios_v0.25.x.js new file mode 100644 index 0000000000..d463de4954 --- /dev/null +++ b/definitions/npm/axios_v0.25.x/flow_v0.83.x-v0.200.x/test_axios_v0.25.x.js @@ -0,0 +1,455 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); diff --git a/definitions/npm/axios_v0.26.x/flow_v0.201.x-/axios_v0.26.x.js b/definitions/npm/axios_v0.26.x/flow_v0.201.x-/axios_v0.26.x.js new file mode 100644 index 0000000000..9125c9be4e --- /dev/null +++ b/definitions/npm/axios_v0.26.x/flow_v0.201.x-/axios_v0.26.x.js @@ -0,0 +1,222 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare class Cancel { + constructor(message?: string): Cancel; + message: string; + } + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v0.26.x/flow_v0.201.x-/test_axios_v0.26.x.js b/definitions/npm/axios_v0.26.x/flow_v0.201.x-/test_axios_v0.26.x.js new file mode 100644 index 0000000000..d463de4954 --- /dev/null +++ b/definitions/npm/axios_v0.26.x/flow_v0.201.x-/test_axios_v0.26.x.js @@ -0,0 +1,455 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); diff --git a/definitions/npm/axios_v0.26.x/flow_v0.83.x-v0.200.x/axios_v0.26.x.js b/definitions/npm/axios_v0.26.x/flow_v0.83.x-v0.200.x/axios_v0.26.x.js new file mode 100644 index 0000000000..9125c9be4e --- /dev/null +++ b/definitions/npm/axios_v0.26.x/flow_v0.83.x-v0.200.x/axios_v0.26.x.js @@ -0,0 +1,222 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare class Cancel { + constructor(message?: string): Cancel; + message: string; + } + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v0.26.x/flow_v0.83.x-v0.200.x/test_axios_v0.26.x.js b/definitions/npm/axios_v0.26.x/flow_v0.83.x-v0.200.x/test_axios_v0.26.x.js new file mode 100644 index 0000000000..d463de4954 --- /dev/null +++ b/definitions/npm/axios_v0.26.x/flow_v0.83.x-v0.200.x/test_axios_v0.26.x.js @@ -0,0 +1,455 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); diff --git a/definitions/npm/axios_v0.27.x/flow_v0.83.x-/axios_v0.27.x.js b/definitions/npm/axios_v0.27.x/flow_v0.201.x-/axios_v0.27.x.js similarity index 100% rename from definitions/npm/axios_v0.27.x/flow_v0.83.x-/axios_v0.27.x.js rename to definitions/npm/axios_v0.27.x/flow_v0.201.x-/axios_v0.27.x.js diff --git a/definitions/npm/axios_v0.27.x/flow_v0.83.x-/test_axios_v0.27.x.js b/definitions/npm/axios_v0.27.x/flow_v0.201.x-/test_axios_v0.27.x.js similarity index 100% rename from definitions/npm/axios_v0.27.x/flow_v0.83.x-/test_axios_v0.27.x.js rename to definitions/npm/axios_v0.27.x/flow_v0.201.x-/test_axios_v0.27.x.js diff --git a/definitions/npm/axios_v1.x.x/flow_v0.83.x-/axios_v1.x.x.js b/definitions/npm/axios_v0.27.x/flow_v0.83.x-v0.200.x/axios_v0.27.x.js similarity index 100% rename from definitions/npm/axios_v1.x.x/flow_v0.83.x-/axios_v1.x.x.js rename to definitions/npm/axios_v0.27.x/flow_v0.83.x-v0.200.x/axios_v0.27.x.js diff --git a/definitions/npm/axios_v1.x.x/flow_v0.83.x-/test_axios_v1.x.x.js b/definitions/npm/axios_v0.27.x/flow_v0.83.x-v0.200.x/test_axios_v0.27.x.js similarity index 100% rename from definitions/npm/axios_v1.x.x/flow_v0.83.x-/test_axios_v1.x.x.js rename to definitions/npm/axios_v0.27.x/flow_v0.83.x-v0.200.x/test_axios_v0.27.x.js diff --git a/definitions/npm/axios_v1.x.x/flow_v0.201.x-/axios_v1.x.x.js b/definitions/npm/axios_v1.x.x/flow_v0.201.x-/axios_v1.x.x.js new file mode 100644 index 0000000000..8378051c1e --- /dev/null +++ b/definitions/npm/axios_v1.x.x/flow_v0.201.x-/axios_v1.x.x.js @@ -0,0 +1,242 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise>; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + static ERR_NETWORK: string; + static ERR_BAD_OPTION_VALUE: string; + static ERR_BAD_OPTION: string; + static ECONNABORTED: string; + static ETIMEDOUT: string; + static ERR_NETWORK: string; + static ERR_FR_TOO_MANY_REDIRECTS: string; + static ERR_DEPRECATED: string; + static ERR_BAD_RESPONSE: string; + static ERR_BAD_REQUEST: string; + static ERR_CANCELED: string; + + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + status?: string; + } + + declare class CanceledError extends AxiosError { + } + + declare class Cancel extends AxiosError { + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + AxiosError: typeof AxiosError; + CanceledError: typeof CanceledError; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + toFormData: ( + obj: { [key: string]: any, ... }, + formData?: FormData, + ) => FormData; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v1.x.x/flow_v0.201.x-/test_axios_v1.x.x.js b/definitions/npm/axios_v1.x.x/flow_v0.201.x-/test_axios_v1.x.x.js new file mode 100644 index 0000000000..7a866cf43c --- /dev/null +++ b/definitions/npm/axios_v1.x.x/flow_v0.201.x-/test_axios_v1.x.x.js @@ -0,0 +1,499 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios, { AxiosError, toFormData } from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); + +describe('formData', () => { + it('returns FormData', () => { + const form = toFormData({ + val: 123, + nested: { + arr: ['hello', 'world'] + } + }); + + form.keys(); + form.get('val'); + form.getAll('arr[]'); + + // $FlowExpectedError[incompatible-call] + toFormData(); + // $FlowExpectedError[incompatible-call] takes object as first arg + toFormData(''); + }); + + it('can accept another FormData', () => { + declare var formData: FormData; + toFormData({}, formData); + + // $FlowExpectedError[incompatible-call] second arg must be FormData type + toFormData({}, ''); + }); +}); + +describe('AxiosError', () => { + it('contains static error codes', () => { + (AxiosError.ERR_NETWORK: string); + (AxiosError.ERR_BAD_OPTION_VALUE: string); + (AxiosError.ERR_BAD_OPTION: string); + (AxiosError.ECONNABORTED: string); + (AxiosError.ETIMEDOUT: string); + (AxiosError.ERR_NETWORK: string); + (AxiosError.ERR_FR_TOO_MANY_REDIRECTS: string); + (AxiosError.ERR_DEPRECATED: string); + (AxiosError.ERR_BAD_RESPONSE: string); + (AxiosError.ERR_BAD_REQUEST: string); + (AxiosError.ERR_CANCELED: string); + }); +}); diff --git a/definitions/npm/axios_v1.x.x/flow_v0.83.x-v0.200.x/axios_v1.x.x.js b/definitions/npm/axios_v1.x.x/flow_v0.83.x-v0.200.x/axios_v1.x.x.js new file mode 100644 index 0000000000..8378051c1e --- /dev/null +++ b/definitions/npm/axios_v1.x.x/flow_v0.83.x-v0.200.x/axios_v1.x.x.js @@ -0,0 +1,242 @@ +declare module 'axios' { + import type { Agent as HttpAgent } from 'http'; + import type { Agent as HttpsAgent } from 'https'; + + declare type AxiosTransformer = ( + data: T, + headers?: { [key: string]: mixed, ...}, + ) => mixed; + + declare type ProxyConfig = {| + host: string, + port: number, + auth?: {| + username: string, + password: string, + |}, + protocol?: string, + |}; + + declare type Canceler = (message?: string) => void; + + declare type CancelTokenSource = {| + token: CancelToken, + cancel: Canceler, + |}; + + declare class CancelToken { + constructor(executor: (cancel: Canceler) => void): void; + static source(): CancelTokenSource; + promise: Promise>; + reason?: Cancel; + throwIfRequested(): void; + } + + declare type Method = + | 'get' + | 'GET' + | 'delete' + | 'DELETE' + | 'head' + | 'HEAD' + | 'options' + | 'OPTIONS' + | 'post' + | 'POST' + | 'put' + | 'PUT' + | 'patch' + | 'PATCH'; + + declare type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + declare type AxiosAdapter = ( + config: AxiosXHRConfig + ) => Promise>; + + declare type AxiosXHRConfigBase = { + adapter?: AxiosAdapter, + auth?: {| + username: string, + password: string, + |}, + baseURL?: string, + cancelToken?: CancelToken, + headers?: { [key: string]: mixed, ...}, + httpAgent?: HttpAgent, + httpsAgent?: HttpsAgent, + maxContentLength?: number, + maxRedirects?: number, + socketPath?: string | null, + params?: { [key: string]: mixed, ...}, + paramsSerializer?: (params: { [key: string]: mixed, ...}) => string, + onUploadProgress?: (progressEvent: ProgressEvent) => void, + onDownloadProgress?: (progressEvent: ProgressEvent) => void, + proxy?: ProxyConfig | false, + responseType?: ResponseType, + timeout?: number, + transformRequest?: AxiosTransformer | Array>, + transformResponse?: AxiosTransformer | Array>, + validateStatus?: (status: number) => boolean, + withCredentials?: boolean, + xsrfCookieName?: string, + xsrfHeaderName?: string, + ... + }; + + declare type AxiosXHRConfig = { + ...$Exact>, + data?: T, + method?: Method, + url: string, + ... + }; + + declare type AxiosXHRConfigShape = $Shape>; + + declare type AxiosXHR = {| + config: AxiosXHRConfig, + data: R, + headers: ?{[key: string]: mixed, ...}, + status: number, + statusText: string, + request: http$ClientRequest<> | XMLHttpRequest | mixed, + |}; + + declare type AxiosInterceptorIdent = number; + + declare type AxiosRequestInterceptor = {| + use( + onFulfilled: ?( + response: AxiosXHRConfig + ) => Promise> | AxiosXHRConfig, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosResponseInterceptor = {| + use( + onFulfilled: ?(response: AxiosXHR) => mixed, + onRejected: ?(error: mixed) => mixed + ): AxiosInterceptorIdent, + eject(ident: AxiosInterceptorIdent): void, + |}; + + declare type AxiosPromise = Promise>; + + declare class Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + constructor(config?: AxiosXHRConfigBase): void; + request( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + delete( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + get( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + head( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + options( + url: string, + config?: AxiosXHRConfigBase + ): AxiosPromise; + post( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + put( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + patch( + url: string, + data?: T, + config?: AxiosXHRConfigBase + ): AxiosPromise; + interceptors: {| + request: AxiosRequestInterceptor, + response: AxiosResponseInterceptor, + |}; + defaults: {| + ...$Exact>, + headers: { [key: string]: mixed, ...}, + |}; + getUri(config?: AxiosXHRConfig): string; + } + + declare class AxiosError extends Error { + static ERR_NETWORK: string; + static ERR_BAD_OPTION_VALUE: string; + static ERR_BAD_OPTION: string; + static ECONNABORTED: string; + static ETIMEDOUT: string; + static ERR_NETWORK: string; + static ERR_FR_TOO_MANY_REDIRECTS: string; + static ERR_DEPRECATED: string; + static ERR_BAD_RESPONSE: string; + static ERR_BAD_REQUEST: string; + static ERR_CANCELED: string; + + config: AxiosXHRConfig; + request?: http$ClientRequest<> | XMLHttpRequest; + response?: AxiosXHR; + code?: string; + isAxiosError: boolean; + status?: string; + } + + declare class CanceledError extends AxiosError { + } + + declare class Cancel extends AxiosError { + } + + declare interface AxiosExport extends Axios { + ( + config: AxiosXHRConfig | string, + config?: AxiosXHRConfigShape + ): AxiosPromise; + Axios: typeof Axios; + AxiosError: typeof AxiosError; + CanceledError: typeof CanceledError; + Cancel: typeof Cancel; + CancelToken: typeof CancelToken; + isCancel(value: mixed): boolean; + create(config?: AxiosXHRConfigBase): Axios; + all: typeof Promise.all; + spread(callback: (...args: T) => R): (array: T) => R; + toFormData: ( + obj: { [key: string]: any, ... }, + formData?: FormData, + ) => FormData; + } + + declare type $AxiosXHRConfigBase = AxiosXHRConfigBase; + + declare type $AxiosXHRConfig = AxiosXHRConfig; + + declare type $AxiosXHR = AxiosXHR; + + declare type $AxiosError = AxiosError; + + declare module.exports: AxiosExport; +} diff --git a/definitions/npm/axios_v1.x.x/flow_v0.83.x-v0.200.x/test_axios_v1.x.x.js b/definitions/npm/axios_v1.x.x/flow_v0.83.x-v0.200.x/test_axios_v1.x.x.js new file mode 100644 index 0000000000..7a866cf43c --- /dev/null +++ b/definitions/npm/axios_v1.x.x/flow_v0.83.x-v0.200.x/test_axios_v1.x.x.js @@ -0,0 +1,499 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import axios, { AxiosError, toFormData } from 'axios'; +import type { + $AxiosError, + $AxiosXHR, + $AxiosXHRConfig, + $AxiosXHRConfigBase, + Axios, + AxiosAdapter, + Canceler, + CancelTokenSource, +} from 'axios'; + +type User = {| + +id: number, + +name: string, +|}; + +type RequestDataUser = {| + +name: string, +|}; + +type Header = {[key: string]: mixed,...}; + +const handleResponse = (response: $AxiosXHR) => { + (response.data: mixed); + (response.status: number); + // $FlowExpectedError[incompatible-cast] + (response.status: string); + (response.statusText: string); + // $FlowExpectedError[incompatible-cast] + (response.statusText: number); + (response.headers: ?{...}); + (response.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (response.config: string); +}; + +const handleUserResponse = ( + response: $AxiosXHR | $AxiosXHR +) => { + (response.data.id: number); + (response.data.name: string); +}; + +const handleError = (error: $AxiosError) => { + (error: Error); + (error.isAxiosError: boolean); + // $FlowExpectedError[incompatible-cast] + (error.isAxiosError: number); + + (error.config: $AxiosXHRConfig); + // $FlowExpectedError[incompatible-cast] + (error.config: string); + + if (error.response) { + (error.response.data: mixed); + (error.response.status: number); + (error.response.headers: ?{...}); + } else { + (error.message: string); + } +}; + +const config: $AxiosXHRConfigBase = { + baseURL: 'https://api.example.com/', + transformRequest: (data: RequestDataUser, headers?: Header) => '{"foo":"bar"}', + transformResponse: [(data: User, headers?: Header) => ({ baz: 'qux' })], + headers: { 'X-FOO': 'bar' }, + params: { id: 12345 }, + paramsSerializer: (params: Object) => 'id=12345', + timeout: 10000, + withCredentials: true, + auth: { + username: 'janedoe', + password: 's00pers3cret', + }, + responseType: 'json', + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + onUploadProgress: (progressEvent: any) => {}, + onDownloadProgress: (progressEvent: any) => {}, + maxContentLength: 2000, + validateStatus: (status: number) => status >= 200 && status < 300, + maxRedirects: 5, + proxy: { + host: '127.0.0.1', + port: 9000, + }, + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), +}; + +describe('Config', () => { + it('Axios Config', () => { + const axiosConfig: $AxiosXHRConfig = { + ...config, + url: '/user', + data: { name: 'new name' }, + method: 'PUT', + }; + + // $FlowExpectedError[incompatible-type] + axiosConfig.method = 'FOOBAR'; + // $FlowExpectedError[incompatible-type] + axiosConfig.responseType = 'foobar'; + }); +}); + +describe('Headers', () => { + it('should take inexact kv pairs with string type as key and mixed type as values', () => { + const test: Header = { 'foo': 1 }; + const test1: Header = { 'bar': 'baz'}; + + // $FlowExpectedError[unsupported-syntax] + const test2: Header = { 1 : 'false'} + }); +}) + +describe('Request methods', () => { + it('returns a promise', () => { + axios({ + url: '/user', + method: 'get', + }) + .then(handleResponse) + .catch(handleError); + + axios('/user', { + method: 'post', + }) + .then(handleResponse) + .catch(handleError); + + axios + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + + axios + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .patch('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + axios + .get('/user?id=12345') + .then(handleUserResponse) + .catch(handleError); + + axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); + + axios + .head('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .delete('/user') + .then(handleUserResponse) + .catch(handleError); + + axios + .post('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .post( + '/user', + { name: 'new name' }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponse) + .catch(handleError); + + axios + .put('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + + axios + .patch('/user', { name: 'new name' }) + .then(handleUserResponse) + .catch(handleError); + }); +}); + +describe('Create instance', () => { + it('returns a callable axios instance', () => { + const instance1: Axios = axios.create(); + const instance2: Axios = axios.create(config); + + instance1('/user', { + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .request({ + url: '/user', + method: 'POST', + }) + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user?id=12345') + .then(handleResponse) + .catch(handleError); + + instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('Defaults', () => { + it('setters default config', () => { + axios.defaults.baseURL = 'https://api.example.com/'; + axios.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + } + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + }}; + axios.defaults.timeout = 2500; + + const instance: Axios = axios.create(); + instance.defaults.baseURL = 'https://api.example.com/'; + instance.defaults.headers = { + 'common': { + 'Authorization': 'token' + } + }; + axios.defaults.headers = { + 'post': { + 'X-FOO': 'bar' + } + }; + + instance.defaults.timeout = 2500; + }); +}); + +describe('Interceptors', () => { + it('use a request interceptor', () => { + const requestInterceptorId: number = axios.interceptors.request.use( + (config: $AxiosXHRConfig) => config, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.eject(requestInterceptorId); + + axios.interceptors.request.use( + (config: $AxiosXHRConfig) => Promise.resolve(config), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.request.use((config: $AxiosXHRConfig) => config); + axios.interceptors.request.use((config: $AxiosXHRConfig) => + Promise.resolve(config) + ); + }); + + it('use a response interceptor', () => { + const responseInterceptorId: number = axios.interceptors.response.use( + (response: $AxiosXHR) => response, + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.eject(responseInterceptorId); + + axios.interceptors.response.use( + (response: $AxiosXHR) => Promise.resolve(response), + (error: mixed) => Promise.reject(error) + ); + + axios.interceptors.response.use((response: $AxiosXHR) => response); + axios.interceptors.response.use((response: $AxiosXHR) => + Promise.resolve(response) + ); + }); +}); + +describe('Adapters', () => { + it('use adapter', () => { + const adapter: AxiosAdapter = (config: $AxiosXHRConfig) => { + const response: $AxiosXHR = { + data: { foo: 'bar' }, + status: 200, + statusText: 'OK', + headers: { 'X-FOO': 'bar' }, + config, + request: {}, + }; + return Promise.resolve(response); + }; + + axios.defaults.adapter = adapter; + }); +}); + +describe('Concurrency', () => { + it('axios.all', () => { + const promises = [Promise.resolve(1), Promise.resolve(2)]; + + const promise: Promise> = axios.all(promises); + // $FlowExpectedError[incompatible-type-arg] + const promise2: Promise> = axios.all(promises); + }); + + it('axios.spread', () => { + const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`; + const fn2: (arr: Array) => string = axios.spread(fn1); + // $FlowExpectedError[incompatible-type] + const fn3: (arr: Array) => string = axios.spread(fn1); + }); +}); + +describe('Cancellation', () => { + it('use a CancelToken', () => { + const source: CancelTokenSource = axios.CancelToken.source(); + + axios.get('/user', { + cancelToken: source.token, + }); + + // $FlowExpectedError[incompatible-call] + axios.get('/something', { cancelToken: source }); + + (source.cancel: Canceler); + source.cancel('Operation has been canceled.'); + // $FlowExpectedError[incompatible-call] + source.cancel(42); + }); +}); + +describe('Extended', () => { + it('create extended', () => { + class AxiosExtended extends axios.Axios { + specialPut(...args) { + return super.put(...args); + } + } + + const extended = new AxiosExtended(); + + extended + .put('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + + extended + .specialPut('/user', { foo: 'bar' }) + .then(handleResponse) + .catch(handleError); + }); +}); + +describe('getUri', () => { + it('returns a string', () => { + const uri: string = axios.getUri({ + method: 'post', + url: '/user/12345', + params: { + foo: 'bar', + }, + }); + + // $FlowExpectedError[incompatible-type] + const uri2: number = axios.getUri(); + }); +}); + +describe('options', () => { + it('accepts string url only', () => { + //$FlowExpectedError[incompatible-call] + axios.options(123) + axios.options('a url') + }); + + it('takes a url and returns a promise', () => { + axios + .options('anyUrl') + .then(handleResponse) + .catch(handleError); + }); + + it('takes url and config, returns a promise', () => { + const axiosConfig:$AxiosXHRConfig = { + url: '/foo', + method: 'OPTIONS', + }; + axios + .options('a url', axiosConfig) + .then(handleResponse) + .catch(handleError) + }); +}); + +describe('formData', () => { + it('returns FormData', () => { + const form = toFormData({ + val: 123, + nested: { + arr: ['hello', 'world'] + } + }); + + form.keys(); + form.get('val'); + form.getAll('arr[]'); + + // $FlowExpectedError[incompatible-call] + toFormData(); + // $FlowExpectedError[incompatible-call] takes object as first arg + toFormData(''); + }); + + it('can accept another FormData', () => { + declare var formData: FormData; + toFormData({}, formData); + + // $FlowExpectedError[incompatible-call] second arg must be FormData type + toFormData({}, ''); + }); +}); + +describe('AxiosError', () => { + it('contains static error codes', () => { + (AxiosError.ERR_NETWORK: string); + (AxiosError.ERR_BAD_OPTION_VALUE: string); + (AxiosError.ERR_BAD_OPTION: string); + (AxiosError.ECONNABORTED: string); + (AxiosError.ETIMEDOUT: string); + (AxiosError.ERR_NETWORK: string); + (AxiosError.ERR_FR_TOO_MANY_REDIRECTS: string); + (AxiosError.ERR_DEPRECATED: string); + (AxiosError.ERR_BAD_RESPONSE: string); + (AxiosError.ERR_BAD_REQUEST: string); + (AxiosError.ERR_CANCELED: string); + }); +}); diff --git a/definitions/npm/cache-manager_v2.x.x/flow_v0.104.x-/cache-manager_v2.x.x.js b/definitions/npm/cache-manager_v2.x.x/flow_v0.104.x-v0.200.x/cache-manager_v2.x.x.js similarity index 100% rename from definitions/npm/cache-manager_v2.x.x/flow_v0.104.x-/cache-manager_v2.x.x.js rename to definitions/npm/cache-manager_v2.x.x/flow_v0.104.x-v0.200.x/cache-manager_v2.x.x.js diff --git a/definitions/npm/cache-manager_v2.x.x/flow_v0.201.x-/cache-manager_v2.x.x.js b/definitions/npm/cache-manager_v2.x.x/flow_v0.201.x-/cache-manager_v2.x.x.js new file mode 100644 index 0000000000..d518c0ee0c --- /dev/null +++ b/definitions/npm/cache-manager_v2.x.x/flow_v0.201.x-/cache-manager_v2.x.x.js @@ -0,0 +1,35 @@ +declare module 'cache-manager' { + declare type _CacheOptions = { ttl?: number, ... } + /*declare type CacheOptions = $Shape<_CacheOptions> | Object*/ + declare type CacheOptions = Object + declare type CachingOptions = _CacheOptions & { + ignoreCacheErrors?: bool, + isCacheableValue?: (value: mixed) => bool, + // typeof Promise? + promiseDependency?: any, + max?: number, + //any because this can be specified by a lot + store: any, + ... + } + declare class Cache { + get(key: mixed, options?: CacheOptions): Promise; + set(key: mixed, value: mixed, options?: CacheOptions): Promise; + del(key: mixed, options?: CacheOptions): Promise; + wrap(key: mixed, cb: (cacheCallback: Function) => mixed, options?: CacheOptions): Promise; + } + declare class caching { + constructor(options?: CachingOptions): Cache; + static (options?: CachingOptions): Cache; + } + declare class multiCaching { + constructor(caches: Cache[], options?: CachingOptions): Cache; + static (caches: Cache[], options?: CachingOptions): Cache; + } + declare module.exports: { + Cache: typeof Cache, + caching: typeof caching, + multiCaching: typeof multiCaching, + ... + } +} diff --git a/definitions/npm/cb-fetch_v1.10.x/flow_v0.104.x-/cb-fetch_v1.10.x.js b/definitions/npm/cb-fetch_v1.10.x/flow_v0.104.x-v0.200.x/cb-fetch_v1.10.x.js similarity index 100% rename from definitions/npm/cb-fetch_v1.10.x/flow_v0.104.x-/cb-fetch_v1.10.x.js rename to definitions/npm/cb-fetch_v1.10.x/flow_v0.104.x-v0.200.x/cb-fetch_v1.10.x.js diff --git a/definitions/npm/cb-fetch_v1.10.x/flow_v0.201.x-/cb-fetch_v1.10.x.js b/definitions/npm/cb-fetch_v1.10.x/flow_v0.201.x-/cb-fetch_v1.10.x.js new file mode 100644 index 0000000000..6c32ddc805 --- /dev/null +++ b/definitions/npm/cb-fetch_v1.10.x/flow_v0.201.x-/cb-fetch_v1.10.x.js @@ -0,0 +1,119 @@ +declare module 'cb-fetch' { + + declare module.exports: typeof request; + + declare type RequestBody = + | BodyInit + | Document + + declare type Type = + | 'arraybuffer' + | 'moz-chunked-arraybuffer' + | 'blob' + | 'moz-blob' + | 'document' + | 'msxml-document' + | 'formdata' + | 'json' + | 'text' + | 'moz-chunked-text' + + declare type Parameters = + | string + | { [string]: ?string | string[], ... } + | URLSearchParams + + declare type RequestURL = + | string + | URL + + declare type RequestOptions = {| + url: RequestURL; + method: string; + headers: HeadersInit; + parameters: Parameters; + body: RequestBody; + credentials: CredentialsType; + mode: ModeType; + responseType: Type; + responseMediaType: string; + timeout: number; + username: string; + password: string; + multipart: boolean; + tunneling: boolean; + XSLPattern: boolean; + |} + + declare type JSONValue = null | void | string | number | boolean | $Shape<{ [string]: JSONValue, ... }> | Array + declare class AnonXMLHttpRequest extends XMLHttpRequest {} + + declare type NormalizedResponse = {| + body: JSONValue | Blob | Document | FormData | ReadableStream | ArrayBuffer; + headers: { [string]: string, ... } | T; + instance: XMLHttpRequest | XDomainRequest | Response | AnonXMLHttpRequest; + statusCode?: number; + statusText?: string; + url?: string; + |} + + declare type ProgressEvent = {| + chunk: string | ArrayBuffer | Blob | Uint8Array | null; + aggregate: string | ArrayBuffer | Blob | Uint8Array | null; + loaded: number; + total: number; + lengthComputable: boolean; + |} + + declare type onSuccess = (response: NormalizedResponse) => any; + declare type onError = (response: NormalizedResponse) => any; + declare type Abort = () => void + + declare interface Done { + (onSuccess?: onSuccess, onError?: onError): Abort; + (callbacks?: { + success?: onSuccess, + error?: onError, + timeout?: () => any, + abort?: (event?: Event) => any, + ... + }): Abort; + } + + declare type Tail = {| + hook: Hook; + done: Done; + |} + + declare interface Hook { + (name: "loadstart", handler: () => boolean | void) : Tail; + (name: "download", handler: (event: ProgressEvent) => any): Tail; + (name: "loadend", handler: () => any) : Tail; + } + + declare type Querier = {| + query: (parameters?: Parameters) => Tail, + ...Tail + |} + + declare type Sender = {| + send: (body?: RequestBody) => Tail, + ...Tail + |} + + declare type Verb = (url?: RequestURL) => T + + declare type Methods = {| + get: Verb, + delete: Verb, + head: Verb, + post: Verb, + put: Verb, + patch: Verb, + ...Tail + |} + + declare function request(options?: $Shape): Methods + declare function request(url?: RequestURL): Methods + +} \ No newline at end of file diff --git a/definitions/npm/cb-fetch_v1.11.x/flow_v0.104.x-/cb-fetch_v1.11.x.js b/definitions/npm/cb-fetch_v1.11.x/flow_v0.104.x-v0.200.x/cb-fetch_v1.11.x.js similarity index 100% rename from definitions/npm/cb-fetch_v1.11.x/flow_v0.104.x-/cb-fetch_v1.11.x.js rename to definitions/npm/cb-fetch_v1.11.x/flow_v0.104.x-v0.200.x/cb-fetch_v1.11.x.js diff --git a/definitions/npm/cb-fetch_v1.11.x/flow_v0.201.x-/cb-fetch_v1.11.x.js b/definitions/npm/cb-fetch_v1.11.x/flow_v0.201.x-/cb-fetch_v1.11.x.js new file mode 100644 index 0000000000..f0f6056228 --- /dev/null +++ b/definitions/npm/cb-fetch_v1.11.x/flow_v0.201.x-/cb-fetch_v1.11.x.js @@ -0,0 +1,121 @@ +declare module 'cb-fetch' { + + declare module.exports: typeof request; + + declare type RequestBody = + | BodyInit + | Document + + declare type Type = + | 'arraybuffer' + | 'moz-chunked-arraybuffer' + | 'blob' + | 'moz-blob' + | 'document' + | 'msxml-document' + | 'formdata' + | 'json' + | 'text' + | 'moz-chunked-text' + + declare type Parameters = + | string + | { [string]: ?string | string[], ... } + | URLSearchParams + + declare type RequestURL = + | string + | URL + + declare type RequestOptions = {| + url: RequestURL; + method: string; + headers: HeadersInit; + parameters: Parameters; + body: RequestBody; + credentials: CredentialsType; + mode: ModeType; + responseType: Type; + responseMediaType: string; + timeout: number; + username: string; + password: string; + multipart: boolean; + tunneling: boolean; + XSLPattern: boolean; + |} + + declare type JSONValue = null | void | string | number | boolean | $Shape<{ [string]: JSONValue, ... }> | Array + declare class AnonXMLHttpRequest extends XMLHttpRequest {} + + declare type NormalizedResponse = {| + body: JSONValue | Blob | Document | FormData | ReadableStream | ArrayBuffer; + headers: { [string]: string, ... } | T; + instance: XMLHttpRequest | XDomainRequest | Response | AnonXMLHttpRequest; + statusCode?: number; + statusText?: string; + url?: string; + |} + + declare type ProgressEvent = {| + chunk: string | ArrayBuffer | Blob | Uint8Array | null; + aggregate: string | ArrayBuffer | Blob | Uint8Array | null; + loaded: number; + total: number; + lengthComputable: boolean; + |} + + declare type onSuccess = (response: NormalizedResponse) => any; + declare type onError = (response: NormalizedResponse) => any; + declare type Abort = () => void + + declare interface Done { + (onSuccess?: onSuccess, onError?: onError): Abort; + (callbacks?: {| + success?: onSuccess, + error?: onError, + timeout?: () => any, + abort?: (event?: Event) => any + |}): Abort; + } + + declare interface Pass { + (name: string, value: string): T; + (headers?: HeadersInit) : T; + } + + declare interface Hook { + (name: "loadstart", handler: () => boolean | void) : T; + (name: "download", handler: (event: ProgressEvent) => any): T; + (name: "loadend", handler: () => any) : T; + } + + declare class Common { + hook: Hook; + pass: Pass; + done: Done; + } + + declare class Querier extends Common { + query: (parameters?: Parameters) => Common; + } + + declare class Sender extends Common { + send: (body?: RequestBody) => Common; + } + + declare type Verb = (url?: RequestURL) => T + + declare class Methods extends Common { + get: Verb; + delete: Verb; + head: Verb; + post: Verb; + put: Verb; + patch: Verb; + } + + declare function request(options?: $Shape): Methods + declare function request(url?: RequestURL): Methods + + } diff --git a/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.104.x-/combine-section-reducers_v1.x.x.js b/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.104.x-v0.200.x/combine-section-reducers_v1.x.x.js similarity index 100% rename from definitions/npm/combine-section-reducers_v1.x.x/flow_v0.104.x-/combine-section-reducers_v1.x.x.js rename to definitions/npm/combine-section-reducers_v1.x.x/flow_v0.104.x-v0.200.x/combine-section-reducers_v1.x.x.js diff --git a/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.104.x-/test_combine-section-reducers.js b/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.104.x-v0.200.x/test_combine-section-reducers.js similarity index 100% rename from definitions/npm/combine-section-reducers_v1.x.x/flow_v0.104.x-/test_combine-section-reducers.js rename to definitions/npm/combine-section-reducers_v1.x.x/flow_v0.104.x-v0.200.x/test_combine-section-reducers.js diff --git a/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.201.x-/combine-section-reducers_v1.x.x.js b/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.201.x-/combine-section-reducers_v1.x.x.js new file mode 100644 index 0000000000..9e9bb35d65 --- /dev/null +++ b/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.201.x-/combine-section-reducers_v1.x.x.js @@ -0,0 +1,15 @@ +declare module 'combine-section-reducers' { + + /* + S = State + A = Action + E = EntireState + */ + + declare type Reducer = (state: S, action: A, ...rest: any) => S; + declare type SectionReducer = (state: S, action: A, entireState?: E) => S; + declare type CombinedSectionReducer = (state: $Shape & {...} | void, action: A, entireState?: E) => S; + declare function combineSectionReducers(reducers: O): CombinedSectionReducer<$ObjMap(r: Reducer) => S>, A, E>; + declare module.exports: typeof combineSectionReducers; + +} diff --git a/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.201.x-/test_combine-section-reducers.js b/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.201.x-/test_combine-section-reducers.js new file mode 100644 index 0000000000..cb1e40675f --- /dev/null +++ b/definitions/npm/combine-section-reducers_v1.x.x/flow_v0.201.x-/test_combine-section-reducers.js @@ -0,0 +1,50 @@ +// @flow +import type { SectionReducer, CombinedSectionReducer } from 'combine-section-reducers' +import combineSectionReducers from 'combine-section-reducers' + +type Action = { type: 'A', ... } | { type: 'B', ... }; +type AState = { foo: number, ... }; +const initialAState: AState = { foo: 1 } +const reducerA = (state = initialAState, action) => { + return state +} +type State = { + a: AState, + name: string, + age: number, + ... +}; + +// +// combineReducers API +// + +function reducerName(name: string, action: Action, entireState: State): string { + return name +} + +function reducerAge(age: number, action: Action, entireState: State): number { + return age +} + +const reducer0: CombinedSectionReducer = combineSectionReducers({ + a: reducerA, + name: reducerName, + age: reducerAge +}) + +const superReducer: SectionReducer<{ data: State, ... }, Action, { data: State, ... }> = combineSectionReducers({ + data: reducer0 +}); + +// $FlowExpectedError +combineSectionReducers() // wrong reducers argument +// $FlowExpectedError +combineSectionReducers([]) // wrong reducers argument + +// $FlowExpectedError +const reducer1: SectionReducer = combineSectionReducers({ + a: reducerA, + name: reducerName + // missing age reducer +}) diff --git a/definitions/npm/decimal.js-light_v2.3.x/flow_v0.104.x-/decimal.js-light_v2.3.x.js b/definitions/npm/decimal.js-light_v2.3.x/flow_v0.104.x-v0.200.x/decimal.js-light_v2.3.x.js similarity index 100% rename from definitions/npm/decimal.js-light_v2.3.x/flow_v0.104.x-/decimal.js-light_v2.3.x.js rename to definitions/npm/decimal.js-light_v2.3.x/flow_v0.104.x-v0.200.x/decimal.js-light_v2.3.x.js diff --git a/definitions/npm/decimal.js-light_v2.4.x/flow_v0.104.x-/decimal.js-light_v2.4.x.js b/definitions/npm/decimal.js-light_v2.3.x/flow_v0.201.x-/decimal.js-light_v2.3.x.js similarity index 100% rename from definitions/npm/decimal.js-light_v2.4.x/flow_v0.104.x-/decimal.js-light_v2.4.x.js rename to definitions/npm/decimal.js-light_v2.3.x/flow_v0.201.x-/decimal.js-light_v2.3.x.js diff --git a/definitions/npm/decimal.js-light_v2.4.x/flow_v0.104.x-v0.200.x/decimal.js-light_v2.4.x.js b/definitions/npm/decimal.js-light_v2.4.x/flow_v0.104.x-v0.200.x/decimal.js-light_v2.4.x.js new file mode 100644 index 0000000000..f78570252a --- /dev/null +++ b/definitions/npm/decimal.js-light_v2.4.x/flow_v0.104.x-v0.200.x/decimal.js-light_v2.4.x.js @@ -0,0 +1,573 @@ +declare module 'decimal.js-light' { + declare type Numeric = string | number | Decimal; + + declare type DecimalConfig = $Shape<{ + precision: number, + rounding: number, + toExpNeg: number, + toExpPos: number, + LN10: Numeric, + ... + }>; + + declare class Decimal { + /** + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * @param value {number|string|Decimal} A numeric value. + * + */ + constructor(value: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the absolute value of this Decimal. + */ + absoluteValue(): Decimal; + + /** + * Return a new Decimal whose value is the absolute value of this Decimal. + */ + abs(): Decimal; + + /** + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value + */ + comparedTo(y: Numeric): 1 | 0 | -1; + + /** + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value + */ + cmp(y: Numeric): 1 | 0 | -1; + + /** + * Return the number of decimal places of the value of this Decimal. + */ + decimalPlaces(): number; + + /** + * Return the number of decimal places of the value of this Decimal. + */ + dp(): number; + + /** + * Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to + * `precision` significant digits. + * + */ + dividedBy(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to + * `precision` significant digits. + * + */ + div(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, truncated to `precision` significant digits. + * + */ + dividedToIntegerBy(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, truncated to `precision` significant digits. + * + */ + idiv(y: Numeric): Decimal; + + /** + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + */ + equals(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + */ + eq(y: Numeric): boolean; + + /** + * Return the (base 10) exponent value of this Decimal (this.e is the base 10000000 exponent). + */ + exponent(): number; + + /** + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + */ + greaterThan(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + */ + gt(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + greaterThanOrEqualTo(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + gte(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + isInteger(): boolean; + + /** + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + isint(): boolean; + + /** + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + isNegative(): boolean; + + /** + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + isneg(): boolean; + + /** + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + isPositive(): boolean; + + /** + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + ispos(): boolean; + + /** + * Return true if the value of this Decimal is 0, otherwise return false. + * + */ + isZero(): boolean; + + /** + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + lessThan(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + lt(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + lessThanOrEqualTo(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + lte(y: Numeric): boolean; + + /** + * Return the logarithm of the value of this Decimal to the specified base, truncated to + * `precision` significant digits. + * + * If no base is specified, return log[10](x). + * + * log[base](x) = ln(x) / ln(base) + * + * The maximum error of the result is 1 ulp (unit in the last place). + * + */ + logarithm(base?: Numeric): Decimal; + + /** + * Return the logarithm of the value of this Decimal to the specified base, truncated to + * `precision` significant digits. + * + * If no base is specified, return log[10](x). + * + * log[base](x) = ln(x) / ln(base) + * + * The maximum error of the result is 1 ulp (unit in the last place). + * + */ + log(base?: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to + * `precision` significant digits. + * + */ + minus(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to + * `precision` significant digits. + * + */ + sub(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to + * `precision` significant digits. + * + */ + modulo(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to + * `precision` significant digits. + * + */ + mod(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, truncated to `precision` + * significant digits. + * + */ + naturalExponetial(): Decimal; + + /** + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, truncated to `precision` + * significant digits. + * + */ + exp(): Decimal; + + /** + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * truncated to `precision` significant digits. + * + */ + naturalLogarithm(): Decimal; + + /** + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * truncated to `precision` significant digits. + * + */ + ln(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + negated(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + neg(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to + * `precision` significant digits. + * + */ + plus(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to + * `precision` significant digits. + * + */ + add(y: Numeric): Decimal; + + /** + * Return the number of significant digits of the value of this Decimal. + * + * @param zeros {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + */ + precision(zeros: boolean | number): number; + + /** + * Return the number of significant digits of the value of this Decimal. + * + * @param zeros {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + */ + sd(zeros: boolean | number): number; + + /** + * Return a new Decimal whose value is the square root of this Decimal, truncated to `precision` + * significant digits. + * + */ + squareRoot(): Decimal; + + /** + * Return a new Decimal whose value is the square root of this Decimal, truncated to `precision` + * significant digits. + * + */ + sqrt(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal times `y`, truncated to + * `precision` significant digits. + * + */ + times(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal times `y`, truncated to + * `precision` significant digits. + * + */ + mul(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * @param dp {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + toDecimalPlaces(dp?: number, rm?: number): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * @param dp {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + todp(dp?: number, rm?: number): Decimal; + + /** + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * @param dp {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + toExponential(dp?: number, rm?: number): string; + + /** + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * @param dp {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ + toFixed(dp?: number, rm?: number): string; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + toInteger(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + toint(): Decimal; + + /** + * Return the value of this Decimal converted to a number primitive. + * + */ + toNumber(): number; + + /** + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, + * truncated to `precision` significant digits. + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * The maximum error is 1 ulp (unit in last place). + * + * @param y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + toPower(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, + * truncated to `precision` significant digits. + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * The maximum error is 1 ulp (unit in last place). + * + * @param y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + pow(y: Numeric): Decimal; + + /** + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * @param sd {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + toPrecision(sd?: number, rm?: number): string; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * @param sd {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + toSignificantDigits(sd?: number, rm?: number): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * @param sd {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + tosd(sd?: number, rm?: number): Decimal; + + /** + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + toString(): string; + + /** + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + valueOf(): string; + + /** + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + val(): string; + + /** + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + toJSON(): string; + + /** + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + * @param config? DecimalConfig + */ + static clone(config?: DecimalConfig): typeof Decimal; + + /** + * Configure global settings for a Decimal constructor. + */ + static config(config: DecimalConfig): Decimal; + + /** + * Configure global settings for a Decimal constructor. + */ + static set(config: DecimalConfig): Decimal; + + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + static precision: number; + + // The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`, + // `toFixed`, `toPrecision` and `toSignificantDigits`. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + static rounding: number; + static +ROUND_UP: number; + static +ROUND_DOWN: number; + static +ROUND_CEIL: number; + static +ROUND_FLOOR: number; + static +ROUND_HALF_UP: number; + static +ROUND_HALF_DOWN: number; + static +ROUND_HALF_EVEN: number; + static +ROUND_HALF_CEIL: number; + static +ROUND_HALF_FLOOR: number; + + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + static toExpNeg: number; // 0 to -MAX_E + + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + static toExpPos: number;// 0 to MAX_E + + // The natural logarithm of 10. + static LN10: Decimal; + } + + declare module.exports: typeof Decimal; +} diff --git a/definitions/npm/decimal.js-light_v2.4.x/flow_v0.201.x-/decimal.js-light_v2.4.x.js b/definitions/npm/decimal.js-light_v2.4.x/flow_v0.201.x-/decimal.js-light_v2.4.x.js new file mode 100644 index 0000000000..f78570252a --- /dev/null +++ b/definitions/npm/decimal.js-light_v2.4.x/flow_v0.201.x-/decimal.js-light_v2.4.x.js @@ -0,0 +1,573 @@ +declare module 'decimal.js-light' { + declare type Numeric = string | number | Decimal; + + declare type DecimalConfig = $Shape<{ + precision: number, + rounding: number, + toExpNeg: number, + toExpPos: number, + LN10: Numeric, + ... + }>; + + declare class Decimal { + /** + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * @param value {number|string|Decimal} A numeric value. + * + */ + constructor(value: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the absolute value of this Decimal. + */ + absoluteValue(): Decimal; + + /** + * Return a new Decimal whose value is the absolute value of this Decimal. + */ + abs(): Decimal; + + /** + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value + */ + comparedTo(y: Numeric): 1 | 0 | -1; + + /** + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value + */ + cmp(y: Numeric): 1 | 0 | -1; + + /** + * Return the number of decimal places of the value of this Decimal. + */ + decimalPlaces(): number; + + /** + * Return the number of decimal places of the value of this Decimal. + */ + dp(): number; + + /** + * Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to + * `precision` significant digits. + * + */ + dividedBy(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to + * `precision` significant digits. + * + */ + div(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, truncated to `precision` significant digits. + * + */ + dividedToIntegerBy(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, truncated to `precision` significant digits. + * + */ + idiv(y: Numeric): Decimal; + + /** + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + */ + equals(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + */ + eq(y: Numeric): boolean; + + /** + * Return the (base 10) exponent value of this Decimal (this.e is the base 10000000 exponent). + */ + exponent(): number; + + /** + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + */ + greaterThan(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + */ + gt(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + greaterThanOrEqualTo(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + gte(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + isInteger(): boolean; + + /** + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + isint(): boolean; + + /** + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + isNegative(): boolean; + + /** + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + isneg(): boolean; + + /** + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + isPositive(): boolean; + + /** + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + ispos(): boolean; + + /** + * Return true if the value of this Decimal is 0, otherwise return false. + * + */ + isZero(): boolean; + + /** + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + lessThan(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + lt(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + lessThanOrEqualTo(y: Numeric): boolean; + + /** + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + lte(y: Numeric): boolean; + + /** + * Return the logarithm of the value of this Decimal to the specified base, truncated to + * `precision` significant digits. + * + * If no base is specified, return log[10](x). + * + * log[base](x) = ln(x) / ln(base) + * + * The maximum error of the result is 1 ulp (unit in the last place). + * + */ + logarithm(base?: Numeric): Decimal; + + /** + * Return the logarithm of the value of this Decimal to the specified base, truncated to + * `precision` significant digits. + * + * If no base is specified, return log[10](x). + * + * log[base](x) = ln(x) / ln(base) + * + * The maximum error of the result is 1 ulp (unit in the last place). + * + */ + log(base?: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to + * `precision` significant digits. + * + */ + minus(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to + * `precision` significant digits. + * + */ + sub(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to + * `precision` significant digits. + * + */ + modulo(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to + * `precision` significant digits. + * + */ + mod(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, truncated to `precision` + * significant digits. + * + */ + naturalExponetial(): Decimal; + + /** + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, truncated to `precision` + * significant digits. + * + */ + exp(): Decimal; + + /** + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * truncated to `precision` significant digits. + * + */ + naturalLogarithm(): Decimal; + + /** + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * truncated to `precision` significant digits. + * + */ + ln(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + negated(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + neg(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to + * `precision` significant digits. + * + */ + plus(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to + * `precision` significant digits. + * + */ + add(y: Numeric): Decimal; + + /** + * Return the number of significant digits of the value of this Decimal. + * + * @param zeros {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + */ + precision(zeros: boolean | number): number; + + /** + * Return the number of significant digits of the value of this Decimal. + * + * @param zeros {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + */ + sd(zeros: boolean | number): number; + + /** + * Return a new Decimal whose value is the square root of this Decimal, truncated to `precision` + * significant digits. + * + */ + squareRoot(): Decimal; + + /** + * Return a new Decimal whose value is the square root of this Decimal, truncated to `precision` + * significant digits. + * + */ + sqrt(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal times `y`, truncated to + * `precision` significant digits. + * + */ + times(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal times `y`, truncated to + * `precision` significant digits. + * + */ + mul(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * @param dp {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + toDecimalPlaces(dp?: number, rm?: number): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * @param dp {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + todp(dp?: number, rm?: number): Decimal; + + /** + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * @param dp {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + toExponential(dp?: number, rm?: number): string; + + /** + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * @param dp {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ + toFixed(dp?: number, rm?: number): string; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + toInteger(): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + toint(): Decimal; + + /** + * Return the value of this Decimal converted to a number primitive. + * + */ + toNumber(): number; + + /** + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, + * truncated to `precision` significant digits. + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * The maximum error is 1 ulp (unit in last place). + * + * @param y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + toPower(y: Numeric): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, + * truncated to `precision` significant digits. + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * The maximum error is 1 ulp (unit in last place). + * + * @param y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + pow(y: Numeric): Decimal; + + /** + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * @param sd {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + toPrecision(sd?: number, rm?: number): string; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * @param sd {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + toSignificantDigits(sd?: number, rm?: number): Decimal; + + /** + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * @param sd {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * @param rm {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + tosd(sd?: number, rm?: number): Decimal; + + /** + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + toString(): string; + + /** + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + valueOf(): string; + + /** + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + val(): string; + + /** + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + toJSON(): string; + + /** + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + * @param config? DecimalConfig + */ + static clone(config?: DecimalConfig): typeof Decimal; + + /** + * Configure global settings for a Decimal constructor. + */ + static config(config: DecimalConfig): Decimal; + + /** + * Configure global settings for a Decimal constructor. + */ + static set(config: DecimalConfig): Decimal; + + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + static precision: number; + + // The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`, + // `toFixed`, `toPrecision` and `toSignificantDigits`. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + static rounding: number; + static +ROUND_UP: number; + static +ROUND_DOWN: number; + static +ROUND_CEIL: number; + static +ROUND_FLOOR: number; + static +ROUND_HALF_UP: number; + static +ROUND_HALF_DOWN: number; + static +ROUND_HALF_EVEN: number; + static +ROUND_HALF_CEIL: number; + static +ROUND_HALF_FLOOR: number; + + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + static toExpNeg: number; // 0 to -MAX_E + + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + static toExpPos: number;// 0 to MAX_E + + // The natural logarithm of 10. + static LN10: Decimal; + } + + declare module.exports: typeof Decimal; +} diff --git a/definitions/npm/deepmerge_v2.1.x/flow_v0.104.x-/deepmerge_v2.1.x.js b/definitions/npm/deepmerge_v2.1.x/flow_v0.104.x-v0.200.x/deepmerge_v2.1.x.js similarity index 100% rename from definitions/npm/deepmerge_v2.1.x/flow_v0.104.x-/deepmerge_v2.1.x.js rename to definitions/npm/deepmerge_v2.1.x/flow_v0.104.x-v0.200.x/deepmerge_v2.1.x.js diff --git a/definitions/npm/deepmerge_v2.1.x/flow_v0.104.x-/test_deepmerge_v2.1.x.js b/definitions/npm/deepmerge_v2.1.x/flow_v0.104.x-v0.200.x/test_deepmerge_v2.1.x.js similarity index 100% rename from definitions/npm/deepmerge_v2.1.x/flow_v0.104.x-/test_deepmerge_v2.1.x.js rename to definitions/npm/deepmerge_v2.1.x/flow_v0.104.x-v0.200.x/test_deepmerge_v2.1.x.js diff --git a/definitions/npm/deepmerge_v2.1.x/flow_v0.201.x-/deepmerge_v2.1.x.js b/definitions/npm/deepmerge_v2.1.x/flow_v0.201.x-/deepmerge_v2.1.x.js new file mode 100644 index 0000000000..e252059db4 --- /dev/null +++ b/definitions/npm/deepmerge_v2.1.x/flow_v0.201.x-/deepmerge_v2.1.x.js @@ -0,0 +1,14 @@ +declare module 'deepmerge' { + declare type Options = { + clone?: boolean, + arrayMerge?: (destination: any[], source: any[], options?: Options) => Array, + ... + } + + declare module.exports: { + (a: A, b: B, options?: Options): A & B, + all(objects: Array<$Shape>, options?: Options): T, + ... + }; + +} diff --git a/definitions/npm/deepmerge_v3.x.x/flow_v0.104.x-/test_deepmerge_v3.x.x.js b/definitions/npm/deepmerge_v2.1.x/flow_v0.201.x-/test_deepmerge_v2.1.x.js similarity index 100% rename from definitions/npm/deepmerge_v3.x.x/flow_v0.104.x-/test_deepmerge_v3.x.x.js rename to definitions/npm/deepmerge_v2.1.x/flow_v0.201.x-/test_deepmerge_v2.1.x.js diff --git a/definitions/npm/deepmerge_v3.x.x/flow_v0.104.x-/deepmerge_v3.x.x.js b/definitions/npm/deepmerge_v3.x.x/flow_v0.104.x-v0.200.x/deepmerge_v3.x.x.js similarity index 100% rename from definitions/npm/deepmerge_v3.x.x/flow_v0.104.x-/deepmerge_v3.x.x.js rename to definitions/npm/deepmerge_v3.x.x/flow_v0.104.x-v0.200.x/deepmerge_v3.x.x.js diff --git a/definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-/test_deepmerge_v4.x.x.js b/definitions/npm/deepmerge_v3.x.x/flow_v0.104.x-v0.200.x/test_deepmerge_v3.x.x.js similarity index 100% rename from definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-/test_deepmerge_v4.x.x.js rename to definitions/npm/deepmerge_v3.x.x/flow_v0.104.x-v0.200.x/test_deepmerge_v3.x.x.js diff --git a/definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-/deepmerge_v4.x.x.js b/definitions/npm/deepmerge_v3.x.x/flow_v0.201.x-/deepmerge_v3.x.x.js similarity index 100% rename from definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-/deepmerge_v4.x.x.js rename to definitions/npm/deepmerge_v3.x.x/flow_v0.201.x-/deepmerge_v3.x.x.js diff --git a/definitions/npm/deepmerge_v3.x.x/flow_v0.201.x-/test_deepmerge_v3.x.x.js b/definitions/npm/deepmerge_v3.x.x/flow_v0.201.x-/test_deepmerge_v3.x.x.js new file mode 100644 index 0000000000..60447b190e --- /dev/null +++ b/definitions/npm/deepmerge_v3.x.x/flow_v0.201.x-/test_deepmerge_v3.x.x.js @@ -0,0 +1,8 @@ +const deepmerge = require("deepmerge"); + +const m1: { a: string, b: string, ... } = deepmerge({a: ''}, { b: '' }) + +const m2: { a: string, b: string, ... } = deepmerge.all([ {a: ''}, { b: '' } ]) + +// $FlowExpectedError[incompatible-type] +const m3: { a: number, b: string, ... } = deepmerge({a: ''}, { b: '' }) diff --git a/definitions/npm/deepmerge_v4.x.x/flow_v0.201.x-/deepmerge_v4.x.x.js b/definitions/npm/deepmerge_v4.x.x/flow_v0.201.x-/deepmerge_v4.x.x.js new file mode 100644 index 0000000000..9b636bb156 --- /dev/null +++ b/definitions/npm/deepmerge_v4.x.x/flow_v0.201.x-/deepmerge_v4.x.x.js @@ -0,0 +1,15 @@ +declare module 'deepmerge' { + declare type Options = { + clone?: boolean, + arrayMerge?: (destination: any[], source: any[], options?: Options) => Array, + isMergeableObject?: (value: { ... }) => boolean, + customMerge?: (key: string, options?: Options) => ((x: any, y: any) => any) | void, + ... + } + + declare module.exports: { + (a: A, b: B, options?: Options): A & B, + all(objects: Array<$Shape>, options?: Options): T, + ... + }; +} diff --git a/definitions/npm/deepmerge_v4.x.x/flow_v0.201.x-/test_deepmerge_v4.x.x.js b/definitions/npm/deepmerge_v4.x.x/flow_v0.201.x-/test_deepmerge_v4.x.x.js new file mode 100644 index 0000000000..60447b190e --- /dev/null +++ b/definitions/npm/deepmerge_v4.x.x/flow_v0.201.x-/test_deepmerge_v4.x.x.js @@ -0,0 +1,8 @@ +const deepmerge = require("deepmerge"); + +const m1: { a: string, b: string, ... } = deepmerge({a: ''}, { b: '' }) + +const m2: { a: string, b: string, ... } = deepmerge.all([ {a: ''}, { b: '' } ]) + +// $FlowExpectedError[incompatible-type] +const m3: { a: number, b: string, ... } = deepmerge({a: ''}, { b: '' }) diff --git a/definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-v0.200.x/deepmerge_v4.x.x.js b/definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-v0.200.x/deepmerge_v4.x.x.js new file mode 100644 index 0000000000..9b636bb156 --- /dev/null +++ b/definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-v0.200.x/deepmerge_v4.x.x.js @@ -0,0 +1,15 @@ +declare module 'deepmerge' { + declare type Options = { + clone?: boolean, + arrayMerge?: (destination: any[], source: any[], options?: Options) => Array, + isMergeableObject?: (value: { ... }) => boolean, + customMerge?: (key: string, options?: Options) => ((x: any, y: any) => any) | void, + ... + } + + declare module.exports: { + (a: A, b: B, options?: Options): A & B, + all(objects: Array<$Shape>, options?: Options): T, + ... + }; +} diff --git a/definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-v0.200.x/test_deepmerge_v4.x.x.js b/definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-v0.200.x/test_deepmerge_v4.x.x.js new file mode 100644 index 0000000000..60447b190e --- /dev/null +++ b/definitions/npm/deepmerge_v4.x.x/flow_v0.83.x-v0.200.x/test_deepmerge_v4.x.x.js @@ -0,0 +1,8 @@ +const deepmerge = require("deepmerge"); + +const m1: { a: string, b: string, ... } = deepmerge({a: ''}, { b: '' }) + +const m2: { a: string, b: string, ... } = deepmerge.all([ {a: ''}, { b: '' } ]) + +// $FlowExpectedError[incompatible-type] +const m3: { a: number, b: string, ... } = deepmerge({a: ''}, { b: '' }) diff --git a/definitions/npm/dompurify_v1.x.x/flow_v0.104.x-/dompurify_v1.x.x.js b/definitions/npm/dompurify_v1.x.x/flow_v0.104.x-v0.200.x/dompurify_v1.x.x.js similarity index 100% rename from definitions/npm/dompurify_v1.x.x/flow_v0.104.x-/dompurify_v1.x.x.js rename to definitions/npm/dompurify_v1.x.x/flow_v0.104.x-v0.200.x/dompurify_v1.x.x.js diff --git a/definitions/npm/dompurify_v1.x.x/flow_v0.201.x-/dompurify_v1.x.x.js b/definitions/npm/dompurify_v1.x.x/flow_v0.201.x-/dompurify_v1.x.x.js new file mode 100644 index 0000000000..4d7bf40f72 --- /dev/null +++ b/definitions/npm/dompurify_v1.x.x/flow_v0.201.x-/dompurify_v1.x.x.js @@ -0,0 +1,740 @@ +type dompurify$htmlTags = + | 'a' + | 'abbr' + | 'acronym' + | 'address' + | 'area' + | 'article' + | 'aside' + | 'audio' + | 'b' + | 'bdi' + | 'bdo' + | 'big' + | 'blink' + | 'blockquote' + | 'body' + | 'br' + | 'button' + | 'canvas' + | 'caption' + | 'center' + | 'cite' + | 'code' + | 'col' + | 'colgroup' + | 'content' + | 'data' + | 'datalist' + | 'dd' + | 'decorator' + | 'del' + | 'details' + | 'dfn' + | 'dir' + | 'div' + | 'dl' + | 'dt' + | 'element' + | 'em' + | 'fieldset' + | 'figcaption' + | 'figure' + | 'font' + | 'footer' + | 'form' + | 'h1' + | 'h2' + | 'h3' + | 'h4' + | 'h5' + | 'h6' + | 'head' + | 'header' + | 'hgroup' + | 'hr' + | 'html' + | 'i' + | 'img' + | 'input' + | 'ins' + | 'kbd' + | 'label' + | 'legend' + | 'li' + | 'main' + | 'map' + | 'mark' + | 'marquee' + | 'menu' + | 'menuitem' + | 'meter' + | 'nav' + | 'nobr' + | 'ol' + | 'optgroup' + | 'option' + | 'output' + | 'p' + | 'pre' + | 'progress' + | 'q' + | 'rp' + | 'rt' + | 'ruby' + | 's' + | 'samp' + | 'section' + | 'select' + | 'shadow' + | 'small' + | 'source' + | 'spacer' + | 'span' + | 'strike' + | 'strong' + | 'style' + | 'sub' + | 'summary' + | 'sup' + | 'table' + | 'tbody' + | 'td' + | 'template' + | 'textarea' + | 'tfoot' + | 'th' + | 'thead' + | 'time' + | 'tr' + | 'track' + | 'tt' + | 'u' + | 'ul' + | 'var' + | 'video' + | 'wbr' + | '#text'; + +type dompurify$htmlAttrs = + | 'accept' + | 'action' + | 'align' + | 'alt' + | 'autocomplete' + | 'background' + | 'bgcolor' + | 'border' + | 'cellpadding' + | 'cellspacing' + | 'checked' + | 'cite' + | 'class' + | 'clear' + | 'color' + | 'cols' + | 'colspan' + | 'coords' + | 'crossorigin' + | 'datetime' + | 'default' + | 'dir' + | 'disabled' + | 'download' + | 'enctype' + | 'face' + | 'for' + | 'headers' + | 'height' + | 'hidden' + | 'high' + | 'href' + | 'hreflang' + | 'id' + | 'integrity' + | 'ismap' + | 'label' + | 'lang' + | 'list' + | 'loop' + | 'low' + | 'max' + | 'maxlength' + | 'media' + | 'method' + | 'min' + | 'multiple' + | 'name' + | 'noshade' + | 'novalidate' + | 'nowrap' + | 'open' + | 'optimum' + | 'pattern' + | 'placeholder' + | 'poster' + | 'preload' + | 'pubdate' + | 'radiogroup' + | 'readonly' + | 'rel' + | 'required' + | 'rev' + | 'reversed' + | 'role' + | 'rows' + | 'rowspan' + | 'spellcheck' + | 'scope' + | 'selected' + | 'shape' + | 'size' + | 'sizes' + | 'span' + | 'srclang' + | 'start' + | 'src' + | 'srcset' + | 'step' + | 'style' + | 'summary' + | 'tabindex' + | 'title' + | 'type' + | 'usemap' + | 'valign' + | 'value' + | 'width' + | 'xmlns'; + +type dompurify$svgTags = + | 'svg' + | 'a' + | 'altglyph' + | 'altglyphdef' + | 'altglyphitem' + | 'animatecolor' + | 'animatemotion' + | 'animatetransform' + | 'audio' + | 'canvas' + | 'circle' + | 'clippath' + | 'defs' + | 'desc' + | 'ellipse' + | 'filter' + | 'font' + | 'g' + | 'glyph' + | 'glyphref' + | 'hkern' + | 'image' + | 'line' + | 'lineargradient' + | 'marker' + | 'mask' + | 'metadata' + | 'mpath' + | 'path' + | 'pattern' + | 'polygon' + | 'polyline' + | 'radialgradient' + | 'rect' + | 'stop' + | 'style' + | 'switch' + | 'symbol' + | 'text' + | 'textpath' + | 'title' + | 'tref' + | 'tspan' + | 'video' + | 'view' + | 'vkern'; + +type dompurify$svgAttrs = + | 'accent-height' + | 'accumulate' + | 'additivive' + | 'alignment-baseline' + | 'ascent' + | 'attributename' + | 'attributetype' + | 'azimuth' + | 'basefrequency' + | 'baseline-shift' + | 'begin' + | 'bias' + | 'by' + | 'class' + | 'clip' + | 'clip-path' + | 'clip-rule' + | 'color' + | 'color-interpolation' + | 'color-interpolation-filters' + | 'color-profile' + | 'color-rendering' + | 'cx' + | 'cy' + | 'd' + | 'dx' + | 'dy' + | 'diffuseconstant' + | 'direction' + | 'display' + | 'divisor' + | 'dur' + | 'edgemode' + | 'elevation' + | 'end' + | 'fill' + | 'fill-opacity' + | 'fill-rule' + | 'filter' + | 'flood-color' + | 'flood-opacity' + | 'font-family' + | 'font-size' + | 'font-size-adjust' + | 'font-stretch' + | 'font-style' + | 'font-variant' + | 'font-weight' + | 'fx' + | 'fy' + | 'g1' + | 'g2' + | 'glyph-name' + | 'glyphref' + | 'gradientunits' + | 'gradienttransform' + | 'height' + | 'href' + | 'id' + | 'image-rendering' + | 'in' + | 'in2' + | 'k' + | 'k1' + | 'k2' + | 'k3' + | 'k4' + | 'kerning' + | 'keypoints' + | 'keysplines' + | 'keytimes' + | 'lang' + | 'lengthadjust' + | 'letter-spacing' + | 'kernelmatrix' + | 'kernelunitlength' + | 'lighting-color' + | 'local' + | 'marker-end' + | 'marker-mid' + | 'marker-start' + | 'markerheight' + | 'markerunits' + | 'markerwidth' + | 'maskcontentunits' + | 'maskunits' + | 'max' + | 'mask' + | 'media' + | 'method' + | 'mode' + | 'min' + | 'name' + | 'numoctaves' + | 'offset' + | 'operator' + | 'opacity' + | 'order' + | 'orient' + | 'orientation' + | 'origin' + | 'overflow' + | 'paint-order' + | 'path' + | 'pathlength' + | 'patterncontentunits' + | 'patterntransform' + | 'patternunits' + | 'points' + | 'preservealpha' + | 'preserveaspectratio' + | 'r' + | 'rx' + | 'ry' + | 'radius' + | 'refx' + | 'refy' + | 'repeatcount' + | 'repeatdur' + | 'restart' + | 'result' + | 'rotate' + | 'scale' + | 'seed' + | 'shape-rendering' + | 'specularconstant' + | 'specularexponent' + | 'spreadmethod' + | 'stddeviation' + | 'stitchtiles' + | 'stop-color' + | 'stop-opacity' + | 'stroke-dasharray' + | 'stroke-dashoffset' + | 'stroke-linecap' + | 'stroke-linejoin' + | 'stroke-miterlimit' + | 'stroke-opacity' + | 'stroke' + | 'stroke-width' + | 'style' + | 'surfacescale' + | 'tabindex' + | 'targetx' + | 'targety' + | 'transform' + | 'text-anchor' + | 'text-decoration' + | 'text-rendering' + | 'textlength' + | 'type' + | 'u1' + | 'u2' + | 'unicode' + | 'values' + | 'viewbox' + | 'visibility' + | 'vert-adv-y' + | 'vert-origin-x' + | 'vert-origin-y' + | 'width' + | 'word-spacing' + | 'wrap' + | 'writing-mode' + | 'xchannelselector' + | 'ychannelselector' + | 'x' + | 'x1' + | 'x2' + | 'xmlns' + | 'y' + | 'y1' + | 'y2' + | 'z' + | 'zoomandpan'; + +type dompurify$svgFilters = + | 'feBlend' + | 'feColorMatrix' + | 'feComponentTransfer' + | 'feComposite' + | 'feConvolveMatrix' + | 'feDiffuseLighting' + | 'feDisplacementMap' + | 'feDistantLight' + | 'feFlood' + | 'feFuncA' + | 'feFuncB' + | 'feFuncG' + | 'feFuncR' + | 'feGaussianBlur' + | 'feMerge' + | 'feMergeNode' + | 'feMorphology' + | 'feOffset' + | 'fePointLight' + | 'feSpecularLighting' + | 'feSpotLight' + | 'feTile' + | 'feTurbulence'; + +type dompurify$mathMlTags = + | 'math' + | 'menclose' + | 'merror' + | 'mfenced' + | 'mfrac' + | 'mglyph' + | 'mi' + | 'mlabeledtr' + | 'mmuliscripts' + | 'mn' + | 'mo' + | 'mover' + | 'mpadded' + | 'mphantom' + | 'mroot' + | 'mrow' + | 'ms' + | 'mpspace' + | 'msqrt' + | 'mystyle' + | 'msub' + | 'msup' + | 'msubsup' + | 'mtable' + | 'mtd' + | 'mtext' + | 'mtr' + | 'munder' + | 'munderover'; + +type dompurify$mathMlAttrs = + | 'accent' + | 'accentunder' + | 'align' + | 'bevelled' + | 'close' + | 'columnsalign' + | 'columnlines' + | 'columnspan' + | 'denomalign' + | 'depth' + | 'dir' + | 'display' + | 'displaystyle' + | 'fence' + | 'frame' + | 'height' + | 'href' + | 'id' + | 'largeop' + | 'length' + | 'linethickness' + | 'lspace' + | 'lquote' + | 'mathbackground' + | 'mathcolor' + | 'mathsize' + | 'mathvariant' + | 'maxsize' + | 'minsize' + | 'movablelimits' + | 'notation' + | 'numalign' + | 'open' + | 'rowalign' + | 'rowlines' + | 'rowspacing' + | 'rowspan' + | 'rspace' + | 'rquote' + | 'scriptlevel' + | 'scriptminsize' + | 'scriptsizemultiplier' + | 'selection' + | 'separator' + | 'separators' + | 'stretchy' + | 'subscriptshift' + | 'supscriptshift' + | 'symmetric' + | 'voffset' + | 'width' + | 'xmlns'; + +type dompurify$tags = dompurify$htmlTags | dompurify$svgTags | dompurify$svgFilters | dompurify$mathMlTags; + +type dompurify$attr = dompurify$htmlAttrs | dompurify$svgAttrs | dompurify$mathMlAttrs; + +type dompurify$configBase = {| + /** + * make output safe for usage in jQuery's $()/html() method (default is false) + */ + SAFE_FOR_JQUERY: boolean, + /** + * strip {{ ... }} and <% ... %> to make output safe for template systems + */ + SAFE_FOR_TEMPLATES: boolean, + /** + * allow only tags + */ + ALLOWED_TAGS: Array, + /** + * allow only attrs + */ + ALLOWED_ATTR: Array, + /** + * allow all safe elements of different types + */ + USE_PROFILES: $Shape<{ + html: boolean, + svg: boolean, + svgFilters: boolean, + mathMl: boolean, + ... + }>, + /** + * leave all as it is but forbid specified tags + */ + FORBID_TAGS: Array, + /** + * leave all as it is but forbid specified attrs + */ + FORBID_ATTR: Array, + /** + * extend the existing array of allowed tags + */ + ADD_TAGS: Array, + /** + * extend the existing array of attributes + */ + ADD_ATTR: Array, + /** + * prohibit HTML5 data attributes (default is true) + */ + ALLOW_DATA_ATTR: boolean, + /** + * allow external protocol handlers in URL attributes (default is false) + * by default only http, https, ftp, ftps, tel, mailto, callto, cid and xmpp are allowed. + */ + ALLOW_UNKNOWN_PROTOCOLS: boolean, + /** + * allow specific protocols handlers in URL attributes (default is false) + * by default only http, https, ftp, ftps, tel, mailto, callto, cid and xmpp are allowed. + * Default RegExp: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i; + */ + ALLOWED_URI_REGEXP: RegExp, + /** + * return a DOM HTMLBodyElement instead of an HTML string (default is false) + */ + RETURN_DOM: boolean, + /** + * return a DOM DocumentFragment instead of an HTML string (default is false) + */ + RETURN_DOM_FRAGMENT: boolean, + /** + * Import DocumentFragment into the current document (default is false). + * RETURN_DOM_IMPORT must be set if you would like to append the returned node to the current document + */ + RETURN_DOM_IMPORT: boolean, + /** + * return entire document as string including tags (default is false) + */ + WHOLE_DOCUMENT: boolean, + /** + * disable DOM Clobbering protection on output (default is true, handle with care!) + */ + SANITIZE_DOM: boolean, + /** + * discard an element's content when the element is removed (default is true) + */ + KEEP_CONTENT: boolean, + /** + * glue elements like style, script or others to document.body and prevent unintuitive browser behavior + * in several edge-cases (default is false) + */ + FORCE_BODY: boolean, + /** + * use the IN_PLACE mode to sanitize a node "in place", which is much faster depending on how you use DOMpurify + */ + IN_PLACE: boolean, +|}; + +type dompurify$hookType = + | 'beforeSanitizeElements' + | 'uponSanitizeElement' + | 'afterSanitizeElements' + | 'beforeSanitizeAttributes' + | 'uponSanitizeAttribute' + | 'afterSanitizeAttributes' + | 'beforeSanitizeShadowDOM' + | 'uponSanitizeShadowNode' + | 'afterSanitizeShadowDOM'; + +type dompurify$hookEvent = { + +tagName: ?dompurify$tags, + +allowedTags: ?{ [dompurify$tags]: boolean, ... }, + +allowedAttributes: ?{ [dompurify$attr]: boolean, ... }, + +attrName: ?dompurify$attr, + +attrValue: ?string, + // This is intended to be writable + keepAttr: ?boolean, + ... +}; + +declare type dompurify$config = $Shape; + +type dompurify$hook = (node: Node, data: ?dompurify$hookEvent, config?: dompurify$config) => void; + +interface dompurify$sanitizer { + (dirty: string, config: $Shape<$Diff>): string, + (dirty: string, config: dompurify$config & { + RETURN_DOM: false, + RETURN_DOM_FRAGMENT: false, + ... + }): string, + (dirty: string, config: dompurify$config & { + RETURN_DOM: true, + RETURN_DOM_FRAGMENT?: void | false, + ... + }): HTMLBodyElement, + (dirty: string, config: dompurify$config & { + RETURN_DOM?: void | false, + RETURN_DOM_FRAGMENT: true, + ... + }): DocumentFragment, + (dirty: string): string, +} + +type dompurify$instance = {| + +version: string, + +removed: Array<{ element: Node, ... } | { + attribute: ?Attr, + from: Node, + ... + }>, + +isSupported: boolean, + sanitize: dompurify$sanitizer, + setConfig: (config: dompurify$config) => void, + clearConfig: () => void, + isValidAttribute: (tag: string, attr: string, value: string) => boolean, + addHook: (dompurify$hookType, dompurify$hook) => void, + removeHook: (dompurify$hookType) => void, + removeHooks: (dompurify$hookType) => void, + removeAllHooks: () => void, +|}; + +type dompurify$creator = (window?: any) => dompurify$instance; + +declare module 'dompurify' { + declare module.exports: dompurify$creator; +} +declare module 'dompurify/dist/purify.cjs' { + declare module.exports: dompurify$creator; +} +declare module 'dompurify/dist/purify.es' { + declare module.exports: dompurify$creator; +} +declare module 'dompurify/dist/purify' { + declare module.exports: dompurify$creator; +} +declare module 'dompurify/dist/purify.min' { + declare module.exports: dompurify$creator; +} + +declare module 'dompurify/dist/purify.cjs.js' { + declare module.exports: $Exports<'dompurify/dist/purify.cjs'>; +} +declare module 'dompurify/dist/purify.es.js' { + declare module.exports: $Exports<'dompurify/dist/purify.es'>; +} +declare module 'dompurify/dist/purify.js' { + declare module.exports: $Exports<'dompurify/dist/purify'>; +} +declare module 'dompurify/dist/purify.min.js' { + declare module.exports: $Exports<'dompurify/dist/purify.min'>; +} diff --git a/definitions/npm/dotenv_v8.x.x/flow_v0.53.x-/dotenv_v8.x.x.js b/definitions/npm/dotenv_v8.x.x/flow_v0.201.x-/dotenv_v8.x.x.js similarity index 100% rename from definitions/npm/dotenv_v8.x.x/flow_v0.53.x-/dotenv_v8.x.x.js rename to definitions/npm/dotenv_v8.x.x/flow_v0.201.x-/dotenv_v8.x.x.js diff --git a/definitions/npm/dotenv_v8.x.x/flow_v0.53.x-v0.200.x/dotenv_v8.x.x.js b/definitions/npm/dotenv_v8.x.x/flow_v0.53.x-v0.200.x/dotenv_v8.x.x.js new file mode 100644 index 0000000000..bb0dd08a6e --- /dev/null +++ b/definitions/npm/dotenv_v8.x.x/flow_v0.53.x-v0.200.x/dotenv_v8.x.x.js @@ -0,0 +1,23 @@ +// @flow + +declare module 'dotenv' { + declare type ParseResult = {| [key: string]: string |}; + declare type ConfigResult = {| parsed: ParseResult |} | {| error: Error |}; + declare function config( + options?: $Shape<{| path: string, encoding: string, debug: boolean |}> + ): ConfigResult; + + declare function parse( + buffer: Buffer | string, + options?: $Shape<{| debug: boolean |}> + ): ParseResult; + + declare module.exports: {| + config: typeof config, + parse: typeof parse, + |}; +} + +// eslint-disable-next-line no-empty +declare module 'dotenv/config' { +} diff --git a/definitions/npm/formik_v0.11.x/flow_v0.104.x-/formik_v0.11.x.js b/definitions/npm/formik_v0.11.x/flow_v0.104.x-v0.200.x/formik_v0.11.x.js similarity index 100% rename from definitions/npm/formik_v0.11.x/flow_v0.104.x-/formik_v0.11.x.js rename to definitions/npm/formik_v0.11.x/flow_v0.104.x-v0.200.x/formik_v0.11.x.js diff --git a/definitions/npm/formik_v0.11.x/flow_v0.104.x-/test_formik.js b/definitions/npm/formik_v0.11.x/flow_v0.104.x-v0.200.x/test_formik.js similarity index 100% rename from definitions/npm/formik_v0.11.x/flow_v0.104.x-/test_formik.js rename to definitions/npm/formik_v0.11.x/flow_v0.104.x-v0.200.x/test_formik.js diff --git a/definitions/npm/formik_v0.11.x/flow_v0.201.x-/formik_v0.11.x.js b/definitions/npm/formik_v0.11.x/flow_v0.201.x-/formik_v0.11.x.js new file mode 100644 index 0000000000..bac9b51f97 --- /dev/null +++ b/definitions/npm/formik_v0.11.x/flow_v0.201.x-/formik_v0.11.x.js @@ -0,0 +1,276 @@ +declare module "formik" { + declare export type FormikErrors = { [field: $Keys]: ?string, ... }; + + declare export type FormikTouched = { [field: $Keys]: boolean, ... }; + + /** + * Using interface here because interfaces support overloaded method signatures + * https://github.com/facebook/flow/issues/1556#issuecomment-200051475 + */ + declare export interface FormikActions { + /** Manually set top level status. */ + setStatus(status?: any): void; + /** + * Manually set top level error + * @deprecated since 0.8.0 + */ + setError(e: any): void; + /** Manually set errors object */ + setErrors(errors: FormikErrors): void; + /** Manually set isSubmitting */ + setSubmitting(isSubmitting: boolean): void; + /** Manually set touched object */ + setTouched(touched: FormikTouched): void; + /** Manually set values object */ + setValues(values: Values): void; + /** Set value of form field directly */ + setFieldValue>( + field: FieldName, + // I don't understand why we have to wrap this with $Call. I feel + // like we should just be able to do + // value: $ElementType. But apparently this + // doesn't work. + value: $Call<() => $ElementType>, + shouldValidate?: boolean + ): void; + /** Set error message of a form field directly */ + setFieldError(field: $Keys, message: string): void; + /** Set whether field has been touched directly */ + setFieldTouched( + field: $Keys, + isTouched?: boolean, + shouldValidate?: boolean + ): void; + /** Validate form values */ + validateForm(values?: any): void; + /** Reset form */ + resetForm(nextValues?: any): void; + /** Submit the form imperatively */ + submitForm(): void; + /** Set Formik state, careful! */ + setFormikState( + f: ( + prevState: $ReadOnly>, + props: any + ) => $Shape>, + callback?: () => any + ): void; + } + + declare export type FormikSharedConfig = { + /** Tells Formik to validate the form on each input's onChange event */ + validateOnChange?: boolean, + /** Tells Formik to validate the form on each input's onBlur event */ + validateOnBlur?: boolean, + /** Tell Formik if initial form values are valid or not on first render */ + isInitialValid?: boolean | ((props: {...}) => boolean | void), + /** Should Formik reset the form when new initialValues change */ + enableReinitialize?: boolean, + ... + }; + + declare export type FormikConfig = FormikSharedConfig & { + /** + * Initial values of the form + */ + initialValues?: Values, + /** + * Reset handler + */ + onReset?: (values: Values, formikActions: FormikActions) => void, + /** + * Submission handler + */ + onSubmit: (values: Values, formikActions: FormikActions) => any, + /** + * Form component to render + */ + component?: React$ComponentType> | React$Node, + /** + * Render prop (works like React router's } />) + */ + render?: (props: FormikProps) => React$Node, + /** + * A Yup Schema or a function that returns a Yup schema + */ + validationSchema?: any | (() => any), + /** + * Validation function. Must return an error object or promise that + * throws an error object where that object keys map to corresponding value. + */ + validate?: (values: Values) => void | FormikErrors | Promise, + /** + * React children or child render callback + */ + children?: ((props: FormikProps) => React$Node) | React$Node, + ... + }; + + /** + * Formik state tree + */ + declare export type FormikState = { + /** Form values */ + values: Values, + /** + * Top level error, in case you need it + * @deprecated since 0.8.0 + */ + error?: any, + /** map of field names to specific error for that field */ + errors: FormikErrors, + /** map of field names to whether the field has been touched */ + touched: FormikTouched, + /** whether the form is currently submitting */ + isSubmitting: boolean, + /** Top level status state, in case you need it */ + status?: any, + /** Number of times user tried to submit the form */ + submitCount: number, + ... + }; + + /** + * Formik computed properties. These are read-only. + */ + declare export type FormikComputedProps = { + /** True if any input has been touched. False otherwise. */ + +dirty: boolean, + /** Result of isInitiallyValid on mount, then whether true values pass validation. */ + +isValid: boolean, + /** initialValues */ + +initialValues: Values, + ... + }; + + /** + * Formik form event handlers + */ + declare export type FormikHandlers = { + /** Form submit handler */ + handleSubmit: (e: SyntheticEvent) => any, + /** Classic React change handler, keyed by input name */ + handleChange: (e: SyntheticEvent) => any, + /** Classic React blur handler */ + handleBlur: (e: any) => void, + /** Reset form event handler */ + handleReset: () => void, + ... + }; + + declare export type FormikProps = FormikState & + FormikActions & + FormikHandlers & + FormikComputedProps; + + declare export class Formik< + Values: Object, + Props: FormikConfig, + + > extends React$Component {} + + /** + * Note: These typings could be more restrictive, but then it would limit the + * reusability of custom components. + * + * @example + * type MyProps = { + * ...FieldProps, + * ... + * } + * + * export const MyInput = ({ + * field, + * form, + * ...props + * }: MyProps) => + *
+ * + * {form.touched[field.name] && form.errors[field.name]} + *
+ */ + declare export type FieldProps = { + field: { + /** Classic React change handler, keyed by input name */ + // TODO: React.ChangeEvent + onChange: (e: any) => any, + /** Mark input as touched */ + onBlur: (e: any) => any, + /** Value of the input */ + value: any, + /* name of the input */ + name: string, + ... + }, + form: FormikProps, + ... + }; + + /* + import * as React from 'react'; + + type OwnProps = {}; + type Props = OwnProps & FormikProps; + class MyFormikHoc extends React.Component { + render() { + const { setFieldValue, status, errors, dirty } = this.props; + } + } + + const enhancer = withFormik({}); + + // TODO - extract FormikProps from enhancer + type FormikProps = $Call + + export default enhancer(MyFormikHoc); + */ + + declare export var Field: React$StatelessFunctionalComponent; + + declare export var Form: React$StatelessFunctionalComponent; + + /** + * Formik actions + { props } + */ + declare export type FormikBag = { props: P, ... } & FormikActions; + + /** + * withFormik() configuration options. Backwards compatible. + */ + declare export type WithFormikConfig< + Props, + Values, + > = FormikSharedConfig & { + /** + * Set the display name of the component. Useful for React DevTools. + */ + displayName?: string, + /** + * Submission handler + */ + handleSubmit: (values: Values, formikBag: FormikBag) => void, + /** + * Map props to the form values + */ + mapPropsToValues?: (props: Props) => Values, + /** + * A Yup Schema or a function that returns a Yup schema + */ + validationSchema?: any | ((props: Props) => any), + /** + * Validation function. Must return an error object or promise that + * throws an error object where that object keys map to corresponding value. + */ + validate?: (values: Values) => void | FormikErrors | Promise, + ... + } + + declare type TypeOrVoid = (V) => (V | void) + + declare export function withFormik< + Props, + Values, + >(WithFormikConfig): ( + Component: React$ComponentType + ) => React$ComponentType<$Diff, TypeOrVoid>>>; +} diff --git a/definitions/npm/formik_v0.11.x/flow_v0.201.x-/test_formik.js b/definitions/npm/formik_v0.11.x/flow_v0.201.x-/test_formik.js new file mode 100644 index 0000000000..196bbd0966 --- /dev/null +++ b/definitions/npm/formik_v0.11.x/flow_v0.201.x-/test_formik.js @@ -0,0 +1,379 @@ +// @flow + +import * as React from "react"; +import { Formik, Form, Field } from "formik"; +import type { FieldProps, FormikActions, FormikProps } from "formik"; +import { describe, it } from "flow-typed-test"; + +const i18n = { loadNamespaces: () => {} }; + +type Values = { + text: string, + ... +}; + +describe("formik", () => { + describe("", () => { + it("passes when used properly", () => { + { + const errors = {}; + if (!values.text) { + errors.text = "Text Required"; + } + return errors; + }} + onSubmit={( + values, + { setSubmitting, setFieldError } + ) => { + setFieldError("text", "Text is Required!"); + setSubmitting(false); + }} + render={({ + values, + errors, + touched, + handleChange, + handleBlur, + handleSubmit, + isSubmitting + }) => { + return ( +
+ ) => { + handleChange(e); + }} + onBlur={handleBlur} + value={values.text} + /> + {touched.text && errors.text &&
{errors.text}
} + +
+ ); + }} + />; + }); + + it("raises error when trying to access values not in Values", () => { + { + const errors = {}; + if (!values.text) { + errors.text = "Text Required"; + } + return errors; + }} + onSubmit={(values) => {}} + render={({ + // $FlowExpectedError[incompatible-use] + values, + // $FlowExpectedError[incompatible-use] + errors, + // $FlowExpectedError[incompatible-use] + touched, + handleChange, + handleBlur, + handleSubmit, + isSubmitting + }) => { + return ( +
+ + {touched.email && errors.email &&
{errors.email}
} + +
+ ); + }} + />; + }); + + it("raises error when trying to update fields with values of the wrong type", () => { + {}} + render={({ + values, + // $FlowExpectedError[incompatible-use] + setFieldValue, + }) => { + return ( +
+ +
+ ); + }} + />; + }); + }); + + it("respects the user specifying more specific initialValues", () => { + type FormValues = { + requestState: "loading" | "ready", + ... + } + const initialValues: FormValues = {requestState: "loading"} + const rendered = {}} + render={({ + // $FlowExpectedError[incompatible-use] + setFieldValue, + }) => { + return ( +
+ +
+ ); + }} + />; + }) + + describe("FormikActions", () => { + describe("setStatus", () => { + it("passes when using setStatus properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setStatus("done"); + }; + }); + + it("raises error when passed more than one argument", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[extra-arg] - no more than 1 argument is expected + actions.setStatus("text", "done"); + }; + }); + }); + + describe("setErrors", () => { + it("passes when using setErrors properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setErrors({ text: "Text is required" }); + }; + }); + + it("raises error when passed an unrecognized value key", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[prop-missing] setErrors keys must match value fields + actions.setErrors({ other: "Text is required" }); + }; + }); + }); + + describe("setSubmitting", () => { + it("passes when using setSubmitting properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setSubmitting(false); + }; + }); + + it("raises error when passed a non-boolean", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[incompatible-call] setSubmitting only takes a boolean + actions.setSubmitting("false"); + }; + }); + }); + + describe("setTouched", () => { + it("passes when using setTouched properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setTouched({ + text: true + }); + }; + }); + + it("raises error when passed an unrecognized field or a non-boolean", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[prop-missing] - property `other` is missing in `Values` + actions.setTouched({ other: true }); + // $FlowExpectedError[incompatible-call] - string is incompatible with boolean + actions.setTouched({ text: "true" }); + }; + }); + }); + + describe("setValues", () => { + it("passes when using setValues properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setValues({ + text: "Text" + }); + }; + }); + + it("raises error when passed something other than Values", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[prop-missing] - property `text` is missing in object + actions.setValues({ other: "Text" }); + }; + }); + }); + + describe("setFieldValue", () => { + it("passes when used properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setFieldValue("text", "Value"); + actions.setFieldValue("text", "Value", true); + // $FlowExpectedError[prop-missing] - property `other` is missing in `Values` + actions.setFieldValue("other", "Value"); + }; + }); + + it("raises error when not passed a field", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[incompatible-call] - object literal is incompatible with key set + actions.setFieldValue<$Keys>({ text: "Text" }); + }; + }); + }); + + describe("setFieldError", () => { + it("passes when used properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setFieldError("text", "Error"); + // $FlowExpectedError[prop-missing] - property `other` is missing in `Values` + actions.setFieldError("other", "Error"); + }; + }); + + it("raises error when field does not exist", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[prop-missing] - property `Error` is missing in `Values` + actions.setFieldError("Error",''); + }; + }); + + it("raises error when not passed a field", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[incompatible-call] - function requires another argument + actions.setFieldError("text"); + }; + }); + }); + + describe("setFieldTouched", () => { + it("passes when used properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setFieldTouched("text", true); + // $FlowExpectedError[prop-missing] - 'other' is not a key in values + actions.setFieldTouched("other", true); + }; + }); + + it("raises error when not passed a field", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[incompatible-call] - Field and value arguments expected + actions.setFieldTouched(true); + }; + }); + }); + + describe("validateForm", () => { + it("passes when used properly", () => { + const testFunc = (actions: FormikActions) => { + actions.validateForm(); + actions.validateForm({ text: "Text" }); + }; + }); + }); + + describe("resetForm", () => { + it("passes when used properly", () => { + const testFunc = (actions: FormikActions) => { + actions.resetForm(); + actions.resetForm({ text: "Text" }); + }; + }); + + it("raises error if pass multiple arguments", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[extra-arg] - resetForm expects 0 or 1 arguments + actions.resetForm("text", "Text"); + }; + }); + }); + + describe("submitForm", () => { + it("passes when used properly", () => { + const testFunc = (actions: FormikActions) => { + actions.submitForm(); + }; + }); + + it("raises error if passed an argument", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[extra-arg] - submitForm expects no arguments + actions.submitForm({ text: "Text" }); + }; + }); + }); + + describe("setFormikState", () => { + it("passes when used properly", () => { + const testFunc = (actions: FormikActions) => { + actions.setFormikState(({ values }) => ({ + values: { text: `#${values.text}` } + })); + actions.setFormikState( + ({ errors }) => ({ + errors: { ...errors, text: "Text is required" } + }), + () => {} + ); + }; + }); + + it("raises error if return state shape other than FormikState", () => { + const testFunc = (actions: FormikActions) => { + // $FlowExpectedError[prop-missing] - must return correct state shape + actions.setFormikState(({ values }) => ({ + text: `#${values.text}` + })); + }; + }); + }); + }); + + describe("
and ", () => { + it("passes when used properly", () => { + const CustomInputComponent = (props: FieldProps) => ; + + + + + + + + + + ; + }); + }); +}); diff --git a/definitions/npm/formik_v2.x.x/flow_v0.104.x-/formik_v2.x.x.js b/definitions/npm/formik_v2.x.x/flow_v0.104.x-v0.200.x/formik_v2.x.x.js similarity index 100% rename from definitions/npm/formik_v2.x.x/flow_v0.104.x-/formik_v2.x.x.js rename to definitions/npm/formik_v2.x.x/flow_v0.104.x-v0.200.x/formik_v2.x.x.js diff --git a/definitions/npm/formik_v2.x.x/flow_v0.104.x-/test_formik.js b/definitions/npm/formik_v2.x.x/flow_v0.104.x-v0.200.x/test_formik.js similarity index 100% rename from definitions/npm/formik_v2.x.x/flow_v0.104.x-/test_formik.js rename to definitions/npm/formik_v2.x.x/flow_v0.104.x-v0.200.x/test_formik.js diff --git a/definitions/npm/formik_v2.x.x/flow_v0.201.x-/formik_v2.x.x.js b/definitions/npm/formik_v2.x.x/flow_v0.201.x-/formik_v2.x.x.js new file mode 100644 index 0000000000..fd49589722 --- /dev/null +++ b/definitions/npm/formik_v2.x.x/flow_v0.201.x-/formik_v2.x.x.js @@ -0,0 +1,454 @@ +declare module 'formik/@@yup' { + declare export type Schema = any; + declare export type YupError = any; +} + +declare module 'formik/@flow-typed' { + import type { Schema } from 'formik/@@yup'; + + declare export type FieldValidator = ( + value: any + ) => ?string | Promise; + declare export type FormikErrors = $ObjMap ?string>; + declare export type FormikTouched = $ObjMap ?boolean>; + + declare export type FormikState = {| + values: Values, + errors: FormikErrors, + touched: FormikTouched, + isSubmitting: boolean, + isValidating: boolean, + submitCount: number, + status?: any, + |}; + + declare export type FormikComputedProps = {| + dirty: boolean, + isValid: boolean, + initialValues: Values, + initialErrors: FormikErrors, + initialTouched: FormikTouched, + initialStatus?: any, + |}; + + declare export type FormikHelpers = {| + setStatus(status?: any): void, + setErrors(errors: FormikErrors): void, + setSubmitting(isSubmitting: boolean): void, + setTouched(touched: FormikTouched): void, + setValues(values: Values): void, + setFieldValue(fieldName: string, value: any, shouldValidate?: boolean): void, + setFieldError(fieldName: $Keys, message: string): void, + setFieldTouched(fieldName: $Keys, isTouched?: boolean, shouldValidate?: boolean): void, + validateForm(values?: $Shape): Promise>, + validateField(field: string): void, + resetForm(nextState?: $Shape>): void, + setFormikState( + state: + | FormikState + | ((prevState: FormikState) => FormikState), + callback?: () => void + ): void, + |}; + + declare export type FormikHandlers = {| + handleSubmit(e?: {...}): void, + handleReset(e?: {...}): void, + handleBlur(eventOrString: string | {...}): void, + handleChange(eventOrPath: string | {...}): void, + |}; + + declare export type FormikSharedConfig = {| + validateOnChange?: boolean, + validateOnBlur?: boolean, + isInitialValid?: boolean | ((props: {...}) => boolean), + enableReinitialize?: boolean, + |}; + + declare export type FormikConfig = {| + ...FormikSharedConfig, + onSubmit: (values: Values, formikHelpers: FormikHelpers) => void | Promise, + + component?: React$ComponentType> | React$Node, + render?: (props: FormikProps) => React$Node, + children?: ((props: FormikProps) => React$Node) | React$Node, + initialValues?: $Shape, + initialStatus?: any, + initialErrors?: FormikErrors, + initialTouched?: FormikTouched, + onReset?: (values: Values, formikHelpers: FormikHelpers) => void, + validationSchema?: (() => Schema) | Schema, + validate?: (values: Values) => void | {...} | Promise>, + innerRef?: { current: FormikProps | null, ... }, + |}; + + declare export type FormikProps = $ReadOnly<{| + ...FormikSharedConfig, + ...FormikState, + ...FormikHelpers, + ...FormikHandlers, + ...FormikComputedProps, + ...FormikRegistration, + submitForm: () => Promise, + |}>; + + declare export type FnsOptions = {| + validate: FieldValidator, + |}; + + declare export type FormikRegistration = {| + unregisterField(fieldName: $Keys): void, + registerField(fieldName: $Keys, fns: FnsOptions): void, + |}; + + declare export type FormikContext = FormikProps & { + validate: $ElementType, 'validate'>, + validationSchema: $ElementType, 'validationSchema'>, + ... + }; + + declare export interface SharedRenderProps { + component?: React$ElementType; + render?: (props: T) => React$Node; + children?: (props: T) => React$Node; + } + + declare export type FieldMetaProps = $ReadOnly<{| + value: Value, + error?: string, + touched: boolean, + initialValue?: Value, + initialTouched: boolean, + initialError?: string, + |}>; + + declare export type FieldInputProps = $ReadOnly<{| + value: Value, + name: string, + multiple?: boolean, + checked?: boolean, + onChange: $ElementType, + onBlur: $ElementType, + |}>; + + declare export type FieldHelperProps = $ReadOnly<{| + setValue: (value: any, shouldValidate?: boolean) => void, + setTouched: (value: boolean, shouldValidate?: boolean) => void, + setError: (value: any) => void, + |}>; +} + +declare module 'formik/@withFormik' { + import type { Schema } from 'formik/@@yup'; + import type { + FormikHelpers, + FormikProps, + FormikSharedConfig, + FormikTouched, + FormikErrors, + } from 'formik/@flow-typed'; + + declare export type InjectedFormikProps = $ReadOnly<{| + ...FormikProps, + ...$Exact, + |}>; + + declare export type FormikBag = $ReadOnly<{| + ...FormikHelpers, + props: Props, + |}>; + + declare export type WithFormikConfig = {| + ...FormikSharedConfig, + + handleSubmit: (values: Values, formikBag: FormikBag) => void, + + displayName?: string, + mapPropsToValues?: (props: Props) => $Shape, + mapPropsToStatus?: (props: Props) => any, + mapPropsToTouched?: (props: Props) => FormikTouched, + mapPropsToErrors?: (props: Props) => FormikErrors, + validate?: (values: Values, props: Props) => void | {...} | Promise, + + validationSchema?: ((props: Props) => Schema) | Schema, + |}; + + declare export function withFormik( + options: WithFormikConfig + ): ( + component: React$ComponentType> + ) => React$ComponentType; +} + +declare module 'formik/@Field' { + import type { + FormikProps, + FieldMetaProps, + FieldInputProps, + FieldValidator, + FieldHelperProps, + } from 'formik/@flow-typed'; + + declare export type FieldProps = {| + field: FieldInputProps, + form: FormikProps, + meta: FieldMetaProps, + |}; + + declare export type FieldConfig = {| + name: string, + component?: React$ElementType, + as?: React$ElementType, + render?: (props: FieldProps) => React$Node, + children?: ((props: FieldProps) => React$Node) | React$Node, + validate?: FieldValidator, + type?: string, + value?: Value, + innerRef?: React$Ref, + |}; + + declare export type FieldAttributes = { ...FieldConfig, ... } & Props; + + declare export type UseFieldConfig = { + name: string, + type?: string, + value?: Value, + as?: React$ElementType, + multiple?: boolean, + ... + }; + + declare export function useField( + propsOrFieldName: string | UseFieldConfig + ): [FieldInputProps, FieldMetaProps, FieldHelperProps]; + + declare export var Field: { (props: FieldAttributes): React$Node, ... }; + + declare export var FastField: typeof Field; +} + +declare module 'formik/@utils' { + declare export function isFunction(value: any): boolean; + declare export function isObject(value: any): boolean; + declare export function isInteger(value: any): boolean; + declare export function isString(value: any): boolean; + declare export function isNaN(value: any): boolean; + declare export function isEmptyChildren(value: any): boolean; + declare export function isPromise(value: any): boolean; + declare export function isInputEvent(value: any): boolean; + declare export function getActiveElement(doc?: Document): Element | null; + declare export function getIn( + obj: any, + key: string | Array, + def?: any, + p?: number + ): any; + declare export function setIn(obj: any, path: string, value: any): any; + declare export function setNestedObjectValues( + object: any, + value: any, + visited?: any, + response?: any + ): T; +} + +declare module 'formik/@FormikContext' { + import type { FormikContext } from 'formik/@flow-typed'; + + declare type _Context = React$Context>; + + declare export var FormikProvider: $ElementType<_Context, 'Provider'>; + declare export var FormikConsumer: $ElementType<_Context, 'Consumer'>; + + declare export function useFormikContext(): FormikContext; +} + +declare module 'formik/@ErrorMessage' { + declare export type ErrorMessageProps = { + name: string, + className?: string, + component?: React$ElementType, + render?: (errorMessage: string) => React$Node, + children?: (errorMessage: string) => React$Node, + ... + }; + + declare export var ErrorMessage: React$ComponentType; +} + +declare module 'formik/@FieldArray' { + import type { SharedRenderProps, FormikProps } from 'formik/@flow-typed'; + + declare export type FieldArrayRenderProps = ArrayHelpers & { + form: FormikProps, + name: string, + ... + }; + + declare export type FieldArrayConfig = { + name: string, + validateOnChange?: boolean, + ... + } & SharedRenderProps>; + + declare export type ArrayHelpers = { + push: (obj: any) => void, + handlePush: (obj: any) => () => void, + swap: (indexA: number, indexB: number) => void, + handleSwap: (indexA: number, indexB: number) => () => void, + move: (from: number, to: number) => void, + handleMove: (from: number, to: number) => () => void, + insert: (index: number, value: any) => void, + handleInsert: (index: number, value: any) => () => void, + replace: (index: number, value: any) => void, + handleReplace: (index: number, value: any) => () => void, + unshift: (value: any) => number, + handleUnshift: (value: any) => () => void, + handleRemove: (index: number) => () => void, + handlePop: () => () => void, + remove(index: number): ?T, + pop(): ?T, + ... + }; + + declare export function move( + array: Array, + from: number, + to: number + ): Array; + declare export function swap( + array: Array, + indexA: number, + indexB: number + ): Array; + declare export function insert( + array: Array, + index: number, + value: T + ): Array; + declare export function replace( + array: Array, + index: number, + value: T + ): Array; + + declare export var FieldArray: { (props: FieldArrayConfig): React$Node, ... }; +} + +declare module 'formik/@Form' { + declare export type HTMLFormAttributes = { + // `onSubmit` and `onReset` are not overwritable props + // https://github.com/jaredpalmer/formik/blob/next/docs/api/form.md + onSubmit?: empty, + onReset?: empty, + ... + }; + + declare export var Form: React$StatelessFunctionalComponent; +} + +declare module 'formik/@Formik' { + import type { UseFieldConfig } from 'formik/@Field'; + import type { YupError, Schema } from 'formik/@@yup'; + import type { + FormikConfig, + FormikErrors, + FormikState, + FormikTouched, + FieldMetaProps, + FieldInputProps, + } from 'formik/@flow-typed'; + + declare export function useFormik( + options: FormikConfig + ): { + initialValues: $Shape, + initialErrors: FormikErrors, + initialTouched: FormikTouched, + initialStatus: any, + handleBlur(fieldName: $Keys): (event: {...}) => void, + handleBlur(event: {...}): void, + handleChange(fieldName: $Keys): (event: {...}) => void, + handleChange(event: {...}): void, + handleReset: (e?: {...}) => void, + handleSubmit: (e?: {...}) => void, + resetForm: (nextState?: $Shape>) => void, + setErrors: (errors: FormikErrors) => void, + setFormikState: ( + stateOrCb: + | FormikState + | ((state: FormikState) => FormikState) + ) => void, + setFieldTouched: ( + fieldName: $Keys, + touched?: boolean, + shouldValidate?: boolean + ) => void, + setFieldValue: >( + fieldName: Name, + value: $ElementType, + shouldValidate?: boolean + ) => void, + setFieldError: (fieldName: $Keys, value: ?string) => void, + setStatus: (status: any) => void, + setSubmitting: (isSubmitting: boolean) => void, + setTouched: (touched: FormikTouched) => void, + setValues: (values: $Shape) => void, + submitForm: () => Promise, + validateForm: (values?: Values) => Promise>, + validateField: (name: $Keys) => Promise, + isValid: boolean, + dirty: boolean, + unregisterField: (name: string) => void, + registerField: (name: string, options: {| validate: any |}) => void, + getFieldProps( + name: Name | UseFieldConfig + ): [ + FieldInputProps<$ElementType>, + FieldMetaProps<$ElementType> + ], + validateOnBlur: boolean, + validateOnChange: boolean, + values: Values, + errors: FormikErrors, + touched: FormikTouched, + isSubmitting: boolean, + isValidating: boolean, + status?: any, + submitCount: number, + ... + }; + + declare export var Formik: { (props: FormikConfig): React$Node, ... }; + + declare export function yupToFormErrors( + yupError: YupError + ): FormikErrors; + + declare export function validateYupSchema( + values: Values, + schema: Schema, + sync?: boolean, + context?: any + ): Promise<$Shape>; +} + +declare module 'formik/@connect' { + declare export function connect>( + c: Comp + ): React$ComponentType<$Diff, { formik: any, ... }>>; +} + +declare module 'formik' { + declare export * from 'formik/@connect' + declare export * from 'formik/@ErrorMessage' + declare export * from 'formik/@Field' + declare export * from 'formik/@FieldArray' + declare export * from 'formik/@flow-typed' + declare export * from 'formik/@flow-typed' + declare export * from 'formik/@Form' + declare export * from 'formik/@Formik' + declare export * from 'formik/@FormikContext' + declare export * from 'formik/@utils' + declare export * from 'formik/@withFormik' +} diff --git a/definitions/npm/formik_v2.x.x/flow_v0.201.x-/test_formik.js b/definitions/npm/formik_v2.x.x/flow_v0.201.x-/test_formik.js new file mode 100644 index 0000000000..b7e058afbf --- /dev/null +++ b/definitions/npm/formik_v2.x.x/flow_v0.201.x-/test_formik.js @@ -0,0 +1,379 @@ +// @flow +import React from 'react'; +import { it, describe } from 'flow-typed-test'; +import { + Form, + getActiveElement, + getIn, + setIn, + setNestedObjectValues, + ErrorMessage, + FormikProvider, + FormikConsumer, + useFormikContext, + Field, + FastField, + isFunction, + isObject, + isInteger, + isString, + isNaN, + isEmptyChildren, + isPromise, + isInputEvent, + useField, + withFormik, + move, + swap, + insert, + replace, + FieldArray, + useFormik, + Formik, + type InjectedFormikProps, +} from 'formik'; + +describe('withFormik HOC', () => { + type FormValues = {| age: number, name: string, birthday: Date |}; + + describe('wrapped component props', () => { + type FormOwnProps = {| + onSubmit: FormValues => void, + variant: 'active' | 'passive', + |}; + + const MyForm = (props: InjectedFormikProps) => + null; + + const WithFormikForm = withFormik({ + handleSubmit(values, { props: { onSubmit }, setSubmitting }) { + onSubmit(values); + setSubmitting(false); + }, + })(MyForm); + + it('should work when pass valid own props', () => { + {}} />; + }); + + it('should raise an error when pass invalid own props', () => { + {}} + />; + + ; + }); + + it('should raise an error when pass injected formik props', () => { + // $FlowExpectedError[prop-missing] - isSubmitting was extracted + {}} + />; + }); + }); + + describe('HOC config', () => { + type Props = {| + initialName: string, + initialAge: number, + initialBirthday: Date, + |}; + const requiredOptions = { handleSubmit: () => {} }; + + describe('handleSubmit', () => { + it('should pass when use properly', () => { + withFormik({ + handleSubmit(values, { props }) { + (values.age: number); + (props.initialName: string); + + // $FlowExpectedError[incompatible-cast] - check any + (values.age: boolean); + // $FlowExpectedError[incompatible-cast] - check any + (props.initialName: boolean); + }, + }); + }); + }); + + describe('handleSubmit', () => { + it('should pass when use properly', () => { + withFormik({ + ...requiredOptions, + mapPropsToValues: ({ initialAge }) => ({ age: initialAge }), + }); + }); + + it('should raise an error when `mapPropsToValues` return invalid values', () => { + withFormik({ + ...requiredOptions, + // $FlowExpectedError[incompatible-call] - `initialAge` is a number but `name` need a string + mapPropsToValues: ({ initialAge }) => ({ + name: initialAge, + }), + }); + }); + + it('should raise an error when `mapPropsToValues` return not missing value', () => { + withFormik({ + ...requiredOptions, + // $FlowExpectedError[prop-missing] - `abc` is missing in values + mapPropsToValues: ({ initialAge }) => ({ + abc: initialAge, + }), + }); + }); + + it('should return partial of values', () => { + withFormik({ + ...requiredOptions, + mapPropsToValues: ({ initialAge }) => ({ + age: initialAge, + }), + }); + }); + }); + }); +}); + +describe('useField hook', () => { + it('should call with string', () => { + useField('name'); + }); + + it('also should call with options', () => { + useField({ name: 'name' }); + }); + + it('should raise error when pass object without required prop `name`', () => { + // $FlowExpectedError[incompatible-call] + useField({ __name: 'name' }); + }); + + it('should return field props', () => { + const [props, meta] = useField('name'); + + (props.value: number); + // $FlowExpectedError[incompatible-cast] - check any + (props.value: boolean); + + (meta.touched: boolean); + // $FlowExpectedError[incompatible-cast] - check any + (meta.touched: number); + + (meta.error: ?string); + // $FlowExpectedError[incompatible-cast] - check any + (meta.error: number); + }); + + it('should return FieldHelperProps', () => { + const [, , helpers] = useField('name'); + + helpers.setValue('a name'); + helpers.setValue('a name', false); + helpers.setTouched(true); + helpers.setTouched(true, false); + helpers.setError('an error'); + }); +}); + +describe('Field and FastField', () => { + it('should render Field component', () => { + ; + ; + }); + + it('should raise an error when pass incompatible name prop', () => { + // $FlowExpectedError[incompatible-type] - `name` must be a string + ; + + // $FlowExpectedError[prop-missing] - `name` is required prop + ; + // $FlowExpectedError[prop-missing] - `name` is required prop + ; + }); + + it('should validate value', () => { + Field<{ disabled: boolean, ... }, '1' | '2'>({ + name: 'count', + disabled: true, + value: '1', + }); + + Field<{ disabled: boolean, ... }, '1' | '2'>({ + name: 'count', + // $FlowExpectedError[incompatible-call] - need a boolean + disabled: 123, + // $FlowExpectedError[incompatible-call] - `12` is missing in enum + value: '12', + }); + }); +}); + +describe('utils', () => { + it('should work properly', () => { + (isFunction(() => {}): boolean); + (isObject({}): boolean); + (isInteger(1): boolean); + (isString(''): boolean); + (isNaN(1 / 0): boolean); + (isEmptyChildren([]): boolean); + (isPromise(Promise.resolve(1)): boolean); + (isInputEvent({}): boolean); + + (getActiveElement(document): Element | null); + + getIn({ a: { b: 2 } }, ['a', 'b']); + setIn({ a: { b: 2 } }, 'a', 3); + setNestedObjectValues({}, 1); + }); +}); + +describe('FormikContext', () => { + it('should work properly', () => { + + {value => { + (value.validateOnBlur: ?boolean); + + // $FlowExpectedError[incompatible-cast] - check any + (value.validateOnBlur: ?string); + + (value.submitForm: () => Promise); + + // $FlowExpectedError[incompatible-cast] - check any + (value.submitForm: number); + + return null; + }} + ; + + // $FlowExpectedError[incompatible-type] - need valid formik context value + ; + }); + + it('should return context with passed values', () => { + const context = useFormikContext<{ age: number, ... }>(); + + (context.values.age: number); + // $FlowExpectedError[incompatible-cast] - check any + (context.values.age: string); + }); +}); + +describe('ErrorMessage', () => { + it('should work properly', () => { + ; + + + {undefined} + ; + + { + (val: string); + + return null; + }} + > + {val => { + (val: string); + + return null; + }} + ; + }); + + it('should raise an error when do not pass required prop `name`', () => { + // $FlowExpectedError[prop-missing] + ; + }); +}); + +describe('FieldArray', () => { + describe('methods', () => { + (move([1], 1, 1): Array); + (swap(['str'], 1, 1): Array); + (insert([true], 1, false): Array); + (replace(['1'], 1, '2'): Array); + }); + + describe('Component', () => { + it('should render FieldArray component', () => { + ; + }); + + it('should raise an error when pass incompatible name prop', () => { + // $FlowExpectedError[incompatible-type] - `name` must be a string + ; + + // $FlowExpectedError[prop-missing] - `name` is required prop + ; + }); + }); +}); + +it('should render Form', () => { +
; + + ; + + // $FlowExpectedError[incompatible-type] - `onSubmit` already provided to `form` yuo can't overwrite it + {}} />; + + // $FlowExpectedError[incompatible-type] - `onReset` already provided to `form` yuo can't overwrite it + {}} />; +}); + +describe('Formik', () => { + describe('Component', () => { + it('should work properly', () => { + {}} />; + }); + it('onSumbit can return promise', () => { + Promise.resolve(null)} />; + }); + }); + + describe('hook', () => { + it('should work properly', () => { + type Vals = {| + name: string, + age: number, + |}; + + const formik = useFormik({ onSubmit: () => {} }); + + formik.setFieldValue('name', '1', true); + + // $FlowExpectedError[prop-missing] - `name` is missing in `Values` + formik.setFieldValue('__name', '1'); + + // $FlowExpectedError[incompatible-call] - `name` expect string value, not `123` + formik.setFieldValue('name', 123); + + (formik.values.name: string); + (formik.values.age: number); + + // $FlowExpectedError[incompatible-cast] - check any + (formik.values.name: boolean); + // $FlowExpectedError[incompatible-cast] - check any + (formik.values.age: boolean); + }); + }); +}); diff --git a/definitions/npm/fuse.js_v6.x.x/flow_v0.106.x-/fuse.js_v6.x.x.js b/definitions/npm/fuse.js_v6.x.x/flow_v0.106.x-v0.200.x/fuse.js_v6.x.x.js similarity index 100% rename from definitions/npm/fuse.js_v6.x.x/flow_v0.106.x-/fuse.js_v6.x.x.js rename to definitions/npm/fuse.js_v6.x.x/flow_v0.106.x-v0.200.x/fuse.js_v6.x.x.js diff --git a/definitions/npm/fuse.js_v6.x.x/flow_v0.106.x-/test_fuse.js_v6.x.x.js b/definitions/npm/fuse.js_v6.x.x/flow_v0.106.x-v0.200.x/test_fuse.js_v6.x.x.js similarity index 100% rename from definitions/npm/fuse.js_v6.x.x/flow_v0.106.x-/test_fuse.js_v6.x.x.js rename to definitions/npm/fuse.js_v6.x.x/flow_v0.106.x-v0.200.x/test_fuse.js_v6.x.x.js diff --git a/definitions/npm/fuse.js_v6.x.x/flow_v0.201.x-/fuse.js_v6.x.x.js b/definitions/npm/fuse.js_v6.x.x/flow_v0.201.x-/fuse.js_v6.x.x.js new file mode 100644 index 0000000000..8fdc98c9d0 --- /dev/null +++ b/definitions/npm/fuse.js_v6.x.x/flow_v0.201.x-/fuse.js_v6.x.x.js @@ -0,0 +1,344 @@ +// @flow + +declare module 'fuse.js' { + declare export default typeof Fuse; + declare class Fuse { + constructor( + list: $ReadOnlyArray, + options?: Fuse$IFuseOptions, + index?: Fuse$FuseIndex + ): this; + + /** + * Search function for the Fuse instance. + * + * ```typescript + * const list: MyType[] = [myType1, myType2, etc...] + * + * const options: Fuse.IFuseOptions = { + * keys: ['key1', 'key2'] + * } + * + * const myFuse = new Fuse(list, options) + * let result = myFuse.search('pattern') + * ``` + * @param pattern The pattern to search + * @param options `Fuse.FuseSearchOptions` + * @returns An array of search results + */ + search( + pattern: string | Fuse$Expression, + options?: Fuse$FuseSearchOptions + ): Fuse$FuseResult[]; + setCollection(docs: $ReadOnlyArray, index?: Fuse$FuseIndex): void; + + /** + * Adds a doc to the end the list. + */ + add(doc: T): void; + + /** + * Removes all documents from the list which the predicate returns truthy for, + * and returns an array of the removed docs. + * The predicate is invoked with two arguments: (doc, index). + */ + remove(predicate: (doc: T, idx: number) => boolean): T[]; + + /** + * Removes the doc at the specified index. + */ + removeAt(idx: number): void; + + /** + * Returns the generated Fuse index + */ + getIndex(): Fuse$FuseIndex; + + /** + * Return the current version. + */ + static version: string; + + /** + * Use this method to pre-generate the index from the list, and pass it + * directly into the Fuse instance. + * + * _Note that Fuse will automatically index the table if one isn't provided + * during instantiation._ + * + * ```typescript + * const list: MyType[] = [myType1, myType2, etc...] + * + * const index = Fuse.createIndex( + * keys: ['key1', 'key2'] + * list: list + * ) + * + * const options: Fuse.IFuseOptions = { + * keys: ['key1', 'key2'] + * } + * + * const myFuse = new Fuse(list, options, index) + * ``` + * @param keys The keys to index + * @param list The list from which to create an index + * @param options ? + * @returns An indexed list + */ + static createIndex( + keys: Array>, + list: $ReadOnlyArray, + options?: Fuse$FuseIndexOptions + ): Fuse$FuseIndex; + static parseIndex( + index: any, + options?: Fuse$FuseIndexOptions + ): Fuse$FuseIndex; + static config: typeof Fuse$config; + static FuseIndex: typeof Fuse$FuseIndex; + } + + declare export class Fuse$FuseIndex { + constructor(options?: Fuse$FuseIndexOptions): this; + setSources(docs: $ReadOnlyArray): void; + setKeys(keys: $ReadOnlyArray): void; + setIndexRecords(records: Fuse$FuseIndexRecords): void; + create(): void; + add(doc: T): void; + toJSON(): { + keys: $ReadOnlyArray, + records: Fuse$FuseIndexRecords, + ... + }; + } + + declare type Fuse$FuseGetFunction = ( + obj: T, + path: string | string[] + ) => $ReadOnlyArray | string; + + declare export type Fuse$FuseIndexOptions = { + getFn: Fuse$FuseGetFunction, + ... + }; + + declare export type Fuse$FuseSortFunctionItem = { + [key: string]: + | { + $: string, + ... + } + | { + $: string, + idx: number, + ... + }[], + ... + }; + + declare export type Fuse$FuseSortFunctionMatch = { + score: number, + key: string, + value: string, + indices: $ReadOnlyArray[], + ... + }; + + declare export type Fuse$FuseSortFunctionMatchList = { + ...Fuse$FuseSortFunctionMatch, + ...{ + idx: number, + ... + }, + ... + }; + + declare export type Fuse$FuseSortFunctionArg = { + idx: number, + item: Fuse$FuseSortFunctionItem, + score: number, + matches?: (Fuse$FuseSortFunctionMatch | Fuse$FuseSortFunctionMatchList)[], + ... + }; + + declare export type Fuse$FuseSortFunction = ( + a: Fuse$FuseSortFunctionArg, + b: Fuse$FuseSortFunctionArg + ) => number; + + declare type Fuse$RecordEntryObject = { + v: string, + n: number, + ... + }; + + declare type Fuse$RecordEntryArrayItem = $ReadOnlyArray<{ + ...Fuse$RecordEntryObject, + ...{ + i: number, + ... + }, + ... + }>; + + declare type Fuse$RecordEntry = { + [key: string]: Fuse$RecordEntryObject | Fuse$RecordEntryArrayItem, + ... + }; + + declare type Fuse$FuseIndexObjectRecord = { + i: number, + $: Fuse$RecordEntry, + ... + }; + + declare type Fuse$FuseIndexStringRecord = { + i: number, + v: string, + n: number, + ... + }; + + declare type Fuse$FuseIndexRecords = + | $ReadOnlyArray + | $ReadOnlyArray; + + declare export type Fuse$FuseOptionKeyObject = { + name: string | string[], + weight?: number, + getFn?: (obj: T) => $ReadOnlyArray | string, + ... + }; + + declare export type Fuse$FuseOptionKey = + | Fuse$FuseOptionKeyObject + | string + | string[]; + + declare interface RequiredIFuseOptions { + /** + * Indicates whether comparisons should be case sensitive. + */ + isCaseSensitive: boolean; + + /** + * Determines how close the match must be to the fuzzy location (specified by `location`). An exact letter match which is `distance` characters away from the fuzzy location would score as a complete mismatch. A `distance` of `0` requires the match be at the exact `location` specified. A distance of `1000` would require a perfect match to be within `800` characters of the `location` to be found using a `threshold` of `0.8`. + */ + distance: number; + + /** + * When true, the matching function will continue to the end of a search pattern even if a perfect match has already been located in the string. + */ + findAllMatches: boolean; + + /** + * The function to use to retrieve an object's value at the provided path. The default will also search nested paths. + */ + getFn: Fuse$FuseGetFunction; + + /** + * When `true`, search will ignore `location` and `distance`, so it won't matter where in the string the pattern appears. + */ + ignoreLocation: boolean; + + /** + * When `true`, the calculation for the relevance score (used for sorting) will ignore the `field-length norm`. + */ + ignoreFieldNorm: boolean; + + /** + * Determines how much the `field-length norm` affects scoring. A value of `0` is equivalent to ignoring the field-length norm. A value of `0.5` will greatly reduce the effect of field-length norm, while a value of `2.0` will greatly increase it. + */ + fieldNormWeight: number; + + /** + * Whether the matches should be included in the result set. When `true`, each record in the result set will include the indices of the matched characters. These can consequently be used for highlighting purposes. + */ + includeMatches: boolean; + + /** + * Whether the score should be included in the result set. A score of `0`indicates a perfect match, while a score of `1` indicates a complete mismatch. + */ + includeScore: boolean; + + /** + * List of keys that will be searched. This supports nested paths, weighted search, searching in arrays of `strings` and `objects`. + */ + keys: Array>; + + /** + * Determines approximately where in the text is the pattern expected to be found. + */ + location: number; + + /** + * Only the matches whose length exceeds this value will be returned. (For instance, if you want to ignore single character matches in the result, set it to `2`). + */ + minMatchCharLength: number; + + /** + * Whether to sort the result list, by score. + */ + shouldSort: boolean; + + /** + * The function to use to sort all the results. The default will sort by ascending relevance score, ascending index. + */ + sortFn?: Fuse$FuseSortFunction; + + /** + * At what point does the match algorithm give up. A threshold of `0.0` requires a perfect match (of both letters and location), a threshold of `1.0` would match anything. + */ + threshold: number; + + /** + * When `true`, it enables the use of unix-like search commands. See [example](/examples.html#extended-search). + */ + useExtendedSearch: boolean; + } + declare export type Fuse$IFuseOptions = $Shape>; + + declare type Fuse$RangeTuple = [number, number]; + + declare export type Fuse$FuseResultMatch = { + indices: $ReadOnlyArray, + key?: string, + refIndex?: number, + value?: string, + ... + }; + + declare export type Fuse$FuseSearchOptions = { + limit: number, + ... + }; + + declare export type Fuse$FuseResult = { + item: T, + refIndex: number, + score?: number, + matches?: $ReadOnlyArray, + ... + }; + + declare export type Fuse$Expression = + | { + [key: string]: string, + ... + } + | { + $path: $ReadOnlyArray, + $val: string, + ... + } + | { + $and?: Fuse$Expression[], + ... + } + | { + $or?: Fuse$Expression[], + ... + }; + + declare export var Fuse$config: RequiredIFuseOptions; +} diff --git a/definitions/npm/fuse.js_v6.x.x/flow_v0.201.x-/test_fuse.js_v6.x.x.js b/definitions/npm/fuse.js_v6.x.x/flow_v0.201.x-/test_fuse.js_v6.x.x.js new file mode 100644 index 0000000000..8cb93f09de --- /dev/null +++ b/definitions/npm/fuse.js_v6.x.x/flow_v0.201.x-/test_fuse.js_v6.x.x.js @@ -0,0 +1,83 @@ +// @flow +import { describe, it } from 'flow-typed-test'; +import Fuse from 'fuse.js'; + +const TEST_LIST = [ + { id: '001', name: 'Alice', age: 21, role: 'admin', city: 'New York' }, + { id: '002', name: 'Alii', age: 22, role: 'user', city: 'Paris' }, + { id: '123', name: 'Bob', age: 22, role: 'admin', city: 'Tokyo' }, + { id: '124', name: 'Charlie', age: 23, role: 'viewer', city: 'Taipei' }, + { id: '125', name: 'David', age: 24, role: 'marketing', city: 'Seoul' }, + { id: '160', name: 'Edward', age: 25, role: 'marketing', city: 'London' }, + { id: '234', name: 'Frank', age: 26, role: 'viewer', city: 'New York' }, +]; + +describe('fuse.js constructor', () => { + it('should type constructor correctly', () => { + const fuse = new Fuse(TEST_LIST); + }); + + it('should error when required parameter of constructor is missing', () => { + // $FlowExpectedError[incompatible-call] `list` is missing + const fuse = new Fuse(); + }); + + describe('options', () => { + it('should type constructor correctly', () => { + const fuse = new Fuse(TEST_LIST, { + keys: ['name', 'city'], + threshold: 0.3, + shouldSort: false, + ignoreLocation: true, + }); + }); + + it('should error when not support option key been set', () => { + // $FlowExpectedError[prop-missing] `notExistOptionKey` is missing in the options + const fuse = new Fuse(TEST_LIST, { + notExistOptionKey: true, + keys: ['name', 'city'], + threshold: 0.3, + shouldSort: false, + ignoreLocation: true, + }); + }); + + it('should error when not support option type been set', () => { + // $FlowExpectedError[incompatible-call] `threshold` should be `number` + const fuse = new Fuse(TEST_LIST, { + keys: ['name', 'city'], + threshold: true, + shouldSort: false, + ignoreLocation: true, + }); + }); + }); +}); + +describe('fuse.js search', () => { + const fuse = new Fuse(TEST_LIST, { + keys: ['name', 'city'], + threshold: 0.3, + shouldSort: false, + ignoreLocation: true, + }); + + it('should type constructor correctly', () => { + const results = fuse.search('Alice'); + }); + + it('should error when required parameter of search is missing', () => { + // $FlowExpectedError[incompatible-call] `pattern` is missing + const results = fuse.search(); + }); + + it('should error when access not exist property from search results', () => { + const results = fuse.search('Alice'); + + results.map(result => result.item); + + // $FlowExpectedError[prop-missing] `notExistKey` is missing in the result + results.map(result => result.notExistKey); + }); +}); diff --git a/definitions/npm/history_v4.9.x/flow_v0.104.x-/history_v4.9.x.js b/definitions/npm/history_v4.9.x/flow_v0.104.x-v0.200.x/history_v4.9.x.js similarity index 100% rename from definitions/npm/history_v4.9.x/flow_v0.104.x-/history_v4.9.x.js rename to definitions/npm/history_v4.9.x/flow_v0.104.x-v0.200.x/history_v4.9.x.js diff --git a/definitions/npm/history_v4.9.x/flow_v0.104.x-/test_history_v4.9.x.js b/definitions/npm/history_v4.9.x/flow_v0.104.x-v0.200.x/test_history_v4.9.x.js similarity index 100% rename from definitions/npm/history_v4.9.x/flow_v0.104.x-/test_history_v4.9.x.js rename to definitions/npm/history_v4.9.x/flow_v0.104.x-v0.200.x/test_history_v4.9.x.js diff --git a/definitions/npm/history_v4.9.x/flow_v0.201.x-/history_v4.9.x.js b/definitions/npm/history_v4.9.x/flow_v0.201.x-/history_v4.9.x.js new file mode 100644 index 0000000000..37f2878a35 --- /dev/null +++ b/definitions/npm/history_v4.9.x/flow_v0.201.x-/history_v4.9.x.js @@ -0,0 +1,138 @@ +declare module 'history' { + declare function Unblock(): void; + + declare export type Action = 'PUSH' | 'REPLACE' | 'POP'; + + declare export type BrowserLocation = { + pathname: string, + search: string, + hash: string, + // Browser and Memory specific + state: {...}, + key: string, + ... + }; + + declare interface IBrowserHistory { + length: number; + location: BrowserLocation; + action: Action; + push(path: string, state?: {...}): void; + push(location: $Shape): void; + replace(path: string, state?: {...}): void; + replace(location: $Shape): void; + go(n: number): void; + goBack(): void; + goForward(): void; + listen((location: BrowserLocation, action: Action) => void): void; + block(message: string): typeof Unblock; + block( + (location: BrowserLocation, action: Action) => string + ): typeof Unblock; + } + + declare export type BrowserHistory = IBrowserHistory; + + declare type BrowserHistoryOpts = { + basename?: string, + forceRefresh?: boolean, + getUserConfirmation?: ( + message: string, + callback: (willContinue: boolean) => void + ) => void, + ... + }; + + declare function createBrowserHistory( + opts?: BrowserHistoryOpts + ): BrowserHistory; + + declare export type MemoryLocation = { + pathname: string, + search: string, + hash: string, + // Browser and Memory specific + state: {...}, + key: string, + ... + }; + + declare interface IMemoryHistory { + length: number; + location: MemoryLocation; + action: Action; + index: number; + entries: Array; + push(path: string, state?: {...}): void; + push(location: $Shape): void; + replace(path: string, state?: {...}): void; + replace(location: $Shape): void; + go(n: number): void; + goBack(): void; + goForward(): void; + // Memory only + canGo(n: number): boolean; + listen((location: MemoryLocation, action: Action) => void): void; + block(message: string): typeof Unblock; + block((location: MemoryLocation, action: Action) => string): typeof Unblock; + } + + declare export type MemoryHistory = IMemoryHistory; + + declare type MemoryHistoryOpts = { + initialEntries?: Array, + initialIndex?: number, + keyLength?: number, + getUserConfirmation?: ( + message: string, + callback: (willContinue: boolean) => void + ) => void, + ... + }; + + declare function createMemoryHistory(opts?: MemoryHistoryOpts): MemoryHistory; + + declare export type HashLocation = { + pathname: string, + search: string, + hash: string, + ... + }; + + declare interface IHashHistory { + length: number; + location: HashLocation; + action: Action; + push(path: string, state?: {...}): void; + push(location: $Shape): void; + replace(path: string, state?: {...}): void; + replace(location: $Shape): void; + go(n: number): void; + goBack(): void; + goForward(): void; + listen((location: HashLocation, action: Action) => void): void; + block(message: string): typeof Unblock; + block((location: HashLocation, action: Action) => string): typeof Unblock; + push(path: string): void; + } + + declare export type HashHistory = IHashHistory; + + declare type HashHistoryOpts = { + basename?: string, + hashType: 'slash' | 'noslash' | 'hashbang', + getUserConfirmation?: ( + message: string, + callback: (willContinue: boolean) => void + ) => void, + ... + }; + + declare function createHashHistory(opts?: HashHistoryOpts): HashHistory; + + declare function parsePath(path: string): BrowserLocation | MemoryLocation | HashLocation; + + declare function createPath( + path: BrowserLocation | MemoryLocation | HashLocation + ): string; +} diff --git a/definitions/npm/history_v4.9.x/flow_v0.201.x-/test_history_v4.9.x.js b/definitions/npm/history_v4.9.x/flow_v0.201.x-/test_history_v4.9.x.js new file mode 100644 index 0000000000..b95a7adbd9 --- /dev/null +++ b/definitions/npm/history_v4.9.x/flow_v0.201.x-/test_history_v4.9.x.js @@ -0,0 +1,295 @@ +// @flow + +import { describe, it } from 'flow-typed-test'; + +import {createBrowserHistory} from 'history'; +import {createMemoryHistory} from 'history'; +import {createHashHistory} from 'history'; +import {createPath} from 'history'; +import {parsePath} from 'history'; + +// browser history + +describe('browser history', () => { + it('should allow to get location fields', () => { + const history = createBrowserHistory({ + basename: "", + forceRefresh: false, + keyLength: 6, + }) + + const pathname: string = history.location.pathname + }); + + it('should allow to get browser and memory specific location fields', () => { + const history = createBrowserHistory({ + basename: "", + forceRefresh: false, + keyLength: 6, + }) + + const key: string = history.location.key + const state: {...} = history.location.state + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createBrowserHistory({ + basename: "", + forceRefresh: false, + keyLength: 6, + }) + + // $FlowExpectedError[prop-missing] + history.foo + }); + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createBrowserHistory({ + basename: "", + forceRefresh: false, + keyLength: 6, + }) + + history.push("/") + }); + + it('should allow to use partial location as first argument', () => { + const history = createBrowserHistory({ + basename: "", + forceRefresh: false, + keyLength: 6, + }) + + history.push({ + pathname: "/", + state: { a: 1 }, + }) + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createBrowserHistory({ + basename: "", + forceRefresh: false, + keyLength: 6, + }) + + history.replace("/") + }); + + it('should allow to use partial location as first argument', () => { + const history = createBrowserHistory({ + basename: "", + forceRefresh: false, + keyLength: 6, + }) + + history.replace({ + pathname: "/", + state: { a: 1 }, + }) + }); + }); +}); + +describe('memory history', () => { + it('should allow to get location fields', () => { + const history = createMemoryHistory({ + initialEntries: ["/"], + initialIndex: 0, + keyLength: 6, + }) + + const pathname: string = history.location.pathname + }); + + it('should allow to get browser and memory specific location fields', () => { + const history = createMemoryHistory({ + initialEntries: ["/"], + initialIndex: 0, + keyLength: 6, + }) + + const key: string = history.location.key + const state: {...} = history.location.state + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createMemoryHistory({ + initialEntries: ["/"], + initialIndex: 0, + keyLength: 6, + }) + + // $FlowExpectedError[prop-missing] + history.foo + }); + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ["/"], + initialIndex: 0, + keyLength: 6, + }) + + history.push("/") + }); + + it('should allow to use partial location as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ["/"], + initialIndex: 0, + keyLength: 6, + }) + + history.push({ + pathname: "/", + state: { a: 1 }, + }) + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ["/"], + initialIndex: 0, + keyLength: 6, + }) + + history.replace("/") + }); + + it('should allow to use partial location as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ["/"], + initialIndex: 0, + keyLength: 6, + }) + + history.replace({ + pathname: "/", + state: { a: 1 }, + }) + }); + }); +}); + +describe('hash history', () => { + it('should allow to get location fields', () => { + const history = createHashHistory({ + basename: "", + hashType: "slash", + }) + + const pathname: string = history.location.pathname + }); + + it('should not allow to get browser and memory specific location fields', () => { + const history = createHashHistory({ + basename: "", + hashType: "slash", + }) + + // $FlowExpectedError[prop-missing] + const key: string = history.location.key + // $FlowExpectedError[prop-missing] + const state: {...} = history.location.state + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createHashHistory({ + basename: "", + hashType: "slash", + }) + + // $FlowExpectedError[prop-missing] + history.foo + }); + + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createHashHistory({ + basename: "", + hashType: "slash", + }) + + history.push("/") + }); + + it('should allow to use partial location as first argument', () => { + const history = createHashHistory({ + basename: "", + hashType: "slash", + }) + + history.push({ + search: "?a=1", + }) + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createHashHistory({ + basename: "", + hashType: "slash", + }) + + history.replace("/") + }); + + it('should allow to use partial location as first argument', () => { + const history = createHashHistory({ + basename: "", + hashType: "slash", + }) + + history.push({ + search: "?a=1", + }) + }); + }); +}); + +describe('create path', () => { + it('should allow to use Location argument', () => { + const path = createPath({ + pathname: '/test', + search: '?a=1', + hash: 'slug', + }) + + const key: string = path + // $FlowExpectedError[incompatible-type] + const state: {...} = path + }); + + it('should not allow to accept void', () => { + // $FlowExpectedError[incompatible-call] + const path = createPath() + + const key: string = path + }); +}); + +describe('parse path', () => { + it('should allow to use string argument', () => { + const location = parsePath('/test?query#hash') + + const state: {...} = location + // $FlowExpectedError[incompatible-type] + const key: string = location + }); + + it('should not allow to accept void', () => { + // $FlowExpectedError[incompatible-call] + const location = parsePath() + + const state: {...} = location + }); +}); diff --git a/definitions/npm/history_v4.x.x/flow_v0.104.x-/history_v4.x.x.js b/definitions/npm/history_v4.x.x/flow_v0.104.x-v0.200.x/history_v4.x.x.js similarity index 100% rename from definitions/npm/history_v4.x.x/flow_v0.104.x-/history_v4.x.x.js rename to definitions/npm/history_v4.x.x/flow_v0.104.x-v0.200.x/history_v4.x.x.js diff --git a/definitions/npm/history_v4.x.x/flow_v0.104.x-/test_history_v4.x.x.js b/definitions/npm/history_v4.x.x/flow_v0.104.x-v0.200.x/test_history_v4.x.x.js similarity index 100% rename from definitions/npm/history_v4.x.x/flow_v0.104.x-/test_history_v4.x.x.js rename to definitions/npm/history_v4.x.x/flow_v0.104.x-v0.200.x/test_history_v4.x.x.js diff --git a/definitions/npm/history_v4.x.x/flow_v0.201.x-/history_v4.x.x.js b/definitions/npm/history_v4.x.x/flow_v0.201.x-/history_v4.x.x.js new file mode 100644 index 0000000000..979b18eee5 --- /dev/null +++ b/definitions/npm/history_v4.x.x/flow_v0.201.x-/history_v4.x.x.js @@ -0,0 +1,106 @@ +declare module 'history' { + declare type Unregister = () => void; + + declare export type Action = 'PUSH' | 'REPLACE' | 'POP'; + + declare export type Location = {| + pathname: string, + search: string, + hash: string, + state: { ... }, + key: string, + |}; + + declare type History = {| + length: number, + location: HistoryLocation, + action: Action, + push: ((path: string, state?: { ... }) => void) & + ((location: $Shape) => void), + replace: ((path: string, state?: { ... }) => void) & + ((location: $Shape) => void), + go(n: number): void, + goBack(): void, + goForward(): void, + listen((location: HistoryLocation, action: Action) => void): Unregister, + block( + prompt: + | string + | boolean + | ((location: HistoryLocation, action: Action) => string | false | void) + ): Unregister, + createHref(location: $Shape): string, + |}; + + declare export type BrowserHistory = History<>; + + declare type BrowserHistoryOpts = {| + basename?: string, + forceRefresh?: boolean, + getUserConfirmation?: ( + message: string, + callback: (willContinue: boolean) => void + ) => void, + keyLength?: number, + |}; + + declare function createBrowserHistory( + opts?: BrowserHistoryOpts + ): BrowserHistory; + + declare export type MemoryHistory = {| + ...History<>, + index: number, + entries: Array, + canGo(n: number): boolean, + |}; + + declare type MemoryHistoryOpts = {| + initialEntries?: Array, + initialIndex?: number, + keyLength?: number, + getUserConfirmation?: ( + message: string, + callback: (willContinue: boolean) => void + ) => void, + |}; + + declare function createMemoryHistory(opts?: MemoryHistoryOpts): MemoryHistory; + + declare export type HashLocation = {| + ...Location, + state: void, + key: void, + |}; + + declare export type HashHistory = History; + + declare type HashHistoryOpts = {| + basename?: string, + hashType: 'slash' | 'noslash' | 'hashbang', + getUserConfirmation?: ( + message: string, + callback: (willContinue: boolean) => void + ) => void, + |}; + + declare function createHashHistory(opts?: HashHistoryOpts): HashHistory; + + // PathUtils + declare function parsePath(path: string): Location; + + declare function createPath(location: $Shape): string; + + // LocationUtils + declare function locationsAreEqual( + a: $Shape, + b: $Shape + ): boolean; + + declare function createLocation( + path: string | $Shape, + state?: { ... }, + key?: string, + currentLocation?: Location + ): Location; +} diff --git a/definitions/npm/history_v4.x.x/flow_v0.201.x-/test_history_v4.x.x.js b/definitions/npm/history_v4.x.x/flow_v0.201.x-/test_history_v4.x.x.js new file mode 100644 index 0000000000..944f84f784 --- /dev/null +++ b/definitions/npm/history_v4.x.x/flow_v0.201.x-/test_history_v4.x.x.js @@ -0,0 +1,333 @@ +// @flow + +import { describe, it } from 'flow-typed-test'; + +import { + createBrowserHistory, + createMemoryHistory, + createHashHistory, + createPath, + parsePath, + locationsAreEqual, + createLocation, +} from 'history'; + +// browser history + +describe('browser history', () => { + it('should allow to get location fields', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + keyLength: 6, + }); + + const pathname: string = history.location.pathname; + }); + + it('should allow to get browser and memory specific location fields', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + keyLength: 6, + }); + + const key: string = history.location.key; + const state: { ... } = history.location.state; + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + keyLength: 6, + }); + + // $FlowExpectedError[prop-missing] + history.foo; + }); + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + keyLength: 6, + }); + + history.push('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + keyLength: 6, + }); + + history.push({ + pathname: '/', + state: { a: 1 }, + }); + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + keyLength: 6, + }); + + history.replace('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + keyLength: 6, + }); + + history.replace({ + pathname: '/', + state: { a: 1 }, + }); + }); + }); +}); + +describe('memory history', () => { + it('should allow to get location fields', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + keyLength: 6, + }); + + const pathname: string = history.location.pathname; + }); + + it('should allow to get browser and memory specific location fields', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + keyLength: 6, + }); + + const key: string = history.location.key; + const state: { ... } = history.location.state; + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + keyLength: 6, + }); + + // $FlowExpectedError[prop-missing] + history.foo; + }); + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + keyLength: 6, + }); + + history.push('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + keyLength: 6, + }); + + history.push({ + pathname: '/', + state: { a: 1 }, + }); + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + keyLength: 6, + }); + + history.replace('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + keyLength: 6, + }); + + history.replace({ + pathname: '/', + state: { a: 1 }, + }); + }); + }); +}); + +describe('hash history', () => { + it('should allow to get location fields', () => { + const history = createHashHistory({ + basename: '', + hashType: 'slash', + }); + + const pathname: string = history.location.pathname; + }); + + it('should not allow to get browser and memory specific location fields', () => { + const history = createHashHistory({ + basename: '', + hashType: 'slash', + }); + + // $FlowExpectedError[incompatible-type] + const key: string = history.location.key; + // $FlowExpectedError[incompatible-type] + const state: { ... } = history.location.state; + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createHashHistory({ + basename: '', + hashType: 'slash', + }); + + // $FlowExpectedError[prop-missing] + history.foo; + }); + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createHashHistory({ + basename: '', + hashType: 'slash', + }); + + history.push('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createHashHistory({ + basename: '', + hashType: 'slash', + }); + + history.push({ + search: '?a=1', + }); + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createHashHistory({ + basename: '', + hashType: 'slash', + }); + + history.replace('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createHashHistory({ + basename: '', + hashType: 'slash', + }); + + history.push({ + search: '?a=1', + }); + }); + }); +}); + +describe('create path', () => { + it('should allow to use Location argument', () => { + const path = createPath({ + pathname: '/test', + search: '?a=1', + hash: 'slug', + }); + + const key: string = path; + // $FlowExpectedError[incompatible-type] + const state: { ... } = path; + }); + + it('should not allow to accept void', () => { + // $FlowExpectedError[incompatible-shape] + const path = createPath(); + + const key: string = path; + }); +}); + +describe('parse path', () => { + it('should allow to use string argument', () => { + const location = parsePath('/test?query#hash'); + + const state: { ... } = location; + // $FlowExpectedError[incompatible-type] + const key: string = location; + }); + + it('should not allow to accept void', () => { + // $FlowExpectedError[incompatible-call] + const location = parsePath(); + + const state: { ... } = location; + }); +}); + +describe('create location', () => { + it('should allow to use string argument', () => { + const location = createLocation('/test?query#hash'); + + const state: { ... } = location; + // $FlowExpectedError[incompatible-type] + const key: string = location; + }); + + it('should allow to use partial location as first argument', () => { + const location = createLocation({ + pathname: '/test', + search: '?a=1', + hash: 'slug', + }); + + const state: { ... } = location; + // $FlowExpectedError[incompatible-type] + const key: string = location; + }); +}); + +describe('locations are equal', () => { + it('should allow to use partial location as arguments and return boolean', () => { + const isEqual = locationsAreEqual( + { pathname: '/test' }, + { pathname: '/test', search: '?a=1' } + ); + + const bool: boolean = isEqual; + // $FlowExpectedError[incompatible-type] + const str: string = isEqual; + }); +}); diff --git a/definitions/npm/history_v5.x.x/flow_v0.104.x-/history_v5.x.x.js b/definitions/npm/history_v5.x.x/flow_v0.104.x-v0.200.x/history_v5.x.x.js similarity index 100% rename from definitions/npm/history_v5.x.x/flow_v0.104.x-/history_v5.x.x.js rename to definitions/npm/history_v5.x.x/flow_v0.104.x-v0.200.x/history_v5.x.x.js diff --git a/definitions/npm/history_v5.x.x/flow_v0.104.x-/test_history_v5.x.x.js b/definitions/npm/history_v5.x.x/flow_v0.104.x-v0.200.x/test_history_v5.x.x.js similarity index 100% rename from definitions/npm/history_v5.x.x/flow_v0.104.x-/test_history_v5.x.x.js rename to definitions/npm/history_v5.x.x/flow_v0.104.x-v0.200.x/test_history_v5.x.x.js diff --git a/definitions/npm/history_v5.x.x/flow_v0.201.x-/history_v5.x.x.js b/definitions/npm/history_v5.x.x/flow_v0.201.x-/history_v5.x.x.js new file mode 100644 index 0000000000..dd5fe4a75c --- /dev/null +++ b/definitions/npm/history_v5.x.x/flow_v0.201.x-/history_v5.x.x.js @@ -0,0 +1,92 @@ +declare module 'history' { + declare type Unregister = () => void; + + declare export type Action = 'PUSH' | 'REPLACE' | 'POP'; + + declare export type Location = {| + pathname: string, + search: string, + hash: string, + state: { ... }, + key: string, + |}; + + declare type History = {| + length: number, + location: HistoryLocation, + action: Action, + push: ((path: string, state?: { ... }) => void) & + ((location: $Shape) => void), + replace: ((path: string, state?: { ... }) => void) & + ((location: $Shape) => void), + go(n: number): void, + back(): void, + forward(): void, + listen(({| location: HistoryLocation, action: Action |}) => void): Unregister, + block( + blocker: (transition: {| + action: Action, + location: HistoryLocation, + retry: () => void, + |}) => void, + ): Unregister, + createHref(location: $Shape): string, + |}; + + declare export type BrowserHistory = History<>; + + declare type BrowserHistoryOpts = {| + basename?: string, + forceRefresh?: boolean, + |}; + + declare function createBrowserHistory( + opts?: BrowserHistoryOpts + ): BrowserHistory; + + declare export type MemoryHistory = {| + ...History<>, + index: number, + entries: Array, + canGo(n: number): boolean, + |}; + + declare type MemoryHistoryOpts = {| + initialEntries?: Array, + initialIndex?: number, + |}; + + declare function createMemoryHistory(opts?: MemoryHistoryOpts): MemoryHistory; + + declare export type HashLocation = {| + ...Location, + state: void, + key: void, + |}; + + declare export type HashHistory = History; + + declare type HashHistoryOpts = {| + basename?: string, + |}; + + declare function createHashHistory(opts?: HashHistoryOpts): HashHistory; + + // PathUtils + declare function parsePath(path: string): Location; + + declare function createPath(location: $Shape): string; + + // LocationUtils + declare function locationsAreEqual( + a: $Shape, + b: $Shape + ): boolean; + + declare function createLocation( + path: string | $Shape, + state?: { ... }, + key?: string, + currentLocation?: Location + ): Location; +} diff --git a/definitions/npm/history_v5.x.x/flow_v0.201.x-/test_history_v5.x.x.js b/definitions/npm/history_v5.x.x/flow_v0.201.x-/test_history_v5.x.x.js new file mode 100644 index 0000000000..64d471dedc --- /dev/null +++ b/definitions/npm/history_v5.x.x/flow_v0.201.x-/test_history_v5.x.x.js @@ -0,0 +1,343 @@ +// @flow +import { describe, it } from 'flow-typed-test'; + +import { + createBrowserHistory, + createMemoryHistory, + createHashHistory, + createPath, + parsePath, + locationsAreEqual, + createLocation, + type Action, + type Location, +} from 'history'; + +// browser history + +describe('browser history', () => { + it('should allow to get location fields', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + }); + + const pathname: string = history.location.pathname; + }); + + it('should allow to get browser and memory specific location fields', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + }); + + const key: string = history.location.key; + const state: { ... } = history.location.state; + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + }); + + // $FlowExpectedError[prop-missing] + history.foo; + }); + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + }); + + history.push('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + }); + + history.push({ + pathname: '/', + state: { a: 1 }, + }); + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + }); + + history.replace('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createBrowserHistory({ + basename: '', + forceRefresh: false, + }); + + history.replace({ + pathname: '/', + state: { a: 1 }, + }); + }); + }); +}); + +describe('memory history', () => { + it('should allow to get location fields', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + }); + + const pathname: string = history.location.pathname; + }); + + it('should allow to get browser and memory specific location fields', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + }); + + const key: string = history.location.key; + const state: { ... } = history.location.state; + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + }); + + // $FlowExpectedError[prop-missing] + history.foo; + }); + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + }); + + history.push('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + }); + + history.push({ + pathname: '/', + state: { a: 1 }, + }); + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + }); + + history.replace('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createMemoryHistory({ + initialEntries: ['/'], + initialIndex: 0, + }); + + history.replace({ + pathname: '/', + state: { a: 1 }, + }); + }); + }); +}); + +describe('hash history', () => { + it('should allow to get location fields', () => { + const history = createHashHistory({ + basename: '', + }); + + const pathname: string = history.location.pathname; + }); + + it('should not allow to get browser and memory specific location fields', () => { + const history = createHashHistory({ + basename: '', + }); + + // $FlowExpectedError[incompatible-type] + const key: string = history.location.key; + // $FlowExpectedError[incompatible-type] + const state: { ... } = history.location.state; + }); + + it('should not allow to get field which is absent in the history', () => { + const history = createHashHistory({ + basename: '', + }); + + // $FlowExpectedError[prop-missing] + history.foo; + }); + + describe('#push', () => { + it('should allow to use string as first argument', () => { + const history = createHashHistory({ + basename: '', + }); + + history.push('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createHashHistory({ + basename: '', + }); + + history.push({ + search: '?a=1', + }); + }); + }); + + describe('#replace', () => { + it('should allow to use string as first argument', () => { + const history = createHashHistory({ + basename: '', + }); + + history.replace('/'); + }); + + it('should allow to use partial location as first argument', () => { + const history = createHashHistory({ + basename: '', + }); + + history.push({ + search: '?a=1', + }); + }); + }); +}); + +describe('create path', () => { + it('should allow to use Location argument', () => { + const path = createPath({ + pathname: '/test', + search: '?a=1', + hash: 'slug', + }); + + const key: string = path; + // $FlowExpectedError[incompatible-type] + const state: { ... } = path; + }); + + it('should not allow to accept void', () => { + // $FlowExpectedError[incompatible-shape] + const path = createPath(); + + const key: string = path; + }); +}); + +describe('parse path', () => { + it('should allow to use string argument', () => { + const location = parsePath('/test?query#hash'); + + const state: { ... } = location; + // $FlowExpectedError[incompatible-type] + const key: string = location; + }); + + it('should not allow to accept void', () => { + // $FlowExpectedError[incompatible-call] + const location = parsePath(); + + const state: { ... } = location; + }); +}); + +describe('create location', () => { + it('should allow to use string argument', () => { + const location = createLocation('/test?query#hash'); + + const state: { ... } = location; + // $FlowExpectedError[incompatible-type] + const key: string = location; + }); + + it('should allow to use partial location as first argument', () => { + const location = createLocation({ + pathname: '/test', + search: '?a=1', + hash: 'slug', + }); + + const state: { ... } = location; + // $FlowExpectedError[incompatible-type] + const key: string = location; + }); +}); + +describe('locations are equal', () => { + it('should allow to use partial location as arguments and return boolean', () => { + const isEqual = locationsAreEqual( + { pathname: '/test' }, + { pathname: '/test', search: '?a=1' } + ); + + const bool: boolean = isEqual; + // $FlowExpectedError[incompatible-type] + const str: string = isEqual; + }); +}); + +describe('block api', () => { + const history = createBrowserHistory({ + basename: '', + }); + + it('returns a callable function', () => { + const unregister = history.block(() => {}); + unregister(); + + // $FlowExpectedError[extra-arg] accepts no args + unregister('test') + }); + + it('passes correct values into blocker', () => { + const unregister = history.block((({ action, location, retry }) => { + (action: Action); + (location: Location); + + retry(); + // $FlowExpectedError[extra-arg] accepts no args + retry('test'); + })); + }); + + it('blocker must be provided', () => { + // $FlowExpectedError[incompatible-call] + const unregister = history.block(); + }); +}); diff --git a/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.104.x-/hoist-non-react-statics_v2.x.x.js b/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.104.x-v0.200.x/hoist-non-react-statics_v2.x.x.js similarity index 100% rename from definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.104.x-/hoist-non-react-statics_v2.x.x.js rename to definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.104.x-v0.200.x/hoist-non-react-statics_v2.x.x.js diff --git a/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.104.x-/test_hoist-non-react-statics_v2.x.x.js b/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.104.x-v0.200.x/test_hoist-non-react-statics_v2.x.x.js similarity index 100% rename from definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.104.x-/test_hoist-non-react-statics_v2.x.x.js rename to definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.104.x-v0.200.x/test_hoist-non-react-statics_v2.x.x.js diff --git a/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.201.x-/hoist-non-react-statics_v2.x.x.js b/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.201.x-/hoist-non-react-statics_v2.x.x.js new file mode 100644 index 0000000000..e8078536df --- /dev/null +++ b/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.201.x-/hoist-non-react-statics_v2.x.x.js @@ -0,0 +1,12 @@ +declare module 'hoist-non-react-statics' { + /* + S - source component statics + TP - target component props + SP - additional source component props + */ + declare module.exports: ( + target: React$ComponentType, + source: React$ComponentType & S, + blacklist?: { [key: $Keys]: boolean, ... } + ) => React$ComponentType & $Shape; +} diff --git a/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.201.x-/test_hoist-non-react-statics_v2.x.x.js b/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.201.x-/test_hoist-non-react-statics_v2.x.x.js new file mode 100644 index 0000000000..7fdf66e257 --- /dev/null +++ b/definitions/npm/hoist-non-react-statics_v2.x.x/flow_v0.201.x-/test_hoist-non-react-statics_v2.x.x.js @@ -0,0 +1,50 @@ +// @flow + +import React from 'react'; +import hoistNonReactStatics from 'hoist-non-react-statics'; + +// $FlowExpectedError +hoistNonReactStatics(1); +// $FlowExpectedError +hoistNonReactStatics(1, 2); +// $FlowExpectedError +hoistNonReactStatics(1, 2, 3); + +let C1 = (props: { + a: number, + b: string, + ... +}) => +
+ {props.a} {props.b} +
; + +const C2 = (props: { + a: number, + b: string, + c: boolean, + ... +}) => +
+ {props.a} {props.b} {props.c} +
; +C2.foo = 1; +C2.bar = 2; + +C1 = hoistNonReactStatics(C1, C2, { foo: true }); +C1.bar; + +class A extends React.Component<{a: number, ...}> { + static foo() { return 123; } +} + +class B extends React.Component<{b: string, ...}> { + render() { return ; } +} + +const C = hoistNonReactStatics(B, A); + +A.foo(); +// $FlowExpectedError +B.foo(); +C.foo(); diff --git a/definitions/npm/idb_v5.x.x/flow_v0.83.x-/idb_v5.x.x.js b/definitions/npm/idb_v5.x.x/flow_v0.201.x-/idb_v5.x.x.js similarity index 100% rename from definitions/npm/idb_v5.x.x/flow_v0.83.x-/idb_v5.x.x.js rename to definitions/npm/idb_v5.x.x/flow_v0.201.x-/idb_v5.x.x.js diff --git a/definitions/npm/idb_v5.x.x/flow_v0.83.x-v0.200.x/idb_v5.x.x.js b/definitions/npm/idb_v5.x.x/flow_v0.83.x-v0.200.x/idb_v5.x.x.js new file mode 100644 index 0000000000..79939d71ec --- /dev/null +++ b/definitions/npm/idb_v5.x.x/flow_v0.83.x-v0.200.x/idb_v5.x.x.js @@ -0,0 +1,643 @@ +// Derived from TS typings at https://github.com/jakearchibald/idb/blob/c8bab898f01bacab96097f87c1e42a0c19e01425/lib/idb.d.ts +// Updated for changes between v2 and v5. + +declare type $idb$IDBArrayKey = $ReadOnlyArray<$idb$IDBValidKey>; +declare type $idb$IDBValidKey = number | string | Date | $idb$IDBArrayKey; + +// TODO: upstream this to Flow DOM definitions +declare class $idb$DOMStringList { + +length: number; + // Comment syntax here as @@iterator is invalid syntax for eslint and babylon + /*:: @@iterator(): Iterator; */ + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; + @@iterator(): Iterator; +} + +/** Similar to equivalent IDBDatabase. */ +declare class $idb$DB> { + /** A DOMString that contains the name of the connected database. */ + +name: string; + + /** A 64-bit integer that contains the version of the connected database. When a database is first created, this attribute is an empty string. */ + +version: number; + + /** A DOMStringList that contains a list of the names of the object stores currently in the connected database. */ + +objectStoreNames: $idb$DOMStringList; + + /** Returns immediately and closes the connection to a database in a separate thread. */ + close(): void; + + /** + * Creates and returns a new object store or index. + * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. + * @param name The name of the new object store to be created. Note that it is possible to create an object store with an empty name. + * @param optionalParameters Optional. An options object whose attributes are optional parameters to the method. + * @returns The new object store. + */ + createObjectStore( + name: string, + optionalParameters?: $Shape<{| + +keyPath: string, + +autoIncrement: boolean, + |}> + ): ObjectStore; + + /** + * Destroys the object store with the given name in the connected database, along with any indexes that reference it. + * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. + * @param name The name of the object store to be removed. + */ + deleteObjectStore(name: string): void; + + /** + * Immediately returns a transaction object (Transaction) containing the IDBTransaction.objectStore method, which you can use to access your object store. Runs in a separate thread. + * @param storeNames The names of object stores and indexes that are in the scope of the new transaction, declared as an array of strings. Specify only the object stores that you need to access. + * If you need to access only one object store, you can specify its name as a string. + * @param mode Optional. The types of access that can be performed in the transaction. Transactions are opened in one of three modes: 'readonly' or 'readwrite'. 'versionchange' mode can't be specified here. If you don't provide the parameter, the default access mode is readonly. To avoid slowing things down, don't open a readwrite transaction unless you actually need to write into the database. + * @returns The transaction object. + */ + transaction( + storeNames: string, + mode?: 'readonly' | 'readwrite' + ): $idb$Transaction; + transaction( + storeNames: Array, + mode?: 'readonly' | 'readwrite' + ): $idb$Transaction; + + /*--- + * These are the objectstore shortcuts: they're the same prototypes of the + * functions in ObjectStore except they also take the store name as first + * parameter. + *--- */ + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) creates a structured clone of the value, and updates the cloned value in the object store. + * This is for updating existing records in an object store when the transaction's mode is readwrite. + * @param storeName the store to use. + * @param value The value to be stored. + * @param key Optional. The key to use to identify the record. If unspecified, it results to null. + * @returns A promise that resolves with the new key when the underlying put IDBRequest is successful. + */ + put(storeName: string, value: mixed, key?: $idb$IDBValidKey): Promise<$idb$IDBValidKey>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) creates a structured clone of the value, and stores the cloned value in the object store. + * This is for adding new records to an object store. + * @param storeName the store to use. + * @param value The value to be stored. + * @param key Optional. The key to use to identify the record. If unspecified, it results to null. + * @returns A promise that resolves with the new key when the underlying add IDBRequest is successful. + */ + add(storeName: string, value: mixed, key?: $idb$IDBValidKey): Promise<$idb$IDBValidKey>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) deletes the store object specified. + * This is for deleting individual records out of an object store. + * @param storeName the store to use. + * @param key The key of the record to be deleted, or an IDBKeyRange to delete all records with keys in range. + * @returns A promise that resolves when the underlying delete IDBRequest is successful. + */ + delete(storeName: string, key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) clears the object store. + * This is for deleting all current records out of an object store. + * @param storeName the store to use. + * @returns A promise that resolves when the underlying clear IDBRequest is successful. + */ + clear(storeName: string): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with the store object store selected by the specified key. + * This is for retrieving specific records from an object store. + * @param storeName the store to use. + * @param key The key or key range that identifies the record to be retrieved. + * @returns A promise that resolves with the item when the underlying get IDBRequest is successful. + */ + get(storeName: string, key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with the objects in the object store matching the specified parameter or all objects in the store if no parameters are given. + * @param storeName the store to use. + * @param query Optional. A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param count Optional. Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. + * @returns A promise that resolves with the items when the underlying getAll IDBRequest is successful. + */ + getAll( + storeName: string, + query?: IDBKeyRange | $idb$IDBValidKey, + count?: number + ): Promise>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) finds either the given key or the primary key, if key is an IDBKeyRange. + * @param storeName the store to use. + * @param key The key or key range that identifies the record to be retrieved. + * @returns A promise that resolves with the item when the underlying get IDBRequest is successful. + */ + getKey(storeName: string, key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with record keys for all the objects matching the specified parameter or all record keys in the store if no parameters are given. + * @param storeName the store to use. + * @param query Optional. A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param count Optional. Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. + * @returns A promise that resolves with the record keys when the underlying getAllKeys IDBRequest is successful. + */ + getAllKeys(storeName: string, query?: IDBKeyRange, count?: number): Promise>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) counts the matching records. + * If no arguments are provided, it returns the total number of records in the store. + * @param storeName the store to use. + * @param key A key or IDBKeyRange object that specifies a range of records you want to count. + * @returns A promise that resolves with the total when the underlying count IDBRequest is successful. + */ + count(storeName: string, key?: IDBKeyRange | $idb$IDBValidKey): Promise; + + /*--- + * These are the index shortcuts: they're the same prototypes of the + * functions in Index except they also take the store and index names as + * first parameters. + *--- */ + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) counts the matching records. + * If no arguments are provided, it returns the total number of records in the store. + * @param storeName the store to use. + * @param indexName the index to use. + * @param key A key or IDBKeyRange object that specifies a range of records you want to count. + * @returns A promise that resolves with the total when the underlying count IDBRequest is successful. + */ + countFromIndex(storeName: string, indexName: string, key?: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with the store object store selected by the specified key. + * This is for retrieving specific records from an object store. + * @param storeName the store to use. + * @param indexName the index to use. + * @param key The key or key range that identifies the record to be retrieved. + * @returns A promise that resolves with the item when the underlying get IDBRequest is successful. + */ + getFromIndex(storeName: string, indexName: string, key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) finds either the given key or the primary key, if key is an IDBKeyRange. + * @param storeName the store to use. + * @param indexName the index to use. + * @param key The key or key range that identifies the record to be retrieved. + * @returns A promise that resolves with the item when the underlying get IDBRequest is successful. + */ + getKeyFromIndex(storeName: string, indexName: string, key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with the objects in the object store matching the specified parameter or all objects in the store if no parameters are given. + * @param storeName the store to use. + * @param indexName the index to use. + * @param query Optional. A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param count Optional. Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. + * @returns A promise that resolves with the items when the underlying getAll IDBRequest is successful. + */ + getAllFromIndex( + storeName: string, + indexName: string, + query?: IDBKeyRange | $idb$IDBValidKey, + count?: number + ): Promise>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with record keys for all the objects matching the specified parameter or all record keys in the store if no parameters are given. + * @param storeName the store to use. + * @param indexName the index to use. + * @param query Optional. A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param count Optional. Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. + * @returns A promise that resolves with the record keys when the underlying getAllKeys IDBRequest is successful. + */ + getAllKeysFromIndex(storeName: string, indexName: string, query?: IDBKeyRange, count?: number): Promise>; +} + +type $idb$OpenDBCallbacks> = {| + /** + * Called if this version of the database has never been opened before. Use it to specify the + * schema for the database. + * + * @param database A database instance that you can use to add/remove stores and indexes. + * @param oldVersion Last version of the database opened by the user. + * @param newVersion Whatever new version you provided. + * @param transaction The transaction for this upgrade. This is useful if you need to get data + * from other stores as part of a migration. + */ + upgrade( + database: $idb$DB, + oldVersion: number, + newVersion: number | null, + transaction: $idb$Transaction + ): void, + /** + * Called if there are older versions of the database open on the origin, so this version cannot + * open. + */ + blocked(): void, + /** + * Called if this connection is blocking a future version of the database from opening. + */ + blocking(): void, + /** + * Called if the browser abnormally terminates the connection. + * This is not called when `db.close()` is called. + */ + terminated(): void, +|}; + +/** Wrapper of IDBTransaction that presents the asynchronous operations as a Promise. */ +declare class $idb$Transaction, StoreType: ObjectStore | null> { + /** Resolves when transaction completes, rejects if transaction aborts or errors. */ + +done: Promise; + +store: StoreType; + + /** Returns a DOMStringList of the names of IDBObjectStore objects. */ + +objectStoreNames: $idb$DOMStringList; + + /** The mode for isolating access to data in the object stores that are in the scope of the transaction. For possible values, see the Constants section below. The default value is readonly. */ + +mode: 'readonly' | 'readwrite' | 'versionchange'; + + /** Rolls back all the changes to objects in the database associated with this transaction. If this transaction has been aborted or completed, then this method throws an error event. */ + abort(): void; + + /** + * Returns an ObjectStore object representing an object store that is part of the scope of this transaction. + * @param name The name of the requested object store. + * @returns The object store in the context of the transaction. + */ + objectStore(name: string): ObjectStore; +} + +/** Common interface for ObjectStore and Index, since both provide these cursor methods */ +declare class $idb$HasCursor { + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves a new cursor object. + * Used for iterating through an object store by primary key with a cursor. + * @param range Optional. A key or IDBKeyRange to be queried. If a single valid key is passed, this will default to a range containing only that key. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param direction Optional. An IDBCursorDirection² telling the cursor what direction to travel. Defaults to "next". + * @returns A promise that resolves with the cursor once it has been opened. + */ + openCursor( + range?: IDBKeyRange | $idb$IDBValidKey | null, + direction?: 'next' | 'nextunique' | 'prev' | 'prevunique' + ): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves a new cursor object. + * Used for iterating through an object store with a key. + * @param range Optional. A key or IDBKeyRange to be queried. If a single valid key is passed, this will default to a range containing only that key. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param direction Optional. An IDBCursorDirection telling the cursor what direction to travel. Defaults to "next". + * @returns A promise that resolves with the cursor once it has been opened. + */ + openKeyCursor( + range?: IDBKeyRange | $idb$IDBValidKey | null, + direction?: 'next' | 'nextunique' | 'prev' | 'prevunique' + ): Promise; +} + +/** Wrapper of IDBObjectStore that presents the asynchronous operations as Promises. */ +declare class $idb$ObjectStore> extends $idb$HasCursor { + /** The name of this object store. Settable only during upgrades. */ + name: string; + + /** The key path of this object store. If this attribute is null, the application must provide a key for each modification operation. */ + +keyPath: string | Array; + + /** A list of the names of indexes on objects in this object store. */ + +indexNames: $idb$DOMStringList; + + /** The value of the auto increment flag for this object store. */ + +autoIncrement: boolean; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) creates a structured clone of the value, and updates the cloned value in the object store. + * This is for updating existing records in an object store when the transaction's mode is readwrite. + * @param value The value to be stored. + * @param key Optional. The key to use to identify the record. If unspecified, it results to null. + * @returns A promise that resolves with the new key when the underlying put IDBRequest is successful. + */ + put(value: mixed, key?: $idb$IDBValidKey): Promise<$idb$IDBValidKey>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) creates a structured clone of the value, and stores the cloned value in the object store. + * This is for adding new records to an object store. + * @param value The value to be stored. + * @param key Optional. The key to use to identify the record. If unspecified, it results to null. + * @returns A promise that resolves with the new key when the underlying add IDBRequest is successful. + */ + add(value: mixed, key?: $idb$IDBValidKey): Promise<$idb$IDBValidKey>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) deletes the store object specified. + * This is for deleting individual records out of an object store. + * @param key The key of the record to be deleted, or an IDBKeyRange to delete all records with keys in range. + * @returns A promise that resolves when the underlying delete IDBRequest is successful. + */ + delete(key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) clears the object store. + * This is for deleting all current records out of an object store. + * @returns A promise that resolves when the underlying clear IDBRequest is successful. + */ + clear(): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with the store object store selected by the specified key. + * This is for retrieving specific records from an object store. + * @param key The key or key range that identifies the record to be retrieved. + * @returns A promise that resolves with the item when the underlying get IDBRequest is successful. + */ + get(key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with the objects in the object store matching the specified parameter or all objects in the store if no parameters are given. + * @param query Optional. A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param count Optional. Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. + * @returns A promise that resolves with the items when the underlying getAll IDBRequest is successful. + */ + getAll( + query?: IDBKeyRange | $idb$IDBValidKey, + count?: number + ): Promise>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) finds either the given key or the primary key, if key is an IDBKeyRange. + * @param key The key or key range that identifies the record to be retrieved. + * @returns A promise that resolves with the item when the underlying get IDBRequest is successful. + */ + getKey(key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with record keys for all the objects matching the specified parameter or all record keys in the store if no parameters are given. + * @param query Optional. A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param count Optional. Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. + * @returns A promise that resolves with the record keys when the underlying getAllKeys IDBRequest is successful. + */ + getAllKeys(query?: IDBKeyRange, count?: number): Promise>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) counts the matching records. + * If no arguments are provided, it returns the total number of records in the store. + * @param key A key or IDBKeyRange object that specifies a range of records you want to count. + * @returns A promise that resolves with the total when the underlying count IDBRequest is successful. + */ + count(key?: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Creates a new index during a version upgrade, returning a new Index object in the connected database. + * @param name The name of the index to create. It is possible to create an index with an empty name. + * @param keyPath The key path for the index to use. It is possible to create an index with an empty keyPath, and also to pass in an array as a keyPath. + * @param optionalParameters Additional options: unique and multiEntry. + * @returns The newly created index. + */ + createIndex( + name: string, + keyPath: string | Array, + optionalParameters?: $Shape<{| + +unique: boolean, + +multiEntry: boolean, + +locale: string | 'auto' | null, + |}> + ): Index; + + /** + * Destroys the specified index in the connected database, used during a version upgrade. + * @param indexName The name of the existing index to remove. + */ + deleteIndex(indexName: string): void; + + /** + * Opens an index from this object store after which it can, for example, be used to return a sequence of records sorted by that index using a cursor. + * @param name The name of the existing index to get. + * @returns The specified index. + */ + index(name: string): Index; +} + +/** Wrapper of IDBIndex that presents the asynchronous operations as Promises. */ +declare class $idb$Index extends $idb$HasCursor { + /** The name of this index. */ + +name: string; + + /** The key path of this index. If null, this index is not auto-populated. */ + +keyPath: string | Array; + + /** + * Affects how the index behaves when the result of evaluating the index's key path yields an array. + * If true, there is one record in the index for each item in an array of keys. + * If false, then there is one record for each key that is an array. + */ + +multiEntry: boolean; + + /** If true, this index does not allow duplicate values for a key. */ + +unique: boolean; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) counts the matching records. + * If no arguments are provided, it returns the total number of records in the store. + * @param key A key or IDBKeyRange object that specifies a range of records you want to count. + * @returns A promise that resolves with the total when the underlying count IDBRequest is successful. + */ + count(key?: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with the store object store selected by the specified key. + * This is for retrieving specific records from an object store. + * @param key The key or key range that identifies the record to be retrieved. + * @returns A promise that resolves with the item when the underlying get IDBRequest is successful. + */ + get(key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) finds either the given key or the primary key, if key is an IDBKeyRange. + * @param key The key or key range that identifies the record to be retrieved. + * @returns A promise that resolves with the item when the underlying get IDBRequest is successful. + */ + getKey(key: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with the objects in the object store matching the specified parameter or all objects in the store if no parameters are given. + * @param query Optional. A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param count Optional. Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. + * @returns A promise that resolves with the items when the underlying getAll IDBRequest is successful. + */ + getAll( + query?: IDBKeyRange | $idb$IDBValidKey, + count?: number + ): Promise>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) resolves with record keys for all the objects matching the specified parameter or all record keys in the store if no parameters are given. + * @param query Optional. A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. + * @param count Optional. Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. + * @returns A promise that resolves with the record keys when the underlying getAllKeys IDBRequest is successful. + */ + getAllKeys(query?: IDBKeyRange, count?: number): Promise>; +} + +/** Wrapper of IDBCursor that presents the asynchronous operations as Promises. */ +declare class $idb$Cursor { + /** The key for the record at the cursor's position. If the cursor is outside its range, this is set to undefined. The cursor's key can be any data type. */ + +key: IDBKeyRange | $idb$IDBValidKey; + + /** The cursor's current effective primary key. If the cursor is currently being iterated or has iterated outside its range, this is set to undefined. The cursor's primary key can be any data type. */ + +primaryKey: any; + + /** The direction of traversal of the cursor. */ + +direction: 'next' | 'nextunique' | 'prev' | 'prevunique'; + + /** The current value under the cursor. */ + +value: any; + + /** Returns the IDBObjectStore or IDBIndex the cursor was opened from. */ + +source: $idb$Index> | $idb$ObjectStore, $idb$Index>>; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) deletes the record at the cursor's position, without changing the cursor's position. + * This can be used to delete specific records. + * @returns A promise that resolves when the underlying delete IDBRequest is successful. + */ + delete(): Promise; + + /** + * Returns a Promise of an IDBRequest object that (in a separate thread) updates the value at the current position of the cursor in the object store. + * This can be used to update specific records. + * @param value The value to write over the current cursor location. + * @returns A promise that resolves when the underlying update IDBRequest is successful. + */ + update(value: any): Promise; + + /** + * Sets the number times a cursor should move its position forward. + * @param count The number of times to move the cursor forward. + * @returns The cursor after having been moved forward the specified number of times. + */ + advance(count: number): Promise; + + /** + * Advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. + * @param key Optional. The key to position the cursor at. If no key is specified, the cursor advances to the immediate next position, based on the its direction. + * @returns The cursor after having been continued to the next or specified record. + */ + continue(key?: IDBKeyRange | $idb$IDBValidKey): Promise; + + /** + * Sets the cursor to the given index key and primary key given as arguments. + * @param key The key to position the cursor at. + * @param primaryKey The primary key to position the cursor at. + * @returns The cursor after having been continued to the next or specified record. + */ + continuePrimaryKey( + key: IDBKeyRange | $idb$IDBValidKey, + primaryKey: IDBKeyRange | $idb$IDBValidKey + ): Promise; +} + +declare module 'idb' { + declare export type ObjectStore = $idb$ObjectStore; + declare export type DB = $idb$DB; + declare export type Index = $idb$Index; + declare export type Cursor = $idb$Cursor; + declare export type Transaction = $idb$Transaction; + + declare type OpenDBCallbacks = $idb$OpenDBCallbacks; + + /** + * This method returns a promise that resolves to a DB. + * @param name The name of the database. + * @param version Optional. The version to open the database with. If the version is not provided and the database exists, then a connection to the database will be opened without changing its version. If the version is not provided and the database does not exist, then it will be created with version 1. + * @param upgradeCallback Optional. Called if version is greater than the version last opened. It's similar to IDB's onupgradeneeded. The callback receives an instance of UpgradeDB. + * @returns A Promise that passes the DB once it has been opened. + */ + declare export function openDB( + name: string, + version: number, + options?: $Shape, + ): Promise; + + /** + * Behaves like indexedDB.deleteDatabase, but returns a promise. + * @param name The name of the database. + * @returns A Promise that completes once the DB has been removed. + */ + declare export function deleteDB(name: string): Promise; + + declare export var wrap: {| + (IDBDatabase): DB; + (IDBTransaction): Transaction; + (IDBObjectStore): ObjectStore; + (IDBIndex): Index; + (IDBRequest): Promise; // Unfortunately the default Flow types for IDB are severaly lacking, so we can't do better. + |}; + + declare export var unwrap: {| + (DB): IDBDatabase; + (Transaction): IDBTransaction; + (ObjectStore): IDBObjectStore; + (Index): IDBIndex; + (Promise): IDBRequest; + |}; +} + +declare module 'idb/with-async-ittr.js' { + declare class HasAsyncCursor { + @@asyncIterator(): AsyncIterator; + iterate( + range?: IDBKeyRange | $idb$IDBValidKey | null, + direction?: 'next' | 'nextunique' | 'prev' | 'prevunique' + ): AsyncIterable; + } + + declare export class ObjectStore extends $idb$ObjectStore mixins HasAsyncCursor {} + declare export class Index extends $idb$Index mixins HasAsyncCursor {} + declare export class Cursor extends $idb$Cursor { + @@asyncIterator(): AsyncIterator; + } + + declare export type DB = $idb$DB; + declare export type Transaction = $idb$Transaction; + + declare type OpenDBCallbacks = $idb$OpenDBCallbacks; + + /** + * This method returns a promise that resolves to a DB. + * @param name The name of the database. + * @param version Optional. The version to open the database with. If the version is not provided and the database exists, then a connection to the database will be opened without changing its version. If the version is not provided and the database does not exist, then it will be created with version 1. + * @param upgradeCallback Optional. Called if version is greater than the version last opened. It's similar to IDB's onupgradeneeded. The callback receives an instance of UpgradeDB. + * @returns A Promise that passes the DB once it has been opened. + */ + declare export function openDB( + name: string, + version: number, + options?: $Shape, + ): Promise; + + /** + * Behaves like indexedDB.deleteDatabase, but returns a promise. + * @param name The name of the database. + * @returns A Promise that completes once the DB has been removed. + */ + declare export function deleteDB(name: string): Promise; + + declare export var wrap: {| + (IDBDatabase): DB; + (IDBTransaction): Transaction; + (IDBObjectStore): ObjectStore; + (IDBIndex): Index; + (IDBRequest): Promise; // Unfortunately the default Flow types for IDB are severaly lacking, so we can't do better. + |}; + + declare export var unwrap: {| + (DB): IDBDatabase; + (Transaction): IDBTransaction; + (ObjectStore): IDBObjectStore; + (Index): IDBIndex; + (Promise): IDBRequest; + |}; +} diff --git a/definitions/npm/introscope_v1.0.10/flow_v0.104.x-/introscope_v1.0.10.js b/definitions/npm/introscope_v1.0.10/flow_v0.104.x-v0.200.x/introscope_v1.0.10.js similarity index 100% rename from definitions/npm/introscope_v1.0.10/flow_v0.104.x-/introscope_v1.0.10.js rename to definitions/npm/introscope_v1.0.10/flow_v0.104.x-v0.200.x/introscope_v1.0.10.js diff --git a/definitions/npm/introscope_v1.0.10/flow_v0.201.x-/introscope_v1.0.10.js b/definitions/npm/introscope_v1.0.10/flow_v0.201.x-/introscope_v1.0.10.js new file mode 100644 index 0000000000..af4198850b --- /dev/null +++ b/definitions/npm/introscope_v1.0.10/flow_v0.201.x-/introscope_v1.0.10.js @@ -0,0 +1,10 @@ +declare module 'introscope' { + // `introscope` is using any type on purpose, + // some developers require only part of their tests + // to have strict types. + // eslint-disable-next-line flowtype/no-weak-types + declare type AnyScope = { [string]: any, ... }; + declare function introscope(scope: AnyScope): AnyScope => AnyScope; + + declare function scope(scope: Scope): ($Shape) => Scope; +} diff --git a/definitions/npm/jsonwebtoken_v8.1.x/flow_v0.104.x-/jsonwebtoken_v8.1.x.js b/definitions/npm/jsonwebtoken_v8.1.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.1.x.js similarity index 100% rename from definitions/npm/jsonwebtoken_v8.1.x/flow_v0.104.x-/jsonwebtoken_v8.1.x.js rename to definitions/npm/jsonwebtoken_v8.1.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.1.x.js diff --git a/definitions/npm/jsonwebtoken_v8.1.x/flow_v0.201.x-/jsonwebtoken_v8.1.x.js b/definitions/npm/jsonwebtoken_v8.1.x/flow_v0.201.x-/jsonwebtoken_v8.1.x.js new file mode 100644 index 0000000000..786abfaaad --- /dev/null +++ b/definitions/npm/jsonwebtoken_v8.1.x/flow_v0.201.x-/jsonwebtoken_v8.1.x.js @@ -0,0 +1,122 @@ +declare module "jsonwebtoken" { + declare module.exports: { + sign: jwt$Sign, + decode: jwt$Decode, + verify: jwt$Verify, + JsonWebTokenError: Class, + NotBeforeError: Class, + TokenExpiredError: Class, + ... + } +} + +declare type jwt$Encodable = String | Buffer | Object; +declare type jwt$Key = { + key: string | Buffer, + passphrase: string | Buffer, + ... +}; +declare type jwt$Algorithm = + 'RS256' + | 'RS384' + | 'RS512' + | 'ES256' + | 'ES384' + | 'ES512' + | 'HS256' + | 'HS384' + | 'HS512' + | 'none'; + +declare type jwt$Callback = (tokenOrError: Error | string) => void; +declare type jwt$SigningOptions = $Shape<{ + algorithm: jwt$Algorithm, + expiresIn: number | string, + notBefore: number | string, + audience: string | string[], + issuer: string, + jwtid: string, + subject: string, + noTimestamp: boolean, + header: Headers, + keyid: string, + ... +}>; + +declare type jwt$SigningOptionsWithAlgorithm = jwt$SigningOptions & { algorithm: jwt$Algorithm, ... }; +declare type jwt$VerifyOptionsWithAlgorithm = jwt$VerifyOptions & { algorithms: Array, ... }; + +declare type jwt$VerifyOptions = $Shape<{ + algorithms: Array, + audience: string, + issuer: string | string[], + ignoreExpiration: boolean, + ignoreNotBefore: boolean, + subject: string | string[], + clockTolerance: number, + maxAge: string | number, + clockTimestamp: number, + ... +}>; + +declare type jwt$DecodingOptions = $Shape<{ + complete: boolean, + json: boolean, + encoding: string, + ... +}>; + +declare interface jwt$Sign { + + (payload: P, secretOrPrivateKey: string | Buffer): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, callback: jwt$Callback): string; + + + (payload: P, secretOrPrivateKey: jwt$Key, options: jwt$SigningOptionsWithAlgorithm): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>, callback: jwt$Callback): string; + + + (payload: P, secretOrPrivateKey: jwt$Key, options: jwt$SigningOptionsWithAlgorithm, callback: jwt$Callback): string; +} + +declare interface jwt$Decode { + (jwt: string): mixed; + + (jwt: string, options: jwt$DecodingOptions): mixed; + + (jwt: string, options: jwt$DecodingOptions & { complete: true, ... }): { + header: Object, + payload: mixed, + signature: string, + ... + }; +} + +declare interface jwt$Verify { + (jwt: string, secretOrPrivateKey: string | Buffer): mixed; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: jwt$VerifyOptions | jwt$Callback): mixed; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: jwt$VerifyOptions, callback: jwt$Callback): mixed; + + (jwt: string, secretOrPrivateKey: jwt$Key, options: jwt$VerifyOptionsWithAlgorithm): mixed; + + (jwt: string, secretOrPrivateKey: jwt$Key, options: jwt$VerifyOptionsWithAlgorithm, callback: jwt$Callback): mixed; +} + +declare class jwt$TokenExpiredError extends Error { +} + +declare class jwt$WebTokenError extends Error { +} + +declare class jwt$NotBeforeError extends Error { +} + diff --git a/definitions/npm/jsonwebtoken_v8.2.x/flow_v0.104.x-/jsonwebtoken_v8.2.x.js b/definitions/npm/jsonwebtoken_v8.2.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.2.x.js similarity index 100% rename from definitions/npm/jsonwebtoken_v8.2.x/flow_v0.104.x-/jsonwebtoken_v8.2.x.js rename to definitions/npm/jsonwebtoken_v8.2.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.2.x.js diff --git a/definitions/npm/jsonwebtoken_v8.2.x/flow_v0.201.x-/jsonwebtoken_v8.2.x.js b/definitions/npm/jsonwebtoken_v8.2.x/flow_v0.201.x-/jsonwebtoken_v8.2.x.js new file mode 100644 index 0000000000..c6e2d0ec44 --- /dev/null +++ b/definitions/npm/jsonwebtoken_v8.2.x/flow_v0.201.x-/jsonwebtoken_v8.2.x.js @@ -0,0 +1,157 @@ +declare module "jsonwebtoken" { + + declare class JsonWebTokenError extends Error { + name: string; + message: string; + inner: Error; + } + + declare class TokenExpiredError extends Error { + name: string; + expiredAt: number; + inner: Error; + } + + declare class NotBeforeError extends Error { + name: string; + date: Date; + inner: Error; + } + + declare type Encodable = String | Buffer | Object; + declare type Key = { + key: string | Buffer, + passphrase: string | Buffer, + ... + }; + declare type Algorithm = + 'RS256' + | 'RS384' + | 'RS512' + | 'ES256' + | 'ES384' + | 'ES512' + | 'HS256' + | 'HS384' + | 'HS512' + | 'none'; + + declare type SignCallback = (err: Error, token: string) => void; + declare type SigningOptions = $Shape<{ + algorithm: Algorithm, + expiresIn: number | string, + notBefore: number | string, + audience: string | string[], + issuer: string | string[], + jwtid: string, + subject: string, + noTimestamp: boolean, + header: Headers, + keyid: string, + ... + }>; + + declare type SigningOptionsWithAlgorithm = SigningOptions & { algorithm: Algorithm, ... }; + + declare type VerifyCallback = (err: JsonWebTokenError | NotBeforeError | TokenExpiredError | null, decoded: Payload) => void; + declare type VerifyOptionsWithAlgorithm = VerifyOptions & { algorithms: Array, ... }; + declare type VerifyOptions = $Shape<{ + algorithms: Array, + audience: string | string[], + issuer: string | string[], + ignoreExpiration: boolean, + ignoreNotBefore: boolean, + subject: string | string[], + clockTolerance: number, + maxAge: string | number, + clockTimestamp: number, + ... + }>; + + declare type DecodingOptions = $Shape<{ + complete: boolean, + json: boolean, + ... + }>; + + declare interface Sign { + + (payload: P, secretOrPrivateKey: string | Buffer): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, callback: SignCallback): string; + + + (payload: P, secretOrPrivateKey: Key, options: SigningOptionsWithAlgorithm): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>, callback: SignCallback): string; + + + (payload: P, secretOrPrivateKey: Key, options: SigningOptionsWithAlgorithm, callback: SignCallback): string; + } + + declare type Payload = Object & { + jti?: string, + iss?: string, + sub?: string, + aud?: string | string[], + exp?: number, + iat?: number, + nbf?: number, + ... + } + + declare type Token = { + header: { + typ: 'JWT', + alg: Algorithm, + ... + }, + payload: Payload, + signature?: string, + ... + } + + declare interface Decode { + (jwt: string): Payload; + + (jwt: string, options: DecodingOptions): Payload; + + (jwt: string, options: DecodingOptions & { complete: true, ... }): Token; + } + + declare interface Verify { + (jwt: string, secretOrPrivateKey: string | Buffer): Payload; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: VerifyOptions | VerifyCallback): Payload; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: VerifyOptions, callback: VerifyCallback): Payload; + + (jwt: string, secretOrPrivateKey: Key, options: VerifyOptionsWithAlgorithm): Payload; + + (jwt: string, secretOrPrivateKey: Key, options: VerifyOptionsWithAlgorithm, callback: VerifyCallback): Payload; + } + + declare class TokenExpiredError extends Error { + } + + declare class WebTokenError extends Error { + } + + declare class NotBeforeError extends Error { + } + + declare module.exports: { + sign: Sign, + decode: Decode, + verify: Verify, + JsonWebTokenError: Class, + NotBeforeError: Class, + TokenExpiredError: Class, + ... + } +} diff --git a/definitions/npm/jsonwebtoken_v8.3.x/flow_v0.104.x-/jsonwebtoken_v8.3.x.js b/definitions/npm/jsonwebtoken_v8.3.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.3.x.js similarity index 100% rename from definitions/npm/jsonwebtoken_v8.3.x/flow_v0.104.x-/jsonwebtoken_v8.3.x.js rename to definitions/npm/jsonwebtoken_v8.3.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.3.x.js diff --git a/definitions/npm/jsonwebtoken_v8.3.x/flow_v0.201.x-/jsonwebtoken_v8.3.x.js b/definitions/npm/jsonwebtoken_v8.3.x/flow_v0.201.x-/jsonwebtoken_v8.3.x.js new file mode 100644 index 0000000000..980b9a61c3 --- /dev/null +++ b/definitions/npm/jsonwebtoken_v8.3.x/flow_v0.201.x-/jsonwebtoken_v8.3.x.js @@ -0,0 +1,161 @@ +declare module "jsonwebtoken" { + + declare class JsonWebTokenError extends Error { + name: string; + message: string; + inner: Error; + } + + declare class TokenExpiredError extends Error { + name: string; + expiredAt: number; + inner: Error; + } + + declare class NotBeforeError extends Error { + name: string; + date: Date; + inner: Error; + } + + declare type Encodable = String | Buffer | Object; + declare type Key = { + key: string | Buffer, + passphrase: string | Buffer, + ... + }; + declare type Algorithm = + 'RS256' + | 'RS384' + | 'RS512' + | 'ES256' + | 'ES384' + | 'ES512' + | 'HS256' + | 'HS384' + | 'HS512' + | 'none'; + + declare type SignCallback = (err: Error, token: string) => void; + declare type SigningOptions = $Shape<{ + algorithm: Algorithm, + expiresIn: number | string, + notBefore: number | string, + audience: string | string[], + issuer: string | string[], + jwtid: string, + subject: string, + noTimestamp: boolean, + header: Headers, + keyid: string, + ... + }>; + + declare type SigningOptionsWithAlgorithm = SigningOptions & { algorithm: Algorithm, ... }; + + declare type VerifyCallback = (err: JsonWebTokenError | NotBeforeError | TokenExpiredError | null, decoded: Payload) => void; + declare type VerifyOptionsWithAlgorithm = VerifyOptions & { algorithms: Array, ... }; + declare type VerifyOptions = $Shape<{ + algorithms: Array, + audience: string | string[], + issuer: string | string[], + ignoreExpiration: boolean, + ignoreNotBefore: boolean, + subject: string | string[], + clockTolerance: number, + maxAge: string | number, + clockTimestamp: number, + ... + }>; + + declare type DecodingOptions = $Shape<{ + complete: boolean, + json: boolean, + ... + }>; + + declare interface Sign { + + (payload: P, secretOrPrivateKey: string | Buffer): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, callback: SignCallback): string; + + + (payload: P, secretOrPrivateKey: Key, options: SigningOptionsWithAlgorithm): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>, callback: SignCallback): string; + + + (payload: P, secretOrPrivateKey: Key, options: SigningOptionsWithAlgorithm, callback: SignCallback): string; + } + + declare type Payload = Object & { + jti?: string, + iss?: string, + sub?: string, + aud?: string | string[], + exp?: number, + iat?: number, + nbf?: number, + ... + } + + declare type Token = { + header: { + typ: 'JWT', + alg: Algorithm, + ... + }, + payload: Payload, + signature?: string, + ... + } + + declare interface Decode { + (jwt: string): Payload; + + (jwt: string, options: DecodingOptions): Payload; + + (jwt: string, options: DecodingOptions & { complete: true, ... }): Token; + } + + declare interface Verify { + (jwt: string, secretOrPrivateKey: string | Buffer): Payload; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: VerifyOptions | VerifyCallback): Payload; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: VerifyOptions, callback: VerifyCallback): Payload; + + (jwt: string, secretOrPrivateKey: Key, options: VerifyOptionsWithAlgorithm): Payload; + + (jwt: string, secretOrPrivateKey: Key, options: VerifyOptionsWithAlgorithm, callback: VerifyCallback): Payload; + + (jwt: string, getKey: (header: { kid: ?string, ... }, callback: (err: ?Error, key?: string) => any) => any, callback: VerifyCallback): Payload; + + (jwt: string, getKey: (header: { kid: ?string, ... }, callback: (err: ?Error, key?: string) => any) => any, options: VerifyOptionsWithAlgorithm, callback: VerifyCallback): Payload; + } + + declare class TokenExpiredError extends Error { + } + + declare class WebTokenError extends Error { + } + + declare class NotBeforeError extends Error { + } + + declare module.exports: { + sign: Sign, + decode: Decode, + verify: Verify, + JsonWebTokenError: Class, + NotBeforeError: Class, + TokenExpiredError: Class, + ... + } +} diff --git a/definitions/npm/jsonwebtoken_v8.4.x/flow_v0.104.x-/jsonwebtoken_v8.4.x.js b/definitions/npm/jsonwebtoken_v8.4.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.4.x.js similarity index 100% rename from definitions/npm/jsonwebtoken_v8.4.x/flow_v0.104.x-/jsonwebtoken_v8.4.x.js rename to definitions/npm/jsonwebtoken_v8.4.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.4.x.js diff --git a/definitions/npm/jsonwebtoken_v8.4.x/flow_v0.201.x-/jsonwebtoken_v8.4.x.js b/definitions/npm/jsonwebtoken_v8.4.x/flow_v0.201.x-/jsonwebtoken_v8.4.x.js new file mode 100644 index 0000000000..8122c31cbd --- /dev/null +++ b/definitions/npm/jsonwebtoken_v8.4.x/flow_v0.201.x-/jsonwebtoken_v8.4.x.js @@ -0,0 +1,162 @@ +declare module "jsonwebtoken" { + + declare class JsonWebTokenError extends Error { + name: string; + message: string; + inner: Error; + } + + declare class TokenExpiredError extends Error { + name: string; + expiredAt: number; + inner: Error; + } + + declare class NotBeforeError extends Error { + name: string; + date: Date; + inner: Error; + } + + declare type Encodable = String | Buffer | Object; + declare type Key = { + key: string | Buffer, + passphrase: string | Buffer, + ... + }; + declare type Algorithm = + 'RS256' + | 'RS384' + | 'RS512' + | 'ES256' + | 'ES384' + | 'ES512' + | 'HS256' + | 'HS384' + | 'HS512' + | 'none'; + + declare type SignCallback = (err: Error, token: string) => void; + declare type SigningOptions = $Shape<{ + algorithm: Algorithm, + expiresIn: number | string, + notBefore: number | string, + audience: string | string[], + issuer: string | string[], + jwtid: string, + subject: string, + noTimestamp: boolean, + header: Headers, + keyid: string, + ... + }>; + + declare type SigningOptionsWithAlgorithm = SigningOptions & { algorithm: Algorithm, ... }; + + declare type VerifyCallback = (err: JsonWebTokenError | NotBeforeError | TokenExpiredError | null, decoded: Payload) => void; + declare type VerifyOptionsWithAlgorithm = VerifyOptions & { algorithms: Array, ... }; + declare type VerifyOptions = $Shape<{ + algorithms: Array, + audience: string | string[], + issuer: string | string[], + ignoreExpiration: boolean, + ignoreNotBefore: boolean, + subject: string | string[], + clockTolerance: number, + maxAge: string | number, + clockTimestamp: number, + nonce?: string, + ... + }>; + + declare type DecodingOptions = $Shape<{ + complete: boolean, + json: boolean, + ... + }>; + + declare interface Sign { + + (payload: P, secretOrPrivateKey: string | Buffer): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, callback: SignCallback): string; + + + (payload: P, secretOrPrivateKey: Key, options: SigningOptionsWithAlgorithm): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>, callback: SignCallback): string; + + + (payload: P, secretOrPrivateKey: Key, options: SigningOptionsWithAlgorithm, callback: SignCallback): string; + } + + declare type Payload = Object & { + jti?: string, + iss?: string, + sub?: string, + aud?: string | string[], + exp?: number, + iat?: number, + nbf?: number, + ... + } + + declare type Token = { + header: { + typ: 'JWT', + alg: Algorithm, + ... + }, + payload: Payload, + signature?: string, + ... + } + + declare interface Decode { + (jwt: string): Payload; + + (jwt: string, options: DecodingOptions): Payload; + + (jwt: string, options: DecodingOptions & { complete: true, ... }): Token; + } + + declare interface Verify { + (jwt: string, secretOrPrivateKey: string | Buffer): Payload; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: VerifyOptions | VerifyCallback): Payload; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: VerifyOptions, callback: VerifyCallback): Payload; + + (jwt: string, secretOrPrivateKey: Key, options: VerifyOptionsWithAlgorithm): Payload; + + (jwt: string, secretOrPrivateKey: Key, options: VerifyOptionsWithAlgorithm, callback: VerifyCallback): Payload; + + (jwt: string, getKey: (header: { kid: ?string, ... }, callback: (err: ?Error, key?: string) => any) => any, callback: VerifyCallback): Payload; + + (jwt: string, getKey: (header: { kid: ?string, ... }, callback: (err: ?Error, key?: string) => any) => any, options: VerifyOptionsWithAlgorithm, callback: VerifyCallback): Payload; + } + + declare class TokenExpiredError extends Error { + } + + declare class WebTokenError extends Error { + } + + declare class NotBeforeError extends Error { + } + + declare module.exports: { + sign: Sign, + decode: Decode, + verify: Verify, + JsonWebTokenError: Class, + NotBeforeError: Class, + TokenExpiredError: Class, + ... + } +} diff --git a/definitions/npm/jsonwebtoken_v8.5.x/flow_v0.104.x-/jsonwebtoken_v8.5.x.js b/definitions/npm/jsonwebtoken_v8.5.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.5.x.js similarity index 100% rename from definitions/npm/jsonwebtoken_v8.5.x/flow_v0.104.x-/jsonwebtoken_v8.5.x.js rename to definitions/npm/jsonwebtoken_v8.5.x/flow_v0.104.x-v0.200.x/jsonwebtoken_v8.5.x.js diff --git a/definitions/npm/jsonwebtoken_v8.5.x/flow_v0.201.x-/jsonwebtoken_v8.5.x.js b/definitions/npm/jsonwebtoken_v8.5.x/flow_v0.201.x-/jsonwebtoken_v8.5.x.js new file mode 100644 index 0000000000..37ef102146 --- /dev/null +++ b/definitions/npm/jsonwebtoken_v8.5.x/flow_v0.201.x-/jsonwebtoken_v8.5.x.js @@ -0,0 +1,164 @@ +declare module "jsonwebtoken" { + + declare class JsonWebTokenError extends Error { + name: string; + message: string; + inner: Error; + } + + declare class TokenExpiredError extends Error { + name: string; + expiredAt: number; + inner: Error; + } + + declare class NotBeforeError extends Error { + name: string; + date: Date; + inner: Error; + } + + declare type Encodable = String | Buffer | Object; + declare type Key = { + key: string | Buffer, + passphrase: string | Buffer, + ... + }; + declare type Algorithm = + 'RS256' + | 'RS384' + | 'RS512' + | 'ES256' + | 'ES384' + | 'ES512' + | 'HS256' + | 'HS384' + | 'HS512' + | 'none'; + + declare type SignCallback = (err: Error, token: string) => void; + declare type SigningOptions = $Shape<{ + algorithm: Algorithm, + expiresIn: number | string, + notBefore: number | string, + audience: string | string[], + issuer: string | string[], + jwtid: string, + subject: string, + noTimestamp: boolean, + header: Headers, + keyid: string, + ... + }>; + + declare type SigningOptionsWithAlgorithm = SigningOptions & { algorithm: Algorithm, ... }; + + declare type VerifyCallback = (err: JsonWebTokenError | NotBeforeError | TokenExpiredError | null, decoded: Payload) => void; + declare type VerifyOptionsWithAlgorithm = VerifyOptions & { algorithms: Array, ... }; + declare type VerifyOptions = $Shape<{ + algorithms: Array, + audience: string | string[], + issuer: string | string[], + ignoreExpiration: boolean, + ignoreNotBefore: boolean, + subject: string | string[], + clockTolerance: number, + maxAge: string | number, + clockTimestamp: number, + nonce?: string, + /** return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload. */ + complete?: boolean, + ... + }>; + + declare type DecodingOptions = $Shape<{ + complete: boolean, + json: boolean, + ... + }>; + + declare interface Sign { + + (payload: P, secretOrPrivateKey: string | Buffer): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, callback: SignCallback): string; + + + (payload: P, secretOrPrivateKey: Key, options: SigningOptionsWithAlgorithm): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>): string; + + + (payload: P, secretOrPrivateKey: string | Buffer, options: $Shape>, callback: SignCallback): string; + + + (payload: P, secretOrPrivateKey: Key, options: SigningOptionsWithAlgorithm, callback: SignCallback): string; + } + + declare type Payload = Object & { + jti?: string, + iss?: string, + sub?: string, + aud?: string | string[], + exp?: number, + iat?: number, + nbf?: number, + ... + } + + declare type Token = { + header: { + typ: 'JWT', + alg: Algorithm, + ... + }, + payload: Payload, + signature?: string, + ... + } + + declare interface Decode { + (jwt: string): Payload; + + (jwt: string, options: DecodingOptions): Payload; + + (jwt: string, options: DecodingOptions & { complete: true, ... }): Token; + } + + declare interface Verify { + (jwt: string, secretOrPrivateKey: string | Buffer): Payload; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: VerifyOptions | VerifyCallback): Payload; + + (jwt: string, secretOrPrivateKey: string | Buffer, options: VerifyOptions, callback: VerifyCallback): Payload; + + (jwt: string, secretOrPrivateKey: Key, options: VerifyOptionsWithAlgorithm): Payload; + + (jwt: string, secretOrPrivateKey: Key, options: VerifyOptionsWithAlgorithm, callback: VerifyCallback): Payload; + + (jwt: string, getKey: (header: { kid: ?string, ... }, callback: (err: ?Error, key?: string) => any) => any, callback: VerifyCallback): Payload; + + (jwt: string, getKey: (header: { kid: ?string, ... }, callback: (err: ?Error, key?: string) => any) => any, options: VerifyOptionsWithAlgorithm, callback: VerifyCallback): Payload; + } + + declare class TokenExpiredError extends Error { + } + + declare class WebTokenError extends Error { + } + + declare class NotBeforeError extends Error { + } + + declare module.exports: { + sign: Sign, + decode: Decode, + verify: Verify, + JsonWebTokenError: Class, + NotBeforeError: Class, + TokenExpiredError: Class, + ... + } +} diff --git a/definitions/npm/koa-json-body_v5.x.x/flow_v0.53.x-/koa-json-body_v5.x.x.js b/definitions/npm/koa-json-body_v5.x.x/flow_v0.201.x-/koa-json-body_v5.x.x.js similarity index 100% rename from definitions/npm/koa-json-body_v5.x.x/flow_v0.53.x-/koa-json-body_v5.x.x.js rename to definitions/npm/koa-json-body_v5.x.x/flow_v0.201.x-/koa-json-body_v5.x.x.js diff --git a/definitions/npm/koa-json-body_v5.x.x/flow_v0.53.x-v0.200.x/koa-json-body_v5.x.x.js b/definitions/npm/koa-json-body_v5.x.x/flow_v0.53.x-v0.200.x/koa-json-body_v5.x.x.js new file mode 100644 index 0000000000..0e68bb8b3a --- /dev/null +++ b/definitions/npm/koa-json-body_v5.x.x/flow_v0.53.x-v0.200.x/koa-json-body_v5.x.x.js @@ -0,0 +1,13 @@ +declare module 'koa-json-body' { + declare type Middleware = ( + ctx: any, + next: () => Promise + ) => Promise | void; + declare type Options = $Shape<{| + fallback: boolean, + limit: string | number, + strict: boolean, + |}>; + + declare module.exports: (options?: Options) => Middleware; +} diff --git a/definitions/npm/mongodb_v3.5.x/flow_v0.114.x-/mongodb_v3.5.x.js b/definitions/npm/mongodb_v3.5.x/flow_v0.114.x-v0.200.x/mongodb_v3.5.x.js similarity index 100% rename from definitions/npm/mongodb_v3.5.x/flow_v0.114.x-/mongodb_v3.5.x.js rename to definitions/npm/mongodb_v3.5.x/flow_v0.114.x-v0.200.x/mongodb_v3.5.x.js diff --git a/definitions/npm/mongodb_v3.5.x/flow_v0.114.x-/test_mongodb_v3.5.x_client.js b/definitions/npm/mongodb_v3.5.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.5.x_client.js similarity index 100% rename from definitions/npm/mongodb_v3.5.x/flow_v0.114.x-/test_mongodb_v3.5.x_client.js rename to definitions/npm/mongodb_v3.5.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.5.x_client.js diff --git a/definitions/npm/mongodb_v3.5.x/flow_v0.114.x-/test_mongodb_v3.5.x_docs_quick_start.js b/definitions/npm/mongodb_v3.5.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.5.x_docs_quick_start.js similarity index 100% rename from definitions/npm/mongodb_v3.5.x/flow_v0.114.x-/test_mongodb_v3.5.x_docs_quick_start.js rename to definitions/npm/mongodb_v3.5.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.5.x_docs_quick_start.js diff --git a/definitions/npm/mongodb_v3.5.x/flow_v0.201.x-/mongodb_v3.5.x.js b/definitions/npm/mongodb_v3.5.x/flow_v0.201.x-/mongodb_v3.5.x.js new file mode 100644 index 0000000000..fe5bd55f54 --- /dev/null +++ b/definitions/npm/mongodb_v3.5.x/flow_v0.201.x-/mongodb_v3.5.x.js @@ -0,0 +1,420 @@ +// @flow + +declare module 'mongodb' { + import type { Readable } from 'stream'; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Admin.html + declare export type Admin = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/AggregationCursor.html + declare export type AggregationCursor = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/AutoEncrypter.html + declare export type AutoEncrypter = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Binary.html + declare export var Binary: any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/BSONRegExp.html + declare export var BSONRegExp: any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/BulkOperationBase.html + declare export type BulkOperationBase = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/BulkWriteError.html + declare export var BulkWriteError: any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/BulkWriteResult.html + declare export type BulkWriteResult = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ChangeStream.html + declare export type ChangeStream = any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ClientEncryption.html + declare export type ClientEncryption = any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ClientSession.html + declare export type ClientSession = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Code.html + declare export var Code: any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Collection.html + declare export type Collection = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/CommandCursor.html + declare export type CommandCursor = any; // TODO (use type shouldn't be instantiated) + + declare export type CursorFlag = 'tailable' | 'oplogReplay' | 'noCursorTimeout' | 'awaitData' | 'partial'; + + declare export type CursorCloseOptions = {| + skipKillCursors?: boolean, + |}; + + declare export type CursorResultCallback = (error: ?(typeof MongoError), result: T) => mixed; + declare export type CursorIteratorCallback = (doc: T) => mixed; + declare export type CursorEndCallback = (error: ?(typeof MongoError)) => mixed; + + // TODO + declare export type CollationOptions = any; + + declare export type CursorCountOptions = {| + skip?: number, + limit?: number, + maxTimeMS?: number, + hint?: string, + readPreference?: ReadPreferenceValue, + |}; + + // TODO: type explain https://docs.mongodb.com/manual/reference/method/cursor.explain/#behavior + declare export type ExplainResult = { ... }; + + declare export type Projection = { + ...$ObjMap (1 | -1 | boolean | string)>, + _id?: 1 | false, + ..., + }; + + // TODO + declare export type CursorOption = { ... }; + + declare export type StreamOptions = {| + transform: Input => Doc, + |}; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Cursor.html + declare export interface Cursor extends Readable { + addCursorFlag(flag: CursorFlag, value: boolean): Cursor; + addQueryModifier(name: string, value: string | number | boolean): Cursor; + batchSize(value: number): Cursor; + clone(): Cursor; + close(options: CursorCloseOptions, cb: CursorResultCallback): void; + close(options: CursorCloseOptions): Promise; + close(cb: CursorResultCallback): void; + close(): Promise; + collation(valie: CollationOptions): Cursor; + comment(value: string): Cursor; + count(applySkipLimit: boolean, options: CursorCountOptions, callback: CursorResultCallback): void; + count(applySkipLimit: boolean, options: CursorCountOptions): Promise; + count(applySkipLimit: boolean, callback: CursorResultCallback): void; + count(applySkipLimit: boolean): Promise; + count(callback: CursorResultCallback): void; + count(): Promise; + // deprecated + each(CursorResultCallback): null; + explain(CursorResultCallback): void; + explain(): Promise; + filter(filter: $Shape): Cursor; + forEach(iterator: CursorIteratorCallback, callback: CursorEndCallback): Cursor; + forEach(iterator: CursorIteratorCallback): Promise; + hasNext(callback: CursorResultCallback): void; + hasNext(): Promise; + hint(hint: string): Cursor; + isClosed(): boolean; + limit(value: number): Cursor; + map(transform: Input => Doc): Cursor; + max(value: number): Cursor; + maxAwaitTimeMS(value: number): Cursor; + // Deprecated + maxScan(maxScan: { ... }): Cursor; + maxTimeMS(value: number): Cursor; + min(value: number): Cursor; + next(callback: CursorResultCallback): void; + next(): Promise; + project(value: Projection): Cursor; + returnKey(returnKey: boolean): Cursor; + setCursorOption(field: 'numberOfRetries' | 'tailableRetryInterval', value: CursorOption): Cursor; + setReadPreference(readPreference: ReadPreferenceValue): Cursor; + // TODO: type showRecordId + showRecordId(showRecordId: { ... }): Cursor; + skip(value: number): Cursor; + // Deprecated + snapshot(snapshot: { ... }): Cursor; + sort(keyOrList: $Keys, direction: 1 | -1): Cursor; + sort(keyOrList: [$Keys, 1 | -1][]): Cursor; + sort(keyOrList: { [string]: 1 | -1, ... }): Cursor; + stream(options: StreamOptions): Cursor; + toArray(callback: CursorResultCallback): void; + toArray(): Promise; + transformStream(options: StreamOptions): Readable; + } + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Db.html + declare export var Db: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/DBRef.html + declare export var DBRef: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Decimal128.html + declare export var Decimal128: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Double.html + declare export var Double: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/FindOperators.html + declare export type FindOperators = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridFSBucket.html + declare export var GridFSBucket: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridFSBucketReadStream.html + declare export type GridFSBucketReadStream = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridFSBucketWriteStream.html + declare export type GridFSBucketWriteStream = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridStore.html + declare export var GridStore: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridStoreStream.html + declare export type GridStoreStream = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Int32.html + declare export var Int32: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Logger.html + declare export var Logger: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Long.html + declare export var Long: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MaxKey.html + declare export var MaxKey: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MinKey.html + declare export var MinKey: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html + declare export class MongoClient { + static connect(url: string, options: MongoClientOptions, callback: ConnectCallback): MongoClient; + static connect(url: string, callback: ConnectCallback): MongoClient; + static connect(url: string, options?: MongoClientOptions): Promise; + + constructor(url: string, options?: MongoClientOptions, callback?: ConnectCallback): MongoClient; + constructor(url: string, callback?: ConnectCallback): MongoClient; + + close(force: boolean, callback: NoResultCallback): void; + close(callback: NoResultCallback): void; + close(force?: boolean): Promise; + + connect(callback: ConnectCallback): void; + connect(): Promise; + + db(dbName?: string, options?: DbOptions): typeof Db; + + isConnected(options?: DbOptions): boolean; + + startSession(options?: SessionOptions): ClientSession; + + watch(pipeline?: AggregationPipeline, options?: ClientWatchOptions): ChangeStream; + + withSession(options?: WithSessionOptions, operation: Operation): Promise; // TODO confirm return + withSession(operation: Operation): Promise; // TODO confirm return + } + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoCryptError.html + declare export var MongoCryptError: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoError.html + declare export var MongoError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoNetworkError.html + declare export var MongoNetworkError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoParseError.html + declare export var MongoParseError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Mongos.html + declare export var Mongos: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoServerSelectionError.html + declare export var MongoServerSelectionError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoTimeoutError.html + declare export var MongoTimeoutError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoWriteConcernError.html + declare export var MongoWriteConcernError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ObjectID.html + declare export var ObjectID: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/OrderedBulkOperation.html + declare export type OrderedBulkOperation = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ReplSet.html + declare export var ReplSet: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Server.html + declare export var Server: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Symbol.html + declare export var Symbol: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Timestamp.html + declare export type Timestamp = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/UnorderedBulkOperation.html + declare export type UnorderedBulkOperation = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/WriteConcernError.html + declare export var WriteConcernError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/WriteError.html + declare export type WriteError = any; // TODO (use type shouldn't be instantiated) + + declare export type ReadPreference = {| + PRIMARY: 'primary', + PRIMARY_PREFERRED: 'primaryPreferred', + SECONDARY: 'secondary', + SECONDARY_PREFERRED: 'secondaryPreferred', + NEAREST: 'nearest', + |}; + declare export type ReadPreferenceValue = 'primary' | 'primaryPreferred' | 'secondary' + | 'secondaryPreferred' | 'nearest' + + declare export type ReadConcernLevel = 'local' | 'available' | 'majority' | 'linearizable' | 'snapshot'; + + declare export type ReadConcern = {| + type: ReadConcernLevel, + |} + + declare export type DriverInfoOptionsObject = {| + name?: string, + version?: string, + platform?: string, + |}; + + declare export type KMSProviders = {| + aws: {| + accessKeyId?: string, + secretAccessKey?: string, + |}, + local: {| + key?: Buffer, + |}, + |}; + + declare export type AutoEncryptionOptionsObject = {| + keyVaultClient?: MongoClient, + keyVaultNamespace?: string, + kmsProviders?: KMSProviders, + schemaMap?: { [string]: mixed, ... }, + bypassAutoEncryption?: boolean, + options?: {| + logger: LoggerInterface, + |}, + extraOptions: {| + mongocryptdURI?: string, + mongocryptdBypassSpawn?: boolean, + mongocryptdSpawnPath?: string, + mongocryptdSpawnArgs?: string[] + |}, + |}; + + declare export type ConnectCallback = (error: typeof MongoError, client: MongoClient) => mixed; + declare export type NoResultCallback = (error: typeof MongoError, null) => mixed; + + declare export type PkFactory = { + createPk(): typeof ObjectID, + ..., + }; + + declare export type LoggerInterface = {| + debug(string): mixed, + info(string): mixed, + warn(string): mixed, + error(string): mixed, + |}; + + declare export type Auth = {| + user: string, password: string, + |} + + declare export type MongoClientOptions = {| + poolSize?: number, + ssl?: boolean, + sslValidate?: boolean, + sslCA?: Buffer, // deprecated + sslCert?: Buffer, // deprecated + sslKey?: Buffer, // deprecated + sslPass?: string, // deprecated + sslCert?: Buffer, // deprecated + sslCRL?: Buffer, // deprecated + checkServerIdentity?: boolean | ((servername: string, cert: string) => boolean); // deprecated + tls?: boolean, + tlsInsecure?: boolean, + tlsCAFile?: string, + tlsCertificateKeyFile?: string, + tlsCertificateKeyFilePassword?: string, + tlsAllowInvalidCertificates?: boolean, + tlsAllowInvalidHostnames?: boolean, + autoReconnect?: boolean, + noDelay?: boolean, + keepAlive?: boolean, + keepAliveInitialDelay?: number, + connectTimeoutMS?: number, + socketTimeoutMS?: number, + family?: 4 | 6 | null, + reconnectTries?: number, + reconnectInterval?: number, + ha?: boolean, + haInterval?: number, + replicaSet?: string, + secondaryAcceptableLatencyMS?: number, + acceptableLatencyMS?: number, + connectWithNoPrimary?: boolean, + authSource?: string, + w?: string | number, + wtimeout?: number, + j?: boolean, + forceServerObjectId?: boolean, + serializeFunctions?: boolean, + ignoreUndefined?: boolean, + raw?: boolean, + bufferMaxEntries?: number, + readPreference?: ReadPreferenceValue, + pkFactory?: PkFactory, + promiseLibrary?: { ... }, // TODO + readConcern?: ReadConcern, + maxStalenessSeconds?: number, + loggerLevel?: 'error' | 'warn' | 'info' | 'debug', + logger?: LoggerInterface, + promoteValues?: boolean, + promoteBuffers?: boolean, + promoteLongs?: boolean, + domainsEnabled?: boolean, + validateOptions?: boolean, + appname?: string, + auth?: Auth, + authMechanism?: 'MDEFAULT' | 'GSSAPI' | 'PLAIN' | 'MONGODB-X509' | 'SCRAM-SHA-1', + compression?: 'snappy' | 'zlib', + fsync?: boolean, + readPreferenceTags?: Array<{ [string]: string, ... }>, + numberOfRetries?: number, + auto_reconnect?: boolean, + monitorCommands?: boolean, + minSize?: number, + useNewUrlParser?: boolean, + useUnifiedTopology?: boolean, + autoEncryption?: AutoEncryptionOptionsObject, + driverInfo?: DriverInfoOptionsObject, + |}; + + declare export type DbOptions = {| + noListener?: boolean, + returnNonCachedInstance?: boolean, + |}; + + declare export type SessionOptions = { ... }; // TODO + declare export type Session = AnalyserNode; // TODO + + declare export type AggregationStage = { ... }; // TODO + declare export type AggregationPipeline = $ReadOnlyArray; + + declare export type ClientWatchOptions = { ... }; // TODO + + declare export type WithSessionOptions = { ... }; // TODO + + declare export type Operation = (session: Session) => mixed; // TODO +} \ No newline at end of file diff --git a/definitions/npm/mongodb_v3.5.x/flow_v0.201.x-/test_mongodb_v3.5.x_client.js b/definitions/npm/mongodb_v3.5.x/flow_v0.201.x-/test_mongodb_v3.5.x_client.js new file mode 100644 index 0000000000..0a340266c2 --- /dev/null +++ b/definitions/npm/mongodb_v3.5.x/flow_v0.201.x-/test_mongodb_v3.5.x_client.js @@ -0,0 +1,480 @@ +// @flow + +import { describe, it } from 'flow-typed-test'; +import { + MongoClient, + type MongoClientOptions, + type ConnectCallback, + type PkFactory, + type ReadConcern, + type LoggerInterface, + type Auth, + type AutoEncryptionOptionsObject, + type DriverInfoOptionsObject, + type ReadPreferenceValue, + type Cursor, +} from 'mongodb'; +import { Readable } from 'stream'; + +describe('static connect', () => { + describe('Promises', () => { + it('url should be a string', () => { + const client: Promise = MongoClient.connect( + 'mongodb://localhost:27017' + ); + // $FlowExpectedError[incompatible-call] + MongoClient.connect(2); + // $FlowExpectedError[incompatible-call] + MongoClient.connect(); + }); + + it('should accepts options', (options: MongoClientOptions) => { + const client: Promise = MongoClient.connect( + 'mongodb://localhost:27017', + options + ); + // $FlowExpectedError[incompatible-call] + MongoClient.connect( + 'mongodb://localhost:27017', + { invalidOptionsKey: 'string' } + ); + }); + }); + describe('Callback', () => { + it('url should be a string', (cb: ConnectCallback) => { + const client: MongoClient = MongoClient.connect( + 'mongodb://localhost:27017', + cb + ); + // $FlowExpectedError[incompatible-call] + MongoClient.connect(2, cb); + // $FlowExpectedError[incompatible-call] + MongoClient.connect(cb); + // $FlowExpectedError[incompatible-call] + MongoClient.connect( + 'mongodb://localhost:27017', + (error: Error, c: string) => true + ); + }); + + it('should accepts options', (cb: ConnectCallback, options: MongoClientOptions) => { + const client: MongoClient = MongoClient.connect( + 'mongodb://localhost:27017', + options, + cb + ); + // $FlowExpectedError[incompatible-call] + MongoClient.connect( + 'mongodb://localhost:27017', + { invalidOptionsKey: 'string' }, + cb + ); + }); + }); +}); + +describe('connect', () => { + describe('Promises', () => { + it('should return a promise', (client: MongoClient) => { + const c: Promise = client.connect(); + // $FlowExpectedError[incompatible-call] + client.connect('mongodb://localhost:27017'); + }); + }); + describe('Callback', () => { + it('should accepts callback', (client: MongoClient, cb: ConnectCallback) => { + client.connect(cb); + // $FlowExpectedError[incompatible-call] + client.connect('mongodb://localhost:27017', cb); + }); + }); +}); + +describe('MongoClientOptions', (options: MongoClientOptions) => { + it('should supports poolSize options', () => { + const a: void | number = options.poolSize; + // $FlowExpectedError[incompatible-type] + const b: number = options.poolSize; + }); + it('should supports ssl options', () => { + const a: void | boolean = options.ssl; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.ssl; + }); + it('should supports sslValidate options', () => { + const a: void | boolean = options.sslValidate; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.sslValidate; + }); + it('should supports sslCA options', () => { + const a: void | Buffer = options.sslCA; + // $FlowExpectedError[incompatible-type] + const b: Buffer = options.sslCA; + }); + it('should supports sslCert options', () => { + const a: void | Buffer = options.sslCert; + // $FlowExpectedError[incompatible-type] + const b: Buffer = options.sslCert; + }); + it('should supports sslKey options', () => { + const a: void | Buffer = options.sslKey; + // $FlowExpectedError[incompatible-type] + const b: Buffer = options.sslKey; + }); + it('should supports sslPass options', () => { + const a: void | string = options.sslPass; + // $FlowExpectedError[incompatible-type] + const b: string = options.sslPass; + }); + it('should supports sslCRL options', () => { + const a: void | Buffer = options.sslCRL; + // $FlowExpectedError[incompatible-type] + const b: Buffer = options.sslCRL; + }); + it('should supports checkServerIdentity options', () => { + const a: MongoClientOptions = { checkServerIdentity: true }; + const b: MongoClientOptions = { + checkServerIdentity: (servername: string, cert: string) => false, + }; + // $FlowExpectedError[incompatible-type] + const c: MongoClientOptions = { checkServerIdentity: (a: boolean) => {} }; + }); + it('should supports tls options', () => { + const a: void | boolean = options.tls; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.tls; + }); + it('should supports tlsInsecure options', () => { + const a: void | boolean = options.tlsInsecure; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.tlsInsecure; + }); + it('should supports tlsCAFile options', () => { + const a: void | string = options.tlsCAFile; + // $FlowExpectedError[incompatible-type] + const b: string = options.tlsCAFile; + }); + it('should supports tlsCertificateKeyFile options', () => { + const a: void | string = options.tlsCertificateKeyFile; + // $FlowExpectedError[incompatible-type] + const b: string = options.tlsCertificateKeyFile; + }); + it('should supports tlsCertificateKeyFilePassword options', () => { + const a: void | string = options.tlsCertificateKeyFilePassword; + // $FlowExpectedError[incompatible-type] + const b: string = options.tlsCertificateKeyFilePassword; + }); + it('should supports tlsAllowInvalidCertificates options', () => { + const a: void | boolean = options.tlsAllowInvalidCertificates; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.tlsAllowInvalidCertificates; + }); + it('should supports tlsAllowInvalidHostnames options', () => { + const a: void | boolean = options.tlsAllowInvalidHostnames; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.tlsAllowInvalidHostnames; + }); + it('should supports autoReconnect options', () => { + const a: void | boolean = options.autoReconnect; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.autoReconnect; + }); + it('should supports noDelay options', () => { + const a: void | boolean = options.noDelay; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.noDelay; + }); + it('should supports keepAlive options', () => { + const a: void | boolean = options.keepAlive; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.keepAlive; + }); + it('should supports keepAliveInitialDelay options', () => { + const a: void | number = options.keepAliveInitialDelay; + // $FlowExpectedError[incompatible-type] + const b: number = options.keepAliveInitialDelay; + }); + it('should supports connectTimeoutMS options', () => { + const a: void | number = options.connectTimeoutMS; + // $FlowExpectedError[incompatible-type] + const b: number = options.connectTimeoutMS; + }); + it('should supports socketTimeoutMS options', () => { + const a: void | number = options.socketTimeoutMS; + // $FlowExpectedError[incompatible-type] + const b: number = options.socketTimeoutMS; + }); + it('should supports keepAliveInitialDelay options', () => { + const a: 4 | 6 | void | null = options.family; + // $FlowExpectedError[incompatible-type] + const b: number = options.family; + }); + it('should supports reconnectTries options', () => { + const a: number | void = options.reconnectTries; + // $FlowExpectedError[incompatible-type] + const b: number = options.reconnectTries; + }); + it('should supports reconnectInterval options', () => { + const a: number | void = options.reconnectInterval; + // $FlowExpectedError[incompatible-type] + const b: number = options.family; + }); + it('should supports ha options', () => { + const a: boolean | void = options.ha; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.ha; + }); + it('should supports haInterval options', () => { + const a: number | void = options.haInterval; + // $FlowExpectedError[incompatible-type] + const b: number = options.haInterval; + }); + it('should supports replicaSet options', () => { + const a: void | string = options.replicaSet; + // $FlowExpectedError[incompatible-type] + const b: string = options.replicaSet; + }); + it('should supports secondaryAcceptableLatencyMS options', () => { + const a: number | void = options.secondaryAcceptableLatencyMS; + // $FlowExpectedError[incompatible-type] + const b: number = options.secondaryAcceptableLatencyMS; + }); + it('should supports acceptableLatencyMS options', () => { + const a: number | void = options.acceptableLatencyMS; + // $FlowExpectedError[incompatible-type] + const b: number = options.acceptableLatencyMS; + }); + it('should supports connectWithNoPrimary options', () => { + const a: boolean | void = options.connectWithNoPrimary; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.connectWithNoPrimary; + }); + it('should supports authSource options', () => { + const a: string | void = options.authSource; + // $FlowExpectedError[incompatible-type] + const b: string = options.authSource; + }); + it('should supports w options', () => { + const a: number | string | void = options.w; + // $FlowExpectedError[incompatible-type] + const b: number | string = options.w; + }); + it('should supports wtimeout options', () => { + const a: number | void = options.wtimeout; + // $FlowExpectedError[incompatible-type] + const b: number = options.wtimeout; + }); + it('should supports j options', () => { + const a: boolean | void = options.j; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.j; + }); + it('should supports forceServerObjectId options', () => { + const a: boolean | void = options.forceServerObjectId; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.forceServerObjectId; + }); + it('should supports serializeFunctions options', () => { + const a: boolean | void = options.serializeFunctions; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.serializeFunctions; + }); + it('should supports ignoreUndefined options', () => { + const a: boolean | void = options.ignoreUndefined; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.ignoreUndefined; + }); + it('should supports raw options', () => { + const a: boolean | void = options.raw; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.raw; + }); + it('should supports bufferMaxEntries options', () => { + const a: number | void = options.bufferMaxEntries; + // $FlowExpectedError[incompatible-type] + const b: number = options.bufferMaxEntries; + }); + it('should supports raw options', () => { + const a: boolean | void = options.raw; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.raw; + }); + it('should supports readPreference options', () => { + const a: ReadPreferenceValue | void = options.readPreference; + // $FlowExpectedError[incompatible-type] + const b: ReadPreferenceValue = options.readPreference; + }); + it('should supports pkFactory options', (pkFactory: PkFactory) => { + const a: PkFactory | void = options.pkFactory; + // $FlowExpectedError[incompatible-type] + const b: PkFactory = options.pkFactory; + }); + it('should supports pkFactory options', (pkFactory: PkFactory) => { + const a: PkFactory | void = options.pkFactory; + // $FlowExpectedError[incompatible-type] + const b: PkFactory = options.pkFactory; + }); + it('should supports promiseLibrary options', () => { + const a: { ... } | void = options.promiseLibrary; + // $FlowExpectedError[incompatible-type] + const b: { ... } = options.promiseLibrary; + }); + it('should supports readConcern options', () => { + const a: ReadConcern | void = options.readConcern; + // $FlowExpectedError[incompatible-type] + const b: ReadConcern = options.readConcern; + }); + it('should supports maxStalenessSeconds options', () => { + const a: number | void = options.maxStalenessSeconds; + // $FlowExpectedError[incompatible-type] + const b: number = options.maxStalenessSeconds; + }); + it('should supports loggerLevel options', () => { + const a: 'error' | 'warn' | 'info' | 'debug' | void = options.loggerLevel; + // $FlowExpectedError[incompatible-type] + const b: 'error' | 'warn' | 'info' | 'debug' = options.loggerLevel; + }); + it('should supports logger options', () => { + const a: LoggerInterface | void = options.logger; + // $FlowExpectedError[incompatible-type] + const b: LoggerInterface = options.logger; + }); + it('should supports promoteValues options', () => { + const a: boolean | void = options.promoteValues; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.promoteValues; + }); + it('should supports promoteBuffers options', () => { + const a: boolean | void = options.promoteBuffers; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.promoteBuffers; + }); + it('should supports promoteLongs options', () => { + const a: boolean | void = options.promoteLongs; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.promoteLongs; + }); + it('should supports domainsEnabled options', () => { + const a: boolean | void = options.domainsEnabled; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.domainsEnabled; + }); + it('should supports validateOptions options', () => { + const a: boolean | void = options.validateOptions; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.validateOptions; + }); + it('should supports appname options', () => { + const a: string | void = options.appname; + // $FlowExpectedError[incompatible-type] + const b: string = options.appname; + }); + it('should supports auth options', () => { + const a: Auth | void = options.auth; + // $FlowExpectedError[incompatible-type] + const b: Auth = options.auth; + }); + it('should supports authMechanism options', () => { + const a: 'MDEFAULT' | 'GSSAPI' | 'PLAIN' | 'MONGODB-X509' | 'SCRAM-SHA-1' | void = options.authMechanism; + // $FlowExpectedError[incompatible-type] + const b: 'MDEFAULT' | 'GSSAPI' | 'PLAIN' | 'MONGODB-X509' | 'SCRAM-SHA-1' = options.authMechanism; + }); + it('should supports compression options', () => { + const a: 'snappy' | 'zlib' | void = options.compression; + // $FlowExpectedError[incompatible-type] + const b: 'snappy' | 'zlib' = options.compression; + }); + it('should supports fsync options', () => { + const a: boolean | void = options.fsync; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.fsync; + }); + it('should supports readPreferenceTags options', () => { + const a: Array<{ [string]: string, ... }> | void = options.readPreferenceTags; + // $FlowExpectedError[incompatible-type] + const b: Array<{ [string]: string, ... }> = options.readPreferenceTags; + }); + it('should supports numberOfRetries options', () => { + const a: number | void = options.numberOfRetries; + // $FlowExpectedError[incompatible-type] + const b: number = options.numberOfRetries; + }); + it('should supports auto_reconnect options', () => { + const a: boolean | void = options.auto_reconnect; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.auto_reconnect; + }); + it('should supports monitorCommands options', () => { + const a: boolean | void = options.monitorCommands; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.monitorCommands; + }); + it('should supports minSize options', () => { + const a: number | void = options.minSize; + // $FlowExpectedError[incompatible-type] + const b: number = options.minSize; + }); + it('should supports useNewUrlParser options', () => { + const a: boolean | void = options.useNewUrlParser; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.useNewUrlParser; + }); + it('should supports useUnifiedTopology options', () => { + const a: boolean | void = options.useUnifiedTopology; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.useUnifiedTopology; + }); + it('should supports autoEncryption options', () => { + const a: AutoEncryptionOptionsObject | void = options.autoEncryption; + // $FlowExpectedError[incompatible-type] + const b: AutoEncryptionOptionsObject = options.autoEncryption; + }); + it('should supports driverInfo options', () => { + const a: DriverInfoOptionsObject | void = options.driverInfo; + // $FlowExpectedError[incompatible-type] + const b: DriverInfoOptionsObject = options.driverInfo; + }); +}); + +describe('Cursor', () => { + it('should supports example from doc', (cursor: Cursor<{ a: number, ... }>) => { + cursor + .project({ a: 1 }) + .skip(1) + .limit(10) + .batchSize(5) + .filter({ a: 1 }) + .comment('add a comment') + .addCursorFlag('tailable', true) + .addCursorFlag('oplogReplay', true) + .addCursorFlag('noCursorTimeout', true) + .addCursorFlag('awaitData', true) + .addCursorFlag('partial', true) + .max(10) + .maxTimeMS(1000) + .min(100) + .returnKey(true) + .setReadPreference("primary") + .sort([['a', 1]]) + .hint('a_1'); + }); + it('should extends readable', (cursor: Cursor<{ ... }>) => { + if (cursor instanceof Readable) { + // cursor is Readable + + cursor.read(5); + + // $FlowExpectedError[incompatible-call] + cursor.read("5"); + } else { + // This should never happen + (cursor: empty) + } + }); + it('should supports doc', (cursor: Cursor<{| a: number |}>) => { + cursor.filter({ a: 1 }); + + // $FlowExpectedError[prop-missing] + cursor.filter({ b: 3 }); + }); +}); diff --git a/definitions/npm/mongodb_v3.6.x/flow_v0.114.x-/test_mongodb_v3.6.x_docs_quick_start.js b/definitions/npm/mongodb_v3.5.x/flow_v0.201.x-/test_mongodb_v3.5.x_docs_quick_start.js similarity index 100% rename from definitions/npm/mongodb_v3.6.x/flow_v0.114.x-/test_mongodb_v3.6.x_docs_quick_start.js rename to definitions/npm/mongodb_v3.5.x/flow_v0.201.x-/test_mongodb_v3.5.x_docs_quick_start.js diff --git a/definitions/npm/mongodb_v3.6.x/flow_v0.114.x-/mongodb_v3.6.x.js b/definitions/npm/mongodb_v3.6.x/flow_v0.114.x-v0.200.x/mongodb_v3.6.x.js similarity index 100% rename from definitions/npm/mongodb_v3.6.x/flow_v0.114.x-/mongodb_v3.6.x.js rename to definitions/npm/mongodb_v3.6.x/flow_v0.114.x-v0.200.x/mongodb_v3.6.x.js diff --git a/definitions/npm/mongodb_v3.6.x/flow_v0.114.x-/test_mongodb_v3.6.x_client.js b/definitions/npm/mongodb_v3.6.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.6.x_client.js similarity index 100% rename from definitions/npm/mongodb_v3.6.x/flow_v0.114.x-/test_mongodb_v3.6.x_client.js rename to definitions/npm/mongodb_v3.6.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.6.x_client.js diff --git a/definitions/npm/mongodb_v3.6.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.6.x_docs_quick_start.js b/definitions/npm/mongodb_v3.6.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.6.x_docs_quick_start.js new file mode 100644 index 0000000000..e58785379d --- /dev/null +++ b/definitions/npm/mongodb_v3.6.x/flow_v0.114.x-v0.200.x/test_mongodb_v3.6.x_docs_quick_start.js @@ -0,0 +1,97 @@ +// @flow + +import { describe, it } from 'flow-typed-test'; +import { Db } from 'mongodb'; + +// http://mongodb.github.io/node-mongodb-native/3.5/quick-start/quick-start/ +describe('Quick Start', () => { + it('connect', () => { + const MongoClient = require('mongodb').MongoClient; + const assert = require('assert'); + + // Connection URL + const url = 'mongodb://localhost:27017'; + + // Database Name + const dbName = 'myproject'; + + // Create a new MongoClient + const client = new MongoClient(url); + + // Use connect method to connect to the Server + client.connect(function(err) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + client.close(); + }); + }); + + it('insertDocuments', (db: typeof Db, callback: () => void) => { + const assert = require('assert'); + // Get the documents collection + const collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the collection"); + callback(); + }); + }); + + it('findDocuments', (db: typeof Db, callback: () => void) => { + const assert = require('assert'); + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({'a': 3}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs); + callback(); + }); + }); + + it('updateDocument', (db: typeof Db, callback: () => void) => { + const assert = require('assert'); + // Get the documents collection + const collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 }, { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(); + }); + }); + + it('removeDocument', (db: typeof Db, callback: () => void) => { + const assert = require('assert'); + // Get the documents collection + const collection = db.collection('documents'); + // Delete document where a is 3 + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(); + }); + }); + + it('indexCollection', (db: typeof Db, callback: () => void) => { + db.collection('documents').createIndex( + { "a": 1 }, + null, + function(err, results) { + console.log(results); + callback(); + } + ); + }); +}) \ No newline at end of file diff --git a/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/mongodb_v3.6.x.js b/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/mongodb_v3.6.x.js new file mode 100644 index 0000000000..016106e5e2 --- /dev/null +++ b/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/mongodb_v3.6.x.js @@ -0,0 +1,667 @@ +// @flow + +declare module 'mongodb' { + import type { Readable } from 'stream'; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Admin.html + declare export type Admin = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/AggregationCursor.html + declare export type AggregationCursor = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/AutoEncrypter.html + declare export type AutoEncrypter = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Binary.html + declare export var Binary: any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/BSONRegExp.html + declare export var BSONRegExp: any; // TODO + + // TODO: type all possible operations + declare export type FilterQuery = $ReadOnly<$Shape | { ... }>; + + // TODO + declare export type UpdatePipeline = $ReadOnlyArray<{ ... }>; + + declare export type BulkWriteInsertOneOperation = {| + +insertOne: {| + +document: $ReadOnly + |} + |}; + + declare export type BulkWriteUpdateOneOperation = {| + +updateOne: {| + +filter?: FilterQuery, + +update: UpdatePipeline | $Shape | {| + +$set?: $Shape, + +$setOnInsert?: $Shape, + |}, + +upsert?: boolean, + +collation?: CollationOptions, + +arrayFilters?: $ReadOnlyArray>, + +hint?: string | Hint, + |} + |}; + + declare export type BulkWriteUpdateManyOperation = {| + +updateMany: {| + +filter?: FilterQuery, + +update: UpdatePipeline | $Shape | {| + +$set?: $Shape, + +$setOnInsert?: $Shape, + |}, + +upsert?: boolean, + +collation?: CollationOptions, + +arrayFilters?: $ReadOnlyArray>, + +hint?: string | Hint, + |} + |}; + + declare export type BulkWriteReplaceOneOperation = {| + +replaceOne: {| + +filter?: FilterQuery, + +replacement: Doc, + +upsert?: boolean, + +collation?: CollationOptions, + +hint?: string | Hint, + |} + |}; + + declare export type BulkWriteDeleteOneOperation = {| + +deleteOne: {| + +filter?: FilterQuery, + +collation?: CollationOptions, + |} + |}; + + declare export type BulkWriteDeleteManyOperation = {| + +deleteMany: {| + +filter?: FilterQuery, + +collation?: CollationOptions, + |} + |}; + + declare export type BulkWriteOperation = + | BulkWriteInsertOneOperation + | BulkWriteUpdateOneOperation + | BulkWriteUpdateManyOperation + | BulkWriteReplaceOneOperation + | BulkWriteDeleteOneOperation + | BulkWriteDeleteManyOperation; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/BulkOperationBase.html + declare export type BulkOperationBase = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/BulkWriteError.html + declare type IBulkWriteError = any; + declare export var BulkWriteError: IBulkWriteError; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/BulkWriteResult.html + declare export type BulkWriteResult = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ChangeStream.html + declare export type ChangeStream = any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ClientEncryption.html + declare export type ClientEncryption = any; // TODO + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ClientSession.html + declare export type ClientSession = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Code.html + declare export var Code: any; // TODO + + declare export type BulkWriteOpResult = {| + insertedCount: number, + matchedCount: number, + modifiedCount: number, + deletedCount: number, + upsertedCount: number, + insertedIds: { [number]: IObjectID, ... }, + upsertedIds: { [number]: IObjectID, ... }, + result: { ... }, + |}; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Collection.html + declare export interface Collection { + +collectionName: string; + +dbName: string; + +hint: Hint; + +namespace: string; + +readConcern: ReadConcern; + +readPreference: ReadPreference; + +writeConcern: WriteConcern; + aggregate( + pipeline: AggregationPipeline, + options?: AggregateOptions, + ): AggregationCursor; + aggregate( + pipeline: AggregationPipeline, + options: AggregateOptions, + (err: IMongoError, cursor: AggregationCursor) => mixed, + ): void; + aggregate( + pipeline: AggregationPipeline, + (err: IMongoError, cursor: AggregationCursor) => mixed, + ): void; + bulkWrite( + operations: $ReadOnlyArray>, + options?: BulkWriteOptions, + ): Promise; + bulkWrite( + operations: BulkWriteOperation, + options: BulkWriteOptions, + (err: IBulkWriteError, result: BulkWriteOpResult) => mixed, + ): void; + bulkWrite( + operations: BulkWriteOperation, + (err: IBulkWriteError, result: BulkWriteOpResult) => mixed, + ): void; + count( + query: FilterQuery, + options?: CollectionCountOptions, + ): Promise; + count( + query: FilterQuery, + options: CollectionCountOptions, + (err: IMongoError, result: number) => mixed, + ): void; + count( + query: FilterQuery, + (err: IMongoError, result: number) => mixed, + ): void; + countDocuments( + query: FilterQuery, + options?: CollectionCountDocumentsOptions, + ): Promise; + countDocuments( + query: FilterQuery, + options: CollectionCountDocumentsOptions, + (err: IMongoError, result: number) => mixed, + ): void; + countDocuments( + query: FilterQuery, + (err: IMongoError, result: number) => mixed, + ): void; + createIndex(...any[]): any; + createIndexes(...any[]): any; + deleteMany(...any[]): any; + deleteOne(...any[]): any; + distinct(...any[]): any; + drop(...any[]): any; + dropAllIndexes(...any[]): any; + dropIndex(...any[]): any; + dropIndexes(...any[]): any; + ensureIndex(...any[]): any; + estimatedDocumentCount(...any[]): any; + find(...any[]): any; + findAndModify(...any[]): any; + findAndRemove(...any[]): any; + findOne(...any[]): any; + findOneAndDelete(...any[]): any; + findOneAndReplace(...any[]): any; + findOneAndUpdate(...any[]): any; + geoHaystackSearch(...any[]): any; + group(...any[]): any; + indexes(...any[]): any; + indexExists(...any[]): any; + indexInformation(...any[]): any; + initializeOrderedBulkOp(...any[]): any; + initializeUnorderedBulkOp(...any[]): any; + insert(...any[]): any; + insertMany(...any[]): any; + insertOne(...any[]): any; + isCapped(...any[]): any; + listIndexes(...any[]): any; + mapReduce(...any[]): any; + options(...any[]): any; + parallelCollectionScan(...any[]): any; + reIndex(...any[]): any; + remove(...any[]): any; + rename(...any[]): any; + replaceOne(...any[]): any; + save(...any[]): any; + stats(...any[]): any; + update(...any[]): any; + updateMany(...any[]): any; + updateOne(...any[]): any; + watch(...any[]): any; + } + + declare export type CollectionCountOptions = {| + skip?: number, + limit?: number, + maxTimeMS?: number, + hint?: string, + readPreference?: ReadPreferenceValue, + collation?: CollationOptions, + session?: ClientSession, + |}; + + declare export type CollectionCountDocumentsOptions = {| + skip?: number, + limit?: number, + maxTimeMS?: number, + hint?: string, + collation?: CollationOptions, + |}; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/CommandCursor.html + declare export type CommandCursor = any; // TODO (use type shouldn't be instantiated) + + declare export type CursorFlag = 'tailable' | 'oplogReplay' | 'noCursorTimeout' | 'awaitData' | 'partial'; + + declare export type CursorCloseOptions = {| + skipKillCursors?: boolean, + |}; + + declare export type CursorResultCallback = (error: ?(IMongoError), result: T) => mixed; + declare export type CursorIteratorCallback = (doc: T) => mixed; + declare export type CursorEndCallback = (error: ?(IMongoError)) => mixed; + + // TODO + declare export type CollationOptions = $ReadOnly<{ ... }>; + + declare export type CursorCountOptions = {| + skip?: number, + limit?: number, + maxTimeMS?: number, + hint?: string, + readPreference?: ReadPreferenceValue, + |}; + + // TODO: type explain https://docs.mongodb.com/manual/reference/method/cursor.explain/#behavior + declare export type ExplainResult = { ... }; + + declare export type Projection = { + ...$ObjMap (1 | -1 | boolean | string)>, + _id?: 1 | false, + ..., + }; + + // TODO + declare export type CursorOption = { ... }; + + declare export type StreamOptions = {| + transform: Input => Doc, + |}; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Cursor.html + declare export interface Cursor extends Readable { + addCursorFlag(flag: CursorFlag, value: boolean): Cursor; + addQueryModifier(name: string, value: string | number | boolean): Cursor; + batchSize(value: number): Cursor; + clone(): Cursor; + close(options: CursorCloseOptions, cb: CursorResultCallback): void; + close(options: CursorCloseOptions): Promise; + close(cb: CursorResultCallback): void; + close(): Promise; + collation(valie: CollationOptions): Cursor; + comment(value: string): Cursor; + count(applySkipLimit: boolean, options: CursorCountOptions, callback: CursorResultCallback): void; + count(applySkipLimit: boolean, options: CursorCountOptions): Promise; + count(applySkipLimit: boolean, callback: CursorResultCallback): void; + count(applySkipLimit: boolean): Promise; + count(callback: CursorResultCallback): void; + count(): Promise; + // deprecated + each(CursorResultCallback): null; + explain(CursorResultCallback): void; + explain(): Promise; + filter(filter: $Shape): Cursor; + forEach(iterator: CursorIteratorCallback, callback: CursorEndCallback): Cursor; + forEach(iterator: CursorIteratorCallback): Promise; + hasNext(callback: CursorResultCallback): void; + hasNext(): Promise; + hint(hint: string): Cursor; + isClosed(): boolean; + limit(value: number): Cursor; + map(transform: Input => Doc): Cursor; + max(value: number): Cursor; + maxAwaitTimeMS(value: number): Cursor; + // Deprecated + maxScan(maxScan: { ... }): Cursor; + maxTimeMS(value: number): Cursor; + min(value: number): Cursor; + next(callback: CursorResultCallback): void; + next(): Promise; + project(value: Projection): Cursor; + returnKey(returnKey: boolean): Cursor; + setCursorOption(field: 'numberOfRetries' | 'tailableRetryInterval', value: CursorOption): Cursor; + setReadPreference(readPreference: ReadPreferenceValue): Cursor; + // TODO: type showRecordId + showRecordId(showRecordId: { ... }): Cursor; + skip(value: number): Cursor; + // Deprecated + snapshot(snapshot: { ... }): Cursor; + sort(keyOrList: $Keys, direction: 1 | -1): Cursor; + sort(keyOrList: [$Keys, 1 | -1][]): Cursor; + sort(keyOrList: { [string]: 1 | -1, ... }): Cursor; + stream(options: StreamOptions): Cursor; + toArray(callback: CursorResultCallback): void; + toArray(): Promise; + transformStream(options: StreamOptions): Readable; + } + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Db.html + declare export var Db: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/DBRef.html + declare export var DBRef: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Decimal128.html + declare export var Decimal128: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Double.html + declare export var Double: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/FindOperators.html + declare export type FindOperators = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridFSBucket.html + declare export var GridFSBucket: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridFSBucketReadStream.html + declare export type GridFSBucketReadStream = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridFSBucketWriteStream.html + declare export type GridFSBucketWriteStream = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridStore.html + declare export var GridStore: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/GridStoreStream.html + declare export type GridStoreStream = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Int32.html + declare export var Int32: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Logger.html + declare export var Logger: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Long.html + declare export var Long: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MaxKey.html + declare export var MaxKey: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MinKey.html + declare export var MinKey: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html + declare export class MongoClient { + static connect(url: string, options: MongoClientOptions, callback: ConnectCallback): MongoClient; + static connect(url: string, callback: ConnectCallback): MongoClient; + static connect(url: string, options?: MongoClientOptions): Promise; + + constructor(url: string, options?: MongoClientOptions, callback?: ConnectCallback): MongoClient; + constructor(url: string, callback?: ConnectCallback): MongoClient; + + close(force: boolean, callback: NoResultCallback): void; + close(callback: NoResultCallback): void; + close(force?: boolean): Promise; + + connect(callback: ConnectCallback): void; + connect(): Promise; + + db(dbName?: string, options?: DbOptions): typeof Db; + + isConnected(options?: DbOptions): boolean; + + startSession(options?: SessionOptions): ClientSession; + + watch(pipeline?: AggregationPipeline, options?: ClientWatchOptions): ChangeStream; + + withSession(options?: WithSessionOptions, operation: Operation): Promise; // TODO confirm return + withSession(operation: Operation): Promise; // TODO confirm return + } + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoCryptError.html + declare export var MongoCryptError: any; // TODO; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/IMongoError.html + declare type IMongoError = any; + declare export var MongoError: IMongoError; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoNetworkError.html + declare export var MongoNetworkError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoParseError.html + declare export var MongoParseError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Mongos.html + declare export var Mongos: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoServerSelectionError.html + declare export var MongoServerSelectionError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoTimeoutError.html + declare export var MongoTimeoutError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/MongoWriteConcernError.html + declare export var MongoWriteConcernError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ObjectID.html + declare type IObjectID = any; + declare export var ObjectID: IObjectID; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/OrderedBulkOperation.html + declare export type OrderedBulkOperation = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/ReplSet.html + declare export var ReplSet: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Server.html + declare export var Server: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Symbol.html + declare export var Symbol: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/Timestamp.html + declare export type Timestamp = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/UnorderedBulkOperation.html + declare export type UnorderedBulkOperation = any; // TODO (use type shouldn't be instantiated) + + // http://mongodb.github.io/node-mongodb-native/3.5/api/WriteConcernError.html + declare export var WriteConcernError: any; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/WriteError.html + declare export type WriteError = any; // TODO (use type shouldn't be instantiated) + + declare export type ReadPreference = {| + PRIMARY: 'primary', + PRIMARY_PREFERRED: 'primaryPreferred', + SECONDARY: 'secondary', + SECONDARY_PREFERRED: 'secondaryPreferred', + NEAREST: 'nearest', + |}; + declare export type ReadPreferenceValue = 'primary' | 'primaryPreferred' | 'secondary' + | 'secondaryPreferred' | 'nearest' + + // http://mongodb.github.io/node-mongodb-native/3.5/api/global.html#ReadConcern + declare export type ReadConcernLevel = 'local' | 'available' | 'majority' | 'linearizable' | 'snapshot'; + + // http://mongodb.github.io/node-mongodb-native/3.5/api/global.html#ReadConcern + declare export type ReadConcern = {| + level: ReadConcernLevel, + |} + + declare export type DriverInfoOptionsObject = {| + name?: string, + version?: string, + platform?: string, + |}; + + declare export type KMSProviders = {| + aws: {| + accessKeyId?: string, + secretAccessKey?: string, + |}, + local: {| + key?: Buffer, + |}, + |}; + + declare export type AutoEncryptionOptionsObject = {| + keyVaultClient?: MongoClient, + keyVaultNamespace?: string, + kmsProviders?: KMSProviders, + schemaMap?: { [string]: mixed, ... }, + bypassAutoEncryption?: boolean, + options?: {| + logger: LoggerInterface, + |}, + extraOptions: {| + mongocryptdURI?: string, + mongocryptdBypassSpawn?: boolean, + mongocryptdSpawnPath?: string, + mongocryptdSpawnArgs?: string[] + |}, + |}; + + declare export type ConnectCallback = (error: IMongoError, client: MongoClient) => mixed; + declare export type NoResultCallback = (error: IMongoError, null) => mixed; + + declare export type PkFactory = { + createPk(): IObjectID, + ..., + }; + + declare export type LoggerInterface = {| + debug(string): mixed, + info(string): mixed, + warn(string): mixed, + error(string): mixed, + |}; + + declare export type Auth = {| + user: string, password: string, + |} + + declare export type MongoClientOptions = {| + poolSize?: number, + ssl?: boolean, + sslValidate?: boolean, + sslCA?: Buffer, // deprecated + sslCert?: Buffer, // deprecated + sslKey?: Buffer, // deprecated + sslPass?: string, // deprecated + sslCert?: Buffer, // deprecated + sslCRL?: Buffer, // deprecated + checkServerIdentity?: boolean | ((servername: string, cert: string) => boolean); // deprecated + tls?: boolean, + tlsInsecure?: boolean, + tlsCAFile?: string, + tlsCertificateKeyFile?: string, + tlsCertificateKeyFilePassword?: string, + tlsAllowInvalidCertificates?: boolean, + tlsAllowInvalidHostnames?: boolean, + autoReconnect?: boolean, + noDelay?: boolean, + keepAlive?: boolean, + keepAliveInitialDelay?: number, + connectTimeoutMS?: number, + socketTimeoutMS?: number, + family?: 4 | 6 | null, + reconnectTries?: number, + reconnectInterval?: number, + ha?: boolean, + haInterval?: number, + replicaSet?: string, + secondaryAcceptableLatencyMS?: number, + acceptableLatencyMS?: number, + connectWithNoPrimary?: boolean, + authSource?: string, + w?: string | number, + wtimeout?: number, + j?: boolean, + forceServerObjectId?: boolean, + serializeFunctions?: boolean, + ignoreUndefined?: boolean, + raw?: boolean, + bufferMaxEntries?: number, + readPreference?: ReadPreferenceValue, + pkFactory?: PkFactory, + promiseLibrary?: { ... }, // TODO + readConcern?: ReadConcern, + maxStalenessSeconds?: number, + loggerLevel?: 'error' | 'warn' | 'info' | 'debug', + logger?: LoggerInterface, + promoteValues?: boolean, + promoteBuffers?: boolean, + promoteLongs?: boolean, + domainsEnabled?: boolean, + validateOptions?: boolean, + appname?: string, + auth?: Auth, + authMechanism?: 'MDEFAULT' | 'GSSAPI' | 'PLAIN' | 'MONGODB-X509' | 'SCRAM-SHA-1', + compression?: 'snappy' | 'zlib', + fsync?: boolean, + readPreferenceTags?: $ReadOnlyArray<{ [string]: string, ... }>, + numberOfRetries?: number, + auto_reconnect?: boolean, + monitorCommands?: boolean, + minSize?: number, + useNewUrlParser?: boolean, + useUnifiedTopology?: boolean, + autoEncryption?: AutoEncryptionOptionsObject, + driverInfo?: DriverInfoOptionsObject, + |}; + + declare export type DbOptions = {| + noListener?: boolean, + returnNonCachedInstance?: boolean, + |}; + + declare export type SessionOptions = { ... }; // TODO + declare export type Session = AnalyserNode; // TODO + + declare export type AggregationStage = { ... }; // TODO + declare export type AggregationPipeline = $ReadOnlyArray; + + declare export type ClientWatchOptions = { ... }; // TODO + + declare export type AggregateOptions = { + +readPreference?: ReadPreferenceValue, + +batchSize?: number, + +cursor?: { batchSize?: number, ... }, + +explain?: boolean, + +allowDiskUse?: boolean, + +maxTimeMS?: number, + +maxAwaitTimeMS?: number, + +bypassDocumentValidation?: boolean, + +raw?: boolean, + +promoteLongs?: boolean, + +promoteValues?: boolean, + +promoteBuffers?: boolean, + +collation?: CollationOptions, + +comment?: string, + +hint?: string | Hint, + +session?: ClientSession, + ... + }; + + declare export type Hint = $ReadOnly<{ ... }>; + + declare export type WithSessionOptions = { ... }; // TODO + + declare export type BulkWriteOptions = { + +ordered?: boolean, + +bypassDocumentValidation?: boolean, + +arrayFilters?: $ReadOnlyArray>, + +w?: WriteConcern, + +wtimeout?: number, + +j?: boolean, + +checkKeys?: boolean, + +serializeFunctions?: boolean, + +ignoreUndefined?: boolean, + +session?: ClientSession, + ..., + } + + declare export type WriteConcern = number | 'majority'; + + declare export type Operation = (session: Session) => mixed; // TODO +} \ No newline at end of file diff --git a/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/test_mongodb_v3.6.x_client.js b/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/test_mongodb_v3.6.x_client.js new file mode 100644 index 0000000000..cd6e2936d7 --- /dev/null +++ b/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/test_mongodb_v3.6.x_client.js @@ -0,0 +1,480 @@ +// @flow + +import { describe, it } from 'flow-typed-test'; +import { + MongoClient, + type MongoClientOptions, + type ConnectCallback, + type PkFactory, + type ReadConcern, + type LoggerInterface, + type Auth, + type AutoEncryptionOptionsObject, + type DriverInfoOptionsObject, + type ReadPreferenceValue, + type Cursor, +} from 'mongodb'; +import { Readable } from 'stream'; + +describe('static connect', () => { + describe('Promises', () => { + it('url should be a string', () => { + const client: Promise = MongoClient.connect( + 'mongodb://localhost:27017' + ); + // $FlowExpectedError[incompatible-call] + MongoClient.connect(2); + // $FlowExpectedError[incompatible-call] + MongoClient.connect(); + }); + + it('should accepts options', (options: MongoClientOptions) => { + const client: Promise = MongoClient.connect( + 'mongodb://localhost:27017', + options + ); + // $FlowExpectedError[incompatible-call] + MongoClient.connect( + 'mongodb://localhost:27017', + { invalidOptionsKey: 'string' } + ); + }); + }); + describe('Callback', () => { + it('url should be a string', (cb: ConnectCallback) => { + const client: MongoClient = MongoClient.connect( + 'mongodb://localhost:27017', + cb + ); + // $FlowExpectedError[incompatible-call] + MongoClient.connect(2, cb); + // $FlowExpectedError[incompatible-call] + MongoClient.connect(cb); + // $FlowExpectedError[incompatible-call] + MongoClient.connect( + 'mongodb://localhost:27017', + (error: Error, c: string) => true + ); + }); + + it('should accepts options', (cb: ConnectCallback, options: MongoClientOptions) => { + const client: MongoClient = MongoClient.connect( + 'mongodb://localhost:27017', + options, + cb + ); + // $FlowExpectedError[incompatible-call] + MongoClient.connect( + 'mongodb://localhost:27017', + { invalidOptionsKey: 'string' }, + cb + ); + }); + }); +}); + +describe('connect', () => { + describe('Promises', () => { + it('should return a promise', (client: MongoClient) => { + const c: Promise = client.connect(); + // $FlowExpectedError[incompatible-call] + client.connect('mongodb://localhost:27017'); + }); + }); + describe('Callback', () => { + it('should accepts callback', (client: MongoClient, cb: ConnectCallback) => { + client.connect(cb); + // $FlowExpectedError[incompatible-call] + client.connect('mongodb://localhost:27017', cb); + }); + }); +}); + +describe('MongoClientOptions', (options: MongoClientOptions) => { + it('should supports poolSize options', () => { + const a: void | number = options.poolSize; + // $FlowExpectedError[incompatible-type] + const b: number = options.poolSize; + }); + it('should supports ssl options', () => { + const a: void | boolean = options.ssl; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.ssl; + }); + it('should supports sslValidate options', () => { + const a: void | boolean = options.sslValidate; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.sslValidate; + }); + it('should supports sslCA options', () => { + const a: void | Buffer = options.sslCA; + // $FlowExpectedError[incompatible-type] + const b: Buffer = options.sslCA; + }); + it('should supports sslCert options', () => { + const a: void | Buffer = options.sslCert; + // $FlowExpectedError[incompatible-type] + const b: Buffer = options.sslCert; + }); + it('should supports sslKey options', () => { + const a: void | Buffer = options.sslKey; + // $FlowExpectedError[incompatible-type] + const b: Buffer = options.sslKey; + }); + it('should supports sslPass options', () => { + const a: void | string = options.sslPass; + // $FlowExpectedError[incompatible-type] + const b: string = options.sslPass; + }); + it('should supports sslCRL options', () => { + const a: void | Buffer = options.sslCRL; + // $FlowExpectedError[incompatible-type] + const b: Buffer = options.sslCRL; + }); + it('should supports checkServerIdentity options', () => { + const a: MongoClientOptions = { checkServerIdentity: true }; + const b: MongoClientOptions = { + checkServerIdentity: (servername: string, cert: string) => false, + }; + // $FlowExpectedError[incompatible-type] + const c: MongoClientOptions = { checkServerIdentity: (a: boolean) => {} }; + }); + it('should supports tls options', () => { + const a: void | boolean = options.tls; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.tls; + }); + it('should supports tlsInsecure options', () => { + const a: void | boolean = options.tlsInsecure; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.tlsInsecure; + }); + it('should supports tlsCAFile options', () => { + const a: void | string = options.tlsCAFile; + // $FlowExpectedError[incompatible-type] + const b: string = options.tlsCAFile; + }); + it('should supports tlsCertificateKeyFile options', () => { + const a: void | string = options.tlsCertificateKeyFile; + // $FlowExpectedError[incompatible-type] + const b: string = options.tlsCertificateKeyFile; + }); + it('should supports tlsCertificateKeyFilePassword options', () => { + const a: void | string = options.tlsCertificateKeyFilePassword; + // $FlowExpectedError[incompatible-type] + const b: string = options.tlsCertificateKeyFilePassword; + }); + it('should supports tlsAllowInvalidCertificates options', () => { + const a: void | boolean = options.tlsAllowInvalidCertificates; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.tlsAllowInvalidCertificates; + }); + it('should supports tlsAllowInvalidHostnames options', () => { + const a: void | boolean = options.tlsAllowInvalidHostnames; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.tlsAllowInvalidHostnames; + }); + it('should supports autoReconnect options', () => { + const a: void | boolean = options.autoReconnect; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.autoReconnect; + }); + it('should supports noDelay options', () => { + const a: void | boolean = options.noDelay; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.noDelay; + }); + it('should supports keepAlive options', () => { + const a: void | boolean = options.keepAlive; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.keepAlive; + }); + it('should supports keepAliveInitialDelay options', () => { + const a: void | number = options.keepAliveInitialDelay; + // $FlowExpectedError[incompatible-type] + const b: number = options.keepAliveInitialDelay; + }); + it('should supports connectTimeoutMS options', () => { + const a: void | number = options.connectTimeoutMS; + // $FlowExpectedError[incompatible-type] + const b: number = options.connectTimeoutMS; + }); + it('should supports socketTimeoutMS options', () => { + const a: void | number = options.socketTimeoutMS; + // $FlowExpectedError[incompatible-type] + const b: number = options.socketTimeoutMS; + }); + it('should supports keepAliveInitialDelay options', () => { + const a: 4 | 6 | void | null = options.family; + // $FlowExpectedError[incompatible-type] + const b: number = options.family; + }); + it('should supports reconnectTries options', () => { + const a: number | void = options.reconnectTries; + // $FlowExpectedError[incompatible-type] + const b: number = options.reconnectTries; + }); + it('should supports reconnectInterval options', () => { + const a: number | void = options.reconnectInterval; + // $FlowExpectedError[incompatible-type] + const b: number = options.family; + }); + it('should supports ha options', () => { + const a: boolean | void = options.ha; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.ha; + }); + it('should supports haInterval options', () => { + const a: number | void = options.haInterval; + // $FlowExpectedError[incompatible-type] + const b: number = options.haInterval; + }); + it('should supports replicaSet options', () => { + const a: void | string = options.replicaSet; + // $FlowExpectedError[incompatible-type] + const b: string = options.replicaSet; + }); + it('should supports secondaryAcceptableLatencyMS options', () => { + const a: number | void = options.secondaryAcceptableLatencyMS; + // $FlowExpectedError[incompatible-type] + const b: number = options.secondaryAcceptableLatencyMS; + }); + it('should supports acceptableLatencyMS options', () => { + const a: number | void = options.acceptableLatencyMS; + // $FlowExpectedError[incompatible-type] + const b: number = options.acceptableLatencyMS; + }); + it('should supports connectWithNoPrimary options', () => { + const a: boolean | void = options.connectWithNoPrimary; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.connectWithNoPrimary; + }); + it('should supports authSource options', () => { + const a: string | void = options.authSource; + // $FlowExpectedError[incompatible-type] + const b: string = options.authSource; + }); + it('should supports w options', () => { + const a: number | string | void = options.w; + // $FlowExpectedError[incompatible-type] + const b: number | string = options.w; + }); + it('should supports wtimeout options', () => { + const a: number | void = options.wtimeout; + // $FlowExpectedError[incompatible-type] + const b: number = options.wtimeout; + }); + it('should supports j options', () => { + const a: boolean | void = options.j; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.j; + }); + it('should supports forceServerObjectId options', () => { + const a: boolean | void = options.forceServerObjectId; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.forceServerObjectId; + }); + it('should supports serializeFunctions options', () => { + const a: boolean | void = options.serializeFunctions; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.serializeFunctions; + }); + it('should supports ignoreUndefined options', () => { + const a: boolean | void = options.ignoreUndefined; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.ignoreUndefined; + }); + it('should supports raw options', () => { + const a: boolean | void = options.raw; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.raw; + }); + it('should supports bufferMaxEntries options', () => { + const a: number | void = options.bufferMaxEntries; + // $FlowExpectedError[incompatible-type] + const b: number = options.bufferMaxEntries; + }); + it('should supports raw options', () => { + const a: boolean | void = options.raw; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.raw; + }); + it('should supports readPreference options', () => { + const a: ReadPreferenceValue | void = options.readPreference; + // $FlowExpectedError[incompatible-type] + const b: ReadPreferenceValue = options.readPreference; + }); + it('should supports pkFactory options', (pkFactory: PkFactory) => { + const a: PkFactory | void = options.pkFactory; + // $FlowExpectedError[incompatible-type] + const b: PkFactory = options.pkFactory; + }); + it('should supports pkFactory options', (pkFactory: PkFactory) => { + const a: PkFactory | void = options.pkFactory; + // $FlowExpectedError[incompatible-type] + const b: PkFactory = options.pkFactory; + }); + it('should supports promiseLibrary options', () => { + const a: { ... } | void = options.promiseLibrary; + // $FlowExpectedError[incompatible-type] + const b: { ... } = options.promiseLibrary; + }); + it('should supports readConcern options', () => { + const a: ReadConcern | void = options.readConcern; + // $FlowExpectedError[incompatible-type] + const b: ReadConcern = options.readConcern; + }); + it('should supports maxStalenessSeconds options', () => { + const a: number | void = options.maxStalenessSeconds; + // $FlowExpectedError[incompatible-type] + const b: number = options.maxStalenessSeconds; + }); + it('should supports loggerLevel options', () => { + const a: 'error' | 'warn' | 'info' | 'debug' | void = options.loggerLevel; + // $FlowExpectedError[incompatible-type] + const b: 'error' | 'warn' | 'info' | 'debug' = options.loggerLevel; + }); + it('should supports logger options', () => { + const a: LoggerInterface | void = options.logger; + // $FlowExpectedError[incompatible-type] + const b: LoggerInterface = options.logger; + }); + it('should supports promoteValues options', () => { + const a: boolean | void = options.promoteValues; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.promoteValues; + }); + it('should supports promoteBuffers options', () => { + const a: boolean | void = options.promoteBuffers; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.promoteBuffers; + }); + it('should supports promoteLongs options', () => { + const a: boolean | void = options.promoteLongs; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.promoteLongs; + }); + it('should supports domainsEnabled options', () => { + const a: boolean | void = options.domainsEnabled; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.domainsEnabled; + }); + it('should supports validateOptions options', () => { + const a: boolean | void = options.validateOptions; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.validateOptions; + }); + it('should supports appname options', () => { + const a: string | void = options.appname; + // $FlowExpectedError[incompatible-type] + const b: string = options.appname; + }); + it('should supports auth options', () => { + const a: Auth | void = options.auth; + // $FlowExpectedError[incompatible-type] + const b: Auth = options.auth; + }); + it('should supports authMechanism options', () => { + const a: 'MDEFAULT' | 'GSSAPI' | 'PLAIN' | 'MONGODB-X509' | 'SCRAM-SHA-1' | void = options.authMechanism; + // $FlowExpectedError[incompatible-type] + const b: 'MDEFAULT' | 'GSSAPI' | 'PLAIN' | 'MONGODB-X509' | 'SCRAM-SHA-1' = options.authMechanism; + }); + it('should supports compression options', () => { + const a: 'snappy' | 'zlib' | void = options.compression; + // $FlowExpectedError[incompatible-type] + const b: 'snappy' | 'zlib' = options.compression; + }); + it('should supports fsync options', () => { + const a: boolean | void = options.fsync; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.fsync; + }); + it('should supports readPreferenceTags options', () => { + const a: $ReadOnlyArray<{ [string]: string, ... }> | void = options.readPreferenceTags; + // $FlowExpectedError[incompatible-type] + const b: $ReadOnlyArray<{ [string]: string, ... }> = options.readPreferenceTags; + }); + it('should supports numberOfRetries options', () => { + const a: number | void = options.numberOfRetries; + // $FlowExpectedError[incompatible-type] + const b: number = options.numberOfRetries; + }); + it('should supports auto_reconnect options', () => { + const a: boolean | void = options.auto_reconnect; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.auto_reconnect; + }); + it('should supports monitorCommands options', () => { + const a: boolean | void = options.monitorCommands; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.monitorCommands; + }); + it('should supports minSize options', () => { + const a: number | void = options.minSize; + // $FlowExpectedError[incompatible-type] + const b: number = options.minSize; + }); + it('should supports useNewUrlParser options', () => { + const a: boolean | void = options.useNewUrlParser; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.useNewUrlParser; + }); + it('should supports useUnifiedTopology options', () => { + const a: boolean | void = options.useUnifiedTopology; + // $FlowExpectedError[incompatible-type] + const b: boolean = options.useUnifiedTopology; + }); + it('should supports autoEncryption options', () => { + const a: AutoEncryptionOptionsObject | void = options.autoEncryption; + // $FlowExpectedError[incompatible-type] + const b: AutoEncryptionOptionsObject = options.autoEncryption; + }); + it('should supports driverInfo options', () => { + const a: DriverInfoOptionsObject | void = options.driverInfo; + // $FlowExpectedError[incompatible-type] + const b: DriverInfoOptionsObject = options.driverInfo; + }); +}); + +describe('Cursor', () => { + it('should supports example from doc', (cursor: Cursor<{ a: number, ... }>) => { + cursor + .project({ a: 1 }) + .skip(1) + .limit(10) + .batchSize(5) + .filter({ a: 1 }) + .comment('add a comment') + .addCursorFlag('tailable', true) + .addCursorFlag('oplogReplay', true) + .addCursorFlag('noCursorTimeout', true) + .addCursorFlag('awaitData', true) + .addCursorFlag('partial', true) + .max(10) + .maxTimeMS(1000) + .min(100) + .returnKey(true) + .setReadPreference("primary") + .sort([['a', 1]]) + .hint('a_1'); + }); + it('should extends readable', (cursor: Cursor<{ ... }>) => { + if (cursor instanceof Readable) { + // cursor is Readable + + cursor.read(5); + + // $FlowExpectedError[incompatible-call] + cursor.read("5"); + } else { + // This should never happen + (cursor: empty) + } + }); + it('should supports doc', (cursor: Cursor<{| a: number |}>) => { + cursor.filter({ a: 1 }); + + // $FlowExpectedError[prop-missing] + cursor.filter({ b: 3 }); + }); +}); diff --git a/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/test_mongodb_v3.6.x_docs_quick_start.js b/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/test_mongodb_v3.6.x_docs_quick_start.js new file mode 100644 index 0000000000..e58785379d --- /dev/null +++ b/definitions/npm/mongodb_v3.6.x/flow_v0.201.x-/test_mongodb_v3.6.x_docs_quick_start.js @@ -0,0 +1,97 @@ +// @flow + +import { describe, it } from 'flow-typed-test'; +import { Db } from 'mongodb'; + +// http://mongodb.github.io/node-mongodb-native/3.5/quick-start/quick-start/ +describe('Quick Start', () => { + it('connect', () => { + const MongoClient = require('mongodb').MongoClient; + const assert = require('assert'); + + // Connection URL + const url = 'mongodb://localhost:27017'; + + // Database Name + const dbName = 'myproject'; + + // Create a new MongoClient + const client = new MongoClient(url); + + // Use connect method to connect to the Server + client.connect(function(err) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + client.close(); + }); + }); + + it('insertDocuments', (db: typeof Db, callback: () => void) => { + const assert = require('assert'); + // Get the documents collection + const collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the collection"); + callback(); + }); + }); + + it('findDocuments', (db: typeof Db, callback: () => void) => { + const assert = require('assert'); + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({'a': 3}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs); + callback(); + }); + }); + + it('updateDocument', (db: typeof Db, callback: () => void) => { + const assert = require('assert'); + // Get the documents collection + const collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 }, { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(); + }); + }); + + it('removeDocument', (db: typeof Db, callback: () => void) => { + const assert = require('assert'); + // Get the documents collection + const collection = db.collection('documents'); + // Delete document where a is 3 + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(); + }); + }); + + it('indexCollection', (db: typeof Db, callback: () => void) => { + db.collection('documents').createIndex( + { "a": 1 }, + null, + function(err, results) { + console.log(results); + callback(); + } + ); + }); +}) \ No newline at end of file diff --git a/definitions/npm/nock_v10.x.x/flow_v0.104.x-/nock_v10.x.x.js b/definitions/npm/nock_v10.x.x/flow_v0.104.x-v0.200.x/nock_v10.x.x.js similarity index 100% rename from definitions/npm/nock_v10.x.x/flow_v0.104.x-/nock_v10.x.x.js rename to definitions/npm/nock_v10.x.x/flow_v0.104.x-v0.200.x/nock_v10.x.x.js diff --git a/definitions/npm/nock_v10.x.x/flow_v0.201.x-/nock_v10.x.x.js b/definitions/npm/nock_v10.x.x/flow_v0.201.x-/nock_v10.x.x.js new file mode 100644 index 0000000000..c97b7d7d48 --- /dev/null +++ b/definitions/npm/nock_v10.x.x/flow_v0.201.x-/nock_v10.x.x.js @@ -0,0 +1,146 @@ +declare type $npm$nock$Path = string | RegExp | ((url: string) => boolean); +declare type $npm$nock$Parameter = + | string + | RegExp + | Array + | Object + | ((body: Object | Array) => boolean); + +declare type $npm$nock$RecordedCall = { + scope: string, + method: string, + path: string, + body: any, + status: number, + response: any, + headers: Object, + reqheader: Object, + ... +}; + +declare class $npm$nock$Recorder { + rec(options?: { + dont_print?: boolean, + output_objects?: boolean, + enable_reqheaders_recording?: boolean, + logging?: (content: any) => any, + use_separator: boolean, + ... + }): void; + play(): $npm$nock$RecordedCall[]; +} + +declare type $npm$nock$InterceptorOptions = { + hostname: string, + path: string, + method: string, + proto: string, + ... +}; + +declare class $npm$nock$NockBack { + static (path: string, cb: (cb: Function) => any): void; + fixtures: string; + setMode(mode: string): void; +} + +declare class $npm$nock$Nock { + static ( + url: string | RegExp, + options?: { + reqheaders?: Object, + badheaders?: string[], + filteringScope?: (scope: string) => boolean, + allowUnmocked?: boolean, + ... + } + ): $npm$nock$Nock; + static restore(): void; + static cleanAll(): void; + static disableNetConnect(): void; + static enableNetConnect(path?: $npm$nock$Path): void; + static load(path: string): $npm$nock$RecordedCall[]; + // TODO: type definitions + static definitions(path: string): any; + static define(nocks: any): any; + static removeInterceptor( + interceptor: $npm$nock$Nock | $Shape<$npm$nock$InterceptorOptions> + ): void; + static emitter: events$EventEmitter; + static recorder: $npm$nock$Recorder; + static back: $npm$nock$NockBack; + get(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + post(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + put(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + head(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + delete(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + patch(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + merge(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + query(query: Object | boolean | ((query: Object) => boolean)): this; + reply( + code: number, + data?: + | (( + uri: string, + body: mixed, + cb: (error: ?Error, result: mixed) => any + ) => mixed) + | mixed, + header?: Object + ): this; + reply( + fn: ( + uri: string, + body: mixed, + cb: (error: ?Error, result: mixed) => any + ) => mixed + ): this; + replyWithFile(code: number, path: string): this; + replyWithError(error: mixed): this; + basicAuth(auth: { + user: string, + pass: string, + ... + }): this; + defaultReplyHeaders(header: { [key: string]: string | ((req: any, res: any, body: any) => any), ... }): this; + replyContentLength(): this; + replyDate(date?: Date): this; + intercept( + path: $npm$nock$Path, + verb: string, + parameter?: $npm$nock$Parameter, + options?: any + ): this; + times(number: number): this; + once(): this; + twice(): this; + thrice(): this; + delayBody(delay: number): this; + delayConnection(delay: number): this; + delay(delay: number | { + head: number, + body: number, + ... + }): this; + socketDelay(delay: number): this; + filtering$npm$nock$Path(path: RegExp, replace: string): this; + filtering$npm$nock$Path(fn: (path: string) => string): this; + filteringRequestBody(body: RegExp, replace: string): this; + filteringRequestBody(fn: (path: string) => string): this; + matchHeader(header: string, value: mixed | ((value: mixed) => boolean)): this; + optionally(optional?: boolean): this; + persist(): this; + + done(): void; + isDone(): boolean; + static isDone(): boolean; + pendingMocks(): string[]; + static pendingMocks(): string[]; + activeMocks(): string[]; + static activeMocks(): string[]; + log(logFn: Function): this; +} + +declare module 'nock' { + declare module.exports: typeof $npm$nock$Nock; +} diff --git a/definitions/npm/nock_v9.x.x/flow_v0.104.x-/nock_v9.x.x.js b/definitions/npm/nock_v9.x.x/flow_v0.104.x-v0.200.x/nock_v9.x.x.js similarity index 100% rename from definitions/npm/nock_v9.x.x/flow_v0.104.x-/nock_v9.x.x.js rename to definitions/npm/nock_v9.x.x/flow_v0.104.x-v0.200.x/nock_v9.x.x.js diff --git a/definitions/npm/nock_v9.x.x/flow_v0.201.x-/nock_v9.x.x.js b/definitions/npm/nock_v9.x.x/flow_v0.201.x-/nock_v9.x.x.js new file mode 100644 index 0000000000..c923ce082b --- /dev/null +++ b/definitions/npm/nock_v9.x.x/flow_v0.201.x-/nock_v9.x.x.js @@ -0,0 +1,148 @@ +import EventEmitter from "eventemitter"; + +declare type $npm$nock$Path = string | RegExp | ((url: string) => boolean); +declare type $npm$nock$Parameter = + | string + | RegExp + | Array + | Object + | ((body: Object | Array) => boolean); + +declare type $npm$nock$RecordedCall = { + scope: string, + method: string, + path: string, + body: any, + status: number, + response: any, + headers: Object, + reqheader: Object, + ... +}; + +declare class $npm$nock$Recorder { + rec(options?: { + dont_print?: boolean, + output_objects?: boolean, + enable_reqheaders_recording?: boolean, + logging?: (content: any) => any, + use_separator: boolean, + ... + }): void; + play(): $npm$nock$RecordedCall[]; +} + +declare type $npm$nock$InterceptorOptions = { + hostname: string, + path: string, + method: string, + proto: string, + ... +}; + +declare class $npm$nock$NockBack { + static (path: string, cb: (cb: Function) => any): void; + fixtures: string; + setMode(mode: string): void; +} + +declare class $npm$nock$Nock { + static ( + url: string | RegExp, + options?: { + reqheaders?: Object, + badheaders?: string[], + filteringScope?: (scope: string) => boolean, + allowUnmocked?: boolean, + ... + } + ): $npm$nock$Nock; + static restore(): void; + static cleanAll(): void; + static disableNetConnect(): void; + static enableNetConnect(path?: $npm$nock$Path): void; + static load(path: string): $npm$nock$RecordedCall[]; + // TODO: type definitions + static definitions(path: string): any; + static define(nocks: any): any; + static removeInterceptor( + interceptor: $npm$nock$Nock | $Shape<$npm$nock$InterceptorOptions> + ): void; + static emitter: EventEmitter; + static recorder: $npm$nock$Recorder; + static back: $npm$nock$NockBack; + get(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + post(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + put(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + head(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + delete(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + patch(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + merge(path: $npm$nock$Path, parameter?: $npm$nock$Parameter): this; + query(query: Object | boolean | ((query: Object) => boolean)): this; + reply( + code: number, + data?: + | (( + uri: string, + body: mixed, + cb: (error: ?Error, result: mixed) => any + ) => mixed) + | mixed, + header?: Object + ): this; + reply( + fn: ( + uri: string, + body: mixed, + cb: (error: ?Error, result: mixed) => any + ) => mixed + ): this; + replyWithFile(code: number, path: string): this; + replyWithError(error: mixed): this; + basicAuth(auth: { + user: string, + pass: string, + ... + }): this; + defaultReplyHeaders(header: { [key: string]: string | ((req: any, res: any, body: any) => any), ... }): this; + replyContentLength(): this; + replyDate(date?: Date): this; + intercept( + path: $npm$nock$Path, + verb: string, + parameter?: $npm$nock$Parameter, + options?: any + ): this; + times(number: number): this; + once(): this; + twice(): this; + thrice(): this; + delayBody(delay: number): this; + delayConnection(delay: number): this; + delay(delay: number | { + head: number, + body: number, + ... + }): this; + socketDelay(delay: number): this; + filteringPath(path: RegExp, replace: string): this; + filteringPath(fn: (path: string) => string): this; + filteringRequestBody(body: RegExp, replace: string): this; + filteringRequestBody(fn: (path: string) => string): this; + matchHeader(header: string, value: mixed | ((value: mixed) => boolean)): this; + optionally(): this; + persist(): this; + + done(): void; + isDone(): boolean; + static isDone(): boolean; + pendingMocks(): string[]; + static pendingMocks(): string[]; + activeMocks(): string[]; + static activeMocks(): string[]; + log(logFn: Function): this; +} + +declare module "nock" { + declare module.exports: typeof $npm$nock$Nock; +} diff --git a/definitions/npm/pell_v1.x.x/flow_v0.104.x-/pell_v1.x.x.js b/definitions/npm/pell_v1.x.x/flow_v0.104.x-v0.200.x/pell_v1.x.x.js similarity index 100% rename from definitions/npm/pell_v1.x.x/flow_v0.104.x-/pell_v1.x.x.js rename to definitions/npm/pell_v1.x.x/flow_v0.104.x-v0.200.x/pell_v1.x.x.js diff --git a/definitions/npm/pell_v1.x.x/flow_v0.201.x-/pell_v1.x.x.js b/definitions/npm/pell_v1.x.x/flow_v0.201.x-/pell_v1.x.x.js new file mode 100644 index 0000000000..e6e60f0309 --- /dev/null +++ b/definitions/npm/pell_v1.x.x/flow_v0.201.x-/pell_v1.x.x.js @@ -0,0 +1,99 @@ +declare module 'pell' { + declare type DefaultAction = + | 'bold' + | 'italic' + | 'underline' + | 'strikethrough' + | 'heading1' + | 'heading2' + | 'paragraph' + | 'quote' + | 'olist' + | 'ulist' + | 'code' + | 'line' + | 'link' + | 'image'; + + declare type CustomAction = {| + /** + * Only required if overwriting + */ + name?: DefaultAction, + /** + * Optional if overwriting, required if custom action + */ + icon?: string, + title?: string, + /** + * Only required if custom action. + * Returns a Boolean that is false if the command is unsupported or disabled. + */ + result?: () => boolean, + state?: () => boolean, + |}; + + declare type Action = DefaultAction | CustomAction; + + declare type ClassNames = $Shape<{| + actionbar: string, + button: string, + content: string, + selected: string, + |}>; + + declare type Options = {| + /** + * , required + */ + element: HTMLElement, + /** + * Use the output html, triggered by element's `oninput` event + */ + onChange: (html: string) => void, + /** + * default = 'div' + * Instructs the editor which element to inject via the return key + */ + defaultParagraphSeparator?: string, + /** + * default = false + * Outputs instead of + */ + styleWithCSS?: boolean, + /** + * Specify the actions you specifically want (in order) + */ + actions?: Array, + /** + * Choose your custom class names + */ + classes?: ClassNames, + |}; + + declare type Element = HTMLElement & { content: HTMLElement, ... }; + + /** + * Execute a document command, see reference: + * https://developer.mozilla.org/en/docs/Web/API/Document/execCommand + * this is just `document.execCommand(command, false, value)` + */ + declare type Exec = (command: string, value?: string) => void; + + declare type Init = (Options) => Element; + + declare export var exec: Exec; + declare export var init: Init; + declare export default {| + exec: Exec, + init: Init, + |}; +} + +declare module 'pell/dist/pell' { + declare module.exports: $Exports<'pell'>; +} + +declare module 'pell/dist/pell.js' { + declare module.exports: $Exports<'pell'>; +} diff --git a/definitions/npm/pg_v6.x.x/flow_v0.104.x-/pg_v6.x.x.js b/definitions/npm/pg_v6.x.x/flow_v0.104.x-v0.200.x/pg_v6.x.x.js similarity index 100% rename from definitions/npm/pg_v6.x.x/flow_v0.104.x-/pg_v6.x.x.js rename to definitions/npm/pg_v6.x.x/flow_v0.104.x-v0.200.x/pg_v6.x.x.js diff --git a/definitions/npm/pg_v6.x.x/flow_v0.201.x-/pg_v6.x.x.js b/definitions/npm/pg_v6.x.x/flow_v0.201.x-/pg_v6.x.x.js new file mode 100644 index 0000000000..bc006a4592 --- /dev/null +++ b/definitions/npm/pg_v6.x.x/flow_v0.201.x-/pg_v6.x.x.js @@ -0,0 +1,299 @@ +declare module 'pg' { + // Note: Currently There are some issues in Function overloading. + // https://github.com/facebook/flow/issues/2423 + // So i temporarily remove the + // `((event: string, listener: Function) => EventEmitter );` + // from all overloading for EventEmitter.on(). + + // `any` types exised in this file, cause of currently `mixed` did not work well + // in Function Overloading. + + // `Function` types exised in this file, cause of they come from another + // untyped npm lib. + + /* Cause of > + /* + * PgPoolConfig's properties are passed unchanged to both + * the node-postgres Client constructor and the node-pool constructor + * allowing you to fully configure the behavior of both + * node-pool (https://github.com/coopernurse/node-pool) + */ + declare type PgPoolConfig = { + // node-pool ---------------- + name: string, + create: Function, + destroy: Function, + max: number, + min: number, + refreshIdle: boolean, + idleTimeoutMillis: number, + reapIntervalMillis: number, + returnToHead: boolean, + priorityRange: number, + validate: Function, + validateAsync: Function, + log: Function, + // node-postgres Client ------ + //database user's name + user: string, + //name of database to connect + database: string, + //database user's password + password: string, + //database port + port: number, + // database host. defaults to localhost + host?: string, + // whether to try SSL/TLS to connect to server. default value: false + ssl?: boolean, + // name displayed in the pg_stat_activity view and included in CSV log entries + // default value: process.env.PGAPPNAME + application_name?: string, + // fallback value for the application_name configuration parameter + // default value: false + fallback_application_name?: string, + // pg-pool + Client: mixed, + Promise: mixed, + onCreate: Function, + ... + }; + + /* + * Not extends from Client, cause some of Client's functions(ex: connect and end) + * should not be used by PoolClient (which returned from Pool.connect). + */ + declare type PoolClient = { + release(error?: mixed): void, + query: + ( (query: QueryConfig|string, callback?: QueryCallback) => Query ) & + ( (text: string, values: Array, callback?: QueryCallback) => Query ), + on: + ((event: 'drain', listener: () => void) => events$EventEmitter )& + ((event: 'error', listener: (err: PG_ERROR) => void) => events$EventEmitter )& + ((event: 'notification', listener: (message: any) => void) => events$EventEmitter )& + ((event: 'notice', listener: (message: any) => void) => events$EventEmitter )& + ((event: 'end', listener: () => void) => events$EventEmitter ), + ... + } + + declare type PoolConnectCallback = (error: PG_ERROR|null, + client: PoolClient|null, done: DoneCallback) => void; + declare type DoneCallback = (error?: mixed) => void; + // https://github.com/facebook/flow/blob/master/lib/node.js#L581 + // on() returns a events$EventEmitter + declare class Pool extends events$EventEmitter { + constructor(options: $Shape, Client?: Class): void; + connect(cb?: PoolConnectCallback): Promise; + take(cb?: PoolConnectCallback): Promise; + end(cb?: DoneCallback): Promise; + + // Note: not like the pg's Client, the Pool.query return a Promise, + // not a Thenable Query which Client returned. + // And there is a flow(<0.34) issue here, when Array, + // the overloading will not work + query: + ( (query: QueryConfig|string, callback?: QueryCallback) => Promise ) & + ( (text: string, values: Array, callback?: QueryCallback) => Promise); + + /* flow issue: https://github.com/facebook/flow/issues/2423 + * When this fixed, this overloading can be used. + */ + /* + on: + ((event: 'connect', listener: (client: PoolClient) => void) => events$EventEmitter )& + ((event: 'acquire', listener: (client: PoolClient) => void) => events$EventEmitter )& + ((event: "error", listener: (err: PG_ERROR) => void) => events$EventEmitter )& + ((event: string, listener: Function) => events$EventEmitter); + */ + } + + // <<------------- copy from 'pg-pool' ------------------------------ + + + // error + declare type PG_ERROR = { + name: string, + length: number, + severity: string, + code: string, + detail: string|void, + hint: string|void, + position: string|void, + internalPosition: string|void, + internalQuery: string|void, + where: string|void, + schema: string|void, + table: string|void, + column: string|void, + dataType: string|void, + constraint: string|void, + file: string|void, + line: string|void, + routine: string|void, + ... + }; + + declare type ClientConfig = { + //database user's name + user?: string, + //name of database to connect + database?: string, + //database user's password + password?: string, + //database port + port?: number, + // database host. defaults to localhost + host?: string, + // whether to try SSL/TLS to connect to server. default value: false + ssl?: boolean, + // name displayed in the pg_stat_activity view and included in CSV log entries + // default value: process.env.PGAPPNAME + application_name?: string, + // fallback value for the application_name configuration parameter + // default value: false + fallback_application_name?: string, + ... + } + + declare type Row = { [key: string]: mixed, ... }; + declare type ResultSet = { + command: string, + rowCount: number, + oid: number, + rows: Array, + ... + }; + declare type ResultBuilder = { + command: string, + rowCount: number, + oid: number, + rows: Array, + addRow: (row: Row) => void, + ... + }; + declare type QueryConfig = { + name?: string, + text: string, + values?: any[], + ... + }; + + declare type QueryCallback = (err: PG_ERROR|null, result: ResultSet|void) => void; + declare type ClientConnectCallback = (err: PG_ERROR|null, client: Client|void) => void; + + /* + * lib/query.js + * Query extends from EventEmitter in source code. + * but in Flow there is no multiple extends. + * And in Flow await is a `declare function $await(p: Promise | T): T;` + * seems can not resolve a Thenable's value type directly + * so `Query extends Promise` to make thing temporarily work. + * like this: + * const q = client.query('select * from some'); + * q.on('row',cb); // Event + * const result = await q; // or await + * + * ToDo: should find a better way. + */ + declare class Query extends Promise { + then( + onFulfill?: ?((value: ResultSet) => Promise | U), + onReject?: ?((error: PG_ERROR) => Promise | U) + ): Promise; + // Because then and catch return a Promise, + // .then.catch will lose catch's type information PG_ERROR. + catch( + onReject?: ?((error: PG_ERROR) => Promise | U) + ): Promise; + + on : + ((event: 'row', listener: (row: Row, result: ResultBuilder) => void) => events$EventEmitter )& + ((event: 'end', listener: (result: ResultBuilder) => void) => events$EventEmitter )& + ((event: 'error', listener: (err: PG_ERROR) => void) => events$EventEmitter ); + } + + /* + * lib/client.js + * Note: not extends from EventEmitter, for This Type returned by on(). + * Flow's EventEmitter force return a EventEmitter in on(). + * ToDo: Not sure in on() if return events$EventEmitter or this will be more suitable + * return this will restrict event to given literial when chain on().on().on(). + * return a events$EventEmitter will fallback to raw EventEmitter, when chains + */ + declare class Client { + constructor(config?: string | ClientConfig): void; + connect(callback?: ClientConnectCallback):void; + end(): void; + + escapeLiteral(str: string): string; + escapeIdentifier(str: string): string; + + query: + ( (query: QueryConfig|string, callback?: QueryCallback) => Query ) & + ( (text: string, values: Array, callback?: QueryCallback) => Query ); + + on: + ((event: 'drain', listener: () => void) => this )& + ((event: 'error', listener: (err: PG_ERROR) => void) => this )& + ((event: 'notification', listener: (message: any) => void) => this )& + ((event: 'notice', listener: (message: any) => void) => this )& + ((event: 'end', listener: () => void) => this ); + } + + /* + * require('pg-types') + */ + declare type TypeParserText = (value: string) => any; + declare type TypeParserBinary = (value: Buffer) => any; + declare type Types = { + getTypeParser: + ((oid: number, format?: 'text') => TypeParserText )& + ((oid: number, format: 'binary') => TypeParserBinary ), + setTypeParser: + ((oid: number, format?: 'text', parseFn: TypeParserText) => void )& + ((oid: number, format: 'binary', parseFn: TypeParserBinary) => void)& + ((oid: number, parseFn: TypeParserText) => void), + ... + } + + /* + * lib/index.js ( class PG) + */ + declare class PG extends events$EventEmitter { + types: Types; + Client: Class; + Pool: Class; + Connection: mixed; //Connection is used internally by the Client. + constructor(client: Client): void; + native: { + // native binding, have the same capability like PG + types: Types, + Client: Class, + Pool: Class, + Connection: mixed, + ... + }; + // The end(),connect(),cancel() in PG is abandoned ? + } + + // These class are not exposed by pg. + declare type PoolType = Pool; + declare type PGType = PG; + declare type QueryType = Query; + // module export, keep same structure with index.js + declare module.exports: PG; +} diff --git a/definitions/npm/pg_v7.x.x/flow_v0.104.x-/pg_v7.x.x.js b/definitions/npm/pg_v7.x.x/flow_v0.104.x-v0.200.x/pg_v7.x.x.js similarity index 100% rename from definitions/npm/pg_v7.x.x/flow_v0.104.x-/pg_v7.x.x.js rename to definitions/npm/pg_v7.x.x/flow_v0.104.x-v0.200.x/pg_v7.x.x.js diff --git a/definitions/npm/pg_v7.x.x/flow_v0.201.x-/pg_v7.x.x.js b/definitions/npm/pg_v7.x.x/flow_v0.201.x-/pg_v7.x.x.js new file mode 100644 index 0000000000..acc3d6a38c --- /dev/null +++ b/definitions/npm/pg_v7.x.x/flow_v0.201.x-/pg_v7.x.x.js @@ -0,0 +1,308 @@ +declare module 'pg' { + // Note: Currently There are some issues in Function overloading. + // https://github.com/facebook/flow/issues/2423 + // So i temporarily remove the + // `((event: string, listener: Function) => EventEmitter );` + // from all overloading for EventEmitter.on(). + + // `any` types exised in this file, cause of currently `mixed` did not work well + // in Function Overloading. + + // `Function` types exised in this file, cause of they come from another + // untyped npm lib. + + /* Cause of > + /* + * PgPoolConfig's properties are passed unchanged to both + * the node-postgres Client constructor and the node-pool constructor + * allowing you to fully configure the behavior of both + * node-pool (https://github.com/coopernurse/node-pool) + */ + declare type PgPoolConfig = { + // node-pool ---------------- + name: string, + create: Function, + destroy: Function, + max: number, + min: number, + refreshIdle: boolean, + idleTimeoutMillis: number, + connectionTimeoutMillis: number, + reapIntervalMillis: number, + returnToHead: boolean, + priorityRange: number, + validate: Function, + validateAsync: Function, + log: Function, + // node-postgres Client ------ + //database connection string to define some other config parameters + connectionString: string, + //database user's name + user: string, + //name of database to connect + database: string, + //database user's password + password: string, + //database port + port: number, + // database host. defaults to localhost + host?: string, + // whether to try SSL/TLS to connect to server. default value: false + ssl?: boolean, + // name displayed in the pg_stat_activity view and included in CSV log entries + // default value: process.env.PGAPPNAME + application_name?: string, + // fallback value for the application_name configuration parameter + // default value: false + fallback_application_name?: string, + // max milliseconds any query using this connection will execute for before timing out in error. false=unlimited + // default value: false + statement_timeout?: boolean | number, + // pg-pool + Client: mixed, + Promise: mixed, + onCreate: Function, + ... + }; + + /* + * Not extends from Client, cause some of Client's functions(ex: connect and end) + * should not be used by PoolClient (which returned from Pool.connect). + */ + declare type PoolClient = { + release(error?: mixed): void, + query: + ( (query: T, callback?: QueryCallback) => T ) & + ( (query: QueryConfig|string, callback?: QueryCallback) => Query ) & + ( (text: string, values: Array, callback?: QueryCallback) => Query ), + on: + ((event: 'drain', listener: () => void) => events$EventEmitter )& + ((event: 'error', listener: (err: PG_ERROR) => void) => events$EventEmitter )& + ((event: 'notification', listener: (message: any) => void) => events$EventEmitter )& + ((event: 'notice', listener: (message: any) => void) => events$EventEmitter )& + ((event: 'end', listener: () => void) => events$EventEmitter ), + ... + } + + declare type PoolConnectCallback = (error: PG_ERROR|null, + client: PoolClient|null, done: DoneCallback) => void; + declare type DoneCallback = (error?: mixed) => void; + // https://github.com/facebook/flow/blob/master/lib/node.js#L581 + // on() returns a events$EventEmitter + declare class Pool extends events$EventEmitter { + constructor(options: $Shape, Client?: Class): void; + connect(cb?: PoolConnectCallback): Promise; + take(cb?: PoolConnectCallback): Promise; + end(cb?: DoneCallback): Promise; + + // Note: not like the pg's Client, the Pool.query return a Promise, + // not a Thenable Query which Client returned. + // And there is a flow(<0.34) issue here, when Array, + // the overloading will not work + query: + ( (query: QueryConfig|string, callback?: QueryCallback) => Promise ) & + ( (text: string, values: Array, callback?: QueryCallback) => Promise); + + /* flow issue: https://github.com/facebook/flow/issues/2423 + * When this fixed, this overloading can be used. + */ + /* + on: + ((event: 'connect', listener: (client: PoolClient) => void) => events$EventEmitter )& + ((event: 'acquire', listener: (client: PoolClient) => void) => events$EventEmitter )& + ((event: "error", listener: (err: PG_ERROR) => void) => events$EventEmitter )& + ((event: string, listener: Function) => events$EventEmitter); + */ + } + + // <<------------- copy from 'pg-pool' ------------------------------ + + + // error + declare type PG_ERROR = { + name: string, + length: number, + severity: string, + code: string, + detail: string|void, + hint: string|void, + position: string|void, + internalPosition: string|void, + internalQuery: string|void, + where: string|void, + schema: string|void, + table: string|void, + column: string|void, + dataType: string|void, + constraint: string|void, + file: string|void, + line: string|void, + routine: string|void, + ... + }; + + declare type ClientConfig = { + //database user's name + user?: string, + //name of database to connect + database?: string, + //database user's password + password?: string, + //database port + port?: number, + // database host. defaults to localhost + host?: string, + // whether to try SSL/TLS to connect to server. default value: false + ssl?: boolean, + // name displayed in the pg_stat_activity view and included in CSV log entries + // default value: process.env.PGAPPNAME + application_name?: string, + // fallback value for the application_name configuration parameter + // default value: false + fallback_application_name?: string, + ... + } + + declare type Row = { [key: string]: mixed, ... }; + declare type ResultSet = { + command: string, + rowCount: number, + oid: number, + rows: Array, + ... + }; + declare type ResultBuilder = { + command: string, + rowCount: number, + oid: number, + rows: Array, + addRow: (row: Row) => void, + ... + }; + declare type QueryConfig = { + name?: string, + text: string, + values?: any[], + ... + }; + declare type QuerySubmittableConfig = QueryConfig & { submit: (connection: mixed) => void, ... }; + + declare type QueryCallback = (err: PG_ERROR|null, result: ResultSet|void) => void; + declare type ClientConnectCallback = (err: PG_ERROR|null, client: Client|void) => void; + + /* + * lib/query.js + * Query extends from EventEmitter in source code. + * but in Flow there is no multiple extends. + * And in Flow await is a `declare function $await(p: Promise | T): T;` + * seems can not resolve a Thenable's value type directly + * so `Query extends Promise` to make thing temporarily work. + * like this: + * const q = client.query('select * from some'); + * q.on('row',cb); // Event + * const result = await q; // or await + * + * ToDo: should find a better way. + */ + declare class Query extends Promise { + then( + onFulfill?: ?((value: ResultSet) => Promise | U), + onReject?: ?((error: PG_ERROR) => Promise | U) + ): Promise; + // Because then and catch return a Promise, + // .then.catch will lose catch's type information PG_ERROR. + catch( + onReject?: ?((error: PG_ERROR) => Promise | U) + ): Promise; + + on : + ((event: 'row', listener: (row: Row, result: ResultBuilder) => void) => events$EventEmitter )& + ((event: 'end', listener: (result: ResultBuilder) => void) => events$EventEmitter )& + ((event: 'error', listener: (err: PG_ERROR) => void) => events$EventEmitter ); + } + + /* + * lib/client.js + * Note: not extends from EventEmitter, for This Type returned by on(). + * Flow's EventEmitter force return a EventEmitter in on(). + * ToDo: Not sure in on() if return events$EventEmitter or this will be more suitable + * return this will restrict event to given literial when chain on().on().on(). + * return a events$EventEmitter will fallback to raw EventEmitter, when chains + */ + declare class Client { + constructor(config?: string | ClientConfig): void; + connect(callback?: ClientConnectCallback):void; + end(): void; + + escapeLiteral(str: string): string; + escapeIdentifier(str: string): string; + + query: + ( (query: T, callback?: QueryCallback) => T ) & + ( (query: QueryConfig|string, callback?: QueryCallback) => Query ) & + ( (text: string, values: Array, callback?: QueryCallback) => Query ); + + on: + ((event: 'drain', listener: () => void) => this )& + ((event: 'error', listener: (err: PG_ERROR) => void) => this )& + ((event: 'notification', listener: (message: any) => void) => this )& + ((event: 'notice', listener: (message: any) => void) => this )& + ((event: 'end', listener: () => void) => this ); + } + + /* + * require('pg-types') + */ + declare type TypeParserText = (value: string) => any; + declare type TypeParserBinary = (value: Buffer) => any; + declare type Types = { + getTypeParser: + ((oid: number, format?: 'text') => TypeParserText )& + ((oid: number, format: 'binary') => TypeParserBinary ), + setTypeParser: + ((oid: number, format?: 'text', parseFn: TypeParserText) => void )& + ((oid: number, format: 'binary', parseFn: TypeParserBinary) => void)& + ((oid: number, parseFn: TypeParserText) => void), + ... + } + + /* + * lib/index.js ( class PG) + */ + declare class PG extends events$EventEmitter { + types: Types; + Client: Class; + Pool: Class; + Connection: mixed; //Connection is used internally by the Client. + constructor(client: Client): void; + native: { + // native binding, have the same capability like PG + types: Types, + Client: Class, + Pool: Class, + Connection: mixed, + ... + }; + // The end(),connect(),cancel() in PG is abandoned ? + } + + // These class are not exposed by pg. + declare type PoolType = Pool; + declare type PGType = PG; + declare type QueryType = Query; + // module export, keep same structure with index.js + declare module.exports: PG; +} diff --git a/definitions/npm/pg_v8.x.x/flow_v0.83.x-/pg_v8.x.x.js b/definitions/npm/pg_v8.x.x/flow_v0.201.x-/pg_v8.x.x.js similarity index 100% rename from definitions/npm/pg_v8.x.x/flow_v0.83.x-/pg_v8.x.x.js rename to definitions/npm/pg_v8.x.x/flow_v0.201.x-/pg_v8.x.x.js diff --git a/definitions/npm/pg_v8.x.x/flow_v0.83.x-/test_pg_v8.x.x.js b/definitions/npm/pg_v8.x.x/flow_v0.201.x-/test_pg_v8.x.x.js similarity index 100% rename from definitions/npm/pg_v8.x.x/flow_v0.83.x-/test_pg_v8.x.x.js rename to definitions/npm/pg_v8.x.x/flow_v0.201.x-/test_pg_v8.x.x.js diff --git a/definitions/npm/pg_v8.x.x/flow_v0.83.x-v0.200.x/pg_v8.x.x.js b/definitions/npm/pg_v8.x.x/flow_v0.83.x-v0.200.x/pg_v8.x.x.js new file mode 100644 index 0000000000..945f0c5fa4 --- /dev/null +++ b/definitions/npm/pg_v8.x.x/flow_v0.83.x-v0.200.x/pg_v8.x.x.js @@ -0,0 +1,308 @@ +declare module 'pg' { + // Note: Currently There are some issues in Function overloading. + // https://github.com/facebook/flow/issues/2423 + // So i temporarily remove the + // `((event: string, listener: Function) => EventEmitter );` + // from all overloading for EventEmitter.on(). + + // `any` types exised in this file, cause of currently `mixed` did not work well + // in Function Overloading. + + // `Function` types exised in this file, cause of they come from another + // untyped npm lib. + + /* Cause of > + /* + * PgPoolConfig's properties are passed unchanged to both + * the node-postgres Client constructor and the node-pool constructor + * allowing you to fully configure the behavior of both + * node-pool (https://github.com/coopernurse/node-pool) + */ + declare type PgPoolConfig = { + // node-pool ---------------- + name: string, + create: Function, + destroy: Function, + max: number, + min: number, + refreshIdle: boolean, + idleTimeoutMillis: number, + connectionTimeoutMillis: number, + reapIntervalMillis: number, + returnToHead: boolean, + priorityRange: number, + validate: Function, + validateAsync: Function, + log: Function, + // node-postgres Client ------ + //database connection string to define some other config parameters + connectionString: string, + //database user's name + user: string, + //name of database to connect + database: string, + //database user's password + password: string, + //database port + port: number, + // database host. defaults to localhost + host?: string, + // whether to try SSL/TLS to connect to server. default value: false + ssl?: boolean | { rejectUnauthorized: boolean, ... }, + // name displayed in the pg_stat_activity view and included in CSV log entries + // default value: process.env.PGAPPNAME + application_name?: string, + // fallback value for the application_name configuration parameter + // default value: false + fallback_application_name?: string, + // max milliseconds any query using this connection will execute for before timing out in error. false=unlimited + // default value: false + statement_timeout?: boolean | number, + // pg-pool + Client: mixed, + Promise: mixed, + onCreate: Function, + ... + }; + + /* + * Not extends from Client, cause some of Client's functions(ex: connect and end) + * should not be used by PoolClient (which returned from Pool.connect). + */ + declare type PoolClient = { + release(error?: mixed): void, + query: + ( (query: T, callback?: QueryCallback) => T ) & + ( (query: QueryConfig|string, callback?: QueryCallback) => Query ) & + ( (text: string, values: Array, callback?: QueryCallback) => Query ), + on: + ((event: 'drain', listener: () => void) => events$EventEmitter )& + ((event: 'error', listener: (err: PG_ERROR) => void) => events$EventEmitter )& + ((event: 'notification', listener: (message: any) => void) => events$EventEmitter )& + ((event: 'notice', listener: (message: any) => void) => events$EventEmitter )& + ((event: 'end', listener: () => void) => events$EventEmitter ), + ... + } + + declare type PoolConnectCallback = (error: PG_ERROR|null, + client: PoolClient|null, done: DoneCallback) => void; + declare type DoneCallback = (error?: mixed) => void; + // https://github.com/facebook/flow/blob/master/lib/node.js#L581 + // on() returns a events$EventEmitter + declare class Pool extends events$EventEmitter { + constructor(options: $Shape, Client?: Class): void; + connect(cb?: PoolConnectCallback): Promise; + take(cb?: PoolConnectCallback): Promise; + end(cb?: DoneCallback): Promise; + + // Note: not like the pg's Client, the Pool.query return a Promise, + // not a Thenable Query which Client returned. + // And there is a flow(<0.34) issue here, when Array, + // the overloading will not work + query: + ( (query: QueryConfig|string, callback?: QueryCallback) => Promise ) & + ( (text: string, values: Array, callback?: QueryCallback) => Promise); + + /* flow issue: https://github.com/facebook/flow/issues/2423 + * When this fixed, this overloading can be used. + */ + /* + on: + ((event: 'connect', listener: (client: PoolClient) => void) => events$EventEmitter )& + ((event: 'acquire', listener: (client: PoolClient) => void) => events$EventEmitter )& + ((event: "error", listener: (err: PG_ERROR) => void) => events$EventEmitter )& + ((event: string, listener: Function) => events$EventEmitter); + */ + } + + // <<------------- copy from 'pg-pool' ------------------------------ + + + // error + declare type PG_ERROR = { + name: string, + length: number, + severity: string, + code: string, + detail: string|void, + hint: string|void, + position: string|void, + internalPosition: string|void, + internalQuery: string|void, + where: string|void, + schema: string|void, + table: string|void, + column: string|void, + dataType: string|void, + constraint: string|void, + file: string|void, + line: string|void, + routine: string|void, + ... + }; + + declare type ClientConfig = { + //database user's name + user?: string, + //name of database to connect + database?: string, + //database user's password + password?: string, + //database port + port?: number, + // database host. defaults to localhost + host?: string, + // whether to try SSL/TLS to connect to server. default value: false + ssl?: boolean | { rejectUnauthorized: boolean, ... }, + // name displayed in the pg_stat_activity view and included in CSV log entries + // default value: process.env.PGAPPNAME + application_name?: string, + // fallback value for the application_name configuration parameter + // default value: false + fallback_application_name?: string, + ... + } + + declare type Row = { [key: string]: mixed, ... }; + declare type ResultSet = { + command: string, + rowCount: number, + oid: number, + rows: Array, + ... + }; + declare type ResultBuilder = { + command: string, + rowCount: number, + oid: number, + rows: Array, + addRow: (row: Row) => void, + ... + }; + declare type QueryConfig = { + name?: string, + text: string, + values?: any[], + ... + }; + declare type QuerySubmittableConfig = QueryConfig & { submit: (connection: mixed) => void, ... }; + + declare type QueryCallback = (err: PG_ERROR|null, result: ResultSet|void) => void; + declare type ClientConnectCallback = (err: PG_ERROR|null, client: Client|void) => void; + + /* + * lib/query.js + * Query extends from EventEmitter in source code. + * but in Flow there is no multiple extends. + * And in Flow await is a `declare function $await(p: Promise | T): T;` + * seems can not resolve a Thenable's value type directly + * so `Query extends Promise` to make thing temporarily work. + * like this: + * const q = client.query('select * from some'); + * q.on('row',cb); // Event + * const result = await q; // or await + * + * ToDo: should find a better way. + */ + declare class Query extends Promise { + then( + onFulfill?: ?((value: ResultSet) => Promise | U), + onReject?: ?((error: PG_ERROR) => Promise | U) + ): Promise; + // Because then and catch return a Promise, + // .then.catch will lose catch's type information PG_ERROR. + catch( + onReject?: ?((error: PG_ERROR) => Promise | U) + ): Promise; + + on : + ((event: 'row', listener: (row: Row, result: ResultBuilder) => void) => events$EventEmitter )& + ((event: 'end', listener: (result: ResultBuilder) => void) => events$EventEmitter )& + ((event: 'error', listener: (err: PG_ERROR) => void) => events$EventEmitter ); + } + + /* + * lib/client.js + * Note: not extends from EventEmitter, for This Type returned by on(). + * Flow's EventEmitter force return a EventEmitter in on(). + * ToDo: Not sure in on() if return events$EventEmitter or this will be more suitable + * return this will restrict event to given literial when chain on().on().on(). + * return a events$EventEmitter will fallback to raw EventEmitter, when chains + */ + declare class Client { + constructor(config?: string | ClientConfig): void; + connect(callback?: ClientConnectCallback):void; + end(): void; + + escapeLiteral(str: string): string; + escapeIdentifier(str: string): string; + + query: + ( (query: T, callback?: QueryCallback) => T ) & + ( (query: QueryConfig|string, callback?: QueryCallback) => Query ) & + ( (text: string, values: Array, callback?: QueryCallback) => Query ); + + on: + ((event: 'drain', listener: () => void) => this )& + ((event: 'error', listener: (err: PG_ERROR) => void) => this )& + ((event: 'notification', listener: (message: any) => void) => this )& + ((event: 'notice', listener: (message: any) => void) => this )& + ((event: 'end', listener: () => void) => this ); + } + + /* + * require('pg-types') + */ + declare type TypeParserText = (value: string) => any; + declare type TypeParserBinary = (value: Buffer) => any; + declare type Types = { + getTypeParser: + ((oid: number, format?: 'text') => TypeParserText )& + ((oid: number, format: 'binary') => TypeParserBinary ), + setTypeParser: + ((oid: number, format?: 'text', parseFn: TypeParserText) => void )& + ((oid: number, format: 'binary', parseFn: TypeParserBinary) => void)& + ((oid: number, parseFn: TypeParserText) => void), + ... + } + + /* + * lib/index.js ( class PG) + */ + declare class PG extends events$EventEmitter { + types: Types; + Client: Class; + Pool: Class; + Connection: mixed; //Connection is used internally by the Client. + constructor(client: Client): void; + native: { + // native binding, have the same capability like PG + types: Types, + Client: Class, + Pool: Class, + Connection: mixed, + ... + }; + // The end(),connect(),cancel() in PG is abandoned ? + } + + // These class are not exposed by pg. + declare type PoolType = Pool; + declare type PGType = PG; + declare type QueryType = Query; + // module export, keep same structure with index.js + declare module.exports: PG; +} diff --git a/definitions/npm/pg_v8.x.x/flow_v0.83.x-v0.200.x/test_pg_v8.x.x.js b/definitions/npm/pg_v8.x.x/flow_v0.83.x-v0.200.x/test_pg_v8.x.x.js new file mode 100644 index 0000000000..1e314e9215 --- /dev/null +++ b/definitions/npm/pg_v8.x.x/flow_v0.83.x-v0.200.x/test_pg_v8.x.x.js @@ -0,0 +1,226 @@ +// @flow +import pg from 'pg'; +import type { + ResultSet, + ResultBuilder, + QueryType, + QuerySubmittableConfig, + PG_ERROR, + Client, + Row, + DoneCallback, + PoolClient, + Pool, + PGType +} from 'pg'; + +pg.types.setTypeParser(1184, v => v); +pg.types.setTypeParser(1184, 'text', (v: string) => v); +// $FlowExpectedError[incompatible-call] +pg.types.setTypeParser(1184, 'binary', (v: string) => v) +pg.types.setTypeParser(1184, 'binary', (v: Buffer) => v) +// $FlowExpectedError[incompatible-call] +pg.types.setTypeParser(1184, (v: Buffer) => v) + +// There are two common ways to use node-postgres. +function test_pg() { + // 1. interact with your server via a pool of clients + function test_pool(pool: Pool) { + // 1.1 you can run queries directly against the pool + const rq: Promise = pool.query('select * from table;'); + // $FlowExpectedError[incompatible-type-arg] + const rqw: Promise = pool.query('select * from table;'); + const rq2: Promise = pool.query('Parameterized Queries',[1], + (err, result) => { + const _err: PG_ERROR|null = err; + // $FlowExpectedError[incompatible-type] + const _err_w: number = err; + const _result: ResultSet|void = result; + // $FlowExpectedError[incompatible-type] + const _result_w: number = result; + }); + // $FlowExpectedError[incompatible-call] + const rq2_w: Promise = pool.query('Parameterized Queries',1); + + // 1.2 the pool also supports checking out a client for + // multiple operations, such as a transaction + const rc: Promise = pool.connect( (err, client, done) => { + const _err: PG_ERROR|null = err; + // $FlowExpectedError[incompatible-type] + const _err_w: number = err; + const _client: PoolClient|null = client; + // $FlowExpectedError[incompatible-type] + const _client_w: number = client; + const _done: DoneCallback = done; + // $FlowExpectedError[incompatible-type] + const _done_w: number = done; + }); + // $FlowExpectedError[incompatible-type] + const rc_w: number = pool.connect(); + + const rt: Promise = pool.take( (err, client, done) => { + const _err: PG_ERROR|null = err; + // $FlowExpectedError[incompatible-type] + const _err_w: number = err; + const _client: PoolClient|null = client; + // $FlowExpectedError[incompatible-type] + const _client_w: number = client; + const _done: DoneCallback = done; + // $FlowExpectedError[incompatible-type] + const _done_w: number = done; + }); + // $FlowExpectedError[incompatible-type] + const rt_w: number = pool.take(); + + const re: Promise = pool.end( err => { + // $FlowExpectedError[incompatible-type] + const _err_w: string = err; // ?:mixed + }); + // $FlowExpectedError[incompatible-type-arg] + const re_w: Promise = pool.end(); + + // Note: There is a slight different between pool.query and client.query. + // client.query return a Query, pool.query return Promise + // class Query extends Promise + function test_PoolClient(client: PoolClient) { + const rr: void = client.release('any msg'); + const rr1: void = client.release(); + // $FlowExpectedError[incompatible-type] + const rr_w: null = client.release(); + const rq: QueryType = client.query('select * from table;'); + // $FlowExpectedError[incompatible-type-arg] + const rqw: Promise = pool.query('select * from table;'); + rq.on('row', (row, result) => { + const _row: Row = row; + const _result: ResultBuilder = result; + // $FlowExpectedError[incompatible-type] + const _row_w: number = row; + // $FlowExpectedError[incompatible-type] + const _result_w: number = result; + }); + rq.on('end', (result) => { + const reselt: ResultBuilder = result; + }); + rq.on('error', (err) => { + const _err: PG_ERROR = err; + // $FlowExpectedError[incompatible-type] + const _err_w: number = err; + }); + // $FlowExpectedError[incompatible-call] + rq.on('wrong', ()=>{}); + + + const rq2: Promise = client.query('Parameterized Queries',[1], + (err, result) => { + const _err: PG_ERROR|null = err; + // $FlowExpectedError[incompatible-type] + const _err_w: number = err; + const _result: ResultSet|void = result; + // $FlowExpectedError[incompatible-type] + const _result_w: number = result; + }); + // $FlowExpectedError[incompatible-call] + const rq2_w: Promise = client.query('Parameterized Queries',1); + + const rq3: QuerySubmittableConfig = client.query({ + text: 'select * from table;', + submit: (connection: mixed): void => { + const _connection: mixed = connection; + }, + }); + } + } + + // 2. instantiate a client directly. + function test_client() { + const client = new pg.Client(); + client.connect((err, client) => { + const _err: PG_ERROR|null = err; + const _client: Client|void = client; + if (_client) { + const rq: QueryType = _client.query('select * from table;'); + const rq2: Promise = _client.query('Parameterized Queries',[1], + (err, result) => { + const _err: PG_ERROR|null = err; + // $FlowExpectedError[incompatible-type] + const _err_w: number = err; + const _result: ResultSet|void = result; + // $FlowExpectedError[incompatible-type] + const _result_w: number = result; + }); + const rq3: QuerySubmittableConfig = _client.query({ + text: 'select * from table;', + submit: (connection: mixed): void => { + const _connection: mixed = connection; + }, + }); + // $FlowExpectedError[incompatible-call] + const rq2_w: Promise = _client.query('Parameterized Queries',1); + + _client.on('drain', _ => { + const a: void = _; + }); + // $FlowExpectedError[incompatible-call] + _client.on('drain',1); + _client.on('error', err => { + const _err: PG_ERROR = err; + }); + // $FlowExpectedError[incompatible-call] + _client.on('error',1); + _client.on('notification', msg => { + }); + // $FlowExpectedError[incompatible-call] + _client.on('notification',1); + _client.on('notice', msg => { + }); + // $FlowExpectedError[incompatible-call] + _client.on('notice',1); + _client.on('end', _ => { + const a: void = _; + }); + // $FlowExpectedError[incompatible-call] + _client.on('end',1); + } + }); + } +} + +// Simple example usage. +const pool = new pg.Pool({ + user: 'testuser', + password: 'testuser', + host: 'localhost', + database: 'testdb', + max: 10, + statement_timeout: false, + idleTimeoutMillis: 1000, + connectionTimeoutMillis: 1000 +}); + +// use pool +const promise_r = pool.query('select * from table;', ['11']); +// $FlowExpectedError[incompatible-type] +const p:boolean = promise_r; // Promise +promise_r.then( result => { + // $FlowExpectedError[incompatible-type] + const v:boolean = result.command; // string + // $FlowExpectedError[incompatible-type] + const v2:boolean = result.oid; // string + // $FlowExpectedError[incompatible-type] + const v3:boolean = result.rowCount; // string + // $FlowExpectedError[incompatible-type] + const v4:boolean = result.rows; // Array + const rt:ResultSet = result; // the type of result +}) + +// directly use client +const promise_client = pool.connect(); +promise_client.then( client => { + client.query('select * from table;') + .then( result => { + // $FlowExpectedError[incompatible-type] + const v:boolean = result; // result should be typed + }); + client.release('error msg'); // accept error msg + client.release(); // or without arguments +}); diff --git a/definitions/npm/plow-js_v2.1.x/flow_v0.104.x-/plow-js_v2.1.x.js b/definitions/npm/plow-js_v2.1.x/flow_v0.104.x-v0.200.x/plow-js_v2.1.x.js similarity index 100% rename from definitions/npm/plow-js_v2.1.x/flow_v0.104.x-/plow-js_v2.1.x.js rename to definitions/npm/plow-js_v2.1.x/flow_v0.104.x-v0.200.x/plow-js_v2.1.x.js diff --git a/definitions/npm/plow-js_v2.1.x/flow_v0.201.x-/plow-js_v2.1.x.js b/definitions/npm/plow-js_v2.1.x/flow_v0.201.x-/plow-js_v2.1.x.js new file mode 100644 index 0000000000..3805fc3777 --- /dev/null +++ b/definitions/npm/plow-js_v2.1.x/flow_v0.201.x-/plow-js_v2.1.x.js @@ -0,0 +1,196 @@ +declare module "plow-js" { + declare type PathPartial = string | number; + declare type Path = PathPartial | Array; + declare type Subject = Object; + declare type Mapper = PathPartial | ((value: any) => any); + declare type TransformShape = { [string]: Function, ... }; + declare type BooleanStatementFn = (...args: any) => boolean; + + /** + * Projections + */ + declare function $get(path: Path, subject: Subject): any; + declare function $get(path: Path): (subject: Subject) => any; + + declare function $count(path: Path, subject: Subject): number; + declare function $count(path: Path): (subject: Subject) => number; + + declare function $contains(value: any, path: Path, subject: Subject): boolean; + declare function $contains( + value: any, + path: Path + ): (subject: Subject) => boolean; + declare function $contains( + value: any + ): (path: Path) => (subject: Subject) => boolean; + + declare function $head(path: Path, subject: Subject): any; + declare function $head(path: Path): (subject: Subject) => any; + + declare function $tail(path: Path, subject: Subject): Array; + declare function $tail(path: Path): (subject: Subject) => Array; + + declare function $last(path: Path, subject: Subject): any; + declare function $last(path: Path): (subject: Subject) => any; + + declare function $map(mapper: Mapper, path: Path, subject: Subject): any; + declare function $map(mapper: Mapper, path: Path): (subject: Subject) => any; + declare function $map( + mapper: Mapper + ): (path: Path) => (subject: Subject) => any; + + declare function $transform(shape: TransformShape, subject: Subject): Object; + declare function $transform( + shape: TransformShape + ): (subject: Subject) => Object; + + declare function $resolve(pointer: Path, subject: Subject): any; + declare function $resolve(pointer: Path): (subject: Subject) => any; + + // The all-in-one call is not yet supported due to https://github.com/facebook/flow/issues/2443 + // declare function $and(...statementsAndSubject: Array): boolean; + declare function $and( + ...statements: Array + ): (subject: Subject) => boolean; + + // The all-in-one call is not yet supported due to https://github.com/facebook/flow/issues/2443 + // declare function $or(...statementsAndSubject: Array): boolean; + declare function $or( + ...statements: Array + ): (subject: Subject) => boolean; + + declare function $not( + statement: BooleanStatementFn, + subject: Subject + ): boolean; + declare function $not( + statement: BooleanStatementFn + ): (subject: Subject) => boolean; + + /** + * Migrations + */ + declare function $set( + path: Path, + ...rest: Array + ): (value: any) => (subject: Subject) => Subject; + declare function $set( + path: Path, + value: any, + ...rest: Array + ): (subject: Subject) => Subject; + declare function $set(path: Path, value: any, subject: Subject): Subject; + + declare function $merge( + path: Path, + ...rest: Array + ): (value: any) => (subject: Subject) => Subject; + declare function $merge( + path: Path, + value: any, + ...rest: Array + ): (subject: Subject) => Subject; + declare function $merge(path: Path, value: any, subject: Subject): Subject; + + declare function $add( + path: Path, + ...rest: Array + ): (value: any) => (subject: S) => $Shape; + declare function $add( + path: Path, + value: any, + ...rest: Array + ): (subject: S) => $Shape; + declare function $add(path: Path, value: any, subject: S): $Shape; + + declare function $drop( + path: Path, + ...rest: Array + ): (subject: S) => $Shape; + declare function $drop(path: Path, subject: S): $Shape; + + declare function $override( + path: Path, + ...rest: Array + ): (value: any) => (subject: Subject) => Subject; + declare function $override( + path: Path, + value: any, + ...rest: Array + ): (subject: Subject) => Subject; + declare function $override(path: Path, value: any, subject: Subject): Subject; + + declare function $pop( + path: Path, + ...rest: Array + ): (subject: S) => $Shape; + declare function $pop(path: Path, subject: S): $Shape; + + declare function $remove( + path: Path, + ...rest: Array + ): (value: any) => (subject: S) => $Shape; + declare function $remove( + path: Path, + value: any, + ...rest: Array + ): (subject: S) => $Shape; + declare function $remove(path: Path, value: any, subject: S): $Shape; + + declare function $shift( + path: Path, + ...rest: Array + ): (subject: S) => $Shape; + declare function $shift(path: Path, subject: S): $Shape; + + declare function $unshift( + path: Path, + ...rest: Array + ): (value: any) => (subject: S) => $Shape; + declare function $unshift( + path: Path, + value: any, + ...rest: Array + ): (subject: S) => $Shape; + declare function $unshift(path: Path, value: any, subject: S): $Shape; + + declare function $toggle( + path: Path, + ...rest: Array + ): (value: any) => (subject: S) => $Shape; + declare function $toggle( + path: Path, + value: any, + ...rest: Array + ): (subject: S) => $Shape; + declare function $toggle(path: Path, value: any, subject: S): $Shape; + + /** + * Connections + */ + // The all-in-one call is not yet supported due to https://github.com/facebook/flow/issues/2443 + // declare function $all(...statementsAndSubject: Array): Subject; + declare function $all( + ...statements: Array + ): (subject: Subject) => Subject; + + declare function $summarize( + operations: Array, + ...rest: Array + ): (finisher: (...args: Array) => R) => (subject: Subject) => R; + declare function $summarize( + operations: Array, + finisher: (...args: Array) => R, + ...rest: Array + ): (subject: Subject) => R; + declare function $summarize( + operations: Array, + finisher: (...args: Array) => R, + subject: Subject + ): R; + + declare function $traverse(actor: Function): (subject: Subject) => Subject; + declare function $traverse(actor: Function, subject: Subject): Subject; + + declare function $log(pathOrSubject: Path | Subject, subject?: Subject): any; +} diff --git a/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/puppeteer_v1.20.x.js b/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/puppeteer_v1.20.x.js similarity index 100% rename from definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/puppeteer_v1.20.x.js rename to definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/puppeteer_v1.20.x.js diff --git a/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/test_puppeteer_v1.20.x_connect.js b/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/test_puppeteer_v1.20.x_connect.js similarity index 100% rename from definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/test_puppeteer_v1.20.x_connect.js rename to definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/test_puppeteer_v1.20.x_connect.js diff --git a/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/test_puppeteer_v1.20.x_defaultArgs.js b/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/test_puppeteer_v1.20.x_defaultArgs.js similarity index 100% rename from definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/test_puppeteer_v1.20.x_defaultArgs.js rename to definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/test_puppeteer_v1.20.x_defaultArgs.js diff --git a/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/test_puppeteer_v1.20.x_executablePath.js b/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/test_puppeteer_v1.20.x_executablePath.js similarity index 100% rename from definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/test_puppeteer_v1.20.x_executablePath.js rename to definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/test_puppeteer_v1.20.x_executablePath.js diff --git a/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/test_puppeteer_v1.20.x_launch.js b/definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/test_puppeteer_v1.20.x_launch.js similarity index 100% rename from definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-/test_puppeteer_v1.20.x_launch.js rename to definitions/npm/puppeteer_v1.20.x/flow_v0.104.x-v0.200.x/test_puppeteer_v1.20.x_launch.js diff --git a/definitions/npm/puppeteer_v1.20.x/flow_v0.201.x-/puppeteer_v1.20.x.js b/definitions/npm/puppeteer_v1.20.x/flow_v0.201.x-/puppeteer_v1.20.x.js new file mode 100644 index 0000000000..0c4c6487ff --- /dev/null +++ b/definitions/npm/puppeteer_v1.20.x/flow_v0.201.x-/puppeteer_v1.20.x.js @@ -0,0 +1,1372 @@ +// @flow + +/** + * Based on typescript definitions found at the url below + * https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/puppeteer + */ + + declare module 'puppeteer' { + import type { ChildProcess } from 'child_process'; + + declare class OverridableEventEmitter extends events$EventEmitter { + /* eslint-disable flowtype/no-weak-types */ + +on: Function; + +once: Function; + /* eslint-enable flowtype/no-weak-types */ + } + + /** Keyboard provides an api for managing a virtual keyboard. */ + declare export type Keyboard = { + /** + * Dispatches a keydown event. + * @param key Name of key to press, such as ArrowLeft. + * @param options Specifies a input text event. + */ + down(key: string, options?: { text?: string, ... }): Promise, + /** Shortcut for `keyboard.down` and `keyboard.up`. */ + press(key: string, options?: { + delay?: number, + text?: string, + ... + }): Promise, + /** Dispatches a `keypress` and `input` event. This does not send a `keydown` or keyup `event`. */ + sendCharacter(char: string): Promise, + /** + * Sends a keydown, keypress/input, and keyup event for each character in the text. + * @param text A text to type into a focused element. + * @param options Specifies the typing options. + */ + type(text: string, options?: { delay?: number, ... }): Promise, + /** + * Dispatches a keyup event. + * @param key Name of key to release, such as ArrowLeft. + */ + up(key: string): Promise, + ... + }; + + declare export type MousePressOptions = { + /** + * left, right, or middle. + * @default left + */ + button?: MouseButtons, + /** + * The number of clicks. + * @default 1 + */ + clickCount?: number, + ... + }; + + declare export type Mouse = { + /** + * Shortcut for `mouse.move`, `mouse.down` and `mouse.up`. + * @param x The x position. + * @param y The y position. + * @param options The click options. + */ + click(x: number, y: number, options?: ClickOptions): Promise, + /** + * Dispatches a `mousedown` event. + * @param options The mouse press options. + */ + down(options?: MousePressOptions): Promise, + /** + * Dispatches a `mousemove` event. + * @param x The x position. + * @param y The y position. + * @param options The mouse move options. + */ + move(x: number, y: number, options?: { steps: number, ... }): Promise, + /** + * Dispatches a `mouseup` event. + * @param options The mouse press options. + */ + up(options?: MousePressOptions): Promise, + ... + }; + + declare export type Touchscreen = { /** + * Dispatches a touchstart and touchend event. + * @param x The x position. + * @param y The y position. + */ + tap(x: number, y: number): Promise, ... }; + + /** + * You can use `tracing.start` and `tracing.stop` to create a trace file which can be opened in Chrome DevTools or timeline viewer. + */ + declare export type Tracing = { + start(options: TracingStartOptions): Promise, + stop(): Promise, + ... + }; + + declare export type TracingStartOptions = { + categories?: Array, + path: string, + screenshots?: boolean, + ... + }; + + /** Dialog objects are dispatched by page via the 'dialog' event. */ + declare export type Dialog = { + /** + * Accepts the dialog. + * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's type is not prompt. + */ + accept(promptText?: string): Promise, + /** If dialog is prompt, returns default prompt value. Otherwise, returns empty string. */ + defaultValue(): string, + /** Dismiss the dialog */ + dismiss(): Promise, + /** Returns the message displayed in the dialog. */ + message(): string, + /** The dialog type. Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. */ + type(): 'alert' | 'beforeunload' | 'confirm' | 'prompt', + ... + }; + + /** ConsoleMessage objects are dispatched by page via the 'console' event. */ + declare export type ConsoleMessage = { + /** The message arguments. */ + args(): Array, + /** The message text. */ + text(): string, + type(): + | 'log' + | 'debug' + | 'info' + | 'error' + | 'warning' + | 'dir' + | 'dirxml' + | 'table' + | 'trace' + | 'clear' + | 'startGroup' + | 'startGroupCollapsed' + | 'endGroup' + | 'assert' + | 'profile' + | 'profileEnd' + | 'count' + | 'timeEnd', + ... + }; + + declare export type PageEvents = + | 'console' + | 'dialog' + | 'error' + | 'frameattached' + | 'framedetached' + | 'framenavigated' + | 'load' + | 'pageerror' + | 'request' + | 'requestfailed' + | 'requestfinished' + | 'response'; + + declare export type BrowserEvents = + | 'disconnected' + | 'targetchanged' + | 'targetcreated' + | 'targetdestroyed'; + + declare export type AuthOptions = { + password: string, + username: string, + ... + }; + + declare export type MouseButtons = 'left' | 'right' | 'middle'; + + declare export type ClickOptions = { + /** defaults to left */ + button?: MouseButtons, + /** defaults to 1 */ + clickCount?: number, + /** + * Time to wait between mousedown and mouseup in milliseconds. + * Defaults to 0. + */ + delay?: number, + ... + }; + + /** Represents a browser cookie. */ + declare export type Cookie = { + /** The cookie domain. */ + domain: string, + /** The cookie Unix expiration time in seconds. */ + expires: number, + /** The cookie http only flag. */ + httpOnly: boolean, + /** The cookie name. */ + name: string, + /** The cookie path. */ + path: string, + /** The cookie same site definition. */ + sameSite: 'Strict' | 'Lax', + /** The cookie secure flag. */ + secure: boolean, + /** The cookie value. */ + value: string, + ... + }; + + declare export type DeleteCookie = { + domain?: string, + /** The cookie name. */ + name: string, + path?: string, + secure?: boolean, + url?: string, + ... + }; + + declare export type SetCookie = { + /** The cookie domain. */ + domain?: string, + /** The cookie Unix expiration time in seconds. */ + expires?: number, + /** The cookie http only flag. */ + httpOnly?: boolean, + /** The cookie name. */ + name: string, + /** The cookie path. */ + path?: string, + /** The cookie same site definition. */ + sameSite?: 'Strict' | 'Lax', + /** The cookie secure flag. */ + secure?: boolean, + /** The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. */ + url?: string, + /** The cookie value. */ + value: string, + ... + }; + + declare export type Viewport = { + /** + * Specify device scale factor (can be thought of as dpr). + * @default 1 + */ + deviceScaleFactor?: number, + /** + * Specifies if viewport supports touch events. + * @default false + */ + hasTouch?: boolean, + /** The page height in pixels. */ + height: number, + /** + * Specifies if viewport is in landscape mode. + * @default false + */ + isLandscape?: boolean, + /** + * Whether the `meta viewport` tag is taken into account. + * @default false + */ + isMobile?: boolean, + /** The page width in pixels. */ + width: number, + ... + }; + + /** Page emulation options. */ + declare export type EmulateOptions = { + /** The emulated user-agent. */ + userAgent?: string, + /** The viewport emulation options. */ + viewport?: Viewport, + ... + }; + + declare export type EvaluateFn = string | ((...args: Array) => mixed); + + declare export type LoadEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'; + + /** The navigation options. */ + declare export type NavigationOptions = { + /** + * Maximum navigation time in milliseconds, pass 0 to disable timeout. + * @default 30000 + */ + timeout?: number, + /** + * When to consider navigation succeeded. + * @default load Navigation is consider when the `load` event is fired. + */ + waitUntil?: LoadEvent | Array, + ... + }; + + declare export type PDFFormat = + | 'Letter' + | 'Legal' + | 'Tabload' + | 'Ledger' + | 'A0' + | 'A1' + | 'A2' + | 'A3' + | 'A4' + | 'A5'; + + declare export type PDFOptions = { + /** + * Display header and footer. + * @default false + */ + displayHeaderFooter?: boolean, + /** + * HTML template for the print footer. Should be valid HTML markup with following classes used to inject printing values into them: + * - `date` formatted print date + * - `title` document title + * - `url` document location + * - `pageNumber` current page number + * - `totalPages` total pages in the document + */ + footerTemplate?: string, + /** Paper format. If set, takes priority over width or height options. Defaults to 'Letter'. */ + format?: PDFFormat, + /** + * HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: + * - `date` formatted print date + * - `title` document title + * - `url` document location + * - `pageNumber` current page number + * - `totalPages` total pages in the document + */ + headerTemplate?: string, + /** Paper height, accepts values labeled with units. */ + height?: string, + /** + * Paper orientation. + * @default false + */ + landscape?: boolean, + /** Paper margins, defaults to none. */ + margin?: { + /** Bottom margin, accepts values labeled with units. */ + bottom?: string, + /** Left margin, accepts values labeled with units. */ + left?: string, + /** Right margin, accepts values labeled with units. */ + right?: string, + /** Top margin, accepts values labeled with units. */ + top?: string, + ... + }, + /** + * Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty + * string, which means print all pages. + */ + pageRanges?: string, + /** + * The file path to save the PDF to. + * If `path` is a relative path, then it is resolved relative to current working directory. + * If no path is provided, the PDF won't be saved to the disk. + */ + path?: string, + /** + * Print background graphics. + * @default false + */ + printBackground?: boolean, + /** + * Scale of the webpage rendering. + * @default 1 + */ + scale?: number, + /** Paper width, accepts values labeled with units. */ + width?: string, + ... + }; + + /** Defines the screenshot options. */ + declare export type ScreenshotOptions = { + /** + * An object which specifies clipping region of the page. + */ + clip?: BoundingBox, + /** + * When true, takes a screenshot of the full scrollable page. + * @default false + */ + fullPage?: boolean, + /** + * Hides default white background and allows capturing screenshots with transparency. + * @default false + */ + omitBackground?: boolean, + /** + * The file path to save the image to. The screenshot type will be inferred from file extension. + * If `path` is a relative path, then it is resolved relative to current working directory. + * If no path is provided, the image won't be saved to the disk. + */ + path?: string, + /** The quality of the image, between 0-100. Not applicable to png images. */ + quality?: number, + /** + * The screenshot type. + * @default png + */ + type?: 'jpeg' | 'png', + ... + }; + + /** Options for `addStyleTag` */ + declare export type StyleTagOptions = { + /** Raw CSS content to be injected into frame. */ + content?: string, + /** Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to current working directory. */ + path?: string, + /** Url of the tag. */ + url?: string, + ... + }; + /** Options for `addScriptTag` */ + declare export type ScriptTagOptions = { + /** Raw JavaScript content to be injected into frame. */ + content?: string, + /** Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to current working directory. */ + path?: string, + /** Script type. Use 'module' in order to load a Javascript ES6 module. */ + type?: string, + /** Url of a script to be added. */ + url?: string, + ... + }; + + declare export type PageFnOptions = { + polling?: 'raf' | 'mutation' | number, + timeout?: number, + ... + }; + + declare export type BoundingBox = { + /** The height. */ + height: number, + /** The width. */ + width: number, + /** The x-coordinate of top-left corner. */ + x: number, + /** The y-coordinate of top-left corner. */ + y: number, + ... + }; + + /** + * Represents an in-page DOM element. ElementHandles can be created with the page.$ method. + */ + declare export type ElementHandle = JSHandle & { + /** + * The method runs element.querySelector within the page. If no element matches the selector, the return value resolve to null. + * @param selector A selector to query element for + * @since 0.13.0 + */ + $(selector: string): Promise, + /** + * The method runs element.querySelectorAll within the page. If no elements match the selector, the return value resolve to []. + * @param selector A selector to query element for + * @since 0.13.0 + */ + $$(selector: string): Promise>, + /** + * @param selector XPath expression to evaluate. + */ + $x(expression: string): Promise>, + /** + * This method returns the value resolve to the bounding box of the element (relative to the main frame), or null if the element is not visible. + */ + boundingBox(): Promise, + /** + * This method scrolls element into view if needed, and then uses page.mouse to click in the center of the element. + * If the element is detached from DOM, the method throws an error. + * @param options Specifies the options. + * @since 0.9.0 + */ + click(options?: ClickOptions): Promise, + /** + * @returns Resolves to the content frame for element handles referencing iframe nodes, or null otherwise. + * @since 1.2.0 + */ + contentFrame(): Promise, + /** + * Calls focus on the element. + */ + focus(): Promise, + /** + * This method scrolls element into view if needed, and then uses page.mouse to hover over the center of the element. + * If the element is detached from DOM, the method throws an error. + */ + hover(): Promise, + /** + * Focuses the element, and then uses keyboard.down and keyboard.up. + * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names. + * @param options The text and delay options. + */ + press(key: string, options?: { + delay?: number, + text?: string, + ... + }): Promise, + /** + * This method scrolls element into view if needed, and then uses page.screenshot to take a screenshot of the element. + * If the element is detached from DOM, the method throws an error. + * @param options Same options as in page.screenshot. + */ + screenshot(options?: ScreenshotOptions): Promise, + /** + * This method scrolls element into view if needed, and then uses touchscreen.tap to tap in the center of the element. + * If the element is detached from DOM, the method throws an error. + */ + tap(): Promise, + toString(): string, + /** + * Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text. + * @param text A text to type into a focused element. + * @param options The typing options. + */ + type(text: string, options?: { delay: number, ... }): Promise, + /** + * This method expects elementHandle to point to an input element. + * @param filePaths Sets the value of the file input these paths. If some of the filePaths are relative paths, then they are resolved relative to current working directory. + */ + uploadFile(...filePaths: Array): Promise, + ... + }; + + /** The class represents a context for JavaScript execution. */ + declare export type ExecutionContext = { + evaluate(fn: EvaluateFn, ...args: Array): Promise, + evaluateHandle(fn: EvaluateFn, ...args: Array): Promise, + queryObjects(prototypeHandle: JSHandle): JSHandle, + ... + }; + + /** JSHandle represents an in-page JavaScript object. */ + declare export type JSHandle = { + /** + * Returns a ElementHandle + */ + asElement(): ElementHandle | null, + /** + * Stops referencing the element handle. + */ + dispose(): Promise, + /** + * Gets the execution context. + */ + executionContext(): ExecutionContext, + /** + * Returns a map with property names as keys and JSHandle instances for the property values. + */ + getProperties(): Promise>, + /** + * Fetches a single property from the objectHandle. + * @param propertyName The property to get. + */ + getProperty(propertyName: string): Promise, + /** + * Returns a JSON representation of the object. + * The JSON is generated by running JSON.stringify on the object in page and consequent JSON.parse in puppeteer. + * @throws The method will throw if the referenced object is not stringifiable. + */ + jsonValue(): Promise, + ... + }; + + declare export type Metrics = { + /** Number of documents in the page. */ + Documents: number, + /** Number of frames in the page. */ + Frames: number, + /** Number of events in the page. */ + JSEventListeners: number, + /** Total JavaScript heap size. */ + JSHeapTotalSize: number, + /** Used JavaScript heap size. */ + JSHeapUsedSize: number, + /** Total number of full or partial page layout. */ + LayoutCount: number, + /** Combined durations of all page layouts. */ + LayoutDuration: number, + /** Number of DOM nodes in the page. */ + Nodes: number, + /** Total number of page style recalculations. */ + RecalcStyleCount: number, + /** Combined duration of all page style recalculations. */ + RecalcStyleDuration: number, + /** Combined duration of JavaScript execution. */ + ScriptDuration: number, + /** Combined duration of all tasks performed by the browser. */ + TaskDuration: number, + /** The timestamp when the metrics sample was taken. */ + Timestamp: number, + ... + }; + + declare export type Headers = { [key: string]: string, ... }; + declare export type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE' | 'OPTIONS'; + + declare export type ResourceType = + | 'document' + | 'stylesheet' + | 'image' + | 'media' + | 'font' + | 'script' + | 'texttrack' + | 'xhr' + | 'fetch' + | 'eventsource' + | 'websocket' + | 'manifest' + | 'other'; + + declare export type Overrides = { + headers?: Headers, + method?: HttpMethod, + postData?: string, + url?: string, + ... + }; + + /** Represents a page request. */ + declare export type Request = { + /** + * Aborts request. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + */ + abort(): Promise, + /** + * Continues request with optional request overrides. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + */ + continue(overrides?: Overrides): Promise, + /** + * @returns The `Frame` object that initiated the request, or `null` if navigating to error pages + */ + frame(): Promise, + /** + * An object with HTTP headers associated with the request. + * All header names are lower-case. + */ + headers(): Headers, + /** Returns the request's method (GET, POST, etc.) */ + + method(): HttpMethod, + /** Contains the request's post body, if any. */ + postData(): ?string, + /** + * A `redirectChain` is a chain of requests initiated to fetch a resource. + * + * - If there are no redirects and the request was successful, the chain will be empty. + * - If a server responds with at least a single redirect, then the chain will contain all the requests that were redirected. + * + * `redirectChain` is shared between all the requests of the same chain. + * + * @since 1.2.0 + */ + redirectChain(): Array, + /** Contains the request's resource type as it was perceived by the rendering engine. */ + resourceType(): ResourceType, + /** + * Fulfills request with given response. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + * @param response The response options that will fulfill this request. + */ + respond(response: RespondOptions): Promise, + /** A matching `Response` object, or `null` if the response has not been received yet. */ + response(): ?Response, + /** Contains the URL of the request. */ + url(): string, + ... + }; + + /** Options for `Request.respond` method */ + declare export type RespondOptions = { + /** Specifies the response body. */ + body?: Buffer | string, + /** Specifies the Content-Type response header. */ + contentType?: string, + /** Specifies the response headers. */ + headers?: Headers, + /** + * Specifies the response status code. + * @default 200 + */ + status?: number, + ... + }; + + /** Response class represents responses which are received by page. */ + declare export type Response = { + /** Promise which resolves to a buffer with response body. */ + buffer(): Promise, + /** True if the response was served from either the browser's disk cache or memory cache. */ + fromCache(): boolean, + /** True if the response was served by a service worker. */ + fromServiceWorker(): boolean, + /** An object with HTTP headers associated with the response. All header names are lower-case. */ + headers(): Headers, + /** + * Promise which resolves to a JSON representation of response body. + * @throws This method will throw if the response body is not parsable via `JSON.parse`. + */ + json(): Promise, + /** Contains a boolean stating whether the response was successful (status in the range 200-299) or not. */ + ok(): boolean, + /** A matching Request object. */ + request(): Request, + /** Contains the status code of the response (e.g., 200 for a success). */ + status(): number, + /** Promise which resolves to a text representation of response body. */ + text(): Promise, + /** Contains the URL of the response. */ + url(): string, + ... + }; + + declare class FrameBase { + /** + * The method runs document.querySelector within the page. + * If no element matches the selector, the return value resolve to null. + */ + $: (selector: string) => Promise; + + /** + * The method runs document.querySelectorAll within the page. If no elements match the selector, the return value resolve to []. + */ + $$: (selector: string) => Promise>; + + /** + * This method runs document.querySelectorAll within the page and passes it as the first argument to `fn`. + * If `fn` returns a Promise, then $$eval would wait for the promise to resolve and return its value. + * @param selector A selector to query frame for + * @param fn Function to be evaluated in browser context + * @param args Arguments to pass to pageFunction + * @returns Promise which resolves to the return value of pageFunction + */ + $$eval: ( + selector: string, + pageFunction: ( + elements: NodeList, + ...args: Array + ) => mixed, + ...args: Array + ) => Promise; + + /** + * This method runs document.querySelector within the page and passes it as the first argument to `fn`. + * If there's no element matching selector, the method throws an error. + * If `fn` returns a Promise, then $eval would wait for the promise to resolve and return its value. + */ + $eval: ( + selector: string, + pageFunction: (element: Element, ...args: Array) => mixed, + ...args: Array + ) => Promise; + + /** + * @param expression XPath expression to evaluate. + */ + $x: (expression: string) => Promise>; + + /** Adds a `