@pradip1995/segment-primitives 0.4.13 → 0.4.15

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.
@@ -1,146 +1,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
- 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
+ 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,8 +1,8 @@
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("/wishlist")
8
+ }
@@ -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
+ }
@@ -1,96 +1,96 @@
1
- import assert from "node:assert/strict"
2
- import { describe, it } from "node:test"
3
- import { nextWishlistCount, type WishlistUpdatedDetail } from "./wishlist-count.ts"
4
-
5
- const CASES: Array<{
6
- name: string
7
- current: number
8
- detail?: WishlistUpdatedDetail | null
9
- want: number
10
- }> = [
11
- {
12
- name: "removing one item decrements the navbar badge",
13
- current: 2,
14
- detail: { delta: -1 },
15
- want: 1,
16
- },
17
- {
18
- name: "removing the last item clears the badge",
19
- current: 1,
20
- detail: { delta: -1 },
21
- want: 0,
22
- },
23
- {
24
- name: "removing from an empty wishlist stays at zero",
25
- current: 0,
26
- detail: { delta: -1 },
27
- want: 0,
28
- },
29
- {
30
- name: "adding an item increments the badge",
31
- current: 0,
32
- detail: { delta: 1 },
33
- want: 1,
34
- },
35
- {
36
- name: "adding onto an existing count increments the badge",
37
- current: 2,
38
- detail: { delta: 1 },
39
- want: 3,
40
- },
41
- {
42
- name: "an explicit count replaces the current badge",
43
- current: 4,
44
- detail: { count: 1 },
45
- want: 1,
46
- },
47
- {
48
- name: "an explicit count wins when delta is also present",
49
- current: 4,
50
- detail: { count: 0, delta: 2 },
51
- want: 0,
52
- },
53
- {
54
- name: "missing detail keeps the current badge",
55
- current: 3,
56
- want: 3,
57
- },
58
- {
59
- name: "null detail keeps the current badge",
60
- current: 3,
61
- detail: null,
62
- want: 3,
63
- },
64
- {
65
- name: "empty detail keeps the current badge",
66
- current: 3,
67
- detail: {},
68
- want: 3,
69
- },
70
- {
71
- name: "non-finite current is treated as zero before applying delta",
72
- current: Number.NaN,
73
- detail: { delta: 2 },
74
- want: 2,
75
- },
76
- {
77
- name: "non-finite delta is ignored",
78
- current: 5,
79
- detail: { delta: Number.NaN },
80
- want: 5,
81
- },
82
- {
83
- name: "fractional values are truncated",
84
- current: 2.9,
85
- detail: { delta: -1.8 },
86
- want: 1,
87
- },
88
- ]
89
-
90
- describe("nextWishlistCount", () => {
91
- for (const row of CASES) {
92
- it(row.name, () => {
93
- assert.equal(nextWishlistCount(row.current, row.detail), row.want)
94
- })
95
- }
96
- })
1
+ import assert from "node:assert/strict"
2
+ import { describe, it } from "node:test"
3
+ import { nextWishlistCount, type WishlistUpdatedDetail } from "./wishlist-count.ts"
4
+
5
+ const CASES: Array<{
6
+ name: string
7
+ current: number
8
+ detail?: WishlistUpdatedDetail | null
9
+ want: number
10
+ }> = [
11
+ {
12
+ name: "removing one item decrements the navbar badge",
13
+ current: 2,
14
+ detail: { delta: -1 },
15
+ want: 1,
16
+ },
17
+ {
18
+ name: "removing the last item clears the badge",
19
+ current: 1,
20
+ detail: { delta: -1 },
21
+ want: 0,
22
+ },
23
+ {
24
+ name: "removing from an empty wishlist stays at zero",
25
+ current: 0,
26
+ detail: { delta: -1 },
27
+ want: 0,
28
+ },
29
+ {
30
+ name: "adding an item increments the badge",
31
+ current: 0,
32
+ detail: { delta: 1 },
33
+ want: 1,
34
+ },
35
+ {
36
+ name: "adding onto an existing count increments the badge",
37
+ current: 2,
38
+ detail: { delta: 1 },
39
+ want: 3,
40
+ },
41
+ {
42
+ name: "an explicit count replaces the current badge",
43
+ current: 4,
44
+ detail: { count: 1 },
45
+ want: 1,
46
+ },
47
+ {
48
+ name: "an explicit count wins when delta is also present",
49
+ current: 4,
50
+ detail: { count: 0, delta: 2 },
51
+ want: 0,
52
+ },
53
+ {
54
+ name: "missing detail keeps the current badge",
55
+ current: 3,
56
+ want: 3,
57
+ },
58
+ {
59
+ name: "null detail keeps the current badge",
60
+ current: 3,
61
+ detail: null,
62
+ want: 3,
63
+ },
64
+ {
65
+ name: "empty detail keeps the current badge",
66
+ current: 3,
67
+ detail: {},
68
+ want: 3,
69
+ },
70
+ {
71
+ name: "non-finite current is treated as zero before applying delta",
72
+ current: Number.NaN,
73
+ detail: { delta: 2 },
74
+ want: 2,
75
+ },
76
+ {
77
+ name: "non-finite delta is ignored",
78
+ current: 5,
79
+ detail: { delta: Number.NaN },
80
+ want: 5,
81
+ },
82
+ {
83
+ name: "fractional values are truncated",
84
+ current: 2.9,
85
+ detail: { delta: -1.8 },
86
+ want: 1,
87
+ },
88
+ ]
89
+
90
+ describe("nextWishlistCount", () => {
91
+ for (const row of CASES) {
92
+ it(row.name, () => {
93
+ assert.equal(nextWishlistCount(row.current, row.detail), row.want)
94
+ })
95
+ }
96
+ })