@teleporthq/teleport-plugin-next-data-source 0.43.62 → 0.43.64
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/__tests__/blog-post-categories.test.ts +131 -0
- package/__tests__/custom-page-transform.test.ts +119 -0
- package/__tests__/ecommerce-product-ratings.test.ts +155 -0
- package/__tests__/ecommerce-product-storefront-contract.test.ts +147 -0
- package/__tests__/filter-groups.test.ts +174 -0
- package/__tests__/product-reviews-structured-data.test.ts +196 -0
- package/dist/cjs/data-source-fetchers.d.ts +3 -3
- package/dist/cjs/data-source-fetchers.d.ts.map +1 -1
- package/dist/cjs/data-source-fetchers.js.map +1 -1
- package/dist/cjs/fetchers/airtable.d.ts.map +1 -1
- package/dist/cjs/fetchers/airtable.js +1 -1
- package/dist/cjs/fetchers/airtable.js.map +1 -1
- package/dist/cjs/fetchers/clickhouse.d.ts.map +1 -1
- package/dist/cjs/fetchers/clickhouse.js +1 -1
- package/dist/cjs/fetchers/clickhouse.js.map +1 -1
- package/dist/cjs/fetchers/csv-file.d.ts.map +1 -1
- package/dist/cjs/fetchers/csv-file.js +3 -3
- package/dist/cjs/fetchers/csv-file.js.map +1 -1
- package/dist/cjs/fetchers/firestore.d.ts.map +1 -1
- package/dist/cjs/fetchers/firestore.js +1 -1
- package/dist/cjs/fetchers/firestore.js.map +1 -1
- package/dist/cjs/fetchers/google-sheets.d.ts.map +1 -1
- package/dist/cjs/fetchers/google-sheets.js +1 -1
- package/dist/cjs/fetchers/google-sheets.js.map +1 -1
- package/dist/cjs/fetchers/javascript.d.ts.map +1 -1
- package/dist/cjs/fetchers/javascript.js +1 -1
- package/dist/cjs/fetchers/javascript.js.map +1 -1
- package/dist/cjs/fetchers/mariadb.d.ts.map +1 -1
- package/dist/cjs/fetchers/mariadb.js +1 -1
- package/dist/cjs/fetchers/mariadb.js.map +1 -1
- package/dist/cjs/fetchers/mongodb.d.ts.map +1 -1
- package/dist/cjs/fetchers/mongodb.js +1 -1
- package/dist/cjs/fetchers/mongodb.js.map +1 -1
- package/dist/cjs/fetchers/mysql.d.ts.map +1 -1
- package/dist/cjs/fetchers/mysql.js +1 -1
- package/dist/cjs/fetchers/mysql.js.map +1 -1
- package/dist/cjs/fetchers/postgresql.d.ts.map +1 -1
- package/dist/cjs/fetchers/postgresql.js +1 -1
- package/dist/cjs/fetchers/postgresql.js.map +1 -1
- package/dist/cjs/fetchers/redis.d.ts.map +1 -1
- package/dist/cjs/fetchers/redis.js +1 -1
- package/dist/cjs/fetchers/redis.js.map +1 -1
- package/dist/cjs/fetchers/redshift.d.ts.map +1 -1
- package/dist/cjs/fetchers/redshift.js +2 -2
- package/dist/cjs/fetchers/redshift.js.map +1 -1
- package/dist/cjs/fetchers/rest-api.d.ts.map +1 -1
- package/dist/cjs/fetchers/rest-api.js +2 -2
- package/dist/cjs/fetchers/rest-api.js.map +1 -1
- package/dist/cjs/fetchers/supabase.d.ts.map +1 -1
- package/dist/cjs/fetchers/supabase.js +1 -1
- package/dist/cjs/fetchers/supabase.js.map +1 -1
- package/dist/cjs/fetchers/teleport.d.ts +2 -2
- package/dist/cjs/fetchers/teleport.d.ts.map +1 -1
- package/dist/cjs/fetchers/teleport.js +1 -1
- package/dist/cjs/fetchers/teleport.js.map +1 -1
- package/dist/cjs/fetchers/turso.d.ts.map +1 -1
- package/dist/cjs/fetchers/turso.js +1 -1
- package/dist/cjs/fetchers/turso.js.map +1 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/pagination-plugin.d.ts.map +1 -1
- package/dist/cjs/pagination-plugin.js.map +1 -1
- package/dist/cjs/transformations/blog-post.d.ts +7 -1
- package/dist/cjs/transformations/blog-post.d.ts.map +1 -1
- package/dist/cjs/transformations/blog-post.js +4 -2
- package/dist/cjs/transformations/blog-post.js.map +1 -1
- package/dist/cjs/transformations/category-taxonomy.d.ts +33 -0
- package/dist/cjs/transformations/category-taxonomy.d.ts.map +1 -0
- package/dist/cjs/transformations/category-taxonomy.js +42 -0
- package/dist/cjs/transformations/category-taxonomy.js.map +1 -0
- package/dist/cjs/transformations/custom-page.d.ts +18 -0
- package/dist/cjs/transformations/custom-page.d.ts.map +1 -0
- package/dist/cjs/transformations/custom-page.js +24 -0
- package/dist/cjs/transformations/custom-page.js.map +1 -0
- package/dist/cjs/transformations/ecommerce-product.d.ts.map +1 -1
- package/dist/cjs/transformations/ecommerce-product.js +2 -35
- package/dist/cjs/transformations/ecommerce-product.js.map +1 -1
- package/dist/cjs/transformations/index.d.ts +23 -4
- package/dist/cjs/transformations/index.d.ts.map +1 -1
- package/dist/cjs/transformations/index.js +38 -8
- package/dist/cjs/transformations/index.js.map +1 -1
- package/dist/cjs/transformations/shared-utils.d.ts.map +1 -1
- package/dist/cjs/transformations/shared-utils.js +1 -1
- package/dist/cjs/transformations/shared-utils.js.map +1 -1
- package/dist/cjs/tsconfig.tsbuildinfo +1 -1
- package/dist/cjs/utils.d.ts +35 -3
- package/dist/cjs/utils.d.ts.map +1 -1
- package/dist/cjs/utils.js +116 -18
- package/dist/cjs/utils.js.map +1 -1
- package/dist/esm/data-source-fetchers.d.ts +3 -3
- package/dist/esm/data-source-fetchers.d.ts.map +1 -1
- package/dist/esm/data-source-fetchers.js.map +1 -1
- package/dist/esm/fetchers/airtable.d.ts.map +1 -1
- package/dist/esm/fetchers/airtable.js +2 -2
- package/dist/esm/fetchers/airtable.js.map +1 -1
- package/dist/esm/fetchers/clickhouse.d.ts.map +1 -1
- package/dist/esm/fetchers/clickhouse.js +2 -2
- package/dist/esm/fetchers/clickhouse.js.map +1 -1
- package/dist/esm/fetchers/csv-file.d.ts.map +1 -1
- package/dist/esm/fetchers/csv-file.js +4 -4
- package/dist/esm/fetchers/csv-file.js.map +1 -1
- package/dist/esm/fetchers/firestore.d.ts.map +1 -1
- package/dist/esm/fetchers/firestore.js +2 -2
- package/dist/esm/fetchers/firestore.js.map +1 -1
- package/dist/esm/fetchers/google-sheets.d.ts.map +1 -1
- package/dist/esm/fetchers/google-sheets.js +2 -2
- package/dist/esm/fetchers/google-sheets.js.map +1 -1
- package/dist/esm/fetchers/javascript.d.ts.map +1 -1
- package/dist/esm/fetchers/javascript.js +2 -2
- package/dist/esm/fetchers/javascript.js.map +1 -1
- package/dist/esm/fetchers/mariadb.d.ts.map +1 -1
- package/dist/esm/fetchers/mariadb.js +2 -2
- package/dist/esm/fetchers/mariadb.js.map +1 -1
- package/dist/esm/fetchers/mongodb.d.ts.map +1 -1
- package/dist/esm/fetchers/mongodb.js +2 -2
- package/dist/esm/fetchers/mongodb.js.map +1 -1
- package/dist/esm/fetchers/mysql.d.ts.map +1 -1
- package/dist/esm/fetchers/mysql.js +2 -2
- package/dist/esm/fetchers/mysql.js.map +1 -1
- package/dist/esm/fetchers/postgresql.d.ts.map +1 -1
- package/dist/esm/fetchers/postgresql.js +2 -2
- package/dist/esm/fetchers/postgresql.js.map +1 -1
- package/dist/esm/fetchers/redis.d.ts.map +1 -1
- package/dist/esm/fetchers/redis.js +2 -2
- package/dist/esm/fetchers/redis.js.map +1 -1
- package/dist/esm/fetchers/redshift.d.ts.map +1 -1
- package/dist/esm/fetchers/redshift.js +3 -3
- package/dist/esm/fetchers/redshift.js.map +1 -1
- package/dist/esm/fetchers/rest-api.d.ts.map +1 -1
- package/dist/esm/fetchers/rest-api.js +3 -3
- package/dist/esm/fetchers/rest-api.js.map +1 -1
- package/dist/esm/fetchers/supabase.d.ts.map +1 -1
- package/dist/esm/fetchers/supabase.js +2 -2
- package/dist/esm/fetchers/supabase.js.map +1 -1
- package/dist/esm/fetchers/teleport.d.ts +2 -2
- package/dist/esm/fetchers/teleport.d.ts.map +1 -1
- package/dist/esm/fetchers/teleport.js +2 -2
- package/dist/esm/fetchers/teleport.js.map +1 -1
- package/dist/esm/fetchers/turso.d.ts.map +1 -1
- package/dist/esm/fetchers/turso.js +2 -2
- package/dist/esm/fetchers/turso.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/pagination-plugin.d.ts.map +1 -1
- package/dist/esm/pagination-plugin.js +1 -1
- package/dist/esm/pagination-plugin.js.map +1 -1
- package/dist/esm/transformations/blog-post.d.ts +7 -1
- package/dist/esm/transformations/blog-post.d.ts.map +1 -1
- package/dist/esm/transformations/blog-post.js +4 -2
- package/dist/esm/transformations/blog-post.js.map +1 -1
- package/dist/esm/transformations/category-taxonomy.d.ts +33 -0
- package/dist/esm/transformations/category-taxonomy.d.ts.map +1 -0
- package/dist/esm/transformations/category-taxonomy.js +37 -0
- package/dist/esm/transformations/category-taxonomy.js.map +1 -0
- package/dist/esm/transformations/custom-page.d.ts +18 -0
- package/dist/esm/transformations/custom-page.d.ts.map +1 -0
- package/dist/esm/transformations/custom-page.js +20 -0
- package/dist/esm/transformations/custom-page.js.map +1 -0
- package/dist/esm/transformations/ecommerce-product.d.ts.map +1 -1
- package/dist/esm/transformations/ecommerce-product.js +3 -36
- package/dist/esm/transformations/ecommerce-product.js.map +1 -1
- package/dist/esm/transformations/index.d.ts +23 -4
- package/dist/esm/transformations/index.d.ts.map +1 -1
- package/dist/esm/transformations/index.js +37 -7
- package/dist/esm/transformations/index.js.map +1 -1
- package/dist/esm/transformations/shared-utils.d.ts.map +1 -1
- package/dist/esm/transformations/shared-utils.js +1 -1
- package/dist/esm/transformations/shared-utils.js.map +1 -1
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/dist/esm/utils.d.ts +35 -3
- package/dist/esm/utils.d.ts.map +1 -1
- package/dist/esm/utils.js +112 -17
- package/dist/esm/utils.js.map +1 -1
- package/package.json +5 -5
- package/src/data-source-fetchers.ts +3 -3
- package/src/fetchers/airtable.ts +35 -36
- package/src/fetchers/clickhouse.ts +26 -36
- package/src/fetchers/csv-file.ts +13 -21
- package/src/fetchers/firestore.ts +41 -35
- package/src/fetchers/google-sheets.ts +15 -23
- package/src/fetchers/javascript.ts +11 -21
- package/src/fetchers/mariadb.ts +33 -44
- package/src/fetchers/mongodb.ts +66 -81
- package/src/fetchers/mysql.ts +33 -45
- package/src/fetchers/postgresql.ts +52 -62
- package/src/fetchers/redis.ts +6 -5
- package/src/fetchers/redshift.ts +29 -41
- package/src/fetchers/rest-api.ts +11 -21
- package/src/fetchers/supabase.ts +104 -41
- package/src/fetchers/teleport.ts +55 -66
- package/src/fetchers/turso.ts +27 -39
- package/src/index.ts +1 -1
- package/src/pagination-plugin.ts +3 -6
- package/src/transformations/blog-post.ts +28 -9
- package/src/transformations/category-taxonomy.ts +107 -0
- package/src/transformations/custom-page.ts +83 -0
- package/src/transformations/ecommerce-product.ts +177 -78
- package/src/transformations/index.ts +85 -11
- package/src/transformations/shared-utils.ts +9 -0
- package/src/utils.ts +191 -34
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateCategoryTaxonomyCode = exports.flattenCategoriesById = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Flattens the nested category tree into an `id -> {name, slug, translations}`
|
|
6
|
+
* lookup map. `translations` is carried through UNRESOLVED (a per-language
|
|
7
|
+
* `{name, description}` map) so the transform can resolve it against the SAME
|
|
8
|
+
* per-request `currentLanguage`/`mainLanguage` used for every other i18n field —
|
|
9
|
+
* `slug` is never localized (it is the language-neutral join key). Tolerant of a
|
|
10
|
+
* missing/malformed tree.
|
|
11
|
+
*/
|
|
12
|
+
var flattenCategoriesById = function (categories) {
|
|
13
|
+
var byId = {};
|
|
14
|
+
var visit = function (nodes) {
|
|
15
|
+
if (!Array.isArray(nodes)) {
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
|
|
19
|
+
var node = nodes_1[_i];
|
|
20
|
+
if (node && typeof node.id === 'string') {
|
|
21
|
+
byId[node.id] = {
|
|
22
|
+
name: node.name || '',
|
|
23
|
+
slug: node.slug || '',
|
|
24
|
+
translations: node.translations,
|
|
25
|
+
};
|
|
26
|
+
visit(node.children);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
visit(categories);
|
|
31
|
+
return byId;
|
|
32
|
+
};
|
|
33
|
+
exports.flattenCategoriesById = flattenCategoriesById;
|
|
34
|
+
/**
|
|
35
|
+
* The baked map plus the `resolveCategoryName` helper the transforms call.
|
|
36
|
+
* Emitted once per fetcher file — the two entity transforms are never
|
|
37
|
+
* concatenated into the same file (`getTransformationCode` picks one per table),
|
|
38
|
+
* so the helper name is unambiguous.
|
|
39
|
+
*/
|
|
40
|
+
var generateCategoryTaxonomyCode = function (mapVarName, categories) { return "\n// Category taxonomy (id -> {name, slug, translations}), baked in at export\n// time \u2014 see flattenCategoriesById in category-taxonomy.ts. Empty when the\n// project has no taxonomy, or the row's category_ids simply resolve to nothing.\nvar ".concat(mapVarName, " = ").concat(JSON.stringify((0, exports.flattenCategoriesById)(categories)), "\n\n// Resolve a baked category's name to currentLang/mainLang from its\n// translations map (same per-request locale as every other i18n field via\n// resolveI18nField), falling back to the main-language name.\nfunction resolveCategoryName(categoryInfo, currentLang, mainLang) {\n if (currentLang && mainLang && currentLang !== mainLang && categoryInfo.translations) {\n var override = categoryInfo.translations[currentLang]\n if (override && override.name) return override.name\n }\n return categoryInfo.name\n}\n\n// The row's assigned category ids -> resolved {id, name, slug} objects, in the\n// order they were assigned. Ids that resolve to nothing (a deleted category) are\n// silently dropped. MUST mirror resolveAssignedCategories in the editor\n// (teleport-gui features/shared/taxonomy/category-tree.ts), which is what the\n// canvas renders from.\nfunction resolveAssignedCategories(categoryIdsRaw, byId, currentLang, mainLang, legacyName) {\n var ids = parseJsonArray(categoryIdsRaw)\n var out = []\n for (var ci = 0; ci < ids.length; ci++) {\n var info = byId[ids[ci]]\n if (!info) continue\n out.push({\n id: ids[ci],\n name: resolveCategoryName(info, currentLang, mainLang),\n slug: info.slug,\n })\n }\n // A row that predates the id column, or one imported with only a name, still\n // shows what it carries \u2014 with an EMPTY id, so a filter link built from it\n // carries no value and every listing reads that as \"no filter\".\n if (out.length === 0 && typeof legacyName === 'string' && legacyName.trim()) {\n var trimmed = legacyName.trim()\n out.push({\n id: '',\n name: trimmed,\n slug: trimmed.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'category',\n })\n }\n return out\n}\n"); };
|
|
41
|
+
exports.generateCategoryTaxonomyCode = generateCategoryTaxonomyCode;
|
|
42
|
+
//# sourceMappingURL=category-taxonomy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"category-taxonomy.js","sourceRoot":"","sources":["../../../src/transformations/category-taxonomy.ts"],"names":[],"mappings":";;;AAmBA;;;;;;;GAOG;AACI,IAAM,qBAAqB,GAAG,UACnC,UAA+C;IAE/C,IAAM,IAAI,GAAsC,EAAE,CAAA;IAClD,IAAM,KAAK,GAAG,UAAC,KAA0C;QACvD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACzB,OAAM;SACP;QACD,KAAmB,UAAK,EAAL,eAAK,EAAL,mBAAK,EAAL,IAAK,EAAE;YAArB,IAAM,IAAI,cAAA;YACb,IAAI,IAAI,IAAI,OAAO,IAAI,CAAC,EAAE,KAAK,QAAQ,EAAE;gBACvC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG;oBACd,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,EAAE;oBACrB,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,EAAE;oBACrB,YAAY,EAAE,IAAI,CAAC,YAAY;iBAChC,CAAA;gBACD,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;aACrB;SACF;IACH,CAAC,CAAA;IACD,KAAK,CAAC,UAAU,CAAC,CAAA;IACjB,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AArBY,QAAA,qBAAqB,yBAqBjC;AAED;;;;;GAKG;AACI,IAAM,4BAA4B,GAAG,UAC1C,UAAkB,EAClB,UAA+C,IACpC,OAAA,iQAIP,UAAU,gBAAM,IAAI,CAAC,SAAS,CAAC,IAAA,6BAAqB,EAAC,UAAU,CAAC,CAAC,4wDA2CtE,EA/CY,CA+CZ,CAAA;AAlDY,QAAA,4BAA4B,gCAkDxC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generates JavaScript code for the `teleport_pages` row transformation — the
|
|
3
|
+
* rows the Custom Pages feature stores from its admin panel.
|
|
4
|
+
*
|
|
5
|
+
* The raw row is kept whole (every column, snake_case) and the SEO fields are
|
|
6
|
+
* normalised beside it under camelCase names, the same way the blog post
|
|
7
|
+
* transform exposes its per-post overrides. That is what lets the page's
|
|
8
|
+
* `<Head>` bind `metaTitle` / `robotsContent` / `canonicalUrl` / the Open Graph
|
|
9
|
+
* fields with plain `??` fallbacks, and lets getStaticProps answer the row's
|
|
10
|
+
* own redirect — without a single table-specific branch in the head or the
|
|
11
|
+
* static-props generators.
|
|
12
|
+
*
|
|
13
|
+
* `metaTitle` falls back to `title`: the column is nullable so an author who
|
|
14
|
+
* never filled it in still gets a real `<title>`, and `ogTitle`/`ogDescription`
|
|
15
|
+
* fall back to the meta pair for the same reason.
|
|
16
|
+
*/
|
|
17
|
+
export declare const generateCustomPageTransformationCode: () => string;
|
|
18
|
+
//# sourceMappingURL=custom-page.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"custom-page.d.ts","sourceRoot":"","sources":["../../../src/transformations/custom-page.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,oCAAoC,QAAO,MAkEvD,CAAA"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateCustomPageTransformationCode = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Generates JavaScript code for the `teleport_pages` row transformation — the
|
|
6
|
+
* rows the Custom Pages feature stores from its admin panel.
|
|
7
|
+
*
|
|
8
|
+
* The raw row is kept whole (every column, snake_case) and the SEO fields are
|
|
9
|
+
* normalised beside it under camelCase names, the same way the blog post
|
|
10
|
+
* transform exposes its per-post overrides. That is what lets the page's
|
|
11
|
+
* `<Head>` bind `metaTitle` / `robotsContent` / `canonicalUrl` / the Open Graph
|
|
12
|
+
* fields with plain `??` fallbacks, and lets getStaticProps answer the row's
|
|
13
|
+
* own redirect — without a single table-specific branch in the head or the
|
|
14
|
+
* static-props generators.
|
|
15
|
+
*
|
|
16
|
+
* `metaTitle` falls back to `title`: the column is nullable so an author who
|
|
17
|
+
* never filled it in still gets a real `<title>`, and `ogTitle`/`ogDescription`
|
|
18
|
+
* fall back to the meta pair for the same reason.
|
|
19
|
+
*/
|
|
20
|
+
var generateCustomPageTransformationCode = function () {
|
|
21
|
+
return "\n// ============================================================\n// Custom Page Transformation\n// ============================================================\n\nfunction buildCustomPage(record, options) {\n if (!record || typeof record !== 'object') return record\n options = options || {}\n var assetMap = options.assetMap || {}\n\n // Every stored column travels through untouched \u2014 the blocks column above\n // all, which the page's array mapper parses \u2014 and the normalised SEO fields\n // are added beside them.\n var out = {}\n for (var key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) out[key] = record[key]\n }\n\n var title = typeof record.title === 'string' ? record.title : ''\n var metaTitle = normalizeSeoTextField(pickFirst(record.meta_title, record.metaTitle)) || title || null\n var metaDescription = normalizeSeoTextField(pickFirst(record.meta_description, record.metaDescription))\n\n var noIndex = coerceBoolean(pickFirst(record.no_index, record.noIndex), false)\n var canonicalUrl = normalizeSeoUrlField(pickFirst(record.canonical_url, record.canonicalUrl))\n var redirectUrl = normalizeSeoUrlField(pickFirst(record.redirect_url, record.redirectUrl))\n var rawRedirectType = pickFirst(record.redirect_type, record.redirectType)\n var redirectType =\n redirectUrl && (rawRedirectType === '301' || rawRedirectType === '302')\n ? rawRedirectType\n : null\n // null \u2014 never '' or false \u2014 for unset rows, so the page-level fallback (the\n // `??` in the generated Head) can take over.\n var robotsContent = noIndex ? 'noindex' : null\n\n var ogTitle = normalizeSeoTextField(pickFirst(record.og_title, record.ogTitle)) || metaTitle\n var ogDescription =\n normalizeSeoTextField(pickFirst(record.og_description, record.ogDescription)) || metaDescription\n var rawOgImage = normalizeSeoUrlField(pickFirst(record.og_image, record.ogImage))\n var ogImage = rawOgImage ? resolveAssetUrl(rawOgImage, assetMap) || rawOgImage : null\n\n out.metaTitle = metaTitle\n out.metaDescription = metaDescription\n out.noIndex = noIndex\n out.canonicalUrl = canonicalUrl\n out.redirectUrl = redirectUrl\n out.redirectType = redirectType\n out.robotsContent = robotsContent\n out.ogTitle = ogTitle\n out.ogDescription = ogDescription\n out.ogImage = ogImage\n return out\n}\n\nfunction transformCustomPages(records, options) {\n if (!Array.isArray(records)) return []\n return records.map(function(record) { return buildCustomPage(record, options) })\n}\n\n// Trims a free-text SEO cell; blank/non-string values become null.\nfunction normalizeSeoTextField(value) {\n if (typeof value !== 'string') return null\n var trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n";
|
|
22
|
+
};
|
|
23
|
+
exports.generateCustomPageTransformationCode = generateCustomPageTransformationCode;
|
|
24
|
+
//# sourceMappingURL=custom-page.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"custom-page.js","sourceRoot":"","sources":["../../../src/transformations/custom-page.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;GAeG;AACI,IAAM,oCAAoC,GAAG;IAClD,OAAO,yuFAgER,CAAA;AACD,CAAC,CAAA;AAlEY,QAAA,oCAAoC,wCAkEhD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ecommerce-product.d.ts","sourceRoot":"","sources":["../../../src/transformations/ecommerce-product.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"ecommerce-product.d.ts","sourceRoot":"","sources":["../../../src/transformations/ecommerce-product.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;AAIvE;;;;GAIG;AACH,MAAM,WAAW,gCAAgC;IAC/C,+EAA+E;IAC/E,UAAU,CAAC,EAAE,qBAAqB,EAAE,CAAA;IACpC;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B;;;;;;;;;;OAUG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED;;;;GAIG;AACH,eAAO,MAAM,0CAA0C,aAC5C,gCAAgC,KACxC,MAi9BF,CAAA"}
|
|
@@ -2,39 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.generateEcommerceProductTransformationCode = void 0;
|
|
4
4
|
var teleport_shared_1 = require("@teleporthq/teleport-shared");
|
|
5
|
-
|
|
6
|
-
* Flattens the nested category tree (`ecommerceSettings.categories`, baked at
|
|
7
|
-
* export time) into an `id -> {name, slug, translations}` lookup map,
|
|
8
|
-
* JSON-embedded into the generated transform below so a product's
|
|
9
|
-
* `category_ids` can be resolved to display names with no runtime DB lookup
|
|
10
|
-
* (there is no DB table for the taxonomy — it lives only in the UIDL).
|
|
11
|
-
* `translations` is carried through unresolved (a per-language `{name,
|
|
12
|
-
* description}` map) so `buildEcommerceProduct` can resolve it against the
|
|
13
|
-
* SAME per-request `currentLanguage`/`mainLanguage` used for every other i18n
|
|
14
|
-
* field — `slug` is never localized (it's the language-neutral join key).
|
|
15
|
-
* Tolerant of a missing/malformed tree.
|
|
16
|
-
*/
|
|
17
|
-
var flattenCategoriesById = function (categories) {
|
|
18
|
-
var byId = {};
|
|
19
|
-
var visit = function (nodes) {
|
|
20
|
-
if (!Array.isArray(nodes)) {
|
|
21
|
-
return;
|
|
22
|
-
}
|
|
23
|
-
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
|
|
24
|
-
var node = nodes_1[_i];
|
|
25
|
-
if (node && typeof node.id === 'string') {
|
|
26
|
-
byId[node.id] = {
|
|
27
|
-
name: node.name || '',
|
|
28
|
-
slug: node.slug || '',
|
|
29
|
-
translations: node.translations,
|
|
30
|
-
};
|
|
31
|
-
visit(node.children);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
|
-
visit(categories);
|
|
36
|
-
return byId;
|
|
37
|
-
};
|
|
5
|
+
var category_taxonomy_1 = require("./category-taxonomy");
|
|
38
6
|
/**
|
|
39
7
|
* Generates JavaScript code for e-commerce product data transformation.
|
|
40
8
|
* Transforms raw snake_case database records into the camelCase shape
|
|
@@ -43,10 +11,9 @@ var flattenCategoriesById = function (categories) {
|
|
|
43
11
|
var generateEcommerceProductTransformationCode = function (options) {
|
|
44
12
|
var _a;
|
|
45
13
|
if (options === void 0) { options = {}; }
|
|
46
|
-
var categoriesByIdJson = JSON.stringify(flattenCategoriesById(options.categories));
|
|
47
14
|
var taxHelperCode = teleport_shared_1.StorefrontTax.generateStorefrontTaxHelperCode((_a = options.storefrontTaxRate) !== null && _a !== void 0 ? _a : 0);
|
|
48
15
|
var allowBackordersLiteral = options.allowBackorders === true ? 'true' : 'false';
|
|
49
|
-
return "\n".concat(taxHelperCode, "\n").concat(teleport_shared_1.ProductDiscounts.generateProductDiscountHelperCode(), "\n\n// Baked from the merchant's stock settings: TRUE when stock never blocks a\n// purchase (stock management off OR backorders allowed). Regenerating the\n// project refreshes it \u2014 do not hand-edit. See EcommerceProductTransformOptions.\nvar ALLOW_BACKORDERS = ").concat(allowBackordersLiteral, "\n\n// Category taxonomy (id -> {name, slug, translations}), baked in at export\n// time \u2014 see flattenCategoriesById in ecommerce-product.ts. Empty when the\n// store has no category taxonomy, or products.category_ids simply resolves\n// to nothing.\nvar PRODUCT_CATEGORIES_BY_ID = ").concat(categoriesByIdJson, "\n\n// Resolve a baked category's name to currentLang/mainLang from its\n// translations map (same per-request locale as every other i18n field via\n// resolveI18nField), falling back to the main-language name.\nfunction resolveCategoryName(categoryInfo, currentLang, mainLang) {\n if (currentLang && mainLang && currentLang !== mainLang && categoryInfo.translations) {\n var override = categoryInfo.translations[currentLang]\n if (override && override.name) return override.name\n }\n return categoryInfo.name\n}\n\n// The merchant's \"Show 3D model by default\" toggle, as every backend may hand\n// it back: a real boolean, 1/0, 'true'/'false'/'t'/'f' strings \u2014 and NULL /\n// absent / '' as ON, because a product that has a model shows it unless the\n// merchant switched it off. MUST mirror normalizeShowModelFlag in the GUI's\n// features/e-commerce/constants/product-model.ts.\nfunction normalizeShowModelFlag(raw) {\n if (raw === null || raw === undefined || raw === '') return true\n if (typeof raw === 'boolean') return raw\n if (typeof raw === 'number') return raw !== 0\n if (typeof raw === 'string') {\n var token = raw.trim().toLowerCase()\n return !(token === 'false' || token === 'f' || token === '0' || token === 'no' || token === 'off')\n }\n return true\n}\n\n// The product's media gallery in display order, HERO FIRST: the model when it\n// is shown by default, otherwise the images with the model last. Each entry is\n// { kind: 'image' | 'model', src, poster, thumbnail, alt }; 'thumbnail' is what\n// a strip draws and is never empty for an entry that can appear in one. MUST\n// mirror buildProductGalleryMedia in the GUI's\n// features/e-commerce/utils/product-gallery-media.ts.\nfunction buildProductGalleryMedia(params) {\n var imageItems = []\n for (var gi = 0; gi < params.images.length; gi++) {\n imageItems.push({\n kind: 'image',\n src: params.images[gi],\n poster: '',\n thumbnail: params.images[gi],\n alt: params.imageAlt || params.name,\n })\n }\n if (!params.modelUrl) return imageItems\n var modelItem = {\n kind: 'model',\n src: params.modelUrl,\n poster: params.modelPoster || '',\n thumbnail: params.modelPoster || params.mainImage || params.images[0] || '',\n alt: params.name,\n }\n return params.showModel === 'true' ? [modelItem].concat(imageItems) : imageItems.concat([modelItem])\n}\n\n// ============================================================\n// E-Commerce Product Transformation\n// ============================================================\n\nfunction buildEcommerceProduct(record, options) {\n if (!record || typeof record !== 'object') return record\n options = options || {}\n var currentLang = options.currentLanguage || null\n var mainLang = options.mainLanguage || null\n var assetMap = options.assetMap || {}\n\n var id = record.id !== undefined && record.id !== null ? record.id : null\n\n // i18n-resolved text fields\n var name = resolveI18nField(record, 'name', 'name', currentLang, mainLang) || ''\n var slug = resolveI18nField(record, 'slug', 'slug', currentLang, mainLang) || ''\n var description = resolveI18nField(record, 'description', 'description', currentLang, mainLang) || ''\n var category = resolveI18nField(record, 'category', 'category', currentLang, mainLang) || null\n var tagsRaw = resolveI18nField(record, 'tags', 'tags', currentLang, mainLang)\n var imageAlt = resolveI18nField(record, 'image_alt', 'imageAlt', currentLang, mainLang) || null\n\n // Computed: plain-text description (HTML stripped)\n var descriptionText = stripHtmlTags(description)\n\n // Numeric fields (with NaN protection)\n var price = safeNumber(record.price, 0)\n var quantity = safeNumber(record.quantity, null)\n\n // Currency\n var currency = (record.currency || 'USD').toUpperCase()\n var rawCurrencySymbol = pickFirst(record.currency_symbol, record.currencySymbol)\n var currencySymbol = rawCurrencySymbol || getCurrencySymbol(currency)\n\n // Status and active (normalize case \u2014 DB / forms may send \"Active\", \"Inactive\", etc.)\n var statusRaw = record.status\n if (statusRaw == null || statusRaw === '') {\n statusRaw = record.active ? 'active' : 'inactive'\n }\n var status =\n typeof statusRaw === 'string'\n ? statusRaw.trim().toLowerCase()\n : String(statusRaw).toLowerCase()\n var active = status === 'active'\n\n // Payment fields\n var paymentType = pickFirst(record.payment_type, record.paymentType) || 'one_time'\n var recurringInterval = pickFirst(record.recurring_interval, record.recurringInterval) || null\n var rawRecurringCount = pickFirst(record.recurring_interval_count, record.recurringIntervalCount)\n var recurringIntervalCount = safeNumber(rawRecurringCount, null)\n\n // Physical product fields\n var sku = record.sku || null\n var weight = safeNumber(record.weight, null)\n var weightUnit = pickFirst(record.weight_unit, record.weightUnit) || null\n var dimensions = record.dimensions || null\n\n // Tags - parse as JSON array (handles JSON strings, arrays, comma-separated)\n var tags = parseJsonArray(tagsRaw)\n\n // Variant AXES (translatable). The i18n-resolved column already carries the\n // display labels for the current language (with the SAME stable keys as the\n // base column); we just parse + normalize. The purchasable combinations live\n // in teleport_product_variants and are fetched by the variant picker widget.\n var variantOptionsRaw = resolveI18nField(record, 'variant_options', 'variantOptions', currentLang, mainLang)\n var variantOptions = normalizeVariantOptions(variantOptionsRaw)\n // Emitted as a STRING ('true'/'false') to match the strict-equality checks the\n // storefront uses (same convention as outOfStock).\n var requiresVariantSelection = variantOptions.length > 0 ? 'true' : 'false'\n\n // Provider fields\n var providerType = pickFirst(record.provider_type, record.providerType) || null\n var providerProductId = pickFirst(record.provider_product_id, record.providerProductId) || null\n var defaultPrice = pickFirst(record.default_price, record.defaultPrice) || null\n\n // Metadata\n var metadata = parseJsonObject(record.metadata)\n\n // Visible custom properties -> [{key,value,kind,color,imageUrl}] for the\n // storefront pills mapper. MUST mirror buildVisibleProductProperties /\n // classifyProductProperty in\n // apps/gui/app/project-page/features/e-commerce/utils/product-property-display.ts\n // (the canvas-preview SSOT) field-for-field: same reserved-key exclusions,\n // same default-VISIBLE (opt-out) rule, same color/image classification. A\n // property is shown unless it is a reserved key, has an empty value, or is\n // explicitly hidden (false) in the _tqPropVisibility map -- so it also\n // renders for products whose form was never opened (no visibility map yet).\n var propVisibility = parseJsonObject(metadata._tqPropVisibility)\n var visibleProperties = []\n Object.keys(metadata).forEach(function (propKey) {\n if (isReservedProductMetadataKey(propKey)) return\n if (propVisibility[propKey] === false) return\n var rawValue = metadata[propKey]\n if (rawValue == null) return\n var propValue = String(rawValue)\n if (propValue.trim() === '') return\n visibleProperties.push(classifyProductProperty(propKey, propValue))\n })\n\n // Assigned category ids -> resolved {id,name,slug} objects for the\n // storefront category pills mapper. The taxonomy itself is not in the DB\n // (categories are authored in the GUI and live only in\n // ecommerceSettings.categories); resolved here against PRODUCT_CATEGORIES_BY_ID,\n // baked in at export time (see flattenCategoriesById). Unknown/stale ids\n // (a deleted category) are silently dropped.\n var categoryIds = parseJsonArray(record.category_ids)\n var categories = []\n for (var ci = 0; ci < categoryIds.length; ci++) {\n var categoryInfo = PRODUCT_CATEGORIES_BY_ID[categoryIds[ci]]\n if (categoryInfo) {\n categories.push({\n id: categoryIds[ci],\n name: resolveCategoryName(categoryInfo, currentLang, mainLang),\n slug: categoryInfo.slug,\n })\n }\n }\n\n // Purchasable variant COMBINATIONS for this product ({id, options map, price,\n // stock, image}). Empty for flat products. Fetched in ONE batched query by\n // transformRecords and passed in via options.variantsByProductId, keyed by\n // product id. The storefront card/details read these to default-select the\n // first in-stock variant, disable dead options, and resolve the chosen id.\n //\n // NULL (not {}) means the lookup could not run \u2014 the table is missing, or the\n // query failed. That is \"combinations UNKNOWN\", which is NOT \"this product has\n // none\": a transient DB failure must never turn every variant product in the\n // catalogue into an unbuyable one. See hasPurchasableVariant below.\n var variantsResolved = options.variantsByProductId != null\n var variantsByProductId = options.variantsByProductId || {}\n var rawVariants = variantsByProductId[id] || []\n var variants = []\n for (var vi = 0; vi < rawVariants.length; vi++) {\n var vrow = rawVariants[vi] || {}\n var vopts = parseJsonObject(vrow.options)\n variants.push({\n id: vrow.id != null ? String(vrow.id) : '',\n options: vopts && typeof vopts === 'object' ? vopts : {},\n price: safeNumber(vrow.price, null),\n quantity: safeNumber(vrow.quantity, null),\n image_url: vrow.image_url ? resolveAssetUrl(vrow.image_url, assetMap) : null,\n })\n }\n\n // The merchant's related-product picks. `relatedProducts` carries the\n // TRANSFORMED rows, not ids, so the details page's related-products rail can\n // map over it and draw a product card per entry; `relatedProductIds` keeps\n // the raw selection for anything that wants it. The rows arrive from ONE\n // batched query (getRelatedProductsMap) that transformRecords runs, keyed by\n // id in options.relatedProductsById.\n //\n // MUST mirror buildRelatedEcommerceProducts in\n // packages/renderer/src/utils/ecommerce-products.ts (the canvas-preview SSOT):\n // the merchant's order, inactive products dropped, self dropped, and the\n // nested build deliberately WITHOUT the map \u2014 two products referencing each\n // other is the normal case (they are each other's accessories) and threading\n // the map through would recurse until the stack ran out.\n var relatedProductIds = parseRelatedIds(record.related_product_ids)\n var relatedProductsById = options.relatedProductsById\n var relatedProducts = []\n if (relatedProductsById && relatedProductIds.length > 0) {\n var relatedNestedOptions = {\n assetMap: assetMap,\n currentLanguage: currentLang,\n mainLanguage: mainLang,\n // Passed through UNCOALESCED so a related product inherits the same\n // known/unknown answer as its parent \u2014 `|| {}` here would tell the nested\n // build \"the lookup ran and found nothing\" and strike out every related\n // card's picker. The batched query includes the related ids for exactly\n // this reason (see getTransformWrapperCode).\n variantsByProductId: options.variantsByProductId,\n }\n for (var rp = 0; rp < relatedProductIds.length; rp++) {\n var relatedId = relatedProductIds[rp]\n if (id != null && relatedId === String(id)) continue\n var relatedRecord = relatedProductsById[relatedId]\n if (!relatedRecord) continue\n // A product taken off sale must not come back through the back door on\n // every product that references it. Missing status reads as active, the\n // same default the main status normalization uses above.\n var relatedStatusRaw = relatedRecord.status\n var relatedStatus =\n relatedStatusRaw == null || relatedStatusRaw === ''\n ? 'active'\n : String(relatedStatusRaw).trim().toLowerCase()\n if (relatedStatus !== 'active') continue\n relatedProducts.push(buildEcommerceProduct(relatedRecord, relatedNestedOptions))\n }\n }\n\n // -------------------------------------------------------\n // Image resolution (complex multi-step process)\n // -------------------------------------------------------\n\n // Step 1: Get raw image values\n var rawImageUrl = pickFirst(record.image_url, record.mainImage, record.imageUrl)\n var rawGalleryImages = pickFirst(record.gallery_images, record.galleryImages)\n var legacyImages = Array.isArray(record.images)\n ? record.images.filter(function(v) { return typeof v === 'string' })\n : []\n\n // Step 2: Parse gallery images from JSON\n var parsedGalleryImages = parseJsonArray(rawGalleryImages)\n\n // Step 3: Build combined raw images array\n var allRawImages = []\n if (rawImageUrl) allRawImages.push(rawImageUrl)\n allRawImages = allRawImages.concat(parsedGalleryImages).concat(legacyImages)\n\n // Step 4: Resolve all asset URLs first, then deduplicate\n var resolvedAll = resolveAssetUrls(allRawImages, assetMap)\n var resolvedImages = deduplicateStrings(resolvedAll)\n\n // Step 5: Determine mainImage\n var mainImage = rawImageUrl\n ? resolveAssetUrl(rawImageUrl, assetMap)\n : (resolvedImages.length > 0 ? resolvedImages[0] : null)\n\n // Step 6: galleryImages = resolvedImages without mainImage\n var galleryImages = mainImage\n ? resolvedImages.filter(function(url) { return url !== mainImage })\n : resolvedImages.slice()\n\n // Step 7: images = full resolved deduplicated array\n var images = resolvedImages\n\n // -------------------------------------------------------\n // 3D model (one per product; GUI: constants/product-model.ts)\n // -------------------------------------------------------\n // model_url / model_poster_url hold an asset id OR a raw URL like image_url.\n // A poster the merchant never got (capture failed, plan cap) falls back to\n // the main image so <model-viewer> always has something to paint first.\n var modelUrl = resolveMediaUrl(record.model_url, assetMap)\n var modelPoster = modelUrl ? resolveMediaUrl(record.model_poster_url, assetMap) || mainImage : null\n var hasModel = modelUrl ? 'true' : 'false'\n // STRING gate ('true'/'false') like outOfStock: whether the model replaces the\n // main image on the card / details hero. A product whose only media is the\n // model always shows it. An absent field must read as the IMAGE branch, so the\n // builders gate the viewer on = 'true' and the image on != 'true'.\n var showModel =\n modelUrl && (normalizeShowModelFlag(record.show_model_by_default) || images.length === 0)\n ? 'true'\n : 'false'\n var galleryMedia = buildProductGalleryMedia({\n images: images,\n mainImage: mainImage,\n modelUrl: modelUrl,\n modelPoster: modelPoster,\n showModel: showModel,\n imageAlt: imageAlt,\n name: name,\n })\n // Everything that is not the hero \u2014 the details thumbnail strip. When the\n // model is the hero the main image moves in here, so the modal stays reachable.\n var galleryThumbnails = galleryMedia.slice(1)\n\n // Timestamps\n var rawCreatedAt = pickFirst(record.created_at, record.createdAt, record.created)\n var createdAt = normalizeTimestamp(rawCreatedAt)\n\n var rawUpdatedAt = pickFirst(record.updated_at, record.updatedAt, record.updated)\n var updatedAt = rawUpdatedAt != null ? normalizeTimestamp(rawUpdatedAt) : createdAt\n\n // Computed: created = Unix seconds\n var created = Math.floor(createdAt / 1000)\n\n // Computed: outOfStock (emitted as a STRING \u2014 'true' / 'false' \u2014 so it\n // matches the strict equality check the AI generates on product\n // cards/details pages: `ecommerceProduct?.outOfStock === 'true'`.\n // A boolean here would silently fail that comparison (boolean !==\n // string), leaving the Add to Cart button visible on out-of-stock\n // products. NULL/NaN quantity \u2192 'false' (treated as \"unlimited\n // stock\", same as the upstream cart-availability rewriter).\n // With ALLOW_BACKORDERS the merchant sells past zero (or does not track\n // stock at all), so nothing is ever presented as out of stock.\n var outOfStock = (!ALLOW_BACKORDERS && quantity !== null && !isNaN(quantity) && quantity <= 0) ? 'true' : 'false'\n\n // Per-value availability + default-selection flags, derived from the\n // purchasable combinations, so the storefront picker renders its\n // Default / Selected / Unavailable states with NO runtime fetch. The card\n // (N instances) first-paints from these data flags; the details page seeds\n // its selection from the same combinations. axisValueKey (axisKey|valueKey)\n // disambiguates same-named values across axes (Size \"s\" vs Sleeve \"s\").\n // Emitted as STRINGS to match the storefront's string-equality convention.\n var variantAxisKeys = []\n for (var ak = 0; ak < variantOptions.length; ak++) { variantAxisKeys.push(variantOptions[ak].key) }\n var firstVariant = pickFirstAvailableVariant(variants, variantAxisKeys)\n var deadValueKeys = computeDeadVariantKeys(variants, variantOptions, variantsResolved)\n for (var ai = 0; ai < variantOptions.length; ai++) {\n var vax = variantOptions[ai]\n for (var vj = 0; vj < vax.values.length; vj++) {\n var vval = vax.values[vj]\n var composite = vax.key + '|' + vval.value\n vval.axisValueKey = composite\n vval.isDead = deadValueKeys[composite] ? 'true' : 'false'\n vval.isDefault =\n firstVariant && firstVariant.options && firstVariant.options[vax.key] === vval.value\n ? 'true'\n : 'false'\n // Whether THIS value renders as a colour swatch vs a text pill. A colour\n // axis whose value has no resolvable colour degrades to a text pill so it\n // is never an invisible empty circle. Emitted as a string to match the\n // picker's string-equality rendering gate. MUST mirror the renderer\n // enrichment in packages/renderer/src/utils/ecommerce-products.ts.\n vval.showSwatch = vax.type === 'color' && vval.color ? 'true' : 'false'\n }\n }\n // The combination the picker auto-selects on first paint: the first in-stock\n // one covering every axis. Absent means there is nothing the shopper could add\n // without choosing \u2014 which is what gates the buy button below.\n var hasInStockCombination = !!(firstVariant && isVariantInStock(firstVariant))\n var defaultVariantId = hasInStockCombination ? firstVariant.id : ''\n var defaultVariantPrice = firstVariant ? formatVariantPrice(firstVariant.price, price) : ''\n // Gross (tax-inclusive) counterparts of the three price fields the STOREFRONT\n // renders. `price` / `defaultVariantPrice` / `variantsJson` deliberately stay\n // NET: the same transform feeds the merchant's admin panel, and every write\n // path (add-to-cart, checkout, the invoice route) re-reads the raw row and\n // must keep seeing the price the merchant typed. Only these three are safe to\n // gross, because nothing writes them back.\n //\n // MUST mirror packages/renderer/src/utils/ecommerce-products.ts.\n // The scheduled markdown in force right now, resolved from the raw column on\n // every read so a discount starts and expires on its own. It comes off the NET\n // price BEFORE tax: tax is a percentage of what is actually charged.\n var activeDiscount = __pdResolveActive(record.discounts, Date.now())\n var displayPrice = grossMoney(__pdDiscountedPrice(price, activeDiscount))\n var defaultVariantNetPrice = firstVariant\n ? safeNumber(formatVariantPrice(firstVariant.price, price), 0)\n : 0\n var defaultVariantDisplayPrice = firstVariant\n ? grossMoney(__pdDiscountedPrice(defaultVariantNetPrice, activeDiscount))\n : ''\n var variantsDisplay = []\n for (var dv = 0; dv < variants.length; dv++) {\n var dvRow = variants[dv]\n // A null variant price INHERITS the product price, so discount and gross the\n // RESOLVED value \u2014 otherwise an inheriting combination would fall back to\n // the net base price in the picker while an overriding one showed gross.\n var dvNetPrice = dvRow.price == null ? price : dvRow.price\n variantsDisplay.push({\n id: dvRow.id,\n options: dvRow.options,\n price: applyStorefrontTax(__pdDiscountedPrice(dvNetPrice, activeDiscount)),\n // What this combination costs WITHOUT the discount, for the struck-through\n // price beside it. Null when nothing is discounted, so the picker's click\n // resolver can tell \"no saving\" from \"a saving of zero\".\n originalPrice: activeDiscount ? applyStorefrontTax(dvNetPrice) : null,\n quantity: dvRow.quantity,\n image_url: dvRow.image_url,\n })\n }\n // Discount display fields. Strings throughout: rendering conditions compare\n // operands as strings, and a bound text node prints its value verbatim.\n var hasDiscount = activeDiscount ? 'true' : 'false'\n var discountLabel = activeDiscount\n ? __pdDiscountLabel(activeDiscount, currencySymbol, getCurrencyInfo(currency).position)\n : ''\n var originalDisplayPrice = activeDiscount ? grossMoney(price) : ''\n var originalDefaultVariantDisplayPrice =\n activeDiscount && firstVariant ? grossMoney(defaultVariantNetPrice) : ''\n // Can this product be added to the cart at all, before the shopper touches the\n // picker? A STRING, same convention as outOfStock/requiresVariantSelection.\n //\n // flat product -> 'true' (stock is governed by outOfStock)\n // combinations UNKNOWN -> 'true' (the lookup could not run; a transient DB\n // failure must never make a whole catalogue\n // unbuyable \u2014 same permissive rule as\n // dead-marking)\n // otherwise -> whether an in-stock combination covering every axis\n // exists. 'false' therefore covers BOTH \"every\n // combination is sold out\" AND \"the axes have no\n // combinations at all\" \u2014 to a shopper those are the\n // same thing: there is no size to pick.\n //\n // MUST mirror packages/renderer/src/utils/ecommerce-products.ts.\n var hasPurchasableVariant =\n (requiresVariantSelection !== 'true' || !variantsResolved || hasInStockCombination)\n ? 'true'\n : 'false'\n // Stringified companions: a data-* attr bound to an ARRAY renders\n // '[object Object]', so the picker's on-mount/click workflows read the\n // combinations + axes from these JSON strings via getAttribute.\n var variantOptionsJson = safeStringifyJson(variantOptions)\n var variantsJson = safeStringifyJson(variants)\n var variantsDisplayJson = safeStringifyJson(variantsDisplay)\n\n return {\n id: id,\n name: name,\n slug: slug,\n description: description,\n descriptionText: descriptionText,\n price: price,\n currency: currency,\n currencySymbol: currencySymbol,\n status: status,\n active: active,\n quantity: quantity,\n paymentType: paymentType,\n recurringInterval: recurringInterval,\n recurringIntervalCount: recurringIntervalCount,\n sku: sku,\n weight: weight,\n weightUnit: weightUnit,\n dimensions: dimensions,\n category: category,\n categories: categories,\n tags: tags,\n relatedProductIds: relatedProductIds,\n relatedProducts: relatedProducts,\n imageAlt: imageAlt,\n providerType: providerType,\n providerProductId: providerProductId,\n default_price: defaultPrice,\n metadata: metadata,\n visibleProperties: visibleProperties,\n mainImage: mainImage,\n imageUrl: mainImage,\n image_url: mainImage,\n galleryImages: galleryImages,\n images: images,\n modelUrl: modelUrl,\n modelPoster: modelPoster,\n hasModel: hasModel,\n showModel: showModel,\n galleryMedia: galleryMedia,\n galleryThumbnails: galleryThumbnails,\n createdAt: createdAt,\n updatedAt: updatedAt,\n created: created,\n outOfStock: outOfStock,\n variantOptions: variantOptions,\n requiresVariantSelection: requiresVariantSelection,\n variants: variants,\n variantOptionsJson: variantOptionsJson,\n variantsJson: variantsJson,\n variantsDisplayJson: variantsDisplayJson,\n defaultVariantId: defaultVariantId,\n defaultVariantPrice: defaultVariantPrice,\n displayPrice: displayPrice,\n defaultVariantDisplayPrice: defaultVariantDisplayPrice,\n hasDiscount: hasDiscount,\n discountLabel: discountLabel,\n originalDisplayPrice: originalDisplayPrice,\n originalDefaultVariantDisplayPrice: originalDefaultVariantDisplayPrice,\n hasPurchasableVariant: hasPurchasableVariant,\n }\n}\n\n// --- Variant availability helpers (mirror packages/renderer ecommerce-products) ---\n// A variant is in stock when its quantity is null (unlimited) or > 0. With\n// ALLOW_BACKORDERS every EXISTING combination is purchasable regardless of its\n// quantity \u2014 but a missing combination (null) is still not in stock: there is\n// no variant row to backorder.\nfunction isVariantInStock(v) {\n if (!v) return false\n if (ALLOW_BACKORDERS) return true\n return v.quantity == null || v.quantity > 0\n}\nfunction variantCoversAllAxes(v, axisKeys) {\n if (!v || !v.options) return false\n for (var i = 0; i < axisKeys.length; i++) {\n if (v.options[axisKeys[i]] == null) return false\n }\n return true\n}\n// First in-stock combination covering every axis; falls back to the first\n// covering combination (even if OOS) so a fully-OOS product still has a\n// visual default; null when no combination covers the axes.\nfunction pickFirstAvailableVariant(variants, axisKeys) {\n if (!Array.isArray(variants) || !axisKeys.length) return null\n for (var i = 0; i < variants.length; i++) {\n if (variantCoversAllAxes(variants[i], axisKeys) && isVariantInStock(variants[i])) return variants[i]\n }\n for (var j = 0; j < variants.length; j++) {\n if (variantCoversAllAxes(variants[j], axisKeys)) return variants[j]\n }\n return null\n}\n// Map of composite \"axisKey|valueKey\" -> true for every value that appears in\n// NO in-stock combination (rendered as the Unavailable state).\n//\n// variantsResolved is the whole subtlety: dead-marking is only meaningful\n// against combinations we actually LOOKED UP. When the lookup could not run,\n// nothing is dead \u2014 a missing table or a failed query must not grey out every\n// picker in the store. When it DID run, an empty list is a fact, not a gap:\n// every value is unbuyable and renders as Unavailable.\nfunction computeDeadVariantKeys(variants, axes, variantsResolved) {\n if (!variantsResolved || !Array.isArray(variants)) return {}\n var alive = {}\n for (var i = 0; i < variants.length; i++) {\n var v = variants[i]\n if (!isVariantInStock(v)) continue\n for (var k in v.options) {\n if (Object.prototype.hasOwnProperty.call(v.options, k)) alive[k + '|' + v.options[k]] = true\n }\n }\n var dead = {}\n for (var a = 0; a < axes.length; a++) {\n var ax = axes[a]\n for (var b = 0; b < ax.values.length; b++) {\n var key = ax.key + '|' + ax.values[b].value\n if (!alive[key]) dead[key] = true\n }\n }\n return dead\n}\n// Variant price with base-price inheritance (null variant price -> product price).\nfunction formatVariantPrice(vprice, basePrice) {\n var p = vprice == null || isNaN(vprice) ? basePrice : vprice\n return String(Number(p).toFixed(2))\n}\nfunction safeStringifyJson(obj) {\n try {\n return JSON.stringify(obj)\n } catch (e) {\n return '[]'\n }\n}\n\n// Parse + normalize the variant_options JSON into render-ready axes. Tolerant of\n// null / malformed / partial data (returns []). Keeps ONLY the fields the pill\n// widget needs; the labels are already language-resolved by the caller.\nfunction normalizeVariantOptions(raw) {\n if (!raw) return []\n var parsed = raw\n if (typeof raw === 'string') {\n try { parsed = JSON.parse(raw) } catch (e) { return [] }\n }\n if (!Array.isArray(parsed)) return []\n var out = []\n for (var i = 0; i < parsed.length; i++) {\n var axis = parsed[i]\n if (!axis || typeof axis !== 'object' || !Array.isArray(axis.values)) continue\n var name = typeof axis.name === 'string' ? axis.name : ''\n var key = typeof axis.key === 'string' && axis.key ? axis.key : name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n if (!key) continue\n var type = axis.type === 'color' ? 'color' : 'text'\n var values = []\n for (var j = 0; j < axis.values.length; j++) {\n var v = axis.values[j]\n if (!v || typeof v !== 'object') continue\n var label = typeof v.label === 'string' ? v.label : ''\n var value = typeof v.value === 'string' && v.value ? v.value : label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n if (!value) continue\n var entry = { value: value, label: label }\n if (type === 'color' && typeof v.color === 'string' && v.color) entry.color = v.color\n values.push(entry)\n }\n if (!values.length) continue\n out.push({ key: key, name: name, type: type, values: values })\n }\n return out\n}\n\n// --- Custom-property classification (MUST mirror product-property-display.ts) ---\n\n// Product-attribute keys that can leak into the free-form `metadata` map (e.g.\n// from a payment-provider sync or legacy data) but are NOT user custom\n// properties. Kept in sync with the GUI's RESERVED_PRODUCT_METADATA_KEYS.\nvar RESERVED_PRODUCT_METADATA_KEYS = {\n paymentType: true, recurringInterval: true, recurringIntervalCount: true,\n price: true, currency: true, status: true, sku: true, weightUnit: true,\n dimensions: true, category: true, brand: true, gtin: true, mpn: true,\n condition: true, tags: true,\n}\nfunction isReservedProductMetadataKey(key) {\n return !!RESERVED_PRODUCT_METADATA_KEYS[key] ||\n key.indexOf('mainImage') === 0 ||\n key.indexOf('secondaryImage') === 0 ||\n key.indexOf('_tq') === 0\n}\n\nvar CSS_NAMED_COLORS = {\n aliceblue: 1, antiquewhite: 1, aqua: 1, aquamarine: 1, azure: 1, beige: 1, bisque: 1,\n black: 1, blanchedalmond: 1, blue: 1, blueviolet: 1, brown: 1, burlywood: 1,\n cadetblue: 1, chartreuse: 1, chocolate: 1, coral: 1, cornflowerblue: 1, cornsilk: 1,\n crimson: 1, cyan: 1, darkblue: 1, darkcyan: 1, darkgoldenrod: 1, darkgray: 1,\n darkgrey: 1, darkgreen: 1, darkkhaki: 1, darkmagenta: 1, darkolivegreen: 1,\n darkorange: 1, darkorchid: 1, darkred: 1, darksalmon: 1, darkseagreen: 1,\n darkslateblue: 1, darkslategray: 1, darkslategrey: 1, darkturquoise: 1,\n darkviolet: 1, deeppink: 1, deepskyblue: 1, dimgray: 1, dimgrey: 1, dodgerblue: 1,\n firebrick: 1, floralwhite: 1, forestgreen: 1, fuchsia: 1, gainsboro: 1,\n ghostwhite: 1, gold: 1, goldenrod: 1, gray: 1, grey: 1, green: 1, greenyellow: 1,\n honeydew: 1, hotpink: 1, indianred: 1, indigo: 1, ivory: 1, khaki: 1, lavender: 1,\n lavenderblush: 1, lawngreen: 1, lemonchiffon: 1, lightblue: 1, lightcoral: 1,\n lightcyan: 1, lightgoldenrodyellow: 1, lightgray: 1, lightgrey: 1, lightgreen: 1,\n lightpink: 1, lightsalmon: 1, lightseagreen: 1, lightskyblue: 1, lightslategray: 1,\n lightslategrey: 1, lightsteelblue: 1, lightyellow: 1, lime: 1, limegreen: 1,\n linen: 1, magenta: 1, maroon: 1, mediumaquamarine: 1, mediumblue: 1,\n mediumorchid: 1, mediumpurple: 1, mediumseagreen: 1, mediumslateblue: 1,\n mediumspringgreen: 1, mediumturquoise: 1, mediumvioletred: 1, midnightblue: 1,\n mintcream: 1, mistyrose: 1, moccasin: 1, navajowhite: 1, navy: 1, oldlace: 1,\n olive: 1, olivedrab: 1, orange: 1, orangered: 1, orchid: 1, palegoldenrod: 1,\n palegreen: 1, paleturquoise: 1, palevioletred: 1, papayawhip: 1, peachpuff: 1,\n peru: 1, pink: 1, plum: 1, powderblue: 1, purple: 1, rebeccapurple: 1, red: 1,\n rosybrown: 1, royalblue: 1, saddlebrown: 1, salmon: 1, sandybrown: 1, seagreen: 1,\n seashell: 1, sienna: 1, silver: 1, skyblue: 1, slateblue: 1, slategray: 1,\n slategrey: 1, snow: 1, springgreen: 1, steelblue: 1, tan: 1, teal: 1, thistle: 1,\n tomato: 1, turquoise: 1, violet: 1, wheat: 1, white: 1, whitesmoke: 1, yellow: 1,\n yellowgreen: 1, transparent: 1,\n}\nvar HEX_COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\nvar FUNCTIONAL_COLOR_RE = /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\\((?:[0-9a-z%.,\\s/+-]+)\\)$/i\nvar COLOR_KEY_WORDS = {\n color: 1, colors: 1, colour: 1, colours: 1, shade: 1, shades: 1, hue: 1, hues: 1,\n tint: 1, tints: 1, tone: 1, tones: 1, swatch: 1, swatches: 1,\n}\nfunction splitKeyWords(key) {\n return key.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)\n}\nfunction keyIndicatesColor(key) {\n var normalized = key.toLowerCase()\n if (/colou?r/.test(normalized)) return true\n return splitKeyWords(key).some(function(word) { return !!COLOR_KEY_WORDS[word] })\n}\nfunction resolvePropertyColor(key, value) {\n var v = value.trim()\n if (!v) return ''\n if (HEX_COLOR_RE.test(v) || FUNCTIONAL_COLOR_RE.test(v)) return v\n if (CSS_NAMED_COLORS[v.toLowerCase()] && keyIndicatesColor(key)) return v\n return ''\n}\n\nvar DATA_IMAGE_URI_RE = /^data:image\\//i\nvar ABSOLUTE_URL_RE = /^(?:https?:)?\\/\\//i\nvar IMAGE_EXTENSION_RE = /\\.(?:png|jpe?g|gif|webp|svg|avif|bmp|ico|tiff?|heic|heif)$/i\nvar IMAGE_KEY_WORDS = {\n image: 1, images: 1, img: 1, imgs: 1, photo: 1, photos: 1, picture: 1, pictures: 1,\n pic: 1, pics: 1, thumbnail: 1, thumbnails: 1, thumb: 1, thumbs: 1, icon: 1, icons: 1,\n logo: 1, logos: 1, avatar: 1, avatars: 1, banner: 1, banners: 1, cover: 1, covers: 1,\n gallery: 1, screenshot: 1, screenshots: 1, poster: 1, posters: 1, artwork: 1,\n graphic: 1, graphics: 1, illustration: 1, wallpaper: 1, preview: 1, snapshot: 1,\n media: 1, visual: 1, visuals: 1,\n}\nfunction keyIndicatesImage(key) {\n var normalized = key.toLowerCase()\n if (/(?:image|img|photo|picture|thumb|icon|logo|avatar|banner|gallery|screenshot|poster|artwork|graphic|wallpaper)/.test(normalized)) return true\n return splitKeyWords(key).some(function(word) { return !!IMAGE_KEY_WORDS[word] })\n}\nfunction stripUrlQueryAndHash(url) {\n return url.split(/[?#]/)[0]\n}\nfunction resolvePropertyImage(key, value) {\n var v = value.trim()\n if (!v) return ''\n if (DATA_IMAGE_URI_RE.test(v)) return v\n var isAbsoluteUrl = ABSOLUTE_URL_RE.test(v)\n var isRootRelative = v.charAt(0) === '/' && !isAbsoluteUrl\n if (!isAbsoluteUrl && !isRootRelative) return ''\n if (IMAGE_EXTENSION_RE.test(stripUrlQueryAndHash(v))) return v\n if (isAbsoluteUrl && keyIndicatesImage(key)) return v\n return ''\n}\n\n// Image wins over colour (a URL can never be a CSS colour, but checking image\n// first keeps the precedence explicit), text is the fallback.\nfunction classifyProductProperty(key, value) {\n var imageUrl = resolvePropertyImage(key, value)\n if (imageUrl) return { key: key, value: value, kind: 'image', color: '', imageUrl: imageUrl }\n var color = resolvePropertyColor(key, value)\n if (color) return { key: key, value: value, kind: 'color', color: color, imageUrl: '' }\n return { key: key, value: value, kind: 'text', color: '', imageUrl: '' }\n}\n\nfunction transformEcommerceProducts(records, options) {\n if (!Array.isArray(records)) return []\n return records.map(function(record) { return buildEcommerceProduct(record, options) })\n}\n\n// Batched fetch of the purchasable variant rows for a set of product ids, keyed\n// by product_id, so buildEcommerceProduct can attach product.variants without a\n// per-product query. Best-effort: a store with no variants (or before the table\n// exists) yields an empty map and flat products keep variants: [].\n// Batched fetch of the product rows a set of products reference as \"related\",\n// keyed by id, so buildEcommerceProduct can attach product.relatedProducts\n// without a query per product.\n//\n// Best-effort by design: a store whose products table predates the column\n// yields no ids at all (the read below is of an absent property, not of a\n// column \u2014 the SQL never names it), the map stays empty, and the details page's\n// rail simply stays hidden behind its is_not_empty gate. Same for a failed\n// query.\nasync function getRelatedProductsMap(getClientFn, records) {\n var map = {}\n if (!Array.isArray(records) || records.length === 0) return map\n\n var wantedIds = []\n for (var i = 0; i < records.length; i++) {\n var ids = parseRelatedIds(records[i] && records[i].related_product_ids)\n for (var j = 0; j < ids.length; j++) {\n if (wantedIds.indexOf(ids[j]) === -1) wantedIds.push(ids[j])\n }\n }\n if (wantedIds.length === 0) return map\n\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query('SELECT * FROM teleport_products WHERE id = ANY($1)', [\n wantedIds,\n ])\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n if (row && row.id != null) map[String(row.id)] = row\n }\n }\n } catch (e) {\n // Leaves relatedProducts empty rather than failing the page.\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n\n// Combinations for every product on the page, keyed by product id. Returns NULL\n// when the lookup could not run, which the transform reads as \"unknown\" and\n// stays permissive with; an empty map means the query ran and this catalogue\n// simply has no combinations.\nasync function getVariantsMap(getClientFn, productIds) {\n var map = {}\n if (!Array.isArray(productIds) || productIds.length === 0) return map\n var uniqueIds = []\n var seenIds = {}\n for (var u = 0; u < productIds.length; u++) {\n var pid0 = productIds[u]\n if (pid0 != null && !seenIds[pid0]) { seenIds[pid0] = true; uniqueIds.push(pid0) }\n }\n if (uniqueIds.length === 0) return map\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query(\n 'SELECT id, product_id, options, price, quantity, image_url FROM teleport_product_variants WHERE product_id = ANY($1) ORDER BY position ASC, id ASC',\n [uniqueIds]\n )\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n var pid = row.product_id\n if (!map[pid]) map[pid] = []\n map[pid].push(row)\n }\n }\n } catch (e) {\n // teleport_product_variants may not exist for a non-variant store, or the\n // query may have failed. Either way the combinations are UNKNOWN \u2014 null\n // keeps every picker selectable instead of declaring the catalogue unbuyable.\n map = null\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n");
|
|
16
|
+
return "\n".concat(taxHelperCode, "\n").concat(teleport_shared_1.ProductDiscounts.generateProductDiscountHelperCode(), "\n").concat(teleport_shared_1.ProductRatings.generateProductRatingHelperCode(), "\n\n// Baked from the merchant's stock settings: TRUE when stock never blocks a\n// purchase (stock management off OR backorders allowed). Regenerating the\n// project refreshes it \u2014 do not hand-edit. See EcommerceProductTransformOptions.\nvar ALLOW_BACKORDERS = ").concat(allowBackordersLiteral, "\n\n").concat((0, category_taxonomy_1.generateCategoryTaxonomyCode)('PRODUCT_CATEGORIES_BY_ID', options.categories), "\n// The merchant's \"Show 3D model by default\" toggle, as every backend may hand\n// it back: a real boolean, 1/0, 'true'/'false'/'t'/'f' strings \u2014 and NULL /\n// absent / '' as ON, because a product that has a model shows it unless the\n// merchant switched it off. MUST mirror normalizeShowModelFlag in the GUI's\n// features/e-commerce/constants/product-model.ts.\nfunction normalizeShowModelFlag(raw) {\n if (raw === null || raw === undefined || raw === '') return true\n if (typeof raw === 'boolean') return raw\n if (typeof raw === 'number') return raw !== 0\n if (typeof raw === 'string') {\n var token = raw.trim().toLowerCase()\n return !(token === 'false' || token === 'f' || token === '0' || token === 'no' || token === 'off')\n }\n return true\n}\n\n// The product's media gallery in display order, HERO FIRST: the model when it\n// is shown by default, otherwise the images with the model last. Each entry is\n// { kind: 'image' | 'model', src, poster, thumbnail, alt }; 'thumbnail' is what\n// a strip draws and is never empty for an entry that can appear in one. MUST\n// mirror buildProductGalleryMedia in the GUI's\n// features/e-commerce/utils/product-gallery-media.ts.\nfunction buildProductGalleryMedia(params) {\n var imageItems = []\n for (var gi = 0; gi < params.images.length; gi++) {\n imageItems.push({\n kind: 'image',\n src: params.images[gi],\n poster: '',\n thumbnail: params.images[gi],\n alt: params.imageAlt || params.name,\n })\n }\n if (!params.modelUrl) return imageItems\n var modelItem = {\n kind: 'model',\n src: params.modelUrl,\n poster: params.modelPoster || '',\n thumbnail: params.modelPoster || params.mainImage || params.images[0] || '',\n alt: params.name,\n }\n return params.showModel === 'true' ? [modelItem].concat(imageItems) : imageItems.concat([modelItem])\n}\n\n// ============================================================\n// E-Commerce Product Transformation\n// ============================================================\n\nfunction buildEcommerceProduct(record, options) {\n if (!record || typeof record !== 'object') return record\n options = options || {}\n var currentLang = options.currentLanguage || null\n var mainLang = options.mainLanguage || null\n var assetMap = options.assetMap || {}\n\n var id = record.id !== undefined && record.id !== null ? record.id : null\n\n // i18n-resolved text fields\n var name = resolveI18nField(record, 'name', 'name', currentLang, mainLang) || ''\n var slug = resolveI18nField(record, 'slug', 'slug', currentLang, mainLang) || ''\n var description = resolveI18nField(record, 'description', 'description', currentLang, mainLang) || ''\n var category = resolveI18nField(record, 'category', 'category', currentLang, mainLang) || null\n var tagsRaw = resolveI18nField(record, 'tags', 'tags', currentLang, mainLang)\n var imageAlt = resolveI18nField(record, 'image_alt', 'imageAlt', currentLang, mainLang) || null\n\n // Computed: plain-text description (HTML stripped)\n var descriptionText = stripHtmlTags(description)\n\n // Numeric fields (with NaN protection)\n var price = safeNumber(record.price, 0)\n var quantity = safeNumber(record.quantity, null)\n\n // Currency\n var currency = (record.currency || 'USD').toUpperCase()\n var rawCurrencySymbol = pickFirst(record.currency_symbol, record.currencySymbol)\n var currencySymbol = rawCurrencySymbol || getCurrencySymbol(currency)\n\n // Status and active (normalize case \u2014 DB / forms may send \"Active\", \"Inactive\", etc.)\n var statusRaw = record.status\n if (statusRaw == null || statusRaw === '') {\n statusRaw = record.active ? 'active' : 'inactive'\n }\n var status =\n typeof statusRaw === 'string'\n ? statusRaw.trim().toLowerCase()\n : String(statusRaw).toLowerCase()\n var active = status === 'active'\n\n // Payment fields\n var paymentType = pickFirst(record.payment_type, record.paymentType) || 'one_time'\n var recurringInterval = pickFirst(record.recurring_interval, record.recurringInterval) || null\n var rawRecurringCount = pickFirst(record.recurring_interval_count, record.recurringIntervalCount)\n var recurringIntervalCount = safeNumber(rawRecurringCount, null)\n\n // Physical product fields\n var sku = record.sku || null\n var weight = safeNumber(record.weight, null)\n var weightUnit = pickFirst(record.weight_unit, record.weightUnit) || null\n var dimensions = record.dimensions || null\n\n // Tags - parse as JSON array (handles JSON strings, arrays, comma-separated)\n var tags = parseJsonArray(tagsRaw)\n\n // Variant AXES (translatable). The i18n-resolved column already carries the\n // display labels for the current language (with the SAME stable keys as the\n // base column); we just parse + normalize. The purchasable combinations live\n // in teleport_product_variants and are fetched by the variant picker widget.\n var variantOptionsRaw = resolveI18nField(record, 'variant_options', 'variantOptions', currentLang, mainLang)\n var variantOptions = normalizeVariantOptions(variantOptionsRaw)\n // Emitted as a STRING ('true'/'false') to match the strict-equality checks the\n // storefront uses (same convention as outOfStock).\n var requiresVariantSelection = variantOptions.length > 0 ? 'true' : 'false'\n\n // Provider fields\n var providerType = pickFirst(record.provider_type, record.providerType) || null\n var providerProductId = pickFirst(record.provider_product_id, record.providerProductId) || null\n var defaultPrice = pickFirst(record.default_price, record.defaultPrice) || null\n\n // Metadata\n var metadata = parseJsonObject(record.metadata)\n\n // Visible custom properties -> [{key,value,kind,color,imageUrl}] for the\n // storefront pills mapper. MUST mirror buildVisibleProductProperties /\n // classifyProductProperty in\n // apps/gui/app/project-page/features/e-commerce/utils/product-property-display.ts\n // (the canvas-preview SSOT) field-for-field: same reserved-key exclusions,\n // same default-VISIBLE (opt-out) rule, same color/image classification. A\n // property is shown unless it is a reserved key, has an empty value, or is\n // explicitly hidden (false) in the _tqPropVisibility map -- so it also\n // renders for products whose form was never opened (no visibility map yet).\n var propVisibility = parseJsonObject(metadata._tqPropVisibility)\n var visibleProperties = []\n Object.keys(metadata).forEach(function (propKey) {\n if (isReservedProductMetadataKey(propKey)) return\n if (propVisibility[propKey] === false) return\n var rawValue = metadata[propKey]\n if (rawValue == null) return\n var propValue = String(rawValue)\n if (propValue.trim() === '') return\n visibleProperties.push(classifyProductProperty(propKey, propValue))\n })\n\n // Assigned category ids -> resolved {id,name,slug} objects for the storefront\n // category pills mapper and the product-details breadcrumbs. The taxonomy\n // itself is not in the DB (categories are authored in the GUI and live only in\n // ecommerceSettings.categories); resolved against PRODUCT_CATEGORIES_BY_ID,\n // baked in at export time. Unknown/stale ids are silently dropped.\n var categories = resolveAssignedCategories(\n record.category_ids,\n PRODUCT_CATEGORIES_BY_ID,\n currentLang,\n mainLang\n )\n\n // Purchasable variant COMBINATIONS for this product ({id, options map, price,\n // stock, image}). Empty for flat products. Fetched in ONE batched query by\n // transformRecords and passed in via options.variantsByProductId, keyed by\n // product id. The storefront card/details read these to default-select the\n // first in-stock variant, disable dead options, and resolve the chosen id.\n //\n // NULL (not {}) means the lookup could not run \u2014 the table is missing, or the\n // query failed. That is \"combinations UNKNOWN\", which is NOT \"this product has\n // none\": a transient DB failure must never turn every variant product in the\n // catalogue into an unbuyable one. See hasPurchasableVariant below.\n var variantsResolved = options.variantsByProductId != null\n var variantsByProductId = options.variantsByProductId || {}\n var rawVariants = variantsByProductId[id] || []\n var variants = []\n for (var vi = 0; vi < rawVariants.length; vi++) {\n var vrow = rawVariants[vi] || {}\n var vopts = parseJsonObject(vrow.options)\n variants.push({\n id: vrow.id != null ? String(vrow.id) : '',\n options: vopts && typeof vopts === 'object' ? vopts : {},\n price: safeNumber(vrow.price, null),\n quantity: safeNumber(vrow.quantity, null),\n image_url: vrow.image_url ? resolveAssetUrl(vrow.image_url, assetMap) : null,\n })\n }\n\n // The merchant's related-product picks. `relatedProducts` carries the\n // TRANSFORMED rows, not ids, so the details page's related-products rail can\n // map over it and draw a product card per entry; `relatedProductIds` keeps\n // the raw selection for anything that wants it. The rows arrive from ONE\n // batched query (getRelatedProductsMap) that transformRecords runs, keyed by\n // id in options.relatedProductsById.\n //\n // MUST mirror buildRelatedEcommerceProducts in\n // packages/renderer/src/utils/ecommerce-products.ts (the canvas-preview SSOT):\n // the merchant's order, inactive products dropped, self dropped, and the\n // nested build deliberately WITHOUT the map \u2014 two products referencing each\n // other is the normal case (they are each other's accessories) and threading\n // the map through would recurse until the stack ran out.\n var relatedProductIds = parseRelatedIds(record.related_product_ids)\n var relatedProductsById = options.relatedProductsById\n var relatedProducts = []\n if (relatedProductsById && relatedProductIds.length > 0) {\n var relatedNestedOptions = {\n assetMap: assetMap,\n currentLanguage: currentLang,\n mainLanguage: mainLang,\n // Passed through UNCOALESCED so a related product inherits the same\n // known/unknown answer as its parent \u2014 `|| {}` here would tell the nested\n // build \"the lookup ran and found nothing\" and strike out every related\n // card's picker. The batched query includes the related ids for exactly\n // this reason (see getTransformWrapperCode).\n variantsByProductId: options.variantsByProductId,\n // Same reason: a related card draws its own star row, and the batched\n // aggregate already covered its id.\n ratingsByProductId: options.ratingsByProductId,\n }\n for (var rp = 0; rp < relatedProductIds.length; rp++) {\n var relatedId = relatedProductIds[rp]\n if (id != null && relatedId === String(id)) continue\n var relatedRecord = relatedProductsById[relatedId]\n if (!relatedRecord) continue\n // A product taken off sale must not come back through the back door on\n // every product that references it. Missing status reads as active, the\n // same default the main status normalization uses above.\n var relatedStatusRaw = relatedRecord.status\n var relatedStatus =\n relatedStatusRaw == null || relatedStatusRaw === ''\n ? 'active'\n : String(relatedStatusRaw).trim().toLowerCase()\n if (relatedStatus !== 'active') continue\n relatedProducts.push(buildEcommerceProduct(relatedRecord, relatedNestedOptions))\n }\n }\n\n // -------------------------------------------------------\n // Image resolution (complex multi-step process)\n // -------------------------------------------------------\n\n // Step 1: Get raw image values\n var rawImageUrl = pickFirst(record.image_url, record.mainImage, record.imageUrl)\n var rawGalleryImages = pickFirst(record.gallery_images, record.galleryImages)\n var legacyImages = Array.isArray(record.images)\n ? record.images.filter(function(v) { return typeof v === 'string' })\n : []\n\n // Step 2: Parse gallery images from JSON\n var parsedGalleryImages = parseJsonArray(rawGalleryImages)\n\n // Step 3: Build combined raw images array\n var allRawImages = []\n if (rawImageUrl) allRawImages.push(rawImageUrl)\n allRawImages = allRawImages.concat(parsedGalleryImages).concat(legacyImages)\n\n // Step 4: Resolve all asset URLs first, then deduplicate\n var resolvedAll = resolveAssetUrls(allRawImages, assetMap)\n var resolvedImages = deduplicateStrings(resolvedAll)\n\n // Step 5: Determine mainImage\n var mainImage = rawImageUrl\n ? resolveAssetUrl(rawImageUrl, assetMap)\n : (resolvedImages.length > 0 ? resolvedImages[0] : null)\n\n // Step 6: galleryImages = resolvedImages without mainImage\n var galleryImages = mainImage\n ? resolvedImages.filter(function(url) { return url !== mainImage })\n : resolvedImages.slice()\n\n // Step 7: images = full resolved deduplicated array\n var images = resolvedImages\n\n // -------------------------------------------------------\n // 3D model (one per product; GUI: constants/product-model.ts)\n // -------------------------------------------------------\n // model_url / model_poster_url hold an asset id OR a raw URL like image_url.\n // A poster the merchant never got (capture failed, plan cap) falls back to\n // the main image so <model-viewer> always has something to paint first.\n var modelUrl = resolveMediaUrl(record.model_url, assetMap)\n var modelPoster = modelUrl ? resolveMediaUrl(record.model_poster_url, assetMap) || mainImage : null\n var hasModel = modelUrl ? 'true' : 'false'\n // STRING gate ('true'/'false') like outOfStock: whether the model replaces the\n // main image on the card / details hero. A product whose only media is the\n // model always shows it. An absent field must read as the IMAGE branch, so the\n // builders gate the viewer on = 'true' and the image on != 'true'.\n var showModel =\n modelUrl && (normalizeShowModelFlag(record.show_model_by_default) || images.length === 0)\n ? 'true'\n : 'false'\n var galleryMedia = buildProductGalleryMedia({\n images: images,\n mainImage: mainImage,\n modelUrl: modelUrl,\n modelPoster: modelPoster,\n showModel: showModel,\n imageAlt: imageAlt,\n name: name,\n })\n // Everything that is not the hero \u2014 the details thumbnail strip. When the\n // model is the hero the main image moves in here, so the modal stays reachable.\n var galleryThumbnails = galleryMedia.slice(1)\n\n // Timestamps\n var rawCreatedAt = pickFirst(record.created_at, record.createdAt, record.created)\n var createdAt = normalizeTimestamp(rawCreatedAt)\n\n var rawUpdatedAt = pickFirst(record.updated_at, record.updatedAt, record.updated)\n var updatedAt = rawUpdatedAt != null ? normalizeTimestamp(rawUpdatedAt) : createdAt\n\n // Computed: created = Unix seconds\n var created = Math.floor(createdAt / 1000)\n\n // Computed: outOfStock (emitted as a STRING \u2014 'true' / 'false' \u2014 so it\n // matches the strict equality check the AI generates on product\n // cards/details pages: `ecommerceProduct?.outOfStock === 'true'`.\n // A boolean here would silently fail that comparison (boolean !==\n // string), leaving the Add to Cart button visible on out-of-stock\n // products. NULL/NaN quantity \u2192 'false' (treated as \"unlimited\n // stock\", same as the upstream cart-availability rewriter).\n // With ALLOW_BACKORDERS the merchant sells past zero (or does not track\n // stock at all), so nothing is ever presented as out of stock.\n var outOfStock = (!ALLOW_BACKORDERS && quantity !== null && !isNaN(quantity) && quantity <= 0) ? 'true' : 'false'\n\n // Per-value availability + default-selection flags, derived from the\n // purchasable combinations, so the storefront picker renders its\n // Default / Selected / Unavailable states with NO runtime fetch. The card\n // (N instances) first-paints from these data flags; the details page seeds\n // its selection from the same combinations. axisValueKey (axisKey|valueKey)\n // disambiguates same-named values across axes (Size \"s\" vs Sleeve \"s\").\n // Emitted as STRINGS to match the storefront's string-equality convention.\n var variantAxisKeys = []\n for (var ak = 0; ak < variantOptions.length; ak++) { variantAxisKeys.push(variantOptions[ak].key) }\n var firstVariant = pickFirstAvailableVariant(variants, variantAxisKeys)\n var deadValueKeys = computeDeadVariantKeys(variants, variantOptions, variantsResolved)\n for (var ai = 0; ai < variantOptions.length; ai++) {\n var vax = variantOptions[ai]\n for (var vj = 0; vj < vax.values.length; vj++) {\n var vval = vax.values[vj]\n var composite = vax.key + '|' + vval.value\n vval.axisValueKey = composite\n vval.isDead = deadValueKeys[composite] ? 'true' : 'false'\n vval.isDefault =\n firstVariant && firstVariant.options && firstVariant.options[vax.key] === vval.value\n ? 'true'\n : 'false'\n // Whether THIS value renders as a colour swatch vs a text pill. A colour\n // axis whose value has no resolvable colour degrades to a text pill so it\n // is never an invisible empty circle. Emitted as a string to match the\n // picker's string-equality rendering gate. MUST mirror the renderer\n // enrichment in packages/renderer/src/utils/ecommerce-products.ts.\n vval.showSwatch = vax.type === 'color' && vval.color ? 'true' : 'false'\n }\n }\n // The combination the picker auto-selects on first paint: the first in-stock\n // one covering every axis. Absent means there is nothing the shopper could add\n // without choosing \u2014 which is what gates the buy button below.\n var hasInStockCombination = !!(firstVariant && isVariantInStock(firstVariant))\n var defaultVariantId = hasInStockCombination ? firstVariant.id : ''\n var defaultVariantPrice = firstVariant ? formatVariantPrice(firstVariant.price, price) : ''\n // Gross (tax-inclusive) counterparts of the three price fields the STOREFRONT\n // renders. `price` / `defaultVariantPrice` / `variantsJson` deliberately stay\n // NET: the same transform feeds the merchant's admin panel, and every write\n // path (add-to-cart, checkout, the invoice route) re-reads the raw row and\n // must keep seeing the price the merchant typed. Only these three are safe to\n // gross, because nothing writes them back.\n //\n // MUST mirror packages/renderer/src/utils/ecommerce-products.ts.\n // The scheduled markdown in force right now, resolved from the raw column on\n // every read so a discount starts and expires on its own. It comes off the NET\n // price BEFORE tax: tax is a percentage of what is actually charged.\n var activeDiscount = __pdResolveActive(record.discounts, Date.now())\n var displayPrice = grossMoney(__pdDiscountedPrice(price, activeDiscount))\n var defaultVariantNetPrice = firstVariant\n ? safeNumber(formatVariantPrice(firstVariant.price, price), 0)\n : 0\n var defaultVariantDisplayPrice = firstVariant\n ? grossMoney(__pdDiscountedPrice(defaultVariantNetPrice, activeDiscount))\n : ''\n var variantsDisplay = []\n for (var dv = 0; dv < variants.length; dv++) {\n var dvRow = variants[dv]\n // A null variant price INHERITS the product price, so discount and gross the\n // RESOLVED value \u2014 otherwise an inheriting combination would fall back to\n // the net base price in the picker while an overriding one showed gross.\n var dvNetPrice = dvRow.price == null ? price : dvRow.price\n variantsDisplay.push({\n id: dvRow.id,\n options: dvRow.options,\n price: applyStorefrontTax(__pdDiscountedPrice(dvNetPrice, activeDiscount)),\n // What this combination costs WITHOUT the discount, for the struck-through\n // price beside it. Null when nothing is discounted, so the picker's click\n // resolver can tell \"no saving\" from \"a saving of zero\".\n originalPrice: activeDiscount ? applyStorefrontTax(dvNetPrice) : null,\n quantity: dvRow.quantity,\n image_url: dvRow.image_url,\n })\n }\n // Discount display fields. Strings throughout: rendering conditions compare\n // operands as strings, and a bound text node prints its value verbatim.\n var hasDiscount = activeDiscount ? 'true' : 'false'\n var discountLabel = activeDiscount\n ? __pdDiscountLabel(activeDiscount, currencySymbol, getCurrencyInfo(currency).position)\n : ''\n var originalDisplayPrice = activeDiscount ? grossMoney(price) : ''\n var originalDefaultVariantDisplayPrice =\n activeDiscount && firstVariant ? grossMoney(defaultVariantNetPrice) : ''\n // Can this product be added to the cart at all, before the shopper touches the\n // picker? A STRING, same convention as outOfStock/requiresVariantSelection.\n //\n // flat product -> 'true' (stock is governed by outOfStock)\n // combinations UNKNOWN -> 'true' (the lookup could not run; a transient DB\n // failure must never make a whole catalogue\n // unbuyable \u2014 same permissive rule as\n // dead-marking)\n // otherwise -> whether an in-stock combination covering every axis\n // exists. 'false' therefore covers BOTH \"every\n // combination is sold out\" AND \"the axes have no\n // combinations at all\" \u2014 to a shopper those are the\n // same thing: there is no size to pick.\n //\n // MUST mirror packages/renderer/src/utils/ecommerce-products.ts.\n var hasPurchasableVariant =\n (requiresVariantSelection !== 'true' || !variantsResolved || hasInStockCombination)\n ? 'true'\n : 'false'\n // Aggregate review rating, from ONE batched COUNT/AVG over approved reviews\n // that transformRecords runs for every product on the page (keyed by product\n // id in options.ratingsByProductId).\n //\n // \u26D4 An ABSENT entry and a NULL map both mean \"no rating to show\", never \"0\n // stars\": a product nobody has reviewed and a product whose rating query\n // failed must both render with no stars at all. \"0.0 out of 5\" is the single\n // worst thing a storefront can say about a product by accident.\n //\n // MUST mirror buildProductRatingFields in the GUI's\n // features/e-commerce/utils/product-ratings.ts.\n var ratingsByProductId = options.ratingsByProductId || {}\n var ratingFields = __prBuildRatingFields(id != null ? ratingsByProductId[id] : null)\n\n // The individual reviews behind those stars, for the product page's JSON-LD.\n // Fetched ONLY for a single-product request (see getTransformWrapperCode), so\n // this is an empty array on every listing \u2014 which is correct: a listing emits\n // no Product markup to put them in.\n //\n // Not rendered anywhere. That is why there is no canvas mirror for it: the\n // three-mirror rule exists for fields the editor DRAWS, and structured data\n // is a publish-time concern the canvas has no equivalent of.\n var reviewsByProductId = options.reviewsByProductId || {}\n var reviews = (id != null && reviewsByProductId[id]) || []\n\n // Stringified companions: a data-* attr bound to an ARRAY renders\n // '[object Object]', so the picker's on-mount/click workflows read the\n // combinations + axes from these JSON strings via getAttribute.\n var variantOptionsJson = safeStringifyJson(variantOptions)\n var variantsJson = safeStringifyJson(variants)\n var variantsDisplayJson = safeStringifyJson(variantsDisplay)\n\n return {\n id: id,\n name: name,\n slug: slug,\n description: description,\n descriptionText: descriptionText,\n price: price,\n currency: currency,\n currencySymbol: currencySymbol,\n status: status,\n active: active,\n quantity: quantity,\n paymentType: paymentType,\n recurringInterval: recurringInterval,\n recurringIntervalCount: recurringIntervalCount,\n sku: sku,\n weight: weight,\n weightUnit: weightUnit,\n dimensions: dimensions,\n category: category,\n categories: categories,\n tags: tags,\n relatedProductIds: relatedProductIds,\n relatedProducts: relatedProducts,\n imageAlt: imageAlt,\n providerType: providerType,\n providerProductId: providerProductId,\n default_price: defaultPrice,\n metadata: metadata,\n visibleProperties: visibleProperties,\n mainImage: mainImage,\n imageUrl: mainImage,\n image_url: mainImage,\n galleryImages: galleryImages,\n images: images,\n modelUrl: modelUrl,\n modelPoster: modelPoster,\n hasModel: hasModel,\n showModel: showModel,\n galleryMedia: galleryMedia,\n galleryThumbnails: galleryThumbnails,\n createdAt: createdAt,\n updatedAt: updatedAt,\n created: created,\n outOfStock: outOfStock,\n variantOptions: variantOptions,\n requiresVariantSelection: requiresVariantSelection,\n variants: variants,\n variantOptionsJson: variantOptionsJson,\n variantsJson: variantsJson,\n variantsDisplayJson: variantsDisplayJson,\n defaultVariantId: defaultVariantId,\n defaultVariantPrice: defaultVariantPrice,\n displayPrice: displayPrice,\n defaultVariantDisplayPrice: defaultVariantDisplayPrice,\n hasDiscount: hasDiscount,\n discountLabel: discountLabel,\n originalDisplayPrice: originalDisplayPrice,\n originalDefaultVariantDisplayPrice: originalDefaultVariantDisplayPrice,\n hasPurchasableVariant: hasPurchasableVariant,\n // Aggregate review rating \u2014 see the ratingFields block above.\n ratingAverage: ratingFields.ratingAverage,\n ratingCount: ratingFields.ratingCount,\n ratingAverageLabel: ratingFields.ratingAverageLabel,\n ratingCountLabel: ratingFields.ratingCountLabel,\n hasRatings: ratingFields.hasRatings,\n ratingStar1: ratingFields.ratingStar1,\n ratingStar2: ratingFields.ratingStar2,\n ratingStar3: ratingFields.ratingStar3,\n ratingStar4: ratingFields.ratingStar4,\n ratingStar5: ratingFields.ratingStar5,\n // Domain-shaped, not schema.org-shaped: the head-config plugin's\n // 'reviewList' computed kind does the vocabulary. NO BACKTICKS ANYWHERE IN\n // THIS FILE \u2014 it is one template literal, and a backtick in a comment ends\n // the string.\n reviews: reviews,\n }\n}\n\n// --- Variant availability helpers (mirror packages/renderer ecommerce-products) ---\n// A variant is in stock when its quantity is null (unlimited) or > 0. With\n// ALLOW_BACKORDERS every EXISTING combination is purchasable regardless of its\n// quantity \u2014 but a missing combination (null) is still not in stock: there is\n// no variant row to backorder.\nfunction isVariantInStock(v) {\n if (!v) return false\n if (ALLOW_BACKORDERS) return true\n return v.quantity == null || v.quantity > 0\n}\nfunction variantCoversAllAxes(v, axisKeys) {\n if (!v || !v.options) return false\n for (var i = 0; i < axisKeys.length; i++) {\n if (v.options[axisKeys[i]] == null) return false\n }\n return true\n}\n// First in-stock combination covering every axis; falls back to the first\n// covering combination (even if OOS) so a fully-OOS product still has a\n// visual default; null when no combination covers the axes.\nfunction pickFirstAvailableVariant(variants, axisKeys) {\n if (!Array.isArray(variants) || !axisKeys.length) return null\n for (var i = 0; i < variants.length; i++) {\n if (variantCoversAllAxes(variants[i], axisKeys) && isVariantInStock(variants[i])) return variants[i]\n }\n for (var j = 0; j < variants.length; j++) {\n if (variantCoversAllAxes(variants[j], axisKeys)) return variants[j]\n }\n return null\n}\n// Map of composite \"axisKey|valueKey\" -> true for every value that appears in\n// NO in-stock combination (rendered as the Unavailable state).\n//\n// variantsResolved is the whole subtlety: dead-marking is only meaningful\n// against combinations we actually LOOKED UP. When the lookup could not run,\n// nothing is dead \u2014 a missing table or a failed query must not grey out every\n// picker in the store. When it DID run, an empty list is a fact, not a gap:\n// every value is unbuyable and renders as Unavailable.\nfunction computeDeadVariantKeys(variants, axes, variantsResolved) {\n if (!variantsResolved || !Array.isArray(variants)) return {}\n var alive = {}\n for (var i = 0; i < variants.length; i++) {\n var v = variants[i]\n if (!isVariantInStock(v)) continue\n for (var k in v.options) {\n if (Object.prototype.hasOwnProperty.call(v.options, k)) alive[k + '|' + v.options[k]] = true\n }\n }\n var dead = {}\n for (var a = 0; a < axes.length; a++) {\n var ax = axes[a]\n for (var b = 0; b < ax.values.length; b++) {\n var key = ax.key + '|' + ax.values[b].value\n if (!alive[key]) dead[key] = true\n }\n }\n return dead\n}\n// Variant price with base-price inheritance (null variant price -> product price).\nfunction formatVariantPrice(vprice, basePrice) {\n var p = vprice == null || isNaN(vprice) ? basePrice : vprice\n return String(Number(p).toFixed(2))\n}\nfunction safeStringifyJson(obj) {\n try {\n return JSON.stringify(obj)\n } catch (e) {\n return '[]'\n }\n}\n\n// Parse + normalize the variant_options JSON into render-ready axes. Tolerant of\n// null / malformed / partial data (returns []). Keeps ONLY the fields the pill\n// widget needs; the labels are already language-resolved by the caller.\nfunction normalizeVariantOptions(raw) {\n if (!raw) return []\n var parsed = raw\n if (typeof raw === 'string') {\n try { parsed = JSON.parse(raw) } catch (e) { return [] }\n }\n if (!Array.isArray(parsed)) return []\n var out = []\n for (var i = 0; i < parsed.length; i++) {\n var axis = parsed[i]\n if (!axis || typeof axis !== 'object' || !Array.isArray(axis.values)) continue\n var name = typeof axis.name === 'string' ? axis.name : ''\n var key = typeof axis.key === 'string' && axis.key ? axis.key : name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n if (!key) continue\n var type = axis.type === 'color' ? 'color' : 'text'\n var values = []\n for (var j = 0; j < axis.values.length; j++) {\n var v = axis.values[j]\n if (!v || typeof v !== 'object') continue\n var label = typeof v.label === 'string' ? v.label : ''\n var value = typeof v.value === 'string' && v.value ? v.value : label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n if (!value) continue\n var entry = { value: value, label: label }\n if (type === 'color' && typeof v.color === 'string' && v.color) entry.color = v.color\n values.push(entry)\n }\n if (!values.length) continue\n out.push({ key: key, name: name, type: type, values: values })\n }\n return out\n}\n\n// --- Custom-property classification (MUST mirror product-property-display.ts) ---\n\n// Product-attribute keys that can leak into the free-form `metadata` map (e.g.\n// from a payment-provider sync or legacy data) but are NOT user custom\n// properties. Kept in sync with the GUI's RESERVED_PRODUCT_METADATA_KEYS.\nvar RESERVED_PRODUCT_METADATA_KEYS = {\n paymentType: true, recurringInterval: true, recurringIntervalCount: true,\n price: true, currency: true, status: true, sku: true, weightUnit: true,\n dimensions: true, category: true, brand: true, gtin: true, mpn: true,\n condition: true, tags: true,\n}\nfunction isReservedProductMetadataKey(key) {\n return !!RESERVED_PRODUCT_METADATA_KEYS[key] ||\n key.indexOf('mainImage') === 0 ||\n key.indexOf('secondaryImage') === 0 ||\n key.indexOf('_tq') === 0\n}\n\nvar CSS_NAMED_COLORS = {\n aliceblue: 1, antiquewhite: 1, aqua: 1, aquamarine: 1, azure: 1, beige: 1, bisque: 1,\n black: 1, blanchedalmond: 1, blue: 1, blueviolet: 1, brown: 1, burlywood: 1,\n cadetblue: 1, chartreuse: 1, chocolate: 1, coral: 1, cornflowerblue: 1, cornsilk: 1,\n crimson: 1, cyan: 1, darkblue: 1, darkcyan: 1, darkgoldenrod: 1, darkgray: 1,\n darkgrey: 1, darkgreen: 1, darkkhaki: 1, darkmagenta: 1, darkolivegreen: 1,\n darkorange: 1, darkorchid: 1, darkred: 1, darksalmon: 1, darkseagreen: 1,\n darkslateblue: 1, darkslategray: 1, darkslategrey: 1, darkturquoise: 1,\n darkviolet: 1, deeppink: 1, deepskyblue: 1, dimgray: 1, dimgrey: 1, dodgerblue: 1,\n firebrick: 1, floralwhite: 1, forestgreen: 1, fuchsia: 1, gainsboro: 1,\n ghostwhite: 1, gold: 1, goldenrod: 1, gray: 1, grey: 1, green: 1, greenyellow: 1,\n honeydew: 1, hotpink: 1, indianred: 1, indigo: 1, ivory: 1, khaki: 1, lavender: 1,\n lavenderblush: 1, lawngreen: 1, lemonchiffon: 1, lightblue: 1, lightcoral: 1,\n lightcyan: 1, lightgoldenrodyellow: 1, lightgray: 1, lightgrey: 1, lightgreen: 1,\n lightpink: 1, lightsalmon: 1, lightseagreen: 1, lightskyblue: 1, lightslategray: 1,\n lightslategrey: 1, lightsteelblue: 1, lightyellow: 1, lime: 1, limegreen: 1,\n linen: 1, magenta: 1, maroon: 1, mediumaquamarine: 1, mediumblue: 1,\n mediumorchid: 1, mediumpurple: 1, mediumseagreen: 1, mediumslateblue: 1,\n mediumspringgreen: 1, mediumturquoise: 1, mediumvioletred: 1, midnightblue: 1,\n mintcream: 1, mistyrose: 1, moccasin: 1, navajowhite: 1, navy: 1, oldlace: 1,\n olive: 1, olivedrab: 1, orange: 1, orangered: 1, orchid: 1, palegoldenrod: 1,\n palegreen: 1, paleturquoise: 1, palevioletred: 1, papayawhip: 1, peachpuff: 1,\n peru: 1, pink: 1, plum: 1, powderblue: 1, purple: 1, rebeccapurple: 1, red: 1,\n rosybrown: 1, royalblue: 1, saddlebrown: 1, salmon: 1, sandybrown: 1, seagreen: 1,\n seashell: 1, sienna: 1, silver: 1, skyblue: 1, slateblue: 1, slategray: 1,\n slategrey: 1, snow: 1, springgreen: 1, steelblue: 1, tan: 1, teal: 1, thistle: 1,\n tomato: 1, turquoise: 1, violet: 1, wheat: 1, white: 1, whitesmoke: 1, yellow: 1,\n yellowgreen: 1, transparent: 1,\n}\nvar HEX_COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\nvar FUNCTIONAL_COLOR_RE = /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\\((?:[0-9a-z%.,\\s/+-]+)\\)$/i\nvar COLOR_KEY_WORDS = {\n color: 1, colors: 1, colour: 1, colours: 1, shade: 1, shades: 1, hue: 1, hues: 1,\n tint: 1, tints: 1, tone: 1, tones: 1, swatch: 1, swatches: 1,\n}\nfunction splitKeyWords(key) {\n return key.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)\n}\nfunction keyIndicatesColor(key) {\n var normalized = key.toLowerCase()\n if (/colou?r/.test(normalized)) return true\n return splitKeyWords(key).some(function(word) { return !!COLOR_KEY_WORDS[word] })\n}\nfunction resolvePropertyColor(key, value) {\n var v = value.trim()\n if (!v) return ''\n if (HEX_COLOR_RE.test(v) || FUNCTIONAL_COLOR_RE.test(v)) return v\n if (CSS_NAMED_COLORS[v.toLowerCase()] && keyIndicatesColor(key)) return v\n return ''\n}\n\nvar DATA_IMAGE_URI_RE = /^data:image\\//i\nvar ABSOLUTE_URL_RE = /^(?:https?:)?\\/\\//i\nvar IMAGE_EXTENSION_RE = /\\.(?:png|jpe?g|gif|webp|svg|avif|bmp|ico|tiff?|heic|heif)$/i\nvar IMAGE_KEY_WORDS = {\n image: 1, images: 1, img: 1, imgs: 1, photo: 1, photos: 1, picture: 1, pictures: 1,\n pic: 1, pics: 1, thumbnail: 1, thumbnails: 1, thumb: 1, thumbs: 1, icon: 1, icons: 1,\n logo: 1, logos: 1, avatar: 1, avatars: 1, banner: 1, banners: 1, cover: 1, covers: 1,\n gallery: 1, screenshot: 1, screenshots: 1, poster: 1, posters: 1, artwork: 1,\n graphic: 1, graphics: 1, illustration: 1, wallpaper: 1, preview: 1, snapshot: 1,\n media: 1, visual: 1, visuals: 1,\n}\nfunction keyIndicatesImage(key) {\n var normalized = key.toLowerCase()\n if (/(?:image|img|photo|picture|thumb|icon|logo|avatar|banner|gallery|screenshot|poster|artwork|graphic|wallpaper)/.test(normalized)) return true\n return splitKeyWords(key).some(function(word) { return !!IMAGE_KEY_WORDS[word] })\n}\nfunction stripUrlQueryAndHash(url) {\n return url.split(/[?#]/)[0]\n}\nfunction resolvePropertyImage(key, value) {\n var v = value.trim()\n if (!v) return ''\n if (DATA_IMAGE_URI_RE.test(v)) return v\n var isAbsoluteUrl = ABSOLUTE_URL_RE.test(v)\n var isRootRelative = v.charAt(0) === '/' && !isAbsoluteUrl\n if (!isAbsoluteUrl && !isRootRelative) return ''\n if (IMAGE_EXTENSION_RE.test(stripUrlQueryAndHash(v))) return v\n if (isAbsoluteUrl && keyIndicatesImage(key)) return v\n return ''\n}\n\n// Image wins over colour (a URL can never be a CSS colour, but checking image\n// first keeps the precedence explicit), text is the fallback.\nfunction classifyProductProperty(key, value) {\n var imageUrl = resolvePropertyImage(key, value)\n if (imageUrl) return { key: key, value: value, kind: 'image', color: '', imageUrl: imageUrl }\n var color = resolvePropertyColor(key, value)\n if (color) return { key: key, value: value, kind: 'color', color: color, imageUrl: '' }\n return { key: key, value: value, kind: 'text', color: '', imageUrl: '' }\n}\n\nfunction transformEcommerceProducts(records, options) {\n if (!Array.isArray(records)) return []\n return records.map(function(record) { return buildEcommerceProduct(record, options) })\n}\n\n// Batched fetch of the purchasable variant rows for a set of product ids, keyed\n// by product_id, so buildEcommerceProduct can attach product.variants without a\n// per-product query. Best-effort: a store with no variants (or before the table\n// exists) yields an empty map and flat products keep variants: [].\n// Batched fetch of the product rows a set of products reference as \"related\",\n// keyed by id, so buildEcommerceProduct can attach product.relatedProducts\n// without a query per product.\n//\n// Best-effort by design: a store whose products table predates the column\n// yields no ids at all (the read below is of an absent property, not of a\n// column \u2014 the SQL never names it), the map stays empty, and the details page's\n// rail simply stays hidden behind its is_not_empty gate. Same for a failed\n// query.\nasync function getRelatedProductsMap(getClientFn, records) {\n var map = {}\n if (!Array.isArray(records) || records.length === 0) return map\n\n var wantedIds = []\n for (var i = 0; i < records.length; i++) {\n var ids = parseRelatedIds(records[i] && records[i].related_product_ids)\n for (var j = 0; j < ids.length; j++) {\n if (wantedIds.indexOf(ids[j]) === -1) wantedIds.push(ids[j])\n }\n }\n if (wantedIds.length === 0) return map\n\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query('SELECT * FROM teleport_products WHERE id = ANY($1)', [\n wantedIds,\n ])\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n if (row && row.id != null) map[String(row.id)] = row\n }\n }\n } catch (e) {\n // Leaves relatedProducts empty rather than failing the page.\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n\n// Aggregate review rating for every product on the page, keyed by product id,\n// so a card can draw its star row without a query per product.\n//\n// APPROVED ONLY, and 'approved' is a fixed literal rather than a bound value\n// because nothing may ever widen it: a pending review is one the merchant has\n// not agreed to publish, and a rejected one is a review they actively removed.\n//\n// Unlike getVariantsMap this returns an EMPTY MAP on failure rather than null.\n// The two \"unknown\" answers differ because the consequences differ: an unknown\n// variant map must stay permissive (never make a catalogue unbuyable), whereas\n// an unknown rating has exactly one safe rendering \u2014 no stars \u2014 which is also\n// what a product with no reviews shows. Collapsing both onto {} means every\n// caller has one case to handle instead of two.\nasync function getRatingsMap(getClientFn, productIds) {\n var map = {}\n if (!Array.isArray(productIds) || productIds.length === 0) return map\n var uniqueIds = []\n var seenIds = {}\n for (var u = 0; u < productIds.length; u++) {\n var pid0 = productIds[u]\n if (pid0 != null && !seenIds[pid0]) { seenIds[pid0] = true; uniqueIds.push(pid0) }\n }\n if (uniqueIds.length === 0) return map\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query(\n \"SELECT product_id, AVG(rating)::float AS average, COUNT(*)::int AS count \" +\n 'FROM teleport_product_reviews ' +\n \"WHERE status = 'approved' AND rating IS NOT NULL AND product_id = ANY($1) \" +\n 'GROUP BY product_id',\n [uniqueIds]\n )\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n if (row && row.product_id != null) {\n map[row.product_id] = { average: row.average, count: row.count }\n }\n }\n }\n } catch (e) {\n // teleport_product_reviews may not exist (reviews were never enabled), or\n // the query may have failed. Either way there is no rating to show, which\n // is exactly what an empty map produces.\n map = {}\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n\n// The most recent APPROVED reviews for a product, for the product page's\n// structured data. Keyed by product id like every other batched lookup, though\n// in practice it is only ever called with one id.\n//\n// Three filters, and each one exists because of what the output is used for:\n// - APPROVED only, as a fixed literal, for the same reason the aggregate is:\n// a pending review is one the merchant has not agreed to publish.\n// - A NON-EMPTY reviewer name. Google requires author.name on a review\n// snippet, and an anonymous row would produce a Review object it rejects \u2014\n// taking the whole Product block down with it on some validators.\n// - A CAP. The reviews are inlined into the page's props and then into its\n// HTML twice over (once as data, once as JSON-LD); a product with four\n// hundred reviews would otherwise put all of them in both.\nasync function getProductReviewsMap(getClientFn, productIds, perProduct) {\n var map = {}\n if (!Array.isArray(productIds) || productIds.length === 0) return map\n var uniqueIds = []\n var seenIds = {}\n for (var u = 0; u < productIds.length; u++) {\n var pid0 = productIds[u]\n if (pid0 != null && !seenIds[pid0]) { seenIds[pid0] = true; uniqueIds.push(pid0) }\n }\n if (uniqueIds.length === 0) return map\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query(\n 'SELECT product_id, reviewer_name, rating, content, created_at ' +\n 'FROM teleport_product_reviews ' +\n \"WHERE status = 'approved' AND rating IS NOT NULL \" +\n \"AND reviewer_name IS NOT NULL AND btrim(reviewer_name) <> '' \" +\n 'AND product_id = ANY($1) ' +\n 'ORDER BY created_at DESC',\n [uniqueIds]\n )\n var cap = typeof perProduct === 'number' && perProduct > 0 ? perProduct : 5\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n if (!row || row.product_id == null) continue\n var bucket = map[row.product_id] || (map[row.product_id] = [])\n if (bucket.length >= cap) continue\n bucket.push({\n author: String(row.reviewer_name).trim(),\n rating: Number(row.rating),\n body: row.content == null ? '' : String(row.content),\n datePublished: row.created_at ? new Date(row.created_at).toISOString() : null,\n })\n }\n }\n } catch (e) {\n // The reviews table may not exist (reviews were never enabled). No reviews\n // to show is both the empty answer and the safe one.\n map = {}\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n\n// Combinations for every product on the page, keyed by product id. Returns NULL\n// when the lookup could not run, which the transform reads as \"unknown\" and\n// stays permissive with; an empty map means the query ran and this catalogue\n// simply has no combinations.\nasync function getVariantsMap(getClientFn, productIds) {\n var map = {}\n if (!Array.isArray(productIds) || productIds.length === 0) return map\n var uniqueIds = []\n var seenIds = {}\n for (var u = 0; u < productIds.length; u++) {\n var pid0 = productIds[u]\n if (pid0 != null && !seenIds[pid0]) { seenIds[pid0] = true; uniqueIds.push(pid0) }\n }\n if (uniqueIds.length === 0) return map\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query(\n 'SELECT id, product_id, options, price, quantity, image_url FROM teleport_product_variants WHERE product_id = ANY($1) ORDER BY position ASC, id ASC',\n [uniqueIds]\n )\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n var pid = row.product_id\n if (!map[pid]) map[pid] = []\n map[pid].push(row)\n }\n }\n } catch (e) {\n // teleport_product_variants may not exist for a non-variant store, or the\n // query may have failed. Either way the combinations are UNKNOWN \u2014 null\n // keeps every picker selectable instead of declaring the catalogue unbuyable.\n map = null\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n");
|
|
50
17
|
};
|
|
51
18
|
exports.generateEcommerceProductTransformationCode = generateEcommerceProductTransformationCode;
|
|
52
19
|
//# sourceMappingURL=ecommerce-product.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ecommerce-product.js","sourceRoot":"","sources":["../../../src/transformations/ecommerce-product.ts"],"names":[],"mappings":";;;AACA,+
|
|
1
|
+
{"version":3,"file":"ecommerce-product.js","sourceRoot":"","sources":["../../../src/transformations/ecommerce-product.ts"],"names":[],"mappings":";;;AACA,+DAA6F;AAC7F,yDAAkE;AA6BlE;;;;GAIG;AACI,IAAM,0CAA0C,GAAG,UACxD,OAA8C;;IAA9C,wBAAA,EAAA,YAA8C;IAE9C,IAAM,aAAa,GAAG,+BAAa,CAAC,+BAA+B,CACjE,MAAA,OAAO,CAAC,iBAAiB,mCAAI,CAAC,CAC/B,CAAA;IACD,IAAM,sBAAsB,GAAG,OAAO,CAAC,eAAe,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;IAElF,OAAO,YACP,aAAa,eACb,kCAAgB,CAAC,iCAAiC,EAAE,eACpD,gCAAc,CAAC,+BAA+B,EAAE,yRAKzB,sBAAsB,iBAE7C,IAAA,gDAA4B,EAAC,0BAA0B,EAAE,OAAO,CAAC,UAAU,CAAC,4o5CAg8B7E,CAAA;AACD,CAAC,CAAA;AAn9BY,QAAA,0CAA0C,8CAm9BtD"}
|
|
@@ -1,6 +1,16 @@
|
|
|
1
|
-
import type { GeneratorOptions } from '@teleporthq/teleport-types';
|
|
1
|
+
import type { GeneratorOptions, UIDLEcommerceCategory } from '@teleporthq/teleport-types';
|
|
2
2
|
import { type EcommerceProductTransformOptions } from './ecommerce-product';
|
|
3
3
|
export type { EcommerceProductTransformOptions };
|
|
4
|
+
/**
|
|
5
|
+
* Everything a generated fetcher bakes in, for EITHER entity. One options object
|
|
6
|
+
* because `getTransformationCode` is called with a table name and has to be able
|
|
7
|
+
* to serve whichever transform that resolves to — the product fields are ignored
|
|
8
|
+
* for a blog table and vice versa.
|
|
9
|
+
*/
|
|
10
|
+
export interface EntityTransformOptions extends EcommerceProductTransformOptions {
|
|
11
|
+
/** Blog post-category taxonomy — see `blogSettings.categories`. */
|
|
12
|
+
blogCategories?: UIDLEcommerceCategory[];
|
|
13
|
+
}
|
|
4
14
|
/**
|
|
5
15
|
* Collects everything the product transform bakes in from the generator
|
|
6
16
|
* options, in ONE place so every fetcher-emitting call site stays in step.
|
|
@@ -10,8 +20,8 @@ export type { EcommerceProductTransformOptions };
|
|
|
10
20
|
* tax-inclusive or untaxed stores. `allowBackorders` is the effective
|
|
11
21
|
* "stock never blocks a purchase" flag — see `resolveAllowBackorders`.
|
|
12
22
|
*/
|
|
13
|
-
export declare const buildProductTransformOptions: (options: Pick<GeneratorOptions, 'ecommerceSettings' | 'invoiceSettings'>) =>
|
|
14
|
-
export type TransformationType = 'blog-post' | 'ecommerce-product' | null;
|
|
23
|
+
export declare const buildProductTransformOptions: (options: Pick<GeneratorOptions, 'ecommerceSettings' | 'invoiceSettings' | 'blogSettings'>) => EntityTransformOptions;
|
|
24
|
+
export type TransformationType = 'blog-post' | 'ecommerce-product' | 'custom-page' | null;
|
|
15
25
|
/**
|
|
16
26
|
* Detects which transformation type to apply based on the table name.
|
|
17
27
|
* Returns null if no transformation is needed.
|
|
@@ -30,7 +40,7 @@ export declare const detectTransformationType: (tableName: string) => Transforma
|
|
|
30
40
|
* to be included in the generated data source fetcher file.
|
|
31
41
|
* Returns empty string if no transformation is needed for this table.
|
|
32
42
|
*/
|
|
33
|
-
export declare const getTransformationCode: (tableName: string, options?:
|
|
43
|
+
export declare const getTransformationCode: (tableName: string, options?: EntityTransformOptions) => string;
|
|
34
44
|
/**
|
|
35
45
|
* Returns the JavaScript expression that transforms the data array.
|
|
36
46
|
* This expression assumes the data array variable is called `safeData`,
|
|
@@ -38,6 +48,15 @@ export declare const getTransformationCode: (tableName: string, options?: Ecomme
|
|
|
38
48
|
* Returns null if no transformation is needed.
|
|
39
49
|
*/
|
|
40
50
|
export declare const getTransformExpression: (tableName: string) => string | null;
|
|
51
|
+
/**
|
|
52
|
+
* How many reviews a product page carries into its structured data.
|
|
53
|
+
*
|
|
54
|
+
* They are inlined TWICE — once into the page's props, once into the JSON-LD
|
|
55
|
+
* script rendered from them — so this number is paid for in bytes on every
|
|
56
|
+
* request. Five is what a review snippet shows; the rest are on the page itself,
|
|
57
|
+
* fetched by the reviews section's own paginated query.
|
|
58
|
+
*/
|
|
59
|
+
export declare const REVIEWS_PER_PRODUCT = 5;
|
|
41
60
|
/**
|
|
42
61
|
* Returns the transform wrapper function code that handles asset map loading
|
|
43
62
|
* and calls the appropriate transformer.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/transformations/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/transformations/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;AAKzF,OAAO,EAEL,KAAK,gCAAgC,EACtC,MAAM,qBAAqB,CAAA;AAE5B,YAAY,EAAE,gCAAgC,EAAE,CAAA;AAEhD;;;;;GAKG;AACH,MAAM,WAAW,sBAAuB,SAAQ,gCAAgC;IAC9E,mEAAmE;IACnE,cAAc,CAAC,EAAE,qBAAqB,EAAE,CAAA;CACzC;AAkBD;;;;;;;;GAQG;AACH,eAAO,MAAM,4BAA4B,YAC9B,KAAK,gBAAgB,EAAE,mBAAmB,GAAG,iBAAiB,GAAG,cAAc,CAAC,KACxF,sBAKD,CAAA;AAEF,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,mBAAmB,GAAG,aAAa,GAAG,IAAI,CAAA;AAezF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,wBAAwB,cAAe,MAAM,KAAG,kBAe5D,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,cACrB,MAAM,YACR,sBAAsB,KAC9B,MAkBF,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,cAAe,MAAM,KAAG,MAAM,GAAG,IAgBnE,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAA;AAEpC;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,cAAe,MAAM,KAAG,MAiI3D,CAAA"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getTransformWrapperCode = exports.getTransformExpression = exports.getTransformationCode = exports.detectTransformationType = exports.buildProductTransformOptions = void 0;
|
|
3
|
+
exports.getTransformWrapperCode = exports.REVIEWS_PER_PRODUCT = exports.getTransformExpression = exports.getTransformationCode = exports.detectTransformationType = exports.buildProductTransformOptions = void 0;
|
|
4
4
|
var teleport_shared_1 = require("@teleporthq/teleport-shared");
|
|
5
5
|
var shared_utils_1 = require("./shared-utils");
|
|
6
6
|
var blog_post_1 = require("./blog-post");
|
|
7
|
+
var custom_page_1 = require("./custom-page");
|
|
7
8
|
var ecommerce_product_1 = require("./ecommerce-product");
|
|
8
9
|
/**
|
|
9
10
|
* Stock never gates purchasability when the merchant disabled stock management
|
|
@@ -29,9 +30,10 @@ var resolveAllowBackorders = function (settings) {
|
|
|
29
30
|
* "stock never blocks a purchase" flag — see `resolveAllowBackorders`.
|
|
30
31
|
*/
|
|
31
32
|
var buildProductTransformOptions = function (options) {
|
|
32
|
-
var _a;
|
|
33
|
+
var _a, _b;
|
|
33
34
|
return ({
|
|
34
35
|
categories: (_a = options.ecommerceSettings) === null || _a === void 0 ? void 0 : _a.categories,
|
|
36
|
+
blogCategories: (_b = options.blogSettings) === null || _b === void 0 ? void 0 : _b.categories,
|
|
35
37
|
storefrontTaxRate: teleport_shared_1.StorefrontTax.resolveStorefrontTaxRate(options.invoiceSettings),
|
|
36
38
|
allowBackorders: resolveAllowBackorders(options.ecommerceSettings),
|
|
37
39
|
});
|
|
@@ -72,6 +74,9 @@ var detectTransformationType = function (tableName) {
|
|
|
72
74
|
if (bare === 'teleport_products') {
|
|
73
75
|
return 'ecommerce-product';
|
|
74
76
|
}
|
|
77
|
+
if (bare === 'teleport_pages') {
|
|
78
|
+
return 'custom-page';
|
|
79
|
+
}
|
|
75
80
|
return null;
|
|
76
81
|
};
|
|
77
82
|
exports.detectTransformationType = detectTransformationType;
|
|
@@ -89,9 +94,11 @@ var getTransformationCode = function (tableName, options) {
|
|
|
89
94
|
var shared = (0, shared_utils_1.generateSharedTransformationCode)();
|
|
90
95
|
switch (type) {
|
|
91
96
|
case 'blog-post':
|
|
92
|
-
return shared + (0, blog_post_1.generateBlogPostTransformationCode)();
|
|
97
|
+
return shared + (0, blog_post_1.generateBlogPostTransformationCode)({ categories: options.blogCategories });
|
|
93
98
|
case 'ecommerce-product':
|
|
94
99
|
return shared + (0, ecommerce_product_1.generateEcommerceProductTransformationCode)(options);
|
|
100
|
+
case 'custom-page':
|
|
101
|
+
return shared + (0, custom_page_1.generateCustomPageTransformationCode)();
|
|
95
102
|
default:
|
|
96
103
|
return '';
|
|
97
104
|
}
|
|
@@ -113,11 +120,22 @@ var getTransformExpression = function (tableName) {
|
|
|
113
120
|
return 'await transformRecords(safeData, getClient, req.query)';
|
|
114
121
|
case 'ecommerce-product':
|
|
115
122
|
return 'await transformRecords(safeData, getClient, req.query)';
|
|
123
|
+
case 'custom-page':
|
|
124
|
+
return 'await transformRecords(safeData, getClient, req.query)';
|
|
116
125
|
default:
|
|
117
126
|
return null;
|
|
118
127
|
}
|
|
119
128
|
};
|
|
120
129
|
exports.getTransformExpression = getTransformExpression;
|
|
130
|
+
/**
|
|
131
|
+
* How many reviews a product page carries into its structured data.
|
|
132
|
+
*
|
|
133
|
+
* They are inlined TWICE — once into the page's props, once into the JSON-LD
|
|
134
|
+
* script rendered from them — so this number is paid for in bytes on every
|
|
135
|
+
* request. Five is what a review snippet shows; the rest are on the page itself,
|
|
136
|
+
* fetched by the reviews section's own paginated query.
|
|
137
|
+
*/
|
|
138
|
+
exports.REVIEWS_PER_PRODUCT = 5;
|
|
121
139
|
/**
|
|
122
140
|
* Returns the transform wrapper function code that handles asset map loading
|
|
123
141
|
* and calls the appropriate transformer.
|
|
@@ -128,7 +146,11 @@ var getTransformWrapperCode = function (tableName) {
|
|
|
128
146
|
if (!type) {
|
|
129
147
|
return '';
|
|
130
148
|
}
|
|
131
|
-
var transformFn = type === 'blog-post'
|
|
149
|
+
var transformFn = type === 'blog-post'
|
|
150
|
+
? 'transformBlogPosts'
|
|
151
|
+
: type === 'custom-page'
|
|
152
|
+
? 'transformCustomPages'
|
|
153
|
+
: 'transformEcommerceProducts';
|
|
132
154
|
// Products additionally get their purchasable variant combinations attached in
|
|
133
155
|
// ONE batched query (keyed by product id). Blog posts have no such enrichment.
|
|
134
156
|
//
|
|
@@ -142,9 +164,11 @@ var getTransformWrapperCode = function (tableName) {
|
|
|
142
164
|
// page draws as real product cards, each with its own picker — get their
|
|
143
165
|
// combinations from the SAME query instead of transforming as variant-less.
|
|
144
166
|
var variantEnrichment = type === 'ecommerce-product'
|
|
145
|
-
? "\n var variantsByProductId = null\n try
|
|
167
|
+
? "\n var variantsByProductId = null\n // Declared OUTSIDE the try because the ratings lookup below reuses it. `var`\n // would hoist it anyway, but relying on that would make this block break\n // silently the day someone modernises it to `let`.\n var __variantPids = []\n try {\n for (var __i = 0; __i < records.length; __i++) {\n if (records[__i] && records[__i].id != null) __variantPids.push(records[__i].id)\n }\n if (relatedProductsById) {\n for (var __rk in relatedProductsById) {\n if (!Object.prototype.hasOwnProperty.call(relatedProductsById, __rk)) continue\n // The ROW's own id, not the map key: the key was stringified when the map\n // was built, and a query parameter array of mixed types is one the driver\n // cannot type against the product_id column.\n var __rrow = relatedProductsById[__rk]\n if (__rrow && __rrow.id != null) __variantPids.push(__rrow.id)\n }\n }\n variantsByProductId = await getVariantsMap(getClientFn, __variantPids)\n } catch (e) {\n // Leaves the map null \u2014 \"unknown\", never \"none\".\n }\n // The aggregate star rating for the same id set, in ONE more query. Reuses\n // __variantPids so a details page's related cards get their ratings from the\n // same round trip rather than one query per card.\n //\n // Unlike the variants map this stays {} on failure: \"no rating to show\" is\n // both the empty answer and the safe answer, so there is no unknown state for\n // a caller to reason about.\n var ratingsByProductId = {}\n try {\n ratingsByProductId = await getRatingsMap(getClientFn, __variantPids)\n } catch (e) {\n // Leaves the map empty \u2014 the star rows simply stay hidden.\n }\n // The individual reviews behind the stars, for the product page's JSON-LD.\n //\n // Gated on the SINGLE-RECORD heuristic, unlike the two lookups above. Those\n // feed something every card on the page draws; this feeds structured data,\n // which only a details page emits \u2014 and a listing of 24 products would\n // otherwise fetch and inline 120 review rows that nothing on it renders or\n // markup-references.\n var reviewsByProductId = {}\n if (Array.isArray(records) && records.length === 1) {\n try {\n reviewsByProductId = await getProductReviewsMap(getClientFn, __variantPids, ".concat(exports.REVIEWS_PER_PRODUCT, ")\n } catch (e) {\n // Best-effort; the product simply ships without review snippets.\n }\n }")
|
|
168
|
+
: '';
|
|
169
|
+
var variantOption = type === 'ecommerce-product'
|
|
170
|
+
? ', variantsByProductId: variantsByProductId, ratingsByProductId: ratingsByProductId, reviewsByProductId: reviewsByProductId'
|
|
146
171
|
: '';
|
|
147
|
-
var variantOption = type === 'ecommerce-product' ? ', variantsByProductId: variantsByProductId' : '';
|
|
148
172
|
// Related items are resolved for a SINGLE-record fetch only — which is the
|
|
149
173
|
// details page, the one surface that renders them (it looks the row up by
|
|
150
174
|
// slug). A listing fetch returns many rows, and resolving there would run an
|
|
@@ -156,10 +180,16 @@ var getTransformWrapperCode = function (tableName) {
|
|
|
156
180
|
// A one-product store's listing does pay for one extra query. That is the
|
|
157
181
|
// whole cost of the heuristic, and it beats plumbing a page-role flag through
|
|
158
182
|
// every fetcher.
|
|
183
|
+
// Custom pages have no related items and no variants: their transform only
|
|
184
|
+
// normalises the row's SEO fields.
|
|
185
|
+
var hasRelatedItems = type === 'blog-post' || type === 'ecommerce-product';
|
|
159
186
|
var relatedMapVar = type === 'blog-post' ? 'relatedPostsById' : 'relatedProductsById';
|
|
160
187
|
var relatedMapFn = type === 'blog-post' ? 'getRelatedPostsMap' : 'getRelatedProductsMap';
|
|
161
|
-
var relatedEnrichment =
|
|
162
|
-
|
|
188
|
+
var relatedEnrichment = hasRelatedItems
|
|
189
|
+
? "\n var ".concat(relatedMapVar, " = null\n if (Array.isArray(records) && records.length === 1) {\n try {\n ").concat(relatedMapVar, " = await ").concat(relatedMapFn, "(getClientFn, records)\n } catch (e) {\n // Best-effort; the related rail stays hidden behind its empty gate.\n }\n }")
|
|
190
|
+
: '';
|
|
191
|
+
var relatedOption = hasRelatedItems ? ", ".concat(relatedMapVar, ": ").concat(relatedMapVar) : '';
|
|
192
|
+
return "\nasync function transformRecords(records, getClientFn, reqQuery) {\n var assetMap = {}\n try {\n assetMap = await getAssetMap(getClientFn)\n } catch (e) {\n // Asset resolution is best-effort; continue without it\n }".concat(relatedEnrichment).concat(variantEnrichment, "\n var currentLanguage = (reqQuery && reqQuery.lang) || null\n var mainLanguage = (reqQuery && reqQuery.mainLang) || null\n var options = { assetMap: assetMap, currentLanguage: currentLanguage, mainLanguage: mainLanguage").concat(variantOption).concat(relatedOption, " }\n return ").concat(transformFn, "(records, options)\n}\n");
|
|
163
193
|
};
|
|
164
194
|
exports.getTransformWrapperCode = getTransformWrapperCode;
|
|
165
195
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/transformations/index.ts"],"names":[],"mappings":";;;AACA,+DAA2D;AAC3D,+CAAiE;AACjE,yCAAgE;AAChE,yDAG4B;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/transformations/index.ts"],"names":[],"mappings":";;;AACA,+DAA2D;AAC3D,+CAAiE;AACjE,yCAAgE;AAChE,6CAAoE;AACpE,yDAG4B;AAe5B;;;;;;GAMG;AACH,IAAM,sBAAsB,GAAG,UAC7B,QAA2D;;IAE3D,IAAI,CAAC,QAAQ,EAAE;QACb,OAAO,KAAK,CAAA;KACb;IACD,OAAO,CAAC,QAAQ,CAAC,eAAe,IAAI,CAAA,MAAA,QAAQ,CAAC,qBAAqB,0CAAE,eAAe,MAAK,IAAI,CAAA;AAC9F,CAAC,CAAA;AAED;;;;;;;;GAQG;AACI,IAAM,4BAA4B,GAAG,UAC1C,OAAyF;;IAC9D,OAAA,CAAC;QAC5B,UAAU,EAAE,MAAA,OAAO,CAAC,iBAAiB,0CAAE,UAAU;QACjD,cAAc,EAAE,MAAA,OAAO,CAAC,YAAY,0CAAE,UAAU;QAChD,iBAAiB,EAAE,+BAAa,CAAC,wBAAwB,CAAC,OAAO,CAAC,eAAe,CAAC;QAClF,eAAe,EAAE,sBAAsB,CAAC,OAAO,CAAC,iBAAiB,CAAC;KACnE,CAAC,CAAA;CAAA,CAAA;AAPW,QAAA,4BAA4B,gCAOvC;AAIF;;;;GAIG;AACH,IAAM,oBAAoB,GAAG,UAAC,SAAiB;IAC7C,IAAM,KAAK,GAAG,SAAS,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAA;IAC5C,IAAM,OAAO,GAAG,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAA;IACtC,IAAM,IAAI,GAAG,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;IAC5D,kEAAkE;IAClE,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAA;AACnC,CAAC,CAAA;AAED;;;;;;;;;;;GAWG;AACI,IAAM,wBAAwB,GAAG,UAAC,SAAiB;IACxD,IAAI,CAAC,SAAS,EAAE;QACd,OAAO,IAAI,CAAA;KACZ;IACD,IAAM,IAAI,GAAG,oBAAoB,CAAC,SAAS,CAAC,CAAA;IAC5C,IAAI,IAAI,KAAK,qBAAqB,EAAE;QAClC,OAAO,WAAW,CAAA;KACnB;IACD,IAAI,IAAI,KAAK,mBAAmB,EAAE;QAChC,OAAO,mBAAmB,CAAA;KAC3B;IACD,IAAI,IAAI,KAAK,gBAAgB,EAAE;QAC7B,OAAO,aAAa,CAAA;KACrB;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAfY,QAAA,wBAAwB,4BAepC;AAED;;;;GAIG;AACI,IAAM,qBAAqB,GAAG,UACnC,SAAiB,EACjB,OAAoC;IAApC,wBAAA,EAAA,YAAoC;IAEpC,IAAM,IAAI,GAAG,IAAA,gCAAwB,EAAC,SAAS,CAAC,CAAA;IAChD,IAAI,CAAC,IAAI,EAAE;QACT,OAAO,EAAE,CAAA;KACV;IAED,IAAM,MAAM,GAAG,IAAA,+CAAgC,GAAE,CAAA;IAEjD,QAAQ,IAAI,EAAE;QACZ,KAAK,WAAW;YACd,OAAO,MAAM,GAAG,IAAA,8CAAkC,EAAC,EAAE,UAAU,EAAE,OAAO,CAAC,cAAc,EAAE,CAAC,CAAA;QAC5F,KAAK,mBAAmB;YACtB,OAAO,MAAM,GAAG,IAAA,8DAA0C,EAAC,OAAO,CAAC,CAAA;QACrE,KAAK,aAAa;YAChB,OAAO,MAAM,GAAG,IAAA,kDAAoC,GAAE,CAAA;QACxD;YACE,OAAO,EAAE,CAAA;KACZ;AACH,CAAC,CAAA;AArBY,QAAA,qBAAqB,yBAqBjC;AAED;;;;;GAKG;AACI,IAAM,sBAAsB,GAAG,UAAC,SAAiB;IACtD,IAAM,IAAI,GAAG,IAAA,gCAAwB,EAAC,SAAS,CAAC,CAAA;IAChD,IAAI,CAAC,IAAI,EAAE;QACT,OAAO,IAAI,CAAA;KACZ;IAED,QAAQ,IAAI,EAAE;QACZ,KAAK,WAAW;YACd,OAAO,wDAAwD,CAAA;QACjE,KAAK,mBAAmB;YACtB,OAAO,wDAAwD,CAAA;QACjE,KAAK,aAAa;YAChB,OAAO,wDAAwD,CAAA;QACjE;YACE,OAAO,IAAI,CAAA;KACd;AACH,CAAC,CAAA;AAhBY,QAAA,sBAAsB,0BAgBlC;AAED;;;;;;;GAOG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAA;AAEpC;;;;GAIG;AACI,IAAM,uBAAuB,GAAG,UAAC,SAAiB;IACvD,IAAM,IAAI,GAAG,IAAA,gCAAwB,EAAC,SAAS,CAAC,CAAA;IAChD,IAAI,CAAC,IAAI,EAAE;QACT,OAAO,EAAE,CAAA;KACV;IAED,IAAM,WAAW,GACf,IAAI,KAAK,WAAW;QAClB,CAAC,CAAC,oBAAoB;QACtB,CAAC,CAAC,IAAI,KAAK,aAAa;YACxB,CAAC,CAAC,sBAAsB;YACxB,CAAC,CAAC,4BAA4B,CAAA;IAElC,+EAA+E;IAC/E,+EAA+E;IAC/E,EAAE;IACF,yEAAyE;IACzE,wEAAwE;IACxE,8EAA8E;IAC9E,2EAA2E;IAC3E,wCAAwC;IACxC,EAAE;IACF,8EAA8E;IAC9E,yEAAyE;IACzE,4EAA4E;IAC5E,IAAM,iBAAiB,GACrB,IAAI,KAAK,mBAAmB;QAC1B,CAAC,CAAC,yzEA+C4E,2BAAmB,8GAInG;QACE,CAAC,CAAC,EAAE,CAAA;IAER,IAAM,aAAa,GACjB,IAAI,KAAK,mBAAmB;QAC1B,CAAC,CAAC,4HAA4H;QAC9H,CAAC,CAAC,EAAE,CAAA;IAER,2EAA2E;IAC3E,0EAA0E;IAC1E,6EAA6E;IAC7E,6EAA6E;IAC7E,0EAA0E;IAC1E,2EAA2E;IAC3E,qBAAqB;IACrB,EAAE;IACF,0EAA0E;IAC1E,8EAA8E;IAC9E,iBAAiB;IACjB,2EAA2E;IAC3E,mCAAmC;IACnC,IAAM,eAAe,GAAG,IAAI,KAAK,WAAW,IAAI,IAAI,KAAK,mBAAmB,CAAA;IAC5E,IAAM,aAAa,GAAG,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,qBAAqB,CAAA;IACvF,IAAM,YAAY,GAAG,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,uBAAuB,CAAA;IAC1F,IAAM,iBAAiB,GAAG,eAAe;QACvC,CAAC,CAAC,kBACE,aAAa,gGAGb,aAAa,sBAAY,YAAY,sIAIzC;QACA,CAAC,CAAC,EAAE,CAAA;IACN,IAAM,aAAa,GAAG,eAAe,CAAC,CAAC,CAAC,YAAK,aAAa,eAAK,aAAa,CAAE,CAAC,CAAC,CAAC,EAAE,CAAA;IAEnF,OAAO,6OAOJ,iBAAiB,SAAG,iBAAiB,4OAG0D,aAAa,SAAG,aAAa,0BACtH,WAAW,4BAErB,CAAA;AACD,CAAC,CAAA;AAjIY,QAAA,uBAAuB,2BAiInC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-utils.d.ts","sourceRoot":"","sources":["../../../src/transformations/shared-utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,QAAO,
|
|
1
|
+
{"version":3,"file":"shared-utils.d.ts","sourceRoot":"","sources":["../../../src/transformations/shared-utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,QAAO,MAoTnD,CAAA"}
|