diff --git a/bundle/umd/moysklad.js b/bundle/umd/moysklad.js index 6d0fe81..c61ca78 100644 --- a/bundle/umd/moysklad.js +++ b/bundle/umd/moysklad.js @@ -633,6 +633,7 @@ module.exports = stampit({ statics: { getTimeString, parseTimeString, + parseUrl, buildFilter, buildQuery, MoyskladError, @@ -1173,7 +1174,17 @@ module.exports = function parseUrl(...args) { { path: 'str or str arr' } ]) - let { endpoint, api, apiVersion } = this.getOptions() + const isCalledOnInstance = !!(this && this.getOptions) + + if (!url && !isCalledOnInstance) { + throw new MoyskladError( + 'Для вызова статического метода parseUrl, необходимо передать url' + ) + } + + let { endpoint, api, apiVersion } = isCalledOnInstance + ? this.getOptions() + : {} let pathStr = '' let queryStr = '' diff --git a/bundle/umd/moysklad.min.js b/bundle/umd/moysklad.min.js index d760d8b..41c4d27 100644 --- a/bundle/umd/moysklad.min.js +++ b/bundle/umd/moysklad.min.js @@ -1 +1 @@ -(()=>{var t={52:t=>{"use strict";let e;if("undefined"!=typeof process&&process.version)e=function(t){return Buffer.from(t).toString("base64")};else if("undefined"!=typeof btoa)e=function(t){return btoa(t)};else{if("undefined"==typeof Utilities||!Utilities.base64Encode)throw new Error("base64encode: Can't determine environment");e=function(t){return Utilities.base64Encode(t)}}t.exports=function(t){return e(String(t))}},91:t=>{"use strict";var e=/^(.+) a(rr(ay)?)?$/i,r=/^(.+) or (.+)$/i,n=/^opt(ional)? (.+)$/i,o=function(t){return Array.isArray(t)},s=function(t){return null!=t&&"object"==typeof t},i=function(t){return"[object Object]"===Object.prototype.toString.call(t)},c={string:function(t){return"string"==typeof t},"s|str":"string",number:function(t){return"number"==typeof t},"n|num":"number",boolean:function(t){return"boolean"==typeof t},"b|bool":"boolean",function:function(t){return"function"==typeof t},"f|fun|func":"function",array:o,"a|arr":"array",object:s,"o|obj":"object",regexp:function(t){return t&&t instanceof RegExp},"r|rx|regex":"regexp",date:function(t){return t&&t instanceof Date},d:"date",Object:i,Obj:"Object"},a=function(t,e){if(!t)throw void 0===e?new Error(t+" == true"):new Error(e)},u="@@have/argumentsObject",l="@@have/defaultMatcher",p={},f={};function d(){var t,e,r,n=Array.prototype.slice.call(arguments,0),o=n[0],s=n.slice(1);for(t=0,e=s.length;te.argIndex?-1:t.argIndex15?f.substring(0,15)+"..":f)+'"')),{fail:O,parsedArgs:b,argIndex:m}}throw new Error("have() `schema` should be an array or an object")}p[u]="Object",f[l]=function(){return!1},t.exports=function(){var t=a;function e(r,n,o){var s=g(r,n,this.matchers,o);return u in s.parsedArgs?e.call(this,s.parsedArgs[u],n,o):(t(!s.fail,s.fail),s.parsedArgs)}return e.assert=function(e){return void 0===e?t:t=e},e.strict=function(t,e){return this(t,e,!0)},e.matchers=d({},p,f),e.argumentsObject=p,e.with=function(t){var r=function(){return e.apply(r,arguments)};if(!i(t))throw new Error("`checkers` argument must to be an object");return d(r,{assert:e.assert,strict:e.strict.bind(r),with:e.with,matchers:d({},h(this.matchers),h(t)),argumentsObject:e.argumentsObject})},e.with(c)}()},992:t=>{!function(){"use strict";var e,r,n,o,s,i="properties",c="deepProperties",a="propertyDescriptors",u="staticProperties",l="staticDeepProperties",p="staticPropertyDescriptors",f="configuration",d="deepConfiguration",h="deepProps",y="deepStatics",g="deepConf",b="initializers",m="methods",w="composers",O="compose";function j(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t):[])}function x(t,e){return Array.prototype.slice.call(arguments,2).reduce(t,e)}var A=x.bind(0,(function(t,e){if(e)for(var r=j(e),n=0;n{"use strict";class e extends Error{constructor(t,...e){super(t,...e),this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class r extends e{constructor(t,e){super(t),e&&(this.url=e.url,this.status=e.status,this.statusText=e.statusText)}}class n extends r{constructor(t,e){const r=t[0];super(r.error+(r.moreInfo?` (${r.moreInfo})`:""),e),this.code=r.code,this.moreInfo=r.moreInfo,null!=r.line&&(this.line=r.line),null!=r.column&&(this.column=r.column),this.errors=t}}t.exports={MoyskladError:e,MoyskladRequestError:r,MoyskladUnexpectedRedirectError:class extends r{constructor(t){super(`Неожиданное перенаправление запроса с кодом ${t.status} (см. подробнее https://github.com/wmakeev/moysklad#moyskladunexpectedredirecterror)`,t);const e=t.headers.get("location");t&&(this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.location=e)}},MoyskladApiError:n,MoyskladCollectionError:class extends n{constructor(t,e,r){super(t,r),this.errorsIndexes=e}}}},112:(t,e,r)=>{"use strict";const n=r(489),o={remap:"1.2",phone:"1.0",posap:"1.0","moysklad/loyalty":"1.0"},s={remap:"REMAP",phone:"PHONE",posap:"POSAP","moysklad/loyalty":"LOYALTY"};t.exports=function(t){const e=o[t],r=s[t]||t.replace(/\W/g,"_").toUpperCase();return n(`MOYSKLAD_${r}_API_VERSION`)||e}},489:(t,e,r)=>{"use strict";t.exports=function(t,e){return"undefined"!=typeof process&&process.env&&process.env[t]?process.env[t]:"undefined"!=typeof window&&null!=window[t]?window[t]:void 0!==r.g&&null!=r.g[t]?r.g[t]:void 0!==e?e:null}},418:(t,e,r)=>{"use strict";const{MoyskladApiError:n,MoyskladCollectionError:o}=r(658);t.exports=function(t,e){if(!t)return null;if(Array.isArray(t)){const r=t.map(((t,e)=>t.errors?[e,t.errors]:null)).filter((t=>null!==t));if(0===r.length)return null;const n=r.map((t=>t[1])).reduce(((t,e)=>t.concat(e)),[]);return new o(n,r,e)}return t.errors?new n(t.errors,e):null}},83:(t,e,r)=>{"use strict";const n=r(91),o=r(823);t.exports=n.with(o)},138:(t,e,r)=>{"use strict";const n=r(992),o=r(83),s=r(112),{version:i}=r(345),c=r(9),a=r(562),u=r(656),l=r(467),p=r(706),f=r(831),d=r(60),h=r(579),y=r(573),g=r(397),b=r(874),m=r(200),{MoyskladApiError:w,MoyskladError:O,MoyskladRequestError:j,MoyskladCollectionError:x,MoyskladUnexpectedRedirectError:A}=r(658);t.exports=n({methods:{getAuthHeader:p,buildUrl:f,buildUri(...t){return console.log("Warning: метод buildUri переименован в buildUrl"),this.buildUrl(...t)},parseUrl:d,parseUri(...t){return console.log("Warning: метод parseUri переименован в parseUrl"),this.parseUrl(...t)},fetchUrl:h,fetchUri(...t){return console.log("Warning: метод fetchUri переименован в fetchUrl"),this.fetchUrl(...t)},GET:y,POST:g,PUT:b,DELETE:m},statics:{getTimeString:c,parseTimeString:a,buildFilter:u,buildQuery:l,MoyskladError:O,MoyskladRequestError:j,MoyskladUnexpectedRedirectError:A,MoyskladApiError:w,MoyskladCollectionError:x}}).init((function(t){o(t,{endpoint:"opt str",api:"opt str",apiVersion:"opt str"}),t.fetch?this.fetch=t.fetch:"undefined"!=typeof window&&window.fetch?this.fetch=window.fetch.bind(window):"undefined"!=typeof fetch?this.fetch=fetch:this.fetch=function(){throw new O("Нельзя выполнить http запрос, т.к. при инициализации экземпляра библиотеки не указан Fetch API модуль (cм. подробнее https://github.com/wmakeev/moysklad#Установка).")},t.emitter&&(this.emitter=t.emitter);const e=Object.assign({endpoint:"https://online.moysklad.ru/api",api:"remap",userAgent:`moysklad/${i} (+https://github.com/wmakeev/moysklad)`},t);if(!e.apiVersion){const t=s(e.api);if(!t)throw new O(`Не указана версия ${e.api} API`);e.apiVersion=t}this.getOptions=function(){return e},this.getVersion=function(){return i}}))},823:t=>{"use strict";const e=/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/,r=t=>"string"==typeof t&&"https://"===t.substring(0,8),n=t=>"string"==typeof t&&e.test(t);t.exports={entity:t=>!!(t&&t.id&&n(t.id)&&t.meta&&t.meta.type),uuid:n,url:r,"Moysklad.Collection":t=>!!(t&&t.meta&&t.meta.type&&r(t.meta.href)&&"number"==typeof t.meta.size)}},200:(t,e,r)=>{"use strict";const n=r(83);t.exports=function(...t){const{path:e,options:r={}}=n.strict(t,[{path:"str or str arr",options:"opt Object"},n.argumentsObject]),o=this.buildUrl(e);return this.fetchUrl(o,{...r,method:"DELETE"})}},573:(t,e,r)=>{"use strict";const n=r(83);t.exports=function(...t){const{path:e,query:r,options:o={}}=n.strict(t,[{path:"str or str arr",query:"opt Object",options:"opt Object"},n.argumentsObject]),s=this.buildUrl(e,r);return this.fetchUrl(s,{...o,method:"GET"})}},397:(t,e,r)=>{"use strict";const n=r(83);t.exports=function(...t){const{path:e,payload:r,query:o,options:s={}}=n.strict(t,[{path:"str or str arr",payload:"opt Object or Object arr or str",query:"opt Object",options:"opt Object"},n.argumentsObject]),i=this.buildUrl(e,o),c={method:"POST"};return r&&(c.body="string"==typeof r?r:JSON.stringify(r)),this.fetchUrl(i,{...s,...c})}},874:(t,e,r)=>{"use strict";const n=r(83);t.exports=function(...t){const{path:e,payload:r,query:o,options:s={}}=n.strict(t,[{path:"str or str arr",payload:"opt Object or str",query:"opt Object",options:"opt Object"},n.argumentsObject]),i=this.buildUrl(e,o),c={method:"PUT"};return r&&(c.body="string"==typeof r?r:JSON.stringify(r)),this.fetchUrl(i,{...s,...c})}},831:(t,e,r)=>{"use strict";const n=r(83),o=r(467),s=r(461);let i=!1;t.exports=function(...t){let{url:e,path:r,query:c}=n.strict(t,[{url:"url",query:"opt Object"},{path:"str or str arr",query:"opt Object"},n.argumentsObject]);if(e){const t=this.parseUrl(e);r=t.path.join("/"),c={...t.query,...c}}Array.isArray(r)&&(i||(console.log("[DEPRECATED] moysklad#buildUrl: для передачи параметра path используйте строку вместо массива"),i=!0),r=r.join("/"));const{endpoint:a,api:u,apiVersion:l}=this.getOptions();let p=s([a,u,l].concat(r).join("/"));if(c){const t=o(c);p+=t?`?${t}`:""}return p}},579:(t,e,r)=>{"use strict";const n=r(83),o=r(418),{MoyskladRequestError:s,MoyskladApiError:i,MoyskladCollectionError:c,MoyskladUnexpectedRedirectError:a}=r(658);let u=0;t.exports=async function(t,e={}){const r=++u;let l,p;n.strict(arguments,{url:"url",options:"opt Object"});let f=!1,d=!1,h=!1,y=!1;const g=this.emitter?this.emitter.emit.bind(this.emitter):null,b={redirect:"manual",...e,headers:{"User-Agent":this.getOptions().userAgent,"Content-Type":"application/json",...e.headers}};b.headers.Authorization||(b.credentials="include"),b.rawResponse&&(f=!0,delete b.rawResponse),b.rawRedirect&&(d=!0,delete b.rawRedirect),b.muteErrors&&(h=!0,delete b.muteErrors),b.muteApiErrors&&(h=!0,delete b.muteApiErrors),b.muteCollectionErrors&&(y=!0,delete b.muteCollectionErrors),b.millisecond&&(b.headers["X-Lognex-Format-Millisecond"]="true",delete b.millisecond),b.precision&&(b.headers["X-Lognex-Precision"]="true",delete b.precision),b.webHookDisable&&(b.headers["X-Lognex-WebHook-Disable"]="true",delete b.webHookDisable),this.getAuthHeader()&&(b.headers.Authorization=this.getAuthHeader()),g&&g("request",{requestId:r,url:t,options:b});const m=await this.fetch(t,b);if(g&&g("response",{requestId:r,url:t,options:b,response:m}),f)return m;if(m.status>=300&&m.status<400){if(d)return m;throw new a(m)}if((m.status<200||m.status>=300)&&(p=new s([m.status,m.statusText].filter((t=>t)).join(" "),m)),m.headers.has("Content-Type")&&-1!==m.headers.get("Content-Type").indexOf("application/json")){const t=await m.text();l=t?JSON.parse(t):void 0,p=o(l,m)||p}if(g&&g("response:body",{requestId:r,url:t,options:b,response:m,body:l}),p){if(p instanceof i&&h)return l;if(p instanceof c&&y)return l;throw g&&g("error",p,{requestId:r}),p}return l}},706:(t,e,r)=>{"use strict";const{MoyskladError:n}=r(658),o=r(52),s=r(489);t.exports=function(){let t,e,r;const i=this.getOptions();switch(!0){case null!=i.token:t=i.token;break;case null!=i.login:e=i.login,r=i.password;break;case null!=s("MOYSKLAD_TOKEN"):t=s("MOYSKLAD_TOKEN");break;case null!=s("MOYSKLAD_LOGIN"):e=s("MOYSKLAD_LOGIN"),r=s("MOYSKLAD_PASSWORD");break;default:return}if(t)return(t=>`Bearer ${t}`)(t);if(r)return((t,e)=>"Basic "+o(`${t}:${e}`))(e,r);throw new n("Не указан пароль для доступа к API")}},60:(t,e,r)=>{const{MoyskladError:n}=r(658),o=r(83),s=r(461),i=r(565),c=/^(https:\/\/.+\/api)\/(.+)\/(\d+\.\d+)\/([^?]+)(?:\?(.+))?$/;t.exports=function(...t){const{url:e,path:r}=o.strict(t,[{url:"url"},{path:"str or str arr"}]);let{endpoint:a,api:u,apiVersion:l}=this.getOptions(),p="",f="";if(r instanceof Array)p=r.join("/");else if("string"==typeof r)p=r;else if(e){const[,t,r,n,o,s]=c.exec(e)||[];a=t,u=r,p=o,l=n,f=s}if(!(a&&u&&l&&p))throw new n(`parseUrl: Url не соответствует API МойСклад - ${e||r}`);return{endpoint:a,api:u,apiVersion:l,path:s(p).split(/\//g),query:i(f)||{}}}},656:(t,e,r)=>{"use strict";const{MoyskladError:n}=r(658),o=r(9),s=r(226),i=r(981),c=t=>(e,r)=>{if(!i(r))throw new n("значение должно быть строкой, числом, датой или null");return[[e,t,r]]},a=t=>{const e=c(t);return(t,r)=>{if(!(r instanceof Array))throw new n(`значение селектора ${t.join(".")} должно быть массивом`);return r.reduce(((r,n)=>r.concat(e(t,n))),[])}},u={eq:{operator:"="},gt:{operator:">"},gte:{operator:">="},lt:{operator:"<"},lte:{operator:"<="},ne:{operator:"!="},contains:{operator:"~"},st:{operator:"~="},et:{operator:"=~"},in:{operator:"=",collection:!0},nin:{operator:"!=",collection:!0}};Object.keys(u).forEach((t=>{u[t].name=`$${t}`})),u.eq.not=u.ne,u.gt.not=u.lte,u.gte.not=u.lt,u.lt.not=u.gte,u.lte.not=u.gt,u.ne.not=u.eq,u.in.not=u.nin,u.nin.not=u.in;const l=Object.keys(u).reduce(((t,e)=>{const r=u[e];return t["$"+e]=(r.collection?a:c)(r),t}),{}),p=t=>{if(!t[1].not)throw new n(`${t[1].name} не поддерживает селектор отрицания $not`);return[t[0],t[1].not,t[2]]};function f(t,e){const r=t.length,o=r?t[r-1]:null;switch(!0){case"$and"===o:if(!(e instanceof Array))throw new n("$and: значение селектора должно быть массивом");return e.reduce(((e,r)=>e.concat(f(t.slice(0,-1),r))),[]);case"$not"===o:if(!s(e))throw new n("$not: значение селектора должно быть объектом");return f(t.slice(0,-1),e).map(p);case"$exists"===o:if("boolean"!=typeof e)throw new n("$exists: значение селектора должно быть логическим значением");return[[t.slice(0,-1),e?u.ne:u.eq,null]];case!!l[o]:try{return l[o](t.slice(0,-1),e)}catch(t){throw new n(`${o}: ${t.message}`)}case o&&"$"===o.substr(0,1)&&t.length>1:throw new n(`Неизвестный селектор "${o}"`);case e instanceof Array:return e.reduce(((e,r)=>e.concat(f(t,r))),[]);case!i(e):return Object.keys(e).reduce(((r,n)=>r.concat(f(t.concat(n),e[n]))),[]);default:return[[t,u.eq,e]]}}t.exports=function(t){if(!s(t))throw new n("Поле filter должно быть объектом");let e=f([],t);return e=e.map((t=>[t[0].join("."),t[1],t[2]])),e.map((t=>{const e=t[0],r=t[1].operator,s=t[2];switch(!0){case void 0===s:return null;case null===s:return[e,r,""];case s instanceof Date:return[e,r,o(s,!0)];case"string"==typeof s:case"number"==typeof s:case"boolean"==typeof s:return[e,r,s];default:throw new n(`Некорректное значение поля "${e}" в фильтре`)}})).filter((t=>null!=t)).map((t=>`${t[0]}${t[1]}${t[2]}`)).sort(((t,e)=>t>e?1:t{"use strict";const{MoyskladError:n}=r(658),o=r(656),s=r(226);t.exports=function(t){return t.expand&&null==t.limit&&(t.limit=100),Object.keys(t).reduce(((e,r)=>{const i=((t,e)=>r=>{if(null===r)t.push([e,""]);else{if(void 0===r)return;if(-1===["string","number","boolean"].indexOf(typeof r))throw new n("Значение поля строки запроса должно быть строкой, числом, логическим значением, null или undefined");t.push([e,encodeURIComponent(r)])}})(e,r);switch(!0){case"filter"===r:if(s(t.filter))i(o(t.filter));else{if("string"!=typeof t.filter)throw new n("Поле filter запроса должно быть строкой или объектом");i(t.filter)}break;case"order"===r&&t.order instanceof Array:i(t.order.map((t=>t instanceof Array?`${t[0]}${null!=t[1]?","+t[1]:""}`:t)).join(";"));break;case t[r]instanceof Array:t[r].forEach(i);break;default:i(t[r])}return e}),[]).map((t=>`${t[0]}=${t[1]}`)).join("&")}},9:(t,e,r)=>{"use strict";const n=r(928)();function o(t){return`0${t}`.slice(-2)}t.exports=function(t,e){const r=new Date(+t+108e5+n),s=r.getUTCMilliseconds();return[r.getUTCFullYear(),"-",o(r.getUTCMonth()+1),"-",o(r.getUTCDate())," ",o(r.getUTCHours()),":",o(r.getUTCMinutes()),":",o(r.getUTCSeconds()),0!==s&&e?`.${i=s,`00${i}`.slice(-3)}`:""].join("");var i}},928:(t,e,r)=>{const{MoyskladError:n}=r(658),o=r(489);t.exports=function(){const t=-60*(new Date).getTimezoneOffset()*1e3;let e=t;const r=o("MOYSKLAD_TIMEZONE");if(r){const t=60*Number.parseInt(r)*1e3;if(Number.isNaN(t))throw new n(`Некорректно указана переменная окружения MOYSKLAD_TIMEZONE - ${r}`);e=t}return t-e}},226:t=>{"use strict";t.exports=function(t){return"[object Object]"===Object.prototype.toString.call(t)}},981:t=>{"use strict";t.exports=function(t){return"object"!=typeof t||t instanceof Date||null===t}},461:t=>{"use strict";const e=/([^:]\/)\/+/g,r=/^\/+|\/+$/g;t.exports=function(t){return t.replace(r,"").replace(e,"$1")}},565:t=>{"use strict";function e(t){if(""===t)return null;const e=Boolean(t);if(e.toString()===t)return e;const r=parseInt(t);return r.toString()===t?r:decodeURIComponent(t)}t.exports=function(t){if(null==t||""===t)return;if(!(t=t.trim()))return;const r=t.split("&").reduce(((t,r)=>{const n=r.split("="),o=n[0],s=-1!==(i=n[1]).indexOf(",")?i.split(",").map((t=>e(t))):[e(i)];var i;const c=t.get(o);return t.set(o,c?c.concat(s):s)}),new Map),n={};for(const t of r.entries()){const[e,r]=t;n[e]=r.length>1?r:r[0]}return n}},562:(t,e,r)=>{"use strict";const{MoyskladError:n}=r(658),o=r(928)(),s=/^(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;t.exports=function(t){const e=s.exec(t);if(!e||e.length<7||e.length>8)throw new n(`Некорректный формат даты "${t}"`);const r=`${e[1]}-${e[2]}-${e[3]}T${e[4]}:${e[5]}:${e[6]}${e[7]&&0!==Number.parseInt(e[7])?"."+(i=e[7],`${i}00`.slice(0,3)):""}+03:00`;var i;const c=new Date(r);return o?new Date(+c-o):c}},345:t=>{t.exports={version:"0.12.0"}}},e={};function r(n){var o=e[n];if(void 0!==o)return o.exports;var s=e[n]={exports:{}};return t[n](s,s.exports,r),s.exports}r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}();var n=r(138);window.MoyskladClient=n})(); \ No newline at end of file +(()=>{var t={52:t=>{"use strict";let e;if("undefined"!=typeof process&&process.version)e=function(t){return Buffer.from(t).toString("base64")};else if("undefined"!=typeof btoa)e=function(t){return btoa(t)};else{if("undefined"==typeof Utilities||!Utilities.base64Encode)throw new Error("base64encode: Can't determine environment");e=function(t){return Utilities.base64Encode(t)}}t.exports=function(t){return e(String(t))}},91:t=>{"use strict";var e=/^(.+) a(rr(ay)?)?$/i,r=/^(.+) or (.+)$/i,n=/^opt(ional)? (.+)$/i,o=function(t){return Array.isArray(t)},s=function(t){return null!=t&&"object"==typeof t},i=function(t){return"[object Object]"===Object.prototype.toString.call(t)},c={string:function(t){return"string"==typeof t},"s|str":"string",number:function(t){return"number"==typeof t},"n|num":"number",boolean:function(t){return"boolean"==typeof t},"b|bool":"boolean",function:function(t){return"function"==typeof t},"f|fun|func":"function",array:o,"a|arr":"array",object:s,"o|obj":"object",regexp:function(t){return t&&t instanceof RegExp},"r|rx|regex":"regexp",date:function(t){return t&&t instanceof Date},d:"date",Object:i,Obj:"Object"},a=function(t,e){if(!t)throw void 0===e?new Error(t+" == true"):new Error(e)},u="@@have/argumentsObject",l="@@have/defaultMatcher",p={},f={};function d(){var t,e,r,n=Array.prototype.slice.call(arguments,0),o=n[0],s=n.slice(1);for(t=0,e=s.length;te.argIndex?-1:t.argIndex15?f.substring(0,15)+"..":f)+'"')),{fail:O,parsedArgs:b,argIndex:m}}throw new Error("have() `schema` should be an array or an object")}p[u]="Object",f[l]=function(){return!1},t.exports=function(){var t=a;function e(r,n,o){var s=g(r,n,this.matchers,o);return u in s.parsedArgs?e.call(this,s.parsedArgs[u],n,o):(t(!s.fail,s.fail),s.parsedArgs)}return e.assert=function(e){return void 0===e?t:t=e},e.strict=function(t,e){return this(t,e,!0)},e.matchers=d({},p,f),e.argumentsObject=p,e.with=function(t){var r=function(){return e.apply(r,arguments)};if(!i(t))throw new Error("`checkers` argument must to be an object");return d(r,{assert:e.assert,strict:e.strict.bind(r),with:e.with,matchers:d({},h(this.matchers),h(t)),argumentsObject:e.argumentsObject})},e.with(c)}()},992:t=>{!function(){"use strict";var e,r,n,o,s,i="properties",c="deepProperties",a="propertyDescriptors",u="staticProperties",l="staticDeepProperties",p="staticPropertyDescriptors",f="configuration",d="deepConfiguration",h="deepProps",y="deepStatics",g="deepConf",b="initializers",m="methods",w="composers",O="compose";function j(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t):[])}function x(t,e){return Array.prototype.slice.call(arguments,2).reduce(t,e)}var A=x.bind(0,(function(t,e){if(e)for(var r=j(e),n=0;n{"use strict";class e extends Error{constructor(t,...e){super(t,...e),this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class r extends e{constructor(t,e){super(t),e&&(this.url=e.url,this.status=e.status,this.statusText=e.statusText)}}class n extends r{constructor(t,e){const r=t[0];super(r.error+(r.moreInfo?` (${r.moreInfo})`:""),e),this.code=r.code,this.moreInfo=r.moreInfo,null!=r.line&&(this.line=r.line),null!=r.column&&(this.column=r.column),this.errors=t}}t.exports={MoyskladError:e,MoyskladRequestError:r,MoyskladUnexpectedRedirectError:class extends r{constructor(t){super(`Неожиданное перенаправление запроса с кодом ${t.status} (см. подробнее https://github.com/wmakeev/moysklad#moyskladunexpectedredirecterror)`,t);const e=t.headers.get("location");t&&(this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.location=e)}},MoyskladApiError:n,MoyskladCollectionError:class extends n{constructor(t,e,r){super(t,r),this.errorsIndexes=e}}}},112:(t,e,r)=>{"use strict";const n=r(489),o={remap:"1.2",phone:"1.0",posap:"1.0","moysklad/loyalty":"1.0"},s={remap:"REMAP",phone:"PHONE",posap:"POSAP","moysklad/loyalty":"LOYALTY"};t.exports=function(t){const e=o[t],r=s[t]||t.replace(/\W/g,"_").toUpperCase();return n(`MOYSKLAD_${r}_API_VERSION`)||e}},489:(t,e,r)=>{"use strict";t.exports=function(t,e){return"undefined"!=typeof process&&process.env&&process.env[t]?process.env[t]:"undefined"!=typeof window&&null!=window[t]?window[t]:void 0!==r.g&&null!=r.g[t]?r.g[t]:void 0!==e?e:null}},418:(t,e,r)=>{"use strict";const{MoyskladApiError:n,MoyskladCollectionError:o}=r(658);t.exports=function(t,e){if(!t)return null;if(Array.isArray(t)){const r=t.map(((t,e)=>t.errors?[e,t.errors]:null)).filter((t=>null!==t));if(0===r.length)return null;const n=r.map((t=>t[1])).reduce(((t,e)=>t.concat(e)),[]);return new o(n,r,e)}return t.errors?new n(t.errors,e):null}},83:(t,e,r)=>{"use strict";const n=r(91),o=r(823);t.exports=n.with(o)},138:(t,e,r)=>{"use strict";const n=r(992),o=r(83),s=r(112),{version:i}=r(345),c=r(9),a=r(562),u=r(656),l=r(467),p=r(706),f=r(831),d=r(60),h=r(579),y=r(573),g=r(397),b=r(874),m=r(200),{MoyskladApiError:w,MoyskladError:O,MoyskladRequestError:j,MoyskladCollectionError:x,MoyskladUnexpectedRedirectError:A}=r(658);t.exports=n({methods:{getAuthHeader:p,buildUrl:f,buildUri(...t){return console.log("Warning: метод buildUri переименован в buildUrl"),this.buildUrl(...t)},parseUrl:d,parseUri(...t){return console.log("Warning: метод parseUri переименован в parseUrl"),this.parseUrl(...t)},fetchUrl:h,fetchUri(...t){return console.log("Warning: метод fetchUri переименован в fetchUrl"),this.fetchUrl(...t)},GET:y,POST:g,PUT:b,DELETE:m},statics:{getTimeString:c,parseTimeString:a,parseUrl:d,buildFilter:u,buildQuery:l,MoyskladError:O,MoyskladRequestError:j,MoyskladUnexpectedRedirectError:A,MoyskladApiError:w,MoyskladCollectionError:x}}).init((function(t){o(t,{endpoint:"opt str",api:"opt str",apiVersion:"opt str"}),t.fetch?this.fetch=t.fetch:"undefined"!=typeof window&&window.fetch?this.fetch=window.fetch.bind(window):"undefined"!=typeof fetch?this.fetch=fetch:this.fetch=function(){throw new O("Нельзя выполнить http запрос, т.к. при инициализации экземпляра библиотеки не указан Fetch API модуль (cм. подробнее https://github.com/wmakeev/moysklad#Установка).")},t.emitter&&(this.emitter=t.emitter);const e=Object.assign({endpoint:"https://online.moysklad.ru/api",api:"remap",userAgent:`moysklad/${i} (+https://github.com/wmakeev/moysklad)`},t);if(!e.apiVersion){const t=s(e.api);if(!t)throw new O(`Не указана версия ${e.api} API`);e.apiVersion=t}this.getOptions=function(){return e},this.getVersion=function(){return i}}))},823:t=>{"use strict";const e=/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/,r=t=>"string"==typeof t&&"https://"===t.substring(0,8),n=t=>"string"==typeof t&&e.test(t);t.exports={entity:t=>!!(t&&t.id&&n(t.id)&&t.meta&&t.meta.type),uuid:n,url:r,"Moysklad.Collection":t=>!!(t&&t.meta&&t.meta.type&&r(t.meta.href)&&"number"==typeof t.meta.size)}},200:(t,e,r)=>{"use strict";const n=r(83);t.exports=function(...t){const{path:e,options:r={}}=n.strict(t,[{path:"str or str arr",options:"opt Object"},n.argumentsObject]),o=this.buildUrl(e);return this.fetchUrl(o,{...r,method:"DELETE"})}},573:(t,e,r)=>{"use strict";const n=r(83);t.exports=function(...t){const{path:e,query:r,options:o={}}=n.strict(t,[{path:"str or str arr",query:"opt Object",options:"opt Object"},n.argumentsObject]),s=this.buildUrl(e,r);return this.fetchUrl(s,{...o,method:"GET"})}},397:(t,e,r)=>{"use strict";const n=r(83);t.exports=function(...t){const{path:e,payload:r,query:o,options:s={}}=n.strict(t,[{path:"str or str arr",payload:"opt Object or Object arr or str",query:"opt Object",options:"opt Object"},n.argumentsObject]),i=this.buildUrl(e,o),c={method:"POST"};return r&&(c.body="string"==typeof r?r:JSON.stringify(r)),this.fetchUrl(i,{...s,...c})}},874:(t,e,r)=>{"use strict";const n=r(83);t.exports=function(...t){const{path:e,payload:r,query:o,options:s={}}=n.strict(t,[{path:"str or str arr",payload:"opt Object or str",query:"opt Object",options:"opt Object"},n.argumentsObject]),i=this.buildUrl(e,o),c={method:"PUT"};return r&&(c.body="string"==typeof r?r:JSON.stringify(r)),this.fetchUrl(i,{...s,...c})}},831:(t,e,r)=>{"use strict";const n=r(83),o=r(467),s=r(461);let i=!1;t.exports=function(...t){let{url:e,path:r,query:c}=n.strict(t,[{url:"url",query:"opt Object"},{path:"str or str arr",query:"opt Object"},n.argumentsObject]);if(e){const t=this.parseUrl(e);r=t.path.join("/"),c={...t.query,...c}}Array.isArray(r)&&(i||(console.log("[DEPRECATED] moysklad#buildUrl: для передачи параметра path используйте строку вместо массива"),i=!0),r=r.join("/"));const{endpoint:a,api:u,apiVersion:l}=this.getOptions();let p=s([a,u,l].concat(r).join("/"));if(c){const t=o(c);p+=t?`?${t}`:""}return p}},579:(t,e,r)=>{"use strict";const n=r(83),o=r(418),{MoyskladRequestError:s,MoyskladApiError:i,MoyskladCollectionError:c,MoyskladUnexpectedRedirectError:a}=r(658);let u=0;t.exports=async function(t,e={}){const r=++u;let l,p;n.strict(arguments,{url:"url",options:"opt Object"});let f=!1,d=!1,h=!1,y=!1;const g=this.emitter?this.emitter.emit.bind(this.emitter):null,b={redirect:"manual",...e,headers:{"User-Agent":this.getOptions().userAgent,"Content-Type":"application/json",...e.headers}};b.headers.Authorization||(b.credentials="include"),b.rawResponse&&(f=!0,delete b.rawResponse),b.rawRedirect&&(d=!0,delete b.rawRedirect),b.muteErrors&&(h=!0,delete b.muteErrors),b.muteApiErrors&&(h=!0,delete b.muteApiErrors),b.muteCollectionErrors&&(y=!0,delete b.muteCollectionErrors),b.millisecond&&(b.headers["X-Lognex-Format-Millisecond"]="true",delete b.millisecond),b.precision&&(b.headers["X-Lognex-Precision"]="true",delete b.precision),b.webHookDisable&&(b.headers["X-Lognex-WebHook-Disable"]="true",delete b.webHookDisable),this.getAuthHeader()&&(b.headers.Authorization=this.getAuthHeader()),g&&g("request",{requestId:r,url:t,options:b});const m=await this.fetch(t,b);if(g&&g("response",{requestId:r,url:t,options:b,response:m}),f)return m;if(m.status>=300&&m.status<400){if(d)return m;throw new a(m)}if((m.status<200||m.status>=300)&&(p=new s([m.status,m.statusText].filter((t=>t)).join(" "),m)),m.headers.has("Content-Type")&&-1!==m.headers.get("Content-Type").indexOf("application/json")){const t=await m.text();l=t?JSON.parse(t):void 0,p=o(l,m)||p}if(g&&g("response:body",{requestId:r,url:t,options:b,response:m,body:l}),p){if(p instanceof i&&h)return l;if(p instanceof c&&y)return l;throw g&&g("error",p,{requestId:r}),p}return l}},706:(t,e,r)=>{"use strict";const{MoyskladError:n}=r(658),o=r(52),s=r(489);t.exports=function(){let t,e,r;const i=this.getOptions();switch(!0){case null!=i.token:t=i.token;break;case null!=i.login:e=i.login,r=i.password;break;case null!=s("MOYSKLAD_TOKEN"):t=s("MOYSKLAD_TOKEN");break;case null!=s("MOYSKLAD_LOGIN"):e=s("MOYSKLAD_LOGIN"),r=s("MOYSKLAD_PASSWORD");break;default:return}if(t)return(t=>`Bearer ${t}`)(t);if(r)return((t,e)=>"Basic "+o(`${t}:${e}`))(e,r);throw new n("Не указан пароль для доступа к API")}},60:(t,e,r)=>{const{MoyskladError:n}=r(658),o=r(83),s=r(461),i=r(565),c=/^(https:\/\/.+\/api)\/(.+)\/(\d+\.\d+)\/([^?]+)(?:\?(.+))?$/;t.exports=function(...t){const{url:e,path:r}=o.strict(t,[{url:"url"},{path:"str or str arr"}]),a=!(!this||!this.getOptions);if(!e&&!a)throw new n("Для вызова статического метода parseUrl, необходимо передать url");let{endpoint:u,api:l,apiVersion:p}=a?this.getOptions():{},f="",d="";if(r instanceof Array)f=r.join("/");else if("string"==typeof r)f=r;else if(e){const[,t,r,n,o,s]=c.exec(e)||[];u=t,l=r,f=o,p=n,d=s}if(!(u&&l&&p&&f))throw new n(`parseUrl: Url не соответствует API МойСклад - ${e||r}`);return{endpoint:u,api:l,apiVersion:p,path:s(f).split(/\//g),query:i(d)||{}}}},656:(t,e,r)=>{"use strict";const{MoyskladError:n}=r(658),o=r(9),s=r(226),i=r(981),c=t=>(e,r)=>{if(!i(r))throw new n("значение должно быть строкой, числом, датой или null");return[[e,t,r]]},a=t=>{const e=c(t);return(t,r)=>{if(!(r instanceof Array))throw new n(`значение селектора ${t.join(".")} должно быть массивом`);return r.reduce(((r,n)=>r.concat(e(t,n))),[])}},u={eq:{operator:"="},gt:{operator:">"},gte:{operator:">="},lt:{operator:"<"},lte:{operator:"<="},ne:{operator:"!="},contains:{operator:"~"},st:{operator:"~="},et:{operator:"=~"},in:{operator:"=",collection:!0},nin:{operator:"!=",collection:!0}};Object.keys(u).forEach((t=>{u[t].name=`$${t}`})),u.eq.not=u.ne,u.gt.not=u.lte,u.gte.not=u.lt,u.lt.not=u.gte,u.lte.not=u.gt,u.ne.not=u.eq,u.in.not=u.nin,u.nin.not=u.in;const l=Object.keys(u).reduce(((t,e)=>{const r=u[e];return t["$"+e]=(r.collection?a:c)(r),t}),{}),p=t=>{if(!t[1].not)throw new n(`${t[1].name} не поддерживает селектор отрицания $not`);return[t[0],t[1].not,t[2]]};function f(t,e){const r=t.length,o=r?t[r-1]:null;switch(!0){case"$and"===o:if(!(e instanceof Array))throw new n("$and: значение селектора должно быть массивом");return e.reduce(((e,r)=>e.concat(f(t.slice(0,-1),r))),[]);case"$not"===o:if(!s(e))throw new n("$not: значение селектора должно быть объектом");return f(t.slice(0,-1),e).map(p);case"$exists"===o:if("boolean"!=typeof e)throw new n("$exists: значение селектора должно быть логическим значением");return[[t.slice(0,-1),e?u.ne:u.eq,null]];case!!l[o]:try{return l[o](t.slice(0,-1),e)}catch(t){throw new n(`${o}: ${t.message}`)}case o&&"$"===o.substr(0,1)&&t.length>1:throw new n(`Неизвестный селектор "${o}"`);case e instanceof Array:return e.reduce(((e,r)=>e.concat(f(t,r))),[]);case!i(e):return Object.keys(e).reduce(((r,n)=>r.concat(f(t.concat(n),e[n]))),[]);default:return[[t,u.eq,e]]}}t.exports=function(t){if(!s(t))throw new n("Поле filter должно быть объектом");let e=f([],t);return e=e.map((t=>[t[0].join("."),t[1],t[2]])),e.map((t=>{const e=t[0],r=t[1].operator,s=t[2];switch(!0){case void 0===s:return null;case null===s:return[e,r,""];case s instanceof Date:return[e,r,o(s,!0)];case"string"==typeof s:case"number"==typeof s:case"boolean"==typeof s:return[e,r,s];default:throw new n(`Некорректное значение поля "${e}" в фильтре`)}})).filter((t=>null!=t)).map((t=>`${t[0]}${t[1]}${t[2]}`)).sort(((t,e)=>t>e?1:t{"use strict";const{MoyskladError:n}=r(658),o=r(656),s=r(226);t.exports=function(t){return t.expand&&null==t.limit&&(t.limit=100),Object.keys(t).reduce(((e,r)=>{const i=((t,e)=>r=>{if(null===r)t.push([e,""]);else{if(void 0===r)return;if(-1===["string","number","boolean"].indexOf(typeof r))throw new n("Значение поля строки запроса должно быть строкой, числом, логическим значением, null или undefined");t.push([e,encodeURIComponent(r)])}})(e,r);switch(!0){case"filter"===r:if(s(t.filter))i(o(t.filter));else{if("string"!=typeof t.filter)throw new n("Поле filter запроса должно быть строкой или объектом");i(t.filter)}break;case"order"===r&&t.order instanceof Array:i(t.order.map((t=>t instanceof Array?`${t[0]}${null!=t[1]?","+t[1]:""}`:t)).join(";"));break;case t[r]instanceof Array:t[r].forEach(i);break;default:i(t[r])}return e}),[]).map((t=>`${t[0]}=${t[1]}`)).join("&")}},9:(t,e,r)=>{"use strict";const n=r(928)();function o(t){return`0${t}`.slice(-2)}t.exports=function(t,e){const r=new Date(+t+108e5+n),s=r.getUTCMilliseconds();return[r.getUTCFullYear(),"-",o(r.getUTCMonth()+1),"-",o(r.getUTCDate())," ",o(r.getUTCHours()),":",o(r.getUTCMinutes()),":",o(r.getUTCSeconds()),0!==s&&e?`.${i=s,`00${i}`.slice(-3)}`:""].join("");var i}},928:(t,e,r)=>{const{MoyskladError:n}=r(658),o=r(489);t.exports=function(){const t=-60*(new Date).getTimezoneOffset()*1e3;let e=t;const r=o("MOYSKLAD_TIMEZONE");if(r){const t=60*Number.parseInt(r)*1e3;if(Number.isNaN(t))throw new n(`Некорректно указана переменная окружения MOYSKLAD_TIMEZONE - ${r}`);e=t}return t-e}},226:t=>{"use strict";t.exports=function(t){return"[object Object]"===Object.prototype.toString.call(t)}},981:t=>{"use strict";t.exports=function(t){return"object"!=typeof t||t instanceof Date||null===t}},461:t=>{"use strict";const e=/([^:]\/)\/+/g,r=/^\/+|\/+$/g;t.exports=function(t){return t.replace(r,"").replace(e,"$1")}},565:t=>{"use strict";function e(t){if(""===t)return null;const e=Boolean(t);if(e.toString()===t)return e;const r=parseInt(t);return r.toString()===t?r:decodeURIComponent(t)}t.exports=function(t){if(null==t||""===t)return;if(!(t=t.trim()))return;const r=t.split("&").reduce(((t,r)=>{const n=r.split("="),o=n[0],s=-1!==(i=n[1]).indexOf(",")?i.split(",").map((t=>e(t))):[e(i)];var i;const c=t.get(o);return t.set(o,c?c.concat(s):s)}),new Map),n={};for(const t of r.entries()){const[e,r]=t;n[e]=r.length>1?r:r[0]}return n}},562:(t,e,r)=>{"use strict";const{MoyskladError:n}=r(658),o=r(928)(),s=/^(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;t.exports=function(t){const e=s.exec(t);if(!e||e.length<7||e.length>8)throw new n(`Некорректный формат даты "${t}"`);const r=`${e[1]}-${e[2]}-${e[3]}T${e[4]}:${e[5]}:${e[6]}${e[7]&&0!==Number.parseInt(e[7])?"."+(i=e[7],`${i}00`.slice(0,3)):""}+03:00`;var i;const c=new Date(r);return o?new Date(+c-o):c}},345:t=>{t.exports={version:"0.12.0"}}},e={};function r(n){var o=e[n];if(void 0!==o)return o.exports;var s=e[n]={exports:{}};return t[n](s,s.exports,r),s.exports}r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}();var n=r(138);window.MoyskladClient=n})(); \ No newline at end of file