@cloudsignal/pwa-sdk 1.1.1 → 1.2.1
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.
- package/CHANGELOG.md +68 -0
- package/README.md +67 -1
- package/dist/chunk-IMM7VF4N.js +97 -0
- package/dist/chunk-IMM7VF4N.js.map +1 -0
- package/dist/hmac-LWLR6F7Z.js +3 -0
- package/dist/hmac-LWLR6F7Z.js.map +1 -0
- package/dist/index.cjs +296 -100
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +150 -9
- package/dist/index.d.ts +150 -9
- package/dist/index.global.js +7 -7
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +182 -101
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,74 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.2.0] - 2025-01-17
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **JWT Authentication** - User-linked registrations via JWT tokens from identity providers
|
|
13
|
+
- **Dual Auth Mode** - Support both HMAC (anonymous) and JWT (authenticated) authentication
|
|
14
|
+
- `userToken` config option for JWT tokens (Supabase, Firebase, Auth0, Clerk, custom OIDC)
|
|
15
|
+
- `onTokenExpired` callback for automatic token refresh on 401 errors
|
|
16
|
+
- `setUserToken()` method to upgrade from anonymous to authenticated registration
|
|
17
|
+
- `getAuthMode()` method to check current auth mode ('hmac' | 'jwt')
|
|
18
|
+
- `auth:tokenUpdated` event emitted when auth token is updated/upgraded
|
|
19
|
+
- Full TypeScript types for JWT auth utilities
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- All API calls now support both HMAC signature and JWT Bearer token authentication
|
|
24
|
+
- Registration API extracts user_id and user_email from JWT claims when in JWT mode
|
|
25
|
+
|
|
26
|
+
### Use Case
|
|
27
|
+
|
|
28
|
+
Enables smart notification routing - send in-app notifications when users are online (MQTT connected) and web push when offline by linking registrations to authenticated user identities.
|
|
29
|
+
|
|
30
|
+
## [1.1.1] - 2025-01-17
|
|
31
|
+
|
|
32
|
+
### Added
|
|
33
|
+
|
|
34
|
+
- **Vitest Test Framework** - Comprehensive unit test suite with jsdom environment
|
|
35
|
+
- **DeviceDetector Tests** - 16 tests covering device/browser/OS detection
|
|
36
|
+
- **WakeLockManager Tests** - 16 tests covering screen wake lock functionality
|
|
37
|
+
- **i18n Translation Tests** - 18 tests covering all 20 supported languages
|
|
38
|
+
- **Fingerprint Tests** - 7 tests covering unique device fingerprint generation
|
|
39
|
+
- `test:coverage` script for code coverage reporting
|
|
40
|
+
- Total: 57 unit tests passing
|
|
41
|
+
|
|
42
|
+
## [1.1.0] - 2025-01-17
|
|
43
|
+
|
|
44
|
+
### Added
|
|
45
|
+
|
|
46
|
+
- **Screen Wake Lock** - Prevent screen sleep during critical operations (WakeLockManager)
|
|
47
|
+
- **Offline Request Queue** - IndexedDB-backed queue with exponential backoff retry (OfflineQueueManager)
|
|
48
|
+
- **iOS Install Banner** - Beautiful modal guiding iOS Safari users to install (IOSInstallBanner)
|
|
49
|
+
- **20-Language i18n** - Auto-detects browser language for iOS banner
|
|
50
|
+
- Supported: en, es, fr, de, it, pt, nl, ru, zh, ja, ko, ar, he, hi, tr, pl, sv, da, no, fi
|
|
51
|
+
- **Network-Aware Heartbeat** - Auto-adjusts interval based on connection type (4G=30s, 3G=60s, 2G=120s)
|
|
52
|
+
- **Battery-Aware Heartbeat** - Pauses heartbeat when battery <15% and not charging
|
|
53
|
+
- **Notification Analytics** - Track displayed/clicked/dismissed events in service worker
|
|
54
|
+
- **Save Data Respect** - Reduces heartbeat frequency when user has Save Data enabled
|
|
55
|
+
|
|
56
|
+
### New Config Options
|
|
57
|
+
|
|
58
|
+
- `wakeLock` - Screen wake lock configuration
|
|
59
|
+
- `offlineQueue` - Offline request queue settings
|
|
60
|
+
- `iosInstallBanner` - iOS install banner customization
|
|
61
|
+
- `notificationAnalytics` - Analytics tracking settings
|
|
62
|
+
|
|
63
|
+
### New Events
|
|
64
|
+
|
|
65
|
+
- `wakeLock:acquired`, `wakeLock:released`, `wakeLock:error`
|
|
66
|
+
- `offlineQueue:queued`, `offlineQueue:processed`, `offlineQueue:flushed`
|
|
67
|
+
- `iosBanner:shown`, `iosBanner:dismissed`, `iosBanner:installClicked`
|
|
68
|
+
- `heartbeat:intervalChanged`, `heartbeat:pausedForBattery`, `heartbeat:resumedFromBattery`
|
|
69
|
+
|
|
70
|
+
### Browser Support Notes
|
|
71
|
+
|
|
72
|
+
- Wake Lock: All modern browsers as of March 2025
|
|
73
|
+
- Battery API: Chromium-based browsers only
|
|
74
|
+
- Network Information API: Chromium-based browsers (graceful fallback)
|
|
75
|
+
|
|
8
76
|
## [1.0.0] - 2025-01-14
|
|
9
77
|
|
|
10
78
|
### Added
|
package/README.md
CHANGED
|
@@ -12,6 +12,12 @@ Progressive Web App SDK for CloudSignal platform with push notifications, instal
|
|
|
12
12
|
- **Service Worker** - Badge management, notification history, offline support
|
|
13
13
|
- **TypeScript** - Full type definitions included
|
|
14
14
|
|
|
15
|
+
### v1.2.0 Features
|
|
16
|
+
- **JWT Authentication** - User-linked registrations via JWT tokens (Supabase, Firebase, Auth0, Clerk)
|
|
17
|
+
- **Dual Auth Mode** - HMAC for anonymous users, JWT for authenticated users
|
|
18
|
+
- **Smart Notification Routing** - Enable in-app vs web push based on user online status
|
|
19
|
+
- **Token Refresh** - Automatic retry on 401 with `onTokenExpired` callback
|
|
20
|
+
|
|
15
21
|
### v1.1.0 Features
|
|
16
22
|
- **Screen Wake Lock** - Prevent screen sleep during critical operations
|
|
17
23
|
- **Offline Request Queue** - IndexedDB-backed queue with auto-retry when online
|
|
@@ -87,6 +93,50 @@ pwa.initialize().then(() => {
|
|
|
87
93
|
</script>
|
|
88
94
|
```
|
|
89
95
|
|
|
96
|
+
### JWT Authentication (v1.2.0)
|
|
97
|
+
|
|
98
|
+
For authenticated user registrations, use JWT instead of HMAC:
|
|
99
|
+
|
|
100
|
+
```javascript
|
|
101
|
+
import { CloudSignalPWA } from '@cloudsignal/pwa-sdk'
|
|
102
|
+
import { supabase } from './supabase' // Your Supabase client
|
|
103
|
+
|
|
104
|
+
const pwa = new CloudSignalPWA({
|
|
105
|
+
organizationId: 'your-org-uuid',
|
|
106
|
+
userToken: (await supabase.auth.getSession()).data.session?.access_token,
|
|
107
|
+
serviceId: 'your-service-uuid',
|
|
108
|
+
onTokenExpired: async () => {
|
|
109
|
+
// Refresh token when 401 received
|
|
110
|
+
const { data } = await supabase.auth.refreshSession()
|
|
111
|
+
return data.session?.access_token || ''
|
|
112
|
+
}
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
await pwa.initialize()
|
|
116
|
+
|
|
117
|
+
// Registration will be linked to the authenticated user
|
|
118
|
+
const registration = await pwa.registerForPush()
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
**Upgrading from Anonymous to Authenticated:**
|
|
122
|
+
|
|
123
|
+
```javascript
|
|
124
|
+
// Start with HMAC (anonymous)
|
|
125
|
+
const pwa = new CloudSignalPWA({
|
|
126
|
+
organizationId: 'your-org-uuid',
|
|
127
|
+
organizationSecret: 'your-secret-key',
|
|
128
|
+
serviceId: 'your-service-uuid'
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
await pwa.initialize()
|
|
132
|
+
await pwa.registerForPush() // Anonymous registration
|
|
133
|
+
|
|
134
|
+
// Later, when user logs in:
|
|
135
|
+
const userToken = await getUserJWT()
|
|
136
|
+
pwa.setUserToken(userToken)
|
|
137
|
+
await pwa.registerForPush() // Re-register with user identity
|
|
138
|
+
```
|
|
139
|
+
|
|
90
140
|
## API Reference
|
|
91
141
|
|
|
92
142
|
### Constructor
|
|
@@ -100,13 +150,17 @@ new CloudSignalPWA(config: PWAConfig)
|
|
|
100
150
|
| Option | Type | Required | Description |
|
|
101
151
|
|--------|------|----------|-------------|
|
|
102
152
|
| `organizationId` | string | Yes | CloudSignal organization UUID |
|
|
103
|
-
| `organizationSecret` | string |
|
|
153
|
+
| `organizationSecret` | string | No* | Organization secret key (HMAC mode) |
|
|
154
|
+
| `userToken` | string | No* | JWT token from identity provider |
|
|
155
|
+
| `onTokenExpired` | function | No | Callback to refresh JWT on 401 |
|
|
104
156
|
| `serviceId` | string | Yes | PWA service UUID |
|
|
105
157
|
| `serviceUrl` | string | No | Service URL (default: `https://pwa.cloudsignal.app`) |
|
|
106
158
|
| `debug` | boolean | No | Enable debug logging |
|
|
107
159
|
| `serviceWorker` | object | No | Service worker config |
|
|
108
160
|
| `heartbeat` | object | No | Heartbeat config |
|
|
109
161
|
|
|
162
|
+
*Either `organizationSecret` or `userToken` must be provided
|
|
163
|
+
|
|
110
164
|
### Initialization
|
|
111
165
|
|
|
112
166
|
```typescript
|
|
@@ -190,6 +244,17 @@ pwa.getNetworkInfo(): NetworkConnectionInfo
|
|
|
190
244
|
await pwa.getBatteryInfo(): Promise<BatteryInfo | null>
|
|
191
245
|
```
|
|
192
246
|
|
|
247
|
+
### Authentication (v1.2.0)
|
|
248
|
+
|
|
249
|
+
```typescript
|
|
250
|
+
// Get current authentication mode
|
|
251
|
+
pwa.getAuthMode(): 'hmac' | 'jwt'
|
|
252
|
+
|
|
253
|
+
// Set/upgrade JWT token (for authenticated users)
|
|
254
|
+
pwa.setUserToken(token: string): void
|
|
255
|
+
// After calling setUserToken, call registerForPush() again to link registration to user
|
|
256
|
+
```
|
|
257
|
+
|
|
193
258
|
### Screen Wake Lock (v1.1.0)
|
|
194
259
|
|
|
195
260
|
```typescript
|
|
@@ -284,6 +349,7 @@ pwa.off(event: PWAEvent, handler: (data) => void): void
|
|
|
284
349
|
| `iosBanner:shown` | iOS install banner shown (v1.1.0) |
|
|
285
350
|
| `iosBanner:dismissed` | iOS install banner dismissed (v1.1.0) |
|
|
286
351
|
| `iosBanner:installClicked` | User clicked install on iOS banner (v1.1.0) |
|
|
352
|
+
| `auth:tokenUpdated` | JWT token updated/upgraded (v1.2.0) |
|
|
287
353
|
| `network:online` | Network came online |
|
|
288
354
|
| `network:offline` | Network went offline |
|
|
289
355
|
| `sw:registered` | Service worker registered |
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CloudSignal PWA SDK v1.0.0
|
|
3
|
+
* https://cloudsignal.io
|
|
4
|
+
* MIT License
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
// src/utils/hmac.ts
|
|
8
|
+
function toHex(buffer) {
|
|
9
|
+
return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
10
|
+
}
|
|
11
|
+
function toBase64(buffer) {
|
|
12
|
+
return btoa(String.fromCharCode(...new Uint8Array(buffer)));
|
|
13
|
+
}
|
|
14
|
+
async function generateHMACSignature(secret, organizationId, timestamp, method, url, body = "") {
|
|
15
|
+
const encoder = new TextEncoder();
|
|
16
|
+
let path;
|
|
17
|
+
let query;
|
|
18
|
+
try {
|
|
19
|
+
const urlObj = url.startsWith("http") ? new URL(url) : new URL(url, "https://pwa.cloudsignal.app");
|
|
20
|
+
path = urlObj.pathname;
|
|
21
|
+
query = urlObj.search ? urlObj.search.slice(1) : "";
|
|
22
|
+
} catch {
|
|
23
|
+
const queryIndex = url.indexOf("?");
|
|
24
|
+
if (queryIndex > -1) {
|
|
25
|
+
path = url.slice(0, queryIndex);
|
|
26
|
+
query = url.slice(queryIndex + 1);
|
|
27
|
+
} else {
|
|
28
|
+
path = url;
|
|
29
|
+
query = "";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const canonicalParts = [
|
|
33
|
+
method.toUpperCase(),
|
|
34
|
+
path,
|
|
35
|
+
query,
|
|
36
|
+
organizationId,
|
|
37
|
+
timestamp
|
|
38
|
+
];
|
|
39
|
+
if (body && body.length > 0) {
|
|
40
|
+
const bodyHashBuffer = await crypto.subtle.digest("SHA-256", encoder.encode(body));
|
|
41
|
+
const bodyHashHex = toHex(bodyHashBuffer);
|
|
42
|
+
canonicalParts.push(bodyHashHex);
|
|
43
|
+
}
|
|
44
|
+
const canonicalString = canonicalParts.join("\n");
|
|
45
|
+
const key = await crypto.subtle.importKey(
|
|
46
|
+
"raw",
|
|
47
|
+
encoder.encode(secret),
|
|
48
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
49
|
+
false,
|
|
50
|
+
["sign"]
|
|
51
|
+
);
|
|
52
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(canonicalString));
|
|
53
|
+
return toBase64(signature);
|
|
54
|
+
}
|
|
55
|
+
async function generateAuthHeaders(organizationId, organizationSecret, method, url, body) {
|
|
56
|
+
const timestamp = Math.floor(Date.now() / 1e3).toString();
|
|
57
|
+
const signature = await generateHMACSignature(
|
|
58
|
+
organizationSecret,
|
|
59
|
+
organizationId,
|
|
60
|
+
timestamp,
|
|
61
|
+
method,
|
|
62
|
+
url,
|
|
63
|
+
body || ""
|
|
64
|
+
);
|
|
65
|
+
return {
|
|
66
|
+
"X-CloudSignal-Organization-ID": organizationId,
|
|
67
|
+
"X-CloudSignal-Timestamp": timestamp,
|
|
68
|
+
"X-CloudSignal-Signature": signature,
|
|
69
|
+
"Content-Type": "application/json"
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
async function makeAuthenticatedRequest(organizationId, organizationSecret, method, url, body) {
|
|
73
|
+
const bodyStr = body ? JSON.stringify(body) : void 0;
|
|
74
|
+
const headers = await generateAuthHeaders(
|
|
75
|
+
organizationId,
|
|
76
|
+
organizationSecret,
|
|
77
|
+
method,
|
|
78
|
+
url,
|
|
79
|
+
bodyStr
|
|
80
|
+
);
|
|
81
|
+
const options = {
|
|
82
|
+
method,
|
|
83
|
+
headers
|
|
84
|
+
};
|
|
85
|
+
if (bodyStr) {
|
|
86
|
+
options.body = bodyStr;
|
|
87
|
+
}
|
|
88
|
+
return fetch(url, options);
|
|
89
|
+
}
|
|
90
|
+
function isValidUUID(value) {
|
|
91
|
+
if (!value || typeof value !== "string") return false;
|
|
92
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export { generateAuthHeaders, generateHMACSignature, isValidUUID, makeAuthenticatedRequest };
|
|
96
|
+
//# sourceMappingURL=chunk-IMM7VF4N.js.map
|
|
97
|
+
//# sourceMappingURL=chunk-IMM7VF4N.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/hmac.ts"],"names":[],"mappings":";;;;;;;AAQA,SAAS,MAAM,MAAA,EAA6B;AAC1C,EAAA,OAAO,MAAM,IAAA,CAAK,IAAI,WAAW,MAAM,CAAC,EACrC,GAAA,CAAI,CAAA,CAAA,KAAK,EAAE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CACxC,KAAK,EAAE,CAAA;AACZ;AAKA,SAAS,SAAS,MAAA,EAA6B;AAC7C,EAAA,OAAO,IAAA,CAAK,OAAO,YAAA,CAAa,GAAG,IAAI,UAAA,CAAW,MAAM,CAAC,CAAC,CAAA;AAC5D;AAaA,eAAsB,sBACpB,MAAA,EACA,cAAA,EACA,WACA,MAAA,EACA,GAAA,EACA,OAAe,EAAA,EACE;AACjB,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAGhC,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI,KAAA;AAEJ,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,GAAA,CAAI,UAAA,CAAW,MAAM,CAAA,GAChC,IAAI,GAAA,CAAI,GAAG,CAAA,GACX,IAAI,GAAA,CAAI,GAAA,EAAK,6BAA6B,CAAA;AAC9C,IAAA,IAAA,GAAO,MAA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EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,UAAU,OAAO,KAAA;AAChD,EAAA,OAAO,4EAAA,CAA6E,KAAK,KAAK,CAAA;AAChG","file":"chunk-IMM7VF4N.js","sourcesContent":["/**\n * HMAC Authentication Utilities\n * Implements CloudSignal's HMAC signature scheme for API authentication\n */\n\n/**\n * Convert ArrayBuffer to hex string\n */\nfunction toHex(buffer: ArrayBuffer): string {\n return Array.from(new Uint8Array(buffer))\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Convert ArrayBuffer to base64 string\n */\nfunction toBase64(buffer: ArrayBuffer): string {\n return btoa(String.fromCharCode(...new Uint8Array(buffer)))\n}\n\n/**\n * Generate HMAC signature for CloudSignal API requests\n * \n * @param secret - Organization secret key\n * @param organizationId - Organization UUID\n * @param timestamp - Unix timestamp string\n * @param method - HTTP method (GET, POST, etc.)\n * @param url - Full URL or path\n * @param body - Request body (optional)\n * @returns Base64-encoded HMAC signature\n */\nexport async function generateHMACSignature(\n secret: string,\n organizationId: string,\n timestamp: string,\n method: string,\n url: string,\n body: string = ''\n): Promise<string> {\n const encoder = new TextEncoder()\n\n // Parse URL to extract path and query\n let path: string\n let query: string\n\n try {\n const urlObj = url.startsWith('http')\n ? new URL(url)\n : new URL(url, 'https://pwa.cloudsignal.app')\n path = urlObj.pathname\n query = urlObj.search ? urlObj.search.slice(1) : ''\n } catch {\n // Fallback for simple paths\n const queryIndex = url.indexOf('?')\n if (queryIndex > -1) {\n path = url.slice(0, queryIndex)\n query = url.slice(queryIndex + 1)\n } else {\n path = url\n query = ''\n }\n }\n\n // Build canonical string parts\n const canonicalParts = [\n method.toUpperCase(),\n path,\n query,\n organizationId,\n timestamp,\n ]\n\n // Add body hash if body is present\n if (body && body.length > 0) {\n const bodyHashBuffer = await crypto.subtle.digest('SHA-256', encoder.encode(body))\n const bodyHashHex = toHex(bodyHashBuffer)\n canonicalParts.push(bodyHashHex)\n }\n\n // Join parts with newlines\n const canonicalString = canonicalParts.join('\\n')\n\n // Import secret as HMAC key\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n )\n\n // Sign the canonical string\n const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(canonicalString))\n\n return toBase64(signature)\n}\n\n/**\n * Generate authentication headers for CloudSignal API requests\n * \n * @param organizationId - Organization UUID\n * @param organizationSecret - Organization secret key\n * @param method - HTTP method\n * @param url - Request URL\n * @param body - Request body (optional)\n * @returns Headers object with authentication headers\n */\nexport async function generateAuthHeaders(\n organizationId: string,\n organizationSecret: string,\n method: string,\n url: string,\n body?: string\n): Promise<Record<string, string>> {\n const timestamp = Math.floor(Date.now() / 1000).toString()\n \n const signature = await generateHMACSignature(\n organizationSecret,\n organizationId,\n timestamp,\n method,\n url,\n body || ''\n )\n\n return {\n 'X-CloudSignal-Organization-ID': organizationId,\n 'X-CloudSignal-Timestamp': timestamp,\n 'X-CloudSignal-Signature': signature,\n 'Content-Type': 'application/json',\n }\n}\n\n/**\n * Make an authenticated request to CloudSignal API\n * \n * @param organizationId - Organization UUID\n * @param organizationSecret - Organization secret key\n * @param method - HTTP method\n * @param url - Request URL\n * @param body - Request body (optional)\n * @returns Fetch Response\n */\nexport async function makeAuthenticatedRequest(\n organizationId: string,\n organizationSecret: string,\n method: string,\n url: string,\n body?: Record<string, any>\n): Promise<Response> {\n const bodyStr = body ? JSON.stringify(body) : undefined\n \n const headers = await generateAuthHeaders(\n organizationId,\n organizationSecret,\n method,\n url,\n bodyStr\n )\n\n const options: RequestInit = {\n method,\n headers,\n }\n\n if (bodyStr) {\n options.body = bodyStr\n }\n\n return fetch(url, options)\n}\n\n/**\n * Validate UUID format\n * \n * @param value - String to validate\n * @returns Whether the string is a valid UUID\n */\nexport function isValidUUID(value: string | null | undefined): boolean {\n if (!value || typeof value !== 'string') return false\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"hmac-LWLR6F7Z.js"}
|