@ecomcx/ecomweb-theme-sdk 1.43.0 → 2.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ Theo [SemVer](https://semver.org/lang/vi/): bản lớn (x.0.0) mới được đổi hoặc bỏ API công khai. Tên công khai là tên có trong [API.md](API.md).
4
+
5
+ ## 2.0.0 (16/11/2026)
6
+
7
+ ### Phá tương thích, cần làm khi nâng cấp
8
+ - **Entry chính chỉ chạy ở server.** `@ecomcx/ecomweb-theme-sdk` có `import "server-only"`: file `"use client"` import giá trị từ entry chính thì Next báo lỗi lúc build. Sửa: import từ `@ecomcx/ecomweb-theme-sdk/client` (`Link`, form đăng nhập, `CommentForm`…). `import type` vẫn dùng được ở mọi nơi. `create-ecomweb validate` báo lỗi này khi đóng gói.
9
+ - **Tên nội bộ của core rời entry chính, chỉ còn ở `/runtime`:** `getActiveTheme`, `getActiveExtensions`, `getSlotItems`, `getSlotComponents`, `findShortcode`, `findWidget`, `findBlock`, `findRoute`, `findRegion`, `resolvePath`, `getPreview`, `getTemplates`, `getAccessToken`, `cmsApi`, `varyHeader`, `UNLOCK_COOKIE`, `UNLOCK_HEADER`, `TEMPLATE_DRAFT_COOKIE`. `ACCESS_COOKIE`, `REFRESH_COOKIE` chỉ còn ở `/auth-shared`. Theme dùng `<Slot>`, `getCurrentUser()`, `pluginFetch(..., { asUser: true })` thay thế.
10
+ - **`getPost`, `getPostById`, `getPattern`, `getMenu`, `getMenuById` chỉ trả `null` khi 404.** Lỗi khác (mạng, 5xx) ném `CmsApiError`. Trước đây `getPost` trả `null` cho mọi lỗi nên trang hiện 404 sai khi CMS lỗi. Nơi dùng kết quả cho phần phụ (link chân trang…) nên tự `.catch(() => null)`.
11
+ - **`PostDate` là Server Component async**, không truyền `site` thì tự đọc cấu hình ngày của website.
12
+ - **Peer dependency có cận trên:** `next >=16 <17`, `react >=19 <20`, `next-fetch-kit >=0.5.0 <1`.
13
+
14
+ ### Đã cũ (vẫn chạy, cảnh báo một lần ở môi trường dev, bỏ ở 3.0)
15
+ - `getTerms(taxonomy, hideEmpty, locale)` → `getTerms({ taxonomy, hideEmpty, locale })`.
16
+ - `getComments(postId, page, unlock, opts)` → `getComments(postId, { page, unlock, perPage, order })`.
17
+
18
+ ### Thêm
19
+ - `getPosts`: `offset`, `noTotal`, `orderBy: "include"`, `parentIn`, `parentNotIn`.
20
+ - `getPostIds(query)`, `getAdjacentPost(post, "prev" | "next", query?)`.
21
+ - Conditional tags: `isFrontPage`, `isHome`, `isSingle`, `isPage`, `isSingular`, `isCategory`, `isTag`, `isTax`, `isAuthor`, `isDate`, `isArchive`, `isSearch`, `is404`.
22
+ - Kiểu `CommentQuery`.
23
+ - `<Menu>`, `<WidgetArea>`, `<Comments>`: CMS lỗi thì ghi log và bỏ phần đó, trang vẫn hiện.
24
+ - JSDoc cho mọi tên công khai; [API.md](API.md) sinh từ mã nguồn (CI kiểm tra khớp).
25
+ - `cmsFetch` được công bố là lối thoát có cam kết khi SDK chưa có hàm riêng.
26
+
27
+ ### Hướng dẫn nâng cấp từ 1.x
28
+ 1. `npx @ecomcx/create-ecomweb validate`: sửa mọi lỗi "component client import … từ @ecomcx/ecomweb-theme-sdk" bằng cách đổi sang `/client`.
29
+ 2. Tìm `getActiveTheme`, `findBlock`, `resolvePath`, `ACCESS_COOKIE`… trong theme / plugin: thay bằng API công khai tương ứng (nếu thật sự cần thì import từ `/runtime`, không có cam kết).
30
+ 3. Nơi gọi `getPost` / `getPostById` / `getMenu` để lấy phần phụ của trang: thêm `.catch(() => null)` nếu muốn giữ cách cũ (lỗi = không có).
31
+ 4. Chạy dev, đọc cảnh báo `[ecomweb-theme-sdk] … đã cũ` và đổi sang dạng object.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ecomcx JSC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # @ecomcx/ecomweb-theme-sdk
2
+
3
+ SDK để viết theme và phần website của plugin cho Ecomweb CMS: React Server Components trên Next.js.
4
+
5
+ Hướng dẫn đầy đủ nằm trong repo core: `docs/theme-guide.md` (theme, kèm bảng tương đương hàm WordPress), `docs/plugin-guide.md` (phần Frontend của plugin) và `docs/query-engine.md` (tham số của `getPosts`).
6
+
7
+ ## Entry
8
+
9
+ | Import | Chạy ở | Dùng cho |
10
+ |---|---|---|
11
+ | `@ecomcx/ecomweb-theme-sdk` | chỉ server (`server-only`) | dữ liệu (`getPosts`, `getSite`…), component server (`PostContent`, `Menu`…), `definePlugin`, conditional tags |
12
+ | `@ecomcx/ecomweb-theme-sdk/client` | trình duyệt (`"use client"`) | `Link`, form đăng nhập / bình luận, `pluginClient`, `emit` / `on`, `useT`, `setPreference` |
13
+ | `@ecomcx/ecomweb-theme-sdk/runtime` | chỉ server (core) | nạp theme / plugin, dựng trang theo URL, xem trước: dành cho core, không có cam kết |
14
+ | `@ecomcx/ecomweb-theme-sdk/auth-shared` | cả hai (core) | hằng và kiểu dùng chung cho proxy đăng nhập |
15
+
16
+ File `"use client"` chỉ import giá trị từ `/client`; import nhầm entry chính thì Next báo lỗi lúc build. `import type` từ entry chính dùng được ở mọi nơi.
17
+
18
+ Tham chiếu đầy đủ từng tên (chữ ký, mô tả, ví dụ): [API.md](API.md), sinh từ mã nguồn.
19
+
20
+ ## Quy tắc đặt tên
21
+
22
+ | Dạng | Nghĩa | Ví dụ |
23
+ |---|---|---|
24
+ | `get*` | lấy dữ liệu từ CMS, async, có cache | `getPosts`, `getSite`, `getAdjacentPost` |
25
+ | `format*` | biến đổi giá trị, không gọi mạng | `formatDate`, `formatMessage` |
26
+ | `is*` / `has*` | trả về boolean | `isArchive`, `hasPlugin` |
27
+ | `require*` | chặn, chuyển hướng nếu không đạt | `requireUser` |
28
+ | `define*` | khai báo | `definePlugin`, `defineBlock` |
29
+ | `use*` | React hook (client) | `useCurrentUser`, `useT` |
30
+ | `PascalCase` | component | `PostDate`, `Menu` |
31
+ | `CONSTANT_CASE` | hằng | `CONSENT_CATEGORIES` |
32
+
33
+ ## Cách báo lỗi
34
+
35
+ | Loại | Không tìm thấy | CMS lỗi (mạng, 5xx) |
36
+ |---|---|---|
37
+ | Hàm lấy một mục: `getPost`, `getPostById`, `getPattern`, `getMenu`, `getMenuById`, `getPlugin` | `null` | ném `CmsApiError` (`status` = mã HTTP, 0 = lỗi mạng) |
38
+ | Hàm lấy danh sách: `getPosts`, `getTerms`, `queryTerms`, `getComments`, `getWidgets`… | danh sách rỗng | ném `CmsApiError` |
39
+ | `getCurrentUser` | `null` (khách) | `null` |
40
+ | Component phần phụ: `<Menu>`, `<WidgetArea>`, `<Comments>`, `<Slot>` | vẽ `fallback` / không vẽ | ghi `console.error`, bỏ phần đó, trang vẫn hiện |
41
+ | Plugin, filter, action lỗi | — | ghi log, bỏ qua plugin đó |
42
+
43
+ Template gặp lỗi không bắt thì Next hiện trang lỗi (`error.tsx`), không hiện 404 sai. Lỗi mạng ngắn (502 / 503 / 504) được thử lại một lần trước khi ném.
44
+
45
+ ## Độ ổn định
46
+
47
+ - Tên công khai theo SemVer: đổi hoặc bỏ chỉ ở bản lớn. Baseline nằm ở `api/theme-sdk.txt` của core, CI so sánh mỗi lần phát hành.
48
+ - Tên có `@internal` trong JSDoc là của core, có thể đổi mà không báo trước.
49
+ - Tên có `@deprecated` vẫn chạy tới bản lớn kế tiếp; JSDoc ghi tên thay thế.
50
+ - `@since x.y.z` = phiên bản SDK có tên đó.
51
+
52
+ Lịch sử thay đổi: [CHANGELOG.md](CHANGELOG.md).
package/dist/api.d.ts CHANGED
@@ -10,6 +10,7 @@ export declare const cmsApi: import("next-fetch-kit").FetchKitInstance;
10
10
  * asUser: gửi kèm phiên của người đang xem (endpoint nhận ICurrentUser) — luôn không cache: pluginFetch("shop", "/cart", { asUser: true }).
11
11
  */
12
12
  export declare function pluginFetch<T>(slug: string, path: string, opts?: FetchOptions): Promise<T>;
13
+ /** Lỗi khi gọi Public API của CMS. `status` = mã HTTP (0 = lỗi mạng / hết thời gian chờ). */
13
14
  export declare class CmsApiError extends Error {
14
15
  status: number;
15
16
  constructor(status: number, message: string);
@@ -28,17 +29,20 @@ export interface FetchOptions {
28
29
  */
29
30
  vary?: Record<string, string>;
30
31
  }
31
- /** Header X-CMS-Vary từ `vary` ("device=mobile,flag:ab=b"); rỗng → không gửi. */
32
+ /** @internal Header X-CMS-Vary từ `vary` ("device=mobile,flag:ab=b"); rỗng → không gửi. */
32
33
  export declare function varyHeader(vary?: Record<string, string>): Record<string, string>;
33
- /** Gọi Public API của CMS. Kết quả được cache và gắn tag "cms" để revalidate khi nội dung thay đổi. */
34
+ /**
35
+ * Gọi thẳng một endpoint của Public API (`/api/public/...`) khi SDK chưa có hàm riêng — lối thoát có cam kết cho theme / plugin.
36
+ * Ưu tiên các hàm `get*`. Lỗi → ném `CmsApiError` (`status` = mã HTTP). Kết quả được cache và gắn tag "cms" để revalidate khi nội dung thay đổi. */
34
37
  export declare function cmsFetch<T>(path: string, opts?: FetchOptions): Promise<T>;
35
38
  /** Thông tin site theo ngôn ngữ của request (hoặc locale truyền vào). */
36
39
  export declare const getSite: (locale?: string) => Promise<Site>;
37
40
  /** Cookie (httpOnly) giữ token mở khoá bài có mật khẩu: "12:token,34:token". */
38
41
  export declare const UNLOCK_COOKIE = "cms-unlock";
39
42
  export declare const UNLOCK_HEADER = "X-CMS-Unlock";
40
- /** unlock: giá trị cookie cms-unlock — có thì không dùng cache (nội dung riêng của người đã nhập mật khẩu). */
43
+ /** @internal Core dùng để dựng trang theo URL. unlock: giá trị cookie cms-unlock — có thì không dùng cache (nội dung riêng của người đã nhập mật khẩu). */
41
44
  export declare const resolvePath: (path: string, query?: Record<string, string | string[] | undefined>, noStore?: boolean, unlock?: string) => Promise<ResolveResult>;
45
+ /** @internal Dữ liệu trang xem trước theo token (core dùng cho Draft Mode). */
42
46
  export declare const getPreview: (token: string) => Promise<ResolveResult>;
43
47
  /** Một điều kiện lọc theo taxonomy: bài phải khớp (hoặc không khớp) các term này. */
44
48
  export interface TaxQueryClause {
@@ -90,17 +94,24 @@ export interface PostQuery {
90
94
  include?: number[];
91
95
  exclude?: number[];
92
96
  parentId?: number;
97
+ /** Bài con của một trong các id này / không thuộc các id này (post_parent__in / __not_in). */
98
+ parentIn?: number[];
99
+ parentNotIn?: number[];
100
+ /** Bỏ qua N bài đầu trước khi phân trang (cộng với (page-1)*perPage) — vd 5 bài nổi bật rồi mới phân trang. */
101
+ offset?: number;
102
+ /** true = không đếm tổng (nhanh hơn): `total` = số bài trả về, `totalPages` = page. Cho Tin liên quan, slider, top N. */
103
+ noTotal?: boolean;
93
104
  /** true = chỉ bài ghim, false = bỏ bài ghim. */
94
105
  sticky?: boolean;
95
106
  /** Kèm nội dung đầy đủ (post.content). Mặc định không — danh sách chỉ cần tiêu đề, sapo, ảnh, giúp trang nhẹ và nhanh. */
96
107
  withContent?: boolean;
97
108
  /**
98
- * `relevance` = theo độ khớp với `search` (trang tìm kiếm dùng mặc định); `rand` = ngẫu nhiên (kết quả vẫn được
109
+ * `include` = đúng thứ tự mảng `include`; `relevance` = theo độ khớp với `search` (trang tìm kiếm dùng mặc định); `rand` = ngẫu nhiên (kết quả vẫn được
99
110
  * cache, đổi khi cache hết hạn hoặc nội dung đổi).
100
111
  */
101
112
  page?: number;
102
113
  perPage?: number;
103
- orderBy?: "date" | "title" | "modified" | "menu_order" | "comment_count" | "id" | "slug" | "rand" | "relevance";
114
+ orderBy?: "date" | "title" | "modified" | "menu_order" | "comment_count" | "id" | "slug" | "rand" | "include" | "relevance";
104
115
  order?: "asc" | "desc";
105
116
  /** Ngày đăng từ (gồm cả mốc), ISO-8601 hoặc Date — vd sự kiện / tin tức từ đầu năm học. */
106
117
  after?: string | Date;
@@ -115,12 +126,35 @@ export interface PostQuery {
115
126
  */
116
127
  orderByMeta?: string;
117
128
  }
129
+ /**
130
+ * Danh sách bài đã đăng theo điều kiện (tương đương `WP_Query`). Mặc định không kèm nội dung đầy đủ (`withContent`).
131
+ * Trả `{ items, total, page, totalPages }`; `noTotal: true` bỏ bước đếm tổng.
132
+ * @example const { items } = await getPosts({ type: "post", taxQuery: [{ taxonomy: "category", terms: ["tin-tuc"] }], perPage: 6 });
133
+ * @see docs/query-engine.md
134
+ */
118
135
  export declare const getPosts: ({ withContent, ...q }?: PostQuery) => Promise<{
119
136
  items: Post[];
120
137
  total: number;
121
138
  page: number;
122
139
  totalPages: number;
123
140
  }>;
141
+ /**
142
+ * Bài liền trước (`"prev"`, đăng sớm hơn) hoặc liền sau (`"next"`) cùng loại nội dung (tương đương `get_adjacent_post`).
143
+ * `query` lọc thêm, vd cùng chuyên mục: `{ taxQuery: [{ taxonomy: "category", terms: [slug] }] }`. Không có → `null`.
144
+ * @since 1.44.0
145
+ * @example const [prev, next] = await Promise.all([getAdjacentPost(post, "prev"), getAdjacentPost(post, "next")]);
146
+ */
147
+ export declare function getAdjacentPost(post: Pick<Post, "id" | "type" | "publishedAt">, direction: "prev" | "next", query?: Omit<PostQuery, "after" | "before" | "orderBy" | "order" | "perPage" | "page" | "offset">): Promise<Post | null>;
148
+ /**
149
+ * Chỉ lấy id bài (tương đương `WP_Query` với `fields => 'ids'`): cùng điều kiện như {@link getPosts}, máy chủ không dựng đối tượng bài.
150
+ * @since 1.44.0
151
+ */
152
+ export declare const getPostIds: ({ withContent: _w, ...q }?: PostQuery) => Promise<{
153
+ items: number[];
154
+ total: number;
155
+ page: number;
156
+ totalPages: number;
157
+ }>;
124
158
  /** Một trang của danh sách công khai (term, tác giả, media). */
125
159
  export interface ListPage<T> {
126
160
  items: T[];
@@ -210,39 +244,77 @@ export interface MediaQuery {
210
244
  }
211
245
  /** Danh sách media (thư viện ảnh, tài liệu tải về) — plugin giới hạn / mở rộng qua filter media.query. */
212
246
  export declare const getMedia: ({ params, ...q }?: MediaQuery) => Promise<ListPage<Media>>;
247
+ /**
248
+ * Bài đã đăng theo loại nội dung + slug, ngôn ngữ của request hiện tại (tương đương `get_page_by_path`).
249
+ * Không có / chưa đăng → `null`. CMS lỗi → ném `CmsApiError`.
250
+ * @example const about = await getPost("page", "gioi-thieu");
251
+ */
213
252
  export declare const getPost: (type: string, slug: string, locale?: string) => Promise<Post | null>;
214
- /** Bài đã đăng theo id (core ≥ 1.20.0 có hàm này; endpoint có từ trước). Không có / chưa đăng → null. */
253
+ /**
254
+ * Bài đã đăng theo id (tương đương `get_post($id)`). Không có / chưa đăng → `null`. CMS lỗi → ném `CmsApiError`.
255
+ * @since 1.31.0
256
+ */
215
257
  export declare const getPostById: (id: number) => Promise<Post | null>;
216
- export declare const getTerms: (taxonomy: string, hideEmpty?: boolean, locale?: string) => Promise<Term[]>;
217
- /** Cookie giữ token bản nháp của Trình dựng (website đang ở chế độ xem trước). */
258
+ /**
259
+ * Mọi term của một phân loại (không phân trang), ngôn ngữ của request (tương đương `get_terms`).
260
+ * `hideEmpty` mặc định `true` = bỏ term chưa có bài. Cần lọc / phân trang / sắp xếp → {@link queryTerms}.
261
+ * @example const cats = await getTerms({ taxonomy: "category" });
262
+ */
263
+ export declare function getTerms(query: {
264
+ taxonomy: string;
265
+ hideEmpty?: boolean;
266
+ locale?: string;
267
+ }): Promise<Term[]>;
268
+ /** @deprecated Từ 2.0: dùng `getTerms({ taxonomy, hideEmpty, locale })`. Dạng tham số vị trí bị bỏ ở 3.0. */
269
+ export declare function getTerms(taxonomy: string, hideEmpty?: boolean, locale?: string): Promise<Term[]>;
270
+ /** @internal Cookie giữ token bản nháp của Trình dựng (website đang ở chế độ xem trước). */
218
271
  export declare const TEMPLATE_DRAFT_COOKIE = "cms-template-draft";
219
- /** Template / phần dựng bằng khối của theme đang dùng (bản sửa trong Trình dựng thắng bản của theme; đang xem trước → bản nháp). */
272
+ /** @internal Template / phần dựng bằng khối của theme đang dùng (bản sửa trong Trình dựng thắng bản của theme; đang xem trước → bản nháp). */
220
273
  export declare const getTemplates: () => Promise<{
221
274
  theme: string;
222
275
  templates: Record<string, PostContentDoc>;
223
276
  parts: Record<string, PostContentDoc>;
224
277
  }>;
225
- /** Nội dung mẫu đồng bộ (khối syncedPattern). null = mẫu đã xoá / chưa xuất bản. */
278
+ /** Nội dung mẫu đồng bộ (khối syncedPattern). Mẫu đã xoá / chưa xuất bản → `null`; CMS lỗi → ném `CmsApiError`. */
226
279
  export declare const getPattern: (id: number) => Promise<PostContentDoc | null>;
280
+ /**
281
+ * Menu gắn ở một vị trí của theme (`theme.json › menuLocations`), ngôn ngữ của request (tương đương `wp_get_nav_menu_items` theo location).
282
+ * Chưa gắn menu → `null`. Vẽ sẵn: `<Menu location="primary" />`.
283
+ */
227
284
  export declare const getMenu: (location: string, locale?: string) => Promise<Menu | null>;
285
+ /** Menu theo id (khối Điều hướng chọn menu cụ thể). Không có → `null`. */
228
286
  export declare const getMenuById: (id: number) => Promise<Menu | null>;
287
+ /** Widget trong một khu vực (`theme.json › widgetAreas`), theo thứ tự. Vẽ sẵn: `<WidgetArea id="sidebar" />`. */
229
288
  export declare const getWidgets: (area: string, locale?: string) => Promise<WidgetInstance[]>;
289
+ /** Tham số của {@link getComments}. Bỏ trống = theo Cài đặt › Thảo luận. */
290
+ export interface CommentQuery {
291
+ page?: number;
292
+ perPage?: number;
293
+ order?: "asc" | "desc";
294
+ /** Bài có mật khẩu: token mở khoá (giá trị cookie, xem {@link requestUnlock}). Có thì không cache. */
295
+ unlock?: string;
296
+ }
230
297
  /**
231
- * Bình luận đã duyệt theo trang (số mỗi trang, thứ tự: Cài đặt › Thảo luận).
232
- * Bài có mật khẩu (core >= 1.15): CMS chỉ trả bình luận khi có token mở khoá — unlock = giá trị cookie cms-unlock (không cache).
298
+ * Bình luận đã duyệt của một bài, theo trang → `{ items, total, count, page, totalPages }` (tương đương `get_comments`).
299
+ * Bài có mật khẩu: CMS chỉ trả bình luận khi có `unlock`.
300
+ * @example const { items } = await getComments(post.id, { page: 2 });
233
301
  */
234
- export declare const getComments: (postId: number, page?: number, unlock?: string, opts?: {
302
+ export declare function getComments(postId: number, query?: CommentQuery): Promise<CommentPage>;
303
+ /** @deprecated Từ 2.0: dùng `getComments(postId, { page, unlock, perPage, order })`. Dạng tham số vị trí bị bỏ ở 3.0. */
304
+ export declare function getComments(postId: number, page: number, unlock?: string, opts?: {
235
305
  perPage?: number;
236
306
  order?: "asc" | "desc";
237
- }) => Promise<CommentPage>;
307
+ }): Promise<CommentPage>;
238
308
  /** Cookie mở khoá bài có mật khẩu của request hiện tại (server component); ngoài request → undefined. */
239
309
  export declare function requestUnlock(): Promise<string | undefined>;
310
+ /** Số bài theo tháng, mới nhất trước, kèm link trang lưu trữ (tương đương `wp_get_archives`). */
240
311
  export declare const getArchives: (locale?: string) => Promise<{
241
312
  year: number;
242
313
  month: number;
243
314
  count: number;
244
315
  link: string;
245
316
  }[]>;
317
+ /** Ngôn ngữ đang bật của website và ngôn ngữ mặc định. */
246
318
  export declare const getLanguages: () => Promise<{
247
319
  defaultLocale: string;
248
320
  languages: Array<{
package/dist/api.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createFetchKit, isFetchKitError } from "next-fetch-kit";
2
2
  import { getRequestLocale } from "./locale.js";
3
+ import { deprecated } from "./utils.js";
3
4
  /**
4
5
  * Client gọi Public API của CMS (dùng next-fetch-kit: chạy được cả SSR lẫn CSR,
5
6
  * tự gộp request trùng trong cùng một lần render, timeout + retry khi lỗi mạng).
@@ -45,6 +46,7 @@ export async function pluginFetch(slug, path, opts = {}) {
45
46
  throw e;
46
47
  }
47
48
  }
49
+ /** Lỗi khi gọi Public API của CMS. `status` = mã HTTP (0 = lỗi mạng / hết thời gian chờ). */
48
50
  export class CmsApiError extends Error {
49
51
  status;
50
52
  constructor(status, message) {
@@ -52,7 +54,7 @@ export class CmsApiError extends Error {
52
54
  this.status = status;
53
55
  }
54
56
  }
55
- /** Header X-CMS-Vary từ `vary` ("device=mobile,flag:ab=b"); rỗng → không gửi. */
57
+ /** @internal Header X-CMS-Vary từ `vary` ("device=mobile,flag:ab=b"); rỗng → không gửi. */
56
58
  export function varyHeader(vary) {
57
59
  const parts = Object.entries(vary ?? {}).filter(([k, v]) => /^(device|flag:[a-z][a-z0-9-]{0,23})$/.test(k) && /^[A-Za-z0-9_-]{1,32}$/.test(v)).map(([k, v]) => `${k}=${v.toLowerCase()}`);
58
60
  return parts.length ? { "X-CMS-Vary": parts.join(",") } : {};
@@ -86,7 +88,9 @@ function waitForApi() {
86
88
  }
87
89
  /** Lỗi mạng hoặc 502/503/504 (proxy/API đang khởi động) — không tính lỗi 500 thật của API. */
88
90
  const isUnavailable = (e) => isFetchKitError(e) && (!e.status || e.status === 502 || e.status === 503 || e.status === 504);
89
- /** Gọi Public API của CMS. Kết quả được cache và gắn tag "cms" để revalidate khi nội dung thay đổi. */
91
+ /**
92
+ * Gọi thẳng một endpoint của Public API (`/api/public/...`) khi SDK chưa có hàm riêng — lối thoát có cam kết cho theme / plugin.
93
+ * Ưu tiên các hàm `get*`. Lỗi → ném `CmsApiError` (`status` = mã HTTP). Kết quả được cache và gắn tag "cms" để revalidate khi nội dung thay đổi. */
90
94
  export async function cmsFetch(path, opts = {}) {
91
95
  if ((breaker.__cmsApiDownUntil ?? 0) > Date.now())
92
96
  throw new CmsApiError(503, `CMS API tạm thời không phản hồi: ${path}`);
@@ -119,9 +123,16 @@ export const getSite = async (locale) => cmsFetch("/site", { tags: ["site"], que
119
123
  /** Cookie (httpOnly) giữ token mở khoá bài có mật khẩu: "12:token,34:token". */
120
124
  export const UNLOCK_COOKIE = "cms-unlock";
121
125
  export const UNLOCK_HEADER = "X-CMS-Unlock";
122
- /** unlock: giá trị cookie cms-unlock — có thì không dùng cache (nội dung riêng của người đã nhập mật khẩu). */
126
+ /** @internal Core dùng để dựng trang theo URL. unlock: giá trị cookie cms-unlock — có thì không dùng cache (nội dung riêng của người đã nhập mật khẩu). */
123
127
  export const resolvePath = (path, query = {}, noStore = false, unlock) => cmsFetch("/resolve", { tags: ["posts"], noStore: noStore || !!unlock, query: clean({ ...query, path }), headers: unlock ? { [UNLOCK_HEADER]: unlock } : undefined });
128
+ /** @internal Dữ liệu trang xem trước theo token (core dùng cho Draft Mode). */
124
129
  export const getPreview = (token) => cmsFetch("/preview", { noStore: true, query: { token } });
130
+ /**
131
+ * Danh sách bài đã đăng theo điều kiện (tương đương `WP_Query`). Mặc định không kèm nội dung đầy đủ (`withContent`).
132
+ * Trả `{ items, total, page, totalPages }`; `noTotal: true` bỏ bước đếm tổng.
133
+ * @example const { items } = await getPosts({ type: "post", taxQuery: [{ taxonomy: "category", terms: ["tin-tuc"] }], perPage: 6 });
134
+ * @see docs/query-engine.md
135
+ */
125
136
  export const getPosts = async ({ withContent, ...q } = {}) => {
126
137
  // Bóc tách TRONG thân hàm, không phải trong tham số: chữ ký đã công bố của getPosts nằm trong baseline
127
138
  // hợp đồng (api/theme-sdk.txt) nên thêm tên vào tham số là đổi một dòng đã ký (CI coi là phá hợp đồng).
@@ -135,6 +146,32 @@ export const getPosts = async ({ withContent, ...q } = {}) => {
135
146
  locale: rest.locale ?? (await getRequestLocale()),
136
147
  }) });
137
148
  };
149
+ /**
150
+ * Bài liền trước (`"prev"`, đăng sớm hơn) hoặc liền sau (`"next"`) cùng loại nội dung (tương đương `get_adjacent_post`).
151
+ * `query` lọc thêm, vd cùng chuyên mục: `{ taxQuery: [{ taxonomy: "category", terms: [slug] }] }`. Không có → `null`.
152
+ * @since 1.44.0
153
+ * @example const [prev, next] = await Promise.all([getAdjacentPost(post, "prev"), getAdjacentPost(post, "next")]);
154
+ */
155
+ export async function getAdjacentPost(post, direction, query = {}) {
156
+ if (!post.publishedAt)
157
+ return null;
158
+ const at = direction === "prev" ? { before: post.publishedAt, order: "desc" } : { after: post.publishedAt, order: "asc" };
159
+ const r = await getPosts({ type: post.type, ...query, ...at, orderBy: "date", perPage: 1, noTotal: true, exclude: [...(query.exclude ?? []), post.id] });
160
+ return r.items[0] ?? null;
161
+ }
162
+ /**
163
+ * Chỉ lấy id bài (tương đương `WP_Query` với `fields => 'ids'`): cùng điều kiện như {@link getPosts}, máy chủ không dựng đối tượng bài.
164
+ * @since 1.44.0
165
+ */
166
+ export const getPostIds = async ({ withContent: _w, ...q } = {}) => {
167
+ const { taxQuery, metaQuery, ...rest } = q;
168
+ return cmsFetch("/posts", { tags: ["posts"], query: clean({
169
+ ...postQueryParams(rest), fields: "ids",
170
+ taxQuery: taxQuery?.length ? JSON.stringify(taxQuery) : undefined,
171
+ metaQuery: metaQuery?.clauses?.length ? JSON.stringify(metaQuery) : undefined,
172
+ locale: rest.locale ?? (await getRequestLocale()),
173
+ }) });
174
+ };
138
175
  const loc = async (locale) => locale ?? (await getRequestLocale());
139
176
  /** Tham số đơn giản của PostQuery → query string (Date → ISO). */
140
177
  function postQueryParams(q) {
@@ -166,11 +203,28 @@ export const queryTerms = async ({ params, ...q }) => cmsFetch("/terms", { tags:
166
203
  export const getAuthors = async ({ params, ...q } = {}) => cmsFetch("/authors", { tags: ["authors"], query: clean({ ...params, ...q, locale: await loc(q.locale) }) });
167
204
  /** Danh sách media (thư viện ảnh, tài liệu tải về) — plugin giới hạn / mở rộng qua filter media.query. */
168
205
  export const getMedia = async ({ params, ...q } = {}) => cmsFetch("/media", { tags: ["media"], query: clean({ ...params, ...q }) });
169
- export const getPost = async (type, slug, locale) => cmsFetch(`/posts/${type}/${encodeURIComponent(slug)}`, { tags: ["posts"], query: clean({ locale: await loc(locale) }) }).catch(() => null);
170
- /** Bài đã đăng theo id (core ≥ 1.20.0 có hàm này; endpoint có từ trước). Không có / chưa đăng → null. */
171
- export const getPostById = async (id) => cmsFetch(`/posts/id/${id}`, { tags: ["posts", `post:${id}`] }).catch(() => null);
172
- export const getTerms = async (taxonomy, hideEmpty = true, locale) => cmsFetch(`/terms/${taxonomy}`, { tags: ["terms"], query: clean({ hideEmpty, locale: await loc(locale) }) });
173
- /** Cookie giữ token bản nháp của Trình dựng (website đang ở chế độ xem trước). */
206
+ /** CMS trả 404 → null; lỗi khác (mạng, 5xx) ném tiếp để trang không hiện "không tìm thấy" sai khi CMS đang lỗi. */
207
+ const nullIf404 = (e) => { if (e instanceof CmsApiError && e.status === 404)
208
+ return null; throw e; };
209
+ /**
210
+ * Bài đã đăng theo loại nội dung + slug, ngôn ngữ của request hiện tại (tương đương `get_page_by_path`).
211
+ * Không có / chưa đăng → `null`. CMS lỗi → ném `CmsApiError`.
212
+ * @example const about = await getPost("page", "gioi-thieu");
213
+ */
214
+ export const getPost = async (type, slug, locale) => cmsFetch(`/posts/${type}/${encodeURIComponent(slug)}`, { tags: ["posts"], query: clean({ locale: await loc(locale) }) }).catch(nullIf404);
215
+ /**
216
+ * Bài đã đăng theo id (tương đương `get_post($id)`). Không có / chưa đăng → `null`. CMS lỗi → ném `CmsApiError`.
217
+ * @since 1.31.0
218
+ */
219
+ export const getPostById = async (id) => cmsFetch(`/posts/id/${id}`, { tags: ["posts", `post:${id}`] }).catch(nullIf404);
220
+ export async function getTerms(q, hideEmpty = true, locale) {
221
+ if (typeof q === "string") {
222
+ deprecated("getTerms(taxonomy, hideEmpty, locale)", "getTerms({ taxonomy, hideEmpty, locale })");
223
+ q = { taxonomy: q, hideEmpty, locale };
224
+ }
225
+ return cmsFetch(`/terms/${encodeURIComponent(q.taxonomy)}`, { tags: ["terms"], query: clean({ hideEmpty: q.hideEmpty ?? true, locale: await loc(q.locale) }) });
226
+ }
227
+ /** @internal Cookie giữ token bản nháp của Trình dựng (website đang ở chế độ xem trước). */
174
228
  export const TEMPLATE_DRAFT_COOKIE = "cms-template-draft";
175
229
  async function templateDraft() {
176
230
  try {
@@ -183,25 +237,34 @@ async function templateDraft() {
183
237
  return null;
184
238
  }
185
239
  }
186
- /** Template / phần dựng bằng khối của theme đang dùng (bản sửa trong Trình dựng thắng bản của theme; đang xem trước → bản nháp). */
240
+ /** @internal Template / phần dựng bằng khối của theme đang dùng (bản sửa trong Trình dựng thắng bản của theme; đang xem trước → bản nháp). */
187
241
  export const getTemplates = async () => {
188
242
  const draft = await templateDraft();
189
243
  // Mỗi ngôn ngữ có thể có bản template / phần riêng (chưa có thì API trả bản mặc định)
190
244
  const locale = await getRequestLocale();
191
245
  return cmsFetch("/templates", draft ? { noStore: true, query: clean({ draft, locale }) } : { tags: ["templates"], query: clean({ locale }) });
192
246
  };
193
- /** Nội dung mẫu đồng bộ (khối syncedPattern). null = mẫu đã xoá / chưa xuất bản. */
194
- export const getPattern = (id) => cmsFetch(`/patterns/${id}`, { tags: ["patterns", "posts"] }).catch(() => null);
195
- export const getMenu = async (location, locale) => cmsFetch(`/menus/${location}`, { tags: ["menus"], query: clean({ locale: await loc(locale) }) });
196
- export const getMenuById = (id) => cmsFetch(`/menus/id/${id}`, { tags: ["menus"] });
197
- export const getWidgets = async (area, locale) => cmsFetch(`/widgets/${area}`, { tags: ["widgets"], query: clean({ locale: await loc(locale) }) });
247
+ /** Nội dung mẫu đồng bộ (khối syncedPattern). Mẫu đã xoá / chưa xuất bản → `null`; CMS lỗi → ném `CmsApiError`. */
248
+ export const getPattern = (id) => cmsFetch(`/patterns/${id}`, { tags: ["patterns", "posts"] }).catch(nullIf404);
198
249
  /**
199
- * Bình luận đã duyệt theo trang (số mỗi trang, thứ tự: Cài đặt › Thảo luận).
200
- * Bài có mật khẩu (core >= 1.15): CMS chỉ trả bình luận khi có token mở khoá — unlock = giá trị cookie cms-unlock (không cache).
250
+ * Menu gắn ở một vị trí của theme (`theme.json › menuLocations`), ngôn ngữ của request (tương đương `wp_get_nav_menu_items` theo location).
251
+ * Chưa gắn menu → `null`. Vẽ sẵn: `<Menu location="primary" />`.
201
252
  */
202
- export const getComments = (postId, page = 1, unlock, opts = {}) => cmsFetch(`/comments/${postId}`, {
203
- tags: [`comments:${postId}`], noStore: !!unlock, query: clean({ page: page > 1 ? page : undefined, perPage: opts.perPage, order: opts.order }), headers: unlock ? { [UNLOCK_HEADER]: unlock } : undefined,
204
- });
253
+ export const getMenu = async (location, locale) => cmsFetch(`/menus/${location}`, { tags: ["menus"], query: clean({ locale: await loc(locale) }) }).catch(nullIf404);
254
+ /** Menu theo id (khối Điều hướng chọn menu cụ thể). Không có → `null`. */
255
+ export const getMenuById = (id) => cmsFetch(`/menus/id/${id}`, { tags: ["menus"] }).catch(nullIf404);
256
+ /** Widget trong một khu vực (`theme.json › widgetAreas`), theo thứ tự. Vẽ sẵn: `<WidgetArea id="sidebar" />`. */
257
+ export const getWidgets = async (area, locale) => cmsFetch(`/widgets/${area}`, { tags: ["widgets"], query: clean({ locale: await loc(locale) }) });
258
+ export function getComments(postId, q = {}, unlock, opts = {}) {
259
+ if (typeof q === "number") {
260
+ deprecated("getComments(postId, page, unlock, opts)", "getComments(postId, { page, unlock, perPage, order })");
261
+ q = { page: q, unlock, ...opts };
262
+ }
263
+ const page = q.page ?? 1;
264
+ return cmsFetch(`/comments/${postId}`, {
265
+ tags: [`comments:${postId}`], noStore: !!q.unlock, query: clean({ page: page > 1 ? page : undefined, perPage: q.perPage, order: q.order }), headers: q.unlock ? { [UNLOCK_HEADER]: q.unlock } : undefined,
266
+ });
267
+ }
205
268
  /** Cookie mở khoá bài có mật khẩu của request hiện tại (server component); ngoài request → undefined. */
206
269
  export async function requestUnlock() {
207
270
  try {
@@ -212,5 +275,7 @@ export async function requestUnlock() {
212
275
  return undefined;
213
276
  }
214
277
  }
278
+ /** Số bài theo tháng, mới nhất trước, kèm link trang lưu trữ (tương đương `wp_get_archives`). */
215
279
  export const getArchives = async (locale) => cmsFetch("/archives", { tags: ["posts"], query: clean({ locale: await loc(locale) }) });
280
+ /** Ngôn ngữ đang bật của website và ngôn ngữ mặc định. */
216
281
  export const getLanguages = () => cmsFetch("/languages", { tags: ["site"] });
@@ -1,5 +1,6 @@
1
- /** Tên cookie phiên đăng nhập của website (httpOnly, do frontend core đặt). Dùng chung cho proxy và SDK. */
1
+ /** @internal Tên cookie phiên đăng nhập của website (httpOnly, do frontend core đặt). Dùng chung cho proxy và SDK. */
2
2
  export declare const ACCESS_COOKIE = "cms_at";
3
+ /** @internal Cookie làm mới phiên đăng nhập (httpOnly). */
3
4
  export declare const REFRESH_COOKIE = "cms_rt";
4
5
  /** Người dùng đang đăng nhập trên website. */
5
6
  export interface CurrentUser {
@@ -1,5 +1,6 @@
1
- /** Tên cookie phiên đăng nhập của website (httpOnly, do frontend core đặt). Dùng chung cho proxy và SDK. */
1
+ /** @internal Tên cookie phiên đăng nhập của website (httpOnly, do frontend core đặt). Dùng chung cho proxy và SDK. */
2
2
  export const ACCESS_COOKIE = "cms_at";
3
+ /** @internal Cookie làm mới phiên đăng nhập (httpOnly). */
3
4
  export const REFRESH_COOKIE = "cms_rt";
4
5
  /**
5
6
  * Chỉ nhận đường dẫn nội bộ ("/account") — chặn chuyển hướng ra trang ngoài (?redirect=https://lừa-đảo).
package/dist/auth.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type CurrentUser } from "./auth-shared.js";
2
2
  export { ACCESS_COOKIE, REFRESH_COOKIE, safeRedirect, type CurrentUser } from "./auth-shared.js";
3
- /** Access token của người đang xem (server). Trang gọi hàm này sẽ render theo từng người (không cache tĩnh). */
3
+ /** @internal Access token của người đang xem (server). Theme dùng `getCurrentUser()` / `pluginFetch(..., { asUser: true })`. Trang gọi hàm này sẽ render theo từng người (không cache tĩnh). */
4
4
  export declare const getAccessToken: () => Promise<string | undefined>;
5
5
  /**
6
6
  * Người đang đăng nhập trên website, null nếu là khách.
package/dist/auth.js CHANGED
@@ -4,7 +4,7 @@ export { ACCESS_COOKIE, REFRESH_COOKIE, safeRedirect } from "./auth-shared.js";
4
4
  const API = (process.env.CMS_API_URL ?? "http://localhost:5100").replace(/\/$/, "");
5
5
  // Khoá frontend: request SSR của website không bị tính chung giới hạn đăng nhập theo IP của máy chủ website
6
6
  const KEY_HEADER = process.env.CMS_FRONTEND_KEY ? { "X-CMS-Frontend-Key": process.env.CMS_FRONTEND_KEY } : {};
7
- /** Access token của người đang xem (server). Trang gọi hàm này sẽ render theo từng người (không cache tĩnh). */
7
+ /** @internal Access token của người đang xem (server). Theme dùng `getCurrentUser()` / `pluginFetch(..., { asUser: true })`. Trang gọi hàm này sẽ render theo từng người (không cache tĩnh). */
8
8
  export const getAccessToken = cache(async () => {
9
9
  try {
10
10
  const { cookies } = await import("next/headers");
package/dist/client.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type CountdownUnit } from "@ecomcx/ecomweb-content";
1
2
  import { Component } from "react";
2
3
  import type { Comment } from "./types.js";
3
4
  import type { AnchorHTMLAttributes, CSSProperties, ReactNode } from "react";
@@ -29,6 +30,7 @@ export declare class ExtensionBoundary extends Component<{
29
30
  componentDidCatch(error: unknown): void;
30
31
  render(): import("react").JSX.Element | null;
31
32
  }
33
+ /** `true` nếu link là trang của website (chuyển trang không tải lại); file, feed, API, link ngoài → `false`. */
32
34
  export declare function isInternalHref(href: string): boolean;
33
35
  export type LinkProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> & {
34
36
  href: string;
@@ -43,9 +45,14 @@ export type LinkProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> &
43
45
  /** Khớp cả trang con (vd /category/a/page/2 vẫn active cho /category/a). Mặc định true, trừ trang chủ. */
44
46
  matchNested?: boolean;
45
47
  };
48
+ /**
49
+ * Link chuyển trang không tải lại (bọc `next/link`); link ngoài, file, RSS tự dùng `<a>` thường.
50
+ * `activeClassName` gắn class khi URL hiện tại khớp (`matchNested`: khớp cả trang con). Prefetch mặc định tắt.
51
+ */
46
52
  export declare function Link({ href, prefetch, activeClassName, matchNested, className, children, ...rest }: LinkProps): import("react").JSX.Element;
47
53
  /** Form tìm kiếm (GET) chuyển trang phía client. */
48
- export declare function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition }: {
54
+ export declare function SearchFormClient({ action, defaultValue, placeholder, label, buttonLabel, postType, showLabel, buttonPosition, buttonIcon }: {
55
+ buttonIcon?: boolean;
49
56
  action: string;
50
57
  defaultValue?: string | null;
51
58
  placeholder: string;
@@ -132,23 +139,37 @@ export declare function LanguageSwitcherClient({ languages, current, defaultLoca
132
139
  export { LoginForm, RegisterForm, ForgotPasswordForm, ResetPasswordForm, LogoutButton, LoginOutLink, useCurrentUser, extraFields, ProfileForm, ChangePasswordForm, DeleteAccountForm, AUTH_LABELS, AUTH_PATHS, type AuthLabels, type AuthPaths, type SignInProvider } from "./auth-forms.js";
133
140
  export { safeRedirect, type CurrentUser } from "./auth-shared.js";
134
141
  /** Khối countdown: đếm ngược tới `target` (ms). Dựng lần đầu cùng giá trị trên máy chủ, rồi cập nhật mỗi giây. */
135
- export declare function CountdownClient({ target, label, expiredText, units, serverNow }: {
142
+ export declare function CountdownClient({ target, label, expiredText, units, serverNow, attrs }: {
136
143
  target: number;
137
144
  label?: string;
138
145
  expiredText?: string;
139
- units?: Partial<Record<"d" | "h" | "m" | "s", string>>;
146
+ units?: Partial<Record<CountdownUnit, string>>;
140
147
  serverNow?: number;
148
+ attrs?: Record<string, unknown>;
141
149
  }): import("react").JSX.Element;
150
+ /** Mục lục: tô đậm mục của tiêu đề đang đọc (tiêu đề cuối cùng đã cuộn qua mép trên 120px) — aria-current="location". */
151
+ export declare function TocSpy(): import("react").JSX.Element;
142
152
  /** Nút ☰ của menu trên điện thoại: <details> gốc + Escape đóng menu và trả focus về nút. */
143
153
  export declare function NavToggle({ label, children, className }: {
144
154
  label: string;
145
155
  children: ReactNode;
146
156
  className?: string;
147
157
  }): import("react").JSX.Element;
148
- /** Khối tabs: các panel đã vẽ sẵn trên máy chủ (nội dung vẫn có trong HTML cho SEO); chỉ đổi panel đang hiện. */
149
- export declare function TabsClient({ titles, panels }: {
158
+ /**
159
+ * Khối tabs: các panel đã vẽ sẵn trên máy chủ (nội dung vẫn có trong HTML cho SEO); chỉ đổi panel đang hiện.
160
+ * Tab dọc (`vertical`), thành accordion trên điện thoại (`mobileAccordion`, chỉ CSS: tiêu đề nằm ngay trên panel của nó);
161
+ * tab có neo → panel mang id = neo, mở thẳng bằng #neo.
162
+ */
163
+ export declare function TabsClient({ titles, panels, initial, icons, subtitles, anchors, vertical, mobileAccordion, extraClass }: {
150
164
  titles: string[];
151
165
  panels: ReactNode[];
166
+ initial?: number;
167
+ icons?: Array<string | undefined>;
168
+ subtitles?: Array<string | undefined>;
169
+ anchors?: Array<string | undefined>;
170
+ vertical?: boolean;
171
+ mobileAccordion?: boolean; /** Class đầy đủ của khối (tabsClass): thay cho class tự ghép. */
172
+ extraClass?: string;
152
173
  }): import("react").JSX.Element;
153
174
  /** Phóng to ảnh: bấm ảnh mở lớp phủ (Esc hoặc bấm nền để đóng). `src` đã qua safeUrl ở máy chủ. */
154
175
  export declare function LightboxClient({ src, alt, children }: {