repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
lakshay-pant/vynoFinalBack | src/main.ts | <reponame>lakshay-pant/vynoFinalBack<filename>src/main.ts
import { NestFactory } from '@nestjs/core';
import { VersioningType } from '@nestjs/common';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';
import { join } from 'path';
var express = require('express');
const bodyParser = require('body-parser');
async function bootstrap() {
// const app = await NestFactory.create(AppModule);
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
{ cors: true }
);
app.use(bodyParser.json({
extended: true,
limit: '50mb'
}));
app.use(express.static('public'));
app.use('/public', express.static('public'));
app.enableVersioning({
type: VersioningType.URI,
});
await app.listen(3000);
//console.log(process.env.MONGODB_URL);
}
bootstrap();
|
lakshay-pant/vynoFinalBack | dist/src/payment/payment.controller.d.ts | <filename>dist/src/payment/payment.controller.d.ts
import { PaymentService } from './payment.service';
import { UpdatePaymentDto } from './dto/update-payment.dto';
import { UsersService } from '../users/users.service';
import { HelperService } from '../common/helper';
export declare class PaymentController {
private readonly paymentService;
private readonly usersService;
private helperService;
constructor(paymentService: PaymentService, usersService: UsersService, helperService: HelperService);
create(body: any): Promise<any>;
findAll(): string;
findOne(id: string): string;
update(id: string, updatePaymentDto: UpdatePaymentDto): string;
remove(id: string): string;
}
|
lakshay-pant/vynoFinalBack | dist/src/document/document.controller.d.ts | <reponame>lakshay-pant/vynoFinalBack
/// <reference types="multer" />
import { DocumentService } from './document.service';
import { CreateDocumentDto } from './dto/create-document.dto';
import { HelperService } from '../common/helper';
import { JwtService } from '@nestjs/jwt';
export declare class DocumentController {
private readonly documentService;
private jwtService;
private helperService;
constructor(documentService: DocumentService, jwtService: JwtService, helperService: HelperService);
create(createDocumentDto: CreateDocumentDto): string;
accountStatus(body: any): Promise<{
status: boolean;
data: {};
} | {
status: boolean;
data: {
user_status: string;
driver_status: string;
};
}>;
updateStatus(body: any): Promise<{
status: boolean;
message: string;
}>;
uploadFile(body: any, files: Array<Express.Multer.File>): Promise<{
status: boolean;
message: any;
}>;
}
|
lakshay-pant/vynoFinalBack | dist/src/singup/singup.controller.d.ts | import { SingupService } from './singup.service';
import { UsersService } from '../users/users.service';
import { CreateUserDto } from '../users/dto/create-user.dto';
import { Request, Response } from 'express';
import { HelperService } from '../common/helper';
import { JwtService } from '@nestjs/jwt';
export declare class SingupController {
private readonly singupService;
private readonly usersService;
private jwtService;
private helperService;
constructor(singupService: SingupService, usersService: UsersService, jwtService: JwtService, helperService: HelperService);
create(createUserDto: CreateUserDto): Promise<{
status: boolean;
id: any;
message: string;
} | {
status: boolean;
message: any;
id?: undefined;
}>;
createMomoAccountAndSaveCredential(user_id: any): Promise<void>;
verifyotp(req: Request, res: Response, data: any): Promise<{
status: boolean;
message: string;
token?: undefined;
data?: undefined;
} | {
status: boolean;
token: string;
data: any;
message: string;
}>;
}
|
lakshay-pant/vynoFinalBack | dist/src/lift/lift.service.d.ts | <reponame>lakshay-pant/vynoFinalBack<gh_stars>0
import { CreateLiftDto } from './dto/create-lift.dto';
import { UpdateLiftDto } from './dto/update-lift.dto';
import { Model } from 'mongoose';
export declare class LiftService {
private liftModel;
private liftRequestModel;
private liftBookingModel;
private liftNotification;
private virtualLift;
private virtualBufferModel;
constructor(liftModel: Model<CreateLiftDto>, liftRequestModel: Model<{}>, liftBookingModel: Model<{}>, liftNotification: Model<{}>, virtualLift: Model<{}>, virtualBufferModel: Model<{}>);
create(createLiftDto: CreateLiftDto): any;
findAll(): Promise<(import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
})[]>;
myAllList(id: any): Promise<(import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
})[]>;
findOne(id: any): Promise<import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
}>;
activeBooking(id: any): import("mongoose").Query<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, {}, {}>;
fetchTodayBooking(user_id: any, date: any): import("mongoose").Aggregate<any[]>;
deleteLift(id: any): import("mongoose").Query<import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
}, import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
}, {}, CreateLiftDto>;
searchLift(query: any, user_id: any): Promise<(import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
})[]>;
update(id: any, updateLiftDto: UpdateLiftDto): import("mongoose").Query<import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
}, import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
}, {}, CreateLiftDto>;
checkRequestExits(data: any): any;
createdLiftRequest(data: any): any;
myLiftUserRequest(id: any): any;
myVirtualLiftRequest(id: any): any;
myLiftDriverRequest(id: any): any;
actionLiftRequest(query: any): import("mongoose").Query<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, {}, {}>;
createdLiftBooking(query: any): any;
cancleBooking(data: any): any;
myBookingData(id: any, role: any): any;
createdNotification(data: any): any;
fetchNotificationUser(userid: any): any;
fetchNotificationDriver(driverid: any): any;
deleteAllNotification(notification_id: any): import("mongoose").Query<import("mongodb").DeleteResult, import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, {}, {}>;
createVirtualLift(data: any): any;
getVirtualLiftDetails(id: any): Promise<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}>;
updateVirtualLiftDetails(id: any, data: any): import("mongoose").Query<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, {}, {}>;
getVirtualLift(user_id: any): any;
acceptVirtualLiftFromDriver(lift_id: any, data: any): import("mongoose").Query<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, {}, {}>;
removeVirtualLiftFromuser(lift_id: any): import("mongoose").Query<import("mongodb").UpdateResult, import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, {}, {}>;
approvalVirtualLift(lift_id: any): import("mongoose").Query<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, {}, {}>;
addAmountInVirtualBuffer(data: any): any;
getVirtualBuffer(id: any): Promise<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}>;
removeBufferData(id: any): import("mongoose").Query<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, import("mongoose").Document<any, any, {}> & {
_id: unknown;
}, {}, {}>;
}
|
lakshay-pant/vynoFinalBack | dist/src/address/schemas/address.schema.d.ts | <filename>dist/src/address/schemas/address.schema.d.ts
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export declare type AddressDocument = Address & Document;
export declare class Address {
user_id: User;
type: string;
lat: string;
long: string;
address: string;
landmark: string;
country: string;
state: string;
city: string;
pin_Code: string;
created_at: string;
updated_at: string;
}
export declare const AddressSchema: mongoose.Schema<Document<Address, any, any>, mongoose.Model<Document<Address, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/singup/dto/create-singup.dto.ts | export class CreateSingupDto {}
|
lakshay-pant/vynoFinalBack | src/document/document.module.ts | import { Module } from '@nestjs/common';
import { DocumentService } from './document.service';
import { MongooseModule } from '@nestjs/mongoose';
import { JwtModule } from '@nestjs/jwt';
import { DocumentController } from './document.controller';
import { Documents, DocumentsSchema } from './schemas/document.schema';
import { HelperService } from '../common/helper';
import { MulterModule } from '@nestjs/platform-express';
@Module({
imports: [
MongooseModule.forFeature([{ name: Documents.name, schema: DocumentsSchema }]),
JwtModule.register({
secret: 'secretKey',
signOptions: { expiresIn: '365d' },
}),
MulterModule.register({
dest: './public/uploads/document/',
})
],
controllers: [DocumentController],
providers: [DocumentService,HelperService]
})
export class DocumentModule {}
|
sthagen/vuepress | packages/@vuepress/types/index.d.ts | <filename>packages/@vuepress/types/index.d.ts
import {
UserConfig,
ThemeConfig,
PluginOptions,
DefaultThemeConfig,
Theme,
Plugin,
} from './src'
export * from './src'
/**
* A helper function to define VuePress config file.
*
* @see https://vuepress.vuejs.org/config/
*/
export function defineConfig(config: UserConfig<DefaultThemeConfig>): void;
/**
* A helper function to define VuePress config file, for custom theme.
*
* @see https://vuepress.vuejs.org/config/
*/
export function defineConfig4CustomTheme<T extends ThemeConfig = ThemeConfig>(
config: UserConfig<T>
): void;
/**
* A helper function to define VuePress theme entry file.
*
* @see https://vuepress.vuejs.org/theme/option-api.html
*/
export function defineTheme<T extends ThemeConfig = ThemeConfig>(config: Theme<T>): void;
/**
* A helper function to define VuePress theme entry file.
*
* @see https://vuepress.vuejs.org/plugin/writing-a-plugin.html
*/
export function definePlugin<T extends PluginOptions = PluginOptions>(config: Plugin<T>): void;
|
Ch4m0/cursoUdemy | src/app/components/home.component.ts | <reponame>Ch4m0/cursoUdemy
import { Component } from '@angular/core';
@Component({
selector: 'home',
templateUrl: './../views/home.html'
})
export class HomeComponent{
public titulo: string;
constructor(){
this.titulo = 'pagina principal';
}
ngOnInit(){
console.log("cargo el componente home");
}
} |
ccosta-fbk/pxt-lamponi | test.ts | // tests go here; this will not be compiled when this package is used as a library
lamponi.showFunFace()
basic.forever(function () {}) |
ccosta-fbk/pxt-lamponi | main.ts | <gh_stars>0
/**
* MakeCode extension di test lamponi
*/
//% color=#009b5b icon="\f025" block="Lamponi"
namespace lamponi {
/**
* Show FunFace
*/
//% block="Show Fun Face"
export function showFunFace() {
basic.showLeds(`
. . . . .
. # . # .
. . # . .
# . . . #
. # # # .
`);
return
}
} |
RubaXa/effector | src/types/types.test.ts | // @flow
/* eslint-disable no-unused-vars */
import * as React from 'react'
import {
step,
createStore,
createNode,
createEvent,
createEffect,
createApi,
createStoreObject,
createDomain,
clearNode,
restoreEffect,
combine,
sample,
Effect,
Store,
Event,
//ComputedStore,
//ComputedEvent,
/*::type*/ kind,
forward,
launch,
split,
} from 'effector'
import {createComponent, createGate, useGate} from 'effector-react'
import {createFormApi} from '@effector/forms'
describe('Unit', () => {
describe('split', () => {
describe('split infer result', () => {
test('split result no false-negative', () => {
{
const source: Event<string[]> = createEvent()
const {emptyList, oneElement, __: commonList} = split(source, {
emptyList: list => list.length === 0,
oneElement: list => list.length === 1,
})
const split_result__nofneg__user_defined: Event<string[]> = emptyList
}
{
const source: Event<string[]> = createEvent()
const {emptyList, oneElement, __} = split(source, {
emptyList: list => list.length === 0,
oneElement: list => list.length === 1,
})
const split_result__nofneg__defaults: Event<string[]> = __
}
})
test('split result no false-positive', () => {
{
const source: Event<string[]> = createEvent()
const {emptyList, oneElement} = split(source, {
emptyList: list => list.length === 0,
oneElement: list => list.length === 1,
})
const split_result__nofpos__user_defined_1: Event<number> = emptyList
const split_result__nofpos__user_defined_2: null = oneElement
}
{
const source: Event<string[]> = createEvent()
const {__} = split(source, {
emptyList: list => list.length === 0,
oneElement: list => list.length === 1,
})
const split_result__nofpos__defaults_1: Event<number> = __
}
{
const source: Event<string[]> = createEvent()
const {__} = split(source, {
emptyList: list => list.length === 0,
oneElement: list => list.length === 1,
})
const split_result__nofpos__defaults_2: null = __
}
})
})
test('split arguments no false-positive', () => {
const source: Event<string[]> = createEvent()
split(source, {
wrongResult: list => null,
wrongArg_1: (list: null) => true,
wrongArg_2: (list: number[]) => true,
})
})
})
describe('sample', () => {
test('event by event', () => {
const a = createEvent<number>()
const b = createEvent<boolean>()
const c = sample(a, b)
const sample_ee_check1: Event<number> = c
const sample_ee_check2: Event<string> = c
})
test('event by event with handler', () => {
const a = createEvent<string>()
const b = createEvent<boolean>()
const c = sample(a, b, (a, b) => ({a, b}))
const sample_eeh_check1: Event<{a: string, b: boolean}> = c
const sample_eeh_check2: Event<string> = c
})
test('store by event', () => {
const d = createStore(0)
const b = createEvent<boolean>()
const e = sample(d, b)
const sample_se_check1: Event<number> = e
const sample_se_check2: Event<string> = e
})
test('store by event with handler', () => {
const d = createStore('')
const b = createEvent<boolean>()
const e = sample(d, b, (a, b) => ({a, b}))
const sample_seh_check1: Event<{a: string, b: boolean}> = e
const sample_seh_check2: Event<string> = e
})
test('effect by event', () => {
const f = createEffect<string, any, any>()
const b = createEvent<boolean>()
const g = sample(f, b)
const sample_efe_check1: Event<string> = g
const sample_efe_check2: Event<number> = g
})
test('effect by event with handler', () => {
const f = createEffect<string, any, any>()
const b = createEvent<boolean>()
const g = sample(f, b, (a, b) => ({a, b}))
const sample_efeh_check1: Event<{a: string, b: boolean}> = g
const sample_efeh_check2: Event<number> = g
})
test('store by store', () => {
const a = createStore(false)
const b = createStore(0)
const c = sample(a, b)
const sample_ss_check1: Store<boolean> = c
const sample_ss_check2: Store<string> = c
})
test('store by store with handler', () => {
const a = createStore('')
const b = createStore(true)
const c = sample(a, b, (a, b) => ({a, b}))
const sample_ssh_check1: Store<{a: string, b: boolean}> = c
const sample_ssh_check2: Store<string> = c
})
describe('sample(Store<T>):Store<T>', () => {
test('correct case', () => {
const a = createStore('')
const sample_s_correct: Store<string> = sample(a)
})
test('incorrect case', () => {
const a = createStore('')
const sample_s_incorrect: Store<number> = sample(a)
})
describe('edge case', () => {
test('correct case', () => {
const a = createStore('')
const clock = createEvent()
const sample_s_edge_correct: Event<string> = sample(a, clock)
})
test('incorrect case', () => {
const a = createStore('')
const clock = createEvent()
const sample_s_edge_incorrect: Event<number> = sample(a, clock)
})
})
})
})
})
describe('Event', () => {
test('createEvent', () => {
const createEvent_event1: Event<number> = createEvent()
const createEvent_event2: Event<number> = createEvent('event name [1]')
const createEvent_event3: Event<number> = createEvent({
name: 'event name [2]'
})
})
test('#map', () => {
const event: Event<number> = createEvent()
const computed = event.map(() => 'foo')
//const check1: Event<string> = computed
const event_map_check2: Event<number> = computed
event(2)
computed('')
})
test('#watch', () => {
const event: Event<number> = createEvent()
event.watch(state => {
const check1: number = state
return state
})
event.watch(state => 'foo')
event.watch(state => {
return
})
event.watch(state => {})
})
describe('#filter', () => {
test('#filter ok', () => {
const event: Event<number> = createEvent()
const filteredEvent_ok: Event<string> = event.filter(n => {
if (n % 2) return n.toString()
})
})
test('#filter incorrect', () => {
const event: Event<number> = createEvent()
const filteredEvent_error: Event<number> = event.filter(n => {
if (n % 2) return n.toString()
})
})
})
})
describe('Effect', () => {
test('createEffect', () => {
const createEffect_effect1: Effect<number, string> = createEffect()
const createEffect_effect2 = createEffect('', {
handler: createEffect_effect1,
})
const createEffect_effect3 = createEffect('', {
handler() {
return 'foo'
},
})
const createEffect_effect4: Effect<number, string> = createEffect('fx 4')
const createEffect_effect5: Effect<number, string> = createEffect({
name: 'fx 5',
})
})
test('#use', () => {
const effect1 = createEffect()
const foo = createEffect<number, string, any>()
effect1.use(params => Promise.resolve('foo'))
effect1.use(foo)
})
describe('void params', () => {
test('with handler', () => {
const handler = () => {}
const effect = createEffect('', {handler})
effect()
})
test('with use', () => {
const handler = () => {}
const effect = createEffect('').use(handler)
effect()
})
})
describe('nested effects', () => {
describe('with handler', () => {
test('no false-positive (should be type error)', () => {
const nestedEffect: Effect<string, string> = createEffect()
const parentEffect: Effect<number, number> = createEffect(
'should not throw',
{
handler: nestedEffect,
},
)
})
})
test('with use', () => {})
})
})
describe('Store', () => {
test('createStore', () => {
const createStore_store1: Store<number> = createStore(0)
const createStore_store2: Store<string> = createStore(0)
})
test('createStoreObject', () => {
const ev = createEvent()
const a = createStore('')
const b = createStore(0)
const c = createStoreObject({a, b})
c.on(ev, (state, payload) => state)
c.reset(ev)
c.off(ev)
})
test('createApi', () => {
const store: Store<number> = createStore(0)
{
const {event} = createApi(store, {
event: (n, x: number) => x,
})
const createApi_check1: Event<number> = event
}
{
const {event} = createApi(store, {
event: (n, x: number) => x,
})
const createApi_check2: Event<string> = event
}
{
const {event} = createApi(store, {
event: (n, x) => x,
})
const createApi_check3: Event<string> = event
}
})
test('createApi voids', () => {
const store = createStore(0)
const api = createApi(store, {
increment: count => count + 1,
decrement: count => count - 1,
double: count => count * 2,
multiply: (count, mp = 2) => count * mp,
})
api.double() // Expected 1 arguments, but got 0.
api.multiply() // Expected 1 arguments, but got 0.
})
test('setStoreName', () => {})
test('combine', () => {
const ev = createEvent()
const a = createStore('')
const b = createStore(0)
const c = combine(a, b, (a, b) => a + b)
c.on(ev, (state, payload) => state)
c.reset(ev)
c.off(ev)
})
test('restore', () => {
const eff = createEffect<{foo: number}, {bar: string}, any>()
const foo = restoreEffect(eff, {bar: ''})
})
test('#(properties)', () => {
const store = createStore(0)
const kind: kind = store.kind
const shortName: string = store.shortName
const defaultState: number = store.defaultState
const computed = store.map(() => 'hello')
const kind1: kind = computed.kind
const shortName1: string = computed.shortName
const defaultState1: string = computed.defaultState
})
test('#getState', () => {
const store = createStore(0)
const state: number = store.getState()
const computed = store.map(() => 'hello')
const state1: string = computed.getState()
})
test('#map', () => {
const store = createStore(0)
const computed = store.map(() => 'hello')
const map_check1: Store<string> = computed
const map_check2: Store<number> = computed
})
test('#reset', () => {
const event = createEvent()
const store = createStore(0)
store.reset(event)
const computed = store.map(() => 'hello')
computed.reset(event)
})
test('#on', () => {
const event = createEvent()
const store = createStore(0)
store.on(event, (state, payload) => state)
const computed = store.map(() => 'hello')
computed.on(event, (state, payload) => state)
})
test('#off', () => {
const event = createEvent()
const store = createStore(0)
store.off(event)
const computed = store.map(() => 'hello')
computed.off(event)
})
test('#subscribe', () => {
const event = createEvent()
const store = createStore(0)
// @ts-ignore I don't know type
store.subscribe(() => {})
const computed = store.map(() => 'hello')
// @ts-ignore I don't know type
computed.subscribe(() => {})
})
test('#watch', () => {
const event: Event<number> = createEvent()
const store = createStore(0)
store.watch((state, payload) => {
const store_watch_check1: number = state
const store_watch_check2: typeof undefined = payload
})
store.watch(event, (state, payload) => {
const store_watchBy_check1: number = state
const store_watchBy_check2: number = payload
})
const computed = store.map(() => 'hello')
computed.watch((state, payload) => {
const store_watchComputed_check1: string = state
const store_watchComputed_check2: typeof undefined = payload
})
computed.watch(event, (state, payload) => {
const store_watchByComputed_check1: string = state
const store_watchByComputed_check2: number = payload
})
})
test('#thru', () => {
const event = createEvent()
const store = createStore(0)
const result = store.thru(store => {
const thru_check1: Store<number> = store
return thru_check1
})
const computed = store.map(() => 'hello')
const result1 = computed.thru(store => {
const thru_computed_check1: Store<string> = store
return thru_computed_check1
})
})
})
describe('Domain', () => {
test('createDomain', () => {
const domain = createDomain()
const domain2 = createDomain('hello')
const domain3 = createDomain(234)
const domain4 = createDomain({foo: true})
})
test('#event', () => {
const domain = createDomain()
const event = domain.event<string>()
})
test('#effect', () => {
const domain = createDomain()
const effect1: Effect<string, number, Error> = domain.effect()
const effect2 = domain.effect('', {
handler(params: string) {
return 256
},
})
effect2(20)
const effect3 = domain.effect('', {
handler: effect1,
})
effect3(20)
})
test('#onCreateStore', () => {
const root = createDomain('root')
root.onCreateStore(store => {
const snapshot = localStorage.getItem(store.shortName)
if (typeof snapshot === 'string') store.setState(JSON.parse(snapshot))
let isFirstSkiped = false
store.watch(newState => {
if (isFirstSkiped) {
localStorage.setItem(store.shortName, JSON.stringify(newState))
}
isFirstSkiped = true
})
return store
})
root.onCreateStore(foo => {
const object = createStoreObject({foo})
object.watch(data => {
data.foo
})
clearNode(foo)
})
})
})
describe('Graph', () => {
describe('forward', () => {
test('forward between events', () => {
const forward_event1 = createEvent<number>()
const forward_event2 = createEvent<number>()
forward({
from: forward_event1,
to: forward_event2,
})
})
describe('forward between effects', () => {
test('start in parallel with the same payload', () => {
const forward_effect_par1 = createEffect<number, string, string>()
const forward_effect_par2 = createEffect<number, string, string>()
forward({
from: forward_effect_par1,
to: forward_effect_par2,
})
})
test('start sequentially', () => {
const forward_effect_seq1 = createEffect<number, string, string>()
const forward_effect_seq2 = createEffect<string, boolean, boolean>()
forward({
from: forward_effect_seq1.done.map(({result}) => result),
to: forward_effect_seq2,
})
})
})
test('forward between stores', () => {
const e = createStore(0)
const f = createStore(0)
forward({from: e, to: f})
})
})
test('launch', () => {
const foo = createEvent<number>()
const customNode = createNode({
scope: {max: 100, lastValue: -1, add: 10},
child: [foo],
node: [
step.compute({
fn: (arg, {add}) => arg + add,
}),
step.filter({
fn: (arg, {max, lastValue}) => arg < max && arg !== lastValue,
}),
step.compute({
fn(arg, scope) {
scope.lastValue = arg
return arg
},
}),
],
})
launch(foo, '')
launch(foo, 0)
launch(customNode, 100)
})
})
describe('effector-react', () => {
test('createComponent', () => {
const ImplicitObject = createComponent(
{
a: createStore<number>(0),
b: createStore<number>(1),
},
(props, state) => {
const createComponent_implicitObject_check1: number = state.a
const createComponent_implicitObject_check2: number = state.b
return null
},
)
const Store = createComponent(createStore(0), (props, state) => {
const createComponent_createStore_check1: number = state
return null
})
const list = createStore<{
[key: number]: {
text: string,
},
}>({})
const InitialProps = createComponent(
(initialProps: {id: number}) => {
const createComponent_initialProps_check1: number = initialProps.id
const createComponent_initialProps_check2: string = initialProps.id
const createComponent_initialProps_check3: string =
initialProps.unknownProp
return list.map(list => list[initialProps.id] || {text: 'Loading...'})
},
(_, state) => {
const createComponent_initialProps_check4: string = state.text
const createComponent_initialProps_check5: number = state.text
return null
},
)
})
test('createGate', () => {
const Foo = createGate<number>('foo')
const Bar = createGate<{a: number}>('bar')
const Baz = createGate<number | null>('baz', null)
const Component = () => {
useGate(Foo, 1)
useGate(Bar, 1)
useGate(Bar, {a: 1})
useGate(Bar, {})
useGate(Baz, null)
useGate(Baz, 1)
}
})
})
describe('effector-vue', () => {})
describe('@effector/forms', () => {
describe('createFormApi', () => {
const form = createFormApi({
fields: {
firstName: '',
lastName: '',
},
})
})
})
|
brad-jones/openapi-spec-builder | src/v2/Strict/ISchema.ts | import { FormatType, Type } from '../TypeDefs';
import IExternalDocs from './IExternalDocs';
import ISharedSchema from './ISharedSchema';
import IXml from './IXml';
/**
* The Schema Object allows the definition of input and output data types.
*
* These types can be objects, but also primitives and arrays. This object is
* based on the JSON Schema Specification Draft 4 and uses a predefined subset
* of it. On top of this subset, there are extensions provided by this
* specification to allow for more complete documentation.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schema-object
*/
interface ISchema extends ISharedSchema
{
/**
* A JSON Reference.
*
* @see https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03
*/
$ref?: string;
/**
* A title for the schema object.
*/
title?: string;
/**
* A short description of the schema object.
*
* GFM syntax can be used for rich text representation.
*/
description?: string;
/**
* Required if type is "array". Describes the type of items in the array.
*/
items?: ISchema;
/**
* Required if type is "object". A recursive structure,
* ie: each property of a schema is defined by another schema.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor64
*/
properties?: { [name: string]: ISchema };
/**
* Use this to describe objects with dynamic keys, much the same
* as the above typescript definition of the properties key.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor64
*/
additionalProperties?: boolean|ISchema;
/**
* Adds support for polymorphism. The discriminator is the schema property
* name that is used to differentiate between other schema that inherit
* this schema.
*
* The property name used MUST be defined at this schema and it MUST be in
* the required property list. When used, the value MUST be the name of this
* schema or any schema that inherits it.
*/
discriminator?: string;
/**
* Relevant only for Schema "properties" definitions.
* Declares the property as "read only".
*
* This means that it MAY be sent as part of a response but MUST NOT be sent
* as part of the request. Properties marked as readOnly being true SHOULD
* NOT be in the required list of the defined schema.
*
* Default value is false.
*/
readOnly?: boolean;
/**
* Adds Additional metadata to describe the
* XML representation format of this property.
*
* This MAY be used only on properties schemas.
* It has no effect on root schemas.
*/
xml?: IXml;
/**
* Additional external documentation.
*/
externalDocs?: IExternalDocs;
/**
* A free-form property to include an example of an instance for this schema.
*/
example?: any;
/**
* An object instance is valid against "maxProperties" if its number
* of properties is less than, or equal to, the value of this keyword.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor54
*/
maxProperties?: number;
/**
* An object instance is valid against "minProperties" if its number
* of properties is greater than, or equal to, the value of this keyword.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor57
*/
minProperties?: number;
/**
* An object instance is valid against this keyword if its property
* set contains all elements in this keyword's array value.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor61
*/
required?: string[];
/**
* An instance validates successfully against this keyword if it validates
* successfully against all schemas defined by this keyword's value.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor82
*/
allOf?: ISchema[];
}
export default ISchema;
|
brad-jones/openapi-spec-builder | src/v2/Strict/ISpec.ts | <gh_stars>1-10
import IExternalDocs from "./IExternalDocs";
import IInfo from "./IInfo";
import IParameter from "./IParameter";
import IPath from "./IPath";
import IResponses from './IResponses';
import ISchema from "./ISchema";
import ISecurityRequirment from './ISecurityRequirment';
import ISecuritySchema from "./ISecuritySchema";
import ITag from "./ITag";
import { Schemes } from '../TypeDefs';
/**
* This is the root document object for the API specification.
* It combines what previously was the Resource Listing and API Declaration
* (version 1.2 and earlier) together into one document.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object
*/
interface ISpec
{
/**
* Required. Specifies the Swagger Specification version being used.
*
* It can be used by the Swagger UI and other clients to interpret
* the API listing. The value MUST be "2.0".
*/
swagger: '2.0';
/**
* Required. Provides metadata about the API.
*
* The metadata can be used by the clients if needed.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#info-object
*/
info: IInfo;
/**
* The host (name or ip) serving the API.
*
* This MUST be the host only and does not include the scheme nor sub-paths.
* It MAY include a port. If the host is not included, the host serving the
* documentation is to be used (including the port).
*
* > NOTE: The host does not support path templating.
*/
host?: string;
/**
* The base path on which the API is served, which is relative to the host.
*
* If it is not included, the API is served directly under the host.
* The value MUST start with a leading slash (/).
*
* > NOTE: The basePath does not support path templating.
*/
basePath?: string;
/**
* The transfer protocol of the API.
*
* Values MUST be from the list: "http", "https", "ws", "wss".
* If the schemes is not included, the default scheme to be used
* is the one used to access the Swagger definition itself.
*/
schemes?: Schemes[];
/**
* A list of MIME types the APIs can consume.
*
* This is global to all APIs but can be overridden on specific API calls.
* Value MUST be as described under Mime Types.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#mime-types
*/
consumes?: string[];
/**
* A list of MIME types the APIs can produce.
*
* This is global to all APIs but can be overridden on specific API calls.
* Value MUST be as described under Mime Types.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#mime-types
*/
produces?: string[];
/**
* Required. The available paths and operations for the API.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#paths-object
*/
paths: { [name: string]: IPath };
/**
* An object to hold data types produced and consumed by operations.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#definitions-object
*/
definitions?: { [name: string]: ISchema };
/**
* An object to hold parameters that can be used across operations.
* This property does not define global parameters for all operations.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameters-definitions-object
*/
parameters?: { [name: string]: IParameter };
/**
* An object to hold responses that can be used across operations.
* This property does not define global responses for all operations.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responses-definitions-object
*/
responses?: IResponses;
/**
* Security scheme definitions that can be used across the specification.
*
* This does not enforce the security schemes on the operations
* and only serves to provide the relevant details for each scheme.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-definitions-object
*/
securityDefinitions?: { [name: string]: ISecuritySchema };
/**
* A declaration of which security schemes are applied for the API as a whole.
*
* The list of values describes alternative security schemes that can be
* used (that is, there is a logical OR between the security requirements).
* Individual operations can override this definition.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-requirement-object
*/
security?: ISecurityRequirment[];
/**
* A list of tags used by the specification with additional metadata.
*
* The order of the tags can be used to reflect on their order by the
* parsing tools. Not all tags that are used by the Operation Object must
* be declared. The tags that are not declared may be organized randomly
* or based on the tools' logic. Each tag name in the list MUST be unique.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#tag-object
*/
tags?: ITag[];
/**
* Additional external documentation.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#external-documentation-object
*/
externalDocs?: IExternalDocs;
}
export default ISpec;
|
brad-jones/openapi-spec-builder | src/v2/Modified/IItems.ts | <gh_stars>1-10
import { FormatType } from '../TypeDefs';
import ISharedSchema from './ISharedSchema';
/**
* A limited subset of JSON-Schema's items object.
*
* It is used by parameter definitions that are not
* located in "body" as well as header definitions.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#items-object
*/
interface IItems extends ISharedSchema
{
/**
* Required. The type of the object.
*
* The value MUST be one of "string", "number", "integer", "boolean",
* or "array". Files and models are not allowed.
*/
type: 'string' | 'number' | 'integer' | 'boolean' | 'array';
/**
* Required if type is "array". Describes the type of items in the array.
*/
items?: IItems;
/**
* Determines the format of the array if type array is used.
*
* Possible values are:
* - csv - comma separated values foo,bar.
* - ssv - space separated values foo bar.
* - tsv - tab separated values foo\tbar.
* - pipes - pipe separated values foo|bar.
*
* Default value is csv.
*/
collectionFormat?: 'csv' | 'ssv' | 'tsv' | 'pipes';
}
export default IItems;
|
brad-jones/openapi-spec-builder | src/v2/Modified/IExample.ts | /**
* Allows sharing examples for operation responses.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#example-object
*/
interface IExample
{
/**
* The name of the property MUST be one of the Operation
* produces values (either implicit or inherited).
*
* The value SHOULD be an example of what such a response would look like.
*/
[name: string]: any;
}
export default IExample;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IOpenAPI.ts | import ITag from './ITag';
import IInfo from './IInfo';
import IPath from './IPath';
import IServer from './IServer';
import IComponent from './IComponent';
import IExternalDocs from './IExternalDocs';
import ISecurityRequirement from './ISecurityRequirement';
import ISpecificationExtension from './ISpecificationExtension';
/**
* OpenAPI Document
*
* This is the root document object of the OpenAPI document.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#openapi-object
*/
export default interface IOpenAPI extends ISpecificationExtension
{
/**
* This string __MUST__ be the semantic version number of the OpenAPI
* Specification version that the OpenAPI document uses.
*
* The openapi field __SHOULD__ be used by tooling specifications and
* clients to interpret the OpenAPI document. This is not related to the
* API `info.version` string.
*
* __REQUIRED__
*/
openapi: string;
/**
* Provides metadata about the API.
*
* The metadata MAY be used by tooling as required.
*
* __REQUIRED__
*/
info: IInfo;
/**
* Provide connectivity information to a target server.
*
* If the servers property is not provided, or is an empty array,
* the default value would be a Server Object with a url value of `/`.
*/
servers?: IServer[];
/**
* The available paths and operations for the API.
*
* __REQUIRED__
*/
paths: IPath;
/**
* An element to hold various schemas for the specification.
*/
components?: IComponent;
/**
* A declaration of which security mechanisms can be used across the API.
*
* The list of values includes alternative security requirement objects
* that can be used. Only one of the security requirement objects need to
* be satisfied to authorize a request. Individual operations can override
* this definition.
*/
security?: ISecurityRequirement;
/**
* A list of tags used by the specification with additional metadata.
*
* The order of the tags can be used to reflect on their order by the
* parsing tools. Not all tags that are used by the Operation Object must
* be declared. The tags that are not declared MAY be organized randomly
* or based on the tools' logic. Each tag name in the list MUST be unique.
*/
tags?: ITag[];
/**
* Additional external documentation.
*/
externalDocs?: IExternalDocs;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IParameter.ts | import { ParameterLocation, SerializationStyle } from '../TypeDefs';
import ISchema from './ISchema';
import IExample from './IExample';
import IReference from './IReference';
import IMediaType from './IMediaType';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Describes a single operation parameter.
*
* A unique parameter is defined by a combination of a name and location.
*
* There are four possible parameter locations specified by the in field:
*
* - path: Used together with Path Templating, where the parameter value is
* actually part of the operation's URL. This does not include the
* host or base path of the API. For example, in /items/{itemId},
* the path parameter is itemId.
*
* - query: Parameters that are appended to the URL.
* For example, in /items?id=###, the query parameter is id.
*
* - header: Custom headers that are expected as part of the request.
* Note that RFC7230 states header names are case insensitive.
*
* - cookie: Used to pass a specific cookie value to the API.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameter-object
*/
export default interface IParameter extends ISpecificationExtension
{
/**
* The name of the parameter.
*
* Parameter names are case sensitive.
*
* If in is `path`, the name field __MUST__ correspond to the associated
* path segment from the path field in the Paths Object.
* See [Path Templating](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#pathTemplating) for further information.
*
* If in is `header` and the name field is `Accept`, `Content-Type` or
* `Authorization`, the parameter definition SHALL be ignored.
*
* For all other cases, the name corresponds to the parameter name used by the in property.
*
* __REQUIRED__
*/
name: string;
/**
* The location of the parameter.
*
* __REQUIRED__
*/
in: ParameterLocation;
/**
* A brief description of the parameter.
*
* This could contain examples of use.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
/**
* Determines whether this parameter is mandatory.
*
* If the parameter location is `path`, this property is __REQUIRED__ and
* its value __MUST__ be true.
*
* Otherwise, the property MAY be included and its default value is false.
*/
required?: boolean;
/**
* Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.
*/
deprecated?: boolean;
/**
* Sets the ability to pass empty-valued parameters.
*
* This is valid only for query parameters and allows
* sending a parameter with an empty value.
*
* Default value is false.
*
* If style is used, and if behavior is n/a (cannot be serialized),
* the value of allowEmptyValue SHALL be ignored.
*/
allowEmptyValue?: boolean;
/**
* Describes how the parameter value will be serialized
* depending on the type of the parameter value.
*
* Default values (based on value of in):
* - for query = form;
* - for path = simple;
* - for header = simple;
* - for cookie = form.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#style-values
*
* TODO: Ensure the rules defined in the above link are validated at runtime.
*/
style?: SerializationStyle;
/**
* When this is true, parameter values of type array or object generate
* separate parameters for each value of the array or key-value pair of
* the map.
*
* For other types of parameters this property has no effect.
*
* When style is form, the default value is true.
*
* For all other styles, the default value is false.
*/
explode?: boolean;
/**
* Determines whether the parameter value SHOULD allow reserved characters,
* as defined by RFC3986 `:/?#[]@!$&'()*+,;=` to be included without
* percent-encoding.
*
* This property only applies to parameters with an `in` value of `query`.
*
* The default value is false.
*/
allowReserved?: boolean;
/**
* The schema defining the type used for the parameter.
*/
schema?: ISchema | IReference;
/**
* Example of the media type.
*
* The example SHOULD match the specified schema and encoding properties
* if present. The example object is mutually exclusive of the examples
* object.
*
* Furthermore, if referencing a schema which contains an example,
* the example value SHALL override the example provided by the schema.
*
* To represent examples of media types that cannot naturally be represented
* in JSON or YAML, a string value can contain the example with escaping
* where necessary.
*/
example?: any;
/**
* Examples of the media type.
*
* Each example SHOULD contain a value in the correct format as specified
* in the parameter encoding. The examples object is mutually exclusive of
* the example object.
*
* Furthermore, if referencing a schema which contains an example,
* the examples value SHALL override the example provided by the schema.
*/
examples?: { [key: string]: IExample | IReference };
/**
* For more complex scenarios, the content property can define the
* media type and schema of the parameter.
*
* A parameter __MUST__ contain either a schema property,
* or a content property, but not both.
*
* When example or examples are provided in conjunction with the
* schema object, the example __MUST__ follow the prescribed
* serialization strategy for the parameter.
*
* The key is the media type and the value describes it.
*
* The map __MUST__ only contain one entry.
*/
content?: { [key: string]: IMediaType };
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IExternalDocs.ts | <reponame>brad-jones/openapi-spec-builder<filename>src/v3.0.0/Strict/IExternalDocs.ts<gh_stars>1-10
import ISpecificationExtension from './ISpecificationExtension';
/**
* Allows referencing an external resource for extended documentation.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#external-documentation-object
*/
export default interface IExternalDocs extends ISpecificationExtension
{
/**
* A short description of the target documentation.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
/**
* The URL for the target documentation.
*
* Value __MUST__ be in the format of a URL.
*
* __REQUIRED__
*/
url: string;
}
|
brad-jones/openapi-spec-builder | src/v2/Strict/IResponse.ts | import IExample from "./IExample";
import IHeader from "./IHeader";
import ISchema from "./ISchema";
/**
* Describes a single response from an API Operation.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#response-object
*/
interface IResponse
{
/**
* Required. A short description of the response.
*
* GFM syntax can be used for rich text representation.
*/
description: string;
/**
* A definition of the response structure.
*
* It can be a primitive, an array or an object. If this field does not
* exist, it means no content is returned as part of the response.
* As an extension to the Schema Object, its root type value may also
* be "file". This SHOULD be accompanied by a relevant produces mime-type.
*/
schema?: ISchema;
/**
* A list of headers that are sent with the response.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#headers-object
*/
headers?: { [name: string]: IHeader };
/**
* An example of the response message.
*/
examples?: IExample;
}
export default IResponse;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/ISecurityScheme.ts | <reponame>brad-jones/openapi-spec-builder
import { SecuritySchemeType, SecuritySchemeIn } from '../TypeDefs';
import IOAuthFlows from './IOAuthFlows';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Defines a security scheme that can be used by the operations.
*
* Supported schemes are HTTP authentication, an API key (either as a header or
* as a query parameter), OAuth2's common flows (implicit, password, application
* and access code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749),
* and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06).
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#securitySchemeObject
*/
export default interface ISecurityScheme extends ISpecificationExtension
{
/**
* The type of the security scheme.
*
* __REQUIRED__
*/
type: SecuritySchemeType;
/**
* A short description for security scheme.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* __MAY__ be used for rich text representation.
*/
description?: string;
/**
* The name of the header, query or cookie parameter to be used.
*
* __REQUIRED__ only when `type` is set to `apiKey`.
*/
name?: string;
/**
* The location of the API key.
*
* __REQUIRED__ only when `type` is set to `apiKey`.
*/
in?: SecuritySchemeIn;
/**
* The name of the HTTP Authorization scheme to be used in the Authorization
* header as defined in [RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1).
*
* __REQUIRED__ only when `type` is set to `http`.
*/
scheme?: string;
/**
* A hint to the client to identify how the bearer token is formatted.
*
* Bearer tokens are usually generated by an authorization server,
* so this information is primarily for documentation purposes.
*
* Applies only when `type` is set to `http`.
*/
bearerFormat?: string;
/**
* An object containing configuration information for the flow types supported.
*
* __REQUIRED__ only when `type` is set to `oauth2`.
*/
flow?: IOAuthFlows;
/**
* OpenId Connect URL to discover OAuth2 configuration values.
*
* This __MUST__ be in the form of a URL.
*
* __REQUIRED__ only when `type` is set to `openIdConnect`.
*/
openIdConnectUrl?: string;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/ISchema.ts | <reponame>brad-jones/openapi-spec-builder<filename>src/v3.0.0/Strict/ISchema.ts<gh_stars>1-10
import { DataType, DataFormat } from '../TypeDefs';
import IXml from './IXml';
import IReference from './IReference';
import IExternalDocs from './IExternalDocs';
import IDiscriminator from './IDiscriminator';
import ISpecificationExtension from './ISpecificationExtension';
/**
* The Schema Object allows the definition of input and output data types.
*
* These types can be objects, but also primitives and arrays. This object is
* an extended subset of the JSON Schema Specification Wright Draft 00.
*
* For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-wright-json-schema-00)
* and [JSON Schema Validation](https://tools.ietf.org/html/draft-wright-json-schema-validation-00).
* Unless stated otherwise, the property definitions follow the JSON Schema.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schema-object
*/
export default interface ISchema extends ISpecificationExtension
{
/**
* The value of this keyword __MUST__ be a string.
*
* It can be used to decorate a user interface with information about the
* data produced by this user interface. A title will preferably be short.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-6.1
*/
title?: string;
/**
* The value of this keyword __MUST__ be a string.
*
* It can be used to decorate a user interface with information about the
* data produced by this user interface. A description will provide
* explanation about the purpose of the instance described by this schema.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* __MAY__ be used for rich text representation.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-6.1
*/
description?: string;
/**
* The value of this keyword __MUST__ be a number, strictly greater than `0`.
*
* A numeric instance is valid only if division
* by this keyword's value results in an integer.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.1
*/
multipleOf?: number;
/**
* The value of this keyword __MUST__ be a number,
* representing an upper limit for a numeric instance.
*
* If the instance is a number, then this keyword validates if
* `exclusiveMaximum` is true and instance is less than the provided
* value, or else if the instance is less than or exactly equal to the
* provided value.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.2
*/
maximum?: number;
/**
* The value of this keyword __MUST__ be a boolean, representing whether
* the limit in `maximum` is exclusive or not. An undefined value is the
* same as `false`.
*
* If this keyword is `true`, then a numeric instance __SHOULD NOT__ be
* equal to the value specified in `maximum`. If this keyword is `false`
* (or not specified), then a numeric instance __MAY__ be equal to the
* value of `maximum`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.3
*/
exclusiveMaximum?: number;
/**
* The value of this keyword __MUST__ be a number,
* representing a lower limit for a numeric instance.
*
* If the instance is a number, then this keyword validates if
* `exclusiveMinimum` is `true` and instance is greater than the
* provided value, or else if the instance is greater than or
* exactly equal to the provided value.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.4
*/
minimum?: number;
/**
* The value of this keyword __MUST__ be a boolean, representing
* whether the limit in `minimum` is exclusive or not. An undefined
* value is the same as `false`.
*
* If this keyword is `true`, then a numeric instance __SHOULD NOT__ be
* equal to the value specified in `minimum`. If this keyword is `false`
* (or not specified), then a numeric instance MAY be equal to the value
* of `minimum`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.5
*/
exclusiveMinimum?: number;
/**
* The value of this keyword __MUST__ be a non-negative integer.
* The value of this keyword __MUST__ be an integer.
* This integer __MUST__ be greater than, or equal to, `0`.
*
* A string instance is valid against this keyword if its length is less
* than, or equal to, the value of this keyword.
*
* The length of a string instance is defined as the number of its
* characters as defined by [RFC 7159](https://tools.ietf.org/html/rfc7159).
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.6
*/
maxLength?: number;
/**
* A string instance is valid against this keyword if its length is
* greater than, or equal to, the value of this keyword.
*
* The length of a string instance is defined as the number of its
* characters as defined by [RFC 7159](https://tools.ietf.org/html/rfc7159).
*
* The value of this keyword __MUST__ be an integer.
* This integer __MUST__ be greater than, or equal to, 0.
*
* This keyword, if absent, may be considered as being present with
* integer value `0`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.7
*/
minLength?: number;
/**
* The value of this keyword __MUST__ be a string. This string __SHOULD__
* be a valid regular expression, according to the [ECMA 262 regular
* expression dialect](https://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5).
*
* A string instance is considered valid if the regular expression
* matches the instance successfully. Recall: regular expressions are
* not implicitly anchored.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.8
*/
pattern?: string;
/**
* The value of this keyword __MUST__ be an integer.
* This integer __MUST__ be greater than, or equal to, 0.
*
* An array instance is valid against `maxItems` if its size is less
* than, or equal to, the value of this keyword.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.10
*/
maxItems?: number;
/**
* The value of this keyword __MUST__ be an integer.
* This integer __MUST__ be greater than, or equal to, 0.
*
* An array instance is valid against `minItems` if its size is greater
* than, or equal to, the value of this keyword.
*
* If this keyword is not present, it may be considered present with a
* value of `0`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.11
*/
minItems?: number;
/**
* The value of this keyword __MUST__ be a boolean.
*
* If this keyword has boolean value `false`, the instance validates
* successfully. If it has boolean value `true`, the instance validates
* successfully if all of its elements are unique.
*
* If not present, this keyword may be considered present with boolean
* value `false`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.12
*/
uniqueItems?: boolean;
/**
* The value of this keyword __MUST__ be an integer.
* This integer __MUST__ be greater than, or equal to, `0`.
*
* An object instance is valid against `maxProperties"` if its number of
* properties is less than, or equal to, the value of this keyword.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.13
*/
maxProperties?: number;
/**
* The value of this keyword __MUST__ be an integer.
* This integer __MUST__ be greater than, or equal to, `0`.
*
* An object instance is valid against `minProperties` if its number of
* properties is greater than, or equal to, the value of this keyword.
*
* If this keyword is not present, it may be considered present with a
* value of `0`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.14
*/
minProperties?: number;
/**
* The value of this keyword __MUST__ be an array.
* This array __MUST__ have at least one element.
* Elements of this array __MUST__ be strings, and __MUST__ be unique.
*
* An object instance is valid against this keyword if its property set
* contains all elements in this keyword's array value.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.15
*/
required?: string[];
/**
* The value of this keyword __MUST__ be an array.
* This array __SHOULD__ have at least one element.
* Elements in the array __SHOULD__ be unique.
*
* Elements in the array __MAY__ be of any type, including `null`.
*
* An instance validates successfully against this keyword if its value
* is equal to one of the elements in this keyword's array value.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.20
*/
enum?: any[];
/**
* The value of this keyword __MUST__ be a string.
* Multiple types via an array are not supported.
*
* String values __MUST__ be one of the seven
* primitive types defined by the core specification.
*
* An instance matches successfully if its primitive type is one of the
* types defined by keyword. Recall: `number` includes `integer`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21
*/
type?: DataType;
/**
* This keyword's value __MUST__ be an array.
* This array __MUST__ have at least one element.
*
* Elements of the array __MUST__ be objects. Each object __MUST__ be a
* valid Reference Object or Schema Object and not a standard JSON Schema.
*
* An instance validates successfully against this keyword if it validates
* successfully against all schemas defined by this keyword's value.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.22
*/
allOf?: (ISchema | IReference)[];
/**
* This keyword's value __MUST__ be an array.
* This array __MUST__ have at least one element.
*
* Elements of the array __MUST__ be objects. Each object __MUST__ be a
* valid Reference Object or Schema Object and not a standard JSON Schema.
*
* An instance validates successfully against this keyword if it validates
* successfully against at least one schema defined by this keyword's value.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.23
*/
anyOf?: (ISchema | IReference)[];
/**
* This keyword's value __MUST__ be an array.
* This array __MUST__ have at least one element.
*
* Elements of the array __MUST__ be objects. Each object __MUST__ be a
* valid Reference Object or Schema Object and not a standard JSON Schema.
*
* An instance validates successfully against this keyword if it validates
* successfully against exactly one schema defined by this keyword's value.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.24
*/
oneOf?: (ISchema | IReference)[];
/**
* This keyword's value __MUST__ be an object. This object __MUST__ be a
* valid Reference Object or Schema Object and not a standard JSON Schema.
*
* An instance is valid against this keyword if it fails to validate
* successfully against the schema defined by this keyword.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.25
*/
not?: ISchema | IReference;
/**
* Value __MUST__ be an object and not an array.
*
* Inline or referenced schema __MUST__ be of a Schema Object
* and not a standard JSON Schema.
*
* `items` __MUST__ be present if the `type` is `array`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.9
*/
items?: ISchema | IReference;
/**
* Property definitions __MUST__ be a Schema Object
* and not a standard JSON Schema (inline or referenced).
*
* If absent, it can be considered the same as an empty object.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.16
*/
properties?: {[propertyName: string]: (ISchema | IReference)};
/**
* Value can be boolean or object.
*
* Inline or referenced schema __MUST__ be of a Schema Object
* and not a standard JSON Schema.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.18
*/
additionalProperties?: (ISchema | IReference)[];
/**
* While relying on JSON Schema's defined formats, the OAS offers a
* few additional predefined formats.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#dataTypeFormat
*/
format?: string | DataFormat;
/**
* The default value represents what would be assumed by the consumer of
* the input as the value of the schema if one is not provided.
*
* Unlike JSON Schema, the value __MUST__ conform to the defined type for
* the Schema Object defined at the same level. For example, if `type` is
* `string`, then `default` can be `"foo"` but cannot be `1`.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-6.2
*/
default?: any;
/**
* Allows sending a null value for the defined schema.
*
* Default value is `false`.
*/
nullable?: boolean;
/**
* Adds support for polymorphism. The discriminator is an object name that
* is used to differentiate between other schemas which may satisfy the
* payload description.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schemaComposition
*/
discriminator?: IDiscriminator;
/**
* Relevant only for Schema `properties` definitions.
*
* Declares the property as _"read only"_. This means that it __MAY__ be
* sent as part of a response but __SHOULD NOT__ be sent as part of the
* request.
*
* If the property is marked as `readOnly` being `true` and is in the
* required list, the required will take effect on the response only.
*
* A property __MUST NOT__ be marked as both `readOnly`
* and `writeOnly` being `true`.
*
* Default value is `false`.
*/
readOnly?: boolean;
/**
* Relevant only for Schema `properties` definitions.
*
* Declares the property as _"write only"_. Therefore, it __MAY__ be sent as
* part of a request but __SHOULD NOT__ be sent as part of the response.
*
* If the property is marked as `writeOnly` being `true` and is in the
* required list, the required will take effect on the request only.
*
* A property __MUST NOT__ be marked as both `readOnly`
* and `writeOnly` being `true`.
*
* Default value is `false`.
*/
writeOnly?: boolean;
/**
* This __MAY__ be used only on properties schemas.
*
* It has no effect on root schemas.
*
* Adds additional metadata to describe the XML representation of this property.
*/
xml?: IXml;
/**
* Additional external documentation for this schema.
*/
externalDocs?: IExternalDocs;
/**
* A free-form property to include an example of an instance for this schema.
*
* To represent examples that cannot be naturally represented in JSON or YAML,
* a string value can be used to contain the example with escaping where necessary.
*/
example?: any;
/**
* Specifies that a schema is deprecated and __SHOULD__
* be transitioned out of usage.
*
* Default value is `false`.
*/
deprecated?: boolean;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IMediaType.ts | import ISchema from './ISchema';
import IExample from './IExample';
import IEncoding from './IEncoding';
import IReference from './IReference';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Each Media Type Object provides schema and examples
* for the media type identified by its key.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#media-type-object
*/
export default interface IMediaType extends ISpecificationExtension
{
/**
* The schema defining the type used for the request body.
*/
schema?: ISchema | IReference;
/**
* Example of the media type.
*
* The example object SHOULD be in the correct format as specified by the
* media type. The example object is mutually exclusive of the examples
* object.
*
* Furthermore, if referencing a schema which contains an example,
* the example value SHALL override the example provided by the schema.
*/
example?: any;
/**
* Examples of the media type.
*
* Each example object SHOULD match the media type and specified schema
* if present. The examples object is mutually exclusive of the example
* object.
*
* Furthermore, if referencing a schema which contains an example,
* the examples value SHALL override the example provided by the schema.
*/
examples?: { [key: string]: IExample | IReference };
/**
* A map between a property name and its encoding information.
*
* The key, being the property name, __MUST__ exist in the schema as a
* property. The encoding object SHALL only apply to requestBody objects
* when the media type is `multipart` or `application/x-www-form-urlencoded`.
*/
encoding?: { [key: string]: IEncoding };
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IResponse.ts | import ILink from './ILink';
import IHeader from './IHeader';
import IReference from './IReference';
import IMediaType from './IMediaType';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Describes a single response from an API Operation,
* including design-time, static links to operations
* based on the response.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#response-object
*/
export default interface IResponse extends ISpecificationExtension
{
/**
* A short description of the response.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*
* __REQUIRED__
*/
description: string;
/**
* Maps a header name to its definition.
*
* RFC7230 states header names are case insensitive.
*
* If a response header is defined with the name "Content-Type",
* it SHALL be ignored.
*/
headers?: { [header: string]: IHeader | IReference };
/**
* A map containing descriptions of potential response payloads.
*
* The key is a media type or media type range and the value describes it.
* For responses that match multiple keys, only the most specific key is
* applicable. e.g. `text/plain` overrides `text/*`
*/
content?: { [header: string]: IMediaType };
/**
* A map of operations links that can be followed from the response.
*
* The key of the map is a short name for the link, following the naming
* constraints of the names for Component Objects.
*/
links?: { [header: string]: ILink | IReference };
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/ITag.ts | import IExternalDocs from './IExternalDocs';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Adds metadata to a single tag that is used by the Operation Object.
*
* It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#tag-object
*/
export default interface ITag extends ISpecificationExtension
{
/**
* The name of the tag.
*
* __REQUIRED__
*/
name: string;
/**
* A short description for the tag.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* __MAY__ be used for rich text representation.
*/
description?: string;
/**
* Additional external documentation for this tag.
*/
externalDocs?: IExternalDocs;
}
|
brad-jones/openapi-spec-builder | src/v2/Strict/IPath.ts | <filename>src/v2/Strict/IPath.ts
import IOperation from './IOperation';
import IParameter from './IParameter';
import IReference from './IReference';
/**
* Describes the operations available on a single path. A Path Item may be
* empty, due to ACL constraints. The path itself is still exposed to the
* documentation viewer but they will not know which operations and
* parameters are available.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#path-item-object
*/
interface IPath
{
/**
* A JSON Reference.
*
* @see https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03
*/
$ref?: string;
/**
* A definition of a GET operation on this path.
*/
get?: IOperation;
/**
* A definition of a PUT operation on this path.
*/
put?: IOperation;
/**
* A definition of a POST operation on this path.
*/
post?: IOperation;
/**
* A definition of a DELETE operation on this path.
*/
delete?: IOperation;
/**
* A definition of a OPTIONS operation on this path.
*/
options?: IOperation;
/**
* A definition of a HEAD operation on this path.
*/
head?: IOperation;
/**
* A definition of a PATCH operation on this path.
*/
patch?: IOperation;
/**
* A list of parameters that are applicable for
* all the operations described under this path.
*
* These parameters can be overridden at the operation level,
* but cannot be removed there. The list MUST NOT include duplicated
* parameters. A unique parameter is defined by a combination of a
* name and location. There can be one "body" parameter at most.
*/
parameters?: Array<IParameter | IReference>;
}
export default IPath;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IServer.ts | import IServerVariable from './IServerVariable';
import ISpecificationExtension from './ISpecificationExtension';
/**
* An object representing a Server.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#server-object
*/
export default interface IServer extends ISpecificationExtension
{
/**
* A URL to the target host.
*
* This URL supports Server Variables and MAY be relative, to indicate that
* the host location is relative to the location where the OpenAPI document
* is being served.
*
* Variable substitutions will be made when a variable is named in `{brackets}`.
*
* __REQUIRED__
*/
url: string;
/**
* An optional string describing the host designated by the URL.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
/**
* A map between a variable name and its value.
*
* The value is used for substitution in the server's URL template.
*/
variables?: { [v: string]: IServerVariable };
}
|
brad-jones/openapi-spec-builder | src/v2/Strict/IXml.ts | <reponame>brad-jones/openapi-spec-builder
/**
* A metadata object that allows for more fine-tuned XML model definitions.
*
* When using arrays, XML element names are not inferred (for singular/plural
* forms) and the name property should be used to add that information.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#xml-object
*/
interface IXml
{
/**
* Replaces the name of the element/attribute
* used for the described schema property.
*
* When defined within the Items Object (items), it will affect the name of
* the individual XML elements within the list. When defined alongside type
* being array (outside the items), it will affect the wrapping element and
* only if wrapped is true. If wrapped is false, it will be ignored.
*/
name?: string;
/**
* The URL of the namespace definition. Value SHOULD be in the form of a URL.
*/
namespace?: string;
/**
* The prefix to be used for the name.
*/
prefix?: string;
/**
* Declares whether the property definition translates
* to an attribute instead of an element.
*
* Default value is false.
*/
attribute?: boolean;
/**
* MAY be used only for an array definition. Signifies whether the array is
* wrapped (for example, <books><book/><book/></books>) or unwrapped (<book/><book/>).
*
* Default value is false.
*
* The definition takes effect only when defined
* alongside type being array (outside the items).
*/
wrapped?: boolean;
}
export default IXml;
|
brad-jones/openapi-spec-builder | src/v2/TypeDefs.ts | <reponame>brad-jones/openapi-spec-builder
/**
* The transfer protocol of the API.
*
* Values MUST be from the list: "http", "https", "ws", "wss".
* If the schemes is not included, the default scheme to be used
* is the one used to access the Swagger definition itself.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object
*/
export type Schemes =
'http' |
'https' |
'ws' |
'wss'
;
/**
* Primitive data types in the Swagger Specification are based on the types
* supported by the JSON-Schema Draft 4. Models are described using the Schema
* Object which is a subset of JSON Schema Draft 4.
*
* An additional primitive data type "file" is used by the Parameter Object
* and the Response Object to set the parameter type or the response as
* being a file.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types
*/
export type Type =
'array' |
'boolean' |
'integer' |
'number' |
'null' |
'object' |
'string' |
'file'
;
/**
* Swagger uses several known formats to more finely define the data type
* being used. However, the format property is an open string-valued property,
* and can have any value to support documentation needs. Formats such as
* "email", "uuid", etc., can be used even though they are not defined by
* this specification.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types
*/
export type FormatType =
'int32' |
'int64' |
'float' |
'double' |
'byte' |
'binary' |
'date' |
'date-time' |
'password'
;
|
brad-jones/openapi-spec-builder | src/v2/Strict/IReference.ts | <gh_stars>1-10
interface IReference
{
/**
* A JSON Reference.
*
* @see https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03
*/
$ref?: string;
}
export default IReference;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IEncoding.ts | <filename>src/v3.0.0/Strict/IEncoding.ts
import { SerializationStyle } from '../TypeDefs';
import IHeader from './IHeader';
import IReference from './IReference';
import ISpecificationExtension from './ISpecificationExtension';
/**
* A single encoding definition applied to a single schema property.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#encoding-object
*/
export default interface IEncoding extends ISpecificationExtension
{
/**
* The Content-Type for encoding a specific property.
*
* Default value depends on the property type:
*
* - for string with format being binary = `application/octet-stream`;
* - for other primitive types = `text/plain`;
* - for object = `application/json`;
* - for array = the default is defined based on the inner type.
*
* The value can be a specific media type (e.g. `application/json`),
* a wildcard media type (e.g. `image/*`), or a comma-separated list
* of the two types.
*/
contentType?: string;
/**
* A map allowing additional information to be provided as headers,
* for example Content-Disposition.
*
* Content-Type is described separately and SHALL be ignored in this section.
*
* This property SHALL be ignored if the request body media type is not a multipart.
*/
headers?: { [key: string]: IHeader | IReference };
/**
* Describes how a specific property value will be
* serialized depending on its type.
*
* See Parameter Object for details on the style property.
*
* The behavior follows the same values as query parameters,
* including default values.
*
* This property SHALL be ignored if the request body media type
* is not `application/x-www-form-urlencoded`.
*
* TODO: Instead of inline string literals we should
* create some more shared types.
*/
style?: SerializationStyle;
/**
* When this is true, property values of type array or object generate
* separate parameters for each value of the array, or key-value-pair
* of the map.
*
* For other types of properties this property has no effect.
*
* When style is `form`, the default value is `true`.
* For all other styles, the default value is `false`.
*
* This property SHALL be ignored if the request body media type
* is not `application/x-www-form-urlencoded`.
*/
explode?: boolean;
/**
* Determines whether the parameter value SHOULD allow reserved characters,
* as defined by RFC3986 `:/?#[]@!$&'()*+,;=` to be included without
* percent-encoding.
*
* The default value is `false`.
*
* This property SHALL be ignored if the request body media type
* is not `application/x-www-form-urlencoded`.
*/
allowReserved?: boolean;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IOAuthFlows.ts | import IOAuthFlow from './IOAuthFlow';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Allows configuration of the supported OAuth Flows.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#oauth-flows-object
*/
export default interface IOAuthFlows extends ISpecificationExtension
{
/**
* Configuration for the OAuth Implicit flow
*/
implicit?: IOAuthFlow;
/**
* Configuration for the OAuth Resource Owner Password flow
*/
password?: IOAuthFlow;
/**
* Configuration for the OAuth Client Credentials flow.
*
* Previously called `application` in OpenAPI 2.0.
*/
clientCredentials?: IOAuthFlow;
/**
* Configuration for the OAuth Authorization Code flow.
*
* Previously called `accessCode` in OpenAPI 2.0.
*/
authorizationCode?: IOAuthFlow;
}
|
brad-jones/openapi-spec-builder | src/v2/Modified/ILicense.ts | <reponame>brad-jones/openapi-spec-builder
/**
* License information for the exposed API.
*
* @https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#license-object
*/
interface ILicense
{
/**
* Required. The license name used for the API.
*/
name?: string;
/**
* A URL to the license used for the API.
*
* MUST be in the format of a URL.
*/
url?: string;
}
export default ILicense;
|
brad-jones/openapi-spec-builder | examples/pet-store/pet-store.ts | <filename>examples/pet-store/pet-store.ts
import IEndpoint from '../../src/v2/Modified/IEndpoint';
import IParameter from '../../src/v2/Modified/IParameter';
import IResponse from '../../src/v2/Modified/IResponse';
import ISchema from '../../src/v2/Modified/ISchema';
import OpenApiSpecBuilder from '../../src/OpenApiSpecBuilder';
let pet: ISchema =
{
type: 'object',
required: ['id', 'name'],
properties:
{
id:
{
type: 'integer',
format: 'int64'
},
name:
{
type: 'string'
},
tag:
{
type: 'string'
}
}
};
let pets: ISchema =
{
type: 'array',
items: pet
};
let defaultResponse: IResponse =
{
statusCode: 0,
description: 'unexpected error',
schema:
{
type: 'object',
required: ['code', 'message'],
properties:
{
code:
{
type: 'integer',
format: 'int32'
},
message:
{
type: 'string'
}
}
}
};
let parameter: IParameter =
{
name: 'limit',
in: 'query',
description: 'How many items to return at one time (max 100)',
required: false,
type: 'integer',
format: 'int32'
};
let endpoint: IEndpoint =
{
path: '/pets',
method: 'get',
summary: 'List all pets',
operationId: 'listPets',
tags: ['pets'],
parameters:[ parameter ],
responses:
[
defaultResponse,
{
statusCode: 200,
description: 'An paged array of pets',
headers:
[
{
name: 'x-next',
type: 'string',
description: 'A link to the next page of responses'
}
],
schema: pets
}
]
};
let petstore = new OpenApiSpecBuilder
({
info:
{
version: '1.0.0',
title: 'Swagger Petstore',
license:
{
name: 'MIT'
}
},
host: 'petstore.swagger.io',
basePath: '/v1',
schemes: ['https'],
consumes:[ 'application/json' ],
produces:[ 'application/json' ],
endpoints:
[
endpoint,
{
path: '/pets',
method: 'post',
summary: 'Create a pet',
operationId: 'createPets',
tags: ['pets'],
parameters:[ parameter ],
responses:
[
defaultResponse,
{
statusCode: 201,
description: 'Null response'
}
]
},
{
path: '/pets/{petId}',
method: 'get',
summary: 'Info for a specific pet',
operationId: 'showPetById',
tags: ['pets'],
parameters:
[
parameter,
{
name: 'petId',
in: 'path',
required: true,
description: 'The id of the pet to retrieve',
type: 'string'
}
],
responses:
[
defaultResponse,
{
statusCode: 200,
description: 'Expected response to a valid request',
schema: pets
}
]
}
]
});
petstore.toJson().then(v => console.log(v)).catch(e => console.error(JSON.stringify(e)));
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IRequestBody.ts | import IMediaType from './IMediaType';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Describes a single request body.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#request-body-object
*/
export default interface IRequestBody extends ISpecificationExtension
{
/**
* A brief description of the request body.
*
* This could contain examples of use.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
/**
* The content of the request body.
*
* The key is a media type or media type range and the value describes it.
*
* For requests that match multiple keys, only the most specific key is
* applicable. e.g. `text/plain` overrides `text/*`
*
* __REQUIRED__
*/
content: { [key: string]: IMediaType };
/**
* Determines if the request body is required in the request.
*
* Defaults to false.
*/
required?: boolean;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IInfo.ts | <reponame>brad-jones/openapi-spec-builder
import IContact from './IContact';
import ILicense from './ILicense';
import ISpecificationExtension from './ISpecificationExtension';
/**
* The object provides metadata about the API.
*
* The metadata MAY be used by the clients if needed, and MAY be presented in
* editing or documentation generation tools for convenience.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#infoObject
*/
export default interface IInfo extends ISpecificationExtension
{
/**
* The title of the application.
*
* __REQUIRED__
*/
title: string;
/**
* A short description of the application.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* __MAY__ be used for rich text representation.
*/
description?: string;
/**
* A URL to the Terms of Service for the API.
*
* __MUST__ be in the format of a URL.
*/
termsOfService?: string;
/**
* The contact information for the exposed API.
*/
contact?: IContact;
/**
* The license information for the exposed API.
*/
license?: ILicense;
/**
* The version of the OpenAPI document.
*
* Which is distinct from the OpenAPI Specification
* version or the API implementation version.
*
* __REQUIRED__
*/
version: string;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IPath.ts | <reponame>brad-jones/openapi-spec-builder
import IPathItem from './IPathItem';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Holds the relative paths to the individual endpoints and their operations.
*
* The path is appended to the URL from the Server Object in order to construct
* the full URL. The Paths MAY be empty, due to ACL constraints.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#paths-object
*/
export default interface IPath extends ISpecificationExtension
{
/**
* A relative path to an individual endpoint.
*
* The field name __MUST__ begin with a slash.
*
* The path is appended (no relative URL resolution) to the expanded URL
* from the Server Object's url field in order to construct the full URL.
*
* Path templating is allowed. When matching URLs, concrete (non-templated)
* paths would be matched before their templated counterparts.
*
* Templated paths with the same hierarchy but different templated names
* __MUST NOT__ exist as they are identical. In case of ambiguous matching,
* it's up to the tooling to decide which one to use.
*/
[path: string]: IPathItem;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IContact.ts | import ISpecificationExtension from './ISpecificationExtension';
/**
* Contact information for the exposed API.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#contact-object
*/
export default interface IContact extends ISpecificationExtension
{
/**
* The identifying name of the contact person/organization.
*/
name?: string;
/**
* The URL pointing to the contact information.
*
* __MUST__ be in the format of a URL.
*/
url?: string;
/**
* The email address of the contact person/organization.
*
* __MUST__ be in the format of an email address.
*/
email?: string;
}
|
brad-jones/openapi-spec-builder | src/v2/Modified/IParameter.ts | <gh_stars>1-10
import { FormatType } from '../TypeDefs';
import IItems from './IItems';
import ISchema from './ISchema';
import ISharedSchema from './ISharedSchema';
/**
* Describes a single operation parameter.
*
* A unique parameter is defined by a combination of a name and location.
* There are five possible parameter types, "path", "query", "header",
* "body", "form".
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object
*/
interface IParameter extends ISharedSchema
{
/**
* Required. The name of the parameter. Parameter names are case sensitive.
*
* If in is "path", the name field MUST correspond to the associated path
* segment from the path field in the Paths Object.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#path-templating
*
* For all other cases, the name corresponds to the parameter name used
* based on the in property.
*/
name: string;
/**
* Required. The location of the parameter.
*
* Possible values are "query", "header", "path", "formData" or "body".
*/
in: 'query' | 'header' | 'path' | 'formData' | 'body';
/**
* A brief description of the parameter. This could contain examples of use.
*
* GFM syntax can be used for rich text representation.
*/
description?: string;
/**
* Determines whether this parameter is mandatory.
*
* If the parameter is in "path", this property is required and its value
* MUST be true. Otherwise, the property MAY be included and its default
* value is false.
*/
required?: boolean;
/**
* The schema defining the type used for the body parameter.
*
* > NOTE: Required when `in` is set to `body`.
*/
schema?: ISchema;
/**
* Required when `in` is not set to `body`. The type of the parameter.
*
* Since the parameter is not located at the request body, it is limited to
* simple types (that is, not an object). The value MUST be one of "string",
* "number", "integer", "boolean", "array" or "file".
*
* If type is "file", the consumes MUST be either "multipart/form-data",
* "application/x-www-form-urlencoded" or both and the parameter MUST
* e in "formData".
*/
type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'file';
/**
* Sets the ability to pass empty-valued parameters.
*
* This is valid only for either query or formData parameters and allows you
* to send a parameter with a name only or an empty value.
*
* Default value is false.
*/
allowEmptyValue?: boolean;
/**
* Required if type is "array". Describes the type of items in the array.
*/
items?: IItems;
/**
* Determines the format of the array if type array is used.
*
* Possible values are:
* - csv - comma separated values foo,bar.
* - ssv - space separated values foo bar.
* - tsv - tab separated values foo\tbar.
* - pipes - pipe separated values foo|bar.
* - multi - corresponds to multiple parameter instances instead of
* multiple values for a single instance foo=bar&foo=baz.
* This is valid only for parameters in "query" or "formData".
*
* Default value is csv.
*/
collectionFormat?: 'csv' | 'ssv' | 'tsv' | 'pipes' | 'multi';
}
export default IParameter;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IReference.ts | /**
* A simple object to allow referencing other components in the specification,
* internally and externally.
*
* The Reference Object is defined by JSON Reference
* and follows the same structure, behavior and rules.
*
* For this specification, reference resolution is accomplished as defined by
* the JSON Reference specification and not by the JSON Schema specification.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#reference-object
*/
export default interface IReference
{
/**
* The reference string.
*
* __REQUIRED__
*/
$ref: string;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IServerVariable.ts | <gh_stars>1-10
import ISpecificationExtension from './ISpecificationExtension';
/**
* An object representing a Server Variable for server URL template substitution.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#server-variable-object
*/
export default interface IServerVariable
{
/**
* An enumeration of string values to be used if the
* substitution options are from a limited set.
*/
enum?: string[];
/**
* The default value to use for substitution, and to send,
* if an alternate value is not supplied.
*
* Unlike the Schema Object's default, this value
* __MUST__ be provided by the consumer.
*
* __REQUIRED__
*/
default: string;
/**
* An optional description for the server variable.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
}
|
brad-jones/openapi-spec-builder | src/v2/Strict/IOperation.ts | import IExternalDocs from './IExternalDocs';
import IParameter from './IParameter';
import IReference from './IReference';
import IResponses from './IResponses';
import ISecurityRequirment from './ISecurityRequirment';
import { Schemes } from '../TypeDefs';
/**
* Describes a single API operation on a path.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operation-object
*/
interface IOperation
{
/**
* A list of tags for API documentation control.
*
* Tags can be used for logical grouping of operations
* by resources or any other qualifier.
*/
tags?: string[];
/**
* A short summary of what the operation does.
*
* For maximum readability in the swagger-ui,
* this field SHOULD be less than 120 characters.
*/
summary?: string;
/**
* A verbose explanation of the operation behavior.
*
* GFM syntax can be used for rich text representation.
*/
description?: string;
/**
* Additional external documentation for this operation.
*/
externalDocs?: IExternalDocs;
/**
* Unique string used to identify the operation.
*
* The id MUST be unique among all operations described in the API.
* Tools and libraries MAY use the operationId to uniquely identify
* an operation, therefore, it is recommended to follow common
* programming naming conventions.
*/
operationId?: string;
/**
* A list of MIME types the operation can consume.
*
* This overrides the consumes definition at the Swagger Object.
* An empty value MAY be used to clear the global definition.
* Value MUST be as described under Mime Types.
*/
consumes?: string[];
/**
* A list of MIME types the operation can produce.
*
* This overrides the produces definition at the Swagger Object.
* An empty value MAY be used to clear the global definition.
* Value MUST be as described under Mime Types.
*/
produces?: string[];
/**
* A list of parameters that are applicable for this operation.
*
* If a parameter is already defined at the Path Item, the new definition
* will override it, but can never remove it. The list MUST NOT include
* duplicated parameters.
*
* A unique parameter is defined by a combination of a name and location.
* There can be one "body" parameter at most.
*/
parameters?: Array<IParameter | IReference>;
/**
* Required. The list of possible responses as they are returned from
* executing this operation.
*/
responses: IResponses;
/**
* The transfer protocol for the operation.
*
* Values MUST be from the list: "http", "https", "ws", "wss".
* The value overrides the Swagger Object schemes definition.
*/
schemes?: Schemes[];
/**
* Declares this operation to be deprecated.
*
* Usage of the declared operation should be refrained.
*
* Default value is false.
*/
deprecated?: boolean;
/**
* A declaration of which security schemes are applied for this operation.
*
* The list of values describes alternative security schemes that can be
* used (that is, there is a logical OR between the security requirements).
*
* This definition overrides any declared top-level security.
* To remove a top-level security declaration, an empty array can be used.
*/
security?: ISecurityRequirment[];
}
export default IOperation;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IOperation.ts | import IServer from './IServer';
import ICallback from './ICallback';
import IResponses from './IResponses';
import IReference from './IReference';
import IParameter from './IParameter';
import IRequestBody from './IRequestBody';
import IExternalDocs from './IExternalDocs';
import ISecurityRequirement from './ISecurityRequirement';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Describes a single API operation on a path.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#operation-object
*/
export default interface IOperation extends ISpecificationExtension
{
/**
* A list of tags for API documentation control.
*
* Tags can be used for logical grouping of operations by resources or any other qualifier.
*/
tags?: string[];
/**
* A short summary of what the operation does.
*/
summary?: string;
/**
* A verbose explanation of the operation behavior.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
/**
* Additional external documentation for this operation.
*/
externalDocs?: IExternalDocs;
/**
* Unique string used to identify the operation.
*
* The id __MUST__ be unique among all operations described in the API.
*
* Tools and libraries MAY use the operationId to uniquely identify an operation,
* therefore, it is RECOMMENDED to follow common programming naming conventions.
*/
operationId?: string;
/**
* A list of parameters that are applicable for this operation.
*
* If a parameter is already defined at the Path Item, the new definition
* will override it but can never remove it.
*
* The list __MUST NOT__ include duplicated parameters.
*
* A unique parameter is defined by a combination of a name and location.
*
* The list can use the Reference Object to link to parameters that are
* defined at the OpenAPI Object's components/parameters.
*/
parameters?: (IParameter | IReference)[];
/**
* The request body applicable for this operation.
*
* The requestBody is only supported in HTTP methods where the HTTP 1.1
* specification RFC7231 has explicitly defined semantics for request bodies.
*
* In other cases where the HTTP spec is vague,
* requestBody SHALL be ignored by consumers.
*/
requestBody?: IRequestBody | IReference;
/**
* The list of possible responses as they are returned from executing this operation.
*
* __REQUIRED__
*/
responses: IResponses;
/**
* A map of possible out-of band callbacks related to the parent operation.
*
* The key is a unique identifier for the Callback Object.
*
* Each value in the map is a Callback Object that describes a request that
* may be initiated by the API provider and the expected responses.
*
* The key value used to identify the callback object is an expression,
* evaluated at runtime, that identifies a URL to use for the callback operation.
*/
callbacks?: { [callback: string]: ICallback | IReference };
/**
* Declares this operation to be deprecated.
*
* Consumers SHOULD refrain from usage of the declared operation.
*
* Default value is false.
*/
deprecated?: boolean;
/**
* A declaration of which security mechanisms can be used for this operation.
*
* The list of values includes alternative security requirement
* objects that can be used.
*
* Only one of the security requirement objects need to be
* satisfied to authorize a request.
*
* This definition overrides any declared top-level security.
*
* To remove a top-level security declaration, an empty array can be used.
*/
security?: ISecurityRequirement[];
/**
* An alternative server array to service this operation.
*
* If an alternative server object is specified at the Path Item Object
* or Root level, it will be overridden by this value.
*/
servers?: IServer[];
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IComponent.ts | import ILink from './ILink';
import ISchema from './ISchema';
import IHeader from './IHeader';
import IExample from './IExample';
import IResponse from './IResponse';
import ICallback from './ICallback';
import IReference from './IReference';
import IParameter from './IParameter';
import IRequestBody from './IRequestBody';
import ISecurityScheme from './ISecurityScheme';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Holds a set of reusable objects for different aspects of the OAS.
*
* All objects defined within the components object will have no effect on the
* API unless they are explicitly referenced from properties outside the
* components object.
*
* > NOTE: All the fixed fields declared, are objects that __MUST__ use keys
* that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`
*
* TODO: Implement this regex check in the builder at runtime.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#components-object
*/
export default interface IComponent extends ISpecificationExtension
{
/**
* An object to hold reusable Schema Objects.
*/
schemas?: { [schema: string]: ISchema | IReference };
/**
* An object to hold reusable Response Objects.
*/
responses?: { [response: string]: IResponse | IReference };
/**
* An object to hold reusable Parameter Objects.
*/
parameters?: { [parameter: string]: IParameter | IReference };
/**
* An object to hold reusable Example Objects.
*/
examples?: { [example: string]: IExample | IReference };
/**
* An object to hold reusable Request Body Objects.
*/
requestBodies?: { [request: string]: IRequestBody | IReference };
/**
* An object to hold reusable Header Objects.
*/
headers?: { [header: string]: IHeader | IReference };
/**
* An object to hold reusable Security Scheme Objects.
*/
securitySchemes?: { [securityScheme: string]: ISecurityScheme | IReference };
/**
* An object to hold reusable Link Objects.
*/
links?: { [link: string]: ILink | IReference };
/**
* An object to hold reusable Callback Objects.
*/
callbacks?: { [callback: string]: ICallback | IReference };
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IDiscriminator.ts | /**
* When request bodies or response payloads may be one of a number of different
* schemas, a discriminator object can be used to aid in serialization,
* deserialization, and validation.
*
* The discriminator is a specific object in a schema which is used to inform
* the consumer of the specification of an alternative schema based on the value
* associated with it.
*
* When using the discriminator, inline schemas will not be considered.
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#discriminator-object
*/
export default interface IDiscriminator
{
/**
* The name of the property in the payload that will hold the discriminator value.
*
* __REQUIRED__
*/
propertyName: string;
/**
* An object to hold mappings between payload values and schema names or references.
*/
mapping?: {[key: string]: string };
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IXml.ts | import ISpecificationExtension from './ISpecificationExtension';
/**
* A metadata object that allows for more fine-tuned XML model definitions.
*
* When using arrays, XML element names are not inferred (for singular/plural
* forms) and the name property __SHOULD__ be used to add that information.
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#xml-object
*/
export default interface IXml extends ISpecificationExtension
{
/**
* Replaces the name of the element/attribute used for the described schema property.
*
* When defined within `items`, it will affect the name of the individual
* XML elements within the list. When defined alongside `type` being `array`
* (outside the `items`), it will affect the wrapping element and only if
* `wrapped` is `true`. If `wrapped` is `false`, it will be ignored.
*/
name?: string;
/**
* The URI of the namespace definition.
*
* Value __MUST__ be in the form of an absolute URI.
*/
namespace?: string;
/**
* The prefix to be used for the [name](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#xmlName).
*/
prefix?: string;
/**
* Declares whether the property definition translates
* to an attribute instead of an element.
*
* Default value is `false`.
*/
attribute?: boolean;
/**
* __MAY__ be used only for an array definition. Signifies whether the array
* is wrapped (for example, `<books><book/><book/></books>`) or unwrapped
* (`<book/><book/>`).
*
* Default value is `false`.
*
* The definition takes effect only when defined alongside `type` being
* `array` (outside the `items`).
*/
wrapped?: boolean;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IPathItem.ts | <filename>src/v3.0.0/Strict/IPathItem.ts
import IServer from './IServer';
import IOperation from './IOperation';
import IParameter from './IParameter';
import IReference from './IReference';
import ISpecificationExtension from './ISpecificationExtension';
/**
* Describes the operations available on a single path.
*
* A Path Item MAY be empty, due to ACL constraints.
*
* The path itself is still exposed to the documentation viewer but they will
* not know which operations and parameters are available.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#path-item-object
*/
export default interface IPathItem extends ISpecificationExtension
{
/**
* Allows for an external definition of this path item.
*
* The referenced structure __MUST__ be in the format of a Path Item Object.
* If there are conflicts between the referenced definition and this Path
* Item's definition, the behavior is undefined.
*/
$ref?: string;
/**
* An optional, string summary, intended to apply to all operations in this path.
*/
summary?: string;
/**
* An optional, string description, intended to apply to all operations in this path.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
/**
* A definition of a GET operation on this path.
*/
get?: IOperation;
/**
* A definition of a PUT operation on this path.
*/
put?: IOperation;
/**
* A definition of a POST operation on this path.
*/
post?: IOperation;
/**
* A definition of a DELETE operation on this path.
*/
delete?: IOperation;
/**
* A definition of a OPTIONS operation on this path.
*/
options?: IOperation;
/**
* A definition of a HEAD operation on this path.
*/
head?: IOperation;
/**
* A definition of a PATCH operation on this path.
*/
patch?: IOperation;
/**
* A definition of a TRACE operation on this path.
*/
trace?: IOperation;
/**
* An alternative server array to service all operations in this path.
*/
servers?: IServer[];
/**
* A list of parameters that are applicable for all the
* operations described under this path.
*
* These parameters can be overridden at the operation level,
* but cannot be removed there.
*
* The list __MUST NOT__ include duplicated parameters.
*
* A unique parameter is defined by a combination of a name and location.
*
* The list can use the Reference Object to link to parameters that are
* defined at the OpenAPI Object's components/parameters.
*/
parameters?: (IParameter | IReference)[];
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/ISecurityRequirement.ts | /**
* Lists the required security schemes to execute this operation.
*
* The name used for each property __MUST__ correspond to a security scheme
* declared in the Security Schemes under the Components Object.
*
* Security Requirement Objects that contain multiple schemes require that all
* schemes __MUST__ be satisfied for a request to be authorized. This enables
* support for scenarios where multiple query parameters or HTTP headers are
* required to convey security information.
*
* When a list of Security Requirement Objects is defined on the Open API object
* or Operation Object, only one of Security Requirement Objects in the list
* needs to be satisfied to authorize the request.
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#security-requirement-object
*/
export default interface ISecurityRequirement
{
/**
* Each name __MUST__ correspond to a security scheme which is declared in
* the Security Schemes under the Components Object.
*
* If the security scheme is of type `oauth2` or `openIdConnect`, then the
* value is a list of scope names required for the execution.
*
* For other security scheme types, the array __MUST__ be empty.
*/
[name: string]: [string];
}
|
brad-jones/openapi-spec-builder | src/OpenApiSpecBuilder.ts | <reponame>brad-jones/openapi-spec-builder<filename>src/OpenApiSpecBuilder.ts<gh_stars>1-10
import deepEqual = require('deep-equal');
import * as swagger from 'swagger-tools';
import IHeader from './v2/Strict/IHeader';
import IParameter from './v2/Strict/IParameter';
import IReference from './v2/Strict/IReference';
import IResponses from './v2/Strict/IResponses';
import ISchema from './v2/Strict/ISchema';
import Modifiedv2ISpec from './v2/Modified/ISpec';
import Strictv2ISpec from './v2/Strict/ISpec';
import traverse = require('traverse');
import md5 = require('md5');
export default class OpenApiSpecBuilder
{
/**
* After the spec builder has worked it's magic,
* this property will contain a strict open api specification.
*/
protected strictSpec: Strictv2ISpec;
/**
* Give us a typescript friendly version of the OpenAPI Spec
* and we will convert it into a Strict version 2.0 Spec Document.
*/
public constructor(protected modifiedSpec: Modifiedv2ISpec) {}
/**
* Perform the conversion between a Modified Spec & a Strict Spec.
*/
public async getStrictSpec(): Promise<Strictv2ISpec>
{
return new Promise<Strictv2ISpec>((resolve, reject) =>
{
// Resolve straight away if we have already done the conversion.
if (this.strictSpec != null) return resolve(this.strictSpec);
// Run our conversion methods over the modified spec.
this.addSwaggerVersion();
this.convertModifiedEndpointsToStrictPaths();
this.convertModifiedResponsesToStrictResponses();
this.convertModifiedHeadersToStrictHeaders();
//this.deDuplicateAndMinify();
// While the typescript interfaces go along way to helping provide
// a valid open api specification, there are certain rules & edge
// cases that can only be validated at RunTime.
(<any>swagger.specs.v2).validate(this.modifiedSpec, (error, result) =>
{
if (error) return reject(error);
if (typeof result !== 'undefined') return reject(result);
this.strictSpec = <any>this.modifiedSpec;
resolve(this.strictSpec);
});
});
}
/**
* Converts the strict spec to a JSON String,
* ready to be consumed by swagger-ui or other tools.
*/
public async toJson(): Promise<string>
{
return JSON.stringify(await this.getStrictSpec());
}
/**
* Our modified spec does not define the swagger version,
* it's static anyway so we automatically add it in.
*/
protected addSwaggerVersion()
{
// Here we create a new object where the swagger key is first.
// It's purely a visual thing to make the final JSON output look familiar.
let spec = this.modifiedSpec;
this.modifiedSpec = <any>{swagger:'2.0'};
for (let key in spec) this.modifiedSpec[key] = spec[key];
}
protected convertModifiedEndpointsToStrictPaths()
{
let endpoints = this.modifiedSpec.endpoints;
delete this.modifiedSpec.endpoints;
this.modifiedSpec['paths'] = {};
for (let endpoint of endpoints)
{
if (this.modifiedSpec['paths'][endpoint.path] == null)
{
this.modifiedSpec['paths'][endpoint.path] = {};
}
let newOperation = Object.assign({}, endpoint);
delete newOperation.path; delete newOperation.method;
this.modifiedSpec['paths'][endpoint.path][endpoint.method] = newOperation;
}
}
/**
* Replace our modified responses array with a strict responses object.
*/
protected convertModifiedResponsesToStrictResponses()
{
for (let path in this.modifiedSpec['paths'])
{
for (let method in this.modifiedSpec['paths'][path])
{
// Grab the operation, ie: GET, POST, PUT, etc...
let operation = this.modifiedSpec['paths'][path][method];
// Create a new object to hold our responses,
// where the keys are HTTP status codes.
let responses: IResponses = {};
operation.responses.forEach(response =>
{
// NOTE: Status Codes of 0 get converted to a "default" response.
let key: any = response.statusCode === 0 ? 'default' : response.statusCode;
// Remove the status code from our modified response
// object to turn it into a strict response object.
let newResponse = Object.assign({}, response);
delete newResponse.statusCode;
// Make sure we don't override a response.
if (responses[key] != null)
{
throw new Error
(
'Duplicate Response Found @ paths.'+path+
'.'+method+'.responses.'+key
);
}
// And add the response to our new list
responses[key] = newResponse;
});
// Overwrite the responses array with a responses object.
operation.responses = <any>responses;
}
}
}
/**
* Replace our modified headers array with a strict headers object.
*/
protected convertModifiedHeadersToStrictHeaders()
{
for (let path in this.modifiedSpec['paths'])
{
for (let method in this.modifiedSpec['paths'][path])
{
// Grab the operation, ie: GET, POST, PUT, etc...
let operation = this.modifiedSpec['paths'][path][method];
// Create a new object to hold our headers,
// where the keys are HTTP header names.
for (let response in operation.responses)
{
if (operation.responses[response].headers == null) continue;
let headers: { [name:string]:IHeader } = {};
operation.responses[response].headers.forEach(header =>
{
// Remove the header name from our modified header
// object to turn it into a strict header object.
let newHeader = Object.assign({}, header);
delete newHeader.name;
// Make sure we don't override a header.
if (headers[header.name] != null)
{
throw new Error
(
'Duplicate Header Found @ paths.'+path+'.'+
method+'.responses.'+response+'.headers.'+
header.name
);
}
// And add the header to our new list
headers[header.name] = newHeader;
});
// Overwrite the headers array with a headers object.
operation.responses[response].headers = <any>headers;
}
}
}
}
/*
protected deDuplicateAndMinify()
{
let allSchemas = this.findAllSchemas();
console.log(allSchemas);
let allParameters = this.findAllParameters();
console.log(allParameters);
// Now look for any duplicates in our list.
let duplicatedSchemas = this.findDuplicatesOfType<ISchema>(allSchemas);
let duplicatedParameters = this.findDuplicatesOfType<IParameter>(allParameters);
this.modifiedSpec['parameters'] = {};
for (let parameterName in duplicatedParameters)
{
for (let keyPath of duplicatedParameters[parameterName].keyPaths)
{
spec.set(keyPath, {$ref:'#/parameters/'+parameterName});
}
this.modifiedSpec['parameters'][parameterName] = duplicatedParameters[parameterName].parameter;
}
}
protected findAllParameters(): { keyPath: string[], value: IParameter }[]
{
let parameters: { keyPath: string[], value: IParameter }[] = [];
traverse(this.modifiedSpec).forEach(function(node)
{
if (this.notRoot && this.parent.key === 'parameters')
{
parameters.push({keyPath: this.path, value: node});
}
});
return parameters;
}
protected findAllSchemas(): { keyPath: string[], value: ISchema }[]
{
let schemas: { keyPath: string[], value: ISchema }[] = [];
traverse(this.modifiedSpec).forEach(function(node)
{
if (this.notRoot && (this.key === 'schema' || this.key === 'items'))
{
if (this.path.indexOf('parameters') == -1 && this.path.indexOf('headers') == -1)
{
schemas.push({keyPath: this.path, value: node});
}
}
});
return schemas;
}
protected findDuplicatesOfType<T>(values: { keyPath: string[], value: T }[]): { [name: string]: { keyPaths: string[][], value: T } }
{
let duplicates: { [name: string]: { keyPaths: string[][], value: T } } = {};
for (let value1 of values)
{
for (let value2 of values)
{
// Ignore the case where both values are from the same place.
if (deepEqual(value1.keyPath, value2.keyPath))
{
continue;
}
// Check to see if we have 2 values that describe the same thing.
if (deepEqual(value1.value, value2.value))
{
let key: string = null;
if (value1.value['name'] != null)
{
// Parameters have name properties.
key = value1.value['name'];
}
else if (value1.value['title'] != null)
{
// Schemas have title properties but they are optional.
key = value1.value['title'];
}
else
{
// As a last restore we make hash of the value.
key = md5(JSON.stringify(value1.value));
}
if (duplicates[key] == null)
{
// The duplicated value does not already exist so lets add it.
duplicates[key] =
{
keyPaths: [value1.keyPath, value2.keyPath],
value: value1.value
};
}
else
{
// The duplicated value already exists in our list
// so all we need to do is append to it's array of keyPaths.
let keyPaths = duplicates[key].keyPaths;
if (keyPaths.find(v => deepEqual(v, value1.keyPath)) == null)
{
keyPaths.push(value1.keyPath);
}
if (keyPaths.find(v => deepEqual(v, value2.keyPath)) == null)
{
keyPaths.push(value2.keyPath);
}
}
}
}
}
return duplicates;
}
*/
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/ILink.ts | <reponame>brad-jones/openapi-spec-builder
import IServer from './IServer';
import ISpecificationExtension from './ISpecificationExtension';
/**
* The Link object represents a possible design-time link for a response.
*
* The presence of a link does not guarantee the caller's ability to
* successfully invoke it, rather it provides a known relationship and
* traversal mechanism between responses and other operations.
*
* Unlike dynamic links (i.e. links provided in the response payload),
* the OAS linking mechanism does not require link information in the
* runtime response.
*
* For computing links, and providing instructions to execute them,
* a runtime expression is used for accessing values in an operation
* and using them as parameters while invoking the linked operation.
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#link-object
*/
export default interface ILink extends ISpecificationExtension
{
/**
* A relative or absolute reference to an OAS operation.
*
* This field is mutually exclusive of the `operationId` field,
* and __MUST__ point to an Operation Object.
*
* Relative `operationRef` values __MAY__ be used to locate an existing
* Operation Object in the OpenAPI definition.
*/
operationRef?: string;
/**
* The name of an existing, resolvable OAS operation,
* as defined with a unique `operationId`.
*
* This field is mutually exclusive of the `operationRef` field.
*/
operationId?: string;
/**
* A map representing parameters to pass to an operation as specified
* with operationId or identified via `operationRef`.
*
* The key is the parameter name to be used, whereas the value can be a
* constant or an expression to be evaluated and passed to the linked
* operation.
*
* The parameter name can be qualified using the parameter location
* `[{in}.]{name}` for operations that use the same parameter name
* in different locations (e.g. path.id).
*/
parameters?: { [key: string]: any | string };
/**
* A literal value or [{expression}](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#runtimeExpression)
* to use as a request body when calling the target operation.
*/
requestBody?: any | string;
/**
* A description of the link.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* __MAY__ be used for rich text representation.
*/
description?: string;
/**
* A server object to be used by the target operation.
*/
server?: IServer;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IOAuthFlow.ts | <reponame>brad-jones/openapi-spec-builder
import ISpecificationExtension from './ISpecificationExtension';
/**
* Configuration details for a supported OAuth Flow
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#oauth-flow-object
*/
export default interface IOAuthFlow extends ISpecificationExtension
{
/**
* The authorization URL to be used for this flow.
*
* This __MUST__ be in the form of a URL.
*
* __REQUIRED__
*/
authorizationUrl: string;
/**
* The token URL to be used for this flow.
*
* This __MUST__ be in the form of a URL.
*
* __REQUIRED__
*/
tokenUrl: string;
/**
* The URL to be used for obtaining refresh tokens.
*
* This __MUST__ be in the form of a URL.
*/
refreshUrl?: string;
/**
* The available scopes for the OAuth2 security scheme.
*
* A map between the scope name and a short description for it.
*
* __REQUIRED__
*/
scopes: { [key: string]: string };
}
|
brad-jones/openapi-spec-builder | src/v2/Strict/IResponses.ts | import IReference from './IReference';
import IResponse from './IResponse';
interface IResponses
{
/**
* The documentation of responses other than the ones declared for
* specific HTTP response codes.
*
* It can be used to cover undeclared responses.
*
* Reference Object can be used to link to a response that is
* defined at the Swagger Object's responses section.
*/
default?: IResponse | IReference;
/**
* Any HTTP status code can be used as the property name
* (one property per HTTP status code).
*
* Describes the expected response for that HTTP status code.
* Reference Object can be used to link to a response that is
* defined at the Swagger Object's responses section.
*/
[name: number]: IResponse | IReference;
}
export default IResponses;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IHeader.ts | import { SerializationStyle } from '../TypeDefs';
import ISchema from './ISchema';
import IExample from './IExample';
import IReference from './IReference';
import IMediaType from './IMediaType';
import ISpecificationExtension from './ISpecificationExtension';
/**
* The Header Object follows the structure of the Parameter Object
* with the following changes:
*
* - `name` __MUST NOT__ be specified, it is given in the corresponding headers map.
* - `in` __MUST NOT__ be specified, it is implicitly in header.
* - All traits that are affected by the location __MUST__ be applicable to a location of header (for example, style).
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#header-object
*/
export default interface IHeader extends ISpecificationExtension
{
/**
* A brief description of the parameter.
*
* This could contain examples of use.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
/**
* Determines whether this parameter is mandatory.
*
* If the parameter location is `path`, this property is __REQUIRED__ and
* its value __MUST__ be true.
*
* Otherwise, the property MAY be included and its default value is false.
*/
required?: boolean;
/**
* Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.
*/
deprecated?: boolean;
/**
* Sets the ability to pass empty-valued parameters.
*
* This is valid only for query parameters and allows
* sending a parameter with an empty value.
*
* Default value is false.
*
* If style is used, and if behavior is n/a (cannot be serialized),
* the value of allowEmptyValue SHALL be ignored.
*/
allowEmptyValue?: boolean;
/**
* Describes how the parameter value will be serialized
* depending on the type of the parameter value.
*
* Default values (based on value of in):
* - for query = form;
* - for path = simple;
* - for header = simple;
* - for cookie = form.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#style-values
*
* TODO: Ensure the rules defined in the above link are validated at runtime.
*/
style?: SerializationStyle;
/**
* When this is true, parameter values of type array or object generate
* separate parameters for each value of the array or key-value pair of
* the map.
*
* For other types of parameters this property has no effect.
*
* When style is form, the default value is true.
*
* For all other styles, the default value is false.
*/
explode?: boolean;
/**
* Determines whether the parameter value SHOULD allow reserved characters,
* as defined by RFC3986 `:/?#[]@!$&'()*+,;=` to be included without
* percent-encoding.
*
* This property only applies to parameters with an `in` value of `query`.
*
* The default value is false.
*/
allowReserved?: boolean;
/**
* The schema defining the type used for the parameter.
*/
schema?: ISchema | IReference;
/**
* Example of the media type.
*
* The example SHOULD match the specified schema and encoding properties
* if present. The example object is mutually exclusive of the examples
* object.
*
* Furthermore, if referencing a schema which contains an example,
* the example value SHALL override the example provided by the schema.
*
* To represent examples of media types that cannot naturally be represented
* in JSON or YAML, a string value can contain the example with escaping
* where necessary.
*/
example?: any;
/**
* Examples of the media type.
*
* Each example SHOULD contain a value in the correct format as specified
* in the parameter encoding. The examples object is mutually exclusive of
* the example object.
*
* Furthermore, if referencing a schema which contains an example,
* the examples value SHALL override the example provided by the schema.
*/
examples?: { [key: string]: IExample | IReference };
/**
* For more complex scenarios, the content property can define the
* media type and schema of the parameter.
*
* A parameter __MUST__ contain either a schema property,
* or a content property, but not both.
*
* When example or examples are provided in conjunction with the
* schema object, the example __MUST__ follow the prescribed
* serialization strategy for the parameter.
*
* The key is the media type and the value describes it.
*
* The map __MUST__ only contain one entry.
*/
content?: { [key: string]: IMediaType };
}
|
brad-jones/openapi-spec-builder | src/v2/Modified/ISharedSchema.ts | <filename>src/v2/Modified/ISharedSchema.ts
import { FormatType, Type } from '../TypeDefs';
interface ISharedSchema
{
/**
* The type that the schema is describing.
*
* > NOTE: In some cases the type can be omitted and it will be inferred
* based on other properties values. However good practise would
* suggest the type is defined regardless.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types
*/
type?: Type;
/**
* The extending format for the previously mentioned type.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types
*/
format?: FormatType;
/**
* Used to supply a default JSON value associated with a particular schema.
*
* > NOTE: Unlike JSON Schema this value MUST conform
* to the defined type for the data type.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor101.
*/
default?: any;
/**
* Successful validation depends on the presence
* and value of "exclusiveMaximum":
*
* - if "exclusiveMaximum" is not present, or has boolean value false,
* then the instance is valid if it is lower than, or equal to,
* the value of "maximum";
*
* - if "exclusiveMaximum" has boolean value true,
* the instance is valid if it is strictly lower
* than the value of "maximum".
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor17.
*/
maximum?: number;
/**
* If "exclusiveMaximum" is present, "maximum" MUST also be present.
* "exclusiveMaximum", if absent, may be considered as being present
* with boolean value false.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor17.
*/
exclusiveMaximum?: boolean;
/**
* Successful validation depends on the presence
* and value of "exclusiveMinimum":
*
* - if "exclusiveMinimum" is not present, or has boolean value false,
* then the instance is valid if it is greater than, or equal to,
* the value of "minimum";
*
* - if "exclusiveMinimum" is present and has boolean value true,
* the instance is valid if it is strictly greater than the value
* of "minimum".
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
minimum?: number;
/**
* If "exclusiveMinimum" is present, "minimum" MUST also be present.
* "exclusiveMinimum", if absent, may be considered as being present
* with boolean value false.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
exclusiveMinimum?: boolean;
/**
* A string instance is valid against this keyword if its length
* is less than, or equal to, the value of this keyword.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor26
*/
maxLength?: number;
/**
* A string instance is valid against this keyword if its length
* is greater than, or equal to, the value of this keyword.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor29
*/
minLength?: number;
/**
* This string SHOULD be a valid regular expression,
* according to the ECMA 262 regular expression dialect.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor33
*/
pattern?: string;
/**
* An array instance is valid against "maxItems" if its size
* is less than, or equal to, the value of this keyword.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor42
*/
maxItems?: number;
/**
* An array instance is valid against "minItems" if its size
* is greater than, or equal to, the value of this keyword.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor45
*/
minItems?: number;
/**
* If it has boolean value true, the instance validates successfully
* if all of its elements are unique.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor49
*/
uniqueItems?: boolean;
/**
* An instance validates successfully against this keyword if its value
* is equal to one of the elements in this keyword's array value.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor76
*/
enum?: any[];
/**
* A numeric instance is valid against "multipleOf" if the result of the
* division of the instance by this keyword's value is an integer.
*
* @see http://json-schema.org/latest/json-schema-validation.html#anchor14
*/
multipleOf?: number;
}
export default ISharedSchema;
|
brad-jones/openapi-spec-builder | src/v2/Strict/IHeader.ts | import IItems from './IItems';
/**
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#header-object
*/
interface IHeader extends IItems
{
/**
* A short description of the header.
*/
description?: string;
}
export default IHeader;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IExample.ts | <reponame>brad-jones/openapi-spec-builder<filename>src/v3.0.0/Strict/IExample.ts
import ISpecificationExtension from './ISpecificationExtension';
/**
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#example-object
*/
export default interface IExample extends ISpecificationExtension
{
/**
* Short description for the example.
*/
summary?: string;
/**
* Long description for the example.
*
* [CommonMark syntax](http://spec.commonmark.org/)
* MAY be used for rich text representation.
*/
description?: string;
/**
* Embedded literal example.
*
* The value field and externalValue field are mutually exclusive.
*
* To represent examples of media types that cannot naturally represented
* in JSON or YAML, use a string value to contain the example,
* escaping where necessary.
*/
value?: any;
/**
* A URL that points to the literal example.
*
* This provides the capability to reference examples that
* cannot easily be included in JSON or YAML documents.
*
* The value field and externalValue field are mutually exclusive.
*/
externalValue?: string;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/IResponses.ts | import IResponse from './IResponse';
import IReference from './IReference';
import ISpecificationExtension from './ISpecificationExtension';
/**
* A container for the expected responses of an operation.
* The container maps a HTTP response code to the expected response.
*
* The documentation is not necessarily expected to cover all possible HTTP
* response codes because they may not be known in advance. However,
* documentation is expected to cover a successful operation response
* and any known errors.
*
* The default MAY be used as a default response object for all HTTP codes
* that are not covered individually by the specification.
*
* The Responses Object __MUST__ contain at least one response code,
* and it __SHOULD__ be the response for a successful operation call.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#responses-object
*/
export default interface IResponses extends ISpecificationExtension
{
/**
* The documentation of responses other than the ones declared
* for specific HTTP response codes.
*
* Use this field to cover undeclared responses.
*
* A Reference Object can link to a response that the OpenAPI Object's
* components/responses section defines.
*/
default?: IResponse | IReference;
/**
* Any HTTP status code can be used as the property name,
* but only one property per code, to describe the expected
* response for that HTTP status code.
*
* A Reference Object can link to a response that is defined in the
* OpenAPI Object's components/responses section.
*
* This field __MUST__ be enclosed in quotation marks (for example, "200")
* for compatibility between JSON and YAML.
*
* To define a range of response codes, this field MAY contain the
* uppercase wildcard character X. For example, 2XX represents all
* response codes between [200-299].
*
* The following range definitions are allowed: 1XX, 2XX, 3XX, 4XX, and 5XX.
*
* If a response range is defined using an explicit code, the explicit code
* definition takes precedence over the range definition for that code.
*/
[statusCode: string]: IResponse | IReference;
}
|
brad-jones/openapi-spec-builder | src/v2/Strict/ISecurityRequirment.ts | <gh_stars>1-10
/**
* Lists the required security schemes to execute this operation.
*
* The object can have multiple security schemes declared in it which are
* all required (that is, there is a logical AND between the schemes).
*
* The name used for each property MUST correspond to a
* security scheme declared in the Security Definitions.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-requirement-object
*/
interface ISecurityRequirment
{
/**
* Each name must correspond to a security scheme
* which is declared in the Security Definitions.
*
* If the security scheme is of type "oauth2", then the value is a list of
* scope names required for the execution. For other security scheme types,
* the array MUST be empty.
*/
[name: string]: string[];
}
export default ISecurityRequirment;
|
brad-jones/openapi-spec-builder | src/v2/Modified/IInfo.ts | <reponame>brad-jones/openapi-spec-builder
import IContact from "./IContact";
import ILicense from "./ILicense";
/**
* The object provides metadata about the API.
*
* The metadata can be used by the clients if needed,
* and can be presented in the Swagger-UI for convenience.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#info-object
*/
interface IInfo
{
/**
* Required. The title of the application.
*/
title: string;
/**
* A short description of the application.
*
* GFM syntax can be used for rich text representation.
*/
description?: string;
/**
* The Terms of Service for the API.
*/
termsOfService?: string;
/**
* The contact information for the exposed API.
*/
contact?: IContact;
/**
* The license information for the exposed API.
*/
license?: ILicense;
/**
* Required Provides the version of the application API.
*
* > NOTE: Not to be confused with the specification version.
*/
version: string;
}
export default IInfo;
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/ILicense.ts | <filename>src/v3.0.0/Strict/ILicense.ts
import ISpecificationExtension from './ISpecificationExtension';
/**
* License information for the exposed API.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#license-object
*/
export default interface ILicense extends ISpecificationExtension
{
/**
* The license name used for the API.
*
* __REQUIRED__
*/
name: string;
/**
* A URL to the license used for the API.
*
* __MUST__ be in the format of a URL.
*/
url?: string;
}
|
brad-jones/openapi-spec-builder | src/v3.0.0/Strict/ISpecificationExtension.ts | <filename>src/v3.0.0/Strict/ISpecificationExtension.ts<gh_stars>1-10
/**
* Specification Extensions
*
* While the OpenAPI Specification tries to accommodate most use cases,
* additional data can be added to extend the specification at certain points.
* The extensions properties are implemented as patterned fields that are
* always prefixed by "x-".
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#specificationExtensions
*/
export default interface ISpecificationExtension
{
// NOTE: It is impossible for us to constraint the key to "^x-".
// This will be done by the builder at runtime.
[extensionName: string]: any;
}
|
brad-jones/openapi-spec-builder | src/v2/Modified/IContact.ts | <reponame>brad-jones/openapi-spec-builder
/**
* Contact information for the exposed API.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#contactObject
*/
interface IContact
{
/**
* The identifying name of the contact person/organization.
*/
name?: string;
/**
* The URL pointing to the contact information.
*
* MUST be in the format of a URL.
*/
url?: string;
/**
* The email address of the contact person/organization.
*
* MUST be in the format of an email address.
*/
email?: string;
}
export default IContact;
|
brad-jones/openapi-spec-builder | src/v2/Strict/ITag.ts | <reponame>brad-jones/openapi-spec-builder<filename>src/v2/Strict/ITag.ts
import IExternalDocs from "./IExternalDocs";
/**
* Allows adding meta data to a single tag that is used by the Operation Object.
* It is not mandatory to have a Tag Object per tag used there.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#tag-object
*/
interface ITag
{
/**
* Required. The name of the tag.
*/
name: string;
/**
* A short description for the tag.
* GFM syntax can be used for rich text representation.
*/
description?: string;
/**
* Additional external documentation for this tag.
*/
externalDocs?: IExternalDocs;
}
export default ITag;
|
brad-jones/openapi-spec-builder | src/v2/Modified/IEndpoint.ts | import IExternalDocs from './IExternalDocs';
import IParameter from './IParameter';
import IResponse from './IResponse';
import ISecurityRequirment from './ISecurityRequirment';
import { Schemes } from '../TypeDefs';
/**
* Describes a single API operation on a path.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operation-object
*/
interface IEndpoint
{
/**
* The path to the endpoint, relative to the host and basePath.
*/
path: string;
/**
* The method the endpoint will response to.
*/
method: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options';
/**
* A list of tags for API documentation control.
*
* Tags can be used for logical grouping of operations
* by resources or any other qualifier.
*/
tags?: string[];
/**
* A short summary of what the operation does.
*
* For maximum readability in the swagger-ui,
* this field SHOULD be less than 120 characters.
*/
summary?: string;
/**
* A verbose explanation of the operation behavior.
*
* GFM syntax can be used for rich text representation.
*/
description?: string;
/**
* Additional external documentation for this operation.
*/
externalDocs?: IExternalDocs;
/**
* Unique string used to identify the operation.
*
* The id MUST be unique among all operations described in the API.
* Tools and libraries MAY use the operationId to uniquely identify
* an operation, therefore, it is recommended to follow common
* programming naming conventions.
*/
operationId?: string;
/**
* A list of MIME types the operation can consume.
*
* This overrides the consumes definition at the Swagger Object.
* An empty value MAY be used to clear the global definition.
* Value MUST be as described under Mime Types.
*/
consumes?: string[];
/**
* A list of MIME types the operation can produce.
*
* This overrides the produces definition at the Swagger Object.
* An empty value MAY be used to clear the global definition.
* Value MUST be as described under Mime Types.
*/
produces?: string[];
/**
* A list of parameters that are applicable for this operation.
*
* If a parameter is already defined at the Path Item, the new definition
* will override it, but can never remove it. The list MUST NOT include
* duplicated parameters.
*
* A unique parameter is defined by a combination of a name and location.
* There can be one "body" parameter at most.
*/
parameters?: IParameter[];
/**
* Required. The list of possible responses as they are returned from
* executing this operation.
*/
responses: IResponse[];
/**
* The transfer protocol for the operation.
*
* Values MUST be from the list: "http", "https", "ws", "wss".
* The value overrides the Swagger Object schemes definition.
*/
schemes?: Schemes[];
/**
* Declares this operation to be deprecated.
*
* Usage of the declared operation should be refrained.
*
* Default value is false.
*/
deprecated?: boolean;
/**
* A declaration of which security schemes are applied for this operation.
*
* The list of values describes alternative security schemes that can be
* used (that is, there is a logical OR between the security requirements).
*
* This definition overrides any declared top-level security.
* To remove a top-level security declaration, an empty array can be used.
*/
security?: ISecurityRequirment[];
}
export default IEndpoint;
|
brad-jones/openapi-spec-builder | src/v2/Strict/ISecuritySchema.ts | <reponame>brad-jones/openapi-spec-builder
/**
* Allows the definition of a security scheme that can be used by the operations.
*
* Supported schemes are basic authentication, an API key (either as a header
* or as a query parameter) and OAuth2's common flows (implicit, password,
* application and access code).
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-scheme-object
*/
interface ISecuritySchema
{
/**
* Required. The type of the security scheme.
* Valid values are "basic", "apiKey" or "oauth2".
*/
type: 'base' | 'apiKey' | 'oauth2';
/**
* A short description for security scheme.
*/
description?: string;
/**
* The name of the header or query parameter to be used.
*
* > NOTE: Required when type is set to "apiKey".
*/
name?: string;
/**
* The location of the API key.
*
* Valid values are "query" or "header".
*
* > NOTE: Required when type is set to "apiKey".
*/
in?: 'query' | 'header';
/**
* The flow used by the OAuth2 security scheme.
*
* Valid values are "implicit", "password", "application" or "accessCode".
*
* > NOTE: Required when type is set to "oauth2".
*/
flow?: 'implicit' | 'password' | 'application' | 'accessCode';
/**
* The authorization URL to be used for this flow.
*
* This SHOULD be in the form of a URL.
*
* > NOTE: Required when type is set to "oauth2" and the flow
* is set to implicit" or "accessCode".
*/
authorizationUrl?: string;
/**
* The token URL to be used for this flow.
*
* This SHOULD be in the form of a URL.
*
* > NOTE: Required when type is set to "oauth2" and the flow
* is set to "password", "application" or "accessCode".
*/
tokenUrl?: string;
/**
* The available scopes for the OAuth2 security scheme.
*
* > NOTE: Required when type is set to "oauth2".
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#scopes-object
*/
scopes?: { [name: string]: string };
}
export default ISecuritySchema;
|
brad-jones/openapi-spec-builder | src/v3.0.0/TypeDefs.ts | <gh_stars>1-10
/**
* There are four possible parameter locations specified by the in field:
*
* - __path:__ Used together with Path Templating, where the parameter value
* is actually part of the operation's URL. This does not include the host
* or base path of the API. For example, in `/items/{itemId}`, the path
* parameter is `itemId`.
*
* - __query:__ Parameters that are appended to the URL. For example,
* in `/items?id=###`, the query parameter is `id`.
*
* - __header:__ Custom headers that are expected as part of the request.
* Note that [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states
* header names are case insensitive.
*
* - __cookie:__ Used to pass a specific cookie value to the API.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameter-locations
*/
export type ParameterLocation =
'query' |
'header' |
'path' |
'cookie';
/**
* In order to support common ways of serializing simple parameters,
* a set of style values are defined.
*
* - __matrix:__ Path style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7)
*
* - __label:__ Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.5)
*
* - __form:__ Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.8).
* This option replaces `collectionFormat` with a `csv` (when `explode` is false)
* or `multi` (when `explode` is true) value from OpenAPI 2.0.
*
* - __simple:__ Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.2).
* This option replaces `collectionFormat` with a `csv` value from OpenAPI 2.0.
*
* - __spaceDelimited:__ Space separated array values.
* This option replaces `collectionFormat` equal to `ssv` from OpenAPI 2.0.
*
* - __pipeDelimited:__ Pipe separated array values.
* This option replaces `collectionFormat` equal to `pipes` from OpenAPI 2.0.
*
* - __deepObject:__ Provides a simple way of rendering nested objects using form parameters.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#style-values
*/
export type SerializationStyle =
'matrix' |
'label' |
'form' |
'simple' |
'spaceDelimited' |
'pipeDelimited' |
'deepObject';
/**
* Primitive data types in the OAS are based on the types supported by the
* [JSON Schema Specification Wright Draft 00](https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2).
*
* Note that `integer` as a type is also supported and is defined as a
* JSON number without a fraction or exponent part.
*
* `null` is not supported as a type (see [nullable](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schemaNullable) for an alternative solution).
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types
*/
export type DataType =
'boolean' |
'object' |
'array' |
'number' |
'integer' |
'string';
/**
* OAS uses several known formats to define in fine detail the data type being used.
*
* However, to support documentation needs, the format property is an open
* `string`-valued property, and can have any value. Formats such as
* `"email", "uuid"`, and so on, __MAY__ be used even though undefined by
* this specification.
*
* Types that are not accompanied by a format property follow the type
* definition in the JSON Schema.
*
* Tools that do not recognize a specific `format` __MAY__ default back to the
* `type` alone, as if the `format` is not specified.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#dataTypeFormat
*/
export type DataFormat =
'date' |
'date-time' |
'email' |
'hostname' |
'ipv4' |
'ipv6' |
'uri' |
'uriref' |
'int32' |
'int64' |
'float' |
'double' |
'byte' |
'binary' |
'password';
/**
* Security scheme types that can be used by the operations.
*
* Supported schemes are HTTP authentication, an API key (either as a header or
* as a query parameter), OAuth2's common flows (implicit, password, application
* and access code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749),
* and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06).
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#security-scheme-object
*/
export type SecuritySchemeType =
'apiKey' |
'http' |
'oauth2' |
'openIdConnect';
/**
* Valid locations for `apiKey`'s.
*
* __REQUIRED__ only when the `SecuritySchemeType` is set to `apiKey`.
*
* @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#security-scheme-object
*/
export type SecuritySchemeIn =
'query' |
'header' |
'cookie';
|
NTejaswi/May-Task2 | src/app/rest-observable/rest-observable.component.ts | import { Component, OnInit } from '@angular/core';
import { RestObservableService } from './rest-observable.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-rest-observable',
templateUrl: './rest-observable.component.html',
styles: ['li { list-style-type: none; padding: 20px 0; }']
})
export class RestObservableComponent implements OnInit {
// getPosts = []; <--- Without async pipe
getPosts: Observable<any>;
getComments: Observable<any>;
getUsers: Observable<any>;
getUsersPosts: Observable<any>;
postPosts: string;
putPosts: string;
patchPosts: string;
deletePosts: string;
errorMessage: string;
constructor(private roservice: RestObservableService) { }
ngOnInit() {
}
// GET
onGetPosts() {
this.getPosts = this.roservice.getPosts()
// .subscribe(
// data => this.getComments = data,
// error => this.errorMessage = <any>error,
// () => console.log('Get specific comments finished')
// );
}
onGetSpecificComments() {
this.getComments = this.roservice.getSpecificComments()
}
onGetUsers() {
this.getUsers = this.roservice.getUsers()
}
onGetUsersPosts() {
this.getUsersPosts = this.roservice.getUsersPosts()
}
// POST
onPostPosts() {
this.roservice.postPosts({userId: '49', id: '48', title: 'new title', body: 'new body text'})
.subscribe(
data => this.postPosts = JSON.stringify(data),
error => this.errorMessage = <any>error,
() => console.log('Post posts finished')
);
}
// PUT
onPutPosts() {
this.roservice.putPosts({userId: '23', id: '9', title: 'new title 2', body: 'new body text 2'})
.subscribe(
data => this.putPosts = JSON.stringify(data),
error => this.errorMessage = <any>error,
() => console.log('Put posts finished')
);
}
// PATCH
onPatchPosts() {
this.roservice.patchPosts({userId: '43', id: '12', title: 'new title 3', body: 'new body text 3'})
.subscribe(
data => this.patchPosts = JSON.stringify(data),
error => this.errorMessage = <any>error,
() => console.log('Patch posts finished')
);
}
// DELETE
onDeletePosts() {
this.roservice.deletePosts()
.subscribe(
data => this.deletePosts = JSON.stringify(data),
error => this.errorMessage = <any>error,
() => console.log('Delete post finished')
);
}
}
|
NTejaswi/May-Task2 | src/app/rest-observable/rest-observable.service.ts | import { Injectable } from '@angular/core';
import { HttpClient, HttpInterceptor, HttpRequest, HttpHandler, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
@Injectable()
export class RestObservableService /* implements HttpInterceptor */ {
headers: HttpHeaders;
options: any;
/*
intercept(req: HttpRequest<any>, next: HttpHandler) {
const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'q=0.8;application/json;q=0.9' });
const clone = req.clone({ headers });
return next.handle(clone);
}
*/
baseUrl = 'https://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {
this.headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'q=0.8;application/json;q=0.9' });
this.options = ({ headers: this.headers });
}
private handleError (error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
// GET
getPosts(): Observable<any> {
return this.http
.get(this.baseUrl + '/posts', this.options)
// With the new HttpClient, .map is no more.
.catch(this.handleError);
}
getSpecificComments(): Observable<any> {
return this.http
.get(this.baseUrl + '/posts/3/comments', this.options)
.catch(this.handleError);
}
getUsers(): Observable<any> {
return this.http
.get(this.baseUrl + '/users', this.options)
.catch(this.handleError);
}
getUsersPosts(): Observable<any> {
return this.http
.get(this.baseUrl + '/users/1/posts', this.options)
.catch(this.handleError);
}
// POST
postPosts(param: any): Observable<any> {
const body = JSON.stringify(param);
return this.http
.post(this.baseUrl + '/posts', body,this.options)
.catch(this.handleError);
}
// PUT
putPosts(param: any): Observable<any> {
const body = JSON.stringify(param);
return this.http
.put(this.baseUrl + '/posts/1', body, this.options)
.catch(this.handleError);
}
// PATCH
patchPosts(param: any): Observable<any> {
const body = JSON.stringify(param);
return this.http
.patch(this.baseUrl + '/posts/2', body, this.options)
.catch(this.handleError);
}
// DELETE
deletePosts(): Observable<any> {
return this.http
.delete(this.baseUrl + "/posts/1", this.options)
.catch(this.handleError);
}
}
|
NekoMoYi/dev2dev | windi.config.ts | <reponame>NekoMoYi/dev2dev
import { defineConfig } from 'windicss/helpers'
export default defineConfig({
theme: {
fontFamily: {
sans: ['Noto Sans SC'],
serif: ['ui-serif', 'Georgia'],
mono: ["'Cascadia Code'"],
display: ["'Cascadia Code'"],
body: ["'Cascadia Code'"]
}
}
})
|
NekoMoYi/dev2dev | src/shims-dataset.d.ts | <reponame>NekoMoYi/dev2dev
declare module 'virtual:dev2dev-dataset' {
export interface ISite {
host: string
name: string
owner: string
logo: string
}
const sites: ISite[]
export default sites
}
|
NekoMoYi/dev2dev | src/utils/async.ts | <gh_stars>1-10
export function wait(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms))
}
export function useAsync(fn: () => Promise<any>) {
fn()
}
|
NekoMoYi/dev2dev | plugins/dataset.ts | import fs from 'fs-extra'
import path from 'path'
import yaml from 'yaml'
import Ajv from 'ajv'
const ROOT = path.resolve(__dirname, '..')
const ajv = new Ajv()
const validator = ajv.compile(
fs.readJSONSync(path.join(ROOT, 'schema', 'site.json'))
)
const DATA_DIR = path.join(ROOT, 'data')
const sites = []
const files = fs.readdirSync(DATA_DIR).filter((x) => x.endsWith('.yml'))
for (const file of files) {
const content = fs.readFileSync(path.join(DATA_DIR, file)).toString()
try {
const parsed = yaml.parse(content)
const valid = validator(parsed)
if (!valid) {
throw new Error(validator.errors.map((x) => x.message).join(','))
}
sites.push(parsed)
} catch (e) {
console.warn(`Site config ${file} is invalid: ${e.message}`)
}
}
const script = `export default ${JSON.stringify(sites)}`
export default function datasetPlugin() {
const virtualFileId = 'virtual:dev2dev-dataset'
return {
name: 'dev2dev-dataset',
resolveId(id) {
if (id === virtualFileId) return virtualFileId
},
load(id) {
if (id === virtualFileId) return script
}
}
}
|
NekoMoYi/dev2dev | src/utils/sites.ts | <filename>src/utils/sites.ts
import sites, { ISite } from 'virtual:dev2dev-dataset'
const siteMap = new Map<string, ISite>(sites.map((x) => [x.host, x]))
function strip(url: string) {
const i = url.indexOf('.')
if (i === -1) return ''
return url.substr(i + 1)
}
function match(url: string) {
let result: ISite | undefined = undefined
do {
result = siteMap.get(url)
url = strip(url)
} while (url && !result)
return result
}
function random(skip?: ISite) {
for (;;) {
const i = Math.floor(Math.random() * sites.length)
const site = sites[i]
if (!skip || site.host !== skip.host) return site
}
}
export async function recommend(referrer: string) {
const cur = match(referrer)
const next = random(cur)
return { cur, next }
}
export async function list() {
return sites
}
|
vibexie/react-native-platform | src/ManufacturerBackgroundManager.ts | import { NativeModules } from 'react-native'
const { RNPlatform } = NativeModules
import { isHuawei, isXiaomi, isVIVO, isOPPO, isMeizu } from './DeviceUtil'
export function isBackgroundSettingSupported() {
return isHuawei() || isXiaomi() || isVIVO() || isOPPO() || isMeizu()
}
export function openBackgroundSettings(): Promise<boolean> {
return RNPlatform.openBackgroundSettings()
}
export function backgroudSettingTip() {
if (isHuawei()) {
return '应用启动管理 -> 关闭应用开关 -> 打开允许自启动'
} else if (isXiaomi()) {
return '授权管理 -> 自启动管理 -> 允许应用自启动'
} else if (isVIVO()) {
return '权限管理 -> 自启动 -> 允许应用自启动'
} else if (isOPPO()) {
return '权限隐私 -> 自启动管理 -> 允许应用自启动'
} else if (isMeizu()) {
return '权限管理 -> 后台管理 -> 点击应用 -> 允许后台运行'
}
return ''
}
|
aslambaba/Developer-Community | src/pages/using-typescript.tsx | import React from 'react';
export default function TSX(){
return(
<h1>TSX Page</h1>
)
} |
aisensiy/update-postman-schema-action | src/main.ts | import * as core from '@actions/core'
import * as fs from 'fs'
import * as util from 'util'
import {inspect} from 'util'
import fetch from 'node-fetch'
async function run() {
const inputs = {
token: core.getInput('postman-key'),
apiId: core.getInput('postman-api-id'),
apiVersionId: core.getInput('postman-api-version'),
schemaId: core.getInput('postman-api-schema-id'),
schemaType: core.getInput('postman-schema-type'),
schemaLanguage: core.getInput('postman-schema-language'),
contentFilepath: core.getInput('schema-filepath')
}
core.debug(`Inputs: ${inspect(inputs)}`)
// Check the file exists
if (await util.promisify(fs.exists)(inputs.contentFilepath)) {
// Fetch the file content
const fileContent = await fs.promises.readFile(inputs.contentFilepath, {
encoding: 'utf8'
})
// Send the request to the Postman API
const url = `https://api.getpostman.com/apis/${inputs.apiId}/versions/${inputs.apiVersionId}/schemas/${inputs.schemaId}`
const response = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': inputs.token
},
body: JSON.stringify({
schema: {
type: inputs.schemaType,
language: inputs.schemaLanguage,
schema: fileContent
}
})
})
const json = await response.json()
core.info(`Update postman schema ${url} response: ${inspect(json)}`)
if (response.status !== 200) {
core.setFailed('The schema was not updated')
}
// Set output
// core.setOutput('issue-number', issueNumber)
} else {
core.info(`File not found at path '${inputs.contentFilepath}'`)
core.setFailed('The schema was not updated')
}
}
run()
|
h-o-t/entente | src/nodes/VariableDeclaration.ts | <reponame>h-o-t/entente
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { Expression } from "./Expression";
export class VariableDeclaration {
constructor(private _node: ts.VariableDeclaration) {}
/** The initializer (value) of the variable declaration. */
get initializer(): Expression {
return new Expression(this._node.getInitializerOrThrow());
}
/** Assert that the variable name matches the expected value. */
name(
expected: string | RegExp,
msg = `Expected name to match "${expected}"`
): this {
const actual = this._node.getName();
if (!actual.match(expected)) {
throw new AssertionError(
msg,
{
actual,
expected,
showDiff: false,
},
this.name
);
}
return this;
}
}
|
h-o-t/entente | src/nodes/ClassMethod.ts | <filename>src/nodes/ClassMethod.ts
import { FunctionLikeDeclaration } from "./FunctionLikeDeclaration";
export class ClassMethod extends FunctionLikeDeclaration {}
|
h-o-t/entente | src/project.ts | import { extname } from "path";
import { CompilerOptions, Project } from "ts-morph";
/** Returns `true` if it appears to be a configuration file, versus a JavaScript
* or TypeScript file. Otherwise `false`. */
function isConfig(value: string): boolean {
return extname(value) === ".json";
}
/** Create a project that can be used to run assertions against. */
export function createProject(root: string): Project {
const compilerOptions: CompilerOptions = {
allowJs: true,
checkJs: true,
noEmit: true,
resolveJsonModule: true,
};
if (isConfig(root)) {
return new Project({ compilerOptions, tsConfigFilePath: root });
}
const project = new Project({ compilerOptions });
project.addSourceFileAtPath(root);
project.resolveSourceFileDependencies();
return project;
}
|
h-o-t/entente | src/nodes/Properties.ts | import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { TypeArray } from "./TypeArray";
export class Properties {
constructor(private _symbols: ts.Symbol[][]) {}
/** Assert that property exists in the object type. If true, returns the
* object properties. */
has(
expected: string | RegExp,
msg = `Expected property to match "${expected}".`
): this {
for (const sa of this._symbols) {
for (const s of sa) {
if (s.getName().match(expected)) {
return this;
}
}
}
throw new AssertionError(msg, undefined, this.has);
}
/**
* Get the type interfaces for properties that match the `name`.
*
* @param name A string or a regular expression.
*/
getTypes(name: string | RegExp): TypeArray {
const types: ts.Type[] = [];
for (const sa of this._symbols) {
for (const s of sa) {
if (s.getName().match(name)) {
types.push(s.getValueDeclarationOrThrow().getType());
}
}
}
return new TypeArray(types);
}
}
|
h-o-t/entente | src/nodes/Type.ts | <reponame>h-o-t/entente<gh_stars>10-100
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { Properties } from "./Properties";
export class Type<T extends ts.ts.Type = ts.ts.Type> {
private _properties?: Properties;
private _types: ts.Type[];
constructor(private _type: ts.Type<T>) {
this._types = _type.isUnion() ? _type.getUnionTypes() : [_type];
}
/** Assert the type is an array type. */
isArray(msg?: string): this {
if (!this._types.every((t) => t.isArray())) {
const actual = this._type.getText();
throw new AssertionError(
`Expected an array type, actual "${actual}".` ?? msg,
{
actual,
expected: "Array<any>",
showDiff: false,
},
this.isArray
);
}
return this;
}
/** Assert the type is an object type. */
isObject(msg?: string): this {
if (!this._types.every((t) => t.isObject())) {
const actual = this._type.getText();
throw new AssertionError(
`Expected an object type, actual "${this._type.getText()}".` ?? msg,
{
actual,
expected: "object",
showDiff: false,
},
this.isObject
);
}
return this;
}
/** Properties associated with the type. */
get properties(): Properties {
if (!this._properties) {
this._properties = new Properties(
this._types.map((t) => t.getProperties())
);
}
return this._properties;
}
/** The type associated with the array element. If the type is not an array
* type, accessing this property will throw. */
get arrayElementType(): Type {
return new Type(this._type.getArrayElementTypeOrThrow());
}
}
|
h-o-t/entente | src/nodes/FunctionLikeDeclaration.ts | import * as ts from "ts-morph";
import { ParameterDeclarationArray } from "./ParameterDeclarationArray";
import { Type } from "./Type";
export class FunctionLikeDeclaration {
private _parameterDeclarations?: ParameterDeclarationArray;
constructor(private _node: ts.FunctionLikeDeclaration) {}
/** The parameters associated with the function like declaration. */
get parameters(): ParameterDeclarationArray {
if (!this._parameterDeclarations) {
this._parameterDeclarations = new ParameterDeclarationArray(
this._node.getParameters()
);
}
return this._parameterDeclarations;
}
/** The return type of the function like declaration. */
get return(): Type {
return new Type(this._node.getReturnType());
}
}
|
h-o-t/entente | tests/fixtures/ts.ts | import { foo } from "./mod1";
// eslint-disable-next-line no-console
console.log(foo);
|
h-o-t/entente | tests/classes.ts | import { assert } from "chai";
import { test } from "./harness";
import { assertSourceFile, createProject } from "../src";
test({
name: "can assert classes in source file",
fn() {
const project = createProject("./tests/fixtures/exportClass.js");
const sourceFiles = project.getSourceFiles();
assertSourceFile(sourceFiles[0]).classes.length(1);
},
});
test({
name: "can assert class is default export",
fn() {
const project = createProject("./tests/fixtures/exportClass.js");
const sourceFiles = project.getSourceFiles();
assertSourceFile(sourceFiles[0]).classes.declarations[0].isDefaultExport();
},
});
test({
name: "can assert class member exists",
fn() {
const project = createProject("./tests/fixtures/exportClass.js");
const sourceFiles = project.getSourceFiles();
const members = assertSourceFile(
sourceFiles[0]
).classes.declarations[0].member("qux");
assert.lengthOf(members, 1, "should have only one member named 'qux'");
},
});
test({
name: "can assert member is method like",
fn() {
const project = createProject("./tests/fixtures/exportClass.js");
const sourceFiles = project.getSourceFiles();
const members = assertSourceFile(
sourceFiles[0]
).classes.declarations[0].member("qux");
members[0].isMethodLike();
},
});
test({
name: "can assert member is property",
fn() {
const project = createProject("./tests/fixtures/exportClass.js");
const sourceFiles = project.getSourceFiles();
const members = assertSourceFile(
sourceFiles[0]
).classes.declarations[0].member("qux");
members[0].isProperty();
},
});
test({
name: "can assert member is method",
fn() {
const project = createProject("./tests/fixtures/exportClass.js");
const sourceFiles = project.getSourceFiles();
const members = assertSourceFile(
sourceFiles[0]
).classes.declarations[0].member("quux");
members[0].isMethod();
},
});
test({
name: "can get property intializer",
fn() {
const project = createProject("./tests/fixtures/exportClass.js");
const sourceFiles = project.getSourceFiles();
const members = assertSourceFile(
sourceFiles[0]
).classes.declarations[0].member("qux");
members[0].isProperty().hasInitializer().isFunctionLike();
},
});
|
h-o-t/entente | src/util.ts | <gh_stars>10-100
import { sep as DEFAULT_SEPARATOR } from "path";
/** Try to detect the path seperator from a set of paths. */
function determineSeperator(paths: string[]): string {
for (const path of paths) {
const match = /(\/|\\)/.exec(path);
if (match !== null) {
return match[0];
}
}
return DEFAULT_SEPARATOR;
}
/** Determine the most common root path for a given set of paths. */
export function commonPath(
paths: string[],
sep = determineSeperator(paths)
): string {
const [first = "", ...remaining] = paths;
if (first === "" || remaining.length === 0) {
return "";
}
const parts = first.split(sep);
let endOfPrefix = parts.length;
for (const path of remaining) {
const compare = path.split(sep);
for (let i = 0; i < endOfPrefix; i++) {
if (compare[i] !== parts[i]) {
endOfPrefix = i;
}
}
if (endOfPrefix === 0) {
return "";
}
}
const prefix = parts.slice(0, endOfPrefix).join(sep);
return prefix.endsWith(sep) ? prefix : `${prefix}${sep}`;
}
|
h-o-t/entente | src/nodes/ClassMember.ts | import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ClassMethod } from "./ClassMethod";
import { ClassProperty } from "./ClassProperty";
export class ClassMember {
constructor(private _node: ts.ClassInstanceMemberTypes) {}
/** Asserts that the member is a method, not a property. */
isMethod(
msg = `Expected class member to be a method, found property.`
): ClassMethod {
if (!ts.TypeGuards.isMethodDeclaration(this._node)) {
throw new AssertionError(msg, undefined, this.isMethod);
}
return new ClassMethod(this._node);
}
/** Asserts that the member is method like. For example properties which are
* initialized with arrow functions would be method like. */
isMethodLike(msg = `Expected class member to be a method like.`): this {
if (!ts.TypeGuards.isMethodDeclaration(this._node)) {
let initializer: ts.Expression | undefined;
if (ts.TypeGuards.isParameterDeclaration(this._node)) {
initializer = this._node.getInitializer();
} else if (ts.TypeGuards.isPropertyDeclaration(this._node)) {
initializer = this._node.getInitializer();
}
if (initializer) {
if (ts.TypeGuards.isFunctionLikeDeclaration(initializer)) {
return this;
}
}
throw new AssertionError(msg, undefined, this.isMethodLike);
}
return this;
}
/** Asserts that the member is a property. */
isProperty(
msg = `Expected class member to be a property, found method.`
): ClassProperty {
if (ts.TypeGuards.isMethodDeclaration(this._node)) {
throw new AssertionError(msg, undefined, this.isProperty);
}
return new ClassProperty(this._node);
}
}
|
h-o-t/entente | tests/fixtures/exports.ts | <reponame>h-o-t/entente
/* eslint-disable */
const foo = () => {};
export default foo;
export function bar() {}
export const baz = 1;
export const qux = "qux";
export const quux = "quux";
export const quuux = "quuux";
|
h-o-t/entente | tests/assert.ts | import { assert } from "chai";
import { test } from "./harness";
import { assertSourceFile, createProject } from "../src";
test({
name: "can assert against a source file",
fn() {
const project = createProject("./tests/fixtures/exports.ts");
const sourceFiles = project.getSourceFiles();
assert(assertSourceFile(sourceFiles[0]));
},
});
test({
name: "can assert against file path",
fn() {
const project = createProject("./tests/fixtures/exports.ts");
const sourceFiles = project.getSourceFiles();
assertSourceFile(sourceFiles[0]).filePath(/\/fixtures\/exports\.ts$/);
},
});
test({
name: "can assert against a default export",
fn() {
const project = createProject("./tests/fixtures/exports.ts");
const sourceFiles = project.getSourceFiles();
const sourceFile = assertSourceFile(sourceFiles[0]);
sourceFile.exports
.default()
.length(1)
.declarations[0].isVariableDeclaration();
},
});
test({
name: "can assert against a named export via string",
fn() {
const project = createProject("./tests/fixtures/exports.ts");
const sourceFiles = project.getSourceFiles();
const sourceFile = assertSourceFile(sourceFiles[0]);
sourceFile.exports
.namedExport("bar")
.length(1)
.declarations[0].isFunctionLike();
},
});
test({
name: "can assert against a named export via a regular expression",
fn() {
const project = createProject("./tests/fixtures/exports.ts");
const sourceFiles = project.getSourceFiles();
const sourceFile = assertSourceFile(sourceFiles[0]);
sourceFile.exports
.namedExport(/qu+x/)
.length(1)
.declarations[0].isVariableDeclaration();
},
});
test({
name: "exports are iterable",
fn() {
const project = createProject("./tests/fixtures/exports.ts");
const sourceFiles = project.getSourceFiles();
const sourceFile = assertSourceFile(sourceFiles[0]);
const exports = [...sourceFile.exports];
assert(exports.length === 6);
},
});
|
h-o-t/entente | src/index.ts | export * from "./assert";
export * from "./harness";
export * from "./project";
|
h-o-t/entente | src/nodes/Expression.ts | <reponame>h-o-t/entente<gh_stars>10-100
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { FunctionLikeDeclaration } from "./FunctionLikeDeclaration";
export class Expression {
constructor(private _node: ts.Expression) {}
/** Assert the expression is function like, and return the function like
* declaration if true. */
isFunctionLike(msg?: string): FunctionLikeDeclaration {
if (!ts.Node.isFunctionLikeDeclaration(this._node)) {
const actual = this._node.getKindName();
throw new AssertionError(
msg ?? `Expected a function like declaration, actual ${actual}.`,
{
actual,
expected: "FunctionLikeDeclaration",
showDiff: false,
},
this.isFunctionLike
);
}
return new FunctionLikeDeclaration(this._node);
}
}
|
h-o-t/entente | tests/imports.ts | import { assert } from "chai";
import { test } from "./harness";
import { assertSourceFile, createProject } from "../src";
test({
name: "can return import specifiers",
fn() {
const project = createProject("./tests/fixtures/imports.ts");
const sourceFile = project.getSourceFiles()[0];
assert.deepEqual(assertSourceFile(sourceFile).imports.specifiers, [
"./mod3",
"./mod4",
]);
},
});
test({
name: "can assert import specifiers - string",
fn() {
const project = createProject("./tests/fixtures/imports.ts");
const sourceFile = project.getSourceFiles()[0];
assertSourceFile(sourceFile).imports.includes("mod").length(2);
},
});
test({
name: "can assert import specifiers - regex",
fn() {
const project = createProject("./tests/fixtures/imports.ts");
const sourceFile = project.getSourceFiles()[0];
assertSourceFile(sourceFile).imports.includes(/\/mod/).length(2);
},
});
test({
name: "throw on failed import specifier assertion",
fn() {
const project = createProject("./tests/fixtures/imports.ts");
const sourceFile = project.getSourceFiles()[0];
assert.throws(
() => assertSourceFile(sourceFile).imports.includes("bar"),
`Expected an import to match "bar".`
);
},
});
|
h-o-t/entente | src/harness.ts | import { format } from "assertion-error-formatter";
import * as chalk from "chalk";
/* eslint-disable no-console */
export interface RunReturn {
/** An array of the results of each of the tests. */
tests: TestResult[];
/** The total number of tests executed. */
count: number;
/** The total number of tests that failed. */
fail: number;
}
export interface RunOptions {
/** If `true` then no output will be logged. Defaults to `false`. */
silent?: boolean;
}
/** A test function. The name of the function will be used for the name of the
* test. */
export type TestFn = () => Promise<void> | void;
export interface TestSpec {
/** The name of the test. */
name: string;
/** The test function, which can return nothing. */
fn: TestFn;
}
export interface TestResult {
/** The name of the test. */
name: string;
/** If the test failed or not. */
fail: boolean;
/** If failed, a rich formatted string of the error that occured. */
errorString?: string;
}
/** Queue of tests. */
const testQueue: TestSpec[] = [];
/** A unique ID used when generating names for tests where one isn't
* supplied. */
let uid = 0;
/** Formatting options for assertion errors. */
const formatOptions = {
colorFns: {
diffAdded: chalk.greenBright,
diffRemoved: chalk.redBright,
errorMessage: chalk.yellowBright,
errorStack: chalk.cyanBright,
},
};
/** A guard for return values from tests. */
function isPromiseLike<T>(value: unknown): value is PromiseLike<T> {
return Boolean(typeof value === "object" && value && "then" in value);
}
/** Default run options. */
const defaultRunOptions: RunOptions = { silent: false };
/**
* Execute any queued tests, resolving with a summary of the test results.
*
* import { run } from "entente";
*
* (async () => {
* const results = await run({ silent: true });
* console.log(results);
* })();
*/
export async function run(options: RunOptions = {}): Promise<RunReturn> {
// eslint-disable-next-line prefer-object-spread
const { silent } = Object.assign({}, defaultRunOptions, options);
const { length } = testQueue;
if (!silent) {
console.log(`\n${chalk.green("Starting...")}\n\n${length} tests to run.\n`);
}
let spec: TestSpec | undefined;
let count = 0;
let fail = 0;
const tests: TestResult[] = [];
while ((spec = testQueue.shift())) {
count++;
try {
const result = spec.fn();
if (isPromiseLike(result)) {
// eslint-disable-next-line no-await-in-loop
await result;
}
if (!silent) {
console.log(
`[${count}/${length}] - ${chalk.greenBright("pass")} - ${chalk.yellow(
spec.name
)}`
);
}
tests.push({
name: spec.name,
fail: false,
});
} catch (e) {
fail++;
const errorString = format(e, formatOptions);
tests.push({
name: spec.name,
fail: true,
errorString,
});
if (!silent) {
console.log(
`[${count}/${length}] - ${chalk.redBright("fail")} - ${chalk.yellow(
spec.name
)}\n`
);
console.log(`${errorString}\n`);
}
}
}
if (!silent) {
console.log(
`\n${chalk.yellow(
"Finished."
)}\n\n${fail} failures out of ${count} tests.\n`
);
for (const result of tests) {
if (result.fail) {
console.log(chalk.red(`${result.name}:\n`));
console.log(result.errorString);
}
}
}
return { tests, count, fail };
}
/**
* Queue up a test to be run.
*
* import { test } from "entente";
*
* test({
* name: "an example test",
* fn() {
* throw new Error("test fail!");
* }
* });
*
* @param item Either a test function or test specification
*/
export function test(item: TestFn | TestSpec): void {
testQueue.push(
typeof item === "function"
? {
name: item.name ?? `test ${++uid}`,
fn: item,
}
: item
);
}
|
h-o-t/entente | src/interfaces.d.ts | <gh_stars>10-100
// there are no `@types` for this module, so providing here
declare module "assertion-error-formatter" {
export function format(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error: any,
options?: {
colorFns?: {
diffAdded?: (str: string) => string;
diffRemoved?: (str: string) => string;
errorMessage?: (str: string) => string;
errorStack?: (str: string) => string;
};
inlineDiff?: boolean;
}
): string;
}
|
h-o-t/entente | src/nodes/SourceFile.ts | <gh_stars>10-100
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ClassDeclarations } from "./ClassDeclarations";
import { Exports } from "./Exports";
import { Imports } from "./Imports";
export class SourceFile {
constructor(private _node: ts.SourceFile) {}
/** The class declarations for the source file. */
get classes(): ClassDeclarations {
return new ClassDeclarations(this._node.getClasses());
}
/** The export interfaces for the source file. */
get exports(): Exports {
return new Exports(this._node.getExportedDeclarations());
}
/** The imports for the source file. */
get imports(): Imports {
return new Imports(this._node.getImportDeclarations());
}
/** The underlying AST node. */
get node(): ts.SourceFile {
return this._node;
}
/** Assert the file path of the source file matches the expected value. */
filePath(expected: string | RegExp, msg = "Unexpected file path."): this {
const actual = this._node.getFilePath();
if (!actual.match(expected)) {
throw new AssertionError(
msg,
{
actual,
expected,
showDiff: false,
},
this.filePath
);
}
return this;
}
}
|
h-o-t/entente | src/nodes/TypeArray.ts | import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
export class TypeArray {
constructor(private _types: ts.Type[]) {}
/** Assert that there are at least a number of types in the type array. */
atLeast(expected: number, msg?: string): this {
const actual = this._types.length;
if (!(actual >= expected)) {
throw new AssertionError(
msg ?? `Expected at least ${expected} type(s), actual is ${actual}.`,
{
actual,
expected,
showDiff: false,
},
this.atLeast
);
}
return this;
}
/** Assert that every type in the type array is an object type. */
isObject(msg = "Expected types to be an object."): this {
if (!this._types.every((t) => t.isObject())) {
throw new AssertionError(
msg,
{
actual: this._types[0].getText(),
expected: "object",
showDiff: false,
},
this.isObject
);
}
return this;
}
/** Assert that every type in the type array is a string type. */
isString(msg = "Expected types to be a string."): this {
if (!this._types.every((t) => t.isString())) {
throw new AssertionError(
msg,
{
actual: this._types[0].getText(),
expected: "string",
showDiff: false,
},
this.isString
);
}
return this;
}
}
|
h-o-t/entente | src/nodes/Imports.ts | <reponame>h-o-t/entente<gh_stars>10-100
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ImportDeclaration } from "./ImportDeclaration";
export class Imports {
constructor(private _declarations: ts.ImportDeclaration[]) {}
get declarations(): ImportDeclaration[] {
return this._declarations.map((id) => new ImportDeclaration(id));
}
get sourceFileNodes(): Record<string, ts.SourceFile | undefined> {
const result: Record<string, ts.SourceFile | undefined> = {};
for (const id of this._declarations) {
result[
id.getModuleSpecifier().getLiteralText()
] = id.getModuleSpecifierSourceFile();
}
return result;
}
get specifiers(): string[] {
return this._declarations.map((id) =>
id.getModuleSpecifier().getLiteralText()
);
}
includes(
value: string | RegExp,
msg = `Expected an import to match "${String(value)}".`
): Imports {
const includeArray = this._declarations.filter((id) => {
const specifier = id.getModuleSpecifier().getLiteralText();
return typeof value === "string"
? specifier.includes(value)
: specifier.match(value);
});
if (!includeArray.length) {
throw new AssertionError(msg, undefined, this.includes);
}
return new Imports(includeArray);
}
length(expected: number, msg = "Unexpected number of imports."): this {
const actual = this._declarations.length;
if (this._declarations.length !== expected) {
throw new AssertionError(
msg,
{
actual,
expected,
showDiff: true,
},
this.length
);
}
return this;
}
*[Symbol.iterator](): IterableIterator<ImportDeclaration> {
for (const importDeclaration of this._declarations) {
yield new ImportDeclaration(importDeclaration);
}
}
}
|
h-o-t/entente | tests/index.ts | <reponame>h-o-t/entente
import { run } from "./harness";
import "./project";
import "./assert";
import "./imports";
import "./classes";
(async () => {
const fails = await run();
process.exit(fails);
})();
|
h-o-t/entente | tests/fixtures/mod3.ts | export const foo = "foo";
export const bar = 1;
export const baz = (): void => {
// eslint-disable-next-line no-console
console.log("baz");
};
export function qat(): boolean {
return true;
}
|
h-o-t/entente | src/nodes/ExportedDeclaration.ts | <filename>src/nodes/ExportedDeclaration.ts
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { FunctionLikeDeclaration } from "./FunctionLikeDeclaration";
import { VariableDeclaration } from "./VariableDeclaration";
export class ExportedDeclaration<
T extends ts.ExportedDeclarations = ts.ExportedDeclarations
> {
constructor(private _declaration: T) {}
get declaration(): T {
return this._declaration;
}
/** Assert the export declaration function like. */
isFunctionLike(msg?: string): FunctionLikeDeclaration {
if (!ts.Node.isFunctionLikeDeclaration(this._declaration)) {
const actual = this._declaration.getKindName();
throw new AssertionError(
msg ?? `Expected FunctionLikeDeclaration, actual ${actual}.`,
{
actual,
expected: "FunctionLikeDeclaration",
showDiff: false,
},
this.isFunctionLike
);
}
return new FunctionLikeDeclaration(this._declaration);
}
/** Assert the export declaration is a variable declaration. */
isVariableDeclaration(msg?: string): VariableDeclaration {
if (!ts.Node.isVariableDeclaration(this._declaration)) {
const actual = this._declaration.getKindName();
throw new AssertionError(
msg ?? `Expected VariableDeclaration, actual ${actual}.`,
{
actual,
expected: "VariableDeclaration",
showDiff: false,
},
this.isVariableDeclaration
);
}
return new VariableDeclaration(this._declaration);
}
}
|
Subsets and Splits