@chrischall/hellofresh-mcp 0.0.0-stage → 0.1.0

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/dist/client.js ADDED
@@ -0,0 +1,248 @@
1
+ // The HelloFresh web-API client: every endpoint in docs/HELLOFRESH-API.md,
2
+ // through ONE private `request()`. Each call is a plain Node fetch with the
3
+ // session's Bearer (the session owns the token lifecycle and the 401 replay).
4
+ //
5
+ // Failure mapping:
6
+ // - a Cloudflare (or other edge) page, as an error status or a 200 → EdgeBlockedError;
7
+ // - a 2xx body that is not JSON → UpstreamFormatError (via parseJsonBody);
8
+ // - a 4xx → McpToolError carrying the status (401/403: credential_rejected);
9
+ // - a WRITE that was sent and then timed out, dropped, broke off mid-body or
10
+ // was answered with a 5xx → WriteOutcomeUnknownError (the write may have
11
+ // happened: check before retrying);
12
+ // - a READ that timed out / could not connect → McpToolError kind timeout / transport.
13
+ // Every request is bounded by a timeout and honours the tool call's
14
+ // cancellation (`currentCallSignal()`, folded in by withAmbientCancellation).
15
+ import { EdgeBlockedError, McpToolError, UpstreamHttpError, WriteOutcomeUnknownError, apiPath, buildQueryString, currentCallSignal, describeTransportFailure, detectEdgeBlock, formatApiError, messageOf, parseJsonBody, truncateErrorMessage, withAmbientCancellation, } from '@chrischall/mcp-utils';
16
+ import { WEB_ORIGIN, signInHint } from './session.js';
17
+ export const API_BASE = `${WEB_ORIGIN}/gw`;
18
+ export const SERVICE = 'HelloFresh';
19
+ /** US market only. */
20
+ export const COUNTRY = 'US';
21
+ export const LOCALE = 'en-US';
22
+ /** Bound on each request, headers AND body. */
23
+ export const REQUEST_TIMEOUT_MS = 30_000;
24
+ export class HelloFreshClient {
25
+ session;
26
+ fetchImpl;
27
+ timeoutMs;
28
+ constructor(opts) {
29
+ this.session = opts.session;
30
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
31
+ this.timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
32
+ }
33
+ // ---- reads ---------------------------------------------------------------
34
+ listSubscriptions() {
35
+ return this.request('GET', '/api/customers/me/subscriptions');
36
+ }
37
+ getSubscription(subscriptionId) {
38
+ return this.request('GET', apiPath `/api/subscriptions/${subscriptionId}`, { route: '/api/subscriptions/{id}' });
39
+ }
40
+ /** Upcoming deliveries (about the next 7 weeks). */
41
+ listDeliveries() {
42
+ return this.request('GET', '/api/customers/me/deliveries');
43
+ }
44
+ getDelivery(subscriptionId, week) {
45
+ return this.request('GET', apiPath `/api/subscriptions/${subscriptionId}/delivery_dates/${week}`, {
46
+ route: `/api/subscriptions/{id}/delivery_dates/${week}`,
47
+ });
48
+ }
49
+ getProductOptions(subscriptionId) {
50
+ return this.request('GET', apiPath `/api/subscriptions/${subscriptionId}/product_options`, {
51
+ route: '/api/subscriptions/{id}/product_options',
52
+ });
53
+ }
54
+ listPlans() {
55
+ return this.request('GET', '/api/plans');
56
+ }
57
+ listMenuWeeks() {
58
+ return this.request('GET', '/menus-service/weeks');
59
+ }
60
+ /** The week's menu for a box size (without `servings` + `product-sku` the API answers 400). */
61
+ getDeliveryMenu(q) {
62
+ return this.request('GET', '/my-deliveries/menu', {
63
+ locale: false,
64
+ query: {
65
+ subscription: q.subscriptionId,
66
+ week: q.week,
67
+ locale: LOCALE,
68
+ servings: q.servings,
69
+ 'product-sku': q.sku,
70
+ customerPlanId: q.customerPlanId,
71
+ 'exclude-feedback': 'true',
72
+ },
73
+ });
74
+ }
75
+ // ---- writes (docs/HELLOFRESH-API.md "Writes" 1–5, 3 split into 3a size / 3b day) -------------------------
76
+ // Each write is built by an exported pure builder (below), so the confirm
77
+ // preview of a write and the request actually sent are the same object.
78
+ /** Write 1: replace the week's meal selection. */
79
+ selectMeals(r) {
80
+ return this.send(selectMealsRequest(r));
81
+ }
82
+ /** Write 2: skip (`PAUSED`) or unskip (`RUNNING`) one week. */
83
+ setDeliveryStatus(r) {
84
+ return this.send(deliveryStatusRequest(r));
85
+ }
86
+ /** Write 3a: one week's box size. Any 2xx is success (the body may be empty or not JSON). */
87
+ async setWeekSize(r) {
88
+ await this.send(weekSizeRequest(r), { discardBody: true });
89
+ }
90
+ /** Write 3b: one week's delivery slot (`deliveryOption`). Does NOT change the size: a new `sku` is ignored. */
91
+ changeOneOff(r) {
92
+ return this.send(oneOffRequest(r));
93
+ }
94
+ /** Write 4: permanent box size. 204, no body. */
95
+ async setPlanProduct(customerPlanId, productHandle) {
96
+ await this.send(planProductRequest(customerPlanId, productHandle));
97
+ }
98
+ /** Write 5: permanent delivery slot + frequency (send BOTH). 200, empty body. */
99
+ async changePlanDeliveryDetails(customerPlanId, details) {
100
+ await this.send(planDeliveryDetailsRequest(customerPlanId, details));
101
+ }
102
+ send(w, opts = {}) {
103
+ return this.request(w.method, w.path, { locale: false, query: w.query, body: w.body, route: w.route, ...opts });
104
+ }
105
+ // ---- the one request -------------------------------------------------------
106
+ async request(method, path, opts = {}) {
107
+ const query = { ...(opts.locale === false ? {} : { country: COUNTRY, locale: LOCALE }), ...opts.query };
108
+ const url = `${API_BASE}${path}${buildQueryString(query)}`;
109
+ const isWrite = method !== 'GET';
110
+ // One timer per request, armed until the body is read (each 401 replay gets a fresh one).
111
+ let timer = AbortSignal.timeout(this.timeoutMs);
112
+ const fail = (err) => this.transportError(err, method, url, isWrite, timer.aborted);
113
+ const res = await this.session.withAuth(async (token) => {
114
+ timer = AbortSignal.timeout(this.timeoutMs);
115
+ const headers = { authorization: `Bearer ${token}`, accept: 'application/json' };
116
+ if (opts.body !== undefined)
117
+ headers['content-type'] = 'application/json';
118
+ try {
119
+ return await this.fetchImpl(url, {
120
+ method,
121
+ headers,
122
+ ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),
123
+ signal: withAmbientCancellation(timer),
124
+ });
125
+ }
126
+ catch (err) {
127
+ throw fail(err);
128
+ }
129
+ });
130
+ let text;
131
+ try {
132
+ text = await res.text();
133
+ }
134
+ catch (err) {
135
+ throw fail(err);
136
+ }
137
+ const where = { service: SERVICE, method, path: opts.route ?? path };
138
+ if (!res.ok) {
139
+ const edge = detectEdgeBlock({ status: res.status, headers: res.headers, body: text });
140
+ if (edge)
141
+ throw new EdgeBlockedError(res.status, edge.vendor, where);
142
+ const message = formatApiError(res.status, method, where.path, this.session.redact(text), { service: SERVICE, max: 300 });
143
+ if (isWrite && res.status >= 500) {
144
+ throw new WriteOutcomeUnknownError(SERVICE, method, { cause: new UpstreamHttpError(res.status, message) });
145
+ }
146
+ const rejected = res.status === 401 || res.status === 403;
147
+ throw new McpToolError(message, {
148
+ status: res.status,
149
+ kind: rejected ? 'credential_rejected' : 'http',
150
+ ...(res.status === 401 ? { hint: signInHint() } : {}),
151
+ });
152
+ }
153
+ if (opts.discardBody) {
154
+ const edge = detectEdgeBlock({ status: res.status, headers: res.headers, body: text });
155
+ if (edge)
156
+ throw new EdgeBlockedError(res.status, edge.vendor, where);
157
+ return undefined;
158
+ }
159
+ return parseJsonBody(text, { ...where, status: res.status, headers: res.headers });
160
+ }
161
+ transportError(err, method, url, isWrite, timedOut) {
162
+ if (isWrite) {
163
+ return new WriteOutcomeUnknownError(SERVICE, method, {
164
+ cause: err,
165
+ ...(timedOut ? { timeoutMs: this.timeoutMs } : {}),
166
+ });
167
+ }
168
+ if (timedOut) {
169
+ return new McpToolError(`${SERVICE} did not answer ${method} in time (${this.timeoutMs} ms).`, { kind: 'timeout', cause: err });
170
+ }
171
+ // The caller cancelled: surface its own abort reason, unchanged.
172
+ if (currentCallSignal()?.aborted)
173
+ return err;
174
+ return (describeTransportFailure(err, url, SERVICE) ??
175
+ new McpToolError(`Could not reach ${SERVICE}: ${truncateErrorMessage(messageOf(err), 200)}`, { kind: 'transport', cause: err }));
176
+ }
177
+ }
178
+ const LOCALE_QUERY = { country: COUNTRY, locale: LOCALE };
179
+ export function selectMealsRequest(r) {
180
+ return {
181
+ method: 'PUT',
182
+ path: apiPath `/v1/carts/${r.week}`,
183
+ route: `/v1/carts/${r.week}`,
184
+ query: {
185
+ subscription: r.subscriptionId,
186
+ customer: r.customerId,
187
+ week: r.week,
188
+ 'product-sku': r.sku,
189
+ preference: r.preference,
190
+ update_quantity: 'false',
191
+ ignore_addons: 'false',
192
+ },
193
+ body: { extras: [], meals: r.meals },
194
+ };
195
+ }
196
+ export function deliveryStatusRequest(r) {
197
+ return {
198
+ method: 'PATCH',
199
+ path: apiPath `/api/subscriptions/${r.subscriptionId}/delivery_dates/${r.week}`,
200
+ route: `/api/subscriptions/{id}/delivery_dates/${r.week}`,
201
+ query: { ...LOCALE_QUERY },
202
+ body: {
203
+ delivery: {
204
+ id: r.week,
205
+ subscriptionId: r.subscriptionId,
206
+ deliveryDate: r.deliveryDate,
207
+ cutoffDate: r.cutoffDate,
208
+ status: r.status,
209
+ },
210
+ },
211
+ };
212
+ }
213
+ export function weekSizeRequest(r) {
214
+ return {
215
+ method: 'PUT',
216
+ path: apiPath `/carts/${r.week}/size`,
217
+ route: `/carts/${r.week}/size`,
218
+ query: { ...LOCALE_QUERY, subscription: r.subscriptionId },
219
+ body: { productHandle: r.sku, hfMarketCode: COUNTRY },
220
+ };
221
+ }
222
+ export function oneOffRequest(r) {
223
+ return {
224
+ method: 'POST',
225
+ path: apiPath `/api/subscriptions/${r.subscriptionId}/oneoff`,
226
+ route: '/api/subscriptions/{id}/oneoff',
227
+ query: { ...LOCALE_QUERY },
228
+ body: { id: r.subscriptionId, week: r.week, sku: r.sku, delivery_option: r.deliveryOption, source: 'one-off' },
229
+ };
230
+ }
231
+ export function planProductRequest(customerPlanId, productHandle) {
232
+ return {
233
+ method: 'PATCH',
234
+ path: apiPath `/api/plans/${customerPlanId}`,
235
+ route: '/api/plans/{planId}',
236
+ query: { ...LOCALE_QUERY },
237
+ body: { productHandle },
238
+ };
239
+ }
240
+ export function planDeliveryDetailsRequest(customerPlanId, details) {
241
+ return {
242
+ method: 'POST',
243
+ path: apiPath `/api/plans/${customerPlanId}/changePlanDeliveryDetails`,
244
+ route: '/api/plans/{planId}/changePlanDeliveryDetails',
245
+ query: { country: COUNTRY },
246
+ body: { deliveryOption: details.deliveryOption, deliveryInterval: details.deliveryInterval },
247
+ };
248
+ }
package/dist/config.js ADDED
@@ -0,0 +1,8 @@
1
+ // Environment config. Read lazily so the server always boots.
2
+ import { readPortEnv } from '@chrischall/mcp-utils';
3
+ /** The fleet-wide ContextMint Bridge concentrator port — never change it. */
4
+ export const DEFAULT_WS_PORT = 37_149;
5
+ /** `HELLOFRESH_WS_PORT`, defaulting to the shared concentrator port. */
6
+ export function readWsPort(env = process.env) {
7
+ return readPortEnv('HELLOFRESH_WS_PORT', DEFAULT_WS_PORT, { env });
8
+ }
package/dist/index.js ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { runMcp } from '@chrischall/mcp-utils';
3
+ import { HelloFreshClient } from './client.js';
4
+ import { readWsPort } from './config.js';
5
+ import { TOOL_REGISTRARS } from './tools/index.js';
6
+ import { createProfileStore } from './profiles.js';
7
+ import { HelloFreshSession } from './session.js';
8
+ import { createHelloFreshBridge } from './transport.js';
9
+ import { VERSION } from './version.js';
10
+ // The bridge only bootstraps the session: it reads (and refreshes) the
11
+ // apiV2Auth cookie through the signed-in www.hellofresh.com tab. Every API
12
+ // call is a plain Node fetch with a Bearer token.
13
+ const bridge = createHelloFreshBridge({ port: readWsPort(), version: VERSION });
14
+ // start() loads the fetchproxy identity (no port bind — that is lazy). A
15
+ // failure is NOT fatal: the next use retries the start (and throws its error
16
+ // if it still fails), so the server still boots and answers tools/list.
17
+ await bridge.start().catch(() => { });
18
+ // Built ONCE, outside the registrars (runMcp builds a server per connection).
19
+ // Nothing here resolves a credential at boot (deferred-config-error pattern).
20
+ const fetchImpl = (input, init) => fetch(input, init);
21
+ const session = new HelloFreshSession({ bridge, fetchImpl });
22
+ const deps = {
23
+ bridge,
24
+ session,
25
+ fetchImpl,
26
+ client: new HelloFreshClient({ session, fetchImpl }),
27
+ // Planner profiles load on first use: a malformed config is a tool error, never a boot failure.
28
+ profiles: createProfileStore(),
29
+ };
30
+ await runMcp({
31
+ name: 'hellofresh-mcp',
32
+ version: VERSION,
33
+ deps,
34
+ tools: [...TOOL_REGISTRARS],
35
+ shutdown: { onSignal: () => bridge.close() },
36
+ banner: '[hellofresh-mcp] Unofficial HelloFresh (US) MCP. HelloFresh has no public API for this; it uses the web app\'s ' +
37
+ 'internal one and may break or violate their ToS. Developed and maintained by AI (Claude). Use at your own discretion.',
38
+ });
@@ -0,0 +1,235 @@
1
+ // Projections of the raw HelloFresh shapes into what tools return, plus the
2
+ // box-total estimate. Subscription and delivery records are projected to an
3
+ // ALLOWLIST: the raw records carry the customer's name, email, shipping and
4
+ // billing addresses and payment token, none of which may ever be returned.
5
+ // ---- small parsers ----------------------------------------------------------
6
+ /** `US-CBU-{meals}-{people}-0` → `{meals, people}`. */
7
+ export function parseSku(sku) {
8
+ const m = /^[A-Z]+-[A-Z]+-(\d+)-(\d+)-\d+$/.exec(sku ?? '');
9
+ return m ? { meals: Number(m[1]), people: Number(m[2]) } : undefined;
10
+ }
11
+ /** ISO-8601 `PT1H5M` → 65 (minutes, seconds rounded up). */
12
+ export function parseDurationMinutes(iso) {
13
+ const m = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/.exec(iso ?? '');
14
+ if (!m || (m[1] === undefined && m[2] === undefined && m[3] === undefined))
15
+ return undefined;
16
+ return Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0) + Math.ceil(Number(m[3] ?? 0) / 60);
17
+ }
18
+ const SHRIMP = /\b(shrimps?|prawns?)\b/i;
19
+ const FISH = /\b(salmon|cod|tilapia|trout|tuna|halibut|haddock|pollock|barramundi|catfish|mahi(?:[- ]mahi)?|branzino|sea bass|swordfish|fish)\b/i;
20
+ /** `shrimp` / `fish` from text, or undefined when it names neither (scallops, lobster, crab → the caller's `other`). */
21
+ export function seafoodKindOf(text) {
22
+ if (SHRIMP.test(text))
23
+ return 'shrimp';
24
+ if (FISH.test(text))
25
+ return 'fish';
26
+ return undefined;
27
+ }
28
+ function toNumber(value) {
29
+ const n = typeof value === 'string' ? Number(value) : value;
30
+ return typeof n === 'number' && Number.isFinite(n) ? n : undefined;
31
+ }
32
+ export function projectSubscription(s) {
33
+ const size = parseSku(s.product?.sku);
34
+ return {
35
+ id: s.id,
36
+ sku: s.product?.sku,
37
+ meals: size?.meals,
38
+ people: size?.people,
39
+ unitPriceCents: s.product?.unitPrice,
40
+ preset: s.preset,
41
+ deliveryWeekday: s.deliveryWeekday,
42
+ deliveryInterval: s.deliveryInterval,
43
+ deliveryOption: s.deliveryOption?.handle ?? s.deliveryTime,
44
+ deliveryName: s.deliveryOption?.deliveryName,
45
+ nextDeliveryWeek: s.nextDeliveryWeek,
46
+ nextCutoffDate: s.nextCutoffDate,
47
+ nextModifiableDeliveryWeek: s.nextModifiableDeliveryWeek,
48
+ firstDeliveryWeek: s.firstDeliveryWeek,
49
+ firstBoxDelivered: s.firstBoxDelivered,
50
+ couponCode: s.couponCode,
51
+ isActive: s.isActive,
52
+ pausedAt: s.pausedAt ?? null,
53
+ canceledAt: s.canceledAt ?? null,
54
+ voucher: s.voucherInfo ? { code: s.voucherInfo.code, active: s.voucherInfo.is_active === true } : undefined,
55
+ };
56
+ }
57
+ const STATUS = {
58
+ RUNNING: 'running',
59
+ PAUSED: 'skipped',
60
+ DELIVERED: 'delivered',
61
+ DONATED: 'donated',
62
+ };
63
+ export function projectDelivery(d) {
64
+ const fromSku = parseSku(d.product?.handle);
65
+ return {
66
+ week: d.id,
67
+ deliveryDate: d.deliveryDate,
68
+ cutoffDate: d.cutoffDate,
69
+ status: d.status ? (STATUS[d.status] ?? d.status.toLowerCase()) : 'unknown',
70
+ subStatus: d.subStatus,
71
+ actionable: d.actionable,
72
+ meals: toNumber(d.product?.specs?.meals) ?? fromSku?.meals,
73
+ servings: toNumber(d.product?.specs?.size) ?? fromSku?.people,
74
+ sku: d.product?.handle,
75
+ productName: d.product?.productName,
76
+ priceCents: d.product?.price,
77
+ feeCents: d.product?.specialFee,
78
+ shippingCents: d.product?.shippingPrice,
79
+ deliveryOption: d.deliveryOption?.handle,
80
+ deliveryName: d.deliveryOption?.deliveryName,
81
+ deliveryDay: d.deliveryOption?.deliveryDay,
82
+ allowedActions: Object.entries(d.allowedActions ?? {})
83
+ .filter(([, allowed]) => allowed === true)
84
+ .map(([name]) => name),
85
+ oneOffDaySlots: (d.availableOneOffOptions ?? []).map((o) => ({ handle: o.handle, deliveryDate: o.deliveryDate })),
86
+ };
87
+ }
88
+ const QUICK_TAGS = new Set(['quick', 'easy-prep']);
89
+ const QUICK_MINUTES = 30;
90
+ function isSeafoodCategory(category) {
91
+ return category === 'Seafood';
92
+ }
93
+ function kindFor(isSeafood, ...texts) {
94
+ if (!isSeafood)
95
+ return null;
96
+ for (const text of texts) {
97
+ const kind = seafoodKindOf(text ?? '');
98
+ if (kind)
99
+ return kind;
100
+ }
101
+ return 'other';
102
+ }
103
+ function premium(meal) {
104
+ return { perServing: meal?.charge?.unitAmount ?? 0, box: meal?.charge?.totalAmount ?? 0 };
105
+ }
106
+ function minutesOf(recipe) {
107
+ const times = [parseDurationMinutes(recipe.prepTime), parseDurationMinutes(recipe.totalTime)].filter((n) => n !== undefined);
108
+ return times.length > 0 ? Math.max(...times) : undefined;
109
+ }
110
+ function projectVariant(variation, meal) {
111
+ const recipe = meal?.recipe ?? {};
112
+ const category = variation.category ?? recipe.category ?? null;
113
+ const isSeafood = isSeafoodCategory(category);
114
+ const charge = premium(meal);
115
+ return {
116
+ index: variation.index,
117
+ title: variation.title,
118
+ name: recipe.name,
119
+ category,
120
+ isSeafood,
121
+ seafoodKind: kindFor(isSeafood, variation.title, `${recipe.name ?? ''} ${recipe.headline ?? ''}`),
122
+ premiumPerServingCents: charge.perServing,
123
+ premiumBoxCents: charge.box,
124
+ selectedQuantity: meal?.selection?.quantity ?? 0,
125
+ };
126
+ }
127
+ function projectMeal(meal, variants) {
128
+ const recipe = meal.recipe ?? {};
129
+ const category = recipe.category ?? null;
130
+ const isSeafood = isSeafoodCategory(category);
131
+ const tags = recipe.tags ?? [];
132
+ const totalMinutes = minutesOf(recipe);
133
+ const charge = premium(meal);
134
+ return {
135
+ index: meal.index,
136
+ name: recipe.name,
137
+ headline: recipe.headline,
138
+ category,
139
+ isSeafood,
140
+ seafoodKind: kindFor(isSeafood, `${recipe.name ?? ''} ${recipe.headline ?? ''}`),
141
+ kidFriendly: tags.some((t) => t.type === 'family-friendly'),
142
+ quick: tags.some((t) => QUICK_TAGS.has(t.type ?? '')) || (totalMinutes !== undefined && totalMinutes <= QUICK_MINUTES),
143
+ totalMinutes,
144
+ premiumPerServingCents: charge.perServing,
145
+ premiumBoxCents: charge.box,
146
+ selectedQuantity: meal.selection?.quantity ?? 0,
147
+ tags: [...new Set(tags.map((t) => t.name).filter((n) => typeof n === 'string' && n !== ''))],
148
+ cuisine: recipe.cuisines?.[0]?.name,
149
+ label: recipe.label?.text,
150
+ url: recipe.websiteURL,
151
+ variants,
152
+ };
153
+ }
154
+ /**
155
+ * Split the week's menu into base courses (with their protein-swap variants
156
+ * nested) and the current selection. A meal whose index appears in another
157
+ * course's `modularity[].variations` is a variant, not a base course.
158
+ */
159
+ export function projectMenu(menu) {
160
+ const meals = menu.meals ?? [];
161
+ const byIndex = new Map(meals.map((m) => [m.index, m]));
162
+ const variationsOf = new Map();
163
+ const baseOf = new Map();
164
+ for (const mod of menu.modularity ?? []) {
165
+ if (mod.defaultCourseIndex === undefined)
166
+ continue;
167
+ const variations = (mod.variations ?? []).filter((v) => v.index !== mod.defaultCourseIndex);
168
+ variationsOf.set(mod.defaultCourseIndex, variations);
169
+ for (const v of variations)
170
+ baseOf.set(v.index, mod.defaultCourseIndex);
171
+ }
172
+ const projected = meals
173
+ .filter((m) => !baseOf.has(m.index))
174
+ .map((m) => projectMeal(m, (variationsOf.get(m.index) ?? []).map((v) => projectVariant(v, byIndex.get(v.index)))));
175
+ const selected = meals
176
+ .filter((m) => (m.selection?.quantity ?? 0) > 0)
177
+ .map((m) => ({
178
+ index: m.index,
179
+ quantity: m.selection.quantity,
180
+ name: m.recipe?.name,
181
+ premiumBoxCents: premium(m).box,
182
+ ...(baseOf.has(m.index) ? { baseIndex: baseOf.get(m.index) } : {}),
183
+ }));
184
+ return { week: menu.week, mealsReady: menu.mealsReady, meals: projected, selected };
185
+ }
186
+ /**
187
+ * Estimate a box total (docs/HELLOFRESH-API.md "Pricing"): product + special
188
+ * fee + shipping + Σ premium upcharges, minus the voucher's percentage for this
189
+ * box number (`applicable_to: 'products'` = product price only, `'both'` =
190
+ * product + shipping + fees). `boxNumber` is 1-based.
191
+ */
192
+ export function estimateBoxTotal(delivery, selection, voucherInfo, boxNumber) {
193
+ const productCents = delivery.priceCents ?? 0;
194
+ const feeCents = delivery.feeCents ?? 0;
195
+ const shippingCents = delivery.shippingCents ?? 0;
196
+ const premiumCents = selection.reduce((sum, s) => sum + (s.premiumBoxCents ?? 0) * (s.quantity ?? 1), 0);
197
+ const subtotalCents = productCents + feeCents + shippingCents + premiumCents;
198
+ const base = {
199
+ estimate: true,
200
+ productCents,
201
+ feeCents,
202
+ shippingCents,
203
+ premiumCents,
204
+ subtotalCents,
205
+ discountCents: 0,
206
+ totalCents: subtotalCents,
207
+ };
208
+ const undiscounted = (warning) => ({ ...base, warning });
209
+ if (!voucherInfo)
210
+ return undiscounted('No voucher on the subscription: the estimate is undiscounted.');
211
+ const name = voucherInfo.code ?? 'the voucher';
212
+ if (voucherInfo.is_active !== true)
213
+ return undiscounted(`Voucher ${name} is not active: the estimate is undiscounted.`);
214
+ const type = voucherInfo.discount_type ?? 'percent';
215
+ if (type !== 'percent')
216
+ return undiscounted(`Voucher ${name} is a "${type}" discount, which is not estimated: the total is undiscounted.`);
217
+ const settings = voucherInfo.discount_settings ?? {};
218
+ const boxCount = settings.box_count;
219
+ if (boxCount !== undefined && boxNumber > boxCount) {
220
+ return undiscounted(`Voucher ${name} covers boxes 1–${boxCount}; this is box ${boxNumber}, so no discount applies.`);
221
+ }
222
+ const rule = settings.discount_rule?.box_rule?.[String(boxNumber)];
223
+ if (!rule)
224
+ return undiscounted(`Voucher ${name} has no discount for box ${boxNumber}: the estimate is undiscounted.`);
225
+ const appliesTo = rule.applicable_to ?? 'products';
226
+ const percent = (rule.discount_value ?? 0) / 100;
227
+ const discountable = appliesTo === 'both' ? productCents + feeCents + shippingCents : productCents;
228
+ const discountCents = Math.round((discountable * percent) / 100);
229
+ return {
230
+ ...base,
231
+ discountCents,
232
+ totalCents: subtotalCents - discountCents,
233
+ voucher: { code: voucherInfo.code, boxNumber, percent, appliesTo },
234
+ };
235
+ }