@40rty/ams-cli 0.5.7 → 0.5.9
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/bin/commands/dev.mjs +4 -1
- package/bin/commands/publish.mjs +12 -9
- package/bin/commands/theme.mjs +126 -0
- package/bin/forty.mjs +3 -0
- package/bin/lib/__tests__/theme-feeds.test.mjs +42 -0
- package/bin/lib/__tests__/theme-normalize.test.mjs +78 -0
- package/bin/lib/build.mjs +4 -3
- package/bin/lib/host-imports.mjs +136 -0
- package/bin/lib/theme/feeds.mjs +178 -0
- package/bin/lib/theme/normalize.mjs +226 -0
- package/dist/wire.js +385 -346
- package/package.json +2 -1
package/bin/commands/dev.mjs
CHANGED
|
@@ -16,7 +16,9 @@ import path from 'node:path';
|
|
|
16
16
|
import { cwd, fail, option, readConfig, readConfigIfPresent, writeDotenv } from '../lib/context.mjs';
|
|
17
17
|
import { call } from '../lib/credentials.mjs';
|
|
18
18
|
import { init } from './init.mjs';
|
|
19
|
-
import { buildRelease
|
|
19
|
+
import { buildRelease } from './publish.mjs';
|
|
20
|
+
import { RELEASE_MESSAGE_MAX as MAX_MESSAGE } from '../../dist/wire.js';
|
|
21
|
+
import { checkHostImports } from '../lib/host-imports.mjs';
|
|
20
22
|
|
|
21
23
|
function git(args) {
|
|
22
24
|
try {
|
|
@@ -72,6 +74,7 @@ export async function dev() {
|
|
|
72
74
|
const started = Date.now();
|
|
73
75
|
try {
|
|
74
76
|
const release = await buildRelease(config);
|
|
77
|
+
if (release.hostImports !== undefined) await checkHostImports(config.apiUrl, release.hostImports);
|
|
75
78
|
const description = draftMessage();
|
|
76
79
|
if (description !== undefined) release.description = description;
|
|
77
80
|
const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/draft`, release);
|
package/bin/commands/publish.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { PackageReleaseSchema, carriesShapeToken, catalogToWire } from '../../dist/wire.js';
|
|
3
|
+
import { PackageReleaseSchema, ReleaseMessageSchema, carriesShapeToken, catalogToWire } from '../../dist/wire.js';
|
|
4
4
|
import { buildBundle, loadBrandDefinition, loadCatalog, loadManifests, loadMark, loadSpacePrompt } from '../lib/build.mjs';
|
|
5
|
+
import { checkHostImports, collectHostImports } from '../lib/host-imports.mjs';
|
|
5
6
|
import { cwd, fail, flag, option, readConfig } from '../lib/context.mjs';
|
|
6
7
|
import { call } from '../lib/credentials.mjs';
|
|
7
8
|
import { registerOrigin } from './origin.mjs';
|
|
@@ -23,7 +24,11 @@ export async function buildRelease(config) {
|
|
|
23
24
|
catalog: catalogToWire(await loadCatalog(config.catalog)),
|
|
24
25
|
manifests: await loadManifests(config.manifests),
|
|
25
26
|
};
|
|
26
|
-
if (config.bundle !== undefined)
|
|
27
|
+
if (config.bundle !== undefined) {
|
|
28
|
+
release.bundle = await buildBundle(config.bundle);
|
|
29
|
+
// What the bundle reads from the page — the platform refuses a release it cannot satisfy.
|
|
30
|
+
release.hostImports = await collectHostImports(config.bundle.entry);
|
|
31
|
+
}
|
|
27
32
|
// The sdk this was built against: the platform picks the bundle's compat
|
|
28
33
|
// shims by it, and refuses one it cannot host.
|
|
29
34
|
const sdk = await resolvedSdkVersion(cwd);
|
|
@@ -59,16 +64,13 @@ function warnShapeTokenExamples(catalog) {
|
|
|
59
64
|
console.warn(' pass `examples` to catalogComponentFrom(...) for each');
|
|
60
65
|
}
|
|
61
66
|
|
|
62
|
-
/** A release's summary is one line a person can read in a version list. */
|
|
63
|
-
export const MAX_MESSAGE = 140;
|
|
64
|
-
|
|
65
67
|
/** `--message "…"`: what this release changed — mandatory; the console's version list shows it. */
|
|
66
68
|
export function releaseMessage() {
|
|
67
69
|
const message = option('message');
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (
|
|
71
|
-
return
|
|
70
|
+
if (typeof message !== 'string' || message.trim() === '') fail('a release needs a short summary of what changed — `forty publish --message "what changed"`');
|
|
71
|
+
const parsed = ReleaseMessageSchema.safeParse(message);
|
|
72
|
+
if (!parsed.success) fail(`the release message: ${parsed.error.issues[0].message}`);
|
|
73
|
+
return parsed.data;
|
|
72
74
|
}
|
|
73
75
|
|
|
74
76
|
/** `forty publish` — release: the package changes, and the space's visitors see it. */
|
|
@@ -78,6 +80,7 @@ export async function publish() {
|
|
|
78
80
|
const config = await readConfig();
|
|
79
81
|
const release = await buildRelease(config);
|
|
80
82
|
release.description = message;
|
|
83
|
+
if (release.hostImports !== undefined) await checkHostImports(config.apiUrl, release.hostImports);
|
|
81
84
|
// `--keep-locked`: a space `forty init` created opens to visitors on its first release — unless asked not to.
|
|
82
85
|
const keepLocked = flag('keep-locked') ? '&keepLocked=true' : '';
|
|
83
86
|
const result = await call(config.apiUrl, 'PUT', `/org/packages/releases?space=${encodeURIComponent(config.spaceSlug)}${keepLocked}`, release);
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// `forty theme sync [--out <path>]` — write the brand's product-page data from
|
|
2
|
+
// the store's own live theme: every product template's sections in the
|
|
3
|
+
// merchant's order, which template each product renders, and what the store's
|
|
4
|
+
// apps add to a product page (video reels, photo walls, sibling tiles, photo
|
|
5
|
+
// badges). Run it again whenever the merchant edits a template.
|
|
6
|
+
//
|
|
7
|
+
// The theme comes through the api (`/org/spaces/:slug/theme-*`), under the
|
|
8
|
+
// store's theme grant — the store's token never reaches this machine. The rest
|
|
9
|
+
// is the store's public storefront. Config, in forty.config.json:
|
|
10
|
+
//
|
|
11
|
+
// "theme": { "designs": "./theme.designs.mjs", "out": "src/theme/pdp-theme.json" }
|
|
12
|
+
//
|
|
13
|
+
// `designs` names what only this store has: its Shogun designs (by id), its
|
|
14
|
+
// AI-generated theme blocks (by type), and the custom liquid in its buy box.
|
|
15
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { pathToFileURL } from 'node:url';
|
|
18
|
+
import { cwd, fail, option, positionals, readConfig } from '../lib/context.mjs';
|
|
19
|
+
import { call } from '../lib/credentials.mjs';
|
|
20
|
+
import { parseThemeJson, templateSections, themeHelpers } from '../lib/theme/normalize.mjs';
|
|
21
|
+
import {
|
|
22
|
+
catalogOf, hasStarApps, hasVimotia, labelerBadges, pageReader, renderedVideos, starappsGroup, storeUrlOf, vimotiaReels, yotpoAppKey, yotpoGallery,
|
|
23
|
+
} from '../lib/theme/feeds.mjs';
|
|
24
|
+
|
|
25
|
+
/** Every theme file matching the patterns, through the api, paged. */
|
|
26
|
+
async function themeFiles(config, patterns) {
|
|
27
|
+
const files = new Map();
|
|
28
|
+
let after = null;
|
|
29
|
+
do {
|
|
30
|
+
const query = new URLSearchParams({ filenames: patterns.join(',') });
|
|
31
|
+
if (after !== null) query.set('after', after);
|
|
32
|
+
const page = await call(config.apiUrl, 'GET', `/org/spaces/${encodeURIComponent(config.spaceSlug)}/theme-files?${query}`);
|
|
33
|
+
for (const f of page.files) if (typeof f.content === 'string') files.set(f.filename, f.content);
|
|
34
|
+
after = page.nextCursor;
|
|
35
|
+
} while (after !== null);
|
|
36
|
+
return files;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The brand's own designs module, completed with empty maps for what it does not name. */
|
|
40
|
+
async function loadDesigns(file) {
|
|
41
|
+
const mod = await import(pathToFileURL(path.resolve(cwd, file)).href);
|
|
42
|
+
const designs = mod.default === undefined ? mod : mod.default;
|
|
43
|
+
return { shogun: designs.shogun === undefined ? {} : designs.shogun, blocks: designs.blocks === undefined ? {} : designs.blocks, liquid: designs.liquid === undefined ? [] : designs.liquid };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const numericId = (gid) => gid.slice(gid.lastIndexOf('/') + 1);
|
|
47
|
+
const templateName = (file) => file.slice('templates/'.length, -'.json'.length);
|
|
48
|
+
|
|
49
|
+
async function sync() {
|
|
50
|
+
const config = await readConfig();
|
|
51
|
+
if (typeof config.theme !== 'object' || config.theme === null || typeof config.theme.designs !== 'string') {
|
|
52
|
+
fail('forty.config.json needs "theme": { "designs": "./theme.designs.mjs", "out": "src/theme/pdp-theme.json" }');
|
|
53
|
+
}
|
|
54
|
+
const flagOut = option('out');
|
|
55
|
+
const out = flagOut !== undefined ? flagOut : typeof config.theme.out === 'string' ? config.theme.out : 'src/theme/pdp-theme.json';
|
|
56
|
+
const designs = await loadDesigns(config.theme.designs);
|
|
57
|
+
|
|
58
|
+
const { domain, products } = await call(config.apiUrl, 'GET', `/org/spaces/${encodeURIComponent(config.spaceSlug)}/theme-products`);
|
|
59
|
+
if (domain === null) fail(`${config.spaceSlug} has no store domain — connect its store first (\`forty connect\`)`);
|
|
60
|
+
if (products.length === 0) fail(`${config.spaceSlug}'s store has no live products`);
|
|
61
|
+
const storeUrl = await storeUrlOf(domain);
|
|
62
|
+
const h = themeHelpers(storeUrl);
|
|
63
|
+
const storePage = pageReader(storeUrl);
|
|
64
|
+
const catalogProducts = await catalogOf(storeUrl);
|
|
65
|
+
const catalog = new Map(catalogProducts.map((p) => [p.id, p]));
|
|
66
|
+
const catalogByHandle = new Map(catalogProducts.map((p) => [p.handle, p]));
|
|
67
|
+
const [templates, shogun] = await Promise.all([themeFiles(config, ['templates/product*.json']), themeFiles(config, ['sections/shogun-custom-*'])]);
|
|
68
|
+
if (!templates.has('templates/product.json')) fail('the live theme has no templates/product.json — is it a JSON-template (Online Store 2.0) theme?');
|
|
69
|
+
|
|
70
|
+
// A suffix whose file is gone renders the default template, as Shopify does.
|
|
71
|
+
const templateOf = (p) => {
|
|
72
|
+
const named = p.templateSuffix !== null ? `templates/product.${p.templateSuffix}.json` : 'templates/product.json';
|
|
73
|
+
return templates.has(named) ? named : 'templates/product.json';
|
|
74
|
+
};
|
|
75
|
+
const used = new Map([['templates/product.json', products[0].handle]]);
|
|
76
|
+
for (const p of products) if (!used.has(templateOf(p))) used.set(templateOf(p), p.handle);
|
|
77
|
+
|
|
78
|
+
const result = { templates: {}, products: {}, reels: {}, galleries: {}, siblings: {}, badges: await labelerBadges(domain) };
|
|
79
|
+
const sectionKeysOf = {};
|
|
80
|
+
const galleryPages = new Map();
|
|
81
|
+
for (const [file, handle] of used) {
|
|
82
|
+
const page = await storePage(handle);
|
|
83
|
+
const videos = renderedVideos(page);
|
|
84
|
+
const name = templateName(file);
|
|
85
|
+
const built = templateSections(parseThemeJson(templates.get(file)), (key) => {
|
|
86
|
+
const played = videos.get(key);
|
|
87
|
+
return { h, designs, shogun, catalogByHandle, videos: played === undefined ? [] : played };
|
|
88
|
+
});
|
|
89
|
+
// Every enabled section is a child of the page's main element, rendered or not — what an app's position counts.
|
|
90
|
+
sectionKeysOf[name] = built.enabled;
|
|
91
|
+
result.templates[name] = built.sections;
|
|
92
|
+
for (const s of built.sections) if (s.kind === 'ugc-gallery' && !galleryPages.has(s.galleryId)) galleryPages.set(s.galleryId, page);
|
|
93
|
+
}
|
|
94
|
+
for (const [galleryId, page] of galleryPages) {
|
|
95
|
+
const appKey = yotpoAppKey(page);
|
|
96
|
+
if (appKey === undefined) fail(`a Yotpo photo wall (${galleryId}) is placed, but the page carries no Yotpo app key`);
|
|
97
|
+
result.galleries[galleryId] = await yotpoGallery(appKey, galleryId);
|
|
98
|
+
}
|
|
99
|
+
// An app is read when the store's pages load it; once installed, every product page must carry its data.
|
|
100
|
+
const firstPage = await storePage(products[0].handle);
|
|
101
|
+
if (hasStarApps(firstPage)) {
|
|
102
|
+
for (const p of products) {
|
|
103
|
+
const group = starappsGroup(await storePage(p.handle), numericId(p.id), catalog);
|
|
104
|
+
if (group !== undefined) result.siblings[p.id] = group;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const vimotia = hasVimotia(firstPage);
|
|
108
|
+
for (const p of products) {
|
|
109
|
+
const name = templateName(templateOf(p));
|
|
110
|
+
result.products[p.id] = name;
|
|
111
|
+
if (!vimotia) continue;
|
|
112
|
+
const reels = await vimotiaReels(domain, numericId(p.id), sectionKeysOf[name]);
|
|
113
|
+
if (reels.length > 0) result.reels[p.id] = reels;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const target = path.resolve(cwd, out);
|
|
117
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
118
|
+
await writeFile(target, `${JSON.stringify(result, null, 1)}\n`);
|
|
119
|
+
console.log(`${Object.keys(result.templates).length} templates, ${Object.keys(result.products).length} products → ${path.relative(cwd, target)}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function theme() {
|
|
123
|
+
const [sub] = positionals();
|
|
124
|
+
if (sub !== 'sync') fail('usage: forty theme sync [--out <path>]');
|
|
125
|
+
await sync();
|
|
126
|
+
}
|
package/bin/forty.mjs
CHANGED
|
@@ -22,6 +22,8 @@
|
|
|
22
22
|
// forty deploy host this Hydrogen app on 40rty, at the space's address
|
|
23
23
|
// (`--detect` prints where the app's own production deploys)
|
|
24
24
|
// forty hosting self the app's own deployment serves the space again
|
|
25
|
+
// forty theme sync write the product pages' data from the store's own live
|
|
26
|
+
// theme (its templates, sections and apps) — `theme` in the config
|
|
25
27
|
//
|
|
26
28
|
// Run from the repo's root. The credential is `FORTY_API_KEY` when set (CI),
|
|
27
29
|
// otherwise the login stored by `forty login`.
|
|
@@ -43,6 +45,7 @@ const commands = {
|
|
|
43
45
|
feedback: () => import('./commands/feedback.mjs').then((m) => m.feedback()),
|
|
44
46
|
deploy: () => import('./commands/deploy.mjs').then((m) => m.deploy()),
|
|
45
47
|
hosting: () => import('./commands/hosting.mjs').then((m) => m.hosting()),
|
|
48
|
+
theme: () => import('./commands/theme.mjs').then((m) => m.theme()),
|
|
46
49
|
};
|
|
47
50
|
try {
|
|
48
51
|
const command = commands[process.argv[2]];
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { balancedObject, renderedVideos, starappsGroup, yotpoAppKey } from '../theme/feeds.mjs';
|
|
3
|
+
|
|
4
|
+
const catalog = new Map([
|
|
5
|
+
[1, { id: 1, title: 'Monitor, one camera', images: [{ src: 'https://cdn/1.png' }] }],
|
|
6
|
+
[2, { id: 2, title: 'Monitor, two cameras', images: [] }],
|
|
7
|
+
]);
|
|
8
|
+
const page = (data) => `<script>var x = {"collection_group_data": ${JSON.stringify(data)},\n"other": 1};</script>`;
|
|
9
|
+
|
|
10
|
+
describe('store feeds', () => {
|
|
11
|
+
it('reads a JSON object by brace depth, braces inside strings included', () => {
|
|
12
|
+
const text = 'x = {"a": "}{", "b": {"c": 1}} tail';
|
|
13
|
+
expect(JSON.parse(balancedObject(text, text.indexOf('{')))).toEqual({ a: '}{', b: { c: 1 } });
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('maps each section to the mp4s it plays', () => {
|
|
17
|
+
const html = '<div id="shopify-section-template--9__vid" class="x"><video src="//cdn/a.mp4?v=1"></video><source data-src="//cdn/a.mp4?v=1"></div><div id="shopify-section-template--9__other"></div>';
|
|
18
|
+
expect([...renderedVideos(html)]).toEqual([['vid', ['https://cdn/a.mp4?v=1']]]);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('reads a StarApps group by product id, ordered, labelled as the store names tiles', () => {
|
|
22
|
+
const data = { 'renamed-handle': { id: 1, groups: [{ default_category_details: '[{"category_name":"Variation"}]', products: [
|
|
23
|
+
{ id: 2, published: true, product_position: 1, product_display_name: { en: '2 Cameras' } },
|
|
24
|
+
{ id: 1, published: true, product_position: 0, product_display_name: { en: '' } },
|
|
25
|
+
{ id: 3, published: false, product_position: 2, product_display_name: null },
|
|
26
|
+
] }] } };
|
|
27
|
+
expect(starappsGroup(page(data), 1, catalog)).toEqual({
|
|
28
|
+
label: 'Variation',
|
|
29
|
+
tiles: [
|
|
30
|
+
{ id: 'gid://shopify/Product/1', title: 'Monitor, one camera', image: 'https://cdn/1.png' },
|
|
31
|
+
{ id: 'gid://shopify/Product/2', title: '2 Cameras', image: undefined },
|
|
32
|
+
],
|
|
33
|
+
});
|
|
34
|
+
expect(() => starappsGroup('<html></html>', 1, catalog)).toThrow(/StarApps data missing/);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('finds the store’s public Yotpo key in its page', () => {
|
|
38
|
+
expect(yotpoAppKey('<script>var yotpo_app_key = "AbC123";</script>')).toBe('AbC123');
|
|
39
|
+
expect(yotpoAppKey('<script src="https://cdn-widgetsrepository.yotpo.com/v1/loader/GYcxUHBDXlibqKgqLLAjwv4yfXdemJJXH5POH6UZ"></script>')).toBe('GYcxUHBDXlibqKgqLLAjwv4yfXdemJJXH5POH6UZ');
|
|
40
|
+
expect(yotpoAppKey('<html></html>')).toBeUndefined();
|
|
41
|
+
});
|
|
42
|
+
});
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { parseThemeJson, shogunContent, templateSections, themeHelpers } from '../theme/normalize.mjs';
|
|
3
|
+
|
|
4
|
+
const h = themeHelpers('https://www.store.test');
|
|
5
|
+
const designs = {
|
|
6
|
+
shogun: { abc: ({ images, texts }) => ({ kind: 'benefits', title: texts[0], items: images.map((icon, i) => ({ icon, label: texts[i + 1] })) }) },
|
|
7
|
+
blocks: { ai_gen_block_x: (s, helpers) => ({ kind: 'icon-grid', items: helpers.numbered(s, { icon: 'image', title: 'text' }) }) },
|
|
8
|
+
liquid: [{ match: (html) => html.includes('registry'), build: () => [{ kind: 'registry', label: 'Add to Registry', links: [] }] }],
|
|
9
|
+
};
|
|
10
|
+
const ctx = (extra = {}) => ({ h, designs, shogun: new Map(), catalogByHandle: new Map(), videos: [], ...extra });
|
|
11
|
+
|
|
12
|
+
describe('theme normalizer', () => {
|
|
13
|
+
it('reads a template Shopify opened with a comment', () => {
|
|
14
|
+
expect(parseThemeJson('/* auto-generated */ {"order":[]}')).toEqual({ order: [] });
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('keeps the merchant order, drops disabled sections and blocks, keys every band', () => {
|
|
18
|
+
const template = {
|
|
19
|
+
order: ['main', 'off', 'tiles', 'faq'],
|
|
20
|
+
sections: {
|
|
21
|
+
main: { type: 'main-product', settings: { show_sticky_add_to_cart: true }, block_order: ['b1', 'b2', 'b3', 'b4'], blocks: {
|
|
22
|
+
b1: { type: 'image', settings: { image: 'shopify://shop_images/a b.png', image_width: 500 } },
|
|
23
|
+
b2: { type: 'liquid', settings: { liquid: '<style>.x{}</style><div class="registry">x</div>' } },
|
|
24
|
+
b3: { type: 'text', disabled: true, settings: { text: '<p>hidden</p>' } },
|
|
25
|
+
b4: { type: 'buy_buttons' },
|
|
26
|
+
} },
|
|
27
|
+
off: { type: 'rich-text', disabled: true, settings: { title: 'x' } },
|
|
28
|
+
tiles: { type: '_blocks', block_order: ['x1', 'x2'], blocks: {
|
|
29
|
+
x1: { type: 'ai_gen_block_x', settings: { icon_1: 'shopify://shop_images/i.svg', title_1: 'Secure' } },
|
|
30
|
+
x2: { type: 'ai_gen_block_x', settings: { title_1: 'Fast' } },
|
|
31
|
+
} },
|
|
32
|
+
faq: { type: 'faq', settings: { title: 'FAQ', background: 'rgba(0,0,0,0)' }, block_order: ['q'], blocks: { q: { type: 'question', settings: { title: 'Q?', answer: '<p>A</p>' } } } },
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
const { enabled, sections } = templateSections(template, () => ctx());
|
|
36
|
+
expect(enabled).toEqual(['main', 'tiles', 'faq']);
|
|
37
|
+
expect(sections.map((s) => s.key)).toEqual(['main', 'tiles', 'tiles#1', 'faq']);
|
|
38
|
+
expect(sections[0].stickyBar).toBe(true);
|
|
39
|
+
expect(sections[0].blocks).toEqual([
|
|
40
|
+
{ kind: 'image', src: 'https://www.store.test/cdn/shop/files/a%20b.png', width: 500 },
|
|
41
|
+
{ kind: 'registry', label: 'Add to Registry', links: [] },
|
|
42
|
+
{ kind: 'buy' },
|
|
43
|
+
]);
|
|
44
|
+
expect(sections[1].items).toEqual([{ icon: 'https://www.store.test/cdn/shop/files/i.svg', title: 'Secure' }]);
|
|
45
|
+
expect(sections[3]).toEqual({ key: 'faq', kind: 'faq', title: 'FAQ', background: undefined, items: [{ question: 'Q?', html: '<p>A</p>' }] });
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('fails loudly on what neither the theme nor the brand names', () => {
|
|
49
|
+
const run = (s) => () => templateSections({ order: ['k'], sections: { k: s } }, () => ctx());
|
|
50
|
+
expect(run({ type: 'mystery' })).toThrow(/section type mystery has no renderer/);
|
|
51
|
+
expect(run({ type: '_blocks', block_order: ['a'], blocks: { a: { type: 'ai_gen_block_new' } } })).toThrow(/ai_gen_block_new has no design/);
|
|
52
|
+
expect(run({ type: 'main-product', block_order: ['a'], blocks: { a: { type: 'liquid', settings: { liquid: '<button>Promo</button>' } } } })).toThrow(/liquid block has no design/);
|
|
53
|
+
expect(run({ type: 'shogun-custom-zzz' })).toThrow(/shogun design zzz/);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('reads a Shogun design once, though it carries a desktop and a mobile copy', () => {
|
|
57
|
+
const asset = '11111111-2222-3333-4444-555555555555';
|
|
58
|
+
const liquid = `<h2>Benefits</h2><img src="https://i.shgcdn.com/${asset}/-/a/"><p>Best Price</p><img src="https://i.shgcdn.com/${asset}/-/b/"><p>Best Price</p>{% schema %}{}`;
|
|
59
|
+
expect(shogunContent(liquid)).toEqual({ images: [`https://i.shgcdn.com/${asset}/-/format/auto/-/preview/3000x3000/-/quality/best/`], texts: ['Benefits', 'Best Price'] });
|
|
60
|
+
const shogun = new Map([['sections/shogun-custom-abc.liquid', liquid]]);
|
|
61
|
+
const { sections } = templateSections({ order: ['s'], sections: { s: { type: 'shogun-custom-abc' } } }, () => ctx({ shogun }));
|
|
62
|
+
expect(sections[0]).toMatchObject({ kind: 'benefits', title: 'Benefits', items: [{ label: 'Best Price' }] });
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('places the store apps a theme carries: Yotpo reviews and photo walls, Vimotia reels', () => {
|
|
66
|
+
const { sections } = templateSections({
|
|
67
|
+
order: ['r', 'v', 'u', 'x'],
|
|
68
|
+
sections: {
|
|
69
|
+
r: { type: 'apps', block_order: ['a'], blocks: { a: { type: 'shopify://apps/yotpo-product-reviews/blocks/reviews/1' } } },
|
|
70
|
+
v: { type: 'apps', block_order: ['a'], blocks: { a: { type: 'shopify://apps/vimotia-shoppable-videos-ugc/blocks/gallery-block/1' } } },
|
|
71
|
+
u: { type: 'custom-liquid', settings: { liquid: '<div class="yotpo yotpo-pictures-widget" data-gallery-id="g1"></div>' } },
|
|
72
|
+
x: { type: 'custom-liquid', settings: { liquid: '<script>track()</script>' } },
|
|
73
|
+
},
|
|
74
|
+
}, () => ctx());
|
|
75
|
+
expect(sections.map((s) => s.kind)).toEqual(['reviews', 'video-stories', 'ugc-gallery']);
|
|
76
|
+
expect(sections[2].galleryId).toBe('g1');
|
|
77
|
+
});
|
|
78
|
+
});
|
package/bin/lib/build.mjs
CHANGED
|
@@ -74,7 +74,7 @@ export async function loadCatalog(file) {
|
|
|
74
74
|
* platform's own code: only a brand that lives in the platform's repository
|
|
75
75
|
* imports it, and only a page the platform hosts provides it.
|
|
76
76
|
*/
|
|
77
|
-
const SHARED = /^(react|react-dom|react\/jsx-runtime|framer-motion|zod|@40rty\/ams-sdk|@40rty\/ams-ui(\/.+)?|@fourty\/.+)$/;
|
|
77
|
+
export const SHARED = /^(react|react-dom|react\/jsx-runtime|framer-motion|zod|@40rty\/ams-sdk|@40rty\/ams-ui(\/.+)?|@fourty\/.+)$/;
|
|
78
78
|
|
|
79
79
|
/** With a named stylesheet, the components' OWN css imports are empty — the named sheet carries them; a package's are bundled. */
|
|
80
80
|
const ownCssIsNamedPlugin = {
|
|
@@ -166,10 +166,11 @@ export async function buildBundle(bundle) {
|
|
|
166
166
|
}
|
|
167
167
|
|
|
168
168
|
/** What a stylesheet points at rather than carries: only what is already somewhere else. */
|
|
169
|
-
const CSS_EXTERNAL = ['http://*', 'https://*', 'data:*'];
|
|
169
|
+
export const CSS_EXTERNAL = ['http://*', 'https://*', 'data:*'];
|
|
170
170
|
|
|
171
171
|
/** What a stylesheet carries as a file of its own, under `assets/` beside it. */
|
|
172
|
-
const
|
|
172
|
+
export const ASSET_EXTENSIONS = ['.woff', '.woff2', '.ttf', '.otf', '.png', '.jpg', '.jpeg', '.svg', '.gif', '.webp'];
|
|
173
|
+
const ASSET_LOADERS = Object.fromEntries(ASSET_EXTENSIONS.map((ext) => [ext, 'file']));
|
|
173
174
|
const ASSET_NAMES = 'assets/[hash]';
|
|
174
175
|
|
|
175
176
|
/** The built asset files, base64, by their path beside the stylesheet. */
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// What a published bundle reads from the page — the bundle side of the name
|
|
2
|
+
// contract (`@fourty/spacestation`'s `host-imports.ts`). A bundle carries none
|
|
3
|
+
// of the modules it shares with the page (`SHARED` in `build.mjs`); it reads
|
|
4
|
+
// each from `globalThis.__forty_host__` at runtime, so a name the page's module
|
|
5
|
+
// does not export is `undefined` there and the first render that calls it
|
|
6
|
+
// throws. The release records every such name (`hostImports`) and the platform
|
|
7
|
+
// refuses one it cannot satisfy; `checkHostImports` asks first, so a refused
|
|
8
|
+
// bundle costs no upload.
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { parse } from 'acorn';
|
|
11
|
+
import { build } from 'esbuild';
|
|
12
|
+
import { HostExportsSchema, hostImportProblems, hostImportsRefusal } from '../../dist/wire.js';
|
|
13
|
+
import { ASSET_EXTENSIONS, CSS_EXTERNAL, SHARED } from './build.mjs';
|
|
14
|
+
import { cwd, fail } from './context.mjs';
|
|
15
|
+
import { request } from './credentials.mjs';
|
|
16
|
+
|
|
17
|
+
/** The shared modules stay real `import` statements, so the output names exactly what is read from each. */
|
|
18
|
+
const sharedExternalPlugin = {
|
|
19
|
+
name: 'forty-shared-external',
|
|
20
|
+
setup(pluginBuild) {
|
|
21
|
+
pluginBuild.onResolve({ filter: SHARED }, (args) => (args.path.endsWith('.css') ? undefined : { path: args.path, external: true }));
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Styles and files carry no imports: read as nothing. */
|
|
26
|
+
const EMPTY_LOADERS = Object.fromEntries(['.css', ...ASSET_EXTENSIONS].map((ext) => [ext, 'empty']));
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Every name the bundle built from `entry` reads from each shared module.
|
|
30
|
+
*
|
|
31
|
+
* The bundle is built a second time, as `buildBundle` builds it but with the
|
|
32
|
+
* shared modules left as ES imports instead of the `__forty_host__` shim.
|
|
33
|
+
* esbuild has then already resolved every re-export chain, dropped what is
|
|
34
|
+
* unused, and renamed any local that would shadow an import — so its output's
|
|
35
|
+
* import statements, read with a real parser, ARE the bundle's reads.
|
|
36
|
+
*/
|
|
37
|
+
export async function collectHostImports(entry) {
|
|
38
|
+
const result = await build({
|
|
39
|
+
entryPoints: [path.resolve(cwd, entry)],
|
|
40
|
+
bundle: true,
|
|
41
|
+
write: false,
|
|
42
|
+
outdir: path.join(cwd, 'node_modules', '.forty', 'host-imports'),
|
|
43
|
+
format: 'esm',
|
|
44
|
+
platform: 'browser',
|
|
45
|
+
target: 'esnext',
|
|
46
|
+
jsx: 'automatic',
|
|
47
|
+
define: { 'process.env.NODE_ENV': '"production"' },
|
|
48
|
+
loader: EMPTY_LOADERS,
|
|
49
|
+
external: CSS_EXTERNAL,
|
|
50
|
+
plugins: [sharedExternalPlugin],
|
|
51
|
+
logLevel: 'error',
|
|
52
|
+
});
|
|
53
|
+
const js = result.outputFiles.find((file) => file.path.endsWith('.js'));
|
|
54
|
+
if (js === undefined) fail(`${entry} produced no module`);
|
|
55
|
+
return hostImportsOf(js.text);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** `import { a }` / `export { a } from` name `a`; a string name (`import { "a-b" as c }`) is the literal. */
|
|
59
|
+
const nameOf = (node) => (node.type === 'Identifier' ? node.name : String(node.value));
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* What an ES module reads from each shared module, `{ specifier: names[] }`,
|
|
63
|
+
* both sorted. A default import is `default`. A namespace import
|
|
64
|
+
* (`import * as ui`) contributes each `ui.name` it is read through; used any
|
|
65
|
+
* other way (passed along whole, indexed by a variable) its other names cannot
|
|
66
|
+
* be known, and only the module itself is required. `export * from` likewise
|
|
67
|
+
* requires the module and names nothing.
|
|
68
|
+
*/
|
|
69
|
+
export function hostImportsOf(code) {
|
|
70
|
+
const program = parse(code, { ecmaVersion: 'latest', sourceType: 'module' });
|
|
71
|
+
const reads = new Map();
|
|
72
|
+
const namesFrom = (specifier) => {
|
|
73
|
+
if (!reads.has(specifier)) reads.set(specifier, new Set());
|
|
74
|
+
return reads.get(specifier);
|
|
75
|
+
};
|
|
76
|
+
const namespaces = new Map();
|
|
77
|
+
for (const node of program.body) {
|
|
78
|
+
if (node.type === 'ImportDeclaration') {
|
|
79
|
+
const names = namesFrom(node.source.value);
|
|
80
|
+
for (const spec of node.specifiers) {
|
|
81
|
+
if (spec.type === 'ImportSpecifier') names.add(nameOf(spec.imported));
|
|
82
|
+
else if (spec.type === 'ImportDefaultSpecifier') names.add('default');
|
|
83
|
+
else namespaces.set(spec.local.name, node.source.value);
|
|
84
|
+
}
|
|
85
|
+
} else if (node.type === 'ExportNamedDeclaration' && node.source !== null) {
|
|
86
|
+
const names = namesFrom(node.source.value);
|
|
87
|
+
for (const spec of node.specifiers) names.add(nameOf(spec.local));
|
|
88
|
+
} else if (node.type === 'ExportAllDeclaration') {
|
|
89
|
+
namesFrom(node.source.value);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (namespaces.size > 0) {
|
|
93
|
+
walk(program, (node) => {
|
|
94
|
+
if (node.type !== 'MemberExpression' || node.object.type !== 'Identifier' || !namespaces.has(node.object.name)) return;
|
|
95
|
+
const names = namesFrom(namespaces.get(node.object.name));
|
|
96
|
+
if (!node.computed) names.add(node.property.name);
|
|
97
|
+
else if (node.property.type === 'Literal' && typeof node.property.value === 'string') names.add(node.property.value);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return Object.fromEntries(
|
|
101
|
+
[...reads.keys()]
|
|
102
|
+
.filter((specifier) => SHARED.test(specifier))
|
|
103
|
+
.sort()
|
|
104
|
+
.map((specifier) => [specifier, [...reads.get(specifier)].sort()]),
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Every node under `node`, depth first. */
|
|
109
|
+
function walk(node, visit) {
|
|
110
|
+
visit(node);
|
|
111
|
+
for (const value of Object.values(node)) {
|
|
112
|
+
if (Array.isArray(value)) {
|
|
113
|
+
for (const child of value) if (child !== null && typeof child === 'object' && typeof child.type === 'string') walk(child, visit);
|
|
114
|
+
} else if (value !== null && typeof value === 'object' && typeof value.type === 'string') {
|
|
115
|
+
walk(value, visit);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Ask the platform what its page shares, and stop here — before the upload —
|
|
122
|
+
* when the bundle reads anything it does not. The platform checks again on
|
|
123
|
+
* receipt (every publisher passes through it); this only saves the trip. A
|
|
124
|
+
* platform too old to answer is said so and not held against the release.
|
|
125
|
+
*/
|
|
126
|
+
export async function checkHostImports(apiUrl, hostImports) {
|
|
127
|
+
const res = await request(apiUrl, 'GET', '/org/host-modules');
|
|
128
|
+
if (!res.ok) {
|
|
129
|
+
console.warn(`the platform did not list what its page shares (${res.status}) — the bundle's imports are checked when it lands`);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const modules = HostExportsSchema.safeParse(res.body.modules);
|
|
133
|
+
if (!modules.success) fail('the platform answered /org/host-modules with something that is not a module map — update the forty CLI');
|
|
134
|
+
const problems = hostImportProblems(hostImports, modules.data);
|
|
135
|
+
if (problems.length > 0) fail(`${hostImportsRefusal(typeof res.body.commit === 'string' ? res.body.commit : null)}\n - ${problems.join('\n - ')}`);
|
|
136
|
+
}
|