@shaggytools/nhtsa-api-wrapper
Version:
Universal javascript wrapper for the NHTSA.dot.gov VPIC 'vehicles' API, useful for VIN decoding, etc.
3 lines (2 loc) • 13.6 kB
JavaScript
var NHTSA=function(s){"use strict";const C=({name:e,value:t,required:n,types:r,errorMode:c="error"})=>{if(v(e)!=="string")throw Error("'name', is required and must be of type string");let a="";const o=v(t),i=`error validating argument named "${e}",`,h=`received value: ${t} - of type: <${o}>`;if(r&&(v(r)!=="array"||!r.length))throw Error(`${i} 'types' must be an array of strings`);const u=r?`<${r.join(" | ")}>`:"";if(n&&!r?t||(a=`${i} is required, ${h}`):r&&!n?t!==void 0&&!r.includes(o)&&(a=`${i} must be of type(s) ${u}, ${h}`):n&&r&&(!t||!r.includes(o))&&(a=`${i} is required and must be of type(s) ${u}, ${h}`),a.length){if(c==="boolean")return!1;throw Error(a)}return!0},l=({args:e,mode:t="default"})=>{if(v(e)!=="array"||!e.length)throw Error('catchInvalidArguments requires "args" that must be an array of IArgToValidate objects');if(t==="default")e.forEach(n=>C(n));else if(t==="atLeast"&&!e.find(r=>!!r.value))throw Error(`must provide at least one of the following arguments: ${e.map(r=>r.name).join(", ")}`);return!0},q=e=>v(e)==="error",N=e=>{let t="an unknown error occurred.";return q(e)?(e.message||(e.message=t),e):(v(e)==="string"&&(t=e),Error(t))},d=async e=>Promise.reject(N(e)),v=e=>{const t=Object.prototype.toString.call(e).toLowerCase();return t.slice(8,t.length-1)},I={A:1,B:2,C:3,D:4,E:5,F:6,G:7,H:8,J:1,K:2,L:3,M:4,N:5,P:7,R:9,S:2,T:3,U:4,V:5,W:6,X:7,Y:8,Z:9},$=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];function j(e){if(typeof e!="string"||e.length!=17)return!1;e=e.toUpperCase();const t=e.split(""),n=t[8];if(isNaN(parseInt(n))&&n!=="X")return!1;const r=n==="X"?10:parseInt(n);return t.map((a,o)=>{let i;isNaN(parseInt(a))?i=I[a]:i=parseInt(a);const h=$[o];return i*h}).reduce((a,o)=>a+o,0)%11===r}const A="https://vpic.nhtsa.dot.gov/api/vehicles",G="json",V=e=>(C({name:"params",value:e,required:!0,types:["object"]}),Object.entries(e).filter(([n,r])=>C({name:n,types:["string","number","boolean"],value:r,errorMode:"boolean"})).reduce((n,[r,c])=>(n[r]=encodeURIComponent(c),n),{})),T=(e={},t=!1)=>{C({name:"params",value:e,types:["object"]});const n=V({...e,format:G});return"?"+Object.entries(n).map(([r,c],a,o)=>c.length||t&&c===""?`${r}=${c}${a<o.length-1?"&":""}`:"").join("")};async function E(e,t,n=!0){const r="DecodeVin";try{typeof t=="boolean"&&(n=t,t=void 0);const c=[{name:"vin",value:e,required:!0,types:["string"]},{name:"params",value:t,types:["object"]},{name:"modelYear",value:t==null?void 0:t.modelYear,types:["string","number"]}];l({args:c});const{get:a,createCachedUrl:o,getCachedUrl:i}=g();return o({endpointName:r,path:e,params:t}),n?a():i()}catch(c){return d(c)}}async function S(e,t,n=!0){const r="DecodeVinExtended";try{typeof t=="boolean"&&(n=t,t=void 0);const c=[{name:"vin",value:e,required:!0,types:["string"]},{name:"params",value:t,types:["object"]},{name:"modelYear",value:t==null?void 0:t.modelYear,types:["string","number"]}];l({args:c});const{get:a,createCachedUrl:o,getCachedUrl:i}=g();return o({endpointName:r,path:e,params:t}),n?a():i()}catch(c){return d(c)}}async function D(e,t,n=!0){const r="DecodeVinValues";try{typeof t=="boolean"&&(n=t,t=void 0);const c=[{name:"vin",value:e,required:!0,types:["string"]},{name:"params",value:t,types:["object"]},{name:"modelYear",value:t==null?void 0:t.modelYear,types:["string","number"]}];l({args:c});const{get:a,createCachedUrl:o,getCachedUrl:i}=g();return o({endpointName:r,path:e,params:t}),n?a():i()}catch(c){return d(c)}}async function Y(e,t=!0){const n="DecodeVinValuesBatch";try{l({args:[{name:"inputString",value:e,required:!0,types:["string"]}]});const{post:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,includeQueryString:!1}),t?c(o(),{body:e}):o()}catch(r){return d(r)}}async function F(e,t,n=!0){const r="DecodeVinValuesExtended";try{typeof t=="boolean"&&(n=t,t=void 0);const c=[{name:"vin",value:e,required:!0,types:["string"]},{name:"params",value:t,types:["object"]},{name:"modelYear",value:t==null?void 0:t.modelYear,types:["string","number"]}];l({args:c});const{get:a,createCachedUrl:o,getCachedUrl:i}=g();return o({endpointName:r,path:e,params:t}),n?a():i()}catch(c){return d(c)}}async function w(e,t=!0){const n="DecodeWMI";try{l({args:[{name:"WMI",value:e,required:!0,types:["string"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e}),t?c():o()}catch(r){return d(r)}}async function P(e=!0){const t="GetAllMakes";try{const{get:n,createCachedUrl:r,getCachedUrl:c}=g();return r({endpointName:t}),e?n():c()}catch(n){return d(n)}}async function L(e,t=!0){const n="GetAllManufacturers";try{typeof e=="boolean"&&(t=e,e=void 0);const r=[{name:"params",value:e,types:["object"]},{name:"manufacturerType",value:e==null?void 0:e.manufacturerType,types:["string"]},{name:"page",value:e==null?void 0:e.page,types:["string","number"]}];l({args:r});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,params:e}),t?c():o()}catch(r){return d(r)}}async function R(e,t=!0){const n="GetCanadianVehicleSpecifications";try{const r=[{name:"params",value:e,required:!0,types:["object"]},{name:"year",value:e.year,required:!0,types:["string","number"]},{name:"make",value:e.make,types:["string"]},{name:"model",value:e.model,types:["string"]},{name:"units",value:e.units,types:["string"]}];l({args:r});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,params:{make:"",model:"",units:"",...e},allowEmptyParams:!0}),t?c():o()}catch(r){return d(r)}}async function O(e,t=!0){const n="GetEquipmentPlantCodes";try{const r=[{name:"params",value:e,required:!0,types:["object"]},{name:"equipmentType",value:e==null?void 0:e.equipmentType,required:!0,types:["string","number"]},{name:"reportType",value:e==null?void 0:e.reportType,required:!0,types:["string"]},{name:"year",value:e==null?void 0:e.year,required:!0,types:["string","number"]}];l({args:r});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,params:e}),t?c():o()}catch(r){return d(r)}}async function _(e,t=!0){const n="GetMakeForManufacturer";try{l({args:[{name:"manufacturer",value:e,required:!0,types:["string","number"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e.toString()}),t?c():o()}catch(r){return d(r)}}async function W(e,t,n=!0){const r="GetMakesForManufacturerAndYear";try{const c=[{name:"manufacturer",value:e,required:!0,types:["string","number"]},{name:"params",value:t,required:!0,types:["object"]},{name:"year",value:t.year,required:!0,types:["string","number"]}];l({args:c});const{get:a,createCachedUrl:o,getCachedUrl:i}=g();return o({endpointName:r,path:e.toString(),params:t}),n?a():i()}catch(c){return d(c)}}async function B(e,t=!0){const n="GetMakesForVehicleType";try{l({args:[{name:"typeName",value:e,required:!0,types:["string"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e}),t?c():o()}catch(r){return d(r)}}async function H(e,t=!0){const n="GetManufacturerDetails";try{l({args:[{name:"manufacturer",value:e,required:!0,types:["string","number"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e.toString()}),t?c():o()}catch(r){return d(r)}}async function Q(e,t=!0){const n="GetModelsForMake";try{l({args:[{name:"makeName",value:e,required:!0,types:["string"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e}),t?c():o()}catch(r){return d(r)}}async function J(e,t=!0){const n="GetModelsForMakeId";try{l({args:[{name:"makeId",value:e,required:!0,types:["string","number"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e.toString()}),t?c():o()}catch(r){return d(r)}}async function X(e,t=!0){const n="GetModelsForMakeIdYear";try{const r=[{name:"modelYear",value:e.modelYear,types:["string","number"]},{name:"vehicleType",value:e.vehicleType,types:["string"]}],c=[{name:"params",value:e,required:!0,types:["object"]},{name:"makeId",value:e.makeId,required:!0,types:["string","number"]},...r];l({args:c}),l({args:r,mode:"atLeast"});const{makeId:a,modelYear:o,vehicleType:i}=V(e);let h=`makeId/${a}/`;h+=o?`modelYear/${o}`:"",h+=i?`${o?"/":""}vehicleType/${i}`:"";const{get:u,createCachedUrl:y,getCachedUrl:m}=g();return y({endpointName:n,path:h}),t?u():m()}catch(r){return d(r)}}async function K(e,t=!0){const n="GetModelsForMakeYear";try{const r=[{name:"modelYear",value:e.modelYear,types:["string","number"]},{name:"vehicleType",value:e.vehicleType,types:["string"]}],c=[{name:"params",value:e,required:!0,types:["object"]},{name:"make",value:e.make,required:!0,types:["string"]},...r];l({args:c}),l({args:r,mode:"atLeast"});const{make:a,modelYear:o,vehicleType:i}=V(e);let h=`make/${a}/`;h+=o?`modelYear/${o}`:"",h+=i?`${o?"/":""}vehicleType/${i}`:"";const{get:u,createCachedUrl:y,getCachedUrl:m}=g();return y({endpointName:n,path:h}),t?u():m()}catch(r){return d(r)}}async function Z(e,t=!0){const n="GetParts";typeof e=="boolean"&&(t=e,e=void 0);try{const r=[{name:"params",value:e,types:["object"]},{name:"manufacturer",value:e==null?void 0:e.manufacturer,types:["string","number"]},{name:"type",value:e==null?void 0:e.type,types:["number"]},{name:"fromDate",value:e==null?void 0:e.fromDate,types:["string"]},{name:"toDate",value:e==null?void 0:e.toDate,types:["string"]},{name:"page",value:e==null?void 0:e.page,types:["string","number"]}];l({args:r});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,params:e}),t?c():o()}catch(r){return d(r)}}async function z(e,t=!0){const n="GetVehicleTypesForMake";try{l({args:[{name:"makeName",value:e,required:!0,types:["string"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e}),t?c():o()}catch(r){return d(r)}}async function x(e,t=!0){const n="GetVehicleTypesForMakeId";try{l({args:[{name:"makeId",value:e,required:!0,types:["string","number"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e.toString()}),t?c():o()}catch(r){return d(r)}}async function ee(e=!0){const t="GetVehicleVariableList";try{const{get:n,createCachedUrl:r,getCachedUrl:c}=g();return r({endpointName:t}),e?n():c()}catch(n){return d(n)}}async function te(e,t=!0){const n="GetVehicleVariableValuesList";try{l({args:[{name:"variableValue",value:e,required:!0,types:["string","number"]}]});const{get:c,createCachedUrl:a,getCachedUrl:o}=g();return a({endpointName:n,path:e.toString()}),t?c():o()}catch(r){return d(r)}}async function re(e,t=!0){const n="GetWMIsForManufacturer";try{const r=[{name:"manufacturer",value:e==null?void 0:e.manufacturer,types:["string","number"]},{name:"vehicleType",value:e==null?void 0:e.vehicleType,types:["string","number"]}],c=[{name:"params",value:e,required:!0,types:["object"]},...r];l({args:c}),l({args:r,mode:"atLeast"});const a=e!=null&&e.manufacturer?encodeURIComponent(e.manufacturer):"",o=(e==null?void 0:e.vehicleType)||"",{get:i,createCachedUrl:h,getCachedUrl:u}=g();return h({endpointName:n,path:a,params:{vehicleType:o}}),t?i():u()}catch(r){return d(r)}}const g=()=>{let e;const t=u=>e=u,n=()=>e,r=()=>e="",c=u=>{if(typeof u=="string")return t(u),u;const{endpointName:y,allowEmptyParams:m=!1,includeQueryString:f=!0,path:b="",params:U,saveUrl:k=!0}=u;if(!y)throw Error("Endpoint name is required to create a VPIC URL string");const p=f?T(U,m):"",M=encodeURI(`${A}/${y}/${b}${p}`);return k&&t(M),M},a=u=>c({...u,saveUrl:!1}),o=u=>encodeURI(`DATA=${u?u+"&":""}format=${G}`),i=async(u,y={saveUrl:!0,method:"GET"})=>(u&&v(u)==="object"&&(u=c({...u,saveUrl:y.saveUrl})),u=v(u)==="string"?u:n(),l({args:[{name:"url",value:u,required:!0,types:["string"]},{name:"options",value:y,types:["object"]}]}),y.saveUrl&&(e=u),await fetch(u,y).then(async f=>{if(!f)throw Error("APi responded with an error, no response object returned");const b=f.headers.get("content-type"),U=`content-type: ${b}, responseStatus: ${f.status}, responseUrl: ${f.url}`;if(!f.ok)throw Error(`APi response not ok, got ${U}`);if(!["application/json","text/json"].some(ne=>b==null?void 0:b.includes(ne))||typeof f.json!="function")throw Error(`API response not in JSON format, got ${U}`);const M=await f.json();if(M)return M;throw Error(`VPIC API returned no data, got ${U}`)}).catch(f=>(f.message=`There was an error fetching API data: ${f.message}`,d(f))));return{setCachedUrl:t,getCachedUrl:n,clearCachedUrl:r,createCachedUrl:c,createUrl:a,createPostBody:o,get:i,post:async(u,y={saveUrl:!0})=>(u&&v(u)==="object"&&(u=c({...u,saveUrl:y.saveUrl,includeQueryString:!1})),u=v(u)==="string"?u:n(),l({args:[{name:"url",value:u,required:!0,types:["string"]},{name:"options",value:y,types:["object"]},{name:"options.body",value:y.body,types:["string"]}]}),await i(u,{...y,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o(y.body)}))}};return s.DecodeVin=E,s.DecodeVinExtended=S,s.DecodeVinValues=D,s.DecodeVinValuesBatch=Y,s.DecodeVinValuesExtended=F,s.DecodeWMI=w,s.GetAllMakes=P,s.GetAllManufacturers=L,s.GetCanadianVehicleSpecifications=R,s.GetEquipmentPlantCodes=O,s.GetMakeForManufacturer=_,s.GetMakesForManufacturerAndYear=W,s.GetMakesForVehicleType=B,s.GetManufacturerDetails=H,s.GetModelsForMake=Q,s.GetModelsForMakeId=J,s.GetModelsForMakeIdYear=X,s.GetModelsForMakeYear=K,s.GetParts=Z,s.GetVehicleTypesForMake=z,s.GetVehicleTypesForMakeId=x,s.GetVehicleVariableList=ee,s.GetVehicleVariableValuesList=te,s.GetWMIsForManufacturer=re,s.createQueryString=T,s.encodeQueryStringParams=V,s.isValidVin=j,s.useNHTSA=g,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),s}({});
//# sourceMappingURL=nhtsa-api-wrapper.iife.js.map