@pradip1995/segment-primitives 0.4.14 → 0.4.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ import { describe, it } from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import {
4
+ resolveProductImage,
5
+ resolveProductImages,
6
+ type ProductImageSource,
7
+ } from "./resolve-media-url.ts"
8
+
9
+ const PRIMARY_CASES: { name: string; product: ProductImageSource; want: string | null }[] = [
10
+ {
11
+ name: "uses thumbnail when present",
12
+ product: {
13
+ thumbnail: "https://cdn.example/thumb.jpg",
14
+ images: [{ url: "https://cdn.example/gallery.jpg" }],
15
+ },
16
+ want: "https://cdn.example/thumb.jpg",
17
+ },
18
+ {
19
+ name: "falls back to first gallery image when thumbnail is missing",
20
+ product: {
21
+ thumbnail: null,
22
+ images: [
23
+ { url: "https://cdn.example/gallery-1.jpg" },
24
+ { url: "https://cdn.example/gallery-2.jpg" },
25
+ ],
26
+ },
27
+ want: "https://cdn.example/gallery-1.jpg",
28
+ },
29
+ {
30
+ name: "skips empty thumbnail and empty gallery urls",
31
+ product: {
32
+ thumbnail: " ",
33
+ images: [{ url: "" }, { url: "https://cdn.example/gallery.jpg" }],
34
+ },
35
+ want: "https://cdn.example/gallery.jpg",
36
+ },
37
+ {
38
+ name: "falls back to first variant image when product media is missing",
39
+ product: {
40
+ thumbnail: null,
41
+ images: [],
42
+ variants: [
43
+ {
44
+ thumbnail: null,
45
+ images: [{ url: "https://cdn.example/variant.jpg" }],
46
+ },
47
+ ],
48
+ },
49
+ want: "https://cdn.example/variant.jpg",
50
+ },
51
+ {
52
+ name: "returns null when no media exists",
53
+ product: { thumbnail: null, images: [], variants: [] },
54
+ want: null,
55
+ },
56
+ ]
57
+
58
+ const GALLERY_CASES: { name: string; product: ProductImageSource; want: string[] }[] = [
59
+ {
60
+ name: "returns unique gallery urls with thumbnail first",
61
+ product: {
62
+ thumbnail: "https://cdn.example/thumb.jpg",
63
+ images: [
64
+ { url: "https://cdn.example/thumb.jpg" },
65
+ { url: "https://cdn.example/gallery.jpg" },
66
+ ],
67
+ },
68
+ want: ["https://cdn.example/thumb.jpg", "https://cdn.example/gallery.jpg"],
69
+ },
70
+ {
71
+ name: "uses gallery when thumbnail is missing",
72
+ product: {
73
+ images: [
74
+ { url: "https://cdn.example/gallery-1.jpg" },
75
+ { url: "https://cdn.example/gallery-2.jpg" },
76
+ ],
77
+ },
78
+ want: ["https://cdn.example/gallery-1.jpg", "https://cdn.example/gallery-2.jpg"],
79
+ },
80
+ ]
81
+
82
+ describe("resolveProductImage", () => {
83
+ for (const { name, product, want } of PRIMARY_CASES) {
84
+ it(name, () => {
85
+ assert.equal(resolveProductImage(product), want)
86
+ })
87
+ }
88
+ })
89
+
90
+ describe("resolveProductImages", () => {
91
+ for (const { name, product, want } of GALLERY_CASES) {
92
+ it(name, () => {
93
+ assert.deepEqual(resolveProductImages(product), want)
94
+ })
95
+ }
96
+ })
@@ -1,146 +1,202 @@
1
- /** Normalize Medusa / S3 / relative media paths and rewrite stale localhost URLs. */
2
- export function resolveMediaUrl(
3
- url: string | null | undefined
4
- ): string | null {
5
- if (!url || typeof url !== "string") return null
6
-
7
- let trimmed = url.trim()
8
- if (!trimmed) return null
9
-
10
- // Uploads stored while AWS_FILE_URL / backend_url was unset:
11
- // "undefined/uploadsFoo.webp" or "undefined/uploads/Foo.webp"
12
- const rewritten = rewriteBrokenUndefinedUploadUrl(trimmed)
13
- if (!rewritten) return null
14
- trimmed = rewritten
15
-
16
- if (trimmed.startsWith("/")) {
17
- return trimmed
18
- }
19
-
20
- if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
21
- return rewriteStoredBackendUrl(trimmed)
22
- }
23
-
24
- const base = mediaBackendBase()
25
- if (!base) return null
26
-
27
- return `${base.replace(/\/$/, "")}/${trimmed.replace(/^\//, "")}`
28
- }
29
-
30
- function mediaBackendBase(): string | null {
31
- const raw =
32
- process.env.FILE_LOCAL_BACKEND_URL ||
33
- process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL ||
34
- process.env.MEDUSA_BACKEND_URL ||
35
- "http://localhost:9000"
36
-
37
- if (!raw || raw === "undefined") return null
38
- return raw
39
- }
40
-
41
- /** Fix DB values like `undefined/uploadsAnalyze_….webp` from misconfigured file provider. */
42
- function rewriteBrokenUndefinedUploadUrl(url: string): string | null {
43
- if (!url.startsWith("undefined/") && !url.startsWith("undefined")) {
44
- return url
45
- }
46
-
47
- const withoutUndefined = url.replace(/^undefined\/?/, "")
48
- // "uploadsFilename" → "uploads/Filename"; keep "uploads/..." as-is
49
- const withSlash = withoutUndefined.replace(
50
- /^uploads(?!\/)(.+)$/i,
51
- "uploads/$1"
52
- )
53
-
54
- const base = mediaBackendBase()
55
- if (!base) return null
56
-
57
- // Local file provider serves from /static; S3 keys are usually uploads/...
58
- const path = withSlash.startsWith("static/")
59
- ? withSlash
60
- : withSlash.startsWith("uploads/")
61
- ? `static/${withSlash}`
62
- : withSlash
63
-
64
- return `${base.replace(/\/$/, "")}/${path.replace(/^\//, "")}`
65
- }
66
-
67
- function rewriteStoredBackendUrl(url: string): string {
68
- const publicBase =
69
- process.env.FILE_LOCAL_BACKEND_URL ||
70
- process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL
71
-
72
- if (!publicBase) return url
73
-
74
- let parsedPublic: URL
75
- try {
76
- parsedPublic = new URL(publicBase)
77
- } catch {
78
- return url
79
- }
80
-
81
- let parsedStored: URL
82
- try {
83
- parsedStored = new URL(url)
84
- } catch {
85
- return url
86
- }
87
-
88
- const isLocalStoredHost =
89
- parsedStored.hostname === "localhost" ||
90
- parsedStored.hostname === "127.0.0.1" ||
91
- parsedStored.hostname === "backend"
92
-
93
- if (!isLocalStoredHost) return url
94
-
95
- if (
96
- parsedStored.port === parsedPublic.port &&
97
- parsedStored.hostname === parsedPublic.hostname
98
- ) {
99
- return url
100
- }
101
-
102
- return `${parsedPublic.origin}${parsedStored.pathname}${parsedStored.search}${parsedStored.hash}`
103
- }
104
-
105
- type MediaRef = { url?: string | null } | string | null | undefined
106
-
107
- type CartLineImageSource = {
108
- thumbnail?: string | null
109
- product?: {
110
- thumbnail?: string | null
111
- images?: Array<{ url?: string | null }> | null
112
- } | null
113
- variant?: {
114
- thumbnail?: string | null
115
- images?: Array<MediaRef> | null
116
- product?: {
117
- thumbnail?: string | null
118
- images?: Array<{ url?: string | null }> | null
119
- } | null
120
- } | null
121
- }
122
-
123
- function mediaRefUrl(value: MediaRef): string | null {
124
- if (!value) return null
125
- if (typeof value === "string") return value
126
- return value.url ?? null
127
- }
128
-
129
- /** Line-item thumbnail, then variant/product thumbnail, then first gallery image. */
130
- export function resolveCartLineItemImage(item: CartLineImageSource): string | null {
131
- const product = item.product || item.variant?.product || null
132
- const candidates = [
133
- item.thumbnail,
134
- item.variant?.thumbnail,
135
- product?.thumbnail,
136
- mediaRefUrl(item.variant?.images?.[0]),
137
- product?.images?.[0]?.url,
138
- ]
139
-
140
- for (const candidate of candidates) {
141
- const resolved = resolveMediaUrl(candidate)
142
- if (resolved) return resolved
143
- }
144
-
145
- return null
146
- }
1
+ /** Normalize Medusa / S3 / relative media paths and rewrite stale localhost URLs. */
2
+ export function resolveMediaUrl(
3
+ url: string | null | undefined
4
+ ): string | null {
5
+ if (!url || typeof url !== "string") return null
6
+
7
+ let trimmed = url.trim()
8
+ if (!trimmed) return null
9
+
10
+ // Uploads stored while AWS_FILE_URL / backend_url was unset:
11
+ // "undefined/uploadsFoo.webp" or "undefined/uploads/Foo.webp"
12
+ const rewritten = rewriteBrokenUndefinedUploadUrl(trimmed)
13
+ if (!rewritten) return null
14
+ trimmed = rewritten
15
+
16
+ if (trimmed.startsWith("/")) {
17
+ return trimmed
18
+ }
19
+
20
+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
21
+ return rewriteStoredBackendUrl(trimmed)
22
+ }
23
+
24
+ const base = mediaBackendBase()
25
+ if (!base) return null
26
+
27
+ return `${base.replace(/\/$/, "")}/${trimmed.replace(/^\//, "")}`
28
+ }
29
+
30
+ function mediaBackendBase(): string | null {
31
+ const raw =
32
+ process.env.FILE_LOCAL_BACKEND_URL ||
33
+ process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL ||
34
+ process.env.MEDUSA_BACKEND_URL ||
35
+ "http://localhost:9000"
36
+
37
+ if (!raw || raw === "undefined") return null
38
+ return raw
39
+ }
40
+
41
+ /** Fix DB values like `undefined/uploadsAnalyze_….webp` from misconfigured file provider. */
42
+ function rewriteBrokenUndefinedUploadUrl(url: string): string | null {
43
+ if (!url.startsWith("undefined/") && !url.startsWith("undefined")) {
44
+ return url
45
+ }
46
+
47
+ const withoutUndefined = url.replace(/^undefined\/?/, "")
48
+ // "uploadsFilename" → "uploads/Filename"; keep "uploads/..." as-is
49
+ const withSlash = withoutUndefined.replace(
50
+ /^uploads(?!\/)(.+)$/i,
51
+ "uploads/$1"
52
+ )
53
+
54
+ const base = mediaBackendBase()
55
+ if (!base) return null
56
+
57
+ // Local file provider serves from /static; S3 keys are usually uploads/...
58
+ const path = withSlash.startsWith("static/")
59
+ ? withSlash
60
+ : withSlash.startsWith("uploads/")
61
+ ? `static/${withSlash}`
62
+ : withSlash
63
+
64
+ return `${base.replace(/\/$/, "")}/${path.replace(/^\//, "")}`
65
+ }
66
+
67
+ function rewriteStoredBackendUrl(url: string): string {
68
+ const publicBase =
69
+ process.env.FILE_LOCAL_BACKEND_URL ||
70
+ process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL
71
+
72
+ if (!publicBase) return url
73
+
74
+ let parsedPublic: URL
75
+ try {
76
+ parsedPublic = new URL(publicBase)
77
+ } catch {
78
+ return url
79
+ }
80
+
81
+ let parsedStored: URL
82
+ try {
83
+ parsedStored = new URL(url)
84
+ } catch {
85
+ return url
86
+ }
87
+
88
+ const isLocalStoredHost =
89
+ parsedStored.hostname === "localhost" ||
90
+ parsedStored.hostname === "127.0.0.1" ||
91
+ parsedStored.hostname === "backend"
92
+
93
+ if (!isLocalStoredHost) return url
94
+
95
+ if (
96
+ parsedStored.port === parsedPublic.port &&
97
+ parsedStored.hostname === parsedPublic.hostname
98
+ ) {
99
+ return url
100
+ }
101
+
102
+ return `${parsedPublic.origin}${parsedStored.pathname}${parsedStored.search}${parsedStored.hash}`
103
+ }
104
+
105
+ type MediaRef = { url?: string | null } | string | null | undefined
106
+
107
+ export type ProductImageSource = {
108
+ thumbnail?: string | null
109
+ images?: Array<{ url?: string | null }> | null
110
+ variants?: Array<{
111
+ thumbnail?: string | null
112
+ images?: Array<MediaRef> | null
113
+ }> | null
114
+ }
115
+
116
+ type CartLineImageSource = {
117
+ thumbnail?: string | null
118
+ product?: {
119
+ thumbnail?: string | null
120
+ images?: Array<{ url?: string | null }> | null
121
+ } | null
122
+ variant?: {
123
+ thumbnail?: string | null
124
+ images?: Array<MediaRef> | null
125
+ product?: {
126
+ thumbnail?: string | null
127
+ images?: Array<{ url?: string | null }> | null
128
+ } | null
129
+ } | null
130
+ }
131
+
132
+ function mediaRefUrl(value: MediaRef): string | null {
133
+ if (!value) return null
134
+ if (typeof value === "string") return value
135
+ return value.url ?? null
136
+ }
137
+
138
+ /** Line-item thumbnail, then variant/product thumbnail, then first gallery image. */
139
+ export function resolveCartLineItemImage(item: CartLineImageSource): string | null {
140
+ const product = item.product || item.variant?.product || null
141
+ const candidates = [
142
+ item.thumbnail,
143
+ item.variant?.thumbnail,
144
+ product?.thumbnail,
145
+ mediaRefUrl(item.variant?.images?.[0]),
146
+ product?.images?.[0]?.url,
147
+ ]
148
+
149
+ for (const candidate of candidates) {
150
+ const resolved = resolveMediaUrl(candidate)
151
+ if (resolved) return resolved
152
+ }
153
+
154
+ return null
155
+ }
156
+
157
+ function firstResolvedUrl(candidates: Array<string | null | undefined>): string | null {
158
+ for (const candidate of candidates) {
159
+ const resolved = resolveMediaUrl(candidate)
160
+ if (resolved) return resolved
161
+ }
162
+ return null
163
+ }
164
+
165
+ /** Product thumbnail, then first gallery image, then first variant image. */
166
+ export function resolveProductImage(product: ProductImageSource): string | null {
167
+ const variant = product.variants?.[0]
168
+ return firstResolvedUrl([
169
+ product.thumbnail,
170
+ ...(product.images ?? []).map((image) => image.url),
171
+ variant?.thumbnail,
172
+ ...(variant?.images ?? []).map((image) => mediaRefUrl(image)),
173
+ ])
174
+ }
175
+
176
+ /** Unique product media URLs for galleries, starting with the primary image. */
177
+ export function resolveProductImages(product: ProductImageSource): string[] {
178
+ const urls: string[] = []
179
+ const seen = new Set<string>()
180
+ const primary = resolveProductImage(product)
181
+ if (primary) {
182
+ urls.push(primary)
183
+ seen.add(primary)
184
+ }
185
+
186
+ const variantImages =
187
+ product.variants?.flatMap((variant) => variant.images ?? []) ?? []
188
+ const candidates = [
189
+ ...(product.images ?? []).map((image) => image.url),
190
+ ...(product.variants ?? []).map((variant) => variant.thumbnail),
191
+ ...variantImages.map((image) => mediaRefUrl(image)),
192
+ ]
193
+
194
+ for (const candidate of candidates) {
195
+ const resolved = resolveMediaUrl(candidate)
196
+ if (!resolved || seen.has(resolved)) continue
197
+ urls.push(resolved)
198
+ seen.add(resolved)
199
+ }
200
+
201
+ return urls
202
+ }
@@ -1,8 +1,9 @@
1
- "use server"
2
-
3
- import { revalidatePath } from "next/cache"
4
-
5
- export async function revalidateWishlistCache() {
6
- revalidatePath("/", "layout")
7
- revalidatePath("/wishlist")
8
- }
1
+ "use server"
2
+
3
+ import { revalidatePath } from "next/cache"
4
+
5
+ export async function revalidateWishlistCache() {
6
+ revalidatePath("/", "layout")
7
+ revalidatePath("/store")
8
+ revalidatePath("/wishlist")
9
+ }
@@ -1,13 +1,13 @@
1
- /** Shared section layout variants — configure per segment in pages.config / segment props */
2
-
3
- export type HeroVariant = "overlay" | "split" | "centered"
4
- export type TrustStripVariant = "grid" | "bar" | "cards"
5
- export type CategoryGridVariant = "staggered" | "bento" | "tiles"
6
- export type TestimonialsVariant = "grid" | "marquee" | "featured"
7
- export type BenefitsVariant = "grid" | "numbered" | "split"
8
- export type ProductRailVariant = "grid" | "carousel" | "featured"
9
- export type ShopByAgeVariant = "circles" | "cards" | "pills"
10
-
11
- export function resolveVariant<T extends string>(value: T | undefined, fallback: T): T {
12
- return value ?? fallback
13
- }
1
+ /** Shared section layout variants — configure per segment in pages.config / segment props */
2
+
3
+ export type HeroVariant = "overlay" | "split" | "centered"
4
+ export type TrustStripVariant = "grid" | "bar" | "cards"
5
+ export type CategoryGridVariant = "staggered" | "bento" | "tiles"
6
+ export type TestimonialsVariant = "grid" | "marquee" | "featured"
7
+ export type BenefitsVariant = "grid" | "numbered" | "split"
8
+ export type ProductRailVariant = "grid" | "carousel" | "featured"
9
+ export type ShopByAgeVariant = "circles" | "cards" | "pills"
10
+
11
+ export function resolveVariant<T extends string>(value: T | undefined, fallback: T): T {
12
+ return value ?? fallback
13
+ }
@@ -0,0 +1,27 @@
1
+ import assert from "node:assert/strict"
2
+ import { describe, it } from "node:test"
3
+ import { skipImageOptimization } from "./skip-image-optimization"
4
+
5
+ const CASES: Array<{ name: string; src: string | undefined | null; want: boolean }> = [
6
+ { name: "empty string skips optimization", src: "", want: true },
7
+ { name: "whitespace-only skips optimization", src: " ", want: true },
8
+ { name: "null skips optimization", src: null, want: true },
9
+ { name: "undefined skips optimization", src: undefined, want: true },
10
+ { name: "data URL skips optimization", src: "data:image/png;base64,abc", want: true },
11
+ { name: "svg path skips optimization", src: "/icon.svg", want: true },
12
+ { name: "svg with query skips optimization", src: "/logo.svg?v=1", want: true },
13
+ { name: "mp4 skips optimization", src: "https://cdn.example.com/clip.mp4", want: true },
14
+ { name: "webm skips optimization", src: "/hero.webm", want: true },
15
+ { name: "png allows optimization", src: "/images/hero.png", want: false },
16
+ { name: "jpeg allows optimization", src: "/photos/a.jpg", want: false },
17
+ { name: "remote s3 jpeg allows optimization", src: "https://bucket.s3.amazonaws.com/a.jpeg", want: false },
18
+ { name: "webp allows optimization", src: "/images/a.webp", want: false },
19
+ ]
20
+
21
+ describe("skipImageOptimization", () => {
22
+ for (const { name, src, want } of CASES) {
23
+ it(name, () => {
24
+ assert.equal(skipImageOptimization(src), want)
25
+ })
26
+ }
27
+ })
@@ -0,0 +1,11 @@
1
+ /**
2
+ * When true, pass `unoptimized` to next/image (SVG, data URLs, video extensions).
3
+ */
4
+ export function skipImageOptimization(src: string | undefined | null): boolean {
5
+ const trimmed = src?.trim() ?? ""
6
+ if (!trimmed) return true
7
+ if (trimmed.startsWith("data:")) return true
8
+ if (/\.svg(\?|#|$)/i.test(trimmed)) return true
9
+ if (/\.(mp4|webm|ogg)(\?.*)?$/i.test(trimmed)) return true
10
+ return false
11
+ }
@@ -1,32 +1,32 @@
1
- "use client"
2
-
3
- import { useEffect, useRef, useState } from "react"
4
- import {
5
- WISHLIST_UPDATED_EVENT,
6
- nextWishlistCount,
7
- type WishlistUpdatedDetail,
8
- } from "./wishlist-count"
9
-
10
- export function useWishlistCount(serverCount: number) {
11
- const initial = nextWishlistCount(serverCount)
12
- const [count, setCount] = useState(initial)
13
- const lastServerCount = useRef(initial)
14
-
15
- useEffect(() => {
16
- const next = nextWishlistCount(serverCount)
17
- if (next === lastServerCount.current) return
18
- lastServerCount.current = next
19
- setCount(next)
20
- }, [serverCount])
21
-
22
- useEffect(() => {
23
- const onUpdate = (event: Event) => {
24
- const detail = (event as CustomEvent<WishlistUpdatedDetail>).detail
25
- setCount((current) => nextWishlistCount(current, detail))
26
- }
27
- window.addEventListener(WISHLIST_UPDATED_EVENT, onUpdate)
28
- return () => window.removeEventListener(WISHLIST_UPDATED_EVENT, onUpdate)
29
- }, [])
30
-
31
- return count
32
- }
1
+ "use client"
2
+
3
+ import { useEffect, useRef, useState } from "react"
4
+ import {
5
+ WISHLIST_UPDATED_EVENT,
6
+ nextWishlistCount,
7
+ type WishlistUpdatedDetail,
8
+ } from "./wishlist-count"
9
+
10
+ export function useWishlistCount(serverCount: number) {
11
+ const initial = nextWishlistCount(serverCount)
12
+ const [count, setCount] = useState(initial)
13
+ const lastServerCount = useRef(initial)
14
+
15
+ useEffect(() => {
16
+ const next = nextWishlistCount(serverCount)
17
+ if (next === lastServerCount.current) return
18
+ lastServerCount.current = next
19
+ setCount(next)
20
+ }, [serverCount])
21
+
22
+ useEffect(() => {
23
+ const onUpdate = (event: Event) => {
24
+ const detail = (event as CustomEvent<WishlistUpdatedDetail>).detail
25
+ setCount((current) => nextWishlistCount(current, detail))
26
+ }
27
+ window.addEventListener(WISHLIST_UPDATED_EVENT, onUpdate)
28
+ return () => window.removeEventListener(WISHLIST_UPDATED_EVENT, onUpdate)
29
+ }, [])
30
+
31
+ return count
32
+ }