@binamik/js-providers 0.1.1 → 0.1.5

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.
@@ -11,10 +11,10 @@ interface AppStorageProviderProps {
11
11
  cookieDomain: string;
12
12
  cookiePrefix: string;
13
13
  }
14
- export declare const AppStorageProvider: ({ cookieDomain, cookiePrefix, }: AppStorageProviderProps) => {
14
+ export declare const AppStorageProvider: ({ cookieDomain, cookiePrefix }: AppStorageProviderProps) => {
15
15
  get: (key: string) => string;
16
16
  set: (key: string, value: string, options?: CookieOptionsType | undefined) => void;
17
17
  remove: (key: string, options?: CookieOptionsType | undefined) => void;
18
- clean: (options?: CookieOptionsType | undefined) => void;
18
+ cleanAuth: (options?: CookieOptionsType | undefined) => void;
19
19
  };
20
20
  export {};
@@ -0,0 +1,35 @@
1
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
+ import { AnyObjectSchema } from 'yup';
3
+ export interface IOIntegrityCheckProps {
4
+ name: string;
5
+ schema: AnyObjectSchema;
6
+ }
7
+ export declare type ApiErrorParserType = (err?: Record<string, unknown> | null) => string[];
8
+ interface IoInstanceOptions {
9
+ withAuth: boolean;
10
+ authKey?: string;
11
+ ioIntegrityCheck?: IOIntegrityCheckProps;
12
+ onStatusCode?: Record<number, (res: AxiosResponse) => void>;
13
+ errorParser?: ApiErrorParserType;
14
+ }
15
+ export interface IoErrorProps {
16
+ status: number;
17
+ message: string;
18
+ errorData: Record<string, unknown> | null;
19
+ errors?: string[];
20
+ }
21
+ export interface IoResponseMetaProps {
22
+ status: number;
23
+ }
24
+ declare type IOResponseType<T> = [T, null, IoResponseMetaProps?];
25
+ declare type IOResponseErrorType = [null, IoErrorProps, IoResponseMetaProps?];
26
+ export declare type ApiResponseDTO<T> = IOResponseType<T> | IOResponseErrorType;
27
+ declare type IoFn = <T>(url: string, payload?: Record<string, unknown>, config?: AxiosRequestConfig) => Promise<ApiResponseDTO<T>>;
28
+ interface IoInstanceProps {
29
+ get: IoFn;
30
+ post: IoFn;
31
+ patch: IoFn;
32
+ delete: IoFn;
33
+ }
34
+ export declare const createIoInstance: (baseUrl: string, options?: IoInstanceOptions | undefined) => IoInstanceProps;
35
+ export {};
@@ -0,0 +1,10 @@
1
+ import { AnyObjectSchema } from 'yup';
2
+ interface CheckIoIntegrityProps {
3
+ name: string;
4
+ url: string;
5
+ req: unknown;
6
+ res: unknown;
7
+ schema: AnyObjectSchema;
8
+ }
9
+ export declare const checkIoIntegrity: ({ name, url, req, res, schema }: CheckIoIntegrityProps) => Promise<void>;
10
+ export {};
@@ -1,14 +1,39 @@
1
+ import { Dayjs } from 'dayjs';
2
+ declare type DateTimeUnits = 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second';
3
+ interface DateTimeOptions {
4
+ years?: number;
5
+ months?: number;
6
+ weeks?: number;
7
+ days?: number;
8
+ hours?: number;
9
+ minutes?: number;
10
+ seconds?: number;
11
+ }
12
+ interface SetToOptions {
13
+ year?: number;
14
+ month?: number;
15
+ day?: number;
16
+ hour?: number;
17
+ minute?: number;
18
+ second?: number;
19
+ milisecond?: number;
20
+ }
1
21
  export declare class SafeDate {
2
22
  private value;
3
- private isValid;
23
+ private isDateValid;
24
+ static isValid(value?: Date | string | Dayjs): boolean;
25
+ private returnHandler;
26
+ get isValid(): boolean;
4
27
  get jsDate(): Date;
5
28
  get timestamp(): number;
6
29
  get isoDate(): string;
7
30
  get isoString(): string;
8
31
  get dateString(): string;
9
32
  get longDayMonth(): string;
33
+ get shortDayMonth(): string;
10
34
  get longDateString(): string;
11
35
  get timeString(): string;
36
+ get daysInMonth(): number;
12
37
  get dateObj(): {
13
38
  year: number;
14
39
  month: number;
@@ -17,9 +42,22 @@ export declare class SafeDate {
17
42
  hours: number;
18
43
  minutes: number;
19
44
  seconds: number;
45
+ milliseconds: number;
20
46
  };
47
+ setToStartOf(unit: DateTimeUnits): this;
21
48
  addDays(days: number): this;
22
49
  addMonths(months: number): this;
23
50
  addYears(years: number): this;
24
- constructor(value?: Date | string);
51
+ addHours(hours: number): this;
52
+ addToDate({ years, months, weeks, days, hours, minutes, seconds }: DateTimeOptions): this;
53
+ setTo(newValues: SetToOptions): this;
54
+ isBefore(date: Date | string, unit?: DateTimeUnits): boolean;
55
+ isAfter(date: Date | string, unit?: DateTimeUnits): boolean;
56
+ isSame(date: Date | string, unit?: DateTimeUnits): boolean;
57
+ isBetween(startingDate: Date | string, endingDate: Date | string, unit?: DateTimeUnits): boolean;
58
+ getDiff(date: Date | string, unit: DateTimeUnits): number;
59
+ clone(): SafeDate;
60
+ format(format: string): string;
61
+ constructor(pValue?: Date | string | Dayjs);
25
62
  }
63
+ export {};
@@ -1,5 +1,19 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
2
5
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
3
17
  var __publicField = (obj, key, value) => {
4
18
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
19
  return value;
@@ -7,71 +21,164 @@ var __publicField = (obj, key, value) => {
7
21
  import dayjs from "dayjs";
8
22
  import "dayjs/locale/pt-br";
9
23
  import { parseCookies, setCookie, destroyCookie } from "nookies";
24
+ import axios from "axios";
25
+ import { object } from "yup";
10
26
  class SafeDate {
11
- constructor(value) {
27
+ constructor(pValue) {
12
28
  __publicField(this, "value", dayjs());
13
- __publicField(this, "isValid", true);
14
- this.value = dayjs(value).locale("pt-br");
15
- this.isValid = this.value.isValid();
16
- if (!this.isValid) {
17
- console.error("Invalid date:", value);
29
+ __publicField(this, "isDateValid", true);
30
+ this.value = dayjs(pValue).locale("pt-br");
31
+ this.isDateValid = this.value.isValid();
32
+ if (!this.isDateValid) {
33
+ console.error("Invalid date:", pValue);
18
34
  }
19
35
  }
36
+ static isValid(value) {
37
+ return dayjs(value || "").isValid();
38
+ }
39
+ returnHandler(value, onInvalid) {
40
+ return this.isDateValid ? value : onInvalid;
41
+ }
42
+ get isValid() {
43
+ return this.isDateValid;
44
+ }
20
45
  get jsDate() {
21
46
  return this.value.toDate();
22
47
  }
23
48
  get timestamp() {
24
- return this.isValid ? this.jsDate.getTime() : NaN;
49
+ return this.returnHandler(this.jsDate.getTime(), NaN);
25
50
  }
26
51
  get isoDate() {
27
- return this.isValid ? this.value.format("YYYY-MM-DD") : "";
52
+ return this.returnHandler(this.value.format("YYYY-MM-DD"), "");
28
53
  }
29
54
  get isoString() {
30
- return this.isValid ? this.value.format("YYYY-MM-DDTHH:mm:ss") : "";
55
+ return this.returnHandler(this.value.format("YYYY-MM-DDTHH:mm:ss"), "");
31
56
  }
32
57
  get dateString() {
33
- return this.isValid ? this.value.format("DD/MM/YYYY") : "";
58
+ return this.returnHandler(this.value.format("DD/MM/YYYY"), "");
34
59
  }
35
60
  get longDayMonth() {
36
- return this.isValid ? this.value.format("DD [de] MMMM") : "";
61
+ return this.returnHandler(this.value.format("DD [de] MMMM"), "");
62
+ }
63
+ get shortDayMonth() {
64
+ return this.returnHandler(this.value.format("DD MMM"), "");
37
65
  }
38
66
  get longDateString() {
39
- return this.isValid ? this.value.format("DD [de] MMMM [de] YYYY") : "";
67
+ return this.returnHandler(this.value.format("DD [de] MMMM [de] YYYY"), "");
40
68
  }
41
69
  get timeString() {
42
- return this.isValid ? this.value.format("HH:mm") : "";
70
+ return this.returnHandler(this.value.format("HH:mm"), "");
71
+ }
72
+ get daysInMonth() {
73
+ return this.returnHandler(this.value.daysInMonth(), 0);
43
74
  }
44
75
  get dateObj() {
45
- return this.isValid ? {
76
+ return this.returnHandler({
46
77
  year: this.value.year(),
47
78
  month: this.value.month(),
48
79
  date: this.value.date(),
49
80
  weekday: this.value.day(),
50
81
  hours: this.value.hour(),
51
82
  minutes: this.value.minute(),
52
- seconds: this.value.second()
53
- } : {
83
+ seconds: this.value.second(),
84
+ milliseconds: this.value.millisecond()
85
+ }, {
54
86
  year: 0,
55
87
  month: 0,
56
88
  date: 0,
57
89
  weekday: 0,
58
90
  hours: 0,
59
91
  minutes: 0,
60
- seconds: 0
61
- };
92
+ seconds: 0,
93
+ milliseconds: 0
94
+ });
95
+ }
96
+ setToStartOf(unit) {
97
+ this.value = this.value.startOf(unit);
98
+ return this;
62
99
  }
63
100
  addDays(days) {
64
- this.value = this.isValid ? this.value.add(days, "day") : this.value;
101
+ this.value = this.isDateValid ? this.value.add(days, "day") : this.value;
65
102
  return this;
66
103
  }
67
104
  addMonths(months) {
68
- this.value = this.isValid ? this.value.add(months, "month") : this.value;
105
+ this.value = this.isDateValid ? this.value.add(months, "month") : this.value;
69
106
  return this;
70
107
  }
71
108
  addYears(years) {
72
- this.value = this.isValid ? this.value.add(years, "year") : this.value;
109
+ this.value = this.isDateValid ? this.value.add(years, "year") : this.value;
110
+ return this;
111
+ }
112
+ addHours(hours) {
113
+ this.value = this.isDateValid ? this.value.add(hours, "hour") : this.value;
114
+ return this;
115
+ }
116
+ addToDate({
117
+ years = 0,
118
+ months = 0,
119
+ weeks = 0,
120
+ days = 0,
121
+ hours = 0,
122
+ minutes = 0,
123
+ seconds = 0
124
+ }) {
125
+ this.value = this.isDateValid ? this.value.add(years, "year").add(months, "month").add(weeks, "week").add(days, "day").add(hours, "hour").add(minutes, "minute").add(seconds, "second") : this.value;
126
+ return this;
127
+ }
128
+ setTo(newValues) {
129
+ const currentValues = this.isDateValid ? {
130
+ year: this.value.year(),
131
+ month: this.value.month(),
132
+ day: this.value.date(),
133
+ hour: this.value.hour(),
134
+ minute: this.value.minute(),
135
+ second: this.value.second(),
136
+ milisecond: this.value.millisecond()
137
+ } : {
138
+ year: 0,
139
+ month: 0,
140
+ day: 0,
141
+ hour: 0,
142
+ minute: 0,
143
+ second: 0,
144
+ milisecond: 0
145
+ };
146
+ const {
147
+ year = currentValues.year,
148
+ month = currentValues.month,
149
+ day = currentValues.day,
150
+ hour = currentValues.hour,
151
+ minute = currentValues.minute,
152
+ second = currentValues.second,
153
+ milisecond = currentValues.milisecond
154
+ } = newValues;
155
+ this.value = this.isDateValid ? this.value.year(year).month(month).date(day).hour(hour).minute(minute).second(second).millisecond(milisecond) : this.value;
73
156
  return this;
74
157
  }
158
+ isBefore(date, unit) {
159
+ return this.returnHandler(this.value.isBefore(date, unit), false);
160
+ }
161
+ isAfter(date, unit) {
162
+ return this.returnHandler(this.value.isAfter(date, unit), false);
163
+ }
164
+ isSame(date, unit) {
165
+ return this.returnHandler(this.value.isSame(date, unit), false);
166
+ }
167
+ isBetween(startingDate, endingDate, unit) {
168
+ const isAfterStartingDate = this.returnHandler(this.value.isAfter(startingDate, unit), false);
169
+ const isBeforeEndingDate = this.returnHandler(this.value.isBefore(endingDate, unit), false);
170
+ const isBetweenDates = isAfterStartingDate && isBeforeEndingDate || !isAfterStartingDate && !isBeforeEndingDate;
171
+ return this.returnHandler(isBetweenDates, false);
172
+ }
173
+ getDiff(date, unit) {
174
+ return this.returnHandler(this.value.diff(date, unit), 0);
175
+ }
176
+ clone() {
177
+ return new SafeDate(this.value);
178
+ }
179
+ format(format) {
180
+ return this.returnHandler(this.value.format(format), "");
181
+ }
75
182
  }
76
183
  const get = (_domain, prefix) => (key) => {
77
184
  const cookies = parseCookies();
@@ -89,7 +196,7 @@ const set = (domain, prefix) => (key, value, options) => {
89
196
  const remove = (_domain, prefix) => (key, options) => {
90
197
  destroyCookie(null, `${prefix}-${key}`, options);
91
198
  };
92
- const clean = (domain, prefix) => (options) => {
199
+ const cleanAuth = (domain, prefix) => (options) => {
93
200
  remove(domain, prefix)("auth-key", options);
94
201
  remove(domain, prefix)("user", options);
95
202
  remove(domain, prefix)("company", options);
@@ -102,6 +209,118 @@ const AppStorageProvider = ({
102
209
  get: get(cookieDomain, cookiePrefix),
103
210
  set: set(cookieDomain, cookiePrefix),
104
211
  remove: remove(cookieDomain, cookiePrefix),
105
- clean: clean(cookieDomain, cookiePrefix)
212
+ cleanAuth: cleanAuth(cookieDomain, cookiePrefix)
106
213
  });
107
- export { AppStorageProvider, SafeDate };
214
+ const isServer = typeof window === "undefined";
215
+ const isIpv4 = (str) => /(^(\d{1,3}\.){3}(\d{1,3})(:\d{1,5})?$)/.test(str);
216
+ const isLocalhost = (host) => {
217
+ const APP_ENVIRONMENT = {}.NEXT_PUBLIC_APP_ENV || {}.REACT_APP_ENVIRONMENT || {}.REACT_APP_ENV || "production";
218
+ return APP_ENVIRONMENT === "local" && (host.includes("localhost") || isIpv4(host));
219
+ };
220
+ const getYupValidationErrors = (err) => {
221
+ var _a;
222
+ const validationErrors = {};
223
+ if ((_a = err == null ? void 0 : err.inner) == null ? void 0 : _a.length) {
224
+ err.inner.forEach((error) => {
225
+ validationErrors[(error == null ? void 0 : error.path) || "unknown"] = error.message;
226
+ });
227
+ } else if ((err == null ? void 0 : err.path) && (err == null ? void 0 : err.message)) {
228
+ validationErrors[err.path] = err.message;
229
+ } else if (!(err == null ? void 0 : err.path) && (err == null ? void 0 : err.type) === "typeError") {
230
+ validationErrors.body = err.errors[0];
231
+ }
232
+ return validationErrors;
233
+ };
234
+ const checkIoIntegrity = async ({
235
+ name = "",
236
+ url = "",
237
+ req = {},
238
+ res = {},
239
+ schema = object()
240
+ }) => {
241
+ var _a;
242
+ if (isServer)
243
+ return;
244
+ if (!isLocalhost((_a = window == null ? void 0 : window.location) == null ? void 0 : _a.hostname))
245
+ return;
246
+ schema.validate(res, { abortEarly: false }).catch((err) => {
247
+ const validationErrors = getYupValidationErrors(err);
248
+ console.warn(`PLEASE check the backend IO for >> ${name} <<, some discrepancies were found in the expected response`, {
249
+ functionName: name,
250
+ endPoint: url,
251
+ request: req,
252
+ response: res,
253
+ validationErrors
254
+ });
255
+ });
256
+ };
257
+ const createCheckStatusCodeFn = (onStatusCode) => (res) => {
258
+ if (onStatusCode && (res == null ? void 0 : res.status)) {
259
+ const statusCode = res.status;
260
+ const handler = onStatusCode[statusCode];
261
+ if (handler)
262
+ handler(res);
263
+ }
264
+ };
265
+ const handleIOSuccess = (integrityCheck) => (res) => {
266
+ var _a, _b;
267
+ if (integrityCheck && integrityCheck.name && integrityCheck.schema) {
268
+ checkIoIntegrity({
269
+ name: integrityCheck.name,
270
+ schema: integrityCheck.schema,
271
+ req: { body: ((_a = res == null ? void 0 : res.config) == null ? void 0 : _a.data) || null, query: (_b = res == null ? void 0 : res.config) == null ? void 0 : _b.params },
272
+ res: res == null ? void 0 : res.data,
273
+ url: res == null ? void 0 : res.request.url
274
+ });
275
+ }
276
+ return [res.data, null, { status: res.status }];
277
+ };
278
+ const handleIOError = (errorParser) => (err) => {
279
+ var _a, _b, _c;
280
+ const resData = (_a = err == null ? void 0 : err.response) == null ? void 0 : _a.data;
281
+ const errors = errorParser ? errorParser(resData || null) : void 0;
282
+ return [
283
+ null,
284
+ {
285
+ status: ((_b = err == null ? void 0 : err.response) == null ? void 0 : _b.status) || 599,
286
+ message: (resData == null ? void 0 : resData.message) || (resData == null ? void 0 : resData.msg) || "Unknown IO Error",
287
+ errorData: resData || null,
288
+ errors
289
+ },
290
+ {
291
+ status: ((_c = err == null ? void 0 : err.response) == null ? void 0 : _c.status) || 599
292
+ }
293
+ ];
294
+ };
295
+ const createIoInstance = (baseUrl, options) => {
296
+ const {
297
+ withAuth = false,
298
+ authKey = "",
299
+ ioIntegrityCheck,
300
+ onStatusCode,
301
+ errorParser
302
+ } = options || {};
303
+ const instance = axios.create({
304
+ baseURL: baseUrl,
305
+ headers: withAuth ? {
306
+ "Content-Type": "application/json",
307
+ Authorization: authKey || "no_auth_key"
308
+ } : { "Content-Type": "application/json" }
309
+ });
310
+ const checkStatusCode = createCheckStatusCodeFn(onStatusCode);
311
+ instance.interceptors.response.use((res) => {
312
+ checkStatusCode(res);
313
+ return res;
314
+ }, (error) => {
315
+ if (error == null ? void 0 : error.response)
316
+ checkStatusCode(error.response);
317
+ throw error;
318
+ });
319
+ return {
320
+ get: (url, params, config = {}) => instance.get(url, __spreadValues({ params }, config)).then(handleIOSuccess(ioIntegrityCheck)).catch(handleIOError(errorParser)),
321
+ post: (url, data, config) => instance.post(url, data, config).then(handleIOSuccess(ioIntegrityCheck)).catch(handleIOError(errorParser)),
322
+ patch: (url, data, config) => instance.patch(url, data, config).then(handleIOSuccess(ioIntegrityCheck)).catch(handleIOError(errorParser)),
323
+ delete: (url, params, config = {}) => instance.delete(url, __spreadValues({ params }, config)).then(handleIOSuccess(ioIntegrityCheck)).catch(handleIOError(errorParser))
324
+ };
325
+ };
326
+ export { AppStorageProvider, SafeDate, createIoInstance };
@@ -1 +1 @@
1
- (function(s,a){typeof exports=="object"&&typeof module!="undefined"?a(exports,require("dayjs"),require("dayjs/locale/pt-br"),require("nookies")):typeof define=="function"&&define.amd?define(["exports","dayjs","dayjs/locale/pt-br","nookies"],a):(s=typeof globalThis!="undefined"?globalThis:s||self,a(s.BinamikJSProviders={},s.dayjs,null,s.nookies))})(this,function(s,a,r,l){"use strict";var M=Object.defineProperty;var D=(s,a,r)=>a in s?M(s,a,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[a]=r;var h=(s,a,r)=>(D(s,typeof a!="symbol"?a+"":a,r),r);function v(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var o=v(a);class m{constructor(e){h(this,"value",o.default());h(this,"isValid",!0);this.value=o.default(e).locale("pt-br"),this.isValid=this.value.isValid(),this.isValid||console.error("Invalid date:",e)}get jsDate(){return this.value.toDate()}get timestamp(){return this.isValid?this.jsDate.getTime():NaN}get isoDate(){return this.isValid?this.value.format("YYYY-MM-DD"):""}get isoString(){return this.isValid?this.value.format("YYYY-MM-DDTHH:mm:ss"):""}get dateString(){return this.isValid?this.value.format("DD/MM/YYYY"):""}get longDayMonth(){return this.isValid?this.value.format("DD [de] MMMM"):""}get longDateString(){return this.isValid?this.value.format("DD [de] MMMM [de] YYYY"):""}get timeString(){return this.isValid?this.value.format("HH:mm"):""}get dateObj(){return this.isValid?{year:this.value.year(),month:this.value.month(),date:this.value.date(),weekday:this.value.day(),hours:this.value.hour(),minutes:this.value.minute(),seconds:this.value.second()}:{year:0,month:0,date:0,weekday:0,hours:0,minutes:0,seconds:0}}addDays(e){return this.value=this.isValid?this.value.add(e,"day"):this.value,this}addMonths(e){return this.value=this.isValid?this.value.add(e,"month"):this.value,this}addYears(e){return this.value=this.isValid?this.value.add(e,"year"):this.value,this}}const y=(t,e)=>i=>l.parseCookies()[`${e}-${i}`],c=(t,e)=>(i,d,n)=>{l.setCookie(null,`${e}-${i}`,d,{maxAge:(n==null?void 0:n.maxAge)||60*60*24*90,path:"/",domain:t,secure:!0,httpOnly:!0})},u=(t,e)=>(i,d)=>{l.destroyCookie(null,`${e}-${i}`,d)},f=(t,e)=>i=>{u(t,e)("auth-key",i),u(t,e)("user",i),u(t,e)("company",i),u(t,e)("orb-selected",i)},g=({cookieDomain:t,cookiePrefix:e})=>({get:y(t,e),set:c(t,e),remove:u(t,e),clean:f(t,e)});s.AppStorageProvider=g,s.SafeDate=m,Object.defineProperties(s,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
1
+ (function(n,i){typeof exports=="object"&&typeof module!="undefined"?i(exports,require("dayjs"),require("dayjs/locale/pt-br"),require("nookies"),require("axios"),require("yup")):typeof define=="function"&&define.amd?define(["exports","dayjs","dayjs/locale/pt-br","nookies","axios","yup"],i):(n=typeof globalThis!="undefined"?globalThis:n||self,i(n.BinamikJSProviders={},n.dayjs,null,n.nookies,n.axios,n.yup))})(this,function(n,i,o,g,S,_){"use strict";var $=Object.defineProperty;var I=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable;var H=(n,i,o)=>i in n?$(n,i,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[i]=o,E=(n,i)=>{for(var o in i||(i={}))R.call(i,o)&&H(n,o,i[o]);if(I)for(var o of I(i))L.call(i,o)&&H(n,o,i[o]);return n};var V=(n,i,o)=>(H(n,typeof i!="symbol"?i+"":i,o),o);function A(e){return e&&typeof e=="object"&&"default"in e?e:{default:e}}var D=A(i),Y=A(S);class M{constructor(t){V(this,"value",D.default());V(this,"isDateValid",!0);this.value=D.default(t).locale("pt-br"),this.isDateValid=this.value.isValid(),this.isDateValid||console.error("Invalid date:",t)}static isValid(t){return D.default(t||"").isValid()}returnHandler(t,a){return this.isDateValid?t:a}get isValid(){return this.isDateValid}get jsDate(){return this.value.toDate()}get timestamp(){return this.returnHandler(this.jsDate.getTime(),NaN)}get isoDate(){return this.returnHandler(this.value.format("YYYY-MM-DD"),"")}get isoString(){return this.returnHandler(this.value.format("YYYY-MM-DDTHH:mm:ss"),"")}get dateString(){return this.returnHandler(this.value.format("DD/MM/YYYY"),"")}get longDayMonth(){return this.returnHandler(this.value.format("DD [de] MMMM"),"")}get shortDayMonth(){return this.returnHandler(this.value.format("DD MMM"),"")}get longDateString(){return this.returnHandler(this.value.format("DD [de] MMMM [de] YYYY"),"")}get timeString(){return this.returnHandler(this.value.format("HH:mm"),"")}get daysInMonth(){return this.returnHandler(this.value.daysInMonth(),0)}get dateObj(){return this.returnHandler({year:this.value.year(),month:this.value.month(),date:this.value.date(),weekday:this.value.day(),hours:this.value.hour(),minutes:this.value.minute(),seconds:this.value.second(),milliseconds:this.value.millisecond()},{year:0,month:0,date:0,weekday:0,hours:0,minutes:0,seconds:0,milliseconds:0})}setToStartOf(t){return this.value=this.value.startOf(t),this}addDays(t){return this.value=this.isDateValid?this.value.add(t,"day"):this.value,this}addMonths(t){return this.value=this.isDateValid?this.value.add(t,"month"):this.value,this}addYears(t){return this.value=this.isDateValid?this.value.add(t,"year"):this.value,this}addHours(t){return this.value=this.isDateValid?this.value.add(t,"hour"):this.value,this}addToDate({years:t=0,months:a=0,weeks:s=0,days:u=0,hours:h=0,minutes:d=0,seconds:r=0}){return this.value=this.isDateValid?this.value.add(t,"year").add(a,"month").add(s,"week").add(u,"day").add(h,"hour").add(d,"minute").add(r,"second"):this.value,this}setTo(t){const a=this.isDateValid?{year:this.value.year(),month:this.value.month(),day:this.value.date(),hour:this.value.hour(),minute:this.value.minute(),second:this.value.second(),milisecond:this.value.millisecond()}:{year:0,month:0,day:0,hour:0,minute:0,second:0,milisecond:0},{year:s=a.year,month:u=a.month,day:h=a.day,hour:d=a.hour,minute:r=a.minute,second:p=a.second,milisecond:l=a.milisecond}=t;return this.value=this.isDateValid?this.value.year(s).month(u).date(h).hour(d).minute(r).second(p).millisecond(l):this.value,this}isBefore(t,a){return this.returnHandler(this.value.isBefore(t,a),!1)}isAfter(t,a){return this.returnHandler(this.value.isAfter(t,a),!1)}isSame(t,a){return this.returnHandler(this.value.isSame(t,a),!1)}isBetween(t,a,s){const u=this.returnHandler(this.value.isAfter(t,s),!1),h=this.returnHandler(this.value.isBefore(a,s),!1),d=u&&h||!u&&!h;return this.returnHandler(d,!1)}getDiff(t,a){return this.returnHandler(this.value.diff(t,a),0)}clone(){return new M(this.value)}format(t){return this.returnHandler(this.value.format(t),"")}}const w=(e,t)=>a=>g.parseCookies()[`${t}-${a}`],T=(e,t)=>(a,s,u)=>{g.setCookie(null,`${t}-${a}`,s,{maxAge:(u==null?void 0:u.maxAge)||60*60*24*90,path:"/",domain:e,secure:!0,httpOnly:!0})},m=(e,t)=>(a,s)=>{g.destroyCookie(null,`${t}-${a}`,s)},j=(e,t)=>a=>{m(e,t)("auth-key",a),m(e,t)("user",a),m(e,t)("company",a),m(e,t)("orb-selected",a)},N=({cookieDomain:e,cookiePrefix:t})=>({get:w(e,t),set:T(e,t),remove:m(e,t),cleanAuth:j(e,t)}),P=typeof window=="undefined",O=e=>/(^(\d{1,3}\.){3}(\d{1,3})(:\d{1,5})?$)/.test(e),b=e=>({}.NEXT_PUBLIC_APP_ENV||{}.REACT_APP_ENVIRONMENT||{}.REACT_APP_ENV||"production")==="local"&&(e.includes("localhost")||O(e)),k=e=>{var a;const t={};return(a=e==null?void 0:e.inner)!=null&&a.length?e.inner.forEach(s=>{t[(s==null?void 0:s.path)||"unknown"]=s.message}):(e==null?void 0:e.path)&&(e==null?void 0:e.message)?t[e.path]=e.message:!(e!=null&&e.path)&&(e==null?void 0:e.type)==="typeError"&&(t.body=e.errors[0]),t},q=async({name:e="",url:t="",req:a={},res:s={},schema:u=_.object()})=>{var h;P||!b((h=window==null?void 0:window.location)==null?void 0:h.hostname)||u.validate(s,{abortEarly:!1}).catch(d=>{const r=k(d);console.warn(`PLEASE check the backend IO for >> ${e} <<, some discrepancies were found in the expected response`,{functionName:e,endPoint:t,request:a,response:s,validationErrors:r})})},B=e=>t=>{if(e&&(t==null?void 0:t.status)){const a=t.status,s=e[a];s&&s(t)}},f=e=>t=>{var a,s;return e&&e.name&&e.schema&&q({name:e.name,schema:e.schema,req:{body:((a=t==null?void 0:t.config)==null?void 0:a.data)||null,query:(s=t==null?void 0:t.config)==null?void 0:s.params},res:t==null?void 0:t.data,url:t==null?void 0:t.request.url}),[t.data,null,{status:t.status}]},y=e=>t=>{var u,h,d;const a=(u=t==null?void 0:t.response)==null?void 0:u.data,s=e?e(a||null):void 0;return[null,{status:((h=t==null?void 0:t.response)==null?void 0:h.status)||599,message:(a==null?void 0:a.message)||(a==null?void 0:a.msg)||"Unknown IO Error",errorData:a||null,errors:s},{status:((d=t==null?void 0:t.response)==null?void 0:d.status)||599}]},C=(e,t)=>{const{withAuth:a=!1,authKey:s="",ioIntegrityCheck:u,onStatusCode:h,errorParser:d}=t||{},r=Y.default.create({baseURL:e,headers:a?{"Content-Type":"application/json",Authorization:s||"no_auth_key"}:{"Content-Type":"application/json"}}),p=B(h);return r.interceptors.response.use(l=>(p(l),l),l=>{throw l!=null&&l.response&&p(l.response),l}),{get:(l,c,v={})=>r.get(l,E({params:c},v)).then(f(u)).catch(y(d)),post:(l,c,v)=>r.post(l,c,v).then(f(u)).catch(y(d)),patch:(l,c,v)=>r.patch(l,c,v).then(f(u)).catch(y(d)),delete:(l,c,v={})=>r.delete(l,E({params:c},v)).then(f(u)).catch(y(d))}};n.AppStorageProvider=N,n.SafeDate=M,n.createIoInstance=C,Object.defineProperties(n,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  export { SafeDate } from './SafeDate/SafeDate';
2
2
  export type { SafeDate as SafeDateType } from './SafeDate/SafeDate';
3
3
  export { AppStorageProvider } from './AppStorageProvider/AppStorageProvider';
4
+ export { createIoInstance } from './IoProvider/IoProvider';
5
+ export type { ApiResponseDTO } from './IoProvider/IoProvider';
@@ -0,0 +1 @@
1
+ export declare const identity: <T>(x: T) => T;
@@ -0,0 +1,4 @@
1
+ export * from './identity';
2
+ export * from './isServer';
3
+ export * from './isLocalhost';
4
+ export * from './yup/getYupValidationErrors';
@@ -0,0 +1 @@
1
+ export declare const isLocalhost: (host: string) => boolean;
@@ -0,0 +1 @@
1
+ export declare const isServer: boolean;
@@ -0,0 +1,2 @@
1
+ import { ValidationError } from 'yup';
2
+ export declare const getYupValidationErrors: (err: ValidationError) => Record<string, string>;
package/package.json CHANGED
@@ -1,12 +1,11 @@
1
1
  {
2
2
  "name": "@binamik/js-providers",
3
- "version": "0.1.1",
3
+ "version": "0.1.5",
4
4
  "scripts": {
5
5
  "dev": "vite",
6
6
  "build": "tsc && vite build",
7
7
  "test": "vitest",
8
- "lint": "eslint",
9
- "publish": "vitest && eslint && yarn build && npm publish"
8
+ "lint": "eslint"
10
9
  },
11
10
  "devDependencies": {
12
11
  "@types/node": "^17.0.41",
@@ -39,13 +38,13 @@
39
38
  "files": [
40
39
  "dist"
41
40
  ],
42
- "main": "./dist/binamik-providers.umd.js",
43
- "module": "./dist/binamik-providers.es.js",
41
+ "main": "./dist/binamik-js-providers.umd.js",
42
+ "module": "./dist/binamik-js-providers.es.js",
44
43
  "types": "./dist/index.d.ts",
45
44
  "exports": {
46
45
  ".": {
47
- "import": "./dist/binamik-providers.es.js",
48
- "require": "./dist/binamik-providers.umd.js"
46
+ "import": "./dist/binamik-js-providers.es.js",
47
+ "require": "./dist/binamik-js-providers.umd.js"
49
48
  }
50
49
  }
51
50
  }