@aglyn/plugins-commerce 1.29.1 → 1.29.3
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/package.json +13 -13
- package/src/lib/components/console/checkout-tax-blocked-notice.component.d.ts +18 -0
- package/src/lib/components/console/checkout-tax-blocked-notice.component.js +67 -0
- package/src/lib/components/console/checkout-tax-blocked-notice.component.js.map +1 -0
- package/src/lib/components/console/payments-settings-card.component.d.ts +2 -2
- package/src/lib/components/console/payments-settings-card.component.js +99 -5
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +14 -3
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +51 -14
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/stripe-tax-readiness.component.d.ts +45 -0
- package/src/lib/components/console/stripe-tax-readiness.component.js +276 -0
- package/src/lib/components/console/stripe-tax-readiness.component.js.map +1 -0
- package/src/lib/components/console/tax-settings-card.component.js +22 -8
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +9 -0
- package/src/lib/constants/operator-alerts.js +22 -1
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/declarations.server.js +11 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/commerce-record-routes.d.ts +13 -1
- package/src/lib/model/commerce-record-routes.js +22 -2
- package/src/lib/model/commerce-record-routes.js.map +1 -1
- package/src/lib/model/commerce-tax-readiness.d.ts +79 -0
- package/src/lib/model/commerce-tax-readiness.js +99 -0
- package/src/lib/model/commerce-tax-readiness.js.map +1 -0
- package/src/lib/model/commerce.d.ts +7 -0
- package/src/lib/model/commerce.js +17 -4
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/payments-setup-status.d.ts +68 -0
- package/src/lib/model/payments-setup-status.js +103 -0
- package/src/lib/model/payments-setup-status.js.map +1 -0
- package/src/lib/plan-entitlements.d.ts +2 -2
- package/src/lib/plan-entitlements.js +4 -12
- package/src/lib/plan-entitlements.js.map +1 -1
- package/src/lib/server/cart-checkout.js +3 -0
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/checkout-tax-refusal.d.ts +51 -0
- package/src/lib/server/checkout-tax-refusal.js +133 -0
- package/src/lib/server/checkout-tax-refusal.js.map +1 -0
- package/src/lib/server/checkout.d.ts +2 -1
- package/src/lib/server/checkout.js +7 -2
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect-prefill.d.ts +65 -0
- package/src/lib/server/connect-prefill.js +85 -0
- package/src/lib/server/connect-prefill.js.map +1 -0
- package/src/lib/server/connect.d.ts +4 -2
- package/src/lib/server/connect.js +117 -37
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +4 -2
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/pos-order.js +1 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/product-writer.d.ts +27 -0
- package/src/lib/server/product-writer.js +174 -4
- package/src/lib/server/product-writer.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +6 -0
- package/src/lib/server/quote-pay.js +8 -2
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +19 -0
- package/src/lib/server/seller-stripe-account.js +40 -4
- package/src/lib/server/seller-stripe-account.js.map +1 -1
- package/src/lib/server/site-page-resolver.d.ts +11 -5
- package/src/lib/server/site-page-resolver.js +102 -19
- package/src/lib/server/site-page-resolver.js.map +1 -1
- package/src/lib/server/site-search.d.ts +43 -0
- package/src/lib/server/site-search.js +124 -0
- package/src/lib/server/site-search.js.map +1 -0
- package/src/lib/server/tax-readiness.d.ts +56 -0
- package/src/lib/server/tax-readiness.js +169 -0
- package/src/lib/server/tax-readiness.js.map +1 -0
- package/src/lib/server.js +10 -2
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/product-image-copy.server.d.ts +77 -0
- package/src/lib/transfer/product-image-copy.server.js +307 -0
- package/src/lib/transfer/product-image-copy.server.js.map +1 -0
- package/src/lib/transfer/product-images.d.ts +62 -0
- package/src/lib/transfer/product-images.js +143 -0
- package/src/lib/transfer/product-images.js.map +1 -0
- package/src/lib/transfer/product-sources.d.ts +92 -0
- package/src/lib/transfer/product-sources.js +519 -0
- package/src/lib/transfer/product-sources.js.map +1 -0
- package/src/lib/transfer/product-transfer.d.ts +26 -1
- package/src/lib/transfer/product-transfer.js +283 -11
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.d.ts +29 -3
- package/src/lib/transfer/products.server.js +289 -13
- package/src/lib/transfer/products.server.js.map +1 -1
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import { PRODUCT_IMPORT_FOLDER_NAME, PRODUCT_IMPORT_IMAGE_CONCURRENCY, PRODUCT_IMPORT_IMAGE_MAX_BYTES, PRODUCT_IMPORT_IMAGE_SLOT_MS, PRODUCT_IMPORT_IMAGE_TIMEOUT_MS, PRODUCT_IMPORT_IMAGE_TYPES, productImageContentType, productImageFileName } from "./product-images.js";
|
|
19
|
+
/*==========================================
|
|
20
|
+
* COPYING A PRODUCT FILE'S PHOTOS, ON THE SERVER (AGL-4245).
|
|
21
|
+
*
|
|
22
|
+
* - **The guard.** A photo's address is the file's, so it is fetched only
|
|
23
|
+
* through the platform's SSRF primitives in `@aglyn/tenant-data-admin`
|
|
24
|
+
* (`resolvePublicIp` + `createPinnedDispatcher`, the plugin fetch proxy's,
|
|
25
|
+
* which `site-image-source.ts` already uses here): https on the default
|
|
26
|
+
* port, no credentials, a name that resolves only to public addresses and
|
|
27
|
+
* a socket pinned to the address checked. A redirect is followed only by
|
|
28
|
+
* running every check again on where it points, up to three hops, so a
|
|
29
|
+
* public address cannot hand the fetch to a private one. The body is read
|
|
30
|
+
* to a byte cap under a clock, and only as JPEG, PNG, WebP or GIF.
|
|
31
|
+
* (Bring my site's `fetchPublicTextDetailed` does the same over the same
|
|
32
|
+
* primitives, but lives in the AI plugin, which this plugin may not import.)
|
|
33
|
+
* - **The store.** Bytes go in only through the media library's server door
|
|
34
|
+
* (`pluginMediaIngest().ingest`), which checks the member, the lockdown,
|
|
35
|
+
* the bytes' structure, the takedown list and the storage band as an
|
|
36
|
+
* upload is checked, and files them in the "Imported products" folder.
|
|
37
|
+
* - **Never a second copy.** Each photo is asked for by its key first
|
|
38
|
+
* (`findImportedPhoto`), so a photo two products share, a chunk retried,
|
|
39
|
+
* or the same file imported again finds the copy already stored.
|
|
40
|
+
* - **One photo never fails a product.** Every refusal is an answer, never
|
|
41
|
+
* a throw, and the product is written without that photo.
|
|
42
|
+
*=========================================*/ /** The key the site's library holds a copied photo by, the same as Bring my site's `siteImportImageKey`. */ export function productImageKey(url) {
|
|
43
|
+
return `import:${createHash('sha256').update(url).digest('hex').slice(0, 32)}`;
|
|
44
|
+
}
|
|
45
|
+
const MAX_REDIRECT_HOPS = 3;
|
|
46
|
+
const REDIRECT_STATUSES = new Set([
|
|
47
|
+
301,
|
|
48
|
+
302,
|
|
49
|
+
303,
|
|
50
|
+
307,
|
|
51
|
+
308
|
|
52
|
+
]);
|
|
53
|
+
async function guardDeps() {
|
|
54
|
+
// By relative path, never by the lib's specifier (`pos-reader-splash-server.ts` says why).
|
|
55
|
+
const { createPinnedDispatcher, resolvePublicIp } = await import("../server/pos-reader-splash-server.js");
|
|
56
|
+
return {
|
|
57
|
+
createPinnedDispatcher,
|
|
58
|
+
resolvePublicIp,
|
|
59
|
+
fetch: (url, init)=>fetch(url, init)
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const refused = (refusal, status)=>_extends({
|
|
63
|
+
ok: false,
|
|
64
|
+
contentType: '',
|
|
65
|
+
refusal
|
|
66
|
+
}, status !== undefined ? {
|
|
67
|
+
status
|
|
68
|
+
} : {});
|
|
69
|
+
async function readCapped(body, maxBytes) {
|
|
70
|
+
const reader = body.getReader();
|
|
71
|
+
const chunks = [];
|
|
72
|
+
let total = 0;
|
|
73
|
+
for(;;){
|
|
74
|
+
const { done, value } = await reader.read();
|
|
75
|
+
if (done) break;
|
|
76
|
+
total += value.byteLength;
|
|
77
|
+
if (total > maxBytes) {
|
|
78
|
+
await reader.cancel().catch(()=>undefined);
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
chunks.push(value);
|
|
82
|
+
}
|
|
83
|
+
const joined = new Uint8Array(total);
|
|
84
|
+
let offset = 0;
|
|
85
|
+
for (const chunk of chunks){
|
|
86
|
+
joined.set(chunk, offset);
|
|
87
|
+
offset += chunk.byteLength;
|
|
88
|
+
}
|
|
89
|
+
return joined;
|
|
90
|
+
}
|
|
91
|
+
/** One photo's bytes, under the guard above. Never throws. */ export async function fetchProductImage(url, options = {}, deps) {
|
|
92
|
+
var _options_maxBytes, _options_timeoutMs;
|
|
93
|
+
const maxBytes = (_options_maxBytes = options.maxBytes) != null ? _options_maxBytes : PRODUCT_IMPORT_IMAGE_MAX_BYTES;
|
|
94
|
+
const timeoutMs = (_options_timeoutMs = options.timeoutMs) != null ? _options_timeoutMs : PRODUCT_IMPORT_IMAGE_TIMEOUT_MS;
|
|
95
|
+
const guard = deps != null ? deps : await guardDeps();
|
|
96
|
+
const controller = new AbortController();
|
|
97
|
+
const timer = setTimeout(()=>controller.abort(), timeoutMs);
|
|
98
|
+
let current = url;
|
|
99
|
+
try {
|
|
100
|
+
for(let hop = 0; hop <= MAX_REDIRECT_HOPS; hop += 1){
|
|
101
|
+
let parsed;
|
|
102
|
+
try {
|
|
103
|
+
parsed = new URL(current);
|
|
104
|
+
} catch (unused) {
|
|
105
|
+
return refused('refused-url');
|
|
106
|
+
}
|
|
107
|
+
if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.port && parsed.port !== '443') {
|
|
108
|
+
return refused('refused-url');
|
|
109
|
+
}
|
|
110
|
+
const pinned = await guard.resolvePublicIp(parsed.hostname);
|
|
111
|
+
if (!pinned) return refused('private-address');
|
|
112
|
+
const dispatcher = guard.createPinnedDispatcher(pinned);
|
|
113
|
+
try {
|
|
114
|
+
var _response_headers_get, _response_headers_get1;
|
|
115
|
+
const response = await guard.fetch(parsed.toString(), {
|
|
116
|
+
method: 'GET',
|
|
117
|
+
redirect: 'manual',
|
|
118
|
+
signal: controller.signal,
|
|
119
|
+
dispatcher,
|
|
120
|
+
headers: {
|
|
121
|
+
Accept: 'image/webp,image/png,image/jpeg,image/gif;q=0.9'
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
if (REDIRECT_STATUSES.has(response.status)) {
|
|
125
|
+
var _response_body;
|
|
126
|
+
await ((_response_body = response.body) == null ? void 0 : _response_body.cancel().catch(()=>undefined));
|
|
127
|
+
const location = response.headers.get('location');
|
|
128
|
+
if (!location) return refused('http-status', response.status);
|
|
129
|
+
try {
|
|
130
|
+
current = new URL(location, parsed).toString();
|
|
131
|
+
} catch (unused) {
|
|
132
|
+
return refused('refused-url');
|
|
133
|
+
}
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (!response.ok || !response.body) {
|
|
137
|
+
var _response_body1;
|
|
138
|
+
await ((_response_body1 = response.body) == null ? void 0 : _response_body1.cancel().catch(()=>undefined));
|
|
139
|
+
return refused('http-status', response.status);
|
|
140
|
+
}
|
|
141
|
+
const contentType = (_response_headers_get = response.headers.get('content-type')) != null ? _response_headers_get : '';
|
|
142
|
+
if (!PRODUCT_IMPORT_IMAGE_TYPES.test(contentType)) {
|
|
143
|
+
await response.body.cancel().catch(()=>undefined);
|
|
144
|
+
return refused('content-type', response.status);
|
|
145
|
+
}
|
|
146
|
+
const declared = Number((_response_headers_get1 = response.headers.get('content-length')) != null ? _response_headers_get1 : '');
|
|
147
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
148
|
+
await response.body.cancel().catch(()=>undefined);
|
|
149
|
+
return refused('too-large', response.status);
|
|
150
|
+
}
|
|
151
|
+
const data = await readCapped(response.body, maxBytes);
|
|
152
|
+
if (!data) return refused('too-large', response.status);
|
|
153
|
+
return {
|
|
154
|
+
ok: true,
|
|
155
|
+
data,
|
|
156
|
+
contentType: productImageContentType(contentType),
|
|
157
|
+
refusal: null
|
|
158
|
+
};
|
|
159
|
+
} finally{
|
|
160
|
+
await (dispatcher.close == null ? void 0 : dispatcher.close.call(dispatcher).catch(()=>undefined));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return refused('too-many-redirects');
|
|
164
|
+
} catch (unused) {
|
|
165
|
+
return refused('network');
|
|
166
|
+
} finally{
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** What the result says of a photo that was not copied. */ export function productImageRefusalWords(refusal, status) {
|
|
171
|
+
switch(refusal){
|
|
172
|
+
case 'refused-url':
|
|
173
|
+
return 'its address is not one a photo can be copied from';
|
|
174
|
+
case 'private-address':
|
|
175
|
+
return 'its address does not lead to a public website';
|
|
176
|
+
case 'too-many-redirects':
|
|
177
|
+
return 'its address forwards too many times';
|
|
178
|
+
case 'http-status':
|
|
179
|
+
return status === 404 || status === 410 ? 'the old store no longer has it' : `the old store answered with an error${status ? ` (${status})` : ''}`;
|
|
180
|
+
case 'content-type':
|
|
181
|
+
return 'it is not a JPEG, PNG, WebP or GIF photo';
|
|
182
|
+
case 'too-large':
|
|
183
|
+
return `it is larger than ${Math.round(PRODUCT_IMPORT_IMAGE_MAX_BYTES / (1024 * 1024))} MB`;
|
|
184
|
+
case 'network':
|
|
185
|
+
return 'the old store did not answer in time';
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** A copier for one chunk of one import: its answers are kept, so a photo two rows share is copied once. */ export function productImageCopier(input, deps) {
|
|
189
|
+
var _deps_now, _deps_fetch;
|
|
190
|
+
const now = (_deps_now = deps.now) != null ? _deps_now : Date.now;
|
|
191
|
+
const fetchImage = (_deps_fetch = deps.fetch) != null ? _deps_fetch : (url)=>fetchProductImage(url);
|
|
192
|
+
const answers = new Map();
|
|
193
|
+
let folder = null;
|
|
194
|
+
const folderId = ()=>{
|
|
195
|
+
const ingest = deps.ingest;
|
|
196
|
+
folder != null ? folder : folder = (ingest == null ? void 0 : ingest.ensureFolder) && input.uid ? ingest.ensureFolder({
|
|
197
|
+
hostId: input.hostId,
|
|
198
|
+
uid: input.uid,
|
|
199
|
+
name: PRODUCT_IMPORT_FOLDER_NAME
|
|
200
|
+
}).catch(()=>null) : Promise.resolve(null);
|
|
201
|
+
return folder;
|
|
202
|
+
};
|
|
203
|
+
const copyOne = async (url)=>{
|
|
204
|
+
const ingest = deps.ingest;
|
|
205
|
+
if (!(ingest == null ? void 0 : ingest.findImportedPhoto) || !input.uid) return {
|
|
206
|
+
ok: false,
|
|
207
|
+
reason: 'the media library could not be reached'
|
|
208
|
+
};
|
|
209
|
+
const key = productImageKey(url);
|
|
210
|
+
try {
|
|
211
|
+
const held = await ingest.findImportedPhoto({
|
|
212
|
+
hostId: input.hostId,
|
|
213
|
+
sourceKey: key
|
|
214
|
+
});
|
|
215
|
+
if (held) return {
|
|
216
|
+
ok: true,
|
|
217
|
+
src: held.src,
|
|
218
|
+
mediaId: held.mediaId,
|
|
219
|
+
created: false,
|
|
220
|
+
key
|
|
221
|
+
};
|
|
222
|
+
const into = await folderId();
|
|
223
|
+
if (!into) return {
|
|
224
|
+
ok: false,
|
|
225
|
+
reason: `the "${PRODUCT_IMPORT_FOLDER_NAME}" folder could not be made in your media library`
|
|
226
|
+
};
|
|
227
|
+
const fetched = await fetchImage(url);
|
|
228
|
+
if (!fetched.ok || !fetched.data) {
|
|
229
|
+
var _fetched_refusal;
|
|
230
|
+
return {
|
|
231
|
+
ok: false,
|
|
232
|
+
reason: productImageRefusalWords((_fetched_refusal = fetched.refusal) != null ? _fetched_refusal : 'network', fetched.status)
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
let domain = '';
|
|
236
|
+
try {
|
|
237
|
+
domain = new URL(url).hostname;
|
|
238
|
+
} catch (unused) {
|
|
239
|
+
// The address was read once already; a name is only a label here.
|
|
240
|
+
}
|
|
241
|
+
const stored = await ingest.ingest({
|
|
242
|
+
hostId: input.hostId,
|
|
243
|
+
uid: input.uid,
|
|
244
|
+
fileName: productImageFileName(url, fetched.contentType),
|
|
245
|
+
contentType: fetched.contentType,
|
|
246
|
+
bytes: fetched.data,
|
|
247
|
+
folderId: into,
|
|
248
|
+
importedFrom: _extends({
|
|
249
|
+
key,
|
|
250
|
+
url,
|
|
251
|
+
domain
|
|
252
|
+
}, input.jobId ? {
|
|
253
|
+
jobId: input.jobId
|
|
254
|
+
} : {})
|
|
255
|
+
});
|
|
256
|
+
// A union does not narrow across this repo's library boundaries (`strictNullChecks` is off).
|
|
257
|
+
if (!stored.ok) {
|
|
258
|
+
var _stored_reason;
|
|
259
|
+
const refusal = String((_stored_reason = stored.reason) != null ? _stored_reason : '').replace(/\.$/, '');
|
|
260
|
+
return {
|
|
261
|
+
ok: false,
|
|
262
|
+
reason: refusal ? `your media library did not take it (${refusal})` : 'your media library did not take it'
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
const asset = stored;
|
|
266
|
+
return {
|
|
267
|
+
ok: true,
|
|
268
|
+
src: asset.src,
|
|
269
|
+
mediaId: asset.mediaId,
|
|
270
|
+
created: true,
|
|
271
|
+
key
|
|
272
|
+
};
|
|
273
|
+
} catch (error) {
|
|
274
|
+
console.warn('[commerce] a product photo could not be copied', {
|
|
275
|
+
hostId: input.hostId,
|
|
276
|
+
error
|
|
277
|
+
});
|
|
278
|
+
return {
|
|
279
|
+
ok: false,
|
|
280
|
+
reason: 'it could not be copied'
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
const pending = (urls)=>[
|
|
285
|
+
...new Set(urls)
|
|
286
|
+
].filter((url)=>!answers.has(url));
|
|
287
|
+
return {
|
|
288
|
+
pending,
|
|
289
|
+
result: (url)=>answers.get(url),
|
|
290
|
+
async copy (urls, deadlineAt) {
|
|
291
|
+
const queue = pending(urls);
|
|
292
|
+
const worker = async ()=>{
|
|
293
|
+
while(queue.length){
|
|
294
|
+
if (deadlineAt - now() < PRODUCT_IMPORT_IMAGE_SLOT_MS) return;
|
|
295
|
+
const url = queue.shift();
|
|
296
|
+
answers.set(url, await copyOne(url));
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
await Promise.all(Array.from({
|
|
300
|
+
length: Math.min(PRODUCT_IMPORT_IMAGE_CONCURRENCY, queue.length)
|
|
301
|
+
}, worker));
|
|
302
|
+
return pending(urls).length === 0;
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
//# sourceMappingURL=product-image-copy.server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/product-image-copy.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginMediaIngest } from '@aglyn/aglyn/plugin-manager/plugin-media-ingest'\nimport { createHash } from 'node:crypto'\nimport {\n PRODUCT_IMPORT_FOLDER_NAME,\n PRODUCT_IMPORT_IMAGE_CONCURRENCY,\n PRODUCT_IMPORT_IMAGE_MAX_BYTES,\n PRODUCT_IMPORT_IMAGE_SLOT_MS,\n PRODUCT_IMPORT_IMAGE_TIMEOUT_MS,\n PRODUCT_IMPORT_IMAGE_TYPES,\n productImageContentType,\n productImageFileName,\n} from './product-images'\n\n/*==========================================\n * COPYING A PRODUCT FILE'S PHOTOS, ON THE SERVER (AGL-4245).\n *\n * - **The guard.** A photo's address is the file's, so it is fetched only\n * through the platform's SSRF primitives in `@aglyn/tenant-data-admin`\n * (`resolvePublicIp` + `createPinnedDispatcher`, the plugin fetch proxy's,\n * which `site-image-source.ts` already uses here): https on the default\n * port, no credentials, a name that resolves only to public addresses and\n * a socket pinned to the address checked. A redirect is followed only by\n * running every check again on where it points, up to three hops, so a\n * public address cannot hand the fetch to a private one. The body is read\n * to a byte cap under a clock, and only as JPEG, PNG, WebP or GIF.\n * (Bring my site's `fetchPublicTextDetailed` does the same over the same\n * primitives, but lives in the AI plugin, which this plugin may not import.)\n * - **The store.** Bytes go in only through the media library's server door\n * (`pluginMediaIngest().ingest`), which checks the member, the lockdown,\n * the bytes' structure, the takedown list and the storage band as an\n * upload is checked, and files them in the \"Imported products\" folder.\n * - **Never a second copy.** Each photo is asked for by its key first\n * (`findImportedPhoto`), so a photo two products share, a chunk retried,\n * or the same file imported again finds the copy already stored.\n * - **One photo never fails a product.** Every refusal is an answer, never\n * a throw, and the product is written without that photo.\n *=========================================*/\n\n/** The key the site's library holds a copied photo by, the same as Bring my site's `siteImportImageKey`. */\nexport function productImageKey(url: string): string {\n return `import:${createHash('sha256').update(url).digest('hex').slice(0, 32)}`\n}\n\n/** Why a photo's fetch read nothing. */\nexport type ProductImageRefusal =\n | 'refused-url'\n | 'private-address'\n | 'too-many-redirects'\n | 'http-status'\n | 'content-type'\n | 'too-large'\n | 'network'\n\nexport interface ProductImageFetchResult {\n ok: boolean\n /** The body, when `ok`. */\n data?: Uint8Array\n contentType: string\n refusal: ProductImageRefusal | null\n status?: number\n}\n\n/** The guard primitives and the transport, injectable for a spec. */\nexport interface ProductImageFetchDeps {\n resolvePublicIp(hostname: string): Promise<string | null>\n createPinnedDispatcher(ip: string): unknown\n fetch: (url: string, init: Record<string, unknown>) => Promise<Response>\n}\n\nconst MAX_REDIRECT_HOPS = 3\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])\n\nasync function guardDeps(): Promise<ProductImageFetchDeps> {\n // By relative path, never by the lib's specifier (`pos-reader-splash-server.ts` says why).\n const { createPinnedDispatcher, resolvePublicIp } = await import('../server/pos-reader-splash-server')\n return { createPinnedDispatcher, resolvePublicIp, fetch: (url, init) => fetch(url, init as RequestInit) }\n}\n\nconst refused = (refusal: ProductImageRefusal, status?: number): ProductImageFetchResult => ({\n ok: false,\n contentType: '',\n refusal,\n ...(status !== undefined ? { status } : {}),\n})\n\nasync function readCapped(body: ReadableStream<Uint8Array>, maxBytes: number): Promise<Uint8Array | null> {\n const reader = body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n total += value.byteLength\n if (total > maxBytes) {\n await reader.cancel().catch(() => undefined)\n return null\n }\n chunks.push(value)\n }\n const joined = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n joined.set(chunk, offset)\n offset += chunk.byteLength\n }\n return joined\n}\n\n/** One photo's bytes, under the guard above. Never throws. */\nexport async function fetchProductImage(\n url: string,\n options: { maxBytes?: number; timeoutMs?: number } = {},\n deps?: ProductImageFetchDeps,\n): Promise<ProductImageFetchResult> {\n const maxBytes = options.maxBytes ?? PRODUCT_IMPORT_IMAGE_MAX_BYTES\n const timeoutMs = options.timeoutMs ?? PRODUCT_IMPORT_IMAGE_TIMEOUT_MS\n const guard = deps ?? (await guardDeps())\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n let current = url\n try {\n for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop += 1) {\n let parsed: URL\n try {\n parsed = new URL(current)\n } catch {\n return refused('refused-url')\n }\n if (parsed.protocol !== 'https:' || parsed.username || parsed.password || (parsed.port && parsed.port !== '443')) {\n return refused('refused-url')\n }\n const pinned = await guard.resolvePublicIp(parsed.hostname)\n if (!pinned) return refused('private-address')\n const dispatcher = guard.createPinnedDispatcher(pinned) as { close?: () => Promise<void> }\n try {\n const response = await guard.fetch(parsed.toString(), {\n method: 'GET',\n redirect: 'manual',\n signal: controller.signal,\n dispatcher,\n headers: { Accept: 'image/webp,image/png,image/jpeg,image/gif;q=0.9' },\n })\n if (REDIRECT_STATUSES.has(response.status)) {\n await response.body?.cancel().catch(() => undefined)\n const location = response.headers.get('location')\n if (!location) return refused('http-status', response.status)\n try {\n current = new URL(location, parsed).toString()\n } catch {\n return refused('refused-url')\n }\n continue\n }\n if (!response.ok || !response.body) {\n await response.body?.cancel().catch(() => undefined)\n return refused('http-status', response.status)\n }\n const contentType = response.headers.get('content-type') ?? ''\n if (!PRODUCT_IMPORT_IMAGE_TYPES.test(contentType)) {\n await response.body.cancel().catch(() => undefined)\n return refused('content-type', response.status)\n }\n const declared = Number(response.headers.get('content-length') ?? '')\n if (Number.isFinite(declared) && declared > maxBytes) {\n await response.body.cancel().catch(() => undefined)\n return refused('too-large', response.status)\n }\n const data = await readCapped(response.body, maxBytes)\n if (!data) return refused('too-large', response.status)\n return { ok: true, data, contentType: productImageContentType(contentType), refusal: null }\n } finally {\n await dispatcher.close?.().catch(() => undefined)\n }\n }\n return refused('too-many-redirects')\n } catch {\n return refused('network')\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** What the result says of a photo that was not copied. */\nexport function productImageRefusalWords(refusal: ProductImageRefusal, status?: number): string {\n switch (refusal) {\n case 'refused-url':\n return 'its address is not one a photo can be copied from'\n case 'private-address':\n return 'its address does not lead to a public website'\n case 'too-many-redirects':\n return 'its address forwards too many times'\n case 'http-status':\n return status === 404 || status === 410 ? 'the old store no longer has it' : `the old store answered with an error${status ? ` (${status})` : ''}`\n case 'content-type':\n return 'it is not a JPEG, PNG, WebP or GIF photo'\n case 'too-large':\n return `it is larger than ${Math.round(PRODUCT_IMPORT_IMAGE_MAX_BYTES / (1024 * 1024))} MB`\n case 'network':\n return 'the old store did not answer in time'\n }\n}\n\n/** One photo's answer. */\nexport type CopiedProductImage =\n | { ok: true; src: string; mediaId: string; created: boolean; key: string }\n | { ok: false; reason: string }\n\nexport interface ProductImageCopierDeps {\n ingest: PluginMediaIngest | null\n fetch?: (url: string) => Promise<ProductImageFetchResult>\n now?: () => number\n}\n\nexport interface ProductImageCopier {\n /** The addresses of `urls` with no answer yet. */\n pending(urls: readonly string[]): string[]\n /** An address's answer, once it has one. */\n result(url: string): CopiedProductImage | undefined\n /**\n * Copies every address of `urls` without an answer, a few at a time,\n * starting none that could not finish before `deadlineAt`. `true` when\n * every one has an answer; `false` when time ran out first, and the row\n * is written on the next pass, which finds what this one stored.\n */\n copy(urls: readonly string[], deadlineAt: number): Promise<boolean>\n}\n\n/** A copier for one chunk of one import: its answers are kept, so a photo two rows share is copied once. */\nexport function productImageCopier(\n input: { hostId: string; uid: string | null; jobId?: string },\n deps: ProductImageCopierDeps,\n): ProductImageCopier {\n const now = deps.now ?? Date.now\n const fetchImage = deps.fetch ?? ((url: string) => fetchProductImage(url))\n const answers = new Map<string, CopiedProductImage>()\n let folder: Promise<string | null> | null = null\n\n const folderId = () => {\n const ingest = deps.ingest\n folder ??= ingest?.ensureFolder && input.uid\n ? ingest.ensureFolder({ hostId: input.hostId, uid: input.uid, name: PRODUCT_IMPORT_FOLDER_NAME }).catch(() => null)\n : Promise.resolve(null)\n return folder\n }\n\n const copyOne = async (url: string): Promise<CopiedProductImage> => {\n const ingest = deps.ingest\n if (!ingest?.findImportedPhoto || !input.uid) return { ok: false, reason: 'the media library could not be reached' }\n const key = productImageKey(url)\n try {\n const held = await ingest.findImportedPhoto({ hostId: input.hostId, sourceKey: key })\n if (held) return { ok: true, src: held.src, mediaId: held.mediaId, created: false, key }\n const into = await folderId()\n if (!into) return { ok: false, reason: `the \"${PRODUCT_IMPORT_FOLDER_NAME}\" folder could not be made in your media library` }\n const fetched = await fetchImage(url)\n if (!fetched.ok || !fetched.data) {\n return { ok: false, reason: productImageRefusalWords(fetched.refusal ?? 'network', fetched.status) }\n }\n let domain = ''\n try {\n domain = new URL(url).hostname\n } catch {\n // The address was read once already; a name is only a label here.\n }\n const stored = await ingest.ingest({\n hostId: input.hostId,\n uid: input.uid,\n fileName: productImageFileName(url, fetched.contentType),\n contentType: fetched.contentType,\n bytes: fetched.data,\n folderId: into,\n importedFrom: { key, url, domain, ...(input.jobId ? { jobId: input.jobId } : {}) },\n })\n // A union does not narrow across this repo's library boundaries (`strictNullChecks` is off).\n if (!stored.ok) {\n const refusal = String((stored as { reason?: string }).reason ?? '').replace(/\\.$/, '')\n return { ok: false, reason: refusal ? `your media library did not take it (${refusal})` : 'your media library did not take it' }\n }\n const asset = stored as { src: string; mediaId: string }\n return { ok: true, src: asset.src, mediaId: asset.mediaId, created: true, key }\n } catch (error) {\n console.warn('[commerce] a product photo could not be copied', { hostId: input.hostId, error })\n return { ok: false, reason: 'it could not be copied' }\n }\n }\n\n const pending = (urls: readonly string[]) => [...new Set(urls)].filter((url) => !answers.has(url))\n\n return {\n pending,\n result: (url) => answers.get(url),\n async copy(urls, deadlineAt) {\n const queue = pending(urls)\n const worker = async () => {\n while (queue.length) {\n if (deadlineAt - now() < PRODUCT_IMPORT_IMAGE_SLOT_MS) return\n const url = queue.shift() as string\n answers.set(url, await copyOne(url))\n }\n }\n await Promise.all(Array.from({ length: Math.min(PRODUCT_IMPORT_IMAGE_CONCURRENCY, queue.length) }, worker))\n return pending(urls).length === 0\n },\n }\n}\n"],"names":["createHash","PRODUCT_IMPORT_FOLDER_NAME","PRODUCT_IMPORT_IMAGE_CONCURRENCY","PRODUCT_IMPORT_IMAGE_MAX_BYTES","PRODUCT_IMPORT_IMAGE_SLOT_MS","PRODUCT_IMPORT_IMAGE_TIMEOUT_MS","PRODUCT_IMPORT_IMAGE_TYPES","productImageContentType","productImageFileName","productImageKey","url","update","digest","slice","MAX_REDIRECT_HOPS","REDIRECT_STATUSES","Set","guardDeps","createPinnedDispatcher","resolvePublicIp","fetch","init","refused","refusal","status","ok","contentType","undefined","readCapped","body","maxBytes","reader","getReader","chunks","total","done","value","read","byteLength","cancel","catch","push","joined","Uint8Array","offset","chunk","set","fetchProductImage","options","deps","timeoutMs","guard","controller","AbortController","timer","setTimeout","abort","current","hop","parsed","URL","protocol","username","password","port","pinned","hostname","dispatcher","response","toString","method","redirect","signal","headers","Accept","has","location","get","test","declared","Number","isFinite","data","close","clearTimeout","productImageRefusalWords","Math","round","productImageCopier","input","now","Date","fetchImage","answers","Map","folder","folderId","ingest","ensureFolder","uid","hostId","name","Promise","resolve","copyOne","findImportedPhoto","reason","key","held","sourceKey","src","mediaId","created","into","fetched","domain","stored","fileName","bytes","importedFrom","jobId","String","replace","asset","error","console","warn","pending","urls","filter","result","copy","deadlineAt","queue","worker","length","shift","all","Array","from","min"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,UAAU,QAAQ,cAAa;AACxC,SACEC,0BAA0B,EAC1BC,gCAAgC,EAChCC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,+BAA+B,EAC/BC,0BAA0B,EAC1BC,uBAAuB,EACvBC,oBAAoB,QACf,sBAAkB;AAEzB;;;;;;;;;;;;;;;;;;;;;;;2CAuB2C,GAE3C,0GAA0G,GAC1G,OAAO,SAASC,gBAAgBC,GAAW;IACzC,OAAO,CAAC,OA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5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/** The folder of the site's media library imported product photos are filed in. */
|
|
18
|
+
export declare const PRODUCT_IMPORT_FOLDER_NAME = "Imported products";
|
|
19
|
+
/**
|
|
20
|
+
* The largest photo copied: the media library's own limit for an uploaded
|
|
21
|
+
* image (`IMAGE_MAX_BYTES` in the console's `media-upload-limits.ts`, 15 MB),
|
|
22
|
+
* which the library checks again when it stores the bytes.
|
|
23
|
+
*/
|
|
24
|
+
export declare const PRODUCT_IMPORT_IMAGE_MAX_BYTES: number;
|
|
25
|
+
/**
|
|
26
|
+
* The most distinct photos one import copies. A 500-product store with four
|
|
27
|
+
* photos each is 2,000; past it the dry run lists what is skipped. The
|
|
28
|
+
* storage itself is held to the plan by the library, photo by photo.
|
|
29
|
+
*/
|
|
30
|
+
export declare const PRODUCT_IMPORT_IMAGES_MAX = 2000;
|
|
31
|
+
/** One photo's own clock, as Bring my site gives one (`SITE_IMPORT_IMAGE_TIMEOUT_MS`). */
|
|
32
|
+
export declare const PRODUCT_IMPORT_IMAGE_TIMEOUT_MS = 8000;
|
|
33
|
+
/** The time a photo is started with: its fetch, and the library storing it. */
|
|
34
|
+
export declare const PRODUCT_IMPORT_IMAGE_SLOT_MS: number;
|
|
35
|
+
/** How many photos are fetched at once. */
|
|
36
|
+
export declare const PRODUCT_IMPORT_IMAGE_CONCURRENCY = 4;
|
|
37
|
+
/** The image types the library takes from a server. */
|
|
38
|
+
export declare const PRODUCT_IMPORT_IMAGE_TYPES: RegExp;
|
|
39
|
+
/** Why a cell's photo is not copied. */
|
|
40
|
+
export type ProductImageSkip = 'notHttps' | 'notAddress' | 'mediaName' | 'overLimit';
|
|
41
|
+
/** What one photo cell is. */
|
|
42
|
+
export type ProductImageCell = {
|
|
43
|
+
kind: 'copy';
|
|
44
|
+
url: string;
|
|
45
|
+
} | {
|
|
46
|
+
kind: 'stored';
|
|
47
|
+
value: string;
|
|
48
|
+
} | {
|
|
49
|
+
kind: 'skip';
|
|
50
|
+
value: string;
|
|
51
|
+
skip: ProductImageSkip;
|
|
52
|
+
};
|
|
53
|
+
/** One photo cell, read. `null` for a blank one. */
|
|
54
|
+
export declare function productImageCell(raw: unknown): ProductImageCell | null;
|
|
55
|
+
/** The photos one cell names: several, split by semicolons, spaces or bars (a Wix or Squarespace cell). */
|
|
56
|
+
export declare function productImageList(raw: unknown): string[];
|
|
57
|
+
/** What the dry run says of a skipped photo. */
|
|
58
|
+
export declare function productImageSkipDetail(skip: ProductImageSkip): string;
|
|
59
|
+
/** A file name for the library, from the photo's address and type. */
|
|
60
|
+
export declare function productImageFileName(url: string, contentType: string): string;
|
|
61
|
+
/** A content type as the library names it: `image/jpg` and `image/pjpeg` are JPEG. */
|
|
62
|
+
export declare function productImageContentType(header: string): string;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { isMediaCdnPath, isMediaRef } from "@aglyn/aglyn/app-utils/media-ref";
|
|
17
|
+
/*==========================================
|
|
18
|
+
* A PRODUCT FILE'S PHOTOS, COPIED INTO THE STORE'S MEDIA LIBRARY (AGL-4245).
|
|
19
|
+
*
|
|
20
|
+
* A file from another store names its photos by their address on that
|
|
21
|
+
* store. Kept as addresses, every photo would keep loading from the old
|
|
22
|
+
* platform and break when the old store closes, so the apply copies each one
|
|
23
|
+
* into the site's own media library and the product names the stored file
|
|
24
|
+
* by its media reference, exactly as a photo the owner picked in the product
|
|
25
|
+
* editor. This module is the pure half: which cells are photos to copy,
|
|
26
|
+
* which are already the library's own, which are skipped and why, and the
|
|
27
|
+
* file name it is stored under. The fetch, the store and the key a copied
|
|
28
|
+
* photo is found by again are `product-image-copy.server.ts`.
|
|
29
|
+
*
|
|
30
|
+
* - **Copied**: an https address on the default port, with no user name.
|
|
31
|
+
* - **Kept as it is**: a media reference or a media CDN path, which is
|
|
32
|
+
* already a file of an Aglyn library (an Aglyn export read back in).
|
|
33
|
+
* - **Skipped, and said so in the dry run**: anything else. An `http://`
|
|
34
|
+
* address, a name with no address (a Wix file lists bare media names, and
|
|
35
|
+
* its host is not guessed), and every photo past the import's limit.
|
|
36
|
+
*=========================================*/ /** The folder of the site's media library imported product photos are filed in. */ export const PRODUCT_IMPORT_FOLDER_NAME = 'Imported products';
|
|
37
|
+
/**
|
|
38
|
+
* The largest photo copied: the media library's own limit for an uploaded
|
|
39
|
+
* image (`IMAGE_MAX_BYTES` in the console's `media-upload-limits.ts`, 15 MB),
|
|
40
|
+
* which the library checks again when it stores the bytes.
|
|
41
|
+
*/ export const PRODUCT_IMPORT_IMAGE_MAX_BYTES = 15 * 1024 * 1024;
|
|
42
|
+
/**
|
|
43
|
+
* The most distinct photos one import copies. A 500-product store with four
|
|
44
|
+
* photos each is 2,000; past it the dry run lists what is skipped. The
|
|
45
|
+
* storage itself is held to the plan by the library, photo by photo.
|
|
46
|
+
*/ export const PRODUCT_IMPORT_IMAGES_MAX = 2000;
|
|
47
|
+
/** One photo's own clock, as Bring my site gives one (`SITE_IMPORT_IMAGE_TIMEOUT_MS`). */ export const PRODUCT_IMPORT_IMAGE_TIMEOUT_MS = 8000;
|
|
48
|
+
/** The time a photo is started with: its fetch, and the library storing it. */ export const PRODUCT_IMPORT_IMAGE_SLOT_MS = PRODUCT_IMPORT_IMAGE_TIMEOUT_MS + 4000;
|
|
49
|
+
/** How many photos are fetched at once. */ export const PRODUCT_IMPORT_IMAGE_CONCURRENCY = 4;
|
|
50
|
+
/** The image types the library takes from a server. */ export const PRODUCT_IMPORT_IMAGE_TYPES = /^image\/(?:jpeg|jpg|pjpeg|png|webp|gif)\b/i;
|
|
51
|
+
const TRACKING_PARAM = /^(?:utm_[a-z]+|fbclid|gclid|msclkid|_ga)$/i;
|
|
52
|
+
const DOMAIN_PATH = /^(?:[\w-]+\.)+[a-z]{2,}(?:[/?#].*)?$/i;
|
|
53
|
+
/** One photo cell, read. `null` for a blank one. */ export function productImageCell(raw) {
|
|
54
|
+
const value = String(raw != null ? raw : '').trim();
|
|
55
|
+
if (!value) return null;
|
|
56
|
+
if (isMediaRef(value) || isMediaCdnPath(value)) return {
|
|
57
|
+
kind: 'stored',
|
|
58
|
+
value
|
|
59
|
+
};
|
|
60
|
+
const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(value);
|
|
61
|
+
if (!hasScheme && !DOMAIN_PATH.test(value)) return {
|
|
62
|
+
kind: 'skip',
|
|
63
|
+
value,
|
|
64
|
+
skip: 'mediaName'
|
|
65
|
+
};
|
|
66
|
+
let url;
|
|
67
|
+
try {
|
|
68
|
+
url = new URL(hasScheme ? value : `https://${value}`);
|
|
69
|
+
} catch (unused) {
|
|
70
|
+
return {
|
|
71
|
+
kind: 'skip',
|
|
72
|
+
value,
|
|
73
|
+
skip: 'notAddress'
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
if (url.protocol === 'http:') return {
|
|
77
|
+
kind: 'skip',
|
|
78
|
+
value,
|
|
79
|
+
skip: 'notHttps'
|
|
80
|
+
};
|
|
81
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.port && url.port !== '443') {
|
|
82
|
+
return {
|
|
83
|
+
kind: 'skip',
|
|
84
|
+
value,
|
|
85
|
+
skip: 'notAddress'
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
url.hash = '';
|
|
89
|
+
for (const key of [
|
|
90
|
+
...url.searchParams.keys()
|
|
91
|
+
])if (TRACKING_PARAM.test(key)) url.searchParams.delete(key);
|
|
92
|
+
return {
|
|
93
|
+
kind: 'copy',
|
|
94
|
+
url: url.toString()
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/** The photos one cell names: several, split by semicolons, spaces or bars (a Wix or Squarespace cell). */ export function productImageList(raw) {
|
|
98
|
+
const list = Array.isArray(raw) ? raw.map((item)=>String(item != null ? item : '')) : String(raw != null ? raw : '').split(/[;|\s]+/);
|
|
99
|
+
const out = [];
|
|
100
|
+
for (const item of list){
|
|
101
|
+
const value = item.trim();
|
|
102
|
+
if (value && !out.includes(value)) out.push(value);
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
/** What the dry run says of a skipped photo. */ export function productImageSkipDetail(skip) {
|
|
107
|
+
switch(skip){
|
|
108
|
+
case 'notHttps':
|
|
109
|
+
return 'Not copied: the address starts with http://, not https://. Add this photo on the product.';
|
|
110
|
+
case 'notAddress':
|
|
111
|
+
return 'Not copied: this is not a web address a photo can be copied from. Add this photo on the product.';
|
|
112
|
+
case 'mediaName':
|
|
113
|
+
return 'Not copied: the file names the photo but not where it is online. Add this photo on the product.';
|
|
114
|
+
case 'overLimit':
|
|
115
|
+
return `Not copied: one import copies up to ${PRODUCT_IMPORT_IMAGES_MAX.toLocaleString('en-US')} photos. Import the rest in a second file, or add them on the product.`;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const EXTENSION = {
|
|
119
|
+
'image/jpeg': 'jpg',
|
|
120
|
+
'image/png': 'png',
|
|
121
|
+
'image/webp': 'webp',
|
|
122
|
+
'image/gif': 'gif'
|
|
123
|
+
};
|
|
124
|
+
/** A file name for the library, from the photo's address and type. */ export function productImageFileName(url, contentType) {
|
|
125
|
+
var _EXTENSION_contentType;
|
|
126
|
+
let base = 'product-photo';
|
|
127
|
+
try {
|
|
128
|
+
var _pathname_split_filter_pop;
|
|
129
|
+
const last = decodeURIComponent((_pathname_split_filter_pop = new URL(url).pathname.split('/').filter(Boolean).pop()) != null ? _pathname_split_filter_pop : '');
|
|
130
|
+
base = last.replace(/\.[a-z0-9]+$/i, '').replace(/[^a-zA-Z0-9 _-]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') || base;
|
|
131
|
+
} catch (unused) {
|
|
132
|
+
// An address that does not decode keeps the plain name.
|
|
133
|
+
}
|
|
134
|
+
return `${base.slice(0, 80)}.${(_EXTENSION_contentType = EXTENSION[contentType]) != null ? _EXTENSION_contentType : 'jpg'}`;
|
|
135
|
+
}
|
|
136
|
+
/** A content type as the library names it: `image/jpg` and `image/pjpeg` are JPEG. */ export function productImageContentType(header) {
|
|
137
|
+
var _ref;
|
|
138
|
+
var _String_split_;
|
|
139
|
+
const type = (_ref = (_String_split_ = String(header != null ? header : '').split(';')[0]) == null ? void 0 : _String_split_.trim().toLowerCase()) != null ? _ref : '';
|
|
140
|
+
return type === 'image/jpg' || type === 'image/pjpeg' ? 'image/jpeg' : type;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
//# sourceMappingURL=product-images.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/product-images.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isMediaCdnPath, isMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\n\n/*==========================================\n * A PRODUCT FILE'S PHOTOS, COPIED INTO THE STORE'S MEDIA LIBRARY (AGL-4245).\n *\n * A file from another store names its photos by their address on that\n * store. Kept as addresses, every photo would keep loading from the old\n * platform and break when the old store closes, so the apply copies each one\n * into the site's own media library and the product names the stored file\n * by its media reference, exactly as a photo the owner picked in the product\n * editor. This module is the pure half: which cells are photos to copy,\n * which are already the library's own, which are skipped and why, and the\n * file name it is stored under. The fetch, the store and the key a copied\n * photo is found by again are `product-image-copy.server.ts`.\n *\n * - **Copied**: an https address on the default port, with no user name.\n * - **Kept as it is**: a media reference or a media CDN path, which is\n * already a file of an Aglyn library (an Aglyn export read back in).\n * - **Skipped, and said so in the dry run**: anything else. An `http://`\n * address, a name with no address (a Wix file lists bare media names, and\n * its host is not guessed), and every photo past the import's limit.\n *=========================================*/\n\n/** The folder of the site's media library imported product photos are filed in. */\nexport const PRODUCT_IMPORT_FOLDER_NAME = 'Imported products'\n\n/**\n * The largest photo copied: the media library's own limit for an uploaded\n * image (`IMAGE_MAX_BYTES` in the console's `media-upload-limits.ts`, 15 MB),\n * which the library checks again when it stores the bytes.\n */\nexport const PRODUCT_IMPORT_IMAGE_MAX_BYTES = 15 * 1024 * 1024\n\n/**\n * The most distinct photos one import copies. A 500-product store with four\n * photos each is 2,000; past it the dry run lists what is skipped. The\n * storage itself is held to the plan by the library, photo by photo.\n */\nexport const PRODUCT_IMPORT_IMAGES_MAX = 2_000\n\n/** One photo's own clock, as Bring my site gives one (`SITE_IMPORT_IMAGE_TIMEOUT_MS`). */\nexport const PRODUCT_IMPORT_IMAGE_TIMEOUT_MS = 8_000\n\n/** The time a photo is started with: its fetch, and the library storing it. */\nexport const PRODUCT_IMPORT_IMAGE_SLOT_MS = PRODUCT_IMPORT_IMAGE_TIMEOUT_MS + 4_000\n\n/** How many photos are fetched at once. */\nexport const PRODUCT_IMPORT_IMAGE_CONCURRENCY = 4\n\n/** The image types the library takes from a server. */\nexport const PRODUCT_IMPORT_IMAGE_TYPES = /^image\\/(?:jpeg|jpg|pjpeg|png|webp|gif)\\b/i\n\n/** Why a cell's photo is not copied. */\nexport type ProductImageSkip = 'notHttps' | 'notAddress' | 'mediaName' | 'overLimit'\n\n/** What one photo cell is. */\nexport type ProductImageCell =\n | { kind: 'copy'; url: string }\n | { kind: 'stored'; value: string }\n | { kind: 'skip'; value: string; skip: ProductImageSkip }\n\nconst TRACKING_PARAM = /^(?:utm_[a-z]+|fbclid|gclid|msclkid|_ga)$/i\nconst DOMAIN_PATH = /^(?:[\\w-]+\\.)+[a-z]{2,}(?:[/?#].*)?$/i\n\n/** One photo cell, read. `null` for a blank one. */\nexport function productImageCell(raw: unknown): ProductImageCell | null {\n const value = String(raw ?? '').trim()\n if (!value) return null\n if (isMediaRef(value) || isMediaCdnPath(value)) return { kind: 'stored', value }\n const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(value)\n if (!hasScheme && !DOMAIN_PATH.test(value)) return { kind: 'skip', value, skip: 'mediaName' }\n let url: URL\n try {\n url = new URL(hasScheme ? value : `https://${value}`)\n } catch {\n return { kind: 'skip', value, skip: 'notAddress' }\n }\n if (url.protocol === 'http:') return { kind: 'skip', value, skip: 'notHttps' }\n if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443')) {\n return { kind: 'skip', value, skip: 'notAddress' }\n }\n url.hash = ''\n for (const key of [...url.searchParams.keys()]) if (TRACKING_PARAM.test(key)) url.searchParams.delete(key)\n return { kind: 'copy', url: url.toString() }\n}\n\n/** The photos one cell names: several, split by semicolons, spaces or bars (a Wix or Squarespace cell). */\nexport function productImageList(raw: unknown): string[] {\n const list = Array.isArray(raw) ? raw.map((item) => String(item ?? '')) : String(raw ?? '').split(/[;|\\s]+/)\n const out: string[] = []\n for (const item of list) {\n const value = item.trim()\n if (value && !out.includes(value)) out.push(value)\n }\n return out\n}\n\n/** What the dry run says of a skipped photo. */\nexport function productImageSkipDetail(skip: ProductImageSkip): string {\n switch (skip) {\n case 'notHttps':\n return 'Not copied: the address starts with http://, not https://. Add this photo on the product.'\n case 'notAddress':\n return 'Not copied: this is not a web address a photo can be copied from. Add this photo on the product.'\n case 'mediaName':\n return 'Not copied: the file names the photo but not where it is online. Add this photo on the product.'\n case 'overLimit':\n return `Not copied: one import copies up to ${PRODUCT_IMPORT_IMAGES_MAX.toLocaleString('en-US')} photos. Import the rest in a second file, or add them on the product.`\n }\n}\n\nconst EXTENSION: Record<string, string> = {\n 'image/jpeg': 'jpg',\n 'image/png': 'png',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n}\n\n/** A file name for the library, from the photo's address and type. */\nexport function productImageFileName(url: string, contentType: string): string {\n let base = 'product-photo'\n try {\n const last = decodeURIComponent(new URL(url).pathname.split('/').filter(Boolean).pop() ?? '')\n base =\n last\n .replace(/\\.[a-z0-9]+$/i, '')\n .replace(/[^a-zA-Z0-9 _-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '') || base\n } catch {\n // An address that does not decode keeps the plain name.\n }\n return `${base.slice(0, 80)}.${EXTENSION[contentType] ?? 'jpg'}`\n}\n\n/** A content type as the library names it: `image/jpg` and `image/pjpeg` are JPEG. */\nexport function productImageContentType(header: string): string {\n const type = String(header ?? '').split(';')[0]?.trim().toLowerCase() ?? ''\n return type === 'image/jpg' || type === 'image/pjpeg' ? 'image/jpeg' : type\n}\n"],"names":["isMediaCdnPath","isMediaRef","PRODUCT_IMPORT_FOLDER_NAME","PRODUCT_IMPORT_IMAGE_MAX_BYTES","PRODUCT_IMPORT_IMAGES_MAX","PRODUCT_IMPORT_IMAGE_TIMEOUT_MS","PRODUCT_IMPORT_IMAGE_SLOT_MS","PRODUCT_IMPORT_IMAGE_CONCURRENCY","PRODUCT_IMPORT_IMAGE_TYPES","TRACKING_PARAM","DOMAIN_PATH","productImageCell","raw","value","String","trim","kind","hasScheme","test","skip","url","URL","protocol","username","password","port","hash","key","searchParams","keys","delete","toString","productImageList","list","Array","isArray","map","item","split","out","includes","push","productImageSkipDetail","toLocaleString","EXTENSION","productImageFileName","contentType","base","last","decodeURIComponent","pathname","filter","Boolean","pop","replace","slice","productImageContentType","header","type","toLowerCase"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,EAAEC,UAAU,QAAQ,mCAAkC;AAE7E;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,iFAAiF,GACjF,OAAO,MAAMC,6BAA6B,oBAAmB;AAE7D;;;;CAIC,GACD,OAAO,MAAMC,iCAAiC,KAAK,OAAO,KAAI;AAE9D;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,KAAK;AAE9C,wFAAwF,GACxF,OAAO,MAAMC,kCAAkC,KAAK;AAEpD,6EAA6E,GAC7E,OAAO,MAAMC,+BAA+BD,kCAAkC,KAAK;AAEnF,yCAAyC,GACzC,OAAO,MAAME,mCAAmC,EAAC;AAEjD,qDAAqD,GACrD,OAAO,MAAMC,6BAA6B,6CAA4C;AAWtF,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AAEpB,kDAAkD,GAClD,OAAO,SAASC,iBAAiBC,GAAY;IAC3C,MAAMC,QAAQC,OAAOF,cAAAA,MAAO,IAAIG,IAAI;IACpC,IAAI,CAACF,OAAO,OAAO;IACnB,IAAIZ,WAAWY,UAAUb,eAAea,QAAQ,OAAO;QAAEG,MAAM;QAAUH;IAAM;IAC/E,MAAMI,YAAY,uBAAuBC,IAAI,CAACL;IAC9C,IAAI,CAACI,aAAa,CAACP,YAAYQ,IAAI,CAACL,QAAQ,OAAO;QAAEG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