@looker/sdk-node 24.14.0 → 24.16.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"nodeSession.js","names":["_sdkRtl","require","_nodeTransport","asyncGeneratorStep","gen","resolve","reject","_next","_throw","key","arg","info","value","error","done","Promise","then","_asyncToGenerator","fn","self","args","arguments","apply","err","undefined","_defineProperty","obj","_toPropertyKey","Object","defineProperty","enumerable","configurable","writable","t","i","_toPrimitive","String","r","e","Symbol","toPrimitive","call","TypeError","Number","strPost","strDelete","NodeSession","AuthSession","constructor","settings","transport","NodeTransport","AuthToken","activeToken","_sudoToken","access_token","_authToken","isAuthenticated","token","isActive","authenticate","props","_this","getToken","headers","Authorization","concat","isSudo","sudoId","_this2","login","reset","_this3","_login","toString","logout","_this4","result","_logout","sudoLogout","_this5","newId","_this6","section","readConfig","clientId","client_id","clientSecret","client_secret","sdkError","message","body","encodeParams","ok","request","apiPath","setToken","promise","encodeURI","init","accessToken","_this7","exports"],"sources":["../src/nodeSession.ts"],"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 {\n HttpMethod,\n IAccessToken,\n IApiSettings,\n IError,\n IRequestProps,\n ITransport,\n} from '@looker/sdk-rtl';\nimport {\n AuthSession,\n AuthToken,\n encodeParams,\n sdkError,\n} from '@looker/sdk-rtl';\nimport { NodeTransport } from './nodeTransport';\n\nconst strPost: HttpMethod = 'POST';\nconst strDelete: HttpMethod = 'DELETE';\n\nexport class NodeSession extends AuthSession {\n private readonly apiPath: string = '/api/4.0';\n _authToken: AuthToken = new AuthToken();\n _sudoToken: AuthToken = new AuthToken();\n\n constructor(\n public settings: IApiSettings,\n transport?: ITransport\n ) {\n super(settings, transport || new NodeTransport(settings));\n }\n\n /**\n * Abstraction of AuthToken retrieval to support sudo mode\n */\n get activeToken() {\n if (this._sudoToken.access_token) {\n return this._sudoToken;\n }\n return this._authToken;\n }\n\n /**\n * Is there an active authentication token?\n */\n isAuthenticated() {\n // TODO I think this can be simplified\n const token = this.activeToken;\n if (!(token && token.access_token)) return false;\n return token.isActive();\n }\n\n /**\n * Add authentication data to the pending API request\n * @param props initialized API request properties\n *\n * @returns the updated request properties\n */\n async authenticate(props: IRequestProps) {\n const token = await this.getToken();\n if (token && token.access_token) {\n props.headers.Authorization = `Bearer ${token.access_token}`;\n }\n return props;\n }\n\n isSudo() {\n return !!this.sudoId && this._sudoToken.isActive();\n }\n\n /**\n * retrieve the current authentication token. If there is no active token, performs default\n * login to retrieve the token\n */\n async getToken() {\n if (!this.isAuthenticated()) {\n await this.login();\n }\n return this.activeToken;\n }\n\n /**\n * Reset the authentication session\n */\n reset() {\n this.sudoId = '';\n this._authToken.reset();\n this._sudoToken.reset();\n }\n\n /**\n * Activate the authentication token for the API3 or sudo user\n * @param sudoId {string | number}: optional. If provided, impersonates the user specified\n *\n */\n async login(sudoId?: string | number) {\n if (sudoId || sudoId !== this.sudoId || !this.isAuthenticated()) {\n if (sudoId) {\n await this._login(sudoId.toString());\n } else {\n await this._login();\n }\n }\n return this.activeToken;\n }\n\n /**\n * Logout the active user. If the active user is sudo, the session reverts to the API3 user\n */\n async logout() {\n let result = false;\n if (this.isAuthenticated()) {\n result = await this._logout();\n }\n return result;\n }\n\n private async sudoLogout() {\n let result = false;\n if (this.isSudo()) {\n result = await this.logout(); // Logout the current sudo\n this._sudoToken.reset();\n }\n return result;\n }\n\n // internal login method that manages default auth token and sudo workflow\n private async _login(newId?: string) {\n // for linty freshness, always logout sudo if set\n await this.sudoLogout();\n\n if (newId !== this.sudoId) {\n // Assign new requested sudo id\n this.sudoId = newId || '';\n }\n\n if (!this._authToken.isActive()) {\n this.reset();\n // only retain client API3 credentials for the lifetime of the login request\n const section = this.settings.readConfig();\n const clientId = section.client_id;\n const clientSecret = section.client_secret;\n if (!clientId || !clientSecret) {\n throw sdkError({\n message: 'API credentials client_id and/or client_secret are not set',\n });\n }\n const body = encodeParams({\n client_id: clientId,\n client_secret: clientSecret,\n });\n // authenticate client\n const token = await this.ok(\n this.transport.request<IAccessToken, IError>(\n strPost,\n `${this.apiPath}/login`,\n undefined,\n body\n )\n );\n this._authToken.setToken(token);\n }\n\n if (this.sudoId) {\n // Use the API user auth to sudo\n const token = this.activeToken;\n const promise = this.transport.request<IAccessToken, IError>(\n strPost,\n encodeURI(`${this.apiPath}/login/${newId}`),\n null,\n null,\n // ensure the auth token is included in the sudo request\n (init: IRequestProps) => {\n if (token.access_token) {\n init.headers.Authorization = `Bearer ${token.access_token}`;\n }\n return init;\n },\n this.settings // TODO this may not be needed here\n );\n\n const accessToken = await this.ok(promise);\n\n this._sudoToken.setToken(accessToken);\n }\n\n return this.activeToken;\n }\n\n private async _logout() {\n const token = this.activeToken;\n const promise = this.transport.request<string, IError>(\n strDelete,\n `${this.apiPath}/logout`,\n null,\n null,\n // ensure the auth token is included in the logout promise\n (init: IRequestProps) => {\n if (token.access_token) {\n init.headers.Authorization = `Bearer ${token.access_token}`;\n }\n return init;\n },\n this.settings\n );\n\n await this.ok(promise);\n\n // If no error was thrown, logout was successful\n if (this.sudoId) {\n // User was logged out, so set auth back to default\n this.sudoId = '';\n this._sudoToken.reset();\n if (!this._authToken.isActive()) {\n await this.login();\n }\n } else {\n // completely logged out\n this.reset();\n }\n return true;\n }\n}\n"],"mappings":";;;;;;AAkCA,IAAAA,OAAA,GAAAC,OAAA;AAMA,IAAAC,cAAA,GAAAD,OAAA;AAAgD,SAAAE,mBAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,GAAA,EAAAC,GAAA,cAAAC,IAAA,GAAAP,GAAA,CAAAK,GAAA,EAAAC,GAAA,OAAAE,KAAA,GAAAD,IAAA,CAAAC,KAAA,WAAAC,KAAA,IAAAP,MAAA,CAAAO,KAAA,iBAAAF,IAAA,CAAAG,IAAA,IAAAT,OAAA,CAAAO,KAAA,YAAAG,OAAA,CAAAV,OAAA,CAAAO,KAAA,EAAAI,IAAA,CAAAT,KAAA,EAAAC,MAAA;AAAA,SAAAS,kBAAAC,EAAA,6BAAAC,IAAA,SAAAC,IAAA,GAAAC,SAAA,aAAAN,OAAA,WAAAV,OAAA,EAAAC,MAAA,QAAAF,GAAA,GAAAc,EAAA,CAAAI,KAAA,CAAAH,IAAA,EAAAC,IAAA,YAAAb,MAAAK,KAAA,IAAAT,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,UAAAI,KAAA,cAAAJ,OAAAe,GAAA,IAAApB,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,WAAAe,GAAA,KAAAhB,KAAA,CAAAiB,SAAA;AAAA,SAAAC,gBAAAC,GAAA,EAAAjB,GAAA,EAAAG,KAAA,IAAAH,GAAA,GAAAkB,cAAA,CAAAlB,GAAA,OAAAA,GAAA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CAACnD,SAAS,CAAC4C,OAAO,CACpCjD,SAAS,KAAAqB,MAAA,CACNmC,MAAI,CAACN,OAAO,cACf,IAAI,EACJ,IAAI,EAEHI,IAAmB,IAAK;QACvB,IAAIzC,KAAK,CAACH,YAAY,EAAE;UACtB4C,IAAI,CAACnC,OAAO,CAACC,aAAa,aAAAC,MAAA,CAAaR,KAAK,CAACH,YAAY,CAAE;QAC7D;QACA,OAAO4C,IAAI;MACb,CAAC,EACDE,MAAI,CAACpD,QACP,CAAC;MAED,MAAMoD,MAAI,CAACR,EAAE,CAACI,OAAO,CAAC;MAGtB,IAAII,MAAI,CAACjC,MAAM,EAAE;QAEfiC,MAAI,CAACjC,MAAM,GAAG,EAAE;QAChBiC,MAAI,CAAC/C,UAAU,CAACiB,KAAK,CAAC,CAAC;QACvB,IAAI,CAAC8B,MAAI,CAAC7C,UAAU,CAACG,QAAQ,CAAC,CAAC,EAAE;UAC/B,MAAM0C,MAAI,CAAC/B,KAAK,CAAC,CAAC;QACpB;MACF,CAAC,MAAM;QAEL+B,MAAI,CAAC9B,KAAK,CAAC,CAAC;MACd;MACA,OAAO,IAAI;IAAC;EACd;AACF;AAAC+B,OAAA,CAAAxD,WAAA,GAAAA,WAAA"}
1
+ {"version":3,"file":"nodeSession.js","names":["_sdkRtl","require","_nodeTransport","asyncGeneratorStep","gen","resolve","reject","_next","_throw","key","arg","info","value","error","done","Promise","then","_asyncToGenerator","fn","self","args","arguments","apply","err","undefined","_defineProperty","obj","_toPropertyKey","Object","defineProperty","enumerable","configurable","writable","t","i","_toPrimitive","String","r","e","Symbol","toPrimitive","call","TypeError","Number","strPost","strDelete","NodeSession","AuthSession","constructor","settings","transport","NodeTransport","AuthToken","activeToken","_sudoToken","access_token","_authToken","isAuthenticated","token","isActive","authenticate","props","_this","getToken","headers","Authorization","concat","isSudo","sudoId","_this2","login","reset","_this3","_login","toString","logout","_this4","result","_logout","sudoLogout","_this5","newId","_this6","section","readConfig","clientId","client_id","clientSecret","client_secret","sdkError","message","body","encodeParams","ok","request","apiPath","setToken","promise","encodeURI","init","accessToken","_this7","exports"],"sources":["../src/nodeSession.ts"],"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 {\n HttpMethod,\n IAccessToken,\n IApiSettings,\n IError,\n IRequestProps,\n ITransport,\n} from '@looker/sdk-rtl';\nimport {\n AuthSession,\n AuthToken,\n encodeParams,\n sdkError,\n} from '@looker/sdk-rtl';\nimport { NodeTransport } from './nodeTransport';\n\nconst strPost: HttpMethod = 'POST';\nconst strDelete: HttpMethod = 'DELETE';\n\nexport class NodeSession extends AuthSession {\n private readonly apiPath: string = '/api/4.0';\n _authToken: AuthToken = new AuthToken();\n _sudoToken: AuthToken = new AuthToken();\n\n constructor(public settings: IApiSettings, transport?: ITransport) {\n super(settings, transport || new NodeTransport(settings));\n }\n\n /**\n * Abstraction of AuthToken retrieval to support sudo mode\n */\n get activeToken() {\n if (this._sudoToken.access_token) {\n return this._sudoToken;\n }\n return this._authToken;\n }\n\n /**\n * Is there an active authentication token?\n */\n isAuthenticated() {\n // TODO I think this can be simplified\n const token = this.activeToken;\n if (!(token && token.access_token)) return false;\n return token.isActive();\n }\n\n /**\n * Add authentication data to the pending API request\n * @param props initialized API request properties\n *\n * @returns the updated request properties\n */\n async authenticate(props: IRequestProps) {\n const token = await this.getToken();\n if (token && token.access_token) {\n props.headers.Authorization = `Bearer ${token.access_token}`;\n }\n return props;\n }\n\n isSudo() {\n return !!this.sudoId && this._sudoToken.isActive();\n }\n\n /**\n * retrieve the current authentication token. If there is no active token, performs default\n * login to retrieve the token\n */\n async getToken() {\n if (!this.isAuthenticated()) {\n await this.login();\n }\n return this.activeToken;\n }\n\n /**\n * Reset the authentication session\n */\n reset() {\n this.sudoId = '';\n this._authToken.reset();\n this._sudoToken.reset();\n }\n\n /**\n * Activate the authentication token for the API3 or sudo user\n * @param sudoId {string | number}: optional. If provided, impersonates the user specified\n *\n */\n async login(sudoId?: string | number) {\n if (sudoId || sudoId !== this.sudoId || !this.isAuthenticated()) {\n if (sudoId) {\n await this._login(sudoId.toString());\n } else {\n await this._login();\n }\n }\n return this.activeToken;\n }\n\n /**\n * Logout the active user. If the active user is sudo, the session reverts to the API3 user\n */\n async logout() {\n let result = false;\n if (this.isAuthenticated()) {\n result = await this._logout();\n }\n return result;\n }\n\n private async sudoLogout() {\n let result = false;\n if (this.isSudo()) {\n result = await this.logout(); // Logout the current sudo\n this._sudoToken.reset();\n }\n return result;\n }\n\n // internal login method that manages default auth token and sudo workflow\n private async _login(newId?: string) {\n // for linty freshness, always logout sudo if set\n await this.sudoLogout();\n\n if (newId !== this.sudoId) {\n // Assign new requested sudo id\n this.sudoId = newId || '';\n }\n\n if (!this._authToken.isActive()) {\n this.reset();\n // only retain client API3 credentials for the lifetime of the login request\n const section = this.settings.readConfig();\n const clientId = section.client_id;\n const clientSecret = section.client_secret;\n if (!clientId || !clientSecret) {\n throw sdkError({\n message: 'API credentials client_id and/or client_secret are not set',\n });\n }\n const body = encodeParams({\n client_id: clientId,\n client_secret: clientSecret,\n });\n const headers = { 'content-type': 'application/x-www-form-urlencoded' };\n // authenticate client\n const token = await this.ok(\n this.transport.request<IAccessToken, IError>(\n strPost,\n `${this.apiPath}/login`,\n undefined,\n body,\n undefined,\n { headers }\n )\n );\n this._authToken.setToken(token);\n }\n\n if (this.sudoId) {\n // Use the API user auth to sudo\n const token = this.activeToken;\n const promise = this.transport.request<IAccessToken, IError>(\n strPost,\n encodeURI(`${this.apiPath}/login/${newId}`),\n null,\n null,\n // ensure the auth token is included in the sudo request\n (init: IRequestProps) => {\n if (token.access_token) {\n init.headers.Authorization = `Bearer ${token.access_token}`;\n }\n return init;\n },\n this.settings // TODO this may not be needed here\n );\n\n const accessToken = await this.ok(promise);\n\n this._sudoToken.setToken(accessToken);\n }\n\n return this.activeToken;\n }\n\n private async _logout() {\n const token = this.activeToken;\n const promise = this.transport.request<string, IError>(\n strDelete,\n `${this.apiPath}/logout`,\n null,\n null,\n // ensure the auth token is included in the logout promise\n (init: IRequestProps) => {\n if (token.access_token) {\n init.headers.Authorization = `Bearer ${token.access_token}`;\n }\n return init;\n },\n this.settings\n );\n\n await this.ok(promise);\n\n // If no error was thrown, logout was successful\n if (this.sudoId) {\n // User was logged out, so set auth back to default\n this.sudoId = '';\n this._sudoToken.reset();\n if (!this._authToken.isActive()) {\n await this.login();\n }\n } else {\n // completely logged out\n this.reset();\n }\n return true;\n }\n}\n"],"mappings":";;;;;;AAkCA,IAAAA,OAAA,GAAAC,OAAA;AAMA,IAAAC,cAAA,GAAAD,OAAA;AAAgD,SAAAE,mBAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,GAAA,EAAAC,GAAA,cAAAC,IAAA,GAAAP,GAAA,CAAAK,GAAA,EAAAC,GAAA,OAAAE,KAAA,GAAAD,IAAA,CAAAC,KAAA,WAAAC,KAAA,IAAAP,MAAA,CAAAO,K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MAAI,CAAC/C,UAAU,CAACiB,KAAK,CAAC,CAAC;QACvB,IAAI,CAAC8B,MAAI,CAAC7C,UAAU,CAACG,QAAQ,CAAC,CAAC,EAAE;UAC/B,MAAM0C,MAAI,CAAC/B,KAAK,CAAC,CAAC;QACpB;MACF,CAAC,MAAM;QAEL+B,MAAI,CAAC9B,KAAK,CAAC,CAAC;MACd;MACA,OAAO,IAAI;IAAC;EACd;AACF;AAAC+B,OAAA,CAAAxD,WAAA,GAAAA,WAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"nodeSettings.js","names":["fs","_interopRequireWildcard","require","ini","_sdkRtl","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","ownKeys","keys","getOwnPropertySymbols","o","filter","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty","getOwnPropertyDescriptors","defineProperties","obj","key","value","_toPropertyKey","configurable","writable","_toPrimitive","String","Symbol","toPrimitive","TypeError","Number","getenv","exports","name","defaultValue","undefined","val","process","env","ApiConfig","contents","parse","ApiConfigSection","section","config","settings","Error","concat","api_version","console","warn","readEnvConfig","envPrefix","values","configMap","ApiConfigMap","envKey","unquote","readIniConfig","fileName","existsSync","readFileSync","NodeSettings","ApiSettings","constructor","DefaultSettings","readConfig","_section","NodeSettingsIniFile","sdkError","message","ValueSettings"],"sources":["../src/nodeSettings.ts"],"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 * as fs from 'fs';\nimport * as ini from 'ini';\nimport type { IApiSection, IApiSettings } from '@looker/sdk-rtl';\nimport {\n ApiConfigMap,\n ApiSettings,\n DefaultSettings,\n ValueSettings,\n sdkError,\n unquote,\n} from '@looker/sdk-rtl';\n\n/**\n * Read an environment key. Use defaultValue if it doesn't exist\n * @param {string} name Environment variable name\n * @param {string | undefined} defaultValue\n * @returns {string | undefined} The value of the environment variable if it exists, or defaultValue\n */\nexport const getenv = (\n name: string,\n defaultValue: string | undefined = undefined\n) => {\n const val = process.env[name];\n return val === undefined ? defaultValue : val;\n};\n\n/**\n * Complete .INI file parse results\n */\nexport interface IApiConfig {\n [key: string]: any;\n}\n\n/**\n * Parses `.ini` formatted content\n * @param contents formatted as an `.ini` file\n * @constructor\n */\nexport const ApiConfig = (contents: string): IApiConfig => ini.parse(contents);\n\n/**\n * Extract named or (default) first section from INI file\n * @param contents {string} Parameters formatted as an INI file\n * @param section {[key: string]: any;} Contents of INI section\n * @constructor\n */\nexport const ApiConfigSection = (\n contents: string,\n section?: string\n): IApiSection => {\n const config = ApiConfig(contents);\n if (!section) {\n // default to the first section if not specified\n section = Object.keys(config)[0];\n }\n const settings = config[section];\n if (!settings) {\n throw new Error(`No section named \"${section}\" was found`);\n }\n if (settings.api_version) {\n console.warn(\n 'api_version is no longer read from a configuration file by the SDK'\n );\n }\n return settings;\n};\n\n/**\n * A utility function that loads environment variables and maps them to the standard configuration values\n *\n * @returns the populated `IApiSection`, which may be empty\n */\nexport const readEnvConfig = (envPrefix: string) => {\n const values: IApiSection = {};\n const configMap = ApiConfigMap(envPrefix);\n Object.keys(configMap).forEach((key) => {\n const envKey = configMap[key];\n if (process.env[envKey] !== undefined) {\n // Value exists. Map environment variable keys to config variable keys\n const val = unquote(process.env[envKey]);\n values[key] = val;\n }\n });\n return values;\n};\n\n/**\n * A utility function that loads the configuration values from the specified file name and overrides them\n * with environment variable values, if the environment variables exist\n *\n * @param {string} fileName Name of configuration file to read\n * @param envPrefix environment variable prefix. Pass an empty string to skip environment reading.\n * @param {string} section Optional. Name of section of configuration file to read\n * @returns {IApiSection} containing the configuration values\n */\nexport const readIniConfig = (\n fileName: string,\n envPrefix: string,\n section?: string\n) => {\n // get environment variables\n let config = readEnvConfig(envPrefix);\n if (fileName && fs.existsSync(fileName)) {\n // override any config file settings with environment values if the environment value is set\n config = {\n ...ApiConfigSection(fs.readFileSync(fileName, 'utf8'), section),\n ...config,\n };\n }\n // Unquote any quoted configuration values\n Object.keys(config).forEach((key) => {\n const val = config[key];\n if (typeof val === 'string') {\n config[key] = unquote(val);\n }\n });\n return config;\n};\n\n/**\n * Read configuration settings from Node environment variables\n *\n * This class initializes SDK settings **only** from the values passed in to its constructor and\n * (potentially) configured environment variables, and does not read a configuration file at all\n *\n * Any environment variables that **are** set, will override the values passed in to the constructor\n * with the same key\n *\n */\nexport class NodeSettings extends ApiSettings {\n protected readonly envPrefix!: string;\n public section: string;\n\n /**\n * Initialize config settings for the node SDK runtime\n * @param envPrefix Environment variable name prefix. Use empty string to not read the environment\n * @param contents contents of the read config\n * @param section name of ini section to process\n */\n constructor(\n envPrefix: string,\n contents?: string | IApiSettings,\n section?: string\n ) {\n let settings: IApiSettings;\n if (contents) {\n if (typeof contents === 'string') {\n settings = ApiConfigSection(contents, section) as IApiSettings;\n } else {\n settings = contents;\n }\n settings = { ...readEnvConfig(envPrefix), ...settings };\n } else {\n settings = readEnvConfig(envPrefix) as IApiSettings;\n }\n super({ ...DefaultSettings(), ...settings });\n this.section = section ?? '';\n this.envPrefix = envPrefix;\n }\n\n /**\n * **NOTE**: If `envPrefix` is defined in the constructor, environment variables will be read in this call.\n *\n * @param _section section name is ignored here.\n */\n readConfig(_section?: string): IApiSection {\n return readEnvConfig(this.envPrefix);\n }\n}\n\n/**\n * Example class that reads a configuration from a file in node\n *\n * If `fileName` is not specified in the constructor, the default file name is `./looker.ini`\n *\n * **Warning**: `.ini` files storing credentials should be secured in the run-time environment, and\n * ignored by version control systems so credentials never get checked in to source code repositories.\n * A recommended pattern is using Node environment variables to specify confidential API credentials\n * while using an `.ini` file for values like `base_url`.\n *\n * **Note**: If the configuration file is specified but does **not** exist, an error will be thrown.\n * No error is thrown if the fileName defaulted to `./looker.ini` inside the constructor and that\n * file does not exist. In that case, configuration from environment variables will be required.\n *\n */\nexport class NodeSettingsIniFile extends NodeSettings {\n private readonly fileName!: string;\n\n constructor(envPrefix: string, fileName = '', section?: string) {\n if (fileName && !fs.existsSync(fileName)) {\n throw sdkError({ message: `File ${fileName} was not found` });\n }\n // default fileName to looker.ini\n fileName = fileName || './looker.ini';\n const config = readIniConfig(fileName, envPrefix, section);\n const settings = ValueSettings(config, envPrefix);\n super(envPrefix, settings, section);\n this.fileName = fileName;\n }\n\n /**\n * Read a configuration section and return it as a generic keyed collection\n * If the configuration file doesn't exist, environment variables will be used for the values\n * Environment variables, if set, also override the configuration file values\n *\n * **NOTE**: If `envPrefix` is defined in the constructor, environment variables will be read in this call.\n *\n * @param section {string} Name of Ini section to read. Optional. Defaults to first section.\n *\n */\n readConfig(section?: string): IApiSection {\n section = section || this.section;\n return readIniConfig(this.fileName, this.envPrefix, section);\n }\n}\n"],"mappings":";;;;;;AA0BA,IAAAA,EAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,GAAA,GAAAF,uBAAA,CAAAC,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AAOyB,SAAAG,yBAA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,SAAA,MAAG,EAAE;IAAA,IAAE8B,OAAgB,GAAA9B,SAAA,CAAAC,MAAA,OAAAD,SAAA,MAAAsB,SAAA;IAC5D,IAAIwB,QAAQ,IAAI,CAACjF,EAAE,CAACkF,UAAU,CAACD,QAAQ,CAAC,EAAE;MACxC,MAAM,IAAAU,gBAAQ,EAAC;QAAEC,OAAO,UAAAvB,MAAA,CAAUY,QAAQ;MAAiB,CAAC,CAAC;IAC/D;IAEAA,QAAQ,GAAGA,QAAQ,IAAI,cAAc;IACrC,IAAMf,MAAM,GAAGc,aAAa,CAACC,QAAQ,EAAEP,SAAS,EAAET,OAAO,CAAC;IAC1D,IAAME,QAAQ,GAAG,IAAA0B,qBAAa,EAAC3B,MAAM,EAAEQ,SAAS,CAAC;IACjD,KAAK,CAACA,SAAS,EAAEP,QAAQ,EAAEF,OAAO,CAAC;IAAC3B,eAAA;IACpC,IAAI,CAAC2C,QAAQ,GAAGA,QAAQ;EAC1B;EAYAO,UAAUA,CAACvB,OAAgB,EAAe;IACxCA,OAAO,GAAGA,OAAO,IAAI,IAAI,CAACA,OAAO;IACjC,OAAOe,aAAa,CAAC,IAAI,CAACC,QAAQ,EAAE,IAAI,CAACP,SAAS,EAAET,OAAO,CAAC;EAC9D;AACF;AAACX,OAAA,CAAAoC,mBAAA,GAAAA,mBAAA"}
1
+ {"version":3,"file":"nodeSettings.js","names":["fs","_interopRequireWildcard","require","ini","_sdkRtl","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","ownKeys","keys","getOwnPropertySymbols","o","filter","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty","getOwnPropertyDescriptors","defineProperties","obj","key","value","_toPropertyKey","configurable","writable","_toPrimitive","String","Symbol","toPrimitive","TypeError","Number","getenv","exports","name","defaultValue","undefined","val","process","env","ApiConfig","contents","parse","ApiConfigSection","section","config","settings","Error","concat","api_version","console","warn","readEnvConfig","envPrefix","values","configMap","ApiConfigMap","envKey","unquote","readIniConfig","fileName","existsSync","readFileSync","NodeSettings","ApiSettings","constructor","DefaultSettings","readConfig","_section","NodeSettingsIniFile","sdkError","message","ValueSettings"],"sources":["../src/nodeSettings.ts"],"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 * as fs from 'fs';\nimport * as ini from 'ini';\nimport type { IApiSection, IApiSettings } from '@looker/sdk-rtl';\nimport {\n ApiConfigMap,\n ApiSettings,\n DefaultSettings,\n ValueSettings,\n sdkError,\n unquote,\n} from '@looker/sdk-rtl';\n\n/**\n * Read an environment key. Use defaultValue if it doesn't exist\n * @param {string} name Environment variable name\n * @param {string | undefined} defaultValue\n * @returns {string | undefined} The value of the environment variable if it exists, or defaultValue\n */\nexport const getenv = (\n name: string,\n defaultValue: string | undefined = undefined\n) => {\n const val = process.env[name];\n return val === undefined ? defaultValue : val;\n};\n\n/**\n * Complete .INI file parse results\n */\nexport interface IApiConfig {\n [key: string]: any;\n}\n\n/**\n * Parses `.ini` formatted content\n * @param contents formatted as an `.ini` file\n * @constructor\n */\nexport const ApiConfig = (contents: string): IApiConfig => ini.parse(contents);\n\n/**\n * Extract named or (default) first section from INI file\n * @param contents {string} Parameters formatted as an INI file\n * @param section {[key: string]: any;} Contents of INI section\n * @constructor\n */\nexport const ApiConfigSection = (\n contents: string,\n section?: string\n): IApiSection => {\n const config = ApiConfig(contents);\n if (!section) {\n // default to the first section if not specified\n section = Object.keys(config)[0];\n }\n const settings = config[section];\n if (!settings) {\n throw new Error(`No section named \"${section}\" was found`);\n }\n if (settings.api_version) {\n console.warn(\n 'api_version is no longer read from a configuration file by the SDK'\n );\n }\n return settings;\n};\n\n/**\n * A utility function that loads environment variables and maps them to the standard configuration values\n *\n * @returns the populated `IApiSection`, which may be empty\n */\nexport const readEnvConfig = (envPrefix: string) => {\n const values: IApiSection = {};\n const configMap = ApiConfigMap(envPrefix);\n Object.keys(configMap).forEach(key => {\n const envKey = configMap[key];\n if (process.env[envKey] !== undefined) {\n // Value exists. Map environment variable keys to config variable keys\n const val = unquote(process.env[envKey]);\n values[key] = val;\n }\n });\n return values;\n};\n\n/**\n * A utility function that loads the configuration values from the specified file name and overrides them\n * with environment variable values, if the environment variables exist\n *\n * @param {string} fileName Name of configuration file to read\n * @param envPrefix environment variable prefix. Pass an empty string to skip environment reading.\n * @param {string} section Optional. Name of section of configuration file to read\n * @returns {IApiSection} containing the configuration values\n */\nexport const readIniConfig = (\n fileName: string,\n envPrefix: string,\n section?: string\n) => {\n // get environment variables\n let config = readEnvConfig(envPrefix);\n if (fileName && fs.existsSync(fileName)) {\n // override any config file settings with environment values if the environment value is set\n config = {\n ...ApiConfigSection(fs.readFileSync(fileName, 'utf8'), section),\n ...config,\n };\n }\n // Unquote any quoted configuration values\n Object.keys(config).forEach(key => {\n const val = config[key];\n if (typeof val === 'string') {\n config[key] = unquote(val);\n }\n });\n return config;\n};\n\n/**\n * Read configuration settings from Node environment variables\n *\n * This class initializes SDK settings **only** from the values passed in to its constructor and\n * (potentially) configured environment variables, and does not read a configuration file at all\n *\n * Any environment variables that **are** set, will override the values passed in to the constructor\n * with the same key\n *\n */\nexport class NodeSettings extends ApiSettings {\n protected readonly envPrefix!: string;\n public section: string;\n\n /**\n * Initialize config settings for the node SDK runtime\n * @param envPrefix Environment variable name prefix. Use empty string to not read the environment\n * @param contents contents of the read config\n * @param section name of ini section to process\n */\n constructor(\n envPrefix: string,\n contents?: string | IApiSettings,\n section?: string\n ) {\n let settings: IApiSettings;\n if (contents) {\n if (typeof contents === 'string') {\n settings = ApiConfigSection(contents, section) as IApiSettings;\n } else {\n settings = contents;\n }\n settings = { ...readEnvConfig(envPrefix), ...settings };\n } else {\n settings = readEnvConfig(envPrefix) as IApiSettings;\n }\n super({ ...DefaultSettings(), ...settings });\n this.section = section ?? '';\n this.envPrefix = envPrefix;\n }\n\n /**\n * **NOTE**: If `envPrefix` is defined in the constructor, environment variables will be read in this call.\n *\n * @param _section section name is ignored here.\n */\n readConfig(_section?: string): IApiSection {\n return readEnvConfig(this.envPrefix);\n }\n}\n\n/**\n * Example class that reads a configuration from a file in node\n *\n * If `fileName` is not specified in the constructor, the default file name is `./looker.ini`\n *\n * **Warning**: `.ini` files storing credentials should be secured in the run-time environment, and\n * ignored by version control systems so credentials never get checked in to source code repositories.\n * A recommended pattern is using Node environment variables to specify confidential API credentials\n * while using an `.ini` file for values like `base_url`.\n *\n * **Note**: If the configuration file is specified but does **not** exist, an error will be thrown.\n * No error is thrown if the fileName defaulted to `./looker.ini` inside the constructor and that\n * file does not exist. In that case, configuration from environment variables will be required.\n *\n */\nexport class NodeSettingsIniFile extends NodeSettings {\n private readonly fileName!: string;\n\n constructor(envPrefix: string, fileName = '', section?: string) {\n if (fileName && !fs.existsSync(fileName)) {\n throw sdkError({ message: `File ${fileName} was not found` });\n }\n // default fileName to looker.ini\n fileName = fileName || './looker.ini';\n const config = readIniConfig(fileName, envPrefix, section);\n const settings = ValueSettings(config, envPrefix);\n super(envPrefix, settings, section);\n this.fileName = fileName;\n }\n\n /**\n * Read a configuration section and return it as a generic keyed collection\n * If the configuration file doesn't exist, environment variables will be used for the values\n * Environment variables, if set, also override the configuration file values\n *\n * **NOTE**: If `envPrefix` is defined in the constructor, environment variables will be read in this call.\n *\n * @param section {string} Name of Ini section to read. Optional. Defaults to first section.\n *\n */\n readConfig(section?: string): IApiSection {\n section = section || this.section;\n return readIniConfig(this.fileName, this.envPrefix, section);\n }\n}\n"],"mappings":";;;;;;AA0BA,IAAAA,EAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,GAAA,GAAAF,uBAAA,CAAAC,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AAOyB,SAAAG,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,yBAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAL,wBAAAK,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAjB,CAAA,EAAAc,CAAA,SAAAI,CAAA,GAAAR,CAAA,GAAAC,MAAA,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CAACP,SAAS,EAAET,OAAO,CAAC;EAC9D;AACF;AAACX,OAAA,CAAAoC,mBAAA,GAAAA,mBAAA"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+
3
+ var _nodeTest = require("node:test");
4
+ var _expect = require("expect");
5
+ var _sdkRtl = require("@looker/sdk-rtl");
6
+ var _nodeTransport = require("./nodeTransport");
7
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
8
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
9
+ (0, _nodeTest.describe)('NodeTransport', () => {
10
+ var hostname = 'https://looker.sdk';
11
+ var settings = {
12
+ base_url: hostname
13
+ };
14
+ var xp = new _nodeTransport.NodeTransport(settings);
15
+ var fullPath = 'https://github.com/looker-open-source/sdk-codegen';
16
+ var badPath = fullPath + '_bogus';
17
+ (0, _nodeTest.it)('raw request retrieves fully qualified url', _asyncToGenerator(function* () {
18
+ var response = yield xp.rawRequest('GET', fullPath);
19
+ (0, _expect.expect)(response).toBeDefined();
20
+ (0, _expect.expect)(response.ok).toEqual(true);
21
+ (0, _expect.expect)(response.method).toEqual('GET');
22
+ (0, _expect.expect)(response.statusCode).toEqual(200);
23
+ (0, _expect.expect)(response.statusMessage).toEqual('OK');
24
+ (0, _expect.expect)(response.contentType).toContain('text/html');
25
+ (0, _expect.expect)(response.body).toBeDefined();
26
+ var html = yield response.body;
27
+ (0, _expect.expect)(html).toContain('One SDK to rule them all, and in the codegen bind them');
28
+ }));
29
+ (0, _nodeTest.describe)('transport errors', () => {
30
+ (0, _nodeTest.it)('gracefully handles transport errors', _asyncToGenerator(function* () {
31
+ var response = yield xp.rawRequest('GET', badPath);
32
+ var errorMessage = 'Not Found';
33
+ (0, _expect.expect)(response).toBeDefined();
34
+ (0, _expect.expect)(response.ok).toEqual(false);
35
+ (0, _expect.expect)(response.method).toEqual('GET');
36
+ (0, _expect.expect)(response.statusCode).toEqual(404);
37
+ (0, _expect.expect)(response.body).toBeDefined();
38
+ (0, _expect.expect)(response.statusMessage).toEqual(errorMessage);
39
+ }));
40
+ });
41
+ (0, _nodeTest.it)('retrieves fully qualified url', _asyncToGenerator(function* () {
42
+ var response = yield xp.request('GET', fullPath);
43
+ (0, _expect.expect)(response).toBeDefined();
44
+ (0, _expect.expect)(response.ok).toEqual(true);
45
+ if (response.ok) {
46
+ var content = response.value;
47
+ (0, _expect.expect)(content).toContain('One SDK to rule them all, and in the codegen bind them');
48
+ }
49
+ }));
50
+ (0, _nodeTest.describe)('ok check', () => {
51
+ var raw = {
52
+ method: 'GET',
53
+ contentType: 'application/json',
54
+ headers: {},
55
+ url: 'bogus',
56
+ ok: true,
57
+ statusCode: _sdkRtl.StatusCode.OK,
58
+ statusMessage: 'Mocked success',
59
+ body: 'body',
60
+ requestStarted: 1000,
61
+ responseCompleted: 2000
62
+ };
63
+ (0, _nodeTest.it)('ok is ok', () => {
64
+ (0, _expect.expect)(xp.ok(raw)).toEqual(true);
65
+ });
66
+ (0, _nodeTest.it)('All 2xx responses are ok', () => {
67
+ raw.statusCode = _sdkRtl.StatusCode.IMUsed;
68
+ (0, _expect.expect)(xp.ok(raw)).toEqual(true);
69
+ });
70
+ (0, _nodeTest.it)('Non-2xx responses are not ok', () => {
71
+ raw.statusCode = 422;
72
+ (0, _expect.expect)(xp.ok(raw)).toEqual(false);
73
+ });
74
+ });
75
+ (0, _nodeTest.it)('does a standard get', _asyncToGenerator(function* () {
76
+ var xp = new _nodeTransport.NodeTransport({});
77
+ var actual = yield xp.rawRequest('GET', 'https://example.com');
78
+ (0, _expect.expect)(actual).toBeDefined();
79
+ }));
80
+ (0, _nodeTest.it)('just deserializes JSON into an object', _asyncToGenerator(function* () {
81
+ var xp = new _nodeTransport.NodeTransport({});
82
+ var resp = {
83
+ headers: {},
84
+ url: '',
85
+ ok: true,
86
+ contentType: 'application/json',
87
+ statusCode: 200,
88
+ statusMessage: 'mock',
89
+ method: 'GET',
90
+ body: "\n{\n \"string1\": 1,\n \"num1\": 1,\n \"string2\": \"2\",\n \"num2\": \"2\",\n \"string3\": \"3\",\n \"num3\": 3,\n \"string4\": \"4\",\n \"num4\": 4\n}\n",
91
+ requestStarted: 1000,
92
+ responseCompleted: 2000
93
+ };
94
+ var untyped = yield (0, _sdkRtl.sdkOk)(xp.parseResponse(resp));
95
+ (0, _expect.expect)(untyped.string1).toBe(1);
96
+ (0, _expect.expect)(untyped.num1).toBe(1);
97
+ (0, _expect.expect)(untyped.string2).toBe('2');
98
+ (0, _expect.expect)(untyped.num2).toBe('2');
99
+ (0, _expect.expect)(untyped.string3).toBe('3');
100
+ (0, _expect.expect)(untyped.num3).toBe(3);
101
+ (0, _expect.expect)(untyped.string4).toBe('4');
102
+ (0, _expect.expect)(untyped.num4).toBe(4);
103
+ var typed = yield (0, _sdkRtl.sdkOk)(xp.parseResponse(resp));
104
+ (0, _expect.expect)(typed.string1).toBe(1);
105
+ (0, _expect.expect)(typed.num1).toBe(1);
106
+ (0, _expect.expect)(typed.string2).toBe('2');
107
+ (0, _expect.expect)(typed.num2).toBe('2');
108
+ (0, _expect.expect)(typed.string3).toBe('3');
109
+ (0, _expect.expect)(typed.num3).toBe(3);
110
+ (0, _expect.expect)(typed.string4).toBe('4');
111
+ (0, _expect.expect)(typed.num4).toBe(4);
112
+ }));
113
+ (0, _nodeTest.describe)('NodeCryptoHash', () => {
114
+ (0, _nodeTest.it)('secureRandom', () => {
115
+ var hasher = new _nodeTransport.NodeCryptoHash();
116
+ var rand1 = hasher.secureRandom(5);
117
+ (0, _expect.expect)(rand1.length).toEqual(10);
118
+ var rand2 = hasher.secureRandom(32);
119
+ (0, _expect.expect)(rand2.length).toEqual(64);
120
+ });
121
+ (0, _nodeTest.it)('sha256hash', _asyncToGenerator(function* () {
122
+ var hasher = new _nodeTransport.NodeCryptoHash();
123
+ var message = 'The quick brown fox jumped over the lazy dog.';
124
+ var hash = yield hasher.sha256Hash(message);
125
+ (0, _expect.expect)(hash).toEqual('aLEoK5HeLAVMNmKcuN1EfxLwltPjxYeXjcIkhERjNIM=');
126
+ }));
127
+ });
128
+ });
129
+ //# sourceMappingURL=nodeTransport.apitest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodeTransport.apitest.js","names":["_nodeTest","require","_expect","_sdkRtl","_nodeTransport","asyncGeneratorStep","gen","resolve","reject","_next","_throw","key","arg","info","value","error","done","Promise","then","_asyncToGenerator","fn","self","args","arguments","apply","err","undefined","describe","hostname","settings","base_url","xp","NodeTransport","fullPath","badPath","it","response","rawRequest","expect","toBeDefined","ok","toEqual","method","statusCode","statusMessage","contentType","toContain","body","html","errorMessage","request","content","raw","headers","url","StatusCode","OK","requestStarted","responseCompleted","IMUsed","actual","resp","untyped","sdkOk","parseResponse","string1","toBe","num1","string2","num2","string3","num3","string4","num4","typed","hasher","NodeCryptoHash","rand1","secureRandom","length","rand2","message","hash","sha256Hash"],"sources":["../src/nodeTransport.apitest.ts"],"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 { describe, it } from 'node:test';\nimport { expect } from 'expect';\nimport type {\n IRawResponse,\n ISDKError,\n ITransportSettings,\n} from '@looker/sdk-rtl';\nimport { StatusCode, sdkOk } from '@looker/sdk-rtl';\nimport { NodeCryptoHash, NodeTransport } from './nodeTransport';\n\ndescribe('NodeTransport', () => {\n const hostname = 'https://looker.sdk';\n const settings = { base_url: hostname } as ITransportSettings;\n const xp = new NodeTransport(settings);\n const fullPath = 'https://github.com/looker-open-source/sdk-codegen';\n const badPath = fullPath + '_bogus';\n // const queryParams = { a: 'b c', d: false, nil: null, skip: undefined }\n\n it('raw request retrieves fully qualified url', async () => {\n const response = await xp.rawRequest('GET', fullPath);\n expect(response).toBeDefined();\n expect(response.ok).toEqual(true);\n expect(response.method).toEqual('GET');\n expect(response.statusCode).toEqual(200);\n expect(response.statusMessage).toEqual('OK');\n expect(response.contentType).toContain('text/html');\n expect(response.body).toBeDefined();\n const html = await response.body;\n expect(html).toContain(\n 'One SDK to rule them all, and in the codegen bind them'\n );\n });\n\n describe('transport errors', () => {\n it('gracefully handles transport errors', async () => {\n const response = await xp.rawRequest('GET', badPath);\n const errorMessage = 'Not Found';\n expect(response).toBeDefined();\n expect(response.ok).toEqual(false);\n expect(response.method).toEqual('GET');\n expect(response.statusCode).toEqual(404);\n expect(response.body).toBeDefined();\n expect(response.statusMessage).toEqual(errorMessage);\n });\n });\n\n it('retrieves fully qualified url', async () => {\n const response = await xp.request<string, Error>('GET', fullPath);\n expect(response).toBeDefined();\n expect(response.ok).toEqual(true);\n if (response.ok) {\n const content = response.value;\n expect(content).toContain(\n 'One SDK to rule them all, and in the codegen bind them'\n );\n }\n });\n\n describe('ok check', () => {\n const raw: IRawResponse = {\n method: 'GET',\n contentType: 'application/json',\n headers: {},\n url: 'bogus',\n ok: true,\n statusCode: StatusCode.OK,\n statusMessage: 'Mocked success',\n body: 'body',\n requestStarted: 1000,\n responseCompleted: 2000,\n };\n\n it('ok is ok', () => {\n expect(xp.ok(raw)).toEqual(true);\n });\n\n it('All 2xx responses are ok', () => {\n raw.statusCode = StatusCode.IMUsed;\n expect(xp.ok(raw)).toEqual(true);\n });\n\n it('Non-2xx responses are not ok', () => {\n raw.statusCode = 422;\n expect(xp.ok(raw)).toEqual(false);\n });\n });\n\n it('does a standard get', async () => {\n const xp = new NodeTransport({} as ITransportSettings);\n const actual = await xp.rawRequest('GET', 'https://example.com');\n expect(actual).toBeDefined();\n });\n\n it('just deserializes JSON into an object', async () => {\n const xp = new NodeTransport({} as ITransportSettings);\n interface ITestModel {\n string1: string;\n num1: number;\n string2: string;\n num2: number;\n string3: string;\n num3: number;\n }\n const resp: IRawResponse = {\n headers: {},\n url: '',\n ok: true,\n contentType: 'application/json',\n statusCode: 200,\n statusMessage: 'mock',\n method: 'GET',\n body: `\n{\n \"string1\": 1,\n \"num1\": 1,\n \"string2\": \"2\",\n \"num2\": \"2\",\n \"string3\": \"3\",\n \"num3\": 3,\n \"string4\": \"4\",\n \"num4\": 4\n}\n`,\n requestStarted: 1000,\n responseCompleted: 2000,\n };\n const untyped: any = await sdkOk(xp.parseResponse(resp));\n expect(untyped.string1).toBe(1);\n expect(untyped.num1).toBe(1);\n expect(untyped.string2).toBe('2');\n expect(untyped.num2).toBe('2');\n expect(untyped.string3).toBe('3');\n expect(untyped.num3).toBe(3);\n expect(untyped.string4).toBe('4');\n expect(untyped.num4).toBe(4);\n const typed = await sdkOk(xp.parseResponse<ITestModel, ISDKError>(resp));\n expect(typed.string1).toBe(1);\n expect(typed.num1).toBe(1);\n expect(typed.string2).toBe('2');\n expect(typed.num2).toBe('2');\n expect(typed.string3).toBe('3');\n expect(typed.num3).toBe(3);\n expect((typed as any).string4).toBe('4');\n expect((typed as any).num4).toBe(4);\n });\n describe('NodeCryptoHash', () => {\n it('secureRandom', () => {\n const hasher = new NodeCryptoHash();\n const rand1 = hasher.secureRandom(5);\n expect(rand1.length).toEqual(10);\n const rand2 = hasher.secureRandom(32);\n expect(rand2.length).toEqual(64);\n });\n\n it('sha256hash', async () => {\n const hasher = new NodeCryptoHash();\n const message = 'The quick brown fox jumped over the lazy dog.';\n const hash = await hasher.sha256Hash(message);\n expect(hash).toEqual('aLEoK5HeLAVMNmKcuN1EfxLwltPjxYeXjcIkhERjNIM=');\n });\n });\n});\n"],"mappings":";;AA0BA,IAAAA,SAAA,GAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AAMA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,cAAA,GAAAH,OAAA;AAAgE,SAAAI,mBAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,GAAA,EAAAC,GAAA,cAAAC,IAAA,GAAAP,GAAA,CAAAK,GAAA,EAAAC,GAAA,OAAAE,KAAA,GAAAD,IAAA,CAAAC,KAAA,WAAAC,KAAA,IAAAP,MAAA,CAAAO,KAAA,iBAAAF,IAAA,CAAAG,IAAA,IAAAT,OAAA,CAAAO,KAAA,YAAAG,OAAA,CAAAV,OAAA,CAAAO,KAAA,EAAAI,IAAA,CAAAT,KAAA,EAAAC,MAAA;AAAA,SAAAS,kBAAAC,EAAA,6BAAAC,IAAA,SAAAC,IAAA,GAAAC,SAAA,aAAAN,OAAA,WAAAV,OAAA,EAAAC,MAAA,QAAAF,GAAA,GAAAc,EAAA,CAAAI,KAAA,CAAAH,IAAA,EAAAC,IAAA,YAAAb,MAAAK,KAAA,IAAAT,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,UA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M,GAAG,IAAIC,6BAAc,CAAC,CAAC;MACnC,IAAMK,OAAO,GAAG,+CAA+C;MAC/D,IAAMC,IAAI,SAASP,MAAM,CAACQ,UAAU,CAACF,OAAO,CAAC;MAC7C,IAAA3C,cAAM,EAAC4C,IAAI,CAAC,CAACzC,OAAO,CAAC,8CAA8C,CAAC;IACtE,CAAC,EAAC;EACJ,CAAC,CAAC;AACJ,CAAC,CAAC"}
@@ -1,23 +1,19 @@
1
- import type { Request } from 'request';
2
- import rq from 'request';
3
- import rp from 'request-promise-native';
4
- import type { Readable } from 'readable-stream';
1
+ import type * as fs from 'fs';
2
+ import type { Authenticator, HttpMethod, ICryptoHash, IRawRequest, IRawResponse, ITransportSettings, SDKResponse, Values } from '@looker/sdk-rtl';
5
3
  import { BaseTransport } from '@looker/sdk-rtl';
6
- import type { Authenticator, HttpMethod, ICryptoHash, IRawResponse, ITransportSettings, SDKResponse, Values } from '@looker/sdk-rtl';
4
+ import { WritableStream } from 'node:stream/web';
7
5
  export declare class NodeCryptoHash implements ICryptoHash {
8
6
  secureRandom(byteCount: number): string;
9
7
  sha256Hash(message: string): Promise<string>;
10
8
  }
11
- export type RequestOptions = rq.RequiredUriUrl & rp.RequestPromiseOptions & rq.OptionsWithUrl;
12
9
  export declare class NodeTransport extends BaseTransport {
13
10
  protected readonly options: ITransportSettings;
14
11
  constructor(options: ITransportSettings);
12
+ retry(request: IRawRequest): Promise<IRawResponse>;
15
13
  rawRequest(method: HttpMethod, path: string, queryParams?: Values, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings>): Promise<IRawResponse>;
16
14
  parseResponse<TSuccess, TError>(res: IRawResponse): Promise<SDKResponse<TSuccess, TError>>;
17
15
  request<TSuccess, TError>(method: HttpMethod, path: string, queryParams?: Values, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings>): Promise<SDKResponse<TSuccess, TError>>;
18
- protected requestor(props: RequestOptions): Request;
19
- stream<TSuccess>(callback: (readable: Readable) => Promise<TSuccess>, method: HttpMethod, path: string, queryParams?: Values, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings>): Promise<TSuccess>;
20
- verifySsl(options?: Partial<ITransportSettings>): boolean | undefined;
21
- timeout(options?: Partial<ITransportSettings>): number;
22
- private initRequest;
16
+ stream<TSuccess>(callback: (response: Response) => Promise<TSuccess>, method: HttpMethod, path: string, queryParams?: Values, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings>): Promise<TSuccess>;
17
+ protected initRequest(method: HttpMethod, path: string, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings>): Promise<import("@looker/sdk-rtl").IRequestProps>;
23
18
  }
19
+ export declare const createWritableStream: (writer: ReturnType<typeof fs.createWriteStream>) => WritableStream<any>;