@chrischall/hellofresh-mcp 0.0.0-stage → 0.0.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.
@@ -0,0 +1,303 @@
1
+ // The read tools: subscription, deliveries (the canonical whats-on read),
2
+ // one delivery, a week's menu, box sizes and recent picks. Every record goes
3
+ // out through the normalize.ts allowlist projections — the raw subscription
4
+ // and delivery records carry the customer's name, email, addresses and
5
+ // payment token, none of which is ever returned.
6
+ import { z } from 'zod';
7
+ import { minifiedResult, resolveView, todayIso, toolAnnotations } from '@chrischall/mcp-utils';
8
+ import { parseSku, projectDelivery, projectSubscription, } from '../normalize.js';
9
+ import { isoWeekOf, shiftWeek } from '../weeks.js';
10
+ import { LOOKUP, foodMeta } from './hints.js';
11
+ import { HF_VIEWS, attempt, boxNumbering, boxNumbers, briefLine, byWeek, compactEstimate, compactSelection, dateOf, estimateFor, hfView, loadAccount, nextBoxNumberParam, readMenu, readPicks, weekParam, } from './shared.js';
12
+ const readOnly = (title) => toolAnnotations({ title, readOnly: true, idempotent: true, openWorld: true });
13
+ // ---- projections for the compact rung --------------------------------------------
14
+ function fullVoucher(v) {
15
+ if (!v)
16
+ return undefined;
17
+ const rules = v.discount_settings?.discount_rule?.box_rule ?? {};
18
+ return {
19
+ code: v.code,
20
+ active: v.is_active === true,
21
+ discountType: v.discount_type,
22
+ boxCount: v.discount_settings?.box_count,
23
+ boxRules: Object.entries(rules)
24
+ .map(([box, rule]) => ({ box: Number(box), percent: (rule?.discount_value ?? 0) / 100, appliesTo: rule?.applicable_to }))
25
+ .sort((a, b) => a.box - b.box),
26
+ };
27
+ }
28
+ function compactDelivery(d) {
29
+ return {
30
+ week: d.week,
31
+ deliveryDate: dateOf(d.deliveryDate),
32
+ cutoffDate: d.cutoffDate,
33
+ status: d.status,
34
+ meals: d.meals,
35
+ servings: d.servings,
36
+ sku: d.sku,
37
+ deliveryName: d.deliveryName,
38
+ };
39
+ }
40
+ const premiumFields = (perServing, box) => perServing > 0 || box > 0 ? { premiumPerServingCents: perServing, premiumBoxCents: box } : {};
41
+ function compactVariant(v) {
42
+ return {
43
+ index: v.index,
44
+ title: v.title,
45
+ ...(v.seafoodKind ? { seafoodKind: v.seafoodKind } : {}),
46
+ ...premiumFields(v.premiumPerServingCents, v.premiumBoxCents),
47
+ ...(v.selectedQuantity > 0 ? { selected: v.selectedQuantity } : {}),
48
+ };
49
+ }
50
+ function compactMeal(m) {
51
+ return {
52
+ index: m.index,
53
+ name: m.name,
54
+ category: m.category,
55
+ ...(m.seafoodKind ? { seafoodKind: m.seafoodKind } : {}),
56
+ kidFriendly: m.kidFriendly,
57
+ quick: m.quick,
58
+ totalMinutes: m.totalMinutes,
59
+ ...premiumFields(m.premiumPerServingCents, m.premiumBoxCents),
60
+ ...(m.selectedQuantity > 0 ? { selected: m.selectedQuantity } : {}),
61
+ ...(m.variants.length > 0 ? { variants: m.variants.map(compactVariant) } : {}),
62
+ };
63
+ }
64
+ /**
65
+ * Kid-friendliness and time belong to the recipe, so they gate the course and
66
+ * its swaps alike. Seafood, premium and selection are per dish: a course that
67
+ * fails them is still listed when one of its swaps passes (with only the
68
+ * passing swaps, and `onlyVariantsMatch`).
69
+ */
70
+ function applyFilters(meals, f) {
71
+ const dish = (d) => (!f.seafood_only || d.isSeafood) &&
72
+ (f.max_premium_per_serving === undefined || d.premiumPerServingCents <= f.max_premium_per_serving) &&
73
+ (!f.selected_only || d.selectedQuantity > 0);
74
+ return meals.flatMap((m) => {
75
+ const recipeOk = (!f.kid_friendly || m.kidFriendly) &&
76
+ (f.max_minutes === undefined || (m.totalMinutes !== undefined && m.totalMinutes <= f.max_minutes));
77
+ if (!recipeOk)
78
+ return [];
79
+ const variants = m.variants.filter(dish);
80
+ if (dish(m))
81
+ return [{ ...m, variants }];
82
+ return variants.length > 0 ? [{ ...m, variants, onlyVariantsMatch: true }] : [];
83
+ });
84
+ }
85
+ // ---- registration -------------------------------------------------------------------
86
+ export function registerReadTools(server, deps) {
87
+ const { client } = deps;
88
+ const now = deps.now ?? Date.now;
89
+ server.registerTool('hf_get_subscription', {
90
+ description: 'Read the HelloFresh meal-kit subscription: the plan’s box size (meals × people, SKU), price per box, ' +
91
+ 'meal-preference preset, delivery weekday/slot and frequency, the next delivery week and its cutoff, ' +
92
+ 'pause/cancel state and the voucher (discount code). Never returns name, email, address or payment details.',
93
+ annotations: readOnly('HelloFresh: get subscription'),
94
+ _meta: foodMeta('lookup', { aliases: ['hellofresh plan', 'meal kit subscription'] }),
95
+ inputSchema: z.object({
96
+ view: hfView('compact keeps the plan, schedule and voucher code; full adds the plan id and the voucher’s per-box discount rules.'),
97
+ }),
98
+ }, async ({ view }) => {
99
+ const { subscription } = await loadAccount(client);
100
+ const projected = projectSubscription(subscription);
101
+ if (resolveView(view, HF_VIEWS) === 'compact')
102
+ return minifiedResult({ subscription: projected });
103
+ return minifiedResult({
104
+ subscription: { ...projected, customerPlanId: subscription.customerPlanId, voucher: fullVoucher(subscription.voucherInfo) },
105
+ });
106
+ });
107
+ server.registerTool('hf_list_deliveries', {
108
+ description: 'List upcoming HelloFresh deliveries (about the next 7 weeks): each week’s delivery date, meal-pick cutoff, ' +
109
+ 'status (running, skipped, delivered), box size and an estimated box total with the voucher discount. ' +
110
+ 'Answers "what HelloFresh boxes are coming?" — view "brief" gives one line per week.',
111
+ annotations: readOnly('HelloFresh: list deliveries'),
112
+ _meta: foodMeta('whats-on', {
113
+ canonical: true,
114
+ aliases: ['hellofresh', 'meal kit', 'meal delivery', 'dinner box', 'hellofresh box'],
115
+ }),
116
+ inputSchema: z.object({
117
+ view: z
118
+ .enum(['brief', 'compact', 'full'])
119
+ .optional()
120
+ .describe('"compact" (default): week, dates, status, box size and a short estimate. "brief": one line per week, ' +
121
+ '`2026-W49 — 2026-11-30 — running, 2×6, cutoff 11-25`. "full": every allowlisted delivery field ' +
122
+ '(allowed actions, alternative delivery-day slots) and the whole estimate.'),
123
+ next_box_number: nextBoxNumberParam,
124
+ }),
125
+ }, async ({ view, next_box_number }) => {
126
+ const account = await loadAccount(client);
127
+ const deliveries = ((await client.listDeliveries()).items ?? []).map(projectDelivery).sort(byWeek);
128
+ if (view === 'brief') {
129
+ const lines = deliveries.map(briefLine);
130
+ return { content: [{ type: 'text', text: (lines.length > 0 ? lines : ['-- none']).join('\n') }] };
131
+ }
132
+ const numbering = boxNumbering(account.subscription, next_box_number);
133
+ const numbers = boxNumbers(deliveries, numbering.next);
134
+ const full = view === 'full';
135
+ return minifiedResult({
136
+ deliveries: deliveries.map((d) => {
137
+ const boxNumber = numbers.get(d.week);
138
+ const estimate = boxNumber !== undefined ? estimateFor(d, [], account, boxNumber) : undefined;
139
+ const base = full ? d : compactDelivery(d);
140
+ if (!estimate)
141
+ return base;
142
+ return { ...base, estimate: full ? estimate : compactEstimate(estimate) };
143
+ }),
144
+ estimateNote: 'Estimates (running weeks only) are product + fees + shipping minus the voucher, WITHOUT premium meal ' +
145
+ `upcharges (hf_get_delivery adds those). ${numbering.note}`,
146
+ });
147
+ });
148
+ server.registerTool('hf_get_delivery', {
149
+ description: 'Read one HelloFresh delivery week: delivery date and slot, meal-pick cutoff, status, box size, the meals ' +
150
+ 'currently picked (with any premium upcharge), allowed actions, alternative delivery days, and an estimated ' +
151
+ 'box total including premium upcharges and the voucher discount.',
152
+ annotations: readOnly('HelloFresh: get delivery'),
153
+ _meta: LOOKUP,
154
+ inputSchema: z.object({
155
+ week: weekParam,
156
+ box_number: z
157
+ .number()
158
+ .int()
159
+ .min(1)
160
+ .max(1000)
161
+ .optional()
162
+ .describe('This box’s number, counting every box ever delivered — overrides the number derived from next_box_number.'),
163
+ next_box_number: nextBoxNumberParam,
164
+ view: hfView('compact keeps the essentials; full adds every allowlisted field (prices, slot handle, sub-status) and the whole estimate.'),
165
+ }),
166
+ }, async ({ week, box_number, next_box_number, view }) => {
167
+ const account = await loadAccount(client);
168
+ const [rawDelivery, upcoming] = await Promise.all([
169
+ client.getDelivery(account.subscriptionId, week),
170
+ client.listDeliveries(),
171
+ ]);
172
+ const delivery = projectDelivery(rawDelivery);
173
+ const running = delivery.status === 'running';
174
+ const menu = delivery.status === 'skipped' ? undefined : await attempt(() => readMenu(client, account, delivery, week));
175
+ const selection = menu?.ok ? menu.value.selected.map(compactSelection) : undefined;
176
+ let estimate;
177
+ let boxNumberNote;
178
+ if (running) {
179
+ const numbering = boxNumbering(account.subscription, next_box_number);
180
+ if (box_number === undefined)
181
+ boxNumberNote = numbering.note;
182
+ const boxNumber = box_number ?? boxNumbers((upcoming.items ?? []).map(projectDelivery), numbering.next).get(week);
183
+ estimate = estimateFor(delivery, selection ?? [], account, boxNumber);
184
+ if (!selection) {
185
+ const note = 'The menu could not be read, so premium upcharges are not included.';
186
+ estimate.warning = estimate.warning ? `${estimate.warning} ${note}` : note;
187
+ }
188
+ }
189
+ const full = resolveView(view, HF_VIEWS) === 'full';
190
+ return minifiedResult({
191
+ ...(full
192
+ ? delivery
193
+ : {
194
+ ...compactDelivery(delivery),
195
+ week,
196
+ productName: delivery.productName,
197
+ deliveryDay: delivery.deliveryDay,
198
+ allowedActions: delivery.allowedActions,
199
+ oneOffDaySlots: delivery.oneOffDaySlots,
200
+ }),
201
+ ...(selection ? { selection } : {}),
202
+ ...(menu && !menu.ok ? { selectionError: menu.reason } : {}),
203
+ ...(estimate ? { estimate: full ? estimate : compactEstimate(estimate) } : {}),
204
+ ...(boxNumberNote ? { boxNumberNote } : {}),
205
+ });
206
+ });
207
+ server.registerTool('hf_get_menu', {
208
+ description: 'Read the HelloFresh menu for a delivery week at that week’s box size: every recipe with its index (used to ' +
209
+ 'pick meals), category, seafood kind (shrimp/fish/other), kid-friendly, quick, total minutes, premium ' +
210
+ 'upcharge per serving and per box, protein swaps (variants) and what is currently picked. Filters: ' +
211
+ 'seafood_only, kid_friendly, max_minutes, max_premium_per_serving, selected_only.',
212
+ annotations: readOnly('HelloFresh: get menu'),
213
+ _meta: foodMeta('lookup', { aliases: ['hellofresh menu', 'hellofresh recipes', 'meal options'] }),
214
+ inputSchema: z.object({
215
+ week: weekParam,
216
+ seafood_only: z.boolean().optional().describe('Only seafood dishes (a course is kept for a seafood protein swap).'),
217
+ kid_friendly: z.boolean().optional().describe('Only recipes HelloFresh tags kid friendly.'),
218
+ max_minutes: z.number().int().positive().optional().describe('Only recipes that take at most this many minutes in total.'),
219
+ max_premium_per_serving: z
220
+ .number()
221
+ .int()
222
+ .min(0)
223
+ .optional()
224
+ .describe('Highest premium upcharge per serving, in US cents (0 = no premium meals; 699 = up to $6.99).'),
225
+ selected_only: z.boolean().optional().describe('Only the meals currently picked for the week.'),
226
+ view: hfView('compact keeps index, name, category, seafood kind, kid-friendly, quick, minutes, premiums (only when non-zero), ' +
227
+ 'selection and swaps; full adds headline, tags, cuisine, label and recipe URL.'),
228
+ }),
229
+ }, async ({ week, view, ...filters }) => {
230
+ const account = await loadAccount(client);
231
+ const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
232
+ const menu = await readMenu(client, account, delivery, week);
233
+ const meals = applyFilters(menu.meals, filters);
234
+ const active = Object.fromEntries(Object.entries(filters).filter(([, v]) => v !== undefined));
235
+ const full = resolveView(view, HF_VIEWS) === 'full';
236
+ return minifiedResult({
237
+ week,
238
+ box: { sku: delivery.sku, meals: delivery.meals, servings: delivery.servings },
239
+ cutoffDate: delivery.cutoffDate,
240
+ status: delivery.status,
241
+ mealsReady: menu.mealsReady,
242
+ selected: menu.selected.map(compactSelection),
243
+ ...(Object.keys(active).length > 0 ? { filters: active } : {}),
244
+ total: menu.meals.length,
245
+ shown: meals.length,
246
+ meals: meals.map((m) => full ? m : { ...compactMeal(m), ...(m.onlyVariantsMatch ? { onlyVariantsMatch: true } : {}) }),
247
+ });
248
+ });
249
+ server.registerTool('hf_list_box_sizes', {
250
+ description: 'List the HelloFresh box sizes this subscription can switch to — meals per week × people (servings), with ' +
251
+ 'the SKU that names it — and mark the current plan size.',
252
+ annotations: readOnly('HelloFresh: list box sizes'),
253
+ _meta: foodMeta('lookup', { aliases: ['box size', 'servings', 'how many meals'] }),
254
+ inputSchema: z.object({
255
+ view: hfView('compact is one flat list sorted by meals then people; full keeps HelloFresh’s product groups.'),
256
+ }),
257
+ }, async ({ view }) => {
258
+ const account = await loadAccount(client);
259
+ const current = account.subscription.product?.sku;
260
+ const options = await client.getProductOptions(account.subscriptionId);
261
+ const groups = (options.items ?? []).map((g) => ({
262
+ handle: g.handle,
263
+ name: g.name,
264
+ products: (g.products ?? []).flatMap((p) => {
265
+ const size = parseSku(p.handle);
266
+ if (!p.handle || !size)
267
+ return [];
268
+ const meals = Number(p.specs?.meals ?? size.meals);
269
+ const people = Number(p.specs?.size ?? size.people);
270
+ return [{ sku: p.handle, meals, people, ...(p.handle === current ? { current: true } : {}) }];
271
+ }),
272
+ }));
273
+ if (resolveView(view, HF_VIEWS) === 'full')
274
+ return minifiedResult({ current, groups });
275
+ const sizes = groups.flatMap((g) => g.products).sort((a, b) => a.meals - b.meals || a.people - b.people);
276
+ return minifiedResult({ current, sizes });
277
+ });
278
+ server.registerTool('hf_recent_picks', {
279
+ description: 'List the HelloFresh meals picked in recent weeks — the current week and the weeks_back weeks before it — ' +
280
+ 'to avoid repeating a recipe. Best effort: each week’s menu is read separately, and weeks that cannot be ' +
281
+ 'read are listed with the reason.',
282
+ annotations: readOnly('HelloFresh: recent picks'),
283
+ _meta: foodMeta('lookup', { aliases: ['recent hellofresh meals', 'what did we have'] }),
284
+ inputSchema: z.object({
285
+ weeks_back: z.number().int().min(0).max(12).optional().describe('How many weeks before through_week to include (default 4).'),
286
+ through_week: weekParam
287
+ .optional()
288
+ .describe('The last week to include, as an ISO week (default: the current week).'),
289
+ }),
290
+ }, async ({ weeks_back, through_week }) => {
291
+ const account = await loadAccount(client);
292
+ const through = through_week ?? isoWeekOf(todayIso({ now: new Date(now()) }));
293
+ const back = weeks_back ?? 4;
294
+ const weeks = Array.from({ length: back + 1 }, (_, i) => shiftWeek(through, i - back));
295
+ const { weeks: read, recipeNames, unreadable } = await readPicks(client, account, weeks);
296
+ return minifiedResult({
297
+ throughWeek: through,
298
+ weeks: read,
299
+ recipeNames,
300
+ ...(unreadable.length > 0 ? { unreadable } : {}),
301
+ });
302
+ });
303
+ }
@@ -0,0 +1,183 @@
1
+ // Shared bits for the hf_ tools: the account context every call starts from
2
+ // (the subscription and its plan id), the `week` / `view` parameters, the
3
+ // box-number and estimate helpers, and the brief line.
4
+ import { z } from 'zod';
5
+ import { McpToolError, messageOf, viewParam } from '@chrischall/mcp-utils';
6
+ import { estimateBoxTotal, projectDelivery, projectMenu, } from '../normalize.js';
7
+ import { WEEK_PATTERN } from '../weeks.js';
8
+ // ---- parameters -----------------------------------------------------------------
9
+ export const HF_VIEWS = ['compact', 'full'];
10
+ /** The `view` parameter. `note` says what compact leaves out. */
11
+ export const hfView = (note) => viewParam(HF_VIEWS, { note });
12
+ export const weekParam = z
13
+ .string()
14
+ .trim()
15
+ .regex(WEEK_PATTERN, 'an ISO week like 2026-W49')
16
+ .describe('The delivery week as an ISO week, e.g. 2026-W49 (from hf_list_deliveries).');
17
+ /**
18
+ * The ASSUMED box number of the next running delivery when HelloFresh says the
19
+ * first box was delivered (or does not say) but not how many boxes since:
20
+ * an established subscription is past its first box. Never used when the
21
+ * first box is not yet delivered — then the next running box is box 1.
22
+ */
23
+ export const ASSUMED_NEXT_BOX_NUMBER = 2;
24
+ export const nextBoxNumberParam = z
25
+ .number()
26
+ .int()
27
+ .min(1)
28
+ .max(1000)
29
+ .optional()
30
+ .describe('Which box this account’s NEXT running delivery will be, counting every box ever delivered (1 = the first ' +
31
+ 'box). The voucher’s discount depends on it. Default: 1 when HelloFresh says the first box is not delivered ' +
32
+ `yet; otherwise an assumed ${ASSUMED_NEXT_BOX_NUMBER} (HelloFresh does not say how many boxes were delivered).`);
33
+ /** The account's subscription: the active one, else the first. */
34
+ export async function loadAccount(client) {
35
+ const items = (await client.listSubscriptions()).items ?? [];
36
+ const subscription = items.find((s) => s.isActive !== false && !s.canceledAt) ?? items[0];
37
+ if (!subscription?.id) {
38
+ throw new McpToolError('This account has no HelloFresh subscription.', {
39
+ hint: 'Check that the browser is signed in to the HelloFresh account that holds the meal-kit plan.',
40
+ });
41
+ }
42
+ return { subscription, subscriptionId: subscription.id };
43
+ }
44
+ /** Wait `ms` milliseconds (the default ToolDeps.sleep). */
45
+ export const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
46
+ /** Whether `week` is the subscription's first box, not yet delivered — HelloFresh will not resize it. */
47
+ export function isUnresizableFirstBox(subscription, week) {
48
+ return subscription.firstBoxDelivered === false && subscription.firstDeliveryWeek === week;
49
+ }
50
+ /** The customer plan id the menu read needs: the subscription's, else the plan whose legacy id matches. */
51
+ export async function customerPlanIdOf(client, account) {
52
+ if (account.subscription.customerPlanId)
53
+ return account.subscription.customerPlanId;
54
+ const plans = await client.listPlans();
55
+ const plan = plans.find((p) => p.legacySubscriptionId === account.subscriptionId) ?? plans[0];
56
+ if (!plan?.id)
57
+ throw new McpToolError('HelloFresh returned no customer plan for this subscription.');
58
+ return plan.id;
59
+ }
60
+ /** The week's menu for the delivery's box size. */
61
+ export async function readMenu(client, account, delivery, week) {
62
+ if (!delivery.sku || !delivery.servings) {
63
+ throw new McpToolError(`HelloFresh returned no box size for ${week}, so its menu cannot be read.`);
64
+ }
65
+ const customerPlanId = await customerPlanIdOf(client, account);
66
+ const menu = await client.getDeliveryMenu({
67
+ subscriptionId: account.subscriptionId,
68
+ week,
69
+ servings: delivery.servings,
70
+ sku: delivery.sku,
71
+ customerPlanId,
72
+ });
73
+ return projectMenu(menu);
74
+ }
75
+ /**
76
+ * The picks of each week, best effort: a skipped week has none (and reads no
77
+ * menu); a week whose delivery or menu cannot be read is listed in
78
+ * `unreadable` with the reason. `recipeNames` are the distinct picked names.
79
+ */
80
+ export async function readPicks(client, account, weeks) {
81
+ const results = await Promise.all(weeks.map(async (week) => {
82
+ const read = await attempt(async () => {
83
+ const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
84
+ if (delivery.status === 'skipped')
85
+ return { delivery, picks: [] };
86
+ const menu = await readMenu(client, account, delivery, week);
87
+ return { delivery, picks: menu.selected.map(compactSelection) };
88
+ });
89
+ return { week, read };
90
+ }));
91
+ const read = results.flatMap(({ week, read: r }) => r.ok ? [{ week, status: r.value.delivery.status, deliveryDate: dateOf(r.value.delivery.deliveryDate), picks: r.value.picks }] : []);
92
+ return {
93
+ weeks: read,
94
+ recipeNames: [...new Set(read.flatMap((w) => w.picks.map((p) => p.name)).filter((n) => !!n))],
95
+ unreadable: results.flatMap(({ week, read: r }) => (r.ok ? [] : [{ week, reason: r.reason }])),
96
+ };
97
+ }
98
+ // ---- estimates --------------------------------------------------------------------
99
+ /** Box number per running week (in week order), starting at `next`; skipped weeks take no number. */
100
+ export function boxNumbers(deliveries, next) {
101
+ const numbers = new Map();
102
+ for (const d of [...deliveries].sort(byWeek)) {
103
+ if (d.status === 'running' && d.week)
104
+ numbers.set(d.week, next + numbers.size);
105
+ }
106
+ return numbers;
107
+ }
108
+ /** Where the box numbering starts, and the note saying how that was decided. */
109
+ export function boxNumbering(subscription, nextBoxNumber) {
110
+ const counting = 'each later running week counts up by one (skipped weeks take no box number)';
111
+ if (nextBoxNumber !== undefined) {
112
+ return { next: nextBoxNumber, note: `Box numbers start at next_box_number ${nextBoxNumber} for the next running delivery; ${counting}.` };
113
+ }
114
+ if (subscription.firstBoxDelivered === false) {
115
+ const first = subscription.firstDeliveryWeek ? ` (first delivery week ${subscription.firstDeliveryWeek})` : '';
116
+ return {
117
+ next: 1,
118
+ note: `HelloFresh says this account’s first box is not delivered yet${first}, so the earliest running delivery is box 1 and ${counting}.`,
119
+ };
120
+ }
121
+ const known = subscription.firstBoxDelivered === true
122
+ ? `HelloFresh says the first box was delivered${subscription.firstDeliveryWeek ? ` in ${subscription.firstDeliveryWeek}` : ''} but not how many boxes since`
123
+ : 'HelloFresh does not say whether the first box was delivered';
124
+ return {
125
+ next: ASSUMED_NEXT_BOX_NUMBER,
126
+ note: `${known}, so this ASSUMES the next running delivery is box ${ASSUMED_NEXT_BOX_NUMBER} and ${counting}. Pass next_box_number to correct it.`,
127
+ };
128
+ }
129
+ export const byWeek = (a, b) => (a.week ?? '').localeCompare(b.week ?? '');
130
+ /** The estimate for a box; an unknown box number gives an undiscounted estimate that says why. */
131
+ export function estimateFor(delivery, selection, account, boxNumber) {
132
+ if (boxNumber === undefined) {
133
+ return {
134
+ ...estimateBoxTotal(delivery, selection, null, 1),
135
+ warning: 'This week is not among the upcoming deliveries, so its box number (and voucher discount) is unknown: the estimate is undiscounted. Pass box_number to apply the voucher.',
136
+ };
137
+ }
138
+ return { boxNumber, ...estimateBoxTotal(delivery, selection, account.subscription.voucherInfo, boxNumber) };
139
+ }
140
+ /** The few estimate fields a compact answer keeps. */
141
+ export function compactEstimate(e) {
142
+ return {
143
+ ...(e.boxNumber !== undefined ? { boxNumber: e.boxNumber } : {}),
144
+ subtotalCents: e.subtotalCents,
145
+ discountCents: e.discountCents,
146
+ totalCents: e.totalCents,
147
+ ...(e.warning ? { warning: e.warning } : {}),
148
+ };
149
+ }
150
+ /** A selection line without its zero-valued fields. */
151
+ export function compactSelection(s) {
152
+ return {
153
+ index: s.index,
154
+ quantity: s.quantity,
155
+ name: s.name,
156
+ ...(s.premiumBoxCents > 0 ? { premiumBoxCents: s.premiumBoxCents } : {}),
157
+ ...(s.baseIndex !== undefined ? { baseIndex: s.baseIndex } : {}),
158
+ };
159
+ }
160
+ /** A best-effort read: the value, or the reason it could not be read. */
161
+ export async function attempt(run) {
162
+ try {
163
+ return { ok: true, value: await run() };
164
+ }
165
+ catch (err) {
166
+ return { ok: false, reason: messageOf(err) };
167
+ }
168
+ }
169
+ // ---- brief ----------------------------------------------------------------------------
170
+ /** `YYYY-MM-DD` of an ISO timestamp as HelloFresh wrote it (its own offset), or undefined. */
171
+ export const dateOf = (iso) => iso?.slice(0, 10);
172
+ /**
173
+ * One delivery as one brief line (≤ 120 chars):
174
+ * `2026-W49 — 2026-11-30 — running, 2×6, cutoff 11-25`.
175
+ */
176
+ export function briefLine(d) {
177
+ const tail = [
178
+ d.status,
179
+ ...(d.meals && d.servings ? [`${d.meals}×${d.servings}`] : []),
180
+ ...(d.cutoffDate ? [`cutoff ${d.cutoffDate.slice(5, 10)}`] : []),
181
+ ].join(', ');
182
+ return `${d.week ?? 'unknown week'} — ${dateOf(d.deliveryDate) ?? 'no date'} — ${tail}`.slice(0, 120);
183
+ }