@looker/sdk-rtl 21.0.20 → 21.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/lib/CSRFSession.d.ts +2 -2
- package/lib/CSRFSession.js.map +1 -1
- package/lib/apiMethods.d.ts +3 -3
- package/lib/apiMethods.js.map +1 -1
- package/lib/apiSettings.d.ts +1 -1
- package/lib/apiSettings.js.map +1 -1
- package/lib/authSession.d.ts +3 -3
- package/lib/authSession.js.map +1 -1
- package/lib/authToken.d.ts +1 -1
- package/lib/authToken.js.map +1 -1
- package/lib/baseTransport.d.ts +1 -1
- package/lib/baseTransport.js.map +1 -1
- package/lib/browserServices.d.ts +4 -4
- package/lib/browserServices.js.map +1 -1
- package/lib/browserSession.d.ts +2 -2
- package/lib/browserSession.js.map +1 -1
- package/lib/browserTransport.d.ts +4 -4
- package/lib/browserTransport.js +3 -7
- package/lib/browserTransport.js.map +1 -1
- package/lib/esm/CSRFSession.js.map +1 -1
- package/lib/esm/apiMethods.js.map +1 -1
- package/lib/esm/apiSettings.js.map +1 -1
- package/lib/esm/authSession.js.map +1 -1
- package/lib/esm/authToken.js.map +1 -1
- package/lib/esm/baseTransport.js.map +1 -1
- package/lib/esm/browserServices.js.map +1 -1
- package/lib/esm/browserSession.js.map +1 -1
- package/lib/esm/browserTransport.js +3 -6
- package/lib/esm/browserTransport.js.map +1 -1
- package/lib/esm/extensionSession.js.map +1 -1
- package/lib/esm/extensionTransport.js.map +1 -1
- package/lib/esm/oauthSession.js +2 -1
- package/lib/esm/oauthSession.js.map +1 -1
- package/lib/esm/paging.js.map +1 -1
- package/lib/esm/proxySession.js.map +1 -1
- package/lib/esm/transport.js +15 -13
- package/lib/esm/transport.js.map +1 -1
- package/lib/extensionSession.d.ts +3 -3
- package/lib/extensionSession.js.map +1 -1
- package/lib/extensionTransport.d.ts +2 -2
- package/lib/extensionTransport.js.map +1 -1
- package/lib/oauthSession.d.ts +3 -3
- package/lib/oauthSession.js +2 -1
- package/lib/oauthSession.js.map +1 -1
- package/lib/paging.d.ts +2 -2
- package/lib/paging.js.map +1 -1
- package/lib/platformServices.d.ts +3 -3
- package/lib/proxySession.d.ts +2 -2
- package/lib/proxySession.js.map +1 -1
- package/lib/transport.d.ts +3 -3
- package/lib/transport.js +14 -13
- package/lib/transport.js.map +1 -1
- package/package.json +2 -2
package/lib/paging.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/paging.ts"],"names":["LinkHeader","TotalCountHeader","linkHeaderParser","linkHeader","re","links","split","obj","arrRes","forEach","link","trim","exec","key","toLocaleLowerCase","url","rel","name","pager","sdk","pageFunc","options","Paging","init","pageAll","onPage","page","paged","items","more","ok","nextPage","err","Promise","reject","constructor","func","transport","authSession","rawCatch","raw","saved","observer","response","Object","keys","length","headers","Error","parse","limit","offset","x","Math","ceil","pages","total","hasRel","paramDefault","value","defaultValue","convert","v","parseInt","reset","getRel","result","authenticator","authenticate","undefined","error","URL","params","searchParams","set","toString","rawRequest","parseResponse","e","findHeader","toLowerCase","toUpperCase","get","totalHeader","firstPage","lastPage","prevPage"],"mappings":";;;;;;;;;AA0BA;;;;;;;;AASO,IAAMA,UAAU,GAAG,MAAnB;;AACA,IAAMC,gBAAgB,GAAG,eAAzB;;;AA+GA,IAAMC,gBAAgB,GAAIC,UAAD,IAAmC;AACjE,MAAMC,EAAE,GAAG,uCAAX;AACA,MAAMC,KAAK,GAAGF,UAAU,CAACG,KAAX,CAAiB,GAAjB,CAAd;AACA,MAAMC,GAAc,GAAG,EAAvB;AACA,MAAIC,MAAJ;AAEAH,EAAAA,KAAK,CAACI,OAAN,CAAeC,IAAD,IAAU;AACtBA,IAAAA,IAAI,GAAGA,IAAI,CAACC,IAAL,EAAP;;AACA,WAAQH,MAAM,GAAGJ,EAAE,CAACQ,IAAH,CAAQF,IAAR,CAAjB,EAAiC;AAC/B,UAAMG,GAAG,GAAGL,MAAM,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ACD,KAFD,MAEO;AACL,WAAKE,KAAL,GAAa,EAAb;AACD;;AACD,QAAM8E,WAAW,GAAG7D,MAAM,CAACyD,UAAP,CAAkBvC,GAAlB,EAAuBvC,gBAAvB,CAApB;;AACA,QAAIkF,WAAJ,EAAiB;AACf,WAAK3B,KAAL,GAAaO,QAAQ,CAACoB,WAAW,CAACxE,IAAZ,EAAD,EAAqB,EAArB,CAArB;AACD,KAFD,MAEO;AACL,WAAK6C,KAAL,GAAa,CAAC,CAAd;AACD;;AACD,WAAO,IAAP;AACD;;AAEK4B,EAAAA,SAAS,GAA2C;AAAA;;AAAA;AACxD,mBAAa,MAAI,CAACnB,MAAL,CAAY,OAAZ,CAAb;AADwD;AAEzD;;AAEKoB,EAAAA,QAAQ,GAA2C;AAAA;;AAAA;AACvD,mBAAa,MAAI,CAACpB,MAAL,CAAY,MAAZ,CAAb;AADuD;AAExD;;AAEKlC,EAAAA,QAAQ,GAA2C;AAAA;;AAAA;AACvD,mBAAa,MAAI,CAACkC,MAAL,CAAY,MAAZ,CAAb;AADuD;AAExD;;AAEKqB,EAAAA,QAAQ,GAA2C;AAAA;;AAAA;AACvD,mBAAa,MAAI,CAACrB,MAAL,CAAY,MAAZ,CAAb;AADuD;AAExD;;AA/LH","sourcesContent":["/*\n\n MIT License\n\n Copyright (c) 2021 Looker Data Sciences, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n */\n\nimport {\n IRawResponse,\n ITransportSettings,\n sdkOk,\n SDKResponse,\n} from './transport'\nimport { IAPIMethods } from './apiMethods'\nimport { BaseTransport } from './baseTransport'\n\nexport const LinkHeader = 'Link'\nexport const TotalCountHeader = 'X-Total-Count'\n\n/**\n * Types of paging link relative URLs\n * based on https://docs.github.com/en/rest/overview/resources-in-the-rest-api#link-header\n */\nexport type PageLinkRel = 'first' | 'last' | 'next' | 'prev'\n\n/** Constraints for TSuccess type */\ninterface ILength {\n length: number\n}\n\n/** Result paging function call */\nexport type PagingFunc<TSuccess, TError> = () => Promise<\n SDKResponse<TSuccess, TError>\n>\n\n/** Page link structure */\nexport interface IPageLink {\n /** Name of link */\n name?: string\n /** Type of link */\n rel: PageLinkRel\n /** Media type for link */\n mediaType?: string\n /** URL for retrieving the link results */\n url: string\n}\n\n/**\n * Collection of page links\n *\n * TODO can this be Record<PageLinkRel, IPageLink> instead and still init to {}?\n */\nexport type PageLinks = Record<string, IPageLink>\n\nexport interface IPager<TSuccess, TError> {\n /** Total number of available items being paginated */\n total: number\n /** Offset extracted from pager request */\n offset: number\n /** Limit extracted from pager request */\n limit: number\n /** Paging links extracted from Link header */\n links: PageLinks\n /** Latest items returned from response */\n items: TSuccess\n /** Captured from the original paging request */\n options?: Partial<ITransportSettings>\n /** Total number of pages. -1 if not known. */\n pages: number\n /** Current page. -1 if not known. */\n page: number\n\n /**\n * Is the specified link rel defined in the Link header?\n * @param link to check\n */\n hasRel(link: PageLinkRel): boolean\n\n /**\n * GET the requested relative link\n *\n * if the requested link is not defined, all calculated values are reset to their defaults, including\n * `total`, `items`, `offset`, and `limit`\n *\n * @param name of Link Relationship\n * @param limit optional limit override to replace limit saved in `rel`\n * @param offset optional offset override to replace offset saved in `rel`\n */\n getRel(\n name: PageLinkRel,\n limit?: number,\n offset?: number\n ): Promise<SDKResponse<TSuccess, TError>>\n\n /** Get the first page of items. This is the same as offset=0 */\n firstPage(): Promise<SDKResponse<TSuccess, TError>>\n /**\n * Get the last page of items\n *\n * @remarks This link is only provided if `total` is known.\n */\n lastPage(): Promise<SDKResponse<TSuccess, TError>>\n /**\n * Get the next page of items\n *\n * @remarks This link is provided if `total` is known, or if the number of items returned == `limit`. In the latter case, this function may return an empty result set.\n */\n nextPage(): Promise<SDKResponse<TSuccess, TError>>\n /**\n * Get the previous page of items\n *\n * @remarks This link is provided if the last page was not the first page.\n */\n prevPage(): Promise<SDKResponse<TSuccess, TError>>\n\n /** `true` if the `next` link is defined */\n more(): boolean\n}\n\n/**\n * Parse a link header to extract rels\n * @param linkHeader to parse\n *\n * Several different approaches are discussed at https://stackoverflow.com/questions/8735792/how-to-parse-link-header-from-github-api\n *\n * Unfortunately, none of them are a good implementation\n *\n */\nexport const linkHeaderParser = (linkHeader: string): PageLinks => {\n const re = /<\\s*(.*)\\s*>;\\s*rel=\"\\s*(.*)\\s*\"\\s*/gm\n const links = linkHeader.split(',')\n const obj: PageLinks = {}\n let arrRes\n\n links.forEach((link) => {\n link = link.trim()\n while ((arrRes = re.exec(link))) {\n const key = arrRes[2].split(' ')[0].trim().toLocaleLowerCase()\n obj[key] = {\n url: arrRes[1].trim(),\n rel: key as PageLinkRel,\n name: arrRes[2].trim(),\n }\n }\n })\n return obj\n}\n\n/** Event to observe the paging call */\nexport type PageObserver<TSuccess> = (\n /** Current retrieved page of results */\n page: TSuccess\n) => TSuccess\n\n/**\n * Create an API response pager for an endpoint that returns a Link header\n * @param sdk implementation of IAPIMethods. Can be a full SDK or functional auth session. The active transport object is captured from this parameter, which is why it must be passed separately from the paging function.\n * @param pageFunc sdk call that includes a paging header\n * @param options transport options override to capture and use in paging requests\n *\n * @remarks `TSuccess` must be a collection type that supports `length`\n */\nexport async function pager<TSuccess extends ILength, TError>(\n sdk: IAPIMethods,\n pageFunc: PagingFunc<TSuccess, TError>,\n options?: Partial<ITransportSettings>\n): Promise<IPager<TSuccess, TError>> {\n return await new Paging<TSuccess, TError>(sdk, pageFunc, options).init()\n}\n\n/**\n * Create an API response pager and iterate through all pages, calling a page event per page\n * @param sdk implementation of IAPIMethods. Can be a full SDK or functional auth session. The active transport object is captured from this parameter, which is why it must be passed separately from the paging function.\n * @param pageFunc sdk call that includes a paging header\n * @param onPage observer of the latest page of results. Defaults to noop.\n * @param options transport options override to capture and use in paging requests\n *\n * @remarks `TSuccess` must be a collection type that supports `length`\n */\nexport async function pageAll<TSuccess extends ILength, TError>(\n sdk: IAPIMethods,\n pageFunc: PagingFunc<TSuccess, TError>,\n onPage: PageObserver<TSuccess> = (page: TSuccess) => page,\n options?: Partial<ITransportSettings>\n): Promise<IPager<TSuccess, TError>> {\n const paged = await pager(sdk, pageFunc, options)\n // Process the first page\n onPage(paged.items)\n try {\n while (paged.more()) {\n // Pass the page items to the event\n onPage(await sdk.ok(paged.nextPage()))\n }\n } catch (err) {\n return Promise.reject(err)\n }\n return paged\n}\n\n/**\n * Link header pages class\n */\nexport class Paging<TSuccess extends ILength, TError>\n implements IPager<TSuccess, TError>\n{\n items: TSuccess = [] as unknown as TSuccess\n links: PageLinks = {}\n total = -1\n offset = -1\n limit = -1\n\n private transport: BaseTransport\n\n /**\n * Create an API paginator\n * @param sdk functional AuthSession or full SDK implementation\n * @param func sdk function to call\n * @param options transport overrides to use for subsequent requests\n */\n constructor(\n public sdk: IAPIMethods,\n public func: PagingFunc<TSuccess, TError>,\n public options?: Partial<ITransportSettings>\n ) {\n this.transport = sdk.authSession.transport as BaseTransport\n }\n\n private async rawCatch(func: () => any) {\n let raw: IRawResponse = {} as IRawResponse\n const saved = this.transport.observer\n try {\n // Capture the raw request for header parsing\n this.transport.observer = (response: IRawResponse) => {\n if (saved) {\n // Chain the observer\n response = saved(response)\n }\n raw = response\n return response\n }\n this.items = await sdkOk(func())\n } finally {\n // Restore the previous observer (if any)\n this.transport.observer = saved\n }\n if (Object.keys(raw).length === 0 || Object.keys(raw.headers).length === 0)\n return Promise.reject(new Error('No paging headers were found'))\n this.parse(raw)\n return this\n }\n\n get page(): number {\n if (this.limit < 1 || this.offset < 0) return -1\n const x = this.offset / this.limit + 1\n return Math.ceil(x)\n }\n\n get pages(): number {\n if (this.total < 1 || this.limit < 1) return -1\n const x = this.total / this.limit\n return Math.ceil(x)\n }\n\n async init() {\n return await this.rawCatch(this.func)\n }\n\n hasRel(link: PageLinkRel): boolean {\n return !!this.links[link]\n }\n\n more() {\n return this.hasRel('next')\n }\n\n /**\n * Default string value\n * @param value to retrieve or default\n * @param defaultValue to apply if string is null\n * @param convert function to convert assigned string value\n * @private\n */\n private static paramDefault(\n value: string | null,\n defaultValue: any,\n convert = (v: string) => parseInt(v, 10)\n ) {\n if (value === null) return defaultValue\n return convert(value)\n }\n\n reset() {\n this.links = {}\n this.total = this.offset = this.limit = -1\n this.items = [] as unknown as TSuccess\n }\n\n async getRel(\n name: PageLinkRel,\n limit?: number,\n offset?: number\n ): Promise<SDKResponse<TSuccess, TError>> {\n const rel = this.links[name]\n let result: SDKResponse<TSuccess, TError>\n this.reset()\n if (!rel) {\n result = { ok: true, value: this.items }\n return result\n }\n const authenticator = (init: any) => {\n return this.sdk.authSession.authenticate(init)\n }\n\n let link = rel.url\n if (limit !== undefined) {\n if (offset === undefined) {\n offset = 0\n }\n if (limit < 1 || offset < 0) {\n result = {\n ok: false,\n error: new Error(\n 'limit must be > 0 and offset must be >= 0'\n ) as unknown as TError,\n }\n return result\n }\n const url = new URL(link)\n const params = url.searchParams\n params.set('limit', limit.toString())\n params.set('offset', offset.toString())\n link = url.toString()\n }\n const raw = await this.transport.rawRequest(\n 'GET',\n link,\n undefined,\n undefined,\n authenticator,\n this.options\n )\n try {\n this.parse(raw)\n this.items = await sdkOk(this.transport.parseResponse(raw))\n result = { ok: true, value: this.items }\n } catch (e) {\n result = { ok: false, error: e }\n }\n return result\n }\n\n static findHeader(raw: IRawResponse, name: string) {\n return (\n raw.headers[name] ||\n raw.headers[name.toLowerCase()] ||\n raw.headers[name.toUpperCase()]\n )\n }\n\n parse(raw: IRawResponse): IPager<TSuccess, TError> {\n const params = new URL(raw.url, 'http://default').searchParams\n this.limit = Paging.paramDefault(params.get('limit'), -1)\n this.offset = Paging.paramDefault(\n params.get('offset'),\n this.limit > 0 ? 0 : -1\n )\n const linkHeader = Paging.findHeader(raw, LinkHeader)\n if (linkHeader) {\n this.links = linkHeaderParser(linkHeader)\n } else {\n this.links = {}\n }\n const totalHeader = Paging.findHeader(raw, TotalCountHeader)\n if (totalHeader) {\n this.total = parseInt(totalHeader.trim(), 10)\n } else {\n this.total = -1\n }\n return this as unknown as IPager<TSuccess, TError>\n }\n\n async firstPage(): Promise<SDKResponse<TSuccess, TError>> {\n return await this.getRel('first')\n }\n\n async lastPage(): Promise<SDKResponse<TSuccess, TError>> {\n return await this.getRel('last')\n }\n\n async nextPage(): Promise<SDKResponse<TSuccess, TError>> {\n return await this.getRel('next')\n }\n\n async prevPage(): Promise<SDKResponse<TSuccess, TError>> {\n return await this.getRel('prev')\n }\n}\n"],"file":"paging.js"}
|
|
1
|
+
{"version":3,"sources":["../src/paging.ts"],"names":["LinkHeader","TotalCountHeader","linkHeaderParser","linkHeader","re","links","split","obj","arrRes","forEach","link","trim","exec","key","toLocaleLowerCase","url","rel","name","pager","sdk","pageFunc","options","Paging","init","pageAll","onPage","page","paged","items","more","ok","nextPage","err","Promise","reject","constructor","func","transport","authSession","rawCatch","raw","saved","observer","response","Object","keys","length","headers","Error","parse","limit","offset","x","Math","ceil","pages","total","hasRel","paramDefault","value","defaultValue","convert","v","parseInt","reset","getRel","result","authenticator","authenticate","undefined","error","URL","params","searchParams","set","toString","rawRequest","parseResponse","e","findHeader","toLowerCase","toUpperCase","get","totalHeader","firstPage","l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Aa,MAAI,CAACrB,MAAL,CAAY,MAAZ,CAAb;AADuD;AAExD;;AA/LH","sourcesContent":["/*\n\n MIT License\n\n Copyright (c) 2021 Looker Data Sciences, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n */\n\nimport type { IRawResponse, ITransportSettings, SDKResponse } from './transport'\nimport { sdkOk } from './transport'\nimport type { IAPIMethods } from './apiMethods'\nimport type { BaseTransport } from './baseTransport'\n\nexport const LinkHeader = 'Link'\nexport const TotalCountHeader = 'X-Total-Count'\n\n/**\n * Types of paging link relative URLs\n * based on https://docs.github.com/en/rest/overview/resources-in-the-rest-api#link-header\n */\nexport type PageLinkRel = 'first' | 'last' | 'next' | 'prev'\n\n/** Constraints for TSuccess type */\ninterface ILength {\n length: number\n}\n\n/** Result paging function call */\nexport type PagingFunc<TSuccess, TError> = () => Promise<\n SDKResponse<TSuccess, TError>\n>\n\n/** Page link structure */\nexport interface IPageLink {\n /** Name of link */\n name?: string\n /** Type of link */\n rel: PageLinkRel\n /** Media type for link */\n mediaType?: string\n /** URL for retrieving the link results */\n url: string\n}\n\n/**\n * Collection of page links\n *\n * TODO can this be Record<PageLinkRel, IPageLink> instead and still init to {}?\n */\nexport type PageLinks = Record<string, IPageLink>\n\nexport interface IPager<TSuccess, TError> {\n /** Total number of available items being paginated */\n total: number\n /** Offset extracted from pager request */\n offset: number\n /** Limit extracted from pager request */\n limit: number\n /** Paging links extracted from Link header */\n links: PageLinks\n /** Latest items returned from response */\n items: TSuccess\n /** Captured from the original paging request */\n options?: Partial<ITransportSettings>\n /** Total number of pages. -1 if not known. */\n pages: number\n /** Current page. -1 if not known. */\n page: number\n\n /**\n * Is the specified link rel defined in the Link header?\n * @param link to check\n */\n hasRel(link: PageLinkRel): boolean\n\n /**\n * GET the requested relative link\n *\n * if the requested link is not defined, all calculated values are reset to their defaults, including\n * `total`, `items`, `offset`, and `limit`\n *\n * @param name of Link Relationship\n * @param limit optional limit override to replace limit saved in `rel`\n * @param offset optional offset override to replace offset saved in `rel`\n */\n getRel(\n name: PageLinkRel,\n limit?: number,\n offset?: number\n ): Promise<SDKResponse<TSuccess, TError>>\n\n /** Get the first page of items. This is the same as offset=0 */\n firstPage(): Promise<SDKResponse<TSuccess, TError>>\n /**\n * Get the last page of items\n *\n * @remarks This link is only provided if `total` is known.\n */\n lastPage(): Promise<SDKResponse<TSuccess, TError>>\n /**\n * Get the next page of items\n *\n * @remarks This link is provided if `total` is known, or if the number of items returned == `limit`. In the latter case, this function may return an empty result set.\n */\n nextPage(): Promise<SDKResponse<TSuccess, TError>>\n /**\n * Get the previous page of items\n *\n * @remarks This link is provided if the last page was not the first page.\n */\n prevPage(): Promise<SDKResponse<TSuccess, TError>>\n\n /** `true` if the `next` link is defined */\n more(): boolean\n}\n\n/**\n * Parse a link header to extract rels\n * @param linkHeader to parse\n *\n * Several different approaches are discussed at https://stackoverflow.com/questions/8735792/how-to-parse-link-header-from-github-api\n *\n * Unfortunately, none of them are a good implementation\n *\n */\nexport const linkHeaderParser = (linkHeader: string): PageLinks => {\n const re = /<\\s*(.*)\\s*>;\\s*rel=\"\\s*(.*)\\s*\"\\s*/gm\n const links = linkHeader.split(',')\n const obj: PageLinks = {}\n let arrRes\n\n links.forEach((link) => {\n link = link.trim()\n while ((arrRes = re.exec(link))) {\n const key = arrRes[2].split(' ')[0].trim().toLocaleLowerCase()\n obj[key] = {\n url: arrRes[1].trim(),\n rel: key as PageLinkRel,\n name: arrRes[2].trim(),\n }\n }\n })\n return obj\n}\n\n/** Event to observe the paging call */\nexport type PageObserver<TSuccess> = (\n /** Current retrieved page of results */\n page: TSuccess\n) => TSuccess\n\n/**\n * Create an API response pager for an endpoint that returns a Link header\n * @param sdk implementation of IAPIMethods. Can be a full SDK or functional auth session. The active transport object is captured from this parameter, which is why it must be passed separately from the paging function.\n * @param pageFunc sdk call that includes a paging header\n * @param options transport options override to capture and use in paging requests\n *\n * @remarks `TSuccess` must be a collection type that supports `length`\n */\nexport async function pager<TSuccess extends ILength, TError>(\n sdk: IAPIMethods,\n pageFunc: PagingFunc<TSuccess, TError>,\n options?: Partial<ITransportSettings>\n): Promise<IPager<TSuccess, TError>> {\n return await new Paging<TSuccess, TError>(sdk, pageFunc, options).init()\n}\n\n/**\n * Create an API response pager and iterate through all pages, calling a page event per page\n * @param sdk implementation of IAPIMethods. Can be a full SDK or functional auth session. The active transport object is captured from this parameter, which is why it must be passed separately from the paging function.\n * @param pageFunc sdk call that includes a paging header\n * @param onPage observer of the latest page of results. Defaults to noop.\n * @param options transport options override to capture and use in paging requests\n *\n * @remarks `TSuccess` must be a collection type that supports `length`\n */\nexport async function pageAll<TSuccess extends ILength, TError>(\n sdk: IAPIMethods,\n pageFunc: PagingFunc<TSuccess, TError>,\n onPage: PageObserver<TSuccess> = (page: TSuccess) => page,\n options?: Partial<ITransportSettings>\n): Promise<IPager<TSuccess, TError>> {\n const paged = await pager(sdk, pageFunc, options)\n // Process the first page\n onPage(paged.items)\n try {\n while (paged.more()) {\n // Pass the page items to the event\n onPage(await sdk.ok(paged.nextPage()))\n }\n } catch (err) {\n return Promise.reject(err)\n }\n return paged\n}\n\n/**\n * Link header pages class\n */\nexport class Paging<TSuccess extends ILength, TError>\n implements IPager<TSuccess, TError>\n{\n items: TSuccess = [] as unknown as TSuccess\n links: PageLinks = {}\n total = -1\n offset = -1\n limit = -1\n\n private transport: BaseTransport\n\n /**\n * Create an API paginator\n * @param sdk functional AuthSession or full SDK implementation\n * @param func sdk function to call\n * @param options transport overrides to use for subsequent requests\n */\n constructor(\n public sdk: IAPIMethods,\n public func: PagingFunc<TSuccess, TError>,\n public options?: Partial<ITransportSettings>\n ) {\n this.transport = sdk.authSession.transport as BaseTransport\n }\n\n private async rawCatch(func: () => any) {\n let raw: IRawResponse = {} as IRawResponse\n const saved = this.transport.observer\n try {\n // Capture the raw request for header parsing\n this.transport.observer = (response: IRawResponse) => {\n if (saved) {\n // Chain the observer\n response = saved(response)\n }\n raw = response\n return response\n }\n this.items = await sdkOk(func())\n } finally {\n // Restore the previous observer (if any)\n this.transport.observer = saved\n }\n if (Object.keys(raw).length === 0 || Object.keys(raw.headers).length === 0)\n return Promise.reject(new Error('No paging headers were found'))\n this.parse(raw)\n return this\n }\n\n get page(): number {\n if (this.limit < 1 || this.offset < 0) return -1\n const x = this.offset / this.limit + 1\n return Math.ceil(x)\n }\n\n get pages(): number {\n if (this.total < 1 || this.limit < 1) return -1\n const x = this.total / this.limit\n return Math.ceil(x)\n }\n\n async init() {\n return await this.rawCatch(this.func)\n }\n\n hasRel(link: PageLinkRel): boolean {\n return !!this.links[link]\n }\n\n more() {\n return this.hasRel('next')\n }\n\n /**\n * Default string value\n * @param value to retrieve or default\n * @param defaultValue to apply if string is null\n * @param convert function to convert assigned string value\n * @private\n */\n private static paramDefault(\n value: string | null,\n defaultValue: any,\n convert = (v: string) => parseInt(v, 10)\n ) {\n if (value === null) return defaultValue\n return convert(value)\n }\n\n reset() {\n this.links = {}\n this.total = this.offset = this.limit = -1\n this.items = [] as unknown as TSuccess\n }\n\n async getRel(\n name: PageLinkRel,\n limit?: number,\n offset?: number\n ): Promise<SDKResponse<TSuccess, TError>> {\n const rel = this.links[name]\n let result: SDKResponse<TSuccess, TError>\n this.reset()\n if (!rel) {\n result = { ok: true, value: this.items }\n return result\n }\n const authenticator = (init: any) => {\n return this.sdk.authSession.authenticate(init)\n }\n\n let link = rel.url\n if (limit !== undefined) {\n if (offset === undefined) {\n offset = 0\n }\n if (limit < 1 || offset < 0) {\n result = {\n ok: false,\n error: new Error(\n 'limit must be > 0 and offset must be >= 0'\n ) as unknown as TError,\n }\n return result\n }\n const url = new URL(link)\n const params = url.searchParams\n params.set('limit', limit.toString())\n params.set('offset', offset.toString())\n link = url.toString()\n }\n const raw = await this.transport.rawRequest(\n 'GET',\n link,\n undefined,\n undefined,\n authenticator,\n this.options\n )\n try {\n this.parse(raw)\n this.items = await sdkOk(this.transport.parseResponse(raw))\n result = { ok: true, value: this.items }\n } catch (e: any) {\n result = { ok: false, error: e }\n }\n return result\n }\n\n static findHeader(raw: IRawResponse, name: string) {\n return (\n raw.headers[name] ||\n raw.headers[name.toLowerCase()] ||\n raw.headers[name.toUpperCase()]\n )\n }\n\n parse(raw: IRawResponse): IPager<TSuccess, TError> {\n const params = new URL(raw.url, 'http://default').searchParams\n this.limit = Paging.paramDefault(params.get('limit'), -1)\n this.offset = Paging.paramDefault(\n params.get('offset'),\n this.limit > 0 ? 0 : -1\n )\n const linkHeader = Paging.findHeader(raw, LinkHeader)\n if (linkHeader) {\n this.links = linkHeaderParser(linkHeader)\n } else {\n this.links = {}\n }\n const totalHeader = Paging.findHeader(raw, TotalCountHeader)\n if (totalHeader) {\n this.total = parseInt(totalHeader.trim(), 10)\n } else {\n this.total = -1\n }\n return this as unknown as IPager<TSuccess, TError>\n }\n\n async firstPage(): Promise<SDKResponse<TSuccess, TError>> {\n return await this.getRel('first')\n }\n\n async lastPage(): Promise<SDKResponse<TSuccess, TError>> {\n return await this.getRel('last')\n }\n\n async nextPage(): Promise<SDKResponse<TSuccess, TError>> {\n return await this.getRel('next')\n }\n\n async prevPage(): Promise<SDKResponse<TSuccess, TError>> {\n return await this.getRel('prev')\n }\n}\n"],"file":"paging.js"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { IApiSettings } from './apiSettings';
|
|
2
|
-
import { ITransport } from './transport';
|
|
3
|
-
import { ICryptoHash } from './cryptoHash';
|
|
1
|
+
import type { IApiSettings } from './apiSettings';
|
|
2
|
+
import type { ITransport } from './transport';
|
|
3
|
+
import type { ICryptoHash } from './cryptoHash';
|
|
4
4
|
export interface IPlatformServices {
|
|
5
5
|
settings: IApiSettings;
|
|
6
6
|
transport: ITransport;
|
package/lib/proxySession.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AuthSession } from './authSession';
|
|
2
|
-
import { ITransport, IRequestProps } from './transport';
|
|
3
|
-
import { IApiSettings } from './apiSettings';
|
|
2
|
+
import type { ITransport, IRequestProps } from './transport';
|
|
3
|
+
import type { IApiSettings } from './apiSettings';
|
|
4
4
|
export declare abstract class ProxySession extends AuthSession {
|
|
5
5
|
settings: IApiSettings;
|
|
6
6
|
proxyUrl: string;
|
package/lib/proxySession.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/proxySession.ts"],"names":["ProxySession","AuthSession","constructor","settings","proxyUrl","transport","BrowserTransport","isAuthenticated","authenticate","props","headers","url","LookerAppId","agentPrefix"],"mappings":";;;;;;;AA0BA;;AACA;;
|
|
1
|
+
{"version":3,"sources":["../src/proxySession.ts"],"names":["ProxySession","AuthSession","constructor","settings","proxyUrl","transport","BrowserTransport","isAuthenticated","authenticate","props","headers","url","LookerAppId","agentPrefix"],"mappings":";;;;;;;AA0BA;;AACA;;AAEA;;;;;;AAWO,MAAeA,YAAf,SAAoCC,wBAApC,CAAgD;AACrDC,EAAAA,WAAW,CACFC,QADE,EAEFC,QAFE,EAGTC,SAHS,EAIT;AACA,UAAMF,QAAN,EAAgBE,SAAS,IAAI,IAAIC,kCAAJ,CAAqBH,QAArB,CAA7B;AADA,SAHOA,QAGP,GAHOA,QAGP;AAAA,SAFOC,QAEP,GAFOA,QAEP;AAED;;AAODG,EAAAA,eAAe,GAAG;AAChB,WAAO,IAAP;AACD;;AAWKC,EAAAA,YAAY,CAACC,KAAD,EAAuB;AAAA;;AAAA;AACvC,UAAI,CAACA,KAAK,CAACC,OAAX,EAAoB;AAClBD,QAAAA,KAAK,CAACC,OAAN,GAAgB,EAAhB;AACD;;AACDD,MAAAA,KAAK,CAACC,OAAN,CAAc,iBAAd,IAAmCD,KAAK,CAACE,GAAzC;AACAF,MAAAA,KAAK,CAACC,OAAN,CAAcE,sBAAd,IAA6BC,sBAA7B;AACAJ,MAAAA,KAAK,CAACE,GAAN,GAAY,KAAI,CAACP,QAAjB;AACA,aAAOK,KAAP;AAPuC;AAQxC;;AAnCoD","sourcesContent":["/*\n\n MIT License\n\n Copyright (c) 2021 Looker Data Sciences, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n */\n\nimport { AuthSession } from './authSession'\nimport { BrowserTransport } from './browserTransport'\nimport type { ITransport, IRequestProps } from './transport'\nimport { LookerAppId, agentPrefix } from './transport'\nimport type { IApiSettings } from './apiSettings'\n\n/**\n * An AuthSession class intended for use with proxied requests\n *\n * This session uses `authenticate` to modify all requests to pass through a proxy server with\n * passing the request to the proxy server specified in the `proxyUrl` parameter, and sets\n * the original request path as an `X-Forwarded-For` header.\n *\n */\nexport abstract class ProxySession extends AuthSession {\n constructor(\n public settings: IApiSettings,\n public proxyUrl: string,\n transport?: ITransport\n ) {\n super(settings, transport || new BrowserTransport(settings))\n }\n\n /**\n * Proxy session is considered to be always authenticated since the proxy handles all auth\n *\n * @returns `true` since the proxy handles all authentication\n */\n isAuthenticated() {\n return true\n }\n\n /**\n * This implementation swaps the request's path with the proxy url, and puts the original\n * request path in the `X-Forwarded-For` header, presuming that the proxy server will add API authentication\n * information to the request that gets submitted to the Looker API, then forward the API response to the requestor\n *\n * @param props the properties of the request\n * @returns the same request properties with \"authentication\" data added\n *\n */\n async authenticate(props: IRequestProps) {\n if (!props.headers) {\n props.headers = {}\n }\n props.headers['X-Forwarded-For'] = props.url\n props.headers[LookerAppId] = agentPrefix\n props.url = this.proxyUrl\n return props\n }\n}\n"],"file":"proxySession.js"}
|
package/lib/transport.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
import { Agent } from 'https';
|
|
3
|
-
import { Headers } from 'request';
|
|
4
|
-
import { Readable } from 'readable-stream';
|
|
2
|
+
import type { Agent } from 'https';
|
|
3
|
+
import type { Headers } from 'request';
|
|
4
|
+
import type { Readable } from 'readable-stream';
|
|
5
5
|
export declare const agentPrefix = "TS-SDK";
|
|
6
6
|
export declare const LookerAppId = "x-looker-appid";
|
|
7
7
|
export declare function trace(message: string, info?: any): void;
|
package/lib/transport.js
CHANGED
|
@@ -176,9 +176,12 @@ function addQueryParams(path, obj) {
|
|
|
176
176
|
return "".concat(path).concat(qp ? '?' + qp : '');
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
-
function
|
|
180
|
-
var
|
|
179
|
+
function bufferString(val) {
|
|
180
|
+
var decoder = new TextDecoder('utf-8');
|
|
181
|
+
return decoder.decode(val);
|
|
182
|
+
}
|
|
181
183
|
|
|
184
|
+
function sdkError(response) {
|
|
182
185
|
if (typeof response === 'string') {
|
|
183
186
|
return new Error(response);
|
|
184
187
|
}
|
|
@@ -190,17 +193,8 @@ function sdkError(response) {
|
|
|
190
193
|
return new Error(_error);
|
|
191
194
|
}
|
|
192
195
|
|
|
193
|
-
if ('
|
|
194
|
-
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
if ('error' in _error && _error.error instanceof Buffer) {
|
|
198
|
-
var result = Buffer.from(_error.error).toString(utf8);
|
|
199
|
-
return new Error(result);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
if (_error instanceof Buffer) {
|
|
203
|
-
var _result = Buffer.from(_error).toString(utf8);
|
|
196
|
+
if ('error' in _error) {
|
|
197
|
+
var _result = bufferString(_error.error);
|
|
204
198
|
|
|
205
199
|
return new Error(_result);
|
|
206
200
|
}
|
|
@@ -208,6 +202,13 @@ function sdkError(response) {
|
|
|
208
202
|
if ('message' in _error) {
|
|
209
203
|
return new Error(response.error.message.toString());
|
|
210
204
|
}
|
|
205
|
+
|
|
206
|
+
if ('statusMessage' in _error) {
|
|
207
|
+
return new Error(_error.statusMessage);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
var result = bufferString(_error);
|
|
211
|
+
return new Error(result);
|
|
211
212
|
}
|
|
212
213
|
|
|
213
214
|
if ('message' in response) {
|
package/lib/transport.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transport.ts"],"names":["agentPrefix","LookerAppId","tracing","trace","message","info","console","debug","ResponseMode","contentPatternString","RegExp","matchModeString","contentPatternBinary","matchModeBinary","charsetUtf8Pattern","matchCharsetUtf8","defaultTimeout","StatusCode","responseMode","contentType","match","string","binary","unknown","isUtf8","encodeParam","value","Date","toISOString","encoded","toString","decoded","decodeURIComponent","encodeURIComponent","e","URIError","encodeParams","values","keys","Object","filter","k","undefined","map","join","addQueryParams","path","obj","qp","sdkError","response","utf8","Error","error","statusMessage","Buffer","result","from","JSON","stringify","sdkOk","promise","ok","safeBase64","u8","rawBase64","btoa","String","fromCharCode","replace","isErrorLike","prototype","hasOwnProperty","call"],"mappings":";;;;;;;;;;;;;;;;;AA6BA;;;;;;AAEO,IAAMA,WAAW,GAAG,QAApB;;AACA,IAAMC,WAAW,GAAG,gBAApB;;AAGP,IAAMC,OAAO,GAAG,KAAhB;;AAOO,SAASC,KAAT,CAAeC,OAAf,EAAgCC,IAAhC,EAA4C;AACjD,MAAIH,OAAJ,EAAa;AAEXI,IAAAA,OAAO,CAACC,KAAR,CAAcH,OAAd;;AACA,QAAIC,IAAJ,EAAU;AAERC,MAAAA,OAAO,CAACC,KAAR,CAAc;AAAEF,QAAAA;AAAF,OAAd;AACD;AACF;AACF;;IAGWG,Y;;;WAAAA,Y;AAAAA,EAAAA,Y,CAAAA,Y;AAAAA,EAAAA,Y,CAAAA,Y;AAAAA,EAAAA,Y,CAAAA,Y;GAAAA,Y,4BAAAA,Y;;AAUL,IAAMC,oBAAoB,GAAG,IAAIC,MAAJ,CAAWC,0BAAX,EAA4B,GAA5B,CAA7B;;AAMA,IAAMC,oBAAoB,GAAG,IAAIF,MAAJ,CAAWG,0BAAX,EAA4B,GAA5B,CAA7B;;AAMA,IAAMC,kBAAkB,GAAG,IAAIJ,MAAJ,CAAWK,2BAAX,EAA6B,GAA7B,CAA3B;;AAMA,IAAMC,cAAc,GAAG,GAAvB;;IAiBKC,U;;;WAAAA,U;AAAAA,EAAAA,U,CAAAA,U;AAAAA,EAAAA,U,CAAAA,U;AAAAA,EAAAA,U,CAAAA,U;AAAAA,EAAAA,U,CAAAA,U;AAAAA,EAAAA,U,CAAAA,U;AAAAA,EAAAA,U,CAAAA,U;AAAAA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AI,OAAQA,KAAD,CAAgCjD,OAAvC,KAAmD,QAAvD,EAAiE,OAAO,KAAP;AACjE,SAAO,IAAP;AACD","sourcesContent":["/*\n\n MIT License\n\n Copyright (c) 2021 Looker Data Sciences, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n */\n\nimport { Agent } from 'https'\nimport { Headers } from 'request'\nimport { Readable } from 'readable-stream'\nimport { matchCharsetUtf8, matchModeBinary, matchModeString } from './constants'\n\nexport const agentPrefix = 'TS-SDK'\nexport const LookerAppId = 'x-looker-appid'\n\n/** Set to `true` to follow streaming process */\nconst tracing = false\n\n/**\n * trivial tracing function that should be replaced with a log plugin\n * @param message description for trace\n * @param info any additional information to produce for output\n */\nexport function trace(message: string, info?: any) {\n if (tracing) {\n // eslint-disable-next-line no-console\n console.debug(message)\n if (info) {\n // eslint-disable-next-line no-console\n console.debug({ info })\n }\n }\n}\n\n/** ResponseMode for an HTTP request */\nexport enum ResponseMode {\n 'binary', // this is a binary response\n 'string', // this is a \"string\" response\n 'unknown', // unrecognized response type\n}\n\n/**\n * MIME patterns for string content types\n * @type {RegExp}\n */\nexport const contentPatternString = new RegExp(matchModeString, 'i')\n\n/**\n * MIME patterns for \"binary\" content types\n * @type {RegExp}\n */\nexport const contentPatternBinary = new RegExp(matchModeBinary, 'i')\n\n/**\n * MIME pattern for UTF8 charset attribute\n * @type {RegExp}\n */\nexport const charsetUtf8Pattern = new RegExp(matchCharsetUtf8, 'i')\n\n/**\n * Default request timeout\n * @type {number} default request timeout is 120 seconds, or two minutes\n */\nexport const defaultTimeout = 120\n\n/** Recognized HTTP methods */\nexport type HttpMethod =\n | 'GET'\n | 'POST'\n | 'PUT'\n | 'DELETE'\n | 'PATCH'\n | 'TRACE'\n | 'HEAD'\n\n/**\n * HTTP status codes\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Status for reference\n * TODO is there a platform-agnostic list of these that can be used instead of this static declaration?\n */\nexport enum StatusCode {\n OK = 200,\n Created,\n Accepted,\n NonAuthoritative,\n NoContent,\n ResetContent,\n PartialContent,\n MultiStatus,\n MultiStatusDav,\n IMUsed = 226,\n MultipleChoice = 300,\n MovedPermanently,\n Found,\n SeeOther,\n NotModified,\n UseProxy,\n UnusedRedirect,\n TemporaryRedirect,\n PermanentRedirect,\n BadRequest = 400,\n Unauthorized,\n PaymentRequired,\n Forbidden,\n NotFound,\n MethodNotAllowed,\n NotAcceptable,\n ProxyAuthRequired,\n RequestTimeout,\n Conflict,\n Gone,\n LengthRequired,\n PreconditionFailed,\n PayloadTooLarge,\n UriTooLong,\n UnsupportedMediaType,\n RequestedRangeNotSatisfiable,\n ExpectationFailed,\n ImATeapot,\n MisdirectedRequest = 421,\n UnprocessableEntity,\n Locked,\n FailedDependency,\n TooEarly,\n UpgradeRequired,\n PreconditionRequired,\n TooManyRequests,\n RequestHeaderFieldsTooLarge,\n UnavailableForLegalReasons,\n InternalServerError = 500,\n NotImplemented,\n BadGateway,\n ServiceUnavailable,\n GatewayTimeout,\n HttpVersionNotSupported,\n VariantAlsoNegotiates,\n InsufficientStorage,\n LoopDetected,\n NotExtended = 510,\n NetworkAuthRequired,\n}\n\n/** Untyped basic HTTP response type for \"raw\" HTTP requests */\nexport interface IRawResponse {\n /** ok is `true` if the response is successful, `false` otherwise */\n ok: boolean\n /** HTTP request url */\n url: string\n /** HTTP response code */\n statusCode: number\n /** HTTP response status message text */\n statusMessage: string\n /** MIME type of the response from the HTTP response header */\n contentType: string\n /** The body of the HTTP response, without any additional processing */\n body: any\n /** Optional performance tracking starting mark name */\n startMark?: string\n /** Response headers */\n headers: IRequestHeaders\n}\n\n/** IRawResponse observer function type */\nexport type RawObserver = (raw: IRawResponse) => IRawResponse\n\n/** Transport plug-in interface */\nexport interface ITransport {\n /** Observer lambda to process raw responses */\n observer: RawObserver | undefined\n\n /**\n * HTTP request function for atomic, fully downloaded raw HTTP responses\n *\n * Note: This method returns the result of the HTTP request without any error handling\n *\n * @param method of HTTP request\n * @param path request path, either relative or fully specified\n * @param queryParams name/value pairs to pass as part of the URL\n * @param body data for the body of the request\n * @param authenticator authenticator callback, typically from `IAuthSession` implementation\n * @param options overrides of default transport settings\n * @returns typed response of `TSuccess`, or `TError` result\n */\n rawRequest(\n method: HttpMethod,\n path: string,\n queryParams?: Values,\n body?: any,\n authenticator?: Authenticator,\n options?: Partial<ITransportSettings>\n ): Promise<IRawResponse>\n\n /**\n * HTTP request function for atomic, fully downloaded responses\n * @param method of HTTP request\n * @param path request path, either relative or fully specified\n * @param queryParams name/value pairs to pass as part of the URL\n * @param body data for the body of the request\n * @param authenticator authenticator callback, typically from `IAuthSession` implementation\n * @param options overrides of default transport settings\n * @returns typed response of `TSuccess`, or `TError` result\n */\n request<TSuccess, TError>(\n method: HttpMethod,\n path: string,\n queryParams?: Values,\n body?: any,\n authenticator?: Authenticator,\n options?: Partial<ITransportSettings>\n ): Promise<SDKResponse<TSuccess, TError>>\n\n /**\n * Processes the raw response, converting it into an SDKResponse\n * @param raw response result\n */\n parseResponse<TSuccess, TError>(\n raw: IRawResponse\n ): Promise<SDKResponse<TSuccess, TError>>\n\n /**\n * HTTP request function for a streamable response\n * @param callback that receives the stream response and pipes it somewhere\n * @param method of HTTP request\n * @param path request path, either relative or fully specified\n * @param queryParams name/value pairs to pass as part of the URL\n * @param body data for the body of the request\n * @param authenticator authenticator callback, typically from `IAuthSession` implementation\n * @param options overrides of default transport settings\n * @returns `T` upon success\n * @throws `ISDKErrorResponse` on failure\n */\n stream<T>(\n callback: (readable: Readable) => Promise<T>,\n method: HttpMethod,\n path: string,\n queryParams?: Values,\n body?: any,\n authenticator?: Authenticator,\n options?: Partial<ITransportSettings>\n ): Promise<T>\n}\n\n/** A successful SDK call. */\nexport interface ISDKSuccessResponse<T> {\n /** Whether the SDK call was successful. */\n ok: true\n /** The object returned by the SDK call. */\n value: T\n}\n\n/** An errant SDK call. */\nexport interface ISDKErrorResponse<T> {\n /** Whether the SDK call was successful. */\n ok: false\n /** The error object returned by the SDK call. */\n error: T\n}\n\n/** An error representing an issue in the SDK, like a network or parsing error. */\nexport interface ISDKError {\n type: 'sdk_error'\n message: string\n}\n\nexport type SDKResponse<TSuccess, TError> =\n | ISDKSuccessResponse<TSuccess>\n | ISDKErrorResponse<TError | ISDKError>\n\n/** Generic collection */\nexport interface IRequestHeaders {\n [key: string]: string\n}\n\n/**\n * Generic http request property collection\n * TODO: Trim this down to what is required\n */\nexport interface IRequestProps {\n [key: string]: any\n /** full url for request, including any query params */\n url: string\n\n /** body of request. optional */\n body?: any\n /** headers for request. optional */\n headers: IRequestHeaders\n /** Http method for request. required. */\n method: HttpMethod\n /** Redirect processing for request. optional */\n redirect?: any\n /** Credentials to use */\n credentials?: 'include' | 'omit' | 'same-origin' | undefined\n\n /** http.Agent instance, allows custom proxy, certificate etc. */\n agent?: Agent\n /** support gzip/deflate content encoding. false to disable */\n compress?: boolean\n /** maximum redirect count. 0 to not follow redirect */\n follow?: number\n /** maximum response body size in bytes */\n size?: number\n /** req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies) */\n timeout?: number\n}\n\n/** General purpose authentication callback */\nexport type Authenticator = (props: any) => any\n\n/** Interface for API transport values */\nexport interface ITransportSettings {\n [key: string]: any\n /** base URL of API REST web service */\n base_url: string\n /** standard headers to provide in all transport requests */\n headers?: Headers\n /** whether to verify ssl certs or not. Defaults to true */\n verify_ssl: boolean\n /** request timeout in seconds. Default to 30 */\n timeout: number\n /** encoding override */\n encoding?: string | null\n /** agent tag to use for the SDK requests */\n agentTag: string\n}\n\n/**\n * Is the content type binary or \"string\"?\n * @param {string} contentType\n * @returns {ResponseMode.binary | ResponseMode.string}\n */\nexport function responseMode(contentType: string) {\n if (contentType.match(contentPatternString)) {\n return ResponseMode.string\n }\n if (contentType.match(contentPatternBinary)) {\n return ResponseMode.binary\n }\n return ResponseMode.unknown\n}\n\n/**\n * Does this content type have a UTF-8 charset?\n * @param contentType\n * @returns match if it exists\n */\nexport function isUtf8(contentType: string) {\n return contentType.match(/;.*\\bcharset\\b=\\butf-8\\b/i)\n}\n\n/** Used for name/value pair collections like for QueryParams */\nexport type Values = { [key: string]: any } | null | undefined\n\n/**\n * Encode parameter if not already encoded\n * @param value value of parameter\n * @returns URI encoded value\n */\nexport function encodeParam(value: any) {\n if (value instanceof Date) {\n value = value.toISOString()\n }\n let encoded = value.toString()\n\n // decodeURIComponent throws URIError if there is a % character\n // without it being part of an encoded\n try {\n const decoded = decodeURIComponent(value)\n if (value === decoded) {\n encoded = encodeURIComponent(value)\n }\n } catch (e) {\n if (e instanceof URIError) {\n encoded = encodeURIComponent(value)\n } else {\n throw e\n }\n }\n return encoded\n}\n\n/**\n * Converts `Values` to query string parameter format\n * @param values Name/value collection to encode\n * @returns {string} query string parameter formatted values. Both `false` and `null` are included. Only `undefined` are omitted.\n */\nexport function encodeParams(values?: Values) {\n if (!values) return ''\n\n const keys = Object.keys(values)\n return keys\n .filter((k) => values[k] !== undefined) // `null` and `false` will both be passed\n .map((k) => k + '=' + encodeParam(values[k]))\n .join('&')\n}\n\n/**\n * constructs the path argument including any optional query parameters\n * @param path the base path of the request\n * @param obj optional collection of query parameters to encode and append to the path\n */\nexport function addQueryParams(path: string, obj?: Values) {\n if (!obj) {\n return path\n }\n const qp = encodeParams(obj)\n return `${path}${qp ? '?' + qp : ''}`\n}\n\n/**\n * SDK error handler\n * @param response any kind of error\n * @returns a new `Error` object with the failure message\n */\nexport function sdkError(response: any) {\n const utf8 = 'utf-8'\n if (typeof response === 'string') {\n return new Error(response)\n }\n if ('error' in response) {\n const error = response.error\n if (typeof error === 'string') {\n return new Error(error)\n }\n // Try to get most specific error first\n if ('statusMessage' in error) {\n return new Error(error.statusMessage)\n }\n if ('error' in error && error.error instanceof Buffer) {\n const result = Buffer.from(error.error).toString(utf8)\n return new Error(result)\n }\n if (error instanceof Buffer) {\n const result = Buffer.from(error).toString(utf8)\n return new Error(result)\n }\n if ('message' in error) {\n return new Error(response.error.message.toString())\n }\n }\n if ('message' in response) {\n return new Error(response.message)\n }\n const error = JSON.stringify(response)\n return new Error(`Unknown error with SDK method ${error}`)\n}\n\n/** A helper method for simplifying error handling of SDK responses.\n *\n * Pass in a promise returned by any SDK method, and it will return a promise\n * that rejects if the `SDKResponse` is not `ok`. This will swallow the type\n * information in the error case, but allows you to route all the error cases\n * into a single promise rejection.\n *\n * The promise will have an `Error` rejection reason with a string `message`.\n * If the server error contains a `message` field, it will be provided, otherwise a\n * generic message will occur.\n *\n * ```ts\n * const sdk = LookerSDK({...})\n * let look\n * try {\n * look = await sdkOk(sdk.create_look({...}))\n * // do something with look\n * }\n * catch(e) {\n * // handle error case\n * }\n * ```\n */\nexport async function sdkOk<TSuccess, TError>(\n promise: Promise<SDKResponse<TSuccess, TError>>\n) {\n const result = await promise\n if (result.ok) {\n return result.value\n } else {\n throw sdkError(result)\n }\n}\n\n/**\n * Converts a byte array to a \"URL safe\" base64 string\n * @param u8 byte array to convert\n */\nexport function safeBase64(u8: Uint8Array) {\n const rawBase64 = btoa(String.fromCharCode(...u8))\n return rawBase64.replace(/\\+/g, '-').replace(/\\//g, '_')\n}\n\n/**\n * Type predicate. Asserts that a given object is error-like.\n * @param error a value of unknown type\n * @return boolean true if the error has a `message` key of type string.\n */\nexport function isErrorLike<T extends unknown>(\n error: T\n): error is T & { message: string } {\n if (typeof error !== 'object') return false\n if (!error) return false\n if (!Object.prototype.hasOwnProperty.call(error, 'message')) return false\n if (typeof (error as { message: unknown }).message !== 'string') return false\n return true\n}\n"],"file":"transport.js"}
|
|
1
|
+
{"version":3,"sources":["../src/transport.ts"],"names":["agentPrefix","LookerAppId","tracing","trace","message","info","console","debug","ResponseMode","contentPatternString","RegExp","matchModeString","contentPatternBinary","matchModeBinary","charsetUtf8Pattern","matchCharsetUtf8","defaultTimeout","StatusCode","responseMode","contentType","match","string","binary","unknown","isUtf8","encodeParam","value","Date","toISOString","encoded","toString","decoded","decodeURIComponent","encodeURIComponent","e","URIError","encodeParams","values","keys","Object","filter","k","undefined","map","join","addQueryParams","path","obj","qp","bufferString","val","decoder","TextDecoder","decode","sdkError","response","Error","error","result","statusMessage","JSON","stringify","sdkOk","promise","ok","safeBase64","u8","rawBase64","btoa","String","fromCharCode","replace","isErrorLike","prototype","hasOwnProperty","call"],"mappings":";;;;;;;;;;;;;;;;;AA6BA;;;;;;AAEO,IAAMA,WAAW,GAAG,QAApB;;AACA,IAAMC,WAAW,GAAG,gBAApB;;AAGP,IAAMC,OAAO,GAAG,KAAhB;;AAOO,SAASC,KAAT,CAAeC,OAAf,EAAgCC,IAAhC,EAA4C;AACjD,MAAIH,OAAJ,EAAa;AAEXI,IAAAA,OAAO,CAACC,KAAR,CAAcH,OAAd;;AACA,QAAIC,IAAJ,EAAU;AAERC,MAAAA,OAAO,CAACC,KAAR,CAAc;AAAEF,QAAAA;AAAF,OAAd;AACD;AACF;AACF;;IAGWG,Y;;;WAAAA,Y;AAAAA,EAAAA,Y,CAAAA,Y;AAAAA,EAAAA,Y,CAAAA,Y;AAAAA,EAAAA,Y,CAAAA,Y;GAAAA,Y,4BAAAA,Y;;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AAD,CAAtB;AACA,SAAOC,SAAS,CAACI,OAAV,CAAkB,KAAlB,EAAyB,GAAzB,EAA8BA,OAA9B,CAAsC,KAAtC,EAA6C,GAA7C,CAAP;AACD;;AAOM,SAASC,WAAT,CACLf,KADK,EAE6B;AAClC,MAAI,OAAOA,KAAP,KAAiB,QAArB,EAA+B,OAAO,KAAP;AAC/B,MAAI,CAACA,KAAL,EAAY,OAAO,KAAP;AACZ,MAAI,CAAClB,MAAM,CAACkC,SAAP,CAAiBC,cAAjB,CAAgCC,IAAhC,CAAqClB,KAArC,EAA4C,SAA5C,CAAL,EAA6D,OAAO,KAAP;AAC7D,MAAI,OAAQA,KAAD,CAAgCrD,OAAvC,KAAmD,QAAvD,EAAiE,OAAO,KAAP;AACjE,SAAO,IAAP;AACD","sourcesContent":["/*\n\n MIT License\n\n Copyright (c) 2021 Looker Data Sciences, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n */\n\nimport type { Agent } from 'https'\nimport type { Headers } from 'request'\nimport type { Readable } from 'readable-stream'\nimport { matchCharsetUtf8, matchModeBinary, matchModeString } from './constants'\n\nexport const agentPrefix = 'TS-SDK'\nexport const LookerAppId = 'x-looker-appid'\n\n/** Set to `true` to follow streaming process */\nconst tracing = false\n\n/**\n * trivial tracing function that should be replaced with a log plugin\n * @param message description for trace\n * @param info any additional information to produce for output\n */\nexport function trace(message: string, info?: any) {\n if (tracing) {\n // eslint-disable-next-line no-console\n console.debug(message)\n if (info) {\n // eslint-disable-next-line no-console\n console.debug({ info })\n }\n }\n}\n\n/** ResponseMode for an HTTP request */\nexport enum ResponseMode {\n 'binary', // this is a binary response\n 'string', // this is a \"string\" response\n 'unknown', // unrecognized response type\n}\n\n/**\n * MIME patterns for string content types\n * @type {RegExp}\n */\nexport const contentPatternString = new RegExp(matchModeString, 'i')\n\n/**\n * MIME patterns for \"binary\" content types\n * @type {RegExp}\n */\nexport const contentPatternBinary = new RegExp(matchModeBinary, 'i')\n\n/**\n * MIME pattern for UTF8 charset attribute\n * @type {RegExp}\n */\nexport const charsetUtf8Pattern = new RegExp(matchCharsetUtf8, 'i')\n\n/**\n * Default request timeout\n * @type {number} default request timeout is 120 seconds, or two minutes\n */\nexport const defaultTimeout = 120\n\n/** Recognized HTTP methods */\nexport type HttpMethod =\n | 'GET'\n | 'POST'\n | 'PUT'\n | 'DELETE'\n | 'PATCH'\n | 'TRACE'\n | 'HEAD'\n\n/**\n * HTTP status codes\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Status for reference\n * TODO is there a platform-agnostic list of these that can be used instead of this static declaration?\n */\nexport enum StatusCode {\n OK = 200,\n Created,\n Accepted,\n NonAuthoritative,\n NoContent,\n ResetContent,\n PartialContent,\n MultiStatus,\n MultiStatusDav,\n IMUsed = 226,\n MultipleChoice = 300,\n MovedPermanently,\n Found,\n SeeOther,\n NotModified,\n UseProxy,\n UnusedRedirect,\n TemporaryRedirect,\n PermanentRedirect,\n BadRequest = 400,\n Unauthorized,\n PaymentRequired,\n Forbidden,\n NotFound,\n MethodNotAllowed,\n NotAcceptable,\n ProxyAuthRequired,\n RequestTimeout,\n Conflict,\n Gone,\n LengthRequired,\n PreconditionFailed,\n PayloadTooLarge,\n UriTooLong,\n UnsupportedMediaType,\n RequestedRangeNotSatisfiable,\n ExpectationFailed,\n ImATeapot,\n MisdirectedRequest = 421,\n UnprocessableEntity,\n Locked,\n FailedDependency,\n TooEarly,\n UpgradeRequired,\n PreconditionRequired,\n TooManyRequests,\n RequestHeaderFieldsTooLarge,\n UnavailableForLegalReasons,\n InternalServerError = 500,\n NotImplemented,\n BadGateway,\n ServiceUnavailable,\n GatewayTimeout,\n HttpVersionNotSupported,\n VariantAlsoNegotiates,\n InsufficientStorage,\n LoopDetected,\n NotExtended = 510,\n NetworkAuthRequired,\n}\n\n/** Untyped basic HTTP response type for \"raw\" HTTP requests */\nexport interface IRawResponse {\n /** ok is `true` if the response is successful, `false` otherwise */\n ok: boolean\n /** HTTP request url */\n url: string\n /** HTTP response code */\n statusCode: number\n /** HTTP response status message text */\n statusMessage: string\n /** MIME type of the response from the HTTP response header */\n contentType: string\n /** The body of the HTTP response, without any additional processing */\n body: any\n /** Optional performance tracking starting mark name */\n startMark?: string\n /** Response headers */\n headers: IRequestHeaders\n}\n\n/** IRawResponse observer function type */\nexport type RawObserver = (raw: IRawResponse) => IRawResponse\n\n/** Transport plug-in interface */\nexport interface ITransport {\n /** Observer lambda to process raw responses */\n observer: RawObserver | undefined\n\n /**\n * HTTP request function for atomic, fully downloaded raw HTTP responses\n *\n * Note: This method returns the result of the HTTP request without any error handling\n *\n * @param method of HTTP request\n * @param path request path, either relative or fully specified\n * @param queryParams name/value pairs to pass as part of the URL\n * @param body data for the body of the request\n * @param authenticator authenticator callback, typically from `IAuthSession` implementation\n * @param options overrides of default transport settings\n * @returns typed response of `TSuccess`, or `TError` result\n */\n rawRequest(\n method: HttpMethod,\n path: string,\n queryParams?: Values,\n body?: any,\n authenticator?: Authenticator,\n options?: Partial<ITransportSettings>\n ): Promise<IRawResponse>\n\n /**\n * HTTP request function for atomic, fully downloaded responses\n * @param method of HTTP request\n * @param path request path, either relative or fully specified\n * @param queryParams name/value pairs to pass as part of the URL\n * @param body data for the body of the request\n * @param authenticator authenticator callback, typically from `IAuthSession` implementation\n * @param options overrides of default transport settings\n * @returns typed response of `TSuccess`, or `TError` result\n */\n request<TSuccess, TError>(\n method: HttpMethod,\n path: string,\n queryParams?: Values,\n body?: any,\n authenticator?: Authenticator,\n options?: Partial<ITransportSettings>\n ): Promise<SDKResponse<TSuccess, TError>>\n\n /**\n * Processes the raw response, converting it into an SDKResponse\n * @param raw response result\n */\n parseResponse<TSuccess, TError>(\n raw: IRawResponse\n ): Promise<SDKResponse<TSuccess, TError>>\n\n /**\n * HTTP request function for a streamable response\n * @param callback that receives the stream response and pipes it somewhere\n * @param method of HTTP request\n * @param path request path, either relative or fully specified\n * @param queryParams name/value pairs to pass as part of the URL\n * @param body data for the body of the request\n * @param authenticator authenticator callback, typically from `IAuthSession` implementation\n * @param options overrides of default transport settings\n * @returns `T` upon success\n * @throws `ISDKErrorResponse` on failure\n */\n stream<T>(\n callback: (readable: Readable) => Promise<T>,\n method: HttpMethod,\n path: string,\n queryParams?: Values,\n body?: any,\n authenticator?: Authenticator,\n options?: Partial<ITransportSettings>\n ): Promise<T>\n}\n\n/** A successful SDK call. */\nexport interface ISDKSuccessResponse<T> {\n /** Whether the SDK call was successful. */\n ok: true\n /** The object returned by the SDK call. */\n value: T\n}\n\n/** An errant SDK call. */\nexport interface ISDKErrorResponse<T> {\n /** Whether the SDK call was successful. */\n ok: false\n /** The error object returned by the SDK call. */\n error: T\n}\n\n/** An error representing an issue in the SDK, like a network or parsing error. */\nexport interface ISDKError {\n type: 'sdk_error'\n message: string\n}\n\nexport type SDKResponse<TSuccess, TError> =\n | ISDKSuccessResponse<TSuccess>\n | ISDKErrorResponse<TError | ISDKError>\n\n/** Generic collection */\nexport interface IRequestHeaders {\n [key: string]: string\n}\n\n/**\n * Generic http request property collection\n * TODO: Trim this down to what is required\n */\nexport interface IRequestProps {\n [key: string]: any\n /** full url for request, including any query params */\n url: string\n\n /** body of request. optional */\n body?: any\n /** headers for request. optional */\n headers: IRequestHeaders\n /** Http method for request. required. */\n method: HttpMethod\n /** Redirect processing for request. optional */\n redirect?: any\n /** Credentials to use */\n credentials?: 'include' | 'omit' | 'same-origin' | undefined\n\n /** http.Agent instance, allows custom proxy, certificate etc. */\n agent?: Agent\n /** support gzip/deflate content encoding. false to disable */\n compress?: boolean\n /** maximum redirect count. 0 to not follow redirect */\n follow?: number\n /** maximum response body size in bytes */\n size?: number\n /** req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies) */\n timeout?: number\n}\n\n/** General purpose authentication callback */\nexport type Authenticator = (props: any) => any\n\n/** Interface for API transport values */\nexport interface ITransportSettings {\n [key: string]: any\n /** base URL of API REST web service */\n base_url: string\n /** standard headers to provide in all transport requests */\n headers?: Headers\n /** whether to verify ssl certs or not. Defaults to true */\n verify_ssl: boolean\n /** request timeout in seconds. Default to 30 */\n timeout: number\n /** encoding override */\n encoding?: string | null\n /** agent tag to use for the SDK requests */\n agentTag: string\n}\n\n/**\n * Is the content type binary or \"string\"?\n * @param {string} contentType\n * @returns {ResponseMode.binary | ResponseMode.string}\n */\nexport function responseMode(contentType: string) {\n if (contentType.match(contentPatternString)) {\n return ResponseMode.string\n }\n if (contentType.match(contentPatternBinary)) {\n return ResponseMode.binary\n }\n return ResponseMode.unknown\n}\n\n/**\n * Does this content type have a UTF-8 charset?\n * @param contentType\n * @returns match if it exists\n */\nexport function isUtf8(contentType: string) {\n return contentType.match(/;.*\\bcharset\\b=\\butf-8\\b/i)\n}\n\n/** Used for name/value pair collections like for QueryParams */\nexport type Values = { [key: string]: any } | null | undefined\n\n/**\n * Encode parameter if not already encoded\n * @param value value of parameter\n * @returns URI encoded value\n */\nexport function encodeParam(value: any) {\n if (value instanceof Date) {\n value = value.toISOString()\n }\n let encoded = value.toString()\n\n // decodeURIComponent throws URIError if there is a % character\n // without it being part of an encoded\n try {\n const decoded = decodeURIComponent(value)\n if (value === decoded) {\n encoded = encodeURIComponent(value)\n }\n } catch (e) {\n if (e instanceof URIError) {\n encoded = encodeURIComponent(value)\n } else {\n throw e\n }\n }\n return encoded\n}\n\n/**\n * Converts `Values` to query string parameter format\n * @param values Name/value collection to encode\n * @returns {string} query string parameter formatted values. Both `false` and `null` are included. Only `undefined` are omitted.\n */\nexport function encodeParams(values?: Values) {\n if (!values) return ''\n\n const keys = Object.keys(values)\n return keys\n .filter((k) => values[k] !== undefined) // `null` and `false` will both be passed\n .map((k) => k + '=' + encodeParam(values[k]))\n .join('&')\n}\n\n/**\n * constructs the path argument including any optional query parameters\n * @param path the base path of the request\n * @param obj optional collection of query parameters to encode and append to the path\n */\nexport function addQueryParams(path: string, obj?: Values) {\n if (!obj) {\n return path\n }\n const qp = encodeParams(obj)\n return `${path}${qp ? '?' + qp : ''}`\n}\n\nfunction bufferString(val: any) {\n const decoder = new TextDecoder('utf-8')\n return decoder.decode(val)\n}\n\n/**\n * SDK error handler\n * @param response any kind of error\n * @returns a new `Error` object with the failure message\n */\nexport function sdkError(response: any) {\n if (typeof response === 'string') {\n return new Error(response)\n }\n if ('error' in response) {\n const error = response.error\n if (typeof error === 'string') {\n return new Error(error)\n }\n // Try to get most specific error first\n if ('error' in error) {\n const result = bufferString(error.error)\n return new Error(result)\n }\n if ('message' in error) {\n return new Error(response.error.message.toString())\n }\n if ('statusMessage' in error) {\n return new Error(error.statusMessage)\n }\n const result = bufferString(error)\n return new Error(result)\n }\n if ('message' in response) {\n return new Error(response.message)\n }\n const error = JSON.stringify(response)\n return new Error(`Unknown error with SDK method ${error}`)\n}\n\n/** A helper method for simplifying error handling of SDK responses.\n *\n * Pass in a promise returned by any SDK method, and it will return a promise\n * that rejects if the `SDKResponse` is not `ok`. This will swallow the type\n * information in the error case, but allows you to route all the error cases\n * into a single promise rejection.\n *\n * The promise will have an `Error` rejection reason with a string `message`.\n * If the server error contains a `message` field, it will be provided, otherwise a\n * generic message will occur.\n *\n * ```ts\n * const sdk = LookerSDK({...})\n * let look\n * try {\n * look = await sdkOk(sdk.create_look({...}))\n * // do something with look\n * }\n * catch(e) {\n * // handle error case\n * }\n * ```\n */\nexport async function sdkOk<TSuccess, TError>(\n promise: Promise<SDKResponse<TSuccess, TError>>\n) {\n const result = await promise\n if (result.ok) {\n return result.value\n } else {\n throw sdkError(result)\n }\n}\n\n/**\n * Converts a byte array to a \"URL safe\" base64 string\n * @param u8 byte array to convert\n */\nexport function safeBase64(u8: Uint8Array) {\n const rawBase64 = btoa(String.fromCharCode(...u8))\n return rawBase64.replace(/\\+/g, '-').replace(/\\//g, '_')\n}\n\n/**\n * Type predicate. Asserts that a given object is error-like.\n * @param error a value of unknown type\n * @return boolean true if the error has a `message` key of type string.\n */\nexport function isErrorLike<T extends unknown>(\n error: T\n): error is T & { message: string } {\n if (typeof error !== 'object') return false\n if (!error) return false\n if (!Object.prototype.hasOwnProperty.call(error, 'message')) return false\n if (typeof (error as { message: unknown }).message !== 'string') return false\n return true\n}\n"],"file":"transport.js"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@looker/sdk-rtl",
|
|
3
|
-
"version": "21.0
|
|
3
|
+
"version": "21.1.0",
|
|
4
4
|
"description": "Looker SDK Runtime Library",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"module": "lib/esm/index.js",
|
|
@@ -51,5 +51,5 @@
|
|
|
51
51
|
"SDK",
|
|
52
52
|
"RTL"
|
|
53
53
|
],
|
|
54
|
-
"gitHead": "
|
|
54
|
+
"gitHead": "295c2ed60f9e41c3664d8505ebc1f2c2b5a1fbbc"
|
|
55
55
|
}
|