[
  {
    "path": ".gitignore",
    "content": "bower_components\nnode_modules\n.idea\nnpm-debug.log\ndist\nyarn-error.log"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2016 Amareis\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.adoc",
    "content": "= another-rest-client\n\nSimple REST API client that makes your code lesser and more beautiful than without it.\n\nThere is some rest clients - https://github.com/marmelab/restful.js[restful.js], https://github.com/cujojs/rest[cujojs/rest] or https://github.com/lincolnloop/amygdala[amygdala] - so why you need another rest client? First, because all of this is not maintained anymore :) But also, because with it your code less and more beautiful than without it or with any analogs. Also, its code really simple - less than 300 sloc and (almost) without magic, so you can just read it (and fix, may be?) if something go wrong.\n\nTo prove my words, here is an minimal working code (you can explore more examples https://github.com/Amareis/another-rest-client/tree/master/examples[here]):\n\nAnd it works with typescript!\n\n[source,typescript]\n----\nimport {RestClient} from 'another-rest-client'\n\nconst api = new RestClient('https://api.github.com').withRes({\n    repos: 'releases',\n} as const)\n\napi.repos('Amareis/another-rest-client').releases('latest').get().then((release: any) => {\n    console.log(release)\n    document.write('Latest release of another-rest-client:<br>')\n    document.write('Published at: ' + release.published_at + '<br>')\n    document.write('Tag: ' + release.tag_name + '<br>')\n})\n----\n\n== Installation\n\nLibrary is available with npm:\n\n[source,shell]\n----\nnpm install another-rest-client\n# or\nyarn add another-rest-client\n----\n\nNow, add it in script tag or require it or import it:\n\n[source,js]\n----\nconst {RestClient} = require('another-rest-client')\nimport {RestClient} from 'another-rest-client'\n----\n\n*ATTENTION:* If you want to use another-rest-client with node.js, you must define XMLHttpRequest before import (https://github.com/driverdan/node-XMLHttpRequest[see here]):\n\n[source,js]\n----\nglobal.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest\n----\n\n== Usage\n\n[source,js]\n----\nconst api = new RestClient('https://example.com')\n----\n\nAnd here we go! First, let's define resources, using `res` method:\n\n[source,js]\n----\napi.res('cookies')         //it gets resource name and returns resource\napi.res(['cows', 'bees'])  //or it gets array of resource names and returns array of resources\napi.res({       //or it gets object and returns object where resource is available by name\n    dogs: [\n        'toys',\n        'friends'],\n    cats: 0,\n    humans:\n        'posts',\n})\n/* last string is equal to:\napi.res('dogs').res(['toys', 'friends'])\napi.res('cats')\napi.res('humans').res('posts') */\n----\n\nNow we can query our resources using methods `get` (optionally gets query args), `post`, `put`, `patch` (gets body content) and `delete`. All these methods returns promise, that resolves with object that given by server or rejects with `XMLHttpRequest` instance:\n\n[source,js]\n----\napi.cookies.get()              //GET https://example.com/cookies\napi.cookies.get({fresh: true}) //GET https://example.com/cookies?fresh=true\napi.cookies.get({'filter[]': 'fresh'}, {'filter[]': 'taste'}) //GET https://example.com/cookies?filter%5B%5D=fresh&filter%5B%5D=taste\n\n//POST https://example.com/cows, body=\"{\"color\":\"white\",\"name\":\"Moo\"}\"\napi.cows.post({color: 'white', name: 'Moo'}).then((cow) => {\n    console.log(cow)    //just object, i.e. {id: 123, name: 'Moo', color: 'white'}\n}, (xhr) => {\n    console.log(xhr)   //XMLHtppRequest instance\n})\n----\n\nIf you want query single resource instance, just pass it id into resource:\n\n[source,js]\n----\napi.cookies(42).get()  //GET https://example.com/cookies/42\n\n//GET https://example.com/cookies/42?fields=ingridients,baker\napi.cookies(42).get({fields: ['ingridients', 'baker']})\n\napi.bees(12).put({state: 'dead'})  //PUT https://example.com/bees/12, body=\"{\"state\":\"dead\"}\"\napi.cats(64).patch({age: 3})       //PATCH https://example.com/cats/64, body=\"{\"age\":3}\"\n----\n\nYou can query subresources easily:\n\n[source,js]\n----\napi.dogs(1337).toys.get()          //GET https://example.com/dogs/1337/toys\napi.dogs(1337).friends(2).delete() //DELETE https://example.com/dogs/1337/friends/2\n\n//POST https://example.com/humans/me/posts, body=\"{\"site\":\"habrahabr.ru\",\"nick\":\"Amareis\"}\"\napi.humans('me').posts.post({site: 'habrahabr.ru', nick: 'Amareis'})\n----\n\nYou can use `url` resource method to get resource url:\n\n[source,js]\n----\napi.dogs.url() === '/dogs'\napi.dogs(1337).friends(1).url() === '/dogs/1337/friends/1'\n----\n\nAnd, of course, you always can use ES6 async/await to make your code more readable:\n\n[source,js]\n----\nconst me = api.humans('me')\nconst i = await me.get()\nconsole.log(i)    //just object, i.e. {id: 1, name: 'Amareis', profession: 'programmer'}\nconst post = await me.posts.post({site: 'habrahabr.ru', nick: i.name})\nconsole.log(post)  //object\n----\n== TypeScript\n\nLibrary infer types from schema, passed to `res`. But it returns new resource (or array or object), so to use it\ncorrectly, you need to use `withRes` method, which returns modified original resource:\n\n[source,typescript]\n----\nlet api = new RestClient('https://api.github.com').withRes({\n    repos: 'releases',\n} as const) // as const needed to infer resources names\n\n// correctly infer all this subresources!\napi.repos('Amareis/another-rest-client').releases('latest').get()\n----\n\nYou can then add more resources reusing already typed resource:\n\n[source,typescript]\n----\napi = api.withRes('additional-resource')\n----\n\n**Custom shortcuts currently not working with TypeScript! And shorcuts always will be in typings, even if they are disabled.**\n\n== Events\n\n`RestClient` use https://github.com/allouis/minivents[minivents] and emit some events:\n\n- `request` - when `open` XMLHttpRequest, but before `send`.\n- `response` - when get server response.\n- `success` - when get server response with status 200, 201 or 204.\n- `error` - when get server response with another status.\n\nAll events gets current XMLHttpRequest instance.\n\nOften use case - authorization:\n\n[source,js]\n----\napi.on('request', xhr => {\n    xhr.setRequestHeader('Authorization', 'Bearer xxxTOKENxxx')\n})\n----\n\nAlso, returns by `get`, `post`, `put`, `patch` and `delete` `Promise` objects also emit these events, but only for current request.\n\n[source,js]\n----\napi.dogs(1337).toys.get().on('success', console.log.bind(console)).then(toys => \"...\") //in log will be xhr instance\napi.dogs(1337).toys.get().then(toys => \"...\") //log is clear\n----\n\nYou can use events to set `responseType` XMLHttpRequest property, to handle binary files (and you can compose it with custom decoders, as described below, to automatically convert blob to File object):\n\n[source,js]\n----\napi.files('presentation.pdf').get().on('request', xhr => xhr.responseType = 'blob').then(blobObj => \"...\")\n----\n\n== Configuration\n\nAll the examples given above are based on the default settings. If for some reason you are not satisfied, read this section.\n\nAll configuration is done using the object passed to the constructor or method `conf`. Some options are also duplicated by optional methods arguments.\n\n`conf` returns full options. If you call it without parameters (just `conf()`), it gives you current options.\n\n[source,js]\n----\nconsole.log(api.conf())\n/* Defaults:\n{\n    \"trailing\": \"\",\n    \"shortcut\": true,\n    \"shortcutRules\": [],\n    \"contentType\": \"application/json\",\n    \"encodings\": {\n        \"application/x-www-form-urlencoded\": {encode: encodeUrl},\n        \"application/json\": {encode: JSON.stringify, decode: JSON.parse}\n    }\n}*/\n----\n\nIf you want change RestClient host (lol why?..), you can just:\n\n[source,js]\n----\napi.host = 'https://example2.com'\n----\n\n=== Trailing symbol\n\nSome APIs require trailing slash (for example, this is the default behavior in the django-rest-framework). By default another-rest-client doesn't use any trailing symbol, but you can change this:\n\n[source,js]\n----\nconst api = new RestClient('https://example.com', {trailing: '/'})\n//or\napi.conf({trailing: '/'})\n----\n\nOf course, you can pass all you want (`{trailing: &#39/i-have-no-idea-why-you-want-this-but-you-can/&#39}`).\n\n=== Shortcuts\n\nShortcuts - resources and subresources, that accessible as parent resource field:\n\n[source,js]\n----\napi.cars === undefined\nconst cars = api.res('cars')\napi.cars === cars   //api.cars is shortcut for 'cars' resource\n----\n\nBy default, another-rest-client will make shortcuts for defined resources. This behavior can be disabled in three ways:\n\n[source,js]\n----\napi.sounds === undefined\n\n//first way\nconst api = new RestClient('https://example.com', {shortcut: false})\n//or, second way\napi.conf({shortcut: false})\n//or, third way\nconst sounds = api.res('sounds', false)\n\n//and, still...\napi.sounds === undefined\n----\n\nFirst two ways disables shortcuts globally - on all resources and subresources. Third way disables shortcuts locally - in one `res` call. Also, with third way you can locally _enable_ shortcuts (pass `true` as second `res` argument) when globally they are disabled.\n\nLocal disable of shortcuts can solve some name conflicts (when resource shortcut overwrites some method), but, probably, you will not be affected by this.\n\n*It is strongly recommended do not disable the shortcuts, they greatly enhance code readability.*\n\nYou can also add custom shortcuts for resources via rules. Those can be configured via the `shortcutRules` array in the options. When a resource is added all rules will be invoked with the resource name as argument. If the return value is a non-empty string, it will serve as an additional shortcut.\n\nHave a look at this example which will convert strings with dashes into their camel-case counterpart to serve as additional shortcut:\n\n[source,js]\n----\nconst DASH_REG = /(-)(.)/g\nfunction dashReplace(resourceName) {\n    return resourceName.replace(DASH_REG, (match, p1, p2) => p2.toUpperCase())\n}\n\nconst api = new RestClient('https://example.com', {shortcutRules: [ dashReplace ]})\napi.res('engine-rest')\napi['engine-rest'] // standard shortcut\napi.engineRest     // custom shortcut to improve readability\n----\n\n=== Request content type\n\nWhen you call `post`, `put` or `patch`, you pass an object to be encoded into string and sent to the server. But how it will be encoded and what `Content-Type` header will be set?\nBy default - in json (`application/json`), using `JSON.stringify`. To change this behavior, you can manually set request content type:\n\n[source,js]\n----\nconst api = new RestClient('https://example.com', {contentType: 'application/x-www-form-urlencoded'})\n//or by conf\napi.conf({contentType: 'application/x-www-form-urlencoded'})\n//or by second argument in 'post', 'put' or 'patch'\napi.cookies.post({fresh: true}, 'application/x-www-form-urlencoded')\n----\n\nBy default RestClient can encode data in `application/json` and `application/x-www-form-urlencoded`. You can add (or replace defaults with) your own encoders:\n\n[source,js]\n----\nconst opts = {\n    contentType: 'application/x-my-cool-mime',\n    encodings: {\n        'application/x-my-cool-mime': {\n            encode: (objectPassedToPostPutOrPatch) => {\n                //...\n                return encodedToStringObject\n            }\n        }\n    }\n}\nconst api = new RestClient('https://example.com', opts)\n//or by conf\napi.conf(opts)\n----\n\nIf there is no suitable encoder, passed object will be passed to the XMLHttpRequest.send without changes.\n\n=== Response content type\n\nWhen server answers, it give `Content-Type` header. another-rest-client smart enough to parse it and decode `XMLHttpRequest.responseText` into object. By default it can decode only `application/json` using `JSON.parse`, but you can add your own decoders:\n\n[source,js]\n----\nconst opts = {\n    encodings: {\n        'application/x-my-cool-mime': {\n            decode: (stringFromXhrResponseText) => {\n                //...\n                return decodedFromStringObject\n            }\n        }\n    }\n}\nconst api = new RestClient('https://example.com', opts)\n//or by conf\napi.conf(opts)\n----\n\nIf there is no suitable decoder (or server given't `Content-Type` header), gotten `XMLHttpRequest.response` will be passed to Promise.resolve without changes.\n\nOf course, you can combine encoders and decoders for single MIME:\n\n[source,js]\n----\nconst opts = {\n    contentType: 'application/x-my-cool-mime',\n    encodings: {\n        'application/x-my-cool-mime': {\n            encode: (objectPassedToPostPutOrPatch) => {\n                //...\n                return encodedToStringObject\n            },\n            decode: (stringFromXhrResponseText) => {\n                //...\n                return decodedFromStringObject\n            }\n        }\n    }\n}\n\nconst api = new RestClient('https://example.com', opts)\n//or by conf\napi.conf(opts)\n----\n\n== Contributing\n\nThat's easy:\n\n[source,bash]\n----\ngit clone https://github.com/Amareis/another-rest-client.git\ncd another-rest-client\nyarn\necho \"//Some changes...\" >> src/rest-client.ts\nyarn build && yarn test\n----\n"
  },
  {
    "path": "build.js",
    "content": "const path = require(\"path\");\nconst esbuild = require(\"esbuild\");\n\nlet outdir = path.resolve(process.cwd(), \"dist\");\n\nconst globalName = 'RestClient';\n\n// esbuild doesn't support umd, here's a hack from\n// https://github.com/evanw/esbuild/pull/1331#issuecomment-887877002\nlet footer = `(function (root, factory) {\n  if (typeof define === 'function' && define.amd) {\n    define(factory);\n  } else if (typeof module === 'object' && module.exports) {\n    module.exports = factory();\n    Object.defineProperty(exports, \"__esModule\", {\n\t  value: true\n\t});\n  } else {\n    root.${globalName} = factory().${globalName};\n  }\n}(typeof self !== 'undefined' ? self : this, () => ${globalName}));`;\n\nlet files = {\n\t'rest-client.js': './src/rest-client.js',\n\t'rest-client.min.js': './src/rest-client.js',\n}\n\nlet builds = Object.entries(files)\n\t.map(([filename, source]) => {\n\t\treturn {\n\t\t\tentryPoints: [source],\n\t\t\tsourcemap: true,\n\t\t\toutfile: path.resolve(outdir, filename),\n\t\t\tbundle: true,\n\t\t\tplatform: \"browser\",\n\t\t\tformat: \"iife\",\n\t\t\tfooter: {\n\t\t\t\tjs: footer,\n\t\t\t},\n\t\t\tglobalName,\n\t\t\tminify: /\\.min\\.m?js$/.test(filename)\n\t\t}\n\t})\n\nPromise.all(builds.map(esbuild.build));"
  },
  {
    "path": "examples/github.html",
    "content": "<html lang=\"en\">\n<head>\n    <title>another-rest-client</title>\n    <script src=\"../dist/rest-client.js\"></script>\n    <script>\n        window.onload = function () {\n            const api = new RestClient('https://api.github.com')\n            api.res({repos: 'releases'})\n\n            window.api = api\n\n            api.repos('Amareis/another-rest-client').releases('latest').get().then((release) => {\n                console.log(release)\n                document.body.innerHTML =\n                    'Latest release of another-rest-client:<br>' +\n                    `Published at: ${release.published_at}<br>` +\n                    `Tag: ${release.tag_name}<br>`\n            })\n        }\n    </script>\n</head>\n<body>\n</body>\n</html>"
  },
  {
    "path": "examples/github.ts",
    "content": "import RestClient from '../src/rest-client'\n\nconst api = new RestClient('https://api.github.com').withRes({\n    repos: 'releases',\n} as const)\n\napi.repos('Amareis/another-rest-client').releases('latest').get().then((release: any) => {\n    console.log(release)\n    document.body.innerHTML =\n        'Latest release of another-rest-client:<br>' +\n        `Published at: ${release.published_at}<br>` +\n        `Tag: ${release.tag_name}<br>`\n})\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"another-rest-client\",\n  \"version\": \"0.7.0\",\n  \"description\": \"Simple REST API client that makes your code lesser and more beautiful than without it.\",\n  \"main\": \"dist/rest-client.js\",\n  \"types\": \"dist/rest-clients.d.ts\",\n  \"scripts\": {\n    \"test\": \"mocha\",\n    \"build\": \"tsc && node ./build.js\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/Amareis/another-rest-client.git\"\n  },\n  \"keywords\": [\n    \"rest\"\n  ],\n  \"author\": \"joe <terma95@gmail.com>\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/Amareis/another-rest-client/issues\"\n  },\n  \"homepage\": \"https://github.com/Amareis/another-rest-client#readme\",\n  \"devDependencies\": {\n    \"chai\": \"^4.3.6\",\n    \"esbuild\": \"^0.14.25\",\n    \"form-data\": \"^4.0.0\",\n    \"mocha\": \"^9.2.1\",\n    \"sinon\": \"^13.0.1\",\n    \"typescript\": \"^4.6.2\"\n  }\n}\n"
  },
  {
    "path": "src/minivents.ts",
    "content": "export type Listener = (...p: any[]) => void\n\nexport type Target = {\n    on: (type: string, func: Listener, ctx: any) => Target\n    off: (type?: string, func?: Listener) => Target\n    emit: (type: string, ...args: any[]) => Target\n}\n\nexport function Events<T>(target: T): T & Target {\n    const t: T & Target = target as any\n    let events: Record<string, [Listener, any]> = {}\n    /**\n     *  On: listen to events\n     */\n    t.on = function(type, func, ctx) {\n        (events[type] = events[type] || []).push([func, ctx])\n        return t\n    }\n    /**\n     *  Off: stop listening to event / specific callback\n     */\n    t.off = function(type, func) {\n        if (!type) events = {}\n        const list = events[type as any] || []\n        let i = func ? list.length : 0\n        while (i--) func == list[i][0] && list.splice(i, 1)\n        return t\n    }\n    /**\n     * Emit: send event, callbacks will be triggered\n     */\n    t.emit = function(type: string, ...args: any[]){\n        const e = events[type] || [], list = e.length > 0 ? e.slice(0, e.length) : e\n        let i = 0, j\n        while (j = list[i++]) j[0].apply(j[1], args)\n        return t\n    }\n\n    return t\n}"
  },
  {
    "path": "src/rest-client.ts",
    "content": "import {Events, Target} from './minivents.js'\n\nfunction entries<T extends Record<string, any>>(obj: T): ([Extract<keyof T, string>, any])[] {\n    return Object.entries(obj) as any\n}\n\ntype Arg = Record<string, string | boolean | number>\n\nfunction encodeUrl(data: Arg) {\n    let res = ''\n    for (let [k, v] of entries(data))\n        res += encodeURIComponent(k) + '=' + encodeURIComponent(v) + '&'\n    return res.slice(0, res.length - 1)\n}\n\nfunction safe(func: Function, data: any) {\n    try {\n        return func(data)\n    }\n    catch(e) {\n        console.error('Error in function \"' + func.name + '\" while decode/encode data')\n        console.log(func)\n        console.log(data)\n        console.log(e)\n        return data\n    }\n}\n\nexport type CustomShortcut = (resName: string) => string\n\nexport type Encodings = {\n    [mime: string]: {\n        encode?: (data: any) => string\n        decode?: (xhrResponse: string) => any\n    }\n}\n\nexport type Opts = {\n    trailing: string\n    shortcut: boolean\n    shortcutRules: CustomShortcut[]\n    contentType: string\n    encodings: Encodings\n}\n\ntype Ress = string | readonly string[] | { [resName: string]: Ress | 0 | null | undefined}\n\ntype MakeRes<T extends Ress> =\n    T extends string ? {[resName in T]: Res}\n        : T extends ReadonlyArray<infer S> ? Res & ([S] extends [string] ? {[resName in S]: Res} : never)\n            : {[ResName in keyof T]: T[ResName] extends Ress ? Res & MakeRes<T[ResName]> : Res}\n\ntype MR<T extends Ress> =\n    T extends string ? Res\n        : T extends string[] ? Res[]\n            : {[ResName in keyof T]: T[ResName] extends Ress ? Res & MR<T[ResName]> : Res}\n\ninterface Res {\n    (id?: string | number): this\n}\n\nclass Res extends Function {\n    private _shortcuts: Record<string, Res> = {}\n    private _resources: Record<string, Res> = {}\n\n    private get _client() {\n        return this._c()\n    }\n\n    constructor(private _c: () => RestClient, private _parent: Res | undefined, private _name: string, private _id?: string) {\n        super('id', 'return arguments.callee.__call(id)')\n    }\n\n    private __call = (newId?: string) => {\n        if (newId === undefined)\n            return this\n        return this._clone(this._parent, newId)\n    }\n\n    private _clone = (parent: Res | undefined, newId?: string) => {\n        let copy = new Res(this._c, parent, this._name, newId)\n        copy._shortcuts = this._shortcuts\n        for (let resName in this._resources) {\n            copy._resources[resName] = this._resources[resName]._clone(copy)\n\n            if (resName in copy._shortcuts)\n                (copy as any)[resName] = copy._resources[resName]\n        }\n        return copy\n    }\n\n    withRes = <T extends Ress>(resources: T, shortcut=this._client._opts.shortcut): this & MakeRes<T> => {\n        this.res(resources, shortcut)\n        return this as any\n    }\n\n    res = <T extends Ress>(resources: T, shortcut=this._client._opts.shortcut): MR<T> => {\n        let makeRes = (resName: string) => {\n            if (resName in this._resources)\n                return this._resources[resName]\n\n            let r = new Res(this._c, this, resName)\n            this._resources[resName] = r\n            if (shortcut) {\n                const self = this as any as MakeRes<T>\n                this._shortcuts[resName] = r\n                self[resName] = r\n                for (const rule of this._client._opts.shortcutRules) {\n                    const customShortcut = rule(resName)\n                    if (customShortcut && typeof customShortcut === 'string') {\n                        this._shortcuts[customShortcut] = r\n                        self[customShortcut] = r\n                    }\n                }\n            }\n            return r\n        }\n\n        // (resources instanceof String) don't work in js.\n        if (typeof resources === 'string')\n            return makeRes(resources) as any\n\n        if (resources instanceof Array)\n            return resources.map(makeRes) as any\n\n        if (resources instanceof Object) {\n            let resObj: Record<string, Res> = {}\n            for (let resName in resources) {\n                let r = makeRes(resName)\n                const nr = resources[resName]\n                if (nr) {\n                    r.res(nr as any)\n                }\n                resObj[resName] = r\n            }\n            return resObj as any\n        }\n\n        throw new TypeError('Wrong \"resources\" argument! Should be string, array of strings or object')\n    }\n\n    url = (): string => {\n        let url = this._parent?.url() ?? ''\n        if (this._name)\n            url += '/' + this._name\n        if (this._id !== undefined)\n            url += '/' + this._id\n        return url\n    }\n\n    get = (...args: Arg[]) => {\n        let url = this.url()\n        const query = args.map(encodeUrl).join('&')\n        if (query)\n            url += '?' + query\n        return this._client._request('GET', url)\n    }\n\n    post = (data: any, contentType = this._client._opts.contentType) => {\n        return this._client._request('POST', this.url(), data, contentType)\n    }\n\n    put = (data: any, contentType = this._client._opts.contentType) => {\n        return this._client._request('PUT', this.url(), data, contentType)\n    }\n\n    patch = (data: any, contentType = this._client._opts.contentType) => {\n        return this._client._request('PATCH', this.url(), data, contentType)\n    }\n\n    delete = () => {\n        return this._client._request('DELETE', this.url())\n    }\n}\n\nexport class RestClient extends Res implements Target {\n    host: string\n\n    _opts: Opts = {\n        trailing: '',\n        shortcut: true,\n        shortcutRules: [],\n        contentType: 'application/json',\n        encodings: {\n            'application/x-www-form-urlencoded': {encode: encodeUrl},\n            'application/json': {encode: JSON.stringify, decode: JSON.parse},\n        }\n    }\n\n    emit!: Target['emit']\n    on!: Target['on']\n    off!: Target['off']\n\n    constructor(host: string, options?: Partial<Opts> & Encodings) {\n        super(() => this, undefined, '', undefined)\n        Events(this)\n\n        this.host = host\n        this.conf(options)\n    }\n\n    conf(options: Partial<Opts> = {}): Opts {\n        for (const [k, v] of entries(options)) {\n            if (k === 'encodings') {\n                Object.assign(this._opts.encodings, v)\n                continue\n            }\n\n            if (k in this._opts) {\n                (this._opts as any)[k] = v\n            } else {\n                this._opts.encodings[k] = v\n                console.warn(`There is no option '${k}' in another-rest-client options. Probably this is encoding and should be in 'encodings' option!`)\n            }\n        }\n\n        return {\n            ...this._opts,\n            encodings: {...this._opts.encodings},\n            shortcutRules: [...this._opts.shortcutRules],\n        }\n    }\n\n    _request(method: string, url: string, data: any = null, contentType: string | null = null) {\n        if (url.indexOf('?') === -1)\n            url += this._opts.trailing\n        else\n            url = url.replace('?', this._opts.trailing + '?')\n\n        let xhr = new XMLHttpRequest()\n        xhr.open(method, this.host + url, true)\n\n        if (contentType) {\n            let mime = this._opts.encodings[contentType]\n            if (mime && mime.encode)\n                data = safe(mime.encode, data)\n            if (!(contentType === 'multipart/form-data' && data instanceof FormData))\n                xhr.setRequestHeader('Content-Type', contentType)\n        }\n\n        let p = Events(new Promise((resolve, reject) =>\n            xhr.onreadystatechange = () => {\n                if (xhr.readyState === 4) {\n                    this.emit('response', xhr)\n                    p.emit('response', xhr)\n                    if (xhr.status === 200 || xhr.status === 201 || xhr.status === 204) {\n                        this.emit('success', xhr)\n                        p.emit('success', xhr)\n\n                        let res = xhr.response\n                        let responseHeader = xhr.getResponseHeader('Content-Type')\n                        if (responseHeader) {\n                            let responseContentType = responseHeader.split(';')[0]\n                            let mime = this._opts.encodings[responseContentType]\n                            if (mime && mime.decode)\n                                res = safe(mime.decode, res)\n                        }\n                        p.off()\n                        resolve(res)\n                    } else {\n                        this.emit('error', xhr)\n                        p.emit('error', xhr)\n                        p.off()\n                        reject(xhr)\n                    }\n                }\n            }\n        ))\n        Promise.resolve().then(() => {\n            this.emit('request', xhr)\n            p.emit('request', xhr)\n            xhr.send(data)\n        })\n        return p\n    }\n}\n\nexport default RestClient\n\n"
  },
  {
    "path": "test/test.js",
    "content": "require('chai').should();\nconst sinon = require('sinon');\nconst FormData = require('form-data');\n\nconst {RestClient} = require('../dist/rest-client');\n\nconst host = 'https://example.com';\n\nxhr = global.XMLHttpRequest = sinon.useFakeXMLHttpRequest();\nglobal.FormData = FormData;\n\ndescribe('RestClient', () => {\n    describe('#_request()', () => {\n        let api;\n\n        beforeEach(() => {\n            api = new RestClient(host);\n            api.res('cookies');\n        });\n\n        it('should append trailing symbol which passed to constructor', () => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            new RestClient(host, {trailing: '/'}).res('cookies').get();\n            req.url.should.be.equal(host + '/cookies/');\n        });\n\n        it('should append trailing symbol before args', () => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            new RestClient(host, {trailing: '/'}).res('cookies').get({fresh: true});\n            req.url.should.be.equal(host + '/cookies/?fresh=true');\n        });\n\n        it('should emit events', (done) => {\n            let req, bool;\n            xhr.onCreate = r => req = r;\n\n            const p = api.on('request', xhr => bool = true).cookies.get({fresh: true});\n            req.url.should.be.equal(host + '/cookies?fresh=true');\n\n            setTimeout(() => req.respond(200, [], '{a:1}'), 0);\n\n            p.then(() => {\n                bool.should.be.equal(true)\n                done();\n            }).catch(done);\n        });\n\n        it('should correct handle form data', () => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            const p = api.cookies.post(new FormData(), 'multipart/form-data');\n            req.url.should.be.equal(host + '/cookies');\n            (typeof req.requestHeaders['Content-Type']).should.be.equal('undefined');\n        });\n    });\n});\n\n\ndescribe('resource', () => {\n    describe('#res()', () => {\n        let api;\n\n        beforeEach(() => api = new RestClient(host));\n\n        it('should accept resource name and return resource', () => {\n            const cookies = api.res('cookies');\n            cookies.should.be.a('function');\n        });\n\n        it('should accept array of resource names and return array of resources', () => {\n            const t = api.res(['bees', 'cows']);\n            t.should.be.an('array');\n        });\n\n        it('should accept object of resource names and return object of resources', () => {\n            const t = api.res({\n                'bees': [\n                    'big',\n                    'small'\n                ],\n                'cows': {\n                    'white': 'good'\n                },\n                'dogs': 0\n            });\n            t.should.be.an('object');\n\n            api.bees.should.be.a('function');\n            api.bees.big.should.be.a('function');\n            api.bees.small.should.be.a('function');\n\n            api.cows.should.be.a('function');\n            api.cows.white.should.be.a('function');\n            api.cows.white.good.should.be.a('function');\n\n            api.dogs.should.be.a('function');\n        });\n\n        it('should make a shortcut for resource by default', () => {\n            api.should.not.have.property('cookies');\n            const cookies = api.res('cookies');\n            api.cookies.should.be.equal(cookies);\n        });\n\n        it('should make a shortcut for resource array by default', () => {\n            api.should.not.have.property('cookies');\n            api.should.not.have.property('cows');\n\n            const arr = api.res(['cookies', 'cows']);\n\n            api.cookies.should.be.equal(arr[0]);\n            api.cows.should.be.equal(arr[1]);\n        });\n\n        it('should not make a shortcut if pass option to constructor', () => {\n            const api = new RestClient(host, {shortcut: false});\n            api.should.not.have.property('cookies');\n            const cookies = api.res('cookies');\n            api.should.not.have.property('cookies');\n        });\n\n        it('should not make a shortcut if pass false to second option', () => {\n            api.should.not.have.property('cookies');\n            const cookies = api.res('cookies', false);\n            api.should.not.have.property('cookies');\n        });\n\n        it('should cache created resources', () => {\n            const cookies = api.res('cookies');\n            cookies.should.be.a('function');\n            const cookies2 = api.res('cookies');\n            cookies.should.be.eql(cookies2);\n        });\n\n        it('should add additional shortcuts for custom rules', () => {\n            const r = /(-)(.)/g;\n            const api = new RestClient(host, {\n                shortcutRules: [\n                    resName => resName.replace(r, (match, p1, p2) => p2.toUpperCase()),\n                ]\n            });\n\n            api.should.not.have.property('cookies-and-biscuits');\n            api.should.not.have.property('cookiesAndBiscuits');\n\n            const cookiesAndBiscuits = api.res('cookies-and-biscuits');\n\n            cookiesAndBiscuits.should.be.a('function');\n            api['cookies-and-biscuits'].should.be.equal(cookiesAndBiscuits);\n            api.cookiesAndBiscuits.should.be.equal(cookiesAndBiscuits);\n        });\n    });\n\n    describe('#url()', () => {\n        let api;\n\n        beforeEach(() => {\n            api = new RestClient(host);\n            api.res('cookies');\n        });\n\n        it('should build correct resource url', () => {\n            api.cookies.url().should.be.equal('/cookies');\n        });\n\n        it('should build correct resource instance url', () => {\n            api.cookies(42).url().should.be.equal('/cookies/42');\n        });\n\n        it('should build correct resource url if two in stack', () => {\n            api.cookies.res('bakers');\n            api.cookies(42).bakers(24).url().should.be.equal('/cookies/42/bakers/24');\n        });\n\n        it('should build correct resource url if more than two in stack', () => {\n            api.cookies.res('bakers').res('cats');\n            api.cookies(42).bakers.cats.url().should.be.equal('/cookies/42/bakers/cats');\n            api.cookies(42).bakers(24).cats(15).url().should.be.equal('/cookies/42/bakers/24/cats/15');\n        });\n    });\n\n    describe('#get()', () => {\n        let api;\n\n        beforeEach(() => {\n            api = new RestClient(host);\n            api.res('cookies');\n        });\n\n        it('should correct form query args when get one instance', () => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            api.cookies(4).get();\n            req.url.should.be.equal(host + '/cookies/4');\n        });\n\n        it('should correct form query args when get multiply instances', () => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            api.cookies.get({fresh: true});\n            req.url.should.be.equal(host + '/cookies?fresh=true');\n        });\n\n        it('should correct form query args when get multiply args', () => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            api.cookies.get({'filter[]': 'fresh'}, {'filter[]': 'taste'});\n            req.url.should.be.equal(host + '/cookies?filter%5B%5D=fresh&filter%5B%5D=taste');\n        });\n\n        it('should work correctly with an undefined content type', (done) => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            const p = api.cookies.get({fresh: true});\n\n            req.respond(200, [], '{a:1}');\n\n            req.url.should.be.equal(host + '/cookies?fresh=true');\n            p.then(r => {\n                r.should.be.equal('{a:1}');\n                done();\n            }).catch(done);\n        });\n\n        it('should correctly parse response', (done) => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            const p = api.cookies.get({fresh: true});\n\n            req.respond(200, {'Content-Type': 'application/json'}, '{\"a\":\"1df\"}');\n\n            req.url.should.be.equal(host + '/cookies?fresh=true');\n            p.then(r => {\n                r.should.be.deep.equal({\"a\": \"1df\"});\n                done();\n            }).catch(done);\n        });\n\n        it('should correctly handle exception with wrong encoded response body', (done) => {\n            let req;\n            xhr.onCreate = r => req = r;\n            sinon.spy(console, 'error');\n            sinon.spy(console, 'log');\n\n            const p = api.cookies.get({fresh: true});\n\n            req.respond(200, {'Content-Type': 'application/json'}, '{\"a\":1df}');\n\n            req.url.should.be.equal(host + '/cookies?fresh=true');\n            p.then(r => {\n                r.should.be.equal('{\"a\":1df}');\n                console.error.callCount.should.equal(1);\n                console.log.callCount.should.equal(3);\n\n                console.error.restore();\n                console.log.restore();\n                done();\n            }).catch(done);\n        });\n\n        it('should emit once event', (done) => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            let respText;\n\n            const p = api.cookies.get({fresh: true}).on('success', xhr => respText = xhr.responseText);\n\n            setTimeout(() => req.respond(200, [], '{a:1}'), 0);\n\n            req.url.should.be.equal(host + '/cookies?fresh=true');\n            p.then(r => {\n                r.should.be.equal('{a:1}');\n                respText.should.be.equal('{a:1}');\n                done();\n            }).catch(done);\n        });\n\n        it('should emit once request event', (done) => {\n            let req;\n            xhr.onCreate = r => req = r;\n\n            let bool;\n\n            const p = api.cookies.get({fresh: true}).on('request', xhr => bool = true);\n\n            setTimeout(() => req.respond(200, [], '{a:1}'), 0);\n\n            req.url.should.be.equal(host + '/cookies?fresh=true');\n            p.then(r => {\n                bool.should.be.equal(true);\n                done();\n            }).catch(done);\n        });\n    });\n});\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2015\",\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"lib\": [\n      \"ES2021\",\n      \"DOM\"\n    ],\n    \"emitDeclarationOnly\": true,\n    \"declaration\": true,\n    \"outDir\": \"dist\"\n  },\n  \"include\": [\"./src/*\"]\n}"
  }
]