Compare commits

...
5 Commits
13 changed files with 569 additions and 20 deletions
+19 -1
View File
@@ -9,6 +9,7 @@ const { registerPrestashopConfigBlocks } = require('./src/register-config');
const { registerPrestashopPermissions } = require('./src/register-permissions');
const { importOrdersForShop, syncPaymentsForShop } = require('./src/automation-jobs');
const { createJobRuntime } = require('./src/job-runtime');
const { ensureShopIcon } = require('./src/shop-icon');
const NEW_ORDERS_WINDOW_MS = 20 * 60 * 1000;
const runtime = createJobRuntime(Core, Log);
@@ -61,6 +62,17 @@ async function runPaymentSync(kind, isLockValid) {
}
}
async function syncShopIcon() {
const configs = await loadEnabledConfigs();
for (const config of configs) {
await ensureShopIcon({
apiUrl: config.apiUrl,
shopName: config.shopName,
force: false,
});
}
}
const jobs = [
new CronJob('0 */5 * * * *', () => runtime.track(() =>
runtime.withRenewedLock('prestashop-orders-puller', 5 * 60 * 1000, runOrdersPuller)
@@ -86,8 +98,14 @@ async function stopJobs() {
// Preserve the module's existing startup behavior; lifecycle callbacks make repeated
// enable/disable transitions safe and ensure no cron remains active while disabled.
startJobs();
syncShopIcon().catch(error => {
Log.warn('PrestaShop favicon: startup synchronization failed', { error: error?.message });
});
Core.onEnabled(async () => {
startJobs();
await syncShopIcon().catch(error => {
Log.warn('PrestaShop favicon: enable synchronization failed', { error: error?.message });
});
Log.info('Module enabled');
});
Core.onDisabled(async () => {
@@ -95,4 +113,4 @@ Core.onDisabled(async () => {
Log.info('Module disabled; PrestaShop cron jobs stopped');
});
module.exports = { startJobs, stopJobs, runOrdersPuller, runPaymentSync };
module.exports = { startJobs, stopJobs, runOrdersPuller, runPaymentSync, syncShopIcon };
+24 -3
View File
@@ -3,11 +3,30 @@ const { isLegacyApi } = require('../../src/utils');
const { loadConfig, isConfigured } = require('../../src/module-config');
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
const MAX_PRODUCT_IDS = 100;
const IMAGE_CONCURRENCY = 5;
async function mapWithConcurrency(values, concurrency, worker) {
let nextIndex = 0;
const runners = Array.from({ length: Math.min(concurrency, values.length) }, async () => {
while (nextIndex < values.length) {
const index = nextIndex++;
await worker(values[index]);
}
});
await Promise.all(runners);
}
module.exports = async function(params, ctx) {
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
const productIds = Array.isArray(params?.productIds) ? params.productIds : [];
const productIds = [...new Set(
(Array.isArray(params?.productIds) ? params.productIds : [])
.map(value => String(value || '').trim())
.filter(Boolean)
)];
if (productIds.length === 0) return {};
if (productIds.length > MAX_PRODUCT_IDS) throw new Error('productIds exceeds the 100 item limit');
const config = await loadConfig();
if (!isConfigured(config)) return {};
@@ -15,12 +34,14 @@ module.exports = async function(params, ctx) {
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
const result = {};
for (const productId of productIds) {
await mapWithConcurrency(productIds, IMAGE_CONCURRENCY, async productId => {
try {
const url = await api.getProductCoverImageUrl(productId);
if (url) result[String(productId)] = url;
} catch (_) { /* product not found or no image */ }
}
});
return result;
};
module.exports._private = { mapWithConcurrency, MAX_PRODUCT_IDS, IMAGE_CONCURRENCY };
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "core/prestashop",
"version": "1.1.2",
"version": "1.1.4",
"singleton": false,
"dependsOn": [
"core/orders",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "core.prestashop",
"version": "1.1.2",
"version": "1.1.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "core.prestashop",
"version": "1.1.2",
"version": "1.1.4",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^2.2.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "core.prestashop",
"version": "1.1.2",
"version": "1.1.4",
"description": "Integracja zamówień i płatności PrestaShop",
"main": "index.js",
"scripts": {
+7 -3
View File
@@ -145,10 +145,14 @@ async function importOrdersForShop(config, api, dependencies = {}) {
cursor = Number(order.id);
processed += 1;
} catch (error) {
Log.error('Failed to import PS order; cursor remains before this order', {
orderId: order.id, cursor, error: error.message,
const previousCursor = cursor;
cursor = Number(order.id);
Log.error('Failed to import PS order; skipping order and continuing', {
orderId: order.id,
previousCursor,
cursor,
error: error.message,
});
break;
}
}
+3 -3
View File
@@ -101,8 +101,8 @@ function buildSearchParams(params = {}) {
}
const searchParams = {
page: parseInt(cleanParams.page, 10) || 1,
perPage: parseInt(cleanParams.perPage, 10) || 20,
page: Math.min(1_000_000, Math.max(1, parseInt(cleanParams.page, 10) || 1)),
perPage: Math.min(100, Math.max(1, parseInt(cleanParams.perPage, 10) || 20)),
source: {
moduleCode: getModuleCode(),
_moduleCodes: getModuleCodes()
@@ -122,7 +122,7 @@ function buildSearchParams(params = {}) {
}
if (cleanParams.query && isUsableParam(cleanParams.query)) {
searchParams.query = String(cleanParams.query).trim();
searchParams.query = String(cleanParams.query).trim().slice(0, 200);
}
const passthroughKeys = [
+6
View File
@@ -4,6 +4,7 @@ const PrestashopApi = require('./PrestaApi');
const { isLegacyApi } = require('./utils');
const { extractPsStateName } = require('./status-mapper');
const { setPsStates, loadPsStates } = require('./module-config');
const { ensureShopIcon } = require('./shop-icon');
const ORBITO_STATUS_OPTIONS = {
module: 'core/orders',
@@ -95,6 +96,11 @@ async function registerPrestashopConfigBlocks() {
try {
const psStates = await fetchPsStates(apiUrl, apiKey, params.versionCode);
await setPsStates(psStates);
await ensureShopIcon({
apiUrl,
shopName: params.shopName,
force: true,
});
Log.info('PrestaShop config: połączenie OK, statusy pobrane', { count: psStates.length });
} catch (err) {
Log.warn('PrestaShop config validate failed', { error: err?.message });
+243
View File
@@ -0,0 +1,243 @@
const { Config, Core, Log } = require('@orbito/api-lib');
const CACHE_KEY = 'runtime.shopIcon';
const MAX_ICON_BYTES = 45 * 1024;
const MAX_HTML_BYTES = 512 * 1024;
const FETCH_TIMEOUT_MS = 10_000;
const MAX_REDIRECTS = 3;
const pendingEnsures = new Map();
function storefrontUrl(apiUrl) {
const url = new URL(String(apiUrl || '').trim());
if (!['http:', 'https:'].includes(url.protocol)) throw new Error('INVALID_SHOP_URL');
url.hash = '';
url.search = '';
const segments = url.pathname.split('/').filter(Boolean);
if (segments[segments.length - 1]?.toLowerCase() === 'api') segments.pop();
url.pathname = `/${segments.join('/')}${segments.length ? '/' : ''}`;
return url.href;
}
function headerValue(headers, name) {
if (!headers) return '';
if (typeof headers.get === 'function') return headers.get(name) || '';
const key = Object.keys(headers).find(item => item.toLowerCase() === name.toLowerCase());
return key ? headers[key] : '';
}
async function responseBuffer(response) {
if (Buffer.isBuffer(response?.data)) return response.data;
if (response?.data != null) return Buffer.from(response.data);
if (typeof response?.arrayBuffer === 'function') {
return Buffer.from(await response.arrayBuffer());
}
if (typeof response?.text === 'function') {
return Buffer.from(await response.text());
}
return Buffer.alloc(0);
}
async function fetchSameHost(url, rootUrl, maxBytes) {
let current = new URL(url);
const root = new URL(rootUrl);
for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {
if (!['http:', 'https:'].includes(current.protocol)
|| current.host !== root.host
|| current.username
|| current.password) {
throw new Error('SHOP_ICON_REDIRECT_REJECTED');
}
const response = await Core.fetch(current.href, {
method: 'GET',
timeout: FETCH_TIMEOUT_MS,
redirect: 'manual',
headers: { Accept: 'image/*,text/html;q=0.8,*/*;q=0.1' },
});
const status = Number(response?.status || 0);
if (status >= 300 && status < 400) {
const location = headerValue(response.headers, 'location');
if (!location || redirect === MAX_REDIRECTS) throw new Error('SHOP_ICON_REDIRECT_REJECTED');
current = new URL(location, current);
continue;
}
if (status < 200 || status >= 300) throw new Error(`SHOP_ICON_HTTP_${status || 'ERROR'}`);
const declaredLength = Number(headerValue(response.headers, 'content-length'));
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
throw new Error('SHOP_ICON_TOO_LARGE');
}
const buffer = await responseBuffer(response);
if (!buffer.length || buffer.length > maxBytes) throw new Error('SHOP_ICON_TOO_LARGE');
return {
buffer,
contentType: headerValue(response.headers, 'content-type'),
url: current.href,
};
}
throw new Error('SHOP_ICON_REDIRECT_REJECTED');
}
function tagAttribute(tag, attribute) {
const escaped = attribute.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const quoted = new RegExp(`\\b${escaped}\\s*=\\s*(["'])(.*?)\\1`, 'i').exec(tag);
if (quoted) return quoted[2];
const bare = new RegExp(`\\b${escaped}\\s*=\\s*([^\\s>]+)`, 'i').exec(tag);
return bare ? bare[1] : '';
}
function faviconCandidates(html, documentUrl) {
const candidates = [];
const seen = new Set();
const tags = String(html || '').match(/<link\b[^>]*>/gi) || [];
for (const tag of tags) {
const rel = tagAttribute(tag, 'rel').toLowerCase();
if (!rel.split(/\s+/).some(token => token === 'icon' || token === 'apple-touch-icon')) continue;
const href = tagAttribute(tag, 'href').replace(/&amp;/gi, '&').trim();
if (!href || href.startsWith('data:')) continue;
try {
const candidate = new URL(href, documentUrl);
if (!['http:', 'https:'].includes(candidate.protocol) || seen.has(candidate.href)) continue;
seen.add(candidate.href);
candidates.push(candidate.href);
} catch {
// Pomijamy nieprawidłowy href i przechodzimy do standardowego favicon.ico.
}
}
const fallback = new URL('favicon.ico', documentUrl).href;
if (!seen.has(fallback)) candidates.push(fallback);
return candidates.slice(0, 5);
}
function detectIconMime(buffer) {
if (!Buffer.isBuffer(buffer)) return '';
if (buffer.length >= 8
&& buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
return 'image/png';
}
if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
return 'image/jpeg';
}
if (buffer.length >= 12
&& buffer.subarray(0, 4).toString('ascii') === 'RIFF'
&& buffer.subarray(8, 12).toString('ascii') === 'WEBP') {
return 'image/webp';
}
if (buffer.length >= 6 && ['GIF87a', 'GIF89a'].includes(buffer.subarray(0, 6).toString('ascii'))) {
return 'image/gif';
}
if (buffer.length >= 4
&& buffer[0] === 0x00 && buffer[1] === 0x00
&& buffer[2] === 0x01 && buffer[3] === 0x00) {
return 'image/vnd.microsoft.icon';
}
return '';
}
async function downloadShopIcon(shopPageUrl) {
let documentUrl = shopPageUrl;
let candidates = [new URL('favicon.ico', shopPageUrl).href];
try {
const page = await fetchSameHost(shopPageUrl, shopPageUrl, MAX_HTML_BYTES);
documentUrl = page.url;
candidates = faviconCandidates(page.buffer.toString('utf8'), documentUrl);
} catch (error) {
Log.warn('PrestaShop favicon: storefront discovery failed', { error: error?.message });
}
for (const candidate of candidates) {
try {
const image = await fetchSameHost(candidate, documentUrl, MAX_ICON_BYTES);
const mime = detectIconMime(image.buffer);
if (!mime) continue;
return {
dataUrl: `data:${mime};base64,${image.buffer.toString('base64')}`,
mime,
sourceUrl: image.url,
};
} catch (error) {
Log.warn('PrestaShop favicon: candidate rejected', {
candidate,
error: error?.message,
});
}
}
return null;
}
async function registerSourceProfile(cache, shopName) {
try {
await Core.callModule('core/orders', 'source.register', {
name: String(shopName || '').trim() || new URL(cache.shopUrl).hostname,
iconDataUrl: cache.dataUrl || '',
iconSourceUrl: cache.sourceUrl || '',
});
return true;
} catch (error) {
Log.warn('PrestaShop favicon: source profile registration failed', { error: error?.message });
return false;
}
}
async function ensureShopIconOnce({ apiUrl, shopName, force = false }) {
const shopUrl = storefrontUrl(apiUrl);
const existing = await Config.get(CACHE_KEY, null);
const sameShop = existing && existing.shopUrl === shopUrl;
if (!force && sameShop && existing.fetchedAt) {
await registerSourceProfile(existing, shopName);
return { ...existing, cacheHit: true };
}
const downloaded = await downloadShopIcon(shopUrl);
const retained = !downloaded && sameShop && existing?.dataUrl ? existing : null;
const cache = {
shopUrl,
dataUrl: downloaded?.dataUrl || retained?.dataUrl || '',
mime: downloaded?.mime || retained?.mime || '',
sourceUrl: downloaded?.sourceUrl || retained?.sourceUrl || '',
fetchedAt: new Date().toISOString(),
};
await Config.set(CACHE_KEY, cache);
await registerSourceProfile(cache, shopName);
return { ...cache, cacheHit: false };
}
function ensureShopIcon(options) {
const key = `${storefrontUrl(options?.apiUrl)}|${options?.force === true ? 'refresh' : 'cached'}`;
if (pendingEnsures.has(key)) return pendingEnsures.get(key);
const promise = ensureShopIconOnce(options).finally(() => {
pendingEnsures.delete(key);
});
pendingEnsures.set(key, promise);
return promise;
}
module.exports = {
ensureShopIcon,
downloadShopIcon,
storefrontUrl,
faviconCandidates,
detectIconMime,
_private: {
CACHE_KEY,
MAX_ICON_BYTES,
MAX_HTML_BYTES,
FETCH_TIMEOUT_MS,
fetchSameHost,
responseBuffer,
tagAttribute,
registerSourceProfile,
},
};
+16 -6
View File
@@ -29,9 +29,10 @@ test('first run safely starts at the newest order without backfilling history',
assert.deepEqual(result, { status: 'initialized', cursor: 812, processed: 0 });
});
test('cursor advances only through confirmed successes and stops before failed order', async () => {
test('a failed order is skipped so later orders can still be imported', async () => {
const writes = [];
const imported = [];
const errors = [];
const config = { _id: 'default', lastOrderId: 10 };
const api = { makeRequest: async () => ({ orders: [oldOrder(11), oldOrder(12), oldOrder(13)] }) };
const result = await importOrdersForShop(config, api, {
@@ -43,14 +44,23 @@ test('cursor advances only through confirmed successes and stops before failed o
return { status: 'imported', psOrderId: id, orbitoOrderId: `orbito-${id}` };
},
setLastOrderId: async id => writes.push(id),
Log: silentLog,
Log: { ...silentLog, error: (message, details) => errors.push({ message, details }) },
now: () => new Date('2026-01-02T00:00:00Z').getTime(),
});
assert.deepEqual(imported, [11, 12]);
assert.deepEqual(writes, [11]);
assert.equal(config.lastOrderId, 11);
assert.deepEqual(result, { status: 'processed', cursor: 11, processed: 1 });
assert.deepEqual(imported, [11, 12, 13]);
assert.deepEqual(writes, [13]);
assert.equal(config.lastOrderId, 13);
assert.deepEqual(result, { status: 'processed', cursor: 13, processed: 2 });
assert.deepEqual(errors, [{
message: 'Failed to import PS order; skipping order and continuing',
details: {
orderId: 12,
previousCursor: 11,
cursor: 12,
error: 'invalid order',
},
}]);
});
test('existing Orbito order repairs a missing mapping before advancing the cursor', async () => {
+52
View File
@@ -0,0 +1,52 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const Module = require('node:module');
const path = require('node:path');
function loadMethod({ onFetch }) {
const methodPath = path.resolve(__dirname, '../methods/product/get_images.js');
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '../../src/PrestaApi') {
return class PrestashopApi {
async getProductCoverImageUrl(id) { return onFetch(id); }
};
}
if (request === '../../src/utils') return { isLegacyApi: () => false };
if (request === '../../src/module-config') {
return { loadConfig: async () => ({ apiUrl: 'https://shop.test', apiKey: 'key' }), isConfigured: () => true };
}
if (request === '../../src/register-permissions') {
return { PERMISSIONS: { ORDERS_VIEW: 'orders.view' }, requirePermission() {} };
}
return originalLoad.call(this, request, parent, isMain);
};
delete require.cache[methodPath];
try {
return require(methodPath);
} finally {
Module._load = originalLoad;
}
}
test('product image lookup deduplicates IDs and bounds external concurrency', async () => {
let active = 0;
let maxActive = 0;
const calls = [];
const method = loadMethod({
onFetch: async id => {
calls.push(id);
active += 1;
maxActive = Math.max(maxActive, active);
await new Promise(resolve => setImmediate(resolve));
active -= 1;
return `https://img.test/${id}.jpg`;
}
});
const result = await method({ productIds: ['1', '1', '2', '3', '4', '5', '6'] }, {});
assert.deepEqual(calls.sort(), ['1', '2', '3', '4', '5', '6']);
assert.equal(maxActive, 5);
assert.equal(result['6'], 'https://img.test/6.jpg');
});
+70
View File
@@ -0,0 +1,70 @@
const assert = require('node:assert/strict');
const Module = require('node:module');
const path = require('node:path');
const test = require('node:test');
const registerConfigPath = path.resolve(__dirname, '../src/register-config.js');
test('saving a valid shop connection refreshes the persisted source icon', async () => {
let blocks;
let iconOptions;
let savedStates;
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '@orbito/api-lib') {
return {
Config: {
PropertyType: { INFO: 'info', STRING: 'string' },
DisplayFormat: { URL: 'url', SECRET: 'secret' },
registerConfigBlocks: async value => { blocks = value; },
},
Log: { info() {}, warn() {} },
};
}
if (request === './PrestaApi') {
return class PrestashopApi {
async getStatuses() {
return [{ id: '2', name: 'Payment accepted', color: '#00ff00' }];
}
};
}
if (request === './utils') return { isLegacyApi: () => false };
if (request === './status-mapper') return { extractPsStateName: value => value };
if (request === './module-config') {
return {
setPsStates: async value => { savedStates = value; },
loadPsStates: async () => [],
};
}
if (request === './shop-icon') {
return { ensureShopIcon: async options => { iconOptions = options; } };
}
return originalLoad.call(this, request, parent, isMain);
};
delete require.cache[registerConfigPath];
try {
const { registerPrestashopConfigBlocks } = require(registerConfigPath);
await registerPrestashopConfigBlocks();
} finally {
Module._load = originalLoad;
}
const errors = [];
await blocks.connection.validate({
apiUrl: 'https://shop.test',
apiKey: 'secret',
versionCode: '8',
shopName: 'Sklep główny',
}, {
addError: (field, message) => errors.push({ field, message }),
});
assert.deepEqual(errors, []);
assert.deepEqual(savedStates, [{ id: 2, name: 'Payment accepted', color: '#00ff00' }]);
assert.deepEqual(iconOptions, {
apiUrl: 'https://shop.test',
shopName: 'Sklep główny',
force: true,
});
});
+125
View File
@@ -0,0 +1,125 @@
const assert = require('node:assert/strict');
const Module = require('node:module');
const path = require('node:path');
const test = require('node:test');
const shopIconPath = path.resolve(__dirname, '../src/shop-icon.js');
function pngBuffer() {
return Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 0]);
}
function loadShopIcon(api) {
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '@orbito/api-lib') return api;
return originalLoad.call(this, request, parent, isMain);
};
delete require.cache[shopIconPath];
try {
return require(shopIconPath);
} finally {
Module._load = originalLoad;
}
}
test('discovers, downloads and persists a favicon once before registering the source', async () => {
const calls = [];
const config = new Map();
const registered = [];
const page = Buffer.from('<html><head><link rel="shortcut icon" href="img/store-icon.png"></head></html>');
const shopIcon = loadShopIcon({
Config: {
get: async (key, fallback) => config.has(key) ? config.get(key) : fallback,
set: async (key, value) => config.set(key, value),
},
Core: {
fetch: async url => {
calls.push(url);
if (url === 'https://shop.test/b2b/') {
return { status: 200, data: page, headers: { 'content-type': 'text/html' } };
}
if (url === 'https://shop.test/b2b/img/store-icon.png') {
return { status: 200, data: pngBuffer(), headers: { 'content-type': 'image/png' } };
}
throw new Error(`Unexpected URL: ${url}`);
},
callModule: async (...args) => registered.push(args),
},
Log: { warn() {} },
});
const first = await shopIcon.ensureShopIcon({
apiUrl: 'https://shop.test/b2b/api/',
shopName: 'Sklep B2B',
force: true,
});
const second = await shopIcon.ensureShopIcon({
apiUrl: 'https://shop.test/b2b/api/',
shopName: 'Sklep B2B',
force: false,
});
assert.deepEqual(calls, [
'https://shop.test/b2b/',
'https://shop.test/b2b/img/store-icon.png',
]);
assert.equal(first.cacheHit, false);
assert.equal(second.cacheHit, true);
assert.equal(first.mime, 'image/png');
assert.match(first.dataUrl, /^data:image\/png;base64,/);
assert.equal(config.get('runtime.shopIcon').sourceUrl, 'https://shop.test/b2b/img/store-icon.png');
assert.deepEqual(registered[0].slice(0, 2), ['core/orders', 'source.register']);
assert.equal(registered[0][2].name, 'Sklep B2B');
assert.equal(registered[0][2].iconDataUrl, first.dataUrl);
assert.equal(registered.length, 2, 'cache hits still re-register metadata after a module restart');
});
test('a failed refresh retains the last icon for the same shop', async () => {
const oldIcon = `data:image/png;base64,${pngBuffer().toString('base64')}`;
let stored = {
shopUrl: 'https://shop.test/',
dataUrl: oldIcon,
mime: 'image/png',
sourceUrl: 'https://shop.test/old.png',
fetchedAt: '2026-01-01T00:00:00.000Z',
};
const shopIcon = loadShopIcon({
Config: {
get: async () => stored,
set: async (key, value) => { stored = value; },
},
Core: {
fetch: async () => ({ status: 503, data: Buffer.alloc(0), headers: {} }),
callModule: async () => ({}),
},
Log: { warn() {} },
});
const result = await shopIcon.ensureShopIcon({
apiUrl: 'https://shop.test/api',
shopName: 'Sklep',
force: true,
});
assert.equal(result.dataUrl, oldIcon);
assert.equal(result.sourceUrl, 'https://shop.test/old.png');
assert.equal(stored.dataUrl, oldIcon);
});
test('favicon discovery rejects cross-host candidates and recognizes common binary formats', () => {
const shopIcon = loadShopIcon({ Config: {}, Core: {}, Log: { warn() {} } });
const candidates = shopIcon.faviconCandidates(
'<link rel="icon" href="https://cdn.test/icon.png"><link rel="apple-touch-icon" href="/touch.png">',
'https://shop.test/catalog/'
);
assert.deepEqual(candidates, [
'https://cdn.test/icon.png',
'https://shop.test/touch.png',
'https://shop.test/catalog/favicon.ico',
]);
assert.equal(shopIcon.detectIconMime(pngBuffer()), 'image/png');
assert.equal(shopIcon.detectIconMime(Buffer.from([0, 0, 1, 0])), 'image/vnd.microsoft.icon');
assert.equal(shopIcon.storefrontUrl('https://shop.test/catalog/api?key=secret'), 'https://shop.test/catalog/');
});