mazey 5.5.0 → 5.6.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.
package/lib/index.d.ts CHANGED
@@ -274,6 +274,188 @@ declare function isHit(rate: number): boolean;
274
274
  */
275
275
  declare function inRate(rate: number): boolean;
276
276
 
277
+ /**
278
+ * Package managers supported by {@link derivePackageMetadata}.
279
+ *
280
+ * @category Util
281
+ */
282
+ type PackageManager = "npm" | "pnpm" | "yarn";
283
+ /**
284
+ * Author identity accepted from a package manifest.
285
+ *
286
+ * @category Util
287
+ */
288
+ interface PackageManifestAuthor {
289
+ name: string;
290
+ email?: string;
291
+ url?: string;
292
+ }
293
+ /**
294
+ * Package manifest fields used by {@link derivePackageMetadata}.
295
+ *
296
+ * @category Util
297
+ */
298
+ interface PackageManifest {
299
+ name: string;
300
+ version?: string;
301
+ description?: string;
302
+ license?: string;
303
+ author?: string | PackageManifestAuthor;
304
+ }
305
+ /**
306
+ * Options for {@link derivePackageMetadata}.
307
+ *
308
+ * @category Util
309
+ */
310
+ interface DerivePackageMetadataOptions {
311
+ /** Package manager used in the generated install command. Defaults to `npm`. */
312
+ packageManager?: PackageManager;
313
+ }
314
+ /**
315
+ * Normalized package metadata derived from a package manifest.
316
+ *
317
+ * @category Util
318
+ */
319
+ interface DerivedPackageMetadata {
320
+ name: string;
321
+ version?: string;
322
+ description?: string;
323
+ license?: string;
324
+ author: PackageManifestAuthor;
325
+ unscopedName: string;
326
+ iifeGlobal: string;
327
+ installCommand: string;
328
+ }
329
+ /**
330
+ * Validate basic package identity and derive reusable package metadata.
331
+ *
332
+ * The helper removes an npm scope for bundle naming, converts that unscoped
333
+ * name with {@link toJavaScriptGlobalName}, normalizes the supported author
334
+ * fields, and creates an install command for npm, pnpm, or Yarn.
335
+ *
336
+ * Usage:
337
+ *
338
+ * ```javascript
339
+ * import { derivePackageMetadata } from "mazey";
340
+ *
341
+ * const metadata = derivePackageMetadata(
342
+ * {
343
+ * name: "@example/my-library",
344
+ * version: "1.0.0",
345
+ * author: { name: "Example Maintainer" },
346
+ * },
347
+ * { packageManager: "pnpm" }
348
+ * );
349
+ * console.log(metadata);
350
+ * ```
351
+ *
352
+ * Output:
353
+ *
354
+ * ```text
355
+ * {
356
+ * name: "@example/my-library",
357
+ * version: "1.0.0",
358
+ * description: undefined,
359
+ * license: undefined,
360
+ * author: { name: "Example Maintainer" },
361
+ * unscopedName: "my-library",
362
+ * iifeGlobal: "MY_LIBRARY",
363
+ * installCommand: "pnpm add @example/my-library"
364
+ * }
365
+ * ```
366
+ *
367
+ * @param manifest Package manifest identity fields. The package name is required.
368
+ * @param options Package-manager selection for the install command.
369
+ * @returns Normalized identity, bundle naming, and installation metadata.
370
+ * @throws {TypeError} If the manifest, package name, author, optional string fields, or package-manager option is invalid.
371
+ * @remarks The input manifest and nested author object are not mutated. This helper does not read files, environment variables, or package-manager configuration.
372
+ * @category Util
373
+ */
374
+ declare function derivePackageMetadata(manifest: PackageManifest, options?: DerivePackageMetadataOptions): DerivedPackageMetadata;
375
+
376
+ /**
377
+ * Precision used by `formatLocalDateTime`.
378
+ *
379
+ * @category Util
380
+ */
381
+ type LocalDateTimePrecision = "minute" | "second" | "millisecond";
382
+ /**
383
+ * Parse an HTML `datetime-local` value into a local `Date`.
384
+ *
385
+ * Accepted normalized values use a year with at least four digits followed by
386
+ * `-MM-DDTHH:mm`, with optional seconds and 1-3 fractional-second digits.
387
+ * Components are validated strictly, so impossible dates and times return
388
+ * `null` instead of being normalized by `Date`.
389
+ *
390
+ * Usage:
391
+ *
392
+ * ```javascript
393
+ * import { parseLocalDateTime } from "mazey";
394
+ *
395
+ * const date = parseLocalDateTime("2026-07-21T14:30:45.123");
396
+ * console.log(date?.getFullYear());
397
+ * console.log(date?.getHours());
398
+ * console.log(date?.getMilliseconds());
399
+ * ```
400
+ *
401
+ * Output:
402
+ *
403
+ * ```text
404
+ * 2026
405
+ * 14
406
+ * 123
407
+ * ```
408
+ *
409
+ * @param value A normalized HTML `datetime-local` value without a timezone.
410
+ * @returns A local `Date`, or `null` when the value is malformed or represents an impossible local date and time.
411
+ * @remarks The value is interpreted using the runtime's local timezone. Timezone suffixes, surrounding whitespace, and date-only values are rejected.
412
+ * @category Util
413
+ */
414
+ declare function parseLocalDateTime(value: string): Date | null;
415
+ /**
416
+ * Format a `Date` as an HTML `datetime-local` value using local fields.
417
+ *
418
+ * | Precision | Output shape |
419
+ * | ------------- | ----------------------------- |
420
+ * | `minute` | `YYYY-MM-DDTHH:mm` |
421
+ * | `second` | `YYYY-MM-DDTHH:mm:ss` |
422
+ * | `millisecond` | `YYYY-MM-DDTHH:mm:ss.SSS` |
423
+ *
424
+ * Usage:
425
+ *
426
+ * ```javascript
427
+ * import { formatLocalDateTime } from "mazey";
428
+ *
429
+ * const date = new Date(2026, 6, 21, 14, 30, 45, 123);
430
+ * const minutes = formatLocalDateTime(date);
431
+ * const seconds = formatLocalDateTime(date, { precision: "second" });
432
+ * const milliseconds = formatLocalDateTime(date, {
433
+ * precision: "millisecond",
434
+ * });
435
+ * console.log(minutes);
436
+ * console.log(seconds);
437
+ * console.log(milliseconds);
438
+ * ```
439
+ *
440
+ * Output:
441
+ *
442
+ * ```text
443
+ * 2026-07-21T14:30
444
+ * 2026-07-21T14:30:45
445
+ * 2026-07-21T14:30:45.123
446
+ * ```
447
+ *
448
+ * @param date A valid `Date` to format.
449
+ * @param options Formatting options. Precision defaults to `minute`.
450
+ * @returns A normalized HTML `datetime-local` value containing local calendar fields. The year is padded to at least four digits.
451
+ * @throws {TypeError} If `date` is not a `Date` or `precision` is unsupported.
452
+ * @throws {RangeError} If `date` is invalid or its local year is earlier than 1.
453
+ * @remarks This function does not call `toISOString()` and does not convert the value to UTC. It does not mutate the supplied `Date`.
454
+ * @category Util
455
+ */
456
+ declare function formatLocalDateTime(date: Date, options?: {
457
+ precision?: LocalDateTimePrecision;
458
+ }): string;
277
459
  /**
278
460
  * Get the current timestamp in milliseconds.
279
461
  *
@@ -3592,6 +3774,99 @@ declare function genBrowserAttrs(prefix?: string, separator?: string): string[];
3592
3774
  * @category Browser Information
3593
3775
  */
3594
3776
  declare function isSupportWebp(): Promise<boolean>;
3777
+ /**
3778
+ * Listen for media-query changes with modern and legacy browser APIs.
3779
+ *
3780
+ * Modern `addEventListener("change", ...)` support is preferred. Browsers
3781
+ * exposing only `addListener` use that legacy API instead. A missing media
3782
+ * query returns an inert cleanup function.
3783
+ *
3784
+ * Usage:
3785
+ *
3786
+ * ```javascript
3787
+ * import { listenMediaQueryChanges } from "mazey";
3788
+ *
3789
+ * const media = window.matchMedia("(prefers-color-scheme: dark)");
3790
+ * const stop = listenMediaQueryChanges(media, event => {
3791
+ * console.log(event.matches);
3792
+ * });
3793
+ *
3794
+ * stop();
3795
+ * stop();
3796
+ * ```
3797
+ *
3798
+ * @param media Media-query result to observe, or `null` when unavailable.
3799
+ * @param listener Callback invoked for media-query change events.
3800
+ * @returns An idempotent function that removes the registered listener.
3801
+ * @throws {TypeError} If `listener` is not a function or `media` is neither an object nor `null`.
3802
+ * @remarks This helper does not call `matchMedia`, invoke the listener immediately, or modify the DOM. It is safe during SSR when `null` is supplied.
3803
+ * @category Browser Information
3804
+ */
3805
+ declare function listenMediaQueryChanges(media: MediaQueryList | null, listener: (event: MediaQueryListEvent) => void): () => void;
3806
+ /**
3807
+ * Callbacks used by {@link watchServiceWorkerUpdates}.
3808
+ *
3809
+ * @category Browser Information
3810
+ */
3811
+ interface ServiceWorkerUpdateCallbacks {
3812
+ /** Called when a waiting update is ready to be activated. */
3813
+ onUpdateAvailable(worker: ServiceWorker): void;
3814
+ /** Called after the service worker controlling the page changes. */
3815
+ onControllerChange?(): void;
3816
+ }
3817
+ /**
3818
+ * Controls returned by {@link watchServiceWorkerUpdates}.
3819
+ *
3820
+ * @category Browser Information
3821
+ */
3822
+ interface ServiceWorkerUpdateWatcher {
3823
+ /**
3824
+ * Post a message to the current waiting worker.
3825
+ * The default message is `{ type: "SKIP_WAITING" }`.
3826
+ */
3827
+ activateWaiting(message?: unknown): boolean;
3828
+ /** Remove every listener installed by the watcher. Idempotent. */
3829
+ dispose(): void;
3830
+ }
3831
+ /**
3832
+ * Watch a service-worker registration for an update ready to activate.
3833
+ *
3834
+ * Existing waiting workers and newly installed workers are reported only when
3835
+ * the page already has a controller, which distinguishes updates from a first
3836
+ * installation. Activation, UI, status copy, and reload policy remain under
3837
+ * caller control.
3838
+ *
3839
+ * Usage:
3840
+ *
3841
+ * ```javascript
3842
+ * import { watchServiceWorkerUpdates } from "mazey";
3843
+ *
3844
+ * const watcher = watchServiceWorkerUpdates(
3845
+ * registration,
3846
+ * navigator.serviceWorker,
3847
+ * {
3848
+ * onUpdateAvailable() {
3849
+ * console.log("Update available");
3850
+ * },
3851
+ * onControllerChange() {
3852
+ * console.log("Controller changed");
3853
+ * },
3854
+ * }
3855
+ * );
3856
+ *
3857
+ * watcher.activateWaiting();
3858
+ * watcher.dispose();
3859
+ * ```
3860
+ *
3861
+ * @param registration Service-worker registration to observe.
3862
+ * @param container Service-worker container that owns the page controller.
3863
+ * @param callbacks Update and optional controller-change callbacks.
3864
+ * @returns Controls for requesting activation and disposing all listeners.
3865
+ * @throws {TypeError} If required registration, container, or callback methods are missing.
3866
+ * @remarks This helper does not register a service worker, mutate the DOM, reload the page, or decide when an update should activate. `activateWaiting` returns `false` when no update is waiting or `postMessage` fails.
3867
+ * @category Browser Information
3868
+ */
3869
+ declare function watchServiceWorkerUpdates(registration: ServiceWorkerRegistration, container: ServiceWorkerContainer, callbacks: ServiceWorkerUpdateCallbacks): ServiceWorkerUpdateWatcher;
3595
3870
 
3596
3871
  /**
3597
3872
  * A user-selectable color-theme preference.
@@ -3856,5 +4131,5 @@ declare const mazeyCon: Console;
3856
4131
  */
3857
4132
  declare const timeCon: Console;
3858
4133
 
3859
- export { addClass, addEvent, addStyle, assignDefined, calLongestCommonSubsequence, calLongestCommonSubstring, calculateCAGR, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHTML, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, convertHttpToHttps, convertKebabToCamel, convertObjectToQuery, convertToHtmlBreaks, convertUnderToCamel, cutCHSString, cutZHString, debounce, deepCopy, deepCopyObject, deepFreeze, delCookie, detectVisitorType, doFn, extractElementText, fireEvent, floatFixed, floatToPercent, formatByteSize, formatDate, formatDistanceToNow, formatDurationFromMs, genBrowserAttrs, genCustomConsole, genHashCode, genRndNumString, genStyleString, genUniqueNumString, generateCalendarVersion, generateRndNum, generateUniqueNum, getAllQueryParams, getBrowserInfo, getCLS, getCookie, getCurrentVersion, getDateDifference, getDefineListeners, getDomain, getFCP, getFID, getFP, getFileSize, getFriendlyInterval, getHashQueryParam, getLCP, getLocalStorage, getPageMeta, getPerformance, getQueryParam, getScriptQueryParam, getSessionStorage, getTTFB, getUrlFileType, getUrlHost, getUrlParam, getUrlPath, hasClass, inRate, invokeEvent, invokeFn, isArray, isBool, isBoolean, isBrowser, isFunction, isHit, isJSONString, isJsonString, isNonEmptyArray, isNonEmptyObject, isNumber, isPureObject, isSafePWAEnv, isStandalonePWA, isString, isSupportWebp, isSupportedEntryType, isThisHour, isThisMonth, isThisWeek, isThisYear, isToday, isUdfOrNul, isValidCssSelector, isValidData, isValidDate, isValidEmail, isValidHttpUrl, isValidPhoneNumber, isValidUrl, loadCSS, loadImage, loadScript, loadScriptIfUndefined, longestComSubsequence, longestComSubstring, mNow, mTrim, mazeyCon, newLine, onURLChange, parseGitHubRepository, parseJsonSafe, removeClass, removeCookie, removeEvent, removeHTML, removeHtml, repeatUntilConditionMet, replaceHttp, resolveLanguagePreference, resolveThemePreference, sanitizeInput, setClass, setCookie, setImgSizeBySrc, setImgWidHeiBySrc, setLanguagePreference, setLocalStorage, setSessionStorage, setThemePreference, sha256Hex, sleep, throttle, timeCon, toJavaScriptGlobalName, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, windowLoaded, zAxiosIsValidRes };
3860
- export type { FormatByteSizeOptions, GitHubRepositoryDetails, InvestmentReturnRate, IsSafePWAEnvOptions, PreferenceResult, ResolvedTheme, ThemePreference, VisitorType };
4134
+ export { addClass, addEvent, addStyle, assignDefined, calLongestCommonSubsequence, calLongestCommonSubstring, calculateCAGR, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHTML, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, convertHttpToHttps, convertKebabToCamel, convertObjectToQuery, convertToHtmlBreaks, convertUnderToCamel, cutCHSString, cutZHString, debounce, deepCopy, deepCopyObject, deepFreeze, delCookie, derivePackageMetadata, detectVisitorType, doFn, extractElementText, fireEvent, floatFixed, floatToPercent, formatByteSize, formatDate, formatDistanceToNow, formatDurationFromMs, formatLocalDateTime, genBrowserAttrs, genCustomConsole, genHashCode, genRndNumString, genStyleString, genUniqueNumString, generateCalendarVersion, generateRndNum, generateUniqueNum, getAllQueryParams, getBrowserInfo, getCLS, getCookie, getCurrentVersion, getDateDifference, getDefineListeners, getDomain, getFCP, getFID, getFP, getFileSize, getFriendlyInterval, getHashQueryParam, getLCP, getLocalStorage, getPageMeta, getPerformance, getQueryParam, getScriptQueryParam, getSessionStorage, getTTFB, getUrlFileType, getUrlHost, getUrlParam, getUrlPath, hasClass, inRate, invokeEvent, invokeFn, isArray, isBool, isBoolean, isBrowser, isFunction, isHit, isJSONString, isJsonString, isNonEmptyArray, isNonEmptyObject, isNumber, isPureObject, isSafePWAEnv, isStandalonePWA, isString, isSupportWebp, isSupportedEntryType, isThisHour, isThisMonth, isThisWeek, isThisYear, isToday, isUdfOrNul, isValidCssSelector, isValidData, isValidDate, isValidEmail, isValidHttpUrl, isValidPhoneNumber, isValidUrl, listenMediaQueryChanges, loadCSS, loadImage, loadScript, loadScriptIfUndefined, longestComSubsequence, longestComSubstring, mNow, mTrim, mazeyCon, newLine, onURLChange, parseGitHubRepository, parseJsonSafe, parseLocalDateTime, removeClass, removeCookie, removeEvent, removeHTML, removeHtml, repeatUntilConditionMet, replaceHttp, resolveLanguagePreference, resolveThemePreference, sanitizeInput, setClass, setCookie, setImgSizeBySrc, setImgWidHeiBySrc, setLanguagePreference, setLocalStorage, setSessionStorage, setThemePreference, sha256Hex, sleep, throttle, timeCon, toJavaScriptGlobalName, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, watchServiceWorkerUpdates, windowLoaded, zAxiosIsValidRes };
4135
+ export type { DerivePackageMetadataOptions, DerivedPackageMetadata, FormatByteSizeOptions, GitHubRepositoryDetails, InvestmentReturnRate, IsSafePWAEnvOptions, LocalDateTimePrecision, PackageManager, PackageManifest, PackageManifestAuthor, PreferenceResult, ResolvedTheme, ServiceWorkerUpdateCallbacks, ServiceWorkerUpdateWatcher, ThemePreference, VisitorType };