@amboras-dev/storefront-core 2026.11.9-rc.1 → 2026.11.10

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,214 @@
1
+ /**
2
+ * The blog on the storefront (Shopify's Online Store blogs, artifact decision
3
+ * "Blog = core Content, as on Shopify"). Moved into core from the opt-in
4
+ * `@amboras-dev/blog` plugin: the same reads, the same response shapes, so a
5
+ * page written against the plugin reads the same data here.
6
+ *
7
+ * Shopify's paths: `/blogs` (every post), `/blogs/<blog>` (one blog),
8
+ * `/blogs/<blog>/<article>` (one post).
9
+ *
10
+ * Server-side reads of the public store API, cached by Next for `revalidate`
11
+ * seconds (60 by default; the store API caches the routes for 60 s too) and
12
+ * bounded by `STORE_FETCH_TIMEOUT_MS`. A missing blog or post (Medusa's own
13
+ * 404, or a store API without the route) resolves to `null` / an empty list,
14
+ * so the page answers `notFound()`. Anything else (a 5xx, a timeout, no
15
+ * response, a 429 or any other 4xx, a body that is not JSON) throws
16
+ * `StoreBlogUnavailableError` to the page's error boundary instead: an
17
+ * outage must never render, or cache, a 404 for a live post (the product
18
+ * page's rule).
19
+ *
20
+ * Moved posts (content module step 5): when a post's handle or blog changed,
21
+ * the store API answers the OLD path with the post it moved to, carrying the
22
+ * CURRENT handles. `articleRedirectPath` / `blogRedirectPath` compare them
23
+ * with the URL asked for; the page answers 308 (`permanentRedirect`) to the
24
+ * returned path, so a shared or indexed link keeps working and search engines
25
+ * learn the new URL.
26
+ *
27
+ * Article `content` is HTML sanitised by the store API: safe to render.
28
+ * Browser-side twins: `client/use-store-blog`.
29
+ *
30
+ * Inert unless imported: no side effects, nothing registers a route. A store
31
+ * on the Blog plugin (`@amboras-dev/blog`, `components/plugins/blog/*`) never
32
+ * imports it, so a core raise changes nothing there.
33
+ */
34
+ export type BlogStatus = 'active' | 'archived';
35
+ export type ArticleStatus = 'draft' | 'published' | 'archived';
36
+ /** A blog as the store API serves it. */
37
+ export interface Blog {
38
+ id: string;
39
+ title: string;
40
+ handle: string;
41
+ description: string | null;
42
+ status: BlogStatus;
43
+ seo_title?: string | null;
44
+ seo_description?: string | null;
45
+ created_at: string;
46
+ updated_at: string;
47
+ /** Posts in the blog, when the store API sends it. */
48
+ article_count?: number;
49
+ }
50
+ /** A published post as the store API serves it. */
51
+ export interface Article {
52
+ id: string;
53
+ blog_id: string;
54
+ title: string;
55
+ handle: string;
56
+ /** Sanitised HTML (safe to render). */
57
+ content: string | null;
58
+ excerpt: string | null;
59
+ author_name: string | null;
60
+ featured_image_url: string | null;
61
+ tags: string[];
62
+ status: ArticleStatus;
63
+ published_at: string | null;
64
+ seo_title: string | null;
65
+ seo_description: string | null;
66
+ created_at: string;
67
+ updated_at: string;
68
+ }
69
+ /** GET /store/content/blogs */
70
+ export interface BlogsResponse {
71
+ blogs: Blog[];
72
+ count: number;
73
+ }
74
+ /** GET /store/content/blogs/:blog/articles */
75
+ export interface BlogArticlesResponse {
76
+ blog: Blog;
77
+ articles: Article[];
78
+ count: number;
79
+ offset: number;
80
+ limit: number;
81
+ }
82
+ /** GET /store/content/blogs/:blog/articles/:handle */
83
+ export interface ArticleResponse {
84
+ blog: Blog;
85
+ article: Article;
86
+ }
87
+ /** A post with its blog (the `/blogs` index lists posts across blogs). */
88
+ export type ArticleWithBlog = Article & {
89
+ blog: Blog;
90
+ };
91
+ export interface BlogReadOptions {
92
+ /** Seconds Next may serve the cached response (default 60). */
93
+ revalidate?: number;
94
+ }
95
+ /** The store API failed a blog read (5xx, timeout, no response, a 4xx other than 404/410). `reason` is PII-free (`HTTP 503`, `TimeoutError`). */
96
+ export declare class StoreBlogUnavailableError extends Error {
97
+ readonly reason: string;
98
+ constructor(reason: string);
99
+ }
100
+ /** The store API's page cap for a blog's posts. */
101
+ export declare const MAX_ARTICLES_PAGE = 50;
102
+ /** `/blogs/<blog>` (handles are URL-encoded). */
103
+ export declare function blogPath(blogHandle: string): string;
104
+ /** `/blogs/<blog>/<article>` (handles are URL-encoded). */
105
+ export declare function articlePath(blogHandle: string, articleHandle: string): string;
106
+ /** The store's active blogs (empty when there are none, or on a store API without the route). */
107
+ export declare function getBlogs(options?: BlogReadOptions): Promise<BlogsResponse>;
108
+ /** A blog and its published, visible-now posts (newest first), or null when there is no such blog. */
109
+ export declare function getBlogArticles(blogHandle: string, params?: {
110
+ limit?: number;
111
+ offset?: number;
112
+ }, options?: BlogReadOptions): Promise<BlogArticlesResponse | null>;
113
+ /**
114
+ * Every published post across every active blog, newest first, each with its
115
+ * blog (for `/blogs/<blog>/<article>` links). Reads at most
116
+ * `perBlog` (default and cap: 50) posts per blog.
117
+ */
118
+ export declare function getAllArticles(options?: BlogReadOptions & {
119
+ perBlog?: number;
120
+ }): Promise<ArticleWithBlog[]>;
121
+ /**
122
+ * One published post by blog + post handle, or null. A moved post comes back
123
+ * under its CURRENT handles: check `articleRedirectPath` before rendering.
124
+ */
125
+ export declare function getArticle(blogHandle: string, articleHandle: string, options?: BlogReadOptions): Promise<ArticleResponse | null>;
126
+ /**
127
+ * The path to 308 to when the post was found under other handles than the URL
128
+ * asked for (its handle or blog changed, or the URL's case differs), else
129
+ * null. Route params may arrive encoded or not; both compare equal.
130
+ *
131
+ * const data = await getArticle(params.blog, params.article)
132
+ * if (!data) notFound()
133
+ * const moved = articleRedirectPath(params.blog, params.article, data)
134
+ * if (moved) permanentRedirect(moved)
135
+ */
136
+ export declare function articleRedirectPath(blogHandle: string, articleHandle: string, data: ArticleResponse): string | null;
137
+ /** The path to 308 to when the blog was found under another handle than the URL asked for, else null. */
138
+ export declare function blogRedirectPath(blogHandle: string, data: {
139
+ blog: Blog;
140
+ }): string | null;
141
+ /** The blog's Comments setting. */
142
+ export type BlogCommentable = 'no' | 'moderate' | 'yes';
143
+ /** A published comment as the store API serves it (`body` is plain text: render it as text, never as HTML). */
144
+ export interface ArticleComment {
145
+ id: string;
146
+ author: string;
147
+ body: string;
148
+ created_at: string;
149
+ }
150
+ /** GET /store/content/blogs/:blog/articles/:handle/comments */
151
+ export interface ArticleCommentsResponse {
152
+ comments: ArticleComment[];
153
+ count: number;
154
+ limit: number;
155
+ offset: number;
156
+ commentable: BlogCommentable;
157
+ }
158
+ /** What a shopper sends. `website` is the honeypot: keep its input visually hidden and leave it empty. */
159
+ export interface ArticleCommentInput {
160
+ author: string;
161
+ email: string;
162
+ body: string;
163
+ website?: string;
164
+ }
165
+ /** The fields a comment can be rejected on. */
166
+ export type ArticleCommentField = 'author' | 'email' | 'body';
167
+ /**
168
+ * What posting a comment came back with:
169
+ * - `posted`: saved; `status` is `published` (the blog publishes automatically) or `pending` (moderated, or held
170
+ * as spam: the shopper is never told, so show the moderated message for `pending`).
171
+ * - `invalid`: rejected; `errors` holds a message per field the store API named, `message` its summary.
172
+ * - `comments_disabled`: the blog's Comments setting is "Comments are disabled".
173
+ * - `rate_limited`: too many comments from this visitor on this post; try again later.
174
+ * - `not_found`: the post is not (or no longer) published.
175
+ * - `unavailable`: the store API did not answer properly (5xx, no response, any other answer); `reason` is PII-free.
176
+ */
177
+ export type PostArticleCommentResult = {
178
+ kind: 'posted';
179
+ id: string;
180
+ status: 'published' | 'pending';
181
+ } | {
182
+ kind: 'invalid';
183
+ errors: Partial<Record<ArticleCommentField, string>>;
184
+ message: string;
185
+ } | {
186
+ kind: 'comments_disabled';
187
+ } | {
188
+ kind: 'rate_limited';
189
+ } | {
190
+ kind: 'not_found';
191
+ } | {
192
+ kind: 'unavailable';
193
+ reason: string;
194
+ };
195
+ /** The store API's page cap for an article's comments. */
196
+ export declare const MAX_COMMENTS_PAGE = 50;
197
+ /**
198
+ * A page of a published post's PUBLISHED comments, NEWEST FIRST as on Shopify (`limit` up to `MAX_COMMENTS_PAGE`,
199
+ * the total in `count`), with the blog's Comments setting (`commentable`), or null when there is no such post (or
200
+ * the store API predates comments). A moved post is found under its old handles, like `getArticle`. With
201
+ * comments disabled (`commentable: 'no'`) the list is empty: render no comments section at all (Shopify's Dawn).
202
+ * Strict like the other reads: a failed read throws `StoreBlogUnavailableError`.
203
+ */
204
+ export declare function getArticleComments(blogHandle: string, articleHandle: string, params?: {
205
+ limit?: number;
206
+ offset?: number;
207
+ }, options?: BlogReadOptions): Promise<ArticleCommentsResponse | null>;
208
+ /**
209
+ * Post a shopper's comment on a published post (browser or server; uncached). Never throws: every outcome is a
210
+ * `PostArticleCommentResult`. The store API saves a moderated blog's comment as `pending` and an auto-publishing
211
+ * blog's as `published`; a filled `website` honeypot is answered as posted and stored nowhere.
212
+ */
213
+ export declare function postArticleComment(blogHandle: string, articleHandle: string, input: ArticleCommentInput): Promise<PostArticleCommentResult>;
214
+ //# sourceMappingURL=store-blog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-blog.d.ts","sourceRoot":"","sources":["../../src/lib/store-blog.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,UAAU,CAAA;AAC9C,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,WAAW,GAAG,UAAU,CAAA;AAE9D,yCAAyC;AACzC,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,WAAW,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1B,MAAM,EAAE,UAAU,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC/B,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,sDAAsD;IACtD,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED,mDAAmD;AACnD,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAA;IACV,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE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AAE,MAAM,EACrB,MAAM,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,EAChD,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,uBAAuB,GAAG,IAAI,CAAC,CAmBzC;AA0BD;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAiCjJ"}
@@ -0,0 +1,204 @@
1
+ import { safeDecode } from './redirects.js';
2
+ import { medusaBackendUrl, storeGetJsonStrict, storeHeaders } from './store-api.js';
3
+ const DEFAULT_REVALIDATE = 60;
4
+ /** The store API failed a blog read (5xx, timeout, no response, a 4xx other than 404/410). `reason` is PII-free (`HTTP 503`, `TimeoutError`). */
5
+ export class StoreBlogUnavailableError extends Error {
6
+ reason;
7
+ constructor(reason) {
8
+ super(`Blog read failed: ${reason}`);
9
+ this.reason = reason;
10
+ this.name = 'StoreBlogUnavailableError';
11
+ }
12
+ }
13
+ /** ok → the body; Medusa's 404/410 → null; anything else throws, so it never becomes a (cached) 404. */
14
+ async function readBlog(path, revalidate) {
15
+ const result = await storeGetJsonStrict(path, { revalidate });
16
+ if (result.kind === 'ok')
17
+ return result.data;
18
+ if (result.kind === 'miss' && (result.status === 404 || result.status === 410))
19
+ return null;
20
+ throw new StoreBlogUnavailableError(result.kind === 'miss' ? `HTTP ${result.status}` : result.reason);
21
+ }
22
+ /** The store API's page cap for a blog's posts. */
23
+ export const MAX_ARTICLES_PAGE = 50;
24
+ /** `/blogs/<blog>` (handles are URL-encoded). */
25
+ export function blogPath(blogHandle) {
26
+ return `/blogs/${encodeURIComponent(blogHandle)}`;
27
+ }
28
+ /** `/blogs/<blog>/<article>` (handles are URL-encoded). */
29
+ export function articlePath(blogHandle, articleHandle) {
30
+ return `${blogPath(blogHandle)}/${encodeURIComponent(articleHandle)}`;
31
+ }
32
+ /** The store's active blogs (empty when there are none, or on a store API without the route). */
33
+ export async function getBlogs(options = {}) {
34
+ const data = await readBlog('/store/content/blogs', options.revalidate ?? DEFAULT_REVALIDATE);
35
+ return { blogs: data?.blogs ?? [], count: data?.count ?? 0 };
36
+ }
37
+ /** A blog and its published, visible-now posts (newest first), or null when there is no such blog. */
38
+ export async function getBlogArticles(blogHandle, params = {}, options = {}) {
39
+ if (!blogHandle)
40
+ return null;
41
+ const query = new URLSearchParams();
42
+ if (params.limit !== undefined)
43
+ query.set('limit', String(params.limit));
44
+ if (params.offset !== undefined)
45
+ query.set('offset', String(params.offset));
46
+ const qs = query.toString();
47
+ const data = await readBlog(`/store/content/blogs/${encodeURIComponent(safeDecode(blogHandle))}/articles${qs ? `?${qs}` : ''}`, options.revalidate ?? DEFAULT_REVALIDATE);
48
+ return data?.blog ? { ...data, articles: data.articles ?? [] } : null;
49
+ }
50
+ /**
51
+ * Every published post across every active blog, newest first, each with its
52
+ * blog (for `/blogs/<blog>/<article>` links). Reads at most
53
+ * `perBlog` (default and cap: 50) posts per blog.
54
+ */
55
+ export async function getAllArticles(options = {}) {
56
+ const perBlog = Math.min(Math.max(options.perBlog ?? MAX_ARTICLES_PAGE, 1), MAX_ARTICLES_PAGE);
57
+ const { blogs } = await getBlogs(options);
58
+ const lists = await Promise.all(blogs.map(async (blog) => {
59
+ const data = await getBlogArticles(blog.handle, { limit: perBlog }, options);
60
+ return (data?.articles ?? []).map((article) => ({ ...article, blog }));
61
+ }));
62
+ return lists.flat().sort((a, b) => new Date(b.published_at ?? 0).getTime() - new Date(a.published_at ?? 0).getTime());
63
+ }
64
+ /**
65
+ * One published post by blog + post handle, or null. A moved post comes back
66
+ * under its CURRENT handles: check `articleRedirectPath` before rendering.
67
+ */
68
+ export async function getArticle(blogHandle, articleHandle, options = {}) {
69
+ if (!blogHandle || !articleHandle)
70
+ return null;
71
+ const data = await readBlog(`/store/content/blogs/${encodeURIComponent(safeDecode(blogHandle))}/articles/${encodeURIComponent(safeDecode(articleHandle))}`, options.revalidate ?? DEFAULT_REVALIDATE);
72
+ return data?.blog && data.article ? data : null;
73
+ }
74
+ const sameHandle = (asked, current) => asked === current || safeDecode(asked) === current;
75
+ /**
76
+ * The path to 308 to when the post was found under other handles than the URL
77
+ * asked for (its handle or blog changed, or the URL's case differs), else
78
+ * null. Route params may arrive encoded or not; both compare equal.
79
+ *
80
+ * const data = await getArticle(params.blog, params.article)
81
+ * if (!data) notFound()
82
+ * const moved = articleRedirectPath(params.blog, params.article, data)
83
+ * if (moved) permanentRedirect(moved)
84
+ */
85
+ export function articleRedirectPath(blogHandle, articleHandle, data) {
86
+ if (sameHandle(blogHandle, data.blog.handle) && sameHandle(articleHandle, data.article.handle))
87
+ return null;
88
+ return articlePath(data.blog.handle, data.article.handle);
89
+ }
90
+ /** The path to 308 to when the blog was found under another handle than the URL asked for, else null. */
91
+ export function blogRedirectPath(blogHandle, data) {
92
+ return sameHandle(blogHandle, data.blog.handle) ? null : blogPath(data.blog.handle);
93
+ }
94
+ /** The store API's page cap for an article's comments. */
95
+ export const MAX_COMMENTS_PAGE = 50;
96
+ const COMMENT_FIELDS = ['author', 'email', 'body'];
97
+ function commentsPath(blogHandle, articleHandle) {
98
+ return `/store/content/blogs/${encodeURIComponent(safeDecode(blogHandle))}/articles/${encodeURIComponent(safeDecode(articleHandle))}/comments`;
99
+ }
100
+ const isCommentable = (value) => value === 'no' || value === 'moderate' || value === 'yes';
101
+ /**
102
+ * A page of a published post's PUBLISHED comments, NEWEST FIRST as on Shopify (`limit` up to `MAX_COMMENTS_PAGE`,
103
+ * the total in `count`), with the blog's Comments setting (`commentable`), or null when there is no such post (or
104
+ * the store API predates comments). A moved post is found under its old handles, like `getArticle`. With
105
+ * comments disabled (`commentable: 'no'`) the list is empty: render no comments section at all (Shopify's Dawn).
106
+ * Strict like the other reads: a failed read throws `StoreBlogUnavailableError`.
107
+ */
108
+ export async function getArticleComments(blogHandle, articleHandle, params = {}, options = {}) {
109
+ if (!blogHandle || !articleHandle)
110
+ return null;
111
+ const query = new URLSearchParams();
112
+ if (params.limit !== undefined)
113
+ query.set('limit', String(params.limit));
114
+ if (params.offset !== undefined)
115
+ query.set('offset', String(params.offset));
116
+ const qs = query.toString();
117
+ const data = await readBlog(`${commentsPath(blogHandle, articleHandle)}${qs ? `?${qs}` : ''}`, options.revalidate ?? DEFAULT_REVALIDATE);
118
+ if (!data)
119
+ return null;
120
+ const comments = Array.isArray(data.comments) ? data.comments : [];
121
+ return {
122
+ comments,
123
+ count: typeof data.count === 'number' ? data.count : comments.length,
124
+ limit: typeof data.limit === 'number' ? data.limit : comments.length,
125
+ offset: typeof data.offset === 'number' ? data.offset : 0,
126
+ commentable: isCommentable(data.commentable) ? data.commentable : 'no',
127
+ };
128
+ }
129
+ /** Field messages from a 400: `{ errors: { email: '…' } }`, `{ errors: [{ field, message }] }`, or the fields named in `message`. */
130
+ function commentFieldErrors(body, message) {
131
+ const errors = {};
132
+ const raw = body.errors ?? body.fields;
133
+ if (Array.isArray(raw)) {
134
+ for (const item of raw) {
135
+ if (!item || typeof item !== 'object')
136
+ continue;
137
+ const { field, path, message: text } = item;
138
+ const name = typeof field === 'string' ? field : Array.isArray(path) ? path[0] : path;
139
+ if (COMMENT_FIELDS.includes(name) && typeof text === 'string')
140
+ errors[name] ??= text;
141
+ }
142
+ }
143
+ else if (raw && typeof raw === 'object') {
144
+ for (const field of COMMENT_FIELDS) {
145
+ const value = raw[field];
146
+ const text = Array.isArray(value) ? value[0] : value;
147
+ if (typeof text === 'string')
148
+ errors[field] = text;
149
+ }
150
+ }
151
+ if (Object.keys(errors).length === 0) {
152
+ for (const field of COMMENT_FIELDS)
153
+ if (new RegExp(`\\b${field}\\b`, 'i').test(message))
154
+ errors[field] = message;
155
+ }
156
+ return errors;
157
+ }
158
+ /**
159
+ * Post a shopper's comment on a published post (browser or server; uncached). Never throws: every outcome is a
160
+ * `PostArticleCommentResult`. The store API saves a moderated blog's comment as `pending` and an auto-publishing
161
+ * blog's as `published`; a filled `website` honeypot is answered as posted and stored nowhere.
162
+ */
163
+ export async function postArticleComment(blogHandle, articleHandle, input) {
164
+ if (!blogHandle || !articleHandle)
165
+ return { kind: 'not_found' };
166
+ let res;
167
+ try {
168
+ res = await fetch(`${medusaBackendUrl()}${commentsPath(blogHandle, articleHandle)}`, {
169
+ method: 'POST',
170
+ headers: storeHeaders(),
171
+ body: JSON.stringify({ author: input.author, email: input.email, body: input.body, website: input.website ?? '' }),
172
+ cache: 'no-store',
173
+ });
174
+ }
175
+ catch (error) {
176
+ return { kind: 'unavailable', reason: error instanceof Error || error instanceof DOMException ? error.name : 'UnknownError' };
177
+ }
178
+ let body = {};
179
+ try {
180
+ const parsed = await res.json();
181
+ if (parsed && typeof parsed === 'object')
182
+ body = parsed;
183
+ }
184
+ catch {
185
+ body = {};
186
+ }
187
+ if (res.ok) {
188
+ const comment = body.comment;
189
+ const status = comment?.status === 'published' ? 'published' : comment?.status === 'pending' ? 'pending' : null;
190
+ return status ? { kind: 'posted', id: typeof comment?.id === 'string' ? comment.id : '', status } : { kind: 'unavailable', reason: `HTTP ${res.status}` };
191
+ }
192
+ if (res.status === 400) {
193
+ const message = typeof body.message === 'string' ? body.message : '';
194
+ return { kind: 'invalid', errors: commentFieldErrors(body, message), message };
195
+ }
196
+ if (res.status === 403 && body.code === 'comments_disabled')
197
+ return { kind: 'comments_disabled' };
198
+ if (res.status === 429)
199
+ return { kind: 'rate_limited' };
200
+ if (res.status === 404 || res.status === 410)
201
+ return { kind: 'not_found' };
202
+ return { kind: 'unavailable', reason: `HTTP ${res.status}` };
203
+ }
204
+ //# sourceMappingURL=store-blog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-blog.js","sourceRoot":"","sources":["../../src/lib/store-blog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAC3C,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,Y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E,CAAC;QACvB,MAAM,OAAO,GAAG,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAA;QACpE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,kBAAkB,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,CAAA;IAChF,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,IAAI,KAAK,mBAAmB;QAAE,OAAO,EAAE,IAAI,EAAE,mBAAmB,EAAE,CAAA;IACjG,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,CAAA;IACvD,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAA;IAC1E,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,GAAG,CAAC,MAAM,EAAE,EAAE,CAAA;AAC9D,CAAC"}
@@ -0,0 +1,115 @@
1
+ import type { StoreMetaobjectEntry } from './store-metaobjects.js';
2
+ /**
3
+ * Product metafields on the storefront (Shopify `product.metafields`).
4
+ *
5
+ * The store API adds them to a product when asked: `?metafields=ns.key,…` on
6
+ * `GET /store/products(/:id)` returns `product.metafields`, an array in the
7
+ * SAME ORDER as the identifiers (`null` where the product has no value, or the
8
+ * definition is not storefront-visible). A metaobject reference comes WITH the
9
+ * entry — its display name and storefront-visible values — so a product's
10
+ * designer shows without a second request:
11
+ *
12
+ * const [designer] = await getProductMetafields(product.id, ['custom.designer'])
13
+ * const entry = metaobjectOf(designer) // { handle, display_name, values: { name, photo } }
14
+ *
15
+ * FAIL-SOFT: any failure resolves to an array of `null`s of the same length.
16
+ */
17
+ /** A metaobject entry as a reference summary (one level: a reference inside its values is an id). */
18
+ export interface MetaobjectReference extends StoreMetaobjectEntry {
19
+ __typename: 'Metaobject';
20
+ type: string;
21
+ }
22
+ export interface StoreMetafield {
23
+ namespace: string;
24
+ key: string;
25
+ /** The definition's display name, or null. */
26
+ name: string | null;
27
+ /** Definition type; `list.<type>` for lists. */
28
+ type: string;
29
+ /** As Shopify gives it: strings as-is, anything else JSON-stringified (a list is a JSON array string). */
30
+ value: string;
31
+ /** A single reference (product, variant, collection, metaobject, file) resolved to its summary, or null. */
32
+ reference: ({
33
+ __typename: string;
34
+ id?: string;
35
+ } & Record<string, unknown>) | null;
36
+ /** A list reference's resolvable summaries; null for non-list types. */
37
+ references: Array<{
38
+ __typename: string;
39
+ id?: string;
40
+ } & Record<string, unknown>> | null;
41
+ /** rich_text_field only: the rich-text tree in `value`, rendered to escaped HTML. Render this, not `value`. */
42
+ html?: string;
43
+ }
44
+ /** A file a file-reference metafield points at (a Files-library file). */
45
+ export interface StoreFile {
46
+ __typename: 'MediaImage' | 'GenericFile';
47
+ id?: string;
48
+ url: string;
49
+ alt?: string | null;
50
+ mime_type?: string | null;
51
+ width?: number | null;
52
+ height?: number | null;
53
+ size?: number | null;
54
+ }
55
+ /** Shopify's rich-text tree, as a rich-text metafield (and a metaobject's rich-text field) stores it. */
56
+ export type RichTextNode = {
57
+ type: 'root';
58
+ children: RichTextNode[];
59
+ } | {
60
+ type: 'paragraph';
61
+ children: RichTextNode[];
62
+ } | {
63
+ type: 'heading';
64
+ level: number;
65
+ children: RichTextNode[];
66
+ } | {
67
+ type: 'list';
68
+ listType: 'ordered' | 'unordered';
69
+ children: RichTextNode[];
70
+ } | {
71
+ type: 'list-item';
72
+ children: RichTextNode[];
73
+ } | {
74
+ type: 'text';
75
+ value: string;
76
+ bold?: boolean;
77
+ italic?: boolean;
78
+ } | {
79
+ type: 'link';
80
+ url: string;
81
+ title?: string;
82
+ target?: string;
83
+ children: RichTextNode[];
84
+ };
85
+ /** The store API reads at most this many identifiers per request (extra ones are ignored). */
86
+ export declare const MAX_METAFIELD_IDENTIFIERS = 50;
87
+ /**
88
+ * One product's metafields by `namespace.key`, in the order asked. Only the
89
+ * product id is fetched with them (`fields=id`), so this is a light call next
90
+ * to the page's own product read.
91
+ */
92
+ export declare function getProductMetafields(productId: string, identifiers: readonly string[], options?: {
93
+ revalidate?: number;
94
+ }): Promise<Array<StoreMetafield | null>>;
95
+ /** The metafield `namespace.key` from a product's `metafields` array (as the store API returns it), or null. */
96
+ export declare function findMetafield(metafields: ReadonlyArray<StoreMetafield | null> | null | undefined, identifier: string): StoreMetafield | null;
97
+ /** The metaobject entry a single metaobject-reference metafield points at, or null. */
98
+ export declare function metaobjectOf(metafield: StoreMetafield | null | undefined): MetaobjectReference | null;
99
+ /** The metaobject entries a list metaobject-reference metafield points at (unresolvable ones are left out). */
100
+ export declare function metaobjectsOf(metafield: StoreMetafield | null | undefined): MetaobjectReference[];
101
+ /** The file a single file-reference metafield points at (url, alt text, size), or null. */
102
+ export declare function fileOf(metafield: StoreMetafield | null | undefined): StoreFile | null;
103
+ /**
104
+ * HTML of a rich-text tree (a metaobject's rich-text field, or a parsed metafield value): every
105
+ * text escaped, unsafe link schemes dropped — the same rendering the store API's `html` uses.
106
+ */
107
+ export declare function richTextToHtml(node: RichTextNode | null | undefined): string;
108
+ /**
109
+ * The HTML to render for a rich-text metafield: the store API's `html`, else the tree in `value`.
110
+ * Anything else in `value` (an older store API's HTML, a value that never became a tree, a
111
+ * non-rich-text metafield passed by mistake) is shown as ESCAPED text, never as markup: this is
112
+ * the string a page renders with dangerouslySetInnerHTML.
113
+ */
114
+ export declare function metafieldHtml(metafield: StoreMetafield | null | undefined): string;
115
+ //# sourceMappingURL=store-metafields.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-metafields.d.ts","sourceRoot":"","sources":["../../src/lib/store-metafields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAA;AAGlE;;;;;;;;;;;;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