From 8f0bd7301f9fde00dd5234658f9d262da1e537ad Mon Sep 17 00:00:00 2001 From: Jean-Michel Douliez Date: Tue, 26 Apr 2016 14:12:58 +0200 Subject: [PATCH 01/53] Update api.mustache --- .../src/main/resources/swift/api.mustache | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 9801182e082..e5fe9651e0c 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -80,11 +80,14 @@ public class {{classname}}: APIBase { ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} - let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} - + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters!){{/bodyParam}} + let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: convertedParameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) } {{/operation}} From 09a02223080c8eb0698120c386639c8868fa3e4d Mon Sep 17 00:00:00 2001 From: Jean-Michel Douliez Date: Tue, 26 Apr 2016 19:31:07 +0200 Subject: [PATCH 02/53] accepting non nil potentially void dictionary --- modules/swagger-codegen/src/main/resources/swift/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index e5fe9651e0c..bdd9f5db5db 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -83,7 +83,7 @@ public class {{classname}}: APIBase { let parameters = APIHelper.rejectNil(nillableParameters) - let convertedParameters = APIHelper.convertBoolToString(parameters!){{/bodyParam}} + let convertedParameters = APIHelper.convertBoolToString(parameters){{/bodyParam}} let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() From 4b39e0579f2b03cbf51702624bf16cd0eb3803f6 Mon Sep 17 00:00:00 2001 From: Jean-Michel Douliez Date: Tue, 26 Apr 2016 19:28:05 +0200 Subject: [PATCH 03/53] returning non nil potentially void dictionary --- .../src/main/resources/swift/APIHelper.mustache | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache index 418f1c8512b..e562ae92cf4 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache @@ -18,4 +18,20 @@ class APIHelper { } return destination } + + static func convertBoolToString(source: [String: AnyObject]) -> [String:AnyObject] { + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + for (key, value) in source { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + return destination + } + } From 949da93a059d0efc8b7df0062f1e21ba8e801990 Mon Sep 17 00:00:00 2001 From: Takuro Wada Date: Wed, 4 May 2016 17:19:00 +0900 Subject: [PATCH 04/53] Update typescript-angular2 client to adopt to rc --- .../typescript-angular2/api.mustache | 12 +++++------ .../typescript-angular2/package.mustache | 18 +++++++++++------ .../typescript-angular2/default/api/PetApi.ts | 12 +++++------ .../default/api/StoreApi.ts | 12 +++++------ .../default/api/UserApi.ts | 12 +++++------ .../typescript-angular2/npm/README.md | 4 ++-- .../typescript-angular2/npm/api/PetApi.ts | 12 +++++------ .../typescript-angular2/npm/api/StoreApi.ts | 12 +++++------ .../typescript-angular2/npm/api/UserApi.ts | 12 +++++------ .../typescript-angular2/npm/package.json | 20 ++++++++++++------- 10 files changed, 69 insertions(+), 57 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index fd37bdd1194..a2f88b05bca 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -1,5 +1,5 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -18,10 +18,10 @@ export class {{classname}} { protected basePath = '{{basePath}}'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { - if (basePath) { - this.basePath = basePath; - } + constructor(protected http: Http) {} + + setBasePath(basePath: string) { + this.basePath = basePath; } {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache index 0b2e50acb44..dff8a68e54d 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache @@ -15,18 +15,24 @@ "scripts": { "build": "typings install && tsc" }, + "dependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0" + }, "peerDependencies": { - "angular2": "^2.0.0-beta.15", - "rxjs": "^5.0.0-beta.2" + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12" }, "devDependencies": { "typescript": "^1.8.10", "typings": "^0.8.1", - "angular2": "^2.0.0-beta.15", "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0", - "rxjs": "5.0.0-beta.2", - "zone.js": "^0.6.10" + "es7-reflect-metadata": "^1.6.0" }{{#npmRepository}}, "publishConfig":{ "registry":"{{npmRepository}}" diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index e2121b52c0b..f69a78df3c4 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -1,5 +1,5 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { - if (basePath) { - this.basePath = basePath; - } + constructor(protected http: Http) {} + + setBasePath(basePath: string) { + this.basePath = basePath; } /** diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index 618b0c23624..f7b52337a0a 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -1,5 +1,5 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { - if (basePath) { - this.basePath = basePath; - } + constructor(protected http: Http) {} + + setBasePath(basePath: string) { + this.basePath = basePath; } /** diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index f52b407d126..95cb5febff5 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -1,5 +1,5 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { - if (basePath) { - this.basePath = basePath; - } + constructor(protected http: Http) {} + + setBasePath(basePath: string) { + this.basePath = basePath; } /** diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 8120c59916e..c3d0ec56956 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201604282253 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605041712 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201604282253 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605041712 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index e2121b52c0b..f69a78df3c4 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -1,5 +1,5 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { - if (basePath) { - this.basePath = basePath; - } + constructor(protected http: Http) {} + + setBasePath(basePath: string) { + this.basePath = basePath; } /** diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index 618b0c23624..f7b52337a0a 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -1,5 +1,5 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { - if (basePath) { - this.basePath = basePath; - } + constructor(protected http: Http) {} + + setBasePath(basePath: string) { + this.basePath = basePath; } /** diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index f52b407d126..95cb5febff5 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -1,5 +1,5 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { - if (basePath) { - this.basePath = basePath; - } + constructor(protected http: Http) {} + + setBasePath(basePath: string) { + this.basePath = basePath; } /** diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index cab5097a4ed..9ac748fce10 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201604282253", + "version": "0.0.1-SNAPSHOT.201605041712", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ @@ -15,18 +15,24 @@ "scripts": { "build": "typings install && tsc" }, + "dependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0" + }, "peerDependencies": { - "angular2": "^2.0.0-beta.15", - "rxjs": "^5.0.0-beta.2" + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12" }, "devDependencies": { "typescript": "^1.8.10", "typings": "^0.8.1", - "angular2": "^2.0.0-beta.15", "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0", - "rxjs": "5.0.0-beta.2", - "zone.js": "^0.6.10" + "es7-reflect-metadata": "^1.6.0" }, "publishConfig":{ "registry":"https://skimdb.npmjs.com/registry" From 366c7d69178dbd8a241e0d60ab17d892c99d0976 Mon Sep 17 00:00:00 2001 From: Takuro Wada Date: Wed, 4 May 2016 18:25:29 +0900 Subject: [PATCH 05/53] Add Opeiontal decorator to basePath --- .../main/resources/typescript-angular2/api.mustache | 10 +++++----- .../petstore/typescript-angular2/default/api/PetApi.ts | 10 +++++----- .../typescript-angular2/default/api/StoreApi.ts | 10 +++++----- .../typescript-angular2/default/api/UserApi.ts | 10 +++++----- .../client/petstore/typescript-angular2/npm/README.md | 4 ++-- .../petstore/typescript-angular2/npm/api/PetApi.ts | 10 +++++----- .../petstore/typescript-angular2/npm/api/StoreApi.ts | 10 +++++----- .../petstore/typescript-angular2/npm/api/UserApi.ts | 10 +++++----- .../petstore/typescript-angular2/npm/package.json | 2 +- 9 files changed, 38 insertions(+), 38 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index a2f88b05bca..4eae99d749e 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -1,5 +1,5 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable} from '@angular/core'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -18,10 +18,10 @@ export class {{classname}} { protected basePath = '{{basePath}}'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http) {} - - setBasePath(basePath: string) { - this.basePath = basePath; + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } } {{#operation}} diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index f69a78df3c4..4a858fa75ed 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -1,5 +1,5 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable} from '@angular/core'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http) {} - - setBasePath(basePath: string) { - this.basePath = basePath; + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } } /** diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index f7b52337a0a..b6c8b5022b0 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -1,5 +1,5 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable} from '@angular/core'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http) {} - - setBasePath(basePath: string) { - this.basePath = basePath; + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } } /** diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index 95cb5febff5..0fd1fd0d25e 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -1,5 +1,5 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable} from '@angular/core'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http) {} - - setBasePath(basePath: string) { - this.basePath = basePath; + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } } /** diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index c3d0ec56956..07c8035e922 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605041712 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605041838 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605041712 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605041838 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index f69a78df3c4..4a858fa75ed 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -1,5 +1,5 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable} from '@angular/core'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http) {} - - setBasePath(basePath: string) { - this.basePath = basePath; + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } } /** diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index f7b52337a0a..b6c8b5022b0 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -1,5 +1,5 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable} from '@angular/core'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http) {} - - setBasePath(basePath: string) { - this.basePath = basePath; + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } } /** diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index 95cb5febff5..0fd1fd0d25e 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -1,5 +1,5 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable} from '@angular/core'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; @@ -12,10 +12,10 @@ export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http) {} - - setBasePath(basePath: string) { - this.basePath = basePath; + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } } /** diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index 9ac748fce10..9fbaef443ff 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201605041712", + "version": "0.0.1-SNAPSHOT.201605041838", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ From 724c25728e7ef01c49f59a1e3f83765d225db562 Mon Sep 17 00:00:00 2001 From: Takuro Wada Date: Fri, 6 May 2016 16:04:24 +0900 Subject: [PATCH 06/53] Move @angular dependencies to peerDependencies --- .../src/main/resources/typescript-angular2/package.mustache | 4 +--- samples/client/petstore/typescript-angular2/npm/README.md | 4 ++-- .../client/petstore/typescript-angular2/npm/package.json | 6 ++---- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache index dff8a68e54d..62270e878c9 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache @@ -15,7 +15,7 @@ "scripts": { "build": "typings install && tsc" }, - "dependencies": { + "peerDependencies": { "@angular/common": "^2.0.0-rc.1", "@angular/compiler": "^2.0.0-rc.1", "@angular/core": "^2.0.0-rc.1", @@ -23,8 +23,6 @@ "@angular/platform-browser": "^2.0.0-rc.1", "@angular/platform-browser-dynamic": "^2.0.0-rc.1", "core-js": "^2.3.0" - }, - "peerDependencies": { "rxjs": "^5.0.0-beta.6", "zone.js": "^0.6.12" }, diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 07c8035e922..6b1e698e766 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605041838 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605061603 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605041838 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605061603 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index 9fbaef443ff..ca4f885a4bf 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201605041838", + "version": "0.0.1-SNAPSHOT.201605061603", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ @@ -15,7 +15,7 @@ "scripts": { "build": "typings install && tsc" }, - "dependencies": { + "peerDependencies": { "@angular/common": "^2.0.0-rc.1", "@angular/compiler": "^2.0.0-rc.1", "@angular/core": "^2.0.0-rc.1", @@ -23,8 +23,6 @@ "@angular/platform-browser": "^2.0.0-rc.1", "@angular/platform-browser-dynamic": "^2.0.0-rc.1", "core-js": "^2.3.0" - }, - "peerDependencies": { "rxjs": "^5.0.0-beta.6", "zone.js": "^0.6.12" }, From 618f4bdd39ce740edca75fa2e9db93656d54ca33 Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sat, 7 May 2016 22:22:48 -0400 Subject: [PATCH 07/53] [csharp] Constructor handling for serialization Resolving an issue with serializing classes that contain required properties. When the only constructor has defaulted parameters, no parameterless constructor is generated but JSON.Net attempts to call the missing constructor on deserialization (because of DataContract). See: https://manski.net/2014/10/net-serializers-comparison-chart/ The fix here is to create a protected constructor, annotate it with JsonConstructorAttribute to inform JSON.Net it is the constructor to use during serialization, then provide settings that explicitly allow JSON.Net to access non-public constructors during serialiazation. --- .../src/main/java/io/swagger/codegen/CodegenModel.java | 2 +- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 2 ++ .../src/main/resources/csharp/ApiClient.mustache | 7 ++++++- .../src/main/resources/csharp/modelGeneric.mustache | 7 +++++++ 4 files changed, 16 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index ccea2ee070e..438eb191294 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -27,7 +27,7 @@ public class CodegenModel { public Set allMandatory; public Set imports = new TreeSet(); - public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum; + public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired; public ExternalDocs externalDocs; public Map vendorExtensions; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index db000e9c63e..abe9dbea04e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2432,6 +2432,7 @@ public class DefaultCodegen { private void addVars(CodegenModel m, Map properties, List required, Map allProperties, List allRequired) { + m.hasRequired = false; if (properties != null && !properties.isEmpty()) { m.hasVars = true; m.hasEnums = false; @@ -2470,6 +2471,7 @@ public class DefaultCodegen { } else { final CodegenProperty cp = fromProperty(key, prop); cp.required = mandatory.contains(key) ? true : null; + m.hasRequired = Boolean.TRUE.equals(m.hasRequired) || Boolean.TRUE.equals(cp.required); if (cp.isEnum) { // FIXME: if supporting inheritance, when called a second time for allProperties it is possible for // m.hasEnums to be set incorrectly if allProperties has enumerations but properties does not. diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 2c0f8f681e3..f9b9f766299 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -20,6 +20,11 @@ namespace {{packageName}}.Client /// public class ApiClient { + private JsonSerializerSettings serializerSettings = new JsonSerializerSettings + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }; + /// /// Initializes a new instance of the class /// with default configuration and base path ({{basePath}}). @@ -305,7 +310,7 @@ namespace {{packageName}}.Client // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content, type); + return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); } catch (Exception e) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 6c5da5e4f56..ebadaf2046a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -24,6 +24,13 @@ public {{{datatypeWithEnum}}}{{#isEnum}}?{{/isEnum}} {{name}} { get; set; } {{/isEnum}} {{/vars}} + {{#hasRequired}} + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected {{classname}}() { } + {{/hasRequired}} /// /// Initializes a new instance of the class. /// From 705ed78de1c6d18255cdd5c32acec3d09470ff7b Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sun, 8 May 2016 08:35:28 -0400 Subject: [PATCH 08/53] [csharp] regenerate client --- .../petstore/csharp/SwaggerClient/IO.Swagger.sln | 10 +++++----- .../client/petstore/csharp/SwaggerClient/README.md | 14 +++++++------- .../src/IO.Swagger.Test/IO.Swagger.Test.csproj | 2 +- .../src/IO.Swagger/Client/ApiClient.cs | 7 ++++++- .../SwaggerClient/src/IO.Swagger/IO.Swagger.csproj | 2 +- .../SwaggerClient/src/IO.Swagger/Model/Animal.cs | 5 +++++ .../SwaggerClient/src/IO.Swagger/Model/Cat.cs | 5 +++++ .../SwaggerClient/src/IO.Swagger/Model/Dog.cs | 5 +++++ .../src/IO.Swagger/Model/FormatTest.cs | 5 +++++ .../SwaggerClient/src/IO.Swagger/Model/Name.cs | 5 +++++ .../SwaggerClient/src/IO.Swagger/Model/Pet.cs | 5 +++++ ...aggerClientTest.csproj.FilesWrittenAbsolute.txt | 11 +++++++++++ 12 files changed, 61 insertions(+), 15 deletions(-) diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 72e6e04d121..f1bdeab367f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{AC0D0300-7030-473F-B672-17C40187815A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{AC0D0300-7030-473F-B672-17C40187815A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{AC0D0300-7030-473F-B672-17C40187815A}.Debug|Any CPU.Build.0 = Debug|Any CPU -{AC0D0300-7030-473F-B672-17C40187815A}.Release|Any CPU.ActiveCfg = Release|Any CPU -{AC0D0300-7030-473F-B672-17C40187815A}.Release|Any CPU.Build.0 = Release|Any CPU +{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}.Debug|Any CPU.Build.0 = Debug|Any CPU +{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}.Release|Any CPU.ActiveCfg = Release|Any CPU +{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 1f7e9f634e0..9c0902bcc9f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-05-07T17:39:09.181+08:00 +- Build date: 2016-05-07T22:34:58.354-04:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -134,12 +134,6 @@ Class | Method | HTTP request | Description ## Documentation for Authorization -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ### petstore_auth - **Type**: OAuth @@ -149,3 +143,9 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index de3b57cfe78..4b99b613fc1 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -65,7 +65,7 @@ - {AC0D0300-7030-473F-B672-17C40187815A} + {086EEE3F-4CAC-475B-A3D9-F0D944DC9D79} IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs index 42299503d2a..fa4f899389a 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs @@ -18,6 +18,11 @@ namespace IO.Swagger.Client /// public class ApiClient { + private JsonSerializerSettings serializerSettings = new JsonSerializerSettings + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }; + /// /// Initializes a new instance of the class /// with default configuration and base path (http://petstore.swagger.io/v2). @@ -289,7 +294,7 @@ namespace IO.Swagger.Client // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content, type); + return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); } catch (Exception e) { diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index 5d9a64329c1..d9b1d9ab07c 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {AC0D0300-7030-473F-B672-17C40187815A} + {086EEE3F-4CAC-475B-A3D9-F0D944DC9D79} Library Properties Swagger Library diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs index f5b9a3efee0..5e5d6a1a52a 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Animal : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Animal() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs index 74bd81aee05..82a9435d57e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Cat : Animal, IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Cat() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs index 6ab8c9ad69f..49ac2ab72c3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Dog : Animal, IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Dog() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs index 33301f02a95..51c2d920e30 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class FormatTest : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected FormatTest() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs index b0e819fec20..e28d061e9f0 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Name : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Name() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs index 420ab138b07..50cdb903f94 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs @@ -53,6 +53,11 @@ namespace IO.Swagger.Model /// /// Initializes a new instance of the class. /// + [JsonConstructorAttribute] + protected Pet() { } + /// + /// Initializes a new instance of the class. + /// /// Id. /// Category. /// Name (required). diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt index fe5b5e6a930..547dccf6f4e 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt @@ -9,3 +9,14 @@ /Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll /Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll /Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll.mdb +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll +/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll.mdb From 51ad775aee4ef3e2bfefaab85f4c734cc376e3da Mon Sep 17 00:00:00 2001 From: Andrew Z Allen Date: Mon, 9 May 2016 22:46:50 -0600 Subject: [PATCH 09/53] Update the injector static variable to contain all injected values. In Angular.js, values are injected into service in one of two ways: 1) Inline (by name). 2) By a static injector variable. The TypeScript generator uses the 2nd method. This method requires you to explicitly enumerate all the values you would like to have injected. If you fail to inject a value the Angular DI system will simply pass you `undefined`. The constructor is expecting 3 values to be passed (the final being basePath) but the injector static only defines 2 values. This results in basePath always being undefined no matter what you define it to be. This change updates the injector variable to handle that properly. --- .../src/main/resources/typescript-angular/api.mustache | 2 +- samples/client/petstore/typescript-angular/API/Client/PetApi.ts | 2 +- .../client/petstore/typescript-angular/API/Client/StoreApi.ts | 2 +- .../client/petstore/typescript-angular/API/Client/UserApi.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache index 427479cf675..6a713376146 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache @@ -15,7 +15,7 @@ namespace {{package}} { protected basePath = '{{basePath}}'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { if (basePath) { diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 62492c17d80..b9567bd6780 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -9,7 +9,7 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { if (basePath) { diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 976ee7acd48..530a46fe1e6 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -9,7 +9,7 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { if (basePath) { diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 79f6326b99c..cd079c32f9d 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -9,7 +9,7 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { if (basePath) { From 0b8c936972e70ace60e985a2e3ec6504c1efa28e Mon Sep 17 00:00:00 2001 From: Andrew Z Allen Date: Mon, 9 May 2016 22:59:25 -0600 Subject: [PATCH 10/53] Update TypeScript to do a better check for empty on basePath. In Angular if a value is not defined for injection it is passed as undefined. That means that most of the time `if (value) {` is a reasonable test. Unfortunately since `""` (empty string) is also falsey by nature, an empty string will not trigger the if properly. Instead you should check `if (value !== undefined) {`. --- .../src/main/resources/typescript-angular/api.mustache | 2 +- samples/client/petstore/typescript-angular/API/Client/PetApi.ts | 2 +- .../client/petstore/typescript-angular/API/Client/StoreApi.ts | 2 +- .../client/petstore/typescript-angular/API/Client/UserApi.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache index 427479cf675..4d2660e82dc 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache @@ -18,7 +18,7 @@ namespace {{package}} { static $inject: string[] = ['$http', '$httpParamSerializer']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 62492c17d80..c68ffcad88d 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -12,7 +12,7 @@ namespace API.Client { static $inject: string[] = ['$http', '$httpParamSerializer']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 976ee7acd48..0b775139936 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -12,7 +12,7 @@ namespace API.Client { static $inject: string[] = ['$http', '$httpParamSerializer']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 79f6326b99c..a593f28b0e1 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -12,7 +12,7 @@ namespace API.Client { static $inject: string[] = ['$http', '$httpParamSerializer']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } From 9f19a74123c12e9d5083ef4fb93fac14ac7786e5 Mon Sep 17 00:00:00 2001 From: Jean-Michel Douliez Date: Tue, 10 May 2016 12:45:38 +0200 Subject: [PATCH 11/53] Update APIHelper.mustache --- .../src/main/resources/swift/APIHelper.mustache | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache index e562ae92cf4..7041709f365 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache @@ -19,16 +19,18 @@ class APIHelper { return destination } - static func convertBoolToString(source: [String: AnyObject]) -> [String:AnyObject] { + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject] { var destination = [String:AnyObject]() let theTrue = NSNumber(bool: true) let theFalse = NSNumber(bool: false) - for (key, value) in source { - switch value { - case let x where x === theTrue || x === theFalse: - destination[key] = "\(value as! Bool)" - default: - destination[key] = value + if (source != nil) { + for (key, value) in source! { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } } } return destination From 6178149f10ddcbcff6e42d18e9e9c342a21e59d7 Mon Sep 17 00:00:00 2001 From: Jean-Michel Douliez Date: Tue, 10 May 2016 12:46:30 +0200 Subject: [PATCH 12/53] Update api.mustache --- modules/swagger-codegen/src/main/resources/swift/api.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index bdd9f5db5db..8e3216052a0 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -81,9 +81,9 @@ public class {{classname}}: APIBase { "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} - let parameters = APIHelper.rejectNil(nillableParameters) + let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} - let convertedParameters = APIHelper.convertBoolToString(parameters){{/bodyParam}} + let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() From 94f49d2275f6898605c6396a97389a1737a5ce7f Mon Sep 17 00:00:00 2001 From: Mateusz Mackowiak Date: Tue, 10 May 2016 21:53:14 +0200 Subject: [PATCH 13/53] [Objc] bump version of JSONModel to 1.2 and ISO8601 to 0.5 --- .../src/main/resources/objc/podspec.mustache | 4 ++-- samples/client/petstore/objc/README.md | 4 ++-- samples/client/petstore/objc/SwaggerClient.podspec | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index 338ded84e89..2adf84d8c3e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -30,7 +30,7 @@ Pod::Spec.new do |s| s.public_header_files = '{{podName}}/**/*.h' s.dependency 'AFNetworking', '~> 2.3' - s.dependency 'JSONModel', '~> 1.1' - s.dependency 'ISO8601', '~> 0.3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' end diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index f4b3f2f2f76..3efbcba5921 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -1,12 +1,12 @@ # SwaggerClient -This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters +This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - Package version: -- Build date: 2016-05-08T12:06:01.121+02:00 +- Build date: 2016-05-10T21:51:45.108+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 740680eb9e2..41c66960b21 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -13,7 +13,7 @@ Pod::Spec.new do |s| s.summary = "Swagger Petstore" s.description = <<-DESC - This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + This is a sample server Petstore server. You can find out more about Swagger at <a href="http://swagger.io">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters DESC s.platform = :ios, '7.0' @@ -30,7 +30,7 @@ Pod::Spec.new do |s| s.public_header_files = 'SwaggerClient/**/*.h' s.dependency 'AFNetworking', '~> 2.3' - s.dependency 'JSONModel', '~> 1.1' - s.dependency 'ISO8601', '~> 0.3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' end From fa7d3c9bad8a559973cc40bca52d01321b996110 Mon Sep 17 00:00:00 2001 From: Mateusz Mackowiak Date: Tue, 10 May 2016 22:06:50 +0200 Subject: [PATCH 14/53] [Objc] - Moved Logging to separate Logger file - Moved selectHeaderAccept and selectHeaderContentType to sanitizer - little optimizations --- .../codegen/languages/ObjcClientCodegen.java | 2 + .../resources/objc/ApiClient-body.mustache | 240 +++++------------- .../resources/objc/ApiClient-header.mustache | 52 +--- .../objc/Configuration-body.mustache | 39 ++- .../objc/Configuration-header.mustache | 24 +- .../main/resources/objc/Logger-body.mustache | 74 ++++++ .../resources/objc/Logger-header.mustache | 54 ++++ .../resources/objc/Sanitizer-body.mustache | 80 ++++++ .../resources/objc/Sanitizer-header.mustache | 20 ++ .../src/main/resources/objc/api-body.mustache | 24 +- .../main/resources/objc/git_push.sh.mustache | 0 samples/client/petstore/objc/README.md | 4 +- .../petstore/objc/SwaggerClient.podspec | 2 +- .../objc/SwaggerClient/SWGApiClient.h | 52 +--- .../objc/SwaggerClient/SWGApiClient.m | 240 +++++------------- .../objc/SwaggerClient/SWGConfiguration.h | 24 +- .../objc/SwaggerClient/SWGConfiguration.m | 39 ++- .../petstore/objc/SwaggerClient/SWGLogger.h | 54 ++++ .../petstore/objc/SwaggerClient/SWGLogger.m | 74 ++++++ .../petstore/objc/SwaggerClient/SWGPetApi.m | 164 ++++-------- .../objc/SwaggerClient/SWGSanitizer.h | 20 ++ .../objc/SwaggerClient/SWGSanitizer.m | 80 ++++++ .../petstore/objc/SwaggerClient/SWGStoreApi.m | 84 ++---- .../petstore/objc/SwaggerClient/SWGUserApi.m | 164 ++++-------- .../SwaggerClientTests/Tests/PetApiTest.m | 11 +- .../Tests/SWGApiClientTest.m | 24 +- 26 files changed, 797 insertions(+), 848 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache mode change 100755 => 100644 modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache create mode 100644 samples/client/petstore/objc/SwaggerClient/SWGLogger.h create mode 100644 samples/client/petstore/objc/SwaggerClient/SWGLogger.m diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 46b6083e2e4..6bb05deb233 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -242,6 +242,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.h")); supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", swaggerFolder, classPrefix + "Sanitizer.m")); supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", swaggerFolder, classPrefix + "Sanitizer.h")); + supportingFiles.add(new SupportingFile("Logger-body.mustache", swaggerFolder, classPrefix + "Logger.m")); + supportingFiles.add(new SupportingFile("Logger-header.mustache", swaggerFolder, classPrefix + "Logger.h")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h")); supportingFiles.add(new SupportingFile("Configuration-body.mustache", swaggerFolder, classPrefix + "Configuration.m")); diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 5afc917e228..6b9d3e841bb 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -2,7 +2,7 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; -static long requestId = 0; +static NSUInteger requestId = 0; static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; @@ -36,7 +36,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) @interface {{classPrefix}}ApiClient () -@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; +@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; @end @@ -88,49 +88,6 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; } -#pragma mark - Log Methods - -+ (void)debugLog:(NSString *)method - message:(NSString *)format, ... { - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - if (!config.debug) { - return; - } - - NSMutableString *message = [NSMutableString stringWithCapacity:1]; - - if (method) { - [message appendString:[NSString stringWithFormat:@"%@: ", method]]; - } - - va_list args; - va_start(args, format); - - [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; - - // If set logging file handler, log into file, - // otherwise log into console. - if (config.loggingFileHanlder) { - [config.loggingFileHanlder seekToEndOfFile]; - [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; - } - else { - NSLog(@"%@", message); - } - - va_end(args); -} - -- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { - - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - responseObject]; - - {{classPrefix}}DebugLog(message); -} - #pragma mark - Cache Methods +(void)clearCache { @@ -151,70 +108,6 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [NSURLCache setSharedURLCache:cache]; } -#pragma mark - Utility Methods - -/* - * Detect `Accept` from accepts - */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { - return @""; - } - - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - // use rangeOfString instead of containsString for iOS 7 support - if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { - return @"application/json"; - } - [lowerAccepts addObject:lowerAccept]; - } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - - return [lowerAccepts componentsJoinedByString:@", "]; -} - -/* - * Detect `Content-Type` from contentTypes - */ -+ (NSString *) selectHeaderContentType:(NSArray *)contentTypes -{ - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; - } - - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; - } -} - -+ (NSString*)escape:(id)unescaped { - if ([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - #pragma mark - Request Methods +(unsigned long)requestQueueSize { @@ -223,14 +116,12 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) +(NSNumber*) nextRequestId { @synchronized(self) { - long nextId = ++requestId; - {{classPrefix}}DebugLog(@"got id %ld", nextId); - return [NSNumber numberWithLong:nextId]; + return @(++requestId); } } +(NSNumber*) queueRequest { - NSNumber* requestId = [{{classPrefix}}ApiClient nextRequestId]; + NSNumber* requestId = [[self class] nextRequestId]; {{classPrefix}}DebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; @@ -294,7 +185,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) if (![strongSelf executeRequestWithId:requestId]) { return; } - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); @@ -321,7 +212,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return; } strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -370,14 +261,13 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { - NSAssert(false, @"unsupport request type %@", requestContentType); + NSAssert(NO, @"Unsupported request type %@", requestContentType); } // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } - else { + } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } @@ -393,8 +283,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSMutableString *resourcePath = [NSMutableString stringWithString:path]; [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] - withString:[{{classPrefix}}ApiClient escape:obj]]; + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; NSMutableURLRequest * request = nil; @@ -489,55 +380,56 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) - (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } NSString * separator = nil; - int counter = 0; + NSUInteger counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if (queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) separator = @"?"; - else separator = @"&"; - id queryParam = [queryParams valueForKey:key]; - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [{{classPrefix}}ApiClient escape:[queryParams valueForKey:key]]]]; - } - else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ - {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - if ([format isEqualToString:@"csv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; - - } - else if ([format isEqualToString:@"tsv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; - - } - else if ([format isEqualToString:@"pipes"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; - - } - else if ([format isEqualToString:@"multi"]) { - for(id obj in values) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; - counter += 1; - } - - } - } - else { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; - } - - counter += 1; + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; } return requestUrl; } @@ -558,15 +450,17 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; for (NSString *auth in authSettings) { - NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - - if (authSetting) { // auth setting is set only if the key is non-empty - if ([authSetting[@"in"] isEqualToString:@"header"] && [authSetting[@"key"] length] != 0) { - [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - else if ([authSetting[@"in"] isEqualToString:@"query"] && [authSetting[@"key"] length] != 0) { - [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } + NSDictionary *authSetting = [config authSettings][auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; } } diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index b08112ba445..28d5b92f628 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -7,6 +7,7 @@ #import "{{classPrefix}}Configuration.h" #import "{{classPrefix}}ResponseDeserializer.h" #import "{{classPrefix}}Sanitizer.h" +#import "{{classPrefix}}Logger.h" /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -26,13 +27,6 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; -/** - * Log debug message macro - */ -#ifndef {{classPrefix}}DebugLog - #define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -#endif - @interface {{classPrefix}}ApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @@ -113,15 +107,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(void) cancelRequest:(NSNumber*)requestId; -/** - * Gets URL encoded NSString - * - * @param unescaped The string which will be escaped. - * - * @return The escaped string. - */ -+(NSString*) escape:(id)unescaped; - /** * Customizes the behavior when the reachability changed * @@ -134,24 +119,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (void)configureCacheReachibility; -/** - * Detects Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ -+(NSString *) selectHeaderAccept:(NSArray *)accepts; - -/** - * Detects Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header - * - * @return The Content-Type header - */ -+(NSString *) selectHeaderContentType:(NSArray *)contentTypes; - /** * Sets header for request * @@ -172,19 +139,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; -/** - * Logs request and response - * - * @param response NSURLResponse for the HTTP request. - * @param responseObject response object of the HTTP request. - * @param request The HTTP request. - * @param error The error of the HTTP request. - */ -- (void)logResponse:(NSURLResponse *)response - responseObject:(id)responseObject - request:(NSURLRequest *)request - error:(NSError *)error; - /** * Performs request * @@ -222,9 +176,5 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (AFSecurityPolicy *) customSecurityPolicy; -/** - * Log debug message - */ -+(void)debugLog:(NSString *)method message:(NSString *)format, ...; @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 527e16c2b91..99708408d4e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -30,12 +30,10 @@ self.username = @""; self.password = @""; self.accessToken= @""; - self.tempFolderPath = nil; - self.debug = NO; self.verifySSL = YES; - self.loggingFile = nil; self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + self.logger = [{{classPrefix}}Logger sharedLogger]; } return self; } @@ -43,11 +41,13 @@ #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; } - else if ([self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; } else { // return empty string if nothing is set return @""; @@ -70,8 +70,7 @@ - (NSString *) getAccessToken { if (self.accessToken.length == 0) { // token not set, return empty string return @""; - } - else { + } else { return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; } } @@ -94,20 +93,6 @@ [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } -- (void) setLoggingFile:(NSString *)loggingFile { - // close old file handler - if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { - [self.loggingFileHanlder closeFile]; - } - - _loggingFile = loggingFile; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (_loggingFileHanlder == nil) { - [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - } -} - #pragma mark - Getter Methods - (NSDictionary *) apiKey { @@ -154,4 +139,12 @@ }; } +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index b77ddfe5dee..c00c7175d2a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -1,5 +1,6 @@ #import #import "{{classPrefix}}ApiClient.h" +#import "{{classPrefix}}Logger.h" /** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. * @@ -12,6 +13,11 @@ @interface {{classPrefix}}Configuration : NSObject +/** + * Default api logger + */ +@property (nonatomic, strong) {{classPrefix}}Logger * logger; + /** * Default api client */ @@ -37,7 +43,7 @@ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename for HTTP Basic Authentication + * Username for HTTP Basic Authentication */ @property (nonatomic) NSString *username; @@ -56,25 +62,11 @@ */ @property (nonatomic) NSString *tempFolderPath; -/** - * Logging Settings - */ - /** * Debug switch, default false */ @property (nonatomic) BOOL debug; -/** - * Debug file location, default log in console - */ -@property (nonatomic) NSString *loggingFile; - -/** - * Log file handler, this property is used by sdk internally. - */ -@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; - /** * Gets configuration singleton instance */ @@ -143,7 +135,7 @@ - (NSString *) getAccessToken; /** - * Gets Authentication Setings + * Gets Authentication Settings */ - (NSDictionary *) authSettings; diff --git a/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache new file mode 100644 index 00000000000..9a8f7de2418 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache @@ -0,0 +1,74 @@ +#import "{{classPrefix}}Logger.h" + +@interface {{classPrefix}}Logger () + +@end + +@implementation {{classPrefix}}Logger + ++ (instancetype) sharedLogger { + static {{classPrefix}}Logger *shardLogger = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardLogger = [[self alloc] init]; + }); + return shardLogger; +} + +#pragma mark - Log Methods + +- (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + if (!self.isEnabled) { + return; + } + + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendFormat:@"%@: ", method]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. + if (self.loggingFileHandler) { + [self.loggingFileHandler seekToEndOfFile]; + [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } else { + NSLog(@"%@", message); + } + + va_end(args); +} + +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + responseObject]; + + {{classPrefix}}DebugLog(message); +} + +- (void) setLoggingFile:(NSString *)loggingFile { + if(_loggingFile == loggingFile) { + return; + } + // close old file handler + if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHandler closeFile]; + } + _loggingFile = loggingFile; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHandler == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache new file mode 100644 index 00000000000..2070f95ae9f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache @@ -0,0 +1,54 @@ +#import + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#ifndef {{classPrefix}}DebugLogResponse +#define {{classPrefix}}DebugLogResponse(response, responseObject,request, error) [[{{classPrefix}}Logger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; +#endif + +/** + * Log debug message macro + */ +#ifndef {{classPrefix}}DebugLog +#define {{classPrefix}}DebugLog(format, ...) [[{{classPrefix}}Logger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif + +@interface {{classPrefix}}Logger : NSObject + ++(instancetype)sharedLogger; + +/** + * Enabled switch, default NO - default set by {{classPrefix}}Configuration debug property + */ +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +/** + * Debug file location, default log in console + */ +@property (nonatomic, strong) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; + +/** + * Log debug message + */ +-(void)debugLog:(NSString *)method message:(NSString *)format, ...; + +/** + * Logs request and response + * + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache index 74b166d75e9..f43e6493d75 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache @@ -3,6 +3,38 @@ #import "{{classPrefix}}QueryParamCollection.h" #import +NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { + static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@"; + static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[k{{classPrefix}}CharactersGeneralDelimitersToEncode stringByAppendingString:k{{classPrefix}}CharactersSubDelimitersToEncode]]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + @interface {{classPrefix}}Sanitizer () @end @@ -79,4 +111,52 @@ } } +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ +- (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts == nil || [accepts count] == 0) { + return @""; + } + + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + NSString * lowerAccept = [string lowercaseString]; + // use rangeOfString instead of containsString for iOS 7 support + if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { + return @"application/json"; + } + [lowerAccepts addObject:lowerAccept]; + } + + if (lowerAccepts.count == 1) { + return [lowerAccepts firstObject]; + } + + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ +- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { + if (contentTypes == nil || [contentTypes count] == 0) { + return @"application/json"; + } + + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerContentTypes addObject:[obj lowercaseString]]; + }]; + + if ([lowerContentTypes containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return lowerContentTypes[0]; + } +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache index 706a94c1d0e..cd946661615 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache @@ -6,6 +6,8 @@ * Do not edit the class manually. */ +extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string); + @protocol {{classPrefix}}Sanitizer /** @@ -20,6 +22,24 @@ */ - (NSString *) parameterToString: (id) param; +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ +-(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ +-(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + @end @interface {{classPrefix}}Sanitizer : NSObject <{{classPrefix}}Sanitizer> diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 2a7880d8367..807acc8ed76 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -15,7 +15,7 @@ static {{classname}}* singletonAPI = nil; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; @@ -28,7 +28,7 @@ static {{classname}}* singletonAPI = nil; return self; } -- (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { +- (instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { self = [super init]; if (self) { self.apiClient = apiClient; @@ -92,9 +92,7 @@ static {{classname}}* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; {{#pathParams}} @@ -121,22 +119,16 @@ static {{classname}}* singletonAPI = nil; {{/headerParams}} // HTTP header `Accept` - headerParams[@"Accept"] = [{{classPrefix}}ApiClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [{{classPrefix}}ApiClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; // Authentication setting NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; diff --git a/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache old mode 100755 new mode 100644 diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index f4b3f2f2f76..d0ae437a93c 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -1,12 +1,12 @@ # SwaggerClient -This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters +This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - Package version: -- Build date: 2016-05-08T12:06:01.121+02:00 +- Build date: 2016-05-10T17:16:13.387+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 740680eb9e2..87fb2f6e494 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -13,7 +13,7 @@ Pod::Spec.new do |s| s.summary = "Swagger Petstore" s.description = <<-DESC - This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + This is a sample server Petstore server. You can find out more about Swagger at <a href="http://swagger.io">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters DESC s.platform = :ios, '7.0' diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 82472ab20bf..adbb8f15a62 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -7,6 +7,7 @@ #import "SWGConfiguration.h" #import "SWGResponseDeserializer.h" #import "SWGSanitizer.h" +#import "SWGLogger.h" /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -30,13 +31,6 @@ */ extern NSString *const SWGResponseObjectErrorKey; -/** - * Log debug message macro - */ -#ifndef SWGDebugLog - #define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -#endif - @interface SWGApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @@ -117,15 +111,6 @@ extern NSString *const SWGResponseObjectErrorKey; */ +(void) cancelRequest:(NSNumber*)requestId; -/** - * Gets URL encoded NSString - * - * @param unescaped The string which will be escaped. - * - * @return The escaped string. - */ -+(NSString*) escape:(id)unescaped; - /** * Customizes the behavior when the reachability changed * @@ -138,24 +123,6 @@ extern NSString *const SWGResponseObjectErrorKey; */ - (void)configureCacheReachibility; -/** - * Detects Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ -+(NSString *) selectHeaderAccept:(NSArray *)accepts; - -/** - * Detects Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header - * - * @return The Content-Type header - */ -+(NSString *) selectHeaderContentType:(NSArray *)contentTypes; - /** * Sets header for request * @@ -176,19 +143,6 @@ extern NSString *const SWGResponseObjectErrorKey; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; -/** - * Logs request and response - * - * @param response NSURLResponse for the HTTP request. - * @param responseObject response object of the HTTP request. - * @param request The HTTP request. - * @param error The error of the HTTP request. - */ -- (void)logResponse:(NSURLResponse *)response - responseObject:(id)responseObject - request:(NSURLRequest *)request - error:(NSError *)error; - /** * Performs request * @@ -226,9 +180,5 @@ extern NSString *const SWGResponseObjectErrorKey; */ - (AFSecurityPolicy *) customSecurityPolicy; -/** - * Log debug message - */ -+(void)debugLog:(NSString *)method message:(NSString *)format, ...; @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 1246dff7fca..a6745932320 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -2,7 +2,7 @@ NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; -static long requestId = 0; +static NSUInteger requestId = 0; static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; @@ -36,7 +36,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { @interface SWGApiClient () -@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; +@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; @end @@ -88,49 +88,6 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; } -#pragma mark - Log Methods - -+ (void)debugLog:(NSString *)method - message:(NSString *)format, ... { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (!config.debug) { - return; - } - - NSMutableString *message = [NSMutableString stringWithCapacity:1]; - - if (method) { - [message appendString:[NSString stringWithFormat:@"%@: ", method]]; - } - - va_list args; - va_start(args, format); - - [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; - - // If set logging file handler, log into file, - // otherwise log into console. - if (config.loggingFileHanlder) { - [config.loggingFileHanlder seekToEndOfFile]; - [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; - } - else { - NSLog(@"%@", message); - } - - va_end(args); -} - -- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { - - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - responseObject]; - - SWGDebugLog(message); -} - #pragma mark - Cache Methods +(void)clearCache { @@ -151,70 +108,6 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { [NSURLCache setSharedURLCache:cache]; } -#pragma mark - Utility Methods - -/* - * Detect `Accept` from accepts - */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { - return @""; - } - - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - // use rangeOfString instead of containsString for iOS 7 support - if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { - return @"application/json"; - } - [lowerAccepts addObject:lowerAccept]; - } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - - return [lowerAccepts componentsJoinedByString:@", "]; -} - -/* - * Detect `Content-Type` from contentTypes - */ -+ (NSString *) selectHeaderContentType:(NSArray *)contentTypes -{ - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; - } - - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; - } -} - -+ (NSString*)escape:(id)unescaped { - if ([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - #pragma mark - Request Methods +(unsigned long)requestQueueSize { @@ -223,14 +116,12 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { +(NSNumber*) nextRequestId { @synchronized(self) { - long nextId = ++requestId; - SWGDebugLog(@"got id %ld", nextId); - return [NSNumber numberWithLong:nextId]; + return @(++requestId); } } +(NSNumber*) queueRequest { - NSNumber* requestId = [SWGApiClient nextRequestId]; + NSNumber* requestId = [[self class] nextRequestId]; SWGDebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; @@ -294,7 +185,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { if (![strongSelf executeRequestWithId:requestId]) { return; } - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + SWGDebugLogResponse(response, responseObject,request,error); strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); @@ -321,7 +212,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return; } strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + SWGDebugLogResponse(response, responseObject,request,error); if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -370,14 +261,13 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { - NSAssert(false, @"unsupport request type %@", requestContentType); + NSAssert(NO, @"Unsupported request type %@", requestContentType); } // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { self.responseSerializer = [SWGJSONResponseSerializer serializer]; - } - else { + } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } @@ -393,8 +283,9 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSMutableString *resourcePath = [NSMutableString stringWithString:path]; [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] - withString:[SWGApiClient escape:obj]]; + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = SWGPercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; NSMutableURLRequest * request = nil; @@ -489,55 +380,56 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { - (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } NSString * separator = nil; - int counter = 0; + NSUInteger counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if (queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) separator = @"?"; - else separator = @"&"; - id queryParam = [queryParams valueForKey:key]; - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [SWGApiClient escape:[queryParams valueForKey:key]]]]; - } - else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ - SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - if ([format isEqualToString:@"csv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; - - } - else if ([format isEqualToString:@"tsv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; - - } - else if ([format isEqualToString:@"pipes"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; - - } - else if ([format isEqualToString:@"multi"]) { - for(id obj in values) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; - counter += 1; - } - - } - } - else { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; - } - - counter += 1; + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = SWGPercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, SWGPercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ + SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = SWGPercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = SWGPercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = SWGPercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; } return requestUrl; } @@ -558,15 +450,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; for (NSString *auth in authSettings) { - NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - - if (authSetting) { // auth setting is set only if the key is non-empty - if ([authSetting[@"in"] isEqualToString:@"header"] && [authSetting[@"key"] length] != 0) { - [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - else if ([authSetting[@"in"] isEqualToString:@"query"] && [authSetting[@"key"] length] != 0) { - [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } + NSDictionary *authSetting = [config authSettings][auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index 27cfe5d6d24..056175019a4 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -1,5 +1,6 @@ #import #import "SWGApiClient.h" +#import "SWGLogger.h" /** The `SWGConfiguration` class manages the configurations for the sdk. * @@ -12,6 +13,11 @@ @interface SWGConfiguration : NSObject +/** + * Default api logger + */ +@property (nonatomic, strong) SWGLogger * logger; + /** * Default api client */ @@ -37,7 +43,7 @@ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename for HTTP Basic Authentication + * Username for HTTP Basic Authentication */ @property (nonatomic) NSString *username; @@ -56,25 +62,11 @@ */ @property (nonatomic) NSString *tempFolderPath; -/** - * Logging Settings - */ - /** * Debug switch, default false */ @property (nonatomic) BOOL debug; -/** - * Debug file location, default log in console - */ -@property (nonatomic) NSString *loggingFile; - -/** - * Log file handler, this property is used by sdk internally. - */ -@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; - /** * Gets configuration singleton instance */ @@ -143,7 +135,7 @@ - (NSString *) getAccessToken; /** - * Gets Authentication Setings + * Gets Authentication Settings */ - (NSDictionary *) authSettings; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index dd1596bf8ce..b2430daaecd 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -30,12 +30,10 @@ self.username = @""; self.password = @""; self.accessToken= @""; - self.tempFolderPath = nil; - self.debug = NO; self.verifySSL = YES; - self.loggingFile = nil; self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + self.logger = [SWGLogger sharedLogger]; } return self; } @@ -43,11 +41,13 @@ #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; } - else if ([self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; } else { // return empty string if nothing is set return @""; @@ -70,8 +70,7 @@ - (NSString *) getAccessToken { if (self.accessToken.length == 0) { // token not set, return empty string return @""; - } - else { + } else { return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; } } @@ -94,20 +93,6 @@ [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } -- (void) setLoggingFile:(NSString *)loggingFile { - // close old file handler - if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { - [self.loggingFileHanlder closeFile]; - } - - _loggingFile = loggingFile; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (_loggingFileHanlder == nil) { - [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - } -} - #pragma mark - Getter Methods - (NSDictionary *) apiKey { @@ -139,4 +124,12 @@ }; } +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGLogger.h b/samples/client/petstore/objc/SwaggerClient/SWGLogger.h new file mode 100644 index 00000000000..19c1e509dfa --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWGLogger.h @@ -0,0 +1,54 @@ +#import + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#ifndef SWGDebugLogResponse +#define SWGDebugLogResponse(response, responseObject,request, error) [[SWGLogger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; +#endif + +/** + * Log debug message macro + */ +#ifndef SWGDebugLog +#define SWGDebugLog(format, ...) [[SWGLogger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif + +@interface SWGLogger : NSObject + ++(instancetype)sharedLogger; + +/** + * Enabled switch, default NO - default set by SWGConfiguration debug property + */ +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +/** + * Debug file location, default log in console + */ +@property (nonatomic, strong) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; + +/** + * Log debug message + */ +-(void)debugLog:(NSString *)method message:(NSString *)format, ...; + +/** + * Logs request and response + * + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGLogger.m b/samples/client/petstore/objc/SwaggerClient/SWGLogger.m new file mode 100644 index 00000000000..322ae9678d7 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWGLogger.m @@ -0,0 +1,74 @@ +#import "SWGLogger.h" + +@interface SWGLogger () + +@end + +@implementation SWGLogger + ++ (instancetype) sharedLogger { + static SWGLogger *shardLogger = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardLogger = [[self alloc] init]; + }); + return shardLogger; +} + +#pragma mark - Log Methods + +- (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + if (!self.isEnabled) { + return; + } + + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendFormat:@"%@: ", method]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. + if (self.loggingFileHandler) { + [self.loggingFileHandler seekToEndOfFile]; + [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } else { + NSLog(@"%@", message); + } + + va_end(args); +} + +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + responseObject]; + + SWGDebugLog(message); +} + +- (void) setLoggingFile:(NSString *)loggingFile { + if(_loggingFile == loggingFile) { + return; + } + // close old file handler + if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHandler closeFile]; + } + _loggingFile = loggingFile; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHandler == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index b3ebc31bf68..37b0f9407f7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -13,7 +13,7 @@ static SWGPetApi* singletonAPI = nil; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; @@ -26,7 +26,7 @@ static SWGPetApi* singletonAPI = nil; return self; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { +- (instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { self.apiClient = apiClient; @@ -79,31 +79,23 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -151,9 +143,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -168,22 +158,16 @@ static SWGPetApi* singletonAPI = nil; } // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -222,9 +206,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -235,22 +217,16 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -289,9 +265,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -302,22 +276,16 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -361,9 +329,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -373,22 +339,16 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth", @"api_key"]; @@ -427,31 +387,23 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -502,9 +454,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -514,22 +464,16 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -585,9 +529,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}/uploadImage"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -597,22 +539,16 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"multipart/form-data"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"multipart/form-data"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h index 5803999f362..aa2c6f85163 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h @@ -6,6 +6,8 @@ * Do not edit the class manually. */ +extern NSString * SWGPercentEscapedStringFromString(NSString *string); + @protocol SWGSanitizer /** @@ -20,6 +22,24 @@ */ - (NSString *) parameterToString: (id) param; +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ +-(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ +-(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + @end @interface SWGSanitizer : NSObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m index 3f1dea7726e..673904d6a83 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m @@ -3,6 +3,38 @@ #import "SWGQueryParamCollection.h" #import +NSString * SWGPercentEscapedStringFromString(NSString *string) { + static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@"; + static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kSWGCharactersGeneralDelimitersToEncode stringByAppendingString:kSWGCharactersSubDelimitersToEncode]]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + @interface SWGSanitizer () @end @@ -79,4 +111,52 @@ } } +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ +- (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts == nil || [accepts count] == 0) { + return @""; + } + + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + NSString * lowerAccept = [string lowercaseString]; + // use rangeOfString instead of containsString for iOS 7 support + if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { + return @"application/json"; + } + [lowerAccepts addObject:lowerAccept]; + } + + if (lowerAccepts.count == 1) { + return [lowerAccepts firstObject]; + } + + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ +- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { + if (contentTypes == nil || [contentTypes count] == 0) { + return @"application/json"; + } + + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerContentTypes addObject:[obj lowercaseString]]; + }]; + + if ([lowerContentTypes containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return lowerContentTypes[0]; + } +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index 336258c3c5b..91e5e495af2 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -13,7 +13,7 @@ static SWGStoreApi* singletonAPI = nil; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; @@ -26,7 +26,7 @@ static SWGStoreApi* singletonAPI = nil; return self; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { +- (instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { self.apiClient = apiClient; @@ -84,9 +84,7 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { @@ -96,22 +94,16 @@ static SWGStoreApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -148,31 +140,23 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"api_key"]; @@ -216,9 +200,7 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { @@ -228,22 +210,16 @@ static SWGStoreApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -282,31 +258,23 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 914d1822402..ecb5aa7ba53 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -13,7 +13,7 @@ static SWGUserApi* singletonAPI = nil; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; @@ -26,7 +26,7 @@ static SWGUserApi* singletonAPI = nil; return self; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { +- (instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { self.apiClient = apiClient; @@ -79,31 +79,23 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -143,31 +135,23 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -207,31 +191,23 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -276,9 +252,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -288,22 +262,16 @@ static SWGUserApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -347,9 +315,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -359,22 +325,16 @@ static SWGUserApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -416,9 +376,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -431,22 +389,16 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -483,31 +435,23 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -554,9 +498,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -566,22 +508,16 @@ static SWGUserApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m index 7ddc817e9ef..f472c4d6ab5 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m @@ -1,7 +1,6 @@ #import #import #import -#import @interface PetApiTest : XCTestCase { @private @@ -165,13 +164,13 @@ which causes an exception when deserializing the data SWGTag* tag = [[SWGTag alloc] init]; tag.name = @"tony"; NSLog(@"%@", pet._id); - pet.tags = (id)[[NSArray alloc] initWithObjects:tag, nil]; + pet.tags = (id) @[tag]; [api addPetWithBody:pet completionHandler:^(NSError *error) { if(error) { XCTFail(@"got error %@", error); } - NSArray* tags = [[NSArray alloc] initWithObjects:@"tony", nil]; + NSArray* tags = @[@"tony",@"tony2"]; [api findPetsByTagsWithTags:tags completionHandler:^(NSArray *output, NSError *error) { if(error){ @@ -275,7 +274,7 @@ which causes an exception when deserializing the data - (SWGPet*) createPet { SWGPet * pet = [[SWGPet alloc] init]; - pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; + pet._id = @((long) [[NSDate date] timeIntervalSince1970]); pet.name = @"monkey"; SWGCategory * category = [[SWGCategory alloc] init]; @@ -289,11 +288,11 @@ which causes an exception when deserializing the data SWGTag *tag2 = [[SWGTag alloc] init]; tag2._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; tag2.name = @"test tag 2"; - pet.tags = (NSArray *)[[NSArray alloc] initWithObjects:tag1, tag2, nil]; + pet.tags = (NSArray *) @[tag1, tag2]; pet.status = @"available"; - NSArray * photos = [[NSArray alloc] initWithObjects:@"http://foo.bar.com/3", @"http://foo.bar.com/4", nil]; + NSArray * photos = @[@"http://foo.bar.com/3", @"http://foo.bar.com/4"]; pet.photoUrls = photos; return pet; } diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index ed87d8f9e2d..644b50f6504 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -25,38 +25,40 @@ NSArray *accepts = nil; accepts = @[@"APPLICATION/JSON", @"APPLICATION/XML"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + SWGSanitizer * sanitizer = [[SWGSanitizer alloc] init]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"application/json", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"APPLICATION/xml", @"APPLICATION/json"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"text/plain", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"text/plain, application/xml"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"text/plain, application/xml"); accepts = @[]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @""); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @""); } - (void)testSelectHeaderContentType { NSArray *contentTypes = nil; - + SWGSanitizer * sanitizer = [[SWGSanitizer alloc] init]; + contentTypes = @[@"APPLICATION/JSON", @"APPLICATION/XML"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); contentTypes = @[@"application/json", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); contentTypes = @[@"APPLICATION/xml", @"APPLICATION/json"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); contentTypes = @[@"text/plain", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"text/plain"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"text/plain"); contentTypes = @[]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); } - (void)testConfiguration { From 620678503828a11baf43fdc792f595972b40d5c5 Mon Sep 17 00:00:00 2001 From: Mateusz Mackowiak Date: Wed, 11 May 2016 10:40:43 +0200 Subject: [PATCH 15/53] [Objc] bump AFNetworking version to 3 --- .../swagger-codegen/src/main/resources/objc/podspec.mustache | 4 ++-- samples/client/petstore/objc/README.md | 2 +- samples/client/petstore/objc/SwaggerClient.podspec | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index 2adf84d8c3e..c308a399c0a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -13,7 +13,7 @@ Pod::Spec.new do |s| {{#apiInfo}}{{#apis}}{{^hasMore}} s.summary = "{{appName}}" s.description = <<-DESC - {{appDescription}} + {{{appDescription}}} DESC {{/hasMore}}{{/apis}}{{/apiInfo}} s.platform = :ios, '7.0' @@ -29,7 +29,7 @@ Pod::Spec.new do |s| s.source_files = '{{podName}}/**/*' s.public_header_files = '{{podName}}/**/*.h' - s.dependency 'AFNetworking', '~> 2.3' + s.dependency 'AFNetworking', '~> 3' s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.5' end diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index 3efbcba5921..42b076c8461 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-05-10T21:51:45.108+02:00 +- Build date: 2016-05-11T10:37:53.050+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 41c66960b21..00766943c86 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -13,7 +13,7 @@ Pod::Spec.new do |s| s.summary = "Swagger Petstore" s.description = <<-DESC - This is a sample server Petstore server. You can find out more about Swagger at <a href="http://swagger.io">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters + This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters DESC s.platform = :ios, '7.0' @@ -29,7 +29,7 @@ Pod::Spec.new do |s| s.source_files = 'SwaggerClient/**/*' s.public_header_files = 'SwaggerClient/**/*.h' - s.dependency 'AFNetworking', '~> 2.3' + s.dependency 'AFNetworking', '~> 3' s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.5' end From 3948ae27a40aa12da4cc7c7872b0b6abc9825527 Mon Sep 17 00:00:00 2001 From: kolyjjj Date: Wed, 11 May 2016 18:28:01 +0800 Subject: [PATCH 16/53] upgrade version and delete scala-test property --- .../JavaSpringMVC/pom-j8-async.mustache | 5 +- .../petstore/spring-mvc-j8-async/pom.xml | 5 +- .../java/io/swagger/api/ApiException.java | 2 +- .../java/io/swagger/api/ApiOriginFilter.java | 2 +- .../io/swagger/api/ApiResponseMessage.java | 2 +- .../io/swagger/api/NotFoundException.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 47 +++++------ .../main/java/io/swagger/api/StoreApi.java | 14 ++-- .../src/main/java/io/swagger/api/UserApi.java | 30 +++---- .../swagger/configuration/SwaggerConfig.java | 6 +- .../configuration/SwaggerUiConfiguration.java | 2 +- .../swagger/configuration/WebApplication.java | 2 +- .../configuration/WebMvcConfiguration.java | 2 +- .../main/java/io/swagger/model/Category.java | 2 +- .../io/swagger/model/ModelApiResponse.java | 84 +++++++++++++++++++ .../src/main/java/io/swagger/model/Order.java | 4 +- .../src/main/java/io/swagger/model/Pet.java | 2 +- .../src/main/java/io/swagger/model/Tag.java | 2 +- .../src/main/java/io/swagger/model/User.java | 2 +- 19 files changed, 148 insertions(+), 69 deletions(-) create mode 100644 samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache index 257a4611db5..95c86d4bc0b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache @@ -163,10 +163,9 @@ 9.2.9.v20150224 1.13 1.6.3 - 1.6.1 4.8.1 2.5 - 2.0.4-SNAPSHOT - 4.0.9.RELEASE + 2.4.0 + 4.2.5.RELEASE \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-async/pom.xml b/samples/server/petstore/spring-mvc-j8-async/pom.xml index 1c535f34084..767c386463f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/pom.xml +++ b/samples/server/petstore/spring-mvc-j8-async/pom.xml @@ -163,10 +163,9 @@ 9.2.9.v20150224 1.13 1.6.3 - 1.6.1 4.8.1 2.5 - 2.0.4-SNAPSHOT - 4.0.9.RELEASE + 2.4.0 + 4.2.5.RELEASE \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java index 608a7957017..041a8a204f3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java index 0a2894d0be4..1276b3cfab0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java index 9bc56631d29..4859dc5c6c4 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java index 72ca217e7c0..67027e9eb9e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index c3d4887b35f..363b8deee1d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -3,6 +3,7 @@ package io.swagger.api; import io.swagger.model.*; import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; import java.io.File; import java.util.concurrent.Callable; @@ -34,7 +35,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface PetApi { @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { @@ -46,12 +47,12 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) default Callable> addPet( -@ApiParam(value = "Pet object that needs to be added to the store" ) @RequestBody Pet body +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body ) throws NotFoundException { // do some magic! @@ -68,7 +69,7 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deletePet( @@ -85,7 +86,7 @@ public interface PetApi { } - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -95,10 +96,10 @@ public interface PetApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid status value") }) @RequestMapping(value = "/findByStatus", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status + default Callable>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status ) @@ -108,7 +109,7 @@ public interface PetApi { } - @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -118,10 +119,10 @@ public interface PetApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid tag value") }) @RequestMapping(value = "/findByTags", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable>> findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags + default Callable>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags ) @@ -131,11 +132,7 @@ public interface PetApi { } - @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }), + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") }) @ApiResponses(value = { @@ -143,11 +140,11 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getPetById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId ) throws NotFoundException { @@ -167,12 +164,12 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found"), @ApiResponse(code = 405, message = "Validation exception") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) default Callable> updatePet( -@ApiParam(value = "Pet object that needs to be added to the store" ) @RequestBody Pet body +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body ) throws NotFoundException { // do some magic! @@ -189,11 +186,11 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) default Callable> updatePetWithForm( -@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId , @@ -212,7 +209,7 @@ public interface PetApi { } - @ApiOperation(value = "uploads an image", notes = "", response = Void.class, authorizations = { + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -221,10 +218,10 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/{petId}/uploadImage", - produces = { "application/json", "application/xml" }, + produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - default Callable> uploadFile( + default Callable> uploadFile( @ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId , @@ -239,7 +236,7 @@ public interface PetApi { ) throws NotFoundException { // do some magic! - return () -> new ResponseEntity(HttpStatus.OK); + return () -> new ResponseEntity(HttpStatus.OK); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java index 4eb6c73849a..f5c454b68e1 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java @@ -34,7 +34,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @@ -42,7 +42,7 @@ public interface StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deleteOrder( @@ -61,7 +61,7 @@ public interface StoreApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/inventory", - produces = { "application/json", "application/xml" }, + produces = { "application/json" }, method = RequestMethod.GET) default Callable>> getInventory() @@ -77,11 +77,11 @@ public interface StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getOrderById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId ) throws NotFoundException { @@ -95,12 +95,12 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid Order") }) @RequestMapping(value = "/order", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> placeOrder( -@ApiParam(value = "order placed for purchasing the pet" ) @RequestBody Order body +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java index b24082923dc..7141c53284d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java @@ -34,19 +34,19 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUser( -@ApiParam(value = "Created user object" ) @RequestBody User body +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body ) throws NotFoundException { // do some magic! @@ -58,12 +58,12 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/createWithArray", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUsersWithArrayInput( -@ApiParam(value = "List of user object" ) @RequestBody List body +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body ) throws NotFoundException { // do some magic! @@ -75,12 +75,12 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/createWithList", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUsersWithListInput( -@ApiParam(value = "List of user object" ) @RequestBody List body +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body ) throws NotFoundException { // do some magic! @@ -93,7 +93,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deleteUser( @@ -112,7 +112,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getUserByName( @@ -130,14 +130,14 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid username/password supplied") }) @RequestMapping(value = "/login", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable> loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username + default Callable> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username , - @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password ) @@ -151,7 +151,7 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/logout", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> logoutUser() @@ -166,7 +166,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid user supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) default Callable> updateUser( @@ -175,7 +175,7 @@ public interface UserApi { , -@ApiParam(value = "Updated user object" ) @RequestBody User body +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java index 5004845542f..3b3f1c4e719 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -20,18 +20,18 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger Petstore") - .description("This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters") + .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .termsOfServiceUrl("") .version("1.0.0") - .contact(new Contact("","", "apiteam@wordnik.com")) + .contact(new Contact("","", "apiteam@swagger.io")) .build(); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index 6b3b305942f..b68e3a5d9f8 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,7 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java index 7e437ae6b14..e99cfea70a2 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,7 +2,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index 40f8a10a438..70ad7190474 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,7 +3,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java index 18f08f895e1..e9d8c1ffed0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..61d9bc8be58 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,84 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" type: ").append(type).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java index 738a9e81f96..8ea322ac31d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Order { private Long id = null; @@ -23,7 +23,7 @@ public class Order { }; private StatusEnum status = null; - private Boolean complete = null; + private Boolean complete = false; /** **/ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java index 26e4d3c529e..482e8e16097 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java @@ -14,7 +14,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java index 2f39f45a1f8..895fb2a7e1f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java index eee7800acbf..5620b9d4b72 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class User { private Long id = null; From 77428b8a836aef477e44c21b957d4e74c41ca1eb Mon Sep 17 00:00:00 2001 From: Takuro Wada Date: Thu, 12 May 2016 00:32:09 +0900 Subject: [PATCH 17/53] Fix npm error & import error in generated code --- .../main/resources/typescript-angular2/api.mustache | 1 + .../resources/typescript-angular2/package.mustache | 11 ++++++++++- .../typescript-angular2/default/api/PetApi.ts | 1 + .../typescript-angular2/default/api/StoreApi.ts | 1 + .../typescript-angular2/default/api/UserApi.ts | 1 + .../petstore/typescript-angular2/npm/README.md | 4 ++-- .../petstore/typescript-angular2/npm/api/PetApi.ts | 1 + .../typescript-angular2/npm/api/StoreApi.ts | 1 + .../petstore/typescript-angular2/npm/api/UserApi.ts | 1 + .../petstore/typescript-angular2/npm/package.json | 13 +++++++++++-- 10 files changed, 30 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index 4eae99d749e..efc6e00c633 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -2,6 +2,7 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@ang import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache index 62270e878c9..547200a6695 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache @@ -22,11 +22,20 @@ "@angular/http": "^2.0.0-rc.1", "@angular/platform-browser": "^2.0.0-rc.1", "@angular/platform-browser-dynamic": "^2.0.0-rc.1", - "core-js": "^2.3.0" + "core-js": "^2.3.0", "rxjs": "^5.0.0-beta.6", "zone.js": "^0.6.12" }, "devDependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12", "typescript": "^1.8.10", "typings": "^0.8.1", "es6-shim": "^0.35.0", diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 4a858fa75ed..a708d49e9f9 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -2,6 +2,7 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@ang import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index b6c8b5022b0..e6602884a81 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -2,6 +2,7 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@ang import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index 0fd1fd0d25e..04d2e8155d5 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -2,6 +2,7 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@ang import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 6b1e698e766..0fdbf4a4ded 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605061603 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605120027 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605061603 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605120027 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 4a858fa75ed..a708d49e9f9 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -2,6 +2,7 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@ang import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index b6c8b5022b0..e6602884a81 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -2,6 +2,7 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@ang import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index 0fd1fd0d25e..04d2e8155d5 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -2,6 +2,7 @@ import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@ang import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index ca4f885a4bf..8447881dafc 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201605061603", + "version": "0.0.1-SNAPSHOT.201605120027", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ @@ -22,11 +22,20 @@ "@angular/http": "^2.0.0-rc.1", "@angular/platform-browser": "^2.0.0-rc.1", "@angular/platform-browser-dynamic": "^2.0.0-rc.1", - "core-js": "^2.3.0" + "core-js": "^2.3.0", "rxjs": "^5.0.0-beta.6", "zone.js": "^0.6.12" }, "devDependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12", "typescript": "^1.8.10", "typings": "^0.8.1", "es6-shim": "^0.35.0", From 567c23a3df7a3517206c8eb0615d3e929a366e3a Mon Sep 17 00:00:00 2001 From: Mateusz Mackowiak Date: Wed, 11 May 2016 17:39:28 +0200 Subject: [PATCH 18/53] [Objc] Support for variations of application/json type --- .../resources/objc/Sanitizer-body.mustache | 84 ++++++++++--------- samples/client/petstore/objc/README.md | 2 +- .../objc/SwaggerClient/SWGSanitizer.m | 80 ++++++++++-------- .../Tests/SWGApiClientTest.m | 23 ++++- 4 files changed, 111 insertions(+), 78 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache index f43e6493d75..a111aad9cef 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache @@ -16,30 +16,44 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { NSMutableString *escaped = @"".mutableCopy; while (index < string.length) { - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wgnu" - NSUInteger length = MIN(string.length - index, batchSize); - #pragma GCC diagnostic pop - NSRange range = NSMakeRange(index, length); + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); - // To avoid breaking up character sequences such as 👴🏻👮🏽 - range = [string rangeOfComposedCharacterSequencesForRange:range]; + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; - NSString *substring = [string substringWithRange:range]; - NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; - [escaped appendString:encoded]; + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; - index += range.length; + index += range.length; } return escaped; } -@interface {{classPrefix}}Sanitizer () +@interface SWGSanitizer () + +@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; @end -@implementation {{classPrefix}}Sanitizer +@implementation SWGSanitizer + +static NSString * kApplicationJSONType = @"application/json"; + +-(instancetype)init { + self = [super init]; + if ( !self ) { + return nil; + } + _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; + return self; +} + - (id) sanitizeForSerialization:(id) object { if (object == nil) { @@ -49,7 +63,7 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { return object; } else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; + return [self dateParameterToString:object]; } else if ([object isKindOfClass:[NSArray class]]) { NSArray *objectArray = object; @@ -93,7 +107,7 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { return [param stringValue]; } else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; + return [self dateParameterToString:param]; } else if ([param isKindOfClass:[NSArray class]]) { NSMutableArray *mutableParam = [NSMutableArray array]; @@ -111,30 +125,26 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { } } +- (NSString *)dateParameterToString:(id)param { + return [param ISO8601String]; +} + #pragma mark - Utility Methods /* * Detect `Accept` from accepts */ - (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { + if (accepts.count == 0) { return @""; } - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - // use rangeOfString instead of containsString for iOS 7 support - if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { - return @"application/json"; + if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { + return kApplicationJSONType; } - [lowerAccepts addObject:lowerAccept]; + [lowerAccepts addObject:[string lowercaseString]]; } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - return [lowerAccepts componentsJoinedByString:@", "]; } @@ -142,21 +152,17 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { * Detect `Content-Type` from contentTypes */ - (NSString *) selectHeaderContentType:(NSArray *)contentTypes { - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; + if (contentTypes.count == 0) { + return kApplicationJSONType; } - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; + for (NSString *string in contentTypes) { + if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ + return kApplicationJSONType; + } + [lowerContentTypes addObject:[string lowercaseString]]; } + return [lowerContentTypes firstObject]; } @end diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index d0ae437a93c..b411635fe8a 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-05-10T17:16:13.387+02:00 +- Build date: 2016-05-11T17:37:37.440+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m index 673904d6a83..a74f72afbe3 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m @@ -16,20 +16,20 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) { NSMutableString *escaped = @"".mutableCopy; while (index < string.length) { - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wgnu" - NSUInteger length = MIN(string.length - index, batchSize); - #pragma GCC diagnostic pop - NSRange range = NSMakeRange(index, length); + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); - // To avoid breaking up character sequences such as 👴🏻👮🏽 - range = [string rangeOfComposedCharacterSequencesForRange:range]; + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; - NSString *substring = [string substringWithRange:range]; - NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; - [escaped appendString:encoded]; + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; - index += range.length; + index += range.length; } return escaped; @@ -37,10 +37,24 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) { @interface SWGSanitizer () +@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; + @end @implementation SWGSanitizer +static NSString * kApplicationJSONType = @"application/json"; + +-(instancetype)init { + self = [super init]; + if ( !self ) { + return nil; + } + _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; + return self; +} + + - (id) sanitizeForSerialization:(id) object { if (object == nil) { return nil; @@ -49,7 +63,7 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) { return object; } else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; + return [self dateParameterToString:object]; } else if ([object isKindOfClass:[NSArray class]]) { NSArray *objectArray = object; @@ -93,7 +107,7 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) { return [param stringValue]; } else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; + return [self dateParameterToString:param]; } else if ([param isKindOfClass:[NSArray class]]) { NSMutableArray *mutableParam = [NSMutableArray array]; @@ -111,30 +125,26 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) { } } +- (NSString *)dateParameterToString:(id)param { + return [param ISO8601String]; +} + #pragma mark - Utility Methods /* * Detect `Accept` from accepts */ - (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { + if (accepts.count == 0) { return @""; } - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - // use rangeOfString instead of containsString for iOS 7 support - if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { - return @"application/json"; + if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { + return kApplicationJSONType; } - [lowerAccepts addObject:lowerAccept]; + [lowerAccepts addObject:[string lowercaseString]]; } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - return [lowerAccepts componentsJoinedByString:@", "]; } @@ -142,21 +152,17 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) { * Detect `Content-Type` from contentTypes */ - (NSString *) selectHeaderContentType:(NSArray *)contentTypes { - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; + if (contentTypes.count == 0) { + return kApplicationJSONType; } - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; + for (NSString *string in contentTypes) { + if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ + return kApplicationJSONType; + } + [lowerContentTypes addObject:[string lowercaseString]]; } + return [lowerContentTypes firstObject]; } @end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index 644b50f6504..205c3a290f8 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -33,6 +33,18 @@ accepts = @[@"APPLICATION/xml", @"APPLICATION/json"]; XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/json;charset=utf-8", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github.v3.html+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github.v3.html+json"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"text/plain", @"application/xml"]; XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"text/plain, application/xml"); @@ -53,7 +65,16 @@ contentTypes = @[@"APPLICATION/xml", @"APPLICATION/json"]; XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); - + + contentTypes = @[@"application/vnd.github+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/json;charset=utf-8", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/vnd.github.v3.html+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + contentTypes = @[@"text/plain", @"application/xml"]; XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"text/plain"); From ac37c4364954f1baa7061ee45f068c1037b0119c Mon Sep 17 00:00:00 2001 From: Mateusz Mackowiak Date: Wed, 11 May 2016 18:20:15 +0200 Subject: [PATCH 19/53] [Objc] Moved [request setHTTPShouldHandleCookies:NO]; to postProcessRequest method for easier override to modify request. --- .../main/resources/objc/ApiClient-body.mustache | 15 ++++++++------- samples/client/petstore/objc/README.md | 2 +- .../petstore/objc/SwaggerClient/SWGApiClient.m | 15 ++++++++------- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 6b9d3e841bb..37bdfd8f4a7 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -329,10 +329,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } // request cache - BOOL hasHeaderParams = false; - if (headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } + BOOL hasHeaderParams = [headerParams count] > 0; if (offlineState) { {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; @@ -353,9 +350,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + [self postProcessRequest:request]; NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { @@ -376,6 +371,12 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return requestId; } +//Added for easier override to modify request +-(void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + #pragma mark - - (NSString*) pathWithQueryParamsToString:(NSString*) path diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index b411635fe8a..6fbc67a7fae 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-05-11T17:37:37.440+02:00 +- Build date: 2016-05-11T18:16:45.229+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index a6745932320..55e84a056a4 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -329,10 +329,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { } // request cache - BOOL hasHeaderParams = false; - if (headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } + BOOL hasHeaderParams = [headerParams count] > 0; if (offlineState) { SWGDebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; @@ -353,9 +350,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { } [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + [self postProcessRequest:request]; NSNumber* requestId = [SWGApiClient queueRequest]; if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { @@ -376,6 +371,12 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return requestId; } +//Added for easier override to modify request +-(void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + #pragma mark - - (NSString*) pathWithQueryParamsToString:(NSString*) path From 524ced1d9bffa392c40460521efcfb0305214343 Mon Sep 17 00:00:00 2001 From: Christophe Jolif Date: Thu, 12 May 2016 11:57:43 +0200 Subject: [PATCH 20/53] Fix regression on swift enum name as well as make sure enum var name with colons ouput compiable swift. Add a test. fixes #2824, fixes #2835 --- .../codegen/languages/SwiftCodegen.java | 8 +- .../Classes/Swaggers/APIs/PetAPI.swift | 106 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 64 +++++------ .../Classes/Swaggers/APIs/UserAPI.swift | 44 ++++---- .../Classes/Swaggers/Models.swift | 4 +- .../Classes/Swaggers/Models/Order.swift | 4 +- .../Classes/Swaggers/Models/Pet.swift | 4 +- .../SwaggerClientTests/StoreAPITests.swift | 3 +- 8 files changed, 120 insertions(+), 117 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index ba846857cb9..9d6d891df70 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -355,8 +355,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { return value; } - char[] separators = {'-', '_', ' '}; - return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ ]", ""); + char[] separators = {'-', '_', ' ', ':'}; + return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :]", ""); } @@ -502,6 +502,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + // TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value)); // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { String varName = new String(name); @@ -525,8 +526,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(); + String enumName = toModelName(property.name); + // TODO: toModelName already does something for names starting with number, so this code is probably never called if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 64aa3c8803c..019be89261f 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -155,13 +155,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -218,20 +218,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -240,21 +240,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -263,7 +263,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -317,26 +317,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -345,21 +345,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -368,7 +368,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 4521afd3d89..5be63ad74d0 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -98,12 +98,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - returns: RequestBuilder<[String:Int32]> */ @@ -153,36 +153,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -235,36 +235,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 62018cd83c2..9e527b4f5f3 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -244,16 +244,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -262,17 +262,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}] + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -281,7 +281,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -336,8 +336,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift index 0aa3b3e381c..f9e2f72b908 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift @@ -156,7 +156,7 @@ class Decoders { instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"]) instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"]) instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"]) - instance.status = Order.ST(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"]) return instance } @@ -175,7 +175,7 @@ class Decoders { instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"]) instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) - instance.status = Pet.ST(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") return instance } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift index e4086143266..87b2a2c5247 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -9,7 +9,7 @@ import Foundation public class Order: JSONEncodable { - public enum ST: String { + public enum Status: String { case Placed = "placed" case Approved = "approved" case Delivered = "delivered" @@ -19,7 +19,7 @@ public class Order: JSONEncodable { public var quantity: Int32? public var shipDate: NSDate? /** Order Status */ - public var status: ST? + public var status: Status? public var complete: Bool? public init() {} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift index ee9aa295a53..ebcd2c1825f 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -9,7 +9,7 @@ import Foundation public class Pet: JSONEncodable { - public enum ST: String { + public enum Status: String { case Available = "available" case Pending = "pending" case Sold = "sold" @@ -20,7 +20,7 @@ public class Pet: JSONEncodable { public var photoUrls: [String]? public var tags: [Tag]? /** pet status in the store */ - public var status: ST? + public var status: Status? public init() {} diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 38948737687..b52fe4a0fa8 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -32,7 +32,8 @@ class StoreAPITests: XCTestCase { order.complete = false order.quantity = 10 order.shipDate = NSDate() - order.status = .Placed + // use explicit naming to reference the enum so that we test we don't regress on enum naming + order.status = Order.Status.Placed let expectation = self.expectationWithDescription("testPlaceOrder") StoreAPI.placeOrder(body: order).then { order -> Void in XCTAssert(order.id == 1000, "invalid id") From a06ba7d4b86e492a1b96128318d1eb970926af0d Mon Sep 17 00:00:00 2001 From: Mikolaj Przybysz Date: Thu, 12 May 2016 16:53:21 +0200 Subject: [PATCH 21/53] Enable skipping version in composer.json --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 738ffd4e0d5..c434bbe7a04 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -35,7 +35,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String composerVendorName = "swagger"; protected String composerProjectName = "swagger-client"; protected String packagePath = "SwaggerClient-php"; - protected String artifactVersion = "1.0.0"; + protected String artifactVersion = null; protected String srcBasePath = "lib"; protected String testBasePath = "test"; protected String docsBasePath = "docs"; From 32a6099853906d38bbd99cb9f8f4951374bfa024 Mon Sep 17 00:00:00 2001 From: zhenjun115 Date: Thu, 12 May 2016 23:04:43 +0800 Subject: [PATCH 22/53] add gitignore.mustache and git_push.mustache for android api client using volley; --- .../languages/AndroidClientCodegen.java | 2 + .../libraries/volley/git_push.sh.mustache | 51 +++++++++++++++++++ .../libraries/volley/gitignore.mustache | 39 ++++++++++++++ .../client/petstore/android/volley/.gitignore | 39 ++++++++++++++ .../petstore/android/volley/git_push.sh | 51 +++++++++++++++++++ 5 files changed, 182 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache create mode 100644 modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache create mode 100644 samples/client/petstore/android/volley/.gitignore create mode 100644 samples/client/petstore/android/volley/git_push.sh diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 282c4d88647..b1e1515254f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -418,6 +418,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi } private void addSupportingFilesForVolley() { + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); // supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache new file mode 100644 index 00000000000..079d91582ef --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache @@ -0,0 +1,51 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache new file mode 100644 index 00000000000..a7b72d554da --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +# Keystore files +*.jks \ No newline at end of file diff --git a/samples/client/petstore/android/volley/.gitignore b/samples/client/petstore/android/volley/.gitignore new file mode 100644 index 00000000000..a7b72d554da --- /dev/null +++ b/samples/client/petstore/android/volley/.gitignore @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +# Keystore files +*.jks \ No newline at end of file diff --git a/samples/client/petstore/android/volley/git_push.sh b/samples/client/petstore/android/volley/git_push.sh new file mode 100644 index 00000000000..f711c4b3130 --- /dev/null +++ b/samples/client/petstore/android/volley/git_push.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' \ No newline at end of file From 154f85992e484f5b747e77b11f7979c14716928d Mon Sep 17 00:00:00 2001 From: Christophe Jolif Date: Thu, 12 May 2016 17:10:01 +0200 Subject: [PATCH 23/53] fix typo --- .../swagger-codegen/src/main/resources/swift/Models.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 378c83525f1..49798250e72 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -46,9 +46,9 @@ class Decoders { } static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { - let sourceDictinoary = source as! [Key: AnyObject] + let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() - for (key, value) in sourceDictinoary { + for (key, value) in sourceDictionary { dictionary[key] = Decoders.decode(clazz: T.self, source: value) } return dictionary From 840adb8aa32d7afa2d9fc8a436229e096bdf93e3 Mon Sep 17 00:00:00 2001 From: Kim Sondrup Date: Thu, 12 May 2016 20:05:55 +0200 Subject: [PATCH 24/53] [PHP] model list_invalid_properties change to camelCase --- modules/swagger-codegen/src/main/resources/php/model.mustache | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Animal.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php | 2 +- samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/Category.php | 2 +- samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/FormatTest.php | 2 +- .../php/SwaggerClient-php/lib/Model/Model200Response.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Name.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Order.php | 2 +- samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php | 2 +- .../php/SwaggerClient-php/lib/Model/SpecialModelName.php | 2 +- samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/User.php | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index f4f415cd4a4..55a7e4458a1 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -140,7 +140,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); {{#vars}}{{#required}} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 82d29699f8a..efe77d9b11c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -129,7 +129,7 @@ class Animal implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index e6e7b7bcd84..0d1177f5e45 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -150,7 +150,7 @@ class ApiResponse implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 4bc0f89d9e2..ba8eee4b01a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -126,7 +126,7 @@ class Cat extends Animal implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 55b391feabd..4fd9c42c290 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -138,7 +138,7 @@ class Category implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index d092850ab79..7030ea05758 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -126,7 +126,7 @@ class Dog extends Animal implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 6f5c75d28eb..a0e4d2ba61f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -258,7 +258,7 @@ class FormatTest implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 1ee9011b8f7..f69261948e1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -126,7 +126,7 @@ class Model200Response implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index d15f82a5057..83ba9847e12 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -126,7 +126,7 @@ class ModelReturn implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index 991ab945b4e..8d5b38d5882 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -150,7 +150,7 @@ class Name implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index a7b6b22f4c7..9a799156399 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -186,7 +186,7 @@ class Order implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 319d23a839e..aacb34bd446 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -186,7 +186,7 @@ class Pet implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index 200470d99d2..7bd4390758f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -126,7 +126,7 @@ class SpecialModelName implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index e493bdfd3e3..50ded1a259c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -138,7 +138,7 @@ class Tag implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 3b09cea0fd2..3c95ec1638b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -210,7 +210,7 @@ class User implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); From 6bb953d0aafa1b325c24b51234bd0612fb90ece8 Mon Sep 17 00:00:00 2001 From: Kim Sondrup Date: Fri, 13 May 2016 00:31:45 +0200 Subject: [PATCH 25/53] [PHP] Remove trailing spaces from templates --- .../src/main/resources/php/ApiClient.mustache | 14 +++++----- .../resources/php/ObjectSerializer.mustache | 12 ++++---- .../src/main/resources/php/README.mustache | 4 +-- .../src/main/resources/php/api.mustache | 24 ++++++++-------- .../src/main/resources/php/api_doc.mustache | 4 +-- .../src/main/resources/php/api_test.mustache | 4 +-- .../src/main/resources/php/autoload.mustache | 6 ++-- .../main/resources/php/git_push.sh.mustache | 2 +- .../src/main/resources/php/model.mustache | 28 +++++++++---------- .../main/resources/php/model_generic.mustache | 28 +++++++++---------- 10 files changed, 63 insertions(+), 63 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 5b8b9b21632..5561828e847 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -160,7 +160,7 @@ class ApiClient if ($this->config->getCurlTimeout() != 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } - // return the result on success, rather than just true + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -300,11 +300,11 @@ class ApiClient // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); $key = ''; - + foreach(explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); - + if (isset($h[1])) { if (!isset($headers[$h[0]])) @@ -317,18 +317,18 @@ class ApiClient { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } - + $key = $h[0]; } else { - if (substr($h[0], 0, 1) == "\t") - $headers[$key] .= "\r\n\t".trim($h[0]); + if (substr($h[0], 0, 1) == "\t") + $headers[$key] .= "\r\n\t".trim($h[0]); elseif (!$key) $headers[0] = trim($h[0]);trim($h[0]); } } - + return $headers; } } diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 34d79b0ae39..46f457fca32 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -1,6 +1,6 @@ fwrite($data); error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); return $deserialized; - + } else { // If a discriminator is defined and points to a valid subclass, use it. if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { @@ -282,11 +282,11 @@ class ObjectSerializer $instance = new $class(); foreach ($instance::swaggerTypes() as $property => $type) { $propertySetter = $instance::setters()[$property]; - + if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { continue; } - + $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index 3049d013ca5..1bc31869371 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -46,7 +46,7 @@ Download the files and include `autoload.php`: require_once('/path/to/{{packagePath}}/autoload.php'); ``` -## Tests +## Tests To run the unit tests: @@ -108,7 +108,7 @@ Class | Method | HTTP request | Description {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} {{#authMethods}}## {{{name}}} -{{#isApiKey}}- **Type**: API key +{{#isApiKey}}- **Type**: API key - **API key parameter name**: {{{keyParamName}}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index cc74dfd3a2a..3e8085fb006 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -55,7 +55,7 @@ use \{{invokerPackage}}\ObjectSerializer; * @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use @@ -66,10 +66,10 @@ use \{{invokerPackage}}\ObjectSerializer; $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('{{basePath}}'); } - + $this->apiClient = $apiClient; } - + /** * Get API client * @return \{{invokerPackage}}\ApiClient get the API client @@ -78,7 +78,7 @@ use \{{invokerPackage}}\ObjectSerializer; { return $this->apiClient; } - + /** * Set the API client * @param \{{invokerPackage}}\ApiClient $apiClient set the API client @@ -89,7 +89,7 @@ use \{{invokerPackage}}\ObjectSerializer; $this->apiClient = $apiClient; return $this; } - + {{#operation}} /** * {{{operationId}}} @@ -103,7 +103,7 @@ use \{{invokerPackage}}\ObjectSerializer; public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { list($response) = $this->{{operationId}}WithHttpInfo ({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - return $response; + return $response; } @@ -153,7 +153,7 @@ use \{{invokerPackage}}\ObjectSerializer; {{/hasValidation}} {{/allParams}} - + // parse inputs $resourcePath = "{{path}}"; $httpBody = ''; @@ -165,7 +165,7 @@ use \{{invokerPackage}}\ObjectSerializer; $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); - + {{#queryParams}}// query params {{#collectionFormat}} if (is_array(${{paramName}})) { @@ -220,7 +220,7 @@ use \{{invokerPackage}}\ObjectSerializer; if (isset(${{paramName}})) { $_tempBody = ${{paramName}}; }{{/bodyParams}} - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -264,7 +264,7 @@ use \{{invokerPackage}}\ObjectSerializer; $e->setResponseObject($data); break;{{/dataType}}{{/responses}} } - + throw $e; } } diff --git a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache index 4cf01aa510b..fa6033b084a 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache @@ -17,7 +17,7 @@ Method | HTTP request | Description {{{notes}}}{{/notes}} -### Example +### Example ```php {{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} print_r($result);{{/returnType}} } catch (Exception $e) { diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index fc07d338301..cd88433de32 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache index 04be6e11992..70a61878edb 100644 --- a/modules/swagger-codegen/src/main/resources/php/autoload.mustache +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -1,13 +1,13 @@ '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - + static function getters() { return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters; } @@ -152,7 +152,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -204,8 +204,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -309,7 +309,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{/vars}} /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -319,17 +319,17 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -341,17 +341,17 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 006cd09c62a..202c608edef 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -1,19 +1,19 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayAccess { /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - + static function swaggerTypes() { return self::$swaggerTypes{{#parent}} + parent::swaggerTypes(){{/parent}}; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -21,7 +21,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - + static function attributeMap() { return {{#parent}}parent::attributeMap() + {{/parent}}self::$attributeMap; } @@ -34,7 +34,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - + static function setters() { return {{#parent}}parent::setters() + {{/parent}}self::$setters; } @@ -47,7 +47,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - + static function getters() { return {{#parent}}parent::getters() + {{/parent}}self::$getters; } @@ -115,7 +115,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{/vars}} /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -125,17 +125,17 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return $this->$offset; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -143,17 +143,17 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA { $this->$offset = $value; } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->$offset); } - + /** * Gets the string presentation of the object. * @return string From b2f5d8c060331826da2f1700f154f575d2a5a3ed Mon Sep 17 00:00:00 2001 From: Kim Sondrup Date: Fri, 13 May 2016 01:47:59 +0200 Subject: [PATCH 26/53] [PHP] Made coding standard more consistent across template files --- .../src/main/resources/php/ApiClient.mustache | 15 ++++++++++++--- .../main/resources/php/ApiException.mustache | 6 ++++++ .../src/main/resources/php/api.mustache | 17 ++++++++++++----- .../src/main/resources/php/api_test.mustache | 9 ++++++--- .../src/main/resources/php/autoload.mustache | 1 + .../src/main/resources/php/model.mustache | 6 ++++-- .../src/main/resources/php/model_enum.mustache | 3 ++- .../main/resources/php/model_generic.mustache | 15 ++++++++++----- .../src/main/resources/php/model_test.mustache | 9 ++++++--- 9 files changed, 59 insertions(+), 22 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 5561828e847..252c5d4a950 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -55,18 +55,21 @@ class ApiClient /** * Configuration + * * @var Configuration */ protected $config; /** * Object Serializer + * * @var ObjectSerializer */ protected $serializer; /** * Constructor of the class + * * @param Configuration $config config for this ApiClient */ public function __construct(\{{invokerPackage}}\Configuration $config = null) @@ -81,6 +84,7 @@ class ApiClient /** * Get the config + * * @return Configuration */ public function getConfig() @@ -90,6 +94,7 @@ class ApiClient /** * Get the serializer + * * @return ObjectSerializer */ public function getSerializer() @@ -99,7 +104,9 @@ class ApiClient /** * Get API key (with prefix if set) + * * @param string $apiKeyIdentifier name of apikey + * * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKeyIdentifier) @@ -122,12 +129,14 @@ class ApiClient /** * Make the HTTP call (Sync) + * * @param string $resourcePath path to method endpoint * @param string $method method to call * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header * @param string $responseType expected response type of the endpoint + * * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ @@ -171,7 +180,7 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } - if (! empty($queryParams)) { + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } @@ -216,7 +225,7 @@ class ApiClient // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = $this->http_parse_headers(substr($response, 0, $http_header_size)); + $http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size)); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); @@ -295,7 +304,7 @@ class ApiClient * * @return string[] Array of HTTP response heaers */ - protected function http_parse_headers($raw_headers) + protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index eee688001ed..64dec1572ab 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -48,24 +48,28 @@ class ApiException extends Exception /** * The HTTP body of the server response either as Json or string. + * * @var mixed */ protected $responseBody; /** * The HTTP header of the server response. + * * @var string[] */ protected $responseHeaders; /** * The deserialized response object + * * @var $responseObject; */ protected $responseObject; /** * Constructor + * * @param string $message Error message * @param int $code HTTP status code * @param string $responseHeaders HTTP response header @@ -100,7 +104,9 @@ class ApiException extends Exception /** * Sets the deseralized response object (during deserialization) + * * @param mixed $obj Deserialized response object + * * @return void */ public function setResponseObject($obj) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 3e8085fb006..34827ed0117 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -52,12 +52,14 @@ use \{{invokerPackage}}\ObjectSerializer; /** * API Client + * * @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ protected $apiClient; /** * Constructor + * * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use */ function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) @@ -72,6 +74,7 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Get API client + * * @return \{{invokerPackage}}\ApiClient get the API client */ public function getApiClient() @@ -81,7 +84,9 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Set the API client + * * @param \{{invokerPackage}}\ApiClient $apiClient set the API client + * * @return {{classname}} */ public function setApiClient(\{{invokerPackage}}\ApiClient $apiClient) @@ -92,28 +97,30 @@ use \{{invokerPackage}}\ObjectSerializer; {{#operation}} /** - * {{{operationId}}} + * Operation {{{operationId}}} * * {{{summary}}} * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} - {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{/allParams}} * + * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} * @throws \{{invokerPackage}}\ApiException on non-2xx response */ public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - list($response) = $this->{{operationId}}WithHttpInfo ({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + list($response) = $this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); return $response; } /** - * {{{operationId}}}WithHttpInfo + * Operation {{{operationId}}}WithHttpInfo * * {{{summary}}} * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} - {{/allParams}} * @return Array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) + {{/allParams}} * + * @return Array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) * @throws \{{invokerPackage}}\ApiException on non-2xx response */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index cd88433de32..d41e76d040d 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -53,14 +53,16 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } @@ -71,7 +73,8 @@ use \{{invokerPackage}}\ObjectSerializer; * {{{summary}}} * */ - public function test_{{operationId}}() { + public function test_{{operationId}}() + { } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache index 70a61878edb..0942715ce8d 100644 --- a/modules/swagger-codegen/src/main/resources/php/autoload.mustache +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -9,6 +9,7 @@ * new \{{invokerPackage}}\Baz\Qux; * * @param string $class The fully-qualified class name. + * * @return void */ spl_autoload_register(function ($class) { diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 993596836a6..80c4a5dde6c 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -103,7 +103,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{/hasMore}}{{/vars}} ); - static function getters() { + static function getters() + { return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters; } @@ -115,7 +116,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_enum.mustache b/modules/swagger-codegen/src/main/resources/php/model_enum.mustache index 4598f9fdff9..ffb268c6cb9 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_enum.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_enum.mustache @@ -7,7 +7,8 @@ class {{classname}} { * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 202c608edef..22f97456e04 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -9,7 +9,8 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{/hasMore}}{{/vars}} ); - static function swaggerTypes() { + static function swaggerTypes() + { return self::$swaggerTypes{{#parent}} + parent::swaggerTypes(){{/parent}}; } @@ -22,7 +23,8 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{/hasMore}}{{/vars}} ); - static function attributeMap() { + static function attributeMap() + { return {{#parent}}parent::attributeMap() + {{/parent}}self::$attributeMap; } @@ -35,7 +37,8 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{/hasMore}}{{/vars}} ); - static function setters() { + static function setters() + { return {{#parent}}parent::setters() + {{/parent}}self::$setters; } @@ -48,7 +51,8 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{/hasMore}}{{/vars}} ); - static function getters() { + static function getters() + { return {{#parent}}parent::getters() + {{/parent}}self::$getters; } @@ -60,7 +64,8 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_test.mustache b/modules/swagger-codegen/src/main/resources/php/model_test.mustache index 0d615eca102..b79b5840e30 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_test.mustache @@ -51,21 +51,24 @@ class {{classname}}Test extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test {{classname}} */ - public function test{{classname}}() { + public function test{{classname}}() + { } From 726228a27d5557956d5bbb406b96ee14f624c257 Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Thu, 12 May 2016 20:56:56 -0400 Subject: [PATCH 27/53] [csharp] Make APIs partial classes --- .../swagger-codegen/src/main/resources/csharp/api.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 2b3f224cfc5..9c0c08fe8ed 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -72,7 +72,7 @@ namespace {{packageName}}.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public class {{classname}} : I{{classname}} + public partial class {{classname}} : I{{classname}} { /// /// Initializes a new instance of the class. @@ -122,7 +122,7 @@ namespace {{packageName}}.Api /// Sets the base path of the API client. /// /// The base path - [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing From 993a21ed5f0c768d6c54d68eafe0f222b67d35ed Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Thu, 12 May 2016 22:06:30 -0400 Subject: [PATCH 28/53] [csharp] Add interface for API config aspects This allows developers to gain access to each API's Configuration and GetBasePath without need for reflection. --- .../languages/CSharpClientCodegen.java | 2 ++ .../resources/csharp/IApiAccessor.mustache | 26 +++++++++++++++++++ .../src/main/resources/csharp/api.mustache | 2 +- 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 2fc8738f067..d9f9ff3a477 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -218,6 +218,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { binRelativePath += "vendor"; additionalProperties.put("binRelativePath", binRelativePath); + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", + clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", diff --git a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache new file mode 100644 index 00000000000..eecd5284493 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; + +namespace {{packageName}}.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + Configuration Configuration {get; set;} + + /// + /// Gets the base path of the API client. + /// + /// The base path + String GetBasePath(); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 9c0c08fe8ed..a96f4ced1ef 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -13,7 +13,7 @@ namespace {{packageName}}.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public interface I{{classname}} + public interface I{{classname}} : IApiAccessor { #region Synchronous Operations {{#operation}} From aed31fbff33760705ebafc040b5e5890f14b8123 Mon Sep 17 00:00:00 2001 From: Leon Yu Date: Tue, 10 May 2016 17:53:54 -0400 Subject: [PATCH 29/53] basic integration test for typescript-fetch fix postpublish script --- .gitignore | 12 +- bin/typescript-fetch-petstore-all.sh | 2 +- bin/typescript-fetch-petstore-target-es6.sh | 2 +- ...ript-fetch-petstore-with-npm-version.json} | 0 ...script-fetch-petstore-with-npm-version.sh} | 2 +- bin/typescript-fetch-petstore.sh | 2 +- .../TypeScriptFetchClientCodegen.java | 1 - .../main/resources/TypeScript-Fetch/README.md | 52 +- .../resources/TypeScript-Fetch/api.mustache | 164 +- .../main/resources/TypeScript-Fetch/assign.ts | 18 - .../TypeScript-Fetch/package.json.mustache | 6 +- .../TypeScript-Fetch/typings.json.mustache | 6 +- .../client/petstore/typescript-fetch/api.ts | 859 -- .../petstore/typescript-fetch/assign.ts | 18 - .../typescript-fetch/builds/default/README.md | 54 + .../typescript-fetch/builds/default/api.ts | 620 + .../default}/git_push.sh | 0 .../default}/package.json | 4 +- .../{ => builds}/default/tsconfig.json | 0 .../default}/typings.json | 4 +- .../builds/es6-target/README.md | 54 + .../typescript-fetch/builds/es6-target/api.ts | 619 + .../es6-target}/git_push.sh | 0 .../es6-target}/package.json | 3 +- .../es6-target}/tsconfig.json | 0 .../es6-target}/typings.json | 2 +- .../builds/with-npm-version/README.md | 54 + .../builds/with-npm-version/api.ts | 620 + .../{ => builds/with-npm-version}/git_push.sh | 0 .../with-npm-version}/package.json | 4 +- .../with-npm-version}/tsconfig.json | 0 .../with-npm-version}/typings.json | 4 +- .../typescript-fetch/default-es6/README.md | 44 - .../typescript-fetch/default-es6/api.ts | 855 -- .../typescript-fetch/default-es6/assign.ts | 18 - .../typescript-fetch/default/README.md | 44 - .../petstore/typescript-fetch/default/api.ts | 855 -- .../typescript-fetch/default/assign.ts | 18 - .../petstore/typescript-fetch/package.json | 10 - .../typescript-fetch/tests/default/bundle.js | 10990 ++++++++++++++++ .../tests/default/package.json | 26 + .../default/run_tests_via_browserify.html | 26 + .../tests/default/run_tests_via_webpack.html | 27 + .../tests/default/scripts/prepublish.sh | 13 + .../tests/default/test/PetApi.ts | 65 + .../tests/default/test/StoreApi.ts | 18 + .../tests/default/test/index.ts | 2 + .../tests/default/test/mocha.opts | 1 + .../tests/default/tsconfig.json | 16 + .../tests/default/typings.json | 9 + .../tests/default/webpack.config.js | 30 + .../petstore/typescript-fetch/tsconfig.json | 11 - .../petstore/typescript-fetch/typings.json | 9 - .../with-package-metadata/README.md | 44 - .../with-package-metadata/api.ts | 855 -- .../with-package-metadata/assign.ts | 18 - .../with-package-metadata/git_push.sh | 52 - 57 files changed, 13374 insertions(+), 3868 deletions(-) rename bin/{typescript-fetch-petstore-target-with-package-metadata.json => typescript-fetch-petstore-with-npm-version.json} (100%) rename bin/{typescript-fetch-petstore-target-with-package-metadata.sh => typescript-fetch-petstore-with-npm-version.sh} (88%) delete mode 100644 modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts delete mode 100644 samples/client/petstore/typescript-fetch/api.ts delete mode 100644 samples/client/petstore/typescript-fetch/assign.ts create mode 100644 samples/client/petstore/typescript-fetch/builds/default/README.md create mode 100644 samples/client/petstore/typescript-fetch/builds/default/api.ts rename samples/client/petstore/typescript-fetch/{default-es6 => builds/default}/git_push.sh (100%) rename samples/client/petstore/typescript-fetch/{default-es6 => builds/default}/package.json (81%) rename samples/client/petstore/typescript-fetch/{ => builds}/default/tsconfig.json (100%) rename samples/client/petstore/typescript-fetch/{with-package-metadata => builds/default}/typings.json (65%) create mode 100644 samples/client/petstore/typescript-fetch/builds/es6-target/README.md create mode 100644 samples/client/petstore/typescript-fetch/builds/es6-target/api.ts rename samples/client/petstore/typescript-fetch/{default => builds/es6-target}/git_push.sh (100%) rename samples/client/petstore/typescript-fetch/{default => builds/es6-target}/package.json (83%) rename samples/client/petstore/typescript-fetch/{default-es6 => builds/es6-target}/tsconfig.json (100%) rename samples/client/petstore/typescript-fetch/{default-es6 => builds/es6-target}/typings.json (86%) create mode 100644 samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md create mode 100644 samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts rename samples/client/petstore/typescript-fetch/{ => builds/with-npm-version}/git_push.sh (100%) rename samples/client/petstore/typescript-fetch/{with-package-metadata => builds/with-npm-version}/package.json (82%) rename samples/client/petstore/typescript-fetch/{with-package-metadata => builds/with-npm-version}/tsconfig.json (100%) rename samples/client/petstore/typescript-fetch/{default => builds/with-npm-version}/typings.json (65%) delete mode 100644 samples/client/petstore/typescript-fetch/default-es6/README.md delete mode 100644 samples/client/petstore/typescript-fetch/default-es6/api.ts delete mode 100644 samples/client/petstore/typescript-fetch/default-es6/assign.ts delete mode 100644 samples/client/petstore/typescript-fetch/default/README.md delete mode 100644 samples/client/petstore/typescript-fetch/default/api.ts delete mode 100644 samples/client/petstore/typescript-fetch/default/assign.ts delete mode 100644 samples/client/petstore/typescript-fetch/package.json create mode 100644 samples/client/petstore/typescript-fetch/tests/default/bundle.js create mode 100644 samples/client/petstore/typescript-fetch/tests/default/package.json create mode 100644 samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html create mode 100644 samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html create mode 100755 samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh create mode 100644 samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts create mode 100644 samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts create mode 100644 samples/client/petstore/typescript-fetch/tests/default/test/index.ts create mode 100644 samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts create mode 100644 samples/client/petstore/typescript-fetch/tests/default/tsconfig.json create mode 100644 samples/client/petstore/typescript-fetch/tests/default/typings.json create mode 100644 samples/client/petstore/typescript-fetch/tests/default/webpack.config.js delete mode 100644 samples/client/petstore/typescript-fetch/tsconfig.json delete mode 100644 samples/client/petstore/typescript-fetch/typings.json delete mode 100644 samples/client/petstore/typescript-fetch/with-package-metadata/README.md delete mode 100644 samples/client/petstore/typescript-fetch/with-package-metadata/api.ts delete mode 100644 samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts delete mode 100644 samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh diff --git a/.gitignore b/.gitignore index 2e1d1355309..ddb31ac6c90 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ samples/server-generator/scalatra/target samples/server-generator/scalatra/output/.history # nodejs +**/node_modules/ samples/server-generator/node/output/node_modules samples/server/petstore/nodejs/node_modules samples/server/petstore/nodejs-server/node_modules @@ -116,13 +117,6 @@ samples/client/petstore/python/.venv/ # ts samples/client/petstore/typescript-node/npm/node_modules -samples/client/petstore/typescript-fetch/with-package-metadata/node_modules -samples/client/petstore/typescript-fetch/with-package-metadata/dist -samples/client/petstore/typescript-fetch/with-package-metadata/typings -samples/client/petstore/typescript-fetch/default/node_modules -samples/client/petstore/typescript-fetch/default/dist -samples/client/petstore/typescript-fetch/default/typings -samples/client/petstore/typescript-fetch/default-es6/node_modules -samples/client/petstore/typescript-fetch/default-es6/dist -samples/client/petstore/typescript-fetch/default-es6/typings +samples/client/petstore/typescript-fetch/**/dist/ +samples/client/petstore/typescript-fetch/**/typings diff --git a/bin/typescript-fetch-petstore-all.sh b/bin/typescript-fetch-petstore-all.sh index d39c16d8803..6365b9032a6 100755 --- a/bin/typescript-fetch-petstore-all.sh +++ b/bin/typescript-fetch-petstore-all.sh @@ -1,5 +1,5 @@ #!/bin/sh ./bin/typescript-fetch-petstore-target-es6.sh -./bin/typescript-fetch-petstore-target-with-package-metadata.sh +./bin/typescript-fetch-petstore-with-npm-version.sh ./bin/typescript-fetch-petstore.sh diff --git a/bin/typescript-fetch-petstore-target-es6.sh b/bin/typescript-fetch-petstore-target-es6.sh index 3734e7e3449..84a6562eeb6 100755 --- a/bin/typescript-fetch-petstore-target-es6.sh +++ b/bin/typescript-fetch-petstore-target-es6.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/default-es6" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/builds/es6-target" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.json b/bin/typescript-fetch-petstore-with-npm-version.json similarity index 100% rename from bin/typescript-fetch-petstore-target-with-package-metadata.json rename to bin/typescript-fetch-petstore-with-npm-version.json diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.sh b/bin/typescript-fetch-petstore-with-npm-version.sh similarity index 88% rename from bin/typescript-fetch-petstore-target-with-package-metadata.sh rename to bin/typescript-fetch-petstore-with-npm-version.sh index 3c4978c8a80..fd9225f0e72 100755 --- a/bin/typescript-fetch-petstore-target-with-package-metadata.sh +++ b/bin/typescript-fetch-petstore-with-npm-version.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-with-package-metadata.json -o samples/client/petstore/typescript-fetch/with-package-metadata" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-with-npm-version.json -o samples/client/petstore/typescript-fetch/builds/with-npm-version" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore.sh b/bin/typescript-fetch-petstore.sh index 6283285c736..50d56f34609 100755 --- a/bin/typescript-fetch-petstore.sh +++ b/bin/typescript-fetch-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/default" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/builds/default" java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java index c817162401e..90f778eae8e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -26,7 +26,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege super.processOpts(); supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("assign.ts", "", "assign.ts")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json")); diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md index 8ec43e76497..db2dfccec36 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md @@ -1,44 +1,54 @@ # TypeScript-Fetch -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: -* Node.JS +Environment +* Node.js * Webpack * Browserify -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) ### Installation ### -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: ``` import * as localName from 'npmName'; import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` import * as localName from './symlinkDir'; import {operationId} from './symlinkDir'; ``` -With CommonJS, the following syntaxes are supported: +The CommonJS syntax is as follows: ``` -import localName = require('npmName'); - import localName = require('./symlinkDir')'; -``` \ No newline at end of file +``` diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 67d61999aa0..4a189097942 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -1,7 +1,23 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; +import * as querystring from "querystring"; +import * as url from "url"; +import * as isomorphicFetch from "isomorphic-fetch"; +{{^supportsES6}} +import * as assign from "core-js/library/fn/object/assign"; +{{/supportsES6}} + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(basePath: string = "{{basePath}}", fetch: FetchAPI = isomorphicFetch) { + this.basePath = basePath; + this.fetch = fetch; + } +} {{#models}} {{#model}} @@ -13,24 +29,20 @@ import {assign} from './assign'; export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{#vars}} {{#description}} - /** * {{{description}}} */ {{/description}} - "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } {{#hasEnums}} -export namespace {{classname}} { {{#vars}} {{#isEnum}} - -export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; +export type {{classname}}{{datatypeWithEnum}} = {{#allowableValues}}{{#values}}"{{.}}"{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; {{/isEnum}} {{/vars}} -} {{/hasEnums}} {{/model}} {{/models}} @@ -38,96 +50,72 @@ export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-las {{#apiInfo}} {{#apis}} {{#operations}} -//export namespace {{package}} { - 'use strict'; {{#description}} - /** - * {{&description}} - */ +/** +* {{&description}} +*/ {{/description}} - export class {{classname}} { - protected basePath = '{{basePath}}'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - +export class {{classname}} extends BaseAPI { {{#operation}} - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{paramName}} {{description}} - {{/allParams}}*/ - public {{nickname}} (params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { - const localVarPath = this.basePath + '{{path}}'{{#pathParams}} - .replace('{' + '{{baseName}}' + '}', String(params.{{paramName}})){{/pathParams}}; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); -{{#hasFormParams}} - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - -{{/hasFormParams}} -{{#hasBodyParam}} - headerParams['Content-Type'] = 'application/json'; - -{{/hasBodyParam}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { {{#allParams}} {{#required}} - // verify required parameter '{{paramName}}' is set - if (params.{{paramName}} == null) { - throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); - } + // verify required parameter "{{paramName}}" is set + if (params["{{paramName}}"] == null) { + throw new Error("Missing required parameter {{paramName}} when calling {{nickname}}"); + } {{/required}} {{/allParams}} -{{#queryParams}} - if (params.{{paramName}} !== undefined) { - queryParameters['{{baseName}}'] = params.{{paramName}}; - } + const baseUrl = `${this.basePath}{{path}}`{{#pathParams}} + .replace(`{${"{{baseName}}"}}`, `${ params.{{paramName}} }`){{/pathParams}}; + let urlObj = url.parse(baseUrl, true); +{{#hasQueryParams}} + urlObj.query = {{#supportsES6}}Object.{{/supportsES6}}assign({}, urlObj.query, { {{#queryParams}} + "{{baseName}}": params.{{paramName}},{{/queryParams}} + }); +{{/hasQueryParams}} + let fetchOptions: RequestInit = { method: "{{httpMethod}}" }; -{{/queryParams}} -{{#headerParams}} - headerParams['{{baseName}}'] = params.{{paramName}}; - -{{/headerParams}} -{{#formParams}} - formParams['{{baseName}}'] = params.{{paramName}}; - -{{/formParams}} - let fetchParams = { - method: '{{httpMethod}}', - headers: headerParams, - {{#bodyParam}}body: JSON.stringify(params.{{paramName}}), - {{/bodyParam}} - {{#hasFormParams}}body: querystring.stringify(formParams), - {{/hasFormParams}} - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); + let contentTypeHeader: Dictionary; +{{#hasFormParams}} + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ {{#formParams}} + "{{baseName}}": params.{{paramName}},{{/formParams}} + }); +{{/hasFormParams}} +{{#hasBodyParam}} + contentTypeHeader = { "Content-Type": "application/json" };{{#bodyParam}} + if (params["{{paramName}}"]) { + fetchOptions.body = JSON.stringify(params["{{paramName}}"] || {}); + }{{/bodyParam}} +{{/hasBodyParam}} +{{#hasHeaderParam}} + fetchOptions.headers = {{#supportsES6}}Object.{{/supportsES6}}assign({ {{#headerParams}} + "{{baseName}}": params.{{paramName}},{{/headerParams}} + }, contentTypeHeader); +{{/hasHeaderParam}} +{{^hasHeaderParam}} + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; } -{{/operation}} +{{/hasHeaderParam}} + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response{{#returnType}}.json(){{/returnType}}; + } else { + throw response; + } + }); } -//} +{{/operation}} +} + {{/operations}} {{/apis}} {{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache index e6379434b80..62a598d536b 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache @@ -1,15 +1,15 @@ { "name": "{{#npmName}}{{{npmName}}}{{/npmName}}{{^npmName}}typescript-fetch-api{{/npmName}}", "version": "{{#npmVersion}}{{{npmVersion}}}{{/npmVersion}}{{^npmVersion}}0.0.0{{/npmVersion}}", - "private": true, "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { - "isomorphic-fetch": "^2.2.1" + {{^supportsES6}}"core-js": "^2.4.0", + {{/supportsES6}}"isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache index 38baf589fb9..3aca69ff648 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache @@ -1,9 +1,9 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { -{{^supportsES6}} "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", -{{/supportsES6}} "node": "registry:dt/node#4.0.0+20160423143914", + "ambientDependencies": { {{^supportsES6}} + "core-js": "registry:dt/core-js#0.0.0+20160317120654",{{/supportsES6}} + "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } } diff --git a/samples/client/petstore/typescript-fetch/api.ts b/samples/client/petstore/typescript-fetch/api.ts deleted file mode 100644 index 0c8f4201e4c..00000000000 --- a/samples/client/petstore/typescript-fetch/api.ts +++ /dev/null @@ -1,859 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - - -export enum StatusEnum { - placed = 'placed', - approved = 'approved', - delivered = 'delivered' -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - - -export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold' -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/assign.ts b/samples/client/petstore/typescript-fetch/assign.ts deleted file mode 100644 index 040f87d7d98..00000000000 --- a/samples/client/petstore/typescript-fetch/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target, ...args) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/default/README.md b/samples/client/petstore/typescript-fetch/builds/default/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts new file mode 100644 index 00000000000..ce059f6c814 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -0,0 +1,620 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): Promise { + const baseUrl = `${this.basePath}/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): Promise> { + const baseUrl = `${this.basePath}/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): Promise> { + const baseUrl = `${this.basePath}/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): Promise { + const baseUrl = `${this.basePath}/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `${this.basePath}/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } +} + + +export class StoreApi extends BaseAPI { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): Promise { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `${this.basePath}/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): Promise<{ [key: string]: number; }> { + const baseUrl = `${this.basePath}/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): Promise { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `${this.basePath}/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): Promise { + const baseUrl = `${this.basePath}/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } +} + + +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): Promise { + const baseUrl = `${this.basePath}/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): Promise { + const baseUrl = `${this.basePath}/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): Promise { + const baseUrl = `${this.basePath}/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): Promise { + const baseUrl = `${this.basePath}/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Logs out current logged in user session + * + */ + logoutUser(): Promise { + const baseUrl = `${this.basePath}/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } +} + diff --git a/samples/client/petstore/typescript-fetch/default-es6/git_push.sh b/samples/client/petstore/typescript-fetch/builds/default/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/default-es6/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/default/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/default-es6/package.json b/samples/client/petstore/typescript-fetch/builds/default/package.json similarity index 81% rename from samples/client/petstore/typescript-fetch/default-es6/package.json rename to samples/client/petstore/typescript-fetch/builds/default/package.json index 84cf629d931..06bb023ad5b 100644 --- a/samples/client/petstore/typescript-fetch/default-es6/package.json +++ b/samples/client/petstore/typescript-fetch/builds/default/package.json @@ -1,15 +1,15 @@ { "name": "typescript-fetch-api", "version": "0.0.0", - "private": true, "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { + "core-js": "^2.4.0", "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", diff --git a/samples/client/petstore/typescript-fetch/default/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json similarity index 100% rename from samples/client/petstore/typescript-fetch/default/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/default/tsconfig.json diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json b/samples/client/petstore/typescript-fetch/builds/default/typings.json similarity index 65% rename from samples/client/petstore/typescript-fetch/with-package-metadata/typings.json rename to samples/client/petstore/typescript-fetch/builds/default/typings.json index eeca5afde97..32c5b1e2b0b 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/default/typings.json @@ -1,8 +1,8 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "ambientDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654", "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/README.md b/samples/client/petstore/typescript-fetch/builds/es6-target/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts new file mode 100644 index 00000000000..80b9e05756f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -0,0 +1,619 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): Promise { + const baseUrl = `${this.basePath}/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): Promise> { + const baseUrl = `${this.basePath}/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): Promise> { + const baseUrl = `${this.basePath}/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): Promise { + const baseUrl = `${this.basePath}/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `${this.basePath}/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } +} + + +export class StoreApi extends BaseAPI { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): Promise { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `${this.basePath}/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): Promise<{ [key: string]: number; }> { + const baseUrl = `${this.basePath}/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): Promise { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `${this.basePath}/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): Promise { + const baseUrl = `${this.basePath}/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } +} + + +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): Promise { + const baseUrl = `${this.basePath}/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): Promise { + const baseUrl = `${this.basePath}/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): Promise { + const baseUrl = `${this.basePath}/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): Promise { + const baseUrl = `${this.basePath}/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Logs out current logged in user session + * + */ + logoutUser(): Promise { + const baseUrl = `${this.basePath}/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } +} + diff --git a/samples/client/petstore/typescript-fetch/default/git_push.sh b/samples/client/petstore/typescript-fetch/builds/es6-target/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/default/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/es6-target/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/default/package.json b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json similarity index 83% rename from samples/client/petstore/typescript-fetch/default/package.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/package.json index 84cf629d931..ab5d5b0ce15 100644 --- a/samples/client/petstore/typescript-fetch/default/package.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json @@ -1,7 +1,6 @@ { "name": "typescript-fetch-api", "version": "0.0.0", - "private": true, "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", @@ -9,7 +8,7 @@ "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", diff --git a/samples/client/petstore/typescript-fetch/default-es6/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json similarity index 100% rename from samples/client/petstore/typescript-fetch/default-es6/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json diff --git a/samples/client/petstore/typescript-fetch/default-es6/typings.json b/samples/client/petstore/typescript-fetch/builds/es6-target/typings.json similarity index 86% rename from samples/client/petstore/typescript-fetch/default-es6/typings.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/typings.json index 3ce24427fc6..0f09addb324 100644 --- a/samples/client/petstore/typescript-fetch/default-es6/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/typings.json @@ -1,7 +1,7 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { + "ambientDependencies": { "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md b/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts new file mode 100644 index 00000000000..ce059f6c814 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -0,0 +1,620 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): Promise { + const baseUrl = `${this.basePath}/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): Promise> { + const baseUrl = `${this.basePath}/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): Promise> { + const baseUrl = `${this.basePath}/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): Promise { + const baseUrl = `${this.basePath}/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `${this.basePath}/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `${this.basePath}/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } +} + + +export class StoreApi extends BaseAPI { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): Promise { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `${this.basePath}/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): Promise<{ [key: string]: number; }> { + const baseUrl = `${this.basePath}/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): Promise { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `${this.basePath}/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): Promise { + const baseUrl = `${this.basePath}/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } +} + + +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): Promise { + const baseUrl = `${this.basePath}/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): Promise { + const baseUrl = `${this.basePath}/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): Promise { + const baseUrl = `${this.basePath}/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): Promise { + const baseUrl = `${this.basePath}/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + } + /** + * Logs out current logged in user session + * + */ + logoutUser(): Promise { + const baseUrl = `${this.basePath}/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): Promise { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `${this.basePath}/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + } +} + diff --git a/samples/client/petstore/typescript-fetch/git_push.sh b/samples/client/petstore/typescript-fetch/builds/with-npm-version/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/package.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json similarity index 82% rename from samples/client/petstore/typescript-fetch/with-package-metadata/package.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json index ab2a67c51d0..7dc5e398bc9 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/package.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json @@ -1,15 +1,15 @@ { "name": "@swagger/typescript-fetch-petstore", "version": "0.0.1", - "private": true, "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { + "core-js": "^2.4.0", "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json similarity index 100% rename from samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json diff --git a/samples/client/petstore/typescript-fetch/default/typings.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json similarity index 65% rename from samples/client/petstore/typescript-fetch/default/typings.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json index eeca5afde97..32c5b1e2b0b 100644 --- a/samples/client/petstore/typescript-fetch/default/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json @@ -1,8 +1,8 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "ambientDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654", "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/default-es6/README.md b/samples/client/petstore/typescript-fetch/default-es6/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default-es6/api.ts b/samples/client/petstore/typescript-fetch/default-es6/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - -export namespace Order { - -export type StatusEnum = 'placed' | 'approved' | 'delivered'; -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - -export namespace Pet { - -export type StatusEnum = 'available' | 'pending' | 'sold'; -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/default-es6/assign.ts b/samples/client/petstore/typescript-fetch/default-es6/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/README.md b/samples/client/petstore/typescript-fetch/default/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/default/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/api.ts b/samples/client/petstore/typescript-fetch/default/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/default/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - -export namespace Order { - -export type StatusEnum = 'placed' | 'approved' | 'delivered'; -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - -export namespace Pet { - -export type StatusEnum = 'available' | 'pending' | 'sold'; -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/default/assign.ts b/samples/client/petstore/typescript-fetch/default/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/default/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/package.json b/samples/client/petstore/typescript-fetch/package.json deleted file mode 100644 index 722c87cc323..00000000000 --- a/samples/client/petstore/typescript-fetch/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "private": true, - "dependencies": { - "isomorphic-fetch": "^2.2.1" - }, - "devDependencies": { - "typescript": "^1.8.10", - "typings": "^0.8.1" - } -} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/bundle.js b/samples/client/petstore/typescript-fetch/tests/default/bundle.js new file mode 100644 index 00000000000..a38402a7904 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/bundle.js @@ -0,0 +1,10990 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],2:[function(require,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.foo = function () { return 42 } + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; i++) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + that.write(string, encoding) + return that +} + +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; i++) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; i++) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'binary': + // Deprecated + case 'raw': + case 'raws': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'binary': + return binarySlice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +function arrayIndexOf (arr, val, byteOffset, encoding) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var foundIndex = -1 + for (var i = 0; byteOffset + i < arrLength; i++) { + if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + return -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset >>= 0 + + if (this.length === 0) return -1 + if (byteOffset >= this.length) return -1 + + // Negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + if (Buffer.isBuffer(val)) { + // special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(this, val, byteOffset, encoding) + } + if (typeof val === 'number') { + if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { + return Uint8Array.prototype.indexOf.call(this, val, byteOffset) + } + return arrayIndexOf(this, [ val ], byteOffset, encoding) + } + + throw new TypeError('val must be string, number or Buffer') +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'binary': + return binaryWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function binarySlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; i--) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; i++) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; i++) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; i++) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; i++) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":1,"ieee754":3,"isarray":4}],3:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],4:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],5:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],6:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],7:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],8:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":6,"./encode":7}],9:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":10,"punycode":5,"querystring":8}],10:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],11:[function(require,module,exports){ +/*! + * assertion-error + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +/*! + * Return a function that will copy properties from + * one object to another excluding any originally + * listed. Returned function will create a new `{}`. + * + * @param {String} excluded properties ... + * @return {Function} + */ + +function exclude () { + var excludes = [].slice.call(arguments); + + function excludeProps (res, obj) { + Object.keys(obj).forEach(function (key) { + if (!~excludes.indexOf(key)) res[key] = obj[key]; + }); + } + + return function extendExclude () { + var args = [].slice.call(arguments) + , i = 0 + , res = {}; + + for (; i < args.length; i++) { + excludeProps(res, args[i]); + } + + return res; + }; +}; + +/*! + * Primary Exports + */ + +module.exports = AssertionError; + +/** + * ### AssertionError + * + * An extension of the JavaScript `Error` constructor for + * assertion and validation scenarios. + * + * @param {String} message + * @param {Object} properties to include (optional) + * @param {callee} start stack function (optional) + */ + +function AssertionError (message, _props, ssf) { + var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') + , props = extend(_props || {}); + + // default values + this.message = message || 'Unspecified AssertionError'; + this.showDiff = false; + + // copy from properties + for (var key in props) { + this[key] = props[key]; + } + + // capture stack trace + ssf = ssf || arguments.callee; + if (ssf && Error.captureStackTrace) { + Error.captureStackTrace(this, ssf); + } else { + this.stack = new Error().stack; + } +} + +/*! + * Inherit from Error.prototype + */ + +AssertionError.prototype = Object.create(Error.prototype); + +/*! + * Statically set name + */ + +AssertionError.prototype.name = 'AssertionError'; + +/*! + * Ensure correct constructor + */ + +AssertionError.prototype.constructor = AssertionError; + +/** + * Allow errors to be converted to JSON for static transfer. + * + * @param {Boolean} include stack (default: `true`) + * @return {Object} object that can be `JSON.stringify` + */ + +AssertionError.prototype.toJSON = function (stack) { + var extend = exclude('constructor', 'toJSON', 'stack') + , props = extend({ name: this.name }, this); + + // include stack if exists and not turned off + if (false !== stack && this.stack) { + props.stack = this.stack; + } + + return props; +}; + +},{}],12:[function(require,module,exports){ +module.exports = require('./lib/chai'); + +},{"./lib/chai":13}],13:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +var used = [] + , exports = module.exports = {}; + +/*! + * Chai version + */ + +exports.version = '3.5.0'; + +/*! + * Assertion Error + */ + +exports.AssertionError = require('assertion-error'); + +/*! + * Utils for plugins (not exported) + */ + +var util = require('./chai/utils'); + +/** + * # .use(function) + * + * Provides a way to extend the internals of Chai + * + * @param {Function} + * @returns {this} for chaining + * @api public + */ + +exports.use = function (fn) { + if (!~used.indexOf(fn)) { + fn(this, util); + used.push(fn); + } + + return this; +}; + +/*! + * Utility Functions + */ + +exports.util = util; + +/*! + * Configuration + */ + +var config = require('./chai/config'); +exports.config = config; + +/*! + * Primary `Assertion` prototype + */ + +var assertion = require('./chai/assertion'); +exports.use(assertion); + +/*! + * Core Assertions + */ + +var core = require('./chai/core/assertions'); +exports.use(core); + +/*! + * Expect interface + */ + +var expect = require('./chai/interface/expect'); +exports.use(expect); + +/*! + * Should interface + */ + +var should = require('./chai/interface/should'); +exports.use(should); + +/*! + * Assert interface + */ + +var assert = require('./chai/interface/assert'); +exports.use(assert); + +},{"./chai/assertion":14,"./chai/config":15,"./chai/core/assertions":16,"./chai/interface/assert":17,"./chai/interface/expect":18,"./chai/interface/should":19,"./chai/utils":33,"assertion-error":11}],14:[function(require,module,exports){ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +var config = require('./config'); + +module.exports = function (_chai, util) { + /*! + * Module dependencies. + */ + + var AssertionError = _chai.AssertionError + , flag = util.flag; + + /*! + * Module export. + */ + + _chai.Assertion = Assertion; + + /*! + * Assertion Constructor + * + * Creates object for chaining. + * + * @api private + */ + + function Assertion (obj, msg, stack) { + flag(this, 'ssfi', stack || arguments.callee); + flag(this, 'object', obj); + flag(this, 'message', msg); + } + + Object.defineProperty(Assertion, 'includeStack', { + get: function() { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + return config.includeStack; + }, + set: function(value) { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + config.includeStack = value; + } + }); + + Object.defineProperty(Assertion, 'showDiff', { + get: function() { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + return config.showDiff; + }, + set: function(value) { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + config.showDiff = value; + } + }); + + Assertion.addProperty = function (name, fn) { + util.addProperty(this.prototype, name, fn); + }; + + Assertion.addMethod = function (name, fn) { + util.addMethod(this.prototype, name, fn); + }; + + Assertion.addChainableMethod = function (name, fn, chainingBehavior) { + util.addChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + Assertion.overwriteProperty = function (name, fn) { + util.overwriteProperty(this.prototype, name, fn); + }; + + Assertion.overwriteMethod = function (name, fn) { + util.overwriteMethod(this.prototype, name, fn); + }; + + Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { + util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + /** + * ### .assert(expression, message, negateMessage, expected, actual, showDiff) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {Philosophical} expression to be tested + * @param {String|Function} message or function that returns message to display if expression fails + * @param {String|Function} negatedMessage or function that returns negatedMessage to display if negated expression fails + * @param {Mixed} expected value (remember to check for negation) + * @param {Mixed} actual (optional) will default to `this.obj` + * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails + * @api private + */ + + Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = util.test(this, arguments); + if (true !== showDiff) showDiff = false; + if (true !== config.showDiff) showDiff = false; + + if (!ok) { + var msg = util.getMessage(this, arguments) + , actual = util.getActual(this, arguments); + throw new AssertionError(msg, { + actual: actual + , expected: expected + , showDiff: showDiff + }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); + } + }; + + /*! + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @api private + */ + + Object.defineProperty(Assertion.prototype, '_obj', + { get: function () { + return flag(this, 'object'); + } + , set: function (val) { + flag(this, 'object', val); + } + }); +}; + +},{"./config":15}],15:[function(require,module,exports){ +module.exports = { + + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {Boolean} + * @api public + */ + + includeStack: false, + + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {Boolean} + * @api public + */ + + showDiff: true, + + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {Number} + * @api public + */ + + truncateThreshold: 40 + +}; + +},{}],16:[function(require,module,exports){ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, _) { + var Assertion = chai.Assertion + , toString = Object.prototype.toString + , flag = _.flag; + + /** + * ### Language Chains + * + * The following are provided as chainable getters to + * improve the readability of your assertions. They + * do not provide testing capabilities unless they + * have been overwritten by a plugin. + * + * **Chains** + * + * - to + * - be + * - been + * - is + * - that + * - which + * - and + * - has + * - have + * - with + * - at + * - of + * - same + * + * @name language chains + * @namespace BDD + * @api public + */ + + [ 'to', 'be', 'been' + , 'is', 'and', 'has', 'have' + , 'with', 'that', 'which', 'at' + , 'of', 'same' ].forEach(function (chain) { + Assertion.addProperty(chain, function () { + return this; + }); + }); + + /** + * ### .not + * + * Negates any of assertions following in the chain. + * + * expect(foo).to.not.equal('bar'); + * expect(goodFn).to.not.throw(Error); + * expect({ foo: 'baz' }).to.have.property('foo') + * .and.not.equal('bar'); + * + * @name not + * @namespace BDD + * @api public + */ + + Assertion.addProperty('not', function () { + flag(this, 'negate', true); + }); + + /** + * ### .deep + * + * Sets the `deep` flag, later used by the `equal` and + * `property` assertions. + * + * expect(foo).to.deep.equal({ bar: 'baz' }); + * expect({ foo: { bar: { baz: 'quux' } } }) + * .to.have.deep.property('foo.bar.baz', 'quux'); + * + * `.deep.property` special characters can be escaped + * by adding two slashes before the `.` or `[]`. + * + * var deepCss = { '.link': { '[target]': 42 }}; + * expect(deepCss).to.have.deep.property('\\.link.\\[target\\]', 42); + * + * @name deep + * @namespace BDD + * @api public + */ + + Assertion.addProperty('deep', function () { + flag(this, 'deep', true); + }); + + /** + * ### .any + * + * Sets the `any` flag, (opposite of the `all` flag) + * later used in the `keys` assertion. + * + * expect(foo).to.have.any.keys('bar', 'baz'); + * + * @name any + * @namespace BDD + * @api public + */ + + Assertion.addProperty('any', function () { + flag(this, 'any', true); + flag(this, 'all', false) + }); + + + /** + * ### .all + * + * Sets the `all` flag (opposite of the `any` flag) + * later used by the `keys` assertion. + * + * expect(foo).to.have.all.keys('bar', 'baz'); + * + * @name all + * @namespace BDD + * @api public + */ + + Assertion.addProperty('all', function () { + flag(this, 'all', true); + flag(this, 'any', false); + }); + + /** + * ### .a(type) + * + * The `a` and `an` assertions are aliases that can be + * used either as language chains or to assert a value's + * type. + * + * // typeof + * expect('test').to.be.a('string'); + * expect({ foo: 'bar' }).to.be.an('object'); + * expect(null).to.be.a('null'); + * expect(undefined).to.be.an('undefined'); + * expect(new Error).to.be.an('error'); + * expect(new Promise).to.be.a('promise'); + * expect(new Float32Array()).to.be.a('float32array'); + * expect(Symbol()).to.be.a('symbol'); + * + * // es6 overrides + * expect({[Symbol.toStringTag]:()=>'foo'}).to.be.a('foo'); + * + * // language chain + * expect(foo).to.be.an.instanceof(Foo); + * + * @name a + * @alias an + * @param {String} type + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function an (type, msg) { + if (msg) flag(this, 'message', msg); + type = type.toLowerCase(); + var obj = flag(this, 'object') + , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + + this.assert( + type === _.type(obj) + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } + + Assertion.addChainableMethod('an', an); + Assertion.addChainableMethod('a', an); + + /** + * ### .include(value) + * + * The `include` and `contain` assertions can be used as either property + * based language chains or as methods to assert the inclusion of an object + * in an array or a substring in a string. When used as language chains, + * they toggle the `contains` flag for the `keys` assertion. + * + * expect([1,2,3]).to.include(2); + * expect('foobar').to.contain('foo'); + * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); + * + * @name include + * @alias contain + * @alias includes + * @alias contains + * @param {Object|String|Number} obj + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function includeChainingBehavior () { + flag(this, 'contains', true); + } + + function include (val, msg) { + _.expectTypes(this, ['array', 'object', 'string']); + + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var expected = false; + + if (_.type(obj) === 'array' && _.type(val) === 'object') { + for (var i in obj) { + if (_.eql(obj[i], val)) { + expected = true; + break; + } + } + } else if (_.type(val) === 'object') { + if (!flag(this, 'negate')) { + for (var k in val) new Assertion(obj).property(k, val[k]); + return; + } + var subset = {}; + for (var k in val) subset[k] = obj[k]; + expected = _.eql(subset, val); + } else { + expected = (obj != undefined) && ~obj.indexOf(val); + } + this.assert( + expected + , 'expected #{this} to include ' + _.inspect(val) + , 'expected #{this} to not include ' + _.inspect(val)); + } + + Assertion.addChainableMethod('include', include, includeChainingBehavior); + Assertion.addChainableMethod('contain', include, includeChainingBehavior); + Assertion.addChainableMethod('contains', include, includeChainingBehavior); + Assertion.addChainableMethod('includes', include, includeChainingBehavior); + + /** + * ### .ok + * + * Asserts that the target is truthy. + * + * expect('everything').to.be.ok; + * expect(1).to.be.ok; + * expect(false).to.not.be.ok; + * expect(undefined).to.not.be.ok; + * expect(null).to.not.be.ok; + * + * @name ok + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ok', function () { + this.assert( + flag(this, 'object') + , 'expected #{this} to be truthy' + , 'expected #{this} to be falsy'); + }); + + /** + * ### .true + * + * Asserts that the target is `true`. + * + * expect(true).to.be.true; + * expect(1).to.not.be.true; + * + * @name true + * @namespace BDD + * @api public + */ + + Assertion.addProperty('true', function () { + this.assert( + true === flag(this, 'object') + , 'expected #{this} to be true' + , 'expected #{this} to be false' + , this.negate ? false : true + ); + }); + + /** + * ### .false + * + * Asserts that the target is `false`. + * + * expect(false).to.be.false; + * expect(0).to.not.be.false; + * + * @name false + * @namespace BDD + * @api public + */ + + Assertion.addProperty('false', function () { + this.assert( + false === flag(this, 'object') + , 'expected #{this} to be false' + , 'expected #{this} to be true' + , this.negate ? true : false + ); + }); + + /** + * ### .null + * + * Asserts that the target is `null`. + * + * expect(null).to.be.null; + * expect(undefined).to.not.be.null; + * + * @name null + * @namespace BDD + * @api public + */ + + Assertion.addProperty('null', function () { + this.assert( + null === flag(this, 'object') + , 'expected #{this} to be null' + , 'expected #{this} not to be null' + ); + }); + + /** + * ### .undefined + * + * Asserts that the target is `undefined`. + * + * expect(undefined).to.be.undefined; + * expect(null).to.not.be.undefined; + * + * @name undefined + * @namespace BDD + * @api public + */ + + Assertion.addProperty('undefined', function () { + this.assert( + undefined === flag(this, 'object') + , 'expected #{this} to be undefined' + , 'expected #{this} not to be undefined' + ); + }); + + /** + * ### .NaN + * Asserts that the target is `NaN`. + * + * expect('foo').to.be.NaN; + * expect(4).not.to.be.NaN; + * + * @name NaN + * @namespace BDD + * @api public + */ + + Assertion.addProperty('NaN', function () { + this.assert( + isNaN(flag(this, 'object')) + , 'expected #{this} to be NaN' + , 'expected #{this} not to be NaN' + ); + }); + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi' + * , bar = null + * , baz; + * + * expect(foo).to.exist; + * expect(bar).to.not.exist; + * expect(baz).to.not.exist; + * + * @name exist + * @namespace BDD + * @api public + */ + + Assertion.addProperty('exist', function () { + this.assert( + null != flag(this, 'object') + , 'expected #{this} to exist' + , 'expected #{this} to not exist' + ); + }); + + + /** + * ### .empty + * + * Asserts that the target's length is `0`. For arrays and strings, it checks + * the `length` property. For objects, it gets the count of + * enumerable keys. + * + * expect([]).to.be.empty; + * expect('').to.be.empty; + * expect({}).to.be.empty; + * + * @name empty + * @namespace BDD + * @api public + */ + + Assertion.addProperty('empty', function () { + var obj = flag(this, 'object') + , expected = obj; + + if (Array.isArray(obj) || 'string' === typeof object) { + expected = obj.length; + } else if (typeof obj === 'object') { + expected = Object.keys(obj).length; + } + + this.assert( + !expected + , 'expected #{this} to be empty' + , 'expected #{this} not to be empty' + ); + }); + + /** + * ### .arguments + * + * Asserts that the target is an arguments object. + * + * function test () { + * expect(arguments).to.be.arguments; + * } + * + * @name arguments + * @alias Arguments + * @namespace BDD + * @api public + */ + + function checkArguments () { + var obj = flag(this, 'object') + , type = Object.prototype.toString.call(obj); + this.assert( + '[object Arguments]' === type + , 'expected #{this} to be arguments but got ' + type + , 'expected #{this} to not be arguments' + ); + } + + Assertion.addProperty('arguments', checkArguments); + Assertion.addProperty('Arguments', checkArguments); + + /** + * ### .equal(value) + * + * Asserts that the target is strictly equal (`===`) to `value`. + * Alternately, if the `deep` flag is set, asserts that + * the target is deeply equal to `value`. + * + * expect('hello').to.equal('hello'); + * expect(42).to.equal(42); + * expect(1).to.not.equal(true); + * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); + * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); + * + * @name equal + * @alias equals + * @alias eq + * @alias deep.equal + * @param {Mixed} value + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertEqual (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'deep')) { + return this.eql(val); + } else { + this.assert( + val === obj + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{exp}' + , val + , this._obj + , true + ); + } + } + + Assertion.addMethod('equal', assertEqual); + Assertion.addMethod('equals', assertEqual); + Assertion.addMethod('eq', assertEqual); + + /** + * ### .eql(value) + * + * Asserts that the target is deeply equal to `value`. + * + * expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); + * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); + * + * @name eql + * @alias eqls + * @param {Mixed} value + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertEql(obj, msg) { + if (msg) flag(this, 'message', msg); + this.assert( + _.eql(obj, flag(this, 'object')) + , 'expected #{this} to deeply equal #{exp}' + , 'expected #{this} to not deeply equal #{exp}' + , obj + , this._obj + , true + ); + } + + Assertion.addMethod('eql', assertEql); + Assertion.addMethod('eqls', assertEql); + + /** + * ### .above(value) + * + * Asserts that the target is greater than `value`. + * + * expect(10).to.be.above(5); + * + * Can also be used in conjunction with `length` to + * assert a minimum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.above(2); + * expect([ 1, 2, 3 ]).to.have.length.above(2); + * + * @name above + * @alias gt + * @alias greaterThan + * @param {Number} value + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertAbove (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len > n + , 'expected #{this} to have a length above #{exp} but got #{act}' + , 'expected #{this} to not have a length above #{exp}' + , n + , len + ); + } else { + this.assert( + obj > n + , 'expected #{this} to be above ' + n + , 'expected #{this} to be at most ' + n + ); + } + } + + Assertion.addMethod('above', assertAbove); + Assertion.addMethod('gt', assertAbove); + Assertion.addMethod('greaterThan', assertAbove); + + /** + * ### .least(value) + * + * Asserts that the target is greater than or equal to `value`. + * + * expect(10).to.be.at.least(10); + * + * Can also be used in conjunction with `length` to + * assert a minimum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.of.at.least(2); + * expect([ 1, 2, 3 ]).to.have.length.of.at.least(3); + * + * @name least + * @alias gte + * @param {Number} value + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertLeast (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len >= n + , 'expected #{this} to have a length at least #{exp} but got #{act}' + , 'expected #{this} to have a length below #{exp}' + , n + , len + ); + } else { + this.assert( + obj >= n + , 'expected #{this} to be at least ' + n + , 'expected #{this} to be below ' + n + ); + } + } + + Assertion.addMethod('least', assertLeast); + Assertion.addMethod('gte', assertLeast); + + /** + * ### .below(value) + * + * Asserts that the target is less than `value`. + * + * expect(5).to.be.below(10); + * + * Can also be used in conjunction with `length` to + * assert a maximum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.below(4); + * expect([ 1, 2, 3 ]).to.have.length.below(4); + * + * @name below + * @alias lt + * @alias lessThan + * @param {Number} value + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertBelow (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len < n + , 'expected #{this} to have a length below #{exp} but got #{act}' + , 'expected #{this} to not have a length below #{exp}' + , n + , len + ); + } else { + this.assert( + obj < n + , 'expected #{this} to be below ' + n + , 'expected #{this} to be at least ' + n + ); + } + } + + Assertion.addMethod('below', assertBelow); + Assertion.addMethod('lt', assertBelow); + Assertion.addMethod('lessThan', assertBelow); + + /** + * ### .most(value) + * + * Asserts that the target is less than or equal to `value`. + * + * expect(5).to.be.at.most(5); + * + * Can also be used in conjunction with `length` to + * assert a maximum length. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.of.at.most(4); + * expect([ 1, 2, 3 ]).to.have.length.of.at.most(3); + * + * @name most + * @alias lte + * @param {Number} value + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertMost (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len <= n + , 'expected #{this} to have a length at most #{exp} but got #{act}' + , 'expected #{this} to have a length above #{exp}' + , n + , len + ); + } else { + this.assert( + obj <= n + , 'expected #{this} to be at most ' + n + , 'expected #{this} to be above ' + n + ); + } + } + + Assertion.addMethod('most', assertMost); + Assertion.addMethod('lte', assertMost); + + /** + * ### .within(start, finish) + * + * Asserts that the target is within a range. + * + * expect(7).to.be.within(5,10); + * + * Can also be used in conjunction with `length` to + * assert a length range. The benefit being a + * more informative error message than if the length + * was supplied directly. + * + * expect('foo').to.have.length.within(2,4); + * expect([ 1, 2, 3 ]).to.have.length.within(2,4); + * + * @name within + * @param {Number} start lowerbound inclusive + * @param {Number} finish upperbound inclusive + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('within', function (start, finish, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , range = start + '..' + finish; + if (flag(this, 'doLength')) { + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + this.assert( + len >= start && len <= finish + , 'expected #{this} to have a length within ' + range + , 'expected #{this} to not have a length within ' + range + ); + } else { + this.assert( + obj >= start && obj <= finish + , 'expected #{this} to be within ' + range + , 'expected #{this} to not be within ' + range + ); + } + }); + + /** + * ### .instanceof(constructor) + * + * Asserts that the target is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , Chai = new Tea('chai'); + * + * expect(Chai).to.be.an.instanceof(Tea); + * expect([ 1, 2, 3 ]).to.be.instanceof(Array); + * + * @name instanceof + * @param {Constructor} constructor + * @param {String} message _optional_ + * @alias instanceOf + * @namespace BDD + * @api public + */ + + function assertInstanceOf (constructor, msg) { + if (msg) flag(this, 'message', msg); + var name = _.getName(constructor); + this.assert( + flag(this, 'object') instanceof constructor + , 'expected #{this} to be an instance of ' + name + , 'expected #{this} to not be an instance of ' + name + ); + }; + + Assertion.addMethod('instanceof', assertInstanceOf); + Assertion.addMethod('instanceOf', assertInstanceOf); + + /** + * ### .property(name, [value]) + * + * Asserts that the target has a property `name`, optionally asserting that + * the value of that property is strictly equal to `value`. + * If the `deep` flag is set, you can use dot- and bracket-notation for deep + * references into objects and arrays. + * + * // simple referencing + * var obj = { foo: 'bar' }; + * expect(obj).to.have.property('foo'); + * expect(obj).to.have.property('foo', 'bar'); + * + * // deep referencing + * var deepObj = { + * green: { tea: 'matcha' } + * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ] + * }; + * + * expect(deepObj).to.have.deep.property('green.tea', 'matcha'); + * expect(deepObj).to.have.deep.property('teas[1]', 'matcha'); + * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha'); + * + * You can also use an array as the starting point of a `deep.property` + * assertion, or traverse nested arrays. + * + * var arr = [ + * [ 'chai', 'matcha', 'konacha' ] + * , [ { tea: 'chai' } + * , { tea: 'matcha' } + * , { tea: 'konacha' } ] + * ]; + * + * expect(arr).to.have.deep.property('[0][1]', 'matcha'); + * expect(arr).to.have.deep.property('[1][2].tea', 'konacha'); + * + * Furthermore, `property` changes the subject of the assertion + * to be the value of that property from the original object. This + * permits for further chainable assertions on that property. + * + * expect(obj).to.have.property('foo') + * .that.is.a('string'); + * expect(deepObj).to.have.property('green') + * .that.is.an('object') + * .that.deep.equals({ tea: 'matcha' }); + * expect(deepObj).to.have.property('teas') + * .that.is.an('array') + * .with.deep.property('[2]') + * .that.deep.equals({ tea: 'konacha' }); + * + * Note that dots and bracket in `name` must be backslash-escaped when + * the `deep` flag is set, while they must NOT be escaped when the `deep` + * flag is not set. + * + * // simple referencing + * var css = { '.link[target]': 42 }; + * expect(css).to.have.property('.link[target]', 42); + * + * // deep referencing + * var deepCss = { '.link': { '[target]': 42 }}; + * expect(deepCss).to.have.deep.property('\\.link.\\[target\\]', 42); + * + * @name property + * @alias deep.property + * @param {String} name + * @param {Mixed} value (optional) + * @param {String} message _optional_ + * @returns value of property for chaining + * @namespace BDD + * @api public + */ + + Assertion.addMethod('property', function (name, val, msg) { + if (msg) flag(this, 'message', msg); + + var isDeep = !!flag(this, 'deep') + , descriptor = isDeep ? 'deep property ' : 'property ' + , negate = flag(this, 'negate') + , obj = flag(this, 'object') + , pathInfo = isDeep ? _.getPathInfo(name, obj) : null + , hasProperty = isDeep + ? pathInfo.exists + : _.hasProperty(name, obj) + , value = isDeep + ? pathInfo.value + : obj[name]; + + if (negate && arguments.length > 1) { + if (undefined === value) { + msg = (msg != null) ? msg + ': ' : ''; + throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name)); + } + } else { + this.assert( + hasProperty + , 'expected #{this} to have a ' + descriptor + _.inspect(name) + , 'expected #{this} to not have ' + descriptor + _.inspect(name)); + } + + if (arguments.length > 1) { + this.assert( + val === value + , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' + , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}' + , val + , value + ); + } + + flag(this, 'object', value); + }); + + + /** + * ### .ownProperty(name) + * + * Asserts that the target has an own property `name`. + * + * expect('test').to.have.ownProperty('length'); + * + * @name ownProperty + * @alias haveOwnProperty + * @param {String} name + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertOwnProperty (name, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + obj.hasOwnProperty(name) + , 'expected #{this} to have own property ' + _.inspect(name) + , 'expected #{this} to not have own property ' + _.inspect(name) + ); + } + + Assertion.addMethod('ownProperty', assertOwnProperty); + Assertion.addMethod('haveOwnProperty', assertOwnProperty); + + /** + * ### .ownPropertyDescriptor(name[, descriptor[, message]]) + * + * Asserts that the target has an own property descriptor `name`, that optionally matches `descriptor`. + * + * expect('test').to.have.ownPropertyDescriptor('length'); + * expect('test').to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 }); + * expect('test').not.to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 }); + * expect('test').ownPropertyDescriptor('length').to.have.property('enumerable', false); + * expect('test').ownPropertyDescriptor('length').to.have.keys('value'); + * + * @name ownPropertyDescriptor + * @alias haveOwnPropertyDescriptor + * @param {String} name + * @param {Object} descriptor _optional_ + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertOwnPropertyDescriptor (name, descriptor, msg) { + if (typeof descriptor === 'string') { + msg = descriptor; + descriptor = null; + } + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + if (actualDescriptor && descriptor) { + this.assert( + _.eql(descriptor, actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) + , descriptor + , actualDescriptor + , true + ); + } else { + this.assert( + actualDescriptor + , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) + , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) + ); + } + flag(this, 'object', actualDescriptor); + } + + Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); + Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); + + /** + * ### .length + * + * Sets the `doLength` flag later used as a chain precursor to a value + * comparison for the `length` property. + * + * expect('foo').to.have.length.above(2); + * expect([ 1, 2, 3 ]).to.have.length.above(2); + * expect('foo').to.have.length.below(4); + * expect([ 1, 2, 3 ]).to.have.length.below(4); + * expect('foo').to.have.length.within(2,4); + * expect([ 1, 2, 3 ]).to.have.length.within(2,4); + * + * *Deprecation notice:* Using `length` as an assertion will be deprecated + * in version 2.4.0 and removed in 3.0.0. Code using the old style of + * asserting for `length` property value using `length(value)` should be + * switched to use `lengthOf(value)` instead. + * + * @name length + * @namespace BDD + * @api public + */ + + /** + * ### .lengthOf(value[, message]) + * + * Asserts that the target's `length` property has + * the expected value. + * + * expect([ 1, 2, 3]).to.have.lengthOf(3); + * expect('foobar').to.have.lengthOf(6); + * + * @name lengthOf + * @param {Number} length + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertLengthChain () { + flag(this, 'doLength', true); + } + + function assertLength (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + new Assertion(obj, msg).to.have.property('length'); + var len = obj.length; + + this.assert( + len == n + , 'expected #{this} to have a length of #{exp} but got #{act}' + , 'expected #{this} to not have a length of #{act}' + , n + , len + ); + } + + Assertion.addChainableMethod('length', assertLength, assertLengthChain); + Assertion.addMethod('lengthOf', assertLength); + + /** + * ### .match(regexp) + * + * Asserts that the target matches a regular expression. + * + * expect('foobar').to.match(/^foo/); + * + * @name match + * @alias matches + * @param {RegExp} RegularExpression + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + function assertMatch(re, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + re.exec(obj) + , 'expected #{this} to match ' + re + , 'expected #{this} not to match ' + re + ); + } + + Assertion.addMethod('match', assertMatch); + Assertion.addMethod('matches', assertMatch); + + /** + * ### .string(string) + * + * Asserts that the string target contains another string. + * + * expect('foobar').to.have.string('bar'); + * + * @name string + * @param {String} string + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('string', function (str, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + new Assertion(obj, msg).is.a('string'); + + this.assert( + ~obj.indexOf(str) + , 'expected #{this} to contain ' + _.inspect(str) + , 'expected #{this} to not contain ' + _.inspect(str) + ); + }); + + + /** + * ### .keys(key1, [key2], [...]) + * + * Asserts that the target contains any or all of the passed-in keys. + * Use in combination with `any`, `all`, `contains`, or `have` will affect + * what will pass. + * + * When used in conjunction with `any`, at least one key that is passed + * in must exist in the target object. This is regardless whether or not + * the `have` or `contain` qualifiers are used. Note, either `any` or `all` + * should be used in the assertion. If neither are used, the assertion is + * defaulted to `all`. + * + * When both `all` and `contain` are used, the target object must have at + * least all of the passed-in keys but may have more keys not listed. + * + * When both `all` and `have` are used, the target object must both contain + * all of the passed-in keys AND the number of keys in the target object must + * match the number of keys passed in (in other words, a target object must + * have all and only all of the passed-in keys). + * + * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo', 'baz'); + * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo'); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys('bar', 'baz'); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys(['foo']); + * expect({ foo: 1, bar: 2 }).to.contain.any.keys({'foo': 6}); + * expect({ foo: 1, bar: 2 }).to.have.all.keys(['bar', 'foo']); + * expect({ foo: 1, bar: 2 }).to.have.all.keys({'bar': 6, 'foo': 7}); + * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys(['bar', 'foo']); + * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys({'bar': 6}); + * + * + * @name keys + * @alias key + * @param {...String|Array|Object} keys + * @namespace BDD + * @api public + */ + + function assertKeys (keys) { + var obj = flag(this, 'object') + , str + , ok = true + , mixedArgsMsg = 'keys must be given single argument of Array|Object|String, or multiple String arguments'; + + switch (_.type(keys)) { + case "array": + if (arguments.length > 1) throw (new Error(mixedArgsMsg)); + break; + case "object": + if (arguments.length > 1) throw (new Error(mixedArgsMsg)); + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + + if (!keys.length) throw new Error('keys required'); + + var actual = Object.keys(obj) + , expected = keys + , len = keys.length + , any = flag(this, 'any') + , all = flag(this, 'all'); + + if (!any && !all) { + all = true; + } + + // Has any + if (any) { + var intersection = expected.filter(function(key) { + return ~actual.indexOf(key); + }); + ok = intersection.length > 0; + } + + // Has all + if (all) { + ok = keys.every(function(key){ + return ~actual.indexOf(key); + }); + if (!flag(this, 'negate') && !flag(this, 'contains')) { + ok = ok && keys.length == actual.length; + } + } + + // Key string + if (len > 1) { + keys = keys.map(function(key){ + return _.inspect(key); + }); + var last = keys.pop(); + if (all) { + str = keys.join(', ') + ', and ' + last; + } + if (any) { + str = keys.join(', ') + ', or ' + last; + } + } else { + str = _.inspect(keys[0]); + } + + // Form + str = (len > 1 ? 'keys ' : 'key ') + str; + + // Have / include + str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; + + // Assertion + this.assert( + ok + , 'expected #{this} to ' + str + , 'expected #{this} to not ' + str + , expected.slice(0).sort() + , actual.sort() + , true + ); + } + + Assertion.addMethod('keys', assertKeys); + Assertion.addMethod('key', assertKeys); + + /** + * ### .throw(constructor) + * + * Asserts that the function target will throw a specific error, or specific type of error + * (as determined using `instanceof`), optionally with a RegExp or string inclusion test + * for the error's message. + * + * var err = new ReferenceError('This is a bad function.'); + * var fn = function () { throw err; } + * expect(fn).to.throw(ReferenceError); + * expect(fn).to.throw(Error); + * expect(fn).to.throw(/bad function/); + * expect(fn).to.not.throw('good function'); + * expect(fn).to.throw(ReferenceError, /bad function/); + * expect(fn).to.throw(err); + * + * Please note that when a throw expectation is negated, it will check each + * parameter independently, starting with error constructor type. The appropriate way + * to check for the existence of a type of error but for a message that does not match + * is to use `and`. + * + * expect(fn).to.throw(ReferenceError) + * .and.not.throw(/good function/); + * + * @name throw + * @alias throws + * @alias Throw + * @param {ErrorConstructor} constructor + * @param {String|RegExp} expected error message + * @param {String} message _optional_ + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @returns error for chaining (null if no error) + * @namespace BDD + * @api public + */ + + function assertThrows (constructor, errMsg, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + new Assertion(obj, msg).is.a('function'); + + var thrown = false + , desiredError = null + , name = null + , thrownError = null; + + if (arguments.length === 0) { + errMsg = null; + constructor = null; + } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) { + errMsg = constructor; + constructor = null; + } else if (constructor && constructor instanceof Error) { + desiredError = constructor; + constructor = null; + errMsg = null; + } else if (typeof constructor === 'function') { + name = constructor.prototype.name; + if (!name || (name === 'Error' && constructor !== Error)) { + name = constructor.name || (new constructor()).name; + } + } else { + constructor = null; + } + + try { + obj(); + } catch (err) { + // first, check desired error + if (desiredError) { + this.assert( + err === desiredError + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + , (desiredError instanceof Error ? desiredError.toString() : desiredError) + , (err instanceof Error ? err.toString() : err) + ); + + flag(this, 'object', err); + return this; + } + + // next, check constructor + if (constructor) { + this.assert( + err instanceof constructor + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp} but #{act} was thrown' + , name + , (err instanceof Error ? err.toString() : err) + ); + + if (!errMsg) { + flag(this, 'object', err); + return this; + } + } + + // next, check message + var message = 'error' === _.type(err) && "message" in err + ? err.message + : '' + err; + + if ((message != null) && errMsg && errMsg instanceof RegExp) { + this.assert( + errMsg.exec(message) + , 'expected #{this} to throw error matching #{exp} but got #{act}' + , 'expected #{this} to throw error not matching #{exp}' + , errMsg + , message + ); + + flag(this, 'object', err); + return this; + } else if ((message != null) && errMsg && 'string' === typeof errMsg) { + this.assert( + ~message.indexOf(errMsg) + , 'expected #{this} to throw error including #{exp} but got #{act}' + , 'expected #{this} to throw error not including #{act}' + , errMsg + , message + ); + + flag(this, 'object', err); + return this; + } else { + thrown = true; + thrownError = err; + } + } + + var actuallyGot = '' + , expectedThrown = name !== null + ? name + : desiredError + ? '#{exp}' //_.inspect(desiredError) + : 'an error'; + + if (thrown) { + actuallyGot = ' but #{act} was thrown' + } + + this.assert( + thrown === true + , 'expected #{this} to throw ' + expectedThrown + actuallyGot + , 'expected #{this} to not throw ' + expectedThrown + actuallyGot + , (desiredError instanceof Error ? desiredError.toString() : desiredError) + , (thrownError instanceof Error ? thrownError.toString() : thrownError) + ); + + flag(this, 'object', thrownError); + }; + + Assertion.addMethod('throw', assertThrows); + Assertion.addMethod('throws', assertThrows); + Assertion.addMethod('Throw', assertThrows); + + /** + * ### .respondTo(method) + * + * Asserts that the object or class target will respond to a method. + * + * Klass.prototype.bar = function(){}; + * expect(Klass).to.respondTo('bar'); + * expect(obj).to.respondTo('bar'); + * + * To check if a constructor will respond to a static function, + * set the `itself` flag. + * + * Klass.baz = function(){}; + * expect(Klass).itself.to.respondTo('baz'); + * + * @name respondTo + * @alias respondsTo + * @param {String} method + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function respondTo (method, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , itself = flag(this, 'itself') + , context = ('function' === _.type(obj) && !itself) + ? obj.prototype[method] + : obj[method]; + + this.assert( + 'function' === typeof context + , 'expected #{this} to respond to ' + _.inspect(method) + , 'expected #{this} to not respond to ' + _.inspect(method) + ); + } + + Assertion.addMethod('respondTo', respondTo); + Assertion.addMethod('respondsTo', respondTo); + + /** + * ### .itself + * + * Sets the `itself` flag, later used by the `respondTo` assertion. + * + * function Foo() {} + * Foo.bar = function() {} + * Foo.prototype.baz = function() {} + * + * expect(Foo).itself.to.respondTo('bar'); + * expect(Foo).itself.not.to.respondTo('baz'); + * + * @name itself + * @namespace BDD + * @api public + */ + + Assertion.addProperty('itself', function () { + flag(this, 'itself', true); + }); + + /** + * ### .satisfy(method) + * + * Asserts that the target passes a given truth test. + * + * expect(1).to.satisfy(function(num) { return num > 0; }); + * + * @name satisfy + * @alias satisfies + * @param {Function} matcher + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function satisfy (matcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var result = matcher(obj); + this.assert( + result + , 'expected #{this} to satisfy ' + _.objDisplay(matcher) + , 'expected #{this} to not satisfy' + _.objDisplay(matcher) + , this.negate ? false : true + , result + ); + } + + Assertion.addMethod('satisfy', satisfy); + Assertion.addMethod('satisfies', satisfy); + + /** + * ### .closeTo(expected, delta) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * expect(1.5).to.be.closeTo(1, 0.5); + * + * @name closeTo + * @alias approximately + * @param {Number} expected + * @param {Number} delta + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function closeTo(expected, delta, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + + new Assertion(obj, msg).is.a('number'); + if (_.type(expected) !== 'number' || _.type(delta) !== 'number') { + throw new Error('the arguments to closeTo or approximately must be numbers'); + } + + this.assert( + Math.abs(obj - expected) <= delta + , 'expected #{this} to be close to ' + expected + ' +/- ' + delta + , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta + ); + } + + Assertion.addMethod('closeTo', closeTo); + Assertion.addMethod('approximately', closeTo); + + function isSubsetOf(subset, superset, cmp) { + return subset.every(function(elem) { + if (!cmp) return superset.indexOf(elem) !== -1; + + return superset.some(function(elem2) { + return cmp(elem, elem2); + }); + }) + } + + /** + * ### .members(set) + * + * Asserts that the target is a superset of `set`, + * or that the target and `set` have the same strictly-equal (===) members. + * Alternately, if the `deep` flag is set, set members are compared for deep + * equality. + * + * expect([1, 2, 3]).to.include.members([3, 2]); + * expect([1, 2, 3]).to.not.include.members([3, 2, 8]); + * + * expect([4, 2]).to.have.members([2, 4]); + * expect([5, 2]).to.not.have.members([5, 2, 1]); + * + * expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }]); + * + * @name members + * @param {Array} set + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('members', function (subset, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + + new Assertion(obj).to.be.an('array'); + new Assertion(subset).to.be.an('array'); + + var cmp = flag(this, 'deep') ? _.eql : undefined; + + if (flag(this, 'contains')) { + return this.assert( + isSubsetOf(subset, obj, cmp) + , 'expected #{this} to be a superset of #{act}' + , 'expected #{this} to not be a superset of #{act}' + , obj + , subset + ); + } + + this.assert( + isSubsetOf(obj, subset, cmp) && isSubsetOf(subset, obj, cmp) + , 'expected #{this} to have the same members as #{act}' + , 'expected #{this} to not have the same members as #{act}' + , obj + , subset + ); + }); + + /** + * ### .oneOf(list) + * + * Assert that a value appears somewhere in the top level of array `list`. + * + * expect('a').to.be.oneOf(['a', 'b', 'c']); + * expect(9).to.not.be.oneOf(['z']); + * expect([3]).to.not.be.oneOf([1, 2, [3]]); + * + * var three = [3]; + * // for object-types, contents are not compared + * expect(three).to.not.be.oneOf([1, 2, [3]]); + * // comparing references works + * expect(three).to.be.oneOf([1, 2, three]); + * + * @name oneOf + * @param {Array<*>} list + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function oneOf (list, msg) { + if (msg) flag(this, 'message', msg); + var expected = flag(this, 'object'); + new Assertion(list).to.be.an('array'); + + this.assert( + list.indexOf(expected) > -1 + , 'expected #{this} to be one of #{exp}' + , 'expected #{this} to not be one of #{exp}' + , list + , expected + ); + } + + Assertion.addMethod('oneOf', oneOf); + + + /** + * ### .change(function) + * + * Asserts that a function changes an object property + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 3 }; + * var noChangeFn = function() { return 'foo' + 'bar'; } + * expect(fn).to.change(obj, 'val'); + * expect(noChangeFn).to.not.change(obj, 'val') + * + * @name change + * @alias changes + * @alias Change + * @param {String} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertChanges (object, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object'); + new Assertion(object, msg).to.have.property(prop); + new Assertion(fn).is.a('function'); + + var initial = object[prop]; + fn(); + + this.assert( + initial !== object[prop] + , 'expected .' + prop + ' to change' + , 'expected .' + prop + ' to not change' + ); + } + + Assertion.addChainableMethod('change', assertChanges); + Assertion.addChainableMethod('changes', assertChanges); + + /** + * ### .increase(function) + * + * Asserts that a function increases an object property + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * expect(fn).to.increase(obj, 'val'); + * + * @name increase + * @alias increases + * @alias Increase + * @param {String} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertIncreases (object, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object'); + new Assertion(object, msg).to.have.property(prop); + new Assertion(fn).is.a('function'); + + var initial = object[prop]; + fn(); + + this.assert( + object[prop] - initial > 0 + , 'expected .' + prop + ' to increase' + , 'expected .' + prop + ' to not increase' + ); + } + + Assertion.addChainableMethod('increase', assertIncreases); + Assertion.addChainableMethod('increases', assertIncreases); + + /** + * ### .decrease(function) + * + * Asserts that a function decreases an object property + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * expect(fn).to.decrease(obj, 'val'); + * + * @name decrease + * @alias decreases + * @alias Decrease + * @param {String} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace BDD + * @api public + */ + + function assertDecreases (object, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object'); + new Assertion(object, msg).to.have.property(prop); + new Assertion(fn).is.a('function'); + + var initial = object[prop]; + fn(); + + this.assert( + object[prop] - initial < 0 + , 'expected .' + prop + ' to decrease' + , 'expected .' + prop + ' to not decrease' + ); + } + + Assertion.addChainableMethod('decrease', assertDecreases); + Assertion.addChainableMethod('decreases', assertDecreases); + + /** + * ### .extensible + * + * Asserts that the target is extensible (can have new properties added to + * it). + * + * var nonExtensibleObject = Object.preventExtensions({}); + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * expect({}).to.be.extensible; + * expect(nonExtensibleObject).to.not.be.extensible; + * expect(sealedObject).to.not.be.extensible; + * expect(frozenObject).to.not.be.extensible; + * + * @name extensible + * @namespace BDD + * @api public + */ + + Assertion.addProperty('extensible', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible + // The following provides ES6 behavior when a TypeError is thrown under ES5. + + var isExtensible; + + try { + isExtensible = Object.isExtensible(obj); + } catch (err) { + if (err instanceof TypeError) isExtensible = false; + else throw err; + } + + this.assert( + isExtensible + , 'expected #{this} to be extensible' + , 'expected #{this} to not be extensible' + ); + }); + + /** + * ### .sealed + * + * Asserts that the target is sealed (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * expect(sealedObject).to.be.sealed; + * expect(frozenObject).to.be.sealed; + * expect({}).to.not.be.sealed; + * + * @name sealed + * @namespace BDD + * @api public + */ + + Assertion.addProperty('sealed', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed + // The following provides ES6 behavior when a TypeError is thrown under ES5. + + var isSealed; + + try { + isSealed = Object.isSealed(obj); + } catch (err) { + if (err instanceof TypeError) isSealed = true; + else throw err; + } + + this.assert( + isSealed + , 'expected #{this} to be sealed' + , 'expected #{this} to not be sealed' + ); + }); + + /** + * ### .frozen + * + * Asserts that the target is frozen (cannot have new properties added to it + * and its existing properties cannot be modified). + * + * var frozenObject = Object.freeze({}); + * + * expect(frozenObject).to.be.frozen; + * expect({}).to.not.be.frozen; + * + * @name frozen + * @namespace BDD + * @api public + */ + + Assertion.addProperty('frozen', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen + // The following provides ES6 behavior when a TypeError is thrown under ES5. + + var isFrozen; + + try { + isFrozen = Object.isFrozen(obj); + } catch (err) { + if (err instanceof TypeError) isFrozen = true; + else throw err; + } + + this.assert( + isFrozen + , 'expected #{this} to be frozen' + , 'expected #{this} to not be frozen' + ); + }); +}; + +},{}],17:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + + +module.exports = function (chai, util) { + + /*! + * Chai dependencies. + */ + + var Assertion = chai.Assertion + , flag = util.flag; + + /*! + * Module export. + */ + + /** + * ### assert(expression, message) + * + * Write your own test expressions. + * + * assert('foo' !== 'bar', 'foo is not bar'); + * assert(Array.isArray([]), 'empty arrays are arrays'); + * + * @param {Mixed} expression to test for truthiness + * @param {String} message to display on error + * @name assert + * @namespace Assert + * @api public + */ + + var assert = chai.assert = function (express, errmsg) { + var test = new Assertion(null, null, chai.assert); + test.assert( + express + , errmsg + , '[ negation message unavailable ]' + ); + }; + + /** + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. Node.js `assert` module-compatible. + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace Assert + * @api public + */ + + assert.fail = function (actual, expected, message, operator) { + message = message || 'assert.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, assert.fail); + }; + + /** + * ### .isOk(object, [message]) + * + * Asserts that `object` is truthy. + * + * assert.isOk('everything', 'everything is ok'); + * assert.isOk(false, 'this will fail'); + * + * @name isOk + * @alias ok + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isOk = function (val, msg) { + new Assertion(val, msg).is.ok; + }; + + /** + * ### .isNotOk(object, [message]) + * + * Asserts that `object` is falsy. + * + * assert.isNotOk('everything', 'this will fail'); + * assert.isNotOk(false, 'this will pass'); + * + * @name isNotOk + * @alias notOk + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotOk = function (val, msg) { + new Assertion(val, msg).is.not.ok; + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * assert.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.equal = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.equal); + + test.assert( + exp == flag(test, 'object') + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{act}' + , exp + , act + ); + }; + + /** + * ### .notEqual(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * assert.notEqual(3, 4, 'these numbers are not equal'); + * + * @name notEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notEqual = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.notEqual); + + test.assert( + exp != flag(test, 'object') + , 'expected #{this} to not equal #{exp}' + , 'expected #{this} to equal #{act}' + , exp + , act + ); + }; + + /** + * ### .strictEqual(actual, expected, [message]) + * + * Asserts strict equality (`===`) of `actual` and `expected`. + * + * assert.strictEqual(true, true, 'these booleans are strictly equal'); + * + * @name strictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.strictEqual = function (act, exp, msg) { + new Assertion(act, msg).to.equal(exp); + }; + + /** + * ### .notStrictEqual(actual, expected, [message]) + * + * Asserts strict inequality (`!==`) of `actual` and `expected`. + * + * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); + * + * @name notStrictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notStrictEqual = function (act, exp, msg) { + new Assertion(act, msg).to.not.equal(exp); + }; + + /** + * ### .deepEqual(actual, expected, [message]) + * + * Asserts that `actual` is deeply equal to `expected`. + * + * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); + * + * @name deepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepEqual = function (act, exp, msg) { + new Assertion(act, msg).to.eql(exp); + }; + + /** + * ### .notDeepEqual(actual, expected, [message]) + * + * Assert that `actual` is not deeply equal to `expected`. + * + * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); + * + * @name notDeepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepEqual = function (act, exp, msg) { + new Assertion(act, msg).to.not.eql(exp); + }; + + /** + * ### .isAbove(valueToCheck, valueToBeAbove, [message]) + * + * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove` + * + * assert.isAbove(5, 2, '5 is strictly greater than 2'); + * + * @name isAbove + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAbove + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAbove = function (val, abv, msg) { + new Assertion(val, msg).to.be.above(abv); + }; + + /** + * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) + * + * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast` + * + * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); + * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); + * + * @name isAtLeast + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtLeast + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtLeast = function (val, atlst, msg) { + new Assertion(val, msg).to.be.least(atlst); + }; + + /** + * ### .isBelow(valueToCheck, valueToBeBelow, [message]) + * + * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow` + * + * assert.isBelow(3, 6, '3 is strictly less than 6'); + * + * @name isBelow + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeBelow + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBelow = function (val, blw, msg) { + new Assertion(val, msg).to.be.below(blw); + }; + + /** + * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) + * + * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost` + * + * assert.isAtMost(3, 6, '3 is less than or equal to 6'); + * assert.isAtMost(4, 4, '4 is less than or equal to 4'); + * + * @name isAtMost + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtMost + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtMost = function (val, atmst, msg) { + new Assertion(val, msg).to.be.most(atmst); + }; + + /** + * ### .isTrue(value, [message]) + * + * Asserts that `value` is true. + * + * var teaServed = true; + * assert.isTrue(teaServed, 'the tea has been served'); + * + * @name isTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isTrue = function (val, msg) { + new Assertion(val, msg).is['true']; + }; + + /** + * ### .isNotTrue(value, [message]) + * + * Asserts that `value` is not true. + * + * var tea = 'tasty chai'; + * assert.isNotTrue(tea, 'great, time for tea!'); + * + * @name isNotTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotTrue = function (val, msg) { + new Assertion(val, msg).to.not.equal(true); + }; + + /** + * ### .isFalse(value, [message]) + * + * Asserts that `value` is false. + * + * var teaServed = false; + * assert.isFalse(teaServed, 'no tea yet? hmm...'); + * + * @name isFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFalse = function (val, msg) { + new Assertion(val, msg).is['false']; + }; + + /** + * ### .isNotFalse(value, [message]) + * + * Asserts that `value` is not false. + * + * var tea = 'tasty chai'; + * assert.isNotFalse(tea, 'great, time for tea!'); + * + * @name isNotFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFalse = function (val, msg) { + new Assertion(val, msg).to.not.equal(false); + }; + + /** + * ### .isNull(value, [message]) + * + * Asserts that `value` is null. + * + * assert.isNull(err, 'there was no error'); + * + * @name isNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNull = function (val, msg) { + new Assertion(val, msg).to.equal(null); + }; + + /** + * ### .isNotNull(value, [message]) + * + * Asserts that `value` is not null. + * + * var tea = 'tasty chai'; + * assert.isNotNull(tea, 'great, time for tea!'); + * + * @name isNotNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNull = function (val, msg) { + new Assertion(val, msg).to.not.equal(null); + }; + + /** + * ### .isNaN + * Asserts that value is NaN + * + * assert.isNaN('foo', 'foo is NaN'); + * + * @name isNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNaN = function (val, msg) { + new Assertion(val, msg).to.be.NaN; + }; + + /** + * ### .isNotNaN + * Asserts that value is not NaN + * + * assert.isNotNaN(4, '4 is not NaN'); + * + * @name isNotNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + assert.isNotNaN = function (val, msg) { + new Assertion(val, msg).not.to.be.NaN; + }; + + /** + * ### .isUndefined(value, [message]) + * + * Asserts that `value` is `undefined`. + * + * var tea; + * assert.isUndefined(tea, 'no tea defined'); + * + * @name isUndefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isUndefined = function (val, msg) { + new Assertion(val, msg).to.equal(undefined); + }; + + /** + * ### .isDefined(value, [message]) + * + * Asserts that `value` is not `undefined`. + * + * var tea = 'cup of chai'; + * assert.isDefined(tea, 'tea has been defined'); + * + * @name isDefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isDefined = function (val, msg) { + new Assertion(val, msg).to.not.equal(undefined); + }; + + /** + * ### .isFunction(value, [message]) + * + * Asserts that `value` is a function. + * + * function serveTea() { return 'cup of tea'; }; + * assert.isFunction(serveTea, 'great, we can have tea now'); + * + * @name isFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFunction = function (val, msg) { + new Assertion(val, msg).to.be.a('function'); + }; + + /** + * ### .isNotFunction(value, [message]) + * + * Asserts that `value` is _not_ a function. + * + * var serveTea = [ 'heat', 'pour', 'sip' ]; + * assert.isNotFunction(serveTea, 'great, we have listed the steps'); + * + * @name isNotFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFunction = function (val, msg) { + new Assertion(val, msg).to.not.be.a('function'); + }; + + /** + * ### .isObject(value, [message]) + * + * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). + * _The assertion does not match subclassed objects._ + * + * var selection = { name: 'Chai', serve: 'with spices' }; + * assert.isObject(selection, 'tea selection is an object'); + * + * @name isObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isObject = function (val, msg) { + new Assertion(val, msg).to.be.a('object'); + }; + + /** + * ### .isNotObject(value, [message]) + * + * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). + * + * var selection = 'chai' + * assert.isNotObject(selection, 'tea selection is not an object'); + * assert.isNotObject(null, 'null is not an object'); + * + * @name isNotObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotObject = function (val, msg) { + new Assertion(val, msg).to.not.be.a('object'); + }; + + /** + * ### .isArray(value, [message]) + * + * Asserts that `value` is an array. + * + * var menu = [ 'green', 'chai', 'oolong' ]; + * assert.isArray(menu, 'what kind of tea do we want?'); + * + * @name isArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isArray = function (val, msg) { + new Assertion(val, msg).to.be.an('array'); + }; + + /** + * ### .isNotArray(value, [message]) + * + * Asserts that `value` is _not_ an array. + * + * var menu = 'green|chai|oolong'; + * assert.isNotArray(menu, 'what kind of tea do we want?'); + * + * @name isNotArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotArray = function (val, msg) { + new Assertion(val, msg).to.not.be.an('array'); + }; + + /** + * ### .isString(value, [message]) + * + * Asserts that `value` is a string. + * + * var teaOrder = 'chai'; + * assert.isString(teaOrder, 'order placed'); + * + * @name isString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isString = function (val, msg) { + new Assertion(val, msg).to.be.a('string'); + }; + + /** + * ### .isNotString(value, [message]) + * + * Asserts that `value` is _not_ a string. + * + * var teaOrder = 4; + * assert.isNotString(teaOrder, 'order placed'); + * + * @name isNotString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotString = function (val, msg) { + new Assertion(val, msg).to.not.be.a('string'); + }; + + /** + * ### .isNumber(value, [message]) + * + * Asserts that `value` is a number. + * + * var cups = 2; + * assert.isNumber(cups, 'how many cups'); + * + * @name isNumber + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNumber = function (val, msg) { + new Assertion(val, msg).to.be.a('number'); + }; + + /** + * ### .isNotNumber(value, [message]) + * + * Asserts that `value` is _not_ a number. + * + * var cups = '2 cups please'; + * assert.isNotNumber(cups, 'how many cups'); + * + * @name isNotNumber + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNumber = function (val, msg) { + new Assertion(val, msg).to.not.be.a('number'); + }; + + /** + * ### .isBoolean(value, [message]) + * + * Asserts that `value` is a boolean. + * + * var teaReady = true + * , teaServed = false; + * + * assert.isBoolean(teaReady, 'is the tea ready'); + * assert.isBoolean(teaServed, 'has tea been served'); + * + * @name isBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBoolean = function (val, msg) { + new Assertion(val, msg).to.be.a('boolean'); + }; + + /** + * ### .isNotBoolean(value, [message]) + * + * Asserts that `value` is _not_ a boolean. + * + * var teaReady = 'yep' + * , teaServed = 'nope'; + * + * assert.isNotBoolean(teaReady, 'is the tea ready'); + * assert.isNotBoolean(teaServed, 'has tea been served'); + * + * @name isNotBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotBoolean = function (val, msg) { + new Assertion(val, msg).to.not.be.a('boolean'); + }; + + /** + * ### .typeOf(value, name, [message]) + * + * Asserts that `value`'s type is `name`, as determined by + * `Object.prototype.toString`. + * + * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); + * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); + * assert.typeOf('tea', 'string', 'we have a string'); + * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); + * assert.typeOf(null, 'null', 'we have a null'); + * assert.typeOf(undefined, 'undefined', 'we have an undefined'); + * + * @name typeOf + * @param {Mixed} value + * @param {String} name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.typeOf = function (val, type, msg) { + new Assertion(val, msg).to.be.a(type); + }; + + /** + * ### .notTypeOf(value, name, [message]) + * + * Asserts that `value`'s type is _not_ `name`, as determined by + * `Object.prototype.toString`. + * + * assert.notTypeOf('tea', 'number', 'strings are not numbers'); + * + * @name notTypeOf + * @param {Mixed} value + * @param {String} typeof name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notTypeOf = function (val, type, msg) { + new Assertion(val, msg).to.not.be.a(type); + }; + + /** + * ### .instanceOf(object, constructor, [message]) + * + * Asserts that `value` is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new Tea('chai'); + * + * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); + * + * @name instanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.instanceOf = function (val, type, msg) { + new Assertion(val, msg).to.be.instanceOf(type); + }; + + /** + * ### .notInstanceOf(object, constructor, [message]) + * + * Asserts `value` is not an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new String('chai'); + * + * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); + * + * @name notInstanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInstanceOf = function (val, type, msg) { + new Assertion(val, msg).to.not.be.instanceOf(type); + }; + + /** + * ### .include(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Works + * for strings and arrays. + * + * assert.include('foobar', 'bar', 'foobar contains string "bar"'); + * assert.include([ 1, 2, 3 ], 3, 'array contains value'); + * + * @name include + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.include = function (exp, inc, msg) { + new Assertion(exp, msg, assert.include).include(inc); + }; + + /** + * ### .notInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Works + * for strings and arrays. + * + * assert.notInclude('foobar', 'baz', 'string not include substring'); + * assert.notInclude([ 1, 2, 3 ], 4, 'array not include contain value'); + * + * @name notInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude).not.include(inc); + }; + + /** + * ### .match(value, regexp, [message]) + * + * Asserts that `value` matches the regular expression `regexp`. + * + * assert.match('foobar', /^foo/, 'regexp matches'); + * + * @name match + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.match = function (exp, re, msg) { + new Assertion(exp, msg).to.match(re); + }; + + /** + * ### .notMatch(value, regexp, [message]) + * + * Asserts that `value` does not match the regular expression `regexp`. + * + * assert.notMatch('foobar', /^foo/, 'regexp does not match'); + * + * @name notMatch + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notMatch = function (exp, re, msg) { + new Assertion(exp, msg).to.not.match(re); + }; + + /** + * ### .property(object, property, [message]) + * + * Asserts that `object` has a property named by `property`. + * + * assert.property({ tea: { green: 'matcha' }}, 'tea'); + * + * @name property + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.property = function (obj, prop, msg) { + new Assertion(obj, msg).to.have.property(prop); + }; + + /** + * ### .notProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a property named by `property`. + * + * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); + * + * @name notProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notProperty = function (obj, prop, msg) { + new Assertion(obj, msg).to.not.have.property(prop); + }; + + /** + * ### .deepProperty(object, property, [message]) + * + * Asserts that `object` has a property named by `property`, which can be a + * string using dot- and bracket-notation for deep reference. + * + * assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green'); + * + * @name deepProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepProperty = function (obj, prop, msg) { + new Assertion(obj, msg).to.have.deep.property(prop); + }; + + /** + * ### .notDeepProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a property named by `property`, which + * can be a string using dot- and bracket-notation for deep reference. + * + * assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); + * + * @name notDeepProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepProperty = function (obj, prop, msg) { + new Assertion(obj, msg).to.not.have.deep.property(prop); + }; + + /** + * ### .propertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with value given + * by `value`. + * + * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); + * + * @name propertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.propertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg).to.have.property(prop, val); + }; + + /** + * ### .propertyNotVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property`, but with a value + * different from that given by `value`. + * + * assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad'); + * + * @name propertyNotVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.propertyNotVal = function (obj, prop, val, msg) { + new Assertion(obj, msg).to.not.have.property(prop, val); + }; + + /** + * ### .deepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with value given + * by `value`. `property` can use dot- and bracket-notation for deep + * reference. + * + * assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); + * + * @name deepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg).to.have.deep.property(prop, val); + }; + + /** + * ### .deepPropertyNotVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property`, but with a value + * different from that given by `value`. `property` can use dot- and + * bracket-notation for deep reference. + * + * assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); + * + * @name deepPropertyNotVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepPropertyNotVal = function (obj, prop, val, msg) { + new Assertion(obj, msg).to.not.have.deep.property(prop, val); + }; + + /** + * ### .lengthOf(object, length, [message]) + * + * Asserts that `object` has a `length` property with the expected value. + * + * assert.lengthOf([1,2,3], 3, 'array has length of 3'); + * assert.lengthOf('foobar', 6, 'string has length of 6'); + * + * @name lengthOf + * @param {Mixed} object + * @param {Number} length + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.lengthOf = function (exp, len, msg) { + new Assertion(exp, msg).to.have.length(len); + }; + + /** + * ### .throws(function, [constructor/string/regexp], [string/regexp], [message]) + * + * Asserts that `function` will throw an error that is an instance of + * `constructor`, or alternately that it will throw an error with message + * matching `regexp`. + * + * assert.throws(fn, 'function throws a reference error'); + * assert.throws(fn, /function throws a reference error/); + * assert.throws(fn, ReferenceError); + * assert.throws(fn, ReferenceError, 'function throws a reference error'); + * assert.throws(fn, ReferenceError, /function throws a reference error/); + * + * @name throws + * @alias throw + * @alias Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.throws = function (fn, errt, errs, msg) { + if ('string' === typeof errt || errt instanceof RegExp) { + errs = errt; + errt = null; + } + + var assertErr = new Assertion(fn, msg).to.throw(errt, errs); + return flag(assertErr, 'object'); + }; + + /** + * ### .doesNotThrow(function, [constructor/regexp], [message]) + * + * Asserts that `function` will _not_ throw an error that is an instance of + * `constructor`, or alternately that it will not throw an error with message + * matching `regexp`. + * + * assert.doesNotThrow(fn, Error, 'function does not throw'); + * + * @name doesNotThrow + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.doesNotThrow = function (fn, type, msg) { + if ('string' === typeof type) { + msg = type; + type = null; + } + + new Assertion(fn, msg).to.not.Throw(type); + }; + + /** + * ### .operator(val1, operator, val2, [message]) + * + * Compares two values using `operator`. + * + * assert.operator(1, '<', 2, 'everything is ok'); + * assert.operator(1, '>', 2, 'this will fail'); + * + * @name operator + * @param {Mixed} val1 + * @param {String} operator + * @param {Mixed} val2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.operator = function (val, operator, val2, msg) { + var ok; + switch(operator) { + case '==': + ok = val == val2; + break; + case '===': + ok = val === val2; + break; + case '>': + ok = val > val2; + break; + case '>=': + ok = val >= val2; + break; + case '<': + ok = val < val2; + break; + case '<=': + ok = val <= val2; + break; + case '!=': + ok = val != val2; + break; + case '!==': + ok = val !== val2; + break; + default: + throw new Error('Invalid operator "' + operator + '"'); + } + var test = new Assertion(ok, msg); + test.assert( + true === flag(test, 'object') + , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) + , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); + }; + + /** + * ### .closeTo(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); + * + * @name closeTo + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.closeTo = function (act, exp, delta, msg) { + new Assertion(act, msg).to.be.closeTo(exp, delta); + }; + + /** + * ### .approximately(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.approximately(1.5, 1, 0.5, 'numbers are close'); + * + * @name approximately + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.approximately = function (act, exp, delta, msg) { + new Assertion(act, msg).to.be.approximately(exp, delta); + }; + + /** + * ### .sameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members. + * Order is not taken into account. + * + * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); + * + * @name sameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameMembers = function (set1, set2, msg) { + new Assertion(set1, msg).to.have.same.members(set2); + } + + /** + * ### .sameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members - using a deep equality checking. + * Order is not taken into account. + * + * assert.sameDeepMembers([ {b: 3}, {a: 2}, {c: 5} ], [ {c: 5}, {b: 3}, {a: 2} ], 'same deep members'); + * + * @name sameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg).to.have.same.deep.members(set2); + } + + /** + * ### .includeMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset`. + * Order is not taken into account. + * + * assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members'); + * + * @name includeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeMembers = function (superset, subset, msg) { + new Assertion(superset, msg).to.include.members(subset); + } + + /** + * ### .includeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` - using deep equality checking. + * Order is not taken into account. + * Duplicates are ignored. + * + * assert.includeDeepMembers([ {a: 1}, {b: 2}, {c: 3} ], [ {b: 2}, {a: 1}, {b: 2} ], 'include deep members'); + * + * @name includeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg).to.include.deep.members(subset); + } + + /** + * ### .oneOf(inList, list, [message]) + * + * Asserts that non-object, non-array value `inList` appears in the flat array `list`. + * + * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); + * + * @name oneOf + * @param {*} inList + * @param {Array<*>} list + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.oneOf = function (inList, list, msg) { + new Assertion(inList, msg).to.be.oneOf(list); + } + + /** + * ### .changes(function, object, property) + * + * Asserts that a function changes the value of a property + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 22 }; + * assert.changes(fn, obj, 'val'); + * + * @name changes + * @param {Function} modifier function + * @param {Object} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changes = function (fn, obj, prop) { + new Assertion(fn).to.change(obj, prop); + } + + /** + * ### .doesNotChange(function, object, property) + * + * Asserts that a function does not changes the value of a property + * + * var obj = { val: 10 }; + * var fn = function() { console.log('foo'); }; + * assert.doesNotChange(fn, obj, 'val'); + * + * @name doesNotChange + * @param {Function} modifier function + * @param {Object} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotChange = function (fn, obj, prop) { + new Assertion(fn).to.not.change(obj, prop); + } + + /** + * ### .increases(function, object, property) + * + * Asserts that a function increases an object property + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 13 }; + * assert.increases(fn, obj, 'val'); + * + * @name increases + * @param {Function} modifier function + * @param {Object} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increases = function (fn, obj, prop) { + new Assertion(fn).to.increase(obj, prop); + } + + /** + * ### .doesNotIncrease(function, object, property) + * + * Asserts that a function does not increase object property + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 8 }; + * assert.doesNotIncrease(fn, obj, 'val'); + * + * @name doesNotIncrease + * @param {Function} modifier function + * @param {Object} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotIncrease = function (fn, obj, prop) { + new Assertion(fn).to.not.increase(obj, prop); + } + + /** + * ### .decreases(function, object, property) + * + * Asserts that a function decreases an object property + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreases(fn, obj, 'val'); + * + * @name decreases + * @param {Function} modifier function + * @param {Object} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreases = function (fn, obj, prop) { + new Assertion(fn).to.decrease(obj, prop); + } + + /** + * ### .doesNotDecrease(function, object, property) + * + * Asserts that a function does not decreases an object property + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.doesNotDecrease(fn, obj, 'val'); + * + * @name doesNotDecrease + * @param {Function} modifier function + * @param {Object} object + * @param {String} property name + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecrease = function (fn, obj, prop) { + new Assertion(fn).to.not.decrease(obj, prop); + } + + /*! + * ### .ifError(object) + * + * Asserts if value is not a false value, and throws if it is a true value. + * This is added to allow for chai to be a drop-in replacement for Node's + * assert class. + * + * var err = new Error('I am a custom error'); + * assert.ifError(err); // Rethrows err! + * + * @name ifError + * @param {Object} object + * @namespace Assert + * @api public + */ + + assert.ifError = function (val) { + if (val) { + throw(val); + } + }; + + /** + * ### .isExtensible(object) + * + * Asserts that `object` is extensible (can have new properties added to it). + * + * assert.isExtensible({}); + * + * @name isExtensible + * @alias extensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isExtensible = function (obj, msg) { + new Assertion(obj, msg).to.be.extensible; + }; + + /** + * ### .isNotExtensible(object) + * + * Asserts that `object` is _not_ extensible. + * + * var nonExtensibleObject = Object.preventExtensions({}); + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freese({}); + * + * assert.isNotExtensible(nonExtensibleObject); + * assert.isNotExtensible(sealedObject); + * assert.isNotExtensible(frozenObject); + * + * @name isNotExtensible + * @alias notExtensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotExtensible = function (obj, msg) { + new Assertion(obj, msg).to.not.be.extensible; + }; + + /** + * ### .isSealed(object) + * + * Asserts that `object` is sealed (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.seal({}); + * + * assert.isSealed(sealedObject); + * assert.isSealed(frozenObject); + * + * @name isSealed + * @alias sealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isSealed = function (obj, msg) { + new Assertion(obj, msg).to.be.sealed; + }; + + /** + * ### .isNotSealed(object) + * + * Asserts that `object` is _not_ sealed. + * + * assert.isNotSealed({}); + * + * @name isNotSealed + * @alias notSealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotSealed = function (obj, msg) { + new Assertion(obj, msg).to.not.be.sealed; + }; + + /** + * ### .isFrozen(object) + * + * Asserts that `object` is frozen (cannot have new properties added to it + * and its existing properties cannot be modified). + * + * var frozenObject = Object.freeze({}); + * assert.frozen(frozenObject); + * + * @name isFrozen + * @alias frozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isFrozen = function (obj, msg) { + new Assertion(obj, msg).to.be.frozen; + }; + + /** + * ### .isNotFrozen(object) + * + * Asserts that `object` is _not_ frozen. + * + * assert.isNotFrozen({}); + * + * @name isNotFrozen + * @alias notFrozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotFrozen = function (obj, msg) { + new Assertion(obj, msg).to.not.be.frozen; + }; + + /*! + * Aliases. + */ + + (function alias(name, as){ + assert[as] = assert[name]; + return alias; + }) + ('isOk', 'ok') + ('isNotOk', 'notOk') + ('throws', 'throw') + ('throws', 'Throw') + ('isExtensible', 'extensible') + ('isNotExtensible', 'notExtensible') + ('isSealed', 'sealed') + ('isNotSealed', 'notSealed') + ('isFrozen', 'frozen') + ('isNotFrozen', 'notFrozen'); +}; + +},{}],18:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + chai.expect = function (val, message) { + return new chai.Assertion(val, message); + }; + + /** + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace Expect + * @api public + */ + + chai.expect.fail = function (actual, expected, message, operator) { + message = message || 'expect.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, chai.expect.fail); + }; +}; + +},{}],19:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + var Assertion = chai.Assertion; + + function loadShould () { + // explicitly define this method as function as to have it's name to include as `ssfi` + function shouldGetter() { + if (this instanceof String || this instanceof Number || this instanceof Boolean ) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + function shouldSetter(value) { + // See https://github.com/chaijs/chai/issues/86: this makes + // `whatever.should = someValue` actually set `someValue`, which is + // especially useful for `global.should = require('chai').should()`. + // + // Note that we have to use [[DefineProperty]] instead of [[Put]] + // since otherwise we would trigger this very setter! + Object.defineProperty(this, 'should', { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } + // modify Object.prototype to have `should` + Object.defineProperty(Object.prototype, 'should', { + set: shouldSetter + , get: shouldGetter + , configurable: true + }); + + var should = {}; + + /** + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace Should + * @api public + */ + + should.fail = function (actual, expected, message, operator) { + message = message || 'should.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, should.fail); + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * should.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.equal(val2); + }; + + /** + * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) + * + * Asserts that `function` will throw an error that is an instance of + * `constructor`, or alternately that it will throw an error with message + * matching `regexp`. + * + * should.throw(fn, 'function throws a reference error'); + * should.throw(fn, /function throws a reference error/); + * should.throw(fn, ReferenceError); + * should.throw(fn, ReferenceError, 'function throws a reference error'); + * should.throw(fn, ReferenceError, /function throws a reference error/); + * + * @name throw + * @alias Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * should.exist(foo, 'foo exists'); + * + * @name exist + * @namespace Should + * @api public + */ + + should.exist = function (val, msg) { + new Assertion(val, msg).to.exist; + } + + // negation + should.not = {} + + /** + * ### .not.equal(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * should.not.equal(3, 4, 'these numbers are not equal'); + * + * @name not.equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.not.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.not.equal(val2); + }; + + /** + * ### .throw(function, [constructor/regexp], [message]) + * + * Asserts that `function` will _not_ throw an error that is an instance of + * `constructor`, or alternately that it will not throw an error with message + * matching `regexp`. + * + * should.not.throw(fn, Error, 'function does not throw'); + * + * @name not.throw + * @alias not.Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.not.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + + /** + * ### .not.exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var bar = null; + * + * should.not.exist(bar, 'bar does not exist'); + * + * @name not.exist + * @namespace Should + * @api public + */ + + should.not.exist = function (val, msg) { + new Assertion(val, msg).to.not.exist; + } + + should['throw'] = should['Throw']; + should.not['throw'] = should.not['Throw']; + + return should; + }; + + chai.should = loadShould; + chai.Should = loadShould; +}; + +},{}],20:[function(require,module,exports){ +/*! + * Chai - addChainingMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var transferFlags = require('./transferFlags'); +var flag = require('./flag'); +var config = require('../config'); + +/*! + * Module variables + */ + +// Check whether `__proto__` is supported +var hasProtoSupport = '__proto__' in Object; + +// Without `__proto__` support, this module will need to add properties to a function. +// However, some Function.prototype methods cannot be overwritten, +// and there seems no easy cross-platform way to detect them (@see chaijs/chai/issues/69). +var excludeNames = /^(?:length|name|arguments|caller)$/; + +// Cache `Function` properties +var call = Function.prototype.call, + apply = Function.prototype.apply; + +/** + * ### addChainableMethod (ctx, name, method, chainingBehavior) + * + * Adds a method to an object, such that the method can also be chained. + * + * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); + * + * The result can then be used as both a method assertion, executing both `method` and + * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. + * + * expect(fooStr).to.be.foo('bar'); + * expect(fooStr).to.be.foo.equal('foo'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for `name`, when called + * @param {Function} chainingBehavior function to be called every time the property is accessed + * @namespace Utils + * @name addChainableMethod + * @api public + */ + +module.exports = function (ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== 'function') { + chainingBehavior = function () { }; + } + + var chainableBehavior = { + method: method + , chainingBehavior: chainingBehavior + }; + + // save the methods so we can overwrite them later, if we need to. + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + + Object.defineProperty(ctx, name, + { get: function () { + chainableBehavior.chainingBehavior.call(this); + + var assert = function assert() { + var old_ssfi = flag(this, 'ssfi'); + if (old_ssfi && config.includeStack === false) + flag(this, 'ssfi', assert); + var result = chainableBehavior.method.apply(this, arguments); + return result === undefined ? this : result; + }; + + // Use `__proto__` if available + if (hasProtoSupport) { + // Inherit all properties from the object by replacing the `Function` prototype + var prototype = assert.__proto__ = Object.create(this); + // Restore the `call` and `apply` methods from `Function` + prototype.call = call; + prototype.apply = apply; + } + // Otherwise, redefine all properties (slow!) + else { + var asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function (asserterName) { + if (!excludeNames.test(asserterName)) { + var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(assert, asserterName, pd); + } + }); + } + + transferFlags(this, assert); + return assert; + } + , configurable: true + }); +}; + +},{"../config":15,"./flag":24,"./transferFlags":40}],21:[function(require,module,exports){ +/*! + * Chai - addMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var config = require('../config'); + +/** + * ### .addMethod (ctx, name, method) + * + * Adds a method to the prototype of an object. + * + * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(fooStr).to.be.foo('bar'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for name + * @namespace Utils + * @name addMethod + * @api public + */ +var flag = require('./flag'); + +module.exports = function (ctx, name, method) { + ctx[name] = function () { + var old_ssfi = flag(this, 'ssfi'); + if (old_ssfi && config.includeStack === false) + flag(this, 'ssfi', ctx[name]); + var result = method.apply(this, arguments); + return result === undefined ? this : result; + }; +}; + +},{"../config":15,"./flag":24}],22:[function(require,module,exports){ +/*! + * Chai - addProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var config = require('../config'); +var flag = require('./flag'); + +/** + * ### addProperty (ctx, name, getter) + * + * Adds a property to the prototype of an object. + * + * utils.addProperty(chai.Assertion.prototype, 'foo', function () { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.instanceof(Foo); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.foo; + * + * @param {Object} ctx object to which the property is added + * @param {String} name of property to add + * @param {Function} getter function to be used for name + * @namespace Utils + * @name addProperty + * @api public + */ + +module.exports = function (ctx, name, getter) { + Object.defineProperty(ctx, name, + { get: function addProperty() { + var old_ssfi = flag(this, 'ssfi'); + if (old_ssfi && config.includeStack === false) + flag(this, 'ssfi', addProperty); + + var result = getter.call(this); + return result === undefined ? this : result; + } + , configurable: true + }); +}; + +},{"../config":15,"./flag":24}],23:[function(require,module,exports){ +/*! + * Chai - expectTypes utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### expectTypes(obj, types) + * + * Ensures that the object being tested against is of a valid type. + * + * utils.expectTypes(this, ['array', 'object', 'string']); + * + * @param {Mixed} obj constructed Assertion + * @param {Array} type A list of allowed types for this assertion + * @namespace Utils + * @name expectTypes + * @api public + */ + +var AssertionError = require('assertion-error'); +var flag = require('./flag'); +var type = require('type-detect'); + +module.exports = function (obj, types) { + var obj = flag(obj, 'object'); + types = types.map(function (t) { return t.toLowerCase(); }); + types.sort(); + + // Transforms ['lorem', 'ipsum'] into 'a lirum, or an ipsum' + var str = types.map(function (t, index) { + var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; + var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; + return or + art + ' ' + t; + }).join(', '); + + if (!types.some(function (expected) { return type(obj) === expected; })) { + throw new AssertionError( + 'object tested must be ' + str + ', but ' + type(obj) + ' given' + ); + } +}; + +},{"./flag":24,"assertion-error":11,"type-detect":82}],24:[function(require,module,exports){ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### flag(object, key, [value]) + * + * Get or set a flag value on an object. If a + * value is provided it will be set, else it will + * return the currently set value or `undefined` if + * the value is not set. + * + * utils.flag(this, 'foo', 'bar'); // setter + * utils.flag(this, 'foo'); // getter, returns `bar` + * + * @param {Object} object constructed Assertion + * @param {String} key + * @param {Mixed} value (optional) + * @namespace Utils + * @name flag + * @api private + */ + +module.exports = function (obj, key, value) { + var flags = obj.__flags || (obj.__flags = Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } +}; + +},{}],25:[function(require,module,exports){ +/*! + * Chai - getActual utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * # getActual(object, [actual]) + * + * Returns the `actual` value for an Assertion + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getActual + */ + +module.exports = function (obj, args) { + return args.length > 4 ? args[4] : obj._obj; +}; + +},{}],26:[function(require,module,exports){ +/*! + * Chai - getEnumerableProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getEnumerableProperties(object) + * + * This allows the retrieval of enumerable property names of an object, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getEnumerableProperties + * @api public + */ + +module.exports = function getEnumerableProperties(object) { + var result = []; + for (var name in object) { + result.push(name); + } + return result; +}; + +},{}],27:[function(require,module,exports){ +/*! + * Chai - message composition utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependancies + */ + +var flag = require('./flag') + , getActual = require('./getActual') + , inspect = require('./inspect') + , objDisplay = require('./objDisplay'); + +/** + * ### .getMessage(object, message, negateMessage) + * + * Construct the error message based on flags + * and template tags. Template tags will return + * a stringified inspection of the object referenced. + * + * Message template tags: + * - `#{this}` current asserted object + * - `#{act}` actual value + * - `#{exp}` expected value + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getMessage + * @api public + */ + +module.exports = function (obj, args) { + var negate = flag(obj, 'negate') + , val = flag(obj, 'object') + , expected = args[3] + , actual = getActual(obj, args) + , msg = negate ? args[2] : args[1] + , flagMsg = flag(obj, 'message'); + + if(typeof msg === "function") msg = msg(); + msg = msg || ''; + msg = msg + .replace(/#\{this\}/g, function () { return objDisplay(val); }) + .replace(/#\{act\}/g, function () { return objDisplay(actual); }) + .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); + + return flagMsg ? flagMsg + ': ' + msg : msg; +}; + +},{"./flag":24,"./getActual":25,"./inspect":34,"./objDisplay":35}],28:[function(require,module,exports){ +/*! + * Chai - getName utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * # getName(func) + * + * Gets the name of a function, in a cross-browser way. + * + * @param {Function} a function (usually a constructor) + * @namespace Utils + * @name getName + */ + +module.exports = function (func) { + if (func.name) return func.name; + + var match = /^\s?function ([^(]*)\(/.exec(func); + return match && match[1] ? match[1] : ""; +}; + +},{}],29:[function(require,module,exports){ +/*! + * Chai - getPathInfo utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var hasProperty = require('./hasProperty'); + +/** + * ### .getPathInfo(path, object) + * + * This allows the retrieval of property info in an + * object given a string path. + * + * The path info consists of an object with the + * following properties: + * + * * parent - The parent object of the property referenced by `path` + * * name - The name of the final property, a number if it was an array indexer + * * value - The value of the property, if it exists, otherwise `undefined` + * * exists - Whether the property exists or not + * + * @param {String} path + * @param {Object} object + * @returns {Object} info + * @namespace Utils + * @name getPathInfo + * @api public + */ + +module.exports = function getPathInfo(path, obj) { + var parsed = parsePath(path), + last = parsed[parsed.length - 1]; + + var info = { + parent: parsed.length > 1 ? _getPathValue(parsed, obj, parsed.length - 1) : obj, + name: last.p || last.i, + value: _getPathValue(parsed, obj) + }; + info.exists = hasProperty(info.name, info.parent); + + return info; +}; + + +/*! + * ## parsePath(path) + * + * Helper function used to parse string object + * paths. Use in conjunction with `_getPathValue`. + * + * var parsed = parsePath('myobject.property.subprop'); + * + * ### Paths: + * + * * Can be as near infinitely deep and nested + * * Arrays are also valid using the formal `myobject.document[3].property`. + * * Literal dots and brackets (not delimiter) must be backslash-escaped. + * + * @param {String} path + * @returns {Object} parsed + * @api private + */ + +function parsePath (path) { + var str = path.replace(/([^\\])\[/g, '$1.[') + , parts = str.match(/(\\\.|[^.]+?)+/g); + return parts.map(function (value) { + var re = /^\[(\d+)\]$/ + , mArr = re.exec(value); + if (mArr) return { i: parseFloat(mArr[1]) }; + else return { p: value.replace(/\\([.\[\]])/g, '$1') }; + }); +} + + +/*! + * ## _getPathValue(parsed, obj) + * + * Helper companion function for `.parsePath` that returns + * the value located at the parsed address. + * + * var value = getPathValue(parsed, obj); + * + * @param {Object} parsed definition from `parsePath`. + * @param {Object} object to search against + * @param {Number} object to search against + * @returns {Object|Undefined} value + * @api private + */ + +function _getPathValue (parsed, obj, index) { + var tmp = obj + , res; + + index = (index === undefined ? parsed.length : index); + + for (var i = 0, l = index; i < l; i++) { + var part = parsed[i]; + if (tmp) { + if ('undefined' !== typeof part.p) + tmp = tmp[part.p]; + else if ('undefined' !== typeof part.i) + tmp = tmp[part.i]; + if (i == (l - 1)) res = tmp; + } else { + res = undefined; + } + } + return res; +} + +},{"./hasProperty":32}],30:[function(require,module,exports){ +/*! + * Chai - getPathValue utility + * Copyright(c) 2012-2014 Jake Luer + * @see https://github.com/logicalparadox/filtr + * MIT Licensed + */ + +var getPathInfo = require('./getPathInfo'); + +/** + * ### .getPathValue(path, object) + * + * This allows the retrieval of values in an + * object given a string path. + * + * var obj = { + * prop1: { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * , prop2: { + * arr: [ { nested: 'Universe' } ] + * , str: 'Hello again!' + * } + * } + * + * The following would be the results. + * + * getPathValue('prop1.str', obj); // Hello + * getPathValue('prop1.att[2]', obj); // b + * getPathValue('prop2.arr[0].nested', obj); // Universe + * + * @param {String} path + * @param {Object} object + * @returns {Object} value or `undefined` + * @namespace Utils + * @name getPathValue + * @api public + */ +module.exports = function(path, obj) { + var info = getPathInfo(path, obj); + return info.value; +}; + +},{"./getPathInfo":29}],31:[function(require,module,exports){ +/*! + * Chai - getProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getProperties(object) + * + * This allows the retrieval of property names of an object, enumerable or not, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getProperties + * @api public + */ + +module.exports = function getProperties(object) { + var result = Object.getOwnPropertyNames(object); + + function addProperty(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + + var proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty); + proto = Object.getPrototypeOf(proto); + } + + return result; +}; + +},{}],32:[function(require,module,exports){ +/*! + * Chai - hasProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var type = require('type-detect'); + +/** + * ### .hasProperty(object, name) + * + * This allows checking whether an object has + * named property or numeric array index. + * + * Basically does the same thing as the `in` + * operator but works properly with natives + * and null/undefined values. + * + * var obj = { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * + * The following would be the results. + * + * hasProperty('str', obj); // true + * hasProperty('constructor', obj); // true + * hasProperty('bar', obj); // false + * + * hasProperty('length', obj.str); // true + * hasProperty(1, obj.str); // true + * hasProperty(5, obj.str); // false + * + * hasProperty('length', obj.arr); // true + * hasProperty(2, obj.arr); // true + * hasProperty(3, obj.arr); // false + * + * @param {Objuect} object + * @param {String|Number} name + * @returns {Boolean} whether it exists + * @namespace Utils + * @name getPathInfo + * @api public + */ + +var literals = { + 'number': Number + , 'string': String +}; + +module.exports = function hasProperty(name, obj) { + var ot = type(obj); + + // Bad Object, obviously no props at all + if(ot === 'null' || ot === 'undefined') + return false; + + // The `in` operator does not work with certain literals + // box these before the check + if(literals[ot] && typeof obj !== 'object') + obj = new literals[ot](obj); + + return name in obj; +}; + +},{"type-detect":82}],33:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011 Jake Luer + * MIT Licensed + */ + +/*! + * Main exports + */ + +var exports = module.exports = {}; + +/*! + * test utility + */ + +exports.test = require('./test'); + +/*! + * type utility + */ + +exports.type = require('type-detect'); + +/*! + * expectTypes utility + */ +exports.expectTypes = require('./expectTypes'); + +/*! + * message utility + */ + +exports.getMessage = require('./getMessage'); + +/*! + * actual utility + */ + +exports.getActual = require('./getActual'); + +/*! + * Inspect util + */ + +exports.inspect = require('./inspect'); + +/*! + * Object Display util + */ + +exports.objDisplay = require('./objDisplay'); + +/*! + * Flag utility + */ + +exports.flag = require('./flag'); + +/*! + * Flag transferring utility + */ + +exports.transferFlags = require('./transferFlags'); + +/*! + * Deep equal utility + */ + +exports.eql = require('deep-eql'); + +/*! + * Deep path value + */ + +exports.getPathValue = require('./getPathValue'); + +/*! + * Deep path info + */ + +exports.getPathInfo = require('./getPathInfo'); + +/*! + * Check if a property exists + */ + +exports.hasProperty = require('./hasProperty'); + +/*! + * Function name + */ + +exports.getName = require('./getName'); + +/*! + * add Property + */ + +exports.addProperty = require('./addProperty'); + +/*! + * add Method + */ + +exports.addMethod = require('./addMethod'); + +/*! + * overwrite Property + */ + +exports.overwriteProperty = require('./overwriteProperty'); + +/*! + * overwrite Method + */ + +exports.overwriteMethod = require('./overwriteMethod'); + +/*! + * Add a chainable method + */ + +exports.addChainableMethod = require('./addChainableMethod'); + +/*! + * Overwrite chainable method + */ + +exports.overwriteChainableMethod = require('./overwriteChainableMethod'); + +},{"./addChainableMethod":20,"./addMethod":21,"./addProperty":22,"./expectTypes":23,"./flag":24,"./getActual":25,"./getMessage":27,"./getName":28,"./getPathInfo":29,"./getPathValue":30,"./hasProperty":32,"./inspect":34,"./objDisplay":35,"./overwriteChainableMethod":36,"./overwriteMethod":37,"./overwriteProperty":38,"./test":39,"./transferFlags":40,"deep-eql":77,"type-detect":82}],34:[function(require,module,exports){ +// This is (almost) directly from Node.js utils +// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js + +var getName = require('./getName'); +var getProperties = require('./getProperties'); +var getEnumerableProperties = require('./getEnumerableProperties'); + +module.exports = inspect; + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Boolean} showHidden Flag that shows hidden (not enumerable) + * properties of objects. + * @param {Number} depth Depth in which to descend in object. Default is 2. + * @param {Boolean} colors Flag to turn on ANSI escape codes to color the + * output. Default is false (no coloring). + * @namespace Utils + * @name inspect + */ +function inspect(obj, showHidden, depth, colors) { + var ctx = { + showHidden: showHidden, + seen: [], + stylize: function (str) { return str; } + }; + return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); +} + +// Returns true if object is a DOM element. +var isDOMElement = function (object) { + if (typeof HTMLElement === 'object') { + return object instanceof HTMLElement; + } else { + return object && + typeof object === 'object' && + object.nodeType === 1 && + typeof object.nodeName === 'string'; + } +}; + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (value && typeof value.inspect === 'function' && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes); + if (typeof ret !== 'string') { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // If this is a DOM element, try to get the outer HTML. + if (isDOMElement(value)) { + if ('outerHTML' in value) { + return value.outerHTML; + // This value does not have an outerHTML attribute, + // it could still be an XML element + } else { + // Attempt to serialize it + try { + if (document.xmlVersion) { + var xmlSerializer = new XMLSerializer(); + return xmlSerializer.serializeToString(value); + } else { + // Firefox 11- do not support outerHTML + // It does, however, support innerHTML + // Use the following to render the element + var ns = "http://www.w3.org/1999/xhtml"; + var container = document.createElementNS(ns, '_'); + + container.appendChild(value.cloneNode(false)); + html = container.innerHTML + .replace('><', '>' + value.innerHTML + '<'); + container.innerHTML = ''; + return html; + } + } catch (err) { + // This could be a non-native DOM implementation, + // continue with the normal flow: + // printing the element as if it is an object. + } + } + } + + // Look up the keys of the object. + var visibleKeys = getEnumerableProperties(value); + var keys = ctx.showHidden ? getProperties(value) : visibleKeys; + + // Some type of object without properties can be shortcutted. + // In IE, errors have a single `stack` property, or if they are vanilla `Error`, + // a `stack` plus `description` property; ignore those for consistency. + if (keys.length === 0 || (isError(value) && ( + (keys.length === 1 && keys[0] === 'stack') || + (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') + ))) { + if (typeof value === 'function') { + var name = getName(value); + var nameSuffix = name ? ': ' + name : ''; + return ctx.stylize('[Function' + nameSuffix + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (typeof value === 'function') { + var name = getName(value); + var nameSuffix = name ? ': ' + name : ''; + base = ' [Function' + nameSuffix + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + return formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + switch (typeof value) { + case 'undefined': + return ctx.stylize('undefined', 'undefined'); + + case 'string': + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + + case 'number': + if (value === 0 && (1/value) === -Infinity) { + return ctx.stylize('-0', 'number'); + } + return ctx.stylize('' + value, 'number'); + + case 'boolean': + return ctx.stylize('' + value, 'boolean'); + } + // For some reason typeof null is "object", so special case here. + if (value === null) { + return ctx.stylize('null', 'null'); + } +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (Object.prototype.hasOwnProperty.call(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str; + if (value.__lookupGetter__) { + if (value.__lookupGetter__(key)) { + if (value.__lookupSetter__(key)) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (value.__lookupSetter__(key)) { + str = ctx.stylize('[Setter]', 'special'); + } + } + } + if (visibleKeys.indexOf(key) < 0) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(value[key]) < 0) { + if (recurseTimes === null) { + str = formatValue(ctx, value[key], null); + } else { + str = formatValue(ctx, value[key], recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (typeof name === 'undefined') { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + +function isArray(ar) { + return Array.isArray(ar) || + (typeof ar === 'object' && objectToString(ar) === '[object Array]'); +} + +function isRegExp(re) { + return typeof re === 'object' && objectToString(re) === '[object RegExp]'; +} + +function isDate(d) { + return typeof d === 'object' && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return typeof e === 'object' && objectToString(e) === '[object Error]'; +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +},{"./getEnumerableProperties":26,"./getName":28,"./getProperties":31}],35:[function(require,module,exports){ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependancies + */ + +var inspect = require('./inspect'); +var config = require('../config'); + +/** + * ### .objDisplay (object) + * + * Determines if an object or an array matches + * criteria to be inspected in-line for error + * messages or should be truncated. + * + * @param {Mixed} javascript object to inspect + * @name objDisplay + * @namespace Utils + * @api public + */ + +module.exports = function (obj) { + var str = inspect(obj) + , type = Object.prototype.toString.call(obj); + + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type === '[object Function]') { + return !obj.name || obj.name === '' + ? '[Function]' + : '[Function: ' + obj.name + ']'; + } else if (type === '[object Array]') { + return '[ Array(' + obj.length + ') ]'; + } else if (type === '[object Object]') { + var keys = Object.keys(obj) + , kstr = keys.length > 2 + ? keys.splice(0, 2).join(', ') + ', ...' + : keys.join(', '); + return '{ Object (' + kstr + ') }'; + } else { + return str; + } + } else { + return str; + } +}; + +},{"../config":15,"./inspect":34}],36:[function(require,module,exports){ +/*! + * Chai - overwriteChainableMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### overwriteChainableMethod (ctx, name, method, chainingBehavior) + * + * Overwites an already existing chainable method + * and provides access to the previous function or + * property. Must return functions to be used for + * name. + * + * utils.overwriteChainableMethod(chai.Assertion.prototype, 'length', + * function (_super) { + * } + * , function (_super) { + * } + * ); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteChainableMethod('foo', fn, fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.have.length(3); + * expect(myFoo).to.have.length.above(3); + * + * @param {Object} ctx object whose method / property is to be overwritten + * @param {String} name of method / property to overwrite + * @param {Function} method function that returns a function to be used for name + * @param {Function} chainingBehavior function that returns a function to be used for property + * @namespace Utils + * @name overwriteChainableMethod + * @api public + */ + +module.exports = function (ctx, name, method, chainingBehavior) { + var chainableBehavior = ctx.__methods[name]; + + var _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = function () { + var result = chainingBehavior(_chainingBehavior).call(this); + return result === undefined ? this : result; + }; + + var _method = chainableBehavior.method; + chainableBehavior.method = function () { + var result = method(_method).apply(this, arguments); + return result === undefined ? this : result; + }; +}; + +},{}],37:[function(require,module,exports){ +/*! + * Chai - overwriteMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### overwriteMethod (ctx, name, fn) + * + * Overwites an already existing method and provides + * access to previous function. Must return function + * to be used for name. + * + * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { + * return function (str) { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.value).to.equal(str); + * } else { + * _super.apply(this, arguments); + * } + * } + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.equal('bar'); + * + * @param {Object} ctx object whose method is to be overwritten + * @param {String} name of method to overwrite + * @param {Function} method function that returns a function to be used for name + * @namespace Utils + * @name overwriteMethod + * @api public + */ + +module.exports = function (ctx, name, method) { + var _method = ctx[name] + , _super = function () { return this; }; + + if (_method && 'function' === typeof _method) + _super = _method; + + ctx[name] = function () { + var result = method(_super).apply(this, arguments); + return result === undefined ? this : result; + } +}; + +},{}],38:[function(require,module,exports){ +/*! + * Chai - overwriteProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### overwriteProperty (ctx, name, fn) + * + * Overwites an already existing property getter and provides + * access to previous value. Must return function to use as getter. + * + * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { + * return function () { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.name).to.equal('bar'); + * } else { + * _super.call(this); + * } + * } + * }); + * + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.ok; + * + * @param {Object} ctx object whose property is to be overwritten + * @param {String} name of property to overwrite + * @param {Function} getter function that returns a getter function to be used for name + * @namespace Utils + * @name overwriteProperty + * @api public + */ + +module.exports = function (ctx, name, getter) { + var _get = Object.getOwnPropertyDescriptor(ctx, name) + , _super = function () {}; + + if (_get && 'function' === typeof _get.get) + _super = _get.get + + Object.defineProperty(ctx, name, + { get: function () { + var result = getter(_super).call(this); + return result === undefined ? this : result; + } + , configurable: true + }); +}; + +},{}],39:[function(require,module,exports){ +/*! + * Chai - test utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependancies + */ + +var flag = require('./flag'); + +/** + * # test(object, expression) + * + * Test and object for expression. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name test + */ + +module.exports = function (obj, args) { + var negate = flag(obj, 'negate') + , expr = args[0]; + return negate ? !expr : expr; +}; + +},{"./flag":24}],40:[function(require,module,exports){ +/*! + * Chai - transferFlags utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### transferFlags(assertion, object, includeAll = true) + * + * Transfer all the flags for `assertion` to `object`. If + * `includeAll` is set to `false`, then the base Chai + * assertion flags (namely `object`, `ssfi`, and `message`) + * will not be transferred. + * + * + * var newAssertion = new Assertion(); + * utils.transferFlags(assertion, newAssertion); + * + * var anotherAsseriton = new Assertion(myObj); + * utils.transferFlags(assertion, anotherAssertion, false); + * + * @param {Assertion} assertion the assertion to transfer the flags from + * @param {Object} object the object to transfer the flags to; usually a new assertion + * @param {Boolean} includeAll + * @namespace Utils + * @name transferFlags + * @api private + */ + +module.exports = function (assertion, object, includeAll) { + var flags = assertion.__flags || (assertion.__flags = Object.create(null)); + + if (!object.__flags) { + object.__flags = Object.create(null); + } + + includeAll = arguments.length === 3 ? includeAll : true; + + for (var flag in flags) { + if (includeAll || + (flag !== 'object' && flag !== 'ssfi' && flag != 'message')) { + object.__flags[flag] = flags[flag]; + } + } +}; + +},{}],41:[function(require,module,exports){ +require('../../modules/es6.object.assign'); +module.exports = require('../../modules/_core').Object.assign; +},{"../../modules/_core":46,"../../modules/es6.object.assign":76}],42:[function(require,module,exports){ +module.exports = function(it){ + if(typeof it != 'function')throw TypeError(it + ' is not a function!'); + return it; +}; +},{}],43:[function(require,module,exports){ +var isObject = require('./_is-object'); +module.exports = function(it){ + if(!isObject(it))throw TypeError(it + ' is not an object!'); + return it; +}; +},{"./_is-object":59}],44:[function(require,module,exports){ +// false -> Array#indexOf +// true -> Array#includes +var toIObject = require('./_to-iobject') + , toLength = require('./_to-length') + , toIndex = require('./_to-index'); +module.exports = function(IS_INCLUDES){ + return function($this, el, fromIndex){ + var O = toIObject($this) + , length = toLength(O.length) + , index = toIndex(fromIndex, length) + , value; + // Array#includes uses SameValueZero equality algorithm + if(IS_INCLUDES && el != el)while(length > index){ + value = O[index++]; + if(value != value)return true; + // Array#toIndex ignores holes, Array#includes - not + } else for(;length > index; index++)if(IS_INCLUDES || index in O){ + if(O[index] === el)return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; +},{"./_to-index":69,"./_to-iobject":71,"./_to-length":72}],45:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = function(it){ + return toString.call(it).slice(8, -1); +}; +},{}],46:[function(require,module,exports){ +var core = module.exports = {version: '2.4.0'}; +if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef +},{}],47:[function(require,module,exports){ +// optional / simple context binding +var aFunction = require('./_a-function'); +module.exports = function(fn, that, length){ + aFunction(fn); + if(that === undefined)return fn; + switch(length){ + case 1: return function(a){ + return fn.call(that, a); + }; + case 2: return function(a, b){ + return fn.call(that, a, b); + }; + case 3: return function(a, b, c){ + return fn.call(that, a, b, c); + }; + } + return function(/* ...args */){ + return fn.apply(that, arguments); + }; +}; +},{"./_a-function":42}],48:[function(require,module,exports){ +// 7.2.1 RequireObjectCoercible(argument) +module.exports = function(it){ + if(it == undefined)throw TypeError("Can't call method on " + it); + return it; +}; +},{}],49:[function(require,module,exports){ +// Thank's IE8 for his funny defineProperty +module.exports = !require('./_fails')(function(){ + return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; +}); +},{"./_fails":53}],50:[function(require,module,exports){ +var isObject = require('./_is-object') + , document = require('./_global').document + // in old IE typeof document.createElement is 'object' + , is = isObject(document) && isObject(document.createElement); +module.exports = function(it){ + return is ? document.createElement(it) : {}; +}; +},{"./_global":54,"./_is-object":59}],51:[function(require,module,exports){ +// IE 8- don't enum bug keys +module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); +},{}],52:[function(require,module,exports){ +var global = require('./_global') + , core = require('./_core') + , ctx = require('./_ctx') + , hide = require('./_hide') + , PROTOTYPE = 'prototype'; + +var $export = function(type, name, source){ + var IS_FORCED = type & $export.F + , IS_GLOBAL = type & $export.G + , IS_STATIC = type & $export.S + , IS_PROTO = type & $export.P + , IS_BIND = type & $export.B + , IS_WRAP = type & $export.W + , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) + , expProto = exports[PROTOTYPE] + , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] + , key, own, out; + if(IS_GLOBAL)source = name; + for(key in source){ + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if(own && key in exports)continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? ctx(out, global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function(C){ + var F = function(a, b, c){ + if(this instanceof C){ + switch(arguments.length){ + case 0: return new C; + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if(IS_PROTO){ + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); + } + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +module.exports = $export; +},{"./_core":46,"./_ctx":47,"./_global":54,"./_hide":56}],53:[function(require,module,exports){ +module.exports = function(exec){ + try { + return !!exec(); + } catch(e){ + return true; + } +}; +},{}],54:[function(require,module,exports){ +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); +if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef +},{}],55:[function(require,module,exports){ +var hasOwnProperty = {}.hasOwnProperty; +module.exports = function(it, key){ + return hasOwnProperty.call(it, key); +}; +},{}],56:[function(require,module,exports){ +var dP = require('./_object-dp') + , createDesc = require('./_property-desc'); +module.exports = require('./_descriptors') ? function(object, key, value){ + return dP.f(object, key, createDesc(1, value)); +} : function(object, key, value){ + object[key] = value; + return object; +}; +},{"./_descriptors":49,"./_object-dp":61,"./_property-desc":66}],57:[function(require,module,exports){ +module.exports = !require('./_descriptors') && !require('./_fails')(function(){ + return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7; +}); +},{"./_descriptors":49,"./_dom-create":50,"./_fails":53}],58:[function(require,module,exports){ +// fallback for non-array-like ES3 and non-enumerable old V8 strings +var cof = require('./_cof'); +module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ + return cof(it) == 'String' ? it.split('') : Object(it); +}; +},{"./_cof":45}],59:[function(require,module,exports){ +module.exports = function(it){ + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; +},{}],60:[function(require,module,exports){ +'use strict'; +// 19.1.2.1 Object.assign(target, source, ...) +var getKeys = require('./_object-keys') + , gOPS = require('./_object-gops') + , pIE = require('./_object-pie') + , toObject = require('./_to-object') + , IObject = require('./_iobject') + , $assign = Object.assign; + +// should work with symbols and should have deterministic property order (V8 bug) +module.exports = !$assign || require('./_fails')(function(){ + var A = {} + , B = {} + , S = Symbol() + , K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function(k){ B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; +}) ? function assign(target, source){ // eslint-disable-line no-unused-vars + var T = toObject(target) + , aLen = arguments.length + , index = 1 + , getSymbols = gOPS.f + , isEnum = pIE.f; + while(aLen > index){ + var S = IObject(arguments[index++]) + , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) + , length = keys.length + , j = 0 + , key; + while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; + } return T; +} : $assign; +},{"./_fails":53,"./_iobject":58,"./_object-gops":62,"./_object-keys":64,"./_object-pie":65,"./_to-object":73}],61:[function(require,module,exports){ +var anObject = require('./_an-object') + , IE8_DOM_DEFINE = require('./_ie8-dom-define') + , toPrimitive = require('./_to-primitive') + , dP = Object.defineProperty; + +exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){ + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if(IE8_DOM_DEFINE)try { + return dP(O, P, Attributes); + } catch(e){ /* empty */ } + if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); + if('value' in Attributes)O[P] = Attributes.value; + return O; +}; +},{"./_an-object":43,"./_descriptors":49,"./_ie8-dom-define":57,"./_to-primitive":74}],62:[function(require,module,exports){ +exports.f = Object.getOwnPropertySymbols; +},{}],63:[function(require,module,exports){ +var has = require('./_has') + , toIObject = require('./_to-iobject') + , arrayIndexOf = require('./_array-includes')(false) + , IE_PROTO = require('./_shared-key')('IE_PROTO'); + +module.exports = function(object, names){ + var O = toIObject(object) + , i = 0 + , result = [] + , key; + for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while(names.length > i)if(has(O, key = names[i++])){ + ~arrayIndexOf(result, key) || result.push(key); + } + return result; +}; +},{"./_array-includes":44,"./_has":55,"./_shared-key":67,"./_to-iobject":71}],64:[function(require,module,exports){ +// 19.1.2.14 / 15.2.3.14 Object.keys(O) +var $keys = require('./_object-keys-internal') + , enumBugKeys = require('./_enum-bug-keys'); + +module.exports = Object.keys || function keys(O){ + return $keys(O, enumBugKeys); +}; +},{"./_enum-bug-keys":51,"./_object-keys-internal":63}],65:[function(require,module,exports){ +exports.f = {}.propertyIsEnumerable; +},{}],66:[function(require,module,exports){ +module.exports = function(bitmap, value){ + return { + enumerable : !(bitmap & 1), + configurable: !(bitmap & 2), + writable : !(bitmap & 4), + value : value + }; +}; +},{}],67:[function(require,module,exports){ +var shared = require('./_shared')('keys') + , uid = require('./_uid'); +module.exports = function(key){ + return shared[key] || (shared[key] = uid(key)); +}; +},{"./_shared":68,"./_uid":75}],68:[function(require,module,exports){ +var global = require('./_global') + , SHARED = '__core-js_shared__' + , store = global[SHARED] || (global[SHARED] = {}); +module.exports = function(key){ + return store[key] || (store[key] = {}); +}; +},{"./_global":54}],69:[function(require,module,exports){ +var toInteger = require('./_to-integer') + , max = Math.max + , min = Math.min; +module.exports = function(index, length){ + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); +}; +},{"./_to-integer":70}],70:[function(require,module,exports){ +// 7.1.4 ToInteger +var ceil = Math.ceil + , floor = Math.floor; +module.exports = function(it){ + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; +},{}],71:[function(require,module,exports){ +// to indexed object, toObject with fallback for non-array-like ES3 strings +var IObject = require('./_iobject') + , defined = require('./_defined'); +module.exports = function(it){ + return IObject(defined(it)); +}; +},{"./_defined":48,"./_iobject":58}],72:[function(require,module,exports){ +// 7.1.15 ToLength +var toInteger = require('./_to-integer') + , min = Math.min; +module.exports = function(it){ + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; +},{"./_to-integer":70}],73:[function(require,module,exports){ +// 7.1.13 ToObject(argument) +var defined = require('./_defined'); +module.exports = function(it){ + return Object(defined(it)); +}; +},{"./_defined":48}],74:[function(require,module,exports){ +// 7.1.1 ToPrimitive(input [, PreferredType]) +var isObject = require('./_is-object'); +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +module.exports = function(it, S){ + if(!isObject(it))return it; + var fn, val; + if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; + if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; + if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; + throw TypeError("Can't convert object to primitive value"); +}; +},{"./_is-object":59}],75:[function(require,module,exports){ +var id = 0 + , px = Math.random(); +module.exports = function(key){ + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); +}; +},{}],76:[function(require,module,exports){ +// 19.1.3.1 Object.assign(target, source) +var $export = require('./_export'); + +$export($export.S + $export.F, 'Object', {assign: require('./_object-assign')}); +},{"./_export":52,"./_object-assign":60}],77:[function(require,module,exports){ +module.exports = require('./lib/eql'); + +},{"./lib/eql":78}],78:[function(require,module,exports){ +/*! + * deep-eql + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var type = require('type-detect'); + +/*! + * Buffer.isBuffer browser shim + */ + +var Buffer; +try { Buffer = require('buffer').Buffer; } +catch(ex) { + Buffer = {}; + Buffer.isBuffer = function() { return false; } +} + +/*! + * Primary Export + */ + +module.exports = deepEqual; + +/** + * Assert super-strict (egal) equality between + * two objects of any type. + * + * @param {Mixed} a + * @param {Mixed} b + * @param {Array} memoised (optional) + * @return {Boolean} equal match + */ + +function deepEqual(a, b, m) { + if (sameValue(a, b)) { + return true; + } else if ('date' === type(a)) { + return dateEqual(a, b); + } else if ('regexp' === type(a)) { + return regexpEqual(a, b); + } else if (Buffer.isBuffer(a)) { + return bufferEqual(a, b); + } else if ('arguments' === type(a)) { + return argumentsEqual(a, b, m); + } else if (!typeEqual(a, b)) { + return false; + } else if (('object' !== type(a) && 'object' !== type(b)) + && ('array' !== type(a) && 'array' !== type(b))) { + return sameValue(a, b); + } else { + return objectEqual(a, b, m); + } +} + +/*! + * Strict (egal) equality test. Ensures that NaN always + * equals NaN and `-0` does not equal `+0`. + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} equal match + */ + +function sameValue(a, b) { + if (a === b) return a !== 0 || 1 / a === 1 / b; + return a !== a && b !== b; +} + +/*! + * Compare the types of two given objects and + * return if they are equal. Note that an Array + * has a type of `array` (not `object`) and arguments + * have a type of `arguments` (not `array`/`object`). + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function typeEqual(a, b) { + return type(a) === type(b); +} + +/*! + * Compare two Date objects by asserting that + * the time values are equal using `saveValue`. + * + * @param {Date} a + * @param {Date} b + * @return {Boolean} result + */ + +function dateEqual(a, b) { + if ('date' !== type(b)) return false; + return sameValue(a.getTime(), b.getTime()); +} + +/*! + * Compare two regular expressions by converting them + * to string and checking for `sameValue`. + * + * @param {RegExp} a + * @param {RegExp} b + * @return {Boolean} result + */ + +function regexpEqual(a, b) { + if ('regexp' !== type(b)) return false; + return sameValue(a.toString(), b.toString()); +} + +/*! + * Assert deep equality of two `arguments` objects. + * Unfortunately, these must be sliced to arrays + * prior to test to ensure no bad behavior. + * + * @param {Arguments} a + * @param {Arguments} b + * @param {Array} memoize (optional) + * @return {Boolean} result + */ + +function argumentsEqual(a, b, m) { + if ('arguments' !== type(b)) return false; + a = [].slice.call(a); + b = [].slice.call(b); + return deepEqual(a, b, m); +} + +/*! + * Get enumerable properties of a given object. + * + * @param {Object} a + * @return {Array} property names + */ + +function enumerable(a) { + var res = []; + for (var key in a) res.push(key); + return res; +} + +/*! + * Simple equality for flat iterable objects + * such as Arrays or Node.js buffers. + * + * @param {Iterable} a + * @param {Iterable} b + * @return {Boolean} result + */ + +function iterableEqual(a, b) { + if (a.length !== b.length) return false; + + var i = 0; + var match = true; + + for (; i < a.length; i++) { + if (a[i] !== b[i]) { + match = false; + break; + } + } + + return match; +} + +/*! + * Extension to `iterableEqual` specifically + * for Node.js Buffers. + * + * @param {Buffer} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function bufferEqual(a, b) { + if (!Buffer.isBuffer(b)) return false; + return iterableEqual(a, b); +} + +/*! + * Block for `objectEqual` ensuring non-existing + * values don't get in. + * + * @param {Mixed} object + * @return {Boolean} result + */ + +function isValue(a) { + return a !== null && a !== undefined; +} + +/*! + * Recursively check the equality of two objects. + * Once basic sameness has been established it will + * defer to `deepEqual` for each enumerable key + * in the object. + * + * @param {Mixed} a + * @param {Mixed} b + * @return {Boolean} result + */ + +function objectEqual(a, b, m) { + if (!isValue(a) || !isValue(b)) { + return false; + } + + if (a.prototype !== b.prototype) { + return false; + } + + var i; + if (m) { + for (i = 0; i < m.length; i++) { + if ((m[i][0] === a && m[i][1] === b) + || (m[i][0] === b && m[i][1] === a)) { + return true; + } + } + } else { + m = []; + } + + try { + var ka = enumerable(a); + var kb = enumerable(b); + } catch (ex) { + return false; + } + + ka.sort(); + kb.sort(); + + if (!iterableEqual(ka, kb)) { + return false; + } + + m.push([ a, b ]); + + var key; + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key], m)) { + return false; + } + } + + return true; +} + +},{"buffer":2,"type-detect":79}],79:[function(require,module,exports){ +module.exports = require('./lib/type'); + +},{"./lib/type":80}],80:[function(require,module,exports){ +/*! + * type-detect + * Copyright(c) 2013 jake luer + * MIT Licensed + */ + +/*! + * Primary Exports + */ + +var exports = module.exports = getType; + +/*! + * Detectable javascript natives + */ + +var natives = { + '[object Array]': 'array' + , '[object RegExp]': 'regexp' + , '[object Function]': 'function' + , '[object Arguments]': 'arguments' + , '[object Date]': 'date' +}; + +/** + * ### typeOf (obj) + * + * Use several different techniques to determine + * the type of object being tested. + * + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ + +function getType (obj) { + var str = Object.prototype.toString.call(obj); + if (natives[str]) return natives[str]; + if (obj === null) return 'null'; + if (obj === undefined) return 'undefined'; + if (obj === Object(obj)) return 'object'; + return typeof obj; +} + +exports.Library = Library; + +/** + * ### Library + * + * Create a repository for custom type detection. + * + * ```js + * var lib = new type.Library; + * ``` + * + */ + +function Library () { + this.tests = {}; +} + +/** + * #### .of (obj) + * + * Expose replacement `typeof` detection to the library. + * + * ```js + * if ('string' === lib.of('hello world')) { + * // ... + * } + * ``` + * + * @param {Mixed} object to test + * @return {String} type + */ + +Library.prototype.of = getType; + +/** + * #### .define (type, test) + * + * Add a test to for the `.test()` assertion. + * + * Can be defined as a regular expression: + * + * ```js + * lib.define('int', /^[0-9]+$/); + * ``` + * + * ... or as a function: + * + * ```js + * lib.define('bln', function (obj) { + * if ('boolean' === lib.of(obj)) return true; + * var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ]; + * if ('string' === lib.of(obj)) obj = obj.toLowerCase(); + * return !! ~blns.indexOf(obj); + * }); + * ``` + * + * @param {String} type + * @param {RegExp|Function} test + * @api public + */ + +Library.prototype.define = function (type, test) { + if (arguments.length === 1) return this.tests[type]; + this.tests[type] = test; + return this; +}; + +/** + * #### .test (obj, test) + * + * Assert that an object is of type. Will first + * check natives, and if that does not pass it will + * use the user defined custom tests. + * + * ```js + * assert(lib.test('1', 'int')); + * assert(lib.test('yes', 'bln')); + * ``` + * + * @param {Mixed} object + * @param {String} type + * @return {Boolean} result + * @api public + */ + +Library.prototype.test = function (obj, type) { + if (type === getType(obj)) return true; + var test = this.tests[type]; + + if (test && 'regexp' === getType(test)) { + return test.test(obj); + } else if (test && 'function' === getType(test)) { + return test(obj); + } else { + throw new ReferenceError('Type test "' + type + '" not defined or invalid.'); + } +}; + +},{}],81:[function(require,module,exports){ +// the whatwg-fetch polyfill installs the fetch() function +// on the global object (window or self) +// +// Return that as the export for use in Webpack, Browserify etc. +require('whatwg-fetch'); +module.exports = self.fetch.bind(self); + +},{"whatwg-fetch":85}],82:[function(require,module,exports){ +arguments[4][79][0].apply(exports,arguments) +},{"./lib/type":83,"dup":79}],83:[function(require,module,exports){ +/*! + * type-detect + * Copyright(c) 2013 jake luer + * MIT Licensed + */ + +/*! + * Primary Exports + */ + +var exports = module.exports = getType; + +/** + * ### typeOf (obj) + * + * Use several different techniques to determine + * the type of object being tested. + * + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ +var objectTypeRegexp = /^\[object (.*)\]$/; + +function getType(obj) { + var type = Object.prototype.toString.call(obj).match(objectTypeRegexp)[1].toLowerCase(); + // Let "new String('')" return 'object' + if (typeof Promise === 'function' && obj instanceof Promise) return 'promise'; + // PhantomJS has type "DOMWindow" for null + if (obj === null) return 'null'; + // PhantomJS has type "DOMWindow" for undefined + if (obj === undefined) return 'undefined'; + return type; +} + +exports.Library = Library; + +/** + * ### Library + * + * Create a repository for custom type detection. + * + * ```js + * var lib = new type.Library; + * ``` + * + */ + +function Library() { + if (!(this instanceof Library)) return new Library(); + this.tests = {}; +} + +/** + * #### .of (obj) + * + * Expose replacement `typeof` detection to the library. + * + * ```js + * if ('string' === lib.of('hello world')) { + * // ... + * } + * ``` + * + * @param {Mixed} object to test + * @return {String} type + */ + +Library.prototype.of = getType; + +/** + * #### .define (type, test) + * + * Add a test to for the `.test()` assertion. + * + * Can be defined as a regular expression: + * + * ```js + * lib.define('int', /^[0-9]+$/); + * ``` + * + * ... or as a function: + * + * ```js + * lib.define('bln', function (obj) { + * if ('boolean' === lib.of(obj)) return true; + * var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ]; + * if ('string' === lib.of(obj)) obj = obj.toLowerCase(); + * return !! ~blns.indexOf(obj); + * }); + * ``` + * + * @param {String} type + * @param {RegExp|Function} test + * @api public + */ + +Library.prototype.define = function(type, test) { + if (arguments.length === 1) return this.tests[type]; + this.tests[type] = test; + return this; +}; + +/** + * #### .test (obj, test) + * + * Assert that an object is of type. Will first + * check natives, and if that does not pass it will + * use the user defined custom tests. + * + * ```js + * assert(lib.test('1', 'int')); + * assert(lib.test('yes', 'bln')); + * ``` + * + * @param {Mixed} object + * @param {String} type + * @return {Boolean} result + * @api public + */ + +Library.prototype.test = function(obj, type) { + if (type === getType(obj)) return true; + var test = this.tests[type]; + + if (test && 'regexp' === getType(test)) { + return test.test(obj); + } else if (test && 'function' === getType(test)) { + return test(obj); + } else { + throw new ReferenceError('Type test "' + type + '" not defined or invalid.'); + } +}; + +},{}],84:[function(require,module,exports){ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var querystring = require("querystring"); +var url = require("url"); +var isomorphicFetch = require("isomorphic-fetch"); +var assign = require("core-js/library/fn/object/assign"); +var BaseAPI = (function () { + function BaseAPI(basePath, fetch) { + if (basePath === void 0) { basePath = "http://petstore.swagger.io/v2"; } + if (fetch === void 0) { fetch = isomorphicFetch; } + this.basePath = basePath; + this.fetch = fetch; + } + return BaseAPI; +}()); +exports.BaseAPI = BaseAPI; +var PetApi = (function (_super) { + __extends(PetApi, _super); + function PetApi() { + _super.apply(this, arguments); + } + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + PetApi.prototype.addPet = function (params) { + var baseUrl = this.basePath + "/pet"; + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "POST" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + PetApi.prototype.deletePet = function (params) { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + var baseUrl = (this.basePath + "/pet/{petId}") + .replace("{" + "petId" + "}", "" + params.petId); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "DELETE" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + PetApi.prototype.findPetsByStatus = function (params) { + var baseUrl = this.basePath + "/pet/findByStatus"; + var urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "status": params.status, + }); + var fetchOptions = { method: "GET" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + PetApi.prototype.findPetsByTags = function (params) { + var baseUrl = this.basePath + "/pet/findByTags"; + var urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "tags": params.tags, + }); + var fetchOptions = { method: "GET" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + PetApi.prototype.getPetById = function (params) { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + var baseUrl = (this.basePath + "/pet/{petId}") + .replace("{" + "petId" + "}", "" + params.petId); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "GET" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + PetApi.prototype.updatePet = function (params) { + var baseUrl = this.basePath + "/pet"; + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "PUT" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + PetApi.prototype.updatePetWithForm = function (params) { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + var baseUrl = (this.basePath + "/pet/{petId}") + .replace("{" + "petId" + "}", "" + params.petId); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "POST" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + PetApi.prototype.uploadFile = function (params) { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + var baseUrl = (this.basePath + "/pet/{petId}/uploadImage") + .replace("{" + "petId" + "}", "" + params.petId); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "POST" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + return PetApi; +}(BaseAPI)); +exports.PetApi = PetApi; +var StoreApi = (function (_super) { + __extends(StoreApi, _super); + function StoreApi() { + _super.apply(this, arguments); + } + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + StoreApi.prototype.deleteOrder = function (params) { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + var baseUrl = (this.basePath + "/store/order/{orderId}") + .replace("{" + "orderId" + "}", "" + params.orderId); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "DELETE" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + StoreApi.prototype.getInventory = function () { + var baseUrl = this.basePath + "/store/inventory"; + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "GET" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + StoreApi.prototype.getOrderById = function (params) { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + var baseUrl = (this.basePath + "/store/order/{orderId}") + .replace("{" + "orderId" + "}", "" + params.orderId); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "GET" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + StoreApi.prototype.placeOrder = function (params) { + var baseUrl = this.basePath + "/store/order"; + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "POST" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + return StoreApi; +}(BaseAPI)); +exports.StoreApi = StoreApi; +var UserApi = (function (_super) { + __extends(UserApi, _super); + function UserApi() { + _super.apply(this, arguments); + } + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + UserApi.prototype.createUser = function (params) { + var baseUrl = this.basePath + "/user"; + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "POST" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + UserApi.prototype.createUsersWithArrayInput = function (params) { + var baseUrl = this.basePath + "/user/createWithArray"; + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "POST" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + UserApi.prototype.createUsersWithListInput = function (params) { + var baseUrl = this.basePath + "/user/createWithList"; + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "POST" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + UserApi.prototype.deleteUser = function (params) { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + var baseUrl = (this.basePath + "/user/{username}") + .replace("{" + "username" + "}", "" + params.username); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "DELETE" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + UserApi.prototype.getUserByName = function (params) { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + var baseUrl = (this.basePath + "/user/{username}") + .replace("{" + "username" + "}", "" + params.username); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "GET" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + UserApi.prototype.loginUser = function (params) { + var baseUrl = this.basePath + "/user/login"; + var urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + var fetchOptions = { method: "GET" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Logs out current logged in user session + * + */ + UserApi.prototype.logoutUser = function () { + var baseUrl = this.basePath + "/user/logout"; + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "GET" }; + var contentTypeHeader; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + UserApi.prototype.updateUser = function (params) { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + var baseUrl = (this.basePath + "/user/{username}") + .replace("{" + "username" + "}", "" + params.username); + var urlObj = url.parse(baseUrl, true); + var fetchOptions = { method: "PUT" }; + var contentTypeHeader; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { + if (response.status >= 200 && response.status < 300) { + return response; + } + else { + throw assign(new Error(response.statusText), { response: response }); + } + }); + }; + return UserApi; +}(BaseAPI)); +exports.UserApi = UserApi; + +},{"core-js/library/fn/object/assign":41,"isomorphic-fetch":81,"querystring":8,"url":9}],85:[function(require,module,exports){ +(function(self) { + 'use strict'; + + if (self.fetch) { + return + } + + var support = { + searchParams: 'URLSearchParams' in self, + iterable: 'Symbol' in self && 'iterator' in Symbol, + blob: 'FileReader' in self && 'Blob' in self && (function() { + try { + new Blob() + return true + } catch(e) { + return false + } + })(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + } + + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name) + } + if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name') + } + return name.toLowerCase() + } + + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value) + } + return value + } + + // Build a destructive iterator for the value list + function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift() + return {done: value === undefined, value: value} + } + } + + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator + } + } + + return iterator + } + + function Headers(headers) { + this.map = {} + + if (headers instanceof Headers) { + headers.forEach(function(value, name) { + this.append(name, value) + }, this) + + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]) + }, this) + } + } + + Headers.prototype.append = function(name, value) { + name = normalizeName(name) + value = normalizeValue(value) + var list = this.map[name] + if (!list) { + list = [] + this.map[name] = list + } + list.push(value) + } + + Headers.prototype['delete'] = function(name) { + delete this.map[normalizeName(name)] + } + + Headers.prototype.get = function(name) { + var values = this.map[normalizeName(name)] + return values ? values[0] : null + } + + Headers.prototype.getAll = function(name) { + return this.map[normalizeName(name)] || [] + } + + Headers.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)) + } + + Headers.prototype.set = function(name, value) { + this.map[normalizeName(name)] = [normalizeValue(value)] + } + + Headers.prototype.forEach = function(callback, thisArg) { + Object.getOwnPropertyNames(this.map).forEach(function(name) { + this.map[name].forEach(function(value) { + callback.call(thisArg, value, name, this) + }, this) + }, this) + } + + Headers.prototype.keys = function() { + var items = [] + this.forEach(function(value, name) { items.push(name) }) + return iteratorFor(items) + } + + Headers.prototype.values = function() { + var items = [] + this.forEach(function(value) { items.push(value) }) + return iteratorFor(items) + } + + Headers.prototype.entries = function() { + var items = [] + this.forEach(function(value, name) { items.push([name, value]) }) + return iteratorFor(items) + } + + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries + } + + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')) + } + body.bodyUsed = true + } + + function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result) + } + reader.onerror = function() { + reject(reader.error) + } + }) + } + + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader() + reader.readAsArrayBuffer(blob) + return fileReaderReady(reader) + } + + function readBlobAsText(blob) { + var reader = new FileReader() + reader.readAsText(blob) + return fileReaderReady(reader) + } + + function Body() { + this.bodyUsed = false + + this._initBody = function(body) { + this._bodyInit = body + if (typeof body === 'string') { + this._bodyText = body + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString() + } else if (!body) { + this._bodyText = '' + } else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) { + // Only support ArrayBuffers for POST method. + // Receiving ArrayBuffers happens via Blobs, instead. + } else { + throw new Error('unsupported BodyInit type') + } + + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8') + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type) + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8') + } + } + } + + if (support.blob) { + this.blob = function() { + var rejected = consumed(this) + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + } + + this.arrayBuffer = function() { + return this.blob().then(readBlobAsArrayBuffer) + } + + this.text = function() { + var rejected = consumed(this) + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + return Promise.resolve(this._bodyText) + } + } + } else { + this.text = function() { + var rejected = consumed(this) + return rejected ? rejected : Promise.resolve(this._bodyText) + } + } + + if (support.formData) { + this.formData = function() { + return this.text().then(decode) + } + } + + this.json = function() { + return this.text().then(JSON.parse) + } + + return this + } + + // HTTP methods whose capitalization should be normalized + var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] + + function normalizeMethod(method) { + var upcased = method.toUpperCase() + return (methods.indexOf(upcased) > -1) ? upcased : method + } + + function Request(input, options) { + options = options || {} + var body = options.body + if (Request.prototype.isPrototypeOf(input)) { + if (input.bodyUsed) { + throw new TypeError('Already read') + } + this.url = input.url + this.credentials = input.credentials + if (!options.headers) { + this.headers = new Headers(input.headers) + } + this.method = input.method + this.mode = input.mode + if (!body) { + body = input._bodyInit + input.bodyUsed = true + } + } else { + this.url = input + } + + this.credentials = options.credentials || this.credentials || 'omit' + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers) + } + this.method = normalizeMethod(options.method || this.method || 'GET') + this.mode = options.mode || this.mode || null + this.referrer = null + + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests') + } + this._initBody(body) + } + + Request.prototype.clone = function() { + return new Request(this) + } + + function decode(body) { + var form = new FormData() + body.trim().split('&').forEach(function(bytes) { + if (bytes) { + var split = bytes.split('=') + var name = split.shift().replace(/\+/g, ' ') + var value = split.join('=').replace(/\+/g, ' ') + form.append(decodeURIComponent(name), decodeURIComponent(value)) + } + }) + return form + } + + function headers(xhr) { + var head = new Headers() + var pairs = (xhr.getAllResponseHeaders() || '').trim().split('\n') + pairs.forEach(function(header) { + var split = header.trim().split(':') + var key = split.shift().trim() + var value = split.join(':').trim() + head.append(key, value) + }) + return head + } + + Body.call(Request.prototype) + + function Response(bodyInit, options) { + if (!options) { + options = {} + } + + this.type = 'default' + this.status = options.status + this.ok = this.status >= 200 && this.status < 300 + this.statusText = options.statusText + this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers) + this.url = options.url || '' + this._initBody(bodyInit) + } + + Body.call(Response.prototype) + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }) + } + + Response.error = function() { + var response = new Response(null, {status: 0, statusText: ''}) + response.type = 'error' + return response + } + + var redirectStatuses = [301, 302, 303, 307, 308] + + Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError('Invalid status code') + } + + return new Response(null, {status: status, headers: {location: url}}) + } + + self.Headers = Headers + self.Request = Request + self.Response = Response + + self.fetch = function(input, init) { + return new Promise(function(resolve, reject) { + var request + if (Request.prototype.isPrototypeOf(input) && !init) { + request = input + } else { + request = new Request(input, init) + } + + var xhr = new XMLHttpRequest() + + function responseURL() { + if ('responseURL' in xhr) { + return xhr.responseURL + } + + // Avoid security warnings on getResponseHeader when not allowed by CORS + if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) { + return xhr.getResponseHeader('X-Request-URL') + } + + return + } + + xhr.onload = function() { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: headers(xhr), + url: responseURL() + } + var body = 'response' in xhr ? xhr.response : xhr.responseText + resolve(new Response(body, options)) + } + + xhr.onerror = function() { + reject(new TypeError('Network request failed')) + } + + xhr.ontimeout = function() { + reject(new TypeError('Network request failed')) + } + + xhr.open(request.method, request.url, true) + + if (request.credentials === 'include') { + xhr.withCredentials = true + } + + if ('responseType' in xhr && support.blob) { + xhr.responseType = 'blob' + } + + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value) + }) + + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) + }) + } + self.fetch.polyfill = true +})(typeof self !== 'undefined' ? self : this); + +},{}],86:[function(require,module,exports){ +"use strict"; +var chai_1 = require('chai'); +var Swagger = require('typescript-fetch-api'); +describe('PetApi', function () { + var api; + var fixture = createTestFixture(); + beforeEach(function () { + api = new Swagger.PetApi(); + }); + it('should add and delete Pet', function () { + return api.addPet({ body: fixture }).then(function () { + }); + }); + it('should get Pet by ID', function () { + return api.getPetById({ petId: fixture.id }).then(function (result) { + return chai_1.expect(result).to.deep.equal(fixture); + }); + }); + it('should update Pet by ID', function () { + return api.getPetById({ petId: fixture.id }).then(function (result) { + result.name = 'newname'; + return api.updatePet({ body: result }).then(function () { + return api.getPetById({ petId: fixture.id }).then(function (result) { + return chai_1.expect(result.name).to.deep.equal('newname'); + }); + }); + }); + }); + it('should delete Pet', function () { + return api.deletePet({ petId: fixture.id }); + }); + it('should not contain deleted Pet', function () { + return api.getPetById({ petId: fixture.id }).then(function (result) { + return chai_1.expect(result).to.not.exist; + }, function (err) { + console.log(err); + return chai_1.expect(err).to.exist; + }); + }); +}); +function createTestFixture(ts) { + if (ts === void 0) { ts = Date.now(); } + var category = { + 'id': ts, + 'name': "category" + ts, + }; + var pet = { + 'id': ts, + 'name': "pet" + ts, + 'category': category, + 'photoUrls': ['http://foo.bar.com/1', 'http://foo.bar.com/2'], + 'status': 'available', + 'tags': [] + }; + return pet; +} +; + +},{"chai":12,"typescript-fetch-api":84}],87:[function(require,module,exports){ +"use strict"; +var chai_1 = require('chai'); +var Swagger = require('typescript-fetch-api'); +describe('StoreApi', function () { + var api; + beforeEach(function () { + api = new Swagger.StoreApi(); + }); + it('should get inventory', function () { + return api.getInventory().then(function (result) { + chai_1.expect(Object.keys(result)).to.not.be.empty; + }); + }); +}); + +},{"chai":12,"typescript-fetch-api":84}],88:[function(require,module,exports){ +"use strict"; +require('./PetApi'); +require('./StoreApi'); + +},{"./PetApi":86,"./StoreApi":87}]},{},[88]); diff --git a/samples/client/petstore/typescript-fetch/tests/default/package.json b/samples/client/petstore/typescript-fetch/tests/default/package.json new file mode 100644 index 00000000000..7653b45f9a1 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/package.json @@ -0,0 +1,26 @@ +{ + "private": true, + "dependencies": { + "chai": "^3.5.0" + }, + "devDependencies": { + "browserify": "^13.0.1", + "ts-loader": "^0.8.2", + "tsify": "^0.15.5", + "typescript": "^1.8.10", + "typings": "^0.8.1", + "webpack": "^1.13.0" + }, + "scripts": { + "prepublish": "./scripts/prepublish.sh", + "test": "mocha" + }, + "name": "typescript-fetch-test", + "version": "1.0.0", + "directories": { + "test": "test" + }, + "author": "", + "license": "ISC", + "description": "" +} diff --git a/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html new file mode 100644 index 00000000000..5d378bac582 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html @@ -0,0 +1,26 @@ + + + + Mocha Tests + + + +
+ + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html new file mode 100644 index 00000000000..625c8859422 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html @@ -0,0 +1,27 @@ + + + + Mocha Tests + + + +
+ + + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh b/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh new file mode 100755 index 00000000000..3c0dfb05953 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +npm install ../../builds/default +typings install + +# Build Node.js +tsc + +# Build Webpack +webpack + +# Build browserify +browserify test -p [ tsify ] > ./dist/test.browserify-bundle.js diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts new file mode 100644 index 00000000000..7ada1ecadc6 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts @@ -0,0 +1,65 @@ +import {expect} from 'chai'; +import * as Swagger from 'typescript-fetch-api'; + +describe('PetApi', () => { + let api: Swagger.PetApi; + + let fixture: Swagger.Pet = createTestFixture(); + + beforeEach(() => { + api = new Swagger.PetApi(); + }); + + it('should add and delete Pet', () => { + return api.addPet({ body: fixture }).then(() => { + }); + }); + + it('should get Pet by ID', () => { + return api.getPetById({ petId: fixture.id }).then((result) => { + return expect(result).to.deep.equal(fixture); + }); + }); + + it('should update Pet by ID', () => { + return api.getPetById({ petId: fixture.id }).then( (result) => { + result.name = 'newname'; + return api.updatePet({ body: result }).then(() => { + return api.getPetById({ petId: fixture.id }).then( (result) => { + return expect(result.name).to.deep.equal('newname'); + }); + }); + }); + }); + + it('should delete Pet', () => { + return api.deletePet({ petId: fixture.id }); + }); + + it('should not contain deleted Pet', () => { + return api.getPetById({ petId: fixture.id }).then((result) => { + return expect(result).to.not.exist; + }, (err) => { + console.log(err) + return expect(err).to.exist; + }); + }); +}); + +function createTestFixture(ts = Date.now()) { + const category: Swagger.Category = { + 'id': ts, + 'name': `category${ts}`, + }; + + const pet: Swagger.Pet = { + 'id': ts, + 'name': `pet${ts}`, + 'category': category, + 'photoUrls': ['http://foo.bar.com/1', 'http://foo.bar.com/2'], + 'status': 'available', + 'tags': [] + }; + + return pet; +}; diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts new file mode 100644 index 00000000000..e993766522d --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts @@ -0,0 +1,18 @@ +import {expect} from 'chai'; +import * as Swagger from 'typescript-fetch-api'; + +describe('StoreApi', function() { + let api: Swagger.StoreApi; + + beforeEach(function() { + api = new Swagger.StoreApi(); + }); + + it('should get inventory', function() { + return api.getInventory().then((result) => { + expect(Object.keys(result)).to.not.be.empty; + }); + }); + +}); + diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/index.ts b/samples/client/petstore/typescript-fetch/tests/default/test/index.ts new file mode 100644 index 00000000000..29369a2d0e2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/index.ts @@ -0,0 +1,2 @@ +import './PetApi'; +import './StoreApi'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts b/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts new file mode 100644 index 00000000000..12ea969970a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts @@ -0,0 +1 @@ +--timeout 10000 dist/test diff --git a/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json b/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json new file mode 100644 index 00000000000..e47c2647e01 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "noImplicitAny": true, + "sourceMap": false, + "outDir": "dist", + "rootDir": "." + }, + "exclude": [ + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/typings.json b/samples/client/petstore/typescript-fetch/tests/default/typings.json new file mode 100644 index 00000000000..e792f9ecd7e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/typings.json @@ -0,0 +1,9 @@ +{ + "name": "typescript-fetch-test", + "version": false, + "ambientDependencies": { + "chai": "registry:dt/chai#3.4.0+20160317120654", + "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "mocha": "registry:dt/mocha#2.2.5+20160317120654" + } +} diff --git a/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js b/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js new file mode 100644 index 00000000000..d3332281c5c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js @@ -0,0 +1,30 @@ +const webpack = require('webpack'); + +module.exports = { + entry: { + app: './test/index.ts', + vendor: [ + // libraries + 'typescript-fetch-api' + ], + }, + output: { + filename: './dist/test.webpack-bundle.js' + }, + plugins: [ + new webpack.optimize.CommonsChunkPlugin(/* chunkName= */'vendor', /* filename= */'./dist/vendor.webpack-bundle.js') + ], + resolve: { + // Add `.ts` and `.tsx` as a resolvable extension. + extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js'] + }, + module: { + loaders: [ + // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader` + { + test: /\.tsx?$/, + loader: 'ts-loader' + } + ] + } +}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tsconfig.json b/samples/client/petstore/typescript-fetch/tsconfig.json deleted file mode 100644 index fc93dc1610e..00000000000 --- a/samples/client/petstore/typescript-fetch/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "compilerOptions": { - "target": "es5" - }, - "exclude": [ - "node_modules", - "typings/browser", - "typings/main", - "typings/main.d.ts" - ] -} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/typings.json b/samples/client/petstore/typescript-fetch/typings.json deleted file mode 100644 index c22f086f7f0..00000000000 --- a/samples/client/petstore/typescript-fetch/typings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "version": false, - "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", - "node": "registry:dt/node#4.0.0+20160423143914", - "isomorphic-fetch": "github:leonyu/DefinitelyTyped/isomorphic-fetch/isomorphic-fetch.d.ts#isomorphic-fetch-fix-module" - } -} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/README.md b/samples/client/petstore/typescript-fetch/with-package-metadata/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts b/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - -export namespace Order { - -export type StatusEnum = 'placed' | 'approved' | 'delivered'; -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - -export namespace Pet { - -export type StatusEnum = 'available' | 'pending' | 'sold'; -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts b/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh b/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh deleted file mode 100644 index ed374619b13..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." - git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - From 610af207121b23a3f556460eb8b3ba96d288c47a Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 13 May 2016 16:40:01 +0800 Subject: [PATCH 30/53] update swift sample --- .../Classes/Swaggers/APIs/PetAPI.swift | 106 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 64 +++++------ .../Classes/Swaggers/APIs/UserAPI.swift | 40 +++---- .../Classes/Swaggers/Models.swift | 4 +- 4 files changed, 107 insertions(+), 107 deletions(-) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 019be89261f..64aa3c8803c 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -155,13 +155,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{contentType=application/json, example={ + - examples: [{example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}}] +}, contentType=application/json}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -218,20 +218,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{contentType=application/json, example=[ { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -} ]}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= 123456 doggie @@ -240,21 +240,21 @@ public class PetAPI: APIBase { string -}] - - examples: [{contentType=application/json, example=[ { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", +, contentType=application/xml}] + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -} ]}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= 123456 doggie @@ -263,7 +263,7 @@ public class PetAPI: APIBase { string -}] +, contentType=application/xml}] - parameter tags: (query) Tags to filter by (optional) @@ -317,26 +317,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - OAuth: - - type: oauth2 - - name: petstore_auth - API Key: - type: apiKey api_key - name: api_key - - examples: [{contentType=application/json, example={ - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= 123456 doggie @@ -345,21 +345,21 @@ public class PetAPI: APIBase { string -}] - - examples: [{contentType=application/json, example={ - "photoUrls" : [ "aeiou" ], - "name" : "doggie", +, contentType=application/xml}] + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= 123456 doggie @@ -368,7 +368,7 @@ public class PetAPI: APIBase { string -}] +, contentType=application/xml}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 5be63ad74d0..4521afd3d89 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -98,12 +98,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{contentType=application/json, example={ + - examples: [{example={ "key" : 123 -}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - - examples: [{contentType=application/json, example={ +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] + - examples: [{example={ "key" : 123 -}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - returns: RequestBuilder<[String:Int32]> */ @@ -153,36 +153,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+0000", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+0000" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+0000", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+0000" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] +, contentType=application/xml}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -235,36 +235,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+0000", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+0000" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+0000", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+0000" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] +, contentType=application/xml}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 9e527b4f5f3..62018cd83c2 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -244,16 +244,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{contentType=application/json, example={ - "firstName" : "aeiou", - "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, - "phone" : "aeiou", + - examples: [{example={ "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "username" : "aeiou", "email" : "aeiou", - "username" : "aeiou" -}}, {contentType=application/xml, example= + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}, contentType=application/json}, {example= 123456 string string @@ -262,17 +262,17 @@ public class UserAPI: APIBase { string string 0 -}] - - examples: [{contentType=application/json, example={ - "firstName" : "aeiou", - "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, - "phone" : "aeiou", +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "username" : "aeiou", "email" : "aeiou", - "username" : "aeiou" -}}, {contentType=application/xml, example= + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}, contentType=application/json}, {example= 123456 string string @@ -281,7 +281,7 @@ public class UserAPI: APIBase { string string 0 -}] +, contentType=application/xml}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -336,8 +336,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift index f9e2f72b908..5a8eade51b3 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift @@ -46,9 +46,9 @@ class Decoders { } static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { - let sourceDictinoary = source as! [Key: AnyObject] + let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() - for (key, value) in sourceDictinoary { + for (key, value) in sourceDictionary { dictionary[key] = Decoders.decode(clazz: T.self, source: value) } return dictionary From e31c71f68543b9634551d01f213ddd701e9674db Mon Sep 17 00:00:00 2001 From: Kim Sondrup Date: Fri, 13 May 2016 10:54:29 +0200 Subject: [PATCH 31/53] [PHP] list_invalid_properties now don't call undefined variables --- .../src/main/resources/php/model.mustache | 14 ++++---- .../SwaggerClient-php/lib/Model/Animal.php | 2 +- .../SwaggerClient-php/lib/Model/EnumTest.php | 6 ++-- .../lib/Model/FormatTest.php | 34 +++++++++---------- .../php/SwaggerClient-php/lib/Model/Name.php | 2 +- .../php/SwaggerClient-php/lib/Model/Order.php | 2 +- .../php/SwaggerClient-php/lib/Model/Pet.php | 6 ++-- 7 files changed, 33 insertions(+), 33 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 6dbf2544a17..d19ae545402 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -161,39 +161,39 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{#vars}} {{#required}} if ($this->container['{{name}}'] === null) { - $invalid_properties[] = "'${{name}}' can't be null"; + $invalid_properties[] = "'{{name}}' can't be null"; } {{/required}} {{#isEnum}} $allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); if (!in_array($this->container['{{name}}'], $allowed_values)) { - $invalid_properties[] = "invalid value for '${{name}}', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for '{{name}}', must be one of #{allowed_values}."; } {{/isEnum}} {{#hasValidation}} {{#maxLength}} if (strlen($this->container['{{name}}']) > {{maxLength}}) { - $invalid_properties[] = "invalid value for '${{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; + $invalid_properties[] = "invalid value for '{{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; } {{/maxLength}} {{#minLength}} if (strlen($this->container['{{name}}']) < {{minLength}}) { - $invalid_properties[] = "invalid value for '${{name}}', the character length must be bigger than or equal to {{{minLength}}}."; + $invalid_properties[] = "invalid value for '{{name}}', the character length must be bigger than or equal to {{{minLength}}}."; } {{/minLength}} {{#maximum}} if ($this->container['{{name}}'] > {{maximum}}) { - $invalid_properties[] = "invalid value for '${{name}}', must be smaller than or equal to {{maximum}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be smaller than or equal to {{maximum}}."; } {{/maximum}} {{#minimum}} if ($this->container['{{name}}'] < {{minimum}}) { - $invalid_properties[] = "invalid value for '${{name}}', must be bigger than or equal to {{minimum}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be bigger than or equal to {{minimum}}."; } {{/minimum}} {{#pattern}} if (!preg_match("{{pattern}}", $this->container['{{name}}'])) { - $invalid_properties[] = "invalid value for '${{name}}', must be conform to the pattern {{pattern}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be conform to the pattern {{pattern}}."; } {{/pattern}} {{/hasValidation}} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 9120535bf5a..d79d3c92ab9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -138,7 +138,7 @@ class Animal implements ArrayAccess { $invalid_properties = array(); if ($this->container['class_name'] === null) { - $invalid_properties[] = "'$class_name' can't be null"; + $invalid_properties[] = "'class_name' can't be null"; } return $invalid_properties; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index 6e10f45dd8f..015297084e9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -179,15 +179,15 @@ class EnumTest implements ArrayAccess $invalid_properties = array(); $allowed_values = array("UPPER", "lower"); if (!in_array($this->container['enum_string'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_string', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_string', must be one of #{allowed_values}."; } $allowed_values = array("1", "-1"); if (!in_array($this->container['enum_integer'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_integer', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_integer', must be one of #{allowed_values}."; } $allowed_values = array("1.1", "-1.2"); if (!in_array($this->container['enum_number'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_number', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_number', must be one of #{allowed_values}."; } return $invalid_properties; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index bf674b05102..3f05fe276ea 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -189,55 +189,55 @@ class FormatTest implements ArrayAccess { $invalid_properties = array(); if ($this->container['integer'] > 100.0) { - $invalid_properties[] = "invalid value for '$integer', must be smaller than or equal to 100.0."; + $invalid_properties[] = "invalid value for 'integer', must be smaller than or equal to 100.0."; } if ($this->container['integer'] < 10.0) { - $invalid_properties[] = "invalid value for '$integer', must be bigger than or equal to 10.0."; + $invalid_properties[] = "invalid value for 'integer', must be bigger than or equal to 10.0."; } if ($this->container['int32'] > 200.0) { - $invalid_properties[] = "invalid value for '$int32', must be smaller than or equal to 200.0."; + $invalid_properties[] = "invalid value for 'int32', must be smaller than or equal to 200.0."; } if ($this->container['int32'] < 20.0) { - $invalid_properties[] = "invalid value for '$int32', must be bigger than or equal to 20.0."; + $invalid_properties[] = "invalid value for 'int32', must be bigger than or equal to 20.0."; } if ($this->container['number'] === null) { - $invalid_properties[] = "'$number' can't be null"; + $invalid_properties[] = "'number' can't be null"; } if ($this->container['number'] > 543.2) { - $invalid_properties[] = "invalid value for '$number', must be smaller than or equal to 543.2."; + $invalid_properties[] = "invalid value for 'number', must be smaller than or equal to 543.2."; } if ($this->container['number'] < 32.1) { - $invalid_properties[] = "invalid value for '$number', must be bigger than or equal to 32.1."; + $invalid_properties[] = "invalid value for 'number', must be bigger than or equal to 32.1."; } if ($this->container['float'] > 987.6) { - $invalid_properties[] = "invalid value for '$float', must be smaller than or equal to 987.6."; + $invalid_properties[] = "invalid value for 'float', must be smaller than or equal to 987.6."; } if ($this->container['float'] < 54.3) { - $invalid_properties[] = "invalid value for '$float', must be bigger than or equal to 54.3."; + $invalid_properties[] = "invalid value for 'float', must be bigger than or equal to 54.3."; } if ($this->container['double'] > 123.4) { - $invalid_properties[] = "invalid value for '$double', must be smaller than or equal to 123.4."; + $invalid_properties[] = "invalid value for 'double', must be smaller than or equal to 123.4."; } if ($this->container['double'] < 67.8) { - $invalid_properties[] = "invalid value for '$double', must be bigger than or equal to 67.8."; + $invalid_properties[] = "invalid value for 'double', must be bigger than or equal to 67.8."; } if (!preg_match("/[a-z]/i", $this->container['string'])) { - $invalid_properties[] = "invalid value for '$string', must be conform to the pattern /[a-z]/i."; + $invalid_properties[] = "invalid value for 'string', must be conform to the pattern /[a-z]/i."; } if ($this->container['byte'] === null) { - $invalid_properties[] = "'$byte' can't be null"; + $invalid_properties[] = "'byte' can't be null"; } if ($this->container['date'] === null) { - $invalid_properties[] = "'$date' can't be null"; + $invalid_properties[] = "'date' can't be null"; } if ($this->container['password'] === null) { - $invalid_properties[] = "'$password' can't be null"; + $invalid_properties[] = "'password' can't be null"; } if (strlen($this->container['password']) > 64) { - $invalid_properties[] = "invalid value for '$password', the character length must be smaller than or equal to 64."; + $invalid_properties[] = "invalid value for 'password', the character length must be smaller than or equal to 64."; } if (strlen($this->container['password']) < 10) { - $invalid_properties[] = "invalid value for '$password', the character length must be bigger than or equal to 10."; + $invalid_properties[] = "invalid value for 'password', the character length must be bigger than or equal to 10."; } return $invalid_properties; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index b77f3d78d0c..e377c39ffe9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -144,7 +144,7 @@ class Name implements ArrayAccess { $invalid_properties = array(); if ($this->container['name'] === null) { - $invalid_properties[] = "'$name' can't be null"; + $invalid_properties[] = "'name' can't be null"; } return $invalid_properties; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 88779ed8c73..d681a74d2ca 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -170,7 +170,7 @@ class Order implements ArrayAccess $invalid_properties = array(); $allowed_values = array("placed", "approved", "delivered"); if (!in_array($this->container['status'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$status', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; } return $invalid_properties; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 5a65e432538..6855bb38048 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -169,14 +169,14 @@ class Pet implements ArrayAccess { $invalid_properties = array(); if ($this->container['name'] === null) { - $invalid_properties[] = "'$name' can't be null"; + $invalid_properties[] = "'name' can't be null"; } if ($this->container['photo_urls'] === null) { - $invalid_properties[] = "'$photo_urls' can't be null"; + $invalid_properties[] = "'photo_urls' can't be null"; } $allowed_values = array("available", "pending", "sold"); if (!in_array($this->container['status'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$status', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; } return $invalid_properties; } From 7737a597052d2907901cdba4497839905b538115 Mon Sep 17 00:00:00 2001 From: Kim Sondrup Date: Fri, 13 May 2016 11:01:10 +0200 Subject: [PATCH 32/53] Run ./bin/php-petstore.sh --- .../php/SwaggerClient-php/docs/Animal.md | 11 +++ .../php/SwaggerClient-php/docs/AnimalFarm.md | 9 +++ .../php/SwaggerClient-php/docs/ApiResponse.md | 12 +++ .../php/SwaggerClient-php/docs/Cat.md | 10 +++ .../php/SwaggerClient-php/docs/Category.md | 11 +++ .../php/SwaggerClient-php/docs/Dog.md | 10 +++ .../php/SwaggerClient-php/docs/EnumClass.md | 9 +++ .../php/SwaggerClient-php/docs/EnumTest.md | 12 +++ .../php/SwaggerClient-php/docs/FormatTest.md | 22 ++++++ .../docs/Model200Response.md | 10 +++ .../php/SwaggerClient-php/docs/ModelReturn.md | 10 +++ .../php/SwaggerClient-php/docs/Name.md | 13 ++++ .../php/SwaggerClient-php/docs/Order.md | 15 ++++ .../php/SwaggerClient-php/docs/Pet.md | 15 ++++ .../docs/SpecialModelName.md | 10 +++ .../php/SwaggerClient-php/docs/Tag.md | 11 +++ .../php/SwaggerClient-php/docs/User.md | 17 +++++ .../SwaggerClient-php/lib/Model/Animal.php | 31 ++++---- .../lib/Model/AnimalFarm.php | 31 ++++---- .../lib/Model/ApiResponse.php | 31 ++++---- .../php/SwaggerClient-php/lib/Model/Cat.php | 31 ++++---- .../SwaggerClient-php/lib/Model/Category.php | 31 ++++---- .../php/SwaggerClient-php/lib/Model/Dog.php | 31 ++++---- .../SwaggerClient-php/lib/Model/EnumClass.php | 31 ++++---- .../SwaggerClient-php/lib/Model/EnumTest.php | 55 +++++++------- .../lib/Model/FormatTest.php | 37 +++++----- .../lib/Model/Model200Response.php | 31 ++++---- .../lib/Model/ModelReturn.php | 31 ++++---- .../php/SwaggerClient-php/lib/Model/Name.php | 31 ++++---- .../php/SwaggerClient-php/lib/Model/Order.php | 41 +++++------ .../php/SwaggerClient-php/lib/Model/Pet.php | 41 +++++------ .../lib/Model/SpecialModelName.php | 31 ++++---- .../php/SwaggerClient-php/lib/Model/Tag.php | 31 ++++---- .../php/SwaggerClient-php/lib/Model/User.php | 31 ++++---- .../lib/Tests/AnimalFarmTest.php | 73 +++++++++++++++++++ .../lib/Tests/AnimalTest.php | 73 +++++++++++++++++++ .../lib/Tests/ApiResponseTest.php | 73 +++++++++++++++++++ .../SwaggerClient-php/lib/Tests/CatTest.php | 73 +++++++++++++++++++ .../lib/Tests/CategoryTest.php | 73 +++++++++++++++++++ .../SwaggerClient-php/lib/Tests/DogTest.php | 73 +++++++++++++++++++ .../lib/Tests/EnumClassTest.php | 73 +++++++++++++++++++ .../lib/Tests/EnumTestTest.php | 73 +++++++++++++++++++ .../lib/Tests/FormatTestTest.php | 73 +++++++++++++++++++ .../lib/Tests/Model200ResponseTest.php | 73 +++++++++++++++++++ .../lib/Tests/ModelReturnTest.php | 73 +++++++++++++++++++ .../SwaggerClient-php/lib/Tests/NameTest.php | 73 +++++++++++++++++++ .../SwaggerClient-php/lib/Tests/OrderTest.php | 73 +++++++++++++++++++ .../SwaggerClient-php/lib/Tests/PetTest.php | 73 +++++++++++++++++++ .../lib/Tests/SpecialModelNameTest.php | 73 +++++++++++++++++++ .../SwaggerClient-php/lib/Tests/TagTest.php | 73 +++++++++++++++++++ .../SwaggerClient-php/lib/Tests/UserTest.php | 73 +++++++++++++++++++ 51 files changed, 1738 insertions(+), 287 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Animal.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/AnimalFarm.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Cat.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Category.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Dog.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Name.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Order.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Pet.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Tag.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/User.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalFarmTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/ApiResponseTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/CatTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/CategoryTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/DogTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumClassTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumTestTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/FormatTestTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/Model200ResponseTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/ModelReturnTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/NameTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/OrderTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/PetTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/SpecialModelNameTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/TagTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/UserTest.php diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Animal.md b/samples/client/petstore/php/SwaggerClient-php/docs/Animal.md new file mode 100644 index 00000000000..c57fbe8ea4a --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **string** | | +**color** | **string** | | [optional] [default to 'red'] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/AnimalFarm.md b/samples/client/petstore/php/SwaggerClient-php/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md b/samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md new file mode 100644 index 00000000000..9d351183422 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | [optional] +**type** | **string** | | [optional] +**message** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md b/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md new file mode 100644 index 00000000000..8d30565d014 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md @@ -0,0 +1,10 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Category.md b/samples/client/petstore/php/SwaggerClient-php/docs/Category.md new file mode 100644 index 00000000000..80aef312e5e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md b/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md new file mode 100644 index 00000000000..3c04bdf4cf7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md @@ -0,0 +1,10 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md b/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md new file mode 100644 index 00000000000..2ef9e6adaac --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **string** | | [optional] +**enum_integer** | **int** | | [optional] +**enum_number** | **double** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md new file mode 100644 index 00000000000..90531d28c40 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **int** | | [optional] +**int32** | **int** | | [optional] +**int64** | **int** | | [optional] +**number** | **float** | | +**float** | **float** | | [optional] +**double** | **double** | | [optional] +**string** | **string** | | [optional] +**byte** | **string** | | +**binary** | **string** | | [optional] +**date** | [**\DateTime**](Date.md) | | +**date_time** | [**\DateTime**](\DateTime.md) | | [optional] +**uuid** | [**UUID**](UUID.md) | | [optional] +**password** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md new file mode 100644 index 00000000000..e29747a87e7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md @@ -0,0 +1,10 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md b/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md new file mode 100644 index 00000000000..9adb62e1e12 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**return** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Name.md b/samples/client/petstore/php/SwaggerClient-php/docs/Name.md new file mode 100644 index 00000000000..4565647e1ef --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | +**snake_case** | **int** | | [optional] +**property** | **string** | | [optional] +**_123_number** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Order.md b/samples/client/petstore/php/SwaggerClient-php/docs/Order.md new file mode 100644 index 00000000000..ddae5cc2b57 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**pet_id** | **int** | | [optional] +**quantity** | **int** | | [optional] +**ship_date** | [**\DateTime**](\DateTime.md) | | [optional] +**status** | **string** | Order Status | [optional] +**complete** | **bool** | | [optional] [default to false] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md b/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md new file mode 100644 index 00000000000..4525fe7d776 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**category** | [**\Swagger\Client\Model\Category**](Category.md) | | [optional] +**name** | **string** | | +**photo_urls** | **string[]** | | +**tags** | [**\Swagger\Client\Model\Tag[]**](Tag.md) | | [optional] +**status** | **string** | pet status in the store | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md b/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md new file mode 100644 index 00000000000..022ee19169c --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**special_property_name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md b/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md new file mode 100644 index 00000000000..15ec3e0a91d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/User.md b/samples/client/petstore/php/SwaggerClient-php/docs/User.md new file mode 100644 index 00000000000..ff278fd4889 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**username** | **string** | | [optional] +**first_name** | **string** | | [optional] +**last_name** | **string** | | [optional] +**email** | **string** | | [optional] +**password** | **string** | | [optional] +**phone** | **string** | | [optional] +**user_status** | **int** | User Status | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 9120535bf5a..bac082da5e7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -54,7 +54,7 @@ class Animal implements ArrayAccess static $swaggerModelName = 'Animal'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -66,7 +66,7 @@ class Animal implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -100,8 +100,9 @@ class Animal implements ArrayAccess 'class_name' => 'getClassName', 'color' => 'getColor' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -131,7 +132,7 @@ class Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -146,8 +147,8 @@ class Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -201,7 +202,7 @@ class Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -211,17 +212,17 @@ class Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -233,17 +234,17 @@ class Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index 2ff9da6a4ea..1bf893935db 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -54,7 +54,7 @@ class AnimalFarm implements ArrayAccess static $swaggerModelName = 'AnimalFarm'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -65,7 +65,7 @@ class AnimalFarm implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -96,8 +96,9 @@ class AnimalFarm implements ArrayAccess static $getters = array( ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -121,7 +122,7 @@ class AnimalFarm implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -133,8 +134,8 @@ class AnimalFarm implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -143,7 +144,7 @@ class AnimalFarm implements ArrayAccess /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -153,17 +154,17 @@ class AnimalFarm implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -175,17 +176,17 @@ class AnimalFarm implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index 8894f835aea..cd9d1debcad 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -54,7 +54,7 @@ class ApiResponse implements ArrayAccess static $swaggerModelName = 'ApiResponse'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -67,7 +67,7 @@ class ApiResponse implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -104,8 +104,9 @@ class ApiResponse implements ArrayAccess 'type' => 'getType', 'message' => 'getMessage' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -132,7 +133,7 @@ class ApiResponse implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -144,8 +145,8 @@ class ApiResponse implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -217,7 +218,7 @@ class ApiResponse implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -227,17 +228,17 @@ class ApiResponse implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -249,17 +250,17 @@ class ApiResponse implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 393f89e5b0f..8fbdd168922 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -54,7 +54,7 @@ class Cat extends Animal implements ArrayAccess static $swaggerModelName = 'Cat'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -65,7 +65,7 @@ class Cat extends Animal implements ArrayAccess return self::$swaggerTypes + parent::swaggerTypes(); } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -96,8 +96,9 @@ class Cat extends Animal implements ArrayAccess static $getters = array( 'declawed' => 'getDeclawed' ); - - static function getters() { + + static function getters() + { return parent::getters() + self::$getters; } @@ -124,7 +125,7 @@ class Cat extends Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -136,8 +137,8 @@ class Cat extends Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -167,7 +168,7 @@ class Cat extends Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -177,17 +178,17 @@ class Cat extends Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -199,17 +200,17 @@ class Cat extends Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 1c1a2340378..9687120c243 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -54,7 +54,7 @@ class Category implements ArrayAccess static $swaggerModelName = 'Category'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -66,7 +66,7 @@ class Category implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -100,8 +100,9 @@ class Category implements ArrayAccess 'id' => 'getId', 'name' => 'getName' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -127,7 +128,7 @@ class Category implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -139,8 +140,8 @@ class Category implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -191,7 +192,7 @@ class Category implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -201,17 +202,17 @@ class Category implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -223,17 +224,17 @@ class Category implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index b79e76a4187..54b271c9e7f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -54,7 +54,7 @@ class Dog extends Animal implements ArrayAccess static $swaggerModelName = 'Dog'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -65,7 +65,7 @@ class Dog extends Animal implements ArrayAccess return self::$swaggerTypes + parent::swaggerTypes(); } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -96,8 +96,9 @@ class Dog extends Animal implements ArrayAccess static $getters = array( 'breed' => 'getBreed' ); - - static function getters() { + + static function getters() + { return parent::getters() + self::$getters; } @@ -124,7 +125,7 @@ class Dog extends Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -136,8 +137,8 @@ class Dog extends Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -167,7 +168,7 @@ class Dog extends Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -177,17 +178,17 @@ class Dog extends Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -199,17 +200,17 @@ class Dog extends Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php index 2b6d36c9b66..e63691cc979 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -54,7 +54,7 @@ class EnumClass implements ArrayAccess static $swaggerModelName = 'EnumClass'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -65,7 +65,7 @@ class EnumClass implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -96,8 +96,9 @@ class EnumClass implements ArrayAccess static $getters = array( ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -121,7 +122,7 @@ class EnumClass implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -133,8 +134,8 @@ class EnumClass implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -143,7 +144,7 @@ class EnumClass implements ArrayAccess /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -153,17 +154,17 @@ class EnumClass implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -175,17 +176,17 @@ class EnumClass implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index 6e10f45dd8f..4353a951d5d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -54,7 +54,7 @@ class EnumTest implements ArrayAccess static $swaggerModelName = 'Enum_Test'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -67,7 +67,7 @@ class EnumTest implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -104,17 +104,12 @@ class EnumTest implements ArrayAccess 'enum_integer' => 'getEnumInteger', 'enum_number' => 'getEnumNumber' ); - - static function getters() { + + static function getters() + { return self::$getters; } - const ENUM_STRING_UPPER = 'UPPER'; - const ENUM_STRING_LOWER = 'lower'; - const ENUM_INTEGER_1 = 1; - const ENUM_INTEGER_MINUS_1 = -1; - const ENUM_NUMBER_1_DOT_1 = 1.1; - const ENUM_NUMBER_MINUS_1_DOT_2 = -1.2; @@ -122,10 +117,10 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumStringAllowableValues() { + public function getEnumStringAllowableValues() + { return [ - self::ENUM_STRING_UPPER, - self::ENUM_STRING_LOWER, + ]; } @@ -133,10 +128,10 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumIntegerAllowableValues() { + public function getEnumIntegerAllowableValues() + { return [ - self::ENUM_INTEGER_1, - self::ENUM_INTEGER_MINUS_1, + ]; } @@ -144,10 +139,10 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumNumberAllowableValues() { + public function getEnumNumberAllowableValues() + { return [ - self::ENUM_NUMBER_1_DOT_1, - self::ENUM_NUMBER_MINUS_1_DOT_2, + ]; } @@ -171,7 +166,7 @@ class EnumTest implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -195,8 +190,8 @@ class EnumTest implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -292,7 +287,7 @@ class EnumTest implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -302,17 +297,17 @@ class EnumTest implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -324,17 +319,17 @@ class EnumTest implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index bf674b05102..17b42e35a0d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -54,7 +54,7 @@ class FormatTest implements ArrayAccess static $swaggerModelName = 'format_test'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -69,7 +69,7 @@ class FormatTest implements ArrayAccess 'binary' => 'string', 'date' => '\DateTime', 'date_time' => '\DateTime', - 'uuid' => 'string', + 'uuid' => 'UUID', 'password' => 'string' ); @@ -77,7 +77,7 @@ class FormatTest implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -144,8 +144,9 @@ class FormatTest implements ArrayAccess 'uuid' => 'getUuid', 'password' => 'getPassword' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -182,7 +183,7 @@ class FormatTest implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -245,8 +246,8 @@ class FormatTest implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -577,7 +578,7 @@ class FormatTest implements ArrayAccess /** * Gets uuid - * @return string + * @return UUID */ public function getUuid() { @@ -586,7 +587,7 @@ class FormatTest implements ArrayAccess /** * Sets uuid - * @param string $uuid + * @param UUID $uuid * @return $this */ public function setUuid($uuid) @@ -624,7 +625,7 @@ class FormatTest implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -634,17 +635,17 @@ class FormatTest implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -656,17 +657,17 @@ class FormatTest implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 68eae680dc6..8422d0cf9e1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -54,7 +54,7 @@ class Model200Response implements ArrayAccess static $swaggerModelName = '200_response'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -65,7 +65,7 @@ class Model200Response implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -96,8 +96,9 @@ class Model200Response implements ArrayAccess static $getters = array( 'name' => 'getName' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -122,7 +123,7 @@ class Model200Response implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -134,8 +135,8 @@ class Model200Response implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -165,7 +166,7 @@ class Model200Response implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +176,17 @@ class Model200Response implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +198,17 @@ class Model200Response implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 7dce6f0029d..e2f619d1ac7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -54,7 +54,7 @@ class ModelReturn implements ArrayAccess static $swaggerModelName = 'Return'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -65,7 +65,7 @@ class ModelReturn implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -96,8 +96,9 @@ class ModelReturn implements ArrayAccess static $getters = array( 'return' => 'getReturn' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -122,7 +123,7 @@ class ModelReturn implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -134,8 +135,8 @@ class ModelReturn implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -165,7 +166,7 @@ class ModelReturn implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +176,17 @@ class ModelReturn implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +198,17 @@ class ModelReturn implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index b77f3d78d0c..c59b79494d2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -54,7 +54,7 @@ class Name implements ArrayAccess static $swaggerModelName = 'Name'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -68,7 +68,7 @@ class Name implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -108,8 +108,9 @@ class Name implements ArrayAccess 'property' => 'getProperty', '_123_number' => 'get123Number' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -137,7 +138,7 @@ class Name implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -152,8 +153,8 @@ class Name implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -249,7 +250,7 @@ class Name implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -259,17 +260,17 @@ class Name implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -281,17 +282,17 @@ class Name implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 88779ed8c73..a457f619e9f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -54,7 +54,7 @@ class Order implements ArrayAccess static $swaggerModelName = 'Order'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -70,7 +70,7 @@ class Order implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -116,14 +116,12 @@ class Order implements ArrayAccess 'status' => 'getStatus', 'complete' => 'getComplete' ); - - static function getters() { + + static function getters() + { return self::$getters; } - const STATUS_PLACED = 'placed'; - const STATUS_APPROVED = 'approved'; - const STATUS_DELIVERED = 'delivered'; @@ -131,11 +129,10 @@ class Order implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getStatusAllowableValues() { + public function getStatusAllowableValues() + { return [ - self::STATUS_PLACED, - self::STATUS_APPROVED, - self::STATUS_DELIVERED, + ]; } @@ -162,7 +159,7 @@ class Order implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -178,8 +175,8 @@ class Order implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -322,7 +319,7 @@ class Order implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -332,17 +329,17 @@ class Order implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -354,17 +351,17 @@ class Order implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 5a65e432538..ea8626540aa 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -54,7 +54,7 @@ class Pet implements ArrayAccess static $swaggerModelName = 'Pet'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -70,7 +70,7 @@ class Pet implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -116,14 +116,12 @@ class Pet implements ArrayAccess 'tags' => 'getTags', 'status' => 'getStatus' ); - - static function getters() { + + static function getters() + { return self::$getters; } - const STATUS_AVAILABLE = 'available'; - const STATUS_PENDING = 'pending'; - const STATUS_SOLD = 'sold'; @@ -131,11 +129,10 @@ class Pet implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getStatusAllowableValues() { + public function getStatusAllowableValues() + { return [ - self::STATUS_AVAILABLE, - self::STATUS_PENDING, - self::STATUS_SOLD, + ]; } @@ -162,7 +159,7 @@ class Pet implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -184,8 +181,8 @@ class Pet implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -334,7 +331,7 @@ class Pet implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -344,17 +341,17 @@ class Pet implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -366,17 +363,17 @@ class Pet implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index 25ebecd55a0..4439913a9bd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -54,7 +54,7 @@ class SpecialModelName implements ArrayAccess static $swaggerModelName = '$special[model.name]'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -65,7 +65,7 @@ class SpecialModelName implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -96,8 +96,9 @@ class SpecialModelName implements ArrayAccess static $getters = array( 'special_property_name' => 'getSpecialPropertyName' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -122,7 +123,7 @@ class SpecialModelName implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -134,8 +135,8 @@ class SpecialModelName implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -165,7 +166,7 @@ class SpecialModelName implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +176,17 @@ class SpecialModelName implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +198,17 @@ class SpecialModelName implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index a2132ca7e5c..03fb1257504 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -54,7 +54,7 @@ class Tag implements ArrayAccess static $swaggerModelName = 'Tag'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -66,7 +66,7 @@ class Tag implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -100,8 +100,9 @@ class Tag implements ArrayAccess 'id' => 'getId', 'name' => 'getName' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -127,7 +128,7 @@ class Tag implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -139,8 +140,8 @@ class Tag implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -191,7 +192,7 @@ class Tag implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -201,17 +202,17 @@ class Tag implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -223,17 +224,17 @@ class Tag implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index a97727f0a8f..6867437da47 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -54,7 +54,7 @@ class User implements ArrayAccess static $swaggerModelName = 'User'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( @@ -72,7 +72,7 @@ class User implements ArrayAccess return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -124,8 +124,9 @@ class User implements ArrayAccess 'phone' => 'getPhone', 'user_status' => 'getUserStatus' ); - - static function getters() { + + static function getters() + { return self::$getters; } @@ -157,7 +158,7 @@ class User implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ public function list_invalid_properties() @@ -169,8 +170,8 @@ class User implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -347,7 +348,7 @@ class User implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -357,17 +358,17 @@ class User implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -379,17 +380,17 @@ class User implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalFarmTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalFarmTest.php new file mode 100644 index 00000000000..61797bfd16c --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalFarmTest.php @@ -0,0 +1,73 @@ + Date: Fri, 13 May 2016 22:17:16 +0800 Subject: [PATCH 33/53] update csharp petstore sample --- .../csharp/SwaggerClient/IO.Swagger.sln | 19 ++++++------------- .../petstore/csharp/SwaggerClient/README.md | 16 ++++++++-------- .../IO.Swagger.Test/IO.Swagger.Test.csproj | 2 +- .../src/IO.Swagger/IO.Swagger.csproj | 2 +- .../SwaggerClientTest.userprefs | 2 +- ...ClientTest.csproj.FilesWrittenAbsolute.txt | 11 ----------- 6 files changed, 17 insertions(+), 35 deletions(-) diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 5c9656b8edb..1088cf28dc3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{74456AF8-75EE-4ABC-97EB-CA96A472DD21}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,17 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -<<<<<<< HEAD -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Debug|Any CPU.Build.0 = Debug|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Release|Any CPU.ActiveCfg = Release|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Release|Any CPU.Build.0 = Release|Any CPU -======= -{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}.Debug|Any CPU.Build.0 = Debug|Any CPU -{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}.Release|Any CPU.ActiveCfg = Release|Any CPU -{086EEE3F-4CAC-475B-A3D9-F0D944DC9D79}.Release|Any CPU.Build.0 = Release|Any CPU ->>>>>>> 705ed78de1c6d18255cdd5c32acec3d09470ff7b +{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Debug|Any CPU.Build.0 = Debug|Any CPU +{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Release|Any CPU.ActiveCfg = Release|Any CPU +{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -31,4 +24,4 @@ EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection -EndGlobal +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index ebb6a8d216d..fbeb46025d0 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -1,12 +1,12 @@ # IO.Swagger - the C# library for the Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-05-10T17:39:13.582+08:00 +- Build date: 2016-05-13T21:50:05.372+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -134,6 +134,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -143,9 +149,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 743b0b97853..fb3fb1ab975 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -65,7 +65,7 @@ - {C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A} + {74456AF8-75EE-4ABC-97EB-CA96A472DD21} IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index ad86456ecea..16f73d99230 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A} + {74456AF8-75EE-4ABC-97EB-CA96A472DD21} Library Properties Swagger Library diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index b87503528b6..a232c3d0177 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -5,7 +5,7 @@ - + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt index 547dccf6f4e..fe5b5e6a930 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt @@ -9,14 +9,3 @@ /Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll /Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll /Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll.mdb -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll -/Volumes/Extra/projects/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll.mdb From 70cbe1042cd34862b5a7479ce69fd56e0b679ccb Mon Sep 17 00:00:00 2001 From: Mateusz Mackowiak Date: Fri, 13 May 2016 17:44:56 +0200 Subject: [PATCH 34/53] [Objc] Moved the generated files to Api, Core and Model folders - Added known response codes in comment --- .../codegen/languages/ObjcClientCodegen.java | 60 +++++++++++-------- .../main/resources/objc/api-header.mustache | 5 +- samples/client/petstore/objc/README.md | 4 +- .../petstore/objc/SwaggerClient.podspec | 2 +- .../objc/SwaggerClient/{ => Api}/SWGPetApi.h | 30 +++++----- .../objc/SwaggerClient/{ => Api}/SWGPetApi.m | 0 .../SwaggerClient/{ => Api}/SWGStoreApi.h | 16 ++--- .../SwaggerClient/{ => Api}/SWGStoreApi.m | 0 .../objc/SwaggerClient/{ => Api}/SWGUserApi.h | 29 ++++----- .../objc/SwaggerClient/{ => Api}/SWGUserApi.m | 0 .../{ => Core}/JSONValueTransformer+ISO8601.h | 0 .../{ => Core}/JSONValueTransformer+ISO8601.m | 0 .../SwaggerClient/{ => Core}/SWGApiClient.h | 0 .../SwaggerClient/{ => Core}/SWGApiClient.m | 0 .../{ => Core}/SWGConfiguration.h | 0 .../{ => Core}/SWGConfiguration.m | 0 .../{ => Core}/SWGJSONRequestSerializer.h | 0 .../{ => Core}/SWGJSONRequestSerializer.m | 0 .../{ => Core}/SWGJSONResponseSerializer.h | 0 .../{ => Core}/SWGJSONResponseSerializer.m | 0 .../objc/SwaggerClient/{ => Core}/SWGLogger.h | 0 .../objc/SwaggerClient/{ => Core}/SWGLogger.m | 0 .../objc/SwaggerClient/{ => Core}/SWGObject.h | 0 .../objc/SwaggerClient/{ => Core}/SWGObject.m | 0 .../{ => Core}/SWGQueryParamCollection.h | 0 .../{ => Core}/SWGQueryParamCollection.m | 0 .../{ => Core}/SWGResponseDeserializer.h | 0 .../{ => Core}/SWGResponseDeserializer.m | 0 .../SwaggerClient/{ => Core}/SWGSanitizer.h | 0 .../SwaggerClient/{ => Core}/SWGSanitizer.m | 0 .../SwaggerClient/{ => Model}/SWGCategory.h | 0 .../SwaggerClient/{ => Model}/SWGCategory.m | 0 .../objc/SwaggerClient/{ => Model}/SWGOrder.h | 0 .../objc/SwaggerClient/{ => Model}/SWGOrder.m | 0 .../objc/SwaggerClient/{ => Model}/SWGPet.h | 0 .../objc/SwaggerClient/{ => Model}/SWGPet.m | 0 .../objc/SwaggerClient/{ => Model}/SWGTag.h | 0 .../objc/SwaggerClient/{ => Model}/SWGTag.m | 0 .../objc/SwaggerClient/{ => Model}/SWGUser.h | 0 .../objc/SwaggerClient/{ => Model}/SWGUser.m | 0 40 files changed, 74 insertions(+), 72 deletions(-) rename samples/client/petstore/objc/SwaggerClient/{ => Api}/SWGPetApi.h (84%) rename samples/client/petstore/objc/SwaggerClient/{ => Api}/SWGPetApi.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Api}/SWGStoreApi.h (84%) rename samples/client/petstore/objc/SwaggerClient/{ => Api}/SWGStoreApi.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Api}/SWGUserApi.h (82%) rename samples/client/petstore/objc/SwaggerClient/{ => Api}/SWGUserApi.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/JSONValueTransformer+ISO8601.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/JSONValueTransformer+ISO8601.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGApiClient.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGApiClient.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGConfiguration.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGConfiguration.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGJSONRequestSerializer.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGJSONRequestSerializer.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGJSONResponseSerializer.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGJSONResponseSerializer.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGLogger.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGLogger.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGObject.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGObject.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGQueryParamCollection.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGQueryParamCollection.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGResponseDeserializer.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGResponseDeserializer.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGSanitizer.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Core}/SWGSanitizer.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGCategory.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGCategory.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGOrder.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGOrder.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGPet.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGPet.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGTag.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGTag.m (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGUser.h (100%) rename samples/client/petstore/objc/SwaggerClient/{ => Model}/SWGUser.m (100%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 6bb05deb233..d7532d86ee3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -42,6 +42,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected String[] specialWords = {"new", "copy"}; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected String modelFilesPath = "Model/"; + protected String coreFilesPath = "Core/"; + protected String apiFilesPath = "Api/"; protected Set advancedMapingTypes = new HashSet(); @@ -223,37 +226,38 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); - String swaggerFolder = podName; + additionalProperties.put("modelFilesPath", modelFilesPath); + additionalProperties.put("coreFilesPath", coreFilesPath); + additionalProperties.put("apiFilesPath", apiFilesPath); - modelPackage = swaggerFolder; - apiPackage = swaggerFolder; + modelPackage = podName; + apiPackage = podName; - supportingFiles.add(new SupportingFile("Object-header.mustache", swaggerFolder, classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", swaggerFolder, classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", swaggerFolder, classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", swaggerFolder, classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", swaggerFolder, classPrefix + "ApiClient.h")); - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", swaggerFolder, classPrefix + "ApiClient.m")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.h")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.m")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.h")); - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", swaggerFolder, classPrefix + "Sanitizer.m")); - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", swaggerFolder, classPrefix + "Sanitizer.h")); - supportingFiles.add(new SupportingFile("Logger-body.mustache", swaggerFolder, classPrefix + "Logger.m")); - supportingFiles.add(new SupportingFile("Logger-header.mustache", swaggerFolder, classPrefix + "Logger.h")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-body.mustache", swaggerFolder, classPrefix + "Configuration.m")); - supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); + supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); + supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); + supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); + supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - } @Override @@ -456,12 +460,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + File.separatorChar + apiPackage(); + return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); } @Override public String modelFileFolder() { - return outputFolder + File.separatorChar + modelPackage(); + return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + } + + public String coreFileFolder() { + return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); } @Override diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 7c5a9d335cf..e7491a14ece 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -22,13 +22,12 @@ +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +({{classname}}*) sharedAPI; {{#operation}} -/// -/// /// {{{summary}}} /// {{#notes}}{{{notes}}}{{/notes}} /// /// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -/// {{/allParams}} +/// {{/allParams}}{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// /// @return {{{returnType}}} -(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index 42b076c8461..d5b72d7cfe9 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -1,12 +1,12 @@ # SwaggerClient -This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters +This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - Package version: -- Build date: 2016-05-11T10:37:53.050+02:00 +- Build date: 2016-05-13T17:46:25.156+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 00766943c86..885b29f7806 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -13,7 +13,7 @@ Pod::Spec.new do |s| s.summary = "Swagger Petstore" s.description = <<-DESC - This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters + This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters DESC s.platform = :ios, '7.0' diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h similarity index 84% rename from samples/client/petstore/objc/SwaggerClient/SWGPetApi.h rename to samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h index 908771588e0..6fea33df4d6 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h @@ -19,27 +19,25 @@ -(unsigned long) requestQueueSize; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGPetApi*) sharedAPI; -/// -/// /// Add a new pet to the store /// /// /// @param body Pet object that needs to be added to the store (optional) /// +/// code:405 message:"Invalid input" /// /// @return -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) /// +/// code:400 message:"Invalid pet value" /// /// @return -(NSNumber*) deletePetWithPetId: (NSNumber*) petId @@ -47,60 +45,60 @@ completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Finds Pets by status /// Multiple status values can be provided with comma seperated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid status value" /// /// @return NSArray* -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; -/// -/// /// Finds Pets by tags /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid tag value" /// /// @return NSArray* -(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; -/// -/// /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// @param petId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found" /// /// @return SWGPet* -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; -/// -/// /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found", +/// code:405 message:"Validation exception" /// /// @return -(NSNumber*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Updates a pet in the store with form data /// /// @@ -108,6 +106,7 @@ /// @param name Updated name of the pet (optional) /// @param status Updated status of the pet (optional) /// +/// code:405 message:"Invalid input" /// /// @return -(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId @@ -116,8 +115,6 @@ completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// uploads an image /// /// @@ -125,6 +122,7 @@ /// @param additionalMetadata Additional data to pass to server (optional) /// @param file file to upload (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) uploadFileWithPetId: (NSNumber*) petId diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGPetApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h similarity index 84% rename from samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h rename to samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h index d86eb23a046..4a29c72e644 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h @@ -19,51 +19,51 @@ -(unsigned long) requestQueueSize; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGStoreApi*) sharedAPI; -/// -/// /// Delete purchase order by ID /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// /// @param orderId ID of the order that needs to be deleted /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" /// /// @return -(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Returns pet inventories by status /// Returns a map of status codes to quantities /// /// +/// code:200 message:"successful operation" /// /// @return NSDictionary* -(NSNumber*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; -/// -/// /// Find purchase order by ID /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// @param orderId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" /// /// @return SWGOrder* -(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; -/// -/// /// Place an order for a pet /// /// /// @param body order placed for purchasing the pet (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid Order" /// /// @return SWGOrder* -(NSNumber*) placeOrderWithBody: (SWGOrder*) body diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h similarity index 82% rename from samples/client/petstore/objc/SwaggerClient/SWGUserApi.h rename to samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h index 6f3561dfbf3..73dcef55c02 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h @@ -19,79 +19,77 @@ -(unsigned long) requestQueueSize; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGUserApi*) sharedAPI; -/// -/// /// Create user /// This can only be done by the logged in user. /// /// @param body Created user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Creates list of users with given input array /// /// /// @param body List of user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Creates list of users with given input array /// /// /// @param body List of user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted /// +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" /// /// @return -(NSNumber*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" /// /// @return SWGUser* -(NSNumber*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; -/// -/// /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username/password supplied" /// /// @return NSString* -(NSNumber*) loginUserWithUsername: (NSString*) username @@ -99,26 +97,25 @@ completionHandler: (void (^)(NSString* output, NSError* error)) handler; -/// -/// /// Logs out current logged in user session /// /// /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Updated user /// This can only be done by the logged in user. /// /// @param username name that need to be deleted /// @param body Updated user object (optional) /// +/// code:400 message:"Invalid user supplied", +/// code:404 message:"User not found" /// /// @return -(NSNumber*) updateUserWithUsername: (NSString*) username diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGUserApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.m diff --git a/samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.h b/samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.h rename to samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h diff --git a/samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.m b/samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.m rename to samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGApiClient.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGApiClient.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGLogger.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGLogger.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGLogger.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGLogger.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGObject.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGObject.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGObject.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGObject.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGObject.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGObject.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGObject.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGObject.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGCategory.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGCategory.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGOrder.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGOrder.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGPet.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGPet.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGPet.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGPet.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGTag.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGTag.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGTag.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGTag.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGUser.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGUser.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGUser.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGUser.m From f87d71883629f20d75486b5c01e763eb0180eeb7 Mon Sep 17 00:00:00 2001 From: cbornet Date: Fri, 13 May 2016 16:23:51 +0000 Subject: [PATCH 35/53] fix issue with expired token refreshing --- .../Java/libraries/feign/auth/OAuth.mustache | 56 +++++++++---------- 1 file changed, 25 insertions(+), 31 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache index 74ff86ebd1b..1df88d403a2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache @@ -23,14 +23,17 @@ import feign.Request.Options; import feign.RequestInterceptor; import feign.RequestTemplate; import feign.Response; +import feign.RetryableException; import feign.Util; import {{invokerPackage}}.StringUtil; public class OAuth implements RequestInterceptor { + static final int MILLIS_PER_SECOND = 1000; + public interface AccessTokenListener { - public void notify(BasicOAuthToken token); + void notify(BasicOAuthToken token); } private volatile String accessToken; @@ -41,21 +44,13 @@ public class OAuth implements RequestInterceptor { private AccessTokenListener accessTokenListener; public OAuth(Client client, TokenRequestBuilder requestBuilder) { - setOauthClient(client); + this.oauthClient = new OAuthClient(new OAuthFeignClient(client)); this.tokenRequestBuilder = requestBuilder; } public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); - setFlow(flow); - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); - } - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); - } - - public void setFlow(OAuthFlow flow) { switch(flow) { case accessCode: case implicit: @@ -70,6 +65,11 @@ public class OAuth implements RequestInterceptor { default: break; } + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); } @Override @@ -80,34 +80,29 @@ public class OAuth implements RequestInterceptor { } // If first time, get the token if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { - try { - updateAccessToken(); - } catch (OAuthSystemException e) { - e.printStackTrace(); - return; - } catch (OAuthProblemException e) { - e.printStackTrace(); - return; - } + updateAccessToken(); } if (getAccessToken() != null) { template.header("Authorization", "Bearer " + getAccessToken()); } } - public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { - if (getAccessToken() == null) { - OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); - if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { - setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); - } + public synchronized void updateAccessToken() { + OAuthJSONAccessTokenResponse accessTokenResponse; + try { + accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + } catch (Exception e) { + throw new RetryableException(e.getMessage(), e,null); + } + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); } } } - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) { this.accessTokenListener = accessTokenListener; } @@ -117,7 +112,7 @@ public class OAuth implements RequestInterceptor { public synchronized void setAccessToken(String accessToken, Long expiresIn) { this.accessToken = accessToken; - this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND; } public TokenRequestBuilder getTokenRequestBuilder() { @@ -148,7 +143,7 @@ public class OAuth implements RequestInterceptor { this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); } - public class OAuthFeignClient implements HttpClient { + public static class OAuthFeignClient implements HttpClient { private Client client; @@ -198,6 +193,5 @@ public class OAuth implements RequestInterceptor { public void shutdown() { // Nothing to do here } - } } From b543a53dc71edf3f8937d611a7dcc703b067d509 Mon Sep 17 00:00:00 2001 From: cbornet Date: Fri, 13 May 2016 16:33:49 +0000 Subject: [PATCH 36/53] update feign sample --- .../io/swagger/client/FormAwareEncoder.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 6 +- .../java/io/swagger/client/api/PetApi.java | 4 +- .../java/io/swagger/client/api/StoreApi.java | 2 +- .../java/io/swagger/client/api/UserApi.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 56 +++++++++---------- .../java/io/swagger/client/model/Animal.java | 27 ++++++++- .../io/swagger/client/model/AnimalFarm.java | 3 +- .../java/io/swagger/client/model/Cat.java | 25 ++++++++- .../io/swagger/client/model/Category.java | 3 +- .../java/io/swagger/client/model/Dog.java | 25 ++++++++- .../io/swagger/client/model/EnumClass.java | 1 + .../io/swagger/client/model/EnumTest.java | 3 +- .../io/swagger/client/model/FormatTest.java | 3 +- .../client/model/Model200Response.java | 3 +- .../client/model/ModelApiResponse.java | 3 +- .../io/swagger/client/model/ModelReturn.java | 3 +- .../java/io/swagger/client/model/Name.java | 17 +++++- .../java/io/swagger/client/model/Order.java | 3 +- .../java/io/swagger/client/model/Pet.java | 3 +- .../client/model/SpecialModelName.java | 3 +- .../java/io/swagger/client/model/Tag.java | 3 +- .../java/io/swagger/client/model/User.java | 3 +- 24 files changed, 143 insertions(+), 62 deletions(-) diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index 4d348dcd9cb..70505097dfa 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -14,7 +14,7 @@ import feign.codec.EncodeException; import feign.codec.Encoder; import feign.RequestTemplate; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class FormAwareEncoder implements Encoder { public static final String UTF_8 = "utf-8"; private static final String LINE_FEED = "\r\n"; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index 3d1b4a72710..47bb5836fa5 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index b1dc92805ab..1231d3f3e0a 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -11,13 +11,13 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public interface FakeApi extends ApiClient.Api { /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index e44f445d291..3b50531c607 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -3,8 +3,8 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; @@ -12,7 +12,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public interface PetApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index 04993aa879a..7bf3a3b44c5 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -10,7 +10,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public interface StoreApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index 13171d4bed4..51e47cb6e33 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -10,7 +10,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public interface UserApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java index 5aafbf81a2f..2653474747d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java @@ -23,14 +23,17 @@ import feign.Request.Options; import feign.RequestInterceptor; import feign.RequestTemplate; import feign.Response; +import feign.RetryableException; import feign.Util; import io.swagger.client.StringUtil; public class OAuth implements RequestInterceptor { + static final int MILLIS_PER_SECOND = 1000; + public interface AccessTokenListener { - public void notify(BasicOAuthToken token); + void notify(BasicOAuthToken token); } private volatile String accessToken; @@ -41,21 +44,13 @@ public class OAuth implements RequestInterceptor { private AccessTokenListener accessTokenListener; public OAuth(Client client, TokenRequestBuilder requestBuilder) { - setOauthClient(client); + this.oauthClient = new OAuthClient(new OAuthFeignClient(client)); this.tokenRequestBuilder = requestBuilder; } public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); - setFlow(flow); - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); - } - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); - } - - public void setFlow(OAuthFlow flow) { switch(flow) { case accessCode: case implicit: @@ -70,6 +65,11 @@ public class OAuth implements RequestInterceptor { default: break; } + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); } @Override @@ -80,34 +80,29 @@ public class OAuth implements RequestInterceptor { } // If first time, get the token if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { - try { - updateAccessToken(); - } catch (OAuthSystemException e) { - e.printStackTrace(); - return; - } catch (OAuthProblemException e) { - e.printStackTrace(); - return; - } + updateAccessToken(); } if (getAccessToken() != null) { template.header("Authorization", "Bearer " + getAccessToken()); } } - public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { - if (getAccessToken() == null) { - OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); - if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { - setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); - } + public synchronized void updateAccessToken() { + OAuthJSONAccessTokenResponse accessTokenResponse; + try { + accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + } catch (Exception e) { + throw new RetryableException(e.getMessage(), e,null); + } + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); } } } - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) { this.accessTokenListener = accessTokenListener; } @@ -117,7 +112,7 @@ public class OAuth implements RequestInterceptor { public synchronized void setAccessToken(String accessToken, Long expiresIn) { this.accessToken = accessToken; - this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND; } public TokenRequestBuilder getTokenRequestBuilder() { @@ -148,7 +143,7 @@ public class OAuth implements RequestInterceptor { this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); } - public class OAuthFeignClient implements HttpClient { + public static class OAuthFeignClient implements HttpClient { private Client client; @@ -198,6 +193,5 @@ public class OAuth implements RequestInterceptor { public void shutdown() { // Nothing to do here } - } } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index d6249c18d7e..2722d7bf0d3 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,10 +10,11 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Animal { private String className = null; + private String color = "red"; /** @@ -32,6 +34,23 @@ public class Animal { } + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -41,12 +60,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -55,6 +75,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index f38bf504d50..29d71fb8604 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -9,7 +10,7 @@ import java.util.List; /** * AnimalFarm */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class AnimalFarm extends ArrayList { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index 278889e60d4..b84e83dc9fb 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,10 +11,11 @@ import io.swagger.client.model.Animal; /** * Cat */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Cat extends Animal { private String className = null; + private String color = "red"; private Boolean declawed = null; @@ -34,6 +36,23 @@ public class Cat extends Animal { } + /** + **/ + public Cat color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Cat declawed(Boolean declawed) { @@ -61,13 +80,14 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, declawed, super.hashCode()); + return Objects.hash(className, color, declawed, super.hashCode()); } @Override @@ -76,6 +96,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index f1df969c29c..d0579ee435f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Category */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 1a6374d54bf..5a7162dce4d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,10 +11,11 @@ import io.swagger.client.model.Animal; /** * Dog */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Dog extends Animal { private String className = null; + private String color = "red"; private String breed = null; @@ -34,6 +36,23 @@ public class Dog extends Animal { } + /** + **/ + public Dog color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Dog breed(String breed) { @@ -61,13 +80,14 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, breed, super.hashCode()); + return Objects.hash(className, color, breed, super.hashCode()); } @Override @@ -76,6 +96,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java index 716bfbbc85e..42434e297ff 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 9148bd3d5d5..6ef0a34b1f9 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; /** * EnumTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class EnumTest { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index 072decf8079..cea8883add4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -11,7 +12,7 @@ import java.util.Date; /** * FormatTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class FormatTest { private Integer integer = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index 4573c22c3da..a2bee4c634e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Model200Response { private Integer name = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index eca2b1fb388..3d4cf0bfc96 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * ModelApiResponse */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class ModelApiResponse { private Integer code = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index 476bf479288..d3fdac81f3d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class ModelReturn { private Integer _return = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index 19ababb8f1c..7a0af504643 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,12 +11,13 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Name { private Integer name = null; private Integer snakeCase = null; private String property = null; + private Integer _123Number = null; /** @@ -59,6 +61,13 @@ public class Name { } + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -70,12 +79,13 @@ public class Name { Name name = (Name) o; return Objects.equals(this.name, name.name) && Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property); + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -86,6 +96,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 359d0105b80..2ca9531a8af 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -11,7 +12,7 @@ import java.util.Date; /** * Order */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Order { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index 511100f868d..bd9248120e8 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -14,7 +15,7 @@ import java.util.List; /** * Pet */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index 37c5823ed2c..58df0f961f0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * SpecialModelName */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class SpecialModelName { private Long specialPropertyName = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index ff51db61fef..24d51b8e59e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Tag */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 6a4414b5f82..450f177103d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * User */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class User { private Long id = null; From 885d3543dfcd67b7eb3f8445447a67c5dd575471 Mon Sep 17 00:00:00 2001 From: Leon Yu Date: Fri, 13 May 2016 17:50:56 -0400 Subject: [PATCH 37/53] functional programming api for typescript-fetch --- .../resources/TypeScript-Fetch/api.mustache | 76 +- .../TypeScript-Fetch/tsconfig.json.mustache | 3 +- .../typescript-fetch/builds/default/api.ts | 980 +- .../builds/default/tsconfig.json | 3 +- .../typescript-fetch/builds/es6-target/api.ts | 980 +- .../builds/es6-target/tsconfig.json | 3 +- .../builds/with-npm-version/api.ts | 980 +- .../builds/with-npm-version/tsconfig.json | 3 +- .../typescript-fetch/tests/default/bundle.js | 10990 ---------------- .../tests/default/test/PetApi.ts | 14 +- .../tests/default/test/StoreApi.ts | 6 +- 11 files changed, 2301 insertions(+), 11737 deletions(-) delete mode 100644 samples/client/petstore/typescript-fetch/tests/default/bundle.js diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 4a189097942..20c303e40eb 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -9,11 +9,18 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } +const BASE_PATH = "{{basePath}}"; + +export interface FetchArgs { + url: string; + options: any; +} + export class BaseAPI { basePath: string; fetch: FetchAPI; - constructor(basePath: string = "{{basePath}}", fetch: FetchAPI = isomorphicFetch) { + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { this.basePath = basePath; this.fetch = fetch; } @@ -51,19 +58,18 @@ export type {{classname}}{{datatypeWithEnum}} = {{#allowableValues}}{{#values}}" {{#apis}} {{#operations}} -{{#description}} /** -* {{&description}} -*/ -{{/description}} -export class {{classname}} extends BaseAPI { + * {{classname}} - fetch parameter creator{{#description}} + * {{&description}}{{/description}} + */ +export const {{classname}}FetchParamCreactor = { {{#operation}} /** {{#summary}} * {{summary}}{{/summary}}{{#notes}} * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}): FetchArgs { {{#allParams}} {{#required}} // verify required parameter "{{paramName}}" is set @@ -72,7 +78,7 @@ export class {{classname}} extends BaseAPI { } {{/required}} {{/allParams}} - const baseUrl = `${this.basePath}{{path}}`{{#pathParams}} + const baseUrl = `{{path}}`{{#pathParams}} .replace(`{${"{{baseName}}"}}`, `${ params.{{paramName}} }`){{/pathParams}}; let urlObj = url.parse(baseUrl, true); {{#hasQueryParams}} @@ -105,13 +111,53 @@ export class {{classname}} extends BaseAPI { fetchOptions.headers = contentTypeHeader; } {{/hasHeaderParam}} - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response{{#returnType}}.json(){{/returnType}}; - } else { - throw response; - } - }); + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +{{/operation}} +} + +/** + * {{classname}} - functional programming interface{{#description}} + * {{&description}}{{/description}} + */ +export const {{classname}}Fp = { +{{#operation}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}; {{/allParams}} }{{/hasParams}}): (fetch: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { + const fetchArgs = {{classname}}FetchParamCreactor.{{nickname}}({{#hasParams}}params{{/hasParams}}); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response{{#returnType}}.json(){{/returnType}}; + } else { + throw response; + } + }); + }; + }, +{{/operation}} +}; + +/** + * {{classname}} - object-oriented interface{{#description}} + * {{&description}}{{/description}} + */ +export class {{classname}} extends BaseAPI { +{{#operation}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}) { + return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(this.fetch, this.basePath); } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache index 06a057d7a49..25f414e9840 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache @@ -4,7 +4,8 @@ "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index ce059f6c814..3882e79a66c 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -7,11 +7,18 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + export class BaseAPI { basePath: string; fetch: FetchAPI; - constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) { + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { this.basePath = basePath; this.fetch = fetch; } @@ -69,14 +76,17 @@ export interface User { -export class PetApi extends BaseAPI { +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { /** * Add a new pet to the store * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): Promise { - const baseUrl = `${this.basePath}/pet`; + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -88,26 +98,23 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Deletes a pet * * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): Promise { + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "DELETE" }; @@ -116,21 +123,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Finds Pets by status * Multiple status values can be provided with comma seperated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): Promise> { - const baseUrl = `${this.basePath}/pet/findByStatus`; + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "status": params.status, @@ -141,21 +145,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): Promise> { - const baseUrl = `${this.basePath}/pet/findByTags`; + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "tags": params.tags, @@ -166,25 +167,22 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * @param petId ID of pet that needs to be fetched */ - getPetById(params: { petId: number; }): Promise { + getPetById(params: { petId: number; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -193,21 +191,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): Promise { - const baseUrl = `${this.basePath}/pet`; + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "PUT" }; @@ -219,14 +214,11 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Updates a pet in the store with form data * @@ -234,12 +226,12 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise { + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -253,14 +245,11 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * uploads an image * @@ -268,12 +257,12 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise { + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); } - const baseUrl = `${this.basePath}/pet/{petId}/uploadImage` + const baseUrl = `/pet/{petId}/uploadImage` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -287,130 +276,453 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); } } +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ export class StoreApi extends BaseAPI { /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - deleteOrder(params: { orderId: string; }): Promise { - // verify required parameter "orderId" is set - if (params["orderId"] == null) { - throw new Error("Missing required parameter orderId when calling deleteOrder"); - } - const baseUrl = `${this.basePath}/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); } /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): Promise<{ [key: string]: number; }> { - const baseUrl = `${this.basePath}/store/inventory`; - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); } /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - getOrderById(params: { orderId: string; }): Promise { - // verify required parameter "orderId" is set - if (params["orderId"] == null) { - throw new Error("Missing required parameter orderId when calling getOrderById"); - } - const baseUrl = `${this.basePath}/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); } /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): Promise { - const baseUrl = `${this.basePath}/store/order`; - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; - - let contentTypeHeader: Dictionary; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); } } -export class UserApi extends BaseAPI { +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { /** * Create user * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): Promise { - const baseUrl = `${this.basePath}/user`; + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -422,21 +734,18 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): Promise { - const baseUrl = `${this.basePath}/user/createWithArray`; + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -448,21 +757,18 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): Promise { - const baseUrl = `${this.basePath}/user/createWithList`; + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -474,25 +780,22 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): Promise { + deleteUser(params: { username: string; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "DELETE" }; @@ -501,25 +804,22 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): Promise { + getUserByName(params: { username: string; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -528,22 +828,19 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Logs user into the system * * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): Promise { - const baseUrl = `${this.basePath}/user/login`; + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "username": params.username, @@ -555,20 +852,17 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Logs out current logged in user session * */ - logoutUser(): Promise { - const baseUrl = `${this.basePath}/user/logout`; + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -576,26 +870,23 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Updated user * This can only be done by the logged in user. * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): Promise { + updateUser(params: { username: string; body?: User; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "PUT" }; @@ -608,13 +899,224 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); } } diff --git a/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json index 18db23e2f5f..72ff2567206 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json @@ -4,7 +4,8 @@ "target": "es5", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index 80b9e05756f..15a61ab6961 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -6,11 +6,18 @@ import * as isomorphicFetch from "isomorphic-fetch"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + export class BaseAPI { basePath: string; fetch: FetchAPI; - constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) { + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { this.basePath = basePath; this.fetch = fetch; } @@ -68,14 +75,17 @@ export interface User { -export class PetApi extends BaseAPI { +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { /** * Add a new pet to the store * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): Promise { - const baseUrl = `${this.basePath}/pet`; + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -87,26 +97,23 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Deletes a pet * * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): Promise { + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "DELETE" }; @@ -115,21 +122,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Finds Pets by status * Multiple status values can be provided with comma seperated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): Promise> { - const baseUrl = `${this.basePath}/pet/findByStatus`; + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { "status": params.status, @@ -140,21 +144,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): Promise> { - const baseUrl = `${this.basePath}/pet/findByTags`; + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { "tags": params.tags, @@ -165,25 +166,22 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * @param petId ID of pet that needs to be fetched */ - getPetById(params: { petId: number; }): Promise { + getPetById(params: { petId: number; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -192,21 +190,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): Promise { - const baseUrl = `${this.basePath}/pet`; + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "PUT" }; @@ -218,14 +213,11 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Updates a pet in the store with form data * @@ -233,12 +225,12 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise { + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -252,14 +244,11 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * uploads an image * @@ -267,12 +256,12 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise { + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); } - const baseUrl = `${this.basePath}/pet/{petId}/uploadImage` + const baseUrl = `/pet/{petId}/uploadImage` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -286,130 +275,453 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); } } +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ export class StoreApi extends BaseAPI { /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - deleteOrder(params: { orderId: string; }): Promise { - // verify required parameter "orderId" is set - if (params["orderId"] == null) { - throw new Error("Missing required parameter orderId when calling deleteOrder"); - } - const baseUrl = `${this.basePath}/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); } /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): Promise<{ [key: string]: number; }> { - const baseUrl = `${this.basePath}/store/inventory`; - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); } /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - getOrderById(params: { orderId: string; }): Promise { - // verify required parameter "orderId" is set - if (params["orderId"] == null) { - throw new Error("Missing required parameter orderId when calling getOrderById"); - } - const baseUrl = `${this.basePath}/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); } /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): Promise { - const baseUrl = `${this.basePath}/store/order`; - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; - - let contentTypeHeader: Dictionary; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); } } -export class UserApi extends BaseAPI { +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { /** * Create user * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): Promise { - const baseUrl = `${this.basePath}/user`; + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -421,21 +733,18 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): Promise { - const baseUrl = `${this.basePath}/user/createWithArray`; + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -447,21 +756,18 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): Promise { - const baseUrl = `${this.basePath}/user/createWithList`; + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -473,25 +779,22 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): Promise { + deleteUser(params: { username: string; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "DELETE" }; @@ -500,25 +803,22 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): Promise { + getUserByName(params: { username: string; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -527,22 +827,19 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Logs user into the system * * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): Promise { - const baseUrl = `${this.basePath}/user/login`; + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { "username": params.username, @@ -554,20 +851,17 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Logs out current logged in user session * */ - logoutUser(): Promise { - const baseUrl = `${this.basePath}/user/logout`; + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -575,26 +869,23 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Updated user * This can only be done by the logged in user. * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): Promise { + updateUser(params: { username: string; body?: User; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "PUT" }; @@ -607,13 +898,224 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); } } diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json index 9d5f166e764..06a8e0437b9 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index ce059f6c814..3882e79a66c 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -7,11 +7,18 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + export class BaseAPI { basePath: string; fetch: FetchAPI; - constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) { + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { this.basePath = basePath; this.fetch = fetch; } @@ -69,14 +76,17 @@ export interface User { -export class PetApi extends BaseAPI { +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { /** * Add a new pet to the store * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): Promise { - const baseUrl = `${this.basePath}/pet`; + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -88,26 +98,23 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Deletes a pet * * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): Promise { + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "DELETE" }; @@ -116,21 +123,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Finds Pets by status * Multiple status values can be provided with comma seperated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): Promise> { - const baseUrl = `${this.basePath}/pet/findByStatus`; + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "status": params.status, @@ -141,21 +145,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): Promise> { - const baseUrl = `${this.basePath}/pet/findByTags`; + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "tags": params.tags, @@ -166,25 +167,22 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * @param petId ID of pet that needs to be fetched */ - getPetById(params: { petId: number; }): Promise { + getPetById(params: { petId: number; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -193,21 +191,18 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): Promise { - const baseUrl = `${this.basePath}/pet`; + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "PUT" }; @@ -219,14 +214,11 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Updates a pet in the store with form data * @@ -234,12 +226,12 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise { + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); } - const baseUrl = `${this.basePath}/pet/{petId}` + const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -253,14 +245,11 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * uploads an image * @@ -268,12 +257,12 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise { + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); } - const baseUrl = `${this.basePath}/pet/{petId}/uploadImage` + const baseUrl = `/pet/{petId}/uploadImage` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -287,130 +276,453 @@ export class PetApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); } } +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ export class StoreApi extends BaseAPI { /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - deleteOrder(params: { orderId: string; }): Promise { - // verify required parameter "orderId" is set - if (params["orderId"] == null) { - throw new Error("Missing required parameter orderId when calling deleteOrder"); - } - const baseUrl = `${this.basePath}/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); } /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): Promise<{ [key: string]: number; }> { - const baseUrl = `${this.basePath}/store/inventory`; - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); } /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - getOrderById(params: { orderId: string; }): Promise { - // verify required parameter "orderId" is set - if (params["orderId"] == null) { - throw new Error("Missing required parameter orderId when calling getOrderById"); - } - const baseUrl = `${this.basePath}/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; - - let contentTypeHeader: Dictionary; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); } /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): Promise { - const baseUrl = `${this.basePath}/store/order`; - let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; - - let contentTypeHeader: Dictionary; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); } } -export class UserApi extends BaseAPI { +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { /** * Create user * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): Promise { - const baseUrl = `${this.basePath}/user`; + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -422,21 +734,18 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): Promise { - const baseUrl = `${this.basePath}/user/createWithArray`; + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -448,21 +757,18 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): Promise { - const baseUrl = `${this.basePath}/user/createWithList`; + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "POST" }; @@ -474,25 +780,22 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): Promise { + deleteUser(params: { username: string; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "DELETE" }; @@ -501,25 +804,22 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): Promise { + getUserByName(params: { username: string; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -528,22 +828,19 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Logs user into the system * * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): Promise { - const baseUrl = `${this.basePath}/user/login`; + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "username": params.username, @@ -555,20 +852,17 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Logs out current logged in user session * */ - logoutUser(): Promise { - const baseUrl = `${this.basePath}/user/logout`; + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "GET" }; @@ -576,26 +870,23 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); - } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, /** * Updated user * This can only be done by the logged in user. * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): Promise { + updateUser(params: { username: string; body?: User; }): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); } - const baseUrl = `${this.basePath}/user/{username}` + const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = { method: "PUT" }; @@ -608,13 +899,224 @@ export class UserApi extends BaseAPI { if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; } - return this.fetch(url.format(urlObj), fetchOptions).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response; - } else { - throw response; - } - }); + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); } } diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json index 18db23e2f5f..72ff2567206 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json @@ -4,7 +4,8 @@ "target": "es5", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/tests/default/bundle.js b/samples/client/petstore/typescript-fetch/tests/default/bundle.js deleted file mode 100644 index a38402a7904..00000000000 --- a/samples/client/petstore/typescript-fetch/tests/default/bundle.js +++ /dev/null @@ -1,10990 +0,0 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders) - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len - - var L = 0 - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } - - parts.push(output) - - return parts.join('') -} - -},{}],2:[function(require,module,exports){ -(function (global){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') -var isArray = require('isarray') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() - -function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.foo = function () { return 42 } - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -} - -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} - -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) -} - -Buffer.poolSize = 8192 // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr -} - -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} - -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } -} - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } -} - -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -} - -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; i++) { - that[i] = 0 - } - } - return that -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -} - -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - that.write(string, encoding) - return that -} - -function fromArrayLike (that, array) { - var length = checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that -} - -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} - -function checked (length) { - // Note: cannot use `length < kMaxLength` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) -} - -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'binary': - case 'base64': - case 'raw': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; i++) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; i++) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'binary': - // Deprecated - case 'raw': - case 'raws': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'binary': - return binarySlice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -function arrayIndexOf (arr, val, byteOffset, encoding) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var foundIndex = -1 - for (var i = 0; byteOffset + i < arrLength; i++) { - if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - return -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset >>= 0 - - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 - - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) - - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - if (Buffer.isBuffer(val)) { - // special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(this, val, byteOffset, encoding) - } - if (typeof val === 'number') { - if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { - return Uint8Array.prototype.indexOf.call(this, val, byteOffset) - } - return arrayIndexOf(this, [ val ], byteOffset, encoding) - } - - throw new TypeError('val must be string, number or Buffer') -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new Error('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; i++) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function binaryWrite (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'binary': - return binaryWrite(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function binarySlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; i++) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; i++) { - newBuf[i] = this[i + start] - } - } - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 -} - -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; i--) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; i++) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; i++) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; i++) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; i++) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; i++) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; i++) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":1,"ieee754":3,"isarray":4}],3:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],4:[function(require,module,exports){ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - -},{}],5:[function(require,module,exports){ -(function (global){ -/*! https://mths.be/punycode v1.4.1 by @mathias */ -;(function(root) { - - /** Detect free variables */ - var freeExports = typeof exports == 'object' && exports && - !exports.nodeType && exports; - var freeModule = typeof module == 'object' && module && - !module.nodeType && module; - var freeGlobal = typeof global == 'object' && global; - if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal - ) { - root = freeGlobal; - } - - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, - - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' - - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, - - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, - - /** Temporary variable */ - key; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw new RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } - - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - - if (index >= inputLength) { - error('invalid-input'); - } - - digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } - - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - - if (digit < t) { - break; - } - - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - - w *= baseMinusT; - - } - - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); - - } - - return ucs2encode(output); - } - - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++delta; - ++n; - - } - return output.join(''); - } - - /** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - function toUnicode(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); - } - - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - function toASCII(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); - } - - /*--------------------------------------------------------------------------*/ - - /** Define the public API */ - punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.4.1', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; - - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define('punycode', function() { - return punycode; - }); - } else if (freeExports && freeModule) { - if (module.exports == freeExports) { - // in Node.js, io.js, or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { - // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } - } else { - // in Rhino or a web browser - root.punycode = punycode; - } - -}(this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],6:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -},{}],7:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } -}; - -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return map(objectKeys(obj), function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (isArray(obj[k])) { - return map(obj[k], function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } - - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -function map (xs, f) { - if (xs.map) return xs.map(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); - } - return res; -} - -var objectKeys = Object.keys || function (obj) { - var res = []; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); - } - return res; -}; - -},{}],8:[function(require,module,exports){ -'use strict'; - -exports.decode = exports.parse = require('./decode'); -exports.encode = exports.stringify = require('./encode'); - -},{"./decode":6,"./encode":7}],9:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var punycode = require('punycode'); -var util = require('./util'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; - -function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; -} - -// Reference: RFC 3986, RFC 1808, RFC 2396 - -// define these here so at least they only have to be -// compiled once on the first module load. -var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = require('querystring'); - -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) return url; - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} - -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - // Copy chrome, IE, opera backslash-handling behavior. - // Back slashes before the query string get converted to forward slashes - // See: https://code.google.com/p/chromium/issues/detail?id=25916 - var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; - uSplit[0] = uSplit[0].replace(slashRegex, '/'); - url = uSplit.join(splitter); - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.path = rest; - this.href = rest; - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - if (parseQueryString) { - this.query = querystring.parse(this.search.substr(1)); - } else { - this.query = this.search.substr(1); - } - } else if (parseQueryString) { - this.search = ''; - this.query = {}; - } - return this; - } - } - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - this.hostname = punycode.toASCII(this.hostname); - } - - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - continue; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } - - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; - -// format a parsed object into a url string -function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); - return obj.format(); -} - -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } - } - - if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; - } else if (!host) { - host = ''; - } - - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; - - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; -}; - -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} - -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); -}; - -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); -} - -Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - var tkeys = Object.keys(this); - for (var tk = 0; tk < tkeys.length; tk++) { - var tkey = tkeys[tk]; - result[tkey] = this[tkey]; - } - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - result[rkey] = relative[rkey]; - } - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); - for (var v = 0; v < keys.length; v++) { - var k = keys[v]; - result[k] = relative[k]; - } - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; - } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //to support request.http - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; -}; - -Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) this.hostname = host; -}; - -},{"./util":10,"punycode":5,"querystring":8}],10:[function(require,module,exports){ -'use strict'; - -module.exports = { - isString: function(arg) { - return typeof(arg) === 'string'; - }, - isObject: function(arg) { - return typeof(arg) === 'object' && arg !== null; - }, - isNull: function(arg) { - return arg === null; - }, - isNullOrUndefined: function(arg) { - return arg == null; - } -}; - -},{}],11:[function(require,module,exports){ -/*! - * assertion-error - * Copyright(c) 2013 Jake Luer - * MIT Licensed - */ - -/*! - * Return a function that will copy properties from - * one object to another excluding any originally - * listed. Returned function will create a new `{}`. - * - * @param {String} excluded properties ... - * @return {Function} - */ - -function exclude () { - var excludes = [].slice.call(arguments); - - function excludeProps (res, obj) { - Object.keys(obj).forEach(function (key) { - if (!~excludes.indexOf(key)) res[key] = obj[key]; - }); - } - - return function extendExclude () { - var args = [].slice.call(arguments) - , i = 0 - , res = {}; - - for (; i < args.length; i++) { - excludeProps(res, args[i]); - } - - return res; - }; -}; - -/*! - * Primary Exports - */ - -module.exports = AssertionError; - -/** - * ### AssertionError - * - * An extension of the JavaScript `Error` constructor for - * assertion and validation scenarios. - * - * @param {String} message - * @param {Object} properties to include (optional) - * @param {callee} start stack function (optional) - */ - -function AssertionError (message, _props, ssf) { - var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') - , props = extend(_props || {}); - - // default values - this.message = message || 'Unspecified AssertionError'; - this.showDiff = false; - - // copy from properties - for (var key in props) { - this[key] = props[key]; - } - - // capture stack trace - ssf = ssf || arguments.callee; - if (ssf && Error.captureStackTrace) { - Error.captureStackTrace(this, ssf); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherit from Error.prototype - */ - -AssertionError.prototype = Object.create(Error.prototype); - -/*! - * Statically set name - */ - -AssertionError.prototype.name = 'AssertionError'; - -/*! - * Ensure correct constructor - */ - -AssertionError.prototype.constructor = AssertionError; - -/** - * Allow errors to be converted to JSON for static transfer. - * - * @param {Boolean} include stack (default: `true`) - * @return {Object} object that can be `JSON.stringify` - */ - -AssertionError.prototype.toJSON = function (stack) { - var extend = exclude('constructor', 'toJSON', 'stack') - , props = extend({ name: this.name }, this); - - // include stack if exists and not turned off - if (false !== stack && this.stack) { - props.stack = this.stack; - } - - return props; -}; - -},{}],12:[function(require,module,exports){ -module.exports = require('./lib/chai'); - -},{"./lib/chai":13}],13:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -var used = [] - , exports = module.exports = {}; - -/*! - * Chai version - */ - -exports.version = '3.5.0'; - -/*! - * Assertion Error - */ - -exports.AssertionError = require('assertion-error'); - -/*! - * Utils for plugins (not exported) - */ - -var util = require('./chai/utils'); - -/** - * # .use(function) - * - * Provides a way to extend the internals of Chai - * - * @param {Function} - * @returns {this} for chaining - * @api public - */ - -exports.use = function (fn) { - if (!~used.indexOf(fn)) { - fn(this, util); - used.push(fn); - } - - return this; -}; - -/*! - * Utility Functions - */ - -exports.util = util; - -/*! - * Configuration - */ - -var config = require('./chai/config'); -exports.config = config; - -/*! - * Primary `Assertion` prototype - */ - -var assertion = require('./chai/assertion'); -exports.use(assertion); - -/*! - * Core Assertions - */ - -var core = require('./chai/core/assertions'); -exports.use(core); - -/*! - * Expect interface - */ - -var expect = require('./chai/interface/expect'); -exports.use(expect); - -/*! - * Should interface - */ - -var should = require('./chai/interface/should'); -exports.use(should); - -/*! - * Assert interface - */ - -var assert = require('./chai/interface/assert'); -exports.use(assert); - -},{"./chai/assertion":14,"./chai/config":15,"./chai/core/assertions":16,"./chai/interface/assert":17,"./chai/interface/expect":18,"./chai/interface/should":19,"./chai/utils":33,"assertion-error":11}],14:[function(require,module,exports){ -/*! - * chai - * http://chaijs.com - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -var config = require('./config'); - -module.exports = function (_chai, util) { - /*! - * Module dependencies. - */ - - var AssertionError = _chai.AssertionError - , flag = util.flag; - - /*! - * Module export. - */ - - _chai.Assertion = Assertion; - - /*! - * Assertion Constructor - * - * Creates object for chaining. - * - * @api private - */ - - function Assertion (obj, msg, stack) { - flag(this, 'ssfi', stack || arguments.callee); - flag(this, 'object', obj); - flag(this, 'message', msg); - } - - Object.defineProperty(Assertion, 'includeStack', { - get: function() { - console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); - return config.includeStack; - }, - set: function(value) { - console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); - config.includeStack = value; - } - }); - - Object.defineProperty(Assertion, 'showDiff', { - get: function() { - console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); - return config.showDiff; - }, - set: function(value) { - console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); - config.showDiff = value; - } - }); - - Assertion.addProperty = function (name, fn) { - util.addProperty(this.prototype, name, fn); - }; - - Assertion.addMethod = function (name, fn) { - util.addMethod(this.prototype, name, fn); - }; - - Assertion.addChainableMethod = function (name, fn, chainingBehavior) { - util.addChainableMethod(this.prototype, name, fn, chainingBehavior); - }; - - Assertion.overwriteProperty = function (name, fn) { - util.overwriteProperty(this.prototype, name, fn); - }; - - Assertion.overwriteMethod = function (name, fn) { - util.overwriteMethod(this.prototype, name, fn); - }; - - Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { - util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); - }; - - /** - * ### .assert(expression, message, negateMessage, expected, actual, showDiff) - * - * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. - * - * @name assert - * @param {Philosophical} expression to be tested - * @param {String|Function} message or function that returns message to display if expression fails - * @param {String|Function} negatedMessage or function that returns negatedMessage to display if negated expression fails - * @param {Mixed} expected value (remember to check for negation) - * @param {Mixed} actual (optional) will default to `this.obj` - * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails - * @api private - */ - - Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { - var ok = util.test(this, arguments); - if (true !== showDiff) showDiff = false; - if (true !== config.showDiff) showDiff = false; - - if (!ok) { - var msg = util.getMessage(this, arguments) - , actual = util.getActual(this, arguments); - throw new AssertionError(msg, { - actual: actual - , expected: expected - , showDiff: showDiff - }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); - } - }; - - /*! - * ### ._obj - * - * Quick reference to stored `actual` value for plugin developers. - * - * @api private - */ - - Object.defineProperty(Assertion.prototype, '_obj', - { get: function () { - return flag(this, 'object'); - } - , set: function (val) { - flag(this, 'object', val); - } - }); -}; - -},{"./config":15}],15:[function(require,module,exports){ -module.exports = { - - /** - * ### config.includeStack - * - * User configurable property, influences whether stack trace - * is included in Assertion error message. Default of false - * suppresses stack trace in the error message. - * - * chai.config.includeStack = true; // enable stack on error - * - * @param {Boolean} - * @api public - */ - - includeStack: false, - - /** - * ### config.showDiff - * - * User configurable property, influences whether or not - * the `showDiff` flag should be included in the thrown - * AssertionErrors. `false` will always be `false`; `true` - * will be true when the assertion has requested a diff - * be shown. - * - * @param {Boolean} - * @api public - */ - - showDiff: true, - - /** - * ### config.truncateThreshold - * - * User configurable property, sets length threshold for actual and - * expected values in assertion errors. If this threshold is exceeded, for - * example for large data structures, the value is replaced with something - * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. - * - * Set it to zero if you want to disable truncating altogether. - * - * This is especially userful when doing assertions on arrays: having this - * set to a reasonable large value makes the failure messages readily - * inspectable. - * - * chai.config.truncateThreshold = 0; // disable truncating - * - * @param {Number} - * @api public - */ - - truncateThreshold: 40 - -}; - -},{}],16:[function(require,module,exports){ -/*! - * chai - * http://chaijs.com - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -module.exports = function (chai, _) { - var Assertion = chai.Assertion - , toString = Object.prototype.toString - , flag = _.flag; - - /** - * ### Language Chains - * - * The following are provided as chainable getters to - * improve the readability of your assertions. They - * do not provide testing capabilities unless they - * have been overwritten by a plugin. - * - * **Chains** - * - * - to - * - be - * - been - * - is - * - that - * - which - * - and - * - has - * - have - * - with - * - at - * - of - * - same - * - * @name language chains - * @namespace BDD - * @api public - */ - - [ 'to', 'be', 'been' - , 'is', 'and', 'has', 'have' - , 'with', 'that', 'which', 'at' - , 'of', 'same' ].forEach(function (chain) { - Assertion.addProperty(chain, function () { - return this; - }); - }); - - /** - * ### .not - * - * Negates any of assertions following in the chain. - * - * expect(foo).to.not.equal('bar'); - * expect(goodFn).to.not.throw(Error); - * expect({ foo: 'baz' }).to.have.property('foo') - * .and.not.equal('bar'); - * - * @name not - * @namespace BDD - * @api public - */ - - Assertion.addProperty('not', function () { - flag(this, 'negate', true); - }); - - /** - * ### .deep - * - * Sets the `deep` flag, later used by the `equal` and - * `property` assertions. - * - * expect(foo).to.deep.equal({ bar: 'baz' }); - * expect({ foo: { bar: { baz: 'quux' } } }) - * .to.have.deep.property('foo.bar.baz', 'quux'); - * - * `.deep.property` special characters can be escaped - * by adding two slashes before the `.` or `[]`. - * - * var deepCss = { '.link': { '[target]': 42 }}; - * expect(deepCss).to.have.deep.property('\\.link.\\[target\\]', 42); - * - * @name deep - * @namespace BDD - * @api public - */ - - Assertion.addProperty('deep', function () { - flag(this, 'deep', true); - }); - - /** - * ### .any - * - * Sets the `any` flag, (opposite of the `all` flag) - * later used in the `keys` assertion. - * - * expect(foo).to.have.any.keys('bar', 'baz'); - * - * @name any - * @namespace BDD - * @api public - */ - - Assertion.addProperty('any', function () { - flag(this, 'any', true); - flag(this, 'all', false) - }); - - - /** - * ### .all - * - * Sets the `all` flag (opposite of the `any` flag) - * later used by the `keys` assertion. - * - * expect(foo).to.have.all.keys('bar', 'baz'); - * - * @name all - * @namespace BDD - * @api public - */ - - Assertion.addProperty('all', function () { - flag(this, 'all', true); - flag(this, 'any', false); - }); - - /** - * ### .a(type) - * - * The `a` and `an` assertions are aliases that can be - * used either as language chains or to assert a value's - * type. - * - * // typeof - * expect('test').to.be.a('string'); - * expect({ foo: 'bar' }).to.be.an('object'); - * expect(null).to.be.a('null'); - * expect(undefined).to.be.an('undefined'); - * expect(new Error).to.be.an('error'); - * expect(new Promise).to.be.a('promise'); - * expect(new Float32Array()).to.be.a('float32array'); - * expect(Symbol()).to.be.a('symbol'); - * - * // es6 overrides - * expect({[Symbol.toStringTag]:()=>'foo'}).to.be.a('foo'); - * - * // language chain - * expect(foo).to.be.an.instanceof(Foo); - * - * @name a - * @alias an - * @param {String} type - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function an (type, msg) { - if (msg) flag(this, 'message', msg); - type = type.toLowerCase(); - var obj = flag(this, 'object') - , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; - - this.assert( - type === _.type(obj) - , 'expected #{this} to be ' + article + type - , 'expected #{this} not to be ' + article + type - ); - } - - Assertion.addChainableMethod('an', an); - Assertion.addChainableMethod('a', an); - - /** - * ### .include(value) - * - * The `include` and `contain` assertions can be used as either property - * based language chains or as methods to assert the inclusion of an object - * in an array or a substring in a string. When used as language chains, - * they toggle the `contains` flag for the `keys` assertion. - * - * expect([1,2,3]).to.include(2); - * expect('foobar').to.contain('foo'); - * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); - * - * @name include - * @alias contain - * @alias includes - * @alias contains - * @param {Object|String|Number} obj - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function includeChainingBehavior () { - flag(this, 'contains', true); - } - - function include (val, msg) { - _.expectTypes(this, ['array', 'object', 'string']); - - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - var expected = false; - - if (_.type(obj) === 'array' && _.type(val) === 'object') { - for (var i in obj) { - if (_.eql(obj[i], val)) { - expected = true; - break; - } - } - } else if (_.type(val) === 'object') { - if (!flag(this, 'negate')) { - for (var k in val) new Assertion(obj).property(k, val[k]); - return; - } - var subset = {}; - for (var k in val) subset[k] = obj[k]; - expected = _.eql(subset, val); - } else { - expected = (obj != undefined) && ~obj.indexOf(val); - } - this.assert( - expected - , 'expected #{this} to include ' + _.inspect(val) - , 'expected #{this} to not include ' + _.inspect(val)); - } - - Assertion.addChainableMethod('include', include, includeChainingBehavior); - Assertion.addChainableMethod('contain', include, includeChainingBehavior); - Assertion.addChainableMethod('contains', include, includeChainingBehavior); - Assertion.addChainableMethod('includes', include, includeChainingBehavior); - - /** - * ### .ok - * - * Asserts that the target is truthy. - * - * expect('everything').to.be.ok; - * expect(1).to.be.ok; - * expect(false).to.not.be.ok; - * expect(undefined).to.not.be.ok; - * expect(null).to.not.be.ok; - * - * @name ok - * @namespace BDD - * @api public - */ - - Assertion.addProperty('ok', function () { - this.assert( - flag(this, 'object') - , 'expected #{this} to be truthy' - , 'expected #{this} to be falsy'); - }); - - /** - * ### .true - * - * Asserts that the target is `true`. - * - * expect(true).to.be.true; - * expect(1).to.not.be.true; - * - * @name true - * @namespace BDD - * @api public - */ - - Assertion.addProperty('true', function () { - this.assert( - true === flag(this, 'object') - , 'expected #{this} to be true' - , 'expected #{this} to be false' - , this.negate ? false : true - ); - }); - - /** - * ### .false - * - * Asserts that the target is `false`. - * - * expect(false).to.be.false; - * expect(0).to.not.be.false; - * - * @name false - * @namespace BDD - * @api public - */ - - Assertion.addProperty('false', function () { - this.assert( - false === flag(this, 'object') - , 'expected #{this} to be false' - , 'expected #{this} to be true' - , this.negate ? true : false - ); - }); - - /** - * ### .null - * - * Asserts that the target is `null`. - * - * expect(null).to.be.null; - * expect(undefined).to.not.be.null; - * - * @name null - * @namespace BDD - * @api public - */ - - Assertion.addProperty('null', function () { - this.assert( - null === flag(this, 'object') - , 'expected #{this} to be null' - , 'expected #{this} not to be null' - ); - }); - - /** - * ### .undefined - * - * Asserts that the target is `undefined`. - * - * expect(undefined).to.be.undefined; - * expect(null).to.not.be.undefined; - * - * @name undefined - * @namespace BDD - * @api public - */ - - Assertion.addProperty('undefined', function () { - this.assert( - undefined === flag(this, 'object') - , 'expected #{this} to be undefined' - , 'expected #{this} not to be undefined' - ); - }); - - /** - * ### .NaN - * Asserts that the target is `NaN`. - * - * expect('foo').to.be.NaN; - * expect(4).not.to.be.NaN; - * - * @name NaN - * @namespace BDD - * @api public - */ - - Assertion.addProperty('NaN', function () { - this.assert( - isNaN(flag(this, 'object')) - , 'expected #{this} to be NaN' - , 'expected #{this} not to be NaN' - ); - }); - - /** - * ### .exist - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var foo = 'hi' - * , bar = null - * , baz; - * - * expect(foo).to.exist; - * expect(bar).to.not.exist; - * expect(baz).to.not.exist; - * - * @name exist - * @namespace BDD - * @api public - */ - - Assertion.addProperty('exist', function () { - this.assert( - null != flag(this, 'object') - , 'expected #{this} to exist' - , 'expected #{this} to not exist' - ); - }); - - - /** - * ### .empty - * - * Asserts that the target's length is `0`. For arrays and strings, it checks - * the `length` property. For objects, it gets the count of - * enumerable keys. - * - * expect([]).to.be.empty; - * expect('').to.be.empty; - * expect({}).to.be.empty; - * - * @name empty - * @namespace BDD - * @api public - */ - - Assertion.addProperty('empty', function () { - var obj = flag(this, 'object') - , expected = obj; - - if (Array.isArray(obj) || 'string' === typeof object) { - expected = obj.length; - } else if (typeof obj === 'object') { - expected = Object.keys(obj).length; - } - - this.assert( - !expected - , 'expected #{this} to be empty' - , 'expected #{this} not to be empty' - ); - }); - - /** - * ### .arguments - * - * Asserts that the target is an arguments object. - * - * function test () { - * expect(arguments).to.be.arguments; - * } - * - * @name arguments - * @alias Arguments - * @namespace BDD - * @api public - */ - - function checkArguments () { - var obj = flag(this, 'object') - , type = Object.prototype.toString.call(obj); - this.assert( - '[object Arguments]' === type - , 'expected #{this} to be arguments but got ' + type - , 'expected #{this} to not be arguments' - ); - } - - Assertion.addProperty('arguments', checkArguments); - Assertion.addProperty('Arguments', checkArguments); - - /** - * ### .equal(value) - * - * Asserts that the target is strictly equal (`===`) to `value`. - * Alternately, if the `deep` flag is set, asserts that - * the target is deeply equal to `value`. - * - * expect('hello').to.equal('hello'); - * expect(42).to.equal(42); - * expect(1).to.not.equal(true); - * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); - * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); - * - * @name equal - * @alias equals - * @alias eq - * @alias deep.equal - * @param {Mixed} value - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertEqual (val, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - if (flag(this, 'deep')) { - return this.eql(val); - } else { - this.assert( - val === obj - , 'expected #{this} to equal #{exp}' - , 'expected #{this} to not equal #{exp}' - , val - , this._obj - , true - ); - } - } - - Assertion.addMethod('equal', assertEqual); - Assertion.addMethod('equals', assertEqual); - Assertion.addMethod('eq', assertEqual); - - /** - * ### .eql(value) - * - * Asserts that the target is deeply equal to `value`. - * - * expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); - * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); - * - * @name eql - * @alias eqls - * @param {Mixed} value - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertEql(obj, msg) { - if (msg) flag(this, 'message', msg); - this.assert( - _.eql(obj, flag(this, 'object')) - , 'expected #{this} to deeply equal #{exp}' - , 'expected #{this} to not deeply equal #{exp}' - , obj - , this._obj - , true - ); - } - - Assertion.addMethod('eql', assertEql); - Assertion.addMethod('eqls', assertEql); - - /** - * ### .above(value) - * - * Asserts that the target is greater than `value`. - * - * expect(10).to.be.above(5); - * - * Can also be used in conjunction with `length` to - * assert a minimum length. The benefit being a - * more informative error message than if the length - * was supplied directly. - * - * expect('foo').to.have.length.above(2); - * expect([ 1, 2, 3 ]).to.have.length.above(2); - * - * @name above - * @alias gt - * @alias greaterThan - * @param {Number} value - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertAbove (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - if (flag(this, 'doLength')) { - new Assertion(obj, msg).to.have.property('length'); - var len = obj.length; - this.assert( - len > n - , 'expected #{this} to have a length above #{exp} but got #{act}' - , 'expected #{this} to not have a length above #{exp}' - , n - , len - ); - } else { - this.assert( - obj > n - , 'expected #{this} to be above ' + n - , 'expected #{this} to be at most ' + n - ); - } - } - - Assertion.addMethod('above', assertAbove); - Assertion.addMethod('gt', assertAbove); - Assertion.addMethod('greaterThan', assertAbove); - - /** - * ### .least(value) - * - * Asserts that the target is greater than or equal to `value`. - * - * expect(10).to.be.at.least(10); - * - * Can also be used in conjunction with `length` to - * assert a minimum length. The benefit being a - * more informative error message than if the length - * was supplied directly. - * - * expect('foo').to.have.length.of.at.least(2); - * expect([ 1, 2, 3 ]).to.have.length.of.at.least(3); - * - * @name least - * @alias gte - * @param {Number} value - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertLeast (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - if (flag(this, 'doLength')) { - new Assertion(obj, msg).to.have.property('length'); - var len = obj.length; - this.assert( - len >= n - , 'expected #{this} to have a length at least #{exp} but got #{act}' - , 'expected #{this} to have a length below #{exp}' - , n - , len - ); - } else { - this.assert( - obj >= n - , 'expected #{this} to be at least ' + n - , 'expected #{this} to be below ' + n - ); - } - } - - Assertion.addMethod('least', assertLeast); - Assertion.addMethod('gte', assertLeast); - - /** - * ### .below(value) - * - * Asserts that the target is less than `value`. - * - * expect(5).to.be.below(10); - * - * Can also be used in conjunction with `length` to - * assert a maximum length. The benefit being a - * more informative error message than if the length - * was supplied directly. - * - * expect('foo').to.have.length.below(4); - * expect([ 1, 2, 3 ]).to.have.length.below(4); - * - * @name below - * @alias lt - * @alias lessThan - * @param {Number} value - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertBelow (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - if (flag(this, 'doLength')) { - new Assertion(obj, msg).to.have.property('length'); - var len = obj.length; - this.assert( - len < n - , 'expected #{this} to have a length below #{exp} but got #{act}' - , 'expected #{this} to not have a length below #{exp}' - , n - , len - ); - } else { - this.assert( - obj < n - , 'expected #{this} to be below ' + n - , 'expected #{this} to be at least ' + n - ); - } - } - - Assertion.addMethod('below', assertBelow); - Assertion.addMethod('lt', assertBelow); - Assertion.addMethod('lessThan', assertBelow); - - /** - * ### .most(value) - * - * Asserts that the target is less than or equal to `value`. - * - * expect(5).to.be.at.most(5); - * - * Can also be used in conjunction with `length` to - * assert a maximum length. The benefit being a - * more informative error message than if the length - * was supplied directly. - * - * expect('foo').to.have.length.of.at.most(4); - * expect([ 1, 2, 3 ]).to.have.length.of.at.most(3); - * - * @name most - * @alias lte - * @param {Number} value - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertMost (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - if (flag(this, 'doLength')) { - new Assertion(obj, msg).to.have.property('length'); - var len = obj.length; - this.assert( - len <= n - , 'expected #{this} to have a length at most #{exp} but got #{act}' - , 'expected #{this} to have a length above #{exp}' - , n - , len - ); - } else { - this.assert( - obj <= n - , 'expected #{this} to be at most ' + n - , 'expected #{this} to be above ' + n - ); - } - } - - Assertion.addMethod('most', assertMost); - Assertion.addMethod('lte', assertMost); - - /** - * ### .within(start, finish) - * - * Asserts that the target is within a range. - * - * expect(7).to.be.within(5,10); - * - * Can also be used in conjunction with `length` to - * assert a length range. The benefit being a - * more informative error message than if the length - * was supplied directly. - * - * expect('foo').to.have.length.within(2,4); - * expect([ 1, 2, 3 ]).to.have.length.within(2,4); - * - * @name within - * @param {Number} start lowerbound inclusive - * @param {Number} finish upperbound inclusive - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('within', function (start, finish, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , range = start + '..' + finish; - if (flag(this, 'doLength')) { - new Assertion(obj, msg).to.have.property('length'); - var len = obj.length; - this.assert( - len >= start && len <= finish - , 'expected #{this} to have a length within ' + range - , 'expected #{this} to not have a length within ' + range - ); - } else { - this.assert( - obj >= start && obj <= finish - , 'expected #{this} to be within ' + range - , 'expected #{this} to not be within ' + range - ); - } - }); - - /** - * ### .instanceof(constructor) - * - * Asserts that the target is an instance of `constructor`. - * - * var Tea = function (name) { this.name = name; } - * , Chai = new Tea('chai'); - * - * expect(Chai).to.be.an.instanceof(Tea); - * expect([ 1, 2, 3 ]).to.be.instanceof(Array); - * - * @name instanceof - * @param {Constructor} constructor - * @param {String} message _optional_ - * @alias instanceOf - * @namespace BDD - * @api public - */ - - function assertInstanceOf (constructor, msg) { - if (msg) flag(this, 'message', msg); - var name = _.getName(constructor); - this.assert( - flag(this, 'object') instanceof constructor - , 'expected #{this} to be an instance of ' + name - , 'expected #{this} to not be an instance of ' + name - ); - }; - - Assertion.addMethod('instanceof', assertInstanceOf); - Assertion.addMethod('instanceOf', assertInstanceOf); - - /** - * ### .property(name, [value]) - * - * Asserts that the target has a property `name`, optionally asserting that - * the value of that property is strictly equal to `value`. - * If the `deep` flag is set, you can use dot- and bracket-notation for deep - * references into objects and arrays. - * - * // simple referencing - * var obj = { foo: 'bar' }; - * expect(obj).to.have.property('foo'); - * expect(obj).to.have.property('foo', 'bar'); - * - * // deep referencing - * var deepObj = { - * green: { tea: 'matcha' } - * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ] - * }; - * - * expect(deepObj).to.have.deep.property('green.tea', 'matcha'); - * expect(deepObj).to.have.deep.property('teas[1]', 'matcha'); - * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha'); - * - * You can also use an array as the starting point of a `deep.property` - * assertion, or traverse nested arrays. - * - * var arr = [ - * [ 'chai', 'matcha', 'konacha' ] - * , [ { tea: 'chai' } - * , { tea: 'matcha' } - * , { tea: 'konacha' } ] - * ]; - * - * expect(arr).to.have.deep.property('[0][1]', 'matcha'); - * expect(arr).to.have.deep.property('[1][2].tea', 'konacha'); - * - * Furthermore, `property` changes the subject of the assertion - * to be the value of that property from the original object. This - * permits for further chainable assertions on that property. - * - * expect(obj).to.have.property('foo') - * .that.is.a('string'); - * expect(deepObj).to.have.property('green') - * .that.is.an('object') - * .that.deep.equals({ tea: 'matcha' }); - * expect(deepObj).to.have.property('teas') - * .that.is.an('array') - * .with.deep.property('[2]') - * .that.deep.equals({ tea: 'konacha' }); - * - * Note that dots and bracket in `name` must be backslash-escaped when - * the `deep` flag is set, while they must NOT be escaped when the `deep` - * flag is not set. - * - * // simple referencing - * var css = { '.link[target]': 42 }; - * expect(css).to.have.property('.link[target]', 42); - * - * // deep referencing - * var deepCss = { '.link': { '[target]': 42 }}; - * expect(deepCss).to.have.deep.property('\\.link.\\[target\\]', 42); - * - * @name property - * @alias deep.property - * @param {String} name - * @param {Mixed} value (optional) - * @param {String} message _optional_ - * @returns value of property for chaining - * @namespace BDD - * @api public - */ - - Assertion.addMethod('property', function (name, val, msg) { - if (msg) flag(this, 'message', msg); - - var isDeep = !!flag(this, 'deep') - , descriptor = isDeep ? 'deep property ' : 'property ' - , negate = flag(this, 'negate') - , obj = flag(this, 'object') - , pathInfo = isDeep ? _.getPathInfo(name, obj) : null - , hasProperty = isDeep - ? pathInfo.exists - : _.hasProperty(name, obj) - , value = isDeep - ? pathInfo.value - : obj[name]; - - if (negate && arguments.length > 1) { - if (undefined === value) { - msg = (msg != null) ? msg + ': ' : ''; - throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name)); - } - } else { - this.assert( - hasProperty - , 'expected #{this} to have a ' + descriptor + _.inspect(name) - , 'expected #{this} to not have ' + descriptor + _.inspect(name)); - } - - if (arguments.length > 1) { - this.assert( - val === value - , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' - , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}' - , val - , value - ); - } - - flag(this, 'object', value); - }); - - - /** - * ### .ownProperty(name) - * - * Asserts that the target has an own property `name`. - * - * expect('test').to.have.ownProperty('length'); - * - * @name ownProperty - * @alias haveOwnProperty - * @param {String} name - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertOwnProperty (name, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - this.assert( - obj.hasOwnProperty(name) - , 'expected #{this} to have own property ' + _.inspect(name) - , 'expected #{this} to not have own property ' + _.inspect(name) - ); - } - - Assertion.addMethod('ownProperty', assertOwnProperty); - Assertion.addMethod('haveOwnProperty', assertOwnProperty); - - /** - * ### .ownPropertyDescriptor(name[, descriptor[, message]]) - * - * Asserts that the target has an own property descriptor `name`, that optionally matches `descriptor`. - * - * expect('test').to.have.ownPropertyDescriptor('length'); - * expect('test').to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 }); - * expect('test').not.to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 }); - * expect('test').ownPropertyDescriptor('length').to.have.property('enumerable', false); - * expect('test').ownPropertyDescriptor('length').to.have.keys('value'); - * - * @name ownPropertyDescriptor - * @alias haveOwnPropertyDescriptor - * @param {String} name - * @param {Object} descriptor _optional_ - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertOwnPropertyDescriptor (name, descriptor, msg) { - if (typeof descriptor === 'string') { - msg = descriptor; - descriptor = null; - } - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); - if (actualDescriptor && descriptor) { - this.assert( - _.eql(descriptor, actualDescriptor) - , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) - , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) - , descriptor - , actualDescriptor - , true - ); - } else { - this.assert( - actualDescriptor - , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) - , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) - ); - } - flag(this, 'object', actualDescriptor); - } - - Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); - Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); - - /** - * ### .length - * - * Sets the `doLength` flag later used as a chain precursor to a value - * comparison for the `length` property. - * - * expect('foo').to.have.length.above(2); - * expect([ 1, 2, 3 ]).to.have.length.above(2); - * expect('foo').to.have.length.below(4); - * expect([ 1, 2, 3 ]).to.have.length.below(4); - * expect('foo').to.have.length.within(2,4); - * expect([ 1, 2, 3 ]).to.have.length.within(2,4); - * - * *Deprecation notice:* Using `length` as an assertion will be deprecated - * in version 2.4.0 and removed in 3.0.0. Code using the old style of - * asserting for `length` property value using `length(value)` should be - * switched to use `lengthOf(value)` instead. - * - * @name length - * @namespace BDD - * @api public - */ - - /** - * ### .lengthOf(value[, message]) - * - * Asserts that the target's `length` property has - * the expected value. - * - * expect([ 1, 2, 3]).to.have.lengthOf(3); - * expect('foobar').to.have.lengthOf(6); - * - * @name lengthOf - * @param {Number} length - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertLengthChain () { - flag(this, 'doLength', true); - } - - function assertLength (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - new Assertion(obj, msg).to.have.property('length'); - var len = obj.length; - - this.assert( - len == n - , 'expected #{this} to have a length of #{exp} but got #{act}' - , 'expected #{this} to not have a length of #{act}' - , n - , len - ); - } - - Assertion.addChainableMethod('length', assertLength, assertLengthChain); - Assertion.addMethod('lengthOf', assertLength); - - /** - * ### .match(regexp) - * - * Asserts that the target matches a regular expression. - * - * expect('foobar').to.match(/^foo/); - * - * @name match - * @alias matches - * @param {RegExp} RegularExpression - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - function assertMatch(re, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - this.assert( - re.exec(obj) - , 'expected #{this} to match ' + re - , 'expected #{this} not to match ' + re - ); - } - - Assertion.addMethod('match', assertMatch); - Assertion.addMethod('matches', assertMatch); - - /** - * ### .string(string) - * - * Asserts that the string target contains another string. - * - * expect('foobar').to.have.string('bar'); - * - * @name string - * @param {String} string - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('string', function (str, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - new Assertion(obj, msg).is.a('string'); - - this.assert( - ~obj.indexOf(str) - , 'expected #{this} to contain ' + _.inspect(str) - , 'expected #{this} to not contain ' + _.inspect(str) - ); - }); - - - /** - * ### .keys(key1, [key2], [...]) - * - * Asserts that the target contains any or all of the passed-in keys. - * Use in combination with `any`, `all`, `contains`, or `have` will affect - * what will pass. - * - * When used in conjunction with `any`, at least one key that is passed - * in must exist in the target object. This is regardless whether or not - * the `have` or `contain` qualifiers are used. Note, either `any` or `all` - * should be used in the assertion. If neither are used, the assertion is - * defaulted to `all`. - * - * When both `all` and `contain` are used, the target object must have at - * least all of the passed-in keys but may have more keys not listed. - * - * When both `all` and `have` are used, the target object must both contain - * all of the passed-in keys AND the number of keys in the target object must - * match the number of keys passed in (in other words, a target object must - * have all and only all of the passed-in keys). - * - * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo', 'baz'); - * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo'); - * expect({ foo: 1, bar: 2 }).to.contain.any.keys('bar', 'baz'); - * expect({ foo: 1, bar: 2 }).to.contain.any.keys(['foo']); - * expect({ foo: 1, bar: 2 }).to.contain.any.keys({'foo': 6}); - * expect({ foo: 1, bar: 2 }).to.have.all.keys(['bar', 'foo']); - * expect({ foo: 1, bar: 2 }).to.have.all.keys({'bar': 6, 'foo': 7}); - * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys(['bar', 'foo']); - * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys({'bar': 6}); - * - * - * @name keys - * @alias key - * @param {...String|Array|Object} keys - * @namespace BDD - * @api public - */ - - function assertKeys (keys) { - var obj = flag(this, 'object') - , str - , ok = true - , mixedArgsMsg = 'keys must be given single argument of Array|Object|String, or multiple String arguments'; - - switch (_.type(keys)) { - case "array": - if (arguments.length > 1) throw (new Error(mixedArgsMsg)); - break; - case "object": - if (arguments.length > 1) throw (new Error(mixedArgsMsg)); - keys = Object.keys(keys); - break; - default: - keys = Array.prototype.slice.call(arguments); - } - - if (!keys.length) throw new Error('keys required'); - - var actual = Object.keys(obj) - , expected = keys - , len = keys.length - , any = flag(this, 'any') - , all = flag(this, 'all'); - - if (!any && !all) { - all = true; - } - - // Has any - if (any) { - var intersection = expected.filter(function(key) { - return ~actual.indexOf(key); - }); - ok = intersection.length > 0; - } - - // Has all - if (all) { - ok = keys.every(function(key){ - return ~actual.indexOf(key); - }); - if (!flag(this, 'negate') && !flag(this, 'contains')) { - ok = ok && keys.length == actual.length; - } - } - - // Key string - if (len > 1) { - keys = keys.map(function(key){ - return _.inspect(key); - }); - var last = keys.pop(); - if (all) { - str = keys.join(', ') + ', and ' + last; - } - if (any) { - str = keys.join(', ') + ', or ' + last; - } - } else { - str = _.inspect(keys[0]); - } - - // Form - str = (len > 1 ? 'keys ' : 'key ') + str; - - // Have / include - str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; - - // Assertion - this.assert( - ok - , 'expected #{this} to ' + str - , 'expected #{this} to not ' + str - , expected.slice(0).sort() - , actual.sort() - , true - ); - } - - Assertion.addMethod('keys', assertKeys); - Assertion.addMethod('key', assertKeys); - - /** - * ### .throw(constructor) - * - * Asserts that the function target will throw a specific error, or specific type of error - * (as determined using `instanceof`), optionally with a RegExp or string inclusion test - * for the error's message. - * - * var err = new ReferenceError('This is a bad function.'); - * var fn = function () { throw err; } - * expect(fn).to.throw(ReferenceError); - * expect(fn).to.throw(Error); - * expect(fn).to.throw(/bad function/); - * expect(fn).to.not.throw('good function'); - * expect(fn).to.throw(ReferenceError, /bad function/); - * expect(fn).to.throw(err); - * - * Please note that when a throw expectation is negated, it will check each - * parameter independently, starting with error constructor type. The appropriate way - * to check for the existence of a type of error but for a message that does not match - * is to use `and`. - * - * expect(fn).to.throw(ReferenceError) - * .and.not.throw(/good function/); - * - * @name throw - * @alias throws - * @alias Throw - * @param {ErrorConstructor} constructor - * @param {String|RegExp} expected error message - * @param {String} message _optional_ - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @returns error for chaining (null if no error) - * @namespace BDD - * @api public - */ - - function assertThrows (constructor, errMsg, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - new Assertion(obj, msg).is.a('function'); - - var thrown = false - , desiredError = null - , name = null - , thrownError = null; - - if (arguments.length === 0) { - errMsg = null; - constructor = null; - } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) { - errMsg = constructor; - constructor = null; - } else if (constructor && constructor instanceof Error) { - desiredError = constructor; - constructor = null; - errMsg = null; - } else if (typeof constructor === 'function') { - name = constructor.prototype.name; - if (!name || (name === 'Error' && constructor !== Error)) { - name = constructor.name || (new constructor()).name; - } - } else { - constructor = null; - } - - try { - obj(); - } catch (err) { - // first, check desired error - if (desiredError) { - this.assert( - err === desiredError - , 'expected #{this} to throw #{exp} but #{act} was thrown' - , 'expected #{this} to not throw #{exp}' - , (desiredError instanceof Error ? desiredError.toString() : desiredError) - , (err instanceof Error ? err.toString() : err) - ); - - flag(this, 'object', err); - return this; - } - - // next, check constructor - if (constructor) { - this.assert( - err instanceof constructor - , 'expected #{this} to throw #{exp} but #{act} was thrown' - , 'expected #{this} to not throw #{exp} but #{act} was thrown' - , name - , (err instanceof Error ? err.toString() : err) - ); - - if (!errMsg) { - flag(this, 'object', err); - return this; - } - } - - // next, check message - var message = 'error' === _.type(err) && "message" in err - ? err.message - : '' + err; - - if ((message != null) && errMsg && errMsg instanceof RegExp) { - this.assert( - errMsg.exec(message) - , 'expected #{this} to throw error matching #{exp} but got #{act}' - , 'expected #{this} to throw error not matching #{exp}' - , errMsg - , message - ); - - flag(this, 'object', err); - return this; - } else if ((message != null) && errMsg && 'string' === typeof errMsg) { - this.assert( - ~message.indexOf(errMsg) - , 'expected #{this} to throw error including #{exp} but got #{act}' - , 'expected #{this} to throw error not including #{act}' - , errMsg - , message - ); - - flag(this, 'object', err); - return this; - } else { - thrown = true; - thrownError = err; - } - } - - var actuallyGot = '' - , expectedThrown = name !== null - ? name - : desiredError - ? '#{exp}' //_.inspect(desiredError) - : 'an error'; - - if (thrown) { - actuallyGot = ' but #{act} was thrown' - } - - this.assert( - thrown === true - , 'expected #{this} to throw ' + expectedThrown + actuallyGot - , 'expected #{this} to not throw ' + expectedThrown + actuallyGot - , (desiredError instanceof Error ? desiredError.toString() : desiredError) - , (thrownError instanceof Error ? thrownError.toString() : thrownError) - ); - - flag(this, 'object', thrownError); - }; - - Assertion.addMethod('throw', assertThrows); - Assertion.addMethod('throws', assertThrows); - Assertion.addMethod('Throw', assertThrows); - - /** - * ### .respondTo(method) - * - * Asserts that the object or class target will respond to a method. - * - * Klass.prototype.bar = function(){}; - * expect(Klass).to.respondTo('bar'); - * expect(obj).to.respondTo('bar'); - * - * To check if a constructor will respond to a static function, - * set the `itself` flag. - * - * Klass.baz = function(){}; - * expect(Klass).itself.to.respondTo('baz'); - * - * @name respondTo - * @alias respondsTo - * @param {String} method - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function respondTo (method, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , itself = flag(this, 'itself') - , context = ('function' === _.type(obj) && !itself) - ? obj.prototype[method] - : obj[method]; - - this.assert( - 'function' === typeof context - , 'expected #{this} to respond to ' + _.inspect(method) - , 'expected #{this} to not respond to ' + _.inspect(method) - ); - } - - Assertion.addMethod('respondTo', respondTo); - Assertion.addMethod('respondsTo', respondTo); - - /** - * ### .itself - * - * Sets the `itself` flag, later used by the `respondTo` assertion. - * - * function Foo() {} - * Foo.bar = function() {} - * Foo.prototype.baz = function() {} - * - * expect(Foo).itself.to.respondTo('bar'); - * expect(Foo).itself.not.to.respondTo('baz'); - * - * @name itself - * @namespace BDD - * @api public - */ - - Assertion.addProperty('itself', function () { - flag(this, 'itself', true); - }); - - /** - * ### .satisfy(method) - * - * Asserts that the target passes a given truth test. - * - * expect(1).to.satisfy(function(num) { return num > 0; }); - * - * @name satisfy - * @alias satisfies - * @param {Function} matcher - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function satisfy (matcher, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - var result = matcher(obj); - this.assert( - result - , 'expected #{this} to satisfy ' + _.objDisplay(matcher) - , 'expected #{this} to not satisfy' + _.objDisplay(matcher) - , this.negate ? false : true - , result - ); - } - - Assertion.addMethod('satisfy', satisfy); - Assertion.addMethod('satisfies', satisfy); - - /** - * ### .closeTo(expected, delta) - * - * Asserts that the target is equal `expected`, to within a +/- `delta` range. - * - * expect(1.5).to.be.closeTo(1, 0.5); - * - * @name closeTo - * @alias approximately - * @param {Number} expected - * @param {Number} delta - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function closeTo(expected, delta, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - - new Assertion(obj, msg).is.a('number'); - if (_.type(expected) !== 'number' || _.type(delta) !== 'number') { - throw new Error('the arguments to closeTo or approximately must be numbers'); - } - - this.assert( - Math.abs(obj - expected) <= delta - , 'expected #{this} to be close to ' + expected + ' +/- ' + delta - , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta - ); - } - - Assertion.addMethod('closeTo', closeTo); - Assertion.addMethod('approximately', closeTo); - - function isSubsetOf(subset, superset, cmp) { - return subset.every(function(elem) { - if (!cmp) return superset.indexOf(elem) !== -1; - - return superset.some(function(elem2) { - return cmp(elem, elem2); - }); - }) - } - - /** - * ### .members(set) - * - * Asserts that the target is a superset of `set`, - * or that the target and `set` have the same strictly-equal (===) members. - * Alternately, if the `deep` flag is set, set members are compared for deep - * equality. - * - * expect([1, 2, 3]).to.include.members([3, 2]); - * expect([1, 2, 3]).to.not.include.members([3, 2, 8]); - * - * expect([4, 2]).to.have.members([2, 4]); - * expect([5, 2]).to.not.have.members([5, 2, 1]); - * - * expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }]); - * - * @name members - * @param {Array} set - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('members', function (subset, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - - new Assertion(obj).to.be.an('array'); - new Assertion(subset).to.be.an('array'); - - var cmp = flag(this, 'deep') ? _.eql : undefined; - - if (flag(this, 'contains')) { - return this.assert( - isSubsetOf(subset, obj, cmp) - , 'expected #{this} to be a superset of #{act}' - , 'expected #{this} to not be a superset of #{act}' - , obj - , subset - ); - } - - this.assert( - isSubsetOf(obj, subset, cmp) && isSubsetOf(subset, obj, cmp) - , 'expected #{this} to have the same members as #{act}' - , 'expected #{this} to not have the same members as #{act}' - , obj - , subset - ); - }); - - /** - * ### .oneOf(list) - * - * Assert that a value appears somewhere in the top level of array `list`. - * - * expect('a').to.be.oneOf(['a', 'b', 'c']); - * expect(9).to.not.be.oneOf(['z']); - * expect([3]).to.not.be.oneOf([1, 2, [3]]); - * - * var three = [3]; - * // for object-types, contents are not compared - * expect(three).to.not.be.oneOf([1, 2, [3]]); - * // comparing references works - * expect(three).to.be.oneOf([1, 2, three]); - * - * @name oneOf - * @param {Array<*>} list - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function oneOf (list, msg) { - if (msg) flag(this, 'message', msg); - var expected = flag(this, 'object'); - new Assertion(list).to.be.an('array'); - - this.assert( - list.indexOf(expected) > -1 - , 'expected #{this} to be one of #{exp}' - , 'expected #{this} to not be one of #{exp}' - , list - , expected - ); - } - - Assertion.addMethod('oneOf', oneOf); - - - /** - * ### .change(function) - * - * Asserts that a function changes an object property - * - * var obj = { val: 10 }; - * var fn = function() { obj.val += 3 }; - * var noChangeFn = function() { return 'foo' + 'bar'; } - * expect(fn).to.change(obj, 'val'); - * expect(noChangeFn).to.not.change(obj, 'val') - * - * @name change - * @alias changes - * @alias Change - * @param {String} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertChanges (object, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object'); - new Assertion(object, msg).to.have.property(prop); - new Assertion(fn).is.a('function'); - - var initial = object[prop]; - fn(); - - this.assert( - initial !== object[prop] - , 'expected .' + prop + ' to change' - , 'expected .' + prop + ' to not change' - ); - } - - Assertion.addChainableMethod('change', assertChanges); - Assertion.addChainableMethod('changes', assertChanges); - - /** - * ### .increase(function) - * - * Asserts that a function increases an object property - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 15 }; - * expect(fn).to.increase(obj, 'val'); - * - * @name increase - * @alias increases - * @alias Increase - * @param {String} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertIncreases (object, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object'); - new Assertion(object, msg).to.have.property(prop); - new Assertion(fn).is.a('function'); - - var initial = object[prop]; - fn(); - - this.assert( - object[prop] - initial > 0 - , 'expected .' + prop + ' to increase' - , 'expected .' + prop + ' to not increase' - ); - } - - Assertion.addChainableMethod('increase', assertIncreases); - Assertion.addChainableMethod('increases', assertIncreases); - - /** - * ### .decrease(function) - * - * Asserts that a function decreases an object property - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 5 }; - * expect(fn).to.decrease(obj, 'val'); - * - * @name decrease - * @alias decreases - * @alias Decrease - * @param {String} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace BDD - * @api public - */ - - function assertDecreases (object, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object'); - new Assertion(object, msg).to.have.property(prop); - new Assertion(fn).is.a('function'); - - var initial = object[prop]; - fn(); - - this.assert( - object[prop] - initial < 0 - , 'expected .' + prop + ' to decrease' - , 'expected .' + prop + ' to not decrease' - ); - } - - Assertion.addChainableMethod('decrease', assertDecreases); - Assertion.addChainableMethod('decreases', assertDecreases); - - /** - * ### .extensible - * - * Asserts that the target is extensible (can have new properties added to - * it). - * - * var nonExtensibleObject = Object.preventExtensions({}); - * var sealedObject = Object.seal({}); - * var frozenObject = Object.freeze({}); - * - * expect({}).to.be.extensible; - * expect(nonExtensibleObject).to.not.be.extensible; - * expect(sealedObject).to.not.be.extensible; - * expect(frozenObject).to.not.be.extensible; - * - * @name extensible - * @namespace BDD - * @api public - */ - - Assertion.addProperty('extensible', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible - // The following provides ES6 behavior when a TypeError is thrown under ES5. - - var isExtensible; - - try { - isExtensible = Object.isExtensible(obj); - } catch (err) { - if (err instanceof TypeError) isExtensible = false; - else throw err; - } - - this.assert( - isExtensible - , 'expected #{this} to be extensible' - , 'expected #{this} to not be extensible' - ); - }); - - /** - * ### .sealed - * - * Asserts that the target is sealed (cannot have new properties added to it - * and its existing properties cannot be removed). - * - * var sealedObject = Object.seal({}); - * var frozenObject = Object.freeze({}); - * - * expect(sealedObject).to.be.sealed; - * expect(frozenObject).to.be.sealed; - * expect({}).to.not.be.sealed; - * - * @name sealed - * @namespace BDD - * @api public - */ - - Assertion.addProperty('sealed', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed - // The following provides ES6 behavior when a TypeError is thrown under ES5. - - var isSealed; - - try { - isSealed = Object.isSealed(obj); - } catch (err) { - if (err instanceof TypeError) isSealed = true; - else throw err; - } - - this.assert( - isSealed - , 'expected #{this} to be sealed' - , 'expected #{this} to not be sealed' - ); - }); - - /** - * ### .frozen - * - * Asserts that the target is frozen (cannot have new properties added to it - * and its existing properties cannot be modified). - * - * var frozenObject = Object.freeze({}); - * - * expect(frozenObject).to.be.frozen; - * expect({}).to.not.be.frozen; - * - * @name frozen - * @namespace BDD - * @api public - */ - - Assertion.addProperty('frozen', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen - // The following provides ES6 behavior when a TypeError is thrown under ES5. - - var isFrozen; - - try { - isFrozen = Object.isFrozen(obj); - } catch (err) { - if (err instanceof TypeError) isFrozen = true; - else throw err; - } - - this.assert( - isFrozen - , 'expected #{this} to be frozen' - , 'expected #{this} to not be frozen' - ); - }); -}; - -},{}],17:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - - -module.exports = function (chai, util) { - - /*! - * Chai dependencies. - */ - - var Assertion = chai.Assertion - , flag = util.flag; - - /*! - * Module export. - */ - - /** - * ### assert(expression, message) - * - * Write your own test expressions. - * - * assert('foo' !== 'bar', 'foo is not bar'); - * assert(Array.isArray([]), 'empty arrays are arrays'); - * - * @param {Mixed} expression to test for truthiness - * @param {String} message to display on error - * @name assert - * @namespace Assert - * @api public - */ - - var assert = chai.assert = function (express, errmsg) { - var test = new Assertion(null, null, chai.assert); - test.assert( - express - , errmsg - , '[ negation message unavailable ]' - ); - }; - - /** - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. Node.js `assert` module-compatible. - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace Assert - * @api public - */ - - assert.fail = function (actual, expected, message, operator) { - message = message || 'assert.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, assert.fail); - }; - - /** - * ### .isOk(object, [message]) - * - * Asserts that `object` is truthy. - * - * assert.isOk('everything', 'everything is ok'); - * assert.isOk(false, 'this will fail'); - * - * @name isOk - * @alias ok - * @param {Mixed} object to test - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isOk = function (val, msg) { - new Assertion(val, msg).is.ok; - }; - - /** - * ### .isNotOk(object, [message]) - * - * Asserts that `object` is falsy. - * - * assert.isNotOk('everything', 'this will fail'); - * assert.isNotOk(false, 'this will pass'); - * - * @name isNotOk - * @alias notOk - * @param {Mixed} object to test - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotOk = function (val, msg) { - new Assertion(val, msg).is.not.ok; - }; - - /** - * ### .equal(actual, expected, [message]) - * - * Asserts non-strict equality (`==`) of `actual` and `expected`. - * - * assert.equal(3, '3', '== coerces values to strings'); - * - * @name equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.equal = function (act, exp, msg) { - var test = new Assertion(act, msg, assert.equal); - - test.assert( - exp == flag(test, 'object') - , 'expected #{this} to equal #{exp}' - , 'expected #{this} to not equal #{act}' - , exp - , act - ); - }; - - /** - * ### .notEqual(actual, expected, [message]) - * - * Asserts non-strict inequality (`!=`) of `actual` and `expected`. - * - * assert.notEqual(3, 4, 'these numbers are not equal'); - * - * @name notEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notEqual = function (act, exp, msg) { - var test = new Assertion(act, msg, assert.notEqual); - - test.assert( - exp != flag(test, 'object') - , 'expected #{this} to not equal #{exp}' - , 'expected #{this} to equal #{act}' - , exp - , act - ); - }; - - /** - * ### .strictEqual(actual, expected, [message]) - * - * Asserts strict equality (`===`) of `actual` and `expected`. - * - * assert.strictEqual(true, true, 'these booleans are strictly equal'); - * - * @name strictEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.strictEqual = function (act, exp, msg) { - new Assertion(act, msg).to.equal(exp); - }; - - /** - * ### .notStrictEqual(actual, expected, [message]) - * - * Asserts strict inequality (`!==`) of `actual` and `expected`. - * - * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); - * - * @name notStrictEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notStrictEqual = function (act, exp, msg) { - new Assertion(act, msg).to.not.equal(exp); - }; - - /** - * ### .deepEqual(actual, expected, [message]) - * - * Asserts that `actual` is deeply equal to `expected`. - * - * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); - * - * @name deepEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepEqual = function (act, exp, msg) { - new Assertion(act, msg).to.eql(exp); - }; - - /** - * ### .notDeepEqual(actual, expected, [message]) - * - * Assert that `actual` is not deeply equal to `expected`. - * - * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); - * - * @name notDeepEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepEqual = function (act, exp, msg) { - new Assertion(act, msg).to.not.eql(exp); - }; - - /** - * ### .isAbove(valueToCheck, valueToBeAbove, [message]) - * - * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove` - * - * assert.isAbove(5, 2, '5 is strictly greater than 2'); - * - * @name isAbove - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAbove - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAbove = function (val, abv, msg) { - new Assertion(val, msg).to.be.above(abv); - }; - - /** - * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) - * - * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast` - * - * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); - * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); - * - * @name isAtLeast - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAtLeast - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAtLeast = function (val, atlst, msg) { - new Assertion(val, msg).to.be.least(atlst); - }; - - /** - * ### .isBelow(valueToCheck, valueToBeBelow, [message]) - * - * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow` - * - * assert.isBelow(3, 6, '3 is strictly less than 6'); - * - * @name isBelow - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeBelow - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isBelow = function (val, blw, msg) { - new Assertion(val, msg).to.be.below(blw); - }; - - /** - * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) - * - * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost` - * - * assert.isAtMost(3, 6, '3 is less than or equal to 6'); - * assert.isAtMost(4, 4, '4 is less than or equal to 4'); - * - * @name isAtMost - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAtMost - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAtMost = function (val, atmst, msg) { - new Assertion(val, msg).to.be.most(atmst); - }; - - /** - * ### .isTrue(value, [message]) - * - * Asserts that `value` is true. - * - * var teaServed = true; - * assert.isTrue(teaServed, 'the tea has been served'); - * - * @name isTrue - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isTrue = function (val, msg) { - new Assertion(val, msg).is['true']; - }; - - /** - * ### .isNotTrue(value, [message]) - * - * Asserts that `value` is not true. - * - * var tea = 'tasty chai'; - * assert.isNotTrue(tea, 'great, time for tea!'); - * - * @name isNotTrue - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotTrue = function (val, msg) { - new Assertion(val, msg).to.not.equal(true); - }; - - /** - * ### .isFalse(value, [message]) - * - * Asserts that `value` is false. - * - * var teaServed = false; - * assert.isFalse(teaServed, 'no tea yet? hmm...'); - * - * @name isFalse - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isFalse = function (val, msg) { - new Assertion(val, msg).is['false']; - }; - - /** - * ### .isNotFalse(value, [message]) - * - * Asserts that `value` is not false. - * - * var tea = 'tasty chai'; - * assert.isNotFalse(tea, 'great, time for tea!'); - * - * @name isNotFalse - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotFalse = function (val, msg) { - new Assertion(val, msg).to.not.equal(false); - }; - - /** - * ### .isNull(value, [message]) - * - * Asserts that `value` is null. - * - * assert.isNull(err, 'there was no error'); - * - * @name isNull - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNull = function (val, msg) { - new Assertion(val, msg).to.equal(null); - }; - - /** - * ### .isNotNull(value, [message]) - * - * Asserts that `value` is not null. - * - * var tea = 'tasty chai'; - * assert.isNotNull(tea, 'great, time for tea!'); - * - * @name isNotNull - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotNull = function (val, msg) { - new Assertion(val, msg).to.not.equal(null); - }; - - /** - * ### .isNaN - * Asserts that value is NaN - * - * assert.isNaN('foo', 'foo is NaN'); - * - * @name isNaN - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNaN = function (val, msg) { - new Assertion(val, msg).to.be.NaN; - }; - - /** - * ### .isNotNaN - * Asserts that value is not NaN - * - * assert.isNotNaN(4, '4 is not NaN'); - * - * @name isNotNaN - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - assert.isNotNaN = function (val, msg) { - new Assertion(val, msg).not.to.be.NaN; - }; - - /** - * ### .isUndefined(value, [message]) - * - * Asserts that `value` is `undefined`. - * - * var tea; - * assert.isUndefined(tea, 'no tea defined'); - * - * @name isUndefined - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isUndefined = function (val, msg) { - new Assertion(val, msg).to.equal(undefined); - }; - - /** - * ### .isDefined(value, [message]) - * - * Asserts that `value` is not `undefined`. - * - * var tea = 'cup of chai'; - * assert.isDefined(tea, 'tea has been defined'); - * - * @name isDefined - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isDefined = function (val, msg) { - new Assertion(val, msg).to.not.equal(undefined); - }; - - /** - * ### .isFunction(value, [message]) - * - * Asserts that `value` is a function. - * - * function serveTea() { return 'cup of tea'; }; - * assert.isFunction(serveTea, 'great, we can have tea now'); - * - * @name isFunction - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isFunction = function (val, msg) { - new Assertion(val, msg).to.be.a('function'); - }; - - /** - * ### .isNotFunction(value, [message]) - * - * Asserts that `value` is _not_ a function. - * - * var serveTea = [ 'heat', 'pour', 'sip' ]; - * assert.isNotFunction(serveTea, 'great, we have listed the steps'); - * - * @name isNotFunction - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotFunction = function (val, msg) { - new Assertion(val, msg).to.not.be.a('function'); - }; - - /** - * ### .isObject(value, [message]) - * - * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). - * _The assertion does not match subclassed objects._ - * - * var selection = { name: 'Chai', serve: 'with spices' }; - * assert.isObject(selection, 'tea selection is an object'); - * - * @name isObject - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isObject = function (val, msg) { - new Assertion(val, msg).to.be.a('object'); - }; - - /** - * ### .isNotObject(value, [message]) - * - * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). - * - * var selection = 'chai' - * assert.isNotObject(selection, 'tea selection is not an object'); - * assert.isNotObject(null, 'null is not an object'); - * - * @name isNotObject - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotObject = function (val, msg) { - new Assertion(val, msg).to.not.be.a('object'); - }; - - /** - * ### .isArray(value, [message]) - * - * Asserts that `value` is an array. - * - * var menu = [ 'green', 'chai', 'oolong' ]; - * assert.isArray(menu, 'what kind of tea do we want?'); - * - * @name isArray - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isArray = function (val, msg) { - new Assertion(val, msg).to.be.an('array'); - }; - - /** - * ### .isNotArray(value, [message]) - * - * Asserts that `value` is _not_ an array. - * - * var menu = 'green|chai|oolong'; - * assert.isNotArray(menu, 'what kind of tea do we want?'); - * - * @name isNotArray - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotArray = function (val, msg) { - new Assertion(val, msg).to.not.be.an('array'); - }; - - /** - * ### .isString(value, [message]) - * - * Asserts that `value` is a string. - * - * var teaOrder = 'chai'; - * assert.isString(teaOrder, 'order placed'); - * - * @name isString - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isString = function (val, msg) { - new Assertion(val, msg).to.be.a('string'); - }; - - /** - * ### .isNotString(value, [message]) - * - * Asserts that `value` is _not_ a string. - * - * var teaOrder = 4; - * assert.isNotString(teaOrder, 'order placed'); - * - * @name isNotString - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotString = function (val, msg) { - new Assertion(val, msg).to.not.be.a('string'); - }; - - /** - * ### .isNumber(value, [message]) - * - * Asserts that `value` is a number. - * - * var cups = 2; - * assert.isNumber(cups, 'how many cups'); - * - * @name isNumber - * @param {Number} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNumber = function (val, msg) { - new Assertion(val, msg).to.be.a('number'); - }; - - /** - * ### .isNotNumber(value, [message]) - * - * Asserts that `value` is _not_ a number. - * - * var cups = '2 cups please'; - * assert.isNotNumber(cups, 'how many cups'); - * - * @name isNotNumber - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotNumber = function (val, msg) { - new Assertion(val, msg).to.not.be.a('number'); - }; - - /** - * ### .isBoolean(value, [message]) - * - * Asserts that `value` is a boolean. - * - * var teaReady = true - * , teaServed = false; - * - * assert.isBoolean(teaReady, 'is the tea ready'); - * assert.isBoolean(teaServed, 'has tea been served'); - * - * @name isBoolean - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isBoolean = function (val, msg) { - new Assertion(val, msg).to.be.a('boolean'); - }; - - /** - * ### .isNotBoolean(value, [message]) - * - * Asserts that `value` is _not_ a boolean. - * - * var teaReady = 'yep' - * , teaServed = 'nope'; - * - * assert.isNotBoolean(teaReady, 'is the tea ready'); - * assert.isNotBoolean(teaServed, 'has tea been served'); - * - * @name isNotBoolean - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotBoolean = function (val, msg) { - new Assertion(val, msg).to.not.be.a('boolean'); - }; - - /** - * ### .typeOf(value, name, [message]) - * - * Asserts that `value`'s type is `name`, as determined by - * `Object.prototype.toString`. - * - * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); - * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); - * assert.typeOf('tea', 'string', 'we have a string'); - * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); - * assert.typeOf(null, 'null', 'we have a null'); - * assert.typeOf(undefined, 'undefined', 'we have an undefined'); - * - * @name typeOf - * @param {Mixed} value - * @param {String} name - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.typeOf = function (val, type, msg) { - new Assertion(val, msg).to.be.a(type); - }; - - /** - * ### .notTypeOf(value, name, [message]) - * - * Asserts that `value`'s type is _not_ `name`, as determined by - * `Object.prototype.toString`. - * - * assert.notTypeOf('tea', 'number', 'strings are not numbers'); - * - * @name notTypeOf - * @param {Mixed} value - * @param {String} typeof name - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notTypeOf = function (val, type, msg) { - new Assertion(val, msg).to.not.be.a(type); - }; - - /** - * ### .instanceOf(object, constructor, [message]) - * - * Asserts that `value` is an instance of `constructor`. - * - * var Tea = function (name) { this.name = name; } - * , chai = new Tea('chai'); - * - * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); - * - * @name instanceOf - * @param {Object} object - * @param {Constructor} constructor - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.instanceOf = function (val, type, msg) { - new Assertion(val, msg).to.be.instanceOf(type); - }; - - /** - * ### .notInstanceOf(object, constructor, [message]) - * - * Asserts `value` is not an instance of `constructor`. - * - * var Tea = function (name) { this.name = name; } - * , chai = new String('chai'); - * - * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); - * - * @name notInstanceOf - * @param {Object} object - * @param {Constructor} constructor - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notInstanceOf = function (val, type, msg) { - new Assertion(val, msg).to.not.be.instanceOf(type); - }; - - /** - * ### .include(haystack, needle, [message]) - * - * Asserts that `haystack` includes `needle`. Works - * for strings and arrays. - * - * assert.include('foobar', 'bar', 'foobar contains string "bar"'); - * assert.include([ 1, 2, 3 ], 3, 'array contains value'); - * - * @name include - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.include = function (exp, inc, msg) { - new Assertion(exp, msg, assert.include).include(inc); - }; - - /** - * ### .notInclude(haystack, needle, [message]) - * - * Asserts that `haystack` does not include `needle`. Works - * for strings and arrays. - * - * assert.notInclude('foobar', 'baz', 'string not include substring'); - * assert.notInclude([ 1, 2, 3 ], 4, 'array not include contain value'); - * - * @name notInclude - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.notInclude).not.include(inc); - }; - - /** - * ### .match(value, regexp, [message]) - * - * Asserts that `value` matches the regular expression `regexp`. - * - * assert.match('foobar', /^foo/, 'regexp matches'); - * - * @name match - * @param {Mixed} value - * @param {RegExp} regexp - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.match = function (exp, re, msg) { - new Assertion(exp, msg).to.match(re); - }; - - /** - * ### .notMatch(value, regexp, [message]) - * - * Asserts that `value` does not match the regular expression `regexp`. - * - * assert.notMatch('foobar', /^foo/, 'regexp does not match'); - * - * @name notMatch - * @param {Mixed} value - * @param {RegExp} regexp - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notMatch = function (exp, re, msg) { - new Assertion(exp, msg).to.not.match(re); - }; - - /** - * ### .property(object, property, [message]) - * - * Asserts that `object` has a property named by `property`. - * - * assert.property({ tea: { green: 'matcha' }}, 'tea'); - * - * @name property - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.property = function (obj, prop, msg) { - new Assertion(obj, msg).to.have.property(prop); - }; - - /** - * ### .notProperty(object, property, [message]) - * - * Asserts that `object` does _not_ have a property named by `property`. - * - * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); - * - * @name notProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notProperty = function (obj, prop, msg) { - new Assertion(obj, msg).to.not.have.property(prop); - }; - - /** - * ### .deepProperty(object, property, [message]) - * - * Asserts that `object` has a property named by `property`, which can be a - * string using dot- and bracket-notation for deep reference. - * - * assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green'); - * - * @name deepProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepProperty = function (obj, prop, msg) { - new Assertion(obj, msg).to.have.deep.property(prop); - }; - - /** - * ### .notDeepProperty(object, property, [message]) - * - * Asserts that `object` does _not_ have a property named by `property`, which - * can be a string using dot- and bracket-notation for deep reference. - * - * assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); - * - * @name notDeepProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepProperty = function (obj, prop, msg) { - new Assertion(obj, msg).to.not.have.deep.property(prop); - }; - - /** - * ### .propertyVal(object, property, value, [message]) - * - * Asserts that `object` has a property named by `property` with value given - * by `value`. - * - * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); - * - * @name propertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.propertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg).to.have.property(prop, val); - }; - - /** - * ### .propertyNotVal(object, property, value, [message]) - * - * Asserts that `object` has a property named by `property`, but with a value - * different from that given by `value`. - * - * assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad'); - * - * @name propertyNotVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.propertyNotVal = function (obj, prop, val, msg) { - new Assertion(obj, msg).to.not.have.property(prop, val); - }; - - /** - * ### .deepPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a property named by `property` with value given - * by `value`. `property` can use dot- and bracket-notation for deep - * reference. - * - * assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); - * - * @name deepPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg).to.have.deep.property(prop, val); - }; - - /** - * ### .deepPropertyNotVal(object, property, value, [message]) - * - * Asserts that `object` has a property named by `property`, but with a value - * different from that given by `value`. `property` can use dot- and - * bracket-notation for deep reference. - * - * assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); - * - * @name deepPropertyNotVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepPropertyNotVal = function (obj, prop, val, msg) { - new Assertion(obj, msg).to.not.have.deep.property(prop, val); - }; - - /** - * ### .lengthOf(object, length, [message]) - * - * Asserts that `object` has a `length` property with the expected value. - * - * assert.lengthOf([1,2,3], 3, 'array has length of 3'); - * assert.lengthOf('foobar', 6, 'string has length of 6'); - * - * @name lengthOf - * @param {Mixed} object - * @param {Number} length - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.lengthOf = function (exp, len, msg) { - new Assertion(exp, msg).to.have.length(len); - }; - - /** - * ### .throws(function, [constructor/string/regexp], [string/regexp], [message]) - * - * Asserts that `function` will throw an error that is an instance of - * `constructor`, or alternately that it will throw an error with message - * matching `regexp`. - * - * assert.throws(fn, 'function throws a reference error'); - * assert.throws(fn, /function throws a reference error/); - * assert.throws(fn, ReferenceError); - * assert.throws(fn, ReferenceError, 'function throws a reference error'); - * assert.throws(fn, ReferenceError, /function throws a reference error/); - * - * @name throws - * @alias throw - * @alias Throw - * @param {Function} function - * @param {ErrorConstructor} constructor - * @param {RegExp} regexp - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Assert - * @api public - */ - - assert.throws = function (fn, errt, errs, msg) { - if ('string' === typeof errt || errt instanceof RegExp) { - errs = errt; - errt = null; - } - - var assertErr = new Assertion(fn, msg).to.throw(errt, errs); - return flag(assertErr, 'object'); - }; - - /** - * ### .doesNotThrow(function, [constructor/regexp], [message]) - * - * Asserts that `function` will _not_ throw an error that is an instance of - * `constructor`, or alternately that it will not throw an error with message - * matching `regexp`. - * - * assert.doesNotThrow(fn, Error, 'function does not throw'); - * - * @name doesNotThrow - * @param {Function} function - * @param {ErrorConstructor} constructor - * @param {RegExp} regexp - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Assert - * @api public - */ - - assert.doesNotThrow = function (fn, type, msg) { - if ('string' === typeof type) { - msg = type; - type = null; - } - - new Assertion(fn, msg).to.not.Throw(type); - }; - - /** - * ### .operator(val1, operator, val2, [message]) - * - * Compares two values using `operator`. - * - * assert.operator(1, '<', 2, 'everything is ok'); - * assert.operator(1, '>', 2, 'this will fail'); - * - * @name operator - * @param {Mixed} val1 - * @param {String} operator - * @param {Mixed} val2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.operator = function (val, operator, val2, msg) { - var ok; - switch(operator) { - case '==': - ok = val == val2; - break; - case '===': - ok = val === val2; - break; - case '>': - ok = val > val2; - break; - case '>=': - ok = val >= val2; - break; - case '<': - ok = val < val2; - break; - case '<=': - ok = val <= val2; - break; - case '!=': - ok = val != val2; - break; - case '!==': - ok = val !== val2; - break; - default: - throw new Error('Invalid operator "' + operator + '"'); - } - var test = new Assertion(ok, msg); - test.assert( - true === flag(test, 'object') - , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) - , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); - }; - - /** - * ### .closeTo(actual, expected, delta, [message]) - * - * Asserts that the target is equal `expected`, to within a +/- `delta` range. - * - * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); - * - * @name closeTo - * @param {Number} actual - * @param {Number} expected - * @param {Number} delta - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.closeTo = function (act, exp, delta, msg) { - new Assertion(act, msg).to.be.closeTo(exp, delta); - }; - - /** - * ### .approximately(actual, expected, delta, [message]) - * - * Asserts that the target is equal `expected`, to within a +/- `delta` range. - * - * assert.approximately(1.5, 1, 0.5, 'numbers are close'); - * - * @name approximately - * @param {Number} actual - * @param {Number} expected - * @param {Number} delta - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.approximately = function (act, exp, delta, msg) { - new Assertion(act, msg).to.be.approximately(exp, delta); - }; - - /** - * ### .sameMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members. - * Order is not taken into account. - * - * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); - * - * @name sameMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameMembers = function (set1, set2, msg) { - new Assertion(set1, msg).to.have.same.members(set2); - } - - /** - * ### .sameDeepMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members - using a deep equality checking. - * Order is not taken into account. - * - * assert.sameDeepMembers([ {b: 3}, {a: 2}, {c: 5} ], [ {c: 5}, {b: 3}, {a: 2} ], 'same deep members'); - * - * @name sameDeepMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameDeepMembers = function (set1, set2, msg) { - new Assertion(set1, msg).to.have.same.deep.members(set2); - } - - /** - * ### .includeMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset`. - * Order is not taken into account. - * - * assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members'); - * - * @name includeMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeMembers = function (superset, subset, msg) { - new Assertion(superset, msg).to.include.members(subset); - } - - /** - * ### .includeDeepMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` - using deep equality checking. - * Order is not taken into account. - * Duplicates are ignored. - * - * assert.includeDeepMembers([ {a: 1}, {b: 2}, {c: 3} ], [ {b: 2}, {a: 1}, {b: 2} ], 'include deep members'); - * - * @name includeDeepMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeDeepMembers = function (superset, subset, msg) { - new Assertion(superset, msg).to.include.deep.members(subset); - } - - /** - * ### .oneOf(inList, list, [message]) - * - * Asserts that non-object, non-array value `inList` appears in the flat array `list`. - * - * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); - * - * @name oneOf - * @param {*} inList - * @param {Array<*>} list - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.oneOf = function (inList, list, msg) { - new Assertion(inList, msg).to.be.oneOf(list); - } - - /** - * ### .changes(function, object, property) - * - * Asserts that a function changes the value of a property - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 22 }; - * assert.changes(fn, obj, 'val'); - * - * @name changes - * @param {Function} modifier function - * @param {Object} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.changes = function (fn, obj, prop) { - new Assertion(fn).to.change(obj, prop); - } - - /** - * ### .doesNotChange(function, object, property) - * - * Asserts that a function does not changes the value of a property - * - * var obj = { val: 10 }; - * var fn = function() { console.log('foo'); }; - * assert.doesNotChange(fn, obj, 'val'); - * - * @name doesNotChange - * @param {Function} modifier function - * @param {Object} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotChange = function (fn, obj, prop) { - new Assertion(fn).to.not.change(obj, prop); - } - - /** - * ### .increases(function, object, property) - * - * Asserts that a function increases an object property - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 13 }; - * assert.increases(fn, obj, 'val'); - * - * @name increases - * @param {Function} modifier function - * @param {Object} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.increases = function (fn, obj, prop) { - new Assertion(fn).to.increase(obj, prop); - } - - /** - * ### .doesNotIncrease(function, object, property) - * - * Asserts that a function does not increase object property - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 8 }; - * assert.doesNotIncrease(fn, obj, 'val'); - * - * @name doesNotIncrease - * @param {Function} modifier function - * @param {Object} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotIncrease = function (fn, obj, prop) { - new Assertion(fn).to.not.increase(obj, prop); - } - - /** - * ### .decreases(function, object, property) - * - * Asserts that a function decreases an object property - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 5 }; - * assert.decreases(fn, obj, 'val'); - * - * @name decreases - * @param {Function} modifier function - * @param {Object} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.decreases = function (fn, obj, prop) { - new Assertion(fn).to.decrease(obj, prop); - } - - /** - * ### .doesNotDecrease(function, object, property) - * - * Asserts that a function does not decreases an object property - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 15 }; - * assert.doesNotDecrease(fn, obj, 'val'); - * - * @name doesNotDecrease - * @param {Function} modifier function - * @param {Object} object - * @param {String} property name - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotDecrease = function (fn, obj, prop) { - new Assertion(fn).to.not.decrease(obj, prop); - } - - /*! - * ### .ifError(object) - * - * Asserts if value is not a false value, and throws if it is a true value. - * This is added to allow for chai to be a drop-in replacement for Node's - * assert class. - * - * var err = new Error('I am a custom error'); - * assert.ifError(err); // Rethrows err! - * - * @name ifError - * @param {Object} object - * @namespace Assert - * @api public - */ - - assert.ifError = function (val) { - if (val) { - throw(val); - } - }; - - /** - * ### .isExtensible(object) - * - * Asserts that `object` is extensible (can have new properties added to it). - * - * assert.isExtensible({}); - * - * @name isExtensible - * @alias extensible - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isExtensible = function (obj, msg) { - new Assertion(obj, msg).to.be.extensible; - }; - - /** - * ### .isNotExtensible(object) - * - * Asserts that `object` is _not_ extensible. - * - * var nonExtensibleObject = Object.preventExtensions({}); - * var sealedObject = Object.seal({}); - * var frozenObject = Object.freese({}); - * - * assert.isNotExtensible(nonExtensibleObject); - * assert.isNotExtensible(sealedObject); - * assert.isNotExtensible(frozenObject); - * - * @name isNotExtensible - * @alias notExtensible - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isNotExtensible = function (obj, msg) { - new Assertion(obj, msg).to.not.be.extensible; - }; - - /** - * ### .isSealed(object) - * - * Asserts that `object` is sealed (cannot have new properties added to it - * and its existing properties cannot be removed). - * - * var sealedObject = Object.seal({}); - * var frozenObject = Object.seal({}); - * - * assert.isSealed(sealedObject); - * assert.isSealed(frozenObject); - * - * @name isSealed - * @alias sealed - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isSealed = function (obj, msg) { - new Assertion(obj, msg).to.be.sealed; - }; - - /** - * ### .isNotSealed(object) - * - * Asserts that `object` is _not_ sealed. - * - * assert.isNotSealed({}); - * - * @name isNotSealed - * @alias notSealed - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isNotSealed = function (obj, msg) { - new Assertion(obj, msg).to.not.be.sealed; - }; - - /** - * ### .isFrozen(object) - * - * Asserts that `object` is frozen (cannot have new properties added to it - * and its existing properties cannot be modified). - * - * var frozenObject = Object.freeze({}); - * assert.frozen(frozenObject); - * - * @name isFrozen - * @alias frozen - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isFrozen = function (obj, msg) { - new Assertion(obj, msg).to.be.frozen; - }; - - /** - * ### .isNotFrozen(object) - * - * Asserts that `object` is _not_ frozen. - * - * assert.isNotFrozen({}); - * - * @name isNotFrozen - * @alias notFrozen - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isNotFrozen = function (obj, msg) { - new Assertion(obj, msg).to.not.be.frozen; - }; - - /*! - * Aliases. - */ - - (function alias(name, as){ - assert[as] = assert[name]; - return alias; - }) - ('isOk', 'ok') - ('isNotOk', 'notOk') - ('throws', 'throw') - ('throws', 'Throw') - ('isExtensible', 'extensible') - ('isNotExtensible', 'notExtensible') - ('isSealed', 'sealed') - ('isNotSealed', 'notSealed') - ('isFrozen', 'frozen') - ('isNotFrozen', 'notFrozen'); -}; - -},{}],18:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -module.exports = function (chai, util) { - chai.expect = function (val, message) { - return new chai.Assertion(val, message); - }; - - /** - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace Expect - * @api public - */ - - chai.expect.fail = function (actual, expected, message, operator) { - message = message || 'expect.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, chai.expect.fail); - }; -}; - -},{}],19:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -module.exports = function (chai, util) { - var Assertion = chai.Assertion; - - function loadShould () { - // explicitly define this method as function as to have it's name to include as `ssfi` - function shouldGetter() { - if (this instanceof String || this instanceof Number || this instanceof Boolean ) { - return new Assertion(this.valueOf(), null, shouldGetter); - } - return new Assertion(this, null, shouldGetter); - } - function shouldSetter(value) { - // See https://github.com/chaijs/chai/issues/86: this makes - // `whatever.should = someValue` actually set `someValue`, which is - // especially useful for `global.should = require('chai').should()`. - // - // Note that we have to use [[DefineProperty]] instead of [[Put]] - // since otherwise we would trigger this very setter! - Object.defineProperty(this, 'should', { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } - // modify Object.prototype to have `should` - Object.defineProperty(Object.prototype, 'should', { - set: shouldSetter - , get: shouldGetter - , configurable: true - }); - - var should = {}; - - /** - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace Should - * @api public - */ - - should.fail = function (actual, expected, message, operator) { - message = message || 'should.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, should.fail); - }; - - /** - * ### .equal(actual, expected, [message]) - * - * Asserts non-strict equality (`==`) of `actual` and `expected`. - * - * should.equal(3, '3', '== coerces values to strings'); - * - * @name equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Should - * @api public - */ - - should.equal = function (val1, val2, msg) { - new Assertion(val1, msg).to.equal(val2); - }; - - /** - * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) - * - * Asserts that `function` will throw an error that is an instance of - * `constructor`, or alternately that it will throw an error with message - * matching `regexp`. - * - * should.throw(fn, 'function throws a reference error'); - * should.throw(fn, /function throws a reference error/); - * should.throw(fn, ReferenceError); - * should.throw(fn, ReferenceError, 'function throws a reference error'); - * should.throw(fn, ReferenceError, /function throws a reference error/); - * - * @name throw - * @alias Throw - * @param {Function} function - * @param {ErrorConstructor} constructor - * @param {RegExp} regexp - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Should - * @api public - */ - - should.Throw = function (fn, errt, errs, msg) { - new Assertion(fn, msg).to.Throw(errt, errs); - }; - - /** - * ### .exist - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var foo = 'hi'; - * - * should.exist(foo, 'foo exists'); - * - * @name exist - * @namespace Should - * @api public - */ - - should.exist = function (val, msg) { - new Assertion(val, msg).to.exist; - } - - // negation - should.not = {} - - /** - * ### .not.equal(actual, expected, [message]) - * - * Asserts non-strict inequality (`!=`) of `actual` and `expected`. - * - * should.not.equal(3, 4, 'these numbers are not equal'); - * - * @name not.equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Should - * @api public - */ - - should.not.equal = function (val1, val2, msg) { - new Assertion(val1, msg).to.not.equal(val2); - }; - - /** - * ### .throw(function, [constructor/regexp], [message]) - * - * Asserts that `function` will _not_ throw an error that is an instance of - * `constructor`, or alternately that it will not throw an error with message - * matching `regexp`. - * - * should.not.throw(fn, Error, 'function does not throw'); - * - * @name not.throw - * @alias not.Throw - * @param {Function} function - * @param {ErrorConstructor} constructor - * @param {RegExp} regexp - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Should - * @api public - */ - - should.not.Throw = function (fn, errt, errs, msg) { - new Assertion(fn, msg).to.not.Throw(errt, errs); - }; - - /** - * ### .not.exist - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var bar = null; - * - * should.not.exist(bar, 'bar does not exist'); - * - * @name not.exist - * @namespace Should - * @api public - */ - - should.not.exist = function (val, msg) { - new Assertion(val, msg).to.not.exist; - } - - should['throw'] = should['Throw']; - should.not['throw'] = should.not['Throw']; - - return should; - }; - - chai.should = loadShould; - chai.Should = loadShould; -}; - -},{}],20:[function(require,module,exports){ -/*! - * Chai - addChainingMethod utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependencies - */ - -var transferFlags = require('./transferFlags'); -var flag = require('./flag'); -var config = require('../config'); - -/*! - * Module variables - */ - -// Check whether `__proto__` is supported -var hasProtoSupport = '__proto__' in Object; - -// Without `__proto__` support, this module will need to add properties to a function. -// However, some Function.prototype methods cannot be overwritten, -// and there seems no easy cross-platform way to detect them (@see chaijs/chai/issues/69). -var excludeNames = /^(?:length|name|arguments|caller)$/; - -// Cache `Function` properties -var call = Function.prototype.call, - apply = Function.prototype.apply; - -/** - * ### addChainableMethod (ctx, name, method, chainingBehavior) - * - * Adds a method to an object, such that the method can also be chained. - * - * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.equal(str); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); - * - * The result can then be used as both a method assertion, executing both `method` and - * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. - * - * expect(fooStr).to.be.foo('bar'); - * expect(fooStr).to.be.foo.equal('foo'); - * - * @param {Object} ctx object to which the method is added - * @param {String} name of method to add - * @param {Function} method function to be used for `name`, when called - * @param {Function} chainingBehavior function to be called every time the property is accessed - * @namespace Utils - * @name addChainableMethod - * @api public - */ - -module.exports = function (ctx, name, method, chainingBehavior) { - if (typeof chainingBehavior !== 'function') { - chainingBehavior = function () { }; - } - - var chainableBehavior = { - method: method - , chainingBehavior: chainingBehavior - }; - - // save the methods so we can overwrite them later, if we need to. - if (!ctx.__methods) { - ctx.__methods = {}; - } - ctx.__methods[name] = chainableBehavior; - - Object.defineProperty(ctx, name, - { get: function () { - chainableBehavior.chainingBehavior.call(this); - - var assert = function assert() { - var old_ssfi = flag(this, 'ssfi'); - if (old_ssfi && config.includeStack === false) - flag(this, 'ssfi', assert); - var result = chainableBehavior.method.apply(this, arguments); - return result === undefined ? this : result; - }; - - // Use `__proto__` if available - if (hasProtoSupport) { - // Inherit all properties from the object by replacing the `Function` prototype - var prototype = assert.__proto__ = Object.create(this); - // Restore the `call` and `apply` methods from `Function` - prototype.call = call; - prototype.apply = apply; - } - // Otherwise, redefine all properties (slow!) - else { - var asserterNames = Object.getOwnPropertyNames(ctx); - asserterNames.forEach(function (asserterName) { - if (!excludeNames.test(asserterName)) { - var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); - Object.defineProperty(assert, asserterName, pd); - } - }); - } - - transferFlags(this, assert); - return assert; - } - , configurable: true - }); -}; - -},{"../config":15,"./flag":24,"./transferFlags":40}],21:[function(require,module,exports){ -/*! - * Chai - addMethod utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var config = require('../config'); - -/** - * ### .addMethod (ctx, name, method) - * - * Adds a method to the prototype of an object. - * - * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.equal(str); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addMethod('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(fooStr).to.be.foo('bar'); - * - * @param {Object} ctx object to which the method is added - * @param {String} name of method to add - * @param {Function} method function to be used for name - * @namespace Utils - * @name addMethod - * @api public - */ -var flag = require('./flag'); - -module.exports = function (ctx, name, method) { - ctx[name] = function () { - var old_ssfi = flag(this, 'ssfi'); - if (old_ssfi && config.includeStack === false) - flag(this, 'ssfi', ctx[name]); - var result = method.apply(this, arguments); - return result === undefined ? this : result; - }; -}; - -},{"../config":15,"./flag":24}],22:[function(require,module,exports){ -/*! - * Chai - addProperty utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var config = require('../config'); -var flag = require('./flag'); - -/** - * ### addProperty (ctx, name, getter) - * - * Adds a property to the prototype of an object. - * - * utils.addProperty(chai.Assertion.prototype, 'foo', function () { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.instanceof(Foo); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addProperty('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.be.foo; - * - * @param {Object} ctx object to which the property is added - * @param {String} name of property to add - * @param {Function} getter function to be used for name - * @namespace Utils - * @name addProperty - * @api public - */ - -module.exports = function (ctx, name, getter) { - Object.defineProperty(ctx, name, - { get: function addProperty() { - var old_ssfi = flag(this, 'ssfi'); - if (old_ssfi && config.includeStack === false) - flag(this, 'ssfi', addProperty); - - var result = getter.call(this); - return result === undefined ? this : result; - } - , configurable: true - }); -}; - -},{"../config":15,"./flag":24}],23:[function(require,module,exports){ -/*! - * Chai - expectTypes utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### expectTypes(obj, types) - * - * Ensures that the object being tested against is of a valid type. - * - * utils.expectTypes(this, ['array', 'object', 'string']); - * - * @param {Mixed} obj constructed Assertion - * @param {Array} type A list of allowed types for this assertion - * @namespace Utils - * @name expectTypes - * @api public - */ - -var AssertionError = require('assertion-error'); -var flag = require('./flag'); -var type = require('type-detect'); - -module.exports = function (obj, types) { - var obj = flag(obj, 'object'); - types = types.map(function (t) { return t.toLowerCase(); }); - types.sort(); - - // Transforms ['lorem', 'ipsum'] into 'a lirum, or an ipsum' - var str = types.map(function (t, index) { - var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; - var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; - return or + art + ' ' + t; - }).join(', '); - - if (!types.some(function (expected) { return type(obj) === expected; })) { - throw new AssertionError( - 'object tested must be ' + str + ', but ' + type(obj) + ' given' - ); - } -}; - -},{"./flag":24,"assertion-error":11,"type-detect":82}],24:[function(require,module,exports){ -/*! - * Chai - flag utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### flag(object, key, [value]) - * - * Get or set a flag value on an object. If a - * value is provided it will be set, else it will - * return the currently set value or `undefined` if - * the value is not set. - * - * utils.flag(this, 'foo', 'bar'); // setter - * utils.flag(this, 'foo'); // getter, returns `bar` - * - * @param {Object} object constructed Assertion - * @param {String} key - * @param {Mixed} value (optional) - * @namespace Utils - * @name flag - * @api private - */ - -module.exports = function (obj, key, value) { - var flags = obj.__flags || (obj.__flags = Object.create(null)); - if (arguments.length === 3) { - flags[key] = value; - } else { - return flags[key]; - } -}; - -},{}],25:[function(require,module,exports){ -/*! - * Chai - getActual utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * # getActual(object, [actual]) - * - * Returns the `actual` value for an Assertion - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name getActual - */ - -module.exports = function (obj, args) { - return args.length > 4 ? args[4] : obj._obj; -}; - -},{}],26:[function(require,module,exports){ -/*! - * Chai - getEnumerableProperties utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .getEnumerableProperties(object) - * - * This allows the retrieval of enumerable property names of an object, - * inherited or not. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getEnumerableProperties - * @api public - */ - -module.exports = function getEnumerableProperties(object) { - var result = []; - for (var name in object) { - result.push(name); - } - return result; -}; - -},{}],27:[function(require,module,exports){ -/*! - * Chai - message composition utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependancies - */ - -var flag = require('./flag') - , getActual = require('./getActual') - , inspect = require('./inspect') - , objDisplay = require('./objDisplay'); - -/** - * ### .getMessage(object, message, negateMessage) - * - * Construct the error message based on flags - * and template tags. Template tags will return - * a stringified inspection of the object referenced. - * - * Message template tags: - * - `#{this}` current asserted object - * - `#{act}` actual value - * - `#{exp}` expected value - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name getMessage - * @api public - */ - -module.exports = function (obj, args) { - var negate = flag(obj, 'negate') - , val = flag(obj, 'object') - , expected = args[3] - , actual = getActual(obj, args) - , msg = negate ? args[2] : args[1] - , flagMsg = flag(obj, 'message'); - - if(typeof msg === "function") msg = msg(); - msg = msg || ''; - msg = msg - .replace(/#\{this\}/g, function () { return objDisplay(val); }) - .replace(/#\{act\}/g, function () { return objDisplay(actual); }) - .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); - - return flagMsg ? flagMsg + ': ' + msg : msg; -}; - -},{"./flag":24,"./getActual":25,"./inspect":34,"./objDisplay":35}],28:[function(require,module,exports){ -/*! - * Chai - getName utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * # getName(func) - * - * Gets the name of a function, in a cross-browser way. - * - * @param {Function} a function (usually a constructor) - * @namespace Utils - * @name getName - */ - -module.exports = function (func) { - if (func.name) return func.name; - - var match = /^\s?function ([^(]*)\(/.exec(func); - return match && match[1] ? match[1] : ""; -}; - -},{}],29:[function(require,module,exports){ -/*! - * Chai - getPathInfo utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var hasProperty = require('./hasProperty'); - -/** - * ### .getPathInfo(path, object) - * - * This allows the retrieval of property info in an - * object given a string path. - * - * The path info consists of an object with the - * following properties: - * - * * parent - The parent object of the property referenced by `path` - * * name - The name of the final property, a number if it was an array indexer - * * value - The value of the property, if it exists, otherwise `undefined` - * * exists - Whether the property exists or not - * - * @param {String} path - * @param {Object} object - * @returns {Object} info - * @namespace Utils - * @name getPathInfo - * @api public - */ - -module.exports = function getPathInfo(path, obj) { - var parsed = parsePath(path), - last = parsed[parsed.length - 1]; - - var info = { - parent: parsed.length > 1 ? _getPathValue(parsed, obj, parsed.length - 1) : obj, - name: last.p || last.i, - value: _getPathValue(parsed, obj) - }; - info.exists = hasProperty(info.name, info.parent); - - return info; -}; - - -/*! - * ## parsePath(path) - * - * Helper function used to parse string object - * paths. Use in conjunction with `_getPathValue`. - * - * var parsed = parsePath('myobject.property.subprop'); - * - * ### Paths: - * - * * Can be as near infinitely deep and nested - * * Arrays are also valid using the formal `myobject.document[3].property`. - * * Literal dots and brackets (not delimiter) must be backslash-escaped. - * - * @param {String} path - * @returns {Object} parsed - * @api private - */ - -function parsePath (path) { - var str = path.replace(/([^\\])\[/g, '$1.[') - , parts = str.match(/(\\\.|[^.]+?)+/g); - return parts.map(function (value) { - var re = /^\[(\d+)\]$/ - , mArr = re.exec(value); - if (mArr) return { i: parseFloat(mArr[1]) }; - else return { p: value.replace(/\\([.\[\]])/g, '$1') }; - }); -} - - -/*! - * ## _getPathValue(parsed, obj) - * - * Helper companion function for `.parsePath` that returns - * the value located at the parsed address. - * - * var value = getPathValue(parsed, obj); - * - * @param {Object} parsed definition from `parsePath`. - * @param {Object} object to search against - * @param {Number} object to search against - * @returns {Object|Undefined} value - * @api private - */ - -function _getPathValue (parsed, obj, index) { - var tmp = obj - , res; - - index = (index === undefined ? parsed.length : index); - - for (var i = 0, l = index; i < l; i++) { - var part = parsed[i]; - if (tmp) { - if ('undefined' !== typeof part.p) - tmp = tmp[part.p]; - else if ('undefined' !== typeof part.i) - tmp = tmp[part.i]; - if (i == (l - 1)) res = tmp; - } else { - res = undefined; - } - } - return res; -} - -},{"./hasProperty":32}],30:[function(require,module,exports){ -/*! - * Chai - getPathValue utility - * Copyright(c) 2012-2014 Jake Luer - * @see https://github.com/logicalparadox/filtr - * MIT Licensed - */ - -var getPathInfo = require('./getPathInfo'); - -/** - * ### .getPathValue(path, object) - * - * This allows the retrieval of values in an - * object given a string path. - * - * var obj = { - * prop1: { - * arr: ['a', 'b', 'c'] - * , str: 'Hello' - * } - * , prop2: { - * arr: [ { nested: 'Universe' } ] - * , str: 'Hello again!' - * } - * } - * - * The following would be the results. - * - * getPathValue('prop1.str', obj); // Hello - * getPathValue('prop1.att[2]', obj); // b - * getPathValue('prop2.arr[0].nested', obj); // Universe - * - * @param {String} path - * @param {Object} object - * @returns {Object} value or `undefined` - * @namespace Utils - * @name getPathValue - * @api public - */ -module.exports = function(path, obj) { - var info = getPathInfo(path, obj); - return info.value; -}; - -},{"./getPathInfo":29}],31:[function(require,module,exports){ -/*! - * Chai - getProperties utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .getProperties(object) - * - * This allows the retrieval of property names of an object, enumerable or not, - * inherited or not. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getProperties - * @api public - */ - -module.exports = function getProperties(object) { - var result = Object.getOwnPropertyNames(object); - - function addProperty(property) { - if (result.indexOf(property) === -1) { - result.push(property); - } - } - - var proto = Object.getPrototypeOf(object); - while (proto !== null) { - Object.getOwnPropertyNames(proto).forEach(addProperty); - proto = Object.getPrototypeOf(proto); - } - - return result; -}; - -},{}],32:[function(require,module,exports){ -/*! - * Chai - hasProperty utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var type = require('type-detect'); - -/** - * ### .hasProperty(object, name) - * - * This allows checking whether an object has - * named property or numeric array index. - * - * Basically does the same thing as the `in` - * operator but works properly with natives - * and null/undefined values. - * - * var obj = { - * arr: ['a', 'b', 'c'] - * , str: 'Hello' - * } - * - * The following would be the results. - * - * hasProperty('str', obj); // true - * hasProperty('constructor', obj); // true - * hasProperty('bar', obj); // false - * - * hasProperty('length', obj.str); // true - * hasProperty(1, obj.str); // true - * hasProperty(5, obj.str); // false - * - * hasProperty('length', obj.arr); // true - * hasProperty(2, obj.arr); // true - * hasProperty(3, obj.arr); // false - * - * @param {Objuect} object - * @param {String|Number} name - * @returns {Boolean} whether it exists - * @namespace Utils - * @name getPathInfo - * @api public - */ - -var literals = { - 'number': Number - , 'string': String -}; - -module.exports = function hasProperty(name, obj) { - var ot = type(obj); - - // Bad Object, obviously no props at all - if(ot === 'null' || ot === 'undefined') - return false; - - // The `in` operator does not work with certain literals - // box these before the check - if(literals[ot] && typeof obj !== 'object') - obj = new literals[ot](obj); - - return name in obj; -}; - -},{"type-detect":82}],33:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011 Jake Luer - * MIT Licensed - */ - -/*! - * Main exports - */ - -var exports = module.exports = {}; - -/*! - * test utility - */ - -exports.test = require('./test'); - -/*! - * type utility - */ - -exports.type = require('type-detect'); - -/*! - * expectTypes utility - */ -exports.expectTypes = require('./expectTypes'); - -/*! - * message utility - */ - -exports.getMessage = require('./getMessage'); - -/*! - * actual utility - */ - -exports.getActual = require('./getActual'); - -/*! - * Inspect util - */ - -exports.inspect = require('./inspect'); - -/*! - * Object Display util - */ - -exports.objDisplay = require('./objDisplay'); - -/*! - * Flag utility - */ - -exports.flag = require('./flag'); - -/*! - * Flag transferring utility - */ - -exports.transferFlags = require('./transferFlags'); - -/*! - * Deep equal utility - */ - -exports.eql = require('deep-eql'); - -/*! - * Deep path value - */ - -exports.getPathValue = require('./getPathValue'); - -/*! - * Deep path info - */ - -exports.getPathInfo = require('./getPathInfo'); - -/*! - * Check if a property exists - */ - -exports.hasProperty = require('./hasProperty'); - -/*! - * Function name - */ - -exports.getName = require('./getName'); - -/*! - * add Property - */ - -exports.addProperty = require('./addProperty'); - -/*! - * add Method - */ - -exports.addMethod = require('./addMethod'); - -/*! - * overwrite Property - */ - -exports.overwriteProperty = require('./overwriteProperty'); - -/*! - * overwrite Method - */ - -exports.overwriteMethod = require('./overwriteMethod'); - -/*! - * Add a chainable method - */ - -exports.addChainableMethod = require('./addChainableMethod'); - -/*! - * Overwrite chainable method - */ - -exports.overwriteChainableMethod = require('./overwriteChainableMethod'); - -},{"./addChainableMethod":20,"./addMethod":21,"./addProperty":22,"./expectTypes":23,"./flag":24,"./getActual":25,"./getMessage":27,"./getName":28,"./getPathInfo":29,"./getPathValue":30,"./hasProperty":32,"./inspect":34,"./objDisplay":35,"./overwriteChainableMethod":36,"./overwriteMethod":37,"./overwriteProperty":38,"./test":39,"./transferFlags":40,"deep-eql":77,"type-detect":82}],34:[function(require,module,exports){ -// This is (almost) directly from Node.js utils -// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js - -var getName = require('./getName'); -var getProperties = require('./getProperties'); -var getEnumerableProperties = require('./getEnumerableProperties'); - -module.exports = inspect; - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Boolean} showHidden Flag that shows hidden (not enumerable) - * properties of objects. - * @param {Number} depth Depth in which to descend in object. Default is 2. - * @param {Boolean} colors Flag to turn on ANSI escape codes to color the - * output. Default is false (no coloring). - * @namespace Utils - * @name inspect - */ -function inspect(obj, showHidden, depth, colors) { - var ctx = { - showHidden: showHidden, - seen: [], - stylize: function (str) { return str; } - }; - return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); -} - -// Returns true if object is a DOM element. -var isDOMElement = function (object) { - if (typeof HTMLElement === 'object') { - return object instanceof HTMLElement; - } else { - return object && - typeof object === 'object' && - object.nodeType === 1 && - typeof object.nodeName === 'string'; - } -}; - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (value && typeof value.inspect === 'function' && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes); - if (typeof ret !== 'string') { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // If this is a DOM element, try to get the outer HTML. - if (isDOMElement(value)) { - if ('outerHTML' in value) { - return value.outerHTML; - // This value does not have an outerHTML attribute, - // it could still be an XML element - } else { - // Attempt to serialize it - try { - if (document.xmlVersion) { - var xmlSerializer = new XMLSerializer(); - return xmlSerializer.serializeToString(value); - } else { - // Firefox 11- do not support outerHTML - // It does, however, support innerHTML - // Use the following to render the element - var ns = "http://www.w3.org/1999/xhtml"; - var container = document.createElementNS(ns, '_'); - - container.appendChild(value.cloneNode(false)); - html = container.innerHTML - .replace('><', '>' + value.innerHTML + '<'); - container.innerHTML = ''; - return html; - } - } catch (err) { - // This could be a non-native DOM implementation, - // continue with the normal flow: - // printing the element as if it is an object. - } - } - } - - // Look up the keys of the object. - var visibleKeys = getEnumerableProperties(value); - var keys = ctx.showHidden ? getProperties(value) : visibleKeys; - - // Some type of object without properties can be shortcutted. - // In IE, errors have a single `stack` property, or if they are vanilla `Error`, - // a `stack` plus `description` property; ignore those for consistency. - if (keys.length === 0 || (isError(value) && ( - (keys.length === 1 && keys[0] === 'stack') || - (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') - ))) { - if (typeof value === 'function') { - var name = getName(value); - var nameSuffix = name ? ': ' + name : ''; - return ctx.stylize('[Function' + nameSuffix + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (typeof value === 'function') { - var name = getName(value); - var nameSuffix = name ? ': ' + name : ''; - base = ' [Function' + nameSuffix + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - return formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - switch (typeof value) { - case 'undefined': - return ctx.stylize('undefined', 'undefined'); - - case 'string': - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - - case 'number': - if (value === 0 && (1/value) === -Infinity) { - return ctx.stylize('-0', 'number'); - } - return ctx.stylize('' + value, 'number'); - - case 'boolean': - return ctx.stylize('' + value, 'boolean'); - } - // For some reason typeof null is "object", so special case here. - if (value === null) { - return ctx.stylize('null', 'null'); - } -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (Object.prototype.hasOwnProperty.call(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str; - if (value.__lookupGetter__) { - if (value.__lookupGetter__(key)) { - if (value.__lookupSetter__(key)) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (value.__lookupSetter__(key)) { - str = ctx.stylize('[Setter]', 'special'); - } - } - } - if (visibleKeys.indexOf(key) < 0) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(value[key]) < 0) { - if (recurseTimes === null) { - str = formatValue(ctx, value[key], null); - } else { - str = formatValue(ctx, value[key], recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (typeof name === 'undefined') { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - -function isArray(ar) { - return Array.isArray(ar) || - (typeof ar === 'object' && objectToString(ar) === '[object Array]'); -} - -function isRegExp(re) { - return typeof re === 'object' && objectToString(re) === '[object RegExp]'; -} - -function isDate(d) { - return typeof d === 'object' && objectToString(d) === '[object Date]'; -} - -function isError(e) { - return typeof e === 'object' && objectToString(e) === '[object Error]'; -} - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -},{"./getEnumerableProperties":26,"./getName":28,"./getProperties":31}],35:[function(require,module,exports){ -/*! - * Chai - flag utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependancies - */ - -var inspect = require('./inspect'); -var config = require('../config'); - -/** - * ### .objDisplay (object) - * - * Determines if an object or an array matches - * criteria to be inspected in-line for error - * messages or should be truncated. - * - * @param {Mixed} javascript object to inspect - * @name objDisplay - * @namespace Utils - * @api public - */ - -module.exports = function (obj) { - var str = inspect(obj) - , type = Object.prototype.toString.call(obj); - - if (config.truncateThreshold && str.length >= config.truncateThreshold) { - if (type === '[object Function]') { - return !obj.name || obj.name === '' - ? '[Function]' - : '[Function: ' + obj.name + ']'; - } else if (type === '[object Array]') { - return '[ Array(' + obj.length + ') ]'; - } else if (type === '[object Object]') { - var keys = Object.keys(obj) - , kstr = keys.length > 2 - ? keys.splice(0, 2).join(', ') + ', ...' - : keys.join(', '); - return '{ Object (' + kstr + ') }'; - } else { - return str; - } - } else { - return str; - } -}; - -},{"../config":15,"./inspect":34}],36:[function(require,module,exports){ -/*! - * Chai - overwriteChainableMethod utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### overwriteChainableMethod (ctx, name, method, chainingBehavior) - * - * Overwites an already existing chainable method - * and provides access to the previous function or - * property. Must return functions to be used for - * name. - * - * utils.overwriteChainableMethod(chai.Assertion.prototype, 'length', - * function (_super) { - * } - * , function (_super) { - * } - * ); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteChainableMethod('foo', fn, fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.have.length(3); - * expect(myFoo).to.have.length.above(3); - * - * @param {Object} ctx object whose method / property is to be overwritten - * @param {String} name of method / property to overwrite - * @param {Function} method function that returns a function to be used for name - * @param {Function} chainingBehavior function that returns a function to be used for property - * @namespace Utils - * @name overwriteChainableMethod - * @api public - */ - -module.exports = function (ctx, name, method, chainingBehavior) { - var chainableBehavior = ctx.__methods[name]; - - var _chainingBehavior = chainableBehavior.chainingBehavior; - chainableBehavior.chainingBehavior = function () { - var result = chainingBehavior(_chainingBehavior).call(this); - return result === undefined ? this : result; - }; - - var _method = chainableBehavior.method; - chainableBehavior.method = function () { - var result = method(_method).apply(this, arguments); - return result === undefined ? this : result; - }; -}; - -},{}],37:[function(require,module,exports){ -/*! - * Chai - overwriteMethod utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### overwriteMethod (ctx, name, fn) - * - * Overwites an already existing method and provides - * access to previous function. Must return function - * to be used for name. - * - * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { - * return function (str) { - * var obj = utils.flag(this, 'object'); - * if (obj instanceof Foo) { - * new chai.Assertion(obj.value).to.equal(str); - * } else { - * _super.apply(this, arguments); - * } - * } - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteMethod('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.equal('bar'); - * - * @param {Object} ctx object whose method is to be overwritten - * @param {String} name of method to overwrite - * @param {Function} method function that returns a function to be used for name - * @namespace Utils - * @name overwriteMethod - * @api public - */ - -module.exports = function (ctx, name, method) { - var _method = ctx[name] - , _super = function () { return this; }; - - if (_method && 'function' === typeof _method) - _super = _method; - - ctx[name] = function () { - var result = method(_super).apply(this, arguments); - return result === undefined ? this : result; - } -}; - -},{}],38:[function(require,module,exports){ -/*! - * Chai - overwriteProperty utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### overwriteProperty (ctx, name, fn) - * - * Overwites an already existing property getter and provides - * access to previous value. Must return function to use as getter. - * - * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { - * return function () { - * var obj = utils.flag(this, 'object'); - * if (obj instanceof Foo) { - * new chai.Assertion(obj.name).to.equal('bar'); - * } else { - * _super.call(this); - * } - * } - * }); - * - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteProperty('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.be.ok; - * - * @param {Object} ctx object whose property is to be overwritten - * @param {String} name of property to overwrite - * @param {Function} getter function that returns a getter function to be used for name - * @namespace Utils - * @name overwriteProperty - * @api public - */ - -module.exports = function (ctx, name, getter) { - var _get = Object.getOwnPropertyDescriptor(ctx, name) - , _super = function () {}; - - if (_get && 'function' === typeof _get.get) - _super = _get.get - - Object.defineProperty(ctx, name, - { get: function () { - var result = getter(_super).call(this); - return result === undefined ? this : result; - } - , configurable: true - }); -}; - -},{}],39:[function(require,module,exports){ -/*! - * Chai - test utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependancies - */ - -var flag = require('./flag'); - -/** - * # test(object, expression) - * - * Test and object for expression. - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name test - */ - -module.exports = function (obj, args) { - var negate = flag(obj, 'negate') - , expr = args[0]; - return negate ? !expr : expr; -}; - -},{"./flag":24}],40:[function(require,module,exports){ -/*! - * Chai - transferFlags utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### transferFlags(assertion, object, includeAll = true) - * - * Transfer all the flags for `assertion` to `object`. If - * `includeAll` is set to `false`, then the base Chai - * assertion flags (namely `object`, `ssfi`, and `message`) - * will not be transferred. - * - * - * var newAssertion = new Assertion(); - * utils.transferFlags(assertion, newAssertion); - * - * var anotherAsseriton = new Assertion(myObj); - * utils.transferFlags(assertion, anotherAssertion, false); - * - * @param {Assertion} assertion the assertion to transfer the flags from - * @param {Object} object the object to transfer the flags to; usually a new assertion - * @param {Boolean} includeAll - * @namespace Utils - * @name transferFlags - * @api private - */ - -module.exports = function (assertion, object, includeAll) { - var flags = assertion.__flags || (assertion.__flags = Object.create(null)); - - if (!object.__flags) { - object.__flags = Object.create(null); - } - - includeAll = arguments.length === 3 ? includeAll : true; - - for (var flag in flags) { - if (includeAll || - (flag !== 'object' && flag !== 'ssfi' && flag != 'message')) { - object.__flags[flag] = flags[flag]; - } - } -}; - -},{}],41:[function(require,module,exports){ -require('../../modules/es6.object.assign'); -module.exports = require('../../modules/_core').Object.assign; -},{"../../modules/_core":46,"../../modules/es6.object.assign":76}],42:[function(require,module,exports){ -module.exports = function(it){ - if(typeof it != 'function')throw TypeError(it + ' is not a function!'); - return it; -}; -},{}],43:[function(require,module,exports){ -var isObject = require('./_is-object'); -module.exports = function(it){ - if(!isObject(it))throw TypeError(it + ' is not an object!'); - return it; -}; -},{"./_is-object":59}],44:[function(require,module,exports){ -// false -> Array#indexOf -// true -> Array#includes -var toIObject = require('./_to-iobject') - , toLength = require('./_to-length') - , toIndex = require('./_to-index'); -module.exports = function(IS_INCLUDES){ - return function($this, el, fromIndex){ - var O = toIObject($this) - , length = toLength(O.length) - , index = toIndex(fromIndex, length) - , value; - // Array#includes uses SameValueZero equality algorithm - if(IS_INCLUDES && el != el)while(length > index){ - value = O[index++]; - if(value != value)return true; - // Array#toIndex ignores holes, Array#includes - not - } else for(;length > index; index++)if(IS_INCLUDES || index in O){ - if(O[index] === el)return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; -}; -},{"./_to-index":69,"./_to-iobject":71,"./_to-length":72}],45:[function(require,module,exports){ -var toString = {}.toString; - -module.exports = function(it){ - return toString.call(it).slice(8, -1); -}; -},{}],46:[function(require,module,exports){ -var core = module.exports = {version: '2.4.0'}; -if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef -},{}],47:[function(require,module,exports){ -// optional / simple context binding -var aFunction = require('./_a-function'); -module.exports = function(fn, that, length){ - aFunction(fn); - if(that === undefined)return fn; - switch(length){ - case 1: return function(a){ - return fn.call(that, a); - }; - case 2: return function(a, b){ - return fn.call(that, a, b); - }; - case 3: return function(a, b, c){ - return fn.call(that, a, b, c); - }; - } - return function(/* ...args */){ - return fn.apply(that, arguments); - }; -}; -},{"./_a-function":42}],48:[function(require,module,exports){ -// 7.2.1 RequireObjectCoercible(argument) -module.exports = function(it){ - if(it == undefined)throw TypeError("Can't call method on " + it); - return it; -}; -},{}],49:[function(require,module,exports){ -// Thank's IE8 for his funny defineProperty -module.exports = !require('./_fails')(function(){ - return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; -}); -},{"./_fails":53}],50:[function(require,module,exports){ -var isObject = require('./_is-object') - , document = require('./_global').document - // in old IE typeof document.createElement is 'object' - , is = isObject(document) && isObject(document.createElement); -module.exports = function(it){ - return is ? document.createElement(it) : {}; -}; -},{"./_global":54,"./_is-object":59}],51:[function(require,module,exports){ -// IE 8- don't enum bug keys -module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' -).split(','); -},{}],52:[function(require,module,exports){ -var global = require('./_global') - , core = require('./_core') - , ctx = require('./_ctx') - , hide = require('./_hide') - , PROTOTYPE = 'prototype'; - -var $export = function(type, name, source){ - var IS_FORCED = type & $export.F - , IS_GLOBAL = type & $export.G - , IS_STATIC = type & $export.S - , IS_PROTO = type & $export.P - , IS_BIND = type & $export.B - , IS_WRAP = type & $export.W - , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) - , expProto = exports[PROTOTYPE] - , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] - , key, own, out; - if(IS_GLOBAL)source = name; - for(key in source){ - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - if(own && key in exports)continue; - // export native or passed - out = own ? target[key] : source[key]; - // prevent global pollution for namespaces - exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] - // bind timers to global for call from export context - : IS_BIND && own ? ctx(out, global) - // wrap global constructors for prevent change them in library - : IS_WRAP && target[key] == out ? (function(C){ - var F = function(a, b, c){ - if(this instanceof C){ - switch(arguments.length){ - case 0: return new C; - case 1: return new C(a); - case 2: return new C(a, b); - } return new C(a, b, c); - } return C.apply(this, arguments); - }; - F[PROTOTYPE] = C[PROTOTYPE]; - return F; - // make static versions for prototype methods - })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% - if(IS_PROTO){ - (exports.virtual || (exports.virtual = {}))[key] = out; - // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% - if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); - } - } -}; -// type bitmap -$export.F = 1; // forced -$export.G = 2; // global -$export.S = 4; // static -$export.P = 8; // proto -$export.B = 16; // bind -$export.W = 32; // wrap -$export.U = 64; // safe -$export.R = 128; // real proto method for `library` -module.exports = $export; -},{"./_core":46,"./_ctx":47,"./_global":54,"./_hide":56}],53:[function(require,module,exports){ -module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } -}; -},{}],54:[function(require,module,exports){ -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); -if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef -},{}],55:[function(require,module,exports){ -var hasOwnProperty = {}.hasOwnProperty; -module.exports = function(it, key){ - return hasOwnProperty.call(it, key); -}; -},{}],56:[function(require,module,exports){ -var dP = require('./_object-dp') - , createDesc = require('./_property-desc'); -module.exports = require('./_descriptors') ? function(object, key, value){ - return dP.f(object, key, createDesc(1, value)); -} : function(object, key, value){ - object[key] = value; - return object; -}; -},{"./_descriptors":49,"./_object-dp":61,"./_property-desc":66}],57:[function(require,module,exports){ -module.exports = !require('./_descriptors') && !require('./_fails')(function(){ - return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7; -}); -},{"./_descriptors":49,"./_dom-create":50,"./_fails":53}],58:[function(require,module,exports){ -// fallback for non-array-like ES3 and non-enumerable old V8 strings -var cof = require('./_cof'); -module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ - return cof(it) == 'String' ? it.split('') : Object(it); -}; -},{"./_cof":45}],59:[function(require,module,exports){ -module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; -}; -},{}],60:[function(require,module,exports){ -'use strict'; -// 19.1.2.1 Object.assign(target, source, ...) -var getKeys = require('./_object-keys') - , gOPS = require('./_object-gops') - , pIE = require('./_object-pie') - , toObject = require('./_to-object') - , IObject = require('./_iobject') - , $assign = Object.assign; - -// should work with symbols and should have deterministic property order (V8 bug) -module.exports = !$assign || require('./_fails')(function(){ - var A = {} - , B = {} - , S = Symbol() - , K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function(k){ B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; -}) ? function assign(target, source){ // eslint-disable-line no-unused-vars - var T = toObject(target) - , aLen = arguments.length - , index = 1 - , getSymbols = gOPS.f - , isEnum = pIE.f; - while(aLen > index){ - var S = IObject(arguments[index++]) - , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) - , length = keys.length - , j = 0 - , key; - while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; - } return T; -} : $assign; -},{"./_fails":53,"./_iobject":58,"./_object-gops":62,"./_object-keys":64,"./_object-pie":65,"./_to-object":73}],61:[function(require,module,exports){ -var anObject = require('./_an-object') - , IE8_DOM_DEFINE = require('./_ie8-dom-define') - , toPrimitive = require('./_to-primitive') - , dP = Object.defineProperty; - -exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){ - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if(IE8_DOM_DEFINE)try { - return dP(O, P, Attributes); - } catch(e){ /* empty */ } - if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); - if('value' in Attributes)O[P] = Attributes.value; - return O; -}; -},{"./_an-object":43,"./_descriptors":49,"./_ie8-dom-define":57,"./_to-primitive":74}],62:[function(require,module,exports){ -exports.f = Object.getOwnPropertySymbols; -},{}],63:[function(require,module,exports){ -var has = require('./_has') - , toIObject = require('./_to-iobject') - , arrayIndexOf = require('./_array-includes')(false) - , IE_PROTO = require('./_shared-key')('IE_PROTO'); - -module.exports = function(object, names){ - var O = toIObject(object) - , i = 0 - , result = [] - , key; - for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while(names.length > i)if(has(O, key = names[i++])){ - ~arrayIndexOf(result, key) || result.push(key); - } - return result; -}; -},{"./_array-includes":44,"./_has":55,"./_shared-key":67,"./_to-iobject":71}],64:[function(require,module,exports){ -// 19.1.2.14 / 15.2.3.14 Object.keys(O) -var $keys = require('./_object-keys-internal') - , enumBugKeys = require('./_enum-bug-keys'); - -module.exports = Object.keys || function keys(O){ - return $keys(O, enumBugKeys); -}; -},{"./_enum-bug-keys":51,"./_object-keys-internal":63}],65:[function(require,module,exports){ -exports.f = {}.propertyIsEnumerable; -},{}],66:[function(require,module,exports){ -module.exports = function(bitmap, value){ - return { - enumerable : !(bitmap & 1), - configurable: !(bitmap & 2), - writable : !(bitmap & 4), - value : value - }; -}; -},{}],67:[function(require,module,exports){ -var shared = require('./_shared')('keys') - , uid = require('./_uid'); -module.exports = function(key){ - return shared[key] || (shared[key] = uid(key)); -}; -},{"./_shared":68,"./_uid":75}],68:[function(require,module,exports){ -var global = require('./_global') - , SHARED = '__core-js_shared__' - , store = global[SHARED] || (global[SHARED] = {}); -module.exports = function(key){ - return store[key] || (store[key] = {}); -}; -},{"./_global":54}],69:[function(require,module,exports){ -var toInteger = require('./_to-integer') - , max = Math.max - , min = Math.min; -module.exports = function(index, length){ - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); -}; -},{"./_to-integer":70}],70:[function(require,module,exports){ -// 7.1.4 ToInteger -var ceil = Math.ceil - , floor = Math.floor; -module.exports = function(it){ - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); -}; -},{}],71:[function(require,module,exports){ -// to indexed object, toObject with fallback for non-array-like ES3 strings -var IObject = require('./_iobject') - , defined = require('./_defined'); -module.exports = function(it){ - return IObject(defined(it)); -}; -},{"./_defined":48,"./_iobject":58}],72:[function(require,module,exports){ -// 7.1.15 ToLength -var toInteger = require('./_to-integer') - , min = Math.min; -module.exports = function(it){ - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 -}; -},{"./_to-integer":70}],73:[function(require,module,exports){ -// 7.1.13 ToObject(argument) -var defined = require('./_defined'); -module.exports = function(it){ - return Object(defined(it)); -}; -},{"./_defined":48}],74:[function(require,module,exports){ -// 7.1.1 ToPrimitive(input [, PreferredType]) -var isObject = require('./_is-object'); -// instead of the ES6 spec version, we didn't implement @@toPrimitive case -// and the second argument - flag - preferred type is a string -module.exports = function(it, S){ - if(!isObject(it))return it; - var fn, val; - if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; - if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - throw TypeError("Can't convert object to primitive value"); -}; -},{"./_is-object":59}],75:[function(require,module,exports){ -var id = 0 - , px = Math.random(); -module.exports = function(key){ - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); -}; -},{}],76:[function(require,module,exports){ -// 19.1.3.1 Object.assign(target, source) -var $export = require('./_export'); - -$export($export.S + $export.F, 'Object', {assign: require('./_object-assign')}); -},{"./_export":52,"./_object-assign":60}],77:[function(require,module,exports){ -module.exports = require('./lib/eql'); - -},{"./lib/eql":78}],78:[function(require,module,exports){ -/*! - * deep-eql - * Copyright(c) 2013 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependencies - */ - -var type = require('type-detect'); - -/*! - * Buffer.isBuffer browser shim - */ - -var Buffer; -try { Buffer = require('buffer').Buffer; } -catch(ex) { - Buffer = {}; - Buffer.isBuffer = function() { return false; } -} - -/*! - * Primary Export - */ - -module.exports = deepEqual; - -/** - * Assert super-strict (egal) equality between - * two objects of any type. - * - * @param {Mixed} a - * @param {Mixed} b - * @param {Array} memoised (optional) - * @return {Boolean} equal match - */ - -function deepEqual(a, b, m) { - if (sameValue(a, b)) { - return true; - } else if ('date' === type(a)) { - return dateEqual(a, b); - } else if ('regexp' === type(a)) { - return regexpEqual(a, b); - } else if (Buffer.isBuffer(a)) { - return bufferEqual(a, b); - } else if ('arguments' === type(a)) { - return argumentsEqual(a, b, m); - } else if (!typeEqual(a, b)) { - return false; - } else if (('object' !== type(a) && 'object' !== type(b)) - && ('array' !== type(a) && 'array' !== type(b))) { - return sameValue(a, b); - } else { - return objectEqual(a, b, m); - } -} - -/*! - * Strict (egal) equality test. Ensures that NaN always - * equals NaN and `-0` does not equal `+0`. - * - * @param {Mixed} a - * @param {Mixed} b - * @return {Boolean} equal match - */ - -function sameValue(a, b) { - if (a === b) return a !== 0 || 1 / a === 1 / b; - return a !== a && b !== b; -} - -/*! - * Compare the types of two given objects and - * return if they are equal. Note that an Array - * has a type of `array` (not `object`) and arguments - * have a type of `arguments` (not `array`/`object`). - * - * @param {Mixed} a - * @param {Mixed} b - * @return {Boolean} result - */ - -function typeEqual(a, b) { - return type(a) === type(b); -} - -/*! - * Compare two Date objects by asserting that - * the time values are equal using `saveValue`. - * - * @param {Date} a - * @param {Date} b - * @return {Boolean} result - */ - -function dateEqual(a, b) { - if ('date' !== type(b)) return false; - return sameValue(a.getTime(), b.getTime()); -} - -/*! - * Compare two regular expressions by converting them - * to string and checking for `sameValue`. - * - * @param {RegExp} a - * @param {RegExp} b - * @return {Boolean} result - */ - -function regexpEqual(a, b) { - if ('regexp' !== type(b)) return false; - return sameValue(a.toString(), b.toString()); -} - -/*! - * Assert deep equality of two `arguments` objects. - * Unfortunately, these must be sliced to arrays - * prior to test to ensure no bad behavior. - * - * @param {Arguments} a - * @param {Arguments} b - * @param {Array} memoize (optional) - * @return {Boolean} result - */ - -function argumentsEqual(a, b, m) { - if ('arguments' !== type(b)) return false; - a = [].slice.call(a); - b = [].slice.call(b); - return deepEqual(a, b, m); -} - -/*! - * Get enumerable properties of a given object. - * - * @param {Object} a - * @return {Array} property names - */ - -function enumerable(a) { - var res = []; - for (var key in a) res.push(key); - return res; -} - -/*! - * Simple equality for flat iterable objects - * such as Arrays or Node.js buffers. - * - * @param {Iterable} a - * @param {Iterable} b - * @return {Boolean} result - */ - -function iterableEqual(a, b) { - if (a.length !== b.length) return false; - - var i = 0; - var match = true; - - for (; i < a.length; i++) { - if (a[i] !== b[i]) { - match = false; - break; - } - } - - return match; -} - -/*! - * Extension to `iterableEqual` specifically - * for Node.js Buffers. - * - * @param {Buffer} a - * @param {Mixed} b - * @return {Boolean} result - */ - -function bufferEqual(a, b) { - if (!Buffer.isBuffer(b)) return false; - return iterableEqual(a, b); -} - -/*! - * Block for `objectEqual` ensuring non-existing - * values don't get in. - * - * @param {Mixed} object - * @return {Boolean} result - */ - -function isValue(a) { - return a !== null && a !== undefined; -} - -/*! - * Recursively check the equality of two objects. - * Once basic sameness has been established it will - * defer to `deepEqual` for each enumerable key - * in the object. - * - * @param {Mixed} a - * @param {Mixed} b - * @return {Boolean} result - */ - -function objectEqual(a, b, m) { - if (!isValue(a) || !isValue(b)) { - return false; - } - - if (a.prototype !== b.prototype) { - return false; - } - - var i; - if (m) { - for (i = 0; i < m.length; i++) { - if ((m[i][0] === a && m[i][1] === b) - || (m[i][0] === b && m[i][1] === a)) { - return true; - } - } - } else { - m = []; - } - - try { - var ka = enumerable(a); - var kb = enumerable(b); - } catch (ex) { - return false; - } - - ka.sort(); - kb.sort(); - - if (!iterableEqual(ka, kb)) { - return false; - } - - m.push([ a, b ]); - - var key; - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!deepEqual(a[key], b[key], m)) { - return false; - } - } - - return true; -} - -},{"buffer":2,"type-detect":79}],79:[function(require,module,exports){ -module.exports = require('./lib/type'); - -},{"./lib/type":80}],80:[function(require,module,exports){ -/*! - * type-detect - * Copyright(c) 2013 jake luer - * MIT Licensed - */ - -/*! - * Primary Exports - */ - -var exports = module.exports = getType; - -/*! - * Detectable javascript natives - */ - -var natives = { - '[object Array]': 'array' - , '[object RegExp]': 'regexp' - , '[object Function]': 'function' - , '[object Arguments]': 'arguments' - , '[object Date]': 'date' -}; - -/** - * ### typeOf (obj) - * - * Use several different techniques to determine - * the type of object being tested. - * - * - * @param {Mixed} object - * @return {String} object type - * @api public - */ - -function getType (obj) { - var str = Object.prototype.toString.call(obj); - if (natives[str]) return natives[str]; - if (obj === null) return 'null'; - if (obj === undefined) return 'undefined'; - if (obj === Object(obj)) return 'object'; - return typeof obj; -} - -exports.Library = Library; - -/** - * ### Library - * - * Create a repository for custom type detection. - * - * ```js - * var lib = new type.Library; - * ``` - * - */ - -function Library () { - this.tests = {}; -} - -/** - * #### .of (obj) - * - * Expose replacement `typeof` detection to the library. - * - * ```js - * if ('string' === lib.of('hello world')) { - * // ... - * } - * ``` - * - * @param {Mixed} object to test - * @return {String} type - */ - -Library.prototype.of = getType; - -/** - * #### .define (type, test) - * - * Add a test to for the `.test()` assertion. - * - * Can be defined as a regular expression: - * - * ```js - * lib.define('int', /^[0-9]+$/); - * ``` - * - * ... or as a function: - * - * ```js - * lib.define('bln', function (obj) { - * if ('boolean' === lib.of(obj)) return true; - * var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ]; - * if ('string' === lib.of(obj)) obj = obj.toLowerCase(); - * return !! ~blns.indexOf(obj); - * }); - * ``` - * - * @param {String} type - * @param {RegExp|Function} test - * @api public - */ - -Library.prototype.define = function (type, test) { - if (arguments.length === 1) return this.tests[type]; - this.tests[type] = test; - return this; -}; - -/** - * #### .test (obj, test) - * - * Assert that an object is of type. Will first - * check natives, and if that does not pass it will - * use the user defined custom tests. - * - * ```js - * assert(lib.test('1', 'int')); - * assert(lib.test('yes', 'bln')); - * ``` - * - * @param {Mixed} object - * @param {String} type - * @return {Boolean} result - * @api public - */ - -Library.prototype.test = function (obj, type) { - if (type === getType(obj)) return true; - var test = this.tests[type]; - - if (test && 'regexp' === getType(test)) { - return test.test(obj); - } else if (test && 'function' === getType(test)) { - return test(obj); - } else { - throw new ReferenceError('Type test "' + type + '" not defined or invalid.'); - } -}; - -},{}],81:[function(require,module,exports){ -// the whatwg-fetch polyfill installs the fetch() function -// on the global object (window or self) -// -// Return that as the export for use in Webpack, Browserify etc. -require('whatwg-fetch'); -module.exports = self.fetch.bind(self); - -},{"whatwg-fetch":85}],82:[function(require,module,exports){ -arguments[4][79][0].apply(exports,arguments) -},{"./lib/type":83,"dup":79}],83:[function(require,module,exports){ -/*! - * type-detect - * Copyright(c) 2013 jake luer - * MIT Licensed - */ - -/*! - * Primary Exports - */ - -var exports = module.exports = getType; - -/** - * ### typeOf (obj) - * - * Use several different techniques to determine - * the type of object being tested. - * - * - * @param {Mixed} object - * @return {String} object type - * @api public - */ -var objectTypeRegexp = /^\[object (.*)\]$/; - -function getType(obj) { - var type = Object.prototype.toString.call(obj).match(objectTypeRegexp)[1].toLowerCase(); - // Let "new String('')" return 'object' - if (typeof Promise === 'function' && obj instanceof Promise) return 'promise'; - // PhantomJS has type "DOMWindow" for null - if (obj === null) return 'null'; - // PhantomJS has type "DOMWindow" for undefined - if (obj === undefined) return 'undefined'; - return type; -} - -exports.Library = Library; - -/** - * ### Library - * - * Create a repository for custom type detection. - * - * ```js - * var lib = new type.Library; - * ``` - * - */ - -function Library() { - if (!(this instanceof Library)) return new Library(); - this.tests = {}; -} - -/** - * #### .of (obj) - * - * Expose replacement `typeof` detection to the library. - * - * ```js - * if ('string' === lib.of('hello world')) { - * // ... - * } - * ``` - * - * @param {Mixed} object to test - * @return {String} type - */ - -Library.prototype.of = getType; - -/** - * #### .define (type, test) - * - * Add a test to for the `.test()` assertion. - * - * Can be defined as a regular expression: - * - * ```js - * lib.define('int', /^[0-9]+$/); - * ``` - * - * ... or as a function: - * - * ```js - * lib.define('bln', function (obj) { - * if ('boolean' === lib.of(obj)) return true; - * var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ]; - * if ('string' === lib.of(obj)) obj = obj.toLowerCase(); - * return !! ~blns.indexOf(obj); - * }); - * ``` - * - * @param {String} type - * @param {RegExp|Function} test - * @api public - */ - -Library.prototype.define = function(type, test) { - if (arguments.length === 1) return this.tests[type]; - this.tests[type] = test; - return this; -}; - -/** - * #### .test (obj, test) - * - * Assert that an object is of type. Will first - * check natives, and if that does not pass it will - * use the user defined custom tests. - * - * ```js - * assert(lib.test('1', 'int')); - * assert(lib.test('yes', 'bln')); - * ``` - * - * @param {Mixed} object - * @param {String} type - * @return {Boolean} result - * @api public - */ - -Library.prototype.test = function(obj, type) { - if (type === getType(obj)) return true; - var test = this.tests[type]; - - if (test && 'regexp' === getType(test)) { - return test.test(obj); - } else if (test && 'function' === getType(test)) { - return test(obj); - } else { - throw new ReferenceError('Type test "' + type + '" not defined or invalid.'); - } -}; - -},{}],84:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var querystring = require("querystring"); -var url = require("url"); -var isomorphicFetch = require("isomorphic-fetch"); -var assign = require("core-js/library/fn/object/assign"); -var BaseAPI = (function () { - function BaseAPI(basePath, fetch) { - if (basePath === void 0) { basePath = "http://petstore.swagger.io/v2"; } - if (fetch === void 0) { fetch = isomorphicFetch; } - this.basePath = basePath; - this.fetch = fetch; - } - return BaseAPI; -}()); -exports.BaseAPI = BaseAPI; -var PetApi = (function (_super) { - __extends(PetApi, _super); - function PetApi() { - _super.apply(this, arguments); - } - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - PetApi.prototype.addPet = function (params) { - var baseUrl = this.basePath + "/pet"; - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "POST" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - PetApi.prototype.deletePet = function (params) { - // verify required parameter "petId" is set - if (params["petId"] == null) { - throw new Error("Missing required parameter petId when calling deletePet"); - } - var baseUrl = (this.basePath + "/pet/{petId}") - .replace("{" + "petId" + "}", "" + params.petId); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "DELETE" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - PetApi.prototype.findPetsByStatus = function (params) { - var baseUrl = this.basePath + "/pet/findByStatus"; - var urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { - "status": params.status, - }); - var fetchOptions = { method: "GET" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - PetApi.prototype.findPetsByTags = function (params) { - var baseUrl = this.basePath + "/pet/findByTags"; - var urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { - "tags": params.tags, - }); - var fetchOptions = { method: "GET" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - PetApi.prototype.getPetById = function (params) { - // verify required parameter "petId" is set - if (params["petId"] == null) { - throw new Error("Missing required parameter petId when calling getPetById"); - } - var baseUrl = (this.basePath + "/pet/{petId}") - .replace("{" + "petId" + "}", "" + params.petId); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "GET" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - PetApi.prototype.updatePet = function (params) { - var baseUrl = this.basePath + "/pet"; - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "PUT" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - PetApi.prototype.updatePetWithForm = function (params) { - // verify required parameter "petId" is set - if (params["petId"] == null) { - throw new Error("Missing required parameter petId when calling updatePetWithForm"); - } - var baseUrl = (this.basePath + "/pet/{petId}") - .replace("{" + "petId" + "}", "" + params.petId); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "POST" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ - "name": params.name, - "status": params.status, - }); - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - PetApi.prototype.uploadFile = function (params) { - // verify required parameter "petId" is set - if (params["petId"] == null) { - throw new Error("Missing required parameter petId when calling uploadFile"); - } - var baseUrl = (this.basePath + "/pet/{petId}/uploadImage") - .replace("{" + "petId" + "}", "" + params.petId); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "POST" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ - "additionalMetadata": params.additionalMetadata, - "file": params.file, - }); - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - return PetApi; -}(BaseAPI)); -exports.PetApi = PetApi; -var StoreApi = (function (_super) { - __extends(StoreApi, _super); - function StoreApi() { - _super.apply(this, arguments); - } - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - StoreApi.prototype.deleteOrder = function (params) { - // verify required parameter "orderId" is set - if (params["orderId"] == null) { - throw new Error("Missing required parameter orderId when calling deleteOrder"); - } - var baseUrl = (this.basePath + "/store/order/{orderId}") - .replace("{" + "orderId" + "}", "" + params.orderId); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "DELETE" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - StoreApi.prototype.getInventory = function () { - var baseUrl = this.basePath + "/store/inventory"; - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "GET" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - StoreApi.prototype.getOrderById = function (params) { - // verify required parameter "orderId" is set - if (params["orderId"] == null) { - throw new Error("Missing required parameter orderId when calling getOrderById"); - } - var baseUrl = (this.basePath + "/store/order/{orderId}") - .replace("{" + "orderId" + "}", "" + params.orderId); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "GET" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - StoreApi.prototype.placeOrder = function (params) { - var baseUrl = this.basePath + "/store/order"; - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "POST" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - return StoreApi; -}(BaseAPI)); -exports.StoreApi = StoreApi; -var UserApi = (function (_super) { - __extends(UserApi, _super); - function UserApi() { - _super.apply(this, arguments); - } - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - UserApi.prototype.createUser = function (params) { - var baseUrl = this.basePath + "/user"; - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "POST" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - UserApi.prototype.createUsersWithArrayInput = function (params) { - var baseUrl = this.basePath + "/user/createWithArray"; - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "POST" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - UserApi.prototype.createUsersWithListInput = function (params) { - var baseUrl = this.basePath + "/user/createWithList"; - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "POST" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - UserApi.prototype.deleteUser = function (params) { - // verify required parameter "username" is set - if (params["username"] == null) { - throw new Error("Missing required parameter username when calling deleteUser"); - } - var baseUrl = (this.basePath + "/user/{username}") - .replace("{" + "username" + "}", "" + params.username); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "DELETE" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - UserApi.prototype.getUserByName = function (params) { - // verify required parameter "username" is set - if (params["username"] == null) { - throw new Error("Missing required parameter username when calling getUserByName"); - } - var baseUrl = (this.basePath + "/user/{username}") - .replace("{" + "username" + "}", "" + params.username); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "GET" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - UserApi.prototype.loginUser = function (params) { - var baseUrl = this.basePath + "/user/login"; - var urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { - "username": params.username, - "password": params.password, - }); - var fetchOptions = { method: "GET" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Logs out current logged in user session - * - */ - UserApi.prototype.logoutUser = function () { - var baseUrl = this.basePath + "/user/logout"; - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "GET" }; - var contentTypeHeader; - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - UserApi.prototype.updateUser = function (params) { - // verify required parameter "username" is set - if (params["username"] == null) { - throw new Error("Missing required parameter username when calling updateUser"); - } - var baseUrl = (this.basePath + "/user/{username}") - .replace("{" + "username" + "}", "" + params.username); - var urlObj = url.parse(baseUrl, true); - var fetchOptions = { method: "PUT" }; - var contentTypeHeader; - contentTypeHeader = { "Content-Type": "application/json" }; - if (params["body"]) { - fetchOptions.body = JSON.stringify(params["body"] || {}); - } - if (contentTypeHeader) { - fetchOptions.headers = contentTypeHeader; - } - return this.fetch(url.format(urlObj), fetchOptions).then(function (response) { - if (response.status >= 200 && response.status < 300) { - return response; - } - else { - throw assign(new Error(response.statusText), { response: response }); - } - }); - }; - return UserApi; -}(BaseAPI)); -exports.UserApi = UserApi; - -},{"core-js/library/fn/object/assign":41,"isomorphic-fetch":81,"querystring":8,"url":9}],85:[function(require,module,exports){ -(function(self) { - 'use strict'; - - if (self.fetch) { - return - } - - var support = { - searchParams: 'URLSearchParams' in self, - iterable: 'Symbol' in self && 'iterator' in Symbol, - blob: 'FileReader' in self && 'Blob' in self && (function() { - try { - new Blob() - return true - } catch(e) { - return false - } - })(), - formData: 'FormData' in self, - arrayBuffer: 'ArrayBuffer' in self - } - - function normalizeName(name) { - if (typeof name !== 'string') { - name = String(name) - } - if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { - throw new TypeError('Invalid character in header field name') - } - return name.toLowerCase() - } - - function normalizeValue(value) { - if (typeof value !== 'string') { - value = String(value) - } - return value - } - - // Build a destructive iterator for the value list - function iteratorFor(items) { - var iterator = { - next: function() { - var value = items.shift() - return {done: value === undefined, value: value} - } - } - - if (support.iterable) { - iterator[Symbol.iterator] = function() { - return iterator - } - } - - return iterator - } - - function Headers(headers) { - this.map = {} - - if (headers instanceof Headers) { - headers.forEach(function(value, name) { - this.append(name, value) - }, this) - - } else if (headers) { - Object.getOwnPropertyNames(headers).forEach(function(name) { - this.append(name, headers[name]) - }, this) - } - } - - Headers.prototype.append = function(name, value) { - name = normalizeName(name) - value = normalizeValue(value) - var list = this.map[name] - if (!list) { - list = [] - this.map[name] = list - } - list.push(value) - } - - Headers.prototype['delete'] = function(name) { - delete this.map[normalizeName(name)] - } - - Headers.prototype.get = function(name) { - var values = this.map[normalizeName(name)] - return values ? values[0] : null - } - - Headers.prototype.getAll = function(name) { - return this.map[normalizeName(name)] || [] - } - - Headers.prototype.has = function(name) { - return this.map.hasOwnProperty(normalizeName(name)) - } - - Headers.prototype.set = function(name, value) { - this.map[normalizeName(name)] = [normalizeValue(value)] - } - - Headers.prototype.forEach = function(callback, thisArg) { - Object.getOwnPropertyNames(this.map).forEach(function(name) { - this.map[name].forEach(function(value) { - callback.call(thisArg, value, name, this) - }, this) - }, this) - } - - Headers.prototype.keys = function() { - var items = [] - this.forEach(function(value, name) { items.push(name) }) - return iteratorFor(items) - } - - Headers.prototype.values = function() { - var items = [] - this.forEach(function(value) { items.push(value) }) - return iteratorFor(items) - } - - Headers.prototype.entries = function() { - var items = [] - this.forEach(function(value, name) { items.push([name, value]) }) - return iteratorFor(items) - } - - if (support.iterable) { - Headers.prototype[Symbol.iterator] = Headers.prototype.entries - } - - function consumed(body) { - if (body.bodyUsed) { - return Promise.reject(new TypeError('Already read')) - } - body.bodyUsed = true - } - - function fileReaderReady(reader) { - return new Promise(function(resolve, reject) { - reader.onload = function() { - resolve(reader.result) - } - reader.onerror = function() { - reject(reader.error) - } - }) - } - - function readBlobAsArrayBuffer(blob) { - var reader = new FileReader() - reader.readAsArrayBuffer(blob) - return fileReaderReady(reader) - } - - function readBlobAsText(blob) { - var reader = new FileReader() - reader.readAsText(blob) - return fileReaderReady(reader) - } - - function Body() { - this.bodyUsed = false - - this._initBody = function(body) { - this._bodyInit = body - if (typeof body === 'string') { - this._bodyText = body - } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { - this._bodyBlob = body - } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { - this._bodyFormData = body - } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { - this._bodyText = body.toString() - } else if (!body) { - this._bodyText = '' - } else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) { - // Only support ArrayBuffers for POST method. - // Receiving ArrayBuffers happens via Blobs, instead. - } else { - throw new Error('unsupported BodyInit type') - } - - if (!this.headers.get('content-type')) { - if (typeof body === 'string') { - this.headers.set('content-type', 'text/plain;charset=UTF-8') - } else if (this._bodyBlob && this._bodyBlob.type) { - this.headers.set('content-type', this._bodyBlob.type) - } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { - this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8') - } - } - } - - if (support.blob) { - this.blob = function() { - var rejected = consumed(this) - if (rejected) { - return rejected - } - - if (this._bodyBlob) { - return Promise.resolve(this._bodyBlob) - } else if (this._bodyFormData) { - throw new Error('could not read FormData body as blob') - } else { - return Promise.resolve(new Blob([this._bodyText])) - } - } - - this.arrayBuffer = function() { - return this.blob().then(readBlobAsArrayBuffer) - } - - this.text = function() { - var rejected = consumed(this) - if (rejected) { - return rejected - } - - if (this._bodyBlob) { - return readBlobAsText(this._bodyBlob) - } else if (this._bodyFormData) { - throw new Error('could not read FormData body as text') - } else { - return Promise.resolve(this._bodyText) - } - } - } else { - this.text = function() { - var rejected = consumed(this) - return rejected ? rejected : Promise.resolve(this._bodyText) - } - } - - if (support.formData) { - this.formData = function() { - return this.text().then(decode) - } - } - - this.json = function() { - return this.text().then(JSON.parse) - } - - return this - } - - // HTTP methods whose capitalization should be normalized - var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] - - function normalizeMethod(method) { - var upcased = method.toUpperCase() - return (methods.indexOf(upcased) > -1) ? upcased : method - } - - function Request(input, options) { - options = options || {} - var body = options.body - if (Request.prototype.isPrototypeOf(input)) { - if (input.bodyUsed) { - throw new TypeError('Already read') - } - this.url = input.url - this.credentials = input.credentials - if (!options.headers) { - this.headers = new Headers(input.headers) - } - this.method = input.method - this.mode = input.mode - if (!body) { - body = input._bodyInit - input.bodyUsed = true - } - } else { - this.url = input - } - - this.credentials = options.credentials || this.credentials || 'omit' - if (options.headers || !this.headers) { - this.headers = new Headers(options.headers) - } - this.method = normalizeMethod(options.method || this.method || 'GET') - this.mode = options.mode || this.mode || null - this.referrer = null - - if ((this.method === 'GET' || this.method === 'HEAD') && body) { - throw new TypeError('Body not allowed for GET or HEAD requests') - } - this._initBody(body) - } - - Request.prototype.clone = function() { - return new Request(this) - } - - function decode(body) { - var form = new FormData() - body.trim().split('&').forEach(function(bytes) { - if (bytes) { - var split = bytes.split('=') - var name = split.shift().replace(/\+/g, ' ') - var value = split.join('=').replace(/\+/g, ' ') - form.append(decodeURIComponent(name), decodeURIComponent(value)) - } - }) - return form - } - - function headers(xhr) { - var head = new Headers() - var pairs = (xhr.getAllResponseHeaders() || '').trim().split('\n') - pairs.forEach(function(header) { - var split = header.trim().split(':') - var key = split.shift().trim() - var value = split.join(':').trim() - head.append(key, value) - }) - return head - } - - Body.call(Request.prototype) - - function Response(bodyInit, options) { - if (!options) { - options = {} - } - - this.type = 'default' - this.status = options.status - this.ok = this.status >= 200 && this.status < 300 - this.statusText = options.statusText - this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers) - this.url = options.url || '' - this._initBody(bodyInit) - } - - Body.call(Response.prototype) - - Response.prototype.clone = function() { - return new Response(this._bodyInit, { - status: this.status, - statusText: this.statusText, - headers: new Headers(this.headers), - url: this.url - }) - } - - Response.error = function() { - var response = new Response(null, {status: 0, statusText: ''}) - response.type = 'error' - return response - } - - var redirectStatuses = [301, 302, 303, 307, 308] - - Response.redirect = function(url, status) { - if (redirectStatuses.indexOf(status) === -1) { - throw new RangeError('Invalid status code') - } - - return new Response(null, {status: status, headers: {location: url}}) - } - - self.Headers = Headers - self.Request = Request - self.Response = Response - - self.fetch = function(input, init) { - return new Promise(function(resolve, reject) { - var request - if (Request.prototype.isPrototypeOf(input) && !init) { - request = input - } else { - request = new Request(input, init) - } - - var xhr = new XMLHttpRequest() - - function responseURL() { - if ('responseURL' in xhr) { - return xhr.responseURL - } - - // Avoid security warnings on getResponseHeader when not allowed by CORS - if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) { - return xhr.getResponseHeader('X-Request-URL') - } - - return - } - - xhr.onload = function() { - var options = { - status: xhr.status, - statusText: xhr.statusText, - headers: headers(xhr), - url: responseURL() - } - var body = 'response' in xhr ? xhr.response : xhr.responseText - resolve(new Response(body, options)) - } - - xhr.onerror = function() { - reject(new TypeError('Network request failed')) - } - - xhr.ontimeout = function() { - reject(new TypeError('Network request failed')) - } - - xhr.open(request.method, request.url, true) - - if (request.credentials === 'include') { - xhr.withCredentials = true - } - - if ('responseType' in xhr && support.blob) { - xhr.responseType = 'blob' - } - - request.headers.forEach(function(value, name) { - xhr.setRequestHeader(name, value) - }) - - xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) - }) - } - self.fetch.polyfill = true -})(typeof self !== 'undefined' ? self : this); - -},{}],86:[function(require,module,exports){ -"use strict"; -var chai_1 = require('chai'); -var Swagger = require('typescript-fetch-api'); -describe('PetApi', function () { - var api; - var fixture = createTestFixture(); - beforeEach(function () { - api = new Swagger.PetApi(); - }); - it('should add and delete Pet', function () { - return api.addPet({ body: fixture }).then(function () { - }); - }); - it('should get Pet by ID', function () { - return api.getPetById({ petId: fixture.id }).then(function (result) { - return chai_1.expect(result).to.deep.equal(fixture); - }); - }); - it('should update Pet by ID', function () { - return api.getPetById({ petId: fixture.id }).then(function (result) { - result.name = 'newname'; - return api.updatePet({ body: result }).then(function () { - return api.getPetById({ petId: fixture.id }).then(function (result) { - return chai_1.expect(result.name).to.deep.equal('newname'); - }); - }); - }); - }); - it('should delete Pet', function () { - return api.deletePet({ petId: fixture.id }); - }); - it('should not contain deleted Pet', function () { - return api.getPetById({ petId: fixture.id }).then(function (result) { - return chai_1.expect(result).to.not.exist; - }, function (err) { - console.log(err); - return chai_1.expect(err).to.exist; - }); - }); -}); -function createTestFixture(ts) { - if (ts === void 0) { ts = Date.now(); } - var category = { - 'id': ts, - 'name': "category" + ts, - }; - var pet = { - 'id': ts, - 'name': "pet" + ts, - 'category': category, - 'photoUrls': ['http://foo.bar.com/1', 'http://foo.bar.com/2'], - 'status': 'available', - 'tags': [] - }; - return pet; -} -; - -},{"chai":12,"typescript-fetch-api":84}],87:[function(require,module,exports){ -"use strict"; -var chai_1 = require('chai'); -var Swagger = require('typescript-fetch-api'); -describe('StoreApi', function () { - var api; - beforeEach(function () { - api = new Swagger.StoreApi(); - }); - it('should get inventory', function () { - return api.getInventory().then(function (result) { - chai_1.expect(Object.keys(result)).to.not.be.empty; - }); - }); -}); - -},{"chai":12,"typescript-fetch-api":84}],88:[function(require,module,exports){ -"use strict"; -require('./PetApi'); -require('./StoreApi'); - -},{"./PetApi":86,"./StoreApi":87}]},{},[88]); diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts index 7ada1ecadc6..04b2c032a34 100644 --- a/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts @@ -1,13 +1,12 @@ import {expect} from 'chai'; -import * as Swagger from 'typescript-fetch-api'; +import {PetApi, Pet, Category} from 'typescript-fetch-api'; describe('PetApi', () => { - let api: Swagger.PetApi; - - let fixture: Swagger.Pet = createTestFixture(); + let api: PetApi; + let fixture: Pet = createTestFixture(); beforeEach(() => { - api = new Swagger.PetApi(); + api = new PetApi(); }); it('should add and delete Pet', () => { @@ -40,19 +39,18 @@ describe('PetApi', () => { return api.getPetById({ petId: fixture.id }).then((result) => { return expect(result).to.not.exist; }, (err) => { - console.log(err) return expect(err).to.exist; }); }); }); function createTestFixture(ts = Date.now()) { - const category: Swagger.Category = { + const category: Category = { 'id': ts, 'name': `category${ts}`, }; - const pet: Swagger.Pet = { + const pet: Pet = { 'id': ts, 'name': `pet${ts}`, 'category': category, diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts index e993766522d..420def0ab62 100644 --- a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts +++ b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts @@ -1,11 +1,11 @@ import {expect} from 'chai'; -import * as Swagger from 'typescript-fetch-api'; +import {StoreApi} from 'typescript-fetch-api'; describe('StoreApi', function() { - let api: Swagger.StoreApi; + let api: StoreApi; beforeEach(function() { - api = new Swagger.StoreApi(); + api = new StoreApi(); }); it('should get inventory', function() { From 0b7d0c34afdede302e2490f8c96cc8d08a5d99d5 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 14 May 2016 17:11:48 +0800 Subject: [PATCH 38/53] add debug switch to print out downloaded file info --- .../resources/php/ObjectSerializer.mustache | 6 +- .../petstore/php/SwaggerClient-php/README.md | 86 ++++----- .../php/SwaggerClient-php/autoload.php | 7 +- .../php/SwaggerClient-php/composer.json | 1 - .../php/SwaggerClient-php/docs/Api/FakeApi.md | 6 +- .../php/SwaggerClient-php/docs/Api/PetApi.md | 80 ++++----- .../SwaggerClient-php/docs/Api/StoreApi.md | 34 ++-- .../php/SwaggerClient-php/docs/Api/UserApi.md | 58 +++---- .../php/SwaggerClient-php/git_push.sh | 2 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 37 ++-- .../php/SwaggerClient-php/lib/Api/PetApi.php | 163 ++++++++++-------- .../SwaggerClient-php/lib/Api/StoreApi.php | 91 +++++----- .../php/SwaggerClient-php/lib/Api/UserApi.php | 163 ++++++++++-------- .../php/SwaggerClient-php/lib/ApiClient.php | 29 ++-- .../SwaggerClient-php/lib/ApiException.php | 6 + .../SwaggerClient-php/lib/Configuration.php | 4 +- .../lib/Model/AnimalFarm.php | 2 +- .../SwaggerClient-php/lib/Model/EnumClass.php | 2 +- .../SwaggerClient-php/lib/Model/EnumTest.php | 17 +- .../lib/Model/FormatTest.php | 6 +- .../php/SwaggerClient-php/lib/Model/Order.php | 7 +- .../php/SwaggerClient-php/lib/Model/Pet.php | 7 +- .../lib/ObjectSerializer.php | 18 +- 23 files changed, 468 insertions(+), 364 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 46f457fca32..62a128cbb36 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -268,7 +268,11 @@ class ObjectSerializer } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + + if (Configuration::getDefaultConfiguration()->getDebug()) { + error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + } + return $deserialized; } else { diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index fe09a19fa93..6385bef4e6b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -1,11 +1,11 @@ # SwaggerClient-php -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Package version: 1.0.0 -- Build date: 2016-05-10T22:37:00.768+08:00 +- Package version: +- Build date: 2016-05-14T17:06:01.056+08:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -41,7 +41,7 @@ Download the files and include `autoload.php`: require_once('/path/to/SwaggerClient-php/autoload.php'); ``` -## Tests +## Tests To run the unit tests: @@ -87,48 +87,48 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**testEndpointParameters**](docs/ApiFakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*PetApi* | [**addPet**](docs/ApiPetApi.md#addpet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](docs/ApiPetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](docs/ApiPetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](docs/ApiPetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](docs/ApiPetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](docs/ApiPetApi.md#updatepet) | **PUT** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](docs/ApiPetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](docs/ApiPetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](docs/ApiStoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**getInventory**](docs/ApiStoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](docs/ApiStoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](docs/ApiStoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet -*UserApi* | [**createUser**](docs/ApiUserApi.md#createuser) | **POST** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](docs/ApiUserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](docs/ApiUserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](docs/ApiUserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user -*UserApi* | [**getUserByName**](docs/ApiUserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](docs/ApiUserApi.md#loginuser) | **GET** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](docs/ApiUserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](docs/ApiUserApi.md#updateuser) | **PUT** /user/{username} | Updated user +*FakeApi* | [**testEndpointParameters**](docs/Api/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*PetApi* | [**addPet**](docs/Api/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/Api/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/Api/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/Api/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/Api/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/Api/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/Api/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/Api/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/Api/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/Api/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/Api/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/Api/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/Api/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/Api/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/Api/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/Api/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/Api/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/Api/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/Api/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/Api/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models - - [Animal](docs/ModelAnimal.md) - - [AnimalFarm](docs/ModelAnimalFarm.md) - - [ApiResponse](docs/ModelApiResponse.md) - - [Cat](docs/ModelCat.md) - - [Category](docs/ModelCategory.md) - - [Dog](docs/ModelDog.md) - - [EnumClass](docs/ModelEnumClass.md) - - [EnumTest](docs/ModelEnumTest.md) - - [FormatTest](docs/ModelFormatTest.md) - - [Model200Response](docs/ModelModel200Response.md) - - [ModelReturn](docs/ModelModelReturn.md) - - [Name](docs/ModelName.md) - - [Order](docs/ModelOrder.md) - - [Pet](docs/ModelPet.md) - - [SpecialModelName](docs/ModelSpecialModelName.md) - - [Tag](docs/ModelTag.md) - - [User](docs/ModelUser.md) + - [Animal](docs/Model/Animal.md) + - [AnimalFarm](docs/Model/AnimalFarm.md) + - [ApiResponse](docs/Model/ApiResponse.md) + - [Cat](docs/Model/Cat.md) + - [Category](docs/Model/Category.md) + - [Dog](docs/Model/Dog.md) + - [EnumClass](docs/Model/EnumClass.md) + - [EnumTest](docs/Model/EnumTest.md) + - [FormatTest](docs/Model/FormatTest.md) + - [Model200Response](docs/Model/Model200Response.md) + - [ModelReturn](docs/Model/ModelReturn.md) + - [Name](docs/Model/Name.md) + - [Order](docs/Model/Order.md) + - [Pet](docs/Model/Pet.md) + - [SpecialModelName](docs/Model/SpecialModelName.md) + - [Tag](docs/Model/Tag.md) + - [User](docs/Model/User.md) ## Documentation For Authorization @@ -136,7 +136,7 @@ Class | Method | HTTP request | Description ## api_key -- **Type**: API key +- **Type**: API key - **API key parameter name**: api_key - **Location**: HTTP header diff --git a/samples/client/petstore/php/SwaggerClient-php/autoload.php b/samples/client/petstore/php/SwaggerClient-php/autoload.php index acbd3968b23..3cbe3df8a21 100644 --- a/samples/client/petstore/php/SwaggerClient-php/autoload.php +++ b/samples/client/petstore/php/SwaggerClient-php/autoload.php @@ -1,14 +1,15 @@ testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); } catch (Exception $e) { echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), "\n"; @@ -71,5 +71,5 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md index bf119270a58..6ab902730c7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md @@ -21,7 +21,7 @@ Add a new pet to the store -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store -try { +try { $api_instance->addPet($body); } catch (Exception $e) { echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), "\n"; @@ -44,7 +44,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Pet**](\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | + **body** | [**\Swagger\Client\Model\Pet**](../Model/\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -52,14 +52,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: application/json, application/xml - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **deletePet** > deletePet($pet_id, $api_key) @@ -68,7 +68,7 @@ Deletes a pet -### Example +### Example ```php deletePet($pet_id, $api_key); } catch (Exception $e) { echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), "\n"; @@ -101,14 +101,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **findPetsByStatus** > \Swagger\Client\Model\Pet[] findPetsByStatus($status) @@ -117,7 +117,7 @@ Finds Pets by status Multiple status values can be provided with comma separated strings -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $status = array("status_example"); // string[] | Status values that need to be considered for filter -try { +try { $result = $api_instance->findPetsByStatus($status); print_r($result); } catch (Exception $e) { @@ -141,22 +141,22 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**string[]**](string.md)| Status values that need to be considered for filter | + **status** | [**string[]**](../Model/string.md)| Status values that need to be considered for filter | ### Return type -[**\Swagger\Client\Model\Pet[]**](Pet.md) +[**\Swagger\Client\Model\Pet[]**](../Model/Pet.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **findPetsByTags** > \Swagger\Client\Model\Pet[] findPetsByTags($tags) @@ -165,7 +165,7 @@ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $tags = array("tags_example"); // string[] | Tags to filter by -try { +try { $result = $api_instance->findPetsByTags($tags); print_r($result); } catch (Exception $e) { @@ -189,22 +189,22 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**string[]**](string.md)| Tags to filter by | + **tags** | [**string[]**](../Model/string.md)| Tags to filter by | ### Return type -[**\Swagger\Client\Model\Pet[]**](Pet.md) +[**\Swagger\Client\Model\Pet[]**](../Model/Pet.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **getPetById** > \Swagger\Client\Model\Pet getPetById($pet_id) @@ -213,7 +213,7 @@ Find pet by ID Returns a single pet -### Example +### Example ```php setApiKey('api_key', 'Y $api_instance = new Swagger\Client\Api\PetApi(); $pet_id = 789; // int | ID of pet to return -try { +try { $result = $api_instance->getPetById($pet_id); print_r($result); } catch (Exception $e) { @@ -243,18 +243,18 @@ Name | Type | Description | Notes ### Return type -[**\Swagger\Client\Model\Pet**](Pet.md) +[**\Swagger\Client\Model\Pet**](../Model/Pet.md) ### Authorization -[api_key](../README.md#api_key) +[api_key](../../README.md#api_key) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **updatePet** > updatePet($body) @@ -263,7 +263,7 @@ Update an existing pet -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store -try { +try { $api_instance->updatePet($body); } catch (Exception $e) { echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), "\n"; @@ -286,7 +286,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Pet**](\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | + **body** | [**\Swagger\Client\Model\Pet**](../Model/\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -294,14 +294,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: application/json, application/xml - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **updatePetWithForm** > updatePetWithForm($pet_id, $name, $status) @@ -310,7 +310,7 @@ Updates a pet in the store with form data -### Example +### Example ```php updatePetWithForm($pet_id, $name, $status); } catch (Exception $e) { echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), "\n"; @@ -345,14 +345,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: application/x-www-form-urlencoded - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **uploadFile** > \Swagger\Client\Model\ApiResponse uploadFile($pet_id, $additional_metadata, $file) @@ -361,7 +361,7 @@ uploads an image -### Example +### Example ```php uploadFile($pet_id, $additional_metadata, $file); print_r($result); } catch (Exception $e) { @@ -393,16 +393,16 @@ Name | Type | Description | Notes ### Return type -[**\Swagger\Client\Model\ApiResponse**](ApiResponse.md) +[**\Swagger\Client\Model\ApiResponse**](../Model/ApiResponse.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[petstore_auth](../../README.md#petstore_auth) ### HTTP request headers - **Content-Type**: multipart/form-data - **Accept**: application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md index 7040df371a4..24cacd22b47 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md @@ -17,7 +17,7 @@ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -### Example +### Example ```php deleteOrder($order_id); } catch (Exception $e) { echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), "\n"; @@ -52,7 +52,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **getInventory** > map[string,int] getInventory() @@ -61,7 +61,7 @@ Returns pet inventories by status Returns a map of status codes to quantities -### Example +### Example ```php setApiKey('api_key', 'Y $api_instance = new Swagger\Client\Api\StoreApi(); -try { +try { $result = $api_instance->getInventory(); print_r($result); } catch (Exception $e) { @@ -87,18 +87,18 @@ This endpoint does not need any parameter. ### Return type -[**map[string,int]**](map.md) +[**map[string,int]**](../Model/map.md) ### Authorization -[api_key](../README.md#api_key) +[api_key](../../README.md#api_key) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **getOrderById** > \Swagger\Client\Model\Order getOrderById($order_id) @@ -107,7 +107,7 @@ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -### Example +### Example ```php getOrderById($order_id); print_r($result); } catch (Exception $e) { @@ -132,7 +132,7 @@ Name | Type | Description | Notes ### Return type -[**\Swagger\Client\Model\Order**](Order.md) +[**\Swagger\Client\Model\Order**](../Model/Order.md) ### Authorization @@ -143,7 +143,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **placeOrder** > \Swagger\Client\Model\Order placeOrder($body) @@ -152,7 +152,7 @@ Place an order for a pet -### Example +### Example ```php placeOrder($body); print_r($result); } catch (Exception $e) { @@ -173,11 +173,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Order**](\Swagger\Client\Model\Order.md)| order placed for purchasing the pet | + **body** | [**\Swagger\Client\Model\Order**](../Model/\Swagger\Client\Model\Order.md)| order placed for purchasing the pet | ### Return type -[**\Swagger\Client\Model\Order**](Order.md) +[**\Swagger\Client\Model\Order**](../Model/Order.md) ### Authorization @@ -188,5 +188,5 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md index 7f048a429e3..5737f3cdb5e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md @@ -21,7 +21,7 @@ Create user This can only be done by the logged in user. -### Example +### Example ```php createUser($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), "\n"; @@ -41,7 +41,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User**](\Swagger\Client\Model\User.md)| Created user object | + **body** | [**\Swagger\Client\Model\User**](../Model/\Swagger\Client\Model\User.md)| Created user object | ### Return type @@ -56,7 +56,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **createUsersWithArrayInput** > createUsersWithArrayInput($body) @@ -65,7 +65,7 @@ Creates list of users with given input array -### Example +### Example ```php createUsersWithArrayInput($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), "\n"; @@ -85,7 +85,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User[]**](User.md)| List of user object | + **body** | [**\Swagger\Client\Model\User[]**](../Model/User.md)| List of user object | ### Return type @@ -100,7 +100,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **createUsersWithListInput** > createUsersWithListInput($body) @@ -109,7 +109,7 @@ Creates list of users with given input array -### Example +### Example ```php createUsersWithListInput($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), "\n"; @@ -129,7 +129,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User[]**](User.md)| List of user object | + **body** | [**\Swagger\Client\Model\User[]**](../Model/User.md)| List of user object | ### Return type @@ -144,7 +144,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **deleteUser** > deleteUser($username) @@ -153,7 +153,7 @@ Delete user This can only be done by the logged in user. -### Example +### Example ```php deleteUser($username); } catch (Exception $e) { echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), "\n"; @@ -188,7 +188,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **getUserByName** > \Swagger\Client\Model\User getUserByName($username) @@ -197,7 +197,7 @@ Get user by user name -### Example +### Example ```php getUserByName($username); print_r($result); } catch (Exception $e) { @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Return type -[**\Swagger\Client\Model\User**](User.md) +[**\Swagger\Client\Model\User**](../Model/User.md) ### Authorization @@ -233,7 +233,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **loginUser** > string loginUser($username, $password) @@ -242,7 +242,7 @@ Logs user into the system -### Example +### Example ```php loginUser($username, $password); print_r($result); } catch (Exception $e) { @@ -280,7 +280,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **logoutUser** > logoutUser() @@ -289,14 +289,14 @@ Logs out current logged in user session -### Example +### Example ```php logoutUser(); } catch (Exception $e) { echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), "\n"; @@ -320,7 +320,7 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **updateUser** > updateUser($username, $body) @@ -329,7 +329,7 @@ Updated user This can only be done by the logged in user. -### Example +### Example ```php updateUser($username, $body); } catch (Exception $e) { echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), "\n"; @@ -351,7 +351,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **string**| name that need to be deleted | - **body** | [**\Swagger\Client\Model\User**](\Swagger\Client\Model\User.md)| Updated user object | + **body** | [**\Swagger\Client\Model\User**](../Model/\Swagger\Client\Model\User.md)| Updated user object | ### Return type @@ -366,5 +366,5 @@ No authorization required - **Content-Type**: Not defined - **Accept**: application/xml, application/json -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/git_push.sh b/samples/client/petstore/php/SwaggerClient-php/git_push.sh index ed374619b13..792320114fb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/git_push.sh +++ b/samples/client/petstore/php/SwaggerClient-php/git_push.sh @@ -28,7 +28,7 @@ git init # Adds the files in the local repository and stages them for commit. git add . -# Commits the tracked changes and prepares them to be pushed to a remote repository. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 5620c82fdcd..794725eff23 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,12 +52,14 @@ class FakeApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ function __construct(\Swagger\Client\ApiClient $apiClient = null) @@ -66,22 +68,25 @@ class FakeApi $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return FakeApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,9 +94,9 @@ class FakeApi $this->apiClient = $apiClient; return $this; } - + /** - * testEndpointParameters + * Operation testEndpointParameters * * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @@ -107,18 +112,19 @@ class FakeApi * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function testEndpointParameters($number, $double, $string, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $binary = null, $date = null, $date_time = null, $password = null) { - list($response) = $this->testEndpointParametersWithHttpInfo ($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); - return $response; + list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); + return $response; } /** - * testEndpointParametersWithHttpInfo + * Operation testEndpointParametersWithHttpInfo * * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @@ -134,6 +140,7 @@ class FakeApi * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -202,7 +209,7 @@ class FakeApi throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } - + // parse inputs $resourcePath = "/fake"; $httpBody = ''; @@ -214,7 +221,7 @@ class FakeApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -259,7 +266,7 @@ class FakeApi $formParams['password'] = $this->apiClient->getSerializer()->toFormValue($password); } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -278,7 +285,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 4ab1529c7c0..30a718c247d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,12 +52,14 @@ class PetApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ function __construct(\Swagger\Client\ApiClient $apiClient = null) @@ -66,22 +68,25 @@ class PetApi $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return PetApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +94,31 @@ class PetApi $this->apiClient = $apiClient; return $this; } - + /** - * addPet + * Operation addPet * * Add a new pet to the store * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function addPet($body) { - list($response) = $this->addPetWithHttpInfo ($body); - return $response; + list($response) = $this->addPetWithHttpInfo($body); + return $response; } /** - * addPetWithHttpInfo + * Operation addPetWithHttpInfo * * Add a new pet to the store * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -122,7 +129,7 @@ class PetApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling addPet'); } - + // parse inputs $resourcePath = "/pet"; $httpBody = ''; @@ -134,7 +141,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); - + @@ -147,7 +154,7 @@ class PetApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -171,34 +178,36 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * deletePet + * Operation deletePet * * Deletes a pet * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deletePet($pet_id, $api_key = null) { - list($response) = $this->deletePetWithHttpInfo ($pet_id, $api_key); - return $response; + list($response) = $this->deletePetWithHttpInfo($pet_id, $api_key); + return $response; } /** - * deletePetWithHttpInfo + * Operation deletePetWithHttpInfo * * Deletes a pet * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -209,7 +218,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -221,7 +230,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // header params if ($api_key !== null) { @@ -240,7 +249,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -264,32 +273,34 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * findPetsByStatus + * Operation findPetsByStatus * * Finds Pets by status * * @param string[] $status Status values that need to be considered for filter (required) + * * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByStatus($status) { - list($response) = $this->findPetsByStatusWithHttpInfo ($status); - return $response; + list($response) = $this->findPetsByStatusWithHttpInfo($status); + return $response; } /** - * findPetsByStatusWithHttpInfo + * Operation findPetsByStatusWithHttpInfo * * Finds Pets by status * * @param string[] $status Status values that need to be considered for filter (required) + * * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -300,7 +311,7 @@ class PetApi if ($status === null) { throw new \InvalidArgumentException('Missing the required parameter $status when calling findPetsByStatus'); } - + // parse inputs $resourcePath = "/pet/findByStatus"; $httpBody = ''; @@ -312,7 +323,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if (is_array($status)) { $status = $this->apiClient->getSerializer()->serializeCollection($status, 'csv', true); @@ -327,7 +338,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -358,32 +369,34 @@ class PetApi $e->setResponseObject($data); break; } - + throw $e; } } /** - * findPetsByTags + * Operation findPetsByTags * * Finds Pets by tags * * @param string[] $tags Tags to filter by (required) + * * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByTags($tags) { - list($response) = $this->findPetsByTagsWithHttpInfo ($tags); - return $response; + list($response) = $this->findPetsByTagsWithHttpInfo($tags); + return $response; } /** - * findPetsByTagsWithHttpInfo + * Operation findPetsByTagsWithHttpInfo * * Finds Pets by tags * * @param string[] $tags Tags to filter by (required) + * * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -394,7 +407,7 @@ class PetApi if ($tags === null) { throw new \InvalidArgumentException('Missing the required parameter $tags when calling findPetsByTags'); } - + // parse inputs $resourcePath = "/pet/findByTags"; $httpBody = ''; @@ -406,7 +419,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if (is_array($tags)) { $tags = $this->apiClient->getSerializer()->serializeCollection($tags, 'csv', true); @@ -421,7 +434,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -452,32 +465,34 @@ class PetApi $e->setResponseObject($data); break; } - + throw $e; } } /** - * getPetById + * Operation getPetById * * Find pet by ID * * @param int $pet_id ID of pet to return (required) + * * @return \Swagger\Client\Model\Pet * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) { - list($response) = $this->getPetByIdWithHttpInfo ($pet_id); - return $response; + list($response) = $this->getPetByIdWithHttpInfo($pet_id); + return $response; } /** - * getPetByIdWithHttpInfo + * Operation getPetByIdWithHttpInfo * * Find pet by ID * * @param int $pet_id ID of pet to return (required) + * * @return Array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -488,7 +503,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -500,7 +515,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -516,7 +531,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -549,32 +564,34 @@ class PetApi $e->setResponseObject($data); break; } - + throw $e; } } /** - * updatePet + * Operation updatePet * * Update an existing pet * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePet($body) { - list($response) = $this->updatePetWithHttpInfo ($body); - return $response; + list($response) = $this->updatePetWithHttpInfo($body); + return $response; } /** - * updatePetWithHttpInfo + * Operation updatePetWithHttpInfo * * Update an existing pet * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -585,7 +602,7 @@ class PetApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updatePet'); } - + // parse inputs $resourcePath = "/pet"; $httpBody = ''; @@ -597,7 +614,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); - + @@ -610,7 +627,7 @@ class PetApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -634,36 +651,38 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * updatePetWithForm + * Operation updatePetWithForm * * Updates a pet in the store with form data * * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePetWithForm($pet_id, $name = null, $status = null) { - list($response) = $this->updatePetWithFormWithHttpInfo ($pet_id, $name, $status); - return $response; + list($response) = $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); + return $response; } /** - * updatePetWithFormWithHttpInfo + * Operation updatePetWithFormWithHttpInfo * * Updates a pet in the store with form data * * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -674,7 +693,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -686,7 +705,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); - + // path params @@ -708,7 +727,7 @@ class PetApi $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -732,36 +751,38 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * uploadFile + * Operation uploadFile * * uploads an image * * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) + * * @return \Swagger\Client\Model\ApiResponse * @throws \Swagger\Client\ApiException on non-2xx response */ public function uploadFile($pet_id, $additional_metadata = null, $file = null) { - list($response) = $this->uploadFileWithHttpInfo ($pet_id, $additional_metadata, $file); - return $response; + list($response) = $this->uploadFileWithHttpInfo($pet_id, $additional_metadata, $file); + return $response; } /** - * uploadFileWithHttpInfo + * Operation uploadFileWithHttpInfo * * uploads an image * * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) + * * @return Array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -772,7 +793,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } - + // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; $httpBody = ''; @@ -784,7 +805,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); - + // path params @@ -812,7 +833,7 @@ class PetApi } } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -843,7 +864,7 @@ class PetApi $e->setResponseObject($data); break; } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index a238eb41312..d05646adb68 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,12 +52,14 @@ class StoreApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ function __construct(\Swagger\Client\ApiClient $apiClient = null) @@ -66,22 +68,25 @@ class StoreApi $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return StoreApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +94,31 @@ class StoreApi $this->apiClient = $apiClient; return $this; } - + /** - * deleteOrder + * Operation deleteOrder * * Delete purchase order by ID * * @param string $order_id ID of the order that needs to be deleted (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrder($order_id) { - list($response) = $this->deleteOrderWithHttpInfo ($order_id); - return $response; + list($response) = $this->deleteOrderWithHttpInfo($order_id); + return $response; } /** - * deleteOrderWithHttpInfo + * Operation deleteOrderWithHttpInfo * * Delete purchase order by ID * * @param string $order_id ID of the order that needs to be deleted (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -126,7 +133,7 @@ class StoreApi throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.deleteOrder, must be bigger than or equal to 1.0.'); } - + // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; @@ -138,7 +145,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -154,7 +161,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -173,36 +180,38 @@ class StoreApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * getInventory + * Operation getInventory * * Returns pet inventories by status * + * * @return map[string,int] * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventory() { - list($response) = $this->getInventoryWithHttpInfo (); - return $response; + list($response) = $this->getInventoryWithHttpInfo(); + return $response; } /** - * getInventoryWithHttpInfo + * Operation getInventoryWithHttpInfo * * Returns pet inventories by status * + * * @return Array of map[string,int], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventoryWithHttpInfo() { - + // parse inputs $resourcePath = "/store/inventory"; $httpBody = ''; @@ -214,7 +223,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -223,7 +232,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -256,32 +265,34 @@ class StoreApi $e->setResponseObject($data); break; } - + throw $e; } } /** - * getOrderById + * Operation getOrderById * * Find purchase order by ID * * @param int $order_id ID of pet that needs to be fetched (required) + * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ public function getOrderById($order_id) { - list($response) = $this->getOrderByIdWithHttpInfo ($order_id); - return $response; + list($response) = $this->getOrderByIdWithHttpInfo($order_id); + return $response; } /** - * getOrderByIdWithHttpInfo + * Operation getOrderByIdWithHttpInfo * * Find purchase order by ID * * @param int $order_id ID of pet that needs to be fetched (required) + * * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -299,7 +310,7 @@ class StoreApi throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.0.'); } - + // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; @@ -311,7 +322,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -327,7 +338,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -353,32 +364,34 @@ class StoreApi $e->setResponseObject($data); break; } - + throw $e; } } /** - * placeOrder + * Operation placeOrder * * Place an order for a pet * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ public function placeOrder($body) { - list($response) = $this->placeOrderWithHttpInfo ($body); - return $response; + list($response) = $this->placeOrderWithHttpInfo($body); + return $response; } /** - * placeOrderWithHttpInfo + * Operation placeOrderWithHttpInfo * * Place an order for a pet * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -389,7 +402,7 @@ class StoreApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling placeOrder'); } - + // parse inputs $resourcePath = "/store/order"; $httpBody = ''; @@ -401,7 +414,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -414,7 +427,7 @@ class StoreApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -440,7 +453,7 @@ class StoreApi $e->setResponseObject($data); break; } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index ed9744b8255..aa57591b9e4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,12 +52,14 @@ class UserApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ function __construct(\Swagger\Client\ApiClient $apiClient = null) @@ -66,22 +68,25 @@ class UserApi $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return UserApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +94,31 @@ class UserApi $this->apiClient = $apiClient; return $this; } - + /** - * createUser + * Operation createUser * * Create user * * @param \Swagger\Client\Model\User $body Created user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUser($body) { - list($response) = $this->createUserWithHttpInfo ($body); - return $response; + list($response) = $this->createUserWithHttpInfo($body); + return $response; } /** - * createUserWithHttpInfo + * Operation createUserWithHttpInfo * * Create user * * @param \Swagger\Client\Model\User $body Created user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -122,7 +129,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUser'); } - + // parse inputs $resourcePath = "/user"; $httpBody = ''; @@ -134,7 +141,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -147,7 +154,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -166,32 +173,34 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * createUsersWithArrayInput + * Operation createUsersWithArrayInput * * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithArrayInput($body) { - list($response) = $this->createUsersWithArrayInputWithHttpInfo ($body); - return $response; + list($response) = $this->createUsersWithArrayInputWithHttpInfo($body); + return $response; } /** - * createUsersWithArrayInputWithHttpInfo + * Operation createUsersWithArrayInputWithHttpInfo * * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -202,7 +211,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithArrayInput'); } - + // parse inputs $resourcePath = "/user/createWithArray"; $httpBody = ''; @@ -214,7 +223,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -227,7 +236,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -246,32 +255,34 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * createUsersWithListInput + * Operation createUsersWithListInput * * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithListInput($body) { - list($response) = $this->createUsersWithListInputWithHttpInfo ($body); - return $response; + list($response) = $this->createUsersWithListInputWithHttpInfo($body); + return $response; } /** - * createUsersWithListInputWithHttpInfo + * Operation createUsersWithListInputWithHttpInfo * * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -282,7 +293,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithListInput'); } - + // parse inputs $resourcePath = "/user/createWithList"; $httpBody = ''; @@ -294,7 +305,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -307,7 +318,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -326,32 +337,34 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * deleteUser + * Operation deleteUser * * Delete user * * @param string $username The name that needs to be deleted (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteUser($username) { - list($response) = $this->deleteUserWithHttpInfo ($username); - return $response; + list($response) = $this->deleteUserWithHttpInfo($username); + return $response; } /** - * deleteUserWithHttpInfo + * Operation deleteUserWithHttpInfo * * Delete user * * @param string $username The name that needs to be deleted (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -362,7 +375,7 @@ class UserApi if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -374,7 +387,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -390,7 +403,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -409,32 +422,34 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * getUserByName + * Operation getUserByName * * Get user by user name * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * * @return \Swagger\Client\Model\User * @throws \Swagger\Client\ApiException on non-2xx response */ public function getUserByName($username) { - list($response) = $this->getUserByNameWithHttpInfo ($username); - return $response; + list($response) = $this->getUserByNameWithHttpInfo($username); + return $response; } /** - * getUserByNameWithHttpInfo + * Operation getUserByNameWithHttpInfo * * Get user by user name * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * * @return Array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -445,7 +460,7 @@ class UserApi if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -457,7 +472,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -473,7 +488,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -499,34 +514,36 @@ class UserApi $e->setResponseObject($data); break; } - + throw $e; } } /** - * loginUser + * Operation loginUser * * Logs user into the system * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) + * * @return string * @throws \Swagger\Client\ApiException on non-2xx response */ public function loginUser($username, $password) { - list($response) = $this->loginUserWithHttpInfo ($username, $password); - return $response; + list($response) = $this->loginUserWithHttpInfo($username, $password); + return $response; } /** - * loginUserWithHttpInfo + * Operation loginUserWithHttpInfo * * Logs user into the system * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) + * * @return Array of string, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -542,7 +559,7 @@ class UserApi if ($password === null) { throw new \InvalidArgumentException('Missing the required parameter $password when calling loginUser'); } - + // parse inputs $resourcePath = "/user/login"; $httpBody = ''; @@ -554,7 +571,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if ($username !== null) { $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); @@ -569,7 +586,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -595,36 +612,38 @@ class UserApi $e->setResponseObject($data); break; } - + throw $e; } } /** - * logoutUser + * Operation logoutUser * * Logs out current logged in user session * + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUser() { - list($response) = $this->logoutUserWithHttpInfo (); - return $response; + list($response) = $this->logoutUserWithHttpInfo(); + return $response; } /** - * logoutUserWithHttpInfo + * Operation logoutUserWithHttpInfo * * Logs out current logged in user session * + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUserWithHttpInfo() { - + // parse inputs $resourcePath = "/user/logout"; $httpBody = ''; @@ -636,7 +655,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -645,7 +664,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -664,34 +683,36 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } /** - * updateUser + * Operation updateUser * * Updated user * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updateUser($username, $body) { - list($response) = $this->updateUserWithHttpInfo ($username, $body); - return $response; + list($response) = $this->updateUserWithHttpInfo($username, $body); + return $response; } /** - * updateUserWithHttpInfo + * Operation updateUserWithHttpInfo * * Updated user * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -707,7 +728,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updateUser'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -719,7 +740,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -739,7 +760,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -758,7 +779,7 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index b28f2f26140..227d6b0d086 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -55,18 +55,21 @@ class ApiClient /** * Configuration + * * @var Configuration */ protected $config; /** * Object Serializer + * * @var ObjectSerializer */ protected $serializer; /** * Constructor of the class + * * @param Configuration $config config for this ApiClient */ public function __construct(\Swagger\Client\Configuration $config = null) @@ -81,6 +84,7 @@ class ApiClient /** * Get the config + * * @return Configuration */ public function getConfig() @@ -90,6 +94,7 @@ class ApiClient /** * Get the serializer + * * @return ObjectSerializer */ public function getSerializer() @@ -99,7 +104,9 @@ class ApiClient /** * Get API key (with prefix if set) + * * @param string $apiKeyIdentifier name of apikey + * * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKeyIdentifier) @@ -122,12 +129,14 @@ class ApiClient /** * Make the HTTP call (Sync) + * * @param string $resourcePath path to method endpoint * @param string $method method to call * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header * @param string $responseType expected response type of the endpoint + * * @throws \Swagger\Client\ApiException on a non 2xx response * @return mixed */ @@ -160,7 +169,7 @@ class ApiClient if ($this->config->getCurlTimeout() != 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } - // return the result on success, rather than just true + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -171,7 +180,7 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } - if (! empty($queryParams)) { + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } @@ -216,7 +225,7 @@ class ApiClient // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = $this->http_parse_headers(substr($response, 0, $http_header_size)); + $http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size)); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); @@ -295,16 +304,16 @@ class ApiClient * * @return string[] Array of HTTP response heaers */ - protected function http_parse_headers($raw_headers) + protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); $key = ''; - + foreach(explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); - + if (isset($h[1])) { if (!isset($headers[$h[0]])) @@ -317,18 +326,18 @@ class ApiClient { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } - + $key = $h[0]; } else { - if (substr($h[0], 0, 1) == "\t") - $headers[$key] .= "\r\n\t".trim($h[0]); + if (substr($h[0], 0, 1) == "\t") + $headers[$key] .= "\r\n\t".trim($h[0]); elseif (!$key) $headers[0] = trim($h[0]);trim($h[0]); } } - + return $headers; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index d6040a0ff20..370e3f8796b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -48,24 +48,28 @@ class ApiException extends Exception /** * The HTTP body of the server response either as Json or string. + * * @var mixed */ protected $responseBody; /** * The HTTP header of the server response. + * * @var string[] */ protected $responseHeaders; /** * The deserialized response object + * * @var $responseObject; */ protected $responseObject; /** * Constructor + * * @param string $message Error message * @param int $code HTTP status code * @param string $responseHeaders HTTP response header @@ -100,7 +104,9 @@ class ApiException extends Exception /** * Sets the deseralized response object (during deserialization) + * * @param mixed $obj Deserialized response object + * * @return void */ public function setResponseObject($obj) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 9da9c7edac0..ab6ebd899ac 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -110,7 +110,7 @@ class Configuration * * @var string */ - protected $userAgent = "Swagger-Codegen/1.0.0/php"; + protected $userAgent = "Swagger-Codegen//php"; /** * Debug switch (default set to false) @@ -517,7 +517,7 @@ class Configuration $report .= " OS: ".php_uname()."\n"; $report .= " PHP Version: ".phpversion()."\n"; $report .= " OpenAPI Spec Version: 1.0.0\n"; - $report .= " SDK Package Version: 1.0.0\n"; + $report .= " SDK Package Version: \n"; $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; return $report; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index 1bf893935db..a3f43300e72 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -125,7 +125,7 @@ class AnimalFarm implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php index e63691cc979..a4f045db926 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -125,7 +125,7 @@ class EnumClass implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index cb2ce24988b..e1cf6f4a0b2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -110,6 +110,12 @@ class EnumTest implements ArrayAccess return self::$getters; } + const ENUM_STRING_UPPER = 'UPPER'; + const ENUM_STRING_LOWER = 'lower'; + const ENUM_INTEGER_1 = 1; + const ENUM_INTEGER_MINUS_1 = -1; + const ENUM_NUMBER_1_DOT_1 = 1.1; + const ENUM_NUMBER_MINUS_1_DOT_2 = -1.2; @@ -120,7 +126,8 @@ class EnumTest implements ArrayAccess public function getEnumStringAllowableValues() { return [ - + self::ENUM_STRING_UPPER, + self::ENUM_STRING_LOWER, ]; } @@ -131,7 +138,8 @@ class EnumTest implements ArrayAccess public function getEnumIntegerAllowableValues() { return [ - + self::ENUM_INTEGER_1, + self::ENUM_INTEGER_MINUS_1, ]; } @@ -142,7 +150,8 @@ class EnumTest implements ArrayAccess public function getEnumNumberAllowableValues() { return [ - + self::ENUM_NUMBER_1_DOT_1, + self::ENUM_NUMBER_MINUS_1_DOT_2, ]; } @@ -169,7 +178,7 @@ class EnumTest implements ArrayAccess * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); $allowed_values = array("UPPER", "lower"); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 4e456262f6c..7cbfc09c168 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -69,7 +69,7 @@ class FormatTest implements ArrayAccess 'binary' => 'string', 'date' => '\DateTime', 'date_time' => '\DateTime', - 'uuid' => 'UUID', + 'uuid' => 'string', 'password' => 'string' ); @@ -578,7 +578,7 @@ class FormatTest implements ArrayAccess /** * Gets uuid - * @return UUID + * @return string */ public function getUuid() { @@ -587,7 +587,7 @@ class FormatTest implements ArrayAccess /** * Sets uuid - * @param UUID $uuid + * @param string $uuid * @return $this */ public function setUuid($uuid) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 6d7d227dd11..ff4feaecd85 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -122,6 +122,9 @@ class Order implements ArrayAccess return self::$getters; } + const STATUS_PLACED = 'placed'; + const STATUS_APPROVED = 'approved'; + const STATUS_DELIVERED = 'delivered'; @@ -132,7 +135,9 @@ class Order implements ArrayAccess public function getStatusAllowableValues() { return [ - + self::STATUS_PLACED, + self::STATUS_APPROVED, + self::STATUS_DELIVERED, ]; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 83e3c2b325f..f7e489f30ce 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -122,6 +122,9 @@ class Pet implements ArrayAccess return self::$getters; } + const STATUS_AVAILABLE = 'available'; + const STATUS_PENDING = 'pending'; + const STATUS_SOLD = 'sold'; @@ -132,7 +135,9 @@ class Pet implements ArrayAccess public function getStatusAllowableValues() { return [ - + self::STATUS_AVAILABLE, + self::STATUS_PENDING, + self::STATUS_SOLD, ]; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 3adaa899f5f..fa3abe1a22a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -1,6 +1,6 @@ fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - return $deserialized; + if (Configuration::getDefaultConfiguration()->getDebug()) { + error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + } + + return $deserialized; + } else { // If a discriminator is defined and points to a valid subclass, use it. if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { @@ -282,11 +286,11 @@ class ObjectSerializer $instance = new $class(); foreach ($instance::swaggerTypes() as $property => $type) { $propertySetter = $instance::setters()[$property]; - + if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { continue; } - + $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); From cc395fdf6326ab1742351a9c5652898b0614cbbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arne=20J=C3=B8rgensen?= Date: Sat, 14 May 2016 12:56:11 +0200 Subject: [PATCH 39/53] [PHP] Improve generated codestyle --- .../codegen/languages/PhpClientCodegen.java | 12 +++++++ .../src/main/resources/php/ApiClient.mustache | 33 ++++++++---------- .../main/resources/php/ApiException.mustache | 2 +- .../resources/php/ObjectSerializer.mustache | 8 ++--- .../src/main/resources/php/api.mustache | 34 ++++++++++++------- .../src/main/resources/php/api_test.mustache | 4 +-- .../main/resources/php/configuration.mustache | 11 +++--- .../src/main/resources/php/model.mustache | 25 ++++++++------ .../main/resources/php/model_test.mustache | 5 ++- .../phpcs-generated-code.xml | 10 ++++++ 10 files changed, 87 insertions(+), 57 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index c434bbe7a04..7bb9714bc0a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -3,6 +3,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; @@ -13,6 +14,7 @@ import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.HashSet; import java.util.regex.Matcher; @@ -626,4 +628,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // process enum in models return postProcessModelsEnum(objs); } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.vendorExtensions.put("x-testOperationId", camelize(op.operationId)); + } + return objs; + } } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 252c5d4a950..bfd811b89f0 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -237,7 +237,7 @@ class ApiClient // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { return array($http_body, $response_info['http_code'], $http_header); @@ -255,7 +255,9 @@ class ApiClient throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $data + $response_info['http_code'], + $http_header, + $data ); } return array($data, $response_info['http_code'], $http_header); @@ -310,31 +312,26 @@ class ApiClient $headers = array(); $key = ''; - foreach(explode("\n", $raw_headers) as $h) - { + foreach (explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); - if (isset($h[1])) - { - if (!isset($headers[$h[0]])) + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); - elseif (is_array($headers[$h[0]])) - { + } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); - } - else - { + } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } $key = $h[0]; - } - else - { - if (substr($h[0], 0, 1) == "\t") + } else { + if (substr($h[0], 0, 1) == "\t") { $headers[$key] .= "\r\n\t".trim($h[0]); - elseif (!$key) - $headers[0] = trim($h[0]);trim($h[0]); + } elseif (!$key) { + $headers[0] = trim($h[0]); + } + trim($h[0]); } } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 64dec1572ab..031e8cd995e 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -75,7 +75,7 @@ class ApiException extends Exception * @param string $responseHeaders HTTP response header * @param mixed $responseBody HTTP body of the server response either as Json or string */ - public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) + public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null) { parent::__construct($message, $code); $this->responseHeaders = $responseHeaders; diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 62a128cbb36..7de8d9d085e 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -185,7 +185,7 @@ class ObjectSerializer * * @return string */ - public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti=false) + public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { // http_build_query() almost does the job for us. We just @@ -219,7 +219,7 @@ class ObjectSerializer * * @return object an instance of $class */ - public static function deserialize($data, $class, $httpHeaders=null, $discriminator=null) + public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) { if (null === $data) { return null; @@ -261,7 +261,8 @@ class ObjectSerializer return $data; } elseif ($class === '\SplFileObject') { // determine file name - if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { + if (array_key_exists('Content-Disposition', $httpHeaders) && + preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); @@ -274,7 +275,6 @@ class ObjectSerializer } return $deserialized; - } else { // If a discriminator is defined and points to a valid subclass, use it. if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 34827ed0117..7a9b2afa993 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -62,7 +62,7 @@ use \{{invokerPackage}}\ObjectSerializer; * * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use */ - function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) + public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); @@ -99,7 +99,7 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Operation {{{operationId}}} * - * {{{summary}}} + * {{{summary}}}. * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @@ -116,7 +116,7 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Operation {{{operationId}}}WithHttpInfo * - * {{{summary}}} + * {{{summary}}}. * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @@ -215,7 +215,7 @@ use \{{invokerPackage}}\ObjectSerializer; if (function_exists('curl_file_create')) { $formParams['{{baseName}}'] = curl_file_create($this->apiClient->getSerializer()->toFormValue(${{paramName}})); } else { - $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); } {{/isFile}} {{^isFile}} @@ -251,9 +251,12 @@ use \{{invokerPackage}}\ObjectSerializer; // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, '{{httpMethod}}', - $queryParams, $httpBody, - $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} + $resourcePath, + '{{httpMethod}}', + $queryParams, + $httpBody, + $headerParams{{#returnType}}, + '{{returnType}}'{{/returnType}} ); {{#returnType}} if (!$response) { @@ -261,15 +264,20 @@ use \{{invokerPackage}}\ObjectSerializer; } return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader); - {{/returnType}}{{^returnType}} + {{/returnType}} + {{^returnType}} return array(null, $statusCode, $httpHeader); {{/returnType}} } catch (ApiException $e) { - switch ($e->getCode()) { {{#responses}}{{#dataType}} - {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); - $e->setResponseObject($data); - break;{{/dataType}}{{/responses}} + switch ($e->getCode()) { + {{#responses}} + {{#dataType}} + {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + {{/dataType}} + {{/responses}} } throw $e; diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index d41e76d040d..6a525223584 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -70,10 +70,10 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Test case for {{{operationId}}} * - * {{{summary}}} + * {{{summary}}}. * */ - public function test_{{operationId}}() + public function test{{vendorExtensions.x-testOperationId}}() { } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 0062fa8c25f..1b920e48357 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -47,7 +47,7 @@ namespace {{invokerPackage}}; class Configuration { - private static $_defaultConfiguration = null; + private static $defaultConfiguration = null; /** * Associate array to store API key(s) @@ -487,11 +487,11 @@ class Configuration */ public static function getDefaultConfiguration() { - if (self::$_defaultConfiguration == null) { - self::$_defaultConfiguration = new Configuration(); + if (self::$defaultConfiguration == null) { + self::$defaultConfiguration = new Configuration(); } - return self::$_defaultConfiguration; + return self::$defaultConfiguration; } /** @@ -503,7 +503,7 @@ class Configuration */ public static function setDefaultConfiguration(Configuration $config) { - self::$_defaultConfiguration = $config; + self::$defaultConfiguration = $config; } /** @@ -522,5 +522,4 @@ class Configuration return $report; } - } diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index ac08ed699b2..488b82433d9 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -41,7 +41,9 @@ use \ArrayAccess; * {{classname}} Class Doc Comment * * @category Class +{{#description}} * @description {{description}} +{{/description}} * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -53,18 +55,19 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * The original name of the model. * @var string */ - static $swaggerModelName = '{{name}}'; + protected static $swaggerModelName = '{{name}}'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes{{#parentSchema}} + parent::swaggerTypes(){{/parentSchema}}; } @@ -72,12 +75,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function attributeMap() { + public static function attributeMap() + { return {{#parentSchema}}parent::attributeMap() + {{/parentSchema}}self::$attributeMap; } @@ -85,12 +89,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function setters() { + public static function setters() + { return {{#parentSchema}}parent::setters() + {{/parentSchema}}self::$setters; } @@ -98,12 +103,12 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function getters() + public static function getters() { return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters; } @@ -267,7 +272,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * Sets {{name}} - * @param {{datatype}} ${{name}} {{#description}}{{{description}}}{{/description}} + * @param {{datatype}} ${{name}}{{#description}} {{{description}}}{{/description}} * @return $this */ public function {{setter}}(${{name}}) diff --git a/modules/swagger-codegen/src/main/resources/php/model_test.mustache b/modules/swagger-codegen/src/main/resources/php/model_test.mustache index b79b5840e30..3482629f917 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_test.mustache @@ -39,7 +39,7 @@ namespace {{modelPackage}}; * {{classname}}Test Class Doc Comment * * @category Class - * @description {{description}} + * @description {{#description}}{{description}}{{/description}}{{^description}}{{classname}}{{/description}} * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -65,13 +65,12 @@ class {{classname}}Test extends \PHPUnit_Framework_TestCase } /** - * Test {{classname}} + * Test "{{classname}}" */ public function test{{classname}}() { } - } {{/model}} {{/models}} diff --git a/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml b/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml new file mode 100644 index 00000000000..a0173077aa9 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml @@ -0,0 +1,10 @@ + + + + Arnes Drupal code checker + + + + * + + From 1f02fd281f30a644eb4e9d4ddfcb8c73b92247fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arne=20J=C3=B8rgensen?= Date: Sat, 14 May 2016 13:04:23 +0200 Subject: [PATCH 40/53] [PHP] Regenerate petstore sample --- .../petstore/php/SwaggerClient-php/README.md | 14 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 15 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 156 ++++++++++-------- .../SwaggerClient-php/lib/Api/StoreApi.php | 90 +++++----- .../php/SwaggerClient-php/lib/Api/UserApi.php | 130 ++++++++------- .../php/SwaggerClient-php/lib/ApiClient.php | 33 ++-- .../SwaggerClient-php/lib/ApiException.php | 2 +- .../SwaggerClient-php/lib/Configuration.php | 11 +- .../SwaggerClient-php/lib/Model/Animal.php | 26 +-- .../lib/Model/AnimalFarm.php | 22 +-- .../lib/Model/ApiResponse.php | 28 ++-- .../php/SwaggerClient-php/lib/Model/Cat.php | 24 +-- .../SwaggerClient-php/lib/Model/Category.php | 26 +-- .../php/SwaggerClient-php/lib/Model/Dog.php | 24 +-- .../SwaggerClient-php/lib/Model/EnumClass.php | 22 +-- .../SwaggerClient-php/lib/Model/EnumTest.php | 28 ++-- .../lib/Model/FormatTest.php | 48 +++--- .../lib/Model/Model200Response.php | 23 +-- .../lib/Model/ModelReturn.php | 23 +-- .../php/SwaggerClient-php/lib/Model/Name.php | 29 ++-- .../php/SwaggerClient-php/lib/Model/Order.php | 32 ++-- .../php/SwaggerClient-php/lib/Model/Pet.php | 32 ++-- .../lib/Model/SpecialModelName.php | 24 +-- .../php/SwaggerClient-php/lib/Model/Tag.php | 26 +-- .../php/SwaggerClient-php/lib/Model/User.php | 36 ++-- .../lib/ObjectSerializer.php | 10 +- .../lib/Tests/AnimalFarmTest.php | 73 -------- .../lib/Tests/AnimalTest.php | 73 -------- .../lib/Tests/ApiResponseTest.php | 73 -------- .../SwaggerClient-php/lib/Tests/CatTest.php | 73 -------- .../lib/Tests/CategoryTest.php | 73 -------- .../SwaggerClient-php/lib/Tests/DogTest.php | 73 -------- .../lib/Tests/EnumClassTest.php | 73 -------- .../lib/Tests/EnumTestTest.php | 73 -------- .../lib/Tests/FormatTestTest.php | 73 -------- .../lib/Tests/Model200ResponseTest.php | 73 -------- .../lib/Tests/ModelReturnTest.php | 73 -------- .../SwaggerClient-php/lib/Tests/NameTest.php | 73 -------- .../SwaggerClient-php/lib/Tests/OrderTest.php | 73 -------- .../SwaggerClient-php/lib/Tests/PetTest.php | 73 -------- .../lib/Tests/SpecialModelNameTest.php | 73 -------- .../SwaggerClient-php/lib/Tests/TagTest.php | 73 -------- .../SwaggerClient-php/lib/Tests/UserTest.php | 73 -------- .../test/Api/FakeApiTest.php | 15 +- .../SwaggerClient-php/test/Api/PetApiTest.php | 50 +++--- .../test/Api/StoreApiTest.php | 30 ++-- .../test/Api/UserApiTest.php | 50 +++--- .../test/Model/AnimalFarmTest.php | 14 +- .../test/Model/AnimalTest.php | 14 +- .../test/Model/ApiResponseTest.php | 14 +- .../SwaggerClient-php/test/Model/CatTest.php | 14 +- .../test/Model/CategoryTest.php | 14 +- .../SwaggerClient-php/test/Model/DogTest.php | 14 +- .../test/Model/EnumClassTest.php | 14 +- .../test/Model/EnumTestTest.php | 14 +- .../test/Model/FormatTestTest.php | 14 +- .../test/Model/Model200ResponseTest.php | 12 +- .../test/Model/ModelReturnTest.php | 12 +- .../SwaggerClient-php/test/Model/NameTest.php | 12 +- .../test/Model/OrderTest.php | 14 +- .../SwaggerClient-php/test/Model/PetTest.php | 14 +- .../test/Model/SpecialModelNameTest.php | 14 +- .../SwaggerClient-php/test/Model/TagTest.php | 14 +- .../SwaggerClient-php/test/Model/UserTest.php | 14 +- 64 files changed, 723 insertions(+), 1829 deletions(-) delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalFarmTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/ApiResponseTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/CatTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/CategoryTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/DogTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumClassTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumTestTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/FormatTestTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/Model200ResponseTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/ModelReturnTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/NameTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/OrderTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/PetTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/SpecialModelNameTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/TagTest.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/UserTest.php diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 6385bef4e6b..9da8dacc922 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -5,7 +5,7 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git - API version: 1.0.0 - Package version: -- Build date: 2016-05-14T17:06:01.056+08:00 +- Build date: 2016-05-14T13:02:51.476+02:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -134,12 +134,6 @@ Class | Method | HTTP request | Description ## Documentation For Authorization -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## petstore_auth - **Type**: OAuth @@ -149,6 +143,12 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 794725eff23..63abb0c94b6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -62,7 +62,7 @@ class FakeApi * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); @@ -98,7 +98,7 @@ class FakeApi /** * Operation testEndpointParameters * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 . * * @param float $number None (required) * @param double $double None (required) @@ -126,7 +126,7 @@ class FakeApi /** * Operation testEndpointParametersWithHttpInfo * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 . * * @param float $number None (required) * @param double $double None (required) @@ -276,14 +276,15 @@ class FakeApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 30a718c247d..402d727c5bf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -62,7 +62,7 @@ class PetApi * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); @@ -98,7 +98,7 @@ class PetApi /** * Operation addPet * - * Add a new pet to the store + * Add a new pet to the store. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @@ -115,7 +115,7 @@ class PetApi /** * Operation addPetWithHttpInfo * - * Add a new pet to the store + * Add a new pet to the store. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @@ -169,14 +169,15 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -185,7 +186,7 @@ class PetApi /** * Operation deletePet * - * Deletes a pet + * Deletes a pet. * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) @@ -203,7 +204,7 @@ class PetApi /** * Operation deletePetWithHttpInfo * - * Deletes a pet + * Deletes a pet. * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) @@ -264,14 +265,15 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -280,7 +282,7 @@ class PetApi /** * Operation findPetsByStatus * - * Finds Pets by status + * Finds Pets by status. * * @param string[] $status Status values that need to be considered for filter (required) * @@ -297,7 +299,7 @@ class PetApi /** * Operation findPetsByStatusWithHttpInfo * - * Finds Pets by status + * Finds Pets by status. * * @param string[] $status Status values that need to be considered for filter (required) * @@ -353,21 +355,24 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet[]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; @@ -376,7 +381,7 @@ class PetApi /** * Operation findPetsByTags * - * Finds Pets by tags + * Finds Pets by tags. * * @param string[] $tags Tags to filter by (required) * @@ -393,7 +398,7 @@ class PetApi /** * Operation findPetsByTagsWithHttpInfo * - * Finds Pets by tags + * Finds Pets by tags. * * @param string[] $tags Tags to filter by (required) * @@ -449,21 +454,24 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet[]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; @@ -472,7 +480,7 @@ class PetApi /** * Operation getPetById * - * Find pet by ID + * Find pet by ID. * * @param int $pet_id ID of pet to return (required) * @@ -489,7 +497,7 @@ class PetApi /** * Operation getPetByIdWithHttpInfo * - * Find pet by ID + * Find pet by ID. * * @param int $pet_id ID of pet to return (required) * @@ -548,21 +556,24 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; @@ -571,7 +582,7 @@ class PetApi /** * Operation updatePet * - * Update an existing pet + * Update an existing pet. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @@ -588,7 +599,7 @@ class PetApi /** * Operation updatePetWithHttpInfo * - * Update an existing pet + * Update an existing pet. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @@ -642,14 +653,15 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'PUT', - $queryParams, $httpBody, + $resourcePath, + 'PUT', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -658,7 +670,7 @@ class PetApi /** * Operation updatePetWithForm * - * Updates a pet in the store with form data + * Updates a pet in the store with form data. * * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) @@ -677,7 +689,7 @@ class PetApi /** * Operation updatePetWithFormWithHttpInfo * - * Updates a pet in the store with form data + * Updates a pet in the store with form data. * * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) @@ -742,14 +754,15 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -758,7 +771,7 @@ class PetApi /** * Operation uploadFile * - * uploads an image + * uploads an image. * * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) @@ -777,7 +790,7 @@ class PetApi /** * Operation uploadFileWithHttpInfo * - * uploads an image + * uploads an image. * * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) @@ -829,7 +842,7 @@ class PetApi if (function_exists('curl_file_create')) { $formParams['file'] = curl_file_create($this->apiClient->getSerializer()->toFormValue($file)); } else { - $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); + $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); } } @@ -848,21 +861,24 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\ApiResponse' + $resourcePath, + 'POST', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\ApiResponse' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index d05646adb68..cfc6ddba361 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -62,7 +62,7 @@ class StoreApi * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); @@ -98,7 +98,7 @@ class StoreApi /** * Operation deleteOrder * - * Delete purchase order by ID + * Delete purchase order by ID. * * @param string $order_id ID of the order that needs to be deleted (required) * @@ -115,7 +115,7 @@ class StoreApi /** * Operation deleteOrderWithHttpInfo * - * Delete purchase order by ID + * Delete purchase order by ID. * * @param string $order_id ID of the order that needs to be deleted (required) * @@ -171,14 +171,15 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -187,7 +188,7 @@ class StoreApi /** * Operation getInventory * - * Returns pet inventories by status + * Returns pet inventories by status. * * * @return map[string,int] @@ -203,7 +204,7 @@ class StoreApi /** * Operation getInventoryWithHttpInfo * - * Returns pet inventories by status + * Returns pet inventories by status. * * * @return Array of map[string,int], HTTP status code, HTTP response headers (array of strings) @@ -249,21 +250,24 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'map[string,int]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + 'map[string,int]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; @@ -272,7 +276,7 @@ class StoreApi /** * Operation getOrderById * - * Find purchase order by ID + * Find purchase order by ID. * * @param int $order_id ID of pet that needs to be fetched (required) * @@ -289,7 +293,7 @@ class StoreApi /** * Operation getOrderByIdWithHttpInfo * - * Find purchase order by ID + * Find purchase order by ID. * * @param int $order_id ID of pet that needs to be fetched (required) * @@ -348,21 +352,24 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Order' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; @@ -371,7 +378,7 @@ class StoreApi /** * Operation placeOrder * - * Place an order for a pet + * Place an order for a pet. * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @@ -388,7 +395,7 @@ class StoreApi /** * Operation placeOrderWithHttpInfo * - * Place an order for a pet + * Place an order for a pet. * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @@ -437,21 +444,24 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order' + $resourcePath, + 'POST', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Order' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index aa57591b9e4..7d3188747a5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -62,7 +62,7 @@ class UserApi * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); @@ -98,7 +98,7 @@ class UserApi /** * Operation createUser * - * Create user + * Create user. * * @param \Swagger\Client\Model\User $body Created user object (required) * @@ -115,7 +115,7 @@ class UserApi /** * Operation createUserWithHttpInfo * - * Create user + * Create user. * * @param \Swagger\Client\Model\User $body Created user object (required) * @@ -164,14 +164,15 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -180,7 +181,7 @@ class UserApi /** * Operation createUsersWithArrayInput * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @@ -197,7 +198,7 @@ class UserApi /** * Operation createUsersWithArrayInputWithHttpInfo * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @@ -246,14 +247,15 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -262,7 +264,7 @@ class UserApi /** * Operation createUsersWithListInput * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @@ -279,7 +281,7 @@ class UserApi /** * Operation createUsersWithListInputWithHttpInfo * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @@ -328,14 +330,15 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -344,7 +347,7 @@ class UserApi /** * Operation deleteUser * - * Delete user + * Delete user. * * @param string $username The name that needs to be deleted (required) * @@ -361,7 +364,7 @@ class UserApi /** * Operation deleteUserWithHttpInfo * - * Delete user + * Delete user. * * @param string $username The name that needs to be deleted (required) * @@ -413,14 +416,15 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -429,7 +433,7 @@ class UserApi /** * Operation getUserByName * - * Get user by user name + * Get user by user name. * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @@ -446,7 +450,7 @@ class UserApi /** * Operation getUserByNameWithHttpInfo * - * Get user by user name + * Get user by user name. * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @@ -498,21 +502,24 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\User' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\User' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; @@ -521,7 +528,7 @@ class UserApi /** * Operation loginUser * - * Logs user into the system + * Logs user into the system. * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) @@ -539,7 +546,7 @@ class UserApi /** * Operation loginUserWithHttpInfo * - * Logs user into the system + * Logs user into the system. * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) @@ -596,21 +603,24 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'string' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + 'string' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } throw $e; @@ -619,7 +629,7 @@ class UserApi /** * Operation logoutUser * - * Logs out current logged in user session + * Logs out current logged in user session. * * * @return void @@ -635,7 +645,7 @@ class UserApi /** * Operation logoutUserWithHttpInfo * - * Logs out current logged in user session + * Logs out current logged in user session. * * * @return Array of null, HTTP status code, HTTP response headers (array of strings) @@ -674,14 +684,15 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, + $resourcePath, + 'GET', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; @@ -690,7 +701,7 @@ class UserApi /** * Operation updateUser * - * Updated user + * Updated user. * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) @@ -708,7 +719,7 @@ class UserApi /** * Operation updateUserWithHttpInfo * - * Updated user + * Updated user. * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) @@ -770,14 +781,15 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'PUT', - $queryParams, $httpBody, + $resourcePath, + 'PUT', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } throw $e; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 227d6b0d086..6370b9be7a5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -237,7 +237,7 @@ class ApiClient // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { return array($http_body, $response_info['http_code'], $http_header); @@ -255,7 +255,9 @@ class ApiClient throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $data + $response_info['http_code'], + $http_header, + $data ); } return array($data, $response_info['http_code'], $http_header); @@ -310,31 +312,26 @@ class ApiClient $headers = array(); $key = ''; - foreach(explode("\n", $raw_headers) as $h) - { + foreach (explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); - if (isset($h[1])) - { - if (!isset($headers[$h[0]])) + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); - elseif (is_array($headers[$h[0]])) - { + } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); - } - else - { + } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } $key = $h[0]; - } - else - { - if (substr($h[0], 0, 1) == "\t") + } else { + if (substr($h[0], 0, 1) == "\t") { $headers[$key] .= "\r\n\t".trim($h[0]); - elseif (!$key) - $headers[0] = trim($h[0]);trim($h[0]); + } elseif (!$key) { + $headers[0] = trim($h[0]); + } + trim($h[0]); } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 370e3f8796b..94421bac149 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -75,7 +75,7 @@ class ApiException extends Exception * @param string $responseHeaders HTTP response header * @param mixed $responseBody HTTP body of the server response either as Json or string */ - public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) + public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null) { parent::__construct($message, $code); $this->responseHeaders = $responseHeaders; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index ab6ebd899ac..33bf0e93651 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -47,7 +47,7 @@ namespace Swagger\Client; class Configuration { - private static $_defaultConfiguration = null; + private static $defaultConfiguration = null; /** * Associate array to store API key(s) @@ -487,11 +487,11 @@ class Configuration */ public static function getDefaultConfiguration() { - if (self::$_defaultConfiguration == null) { - self::$_defaultConfiguration = new Configuration(); + if (self::$defaultConfiguration == null) { + self::$defaultConfiguration = new Configuration(); } - return self::$_defaultConfiguration; + return self::$defaultConfiguration; } /** @@ -503,7 +503,7 @@ class Configuration */ public static function setDefaultConfiguration(Configuration $config) { - self::$_defaultConfiguration = $config; + self::$defaultConfiguration = $config; } /** @@ -522,5 +522,4 @@ class Configuration return $report; } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 732153c3aab..6b05974a644 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Animal Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,18 +50,19 @@ class Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Animal'; + protected static $swaggerModelName = 'Animal'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'class_name' => 'string', 'color' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -70,12 +70,13 @@ class Animal implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'class_name' => 'className', 'color' => 'color' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +84,13 @@ class Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'class_name' => 'setClassName', 'color' => 'setColor' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +98,12 @@ class Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'class_name' => 'getClassName', 'color' => 'getColor' ); - static function getters() + public static function getters() { return self::$getters; } @@ -170,7 +172,7 @@ class Animal implements ArrayAccess /** * Sets class_name - * @param string $class_name + * @param string $class_name * @return $this */ public function setClassName($class_name) @@ -191,7 +193,7 @@ class Animal implements ArrayAccess /** * Sets color - * @param string $color + * @param string $color * @return $this */ public function setColor($color) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index a3f43300e72..a699455bcf9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -39,7 +39,6 @@ use \ArrayAccess; * AnimalFarm Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,17 +50,18 @@ class AnimalFarm implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'AnimalFarm'; + protected static $swaggerModelName = 'AnimalFarm'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -69,11 +69,12 @@ class AnimalFarm implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +82,12 @@ class AnimalFarm implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +95,11 @@ class AnimalFarm implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( ); - static function getters() + public static function getters() { return self::$getters; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index b2a8628df50..53ced7e8810 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -39,7 +39,6 @@ use \ArrayAccess; * ApiResponse Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,19 +50,20 @@ class ApiResponse implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'ApiResponse'; + protected static $swaggerModelName = 'ApiResponse'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'code' => 'int', 'type' => 'string', 'message' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -71,13 +71,14 @@ class ApiResponse implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'code' => 'code', 'type' => 'type', 'message' => 'message' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -85,13 +86,14 @@ class ApiResponse implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'code' => 'setCode', 'type' => 'setType', 'message' => 'setMessage' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -99,13 +101,13 @@ class ApiResponse implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'code' => 'getCode', 'type' => 'getType', 'message' => 'getMessage' ); - static function getters() + public static function getters() { return self::$getters; } @@ -165,7 +167,7 @@ class ApiResponse implements ArrayAccess /** * Sets code - * @param int $code + * @param int $code * @return $this */ public function setCode($code) @@ -186,7 +188,7 @@ class ApiResponse implements ArrayAccess /** * Sets type - * @param string $type + * @param string $type * @return $this */ public function setType($type) @@ -207,7 +209,7 @@ class ApiResponse implements ArrayAccess /** * Sets message - * @param string $message + * @param string $message * @return $this */ public function setMessage($message) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 0c9f1c3652f..9eb4de596d8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Cat Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,17 +50,18 @@ class Cat extends Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Cat'; + protected static $swaggerModelName = 'Cat'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'declawed' => 'bool' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes + parent::swaggerTypes(); } @@ -69,11 +69,12 @@ class Cat extends Animal implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'declawed' => 'declawed' ); - static function attributeMap() { + public static function attributeMap() + { return parent::attributeMap() + self::$attributeMap; } @@ -81,11 +82,12 @@ class Cat extends Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'declawed' => 'setDeclawed' ); - static function setters() { + public static function setters() + { return parent::setters() + self::$setters; } @@ -93,11 +95,11 @@ class Cat extends Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'declawed' => 'getDeclawed' ); - static function getters() + public static function getters() { return parent::getters() + self::$getters; } @@ -157,7 +159,7 @@ class Cat extends Animal implements ArrayAccess /** * Sets declawed - * @param bool $declawed + * @param bool $declawed * @return $this */ public function setDeclawed($declawed) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 720e17a6200..8e3c5e6fb5e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Category Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,18 +50,19 @@ class Category implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Category'; + protected static $swaggerModelName = 'Category'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'name' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -70,12 +70,13 @@ class Category implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +84,13 @@ class Category implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +98,12 @@ class Category implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'name' => 'getName' ); - static function getters() + public static function getters() { return self::$getters; } @@ -160,7 +162,7 @@ class Category implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -181,7 +183,7 @@ class Category implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index 7e162508f5f..9212a8c5d3b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Dog Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,17 +50,18 @@ class Dog extends Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Dog'; + protected static $swaggerModelName = 'Dog'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'breed' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes + parent::swaggerTypes(); } @@ -69,11 +69,12 @@ class Dog extends Animal implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'breed' => 'breed' ); - static function attributeMap() { + public static function attributeMap() + { return parent::attributeMap() + self::$attributeMap; } @@ -81,11 +82,12 @@ class Dog extends Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'breed' => 'setBreed' ); - static function setters() { + public static function setters() + { return parent::setters() + self::$setters; } @@ -93,11 +95,11 @@ class Dog extends Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'breed' => 'getBreed' ); - static function getters() + public static function getters() { return parent::getters() + self::$getters; } @@ -157,7 +159,7 @@ class Dog extends Animal implements ArrayAccess /** * Sets breed - * @param string $breed + * @param string $breed * @return $this */ public function setBreed($breed) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php index a4f045db926..71fb3357d14 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -39,7 +39,6 @@ use \ArrayAccess; * EnumClass Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,17 +50,18 @@ class EnumClass implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'EnumClass'; + protected static $swaggerModelName = 'EnumClass'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -69,11 +69,12 @@ class EnumClass implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +82,12 @@ class EnumClass implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +95,11 @@ class EnumClass implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( ); - static function getters() + public static function getters() { return self::$getters; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index e1cf6f4a0b2..77751f9c43f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -39,7 +39,6 @@ use \ArrayAccess; * EnumTest Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,19 +50,20 @@ class EnumTest implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Enum_Test'; + protected static $swaggerModelName = 'Enum_Test'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'enum_string' => 'string', 'enum_integer' => 'int', 'enum_number' => 'double' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -71,13 +71,14 @@ class EnumTest implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'enum_string' => 'enum_string', 'enum_integer' => 'enum_integer', 'enum_number' => 'enum_number' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -85,13 +86,14 @@ class EnumTest implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'enum_string' => 'setEnumString', 'enum_integer' => 'setEnumInteger', 'enum_number' => 'setEnumNumber' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -99,13 +101,13 @@ class EnumTest implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'enum_string' => 'getEnumString', 'enum_integer' => 'getEnumInteger', 'enum_number' => 'getEnumNumber' ); - static function getters() + public static function getters() { return self::$getters; } @@ -231,7 +233,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_string - * @param string $enum_string + * @param string $enum_string * @return $this */ public function setEnumString($enum_string) @@ -256,7 +258,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_integer - * @param int $enum_integer + * @param int $enum_integer * @return $this */ public function setEnumInteger($enum_integer) @@ -281,7 +283,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_number - * @param double $enum_number + * @param double $enum_number * @return $this */ public function setEnumNumber($enum_number) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 7cbfc09c168..07148e70189 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -39,7 +39,6 @@ use \ArrayAccess; * FormatTest Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +50,13 @@ class FormatTest implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'format_test'; + protected static $swaggerModelName = 'format_test'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'integer' => 'int', 'int32' => 'int', 'int64' => 'int', @@ -73,7 +72,8 @@ class FormatTest implements ArrayAccess 'password' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -81,7 +81,7 @@ class FormatTest implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'integer' => 'integer', 'int32' => 'int32', 'int64' => 'int64', @@ -97,7 +97,8 @@ class FormatTest implements ArrayAccess 'password' => 'password' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -105,7 +106,7 @@ class FormatTest implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'integer' => 'setInteger', 'int32' => 'setInt32', 'int64' => 'setInt64', @@ -121,7 +122,8 @@ class FormatTest implements ArrayAccess 'password' => 'setPassword' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -129,7 +131,7 @@ class FormatTest implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'integer' => 'getInteger', 'int32' => 'getInt32', 'int64' => 'getInt64', @@ -145,7 +147,7 @@ class FormatTest implements ArrayAccess 'password' => 'getPassword' ); - static function getters() + public static function getters() { return self::$getters; } @@ -317,7 +319,7 @@ class FormatTest implements ArrayAccess /** * Sets integer - * @param int $integer + * @param int $integer * @return $this */ public function setInteger($integer) @@ -345,7 +347,7 @@ class FormatTest implements ArrayAccess /** * Sets int32 - * @param int $int32 + * @param int $int32 * @return $this */ public function setInt32($int32) @@ -373,7 +375,7 @@ class FormatTest implements ArrayAccess /** * Sets int64 - * @param int $int64 + * @param int $int64 * @return $this */ public function setInt64($int64) @@ -394,7 +396,7 @@ class FormatTest implements ArrayAccess /** * Sets number - * @param float $number + * @param float $number * @return $this */ public function setNumber($number) @@ -422,7 +424,7 @@ class FormatTest implements ArrayAccess /** * Sets float - * @param float $float + * @param float $float * @return $this */ public function setFloat($float) @@ -450,7 +452,7 @@ class FormatTest implements ArrayAccess /** * Sets double - * @param double $double + * @param double $double * @return $this */ public function setDouble($double) @@ -478,7 +480,7 @@ class FormatTest implements ArrayAccess /** * Sets string - * @param string $string + * @param string $string * @return $this */ public function setString($string) @@ -503,7 +505,7 @@ class FormatTest implements ArrayAccess /** * Sets byte - * @param string $byte + * @param string $byte * @return $this */ public function setByte($byte) @@ -524,7 +526,7 @@ class FormatTest implements ArrayAccess /** * Sets binary - * @param string $binary + * @param string $binary * @return $this */ public function setBinary($binary) @@ -545,7 +547,7 @@ class FormatTest implements ArrayAccess /** * Sets date - * @param \DateTime $date + * @param \DateTime $date * @return $this */ public function setDate($date) @@ -566,7 +568,7 @@ class FormatTest implements ArrayAccess /** * Sets date_time - * @param \DateTime $date_time + * @param \DateTime $date_time * @return $this */ public function setDateTime($date_time) @@ -587,7 +589,7 @@ class FormatTest implements ArrayAccess /** * Sets uuid - * @param string $uuid + * @param string $uuid * @return $this */ public function setUuid($uuid) @@ -608,7 +610,7 @@ class FormatTest implements ArrayAccess /** * Sets password - * @param string $password + * @param string $password * @return $this */ public function setPassword($password) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 989602fa2c5..88a28981f29 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -51,17 +51,18 @@ class Model200Response implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = '200_response'; + protected static $swaggerModelName = '200_response'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'name' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -69,11 +70,12 @@ class Model200Response implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +83,12 @@ class Model200Response implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +96,11 @@ class Model200Response implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'name' => 'getName' ); - static function getters() + public static function getters() { return self::$getters; } @@ -155,7 +158,7 @@ class Model200Response implements ArrayAccess /** * Sets name - * @param int $name + * @param int $name * @return $this */ public function setName($name) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 64a19e20cf8..d1b188ff231 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -51,17 +51,18 @@ class ModelReturn implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Return'; + protected static $swaggerModelName = 'Return'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'return' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -69,11 +70,12 @@ class ModelReturn implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'return' => 'return' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +83,12 @@ class ModelReturn implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'return' => 'setReturn' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +96,11 @@ class ModelReturn implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'return' => 'getReturn' ); - static function getters() + public static function getters() { return self::$getters; } @@ -155,7 +158,7 @@ class ModelReturn implements ArrayAccess /** * Sets return - * @param int $return + * @param int $return * @return $this */ public function setReturn($return) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index 4caea36ff6d..294d45dffe3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -51,20 +51,21 @@ class Name implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Name'; + protected static $swaggerModelName = 'Name'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'name' => 'int', 'snake_case' => 'int', 'property' => 'string', '_123_number' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -72,14 +73,15 @@ class Name implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'name' => 'name', 'snake_case' => 'snake_case', 'property' => 'property', '_123_number' => '123Number' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -87,14 +89,15 @@ class Name implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'name' => 'setName', 'snake_case' => 'setSnakeCase', 'property' => 'setProperty', '_123_number' => 'set123Number' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -102,14 +105,14 @@ class Name implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'name' => 'getName', 'snake_case' => 'getSnakeCase', 'property' => 'getProperty', '_123_number' => 'get123Number' ); - static function getters() + public static function getters() { return self::$getters; } @@ -176,7 +179,7 @@ class Name implements ArrayAccess /** * Sets name - * @param int $name + * @param int $name * @return $this */ public function setName($name) @@ -197,7 +200,7 @@ class Name implements ArrayAccess /** * Sets snake_case - * @param int $snake_case + * @param int $snake_case * @return $this */ public function setSnakeCase($snake_case) @@ -218,7 +221,7 @@ class Name implements ArrayAccess /** * Sets property - * @param string $property + * @param string $property * @return $this */ public function setProperty($property) @@ -239,7 +242,7 @@ class Name implements ArrayAccess /** * Sets _123_number - * @param int $_123_number + * @param int $_123_number * @return $this */ public function set123Number($_123_number) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index ff4feaecd85..3bd377eae71 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Order Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +50,13 @@ class Order implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Order'; + protected static $swaggerModelName = 'Order'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'pet_id' => 'int', 'quantity' => 'int', @@ -66,7 +65,8 @@ class Order implements ArrayAccess 'complete' => 'bool' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -74,7 +74,7 @@ class Order implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'pet_id' => 'petId', 'quantity' => 'quantity', @@ -83,7 +83,8 @@ class Order implements ArrayAccess 'complete' => 'complete' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -91,7 +92,7 @@ class Order implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'pet_id' => 'setPetId', 'quantity' => 'setQuantity', @@ -100,7 +101,8 @@ class Order implements ArrayAccess 'complete' => 'setComplete' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -108,7 +110,7 @@ class Order implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'pet_id' => 'getPetId', 'quantity' => 'getQuantity', @@ -117,7 +119,7 @@ class Order implements ArrayAccess 'complete' => 'getComplete' ); - static function getters() + public static function getters() { return self::$getters; } @@ -204,7 +206,7 @@ class Order implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -225,7 +227,7 @@ class Order implements ArrayAccess /** * Sets pet_id - * @param int $pet_id + * @param int $pet_id * @return $this */ public function setPetId($pet_id) @@ -246,7 +248,7 @@ class Order implements ArrayAccess /** * Sets quantity - * @param int $quantity + * @param int $quantity * @return $this */ public function setQuantity($quantity) @@ -267,7 +269,7 @@ class Order implements ArrayAccess /** * Sets ship_date - * @param \DateTime $ship_date + * @param \DateTime $ship_date * @return $this */ public function setShipDate($ship_date) @@ -313,7 +315,7 @@ class Order implements ArrayAccess /** * Sets complete - * @param bool $complete + * @param bool $complete * @return $this */ public function setComplete($complete) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index f7e489f30ce..378c979629c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Pet Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +50,13 @@ class Pet implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Pet'; + protected static $swaggerModelName = 'Pet'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'category' => '\Swagger\Client\Model\Category', 'name' => 'string', @@ -66,7 +65,8 @@ class Pet implements ArrayAccess 'status' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -74,7 +74,7 @@ class Pet implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'category' => 'category', 'name' => 'name', @@ -83,7 +83,8 @@ class Pet implements ArrayAccess 'status' => 'status' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -91,7 +92,7 @@ class Pet implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'category' => 'setCategory', 'name' => 'setName', @@ -100,7 +101,8 @@ class Pet implements ArrayAccess 'status' => 'setStatus' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -108,7 +110,7 @@ class Pet implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'category' => 'getCategory', 'name' => 'getName', @@ -117,7 +119,7 @@ class Pet implements ArrayAccess 'status' => 'getStatus' ); - static function getters() + public static function getters() { return self::$getters; } @@ -216,7 +218,7 @@ class Pet implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -237,7 +239,7 @@ class Pet implements ArrayAccess /** * Sets category - * @param \Swagger\Client\Model\Category $category + * @param \Swagger\Client\Model\Category $category * @return $this */ public function setCategory($category) @@ -258,7 +260,7 @@ class Pet implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) @@ -279,7 +281,7 @@ class Pet implements ArrayAccess /** * Sets photo_urls - * @param string[] $photo_urls + * @param string[] $photo_urls * @return $this */ public function setPhotoUrls($photo_urls) @@ -300,7 +302,7 @@ class Pet implements ArrayAccess /** * Sets tags - * @param \Swagger\Client\Model\Tag[] $tags + * @param \Swagger\Client\Model\Tag[] $tags * @return $this */ public function setTags($tags) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index 00d6d960e07..025ee4b7b3b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -39,7 +39,6 @@ use \ArrayAccess; * SpecialModelName Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,17 +50,18 @@ class SpecialModelName implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = '$special[model.name]'; + protected static $swaggerModelName = '$special[model.name]'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'special_property_name' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -69,11 +69,12 @@ class SpecialModelName implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'special_property_name' => '$special[property.name]' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +82,12 @@ class SpecialModelName implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'special_property_name' => 'setSpecialPropertyName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +95,11 @@ class SpecialModelName implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'special_property_name' => 'getSpecialPropertyName' ); - static function getters() + public static function getters() { return self::$getters; } @@ -155,7 +157,7 @@ class SpecialModelName implements ArrayAccess /** * Sets special_property_name - * @param int $special_property_name + * @param int $special_property_name * @return $this */ public function setSpecialPropertyName($special_property_name) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 19f44cc9456..8fba6e43dd8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Tag Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,18 +50,19 @@ class Tag implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Tag'; + protected static $swaggerModelName = 'Tag'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'name' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -70,12 +70,13 @@ class Tag implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +84,13 @@ class Tag implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +98,12 @@ class Tag implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'name' => 'getName' ); - static function getters() + public static function getters() { return self::$getters; } @@ -160,7 +162,7 @@ class Tag implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -181,7 +183,7 @@ class Tag implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 5de8893be43..04b4f749437 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -39,7 +39,6 @@ use \ArrayAccess; * User Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +50,13 @@ class User implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'User'; + protected static $swaggerModelName = 'User'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'username' => 'string', 'first_name' => 'string', @@ -68,7 +67,8 @@ class User implements ArrayAccess 'user_status' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } @@ -76,7 +76,7 @@ class User implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'username' => 'username', 'first_name' => 'firstName', @@ -87,7 +87,8 @@ class User implements ArrayAccess 'user_status' => 'userStatus' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -95,7 +96,7 @@ class User implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'username' => 'setUsername', 'first_name' => 'setFirstName', @@ -106,7 +107,8 @@ class User implements ArrayAccess 'user_status' => 'setUserStatus' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -114,7 +116,7 @@ class User implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'username' => 'getUsername', 'first_name' => 'getFirstName', @@ -125,7 +127,7 @@ class User implements ArrayAccess 'user_status' => 'getUserStatus' ); - static function getters() + public static function getters() { return self::$getters; } @@ -190,7 +192,7 @@ class User implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -211,7 +213,7 @@ class User implements ArrayAccess /** * Sets username - * @param string $username + * @param string $username * @return $this */ public function setUsername($username) @@ -232,7 +234,7 @@ class User implements ArrayAccess /** * Sets first_name - * @param string $first_name + * @param string $first_name * @return $this */ public function setFirstName($first_name) @@ -253,7 +255,7 @@ class User implements ArrayAccess /** * Sets last_name - * @param string $last_name + * @param string $last_name * @return $this */ public function setLastName($last_name) @@ -274,7 +276,7 @@ class User implements ArrayAccess /** * Sets email - * @param string $email + * @param string $email * @return $this */ public function setEmail($email) @@ -295,7 +297,7 @@ class User implements ArrayAccess /** * Sets password - * @param string $password + * @param string $password * @return $this */ public function setPassword($password) @@ -316,7 +318,7 @@ class User implements ArrayAccess /** * Sets phone - * @param string $phone + * @param string $phone * @return $this */ public function setPhone($phone) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index fa3abe1a22a..6d656ac2b97 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -185,7 +185,7 @@ class ObjectSerializer * * @return string */ - public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti=false) + public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { // http_build_query() almost does the job for us. We just @@ -219,7 +219,7 @@ class ObjectSerializer * * @return object an instance of $class */ - public static function deserialize($data, $class, $httpHeaders=null, $discriminator=null) + public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) { if (null === $data) { return null; @@ -256,12 +256,13 @@ class ObjectSerializer } else { return null; } - } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { + } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { // determine file name - if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { + if (array_key_exists('Content-Disposition', $httpHeaders) && + preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); @@ -274,7 +275,6 @@ class ObjectSerializer } return $deserialized; - } else { // If a discriminator is defined and points to a valid subclass, use it. if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalFarmTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalFarmTest.php deleted file mode 100644 index 61797bfd16c..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalFarmTest.php +++ /dev/null @@ -1,73 +0,0 @@ - Date: Sat, 14 May 2016 13:41:13 +0200 Subject: [PATCH 41/53] [PHP] Improve codestyle of phpunit tests --- .../tests/ObjectSerializerTest.php | 8 +- .../SwaggerClient-php/tests/OrderApiTest.php | 44 ++-- .../SwaggerClient-php/tests/PetApiTest.php | 194 ++++++++++-------- .../SwaggerClient-php/tests/StoreApiTest.php | 29 ++- .../SwaggerClient-php/tests/UserApiTest.php | 49 ++--- 5 files changed, 168 insertions(+), 156 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php index 14bbc0de913..ce147d0e9e2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php @@ -1,6 +1,6 @@ assertSame("sun.gif", $s->sanitizeFilename("sun.gif")); $this->assertSame("sun.gif", $s->sanitizeFilename("../sun.gif")); @@ -22,8 +22,4 @@ class ObjectSerializerTest extends \PHPUnit_Framework_TestCase $this->assertSame("sun.gif", $s->sanitizeFilename("c:\var\tmp\sun.gif")); $this->assertSame("sun.gif", $s->sanitizeFilename(".\sun.gif")); } - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php index 8ef5a8e5058..8b5c8f7e499 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -1,12 +1,13 @@ assertSame(Swagger\Client\Model\Order::STATUS_PLACED, "placed"); - $this->assertSame(Swagger\Client\Model\Order::STATUS_APPROVED, "approved"); + $this->assertSame(Model\Order::STATUS_PLACED, "placed"); + $this->assertSame(Model\Order::STATUS_APPROVED, "approved"); } // test get inventory public function testOrder() { // initialize the API client - $order = new Swagger\Client\Model\Order(); + $order = new Model\Order(); $order->setStatus("placed"); $this->assertSame("placed", $order->getStatus()); @@ -31,11 +32,11 @@ class OrderApiTest extends \PHPUnit_Framework_TestCase /** * @expectedException InvalidArgumentException - */ + */ public function testOrderException() { // initialize the API client - $order = new Swagger\Client\Model\Order(); + $order = new Model\Order(); $order->setStatus("invalid_value"); } @@ -52,13 +53,16 @@ class OrderApiTest extends \PHPUnit_Framework_TestCase "complete": false } ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'Swagger\Client\Model\Order'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'Swagger\Client\Model\Order' + ); $this->assertInstanceOf('Swagger\Client\Model\Order', $order); $this->assertSame(10, $order->getId()); $this->assertSame(20, $order->getPetId()); $this->assertSame(30, $order->getQuantity()); - $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); $this->assertSame("placed", $order->getStatus()); $this->assertSame(false, $order->getComplete()); } @@ -76,16 +80,19 @@ ORDER; "complete": false }]] ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'Swagger\Client\Model\Order[][]'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'Swagger\Client\Model\Order[][]' + ); - $this->assertArrayHasKey(0, $order); + $this->assertArrayHasKey(0, $order); $this->assertArrayHasKey(0, $order[0]); $_order = $order[0][0]; $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); $this->assertSame(10, $_order->getId()); $this->assertSame(20, $_order->getPetId()); $this->assertSame(30, $_order->getQuantity()); - $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); $this->assertSame("placed", $_order->getStatus()); $this->assertSame(false, $_order->getComplete()); } @@ -107,21 +114,20 @@ ORDER; } } ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'map[string,map[string,\Swagger\Client\Model\Order]]'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'map[string,map[string,\Swagger\Client\Model\Order]]' + ); - $this->assertArrayHasKey('test', $order); + $this->assertArrayHasKey('test', $order); $this->assertArrayHasKey('test2', $order['test']); $_order = $order['test']['test2']; $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); $this->assertSame(10, $_order->getId()); $this->assertSame(20, $_order->getPetId()); $this->assertSame(30, $_order->getQuantity()); - $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); $this->assertSame("placed", $_order->getStatus()); $this->assertSame(false, $_order->getComplete()); } - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 9feabf142cf..fa3733a8be2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -1,16 +1,17 @@ setId($new_pet_id); $new_pet->setName("PHP Unit Test"); $new_pet->setPhotoUrls(array("http://test_php_unit_test.com")); // new tag - $tag= new Swagger\Client\Model\Tag; + $tag= new Model\Tag; $tag->setId($new_pet_id); // use the same id as pet $tag->setName("test php tag"); // new category - $category = new Swagger\Client\Model\Category; + $category = new Model\Category; $category->setId($new_pet_id); // use the same id as pet $category->setName("test php category"); $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } // test static functions defined in ApiClient public function testApiClient() - { + { // test selectHeaderAccept - $api_client = new Swagger\Client\ApiClient(); - $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json'))); - $this->assertSame(NULL, $api_client->selectHeaderAccept(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml'))); + $api_client = new ApiClient(); + $this->assertSame('application/json', $api_client->selectHeaderAccept(array( + 'application/xml', + 'application/json' + ))); + $this->assertSame(null, $api_client->selectHeaderAccept(array())); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array( + 'application/yaml', + 'application/xml' + ))); // test selectHeaderContentType - $this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml','application/json'))); + $this->assertSame('application/json', $api_client->selectHeaderContentType(array( + 'application/xml', + 'application/json' + ))); $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array( + 'application/yaml', + 'application/xml' + ))); // test addDefaultHeader and getDefaultHeader $api_client->getConfig()->addDefaultHeader('test1', 'value1'); @@ -74,16 +87,16 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertFalse(isset($defaultHeader['test2'])); - $pet_api2 = new Swagger\Client\Api\PetApi(); - $config3 = new Swagger\Client\Configuration(); - $apiClient3 = new Swagger\Client\ApiClient($config3); + $pet_api2 = new Api\PetApi(); + $config3 = new Configuration(); + $apiClient3 = new ApiClient($config3); $apiClient3->getConfig()->setUserAgent('api client 3'); - $config4 = new Swagger\Client\Configuration(); - $apiClient4 = new Swagger\Client\ApiClient($config4); + $config4 = new Configuration(); + $apiClient4 = new ApiClient($config4); $apiClient4->getConfig()->setUserAgent('api client 4'); - $pet_api3 = new Swagger\Client\Api\PetApi($apiClient3); + $pet_api3 = new Api\PetApi($apiClient3); - // 2 different api clients are not the same + // 2 different api clients are not the same $this->assertNotEquals($apiClient3, $apiClient4); // customied pet api not using the old pet api's api client $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); @@ -98,7 +111,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) $response = $pet_api->getPetById($pet_id); @@ -111,7 +124,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); } - /* + /** * comment out as we've removed invalid endpoints from the spec, we'll introduce something * similar in the future when we've time to update the petstore server * @@ -120,7 +133,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (inline model) $response = $pet_api->getPetByIdInObject($pet_id); @@ -144,7 +157,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); @@ -162,18 +175,18 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testFindPetByStatus() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); $this->assertGreaterThan(0, count($response)); // at least one object returned $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" + // loop through result to ensure status is "available" foreach ($response as $_pet) { $this->assertSame($_pet['status'], "available"); } - // test invalid status + // test invalid status $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); $this->assertSame(count($response), 0); // confirm no object returned } @@ -182,18 +195,18 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testFindPetsByTags() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // return Pet (model) $response = $pet_api->findPetsByTags("test php tag"); $this->assertGreaterThan(0, count($response)); // at least one object returned $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" + // loop through result to ensure status is "available" foreach ($response as $_pet) { $this->assertSame($_pet['tags'][0]['name'], "test php tag"); } - // test invalid status + // test invalid status $response = $pet_api->findPetsByTags("unknown_and_incorrect_tag"); $this->assertSame(count($response), 0); // confirm no object returned } @@ -202,19 +215,19 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePet() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // create updated pet object - $updated_pet = new Swagger\Client\Model\Pet; + $updated_pet = new Model\Pet; $updated_pet->setId($pet_id); $updated_pet->setName('updatePet'); // new name $updated_pet->setStatus('pending'); // new status // update Pet (model/json) $update_response = $pet_api->updatePet($updated_pet); // return nothing (void) - $this->assertSame($update_response, NULL); + $this->assertSame($update_response, null); // verify updated Pet $response = $pet_api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); @@ -226,12 +239,15 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePetWithFormWithHttpInfo() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // update Pet (form) - list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo($pet_id, 'update pet with form with http info'); + list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo( + $pet_id, + 'update pet with form with http info' + ); // return nothing (void) $this->assertNull($update_response); $this->assertSame($status_code, 200); @@ -245,14 +261,14 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePetWithForm() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // update Pet (form) $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) - $this->assertSame($update_response, NULL); + $this->assertSame($update_response, null); $response = $pet_api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getName(), 'update pet with form'); @@ -263,17 +279,17 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testAddPet() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test 2"); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); // return nothing (void) - $this->assertSame($add_response, NULL); + $this->assertSame($add_response, null); // verify added Pet $response = $pet_api->getPetById($new_pet_id); $this->assertSame($response->getId(), $new_pet_id); @@ -288,28 +304,28 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testAddPetUsingByteArray() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test 3"); // new tag - $tag= new Swagger\Client\Model\Tag; + $tag= new Model\Tag; $tag->setId($new_pet_id); // use the same id as pet $tag->setName("test php tag"); // new category - $category = new Swagger\Client\Model\Category; + $category = new Model\Category; $category->setId($new_pet_id); // use the same id as pet $category->setName("test php category"); $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // add a new pet (model) - $object_serializer = new Swagger\Client\ObjectSerializer(); + $object_serializer = new ObjectSerializer(); $pet_json_string = json_encode($object_serializer->sanitizeForSerialization($new_pet)); $add_response = $pet_api->addPetUsingByteArray($pet_json_string); // return nothing (void) @@ -325,13 +341,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUploadFile() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // upload file $pet_id = 10001; $response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); - // return ApiResponse + // return ApiResponse $this->assertInstanceOf('Swagger\Client\Model\ApiResponse', $response); } @@ -340,10 +356,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $config = new Swagger\Client\Configuration(); + $config = new Configuration(); $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\APIClient($config); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + $api_client = new APIClient($config); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventory(); @@ -359,10 +375,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetPetByIdWithByteArray() { // initialize the API client - $config = new Swagger\Client\Configuration(); + $config = new Configuration(); $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\APIClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $api_client = new APIClient($config); + $pet_api = new Api\PetApi($api_client); // test getPetByIdWithByteArray $pet_id = 10005; $bytes = $pet_api->petPetIdtestingByteArraytrueGet($pet_id); @@ -383,7 +399,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test empty object serialization public function testEmptyPetSerialization() { - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; // the empty object should be serialised to {} $this->assertSame("{}", "$new_pet"); @@ -392,7 +408,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test inheritance in the model public function testInheritance() { - $new_dog = new Swagger\Client\Model\Dog; + $new_dog = new Model\Dog; // the object should be an instance of the derived class $this->assertInstanceOf('Swagger\Client\Model\Dog', $new_dog); // the object should also be an instance of the parent class @@ -408,7 +424,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase 'class_name' => 'Dog', 'breed' => 'Great Dane' ); - $new_dog = new Swagger\Client\Model\Dog($data); + $new_dog = new Model\Dog($data); // the property on the derived class should be set $this->assertSame('Great Dane', $new_dog->getBreed()); @@ -419,7 +435,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test if discriminator is initialized automatically public function testDiscriminatorInitialization() { - $new_dog = new Swagger\Client\Model\Dog(); + $new_dog = new Model\Dog(); $this->assertSame('Dog', $new_dog->getClassName()); } @@ -428,13 +444,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // create an AnimalFarm which is an object implementing the // ArrayAccess interface - $farm = new Swagger\Client\Model\AnimalFarm(); + $farm = new Model\AnimalFarm(); // add some animals to the farm to make sure the ArrayAccess // interface works - $farm[] = new Swagger\Client\Model\Dog(); - $farm[] = new Swagger\Client\Model\Cat(); - $farm[] = new Swagger\Client\Model\Animal(); + $farm[] = new Model\Dog(); + $farm[] = new Model\Cat(); + $farm[] = new Model\Animal(); // assert we can look up the animals in the farm by array // indices (let's try a random order) @@ -455,16 +471,12 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // add some animals to the farm to make sure the ArrayAccess // interface works - $dog = new Swagger\Client\Model\Dog(); - $animal = new Swagger\Client\Model\Animal(); + $dog = new Model\Dog(); + $animal = new Model\Animal(); // assert we can look up the animals in the farm by array // indices (let's try a random order) $this->assertSame('red', $dog->getColor()); $this->assertSame('red', $animal->getColor()); } - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index 7d7dcf3ede3..800cd512e4f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -1,34 +1,35 @@ setId($new_pet_id); $new_pet->setName("PHP Unit Test"); $new_pet->setStatus("available"); // new tag - $tag= new Swagger\Client\Model\Tag; + $tag= new Model\Tag; $tag->setId($new_pet_id); // use the same id as pet $tag->setName("test php tag"); // new category - $category = new Swagger\Client\Model\Category; + $category = new Model\Category; $category->setId($new_pet_id); // use the same id as pet $category->setName("test php category"); $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api = new Api\PetAPI(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } @@ -37,9 +38,9 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventory(); @@ -55,9 +56,9 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase public function testGetInventoryInObject() { // initialize the API client - //$config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient(); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + //$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient(); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventoryInObject(); @@ -65,8 +66,4 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase $this->assertInternalType("int", $get_response['available']); } */ - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index 3efce8b08ba..a8487e58764 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -1,33 +1,34 @@ setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $user_api = new Swagger\Client\Api\UserApi($api_client); - // login - $response = $user_api->loginUser("xxxxx", "yyyyyyyy"); - - $this->assertInternalType("string", $response); - $this->assertRegExp("/^logged in user session/", $response, "response string starts with 'logged in user session'"); - - } + // test login user + public function testLoginUser() + { + // initialize the API client + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $user_api = new Api\UserApi($api_client); + // login + $response = $user_api->loginUser("xxxxx", "yyyyyyyy"); + + $this->assertInternalType("string", $response); + $this->assertRegExp( + "/^logged in user session/", + $response, + "response string starts with 'logged in user session'" + ); + } } - -?> - From 88474621987be4d63edc5a5014119e02bd89e325 Mon Sep 17 00:00:00 2001 From: Newell Zhu Date: Thu, 12 May 2016 01:12:44 +0800 Subject: [PATCH 42/53] setup rails 5 basic structure --- bin/rails5-petstore-server.sh | 31 ++ bin/windows/rails-petstore-server.bat | 10 + .../languages/Rails5ServerCodegen.java | 323 ++++++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../src/main/resources/rails5/.keep | 0 .../src/main/resources/rails5/404.html | 67 ++++ .../src/main/resources/rails5/422.html | 67 ++++ .../src/main/resources/rails5/500.html | 66 ++++ .../src/main/resources/rails5/Gemfile | 36 ++ .../src/main/resources/rails5/README.md | 25 ++ .../src/main/resources/rails5/Rakefile | 6 + ...e_record_belongs_to_required_by_default.rb | 6 + .../rails5/apple-touch-icon-precomposed.png | 0 .../resources/rails5/apple-touch-icon.png | 0 .../src/main/resources/rails5/application.rb | 30 ++ .../rails5/application_controller.rb | 2 + .../rails5/application_controller_renderer.rb | 6 + .../main/resources/rails5/application_job.rb | 2 + .../resources/rails5/application_mailer.rb | 4 + .../resources/rails5/application_record.rb | 3 + .../resources/rails5/backtrace_silencers.rb | 7 + .../src/main/resources/rails5/boot.rb | 3 + .../src/main/resources/rails5/bundle | 3 + .../src/main/resources/rails5/cable.yml | 10 + .../resources/rails5/callback_terminator.rb | 6 + .../src/main/resources/rails5/channel.rb | 5 + .../src/main/resources/rails5/config.ru | 5 + .../src/main/resources/rails5/connection.rb | 5 + .../main/resources/rails5/controller.mustache | 22 ++ .../src/main/resources/rails5/cors.rb | 16 + .../src/main/resources/rails5/database.yml | 54 +++ .../src/main/resources/rails5/development.rb | 47 +++ .../src/main/resources/rails5/en.yml | 23 ++ .../src/main/resources/rails5/environment.rb | 5 + .../src/main/resources/rails5/favicon.ico | 0 .../rails5/filter_parameter_logging.rb | 4 + .../src/main/resources/rails5/inflections.rb | 16 + .../src/main/resources/rails5/mailer.html.erb | 13 + .../src/main/resources/rails5/mailer.text.erb | 1 + .../src/main/resources/rails5/mime_types.rb | 4 + .../src/main/resources/rails5/production.rb | 80 +++++ .../src/main/resources/rails5/puma.rb | 47 +++ .../src/main/resources/rails5/rails | 4 + .../src/main/resources/rails5/rake | 4 + .../src/main/resources/rails5/restart.txt | 0 .../src/main/resources/rails5/robots.txt | 5 + .../src/main/resources/rails5/routes.mustache | 3 + .../src/main/resources/rails5/schema.rb | 16 + .../src/main/resources/rails5/secrets.yml | 22 ++ .../src/main/resources/rails5/seeds.rb | 7 + .../src/main/resources/rails5/setup | 34 ++ .../src/main/resources/rails5/spring.rb | 6 + .../src/main/resources/rails5/ssl_options.rb | 4 + .../src/main/resources/rails5/test.rb | 42 +++ .../src/main/resources/rails5/test_helper.rb | 10 + .../rails5/to_time_preserves_timezone.rb | 10 + .../src/main/resources/rails5/update | 29 ++ .../main/resources/rails5/wrap_parameters.rb | 14 + .../options/Rails5ServerOptionsProvider.java | 23 ++ 59 files changed, 1294 insertions(+) create mode 100755 bin/rails5-petstore-server.sh create mode 100644 bin/windows/rails-petstore-server.bat create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/rails5/.keep create mode 100644 modules/swagger-codegen/src/main/resources/rails5/404.html create mode 100644 modules/swagger-codegen/src/main/resources/rails5/422.html create mode 100644 modules/swagger-codegen/src/main/resources/rails5/500.html create mode 100644 modules/swagger-codegen/src/main/resources/rails5/Gemfile create mode 100644 modules/swagger-codegen/src/main/resources/rails5/README.md create mode 100644 modules/swagger-codegen/src/main/resources/rails5/Rakefile create mode 100644 modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon-precomposed.png create mode 100644 modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon.png create mode 100644 modules/swagger-codegen/src/main/resources/rails5/application.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/application_controller.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/application_job.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/application_record.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/boot.rb create mode 100755 modules/swagger-codegen/src/main/resources/rails5/bundle create mode 100644 modules/swagger-codegen/src/main/resources/rails5/cable.yml create mode 100644 modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/channel.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/config.ru create mode 100644 modules/swagger-codegen/src/main/resources/rails5/connection.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/controller.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rails5/cors.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/database.yml create mode 100644 modules/swagger-codegen/src/main/resources/rails5/development.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/en.yml create mode 100644 modules/swagger-codegen/src/main/resources/rails5/environment.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/favicon.ico create mode 100644 modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/inflections.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/mime_types.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/production.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/puma.rb create mode 100755 modules/swagger-codegen/src/main/resources/rails5/rails create mode 100755 modules/swagger-codegen/src/main/resources/rails5/rake create mode 100644 modules/swagger-codegen/src/main/resources/rails5/restart.txt create mode 100644 modules/swagger-codegen/src/main/resources/rails5/robots.txt create mode 100644 modules/swagger-codegen/src/main/resources/rails5/routes.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rails5/schema.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/secrets.yml create mode 100644 modules/swagger-codegen/src/main/resources/rails5/seeds.rb create mode 100755 modules/swagger-codegen/src/main/resources/rails5/setup create mode 100644 modules/swagger-codegen/src/main/resources/rails5/spring.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/test.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/test_helper.rb create mode 100644 modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb create mode 100755 modules/swagger-codegen/src/main/resources/rails5/update create mode 100644 modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java diff --git a/bin/rails5-petstore-server.sh b/bin/rails5-petstore-server.sh new file mode 100755 index 00000000000..28b3ca3069b --- /dev/null +++ b/bin/rails5-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/rails5 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l rails5 -o samples/server/petstore/rails5" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/rails-petstore-server.bat b/bin/windows/rails-petstore-server.bat new file mode 100644 index 00000000000..55677b55197 --- /dev/null +++ b/bin/windows/rails-petstore-server.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\rails5 -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l aspnet5 -o samples\server\petstore\rails5\ + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java new file mode 100644 index 00000000000..cbf77338ab3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -0,0 +1,323 @@ +package io.swagger.codegen.languages; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.Swagger; +import io.swagger.util.Yaml; + +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class); + + protected String gemName; + protected String moduleName; + protected String gemVersion = "1.0.0"; + protected String appFolder = "app"; + protected String channelsFolder = appFolder + File.separator + "channels"; + protected String applicationCableFolder = channelsFolder + File.separator + "application_cable"; + protected String controllersFolder = appFolder + File.separator + "controllers"; + protected String jobsFolder = appFolder + File.separator + "jobs"; + protected String mailersFolder = appFolder + File.separator + "mailers"; + protected String modelsFolder = appFolder + File.separator + "models"; + protected String viewsFolder = appFolder + File.separator + "views"; + protected String layoutsFolder = viewsFolder + File.separator + "layouts"; + protected String binFolder = "bin"; + protected String configFolder = "config"; + protected String environmentsFolder = configFolder + File.separator + "config"; + protected String initializersFolder = configFolder + File.separator + "initializers"; + protected String localesFolder = configFolder + File.separator + "locales"; + protected String dbFolder = "db"; + protected String migrateFolder = dbFolder + File.separator + "migrate"; + protected String libFolder = "lib"; + protected String tasksFolder = libFolder + File.separator + "tasks"; + protected String logFolder = "log"; + protected String publicFolder = "public"; + protected String testFolder = "test"; + protected String tmpFolder = "tmp"; + protected String cacheFolder = tmpFolder + File.separator + "cache"; + protected String pidFolder = tmpFolder + File.separator + "pids"; + protected String socketsFolder = tmpFolder + File.separator + "sockets"; + protected String vendorFolder = "vendor"; + + public Rails5ServerCodegen() { + super(); + apiPackage = "app/controllers"; + outputFolder = "generated-code" + File.separator + "rails5"; + + // no model + modelTemplateFiles.clear(); + apiTemplateFiles.put("controller.mustache", ".rb"); + embeddedTemplateDir = templateDir = "rails5"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + setReservedWordsLowerCase( + Arrays.asList( + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", + "if", "not", "return", "undef", "yield") + ); + + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("array"); + languageSpecificPrimitives.add("map"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("DateTime"); + + typeMapping.put("long", "int"); + typeMapping.put("integer", "int"); + typeMapping.put("Array", "array"); + typeMapping.put("String", "string"); + typeMapping.put("List", "array"); + typeMapping.put("map", "map"); + //TODO binary should be mapped to byte array + // mapped to String as a workaround + typeMapping.put("binary", "string"); + + // remove modelPackage and apiPackage added by default + cliOptions.clear(); + } + + @Override + public void processOpts() { + super.processOpts(); + + // use constant model/api package (folder path) + //setModelPackage("models"); + setApiPackage("app/controllers"); + + supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("Rakefile", "", "Rakefile")); + supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); + supportingFiles.add(new SupportingFile("channel.rb", applicationCableFolder, "channel.rb")); + supportingFiles.add(new SupportingFile("connection.rb", applicationCableFolder, "connection.rb")); + supportingFiles.add(new SupportingFile("application_controller.rb", controllersFolder, "application_controller.rb")); + supportingFiles.add(new SupportingFile("application_job.rb", jobsFolder, "application_job.rb")); + supportingFiles.add(new SupportingFile("application_mailer.rb", mailersFolder, "application_mailer.rb")); + supportingFiles.add(new SupportingFile("application_record.rb", modelsFolder, "application_record.rb")); + supportingFiles.add(new SupportingFile("mailer.html.erb", layoutsFolder, "mailer.html.erb")); + supportingFiles.add(new SupportingFile("mailer.text.erb", layoutsFolder, "mailer.text.erb")); + supportingFiles.add(new SupportingFile("bundle", binFolder, "bundle")); + supportingFiles.add(new SupportingFile("rails", binFolder, "rails")); + supportingFiles.add(new SupportingFile("rake", binFolder, "rake")); + supportingFiles.add(new SupportingFile("setup", binFolder, "setup")); + supportingFiles.add(new SupportingFile("update", binFolder, "update")); + supportingFiles.add(new SupportingFile("development.rb", environmentsFolder, "development.rb")); + supportingFiles.add(new SupportingFile("production.rb", environmentsFolder, "production.rb")); + supportingFiles.add(new SupportingFile("active_record_belongs_to_required_by_default.rb", initializersFolder, "active_record_belongs_to_required_by_default.rb")); + supportingFiles.add(new SupportingFile("application_controller_renderer.rb", initializersFolder, "application_controller_renderer.rb")); + supportingFiles.add(new SupportingFile("backtrace_silencers.rb", initializersFolder, "backtrace_silencers.rb")); + supportingFiles.add(new SupportingFile("callback_terminator.rb", initializersFolder, "callback_terminator.rb")); + supportingFiles.add(new SupportingFile("cors.rb", initializersFolder, "cors.rb")); + supportingFiles.add(new SupportingFile("filter_parameter_logging.rb", initializersFolder, "filter_parameter_logging.rb")); + supportingFiles.add(new SupportingFile("inflections.rb", initializersFolder, "inflections.rb")); + supportingFiles.add(new SupportingFile("mime_types.rb", initializersFolder, "mime_types.rb")); + supportingFiles.add(new SupportingFile("ssl_options.rb", initializersFolder, "ssl_options.rb")); + supportingFiles.add(new SupportingFile("to_time_preserves_timezone.rb", initializersFolder, "to_time_preserves_timezone.rb")); + supportingFiles.add(new SupportingFile("en.yml", localesFolder, "en.yml")); + supportingFiles.add(new SupportingFile("application.rb", configFolder, "application.rb")); + supportingFiles.add(new SupportingFile("boot.rb", configFolder, "boot.rb")); + supportingFiles.add(new SupportingFile("cable.yml", configFolder, "cable.yml")); + supportingFiles.add(new SupportingFile("database.yml", configFolder, "database.yml")); + supportingFiles.add(new SupportingFile("environment.rb", configFolder, "environment.rb")); + supportingFiles.add(new SupportingFile("puma.rb", configFolder, "puma.rb")); + supportingFiles.add(new SupportingFile("routes.mustache", configFolder, "routes.rb")); + supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml")); + supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb")); + supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep")); + supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb")); + supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb")); + supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", logFolder, ".keep")); + supportingFiles.add(new SupportingFile("404.html", publicFolder, "404.html")); + supportingFiles.add(new SupportingFile("422.html", publicFolder, "422.html")); + supportingFiles.add(new SupportingFile("500.html", publicFolder, "500.html")); + supportingFiles.add(new SupportingFile("apple-touch-icon-precomposed.png", publicFolder, "apple-touch-icon-precomposed.png")); + supportingFiles.add(new SupportingFile("apple-touch-icon.png", publicFolder, "apple-touch-icon.png")); + supportingFiles.add(new SupportingFile("favicon.ico", publicFolder, "favicon.ico")); + supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt")); + supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt")); + supportingFiles.add(new SupportingFile("test_helper.rb", testFolder, "test_helper.rb")); + supportingFiles.add(new SupportingFile(".keep", cacheFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", pidFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", socketsFolder, ".keep")); + supportingFiles.add(new SupportingFile("restart.txt", tmpFolder, "restart.txt")); + supportingFiles.add(new SupportingFile(".keep", vendorFolder, ".keep")); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "rails5"; + } + + @Override + public String getHelp() { + return "Generates a Rails5 server library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage.replace("/", File.separator); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = swaggerType; + } + if (type == null) { + return null; + } + return type; + } + + @Override + public String toDefaultValue(Property p) { + return "null"; + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // camelize (lower first character) the variable name + // petId => pet_id + name = underscore(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // underscore the model file name + // PhoneNumber.rb => phone_number.rb + return underscore(name); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_controllers"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "ApiController"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Controller"; + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return underscore(operationId); + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + } + return super.postProcessSupportingFileData(objs); + } + +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index c84abac129c..f0d0fde5e57 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -27,6 +27,7 @@ io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen io.swagger.codegen.languages.SilexServerCodegen io.swagger.codegen.languages.SinatraServerCodegen +io.swagger.codegen.languages.Rails5ServerCodegen io.swagger.codegen.languages.SlimFrameworkServerCodegen io.swagger.codegen.languages.SpringBootServerCodegen io.swagger.codegen.languages.SpringMVCServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/rails5/.keep b/modules/swagger-codegen/src/main/resources/rails5/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/404.html b/modules/swagger-codegen/src/main/resources/rails5/404.html new file mode 100644 index 00000000000..b612547fc21 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/422.html b/modules/swagger-codegen/src/main/resources/rails5/422.html new file mode 100644 index 00000000000..a21f82b3bdb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/500.html b/modules/swagger-codegen/src/main/resources/rails5/500.html new file mode 100644 index 00000000000..061abc587dc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/Gemfile b/modules/swagger-codegen/src/main/resources/rails5/Gemfile new file mode 100644 index 00000000000..b553bf7355d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/Gemfile @@ -0,0 +1,36 @@ +source 'https://rubygems.org' + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '>= 5.0.0.racecar1', '< 5.1' +# Use mysql as the database for Active Record +gem 'mysql2', '>= 0.3.18', '< 0.5' +# Use Puma as the app server +gem 'puma', '~> 3.0' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.0' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 3.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platform: :mri +end + +group :development do + gem 'listen', '~> 3.0.5' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/modules/swagger-codegen/src/main/resources/rails5/README.md b/modules/swagger-codegen/src/main/resources/rails5/README.md new file mode 100644 index 00000000000..c5cb90075a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/README.md @@ -0,0 +1,25 @@ +# Swagger for Rails 5 + +This is a project to provide Swagger support inside the [Sinatra](http://rubyonrails.org/) framework. + +## Prerequisites +You need to install ruby >= 2.2.2 and run: + +``` +bundle install +``` + +## Getting started + +This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. + +``` +bin/rake db:create +bin/rails s +``` + +To list all your routes, use: + +``` +bin/rake routes +``` diff --git a/modules/swagger-codegen/src/main/resources/rails5/Rakefile b/modules/swagger-codegen/src/main/resources/rails5/Rakefile new file mode 100644 index 00000000000..e85f913914b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb b/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb new file mode 100644 index 00000000000..f613b40f804 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Require `belongs_to` associations by default. This is a new Rails 5.0 +# default, so it is introduced as a configuration option to ensure that apps +# made on earlier versions of Rails are not affected when upgrading. +Rails.application.config.active_record.belongs_to_required_by_default = true diff --git a/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon-precomposed.png b/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon-precomposed.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon.png b/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/application.rb b/modules/swagger-codegen/src/main/resources/rails5/application.rb new file mode 100644 index 00000000000..70bea9ecf69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application.rb @@ -0,0 +1,30 @@ +require_relative 'boot' + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "action_cable/engine" +# require "sprockets/railtie" +require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ApiDemo + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb b/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb new file mode 100644 index 00000000000..4ac8823b095 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb b/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb new file mode 100644 index 00000000000..51639b67a00 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_job.rb b/modules/swagger-codegen/src/main/resources/rails5/application_job.rb new file mode 100644 index 00000000000..a009ace51cc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb b/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb new file mode 100644 index 00000000000..286b2239d13 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_record.rb b/modules/swagger-codegen/src/main/resources/rails5/application_record.rb new file mode 100644 index 00000000000..10a4cba84df --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb b/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb new file mode 100644 index 00000000000..59385cdf379 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/modules/swagger-codegen/src/main/resources/rails5/boot.rb b/modules/swagger-codegen/src/main/resources/rails5/boot.rb new file mode 100644 index 00000000000..30f5120df69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/modules/swagger-codegen/src/main/resources/rails5/bundle b/modules/swagger-codegen/src/main/resources/rails5/bundle new file mode 100755 index 00000000000..66e9889e8b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/modules/swagger-codegen/src/main/resources/rails5/cable.yml b/modules/swagger-codegen/src/main/resources/rails5/cable.yml new file mode 100644 index 00000000000..aa4e832748c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/cable.yml @@ -0,0 +1,10 @@ +# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket. +production: + adapter: redis + url: redis://localhost:6379/1 + +development: + adapter: async + +test: + adapter: async diff --git a/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb b/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb new file mode 100644 index 00000000000..649e82280e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Do not halt callback chains when a callback returns false. This is a new +# Rails 5.0 default, so it is introduced as a configuration option to ensure +# that apps made with earlier versions of Rails are not affected when upgrading. +ActiveSupport.halt_callback_chains_on_return_false = false diff --git a/modules/swagger-codegen/src/main/resources/rails5/channel.rb b/modules/swagger-codegen/src/main/resources/rails5/channel.rb new file mode 100644 index 00000000000..d56fa30f4d8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/channel.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/config.ru b/modules/swagger-codegen/src/main/resources/rails5/config.ru new file mode 100644 index 00000000000..f7ba0b527b1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/modules/swagger-codegen/src/main/resources/rails5/connection.rb b/modules/swagger-codegen/src/main/resources/rails5/connection.rb new file mode 100644 index 00000000000..b4f41389ad0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/connection.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/controller.mustache b/modules/swagger-codegen/src/main/resources/rails5/controller.mustache new file mode 100644 index 00000000000..5fac9b34d30 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/controller.mustache @@ -0,0 +1,22 @@ +class ProductController < ApplicationController + + def index + # Your code here + end + + def show + # Your code here + end + + def create + # Your code here + end + + def update + # Your code here + end + + def destroy + # Your code here + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/cors.rb b/modules/swagger-codegen/src/main/resources/rails5/cors.rb new file mode 100644 index 00000000000..3b1c1b5ed14 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/modules/swagger-codegen/src/main/resources/rails5/database.yml b/modules/swagger-codegen/src/main/resources/rails5/database.yml new file mode 100644 index 00000000000..e536d9f37dc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/database.yml @@ -0,0 +1,54 @@ +# MySQL. Versions 5.0 and up are supported. +# +# Install the MySQL driver +# gem install mysql2 +# +# Ensure the MySQL gem is defined in your Gemfile +# gem 'mysql2' +# +# And be sure to use new-style password hashing: +# http://dev.mysql.com/doc/refman/5.7/en/old-client.html +# +default: &default + adapter: mysql2 + encoding: utf8 + pool: 5 + username: root + password: + socket: /tmp/mysql.sock + +development: + <<: *default + database: api_demo_development + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: api_demo_test + +# As with config/secrets.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password as a unix environment variable when you boot +# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full rundown on how to provide these environment variables in a +# production deployment. +# +# On Heroku and other platform providers, you may have a full connection URL +# available as an environment variable. For example: +# +# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase" +# +# You can use this database configuration with: +# +# production: +# url: <%= ENV['DATABASE_URL'] %> +# +production: + <<: *default + database: api_demo_production + username: api_demo + password: <%= ENV['API_DEMO_DATABASE_PASSWORD'] %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/development.rb b/modules/swagger-codegen/src/main/resources/rails5/development.rb new file mode 100644 index 00000000000..082a013ab36 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/development.rb @@ -0,0 +1,47 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=172800' + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/en.yml b/modules/swagger-codegen/src/main/resources/rails5/en.yml new file mode 100644 index 00000000000..0653957166e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/modules/swagger-codegen/src/main/resources/rails5/environment.rb b/modules/swagger-codegen/src/main/resources/rails5/environment.rb new file mode 100644 index 00000000000..426333bb469 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/modules/swagger-codegen/src/main/resources/rails5/favicon.ico b/modules/swagger-codegen/src/main/resources/rails5/favicon.ico new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb b/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb new file mode 100644 index 00000000000..4a994e1e7bb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/modules/swagger-codegen/src/main/resources/rails5/inflections.rb b/modules/swagger-codegen/src/main/resources/rails5/inflections.rb new file mode 100644 index 00000000000..ac033bf9dc8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb b/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb new file mode 100644 index 00000000000..cbd34d2e9dd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb b/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb new file mode 100644 index 00000000000..37f0bddbd74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb b/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb new file mode 100644 index 00000000000..dc1899682b0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/modules/swagger-codegen/src/main/resources/rails5/production.rb b/modules/swagger-codegen/src/main/resources/rails5/production.rb new file mode 100644 index 00000000000..6cb0a8fe61c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/production.rb @@ -0,0 +1,80 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Action Cable endpoint configuration + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Don't mount Action Cable in the main server process. + # config.action_cable.mount_path = nil + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "api_demo_#{Rails.env}" + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/puma.rb b/modules/swagger-codegen/src/main/resources/rails5/puma.rb new file mode 100644 index 00000000000..c7f311f8116 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/puma.rb @@ -0,0 +1,47 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum, this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests, default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. If you use this option +# you need to make sure to reconnect any threads in the `on_worker_boot` +# block. +# +# preload_app! + +# The code in the `on_worker_boot` will be called if you are using +# clustered mode by specifying a number of `workers`. After each worker +# process is booted this block will be run, if you are using `preload_app!` +# option you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, Ruby +# cannot share connections between processes. +# +# on_worker_boot do +# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) +# end + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/modules/swagger-codegen/src/main/resources/rails5/rails b/modules/swagger-codegen/src/main/resources/rails5/rails new file mode 100755 index 00000000000..07396602377 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/modules/swagger-codegen/src/main/resources/rails5/rake b/modules/swagger-codegen/src/main/resources/rails5/rake new file mode 100755 index 00000000000..17240489f64 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/modules/swagger-codegen/src/main/resources/rails5/restart.txt b/modules/swagger-codegen/src/main/resources/rails5/restart.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/robots.txt b/modules/swagger-codegen/src/main/resources/rails5/robots.txt new file mode 100644 index 00000000000..3c9c7c01f30 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/modules/swagger-codegen/src/main/resources/rails5/routes.mustache b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache new file mode 100644 index 00000000000..df5d7e453fe --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache @@ -0,0 +1,3 @@ +Rails.application.routes.draw do + resources :product +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/schema.rb b/modules/swagger-codegen/src/main/resources/rails5/schema.rb new file mode 100644 index 00000000000..4dfbb16804e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/schema.rb @@ -0,0 +1,16 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 0) do + +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/secrets.yml b/modules/swagger-codegen/src/main/resources/rails5/secrets.yml new file mode 100644 index 00000000000..179b066b84d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: 2e13a003477a557ba3fcc6260c2ec69e411238b9b8b530c3c70e71f7cfc905b5f746f5c195a0282342a77ad6acd4e6ef8949106723200a99414fe83393d67344 + +test: + secret_key_base: fedf54236a94882c00e2fa0af308a4135f50941396437b9fbc38dd340c0a8bcf38cfcf6264cc2abc2af5bda26252293fe48e9a3e90fbfc4d25d6886d6d14b300 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/seeds.rb b/modules/swagger-codegen/src/main/resources/rails5/seeds.rb new file mode 100644 index 00000000000..1beea2accd7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/modules/swagger-codegen/src/main/resources/rails5/setup b/modules/swagger-codegen/src/main/resources/rails5/setup new file mode 100755 index 00000000000..e620b4dadb2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/spring.rb b/modules/swagger-codegen/src/main/resources/rails5/spring.rb new file mode 100644 index 00000000000..c9119b40c08 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/spring.rb @@ -0,0 +1,6 @@ +%w( + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +).each { |path| Spring.watch(path) } diff --git a/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb b/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb new file mode 100644 index 00000000000..1775dea1e76 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure SSL options to enable HSTS with subdomains. +Rails.application.config.ssl_options = { hsts: { subdomains: true } } diff --git a/modules/swagger-codegen/src/main/resources/rails5/test.rb b/modules/swagger-codegen/src/main/resources/rails5/test.rb new file mode 100644 index 00000000000..30587ef6d5e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/test.rb @@ -0,0 +1,42 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=3600' + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb b/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb new file mode 100644 index 00000000000..92e39b2d78c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb @@ -0,0 +1,10 @@ +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +require 'rails/test_help' + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb b/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb new file mode 100644 index 00000000000..8674be3227e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb @@ -0,0 +1,10 @@ +# Be sure to restart your server when you modify this file. + +# Preserve the timezone of the receiver when calling to `to_time`. +# Ruby 2.4 will change the behavior of `to_time` to preserve the timezone +# when converting to an instance of `Time` instead of the previous behavior +# of converting to the local system timezone. +# +# Rails 5.0 introduced this config option so that apps made with earlier +# versions of Rails are not affected when upgrading. +ActiveSupport.to_time_preserves_timezone = true diff --git a/modules/swagger-codegen/src/main/resources/rails5/update b/modules/swagger-codegen/src/main/resources/rails5/update new file mode 100755 index 00000000000..a8e4462f203 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/update @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb b/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb new file mode 100644 index 00000000000..bbfc3961bff --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java new file mode 100644 index 00000000000..c75053b84e2 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java @@ -0,0 +1,23 @@ +package io.swagger.codegen.options; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class Rails5ServerOptionsProvider implements OptionsProvider { + @Override + public String getLanguage() { + return "Rails5"; + } + + @Override + public Map createOptions() { + //Rails5ServerCodegen doesn't have its own options and base options are cleared + return ImmutableMap.of(); + } + + @Override + public boolean isServer() { + return true; + } +} From da50a6e1f0bc7def00de69470291fd3dc25ba0e9 Mon Sep 17 00:00:00 2001 From: Newell Zhu Date: Fri, 13 May 2016 01:44:20 +0800 Subject: [PATCH 43/53] Complete controller mustache --- .../io/swagger/codegen/CodegenOperation.java | 80 ++++++++++++++++++- .../io/swagger/codegen/DefaultCodegen.java | 8 ++ .../main/resources/rails5/controller.mustache | 37 +++++++-- 3 files changed, 119 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 48858a0d504..9dfe0d45c88 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -7,13 +7,16 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.Arrays; public class CodegenOperation { public final List responseHeaders = new ArrayList(); public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, isListContainer, isMultipart, hasMore = Boolean.TRUE, - isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE; + isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE, + isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, + isRestful; public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator; public List> consumes, produces; @@ -88,6 +91,81 @@ public class CodegenOperation { return nonempty(formParams); } + /** + * Check if act as Restful index method + * + * @return true if act as Restful index method, false otherwise + */ + public boolean isRestfulIndex() { + return "GET".equals(httpMethod) && "".equals(pathWithoutBaseName()); + } + + /** + * Check if act as Restful show method + * + * @return true if act as Restful show method, false otherwise + */ + public boolean isRestfulShow() { + return "GET".equals(httpMethod) && isMemberPath(); + } + + /** + * Check if act as Restful create method + * + * @return true if act as Restful create method, false otherwise + */ + public boolean isRestfulCreate() { + return "POST".equals(httpMethod) && "".equals(pathWithoutBaseName()); + } + + /** + * Check if act as Restful update method + * + * @return true if act as Restful update method, false otherwise + */ + public boolean isRestfulUpdate() { + return Arrays.asList("PUT", "PATCH").contains(httpMethod) && isMemberPath(); + } + + /** + * Check if act as Restful destroy method + * + * @return true if act as Restful destroy method, false otherwise + */ + public boolean isRestfulDestroy() { + return "DELETE".equals(httpMethod) && isMemberPath(); + } + + /** + * Check if Restful-style + * + * @return true if Restful-style, false otherwise + */ + public boolean isRestful() { + return isRestfulIndex() || isRestfulShow() || isRestfulCreate() || isRestfulUpdate() || isRestfulDestroy(); + } + + /** + * Get the substring except baseName from path + * + * @return the substring + */ + private String pathWithoutBaseName() { + return baseName != null ? path.replace("/" + baseName.toLowerCase(), "") : path; + } + + /** + * Check if the path match format /xxx/:id + * + * @return true if path act as member + */ + private boolean isMemberPath() { + if (pathParams.size() != 1) return false; + + String id = pathParams.get(0).baseName; + return ("/{" + id + "}").equals(pathWithoutBaseName()); + } + @Override public String toString() { return String.format("%s(%s)", baseName, path); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index be0f698c5b7..8f3fc7be632 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1847,6 +1847,14 @@ public class DefaultCodegen { } op.externalDocs = operation.getExternalDocs(); + // set Restful Flag + op.isRestfulShow = op.isRestfulShow(); + op.isRestfulIndex = op.isRestfulIndex(); + op.isRestfulCreate = op.isRestfulCreate(); + op.isRestfulUpdate = op.isRestfulUpdate(); + op.isRestfulDestroy = op.isRestfulDestroy(); + op.isRestful = op.isRestful(); + return op; } diff --git a/modules/swagger-codegen/src/main/resources/rails5/controller.mustache b/modules/swagger-codegen/src/main/resources/rails5/controller.mustache index 5fac9b34d30..321960875d8 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/rails5/controller.mustache @@ -1,22 +1,49 @@ -class ProductController < ApplicationController +class {{classname}} < ApplicationController +{{#operations}} +{{#operation}} +{{#isRestfulIndex}} def index # Your code here - end + render json: {"message" => "yes, it worked"} + end +{{/isRestfulIndex}} +{{#isRestfulShow}} def show # Your code here - end + render json: {"message" => "yes, it worked"} + end +{{/isRestfulShow}} +{{#isRestfulCreate}} def create # Your code here - end + render json: {"message" => "yes, it worked"} + end +{{/isRestfulCreate}} +{{#isRestfulUpdate}} def update # Your code here - end + render json: {"message" => "yes, it worked"} + end +{{/isRestfulUpdate}} +{{#isRestfulDestroy}} def destroy # Your code here + + render json: {"message" => "yes, it worked"} end +{{/isRestfulDestroy}} +{{^isRestful}} + def {{nickname}} + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestful}} +{{/operation}} +{{/operations}} end From d0dcec85cc26648b4afbe75da5289ed51f2e5394 Mon Sep 17 00:00:00 2001 From: Newell Zhu Date: Sat, 14 May 2016 23:30:46 +0800 Subject: [PATCH 44/53] build route.mustache --- .../src/main/resources/rails5/routes.mustache | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/rails5/routes.mustache b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache index df5d7e453fe..e6b95be33a4 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/routes.mustache +++ b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache @@ -1,3 +1,31 @@ Rails.application.routes.draw do - resources :product + + def add_swagger_route http_method, path, opts = {} + full_path = path.gsub(/{(.*?)}/, ':\1') + action = + (opts[:isRestfulIndex] && :index) || + (opts[:isRestfulShow] && :show) || + (opts[:isRestfulCreate] && :create) || + (opts[:isRestfulUpdate] && :update) || + (opts[:isRestfulDestroy] && :destroy) || + opts[:nickname] + + match full_path, to: "#{opts.fetch(:classVarName)}##{action}", via: http_method + end + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + add_swagger_route '{{httpMethod}}', '{{basePathWithoutHost}}{{path}}', + classVarName: '{{classVarName}}', nickname: '{{nickname}}', + isRestfulIndex: {{#isRestfulIndex}}true{{/isRestfulIndex}}{{^isRestfulIndex}}false{{/isRestfulIndex}}, + isRestfulCreate: {{#isRestfulCreate}}true{{/isRestfulCreate}}{{^isRestfulCreate}}false{{/isRestfulCreate}}, + isRestfulUpdate: {{#isRestfulUpdate}}true{{/isRestfulUpdate}}{{^isRestfulUpdate}}false{{/isRestfulUpdate}}, + isRestfulShow: {{#isRestfulShow}}true{{/isRestfulShow}}{{^isRestfulShow}}false{{/isRestfulShow}}, + isRestfulDestroy: {{#isRestfulDestroy}}true{{/isRestfulDestroy}}{{^isRestfulDestroy}}false{{/isRestfulDestroy}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} end From 83b5c2eeec18845e6efa51b2054d405979ba43d8 Mon Sep 17 00:00:00 2001 From: Newell Zhu Date: Sun, 15 May 2016 00:19:51 +0800 Subject: [PATCH 45/53] Add Rails5 sample --- samples/server/petstore/rails5/Gemfile | 36 ++++ samples/server/petstore/rails5/Gemfile.lock | 141 ++++++++++++++++ samples/server/petstore/rails5/README.md | 25 +++ samples/server/petstore/rails5/Rakefile | 6 + .../app/channels/application_cable/channel.rb | 5 + .../channels/application_cable/connection.rb | 5 + .../app/controllers/application_controller.rb | 2 + .../rails5/app/controllers/pet_controllers.rb | 50 ++++++ .../app/controllers/store_controllers.rb | 26 +++ .../app/controllers/user_controllers.rb | 50 ++++++ .../rails5/app/jobs/application_job.rb | 2 + .../rails5/app/mailers/application_mailer.rb | 4 + .../rails5/app/models/application_record.rb | 3 + .../rails5/app/views/layouts/mailer.html.erb | 13 ++ .../rails5/app/views/layouts/mailer.text.erb | 1 + samples/server/petstore/rails5/bin/bundle | 3 + samples/server/petstore/rails5/bin/rails | 4 + samples/server/petstore/rails5/bin/rake | 4 + samples/server/petstore/rails5/bin/setup | 34 ++++ samples/server/petstore/rails5/bin/update | 29 ++++ samples/server/petstore/rails5/config.ru | 5 + .../petstore/rails5/config/application.rb | 30 ++++ samples/server/petstore/rails5/config/boot.rb | 3 + .../server/petstore/rails5/config/cable.yml | 10 ++ .../rails5/config/config/development.rb | 47 ++++++ .../rails5/config/config/production.rb | 80 +++++++++ .../petstore/rails5/config/database.yml | 54 ++++++ .../petstore/rails5/config/environment.rb | 5 + ...e_record_belongs_to_required_by_default.rb | 6 + .../application_controller_renderer.rb | 6 + .../initializers/backtrace_silencers.rb | 7 + .../initializers/callback_terminator.rb | 6 + .../rails5/config/initializers/cors.rb | 16 ++ .../initializers/filter_parameter_logging.rb | 4 + .../rails5/config/initializers/inflections.rb | 16 ++ .../rails5/config/initializers/mime_types.rb | 4 + .../rails5/config/initializers/ssl_options.rb | 4 + .../to_time_preserves_timezone.rb | 10 ++ .../petstore/rails5/config/locales/en.yml | 23 +++ samples/server/petstore/rails5/config/puma.rb | 47 ++++++ .../server/petstore/rails5/config/routes.rb | 156 ++++++++++++++++++ .../server/petstore/rails5/config/secrets.yml | 22 +++ .../server/petstore/rails5/config/spring.rb | 6 + .../server/petstore/rails5/db/migrate/.keep | 0 samples/server/petstore/rails5/db/schema.rb | 16 ++ samples/server/petstore/rails5/db/seeds.rb | 7 + .../server/petstore/rails5/lib/tasks/.keep | 0 samples/server/petstore/rails5/log/.keep | 0 .../petstore/rails5/log/development.log | 0 .../server/petstore/rails5/public/404.html | 67 ++++++++ .../server/petstore/rails5/public/422.html | 67 ++++++++ .../server/petstore/rails5/public/500.html | 66 ++++++++ .../public/apple-touch-icon-precomposed.png | 0 .../rails5/public/apple-touch-icon.png | 0 .../server/petstore/rails5/public/favicon.ico | 0 .../server/petstore/rails5/public/robots.txt | 5 + .../petstore/rails5/test/test_helper.rb | 10 ++ .../server/petstore/rails5/tmp/cache/.keep | 0 samples/server/petstore/rails5/tmp/pids/.keep | 0 .../server/petstore/rails5/tmp/restart.txt | 0 .../server/petstore/rails5/tmp/sockets/.keep | 0 samples/server/petstore/rails5/vendor/.keep | 0 62 files changed, 1248 insertions(+) create mode 100644 samples/server/petstore/rails5/Gemfile create mode 100644 samples/server/petstore/rails5/Gemfile.lock create mode 100644 samples/server/petstore/rails5/README.md create mode 100644 samples/server/petstore/rails5/Rakefile create mode 100644 samples/server/petstore/rails5/app/channels/application_cable/channel.rb create mode 100644 samples/server/petstore/rails5/app/channels/application_cable/connection.rb create mode 100644 samples/server/petstore/rails5/app/controllers/application_controller.rb create mode 100644 samples/server/petstore/rails5/app/controllers/pet_controllers.rb create mode 100644 samples/server/petstore/rails5/app/controllers/store_controllers.rb create mode 100644 samples/server/petstore/rails5/app/controllers/user_controllers.rb create mode 100644 samples/server/petstore/rails5/app/jobs/application_job.rb create mode 100644 samples/server/petstore/rails5/app/mailers/application_mailer.rb create mode 100644 samples/server/petstore/rails5/app/models/application_record.rb create mode 100644 samples/server/petstore/rails5/app/views/layouts/mailer.html.erb create mode 100644 samples/server/petstore/rails5/app/views/layouts/mailer.text.erb create mode 100755 samples/server/petstore/rails5/bin/bundle create mode 100755 samples/server/petstore/rails5/bin/rails create mode 100755 samples/server/petstore/rails5/bin/rake create mode 100755 samples/server/petstore/rails5/bin/setup create mode 100755 samples/server/petstore/rails5/bin/update create mode 100644 samples/server/petstore/rails5/config.ru create mode 100644 samples/server/petstore/rails5/config/application.rb create mode 100644 samples/server/petstore/rails5/config/boot.rb create mode 100644 samples/server/petstore/rails5/config/cable.yml create mode 100644 samples/server/petstore/rails5/config/config/development.rb create mode 100644 samples/server/petstore/rails5/config/config/production.rb create mode 100644 samples/server/petstore/rails5/config/database.yml create mode 100644 samples/server/petstore/rails5/config/environment.rb create mode 100644 samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb create mode 100644 samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb create mode 100644 samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb create mode 100644 samples/server/petstore/rails5/config/initializers/callback_terminator.rb create mode 100644 samples/server/petstore/rails5/config/initializers/cors.rb create mode 100644 samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb create mode 100644 samples/server/petstore/rails5/config/initializers/inflections.rb create mode 100644 samples/server/petstore/rails5/config/initializers/mime_types.rb create mode 100644 samples/server/petstore/rails5/config/initializers/ssl_options.rb create mode 100644 samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb create mode 100644 samples/server/petstore/rails5/config/locales/en.yml create mode 100644 samples/server/petstore/rails5/config/puma.rb create mode 100644 samples/server/petstore/rails5/config/routes.rb create mode 100644 samples/server/petstore/rails5/config/secrets.yml create mode 100644 samples/server/petstore/rails5/config/spring.rb create mode 100644 samples/server/petstore/rails5/db/migrate/.keep create mode 100644 samples/server/petstore/rails5/db/schema.rb create mode 100644 samples/server/petstore/rails5/db/seeds.rb create mode 100644 samples/server/petstore/rails5/lib/tasks/.keep create mode 100644 samples/server/petstore/rails5/log/.keep create mode 100644 samples/server/petstore/rails5/log/development.log create mode 100644 samples/server/petstore/rails5/public/404.html create mode 100644 samples/server/petstore/rails5/public/422.html create mode 100644 samples/server/petstore/rails5/public/500.html create mode 100644 samples/server/petstore/rails5/public/apple-touch-icon-precomposed.png create mode 100644 samples/server/petstore/rails5/public/apple-touch-icon.png create mode 100644 samples/server/petstore/rails5/public/favicon.ico create mode 100644 samples/server/petstore/rails5/public/robots.txt create mode 100644 samples/server/petstore/rails5/test/test_helper.rb create mode 100644 samples/server/petstore/rails5/tmp/cache/.keep create mode 100644 samples/server/petstore/rails5/tmp/pids/.keep create mode 100644 samples/server/petstore/rails5/tmp/restart.txt create mode 100644 samples/server/petstore/rails5/tmp/sockets/.keep create mode 100644 samples/server/petstore/rails5/vendor/.keep diff --git a/samples/server/petstore/rails5/Gemfile b/samples/server/petstore/rails5/Gemfile new file mode 100644 index 00000000000..b553bf7355d --- /dev/null +++ b/samples/server/petstore/rails5/Gemfile @@ -0,0 +1,36 @@ +source 'https://rubygems.org' + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '>= 5.0.0.racecar1', '< 5.1' +# Use mysql as the database for Active Record +gem 'mysql2', '>= 0.3.18', '< 0.5' +# Use Puma as the app server +gem 'puma', '~> 3.0' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.0' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 3.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platform: :mri +end + +group :development do + gem 'listen', '~> 3.0.5' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/samples/server/petstore/rails5/Gemfile.lock b/samples/server/petstore/rails5/Gemfile.lock new file mode 100644 index 00000000000..f544bc0f702 --- /dev/null +++ b/samples/server/petstore/rails5/Gemfile.lock @@ -0,0 +1,141 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + nio4r (~> 1.2) + websocket-driver (~> 0.6.1) + actionmailer (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + actionview (= 5.0.0.rc1) + activejob (= 5.0.0.rc1) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 1.0, >= 1.0.5) + actionpack (5.0.0.rc1) + actionview (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + rack (~> 2.x) + rack-test (~> 0.6.3) + rails-dom-testing (~> 1.0, >= 1.0.5) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + actionview (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + builder (~> 3.1) + erubis (~> 2.7.0) + rails-dom-testing (~> 1.0, >= 1.0.5) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + activejob (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + globalid (>= 0.3.6) + activemodel (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + activerecord (5.0.0.rc1) + activemodel (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + arel (~> 7.0) + activesupport (5.0.0.rc1) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (~> 0.7) + minitest (~> 5.1) + tzinfo (~> 1.1) + arel (7.0.0) + builder (3.2.2) + byebug (9.0.0) + concurrent-ruby (1.0.2) + erubis (2.7.0) + ffi (1.9.10) + globalid (0.3.6) + activesupport (>= 4.1.0) + i18n (0.7.0) + jbuilder (2.4.1) + activesupport (>= 3.0.0, < 5.1) + multi_json (~> 1.2) + json (1.8.3) + listen (3.0.7) + rb-fsevent (>= 0.9.3) + rb-inotify (>= 0.9.7) + loofah (2.0.3) + nokogiri (>= 1.5.9) + mail (2.6.4) + mime-types (>= 1.16, < 4) + method_source (0.8.2) + mime-types (3.0) + mime-types-data (~> 3.2015) + mime-types-data (3.2016.0221) + mini_portile2 (2.0.0) + minitest (5.8.4) + multi_json (1.12.0) + mysql2 (0.4.4) + nio4r (1.2.1) + nokogiri (1.6.7.2) + mini_portile2 (~> 2.0.0.rc2) + puma (3.4.0) + rack (2.0.0.rc1) + json + rack-test (0.6.3) + rack (>= 1.0) + rails (5.0.0.rc1) + actioncable (= 5.0.0.rc1) + actionmailer (= 5.0.0.rc1) + actionpack (= 5.0.0.rc1) + actionview (= 5.0.0.rc1) + activejob (= 5.0.0.rc1) + activemodel (= 5.0.0.rc1) + activerecord (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + bundler (>= 1.3.0, < 2.0) + railties (= 5.0.0.rc1) + sprockets-rails (>= 2.0.0) + rails-deprecated_sanitizer (1.0.3) + activesupport (>= 4.2.0.alpha) + rails-dom-testing (1.0.7) + activesupport (>= 4.2.0.beta, < 5.0) + nokogiri (~> 1.6.0) + rails-deprecated_sanitizer (>= 1.0.1) + rails-html-sanitizer (1.0.3) + loofah (~> 2.0) + railties (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + method_source + rake (>= 0.8.7) + thor (>= 0.18.1, < 2.0) + rake (11.1.2) + rb-fsevent (0.9.7) + rb-inotify (0.9.7) + ffi (>= 0.5.0) + spring (1.7.1) + spring-watcher-listen (2.0.0) + listen (>= 2.7, < 4.0) + spring (~> 1.2) + sprockets (3.6.0) + concurrent-ruby (~> 1.0) + rack (> 1, < 3) + sprockets-rails (3.0.4) + actionpack (>= 4.0) + activesupport (>= 4.0) + sprockets (>= 3.0.0) + thor (0.19.1) + thread_safe (0.3.5) + tzinfo (1.2.2) + thread_safe (~> 0.1) + websocket-driver (0.6.3) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.2) + +PLATFORMS + ruby + +DEPENDENCIES + byebug + jbuilder (~> 2.0) + listen (~> 3.0.5) + mysql2 (>= 0.3.18, < 0.5) + puma (~> 3.0) + rails (>= 5.0.0.racecar1, < 5.1) + spring + spring-watcher-listen (~> 2.0.0) + tzinfo-data + +BUNDLED WITH + 1.11.2 diff --git a/samples/server/petstore/rails5/README.md b/samples/server/petstore/rails5/README.md new file mode 100644 index 00000000000..c5cb90075a6 --- /dev/null +++ b/samples/server/petstore/rails5/README.md @@ -0,0 +1,25 @@ +# Swagger for Rails 5 + +This is a project to provide Swagger support inside the [Sinatra](http://rubyonrails.org/) framework. + +## Prerequisites +You need to install ruby >= 2.2.2 and run: + +``` +bundle install +``` + +## Getting started + +This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. + +``` +bin/rake db:create +bin/rails s +``` + +To list all your routes, use: + +``` +bin/rake routes +``` diff --git a/samples/server/petstore/rails5/Rakefile b/samples/server/petstore/rails5/Rakefile new file mode 100644 index 00000000000..e85f913914b --- /dev/null +++ b/samples/server/petstore/rails5/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/samples/server/petstore/rails5/app/channels/application_cable/channel.rb b/samples/server/petstore/rails5/app/channels/application_cable/channel.rb new file mode 100644 index 00000000000..d56fa30f4d8 --- /dev/null +++ b/samples/server/petstore/rails5/app/channels/application_cable/channel.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/samples/server/petstore/rails5/app/channels/application_cable/connection.rb b/samples/server/petstore/rails5/app/channels/application_cable/connection.rb new file mode 100644 index 00000000000..b4f41389ad0 --- /dev/null +++ b/samples/server/petstore/rails5/app/channels/application_cable/connection.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/samples/server/petstore/rails5/app/controllers/application_controller.rb b/samples/server/petstore/rails5/app/controllers/application_controller.rb new file mode 100644 index 00000000000..4ac8823b095 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/samples/server/petstore/rails5/app/controllers/pet_controllers.rb b/samples/server/petstore/rails5/app/controllers/pet_controllers.rb new file mode 100644 index 00000000000..fa7e2557947 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/pet_controllers.rb @@ -0,0 +1,50 @@ +class PetController < ApplicationController + + def create + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def destroy + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def find_pets_by_status + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def find_pets_by_tags + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def show + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update_pet + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update_pet_with_form + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def upload_file + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/controllers/store_controllers.rb b/samples/server/petstore/rails5/app/controllers/store_controllers.rb new file mode 100644 index 00000000000..71fef4d92f8 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/store_controllers.rb @@ -0,0 +1,26 @@ +class StoreController < ApplicationController + + def delete_order + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def get_inventory + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def get_order_by_id + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def place_order + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/controllers/user_controllers.rb b/samples/server/petstore/rails5/app/controllers/user_controllers.rb new file mode 100644 index 00000000000..b8b2ce93634 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/user_controllers.rb @@ -0,0 +1,50 @@ +class UserController < ApplicationController + + def create + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def create_users_with_array_input + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def create_users_with_list_input + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def destroy + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def show + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def login_user + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def logout_user + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/jobs/application_job.rb b/samples/server/petstore/rails5/app/jobs/application_job.rb new file mode 100644 index 00000000000..a009ace51cc --- /dev/null +++ b/samples/server/petstore/rails5/app/jobs/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/samples/server/petstore/rails5/app/mailers/application_mailer.rb b/samples/server/petstore/rails5/app/mailers/application_mailer.rb new file mode 100644 index 00000000000..286b2239d13 --- /dev/null +++ b/samples/server/petstore/rails5/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/samples/server/petstore/rails5/app/models/application_record.rb b/samples/server/petstore/rails5/app/models/application_record.rb new file mode 100644 index 00000000000..10a4cba84df --- /dev/null +++ b/samples/server/petstore/rails5/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb b/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb new file mode 100644 index 00000000000..cbd34d2e9dd --- /dev/null +++ b/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb b/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb new file mode 100644 index 00000000000..37f0bddbd74 --- /dev/null +++ b/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/samples/server/petstore/rails5/bin/bundle b/samples/server/petstore/rails5/bin/bundle new file mode 100755 index 00000000000..66e9889e8b4 --- /dev/null +++ b/samples/server/petstore/rails5/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/samples/server/petstore/rails5/bin/rails b/samples/server/petstore/rails5/bin/rails new file mode 100755 index 00000000000..07396602377 --- /dev/null +++ b/samples/server/petstore/rails5/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/samples/server/petstore/rails5/bin/rake b/samples/server/petstore/rails5/bin/rake new file mode 100755 index 00000000000..17240489f64 --- /dev/null +++ b/samples/server/petstore/rails5/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/samples/server/petstore/rails5/bin/setup b/samples/server/petstore/rails5/bin/setup new file mode 100755 index 00000000000..e620b4dadb2 --- /dev/null +++ b/samples/server/petstore/rails5/bin/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/samples/server/petstore/rails5/bin/update b/samples/server/petstore/rails5/bin/update new file mode 100755 index 00000000000..a8e4462f203 --- /dev/null +++ b/samples/server/petstore/rails5/bin/update @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/samples/server/petstore/rails5/config.ru b/samples/server/petstore/rails5/config.ru new file mode 100644 index 00000000000..f7ba0b527b1 --- /dev/null +++ b/samples/server/petstore/rails5/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/samples/server/petstore/rails5/config/application.rb b/samples/server/petstore/rails5/config/application.rb new file mode 100644 index 00000000000..70bea9ecf69 --- /dev/null +++ b/samples/server/petstore/rails5/config/application.rb @@ -0,0 +1,30 @@ +require_relative 'boot' + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "action_cable/engine" +# require "sprockets/railtie" +require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ApiDemo + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/samples/server/petstore/rails5/config/boot.rb b/samples/server/petstore/rails5/config/boot.rb new file mode 100644 index 00000000000..30f5120df69 --- /dev/null +++ b/samples/server/petstore/rails5/config/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/samples/server/petstore/rails5/config/cable.yml b/samples/server/petstore/rails5/config/cable.yml new file mode 100644 index 00000000000..aa4e832748c --- /dev/null +++ b/samples/server/petstore/rails5/config/cable.yml @@ -0,0 +1,10 @@ +# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket. +production: + adapter: redis + url: redis://localhost:6379/1 + +development: + adapter: async + +test: + adapter: async diff --git a/samples/server/petstore/rails5/config/config/development.rb b/samples/server/petstore/rails5/config/config/development.rb new file mode 100644 index 00000000000..082a013ab36 --- /dev/null +++ b/samples/server/petstore/rails5/config/config/development.rb @@ -0,0 +1,47 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=172800' + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/samples/server/petstore/rails5/config/config/production.rb b/samples/server/petstore/rails5/config/config/production.rb new file mode 100644 index 00000000000..6cb0a8fe61c --- /dev/null +++ b/samples/server/petstore/rails5/config/config/production.rb @@ -0,0 +1,80 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Action Cable endpoint configuration + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Don't mount Action Cable in the main server process. + # config.action_cable.mount_path = nil + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "api_demo_#{Rails.env}" + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/samples/server/petstore/rails5/config/database.yml b/samples/server/petstore/rails5/config/database.yml new file mode 100644 index 00000000000..e536d9f37dc --- /dev/null +++ b/samples/server/petstore/rails5/config/database.yml @@ -0,0 +1,54 @@ +# MySQL. Versions 5.0 and up are supported. +# +# Install the MySQL driver +# gem install mysql2 +# +# Ensure the MySQL gem is defined in your Gemfile +# gem 'mysql2' +# +# And be sure to use new-style password hashing: +# http://dev.mysql.com/doc/refman/5.7/en/old-client.html +# +default: &default + adapter: mysql2 + encoding: utf8 + pool: 5 + username: root + password: + socket: /tmp/mysql.sock + +development: + <<: *default + database: api_demo_development + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: api_demo_test + +# As with config/secrets.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password as a unix environment variable when you boot +# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full rundown on how to provide these environment variables in a +# production deployment. +# +# On Heroku and other platform providers, you may have a full connection URL +# available as an environment variable. For example: +# +# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase" +# +# You can use this database configuration with: +# +# production: +# url: <%= ENV['DATABASE_URL'] %> +# +production: + <<: *default + database: api_demo_production + username: api_demo + password: <%= ENV['API_DEMO_DATABASE_PASSWORD'] %> diff --git a/samples/server/petstore/rails5/config/environment.rb b/samples/server/petstore/rails5/config/environment.rb new file mode 100644 index 00000000000..426333bb469 --- /dev/null +++ b/samples/server/petstore/rails5/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb b/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb new file mode 100644 index 00000000000..f613b40f804 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Require `belongs_to` associations by default. This is a new Rails 5.0 +# default, so it is introduced as a configuration option to ensure that apps +# made on earlier versions of Rails are not affected when upgrading. +Rails.application.config.active_record.belongs_to_required_by_default = true diff --git a/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb b/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb new file mode 100644 index 00000000000..51639b67a00 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) diff --git a/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb b/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb new file mode 100644 index 00000000000..59385cdf379 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/samples/server/petstore/rails5/config/initializers/callback_terminator.rb b/samples/server/petstore/rails5/config/initializers/callback_terminator.rb new file mode 100644 index 00000000000..649e82280e1 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/callback_terminator.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Do not halt callback chains when a callback returns false. This is a new +# Rails 5.0 default, so it is introduced as a configuration option to ensure +# that apps made with earlier versions of Rails are not affected when upgrading. +ActiveSupport.halt_callback_chains_on_return_false = false diff --git a/samples/server/petstore/rails5/config/initializers/cors.rb b/samples/server/petstore/rails5/config/initializers/cors.rb new file mode 100644 index 00000000000..3b1c1b5ed14 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb b/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb new file mode 100644 index 00000000000..4a994e1e7bb --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/samples/server/petstore/rails5/config/initializers/inflections.rb b/samples/server/petstore/rails5/config/initializers/inflections.rb new file mode 100644 index 00000000000..ac033bf9dc8 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/samples/server/petstore/rails5/config/initializers/mime_types.rb b/samples/server/petstore/rails5/config/initializers/mime_types.rb new file mode 100644 index 00000000000..dc1899682b0 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/samples/server/petstore/rails5/config/initializers/ssl_options.rb b/samples/server/petstore/rails5/config/initializers/ssl_options.rb new file mode 100644 index 00000000000..1775dea1e76 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/ssl_options.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure SSL options to enable HSTS with subdomains. +Rails.application.config.ssl_options = { hsts: { subdomains: true } } diff --git a/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb b/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb new file mode 100644 index 00000000000..8674be3227e --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb @@ -0,0 +1,10 @@ +# Be sure to restart your server when you modify this file. + +# Preserve the timezone of the receiver when calling to `to_time`. +# Ruby 2.4 will change the behavior of `to_time` to preserve the timezone +# when converting to an instance of `Time` instead of the previous behavior +# of converting to the local system timezone. +# +# Rails 5.0 introduced this config option so that apps made with earlier +# versions of Rails are not affected when upgrading. +ActiveSupport.to_time_preserves_timezone = true diff --git a/samples/server/petstore/rails5/config/locales/en.yml b/samples/server/petstore/rails5/config/locales/en.yml new file mode 100644 index 00000000000..0653957166e --- /dev/null +++ b/samples/server/petstore/rails5/config/locales/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/samples/server/petstore/rails5/config/puma.rb b/samples/server/petstore/rails5/config/puma.rb new file mode 100644 index 00000000000..c7f311f8116 --- /dev/null +++ b/samples/server/petstore/rails5/config/puma.rb @@ -0,0 +1,47 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum, this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests, default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. If you use this option +# you need to make sure to reconnect any threads in the `on_worker_boot` +# block. +# +# preload_app! + +# The code in the `on_worker_boot` will be called if you are using +# clustered mode by specifying a number of `workers`. After each worker +# process is booted this block will be run, if you are using `preload_app!` +# option you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, Ruby +# cannot share connections between processes. +# +# on_worker_boot do +# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) +# end + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/samples/server/petstore/rails5/config/routes.rb b/samples/server/petstore/rails5/config/routes.rb new file mode 100644 index 00000000000..502140c332b --- /dev/null +++ b/samples/server/petstore/rails5/config/routes.rb @@ -0,0 +1,156 @@ +Rails.application.routes.draw do + + def add_swagger_route http_method, path, opts = {} + full_path = path.gsub(/{(.*?)}/, ':\1') + action = + (opts[:isRestfulIndex] && :index) || + (opts[:isRestfulShow] && :show) || + (opts[:isRestfulCreate] && :create) || + (opts[:isRestfulUpdate] && :update) || + (opts[:isRestfulDestroy] && :destroy) || + opts[:nickname] + + match full_path, to: "#{opts.fetch(:classVarName)}##{action}", via: http_method + end + + add_swagger_route 'POST', '/v2/pet', + classVarName: 'pet', nickname: 'add_pet', + isRestfulIndex: false, + isRestfulCreate: true, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'DELETE', '/v2/pet/{petId}', + classVarName: 'pet', nickname: 'delete_pet', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: true + add_swagger_route 'GET', '/v2/pet/findByStatus', + classVarName: 'pet', nickname: 'find_pets_by_status', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'GET', '/v2/pet/findByTags', + classVarName: 'pet', nickname: 'find_pets_by_tags', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'GET', '/v2/pet/{petId}', + classVarName: 'pet', nickname: 'get_pet_by_id', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: true, + isRestfulDestroy: false + add_swagger_route 'PUT', '/v2/pet', + classVarName: 'pet', nickname: 'update_pet', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'POST', '/v2/pet/{petId}', + classVarName: 'pet', nickname: 'update_pet_with_form', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'POST', '/v2/pet/{petId}/uploadImage', + classVarName: 'pet', nickname: 'upload_file', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'DELETE', '/v2/store/order/{orderId}', + classVarName: 'store', nickname: 'delete_order', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'GET', '/v2/store/inventory', + classVarName: 'store', nickname: 'get_inventory', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'GET', '/v2/store/order/{orderId}', + classVarName: 'store', nickname: 'get_order_by_id', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'POST', '/v2/store/order', + classVarName: 'store', nickname: 'place_order', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'POST', '/v2/user', + classVarName: 'user', nickname: 'create_user', + isRestfulIndex: false, + isRestfulCreate: true, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'POST', '/v2/user/createWithArray', + classVarName: 'user', nickname: 'create_users_with_array_input', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'POST', '/v2/user/createWithList', + classVarName: 'user', nickname: 'create_users_with_list_input', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'DELETE', '/v2/user/{username}', + classVarName: 'user', nickname: 'delete_user', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: true + add_swagger_route 'GET', '/v2/user/{username}', + classVarName: 'user', nickname: 'get_user_by_name', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: true, + isRestfulDestroy: false + add_swagger_route 'GET', '/v2/user/login', + classVarName: 'user', nickname: 'login_user', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'GET', '/v2/user/logout', + classVarName: 'user', nickname: 'logout_user', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: false, + isRestfulShow: false, + isRestfulDestroy: false + add_swagger_route 'PUT', '/v2/user/{username}', + classVarName: 'user', nickname: 'update_user', + isRestfulIndex: false, + isRestfulCreate: false, + isRestfulUpdate: true, + isRestfulShow: false, + isRestfulDestroy: false +end diff --git a/samples/server/petstore/rails5/config/secrets.yml b/samples/server/petstore/rails5/config/secrets.yml new file mode 100644 index 00000000000..179b066b84d --- /dev/null +++ b/samples/server/petstore/rails5/config/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: 2e13a003477a557ba3fcc6260c2ec69e411238b9b8b530c3c70e71f7cfc905b5f746f5c195a0282342a77ad6acd4e6ef8949106723200a99414fe83393d67344 + +test: + secret_key_base: fedf54236a94882c00e2fa0af308a4135f50941396437b9fbc38dd340c0a8bcf38cfcf6264cc2abc2af5bda26252293fe48e9a3e90fbfc4d25d6886d6d14b300 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/samples/server/petstore/rails5/config/spring.rb b/samples/server/petstore/rails5/config/spring.rb new file mode 100644 index 00000000000..c9119b40c08 --- /dev/null +++ b/samples/server/petstore/rails5/config/spring.rb @@ -0,0 +1,6 @@ +%w( + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +).each { |path| Spring.watch(path) } diff --git a/samples/server/petstore/rails5/db/migrate/.keep b/samples/server/petstore/rails5/db/migrate/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/db/schema.rb b/samples/server/petstore/rails5/db/schema.rb new file mode 100644 index 00000000000..4dfbb16804e --- /dev/null +++ b/samples/server/petstore/rails5/db/schema.rb @@ -0,0 +1,16 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 0) do + +end diff --git a/samples/server/petstore/rails5/db/seeds.rb b/samples/server/petstore/rails5/db/seeds.rb new file mode 100644 index 00000000000..1beea2accd7 --- /dev/null +++ b/samples/server/petstore/rails5/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/samples/server/petstore/rails5/lib/tasks/.keep b/samples/server/petstore/rails5/lib/tasks/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/log/.keep b/samples/server/petstore/rails5/log/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/log/development.log b/samples/server/petstore/rails5/log/development.log new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/404.html b/samples/server/petstore/rails5/public/404.html new file mode 100644 index 00000000000..b612547fc21 --- /dev/null +++ b/samples/server/petstore/rails5/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/422.html b/samples/server/petstore/rails5/public/422.html new file mode 100644 index 00000000000..a21f82b3bdb --- /dev/null +++ b/samples/server/petstore/rails5/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/500.html b/samples/server/petstore/rails5/public/500.html new file mode 100644 index 00000000000..061abc587dc --- /dev/null +++ b/samples/server/petstore/rails5/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/apple-touch-icon-precomposed.png b/samples/server/petstore/rails5/public/apple-touch-icon-precomposed.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/apple-touch-icon.png b/samples/server/petstore/rails5/public/apple-touch-icon.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/favicon.ico b/samples/server/petstore/rails5/public/favicon.ico new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/robots.txt b/samples/server/petstore/rails5/public/robots.txt new file mode 100644 index 00000000000..3c9c7c01f30 --- /dev/null +++ b/samples/server/petstore/rails5/public/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/samples/server/petstore/rails5/test/test_helper.rb b/samples/server/petstore/rails5/test/test_helper.rb new file mode 100644 index 00000000000..92e39b2d78c --- /dev/null +++ b/samples/server/petstore/rails5/test/test_helper.rb @@ -0,0 +1,10 @@ +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +require 'rails/test_help' + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/samples/server/petstore/rails5/tmp/cache/.keep b/samples/server/petstore/rails5/tmp/cache/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/pids/.keep b/samples/server/petstore/rails5/tmp/pids/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/restart.txt b/samples/server/petstore/rails5/tmp/restart.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/sockets/.keep b/samples/server/petstore/rails5/tmp/sockets/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/vendor/.keep b/samples/server/petstore/rails5/vendor/.keep new file mode 100644 index 00000000000..e69de29bb2d From 1d6eef715c3e99bf6bbc8f81cb21ed15f230f443 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 15 May 2016 01:35:01 +0800 Subject: [PATCH 46/53] update swift petstore sample --- .../Classes/Swaggers/APIHelper.swift | 18 +++++++ .../Classes/Swaggers/APIs/PetAPI.swift | 54 +++++++++++++------ .../Classes/Swaggers/APIs/StoreAPI.swift | 27 +++++++--- .../Classes/Swaggers/APIs/UserAPI.swift | 52 ++++++++++++------ 4 files changed, 111 insertions(+), 40 deletions(-) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift index 418f1c8512b..7041709f365 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -18,4 +18,22 @@ class APIHelper { } return destination } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject] { + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + if (source != nil) { + for (key, value) in source! { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + } + return destination + } + } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 64aa3c8803c..c7e5a6402b5 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -57,10 +57,12 @@ public class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -111,11 +113,14 @@ public class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -174,11 +179,14 @@ public class PetAPI: APIBase { let nillableParameters: [String:AnyObject?] = [ "status": status ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -276,11 +284,14 @@ public class PetAPI: APIBase { let nillableParameters: [String:AnyObject?] = [ "tags": tags ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -380,11 +391,14 @@ public class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -433,10 +447,12 @@ public class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -496,11 +512,14 @@ public class PetAPI: APIBase { "name": name, "status": status ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -560,11 +579,14 @@ public class PetAPI: APIBase { "additionalMetadata": additionalMetadata, "file": file ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 4521afd3d89..be7d36b91f3 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -56,11 +56,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -112,11 +115,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -194,11 +200,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -274,10 +283,12 @@ public class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 62018cd83c2..1b5ada9da67 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -54,10 +54,12 @@ public class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -103,10 +105,12 @@ public class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -152,10 +156,12 @@ public class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -203,11 +209,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -293,11 +302,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -352,11 +364,14 @@ public class UserAPI: APIBase { "username": username, "password": password ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -399,11 +414,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -453,10 +471,12 @@ public class UserAPI: APIBase { path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) } } From f38bdae6c04f86d6c7975d7360ef3ebb7dc34bd3 Mon Sep 17 00:00:00 2001 From: J Webb Date: Sat, 14 May 2016 16:38:00 -0400 Subject: [PATCH 47/53] Fixes instructions for generating PHP Silex code. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bce750740c7..30d988df0d0 100644 --- a/README.md +++ b/README.md @@ -608,7 +608,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ - -l silex \ + -l silex-PHP \ -o samples/server/petstore/silex ``` From 33a1d24e1ecc6cf1577d6ba54fb1b022d2bd1db6 Mon Sep 17 00:00:00 2001 From: Newell Zhu Date: Sun, 15 May 2016 11:53:54 +0800 Subject: [PATCH 48/53] change better method call --- .../src/main/resources/rails5/routes.mustache | 18 +- .../server/petstore/rails5/config/routes.rb | 170 +++--------------- 2 files changed, 23 insertions(+), 165 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/rails5/routes.mustache b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache index e6b95be33a4..6ebc0d4965d 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/routes.mustache +++ b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache @@ -2,28 +2,14 @@ Rails.application.routes.draw do def add_swagger_route http_method, path, opts = {} full_path = path.gsub(/{(.*?)}/, ':\1') - action = - (opts[:isRestfulIndex] && :index) || - (opts[:isRestfulShow] && :show) || - (opts[:isRestfulCreate] && :create) || - (opts[:isRestfulUpdate] && :update) || - (opts[:isRestfulDestroy] && :destroy) || - opts[:nickname] - - match full_path, to: "#{opts.fetch(:classVarName)}##{action}", via: http_method + match full_path, to: "#{opts.fetch(:controller_name)}##{opts[:action_name]}", via: http_method end {{#apiInfo}} {{#apis}} {{#operations}} {{#operation}} - add_swagger_route '{{httpMethod}}', '{{basePathWithoutHost}}{{path}}', - classVarName: '{{classVarName}}', nickname: '{{nickname}}', - isRestfulIndex: {{#isRestfulIndex}}true{{/isRestfulIndex}}{{^isRestfulIndex}}false{{/isRestfulIndex}}, - isRestfulCreate: {{#isRestfulCreate}}true{{/isRestfulCreate}}{{^isRestfulCreate}}false{{/isRestfulCreate}}, - isRestfulUpdate: {{#isRestfulUpdate}}true{{/isRestfulUpdate}}{{^isRestfulUpdate}}false{{/isRestfulUpdate}}, - isRestfulShow: {{#isRestfulShow}}true{{/isRestfulShow}}{{^isRestfulShow}}false{{/isRestfulShow}}, - isRestfulDestroy: {{#isRestfulDestroy}}true{{/isRestfulDestroy}}{{^isRestfulDestroy}}false{{/isRestfulDestroy}} + add_swagger_route '{{httpMethod}}', '{{basePathWithoutHost}}{{path}}', controller_name: '{{classVarName}}', action_name: {{#isRestfulIndex}}'index'{{/isRestfulIndex}}{{#isRestfulCreate}}'create'{{/isRestfulCreate}}{{#isRestfulUpdate}}'update'{{/isRestfulUpdate}}{{#isRestfulShow}}'show'{{/isRestfulShow}}{{#isRestfulDestroy}}'destroy'{{/isRestfulDestroy}}{{^isRestful}}'{{nickname}}'{{/isRestful}} {{/operation}} {{/operations}} {{/apis}} diff --git a/samples/server/petstore/rails5/config/routes.rb b/samples/server/petstore/rails5/config/routes.rb index 502140c332b..de0b1f61035 100644 --- a/samples/server/petstore/rails5/config/routes.rb +++ b/samples/server/petstore/rails5/config/routes.rb @@ -2,155 +2,27 @@ Rails.application.routes.draw do def add_swagger_route http_method, path, opts = {} full_path = path.gsub(/{(.*?)}/, ':\1') - action = - (opts[:isRestfulIndex] && :index) || - (opts[:isRestfulShow] && :show) || - (opts[:isRestfulCreate] && :create) || - (opts[:isRestfulUpdate] && :update) || - (opts[:isRestfulDestroy] && :destroy) || - opts[:nickname] - - match full_path, to: "#{opts.fetch(:classVarName)}##{action}", via: http_method + match full_path, to: "#{opts.fetch(:controller_name)}##{opts[:action_name]}", via: http_method end - add_swagger_route 'POST', '/v2/pet', - classVarName: 'pet', nickname: 'add_pet', - isRestfulIndex: false, - isRestfulCreate: true, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'DELETE', '/v2/pet/{petId}', - classVarName: 'pet', nickname: 'delete_pet', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: true - add_swagger_route 'GET', '/v2/pet/findByStatus', - classVarName: 'pet', nickname: 'find_pets_by_status', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'GET', '/v2/pet/findByTags', - classVarName: 'pet', nickname: 'find_pets_by_tags', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'GET', '/v2/pet/{petId}', - classVarName: 'pet', nickname: 'get_pet_by_id', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: true, - isRestfulDestroy: false - add_swagger_route 'PUT', '/v2/pet', - classVarName: 'pet', nickname: 'update_pet', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'POST', '/v2/pet/{petId}', - classVarName: 'pet', nickname: 'update_pet_with_form', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'POST', '/v2/pet/{petId}/uploadImage', - classVarName: 'pet', nickname: 'upload_file', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'DELETE', '/v2/store/order/{orderId}', - classVarName: 'store', nickname: 'delete_order', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'GET', '/v2/store/inventory', - classVarName: 'store', nickname: 'get_inventory', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'GET', '/v2/store/order/{orderId}', - classVarName: 'store', nickname: 'get_order_by_id', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'POST', '/v2/store/order', - classVarName: 'store', nickname: 'place_order', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'POST', '/v2/user', - classVarName: 'user', nickname: 'create_user', - isRestfulIndex: false, - isRestfulCreate: true, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'POST', '/v2/user/createWithArray', - classVarName: 'user', nickname: 'create_users_with_array_input', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'POST', '/v2/user/createWithList', - classVarName: 'user', nickname: 'create_users_with_list_input', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'DELETE', '/v2/user/{username}', - classVarName: 'user', nickname: 'delete_user', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: true - add_swagger_route 'GET', '/v2/user/{username}', - classVarName: 'user', nickname: 'get_user_by_name', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: true, - isRestfulDestroy: false - add_swagger_route 'GET', '/v2/user/login', - classVarName: 'user', nickname: 'login_user', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'GET', '/v2/user/logout', - classVarName: 'user', nickname: 'logout_user', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: false, - isRestfulShow: false, - isRestfulDestroy: false - add_swagger_route 'PUT', '/v2/user/{username}', - classVarName: 'user', nickname: 'update_user', - isRestfulIndex: false, - isRestfulCreate: false, - isRestfulUpdate: true, - isRestfulShow: false, - isRestfulDestroy: false + add_swagger_route 'POST', '/v2/pet', controller_name: 'pet', action_name: 'create' + add_swagger_route 'DELETE', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'destroy' + add_swagger_route 'GET', '/v2/pet/findByStatus', controller_name: 'pet', action_name: 'find_pets_by_status' + add_swagger_route 'GET', '/v2/pet/findByTags', controller_name: 'pet', action_name: 'find_pets_by_tags' + add_swagger_route 'GET', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'show' + add_swagger_route 'PUT', '/v2/pet', controller_name: 'pet', action_name: 'update_pet' + add_swagger_route 'POST', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'update_pet_with_form' + add_swagger_route 'POST', '/v2/pet/{petId}/uploadImage', controller_name: 'pet', action_name: 'upload_file' + add_swagger_route 'DELETE', '/v2/store/order/{orderId}', controller_name: 'store', action_name: 'delete_order' + add_swagger_route 'GET', '/v2/store/inventory', controller_name: 'store', action_name: 'get_inventory' + add_swagger_route 'GET', '/v2/store/order/{orderId}', controller_name: 'store', action_name: 'get_order_by_id' + add_swagger_route 'POST', '/v2/store/order', controller_name: 'store', action_name: 'place_order' + add_swagger_route 'POST', '/v2/user', controller_name: 'user', action_name: 'create' + add_swagger_route 'POST', '/v2/user/createWithArray', controller_name: 'user', action_name: 'create_users_with_array_input' + add_swagger_route 'POST', '/v2/user/createWithList', controller_name: 'user', action_name: 'create_users_with_list_input' + add_swagger_route 'DELETE', '/v2/user/{username}', controller_name: 'user', action_name: 'destroy' + add_swagger_route 'GET', '/v2/user/{username}', controller_name: 'user', action_name: 'show' + add_swagger_route 'GET', '/v2/user/login', controller_name: 'user', action_name: 'login_user' + add_swagger_route 'GET', '/v2/user/logout', controller_name: 'user', action_name: 'logout_user' + add_swagger_route 'PUT', '/v2/user/{username}', controller_name: 'user', action_name: 'update' end From c5136e4ddabc8c572d3e763e8063a8924582b6a2 Mon Sep 17 00:00:00 2001 From: zhenjun115 Date: Sun, 15 May 2016 13:43:08 +0800 Subject: [PATCH 49/53] change volley to the default http library for android (existing errors); --- bin/android-petstore-httpclient.sh | 31 +++++++++++++++++++ bin/android-petstore.sh | 4 +-- .../languages/AndroidClientCodegen.java | 17 +++++++--- 3 files changed, 45 insertions(+), 7 deletions(-) create mode 100755 bin/android-petstore-httpclient.sh diff --git a/bin/android-petstore-httpclient.sh b/bin/android-petstore-httpclient.sh new file mode 100755 index 00000000000..1b1609f0307 --- /dev/null +++ b/bin/android-petstore-httpclient.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android/httpclient" + +java $JAVA_OPTS -jar $executable $ags \ No newline at end of file diff --git a/bin/android-petstore.sh b/bin/android-petstore.sh index 72b12f92e55..93016af8487 100755 --- a/bin/android-petstore.sh +++ b/bin/android-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android/default" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -c bin/android-petstore-volley.json -o samples/client/petstore/android/volley" -java $JAVA_OPTS -jar $executable $ags +java $JAVA_OPTS -jar $executable $ags \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index b1e1515254f..486dae8d5b2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -89,8 +89,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.") .defaultValue(Boolean.TRUE.toString())); - supportedLibraries.put("", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1"); supportedLibraries.put("volley", "HTTP client: Volley 1.0.19"); + supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setEnum(supportedLibraries); cliOptions.add(library); @@ -384,21 +384,28 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi if (StringUtils.isEmpty(getLibrary())) { modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - addSupportingFilesForDefault(); - } else if ("volley".equals(getLibrary())) { + addSupportingFilesForVolley(); + }else if( "volley".equals( getLibrary() ) ){ modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); addSupportingFilesForVolley(); + }else if ("http-client".equals(getLibrary())) { + modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); + apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); + //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + addSupportingFilesForHttpClient(); } } - private void addSupportingFilesForDefault() { + private void addSupportingFilesForHttpClient() { supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); From d01305671f5415e07b08eed0b675257cfa9b7540 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 15 May 2016 14:40:20 +0800 Subject: [PATCH 50/53] minor fix to android after switching default lib --- bin/android-petstore-httpclient.sh | 4 +- bin/android-petstore.sh | 4 +- .../languages/AndroidClientCodegen.java | 45 ++++++++++--------- .../options/AndroidClientOptionsProvider.java | 2 +- pom.xml | 4 +- .../{default => httpclient}/.gitignore | 0 .../android/{default => httpclient}/README.md | 12 ++--- .../{default => httpclient}/build.gradle | 0 .../{default => httpclient}/docs/Category.md | 0 .../{default => httpclient}/docs/Order.md | 0 .../{default => httpclient}/docs/Pet.md | 0 .../{default => httpclient}/docs/PetApi.md | 2 +- .../{default => httpclient}/docs/StoreApi.md | 0 .../{default => httpclient}/docs/Tag.md | 0 .../{default => httpclient}/docs/User.md | 0 .../{default => httpclient}/docs/UserApi.md | 0 .../{default => httpclient}/git_push.sh | 0 .../android/{default => httpclient}/pom.xml | 0 .../{default => httpclient}/settings.gradle | 0 .../src/main/AndroidManifest.xml | 0 .../java/io/swagger/client/ApiException.java | 0 .../java/io/swagger/client/ApiInvoker.java | 0 .../java/io/swagger/client/HttpPatch.java | 0 .../main/java/io/swagger/client/JsonUtil.java | 0 .../src/main/java/io/swagger/client/Pair.java | 0 .../java/io/swagger/client/api/PetApi.java | 0 .../java/io/swagger/client/api/StoreApi.java | 0 .../java/io/swagger/client/api/UserApi.java | 0 .../io/swagger/client/model/Category.java | 0 .../java/io/swagger/client/model/Order.java | 0 .../java/io/swagger/client/model/Pet.java | 0 .../java/io/swagger/client/model/Tag.java | 0 .../java/io/swagger/client/model/User.java | 0 .../client/petstore/android/volley/README.md | 12 ++--- .../petstore/android/volley/docs/PetApi.md | 2 +- 35 files changed, 44 insertions(+), 43 deletions(-) rename samples/client/petstore/android/{default => httpclient}/.gitignore (100%) rename samples/client/petstore/android/{default => httpclient}/README.md (100%) rename samples/client/petstore/android/{default => httpclient}/build.gradle (100%) rename samples/client/petstore/android/{default => httpclient}/docs/Category.md (100%) rename samples/client/petstore/android/{default => httpclient}/docs/Order.md (100%) rename samples/client/petstore/android/{default => httpclient}/docs/Pet.md (100%) rename samples/client/petstore/android/{default => httpclient}/docs/PetApi.md (99%) rename samples/client/petstore/android/{default => httpclient}/docs/StoreApi.md (100%) rename samples/client/petstore/android/{default => httpclient}/docs/Tag.md (100%) rename samples/client/petstore/android/{default => httpclient}/docs/User.md (100%) rename samples/client/petstore/android/{default => httpclient}/docs/UserApi.md (100%) rename samples/client/petstore/android/{default => httpclient}/git_push.sh (100%) rename samples/client/petstore/android/{default => httpclient}/pom.xml (100%) rename samples/client/petstore/android/{default => httpclient}/settings.gradle (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/AndroidManifest.xml (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/ApiException.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/ApiInvoker.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/HttpPatch.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/JsonUtil.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/Pair.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/api/PetApi.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/api/StoreApi.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/api/UserApi.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/model/Category.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/model/Order.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/model/Pet.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/model/Tag.java (100%) rename samples/client/petstore/android/{default => httpclient}/src/main/java/io/swagger/client/model/User.java (100%) diff --git a/bin/android-petstore-httpclient.sh b/bin/android-petstore-httpclient.sh index 1b1609f0307..097484e0410 100755 --- a/bin/android-petstore-httpclient.sh +++ b/bin/android-petstore-httpclient.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android/httpclient" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -Dlibrary=httpclient -o samples/client/petstore/android/httpclient" -java $JAVA_OPTS -jar $executable $ags \ No newline at end of file +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/android-petstore.sh b/bin/android-petstore.sh index 93016af8487..67256debeb0 100755 --- a/bin/android-petstore.sh +++ b/bin/android-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -c bin/android-petstore-volley.json -o samples/client/petstore/android/volley" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android/volley" -java $JAVA_OPTS -jar $executable $ags \ No newline at end of file +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 486dae8d5b2..58b59f71364 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -89,8 +89,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.") .defaultValue(Boolean.TRUE.toString())); - supportedLibraries.put("volley", "HTTP client: Volley 1.0.19"); - supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1"); + supportedLibraries.put("volley", "HTTP client: Volley 1.0.19 (default)"); + supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release."); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setEnum(supportedLibraries); cliOptions.add(library); @@ -382,30 +382,26 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi additionalProperties.put( "modelDocPath", modelDocPath ); if (StringUtils.isEmpty(getLibrary())) { - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); - //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); - addSupportingFilesForVolley(); - }else if( "volley".equals( getLibrary() ) ){ - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); - //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); - addSupportingFilesForVolley(); - }else if ("http-client".equals(getLibrary())) { - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); - //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - addSupportingFilesForHttpClient(); + setLibrary("volley"); // set volley as the default library } + + // determine which file (mustache) to add based on library + if ("volley".equals(getLibrary())) { + addSupportingFilesForVolley(); + } else if ("httpclient".equals(getLibrary())) { + addSupportingFilesForHttpClient(); + } else { + throw new IllegalArgumentException("Invalid 'library' option specified: '" + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)"); + } + } private void addSupportingFilesForHttpClient() { + // documentation files + modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); + apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); @@ -425,6 +421,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi } private void addSupportingFilesForVolley() { + // documentation files + modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); + apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java index 82bb13029e5..82ffa437f2a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java @@ -18,7 +18,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true"; - public static final String LIBRARY_VALUE = "volley"; + public static final String LIBRARY_VALUE = "httpclient"; @Override public String getLanguage() { diff --git a/pom.xml b/pom.xml index 1b5c3d7580f..4b11b1230e2 100644 --- a/pom.xml +++ b/pom.xml @@ -267,7 +267,7 @@ - samples/client/petstore/android/default + samples/client/petstore/android/volley @@ -471,7 +471,7 @@ - samples/client/petstore/android/default + samples/client/petstore/android/volley samples/client/petstore/clojure samples/client/petstore/java/default samples/client/petstore/java/feign diff --git a/samples/client/petstore/android/default/.gitignore b/samples/client/petstore/android/httpclient/.gitignore similarity index 100% rename from samples/client/petstore/android/default/.gitignore rename to samples/client/petstore/android/httpclient/.gitignore diff --git a/samples/client/petstore/android/default/README.md b/samples/client/petstore/android/httpclient/README.md similarity index 100% rename from samples/client/petstore/android/default/README.md rename to samples/client/petstore/android/httpclient/README.md index a1c37674b81..65931066a32 100644 --- a/samples/client/petstore/android/default/README.md +++ b/samples/client/petstore/android/httpclient/README.md @@ -116,6 +116,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -125,12 +131,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/android/default/build.gradle b/samples/client/petstore/android/httpclient/build.gradle similarity index 100% rename from samples/client/petstore/android/default/build.gradle rename to samples/client/petstore/android/httpclient/build.gradle diff --git a/samples/client/petstore/android/default/docs/Category.md b/samples/client/petstore/android/httpclient/docs/Category.md similarity index 100% rename from samples/client/petstore/android/default/docs/Category.md rename to samples/client/petstore/android/httpclient/docs/Category.md diff --git a/samples/client/petstore/android/default/docs/Order.md b/samples/client/petstore/android/httpclient/docs/Order.md similarity index 100% rename from samples/client/petstore/android/default/docs/Order.md rename to samples/client/petstore/android/httpclient/docs/Order.md diff --git a/samples/client/petstore/android/default/docs/Pet.md b/samples/client/petstore/android/httpclient/docs/Pet.md similarity index 100% rename from samples/client/petstore/android/default/docs/Pet.md rename to samples/client/petstore/android/httpclient/docs/Pet.md diff --git a/samples/client/petstore/android/default/docs/PetApi.md b/samples/client/petstore/android/httpclient/docs/PetApi.md similarity index 99% rename from samples/client/petstore/android/default/docs/PetApi.md rename to samples/client/petstore/android/httpclient/docs/PetApi.md index f8ba698c05a..f0f8ad40fbe 100644 --- a/samples/client/petstore/android/default/docs/PetApi.md +++ b/samples/client/petstore/android/httpclient/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/android/default/docs/StoreApi.md b/samples/client/petstore/android/httpclient/docs/StoreApi.md similarity index 100% rename from samples/client/petstore/android/default/docs/StoreApi.md rename to samples/client/petstore/android/httpclient/docs/StoreApi.md diff --git a/samples/client/petstore/android/default/docs/Tag.md b/samples/client/petstore/android/httpclient/docs/Tag.md similarity index 100% rename from samples/client/petstore/android/default/docs/Tag.md rename to samples/client/petstore/android/httpclient/docs/Tag.md diff --git a/samples/client/petstore/android/default/docs/User.md b/samples/client/petstore/android/httpclient/docs/User.md similarity index 100% rename from samples/client/petstore/android/default/docs/User.md rename to samples/client/petstore/android/httpclient/docs/User.md diff --git a/samples/client/petstore/android/default/docs/UserApi.md b/samples/client/petstore/android/httpclient/docs/UserApi.md similarity index 100% rename from samples/client/petstore/android/default/docs/UserApi.md rename to samples/client/petstore/android/httpclient/docs/UserApi.md diff --git a/samples/client/petstore/android/default/git_push.sh b/samples/client/petstore/android/httpclient/git_push.sh similarity index 100% rename from samples/client/petstore/android/default/git_push.sh rename to samples/client/petstore/android/httpclient/git_push.sh diff --git a/samples/client/petstore/android/default/pom.xml b/samples/client/petstore/android/httpclient/pom.xml similarity index 100% rename from samples/client/petstore/android/default/pom.xml rename to samples/client/petstore/android/httpclient/pom.xml diff --git a/samples/client/petstore/android/default/settings.gradle b/samples/client/petstore/android/httpclient/settings.gradle similarity index 100% rename from samples/client/petstore/android/default/settings.gradle rename to samples/client/petstore/android/httpclient/settings.gradle diff --git a/samples/client/petstore/android/default/src/main/AndroidManifest.xml b/samples/client/petstore/android/httpclient/src/main/AndroidManifest.xml similarity index 100% rename from samples/client/petstore/android/default/src/main/AndroidManifest.xml rename to samples/client/petstore/android/httpclient/src/main/AndroidManifest.xml diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiException.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/HttpPatch.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/HttpPatch.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/JsonUtil.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/JsonUtil.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/Pair.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Category.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Order.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Pet.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/User.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md index 6f0a2c65f92..e4aa4748243 100644 --- a/samples/client/petstore/android/volley/README.md +++ b/samples/client/petstore/android/volley/README.md @@ -116,6 +116,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -125,12 +131,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index f8ba698c05a..f0f8ad40fbe 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers From cda6bc380eba7eb6e5cceca226bdbafbb275609b Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 15 May 2016 17:06:46 +0800 Subject: [PATCH 51/53] update android volley dependencies, add source and target in pom.xml --- .../android/libraries/volley/pom.mustache | 17 +++++++++++++++-- .../client/petstore/android/volley/README.md | 8 ++++---- .../client/petstore/android/volley/pom.xml | 19 ++++++++++++++++--- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache index 4036bb32afb..80ba5feacab 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache @@ -37,11 +37,24 @@ ${android-platform-version} + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.6 + 1.6 + + + + - 1.5.0 + 1.5.8 4.4.4 4.5.2 - 2.3.1 + 2.6.2 1.0.19 4.1.1.4 diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md index e4aa4748243..65931066a32 100644 --- a/samples/client/petstore/android/volley/README.md +++ b/samples/client/petstore/android/volley/README.md @@ -1,4 +1,4 @@ -# swagger-petstore-android-volley +# swagger-android-client ## Requirements @@ -27,7 +27,7 @@ Add this dependency to your project's POM: ```xml io.swagger - swagger-petstore-android-volley + swagger-android-client 1.0.0 compile @@ -38,7 +38,7 @@ Add this dependency to your project's POM: Add this dependency to your project's build file: ```groovy -compile "io.swagger:swagger-petstore-android-volley:1.0.0" +compile "io.swagger:swagger-android-client:1.0.0" ``` ### Others @@ -49,7 +49,7 @@ At first generate the JAR by executing: Then manually install the following JARs: -* target/swagger-petstore-android-volley-1.0.0.jar +* target/swagger-android-client-1.0.0.jar * target/lib/*.jar ## Getting Started diff --git a/samples/client/petstore/android/volley/pom.xml b/samples/client/petstore/android/volley/pom.xml index 98572662fb2..04369688c3b 100644 --- a/samples/client/petstore/android/volley/pom.xml +++ b/samples/client/petstore/android/volley/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 io.swagger - swagger-petstore-android-volley + swagger-android-client 1.0.0 @@ -37,11 +37,24 @@ ${android-platform-version} + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.6 + 1.6 + + + + - 1.5.0 + 1.5.8 4.4.4 4.5.2 - 2.3.1 + 2.6.2 1.0.19 4.1.1.4 From b1572af65de0bcbd5205bef96a50f2252cad5491 Mon Sep 17 00:00:00 2001 From: cbornet Date: Sun, 15 May 2016 16:08:43 +0200 Subject: [PATCH 52/53] update versions in java libraries descriptions --- .../swagger/codegen/languages/JavaClientCodegen.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index bc839f07d18..30c4941c57d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -107,12 +107,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated")); - supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); - supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); - supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); - supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); - supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); - supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.1). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.2)"); + supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2"); + supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); + supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); From 10f11ad91e92307b13481f7fb474663745f67707 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 16 May 2016 14:37:47 +0800 Subject: [PATCH 53/53] add zlx --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 30d988df0d0..52c8b8c4749 100644 --- a/README.md +++ b/README.md @@ -894,6 +894,7 @@ Here is a list of template creators: * JAX-RS CXF: @hiveship * PHP Lumen: @abcsum * PHP Slim: @jfastnacht + * Ruby on Rails 5: @zlx ## How to join the core team