@01.software/sdk 0.35.0 → 0.37.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/README.md +71 -6
- package/dist/analytics/react.cjs +33 -9
- package/dist/analytics/react.cjs.map +1 -1
- package/dist/analytics/react.d.cts +1 -1
- package/dist/analytics/react.d.ts +1 -1
- package/dist/analytics/react.js +33 -9
- package/dist/analytics/react.js.map +1 -1
- package/dist/analytics.cjs +30 -8
- package/dist/analytics.cjs.map +1 -1
- package/dist/analytics.d.cts +6 -0
- package/dist/analytics.d.ts +6 -0
- package/dist/analytics.js +30 -8
- package/dist/analytics.js.map +1 -1
- package/dist/client.cjs +94 -114
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +6 -6
- package/dist/client.d.ts +6 -6
- package/dist/client.js +94 -114
- package/dist/client.js.map +1 -1
- package/dist/{collection-client-DkREjhQ9.d.ts → collection-client-DyELGUcL.d.ts} +3 -3
- package/dist/{collection-client-CR2B8c1v.d.cts → collection-client-zOmnxwdA.d.cts} +3 -3
- package/dist/{const-CdqCauHQ.d.ts → const-CK_FPaIn.d.cts} +3 -3
- package/dist/{const-BTvdrXtY.d.cts → const-Dqz05oaG.d.ts} +3 -3
- package/dist/{image-BDz2-AaO.d.cts → image-BDjHp03R.d.cts} +13 -9
- package/dist/{image-BDz2-AaO.d.ts → image-BDjHp03R.d.ts} +13 -9
- package/dist/{index-DK8_NXkh.d.ts → index-DRJs7QIh.d.cts} +9 -6
- package/dist/{index-CjA3U6X3.d.cts → index-DTqoUZk_.d.ts} +9 -6
- package/dist/index.cjs +229 -136
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -9
- package/dist/index.d.ts +10 -9
- package/dist/index.js +229 -136
- package/dist/index.js.map +1 -1
- package/dist/metadata.cjs +5 -3
- package/dist/metadata.cjs.map +1 -1
- package/dist/metadata.js +5 -3
- package/dist/metadata.js.map +1 -1
- package/dist/{payload-types-C7tb7Xbs.d.cts → payload-types-CREOjFNT.d.cts} +281 -128
- package/dist/{payload-types-C7tb7Xbs.d.ts → payload-types-CREOjFNT.d.ts} +281 -128
- package/dist/query.cjs +5 -3
- package/dist/query.cjs.map +1 -1
- package/dist/query.d.cts +5 -5
- package/dist/query.d.ts +5 -5
- package/dist/query.js +5 -3
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.cts +2 -2
- package/dist/realtime.d.ts +2 -2
- package/dist/server.cjs +99 -69
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +7 -7
- package/dist/server.d.ts +7 -7
- package/dist/server.js +99 -69
- package/dist/server.js.map +1 -1
- package/dist/{types-DDhtZI6E.d.cts → types-BWMUr3Zw.d.cts} +274 -84
- package/dist/{types-Bx558PU6.d.cts → types-BkZNhuBh.d.cts} +1 -1
- package/dist/{types-1ylMrCuW.d.ts → types-CxzWHspI.d.ts} +1 -1
- package/dist/{types-Byo_Rty4.d.ts → types-DMvVHdb1.d.ts} +274 -84
- package/dist/ui/canvas.cjs +15 -5
- package/dist/ui/canvas.cjs.map +1 -1
- package/dist/ui/canvas.d.cts +1 -1
- package/dist/ui/canvas.d.ts +1 -1
- package/dist/ui/canvas.js +15 -5
- package/dist/ui/canvas.js.map +1 -1
- package/dist/ui/form.d.cts +1 -1
- package/dist/ui/form.d.ts +1 -1
- package/dist/ui/image.cjs +15 -5
- package/dist/ui/image.cjs.map +1 -1
- package/dist/ui/image.d.cts +1 -1
- package/dist/ui/image.d.ts +1 -1
- package/dist/ui/image.js +15 -5
- package/dist/ui/image.js.map +1 -1
- package/dist/ui/video.d.cts +1 -1
- package/dist/ui/video.d.ts +1 -1
- package/dist/webhook.cjs +5 -1
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.d.cts +4 -4
- package/dist/webhook.d.ts +4 -4
- package/dist/webhook.js +5 -1
- package/dist/webhook.js.map +1 -1
- package/package.json +3 -3
package/dist/ui/form.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
import { F as Form } from '../payload-types-
|
|
2
|
+
import { F as Form } from '../payload-types-CREOjFNT.cjs';
|
|
3
3
|
import { RichTextData } from './rich-text.cjs';
|
|
4
4
|
import '@payloadcms/richtext-lexical';
|
|
5
5
|
import '@payloadcms/richtext-lexical/lexical';
|
package/dist/ui/form.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
import { F as Form } from '../payload-types-
|
|
2
|
+
import { F as Form } from '../payload-types-CREOjFNT.js';
|
|
3
3
|
import { RichTextData } from './rich-text.js';
|
|
4
4
|
import '@payloadcms/richtext-lexical';
|
|
5
5
|
import '@payloadcms/richtext-lexical/lexical';
|
package/dist/ui/image.cjs
CHANGED
|
@@ -37,19 +37,29 @@ module.exports = __toCommonJS(Image_exports);
|
|
|
37
37
|
var import_react = __toESM(require("react"), 1);
|
|
38
38
|
|
|
39
39
|
// src/utils/image.ts
|
|
40
|
-
var IMAGE_SIZES = [
|
|
40
|
+
var IMAGE_SIZES = [200, 400, 800, 1200, 1600];
|
|
41
|
+
function imageSizeCandidates(sizes) {
|
|
42
|
+
const keys = new Set(IMAGE_SIZES);
|
|
43
|
+
for (const key of Object.keys(sizes)) {
|
|
44
|
+
const value = Number(key);
|
|
45
|
+
if (Number.isFinite(value) && value > 0) keys.add(value);
|
|
46
|
+
}
|
|
47
|
+
return [...keys].sort((a, b) => a - b);
|
|
48
|
+
}
|
|
41
49
|
function getImageSrcSet(image) {
|
|
42
50
|
const parts = [];
|
|
51
|
+
const emittedWidths = /* @__PURE__ */ new Set();
|
|
43
52
|
const sizes = image.sizes;
|
|
44
53
|
if (sizes) {
|
|
45
|
-
for (const size of
|
|
46
|
-
const entry = sizes[
|
|
47
|
-
if (entry?.url && entry.width) {
|
|
54
|
+
for (const size of imageSizeCandidates(sizes)) {
|
|
55
|
+
const entry = sizes[`${size}`];
|
|
56
|
+
if (entry?.url && entry.width && !emittedWidths.has(entry.width)) {
|
|
57
|
+
emittedWidths.add(entry.width);
|
|
48
58
|
parts.push(`${entry.url} ${entry.width}w`);
|
|
49
59
|
}
|
|
50
60
|
}
|
|
51
61
|
}
|
|
52
|
-
if (image.url && image.width) {
|
|
62
|
+
if (image.url && image.width && !emittedWidths.has(image.width)) {
|
|
53
63
|
parts.push(`${image.url} ${image.width}w`);
|
|
54
64
|
}
|
|
55
65
|
return parts.join(", ");
|
package/dist/ui/image.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ui/Image/index.tsx","../../src/utils/image.ts"],"sourcesContent":["'use client'\n\nimport React, { useCallback, useRef, useState } from 'react'\nimport type { CSSProperties } from 'react'\nimport type { ImageData } from '../../utils/image'\nimport { getImageSrcSet, getImagePlaceholderStyle } from '../../utils/image'\n\nexport interface ImageProps {\n /** Payload image document */\n image: ImageData\n /** Display width in CSS pixels (for selecting optimal srcset size) */\n width?: number\n /** Device pixel ratio (default: 1) */\n dpr?: number\n /** Placeholder strategy (default: 'blur'; defaults to 'none' when imageRendering is 'pixelated' or 'crisp-edges') */\n placeholder?: 'blur' | 'color' | 'none'\n /** Container className */\n className?: string\n /** Container style */\n style?: CSSProperties\n /** Inner `<img>` className */\n imgClassName?: string\n /** Inner `<img>` style */\n imgStyle?: CSSProperties\n /** HTML sizes attribute */\n sizes?: string\n /** Loading strategy (default: 'lazy'; automatically 'eager' when priority is true) */\n loading?: 'lazy' | 'eager'\n /** Callback when image finishes loading */\n onLoad?: () => void\n /** Object-fit for the image (default: 'cover') */\n objectFit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down'\n /** When true, loads eagerly with high fetch priority (for LCP images) */\n priority?: boolean\n /** When true, fills parent container (width/height: 100%, no aspect ratio) */\n fill?: boolean\n /** CSS image-rendering mode (e.g. 'pixelated' for pixel art) */\n imageRendering?: 'auto' | 'pixelated' | 'crisp-edges'\n /** alt text override (falls back to image.alt, then empty string) */\n alt?: string\n}\n\n/**\n * Image component with blur-up / color placeholder support.\n *\n * Uses LQIP (Low Quality Image Placeholder) for a smooth blur-up effect,\n * falling back to palette color or no placeholder.\n */\nexport function Image({\n image,\n width,\n dpr = 1,\n placeholder: placeholderProp,\n className,\n style,\n imgClassName,\n imgStyle,\n sizes,\n loading: loadingProp,\n onLoad,\n objectFit = 'cover',\n priority = false,\n fill = false,\n imageRendering,\n alt: altProp,\n}: ImageProps) {\n const [loaded, setLoaded] = useState(false)\n const firedRef = useRef(false)\n\n // Resolve defaults based on other props\n const isPixelRendering =\n imageRendering === 'pixelated' || imageRendering === 'crisp-edges'\n const placeholder = placeholderProp ?? (isPixelRendering ? 'none' : 'blur')\n const loading = priority ? 'eager' : (loadingProp ?? 'lazy')\n\n const aspectRatio =\n !fill && image.width && image.height\n ? `${image.width} / ${image.height}`\n : undefined\n\n const srcSet = getImageSrcSet(image)\n const src = image.url ?? undefined\n\n // Placeholder: LQIP overlay or color overlay (mutually exclusive)\n const hasLqip = placeholder === 'blur' && !!image.lqip\n const placeholderStyle = getImagePlaceholderStyle(image, {\n type: placeholder,\n })\n const placeholderColor =\n !hasLqip && 'backgroundColor' in placeholderStyle\n ? placeholderStyle.backgroundColor\n : undefined\n\n const fireLoad = useCallback(() => {\n if (firedRef.current) return\n firedRef.current = true\n setLoaded(true)\n onLoad?.()\n }, [onLoad])\n\n // Callback ref: detect SSR-cached images that are already loaded\n const imgRef = useCallback(\n (node: HTMLImageElement | null) => {\n if (node && node.complete && node.naturalWidth > 0) {\n fireLoad()\n }\n },\n [fireLoad],\n )\n\n // Container styles\n const containerStyle: CSSProperties = {\n position: 'relative',\n overflow: 'hidden',\n ...(fill ? { width: '100%', height: '100%' } : {}),\n ...(aspectRatio ? { aspectRatio } : {}),\n ...style,\n }\n\n // Shared overlay styles (LQIP and color)\n const overlayBase: CSSProperties = {\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n height: '100%',\n opacity: loaded ? 0 : 1,\n transition: 'opacity 0.3s ease',\n pointerEvents: 'none',\n }\n\n // Main image styles\n const mainImgStyle: CSSProperties = {\n display: 'block',\n width: '100%',\n height: '100%',\n objectFit,\n ...(imageRendering ? { imageRendering } : {}),\n opacity: loaded ? 1 : 0,\n transition: 'opacity 0.3s ease',\n ...imgStyle,\n }\n\n return (\n <div className={className} style={containerStyle}>\n {hasLqip && (\n <img\n aria-hidden\n alt=\"\"\n src={image.lqip!}\n style={{\n ...overlayBase,\n display: 'block',\n objectFit,\n filter: 'blur(20px)',\n transform: 'scale(1.1)',\n }}\n />\n )}\n {placeholderColor && (\n <div\n aria-hidden\n style={{\n ...overlayBase,\n backgroundColor: placeholderColor,\n }}\n />\n )}\n <img\n ref={imgRef}\n alt={altProp ?? image.alt ?? ''}\n src={src}\n srcSet={srcSet || undefined}\n sizes={sizes}\n width={width ? width * dpr : undefined}\n loading={loading}\n decoding=\"async\"\n fetchPriority={priority ? 'high' : undefined}\n onLoad={fireLoad}\n className={imgClassName}\n style={mainImgStyle}\n />\n </div>\n )\n}\n","/** Palette colors extracted from an image */\nexport interface ImagePalette {\n vibrant?: string | null\n muted?: string | null\n darkVibrant?: string | null\n darkMuted?: string | null\n lightVibrant?: string | null\n lightMuted?: string | null\n}\n\n/** Common image data shape from Payload CMS upload collections */\nexport interface ImageData {\n url?: string | null\n width?: number | null\n height?: number | null\n alt?: string | null\n lqip?: string | null\n palette?: ImagePalette | null\n sizes?: Record<\n string,\n | {\n url?: string | null\n width?: number | null\n height?: number | null\n }\n | undefined\n >\n}\n\n/** Pre-generated image size breakpoints (px) */\nexport const IMAGE_SIZES = [384, 768, 1536] as const\n\n/**\n * Returns the optimal image URL for a given display width.\n *\n * Picks the smallest pre-generated size whose width >= displayWidth × dpr.\n * Falls back to the original URL when no matching size exists.\n *\n * @param image - Payload image document\n * @param displayWidth - CSS pixel width the image will be displayed at\n * @param dpr - Device pixel ratio (default: 1)\n * @returns URL string, or empty string if no URL is available\n */\nexport function getImageUrl(\n image: ImageData,\n displayWidth: number,\n dpr: number = 1,\n): string {\n const target = displayWidth * dpr\n const sizes = image.sizes\n\n if (sizes) {\n for (const size of IMAGE_SIZES) {\n if (size >= target) {\n const entry = sizes[String(size)]\n if (entry?.url) return entry.url\n }\n }\n }\n\n return image.url ?? ''\n}\n\n/**\n * Generates an HTML `srcset` attribute string from pre-generated sizes.\n *\n * Includes all available sizes plus the original image.\n * Example output: `\"url-384 384w, url-768 768w, url-1536 1536w, url-original 2000w\"`\n *\n * @param image - Payload image document\n * @returns srcset string, or empty string if no URLs are available\n */\nexport function getImageSrcSet(image: ImageData): string {\n const parts: string[] = []\n const sizes = image.sizes\n\n if (sizes) {\n for (const size of IMAGE_SIZES) {\n const entry = sizes[String(size)]\n if (entry?.url && entry.width) {\n parts.push(`${entry.url} ${entry.width}w`)\n }\n }\n }\n\n if (image.url && image.width) {\n parts.push(`${image.url} ${image.width}w`)\n }\n\n return parts.join(', ')\n}\n\n/**\n * Returns the LQIP (Low Quality Image Placeholder) data URL for an image.\n *\n * @param image - Payload image document\n * @returns LQIP data URL string, or undefined if not available\n */\nexport function getImageLqip(image: ImageData): string | undefined {\n return image.lqip ?? undefined\n}\n\n/**\n * Returns the extracted color palette for an image.\n *\n * @param image - Payload image document\n * @returns ImagePalette object, or undefined if not available\n */\nexport function getImagePalette(image: ImageData): ImagePalette | undefined {\n return image.palette ?? undefined\n}\n\n/** Options for `getImagePlaceholderStyle` */\nexport interface ImagePlaceholderOptions {\n /** Placeholder strategy (default: 'blur') */\n type?: 'blur' | 'color' | 'none'\n /** Which palette color to use for 'color' strategy (default: 'muted') */\n paletteColor?: keyof ImagePalette\n}\n\n/**\n * Returns inline CSS styles for an image placeholder.\n *\n * - `blur`: uses LQIP as background, falls back to palette color, then empty\n * - `color`: uses palette color as background, falls back to empty\n * - `none`: always returns empty\n *\n * @param image - Payload image document\n * @param options - Placeholder options\n * @returns CSS style object compatible with React CSSProperties\n */\nexport function getImagePlaceholderStyle(\n image: ImageData,\n options?: ImagePlaceholderOptions,\n): Record<string, string> {\n const type = options?.type ?? 'blur'\n const paletteColor = options?.paletteColor ?? 'muted'\n\n if (type === 'none') return {}\n\n const color = image.palette?.[paletteColor]\n\n if (type === 'blur') {\n const lqip = image.lqip\n if (lqip) {\n return {\n backgroundImage: `url(${lqip})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n }\n }\n // Cascade: fall back to color\n if (color) {\n return { backgroundColor: color }\n }\n return {}\n }\n\n // type === 'color'\n if (color) {\n return { backgroundColor: color }\n }\n return {}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAqD;;;AC4B9C,IAAM,cAAc,CAAC,KAAK,KAAK,IAAI;AA0CnC,SAAS,eAAe,OAA0B;AACvD,QAAM,QAAkB,CAAC;AACzB,QAAM,QAAQ,MAAM;AAEpB,MAAI,OAAO;AACT,eAAW,QAAQ,aAAa;AAC9B,YAAM,QAAQ,MAAM,OAAO,IAAI,CAAC;AAChC,UAAI,OAAO,OAAO,MAAM,OAAO;AAC7B,cAAM,KAAK,GAAG,MAAM,GAAG,IAAI,MAAM,KAAK,GAAG;AAAA,MAC3C;AAAA,IACF;AAAA,EACF;AAEA,MAAI,MAAM,OAAO,MAAM,OAAO;AAC5B,UAAM,KAAK,GAAG,MAAM,GAAG,IAAI,MAAM,KAAK,GAAG;AAAA,EAC3C;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;AAyCO,SAAS,yBACd,OACA,SACwB;AACxB,QAAM,OAAO,SAAS,QAAQ;AAC9B,QAAM,eAAe,SAAS,gBAAgB;AAE9C,MAAI,SAAS,OAAQ,QAAO,CAAC;AAE7B,QAAM,QAAQ,MAAM,UAAU,YAAY;AAE1C,MAAI,SAAS,QAAQ;AACnB,UAAM,OAAO,MAAM;AACnB,QAAI,MAAM;AACR,aAAO;AAAA,QACL,iBAAiB,OAAO,IAAI;AAAA,QAC5B,gBAAgB;AAAA,QAChB,oBAAoB;AAAA,MACtB;AAAA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AA,MAC7B;AAAA,MACA,UAAS;AAAA,MACT,eAAe,WAAW,SAAS;AAAA,MACnC,QAAQ;AAAA,MACR,WAAW;AAAA,MACX,OAAO;AAAA;AAAA,EACT,CACF;AAEJ;","names":["React"]}
|
|
1
|
+
{"version":3,"sources":["../../src/ui/Image/index.tsx","../../src/utils/image.ts"],"sourcesContent":["'use client'\n\nimport React, { useCallback, useRef, useState } from 'react'\nimport type { CSSProperties } from 'react'\nimport type { ImageData } from '../../utils/image'\nimport { getImageSrcSet, getImagePlaceholderStyle } from '../../utils/image'\n\nexport interface ImageProps {\n /** Payload image document */\n image: ImageData\n /** Display width in CSS pixels (for selecting optimal srcset size) */\n width?: number\n /** Device pixel ratio (default: 1) */\n dpr?: number\n /** Placeholder strategy (default: 'blur'; defaults to 'none' when imageRendering is 'pixelated' or 'crisp-edges') */\n placeholder?: 'blur' | 'color' | 'none'\n /** Container className */\n className?: string\n /** Container style */\n style?: CSSProperties\n /** Inner `<img>` className */\n imgClassName?: string\n /** Inner `<img>` style */\n imgStyle?: CSSProperties\n /** HTML sizes attribute */\n sizes?: string\n /** Loading strategy (default: 'lazy'; automatically 'eager' when priority is true) */\n loading?: 'lazy' | 'eager'\n /** Callback when image finishes loading */\n onLoad?: () => void\n /** Object-fit for the image (default: 'cover') */\n objectFit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down'\n /** When true, loads eagerly with high fetch priority (for LCP images) */\n priority?: boolean\n /** When true, fills parent container (width/height: 100%, no aspect ratio) */\n fill?: boolean\n /** CSS image-rendering mode (e.g. 'pixelated' for pixel art) */\n imageRendering?: 'auto' | 'pixelated' | 'crisp-edges'\n /** alt text override (falls back to image.alt, then empty string) */\n alt?: string\n}\n\n/**\n * Image component with blur-up / color placeholder support.\n *\n * Uses LQIP (Low Quality Image Placeholder) for a smooth blur-up effect,\n * falling back to palette color or no placeholder.\n */\nexport function Image({\n image,\n width,\n dpr = 1,\n placeholder: placeholderProp,\n className,\n style,\n imgClassName,\n imgStyle,\n sizes,\n loading: loadingProp,\n onLoad,\n objectFit = 'cover',\n priority = false,\n fill = false,\n imageRendering,\n alt: altProp,\n}: ImageProps) {\n const [loaded, setLoaded] = useState(false)\n const firedRef = useRef(false)\n\n // Resolve defaults based on other props\n const isPixelRendering =\n imageRendering === 'pixelated' || imageRendering === 'crisp-edges'\n const placeholder = placeholderProp ?? (isPixelRendering ? 'none' : 'blur')\n const loading = priority ? 'eager' : (loadingProp ?? 'lazy')\n\n const aspectRatio =\n !fill && image.width && image.height\n ? `${image.width} / ${image.height}`\n : undefined\n\n const srcSet = getImageSrcSet(image)\n const src = image.url ?? undefined\n\n // Placeholder: LQIP overlay or color overlay (mutually exclusive)\n const hasLqip = placeholder === 'blur' && !!image.lqip\n const placeholderStyle = getImagePlaceholderStyle(image, {\n type: placeholder,\n })\n const placeholderColor =\n !hasLqip && 'backgroundColor' in placeholderStyle\n ? placeholderStyle.backgroundColor\n : undefined\n\n const fireLoad = useCallback(() => {\n if (firedRef.current) return\n firedRef.current = true\n setLoaded(true)\n onLoad?.()\n }, [onLoad])\n\n // Callback ref: detect SSR-cached images that are already loaded\n const imgRef = useCallback(\n (node: HTMLImageElement | null) => {\n if (node && node.complete && node.naturalWidth > 0) {\n fireLoad()\n }\n },\n [fireLoad],\n )\n\n // Container styles\n const containerStyle: CSSProperties = {\n position: 'relative',\n overflow: 'hidden',\n ...(fill ? { width: '100%', height: '100%' } : {}),\n ...(aspectRatio ? { aspectRatio } : {}),\n ...style,\n }\n\n // Shared overlay styles (LQIP and color)\n const overlayBase: CSSProperties = {\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n height: '100%',\n opacity: loaded ? 0 : 1,\n transition: 'opacity 0.3s ease',\n pointerEvents: 'none',\n }\n\n // Main image styles\n const mainImgStyle: CSSProperties = {\n display: 'block',\n width: '100%',\n height: '100%',\n objectFit,\n ...(imageRendering ? { imageRendering } : {}),\n opacity: loaded ? 1 : 0,\n transition: 'opacity 0.3s ease',\n ...imgStyle,\n }\n\n return (\n <div className={className} style={containerStyle}>\n {hasLqip && (\n <img\n aria-hidden\n alt=\"\"\n src={image.lqip!}\n style={{\n ...overlayBase,\n display: 'block',\n objectFit,\n filter: 'blur(20px)',\n transform: 'scale(1.1)',\n }}\n />\n )}\n {placeholderColor && (\n <div\n aria-hidden\n style={{\n ...overlayBase,\n backgroundColor: placeholderColor,\n }}\n />\n )}\n <img\n ref={imgRef}\n alt={altProp ?? image.alt ?? ''}\n src={src}\n srcSet={srcSet || undefined}\n sizes={sizes}\n width={width ? width * dpr : undefined}\n loading={loading}\n decoding=\"async\"\n fetchPriority={priority ? 'high' : undefined}\n onLoad={fireLoad}\n className={imgClassName}\n style={mainImgStyle}\n />\n </div>\n )\n}\n","/** Palette colors extracted from an image */\nexport interface ImagePalette {\n vibrant?: string | null\n muted?: string | null\n darkVibrant?: string | null\n darkMuted?: string | null\n lightVibrant?: string | null\n lightMuted?: string | null\n}\n\n/** Structural image size entry accepted by public image helpers. */\nexport interface ImageDataSizeEntry {\n url?: string | null\n width?: number | null\n height?: number | null\n}\n\n/** Structural image sizes accepted from Payload upload-like collections. */\nexport type ImageDataSizes = Partial<\n Record<string, ImageDataSizeEntry | null | undefined>\n>\n\n/** Common image data shape from Payload CMS upload collections */\nexport interface ImageData {\n url?: string | null\n width?: number | null\n height?: number | null\n alt?: string | null\n lqip?: string | null\n palette?: ImagePalette | null\n sizes?: ImageDataSizes\n}\n\n/** Pre-generated image size breakpoints (px), aligned with Payload Image.sizes. */\nexport const IMAGE_SIZES = [200, 400, 800, 1200, 1600] as const\n\n/** Numeric rendition keys from `IMAGE_SIZES` plus any numeric keys on the image. */\nfunction imageSizeCandidates(sizes: ImageDataSizes): number[] {\n const keys = new Set<number>(IMAGE_SIZES)\n for (const key of Object.keys(sizes)) {\n const value = Number(key)\n if (Number.isFinite(value) && value > 0) keys.add(value)\n }\n return [...keys].sort((a, b) => a - b)\n}\n\n/**\n * Returns the optimal image URL for a given display width.\n *\n * Picks the smallest pre-generated size whose width >= displayWidth × dpr.\n * Falls back to the original URL when no matching size exists.\n *\n * @param image - Payload image document\n * @param displayWidth - CSS pixel width the image will be displayed at\n * @param dpr - Device pixel ratio (default: 1)\n * @returns URL string, or empty string if no URL is available\n */\nexport function getImageUrl(\n image: ImageData,\n displayWidth: number,\n dpr: number = 1,\n): string {\n const target = displayWidth * dpr\n const sizes = image.sizes\n\n if (sizes) {\n for (const size of imageSizeCandidates(sizes)) {\n if (size >= target) {\n const entry = sizes[`${size}`]\n if (entry?.url) return entry.url\n }\n }\n }\n\n return image.url ?? ''\n}\n\n/**\n * Generates an HTML `srcset` attribute string from pre-generated sizes.\n *\n * Includes all available sizes plus the original image.\n * Example output: `\"url-200 200w, url-400 400w, url-800 800w, url-1200 1200w, url-1600 1600w, url-original 2000w\"`\n *\n * @param image - Payload image document\n * @returns srcset string, or empty string if no URLs are available\n */\nexport function getImageSrcSet(image: ImageData): string {\n const parts: string[] = []\n const emittedWidths = new Set<number>()\n const sizes = image.sizes\n\n if (sizes) {\n for (const size of imageSizeCandidates(sizes)) {\n const entry = sizes[`${size}`]\n if (entry?.url && entry.width && !emittedWidths.has(entry.width)) {\n emittedWidths.add(entry.width)\n parts.push(`${entry.url} ${entry.width}w`)\n }\n }\n }\n\n if (image.url && image.width && !emittedWidths.has(image.width)) {\n parts.push(`${image.url} ${image.width}w`)\n }\n\n return parts.join(', ')\n}\n\n/**\n * Returns the LQIP (Low Quality Image Placeholder) data URL for an image.\n *\n * @param image - Payload image document\n * @returns LQIP data URL string, or undefined if not available\n */\nexport function getImageLqip(image: ImageData): string | undefined {\n return image.lqip ?? undefined\n}\n\n/**\n * Returns the extracted color palette for an image.\n *\n * @param image - Payload image document\n * @returns ImagePalette object, or undefined if not available\n */\nexport function getImagePalette(image: ImageData): ImagePalette | undefined {\n return image.palette ?? undefined\n}\n\n/** Options for `getImagePlaceholderStyle` */\nexport interface ImagePlaceholderOptions {\n /** Placeholder strategy (default: 'blur') */\n type?: 'blur' | 'color' | 'none'\n /** Which palette color to use for 'color' strategy (default: 'muted') */\n paletteColor?: keyof ImagePalette\n}\n\n/**\n * Returns inline CSS styles for an image placeholder.\n *\n * - `blur`: uses LQIP as background, falls back to palette color, then empty\n * - `color`: uses palette color as background, falls back to empty\n * - `none`: always returns empty\n *\n * @param image - Payload image document\n * @param options - Placeholder options\n * @returns CSS style object compatible with React CSSProperties\n */\nexport function getImagePlaceholderStyle(\n image: ImageData,\n options?: ImagePlaceholderOptions,\n): Record<string, string> {\n const type = options?.type ?? 'blur'\n const paletteColor = options?.paletteColor ?? 'muted'\n\n if (type === 'none') return {}\n\n const color = image.palette?.[paletteColor]\n\n if (type === 'blur') {\n const lqip = image.lqip\n if (lqip) {\n return {\n backgroundImage: `url(${lqip})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n }\n }\n // Cascade: fall back to color\n if (color) {\n return { backgroundColor: color }\n }\n return {}\n }\n\n // type === 'color'\n if (color) {\n return { backgroundColor: color }\n }\n return {}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAqD;;;ACgC9C,IAAM,cAAc,CAAC,KAAK,KAAK,KAAK,MAAM,IAAI;AAGrD,SAAS,oBAAoB,OAAiC;AAC5D,QAAM,OAAO,IAAI,IAAY,WAAW;AACxC,aAAW,OAAO,OAAO,KAAK,KAAK,GAAG;AACpC,UAAM,QAAQ,OAAO,GAAG;AACxB,QAAI,OAAO,SAAS,KAAK,KAAK,QAAQ,EAAG,MAAK,IAAI,KAAK;AAAA,EACzD;AACA,SAAO,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AACvC;AA0CO,SAAS,eAAe,OAA0B;AACvD,QAAM,QAAkB,CAAC;AACzB,QAAM,gBAAgB,oBAAI,IAAY;AACtC,QAAM,QAAQ,MAAM;AAEpB,MAAI,OAAO;AACT,eAAW,QAAQ,oBAAoB,KAAK,GAA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AAAA,IACT,OAAO;AAAA,IACP,QAAQ;AAAA,IACR;AAAA,IACA,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC;AAAA,IAC3C,SAAS,SAAS,IAAI;AAAA,IACtB,YAAY;AAAA,IACZ,GAAG;AAAA,EACL;AAEA,SACE,6BAAAA,QAAA,cAAC,SAAI,WAAsB,OAAO,kBAC/B,WACC,6BAAAA,QAAA;AAAA,IAAC;AAAA;AAAA,MACC,eAAW;AAAA,MACX,KAAI;AAAA,MACJ,KAAK,MAAM;AAAA,MACX,OAAO;AAAA,QACL,GAAG;AAAA,QACH,SAAS;AAAA,QACT;AAAA,QACA,QAAQ;AAAA,QACR,WAAW;AAAA,MACb;AAAA;AAAA,EACF,GAED,oBACC,6BAAAA,QAAA;AAAA,IAAC;AAAA;AAAA,MACC,eAAW;AAAA,MACX,OAAO;AAAA,QACL,GAAG;AAAA,QACH,iBAAiB;AAAA,MACnB;AAAA;AAAA,EACF,GAEF,6BAAAA,QAAA;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL,KAAK,WAAW,MAAM,OAAO;AAAA,MAC7B;AAAA,MACA,QAAQ,UAAU;AAAA,MAClB;AAAA,MACA,OAAO,QAAQ,QAAQ,MAAM;AAAA,MAC7B;AAAA,MACA,UAAS;AAAA,MACT,eAAe,WAAW,SAAS;AAAA,MACnC,QAAQ;AAAA,MACR,WAAW;AAAA,MACX,OAAO;AAAA;AAAA,EACT,CACF;AAEJ;","names":["React"]}
|
package/dist/ui/image.d.cts
CHANGED
package/dist/ui/image.d.ts
CHANGED
package/dist/ui/image.js
CHANGED
|
@@ -4,19 +4,29 @@
|
|
|
4
4
|
import React, { useCallback, useRef, useState } from "react";
|
|
5
5
|
|
|
6
6
|
// src/utils/image.ts
|
|
7
|
-
var IMAGE_SIZES = [
|
|
7
|
+
var IMAGE_SIZES = [200, 400, 800, 1200, 1600];
|
|
8
|
+
function imageSizeCandidates(sizes) {
|
|
9
|
+
const keys = new Set(IMAGE_SIZES);
|
|
10
|
+
for (const key of Object.keys(sizes)) {
|
|
11
|
+
const value = Number(key);
|
|
12
|
+
if (Number.isFinite(value) && value > 0) keys.add(value);
|
|
13
|
+
}
|
|
14
|
+
return [...keys].sort((a, b) => a - b);
|
|
15
|
+
}
|
|
8
16
|
function getImageSrcSet(image) {
|
|
9
17
|
const parts = [];
|
|
18
|
+
const emittedWidths = /* @__PURE__ */ new Set();
|
|
10
19
|
const sizes = image.sizes;
|
|
11
20
|
if (sizes) {
|
|
12
|
-
for (const size of
|
|
13
|
-
const entry = sizes[
|
|
14
|
-
if (entry?.url && entry.width) {
|
|
21
|
+
for (const size of imageSizeCandidates(sizes)) {
|
|
22
|
+
const entry = sizes[`${size}`];
|
|
23
|
+
if (entry?.url && entry.width && !emittedWidths.has(entry.width)) {
|
|
24
|
+
emittedWidths.add(entry.width);
|
|
15
25
|
parts.push(`${entry.url} ${entry.width}w`);
|
|
16
26
|
}
|
|
17
27
|
}
|
|
18
28
|
}
|
|
19
|
-
if (image.url && image.width) {
|
|
29
|
+
if (image.url && image.width && !emittedWidths.has(image.width)) {
|
|
20
30
|
parts.push(`${image.url} ${image.width}w`);
|
|
21
31
|
}
|
|
22
32
|
return parts.join(", ");
|
package/dist/ui/image.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ui/Image/index.tsx","../../src/utils/image.ts"],"sourcesContent":["'use client'\n\nimport React, { useCallback, useRef, useState } from 'react'\nimport type { CSSProperties } from 'react'\nimport type { ImageData } from '../../utils/image'\nimport { getImageSrcSet, getImagePlaceholderStyle } from '../../utils/image'\n\nexport interface ImageProps {\n /** Payload image document */\n image: ImageData\n /** Display width in CSS pixels (for selecting optimal srcset size) */\n width?: number\n /** Device pixel ratio (default: 1) */\n dpr?: number\n /** Placeholder strategy (default: 'blur'; defaults to 'none' when imageRendering is 'pixelated' or 'crisp-edges') */\n placeholder?: 'blur' | 'color' | 'none'\n /** Container className */\n className?: string\n /** Container style */\n style?: CSSProperties\n /** Inner `<img>` className */\n imgClassName?: string\n /** Inner `<img>` style */\n imgStyle?: CSSProperties\n /** HTML sizes attribute */\n sizes?: string\n /** Loading strategy (default: 'lazy'; automatically 'eager' when priority is true) */\n loading?: 'lazy' | 'eager'\n /** Callback when image finishes loading */\n onLoad?: () => void\n /** Object-fit for the image (default: 'cover') */\n objectFit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down'\n /** When true, loads eagerly with high fetch priority (for LCP images) */\n priority?: boolean\n /** When true, fills parent container (width/height: 100%, no aspect ratio) */\n fill?: boolean\n /** CSS image-rendering mode (e.g. 'pixelated' for pixel art) */\n imageRendering?: 'auto' | 'pixelated' | 'crisp-edges'\n /** alt text override (falls back to image.alt, then empty string) */\n alt?: string\n}\n\n/**\n * Image component with blur-up / color placeholder support.\n *\n * Uses LQIP (Low Quality Image Placeholder) for a smooth blur-up effect,\n * falling back to palette color or no placeholder.\n */\nexport function Image({\n image,\n width,\n dpr = 1,\n placeholder: placeholderProp,\n className,\n style,\n imgClassName,\n imgStyle,\n sizes,\n loading: loadingProp,\n onLoad,\n objectFit = 'cover',\n priority = false,\n fill = false,\n imageRendering,\n alt: altProp,\n}: ImageProps) {\n const [loaded, setLoaded] = useState(false)\n const firedRef = useRef(false)\n\n // Resolve defaults based on other props\n const isPixelRendering =\n imageRendering === 'pixelated' || imageRendering === 'crisp-edges'\n const placeholder = placeholderProp ?? (isPixelRendering ? 'none' : 'blur')\n const loading = priority ? 'eager' : (loadingProp ?? 'lazy')\n\n const aspectRatio =\n !fill && image.width && image.height\n ? `${image.width} / ${image.height}`\n : undefined\n\n const srcSet = getImageSrcSet(image)\n const src = image.url ?? undefined\n\n // Placeholder: LQIP overlay or color overlay (mutually exclusive)\n const hasLqip = placeholder === 'blur' && !!image.lqip\n const placeholderStyle = getImagePlaceholderStyle(image, {\n type: placeholder,\n })\n const placeholderColor =\n !hasLqip && 'backgroundColor' in placeholderStyle\n ? placeholderStyle.backgroundColor\n : undefined\n\n const fireLoad = useCallback(() => {\n if (firedRef.current) return\n firedRef.current = true\n setLoaded(true)\n onLoad?.()\n }, [onLoad])\n\n // Callback ref: detect SSR-cached images that are already loaded\n const imgRef = useCallback(\n (node: HTMLImageElement | null) => {\n if (node && node.complete && node.naturalWidth > 0) {\n fireLoad()\n }\n },\n [fireLoad],\n )\n\n // Container styles\n const containerStyle: CSSProperties = {\n position: 'relative',\n overflow: 'hidden',\n ...(fill ? { width: '100%', height: '100%' } : {}),\n ...(aspectRatio ? { aspectRatio } : {}),\n ...style,\n }\n\n // Shared overlay styles (LQIP and color)\n const overlayBase: CSSProperties = {\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n height: '100%',\n opacity: loaded ? 0 : 1,\n transition: 'opacity 0.3s ease',\n pointerEvents: 'none',\n }\n\n // Main image styles\n const mainImgStyle: CSSProperties = {\n display: 'block',\n width: '100%',\n height: '100%',\n objectFit,\n ...(imageRendering ? { imageRendering } : {}),\n opacity: loaded ? 1 : 0,\n transition: 'opacity 0.3s ease',\n ...imgStyle,\n }\n\n return (\n <div className={className} style={containerStyle}>\n {hasLqip && (\n <img\n aria-hidden\n alt=\"\"\n src={image.lqip!}\n style={{\n ...overlayBase,\n display: 'block',\n objectFit,\n filter: 'blur(20px)',\n transform: 'scale(1.1)',\n }}\n />\n )}\n {placeholderColor && (\n <div\n aria-hidden\n style={{\n ...overlayBase,\n backgroundColor: placeholderColor,\n }}\n />\n )}\n <img\n ref={imgRef}\n alt={altProp ?? image.alt ?? ''}\n src={src}\n srcSet={srcSet || undefined}\n sizes={sizes}\n width={width ? width * dpr : undefined}\n loading={loading}\n decoding=\"async\"\n fetchPriority={priority ? 'high' : undefined}\n onLoad={fireLoad}\n className={imgClassName}\n style={mainImgStyle}\n />\n </div>\n )\n}\n","/** Palette colors extracted from an image */\nexport interface ImagePalette {\n vibrant?: string | null\n muted?: string | null\n darkVibrant?: string | null\n darkMuted?: string | null\n lightVibrant?: string | null\n lightMuted?: string | null\n}\n\n/** Common image data shape from Payload CMS upload collections */\nexport interface ImageData {\n url?: string | null\n width?: number | null\n height?: number | null\n alt?: string | null\n lqip?: string | null\n palette?: ImagePalette | null\n sizes?: Record<\n string,\n | {\n url?: string | null\n width?: number | null\n height?: number | null\n }\n | undefined\n >\n}\n\n/** Pre-generated image size breakpoints (px) */\nexport const IMAGE_SIZES = [384, 768, 1536] as const\n\n/**\n * Returns the optimal image URL for a given display width.\n *\n * Picks the smallest pre-generated size whose width >= displayWidth × dpr.\n * Falls back to the original URL when no matching size exists.\n *\n * @param image - Payload image document\n * @param displayWidth - CSS pixel width the image will be displayed at\n * @param dpr - Device pixel ratio (default: 1)\n * @returns URL string, or empty string if no URL is available\n */\nexport function getImageUrl(\n image: ImageData,\n displayWidth: number,\n dpr: number = 1,\n): string {\n const target = displayWidth * dpr\n const sizes = image.sizes\n\n if (sizes) {\n for (const size of IMAGE_SIZES) {\n if (size >= target) {\n const entry = sizes[String(size)]\n if (entry?.url) return entry.url\n }\n }\n }\n\n return image.url ?? ''\n}\n\n/**\n * Generates an HTML `srcset` attribute string from pre-generated sizes.\n *\n * Includes all available sizes plus the original image.\n * Example output: `\"url-384 384w, url-768 768w, url-1536 1536w, url-original 2000w\"`\n *\n * @param image - Payload image document\n * @returns srcset string, or empty string if no URLs are available\n */\nexport function getImageSrcSet(image: ImageData): string {\n const parts: string[] = []\n const sizes = image.sizes\n\n if (sizes) {\n for (const size of IMAGE_SIZES) {\n const entry = sizes[String(size)]\n if (entry?.url && entry.width) {\n parts.push(`${entry.url} ${entry.width}w`)\n }\n }\n }\n\n if (image.url && image.width) {\n parts.push(`${image.url} ${image.width}w`)\n }\n\n return parts.join(', ')\n}\n\n/**\n * Returns the LQIP (Low Quality Image Placeholder) data URL for an image.\n *\n * @param image - Payload image document\n * @returns LQIP data URL string, or undefined if not available\n */\nexport function getImageLqip(image: ImageData): string | undefined {\n return image.lqip ?? undefined\n}\n\n/**\n * Returns the extracted color palette for an image.\n *\n * @param image - Payload image document\n * @returns ImagePalette object, or undefined if not available\n */\nexport function getImagePalette(image: ImageData): ImagePalette | undefined {\n return image.palette ?? undefined\n}\n\n/** Options for `getImagePlaceholderStyle` */\nexport interface ImagePlaceholderOptions {\n /** Placeholder strategy (default: 'blur') */\n type?: 'blur' | 'color' | 'none'\n /** Which palette color to use for 'color' strategy (default: 'muted') */\n paletteColor?: keyof ImagePalette\n}\n\n/**\n * Returns inline CSS styles for an image placeholder.\n *\n * - `blur`: uses LQIP as background, falls back to palette color, then empty\n * - `color`: uses palette color as background, falls back to empty\n * - `none`: always returns empty\n *\n * @param image - Payload image document\n * @param options - Placeholder options\n * @returns CSS style object compatible with React CSSProperties\n */\nexport function getImagePlaceholderStyle(\n image: ImageData,\n options?: ImagePlaceholderOptions,\n): Record<string, string> {\n const type = options?.type ?? 'blur'\n const paletteColor = options?.paletteColor ?? 'muted'\n\n if (type === 'none') return {}\n\n const color = image.palette?.[paletteColor]\n\n if (type === 'blur') {\n const lqip = image.lqip\n if (lqip) {\n return {\n backgroundImage: `url(${lqip})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n }\n }\n // Cascade: fall back to color\n if (color) {\n return { backgroundColor: color }\n }\n return {}\n }\n\n // type === 'color'\n if (color) {\n return { backgroundColor: color }\n }\n return {}\n}\n"],"mappings":";;;AAEA,OAAO,SAAS,aAAa,QAAQ,gBAAgB;;;AC4B9C,IAAM,cAAc,CAAC,KAAK,KAAK,IAAI;AA0CnC,SAAS,eAAe,OAA0B;AACvD,QAAM,QAAkB,CAAC;AACzB,QAAM,QAAQ,MAAM;AAEpB,MAAI,OAAO;AACT,eAAW,QAAQ,aAAa;AAC9B,YAAM,QAAQ,MAAM,OAAO,IAAI,CAAC;AAChC,UAAI,OAAO,OAAO,MAAM,OAAO;AAC7B,cAAM,KAAK,GAAG,MAAM,GAAG,IAAI,MAAM,KAAK,GAAG;AAAA,MAC3C;AAAA,IACF;AAAA,EACF;AAEA,MAAI,MAAM,OAAO,MAAM,O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AA,QACL,GAAG;AAAA,QACH,SAAS;AAAA,QACT;AAAA,QACA,QAAQ;AAAA,QACR,WAAW;AAAA,MACb;AAAA;AAAA,EACF,GAED,oBACC;AAAA,IAAC;AAAA;AAAA,MACC,eAAW;AAAA,MACX,OAAO;AAAA,QACL,GAAG;AAAA,QACH,iBAAiB;AAAA,MACnB;AAAA;AAAA,EACF,GAEF;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL,KAAK,WAAW,MAAM,OAAO;AAAA,MAC7B;AAAA,MACA,QAAQ,UAAU;AAAA,MAClB;AAAA,MACA,OAAO,QAAQ,QAAQ,MAAM;AAAA,MAC7B;AAAA,MACA,UAAS;AAAA,MACT,eAAe,WAAW,SAAS;AAAA,MACnC,QAAQ;AAAA,MACR,WAAW;AAAA,MACX,OAAO;AAAA;AAAA,EACT,CACF;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/ui/Image/index.tsx","../../src/utils/image.ts"],"sourcesContent":["'use client'\n\nimport React, { useCallback, useRef, useState } from 'react'\nimport type { CSSProperties } from 'react'\nimport type { ImageData } from '../../utils/image'\nimport { getImageSrcSet, getImagePlaceholderStyle } from '../../utils/image'\n\nexport interface ImageProps {\n /** Payload image document */\n image: ImageData\n /** Display width in CSS pixels (for selecting optimal srcset size) */\n width?: number\n /** Device pixel ratio (default: 1) */\n dpr?: number\n /** Placeholder strategy (default: 'blur'; defaults to 'none' when imageRendering is 'pixelated' or 'crisp-edges') */\n placeholder?: 'blur' | 'color' | 'none'\n /** Container className */\n className?: string\n /** Container style */\n style?: CSSProperties\n /** Inner `<img>` className */\n imgClassName?: string\n /** Inner `<img>` style */\n imgStyle?: CSSProperties\n /** HTML sizes attribute */\n sizes?: string\n /** Loading strategy (default: 'lazy'; automatically 'eager' when priority is true) */\n loading?: 'lazy' | 'eager'\n /** Callback when image finishes loading */\n onLoad?: () => void\n /** Object-fit for the image (default: 'cover') */\n objectFit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down'\n /** When true, loads eagerly with high fetch priority (for LCP images) */\n priority?: boolean\n /** When true, fills parent container (width/height: 100%, no aspect ratio) */\n fill?: boolean\n /** CSS image-rendering mode (e.g. 'pixelated' for pixel art) */\n imageRendering?: 'auto' | 'pixelated' | 'crisp-edges'\n /** alt text override (falls back to image.alt, then empty string) */\n alt?: string\n}\n\n/**\n * Image component with blur-up / color placeholder support.\n *\n * Uses LQIP (Low Quality Image Placeholder) for a smooth blur-up effect,\n * falling back to palette color or no placeholder.\n */\nexport function Image({\n image,\n width,\n dpr = 1,\n placeholder: placeholderProp,\n className,\n style,\n imgClassName,\n imgStyle,\n sizes,\n loading: loadingProp,\n onLoad,\n objectFit = 'cover',\n priority = false,\n fill = false,\n imageRendering,\n alt: altProp,\n}: ImageProps) {\n const [loaded, setLoaded] = useState(false)\n const firedRef = useRef(false)\n\n // Resolve defaults based on other props\n const isPixelRendering =\n imageRendering === 'pixelated' || imageRendering === 'crisp-edges'\n const placeholder = placeholderProp ?? (isPixelRendering ? 'none' : 'blur')\n const loading = priority ? 'eager' : (loadingProp ?? 'lazy')\n\n const aspectRatio =\n !fill && image.width && image.height\n ? `${image.width} / ${image.height}`\n : undefined\n\n const srcSet = getImageSrcSet(image)\n const src = image.url ?? undefined\n\n // Placeholder: LQIP overlay or color overlay (mutually exclusive)\n const hasLqip = placeholder === 'blur' && !!image.lqip\n const placeholderStyle = getImagePlaceholderStyle(image, {\n type: placeholder,\n })\n const placeholderColor =\n !hasLqip && 'backgroundColor' in placeholderStyle\n ? placeholderStyle.backgroundColor\n : undefined\n\n const fireLoad = useCallback(() => {\n if (firedRef.current) return\n firedRef.current = true\n setLoaded(true)\n onLoad?.()\n }, [onLoad])\n\n // Callback ref: detect SSR-cached images that are already loaded\n const imgRef = useCallback(\n (node: HTMLImageElement | null) => {\n if (node && node.complete && node.naturalWidth > 0) {\n fireLoad()\n }\n },\n [fireLoad],\n )\n\n // Container styles\n const containerStyle: CSSProperties = {\n position: 'relative',\n overflow: 'hidden',\n ...(fill ? { width: '100%', height: '100%' } : {}),\n ...(aspectRatio ? { aspectRatio } : {}),\n ...style,\n }\n\n // Shared overlay styles (LQIP and color)\n const overlayBase: CSSProperties = {\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n height: '100%',\n opacity: loaded ? 0 : 1,\n transition: 'opacity 0.3s ease',\n pointerEvents: 'none',\n }\n\n // Main image styles\n const mainImgStyle: CSSProperties = {\n display: 'block',\n width: '100%',\n height: '100%',\n objectFit,\n ...(imageRendering ? { imageRendering } : {}),\n opacity: loaded ? 1 : 0,\n transition: 'opacity 0.3s ease',\n ...imgStyle,\n }\n\n return (\n <div className={className} style={containerStyle}>\n {hasLqip && (\n <img\n aria-hidden\n alt=\"\"\n src={image.lqip!}\n style={{\n ...overlayBase,\n display: 'block',\n objectFit,\n filter: 'blur(20px)',\n transform: 'scale(1.1)',\n }}\n />\n )}\n {placeholderColor && (\n <div\n aria-hidden\n style={{\n ...overlayBase,\n backgroundColor: placeholderColor,\n }}\n />\n )}\n <img\n ref={imgRef}\n alt={altProp ?? image.alt ?? ''}\n src={src}\n srcSet={srcSet || undefined}\n sizes={sizes}\n width={width ? width * dpr : undefined}\n loading={loading}\n decoding=\"async\"\n fetchPriority={priority ? 'high' : undefined}\n onLoad={fireLoad}\n className={imgClassName}\n style={mainImgStyle}\n />\n </div>\n )\n}\n","/** Palette colors extracted from an image */\nexport interface ImagePalette {\n vibrant?: string | null\n muted?: string | null\n darkVibrant?: string | null\n darkMuted?: string | null\n lightVibrant?: string | null\n lightMuted?: string | null\n}\n\n/** Structural image size entry accepted by public image helpers. */\nexport interface ImageDataSizeEntry {\n url?: string | null\n width?: number | null\n height?: number | null\n}\n\n/** Structural image sizes accepted from Payload upload-like collections. */\nexport type ImageDataSizes = Partial<\n Record<string, ImageDataSizeEntry | null | undefined>\n>\n\n/** Common image data shape from Payload CMS upload collections */\nexport interface ImageData {\n url?: string | null\n width?: number | null\n height?: number | null\n alt?: string | null\n lqip?: string | null\n palette?: ImagePalette | null\n sizes?: ImageDataSizes\n}\n\n/** Pre-generated image size breakpoints (px), aligned with Payload Image.sizes. */\nexport const IMAGE_SIZES = [200, 400, 800, 1200, 1600] as const\n\n/** Numeric rendition keys from `IMAGE_SIZES` plus any numeric keys on the image. */\nfunction imageSizeCandidates(sizes: ImageDataSizes): number[] {\n const keys = new Set<number>(IMAGE_SIZES)\n for (const key of Object.keys(sizes)) {\n const value = Number(key)\n if (Number.isFinite(value) && value > 0) keys.add(value)\n }\n return [...keys].sort((a, b) => a - b)\n}\n\n/**\n * Returns the optimal image URL for a given display width.\n *\n * Picks the smallest pre-generated size whose width >= displayWidth × dpr.\n * Falls back to the original URL when no matching size exists.\n *\n * @param image - Payload image document\n * @param displayWidth - CSS pixel width the image will be displayed at\n * @param dpr - Device pixel ratio (default: 1)\n * @returns URL string, or empty string if no URL is available\n */\nexport function getImageUrl(\n image: ImageData,\n displayWidth: number,\n dpr: number = 1,\n): string {\n const target = displayWidth * dpr\n const sizes = image.sizes\n\n if (sizes) {\n for (const size of imageSizeCandidates(sizes)) {\n if (size >= target) {\n const entry = sizes[`${size}`]\n if (entry?.url) return entry.url\n }\n }\n }\n\n return image.url ?? ''\n}\n\n/**\n * Generates an HTML `srcset` attribute string from pre-generated sizes.\n *\n * Includes all available sizes plus the original image.\n * Example output: `\"url-200 200w, url-400 400w, url-800 800w, url-1200 1200w, url-1600 1600w, url-original 2000w\"`\n *\n * @param image - Payload image document\n * @returns srcset string, or empty string if no URLs are available\n */\nexport function getImageSrcSet(image: ImageData): string {\n const parts: string[] = []\n const emittedWidths = new Set<number>()\n const sizes = image.sizes\n\n if (sizes) {\n for (const size of imageSizeCandidates(sizes)) {\n const entry = sizes[`${size}`]\n if (entry?.url && entry.width && !emittedWidths.has(entry.width)) {\n emittedWidths.add(entry.width)\n parts.push(`${entry.url} ${entry.width}w`)\n }\n }\n }\n\n if (image.url && image.width && !emittedWidths.has(image.width)) {\n parts.push(`${image.url} ${image.width}w`)\n }\n\n return parts.join(', ')\n}\n\n/**\n * Returns the LQIP (Low Quality Image Placeholder) data URL for an image.\n *\n * @param image - Payload image document\n * @returns LQIP data URL string, or undefined if not available\n */\nexport function getImageLqip(image: ImageData): string | undefined {\n return image.lqip ?? undefined\n}\n\n/**\n * Returns the extracted color palette for an image.\n *\n * @param image - Payload image document\n * @returns ImagePalette object, or undefined if not available\n */\nexport function getImagePalette(image: ImageData): ImagePalette | undefined {\n return image.palette ?? undefined\n}\n\n/** Options for `getImagePlaceholderStyle` */\nexport interface ImagePlaceholderOptions {\n /** Placeholder strategy (default: 'blur') */\n type?: 'blur' | 'color' | 'none'\n /** Which palette color to use for 'color' strategy (default: 'muted') */\n paletteColor?: keyof ImagePalette\n}\n\n/**\n * Returns inline CSS styles for an image placeholder.\n *\n * - `blur`: uses LQIP as background, falls back to palette color, then empty\n * - `color`: uses palette color as background, falls back to empty\n * - `none`: always returns empty\n *\n * @param image - Payload image document\n * @param options - Placeholder options\n * @returns CSS style object compatible with React CSSProperties\n */\nexport function getImagePlaceholderStyle(\n image: ImageData,\n options?: ImagePlaceholderOptions,\n): Record<string, string> {\n const type = options?.type ?? 'blur'\n const paletteColor = options?.paletteColor ?? 'muted'\n\n if (type === 'none') return {}\n\n const color = image.palette?.[paletteColor]\n\n if (type === 'blur') {\n const lqip = image.lqip\n if (lqip) {\n return {\n backgroundImage: `url(${lqip})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n }\n }\n // Cascade: fall back to color\n if (color) {\n return { backgroundColor: color }\n }\n return {}\n }\n\n // type === 'color'\n if (color) {\n return { backgroundColor: color }\n }\n return {}\n}\n"],"mappings":";;;AAEA,OAAO,SAAS,aAAa,QAAQ,gBAAgB;;;ACgC9C,IAAM,cAAc,CAAC,KAAK,KAAK,KAAK,MAAM,IAAI;AAGrD,SAAS,oBAAoB,OAAiC;AAC5D,QAAM,OAAO,IAAI,IAAY,WAAW;AACxC,aAAW,OAAO,OAAO,KAAK,KAAK,GAA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cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import React, { CSSProperties } from 'react';
|
|
2
2
|
import { MuxPlayerProps, MuxPlayerRefAttributes } from '@mux/mux-player-react';
|
|
3
3
|
export { MuxPlayerRefAttributes as VideoPlayerRef } from '@mux/mux-player-react';
|
|
4
|
-
import { V as Video } from '../payload-types-
|
|
4
|
+
import { V as Video } from '../payload-types-CREOjFNT.cjs';
|
|
5
5
|
export { V as VideoGifOptions, a as VideoThumbnailOptions, g as getVideoGif, b as getVideoMp4Url, c as getVideoStoryboard, d as getVideoStreamUrl, e as getVideoThumbnail } from '../video-WR_TFO9a.cjs';
|
|
6
6
|
|
|
7
7
|
interface VideoPlayerCSSProperties extends CSSProperties {
|
package/dist/ui/video.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import React, { CSSProperties } from 'react';
|
|
2
2
|
import { MuxPlayerProps, MuxPlayerRefAttributes } from '@mux/mux-player-react';
|
|
3
3
|
export { MuxPlayerRefAttributes as VideoPlayerRef } from '@mux/mux-player-react';
|
|
4
|
-
import { V as Video } from '../payload-types-
|
|
4
|
+
import { V as Video } from '../payload-types-CREOjFNT.js';
|
|
5
5
|
export { V as VideoGifOptions, a as VideoThumbnailOptions, g as getVideoGif, b as getVideoMp4Url, c as getVideoStoryboard, d as getVideoStreamUrl, e as getVideoThumbnail } from '../video-WR_TFO9a.js';
|
|
6
6
|
|
|
7
7
|
interface VideoPlayerCSSProperties extends CSSProperties {
|
package/dist/webhook.cjs
CHANGED
|
@@ -26,6 +26,7 @@ __export(webhook_exports, {
|
|
|
26
26
|
CUSTOMER_PASSWORD_RESET_OPERATION: () => CUSTOMER_PASSWORD_RESET_OPERATION,
|
|
27
27
|
ORDER_CHANGED_EVENT_TYPE: () => ORDER_CHANGED_EVENT_TYPE,
|
|
28
28
|
createCommerceEmailWebhookHandler: () => createCommerceEmailWebhookHandler,
|
|
29
|
+
createCommerceNotificationWebhookHandler: () => createCommerceNotificationWebhookHandler,
|
|
29
30
|
createCustomerAuthWebhookHandler: () => createCustomerAuthWebhookHandler,
|
|
30
31
|
createTypedWebhookHandler: () => createTypedWebhookHandler,
|
|
31
32
|
defineCommerceEmailConfig: () => defineCommerceEmailConfig,
|
|
@@ -154,7 +155,7 @@ function getCommerceNotificationIdempotencyKey(event) {
|
|
|
154
155
|
function defineCommerceEmailConfig(config) {
|
|
155
156
|
return config;
|
|
156
157
|
}
|
|
157
|
-
function
|
|
158
|
+
function createCommerceNotificationWebhookHandler(handlers) {
|
|
158
159
|
return async (event) => {
|
|
159
160
|
if (!isCommerceNotificationWebhookEvent(event)) {
|
|
160
161
|
await handlers.unhandled?.(event);
|
|
@@ -171,6 +172,9 @@ function createCommerceEmailWebhookHandler(handlers) {
|
|
|
171
172
|
});
|
|
172
173
|
};
|
|
173
174
|
}
|
|
175
|
+
function createCommerceEmailWebhookHandler(handlers) {
|
|
176
|
+
return createCommerceNotificationWebhookHandler(handlers);
|
|
177
|
+
}
|
|
174
178
|
function isWebhookCollection(event, collection) {
|
|
175
179
|
return isValidWebhookEvent(event) && event.collection === collection;
|
|
176
180
|
}
|
package/dist/webhook.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webhook.ts","../src/core/webhook/index.ts"],"sourcesContent":["export {\n handleWebhook,\n createTypedWebhookHandler,\n createCommerceEmailWebhookHandler,\n createCustomerAuthWebhookHandler,\n defineCommerceEmailConfig,\n getCommerceNotificationIdempotencyKey,\n isValidWebhookEvent,\n isCommerceNotificationWebhookEvent,\n isCustomerPasswordResetWebhookEvent,\n isOrderChangedWebhookEvent,\n isWebhookCollection,\n isWebhookOperation,\n CUSTOMER_PASSWORD_RESET_OPERATION,\n COMMERCE_NOTIFICATION_EVENT_TYPE,\n COMMERCE_NOTIFICATION_EVENTS,\n COMMERCE_NOTIFICATION_OPERATION,\n ORDER_CHANGED_EVENT_TYPE,\n} from './core/webhook'\nexport type {\n CollectionWebhookOperation,\n CommerceEmailChannel,\n CommerceEmailConfig,\n CommerceEmailEventConfig,\n CommerceEmailEventHandlers,\n CommerceEmailHandlerContext,\n CommerceNotification,\n CommerceNotificationData,\n CommerceNotificationEventName,\n CommerceNotificationSource,\n CommerceNotificationSourceCollection,\n CommerceNotificationWebhookEvent,\n CustomerAuthWebhookEvent,\n CustomerAuthWebhookHandlers,\n CustomerPasswordResetWebhookData,\n CustomerPasswordResetWebhookEvent,\n OrderChangedWebhookEvent,\n WebhookChange,\n WebhookCommerceNotificationChange,\n WebhookEvent,\n WebhookHandler,\n WebhookKnownOperation,\n WebhookOperation,\n WebhookOptions,\n WebhookOrderChange,\n WebhookOrderMoved,\n WebhookOrderScope,\n} from './core/webhook'\nexport type {\n WebhookSigningSecretReveal,\n WebhookWithoutSecret,\n} from './webhook-types'\n","import type { Collection } from '../client/types'\nimport type { CollectionType } from '../collection/types'\n\nexport type WebhookOperation = string\n\n/**\n * Semantic event type for manual Admin Panel ordering changes.\n *\n * Order-change webhooks remain `operation: \"update\"` events for compatibility.\n * Do not filter on or emit `operation: \"reorder\"`; use this event type with\n * `isOrderChangedWebhookEvent()` to distinguish ordering from normal content\n * updates.\n */\nexport const ORDER_CHANGED_EVENT_TYPE = 'collection.orderChanged' as const\n\n/** Semantic event type for v1 commerce notification webhooks. */\nexport const COMMERCE_NOTIFICATION_EVENT_TYPE = 'commerce.notification' as const\n\n/** Collection webhook operations emitted for tenant collection writes. */\nexport type CollectionWebhookOperation = 'create' | 'update'\n\n/** Describes the ordered area affected by an order-change webhook. */\nexport type WebhookOrderScope =\n | { kind: 'collection'; collection: string }\n | { kind: 'join'; collection: string; field: string; id: string | number }\n\n/** Identifies the public moved document for the ordered scope. */\nexport type WebhookOrderMoved = {\n collection: string\n id: string | number\n relatedCollection?: string\n relatedId?: string | number\n}\n\n/** Metadata attached to `collection.orderChanged` webhook events. */\nexport type WebhookOrderChange = {\n type: 'order'\n source: 'payload-orderable'\n /**\n * Diagnostic Payload order field name.\n *\n * This may contain hidden implementation field names. Application routing\n * should use `change.scope` and `change.moved` instead.\n */\n orderableFieldName?: string\n previousOrder?: string | null\n nextOrder?: string | null\n scope: WebhookOrderScope\n moved: WebhookOrderMoved\n}\n\n/** Known semantic webhook change metadata. */\nexport type WebhookChange = WebhookOrderChange | WebhookCommerceNotificationChange\n\nexport interface WebhookEvent<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> {\n collection: T\n operation: WebhookOperation\n data: TData\n eventType?: string\n change?: unknown\n timestamp?: string\n deliveryId?: string\n}\n\nexport type WebhookHandler<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> = (event: WebhookEvent<T, TData>) => Promise<void> | void\n\nexport interface WebhookOptions {\n secret?: string\n /** Max accepted skew for signed webhook delivery timestamps. Default: 300s. */\n toleranceSeconds?: number\n}\n\nexport function isValidWebhookEvent(data: unknown): data is WebhookEvent {\n if (typeof data !== 'object' || data === null) return false\n const obj = data as Record<string, unknown>\n return (\n typeof obj.collection === 'string' &&\n typeof obj.operation === 'string' &&\n obj.operation.length > 0 &&\n typeof obj.data === 'object' &&\n obj.data !== null\n )\n}\n\n/** Webhook event emitted when manual Admin Panel ordering changes. */\nexport type OrderChangedWebhookEvent<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> = WebhookEvent<T, TData> & {\n operation: 'update'\n eventType: typeof ORDER_CHANGED_EVENT_TYPE\n change: WebhookOrderChange\n}\n\nexport const COMMERCE_NOTIFICATION_OPERATION = 'notification' as const\n\nexport const COMMERCE_NOTIFICATION_EVENTS = [\n 'orderPaid',\n 'orderCanceled',\n 'fulfillmentShipped',\n 'orderDelivered',\n 'returnRequested',\n 'returnCompleted',\n] as const\n\nexport type CommerceNotificationEventName =\n (typeof COMMERCE_NOTIFICATION_EVENTS)[number]\n\nexport type CommerceNotificationSourceCollection =\n | 'orders'\n | 'fulfillments'\n | 'returns'\n\nexport type CommerceNotificationSource = {\n collection: CommerceNotificationSourceCollection\n id: string | number\n}\n\nexport type CommerceNotificationData = {\n source?: CommerceNotificationSource\n orderId?: string | number\n orderNumber?: string\n status?: string\n totalAmount?: number\n currency?: string\n fulfillmentId?: string | number\n fulfillmentStatus?: string\n shippedAt?: string\n returnId?: string | number\n returnStatus?: string\n refundAmount?: number\n completedAt?: string\n}\n\nexport type CommerceNotification = {\n event: CommerceNotificationEventName\n intentId: string\n dedupeKey: string\n orderId?: string\n fulfillmentId?: string\n returnId?: string\n}\n\nexport type WebhookCommerceNotificationChange = {\n type: 'notification'\n source: 'commerce-notifications'\n event: CommerceNotificationEventName\n sourceCollection: CommerceNotificationSourceCollection\n sourceId: string | number\n}\n\n/** Webhook event emitted for v1 commerce notification deliveries. */\nexport type CommerceNotificationWebhookEvent = WebhookEvent<\n CommerceNotificationSourceCollection,\n CommerceNotificationData\n> & {\n operation: typeof COMMERCE_NOTIFICATION_OPERATION\n eventType: typeof COMMERCE_NOTIFICATION_EVENT_TYPE\n change?: WebhookCommerceNotificationChange\n notification: CommerceNotification\n}\n\nexport type CommerceEmailChannel = 'webhook' | 'provider'\n\nexport type CommerceEmailEventConfig = {\n enabled: boolean\n channel: CommerceEmailChannel\n template?: string\n}\n\nexport type CommerceEmailConfig = {\n version: 1\n commerceNotifications: Partial<\n Record<CommerceNotificationEventName, CommerceEmailEventConfig>\n >\n}\n\nexport type CommerceEmailHandlerContext = {\n event: CommerceNotificationWebhookEvent\n idempotencyKey: string\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nexport type CommerceEmailEventHandlers = Partial<\n Record<\n CommerceNotificationEventName,\n (context: CommerceEmailHandlerContext) => MaybePromise<void>\n >\n> & {\n unhandled?: (event: WebhookEvent<string, unknown>) => MaybePromise<void>\n}\n\nfunction isStringOrNumber(value: unknown): value is string | number {\n return typeof value === 'string' || typeof value === 'number'\n}\n\nfunction isWebhookOrderScope(value: unknown): value is WebhookOrderScope {\n if (!isRecord(value)) return false\n\n if (value.kind === 'collection') {\n return typeof value.collection === 'string'\n }\n\n if (value.kind === 'join') {\n return (\n typeof value.collection === 'string' &&\n typeof value.field === 'string' &&\n isStringOrNumber(value.id)\n )\n }\n\n return false\n}\n\nfunction isWebhookOrderMoved(value: unknown): value is WebhookOrderMoved {\n if (!isRecord(value)) return false\n\n return (\n typeof value.collection === 'string' &&\n isStringOrNumber(value.id) &&\n (value.relatedCollection === undefined ||\n typeof value.relatedCollection === 'string') &&\n (value.relatedId === undefined || isStringOrNumber(value.relatedId))\n )\n}\n\nfunction hasOptionalOrderValue(\n value: Record<string, unknown>,\n key: string,\n): boolean {\n return (\n value[key] === undefined ||\n value[key] === null ||\n typeof value[key] === 'string'\n )\n}\n\nfunction isWebhookOrderChange(value: unknown): value is WebhookOrderChange {\n if (!isRecord(value)) return false\n\n return (\n value.type === 'order' &&\n value.source === 'payload-orderable' &&\n (value.orderableFieldName === undefined ||\n typeof value.orderableFieldName === 'string') &&\n hasOptionalOrderValue(value, 'previousOrder') &&\n hasOptionalOrderValue(value, 'nextOrder') &&\n isWebhookOrderScope(value.scope) &&\n isWebhookOrderMoved(value.moved)\n )\n}\n\nfunction isCommerceNotificationEventName(\n value: unknown,\n): value is CommerceNotificationEventName {\n return (\n typeof value === 'string' &&\n (COMMERCE_NOTIFICATION_EVENTS as readonly string[]).includes(value)\n )\n}\n\nfunction isCommerceNotificationSourceCollection(\n value: unknown,\n): value is CommerceNotificationSourceCollection {\n return value === 'orders' || value === 'fulfillments' || value === 'returns'\n}\n\nfunction isCommerceNotificationData(\n value: unknown,\n): value is CommerceNotificationData {\n if (!isRecord(value)) return false\n if (\n value.source !== undefined &&\n (!isRecord(value.source) ||\n !isCommerceNotificationSourceCollection(value.source.collection) ||\n !isStringOrNumber(value.source.id))\n ) {\n return false\n }\n\n return (\n (value.orderId === undefined || isStringOrNumber(value.orderId)) &&\n (value.orderNumber === undefined || typeof value.orderNumber === 'string') &&\n (value.status === undefined || typeof value.status === 'string') &&\n (value.totalAmount === undefined || typeof value.totalAmount === 'number') &&\n (value.currency === undefined || typeof value.currency === 'string') &&\n (value.fulfillmentId === undefined ||\n isStringOrNumber(value.fulfillmentId)) &&\n (value.fulfillmentStatus === undefined ||\n typeof value.fulfillmentStatus === 'string') &&\n (value.shippedAt === undefined || typeof value.shippedAt === 'string') &&\n (value.returnId === undefined || isStringOrNumber(value.returnId)) &&\n (value.returnStatus === undefined ||\n typeof value.returnStatus === 'string') &&\n (value.refundAmount === undefined ||\n typeof value.refundAmount === 'number') &&\n (value.completedAt === undefined || typeof value.completedAt === 'string')\n )\n}\n\nfunction isCommerceNotification(\n value: unknown,\n): value is CommerceNotification {\n if (!isRecord(value)) return false\n return (\n isCommerceNotificationEventName(value.event) &&\n typeof value.intentId === 'string' &&\n value.intentId.length > 0 &&\n typeof value.dedupeKey === 'string' &&\n value.dedupeKey.length > 0 &&\n (value.orderId === undefined || typeof value.orderId === 'string') &&\n (value.fulfillmentId === undefined ||\n typeof value.fulfillmentId === 'string') &&\n (value.returnId === undefined || typeof value.returnId === 'string')\n )\n}\n\nfunction isWebhookCommerceNotificationChange(\n value: unknown,\n): value is WebhookCommerceNotificationChange {\n if (!isRecord(value)) return false\n return (\n value.type === 'notification' &&\n value.source === 'commerce-notifications' &&\n isCommerceNotificationEventName(value.event) &&\n isCommerceNotificationSourceCollection(value.sourceCollection) &&\n isStringOrNumber(value.sourceId)\n )\n}\n\nfunction matchesOptionalId(\n actual: string | number | undefined,\n expected: string | number | undefined,\n): boolean {\n return actual === undefined || expected === undefined || actual === expected\n}\n\n/**\n * Returns true for semantic order-change webhooks emitted as update events.\n *\n * Use this guard with `ORDER_CHANGED_EVENT_TYPE` instead of filtering on\n * `operation: \"reorder\"`. Tenant order-change webhooks intentionally keep\n * `operation: \"update\"` for compatibility with existing webhook handlers.\n */\nexport function isOrderChangedWebhookEvent(\n event: unknown,\n): event is OrderChangedWebhookEvent<string, unknown> {\n if (\n !isValidWebhookEvent(event) ||\n event.operation !== 'update' ||\n event.eventType !== ORDER_CHANGED_EVENT_TYPE ||\n !isWebhookOrderChange(event.change)\n ) {\n return false\n }\n\n if (event.collection !== event.change.scope.collection) {\n return false\n }\n\n if (\n event.change.scope.kind === 'collection' &&\n event.change.moved.collection !== event.change.scope.collection\n ) {\n return false\n }\n\n return true\n}\n\n/**\n * Returns true for semantic commerce notification webhooks.\n *\n * Use `notification.intentId` and `notification.dedupeKey` for semantic\n * idempotency. `deliveryId`, when present, identifies a delivery attempt for\n * observability and is not the semantic notification identity.\n */\nexport function isCommerceNotificationWebhookEvent(\n event: unknown,\n): event is CommerceNotificationWebhookEvent {\n if (\n !isValidWebhookEvent(event) ||\n event.operation !== COMMERCE_NOTIFICATION_OPERATION ||\n event.eventType !== COMMERCE_NOTIFICATION_EVENT_TYPE ||\n !isCommerceNotificationData(event.data) ||\n !isCommerceNotification((event as { notification?: unknown }).notification)\n ) {\n return false\n }\n\n const notification = (event as unknown as CommerceNotificationWebhookEvent)\n .notification\n const data = event.data\n const change = event.change\n const sourceCollection = data.source?.collection ?? event.collection\n const sourceId = data.source?.id\n\n if (!isCommerceNotificationSourceCollection(sourceCollection)) return false\n if (data.source !== undefined && event.collection !== data.source.collection) {\n return false\n }\n\n if (change !== undefined) {\n if (!isWebhookCommerceNotificationChange(change)) return false\n if (change.sourceCollection !== sourceCollection) return false\n if (change.event !== notification.event) return false\n if (!matchesOptionalId(change.sourceId, sourceId)) return false\n }\n const changeSourceId = isWebhookCommerceNotificationChange(change)\n ? change.sourceId\n : undefined\n\n if (\n notification.event === 'orderPaid' ||\n notification.event === 'orderCanceled' ||\n notification.event === 'orderDelivered'\n ) {\n return (\n sourceCollection === 'orders' &&\n typeof notification.orderId === 'string' &&\n notification.orderId.length > 0 &&\n matchesOptionalId(data.orderId, sourceId) &&\n matchesOptionalId(notification.orderId, sourceId) &&\n matchesOptionalId(data.orderId, notification.orderId) &&\n matchesOptionalId(changeSourceId, data.orderId ?? notification.orderId)\n )\n }\n\n if (notification.event === 'fulfillmentShipped') {\n return (\n sourceCollection === 'fulfillments' &&\n matchesOptionalId(data.fulfillmentId, sourceId) &&\n typeof notification.fulfillmentId === 'string' &&\n notification.fulfillmentId.length > 0 &&\n matchesOptionalId(notification.fulfillmentId, sourceId) &&\n matchesOptionalId(data.fulfillmentId, notification.fulfillmentId) &&\n matchesOptionalId(changeSourceId, notification.fulfillmentId)\n )\n }\n\n if (\n notification.event === 'returnRequested' ||\n notification.event === 'returnCompleted'\n ) {\n return (\n sourceCollection === 'returns' &&\n matchesOptionalId(data.returnId, sourceId) &&\n typeof notification.returnId === 'string' &&\n notification.returnId.length > 0 &&\n matchesOptionalId(notification.returnId, sourceId) &&\n matchesOptionalId(data.returnId, notification.returnId) &&\n matchesOptionalId(changeSourceId, notification.returnId)\n )\n }\n\n return false\n}\n\nexport function getCommerceNotificationIdempotencyKey(\n event: Pick<CommerceNotificationWebhookEvent, 'notification'>,\n): string {\n return `${event.notification.intentId}:${event.notification.dedupeKey}`\n}\n\nexport function defineCommerceEmailConfig<TConfig extends CommerceEmailConfig>(\n config: TConfig,\n): TConfig {\n return config\n}\n\nexport function createCommerceEmailWebhookHandler(\n handlers: CommerceEmailEventHandlers,\n): WebhookHandler<string, unknown> {\n return async (event) => {\n if (!isCommerceNotificationWebhookEvent(event)) {\n await handlers.unhandled?.(event)\n return\n }\n\n const handler = handlers[event.notification.event]\n if (!handler) {\n await handlers.unhandled?.(event)\n return\n }\n\n await handler({\n event,\n idempotencyKey: getCommerceNotificationIdempotencyKey(event),\n })\n }\n}\n\n/** Narrows a webhook event to a specific collection. */\nexport function isWebhookCollection<TCollection extends string>(\n event: unknown,\n collection: TCollection,\n): event is WebhookEvent<TCollection, unknown> {\n return isValidWebhookEvent(event) && event.collection === collection\n}\n\n/** Narrows a webhook event to a specific operation. */\nexport function isWebhookOperation<TOperation extends string>(\n event: unknown,\n operation: TOperation,\n): event is WebhookEvent<string, unknown> & { operation: TOperation } {\n return isValidWebhookEvent(event) && event.operation === operation\n}\n\nexport const CUSTOMER_PASSWORD_RESET_OPERATION = 'password-reset' as const\n\nexport type WebhookKnownOperation =\n | CollectionWebhookOperation\n | typeof CUSTOMER_PASSWORD_RESET_OPERATION\n | typeof COMMERCE_NOTIFICATION_OPERATION\n\nexport interface CustomerPasswordResetWebhookData {\n customerId: string | number\n email: string\n name: string\n resetPasswordToken: string\n resetPasswordExpiresAt: string\n}\n\nexport type CustomerPasswordResetWebhookEvent = WebhookEvent<\n 'customers',\n CustomerPasswordResetWebhookData\n> & {\n operation: typeof CUSTOMER_PASSWORD_RESET_OPERATION\n}\n\nexport type CustomerAuthWebhookEvent = CustomerPasswordResetWebhookEvent\n\nexport interface CustomerAuthWebhookHandlers {\n passwordReset?: (\n data: CustomerPasswordResetWebhookData,\n event: CustomerPasswordResetWebhookEvent,\n ) => MaybePromise<void>\n unhandled?: (event: WebhookEvent<string, unknown>) => MaybePromise<void>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction hasString(value: Record<string, unknown>, key: string): boolean {\n return typeof value[key] === 'string'\n}\n\nfunction hasStringOrNumber(\n value: Record<string, unknown>,\n key: string,\n): boolean {\n return typeof value[key] === 'string' || typeof value[key] === 'number'\n}\n\nexport function isCustomerPasswordResetWebhookEvent(\n event: WebhookEvent<string, unknown>,\n): event is CustomerPasswordResetWebhookEvent {\n if (\n event.collection !== 'customers' ||\n event.operation !== CUSTOMER_PASSWORD_RESET_OPERATION ||\n !isRecord(event.data)\n ) {\n return false\n }\n\n return (\n hasStringOrNumber(event.data, 'customerId') &&\n hasString(event.data, 'email') &&\n hasString(event.data, 'name') &&\n hasString(event.data, 'resetPasswordToken') &&\n hasString(event.data, 'resetPasswordExpiresAt')\n )\n}\n\nexport function createCustomerAuthWebhookHandler(\n handlers: CustomerAuthWebhookHandlers,\n): WebhookHandler<string, unknown> {\n return async (event) => {\n if (isCustomerPasswordResetWebhookEvent(event) && handlers.passwordReset) {\n await handlers.passwordReset(event.data, event)\n return\n }\n\n await handlers.unhandled?.(event)\n }\n}\n\nasync function verifySignature(\n payload: string,\n secret: string,\n signature: string,\n timestamp: string,\n deliveryId: string,\n): Promise<boolean> {\n const encoder = new TextEncoder()\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['verify'],\n )\n // Validate and convert hex signature to Uint8Array\n if (signature.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(signature)) {\n return false\n }\n const sigBytes = new Uint8Array(\n (signature.match(/.{2}/g) ?? []).map((byte) => parseInt(byte, 16)),\n )\n // crypto.subtle.verify performs constant-time comparison internally\n return crypto.subtle.verify(\n 'HMAC',\n key,\n sigBytes,\n encoder.encode(`${timestamp}.${deliveryId}.${payload}`),\n )\n}\n\nfunction timestampIsFresh(\n timestamp: string,\n toleranceSeconds: number,\n): boolean {\n if (!/^\\d+$/.test(timestamp)) return false\n const timestampMs = Number(timestamp)\n if (!Number.isFinite(timestampMs)) return false\n const skewMs = Math.abs(Date.now() - timestampMs)\n return skewMs <= toleranceSeconds * 1000\n}\n\nexport async function handleWebhook<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n>(\n request: Request,\n handler: WebhookHandler<T, TData>,\n options?: WebhookOptions,\n): Promise<Response> {\n try {\n const rawBody = await request.text()\n\n if (options?.secret) {\n const signature = request.headers.get('x-webhook-signature') || ''\n const timestamp = request.headers.get('x-webhook-timestamp') || ''\n const deliveryId = request.headers.get('x-webhook-delivery-id') || ''\n const toleranceSeconds = options.toleranceSeconds ?? 300\n const valid =\n Boolean(timestamp && deliveryId) &&\n timestampIsFresh(timestamp, toleranceSeconds) &&\n (await verifySignature(\n rawBody,\n options.secret,\n signature,\n timestamp,\n deliveryId,\n ))\n if (!valid) {\n return new Response(\n JSON.stringify({ error: 'Invalid webhook signature' }),\n { status: 401, headers: { 'Content-Type': 'application/json' } },\n )\n }\n } else {\n console.warn(\n '[@01.software/sdk] Webhook signature verification is disabled. ' +\n 'Set { secret } in handleWebhook() options to enable HMAC-SHA256 verification.',\n )\n }\n\n const body = JSON.parse(rawBody)\n\n if (!isValidWebhookEvent(body)) {\n return new Response(\n JSON.stringify({ error: 'Invalid webhook event format' }),\n { status: 400, headers: { 'Content-Type': 'application/json' } },\n )\n }\n\n await handler(body as WebhookEvent<T, TData>)\n\n return new Response(\n JSON.stringify({ success: true, message: 'Webhook processed' }),\n { status: 200, headers: { 'Content-Type': 'application/json' } },\n )\n } catch (error) {\n console.error('Webhook processing error:', error)\n\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n}\n\nexport function createTypedWebhookHandler<T extends Collection>(\n collection: T,\n handler: (event: WebhookEvent<T>) => Promise<void> | void,\n): WebhookHandler<T> {\n return async (event: WebhookEvent<T>) => {\n if (event.collection !== collection) {\n throw new Error(\n `Expected collection \"${collection}\", got \"${event.collection}\"`,\n )\n }\n return handler(event)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,2BAA2B;AAGjC,IAAM,mCAAmC;AA8DzC,SAAS,oBAAoB,MAAqC;AACvE,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAM;AACZ,SACE,OAAO,IAAI,eAAe,YAC1B,OAAO,IAAI,cAAc,YACzB,IAAI,UAAU,SAAS,KACvB,OAAO,IAAI,SAAS,YACpB,IAAI,SAAS;AAEjB;AAYO,IAAM,kCAAkC;AAExC,IAAM,+BAA+B;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA0FA,SAAS,iBAAiB,OAA0C;AAClE,SAAO,O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EF;AAAA,IACF;AAEA,UAAM,OAAO,KAAK,MAAM,OAAO;AAE/B,QAAI,CAAC,oBAAoB,IAAI,GAAG;AAC9B,aAAO,IAAI;AAAA,QACT,KAAK,UAAU,EAAE,OAAO,+BAA+B,CAAC;AAAA,QACxD,EAAE,QAAQ,KAAK,SAAS,EAAE,gBAAgB,mBAAmB,EAAE;AAAA,MACjE;AAAA,IACF;AAEA,UAAM,QAAQ,IAA8B;AAE5C,WAAO,IAAI;AAAA,MACT,KAAK,UAAU,EAAE,SAAS,MAAM,SAAS,oBAAoB,CAAC;AAAA,MAC9D,EAAE,QAAQ,KAAK,SAAS,EAAE,gBAAgB,mBAAmB,EAAE;AAAA,IACjE;AAAA,EACF,SAAS,OAAO;AACd,YAAQ,MAAM,6BAA6B,KAAK;AAEhD,WAAO,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,wBAAwB,CAAC,GAAG;AAAA,MACtE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAChD,CAAC;AAAA,EACH;AACF;AAEO,SAAS,0BACd,YACA,SACmB;AACnB,SAAO,OAAO,UAA2B;AACvC,QAAI,MAAM,eAAe,YAAY;AACnC,YAAM,IAAI;AAAA,QACR,wBAAwB,UAAU,WAAW,MAAM,UAAU;AAAA,MAC/D;AAAA,IACF;AACA,WAAO,QAAQ,KAAK;AAAA,EACtB;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/webhook.ts","../src/core/webhook/index.ts"],"sourcesContent":["export {\n handleWebhook,\n createTypedWebhookHandler,\n createCommerceEmailWebhookHandler,\n createCommerceNotificationWebhookHandler,\n createCustomerAuthWebhookHandler,\n defineCommerceEmailConfig,\n getCommerceNotificationIdempotencyKey,\n isValidWebhookEvent,\n isCommerceNotificationWebhookEvent,\n isCustomerPasswordResetWebhookEvent,\n isOrderChangedWebhookEvent,\n isWebhookCollection,\n isWebhookOperation,\n CUSTOMER_PASSWORD_RESET_OPERATION,\n COMMERCE_NOTIFICATION_EVENT_TYPE,\n COMMERCE_NOTIFICATION_EVENTS,\n COMMERCE_NOTIFICATION_OPERATION,\n ORDER_CHANGED_EVENT_TYPE,\n} from './core/webhook'\nexport type {\n CollectionWebhookOperation,\n CommerceEmailChannel,\n CommerceEmailConfig,\n CommerceEmailEventConfig,\n CommerceEmailEventHandlers,\n CommerceEmailHandlerContext,\n CommerceNotification,\n CommerceNotificationData,\n CommerceNotificationEventName,\n CommerceNotificationEventHandlers,\n CommerceNotificationHandlerContext,\n CommerceNotificationSource,\n CommerceNotificationSourceCollection,\n CommerceNotificationWebhookEvent,\n CustomerAuthWebhookEvent,\n CustomerAuthWebhookHandlers,\n CustomerPasswordResetWebhookData,\n CustomerPasswordResetWebhookEvent,\n OrderChangedWebhookEvent,\n WebhookChange,\n WebhookCommerceNotificationChange,\n WebhookEvent,\n WebhookHandler,\n WebhookKnownOperation,\n WebhookOperation,\n WebhookOptions,\n WebhookOrderChange,\n WebhookOrderMoved,\n WebhookOrderScope,\n} from './core/webhook'\nexport type {\n WebhookSigningSecretReveal,\n WebhookWithoutSecret,\n} from './webhook-types'\n","import type { Collection } from '../client/types'\nimport type { CollectionType } from '../collection/types'\n\nexport type WebhookOperation = string\n\n/**\n * Semantic event type for manual Admin Panel ordering changes.\n *\n * Order-change webhooks remain `operation: \"update\"` events for compatibility.\n * Do not filter on or emit `operation: \"reorder\"`; use this event type with\n * `isOrderChangedWebhookEvent()` to distinguish ordering from normal content\n * updates.\n */\nexport const ORDER_CHANGED_EVENT_TYPE = 'collection.orderChanged' as const\n\n/** Semantic event type for v1 commerce notification webhooks. */\nexport const COMMERCE_NOTIFICATION_EVENT_TYPE = 'commerce.notification' as const\n\n/** Collection webhook operations emitted for tenant collection writes. */\nexport type CollectionWebhookOperation = 'create' | 'update'\n\n/** Describes the ordered area affected by an order-change webhook. */\nexport type WebhookOrderScope =\n | { kind: 'collection'; collection: string }\n | { kind: 'join'; collection: string; field: string; id: string | number }\n\n/** Identifies the public moved document for the ordered scope. */\nexport type WebhookOrderMoved = {\n collection: string\n id: string | number\n relatedCollection?: string\n relatedId?: string | number\n}\n\n/** Metadata attached to `collection.orderChanged` webhook events. */\nexport type WebhookOrderChange = {\n type: 'order'\n source: 'payload-orderable'\n /**\n * Diagnostic Payload order field name.\n *\n * This may contain hidden implementation field names. Application routing\n * should use `change.scope` and `change.moved` instead.\n */\n orderableFieldName?: string\n previousOrder?: string | null\n nextOrder?: string | null\n scope: WebhookOrderScope\n moved: WebhookOrderMoved\n}\n\n/** Known semantic webhook change metadata. */\nexport type WebhookChange = WebhookOrderChange | WebhookCommerceNotificationChange\n\nexport interface WebhookEvent<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> {\n collection: T\n operation: WebhookOperation\n data: TData\n eventType?: string\n change?: unknown\n timestamp?: string\n deliveryId?: string\n}\n\nexport type WebhookHandler<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> = (event: WebhookEvent<T, TData>) => Promise<void> | void\n\nexport interface WebhookOptions {\n secret?: string\n /** Max accepted skew for signed webhook delivery timestamps. Default: 300s. */\n toleranceSeconds?: number\n}\n\nexport function isValidWebhookEvent(data: unknown): data is WebhookEvent {\n if (typeof data !== 'object' || data === null) return false\n const obj = data as Record<string, unknown>\n return (\n typeof obj.collection === 'string' &&\n typeof obj.operation === 'string' &&\n obj.operation.length > 0 &&\n typeof obj.data === 'object' &&\n obj.data !== null\n )\n}\n\n/** Webhook event emitted when manual Admin Panel ordering changes. */\nexport type OrderChangedWebhookEvent<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> = WebhookEvent<T, TData> & {\n operation: 'update'\n eventType: typeof ORDER_CHANGED_EVENT_TYPE\n change: WebhookOrderChange\n}\n\nexport const COMMERCE_NOTIFICATION_OPERATION = 'notification' as const\n\nexport const COMMERCE_NOTIFICATION_EVENTS = [\n 'orderPaid',\n 'orderCanceled',\n 'fulfillmentShipped',\n 'orderDelivered',\n 'returnRequested',\n 'returnCompleted',\n] as const\n\nexport type CommerceNotificationEventName =\n (typeof COMMERCE_NOTIFICATION_EVENTS)[number]\n\nexport type CommerceNotificationSourceCollection =\n | 'orders'\n | 'fulfillments'\n | 'returns'\n\nexport type CommerceNotificationSource = {\n collection: CommerceNotificationSourceCollection\n id: string | number\n}\n\nexport type CommerceNotificationData = {\n source?: CommerceNotificationSource\n orderId?: string | number\n orderNumber?: string\n status?: string\n totalAmount?: number\n currency?: string\n fulfillmentId?: string | number\n fulfillmentStatus?: string\n shippedAt?: string\n returnId?: string | number\n returnStatus?: string\n refundAmount?: number\n completedAt?: string\n}\n\nexport type CommerceNotification = {\n event: CommerceNotificationEventName\n intentId: string\n dedupeKey: string\n orderId?: string\n fulfillmentId?: string\n returnId?: string\n}\n\nexport type WebhookCommerceNotificationChange = {\n type: 'notification'\n source: 'commerce-notifications'\n event: CommerceNotificationEventName\n sourceCollection: CommerceNotificationSourceCollection\n sourceId: string | number\n}\n\n/** Webhook event emitted for v1 commerce notification deliveries. */\nexport type CommerceNotificationWebhookEvent = WebhookEvent<\n CommerceNotificationSourceCollection,\n CommerceNotificationData\n> & {\n operation: typeof COMMERCE_NOTIFICATION_OPERATION\n eventType: typeof COMMERCE_NOTIFICATION_EVENT_TYPE\n change?: WebhookCommerceNotificationChange\n notification: CommerceNotification\n}\n\nexport type CommerceEmailChannel = 'webhook' | 'provider'\n\nexport type CommerceEmailEventConfig = {\n enabled: boolean\n channel: CommerceEmailChannel\n template?: string\n}\n\nexport type CommerceEmailConfig = {\n version: 1\n commerceNotifications: Partial<\n Record<CommerceNotificationEventName, CommerceEmailEventConfig>\n >\n}\n\nexport type CommerceNotificationHandlerContext = {\n event: CommerceNotificationWebhookEvent\n idempotencyKey: string\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nexport type CommerceNotificationEventHandlers = Partial<\n Record<\n CommerceNotificationEventName,\n (context: CommerceNotificationHandlerContext) => MaybePromise<void>\n >\n> & {\n unhandled?: (event: WebhookEvent<string, unknown>) => MaybePromise<void>\n}\n\nexport type CommerceEmailHandlerContext = CommerceNotificationHandlerContext\n\nexport type CommerceEmailEventHandlers = CommerceNotificationEventHandlers\n\nfunction isStringOrNumber(value: unknown): value is string | number {\n return typeof value === 'string' || typeof value === 'number'\n}\n\nfunction isWebhookOrderScope(value: unknown): value is WebhookOrderScope {\n if (!isRecord(value)) return false\n\n if (value.kind === 'collection') {\n return typeof value.collection === 'string'\n }\n\n if (value.kind === 'join') {\n return (\n typeof value.collection === 'string' &&\n typeof value.field === 'string' &&\n isStringOrNumber(value.id)\n )\n }\n\n return false\n}\n\nfunction isWebhookOrderMoved(value: unknown): value is WebhookOrderMoved {\n if (!isRecord(value)) return false\n\n return (\n typeof value.collection === 'string' &&\n isStringOrNumber(value.id) &&\n (value.relatedCollection === undefined ||\n typeof value.relatedCollection === 'string') &&\n (value.relatedId === undefined || isStringOrNumber(value.relatedId))\n )\n}\n\nfunction hasOptionalOrderValue(\n value: Record<string, unknown>,\n key: string,\n): boolean {\n return (\n value[key] === undefined ||\n value[key] === null ||\n typeof value[key] === 'string'\n )\n}\n\nfunction isWebhookOrderChange(value: unknown): value is WebhookOrderChange {\n if (!isRecord(value)) return false\n\n return (\n value.type === 'order' &&\n value.source === 'payload-orderable' &&\n (value.orderableFieldName === undefined ||\n typeof value.orderableFieldName === 'string') &&\n hasOptionalOrderValue(value, 'previousOrder') &&\n hasOptionalOrderValue(value, 'nextOrder') &&\n isWebhookOrderScope(value.scope) &&\n isWebhookOrderMoved(value.moved)\n )\n}\n\nfunction isCommerceNotificationEventName(\n value: unknown,\n): value is CommerceNotificationEventName {\n return (\n typeof value === 'string' &&\n (COMMERCE_NOTIFICATION_EVENTS as readonly string[]).includes(value)\n )\n}\n\nfunction isCommerceNotificationSourceCollection(\n value: unknown,\n): value is CommerceNotificationSourceCollection {\n return value === 'orders' || value === 'fulfillments' || value === 'returns'\n}\n\nfunction isCommerceNotificationData(\n value: unknown,\n): value is CommerceNotificationData {\n if (!isRecord(value)) return false\n if (\n value.source !== undefined &&\n (!isRecord(value.source) ||\n !isCommerceNotificationSourceCollection(value.source.collection) ||\n !isStringOrNumber(value.source.id))\n ) {\n return false\n }\n\n return (\n (value.orderId === undefined || isStringOrNumber(value.orderId)) &&\n (value.orderNumber === undefined || typeof value.orderNumber === 'string') &&\n (value.status === undefined || typeof value.status === 'string') &&\n (value.totalAmount === undefined || typeof value.totalAmount === 'number') &&\n (value.currency === undefined || typeof value.currency === 'string') &&\n (value.fulfillmentId === undefined ||\n isStringOrNumber(value.fulfillmentId)) &&\n (value.fulfillmentStatus === undefined ||\n typeof value.fulfillmentStatus === 'string') &&\n (value.shippedAt === undefined || typeof value.shippedAt === 'string') &&\n (value.returnId === undefined || isStringOrNumber(value.returnId)) &&\n (value.returnStatus === undefined ||\n typeof value.returnStatus === 'string') &&\n (value.refundAmount === undefined ||\n typeof value.refundAmount === 'number') &&\n (value.completedAt === undefined || typeof value.completedAt === 'string')\n )\n}\n\nfunction isCommerceNotification(\n value: unknown,\n): value is CommerceNotification {\n if (!isRecord(value)) return false\n return (\n isCommerceNotificationEventName(value.event) &&\n typeof value.intentId === 'string' &&\n value.intentId.length > 0 &&\n typeof value.dedupeKey === 'string' &&\n value.dedupeKey.length > 0 &&\n (value.orderId === undefined || typeof value.orderId === 'string') &&\n (value.fulfillmentId === undefined ||\n typeof value.fulfillmentId === 'string') &&\n (value.returnId === undefined || typeof value.returnId === 'string')\n )\n}\n\nfunction isWebhookCommerceNotificationChange(\n value: unknown,\n): value is WebhookCommerceNotificationChange {\n if (!isRecord(value)) return false\n return (\n value.type === 'notification' &&\n value.source === 'commerce-notifications' &&\n isCommerceNotificationEventName(value.event) &&\n isCommerceNotificationSourceCollection(value.sourceCollection) &&\n isStringOrNumber(value.sourceId)\n )\n}\n\nfunction matchesOptionalId(\n actual: string | number | undefined,\n expected: string | number | undefined,\n): boolean {\n return actual === undefined || expected === undefined || actual === expected\n}\n\n/**\n * Returns true for semantic order-change webhooks emitted as update events.\n *\n * Use this guard with `ORDER_CHANGED_EVENT_TYPE` instead of filtering on\n * `operation: \"reorder\"`. Tenant order-change webhooks intentionally keep\n * `operation: \"update\"` for compatibility with existing webhook handlers.\n */\nexport function isOrderChangedWebhookEvent(\n event: unknown,\n): event is OrderChangedWebhookEvent<string, unknown> {\n if (\n !isValidWebhookEvent(event) ||\n event.operation !== 'update' ||\n event.eventType !== ORDER_CHANGED_EVENT_TYPE ||\n !isWebhookOrderChange(event.change)\n ) {\n return false\n }\n\n if (event.collection !== event.change.scope.collection) {\n return false\n }\n\n if (\n event.change.scope.kind === 'collection' &&\n event.change.moved.collection !== event.change.scope.collection\n ) {\n return false\n }\n\n return true\n}\n\n/**\n * Returns true for semantic commerce notification webhooks.\n *\n * Use `notification.intentId` and `notification.dedupeKey` for semantic\n * idempotency. `deliveryId`, when present, identifies a delivery attempt for\n * observability and is not the semantic notification identity.\n */\nexport function isCommerceNotificationWebhookEvent(\n event: unknown,\n): event is CommerceNotificationWebhookEvent {\n if (\n !isValidWebhookEvent(event) ||\n event.operation !== COMMERCE_NOTIFICATION_OPERATION ||\n event.eventType !== COMMERCE_NOTIFICATION_EVENT_TYPE ||\n !isCommerceNotificationData(event.data) ||\n !isCommerceNotification((event as { notification?: unknown }).notification)\n ) {\n return false\n }\n\n const notification = (event as unknown as CommerceNotificationWebhookEvent)\n .notification\n const data = event.data\n const change = event.change\n const sourceCollection = data.source?.collection ?? event.collection\n const sourceId = data.source?.id\n\n if (!isCommerceNotificationSourceCollection(sourceCollection)) return false\n if (data.source !== undefined && event.collection !== data.source.collection) {\n return false\n }\n\n if (change !== undefined) {\n if (!isWebhookCommerceNotificationChange(change)) return false\n if (change.sourceCollection !== sourceCollection) return false\n if (change.event !== notification.event) return false\n if (!matchesOptionalId(change.sourceId, sourceId)) return false\n }\n const changeSourceId = isWebhookCommerceNotificationChange(change)\n ? change.sourceId\n : undefined\n\n if (\n notification.event === 'orderPaid' ||\n notification.event === 'orderCanceled' ||\n notification.event === 'orderDelivered'\n ) {\n return (\n sourceCollection === 'orders' &&\n typeof notification.orderId === 'string' &&\n notification.orderId.length > 0 &&\n matchesOptionalId(data.orderId, sourceId) &&\n matchesOptionalId(notification.orderId, sourceId) &&\n matchesOptionalId(data.orderId, notification.orderId) &&\n matchesOptionalId(changeSourceId, data.orderId ?? notification.orderId)\n )\n }\n\n if (notification.event === 'fulfillmentShipped') {\n return (\n sourceCollection === 'fulfillments' &&\n matchesOptionalId(data.fulfillmentId, sourceId) &&\n typeof notification.fulfillmentId === 'string' &&\n notification.fulfillmentId.length > 0 &&\n matchesOptionalId(notification.fulfillmentId, sourceId) &&\n matchesOptionalId(data.fulfillmentId, notification.fulfillmentId) &&\n matchesOptionalId(changeSourceId, notification.fulfillmentId)\n )\n }\n\n if (\n notification.event === 'returnRequested' ||\n notification.event === 'returnCompleted'\n ) {\n return (\n sourceCollection === 'returns' &&\n matchesOptionalId(data.returnId, sourceId) &&\n typeof notification.returnId === 'string' &&\n notification.returnId.length > 0 &&\n matchesOptionalId(notification.returnId, sourceId) &&\n matchesOptionalId(data.returnId, notification.returnId) &&\n matchesOptionalId(changeSourceId, notification.returnId)\n )\n }\n\n return false\n}\n\nexport function getCommerceNotificationIdempotencyKey(\n event: Pick<CommerceNotificationWebhookEvent, 'notification'>,\n): string {\n return `${event.notification.intentId}:${event.notification.dedupeKey}`\n}\n\nexport function defineCommerceEmailConfig<TConfig extends CommerceEmailConfig>(\n config: TConfig,\n): TConfig {\n return config\n}\n\nexport function createCommerceNotificationWebhookHandler(\n handlers: CommerceNotificationEventHandlers,\n): WebhookHandler<string, unknown> {\n return async (event) => {\n if (!isCommerceNotificationWebhookEvent(event)) {\n await handlers.unhandled?.(event)\n return\n }\n\n const handler = handlers[event.notification.event]\n if (!handler) {\n await handlers.unhandled?.(event)\n return\n }\n\n await handler({\n event,\n idempotencyKey: getCommerceNotificationIdempotencyKey(event),\n })\n }\n}\n\nexport function createCommerceEmailWebhookHandler(\n handlers: CommerceEmailEventHandlers,\n): WebhookHandler<string, unknown> {\n return createCommerceNotificationWebhookHandler(handlers)\n}\n\n/** Narrows a webhook event to a specific collection. */\nexport function isWebhookCollection<TCollection extends string>(\n event: unknown,\n collection: TCollection,\n): event is WebhookEvent<TCollection, unknown> {\n return isValidWebhookEvent(event) && event.collection === collection\n}\n\n/** Narrows a webhook event to a specific operation. */\nexport function isWebhookOperation<TOperation extends string>(\n event: unknown,\n operation: TOperation,\n): event is WebhookEvent<string, unknown> & { operation: TOperation } {\n return isValidWebhookEvent(event) && event.operation === operation\n}\n\nexport const CUSTOMER_PASSWORD_RESET_OPERATION = 'password-reset' as const\n\nexport type WebhookKnownOperation =\n | CollectionWebhookOperation\n | typeof CUSTOMER_PASSWORD_RESET_OPERATION\n | typeof COMMERCE_NOTIFICATION_OPERATION\n\nexport interface CustomerPasswordResetWebhookData {\n customerId: string | number\n email: string\n name: string\n resetPasswordToken: string\n resetPasswordExpiresAt: string\n}\n\nexport type CustomerPasswordResetWebhookEvent = WebhookEvent<\n 'customers',\n CustomerPasswordResetWebhookData\n> & {\n operation: typeof CUSTOMER_PASSWORD_RESET_OPERATION\n}\n\nexport type CustomerAuthWebhookEvent = CustomerPasswordResetWebhookEvent\n\nexport interface CustomerAuthWebhookHandlers {\n passwordReset?: (\n data: CustomerPasswordResetWebhookData,\n event: CustomerPasswordResetWebhookEvent,\n ) => MaybePromise<void>\n unhandled?: (event: WebhookEvent<string, unknown>) => MaybePromise<void>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction hasString(value: Record<string, unknown>, key: string): boolean {\n return typeof value[key] === 'string'\n}\n\nfunction hasStringOrNumber(\n value: Record<string, unknown>,\n key: string,\n): boolean {\n return typeof value[key] === 'string' || typeof value[key] === 'number'\n}\n\nexport function isCustomerPasswordResetWebhookEvent(\n event: WebhookEvent<string, unknown>,\n): event is CustomerPasswordResetWebhookEvent {\n if (\n event.collection !== 'customers' ||\n event.operation !== CUSTOMER_PASSWORD_RESET_OPERATION ||\n !isRecord(event.data)\n ) {\n return false\n }\n\n return (\n hasStringOrNumber(event.data, 'customerId') &&\n hasString(event.data, 'email') &&\n hasString(event.data, 'name') &&\n hasString(event.data, 'resetPasswordToken') &&\n hasString(event.data, 'resetPasswordExpiresAt')\n )\n}\n\nexport function createCustomerAuthWebhookHandler(\n handlers: CustomerAuthWebhookHandlers,\n): WebhookHandler<string, unknown> {\n return async (event) => {\n if (isCustomerPasswordResetWebhookEvent(event) && handlers.passwordReset) {\n await handlers.passwordReset(event.data, event)\n return\n }\n\n await handlers.unhandled?.(event)\n }\n}\n\nasync function verifySignature(\n payload: string,\n secret: string,\n signature: string,\n timestamp: string,\n deliveryId: string,\n): Promise<boolean> {\n const encoder = new TextEncoder()\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['verify'],\n )\n // Validate and convert hex signature to Uint8Array\n if (signature.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(signature)) {\n return false\n }\n const sigBytes = new Uint8Array(\n (signature.match(/.{2}/g) ?? []).map((byte) => parseInt(byte, 16)),\n )\n // crypto.subtle.verify performs constant-time comparison internally\n return crypto.subtle.verify(\n 'HMAC',\n key,\n sigBytes,\n encoder.encode(`${timestamp}.${deliveryId}.${payload}`),\n )\n}\n\nfunction timestampIsFresh(\n timestamp: string,\n toleranceSeconds: number,\n): boolean {\n if (!/^\\d+$/.test(timestamp)) return false\n const timestampMs = Number(timestamp)\n if (!Number.isFinite(timestampMs)) return false\n const skewMs = Math.abs(Date.now() - timestampMs)\n return skewMs <= toleranceSeconds * 1000\n}\n\nexport async function handleWebhook<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n>(\n request: Request,\n handler: WebhookHandler<T, TData>,\n options?: WebhookOptions,\n): Promise<Response> {\n try {\n const rawBody = await request.text()\n\n if (options?.secret) {\n const signature = request.headers.get('x-webhook-signature') || ''\n const timestamp = request.headers.get('x-webhook-timestamp') || ''\n const deliveryId = request.headers.get('x-webhook-delivery-id') || ''\n const toleranceSeconds = options.toleranceSeconds ?? 300\n const valid =\n Boolean(timestamp && deliveryId) &&\n timestampIsFresh(timestamp, toleranceSeconds) &&\n (await verifySignature(\n rawBody,\n options.secret,\n signature,\n timestamp,\n deliveryId,\n ))\n if (!valid) {\n return new Response(\n JSON.stringify({ error: 'Invalid webhook signature' }),\n { status: 401, headers: { 'Content-Type': 'application/json' } },\n )\n }\n } else {\n console.warn(\n '[@01.software/sdk] Webhook signature verification is disabled. ' +\n 'Set { secret } in handleWebhook() options to enable HMAC-SHA256 verification.',\n )\n }\n\n const body = JSON.parse(rawBody)\n\n if (!isValidWebhookEvent(body)) {\n return new Response(\n JSON.stringify({ error: 'Invalid webhook event format' }),\n { status: 400, headers: { 'Content-Type': 'application/json' } },\n )\n }\n\n await handler(body as WebhookEvent<T, TData>)\n\n return new Response(\n JSON.stringify({ success: true, message: 'Webhook processed' }),\n { status: 200, headers: { 'Content-Type': 'application/json' } },\n )\n } catch (error) {\n console.error('Webhook processing error:', error)\n\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n}\n\nexport function createTypedWebhookHandler<T extends Collection>(\n collection: T,\n handler: (event: WebhookEvent<T>) => Promise<void> | void,\n): WebhookHandler<T> {\n return async (event: WebhookEvent<T>) => {\n if (event.collection !== collection) {\n throw new Error(\n `Expected collection \"${collection}\", got \"${event.collection}\"`,\n )\n }\n return handler(event)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,2BAA2B;AAGjC,IAAM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,MAAM,UAAU;AAAA,MAC/D;AAAA,IACF;AACA,WAAO,QAAQ,KAAK;AAAA,EACtB;AACF;","names":[]}
|
package/dist/webhook.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { C as COMMERCE_NOTIFICATION_EVENTS, a as COMMERCE_NOTIFICATION_EVENT_TYPE, b as COMMERCE_NOTIFICATION_OPERATION, c as CUSTOMER_PASSWORD_RESET_OPERATION, d as CollectionWebhookOperation, e as CommerceEmailChannel, f as CommerceEmailConfig, g as CommerceEmailEventConfig, h as CommerceEmailEventHandlers, i as CommerceEmailHandlerContext, j as CommerceNotification, k as CommerceNotificationData, l as
|
|
2
|
-
import { W as Webhook } from './payload-types-
|
|
3
|
-
import './const-
|
|
4
|
-
import './types-
|
|
1
|
+
export { C as COMMERCE_NOTIFICATION_EVENTS, a as COMMERCE_NOTIFICATION_EVENT_TYPE, b as COMMERCE_NOTIFICATION_OPERATION, c as CUSTOMER_PASSWORD_RESET_OPERATION, d as CollectionWebhookOperation, e as CommerceEmailChannel, f as CommerceEmailConfig, g as CommerceEmailEventConfig, h as CommerceEmailEventHandlers, i as CommerceEmailHandlerContext, j as CommerceNotification, k as CommerceNotificationData, l as CommerceNotificationEventHandlers, m as CommerceNotificationEventName, n as CommerceNotificationHandlerContext, o as CommerceNotificationSource, p as CommerceNotificationSourceCollection, q as CommerceNotificationWebhookEvent, r as CustomerAuthWebhookEvent, s as CustomerAuthWebhookHandlers, t as CustomerPasswordResetWebhookData, u as CustomerPasswordResetWebhookEvent, O as ORDER_CHANGED_EVENT_TYPE, v as OrderChangedWebhookEvent, W as WebhookChange, w as WebhookCommerceNotificationChange, x as WebhookEvent, y as WebhookHandler, z as WebhookKnownOperation, A as WebhookOperation, B as WebhookOptions, D as WebhookOrderChange, E as WebhookOrderMoved, F as WebhookOrderScope, G as createCommerceEmailWebhookHandler, H as createCommerceNotificationWebhookHandler, I as createCustomerAuthWebhookHandler, J as createTypedWebhookHandler, K as defineCommerceEmailConfig, L as getCommerceNotificationIdempotencyKey, M as handleWebhook, N as isCommerceNotificationWebhookEvent, P as isCustomerPasswordResetWebhookEvent, Q as isOrderChangedWebhookEvent, R as isValidWebhookEvent, S as isWebhookCollection, T as isWebhookOperation } from './index-DRJs7QIh.cjs';
|
|
2
|
+
import { W as Webhook } from './payload-types-CREOjFNT.cjs';
|
|
3
|
+
import './const-CK_FPaIn.cjs';
|
|
4
|
+
import './types-BkZNhuBh.cjs';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Webhook records returned from ordinary list/find — `secret` is encrypted at
|
package/dist/webhook.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { C as COMMERCE_NOTIFICATION_EVENTS, a as COMMERCE_NOTIFICATION_EVENT_TYPE, b as COMMERCE_NOTIFICATION_OPERATION, c as CUSTOMER_PASSWORD_RESET_OPERATION, d as CollectionWebhookOperation, e as CommerceEmailChannel, f as CommerceEmailConfig, g as CommerceEmailEventConfig, h as CommerceEmailEventHandlers, i as CommerceEmailHandlerContext, j as CommerceNotification, k as CommerceNotificationData, l as
|
|
2
|
-
import { W as Webhook } from './payload-types-
|
|
3
|
-
import './const-
|
|
4
|
-
import './types-
|
|
1
|
+
export { C as COMMERCE_NOTIFICATION_EVENTS, a as COMMERCE_NOTIFICATION_EVENT_TYPE, b as COMMERCE_NOTIFICATION_OPERATION, c as CUSTOMER_PASSWORD_RESET_OPERATION, d as CollectionWebhookOperation, e as CommerceEmailChannel, f as CommerceEmailConfig, g as CommerceEmailEventConfig, h as CommerceEmailEventHandlers, i as CommerceEmailHandlerContext, j as CommerceNotification, k as CommerceNotificationData, l as CommerceNotificationEventHandlers, m as CommerceNotificationEventName, n as CommerceNotificationHandlerContext, o as CommerceNotificationSource, p as CommerceNotificationSourceCollection, q as CommerceNotificationWebhookEvent, r as CustomerAuthWebhookEvent, s as CustomerAuthWebhookHandlers, t as CustomerPasswordResetWebhookData, u as CustomerPasswordResetWebhookEvent, O as ORDER_CHANGED_EVENT_TYPE, v as OrderChangedWebhookEvent, W as WebhookChange, w as WebhookCommerceNotificationChange, x as WebhookEvent, y as WebhookHandler, z as WebhookKnownOperation, A as WebhookOperation, B as WebhookOptions, D as WebhookOrderChange, E as WebhookOrderMoved, F as WebhookOrderScope, G as createCommerceEmailWebhookHandler, H as createCommerceNotificationWebhookHandler, I as createCustomerAuthWebhookHandler, J as createTypedWebhookHandler, K as defineCommerceEmailConfig, L as getCommerceNotificationIdempotencyKey, M as handleWebhook, N as isCommerceNotificationWebhookEvent, P as isCustomerPasswordResetWebhookEvent, Q as isOrderChangedWebhookEvent, R as isValidWebhookEvent, S as isWebhookCollection, T as isWebhookOperation } from './index-DTqoUZk_.js';
|
|
2
|
+
import { W as Webhook } from './payload-types-CREOjFNT.js';
|
|
3
|
+
import './const-Dqz05oaG.js';
|
|
4
|
+
import './types-CxzWHspI.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Webhook records returned from ordinary list/find — `secret` is encrypted at
|
package/dist/webhook.js
CHANGED
|
@@ -112,7 +112,7 @@ function getCommerceNotificationIdempotencyKey(event) {
|
|
|
112
112
|
function defineCommerceEmailConfig(config) {
|
|
113
113
|
return config;
|
|
114
114
|
}
|
|
115
|
-
function
|
|
115
|
+
function createCommerceNotificationWebhookHandler(handlers) {
|
|
116
116
|
return async (event) => {
|
|
117
117
|
if (!isCommerceNotificationWebhookEvent(event)) {
|
|
118
118
|
await handlers.unhandled?.(event);
|
|
@@ -129,6 +129,9 @@ function createCommerceEmailWebhookHandler(handlers) {
|
|
|
129
129
|
});
|
|
130
130
|
};
|
|
131
131
|
}
|
|
132
|
+
function createCommerceEmailWebhookHandler(handlers) {
|
|
133
|
+
return createCommerceNotificationWebhookHandler(handlers);
|
|
134
|
+
}
|
|
132
135
|
function isWebhookCollection(event, collection) {
|
|
133
136
|
return isValidWebhookEvent(event) && event.collection === collection;
|
|
134
137
|
}
|
|
@@ -252,6 +255,7 @@ export {
|
|
|
252
255
|
CUSTOMER_PASSWORD_RESET_OPERATION,
|
|
253
256
|
ORDER_CHANGED_EVENT_TYPE,
|
|
254
257
|
createCommerceEmailWebhookHandler,
|
|
258
|
+
createCommerceNotificationWebhookHandler,
|
|
255
259
|
createCustomerAuthWebhookHandler,
|
|
256
260
|
createTypedWebhookHandler,
|
|
257
261
|
defineCommerceEmailConfig,
|