@fajarmaulana/komerce-lp-helper 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ interface ICheckImage {
2
+ (url: string): Promise<string>;
3
+ }
4
+ interface IConvertBlob {
5
+ (blob: Blob): Promise<string>;
6
+ }
7
+ interface ICreateDownloadAnchor {
8
+ (blob: Blob, options?: {
9
+ filename?: string;
10
+ target?: string;
11
+ }): {
12
+ anchor: HTMLAnchorElement;
13
+ blobUrl: string;
14
+ };
15
+ }
16
+ interface IDownloadBlob {
17
+ (blob: Blob, filename: string): void;
18
+ }
19
+ /**
20
+ * Check if an image URL is valid by attempting to load it.
21
+ *
22
+ * @param url - The image URL to check.
23
+ */
24
+ export declare const checkImage: ICheckImage;
25
+ /**
26
+ * Converts a Blob object into a Base64-encoded data URL string.
27
+ *
28
+ * @param blob - The Blob object to be converted.
29
+ * @returns - A Promise that resolves to a Base64-encoded data URL string.
30
+ */
31
+ export declare const convertBlob: IConvertBlob;
32
+ /**
33
+ * Gets the file extension suggestion based on MIME type
34
+ *
35
+ * @param mimeType - The MIME type string
36
+ * @returns Suggested file extension (without dot)
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const ext = getExtension('application/pdf')
41
+ * console.log(ext) // 'pdf'
42
+ * ```
43
+ */
44
+ export declare function getExtension(mimeType: string): string;
45
+ /**
46
+ * Generates a suggested filename from a Blob based on its MIME type
47
+ *
48
+ * @param blob - The Blob to generate filename for
49
+ * @param prefix - Optional prefix for the filename (default: 'download')
50
+ * @returns Suggested filename with extension
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * const blob = new Blob(['data'], { type: 'application/pdf' })
55
+ * const filename = filenameWithExtension(blob)
56
+ * console.log(filename) // 'download.pdf'
57
+ * ```
58
+ */
59
+ export declare function filenameWithExtension(blob: Blob, prefix?: string): string;
60
+ /**
61
+ * Creates an HTMLAnchorElement configured for downloading a Blob.
62
+ * The anchor has href set to a blob URL and target="_blank".
63
+ *
64
+ * @param blob - The Blob to download
65
+ * @param options - Optional configuration
66
+ * @param options.filename - Default filename for download (can be overridden later with anchor.download)
67
+ * @param options.target - Target attribute for anchor (default: '_blank')
68
+ * @returns Object containing the anchor element and blob URL (for cleanup)
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * const blob = new Blob(['Hello'], { type: 'text/plain' })
73
+ * const { anchor, blobUrl } = createDownloadAnchor(blob, { filename: 'hello.txt' })
74
+ *
75
+ * // Dont forget to cleanup while done
76
+ * URL.revokeObjectURL(blobUrl)
77
+ * ```
78
+ */
79
+ export declare const createDownloadAnchor: ICreateDownloadAnchor;
80
+ /**
81
+ * Triggers a download of a Blob by creating a temporary anchor, clicking it, and cleaning up.
82
+ * This is a one-shot download function that handles all cleanup automatically.
83
+ *
84
+ * @param blob - The Blob to download
85
+ * @param filename - The filename for the download
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * const blob = new Blob(['Hello World'], { type: 'text/plain' })
90
+ * downloadBlob(blob, 'hello.txt')
91
+ * // Download starts immediately, cleanup is automatic
92
+ * ```
93
+ */
94
+ export declare const downloadBlob: IDownloadBlob;
95
+ export {};
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Check if an image URL is valid by attempting to load it.
3
+ *
4
+ * @param url - The image URL to check.
5
+ */
6
+ export var checkImage = function (url) {
7
+ return new Promise(function (resolve) {
8
+ var img = new Image();
9
+ img.src = url;
10
+ img.onload = function () { return resolve(url); };
11
+ img.onerror = function () { return resolve(''); };
12
+ });
13
+ };
14
+ /**
15
+ * Converts a Blob object into a Base64-encoded data URL string.
16
+ *
17
+ * @param blob - The Blob object to be converted.
18
+ * @returns - A Promise that resolves to a Base64-encoded data URL string.
19
+ */
20
+ export var convertBlob = function (blob) {
21
+ return new Promise(function (resolve) {
22
+ var reader = new FileReader();
23
+ reader.onload = function () { return resolve(reader.result); };
24
+ reader.readAsDataURL(blob);
25
+ });
26
+ };
27
+ /**
28
+ * Gets the file extension suggestion based on MIME type
29
+ *
30
+ * @param mimeType - The MIME type string
31
+ * @returns Suggested file extension (without dot)
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const ext = getExtension('application/pdf')
36
+ * console.log(ext) // 'pdf'
37
+ * ```
38
+ */
39
+ export function getExtension(mimeType) {
40
+ var cleanMimeType = mimeType.split(';')[0].trim().toLowerCase();
41
+ var mimeMap = {
42
+ 'application/pdf': 'pdf',
43
+ 'application/msword': 'doc',
44
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
45
+ 'application/vnd.ms-excel': 'xls',
46
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
47
+ 'application/vnd.ms-powerpoint': 'ppt',
48
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
49
+ 'application/vnd.oasis.opendocument.text': 'odt',
50
+ 'application/vnd.oasis.opendocument.spreadsheet': 'ods',
51
+ 'application/vnd.oasis.opendocument.presentation': 'odp',
52
+ 'application/rtf': 'rtf',
53
+ 'application/json': 'json',
54
+ 'application/xml': 'xml',
55
+ 'application/yaml': 'yaml',
56
+ 'text/xml': 'xml',
57
+ 'text/csv': 'csv',
58
+ 'text/plain': 'txt',
59
+ 'text/markdown': 'md',
60
+ 'text/html': 'html',
61
+ 'text/css': 'css',
62
+ 'text/javascript': 'js',
63
+ 'application/javascript': 'js',
64
+ 'application/typescript': 'ts',
65
+ 'application/xhtml+xml': 'xhtml',
66
+ 'application/zip': 'zip',
67
+ 'application/x-rar-compressed': 'rar',
68
+ 'application/x-7z-compressed': '7z',
69
+ 'application/gzip': 'gz',
70
+ 'application/x-tar': 'tar',
71
+ 'application/x-bzip2': 'bz2',
72
+ 'image/png': 'png',
73
+ 'image/jpeg': 'jpg',
74
+ 'image/gif': 'gif',
75
+ 'image/svg+xml': 'svg',
76
+ 'image/webp': 'webp',
77
+ 'image/bmp': 'bmp',
78
+ 'image/tiff': 'tiff',
79
+ 'image/x-icon': 'ico',
80
+ 'image/vnd.microsoft.icon': 'ico',
81
+ 'image/heic': 'heic',
82
+ 'image/heif': 'heif',
83
+ 'image/avif': 'avif',
84
+ 'video/mp4': 'mp4',
85
+ 'video/webm': 'webm',
86
+ 'video/x-msvideo': 'avi',
87
+ 'video/quicktime': 'mov',
88
+ 'video/x-matroska': 'mkv',
89
+ 'video/mpeg': 'mpeg',
90
+ 'video/x-flv': 'flv',
91
+ 'video/3gpp': '3gp',
92
+ 'audio/mpeg': 'mp3',
93
+ 'audio/wav': 'wav',
94
+ 'audio/ogg': 'ogg',
95
+ 'audio/webm': 'weba',
96
+ 'audio/aac': 'aac',
97
+ 'audio/flac': 'flac',
98
+ 'audio/x-m4a': 'm4a',
99
+ 'audio/midi': 'midi',
100
+ 'font/woff': 'woff',
101
+ 'font/woff2': 'woff2',
102
+ 'font/ttf': 'ttf',
103
+ 'font/otf': 'otf',
104
+ 'application/font-woff': 'woff',
105
+ 'application/font-woff2': 'woff2',
106
+ 'application/x-font-ttf': 'ttf',
107
+ 'application/x-font-otf': 'otf',
108
+ 'application/octet-stream': 'bin',
109
+ 'application/x-shockwave-flash': 'swf',
110
+ 'application/vnd.apple.installer+xml': 'mpkg',
111
+ 'application/x-apple-diskimage': 'dmg',
112
+ };
113
+ if (mimeMap[cleanMimeType]) {
114
+ return mimeMap[cleanMimeType];
115
+ }
116
+ var parts = cleanMimeType.split('/');
117
+ if (parts.length === 2) {
118
+ var subtype = parts[1];
119
+ subtype = subtype.replace(/^(x-|vnd\.)/, '');
120
+ subtype = subtype.split('+')[0];
121
+ var dashParts = subtype.split('-');
122
+ subtype = dashParts[dashParts.length - 1];
123
+ if (subtype && /^[a-z0-9]{2,4}$/.test(subtype)) {
124
+ return subtype;
125
+ }
126
+ }
127
+ return 'bin';
128
+ }
129
+ /**
130
+ * Generates a suggested filename from a Blob based on its MIME type
131
+ *
132
+ * @param blob - The Blob to generate filename for
133
+ * @param prefix - Optional prefix for the filename (default: 'download')
134
+ * @returns Suggested filename with extension
135
+ *
136
+ * @example
137
+ * ```ts
138
+ * const blob = new Blob(['data'], { type: 'application/pdf' })
139
+ * const filename = filenameWithExtension(blob)
140
+ * console.log(filename) // 'download.pdf'
141
+ * ```
142
+ */
143
+ export function filenameWithExtension(blob, prefix) {
144
+ if (prefix === void 0) { prefix = 'download'; }
145
+ var ext = getExtension(blob.type);
146
+ return "".concat(prefix, ".").concat(ext);
147
+ }
148
+ /**
149
+ * Creates an HTMLAnchorElement configured for downloading a Blob.
150
+ * The anchor has href set to a blob URL and target="_blank".
151
+ *
152
+ * @param blob - The Blob to download
153
+ * @param options - Optional configuration
154
+ * @param options.filename - Default filename for download (can be overridden later with anchor.download)
155
+ * @param options.target - Target attribute for anchor (default: '_blank')
156
+ * @returns Object containing the anchor element and blob URL (for cleanup)
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * const blob = new Blob(['Hello'], { type: 'text/plain' })
161
+ * const { anchor, blobUrl } = createDownloadAnchor(blob, { filename: 'hello.txt' })
162
+ *
163
+ * // Dont forget to cleanup while done
164
+ * URL.revokeObjectURL(blobUrl)
165
+ * ```
166
+ */
167
+ export var createDownloadAnchor = function (blob, options) {
168
+ var _a;
169
+ var blobUrl = URL.createObjectURL(blob);
170
+ var anchor = document.createElement('a');
171
+ anchor.href = blobUrl;
172
+ anchor.target = (_a = options === null || options === void 0 ? void 0 : options.target) !== null && _a !== void 0 ? _a : '_blank';
173
+ if (options === null || options === void 0 ? void 0 : options.filename) {
174
+ anchor.download = options.filename;
175
+ }
176
+ return { anchor: anchor, blobUrl: blobUrl };
177
+ };
178
+ /**
179
+ * Triggers a download of a Blob by creating a temporary anchor, clicking it, and cleaning up.
180
+ * This is a one-shot download function that handles all cleanup automatically.
181
+ *
182
+ * @param blob - The Blob to download
183
+ * @param filename - The filename for the download
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * const blob = new Blob(['Hello World'], { type: 'text/plain' })
188
+ * downloadBlob(blob, 'hello.txt')
189
+ * // Download starts immediately, cleanup is automatic
190
+ * ```
191
+ */
192
+ export var downloadBlob = function (blob, filename) {
193
+ var _a = createDownloadAnchor(blob, { filename: filename }), anchor = _a.anchor, blobUrl = _a.blobUrl;
194
+ document.body.appendChild(anchor);
195
+ anchor.click();
196
+ document.body.removeChild(anchor);
197
+ setTimeout(function () {
198
+ URL.revokeObjectURL(blobUrl);
199
+ }, 100);
200
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Get a DOM element by its ID.
3
+ *
4
+ * @param id - The ID of the element to get.
5
+ */
6
+ export declare const getById: <T = HTMLElement>(id: string) => T;
7
+ /**
8
+ * Get a DOM element by any valid CSS selector.
9
+ *
10
+ * @param str - A string containing a CSS selector to match an element in the document.
11
+ */
12
+ export declare const getByAny: <T = HTMLElement>(str: string) => T;
13
+ /**
14
+ * Trigger a click event on an element by its ID.
15
+ *
16
+ * @param id - The ID of the element to click.
17
+ */
18
+ export declare const clickById: (id: string) => void;
19
+ /**
20
+ * Focus an element by its ID.
21
+ *
22
+ * @param id - The ID of the element to focus.
23
+ */
24
+ export declare const focusById: (id: string) => void;
25
+ /**
26
+ * Smoothly scrolls the window to an element's position when click on active Link.
27
+ *
28
+ * @param hash - Hash of the link.
29
+ * @param currentHash - Current hash in URL.
30
+ * @param func - Optional function to triggered before main logic.
31
+ */
32
+ export declare const handleHashLink: (hash: string, currentHash: string, func?: () => void) => void;
33
+ /**
34
+ * Get acronym (max 2 characters) from a full name string.
35
+ *
36
+ * @param name - Full name string.
37
+ */
38
+ export declare const acronym: (name: string) => string;
39
+ /**
40
+ * Check primitive data type status of a value
41
+ *
42
+ * @param value
43
+ * @returns - data type status
44
+ */
45
+ export declare const isNotPrimitive: (value: unknown) => value is object;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Get a DOM element by its ID.
3
+ *
4
+ * @param id - The ID of the element to get.
5
+ */
6
+ export var getById = function (id) { return document.getElementById(id); };
7
+ /**
8
+ * Get a DOM element by any valid CSS selector.
9
+ *
10
+ * @param str - A string containing a CSS selector to match an element in the document.
11
+ */
12
+ export var getByAny = function (str) { return document.querySelector(str); };
13
+ /**
14
+ * Trigger a click event on an element by its ID.
15
+ *
16
+ * @param id - The ID of the element to click.
17
+ */
18
+ export var clickById = function (id) {
19
+ var el = getById(id);
20
+ if (el) {
21
+ el.click();
22
+ }
23
+ };
24
+ /**
25
+ * Focus an element by its ID.
26
+ *
27
+ * @param id - The ID of the element to focus.
28
+ */
29
+ export var focusById = function (id) {
30
+ var el = getById(id);
31
+ if (el) {
32
+ el.focus();
33
+ }
34
+ };
35
+ /**
36
+ * Smoothly scrolls the window to an element's position when click on active Link.
37
+ *
38
+ * @param hash - Hash of the link.
39
+ * @param currentHash - Current hash in URL.
40
+ * @param func - Optional function to triggered before main logic.
41
+ */
42
+ export var handleHashLink = function (hash, currentHash, func) {
43
+ if (func)
44
+ func();
45
+ if (hash === currentHash) {
46
+ if (!hash) {
47
+ window.scrollTo({ top: 0, behavior: 'smooth' });
48
+ return;
49
+ }
50
+ var target = getByAny(hash);
51
+ target.scrollIntoView({ behavior: 'smooth' });
52
+ }
53
+ };
54
+ /**
55
+ * Get acronym (max 2 characters) from a full name string.
56
+ *
57
+ * @param name - Full name string.
58
+ */
59
+ export var acronym = function (name) {
60
+ var parts = name.trim().split(/\s+/);
61
+ if (parts.length === 0)
62
+ return '.';
63
+ if (parts.length === 1)
64
+ return parts[0][0].toUpperCase();
65
+ return (parts[0][0] + parts[1][0]).toUpperCase();
66
+ };
67
+ /**
68
+ * Check primitive data type status of a value
69
+ *
70
+ * @param value
71
+ * @returns - data type status
72
+ */
73
+ export var isNotPrimitive = function (value) {
74
+ return typeof value === 'object' && value !== null;
75
+ };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Clear localStorage.
3
+ */
4
+ export declare const clearLocals: () => void;
5
+ /**
6
+ * Removes an item from localStorage by key.
7
+ *
8
+ * @param key - The key of the item to remove.
9
+ */
10
+ export declare const removeLocal: (key: string) => void;
11
+ /**
12
+ * Sets an item in localStorage after serializing it to JSON.
13
+ *
14
+ * @param key - The key under which to store the value.
15
+ * @param value - The value to store (will be JSON-stringified).
16
+ */
17
+ export declare const setLocal: <T>(key: string, value: T) => void;
18
+ /**
19
+ * Sets multiple items in localStorage after serializing it to JSON.
20
+ *
21
+ * @param items - Array of local storage items to set.
22
+ */
23
+ export declare const setLocals: <T extends Record<string, unknown>>(items: { [K in keyof T]: {
24
+ key: K & string;
25
+ value: T[K];
26
+ }; }[keyof T][]) => void;
27
+ /**
28
+ * Retrieves and parses a JSON item from localStorage by key.
29
+ *
30
+ * @param key - The key of the item to retrieve.
31
+ * @returns The parsed value from localStorage, or null if not found.
32
+ */
33
+ export declare const getLocal: <T>(key: string) => T | null;
34
+ /**
35
+ * Retrieves and parses multiple JSON items from localStorage by key.
36
+ *
37
+ * @param keys - The keys of the items to retrieve.
38
+ * @returns The parsed values from localStorage.
39
+ */
40
+ export declare const getLocals: <T extends Record<string, unknown>, K extends keyof T = keyof T>(keys: readonly K[]) => { [P in K]: T[P] | null; };
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Clear localStorage.
3
+ */
4
+ export var clearLocals = function () { return localStorage.clear(); };
5
+ /**
6
+ * Removes an item from localStorage by key.
7
+ *
8
+ * @param key - The key of the item to remove.
9
+ */
10
+ export var removeLocal = function (key) { return localStorage.removeItem(key); };
11
+ /**
12
+ * Sets an item in localStorage after serializing it to JSON.
13
+ *
14
+ * @param key - The key under which to store the value.
15
+ * @param value - The value to store (will be JSON-stringified).
16
+ */
17
+ export var setLocal = function (key, value) { return localStorage.setItem(key, JSON.stringify(value)); };
18
+ /**
19
+ * Sets multiple items in localStorage after serializing it to JSON.
20
+ *
21
+ * @param items - Array of local storage items to set.
22
+ */
23
+ export var setLocals = function (items) {
24
+ items.forEach(function (item) { return setLocal(item.key, item.value); });
25
+ };
26
+ /**
27
+ * Retrieves and parses a JSON item from localStorage by key.
28
+ *
29
+ * @param key - The key of the item to retrieve.
30
+ * @returns The parsed value from localStorage, or null if not found.
31
+ */
32
+ export var getLocal = function (key) {
33
+ var item = localStorage.getItem(key);
34
+ try {
35
+ if (item)
36
+ return JSON.parse(item);
37
+ return null;
38
+ }
39
+ catch (_a) {
40
+ return item;
41
+ }
42
+ };
43
+ /**
44
+ * Retrieves and parses multiple JSON items from localStorage by key.
45
+ *
46
+ * @param keys - The keys of the items to retrieve.
47
+ * @returns The parsed values from localStorage.
48
+ */
49
+ export var getLocals = function (keys) {
50
+ return keys.reduce(function (acc, key) {
51
+ acc[key] = getLocal(key);
52
+ return acc;
53
+ }, {});
54
+ };
@@ -0,0 +1,94 @@
1
+ import { type IApiInterceptor, type TApiConfig, type TApiInstanceOptions, type TApiResponse, type THttpConfig, type TProgress } from './api';
2
+ type TFetchState<T> = {
3
+ data: T | null;
4
+ error: unknown;
5
+ isLoading: boolean;
6
+ cacheKey: string | null;
7
+ };
8
+ type TFetchResult<T> = TFetchState<T> & {
9
+ refetch: () => Promise<TFetchState<T>>;
10
+ };
11
+ type TMutationOptions = Pick<TApiConfig, 'cache' | 'headers' | 'method' | 'signal'> & {
12
+ progress?: 'upload' | 'download';
13
+ queryMutation?: boolean;
14
+ };
15
+ type TMutationResult<TData, TRequest> = {
16
+ mutate: (request?: TRequest) => Promise<TApiResponse<TData>>;
17
+ isLoading: boolean;
18
+ cacheKey: string | null;
19
+ progress: TProgress | null;
20
+ };
21
+ type TInfiniteFetchOptions<T> = {
22
+ initialOffset: number;
23
+ offsetKey?: string;
24
+ setOffset: (lastItems: T, allItems: T[], lastOffset: number) => number | null;
25
+ };
26
+ /**
27
+ * Creates a new API instance with built-in React hooks (`fetch`, `mutation`, `infinite`)
28
+ * for performing typed data fetching and mutations with progress tracking.
29
+ *
30
+ * @param options - Optional configuration for the API instance (e.g. baseURL, default headers).
31
+ * @returns An object containing data hooks (`fetch`, `mutation`, `infinite`), cache manipulation methods, and interceptor registration.
32
+ *
33
+ * @example
34
+ * ```tsx
35
+ * const api = createApi({ baseURL: '/api' })
36
+ *
37
+ * const { data, isLoading, refetch } = api.fetch<User[]>('/users')
38
+ *
39
+ * const { mutate, isLoading, progress } = api.mutation<User, FormData>('/users', { method: 'POST' })
40
+ *
41
+ * const { data, isLoading, refetch } = api.infinite<User[]>('/users', { initialOffset: 0 })
42
+ * ```
43
+ */
44
+ export default function createApi(options?: TApiInstanceOptions): {
45
+ fetch: <T>(url: string, config?: Omit<THttpConfig, "onUpload" | "onDownload">, enabled?: boolean) => TFetchResult<T>;
46
+ mutation: <TData, TRequest = void>(url: string, config?: TMutationOptions) => TMutationResult<TData, TRequest>;
47
+ infinite: <T>(url: string, options: TInfiniteFetchOptions<T>, config?: THttpConfig) => {
48
+ data: T[];
49
+ error: unknown;
50
+ isLoading: boolean;
51
+ hasNextPage: boolean;
52
+ isFetchingNextPage: boolean;
53
+ fetchNextPage: () => Promise<void>;
54
+ refetch: () => Promise<void>;
55
+ };
56
+ /**
57
+ * Retrieves a cached response by its key.
58
+ * @param key - Unique cache key.
59
+ * @returns Cached data or `undefined` if not found.
60
+ */
61
+ getCache: <T>(key: string) => T | undefined;
62
+ /**
63
+ * Stores data in cache.
64
+ * @param key - Cache key.
65
+ * @param data - Data to store.
66
+ * @param ttl - Optional time-to-live in milliseconds.
67
+ */
68
+ setCache: <T>(key: string, data: T, ttl?: number) => void;
69
+ /**
70
+ * Removes a single cached entry.
71
+ * @param key - Cache key to remove.
72
+ */
73
+ removeCache: (key: string) => void;
74
+ /**
75
+ * Clears all cache entries.
76
+ */
77
+ clearCache: () => void;
78
+ /**
79
+ * Registers custom request/response interceptors.
80
+ *
81
+ * @param interceptors - Object containing optional `request`, `response`, and `error` interceptors.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * api.setInterceptors({
86
+ * request: config => config,
87
+ * response: res => res,
88
+ * error: err => Promise.reject(err),
89
+ * })
90
+ * ```
91
+ */
92
+ setInterceptors: (interceptors: IApiInterceptor) => void;
93
+ };
94
+ export {};