@eldrajs/theme-nuxt 0.0.0-stage → 0.1.1

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/LICENSE +21 -0
  3. package/README.md +324 -2
  4. package/dist/module.cjs +5 -0
  5. package/dist/module.d.mts +56 -0
  6. package/dist/module.d.ts +56 -0
  7. package/dist/module.json +12 -0
  8. package/dist/module.mjs +265 -0
  9. package/dist/runtime/catalog.d.ts +119 -0
  10. package/dist/runtime/catalog.js +226 -0
  11. package/dist/runtime/commerce.d.ts +68 -0
  12. package/dist/runtime/commerce.js +40 -0
  13. package/dist/runtime/composables/useEldraPage.d.ts +17 -0
  14. package/dist/runtime/composables/useEldraPage.js +229 -0
  15. package/dist/runtime/designTokens.d.ts +59 -0
  16. package/dist/runtime/designTokens.js +55 -0
  17. package/dist/runtime/drafts.d.ts +3 -0
  18. package/dist/runtime/drafts.js +83 -0
  19. package/dist/runtime/links.d.ts +32 -0
  20. package/dist/runtime/links.js +132 -0
  21. package/dist/runtime/locale.d.ts +21 -0
  22. package/dist/runtime/locale.js +9 -0
  23. package/dist/runtime/localeState.d.ts +52 -0
  24. package/dist/runtime/localeState.js +48 -0
  25. package/dist/runtime/locales.d.ts +186 -0
  26. package/dist/runtime/locales.js +109 -0
  27. package/dist/runtime/messages.d.ts +59 -0
  28. package/dist/runtime/messages.js +66 -0
  29. package/dist/runtime/origins.d.ts +18 -0
  30. package/dist/runtime/origins.js +28 -0
  31. package/dist/runtime/plugin.d.ts +3 -0
  32. package/dist/runtime/plugin.js +83 -0
  33. package/dist/runtime/resolveRoute.d.ts +81 -0
  34. package/dist/runtime/resolveRoute.js +166 -0
  35. package/dist/runtime/routePath.d.ts +31 -0
  36. package/dist/runtime/routePath.js +7 -0
  37. package/dist/runtime/staticRoutes.d.ts +14 -0
  38. package/dist/runtime/staticRoutes.js +26 -0
  39. package/dist/types.d.mts +7 -0
  40. package/dist/types.d.ts +7 -0
  41. package/package.json +66 -3
@@ -0,0 +1,56 @@
1
+ import { NuxtModule } from '@nuxt/schema';
2
+ import { EldraRetryOptions } from '@eldrajs/theme-core';
3
+ import { ManifestRoute, DeclaredThemeCodePage, DeclaredSeed, ManifestTemplateRoles } from '@eldrajs/vite-plugin-theme';
4
+ import { LayoutBreakpoints } from '@eldrajs/theme-core/layout';
5
+
6
+ interface ModuleOptions {
7
+ gatewayUrl: string;
8
+ orgId: string;
9
+ studioOrigins: string[];
10
+ pageSchema: string;
11
+ routeTemplateSchema: string;
12
+ locale?: string;
13
+ routes?: ManifestRoute[];
14
+ customPages?: DeclaredThemeCodePage[];
15
+ /** What to seed a site with on its first deploy: route templates (at most 8)
16
+ * and static pages (`{ page: { slug }, title, blocks }`, at most 16) in one
17
+ * list. A seed is ignored once the site has a template for its route pattern,
18
+ * or a page with its slug, so nothing a merchant has edited is overwritten by
19
+ * a later deploy. */
20
+ templates?: DeclaredSeed[];
21
+ /** The block data behind the `header`/`footer` roles the declared
22
+ * `templates` layouts may reference. See that package's changelog for the
23
+ * validation rules. */
24
+ templateRoles?: ManifestTemplateRoles;
25
+ tailwind?: boolean;
26
+ /** The theme's own tablet/normal layout breakpoints (min-width px), so
27
+ * Studio's UI can react to the theme's actual ranges (its side panels
28
+ * overlay the preview at `tablet + 100`px) instead of a value the theme
29
+ * may not share. Resolved and validated in @eldrajs/theme-core
30
+ * (resolveLayoutBreakpoints) — an invalid pair falls back to the defaults
31
+ * (768/1024) with a console warning rather than failing the build.
32
+ * Reaches both the layout stylesheet and `theme:ready` via the theme
33
+ * manifest (`virtual:eldra/manifest`), the one resolved value every
34
+ * consumer reads. */
35
+ breakpoints?: LayoutBreakpoints;
36
+ /**
37
+ * How hard every gateway read tries again when the gateway says "not now" —
38
+ * a `429` from its rate limit, a `503` while it restarts, a dropped
39
+ * connection. Defaults to five attempts with exponential backoff and jitter,
40
+ * honouring `Retry-After`; `{ attempts: 0 }` turns it off.
41
+ *
42
+ * It is what keeps a static build of a large site alive: a `nuxi generate`
43
+ * is thousands of reads from one address, which is enough to meet a
44
+ * per-minute rate limit, and with `nitro.prerender.failOnError` set (as it
45
+ * should be) one refusal ends the build. Reaches **both** transports — this
46
+ * module's own prerender reads and the theme's at request time
47
+ * (`@eldrajs/theme-core`), and the platform read behind `commerce`/`locales`
48
+ * (`@eldrajs/sdk`) — and is carried in the public runtime config, so a
49
+ * storefront building its own commerce client reads the same policy.
50
+ */
51
+ retry?: EldraRetryOptions;
52
+ }
53
+ declare const eldraModule: NuxtModule<ModuleOptions>;
54
+
55
+ export { eldraModule as default };
56
+ export type { ModuleOptions };
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@eldrajs/theme-nuxt",
3
+ "configKey": "eldra",
4
+ "compatibility": {
5
+ "nuxt": ">=3.13.0"
6
+ },
7
+ "version": "0.1.1",
8
+ "builder": {
9
+ "@nuxt/module-builder": "0.8.4",
10
+ "unbuild": "unknown"
11
+ }
12
+ }
@@ -0,0 +1,265 @@
1
+ import { mkdirSync, existsSync, readFileSync, writeFileSync, copyFileSync, cpSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { defineNuxtModule, createResolver, addVitePlugin, addPlugin, addImports } from '@nuxt/kit';
4
+ import { createEldraClient, resolvePagePath, parseDynamicRoutePattern, catalogRouteTarget, buildDynamicRoutePath, normalizeThemeDesignTokens, EldraClientError, stripStega } from '@eldrajs/theme-core';
5
+ import { createEldraClient as createEldraClient$1 } from '@eldrajs/sdk';
6
+ import eldraTheme from '@eldrajs/vite-plugin-theme';
7
+ import { listCatalogDocs, catalogDocRoutes } from '../dist/runtime/catalog.js';
8
+ import { readStoreCommerce } from '../dist/runtime/commerce.js';
9
+ import { readDesignTokens } from '../dist/runtime/designTokens.js';
10
+ import { normalizeLocale } from '../dist/runtime/locale.js';
11
+ import { resolveLocaleRouting, readStoreLocales, localePathFor } from '../dist/runtime/locales.js';
12
+ import { readThemeMessages, resolveSiteMessages } from '../dist/runtime/messages.js';
13
+ import { listAllEntries } from '../dist/runtime/resolveRoute.js';
14
+
15
+ const eldraModule = defineNuxtModule({
16
+ meta: {
17
+ name: "@eldrajs/theme-nuxt",
18
+ configKey: "eldra",
19
+ compatibility: { nuxt: ">=3.13.0" }
20
+ },
21
+ defaults: {
22
+ gatewayUrl: process.env.ELDRA_GATEWAY_URL ?? "",
23
+ orgId: process.env.ELDRA_ORG_ID ?? "",
24
+ locale: process.env.ELDRA_LOCALE ?? void 0,
25
+ // A preview bridge must be explicitly scoped by the consuming theme.
26
+ // Never supply a broad fallback origin.
27
+ studioOrigins: [],
28
+ pageSchema: "page",
29
+ routeTemplateSchema: "route-template",
30
+ tailwind: false
31
+ },
32
+ async setup(options, nuxt) {
33
+ const resolver = createResolver(import.meta.url);
34
+ const studioOrigins = validateStudioOrigins(options.studioOrigins);
35
+ const themeOptions = {
36
+ framework: "nuxt",
37
+ routes: options.routes,
38
+ customPages: options.customPages,
39
+ templates: options.templates,
40
+ templateRoles: options.templateRoles,
41
+ themeDir: nuxt.options.rootDir,
42
+ tailwind: options.tailwind,
43
+ breakpoints: options.breakpoints
44
+ };
45
+ addVitePlugin(eldraTheme(themeOptions));
46
+ if (options.tailwind === true) {
47
+ nuxt.options.css.push("virtual:eldra/tailwind-theme.css");
48
+ }
49
+ const existingRuntimeConfig = nuxt.options.runtimeConfig.public.eldra;
50
+ nuxt.options.runtimeConfig.public.eldra = {
51
+ ...existingRuntimeConfig,
52
+ gatewayUrl: options.gatewayUrl,
53
+ orgId: options.orgId,
54
+ studioOrigins: [...studioOrigins],
55
+ pageSchema: options.pageSchema,
56
+ routeTemplateSchema: options.routeTemplateSchema,
57
+ // Normalised here too, so a blank `ELDRA_LOCALE` or `eldra.locale`
58
+ // reaches the client as "no locale" rather than an empty `?locale=`.
59
+ locale: normalizeLocale(options.locale) ?? null,
60
+ // What the store sells in, filled in below once the platform has
61
+ // answered. Written here as well so the key exists for anything that
62
+ // reads this object during another module's own `setup`.
63
+ commerce: null,
64
+ // Which locales the site serves, filled in below from the same platform read. Written here
65
+ // first for the same reason: the key has to exist before another module's `setup` can look
66
+ // for it. See `./runtime/locales.ts`.
67
+ locales: null,
68
+ // The organisation's resolved design-token catalog (the theme's own tokens with the site's
69
+ // overrides already applied), filled in below from the same platform read settling. Written
70
+ // here first for the same reason `commerce`/`locales` are: the key has to exist before
71
+ // another module's own `setup` looks for it. See `./runtime/designTokens.ts`.
72
+ designTokens: null,
73
+ // `null`, not `undefined`: the key has to survive the payload so a
74
+ // storefront's own client (`examples/starter-nuxt`'s storefront plugin)
75
+ // reads the same policy the module's reads use.
76
+ retry: options.retry ?? null
77
+ };
78
+ addPlugin(resolver.resolve("./runtime/plugin"));
79
+ addImports([
80
+ { name: "useEldraPage", from: resolver.resolve("./runtime/composables/useEldraPage") },
81
+ // The route key a theme's catch-all page gives `<NuxtPage>`; see `./runtime/routePath`.
82
+ { name: "eldraRouteKey", from: resolver.resolve("./runtime/routePath") },
83
+ { name: "useEldra", from: "@eldrajs/theme-vue" },
84
+ // The active content locale and the path helpers around it. Re-exported from theme-vue
85
+ // rather than defined here: the state lives on the theme context so a **block** can read it
86
+ // through one `inject` with no Nuxt around it (a Storybook story, a unit mount), and this
87
+ // module is what fills it from the route.
88
+ { name: "useEldraLocale", from: "@eldrajs/theme-vue" },
89
+ { name: "useEldraEntry", from: "@eldrajs/theme-vue" },
90
+ { name: "useEldraPreview", from: "@eldrajs/theme-vue" }
91
+ ]);
92
+ let localeRouting = resolveLocaleRouting(null, options.locale);
93
+ nuxt.hook("prerender:routes", async (ctx) => {
94
+ if (options.gatewayUrl === "" || options.orgId === "") {
95
+ console.warn('[eldra] ELDRA_GATEWAY_URL / ELDRA_ORG_ID not set \u2014 prerendering "/" only');
96
+ ctx.routes.add("/");
97
+ return;
98
+ }
99
+ const client = createEldraClient({
100
+ gatewayUrl: options.gatewayUrl,
101
+ orgId: options.orgId,
102
+ retry: options.retry
103
+ });
104
+ const locale = normalizeLocale(options.locale);
105
+ const [pages, templates] = await Promise.all([
106
+ listAllEntries(client, options.pageSchema, locale),
107
+ listRouteTemplateEntries(client, options.routeTemplateSchema, locale)
108
+ ]);
109
+ const generated = /* @__PURE__ */ new Set();
110
+ const addRoute = (path) => {
111
+ ctx.routes.add(path);
112
+ for (const prefixed of localeRouting.prefixed) {
113
+ ctx.routes.add(localePathFor(path, prefixed, localeRouting));
114
+ }
115
+ };
116
+ for (const page of pages) {
117
+ const path = resolvePagePath(page, pages);
118
+ generated.add(path);
119
+ addRoute(path);
120
+ }
121
+ const codeOwned = new Set((options.customPages ?? []).map((page) => page.path));
122
+ const entriesBySchema = /* @__PURE__ */ new Map();
123
+ const catalogByKind = /* @__PURE__ */ new Map();
124
+ for (const template of templates) {
125
+ const pattern = routeString(template.data.routePattern);
126
+ const schemaApiId = routeString(template.data.schemaApiId);
127
+ const slugField = routeString(template.data.slugField);
128
+ const parsed = parseDynamicRoutePattern(pattern);
129
+ if (parsed === null || parsed.paramName !== slugField || schemaApiId === "") {
130
+ throw new Error(`@eldrajs/theme-nuxt: invalid published route template ${template.id}`);
131
+ }
132
+ const catalogKind = catalogRouteTarget(schemaApiId);
133
+ if (catalogKind !== null) {
134
+ let catalogPromise = catalogByKind.get(catalogKind);
135
+ if (catalogPromise === void 0) {
136
+ catalogPromise = listCatalogDocs(client, catalogKind, locale);
137
+ catalogByKind.set(catalogKind, catalogPromise);
138
+ }
139
+ for (const path of catalogDocRoutes(catalogKind, await catalogPromise, pattern)) {
140
+ if (codeOwned.has(path))
141
+ continue;
142
+ if (generated.has(path)) {
143
+ console.warn(`[eldra] skipped ${path}: another route already generates this path`);
144
+ continue;
145
+ }
146
+ generated.add(path);
147
+ addRoute(path);
148
+ }
149
+ continue;
150
+ }
151
+ let entriesPromise = entriesBySchema.get(schemaApiId);
152
+ if (entriesPromise === void 0) {
153
+ entriesPromise = listAllEntries(client, schemaApiId, locale);
154
+ entriesBySchema.set(schemaApiId, entriesPromise);
155
+ }
156
+ for (const entry of await entriesPromise) {
157
+ const path = buildDynamicRoutePath(pattern, entry.data[slugField]);
158
+ if (path === null) {
159
+ throw new Error(`@eldrajs/theme-nuxt: invalid route slug for template ${template.id}`);
160
+ }
161
+ if (codeOwned.has(path))
162
+ continue;
163
+ if (generated.has(path)) {
164
+ throw new Error(
165
+ `@eldrajs/theme-nuxt: duplicate generated route ${JSON.stringify(path)}`
166
+ );
167
+ }
168
+ generated.add(path);
169
+ addRoute(path);
170
+ }
171
+ }
172
+ });
173
+ nuxt.hooks.hook(
174
+ "nitro:init",
175
+ (nitro) => {
176
+ nitro.hooks.hook("prerender:done", () => {
177
+ const publicDir = nitro.options.output.publicDir;
178
+ mkdirSync(publicDir, { recursive: true });
179
+ copyGeneratedManifest(nuxt.options.rootDir, publicDir);
180
+ const target = join(publicDir, "_headers");
181
+ const existing = existsSync(target) ? readFileSync(target, "utf8").replace(/^\s*Content-Security-Policy:\s*frame-ancestors[^\r\n]*(?:\r?\n|$)/gim, "").trimEnd() + "\n\n" : "";
182
+ const ancestors = ["'self'", ...studioOrigins].join(" ");
183
+ writeFileSync(
184
+ target,
185
+ `${existing}/*
186
+ Content-Security-Policy: frame-ancestors ${ancestors}
187
+ `
188
+ );
189
+ });
190
+ }
191
+ );
192
+ nuxt.options.app.head.meta = [
193
+ ...nuxt.options.app.head.meta ?? [],
194
+ { name: "eldra-theme-version", content: themeVersion(nuxt.options.rootDir) },
195
+ { name: "eldra-sdk-version", content: packageVersion(resolver.resolve("../package.json")) }
196
+ ];
197
+ const platformClient = options.gatewayUrl === "" || options.orgId === "" ? null : createEldraClient$1({
198
+ apiBaseUrl: options.gatewayUrl,
199
+ orgId: options.orgId,
200
+ retry: options.retry
201
+ });
202
+ const [commerce, locales, platformMessages, platformDesignTokens] = await Promise.all([
203
+ readStoreCommerce(platformClient),
204
+ readStoreLocales(platformClient),
205
+ readThemeMessages(platformClient),
206
+ readDesignTokens(platformClient)
207
+ ]);
208
+ const runtimeEldra = nuxt.options.runtimeConfig.public.eldra;
209
+ runtimeEldra.commerce = commerce;
210
+ runtimeEldra.locales = locales;
211
+ runtimeEldra.designTokens = platformDesignTokens;
212
+ localeRouting = resolveLocaleRouting(locales, options.locale);
213
+ themeOptions.resolveMessages = (manifestMessages) => resolveSiteMessages(manifestMessages, platformMessages, locales);
214
+ themeOptions.resolveTokens = (manifestTokens) => platformDesignTokens ?? normalizeThemeDesignTokens(manifestTokens);
215
+ }
216
+ });
217
+ async function listRouteTemplateEntries(client, schemaApiId, locale) {
218
+ try {
219
+ return await listAllEntries(client, schemaApiId, locale);
220
+ } catch (error) {
221
+ if (error instanceof EldraClientError && error.status === 404)
222
+ return [];
223
+ throw error;
224
+ }
225
+ }
226
+ function routeString(value) {
227
+ return typeof value === "string" ? stripStega(value).trim() : "";
228
+ }
229
+ function validateStudioOrigins(origins) {
230
+ if (origins.length === 0)
231
+ throw new Error("@eldrajs/theme-nuxt: studioOrigins must not be empty");
232
+ return origins.map((origin) => {
233
+ if (/^https:\/\/(?:\*\.)?[a-z0-9.-]+(?::\d+)?$/i.test(origin))
234
+ return origin;
235
+ if (/^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/i.test(origin))
236
+ return origin;
237
+ throw new Error(`@eldrajs/theme-nuxt: invalid Studio origin "${origin}"`);
238
+ });
239
+ }
240
+ function themeVersion(rootDir) {
241
+ return packageVersion(join(rootDir, "package.json"));
242
+ }
243
+ function packageVersion(path) {
244
+ try {
245
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
246
+ return typeof pkg.version === "string" ? pkg.version : "0.0.0";
247
+ } catch {
248
+ return "0.0.0";
249
+ }
250
+ }
251
+ function copyGeneratedManifest(rootDir, publicDir) {
252
+ const sourceDir = join(rootDir, ".eldra");
253
+ const sourceManifest = join(sourceDir, "manifest.json");
254
+ if (!existsSync(sourceManifest)) {
255
+ throw new Error("@eldrajs/theme-nuxt: generated .eldra/manifest.json is missing");
256
+ }
257
+ const targetDir = join(publicDir, ".eldra");
258
+ mkdirSync(targetDir, { recursive: true });
259
+ copyFileSync(sourceManifest, join(targetDir, "manifest.json"));
260
+ const previews = join(sourceDir, "previews");
261
+ if (existsSync(previews))
262
+ cpSync(previews, join(targetDir, "previews"), { recursive: true });
263
+ }
264
+
265
+ export { eldraModule as default };
@@ -0,0 +1,119 @@
1
+ import { type CatalogDoc, type EldraClient, type EntryDoc } from '@eldrajs/theme-core';
2
+ export type CatalogRouteKind = 'product' | 'collection' | 'category';
3
+ /** Which catalog object a resolved route is showing, and under which slug. */
4
+ export interface CatalogRouteRef {
5
+ kind: CatalogRouteKind;
6
+ /** The object's own slug — for a category, the **leaf's**. */
7
+ slug: string;
8
+ /**
9
+ * A category's canonical path, root slug first, joined with `/` and without a
10
+ * leading slash (`billinn/bilstolar`) — the value the route's catch-all
11
+ * parameter carried. Set for `kind: 'category'` and for nothing else, because
12
+ * a product and a collection are addressed by one segment.
13
+ */
14
+ path?: string;
15
+ }
16
+ /**
17
+ * Map a public catalog response onto the binding paths a catalog-backed route
18
+ * template exposes. These keys are the documented, stable surface a template's
19
+ * `bindings`/`templates` address — a product's `title`, `variants.0.price`,
20
+ * `images.0.url` — so every one of them is always present, whatever the
21
+ * response omitted. The gateway resolves a product's or collection's title and
22
+ * description for the requested locale (falling back to the default one)
23
+ * before serving it, so no translation table is walked here.
24
+ *
25
+ * Returns null when the response carries no id: an entry without one cannot be
26
+ * addressed, overlaid or keyed, and inventing one would hide a broken read.
27
+ */
28
+ export declare function projectCatalogEntry(
29
+ /**
30
+ * A category is not one of the two: its binding fields are the **tree's** —
31
+ * the canonical path, the ancestors and the children — so none of them is
32
+ * knowable from one response and `projectCategoryNode` is what builds them.
33
+ */
34
+ kind: 'product' | 'collection', doc: unknown): EntryDoc | null;
35
+ /** One level of a category's trail, as the binding fields carry it. */
36
+ export interface CatalogCategoryRef {
37
+ slug: string;
38
+ title: string;
39
+ /** Canonical path, root slug first, no leading slash. */
40
+ path: string;
41
+ }
42
+ /** One category placed in the tree: everything a route and its template need. */
43
+ export interface CatalogCategoryNode extends CatalogCategoryRef {
44
+ id: string;
45
+ /** Root first, the category itself excluded. */
46
+ ancestors: CatalogCategoryRef[];
47
+ /** Direct children only, in the order the list served them. */
48
+ children: CatalogCategoryRef[];
49
+ raw: CatalogDoc;
50
+ }
51
+ /**
52
+ * **Every category the site can address, keyed by its canonical path** —
53
+ * `billinn/bilstolar`, root slug first, joined with `/`.
54
+ *
55
+ * `GET /catalog/v1/categories` answers `{id, slug, title, parentId}` rows and no
56
+ * trail at all, so the chain is this walk and nothing else. A row is dropped
57
+ * whenever it cannot have a canonical path: no id or no slug, or a `parentId`
58
+ * naming a row this list does not hold (a category whose parent was
59
+ * unpublished) — a path built over that gap would address a different category,
60
+ * so the subtree under such a row is dropped with it. The **first** row wins a
61
+ * duplicate path, the same rule the slug lookups in the kit already use.
62
+ */
63
+ export declare function buildCategoryTree(docs: readonly CatalogDoc[]): ReadonlyMap<string, CatalogCategoryNode>;
64
+ /**
65
+ * A placed category as the binding paths a `catalog:category` route template
66
+ * addresses: `slug`, `title`, `path`,
67
+ * `ancestors[]` and `children[]` are always present, because a template binds
68
+ * them and an absent path renders as nothing.
69
+ *
70
+ * `description` and `productCount` are carried **only when the public read
71
+ * carried them**, which is the one place this projection differs from the
72
+ * product's and the collection's. The catalog category model may have neither,
73
+ * and a key invented here would bind a template to an empty value for every
74
+ * category on every site that does not have one. `description` is **plain
75
+ * text** — a string, like a collection's and unlike a product's rich-text
76
+ * document — so a non-string is no description at all rather than something a
77
+ * text template would render as `[object Object]`.
78
+ */
79
+ export declare function projectCategoryNode(node: CatalogCategoryNode): EntryDoc;
80
+ /**
81
+ * The category a canonical path names, or null.
82
+ *
83
+ * **Canonical only, no redirects**: the path's segments must be exactly a
84
+ * root→descendant slug chain, so a leaf on its own (`/categories/bilstolar`), a
85
+ * wrong parent and a trailing extra segment are all misses — and a miss is the
86
+ * theme's not-found shell, not an error.
87
+ */
88
+ export declare function findCategoryByPath(tree: ReadonlyMap<string, CatalogCategoryNode>, path: string): CatalogCategoryNode | null;
89
+ /** Read one catalog object by slug and project it. A 404 is the caller's to
90
+ * handle — it is the not-found shell, not an error.
91
+ *
92
+ * A **category** is resolved differently and deliberately: there is no read that
93
+ * takes a path, so the whole category list is read (cached per request by
94
+ * `listCatalogDocs`'s caller) and the path's segments are walked down the tree
95
+ * by slug. A reader with no `listCategories` resolves none, which is the same
96
+ * answer as a path no category occupies. */
97
+ export declare function loadCatalogEntry(client: EldraClient, kind: CatalogRouteKind, slug: string, locale?: string): Promise<EntryDoc | null>;
98
+ /** Page through every catalog object a storefront route may exist for. The
99
+ * product list endpoint filters on status server-side; the collection list
100
+ * serves published collections only and exposes no status field, so anything
101
+ * it does report is filtered again below, client-side.
102
+ *
103
+ * The **category** list is optional on the reader (`EldraCatalogReader`), so one
104
+ * that predates it answers no categories at all — which is the same answer as a
105
+ * store with none, and leaves a category template generating nothing rather than
106
+ * failing the build. */
107
+ export declare function listCatalogDocs(client: EldraClient, kind: CatalogRouteKind, locale?: string): Promise<CatalogDoc[]>;
108
+ /**
109
+ * Turn catalog documents into the routes a template generates. A slug that
110
+ * cannot become a path is skipped with a warning naming it; the build goes on,
111
+ * because one unusable merchant record must not cost every other page.
112
+ *
113
+ * A **category** template generates one route per **canonical path** rather than
114
+ * per slug, because that is the only path its route answers: the tree is built
115
+ * from the same list and a row it cannot place — a missing field, a parent the
116
+ * list does not hold — has no route at all, which is exactly what the resolver
117
+ * would answer for it at request time.
118
+ */
119
+ export declare function catalogDocRoutes(kind: CatalogRouteKind, docs: readonly CatalogDoc[], pattern: string, warn?: (message: string) => void): string[];
@@ -0,0 +1,226 @@
1
+ import {
2
+ buildDynamicRoutePath
3
+ } from "@eldrajs/theme-core";
4
+ import { localeQuery } from "./locale.js";
5
+ const CATALOG_PAGE_SIZE = 100;
6
+ const ACTIVE_STATUS = "ACTIVE";
7
+ export function projectCatalogEntry(kind, doc) {
8
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return null;
9
+ const raw = doc;
10
+ const id = text(raw.id);
11
+ if (id === "") return null;
12
+ return {
13
+ id,
14
+ data: kind === "product" ? productProjection(raw) : collectionProjection(raw)
15
+ };
16
+ }
17
+ function productProjection(raw) {
18
+ return {
19
+ slug: text(raw.slug),
20
+ title: text(raw.title),
21
+ // Rich text: handed to the theme's rich-text renderer unchanged.
22
+ description: raw.description ?? null,
23
+ status: text(raw.status),
24
+ categoryId: optionalText(raw.categoryId),
25
+ tags: stringList(raw.tags),
26
+ variants: list(raw.variants).map((variant) => ({
27
+ sku: text(variant.sku),
28
+ price: optionalNumber(variant.price),
29
+ compareAtPrice: optionalNumber(variant.compareAtPrice),
30
+ optionValues: list(variant.optionValues).map((value) => ({
31
+ id: text(value.id),
32
+ name: text(value.name),
33
+ optionId: text(value.optionId),
34
+ optionValueId: text(value.optionValueId)
35
+ }))
36
+ })),
37
+ images: mediaList(raw.mediaLinks)
38
+ };
39
+ }
40
+ function collectionProjection(raw) {
41
+ return {
42
+ slug: text(raw.slug),
43
+ title: text(raw.title),
44
+ description: optionalText(raw.description),
45
+ productCount: typeof raw.productCount === "number" ? raw.productCount : 0,
46
+ image: mediaItem(raw.image)
47
+ };
48
+ }
49
+ const MAX_CATEGORY_DEPTH = 6;
50
+ export function buildCategoryTree(docs) {
51
+ const rows = /* @__PURE__ */ new Map();
52
+ const order = [];
53
+ for (const doc of docs) {
54
+ const id = text(doc.id);
55
+ const slug = text(doc.slug);
56
+ const title = text(doc.title);
57
+ if (id === "" || slug === "" || rows.has(id)) continue;
58
+ const row = { id, slug, title, parentId: optionalText(doc.parentId), raw: doc };
59
+ rows.set(id, row);
60
+ order.push(row);
61
+ }
62
+ const chainOf = (row) => {
63
+ const chain = [];
64
+ const seen = /* @__PURE__ */ new Set([row.id]);
65
+ let parentId = row.parentId;
66
+ for (let depth = 0; depth < MAX_CATEGORY_DEPTH; depth += 1) {
67
+ if (parentId === null) return chain;
68
+ if (seen.has(parentId)) return null;
69
+ const parent = rows.get(parentId);
70
+ if (parent === void 0) return null;
71
+ seen.add(parentId);
72
+ chain.unshift(parent);
73
+ parentId = parent.parentId;
74
+ }
75
+ return null;
76
+ };
77
+ const chains = /* @__PURE__ */ new Map();
78
+ const pathOf = /* @__PURE__ */ new Map();
79
+ for (const row of order) {
80
+ const chain = chainOf(row);
81
+ if (chain === null) continue;
82
+ chains.set(row.id, chain);
83
+ pathOf.set(row.id, [...chain, row].map((level) => level.slug).join("/"));
84
+ }
85
+ const childrenOf = /* @__PURE__ */ new Map();
86
+ for (const row of order) {
87
+ const parentId = row.parentId;
88
+ if (parentId === null || !pathOf.has(row.id) || !pathOf.has(parentId)) continue;
89
+ const siblings = childrenOf.get(parentId);
90
+ if (siblings === void 0) childrenOf.set(parentId, [row]);
91
+ else siblings.push(row);
92
+ }
93
+ const refOf = (row) => ({
94
+ slug: row.slug,
95
+ title: row.title,
96
+ path: pathOf.get(row.id) ?? ""
97
+ });
98
+ const tree = /* @__PURE__ */ new Map();
99
+ for (const row of order) {
100
+ const path = pathOf.get(row.id);
101
+ if (path === void 0 || tree.has(path)) continue;
102
+ tree.set(path, {
103
+ id: row.id,
104
+ slug: row.slug,
105
+ title: row.title,
106
+ path,
107
+ ancestors: (chains.get(row.id) ?? []).map(refOf),
108
+ children: (childrenOf.get(row.id) ?? []).map(refOf),
109
+ raw: row.raw
110
+ });
111
+ }
112
+ return tree;
113
+ }
114
+ export function projectCategoryNode(node) {
115
+ const description = node.raw.description;
116
+ const productCount = node.raw.productCount;
117
+ return {
118
+ id: node.id,
119
+ data: {
120
+ slug: node.slug,
121
+ title: node.title,
122
+ path: node.path,
123
+ ancestors: node.ancestors.map(plainRef),
124
+ children: node.children.map(plainRef),
125
+ ...typeof description === "string" && description !== "" ? { description } : {},
126
+ ...typeof productCount === "number" ? { productCount } : {}
127
+ }
128
+ };
129
+ }
130
+ function plainRef(ref) {
131
+ return { slug: ref.slug, title: ref.title, path: ref.path };
132
+ }
133
+ export function findCategoryByPath(tree, path) {
134
+ return tree.get(path) ?? null;
135
+ }
136
+ export async function loadCatalogEntry(client, kind, slug, locale) {
137
+ const query = localeQuery(locale);
138
+ if (kind === "category") {
139
+ const node = findCategoryByPath(
140
+ buildCategoryTree(await listCatalogDocs(client, "category", locale)),
141
+ slug
142
+ );
143
+ return node === null ? null : projectCategoryNode(node);
144
+ }
145
+ const doc = kind === "product" ? await client.catalog.getProduct(slug, query) : await client.catalog.getCollection(slug, query);
146
+ return projectCatalogEntry(kind, doc);
147
+ }
148
+ export async function listCatalogDocs(client, kind, locale) {
149
+ const listCategories = client.catalog.listCategories?.bind(client.catalog);
150
+ if (kind === "category" && listCategories === void 0) return [];
151
+ const docs = [];
152
+ let page = 1;
153
+ for (; ; ) {
154
+ const query = { page, pageSize: CATALOG_PAGE_SIZE, ...localeQuery(locale) };
155
+ const list2 = kind === "product" ? await client.catalog.listProducts({ ...query, filter: [`status:eq:${ACTIVE_STATUS}`] }) : kind === "collection" ? await client.catalog.listCollections(query) : await listCategories(query);
156
+ docs.push(...list2.data);
157
+ if (list2.meta.hasNext !== true || list2.data.length === 0) return docs;
158
+ page += 1;
159
+ }
160
+ }
161
+ export function catalogDocRoutes(kind, docs, pattern, warn = (message) => console.warn(message)) {
162
+ const paths = [];
163
+ if (kind === "category") {
164
+ for (const node of buildCategoryTree(docs).values()) {
165
+ const path = buildDynamicRoutePath(pattern, node.path);
166
+ if (path === null) {
167
+ warn(
168
+ `[eldra] skipped ${routeLabel(pattern, node.path)}: unusable category path ${JSON.stringify(node.path)}`
169
+ );
170
+ continue;
171
+ }
172
+ paths.push(path);
173
+ }
174
+ return paths;
175
+ }
176
+ for (const doc of docs) {
177
+ if (!isActive(doc)) continue;
178
+ const path = buildDynamicRoutePath(pattern, doc.slug);
179
+ if (path === null) {
180
+ warn(
181
+ `[eldra] skipped ${routeLabel(pattern, doc.slug)}: unusable catalog slug ${JSON.stringify(
182
+ text(doc.slug)
183
+ )}`
184
+ );
185
+ continue;
186
+ }
187
+ paths.push(path);
188
+ }
189
+ return paths;
190
+ }
191
+ function isActive(doc) {
192
+ const status = doc.status;
193
+ return typeof status !== "string" || status.toUpperCase() === ACTIVE_STATUS;
194
+ }
195
+ function routeLabel(pattern, slug) {
196
+ return `${pattern.replace(/:[^/]*$/, "")}${text(slug)}`;
197
+ }
198
+ function mediaList(value) {
199
+ return list(value).filter((item) => text(item.url) !== "").map((item, index) => ({ item, index })).sort((a, b) => sortOrder(a.item) - sortOrder(b.item) || a.index - b.index).map(({ item }) => ({ url: text(item.url), alt: text(item.altText) }));
200
+ }
201
+ function mediaItem(value) {
202
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
203
+ const record = value;
204
+ const url = text(record.url);
205
+ return url === "" ? null : { url, alt: text(record.altText) };
206
+ }
207
+ function sortOrder(item) {
208
+ return typeof item.sortOrder === "number" ? item.sortOrder : Number.MAX_SAFE_INTEGER;
209
+ }
210
+ function list(value) {
211
+ return Array.isArray(value) ? value.filter(
212
+ (item) => typeof item === "object" && item !== null && !Array.isArray(item)
213
+ ) : [];
214
+ }
215
+ function stringList(value) {
216
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
217
+ }
218
+ function text(value) {
219
+ return typeof value === "string" ? value : "";
220
+ }
221
+ function optionalText(value) {
222
+ return typeof value === "string" && value !== "" ? value : null;
223
+ }
224
+ function optionalNumber(value) {
225
+ return typeof value === "number" ? value : null;
226
+ }