jsfe 1.104.1 → 1.105.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/README.md CHANGED
@@ -543,6 +543,13 @@ const engine = new WorkflowEngine(logger, aiCallback, flows, tools,
543
543
  elsewhere, or the host's `cargo.verb`), and `yesNoKeys(lang, cargo, yes, no)` ("Press 1 or say YES, or press 2 or say
544
544
  NO." on a call): every yes/no question names 1 for YES and 2 for NO on a call. A FLOW call's parameters interpolate
545
545
  values, not expressions, so build such a question in a SET step and pass the variable.
546
+ - Schedules and appointment times (`{timezone, hours: {mon: [{open, close}]}}`, the User Admin hours editor's shape):
547
+ `scheduleOpenNow(schedule, now)` (no hours = always open), `hoursPhrase(schedule, lang)` ("every day from 9 AM to 5 PM,
548
+ Pacific time"), `zipCovered(zips, zip)` ('913xx', '91301-91311', '91325'), `readWhen(text, {now, timezone})` (what a
549
+ customer said about when, in English or Spanish, as `{dates, from, to, at, later, any}`, or null), `openSlots({hours,
550
+ calendars, service, busy, preference, now, zip, calendar, count})` (up to `count` open times, earliest first, with
551
+ `label` / `label_es`; no business hours = nothing to book), `slotToWords(slot, lang, today)`, `todayIn(timezone)` and
552
+ `minutesUntil(time)`.
546
553
  - Checks: `validateDigits(input, min, max)` (digits only, length in range), `validatePhone(phone, acceptInternational)`
547
554
  (10 digits, or 11 with a leading 1; with `acceptInternational`, any 11 to 15), `validateEmail` (`x@y.z`, no spaces),
548
555
  `validateCardNumber` (12 to 19 digits passing Luhn), `validateExpiration(MM, YY)` (a real month, not expired, at most
@@ -973,6 +980,8 @@ See the [retry/yield/recovery contract](docs/copilot-reference.md#retry-yield-an
973
980
 
974
981
  > Transfer departments (`transfer-to-line`): the host stamps `cargo.transferLines` and consumes `cargo.transferTo`, see [docs/transfer-lines.md](docs/transfer-lines.md).
975
982
 
983
+ > Scheduling (`sched-*` workers): the host stamps `cargo.scheduling` and answers one tool, `iag:calendar` (busy, find, book, move, cancel); the host's Save attaches the fixed part of each tenant-authored booking form with `attachScheduling(form, {service, op})` and installs `schedulingChangeForms()`; the shapes are in the header of [src/forms/scheduling-flows.js](src/forms/scheduling-flows.js).
984
+
976
985
  A flow can take actions in the outside world through `CALL-TOOL` — charge a card, send an SMS,
977
986
  create a ticket. For ordinary `CALL-TOOL` flows, **the session returned by `updateActivity` records
978
987
  which steps already ran**; the host owns its persistence. Native performers can additionally use an
@@ -5,6 +5,7 @@ export { explainSession } from "./inspection.js";
5
5
  export { continuationBreaks } from "./continuation-compat.js";
6
6
  export { inheritFlowDeclaration } from "./declaration-capture.js";
7
7
  export { withSafetyRevision, CONTINUATION_SAFETY_REQUIREMENT } from "./continuation-safety.js";
8
+ export { attachScheduling, schedulingChangeForms } from "./scheduling-flows.js";
8
9
  export { FIELD_PRESETS, formFlow, declinedFlow, textValue, confirmationFirmness } from "./flows.js";
9
10
  export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from "./contracts.js";
10
11
  export { addressDraft, zipLocation, streetLocation, resolvedAddress } from "../helpers/address.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.js"],"names":[],"mappings":"AAQA,0BAA+K"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.js"],"names":[],"mappings":"AAUA,0BAA6L"}
@@ -6,7 +6,9 @@ import { FLOWS as CHOICE_FLOWS } from './choice-flow.js';
6
6
  import { FLOWS as IDENTITY } from './identity-flows.js';
7
7
  import { FLOWS as SEND_COPY } from './send-copy-flow.js';
8
8
  import { FLOWS as TRANSFER_LINE } from './transfer-line-flow.js';
9
- export const FLOWS = [...FORM_FLOWS, ...ADDRESS_FLOWS, ...CHOICE_FLOWS, ...IDENTITY, ...SEND_COPY, ...TRANSFER_LINE].map(flow => withSafetyRevision(flow, 'dispatch-intake-2026-10-22'));
9
+ import { FLOWS as SCHEDULING } from './scheduling-flows.js';
10
+ export { attachScheduling, schedulingChangeForms } from './scheduling-flows.js';
11
+ export const FLOWS = [...FORM_FLOWS, ...ADDRESS_FLOWS, ...CHOICE_FLOWS, ...IDENTITY, ...SEND_COPY, ...TRANSFER_LINE, ...SCHEDULING].map(flow => withSafetyRevision(flow, 'dispatch-intake-2026-10-22'));
10
12
  export { FIELD_PRESETS, formFlow, declinedFlow, textValue, confirmationFirmness } from './flows.js';
11
13
  export { FLOWS as IDENTITY_FLOWS } from './identity-flows.js';
12
14
  export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from './contracts.js';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The scheduling inputs, first step, read-back and action, attached to a form the tenant authored (its name, description
3
+ * and own fields, as the Leads card writes them). `op` is book, move or cancel; `service` the cargo.scheduling.services
4
+ * key a booking form books. Idempotent: a form saved again gets the current fixed part, its own fields untouched.
5
+ */
6
+ export function attachScheduling(declaration: any, { service, op }?: {
7
+ service?: string | undefined;
8
+ op?: string | undefined;
9
+ }): any;
10
+ /** The tenant's reschedule and cancel forms: no fields of their own, so nothing for the tenant to author. */
11
+ export function schedulingChangeForms(): any[];
12
+ export const FLOWS: any[];
13
+ //# sourceMappingURL=scheduling-flows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduling-flows.d.ts","sourceRoot":"","sources":["../../src/forms/scheduling-flows.js"],"names":[],"mappings":"AAoRA;;;;GAIG;AACH;;;QAeC;AAED,6GAA6G;AAC7G,+CAMC;AAED,0BAAwG"}
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Scheduling (owner 2026-12-05): the shared workers behind the tenant's booking, reschedule and cancel forms.
3
+ * Tenant-agnostic; built into the system set like transfer-to-line.
4
+ *
5
+ * The User Admin Scheduling card writes ordinary native Performers that call these workers; the tenant's calendars and
6
+ * services are not in any flow. The host stamps them on every turn as cargo.scheduling:
7
+ * { hours: { timezone, hours }, the business hours (the User Admin hours editor's shape)
8
+ * calendars: [{ key, name, name_es?, schedule?, zips?, skills? }],
9
+ * services: { <key>: { name, name_es?, length, buffer?, time: 'exact'|'window', step?, windows?, per?,
10
+ * avail: 'check'|'accept', notice?, ahead?, skill?, who: 'pick'|'first'|'later', leads: 'us'|'customer',
11
+ * cutoff? (minutes before the start after which it cannot be changed here) } },
12
+ * identified: true when the channel's own number identifies the customer (a call, a text) }
13
+ *
14
+ * One host tool, iag:calendar ({ op, request, container: the cargo }), does everything that needs a tenant's data or credentials:
15
+ * busy { calendars, days } → [{ calendar, start, end }]
16
+ * find {} → { bookings: [{ id, service, calendar, start, end, date, from, to, window }] }
17
+ * the bookings of the verified customer: the caller's own number, or the contact a one-time code proved
18
+ * book { service, calendar, start, end, window, zip, customer } → { status: 'booked'|'taken'|'failed', id? }
19
+ * move { id, service, calendar, start, end, window } → { status: 'moved'|'taken'|'failed' } (the old time
20
+ * is kept until the new one is booked)
21
+ * cancel { id } → { status: 'cancelled'|'failed' }
22
+ *
23
+ * The forms: the tenant authors a booking form per service (name, description and its own fields, as the Leads card
24
+ * writes them); the host's Save calls attachScheduling(form, {service, op:'book'}) for the fixed part (inputs sched_zip,
25
+ * sched_calendar, sched_when, sched_slot, the first step, the read-back and the action) and installs
26
+ * schedulingChangeForms() for reschedule and cancel. Both are below; the journeys test exactly these.
27
+ */
28
+ import { defineWorker } from './contracts.js';
29
+ const S = (id, variable, value) => ({ id, type: 'SET', variable, value });
30
+ const W = (id, condition, step) => ({ id, type: 'CASE', branches: { ['condition: ' + condition]: step, default: S(id + '_skip', 'noop', 'true') } });
31
+ const V = o => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, { type: Array.isArray(v) ? 'array' : v === null || typeof v === 'object' ? 'object' : typeof v, value: v }]));
32
+ const E = (fn, ...args) => `(${fn.toString()})(${args.join(',')})`;
33
+ const P = (name, type = 'string') => ({ name, type, description: name });
34
+ const C = (id, summary, steps, extra = {}) => defineWorker({ id, name: id.split('-').map(w => w[0].toUpperCase() + w.slice(1)).join(''), description: summary, ...extra, contract: { role: 'worker', summary, ...extra.contract }, steps });
35
+ const CALENDAR = (id, op, request, variable, fallback) => ({ id, type: 'CALL-TOOL', tool: 'iag:calendar', variable, args: { op, request, container: '{{cargo}}' }, onFail: S(id + '_failed', variable, fallback) });
36
+ // Ends the form and every flow under it: a worker's own END would end only the worker, and the form would ask on.
37
+ // Its wording is set in the worker's own stop_* variables first, so the new root flow receives plain values.
38
+ const STOP = (id, condition, message, message_es, outcome, reason) => [
39
+ S(id + '_message', 'stop_message', message), S(id + '_message_es', 'stop_message_es', message_es), S(id + '_outcome', 'stop_outcome', outcome), S(id + '_reason', 'stop_reason', reason),
40
+ W(id, condition, { id: id + '_flow', type: 'FLOW', value: 'sched-stop', callType: 'reboot', parameters: { message: '{{stop_message}}', message_es: '{{stop_message_es}}', outcome: '{{stop_outcome}}', reason: '{{stop_reason}}' } })
41
+ ];
42
+ const STOP_VARS = { stop_message: '', stop_message_es: '', stop_outcome: '', stop_reason: '' };
43
+ const ANYTHING_ELSE = " {{anythingElse('en')}}";
44
+ const ANYTHING_ELSE_ES = " {{anythingElse('es')}}";
45
+ // ---- pure pieces, inlined into the expressions (standard functions are in scope by name there) ----
46
+ // The form's settings, from cargo.scheduling and the service the form names.
47
+ function startData(cargo, form, service, op) {
48
+ const cfg = cargo.scheduling || {}, svc = (cfg.services || {})[service] || null, cals = Array.isArray(cfg.calendars) ? cfg.calendars : [];
49
+ // every flag a form's conditions read is set, false when it does not apply: an unset one blocks the form
50
+ const data = Object.assign({}, cargo.forms[form].data || {}, { op: op, service: service, ok: op !== 'book' || !!svc, need_zip: false, pick: false, customer_leads: false });
51
+ if (svc) {
52
+ data.service_name = String(svc.name || service);
53
+ data.service_name_es = String(svc.name_es || svc.name || service);
54
+ data.need_zip = cals.some(function (c) { return Array.isArray(c.zips) && c.zips.length > 0; });
55
+ data.pick = svc.who === 'pick' && cals.length > 1;
56
+ data.customer_leads = svc.leads === 'customer';
57
+ }
58
+ else {
59
+ data.service_name = '';
60
+ data.service_name_es = '';
61
+ }
62
+ cargo.forms[form].data = data;
63
+ return data.ok;
64
+ }
65
+ // The calendars that can take the service at the customer's zip code.
66
+ function eligible(cfg, svc, zip) {
67
+ const skill = String((svc && svc.skill) || '').toLowerCase();
68
+ return (Array.isArray(cfg.calendars) ? cfg.calendars : []).filter(function (c) {
69
+ return zipCovered(c.zips, zip) && (!skill || (Array.isArray(c.skills) && c.skills.some(function (s) { return String(s).toLowerCase() === skill; })));
70
+ });
71
+ }
72
+ // "a, b or c" / "a, b o c" (inlined functions see no module scope: offerData and bookingData carry their own copy).
73
+ function listed(items, or) {
74
+ return items.length < 2 ? (items[0] || '') : items.slice(0, -1).join(', ') + ' ' + or + ' ' + items[items.length - 1];
75
+ }
76
+ // The offered times as choices, and the question that offers them.
77
+ function offerData(data, slots, voice) {
78
+ const listed = function (items, or) { return items.length < 2 ? (items[0] || '') : items.slice(0, -1).join(', ') + ' ' + or + ' ' + items[items.length - 1]; };
79
+ const later = { key: 'later', phrases: ['later', 'something later', 'a later time', 'later times', 'más tarde', 'algo más tarde', 'otra hora más tarde'], label: 'A later time', label_es: 'Más tarde', neutral: true };
80
+ data.slots = slots;
81
+ // an exact time is also picked by its clock ("10 AM", "a las 10"), never by a bare number, which is a key
82
+ const clocks = function (s) {
83
+ if (s.window)
84
+ return [];
85
+ const h = parseInt(s.from, 10), m = s.from.slice(3), h12 = h % 12 || 12, ap = h < 12 ? 'am' : 'pm', hm = m === '00' ? String(h12) : h12 + ':' + m;
86
+ return [hm + ' ' + ap, hm + ap, 'at ' + hm, 'a las ' + (m === '00' ? String(h) : h + ':' + m), 'a la ' + hm];
87
+ };
88
+ const clockCount = {};
89
+ slots.forEach(function (s) { clocks(s).forEach(function (c) { clockCount[c] = (clockCount[c] || 0) + 1; }); });
90
+ data.slot_choices = slots.map(function (s, i) {
91
+ const own = clocks(s).filter(function (c) { return clockCount[c] === 1; });
92
+ return { key: s.key, keys: [String(i + 1)], phrases: [s.label, s.label_es].concat(own, slots.length === 1 ? ['yes', 'sí', 'si', 'that works', 'ok', 'okay'] : []), label: s.label, label_es: s.label_es, neutral: true };
93
+ }).concat(slots.length ? [later] : []);
94
+ const en = slots.map(function (s) { return s.label; }), es = slots.map(function (s) { return s.label_es; });
95
+ const keysEn = voice ? '' : ' ' + (slots.length > 1 ? 'Type 1 to ' + slots.length + '.' : 'Type 1 or YES.');
96
+ const keysEs = voice ? '' : ' ' + (slots.length > 1 ? 'Escriba del 1 al ' + slots.length + '.' : 'Escriba 1 o SÍ.');
97
+ if (!slots.length) {
98
+ data.slot_question = data.pref ? 'I do not have an opening then. What other day or time would work for you?' : 'I do not see an opening in the coming days. What day or time would work for you?';
99
+ data.slot_question_es = data.pref ? 'No tengo un espacio disponible en ese momento. ¿Qué otro día u hora le funcionaría?' : 'No veo espacios disponibles en los próximos días. ¿Qué día u hora le funcionaría?';
100
+ }
101
+ else if (slots.length === 1) {
102
+ data.slot_question = 'I have ' + en[0] + '. Does that work for you?' + keysEn;
103
+ data.slot_question_es = 'Tengo ' + es[0] + '. ¿Le funciona?' + keysEs;
104
+ }
105
+ else {
106
+ data.slot_question = 'I have ' + listed(en, 'or') + '. Which works for you? You can also ask for another day or time.' + keysEn;
107
+ data.slot_question_es = 'Tengo ' + listed(es, 'o') + '. ¿Cuál le funciona? También puede pedir otro día u hora.' + keysEs;
108
+ }
109
+ return true;
110
+ }
111
+ // The customer's bookings as choices; one too close to change is named and not offered.
112
+ function bookingData(data, bookings, services, timezone, voice) {
113
+ const listed = function (items, or) { return items.length < 2 ? (items[0] || '') : items.slice(0, -1).join(', ') + ' ' + or + ' ' + items[items.length - 1]; };
114
+ const today = todayIn(timezone);
115
+ const name = function (b, es) { const s = services[b.service] || {}; return String((es ? s.name_es : '') || s.name || b.service || (es ? 'cita' : 'appointment')); };
116
+ const word = function (b, es) { return name(b, es) + (es ? ' ' : ' ') + slotToWords(b, es ? 'es' : 'en', today); };
117
+ const open = [], locked = [];
118
+ (Array.isArray(bookings) ? bookings : []).forEach(function (b) {
119
+ const cutoff = Number((services[b.service] || {}).cutoff) || 0;
120
+ if (minutesUntil(b.start) < Math.max(0, cutoff)) {
121
+ locked.push(b);
122
+ }
123
+ else {
124
+ open.push(b);
125
+ }
126
+ });
127
+ data.bookings = open;
128
+ data.booking_choices = open.map(function (b, i) { return { key: String(b.id), keys: [String(i + 1)], phrases: [word(b, false), word(b, true)].concat(open.length === 1 ? ['yes', 'sí', 'si', 'that one', 'esa'] : []), label: word(b, false), label_es: word(b, true), neutral: true }; });
129
+ data.locked_note = locked.length ? 'Your ' + word(locked[0], false) + ' is too close to change here; please call our office.' : '';
130
+ data.locked_note_es = locked.length ? 'Su cita de ' + word(locked[0], true) + ' está demasiado cerca para cambiarla aquí; por favor llame a nuestra oficina.' : '';
131
+ data.no_bookings = !open.length;
132
+ const keys = voice ? '' : (open.length > 1 ? ' Type 1 to ' + open.length + '.' : ' Type 1 or YES.');
133
+ const keysEs = voice ? '' : (open.length > 1 ? ' Escriba del 1 al ' + open.length + '.' : ' Escriba 1 o SÍ.');
134
+ data.booking_question = open.length === 1 ? 'I found your ' + word(open[0], false) + '. Is that the one?' + keys : 'Which appointment is it: ' + listed(open.map(function (b) { return word(b, false); }), 'or') + '?' + keys;
135
+ data.booking_question_es = open.length === 1 ? 'Encontré su cita de ' + word(open[0], true) + '. ¿Es esa?' + keysEs : '¿Qué cita es: ' + listed(open.map(function (b) { return word(b, true); }), 'o') + '?' + keysEs;
136
+ return true;
137
+ }
138
+ // The exact request for the confirmed action, and the read-back that confirms it.
139
+ function prepareData(cargo, form) {
140
+ const f = cargo.forms[form], d = f.data || {}, v = f.values || {}, cfg = cargo.scheduling || {};
141
+ const svc = (cfg.services || {})[d.service] || {}, tz = (cfg.hours && cfg.hours.timezone) || 'UTC', today = todayIn(tz);
142
+ const cal = (cfg.calendars || []).filter(function (c) { return d.slot && c.key === d.slot.calendar; })[0];
143
+ const yn = { en: yesNoKeys('en', cargo), es: yesNoKeys('es', cargo) };
144
+ const name = { en: d.service_name || 'appointment', es: d.service_name_es || d.service_name || 'cita' };
145
+ const customer = {};
146
+ Object.keys(v).forEach(function (k) { if (k.indexOf('sched_') !== 0)
147
+ customer[k] = v[k]; });
148
+ if (d.op === 'cancel') {
149
+ cargo.actionRequest = { op: 'cancel', id: String(d.booking.id) };
150
+ cargo.schedulingConfirm = {
151
+ question: 'Would you like me to cancel your ' + name.en + ' ' + slotToWords(d.booking, 'en', today) + '? If you would rather move it to another time, just say so. ' + yn.en,
152
+ question_es: '¿Desea que cancele su cita de ' + name.es + ' ' + slotToWords(d.booking, 'es', today) + '? Si prefiere cambiarla a otra hora, solo dígalo. ' + yn.es
153
+ };
154
+ return true;
155
+ }
156
+ const who = svc.who === 'later' ? '' : String(d.slot.calendar || '');
157
+ const withWhom = d.pick && cal ? { en: ' with ' + cal.name, es: ' con ' + (cal.name_es || cal.name) } : { en: '', es: '' };
158
+ if (d.op === 'move') {
159
+ cargo.actionRequest = { op: 'move', id: String(d.booking.id), service: d.service, calendar: who, start: d.slot.start, end: d.slot.end, window: !!d.slot.window };
160
+ cargo.schedulingConfirm = {
161
+ question: 'To confirm: I will move your ' + name.en + ' from ' + slotToWords(d.booking, 'en', today) + ' to ' + slotToWords(d.slot, 'en', today) + '. Is that right? ' + yn.en,
162
+ question_es: 'Para confirmar: cambiaré su cita de ' + name.es + ' de ' + slotToWords(d.booking, 'es', today) + ' a ' + slotToWords(d.slot, 'es', today) + '. ¿Es correcto? ' + yn.es
163
+ };
164
+ return true;
165
+ }
166
+ cargo.actionRequest = { op: 'book', service: d.service, calendar: who, start: d.slot.start, end: d.slot.end, window: !!d.slot.window, zip: String(v.sched_zip || ''), customer: customer };
167
+ cargo.schedulingConfirm = {
168
+ question: 'To confirm: ' + name.en + ' ' + slotToWords(d.slot, 'en', today) + withWhom.en + '. Shall I book it? ' + yn.en,
169
+ question_es: 'Para confirmar: ' + name.es + ' ' + slotToWords(d.slot, 'es', today) + withWhom.es + '. ¿Reservo la cita? ' + yn.es
170
+ };
171
+ return true;
172
+ }
173
+ // What the customer hears once the calendar answered.
174
+ function presentLine(cargo, form, result, es) {
175
+ const d = cargo.forms[form].data || {}, cfg = cargo.scheduling || {}, svc = (cfg.services || {})[d.service] || {};
176
+ const today = todayIn((cfg.hours && cfg.hours.timezone) || 'UTC');
177
+ const L = es ? 'es' : 'en', name = es ? (d.service_name_es || d.service_name || 'cita') : (d.service_name || 'appointment');
178
+ const status = result && result.status;
179
+ if (status === 'booked') {
180
+ return es ? 'Listo, su cita de ' + name + ' quedó reservada para ' + slotToWords(d.slot, L, today) + '.' + (svc.who === 'later' ? ' Nuestra oficina le avisará quién irá.' : '')
181
+ : 'You are all set: ' + name + ' ' + slotToWords(d.slot, L, today) + '.' + (svc.who === 'later' ? ' Our office will let you know who is coming.' : '');
182
+ }
183
+ else if (status === 'moved') {
184
+ return es ? 'Listo, su cita de ' + name + ' ahora es ' + slotToWords(d.slot, L, today) + '.' : 'Done. Your ' + name + ' is now ' + slotToWords(d.slot, L, today) + '.';
185
+ }
186
+ else if (status === 'cancelled') {
187
+ return es ? 'Su cita de ' + name + ' ' + slotToWords(d.booking, L, today) + ' quedó cancelada.' : 'Your ' + name + ' ' + slotToWords(d.booking, L, today) + ' is cancelled.';
188
+ }
189
+ else if (status === 'taken') {
190
+ return es ? 'Lo siento, ese horario se acaba de ocupar. Pídame otra hora cuando guste.' : 'I am sorry, that time was just taken. Ask me for another time whenever you like.';
191
+ }
192
+ else if (status === 'failed') {
193
+ return es ? 'Lo siento, no pude hacer ese cambio en este momento.' : 'I am sorry, I could not make that change right now.';
194
+ }
195
+ else {
196
+ return es ? 'No pude confirmar si el cambio se hizo, así que por favor consulte con nuestra oficina antes de intentarlo de nuevo.' : 'I could not confirm whether that went through, so please check with our office before trying again.';
197
+ }
198
+ }
199
+ // ---- workers ----
200
+ const start = C('sched-start', 'Load the service the form books from cargo.scheduling; a service the tenant does not offer ends the form.', [
201
+ S('sched_start', 'ok', E(startData, 'cargo', 'form', 'service', 'op')),
202
+ ...STOP('sched_start_stop', '!ok', "'Sorry, I cannot book that here.'", "'Lo siento, no puedo reservar eso aquí.'", "'unresolved'", "'scheduling_not_offered'")
203
+ ], { parameters: [P('form'), P('service'), P('op')], variables: V({ ok: false, ...STOP_VARS }), contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
204
+ const zip = C('sched-zip-validate', 'A zip code no calendar covers is outside the service area.', [
205
+ S('sched_zip_check', 'noop', "(function(cfg,svc,zip){var ok=" + E(eligible, 'cfg', 'svc', 'zip') + ".length>0;cargo.inputCheck=ok?{ok:true,value:zip}:{ok:false,message:'Sorry, we do not serve zip code '+zip+'.',message_es:'Lo siento, no damos servicio en el código postal '+zip+'.'};return true;})(cargo.scheduling||{},((cargo.scheduling||{}).services||{})[cargo.forms[form].data.service],String(value))")
206
+ ], { parameters: [P('form'), P('value')], contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
207
+ const calendarPrompt = C('sched-calendar-prompt', 'Offer the calendars that cover the customer\'s zip code, by name, and first available.', [
208
+ S('sched_calendar_prompt', 'noop', "(function(d,cfg,voice){var cals=" + E(eligible, 'cfg', '(cfg.services||{})[d.service]', "String((cargo.forms[form].values||{}).sched_zip||'')") + ",names=cals.map(function(c){return c.name;}),names_es=cals.map(function(c){return c.name_es||c.name;});d.calendar_choices=cals.map(function(c,i){return {key:c.key,keys:[String(i+1)],phrases:[c.name].concat(c.name_es?[c.name_es]:[]),label:c.name,label_es:c.name_es||c.name,neutral:true};}).concat([{key:'any',keys:[String(cals.length+1)],phrases:['first available','anyone','any','whoever is first','el primero disponible','cualquiera'],label:'First available',label_es:'El primero disponible',neutral:true}]);d.calendar_question='Who would you like: '+" + E(listed, 'names', "'or'") + "+'? Or I can book whoever is first available.'+(voice?'':' Type 1 to '+(cals.length+1)+'.');d.calendar_question_es='¿Con quién desea: '+" + E(listed, 'names_es', "'o'") + "+'? O puedo reservar con el primero disponible.'+(voice?'':' Escriba del 1 al '+(cals.length+1)+'.');return true;})(cargo.forms[form].data,cargo.scheduling||{},cargo.voice===true)")
209
+ ], { parameters: [P('form'), P('input')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
210
+ const when = C('sched-when-validate', 'Read when the customer would like to come; a time with no day keeps the day already asked for; words with no day or time are asked again.', [
211
+ S('sched_when_read', 'pref', "readWhen(String(value),{timezone:((cargo.scheduling||{}).hours||{}).timezone||'UTC'})"),
212
+ S('sched_when_check', 'noop', "(function(d){if(!pref){cargo.inputCheck={ok:false,message:'Sorry, I did not catch a day or time.',message_es:'Disculpe, no entendí un día o una hora.'};return true;}if(!pref.dates&&!pref.later&&!pref.any&&d.pref&&d.pref.dates){pref.dates=d.pref.dates;}d.not_before=pref.later&&d.slots&&d.slots.length?new Date(Date.parse(d.slots[d.slots.length-1].start)+60000).toISOString():null;d.pref=pref.any||pref.later?null:pref;cargo.inputCheck={ok:true,value:String(value)};return true;})(cargo.forms[form].data)")
213
+ ], { parameters: [P('form'), P('value')], variables: V({ pref: null }), contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
214
+ const offer = C('sched-offer', 'Before each time question: read the busy times (unless the customer\'s time is accepted) and offer up to three open times.', [
215
+ S('sched_offer_cfg', 'cfg', 'cargo.scheduling || {}'),
216
+ S('sched_offer_data', 'd', 'cargo.forms[form].data'),
217
+ S('sched_offer_svc', 'svc', "(cfg.services || {})[d.service] || {}"),
218
+ S('sched_offer_values', 'vals', 'cargo.forms[form].values || {}'),
219
+ S('sched_offer_cals', 'cals', E(eligible, 'cfg', 'svc', "String(vals.sched_zip || '')") + ".filter(function(c){return (!vals.sched_calendar || vals.sched_calendar === 'any' || c.key === vals.sched_calendar) && (!d.booking || !d.booking.calendar || c.key === d.booking.calendar);})"),
220
+ S('sched_offer_keys', 'keys', 'cals.map(function(c){return c.key;})'),
221
+ S('sched_offer_days', 'days', 'Number(svc.ahead) || 30'),
222
+ W('sched_offer_busy', "svc.avail !== 'accept' && cals.length > 0", CALENDAR('sched_offer_busy_tool', 'busy', { calendars: '{{keys}}', days: '{{days}}' }, 'busy', 'null')),
223
+ S('sched_offer_slots', 'slots', "svc.avail !== 'accept' && !Array.isArray(busy) ? [] : openSlots({hours:cfg.hours,calendars:cals,service:svc,busy:Array.isArray(busy)?busy:[],preference:d.not_before?Object.assign({},d.pref||{},{notBefore:d.not_before}):d.pref,zip:String(vals.sched_zip||''),count:3})"),
224
+ S('sched_offer_question', 'noop', E(offerData, 'd', 'slots', 'cargo.voice === true')),
225
+ W('sched_offer_unreachable', "svc.avail !== 'accept' && cals.length > 0 && !Array.isArray(busy)", S('sched_offer_unreachable_q', 'noop', "(d.slot_question='I am sorry, I cannot see our calendar right now. Please try again a little later.',d.slot_question_es='Lo siento, no puedo ver nuestro calendario en este momento. Por favor intente un poco más tarde.',true)"))
226
+ ], { parameters: [P('form'), P('input')], variables: V({ cfg: null, d: null, svc: null, vals: null, cals: [], keys: [], days: 30, busy: null, slots: [] }), contract: { tools: ['iag:calendar'], result: { path: 'cargo.forms[form].data', type: 'object' } } });
227
+ const slot = C('sched-slot-validate', 'Take an offered time; LATER moves the offer past the last time offered.', [
228
+ S('sched_slot_check', 'noop', "(function(d){var key=String(value),s=(d.slots||[]).filter(function(x){return x.key===key;})[0];if(key==='later'){d.not_before=d.slots&&d.slots.length?new Date(Date.parse(d.slots[d.slots.length-1].start)+60000).toISOString():null;cargo.inputCheck={ok:false,quiet:true};return true;}if(!s){cargo.inputCheck={ok:false,quiet:true};return true;}d.slot=s;cargo.inputCheck={ok:true,value:key};return true;})(cargo.forms[form].data)")
229
+ ], { parameters: [P('form'), P('value')], contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
230
+ const find = C('sched-find', 'Before the booking question: prove who the customer is (a one-time code unless their own number identifies them), then list their upcoming bookings.', [
231
+ W('sched_find_verify', "!((cargo.scheduling || {}).identified === true) && cargo.otpVerified !== true", { id: 'sched_find_auth', type: 'FLOW', value: 'authenticate-user', callType: 'call', parameters: { parent_form: '{{form}}' } }),
232
+ W('sched_find_lookup', "(cargo.scheduling || {}).identified === true || cargo.otpVerified === true", CALENDAR('sched_find_tool', 'find', {}, 'found', 'null')),
233
+ S('sched_find_data', 'noop', E(bookingData, 'cargo.forms[form].data', 'found && found.bookings', "(cargo.scheduling || {}).services || {}", "((cargo.scheduling || {}).hours || {}).timezone || 'UTC'", 'cargo.voice === true')),
234
+ ...STOP('sched_find_stop', "cargo.forms[form].data.no_bookings", "!found ? 'I am sorry, I cannot look up appointments right now.' : (cargo.forms[form].data.locked_note || 'I do not see any upcoming appointments for you.')", "!found ? 'Lo siento, no puedo consultar citas en este momento.' : (cargo.forms[form].data.locked_note_es || 'No veo citas próximas a su nombre.')", "found ? 'resolved' : 'unresolved'", "found ? (cargo.forms[form].data.locked_note ? 'booking_inside_cutoff' : 'no_bookings') : 'calendar_unavailable'")
235
+ ], { parameters: [P('form'), P('input')], variables: V({ found: null, ...STOP_VARS }), contract: { tools: ['iag:calendar'], result: { path: 'cargo.forms[form].data', type: 'object' } } });
236
+ const booking = C('sched-booking-validate', 'Take one of the customer\'s bookings; a move offers times for the same service, on the same calendar.', [
237
+ S('sched_booking_check', 'noop', "(function(d){var b=(d.bookings||[]).filter(function(x){return String(x.id)===String(value);})[0];if(!b){cargo.inputCheck={ok:false,quiet:true};return true;}var svc=((cargo.scheduling||{}).services||{})[b.service]||{};d.booking=b;d.service=b.service;d.customer_leads=svc.leads==='customer';d.service_name=String(svc.name||b.service||'');d.service_name_es=String(svc.name_es||svc.name||b.service||'');cargo.inputCheck={ok:true,value:String(b.id)};return true;})(cargo.forms[form].data)")
238
+ ], { parameters: [P('form'), P('value')], contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
239
+ const prepare = C('sched-prepare', 'The exact request for the confirmed booking, move or cancellation, and its read-back.', [
240
+ S('sched_prepare', 'noop', E(prepareData, 'cargo', 'form'))
241
+ ], { parameters: [P('form')], contract: { result: { path: 'cargo.actionRequest', type: 'object' } } });
242
+ const execute = C('sched-execute', 'Send the confirmed request to the tenant\'s calendar once; no answer is an unknown result, never a retry.', [
243
+ CALENDAR('sched_execute_tool', '{{request.op}}', '{{request}}', 'reply', "({status:'unknown'})"),
244
+ S('sched_execute_result', 'noop', "(cargo.actionOutcome = reply && typeof reply === 'object' && reply.status ? reply : {status:'unknown'}, true)")
245
+ ], { parameters: [P('request', 'object')], variables: V({ reply: null }), contract: { tools: ['iag:calendar'], result: { path: 'cargo.actionOutcome', type: 'object' } } });
246
+ const present = C('sched-present', 'Tell the customer what the calendar did.', [
247
+ S('sched_present_en', 'line', E(presentLine, 'cargo', 'form', 'result', 'false')),
248
+ S('sched_present_es', 'line_es', E(presentLine, 'cargo', 'form', 'result', 'true')),
249
+ { id: 'sched_present_say', type: 'SAY', value: '{{line}}' + ANYTHING_ELSE, value_es: '{{line_es}}' + ANYTHING_ELSE_ES }
250
+ ], { parameters: [P('form'), P('request', 'object'), P('result', 'object')], variables: V({ line: '', line_es: '' }) });
251
+ const stop = C('sched-stop', 'Say why scheduling cannot go on here, and end.', [
252
+ { id: 'sched_stop_say', type: 'SAY', value: '{{message}}' + ANYTHING_ELSE, value_es: '{{message_es || message}}' + ANYTHING_ELSE_ES },
253
+ { id: 'sched_stop_end', type: 'END', outcome: '{{outcome}}', reason: '{{reason}}' }
254
+ ], { parameters: [P('message'), P('message_es'), P('outcome'), P('reason')] });
255
+ // ---- the fixed part of every scheduling form: one source for the host's Save and for the tests ----
256
+ const WHEN_HINT = 'When the customer would rather come, in their own words: a day, a date, a part of the day or a time ("Thursday afternoon", "after 5", "el sábado por la mañana"), or a request for later times';
257
+ const INPUTS = {
258
+ sched_zip: { name: 'sched_zip', field: 'zip', when: { 'form.data.need_zip': true }, validator: 'sched-zip-validate', question: 'What is the zip code where you need us?', question_es: '¿Cuál es el código postal donde nos necesita?' },
259
+ sched_calendar: { name: 'sched_calendar', label: 'who', label_es: 'con quién', profile: { kind: 'choice', choices: [] }, choices_from: 'calendar_choices', refresh: 'sched-calendar-prompt', question_from: 'calendar_question', question: 'Who would you like?', question_es: '¿Con quién desea?', when: { 'form.data.pick': true }, reset_on: ['sched_zip'] },
260
+ sched_when: { name: 'sched_when', label: 'preferred time', label_es: 'hora preferida', argument_description: WHEN_HINT, profile: { kind: 'text' }, validator: 'sched-when-validate', required_when: { 'form.data.customer_leads': true }, question: 'When would be a good time for us?', question_es: '¿Cuándo sería un buen momento para usted?' },
261
+ sched_slot: { name: 'sched_slot', label: 'time', label_es: 'hora', profile: { kind: 'choice', choices: [] }, choices_from: 'slot_choices', refresh: 'sched-offer', question_from: 'slot_question', validator: 'sched-slot-validate', max_attempts: 8, rank_parameters: [{ name: 'sched_when', description: WHEN_HINT, reads: 'sched_when' }], question: 'Which time works for you?', question_es: '¿Qué hora le funciona?' },
262
+ sched_booking: { name: 'sched_booking', label: 'appointment', label_es: 'cita', profile: { kind: 'choice', choices: [] }, choices_from: 'booking_choices', refresh: 'sched-find', question_from: 'booking_question', validator: 'sched-booking-validate', question: 'Which appointment is it?', question_es: '¿Qué cita es?' },
263
+ };
264
+ const ACTIONS = {
265
+ book: { action: 'book_appointment', effect: 'write', ok: 'booked' },
266
+ move: { action: 'move_appointment', effect: 'write', ok: 'moved' },
267
+ cancel: { action: 'cancel_appointment', effect: 'cancel', ok: 'cancelled' },
268
+ };
269
+ const OWN_STEP = 'sched_begin';
270
+ const clone = value => JSON.parse(JSON.stringify(value));
271
+ /**
272
+ * The scheduling inputs, first step, read-back and action, attached to a form the tenant authored (its name, description
273
+ * and own fields, as the Leads card writes them). `op` is book, move or cancel; `service` the cargo.scheduling.services
274
+ * key a booking form books. Idempotent: a form saved again gets the current fixed part, its own fields untouched.
275
+ */
276
+ export function attachScheduling(declaration, { service = '', op = 'book' } = {}) {
277
+ if (!ACTIONS[op])
278
+ throw new Error(`attachScheduling: unknown op ${op}`);
279
+ const flow = clone(declaration), form = flow.form = flow.form || {};
280
+ const own = (form.inputs || []).filter(input => !String(input && input.name || '').startsWith('sched_'));
281
+ const fixed = op === 'book' ? [INPUTS.sched_zip, INPUTS.sched_calendar, INPUTS.sched_when, { ...INPUTS.sched_slot, reset_on: ['sched_zip', 'sched_calendar', 'sched_when'] }]
282
+ : op === 'move' ? [INPUTS.sched_booking, INPUTS.sched_when, { ...INPUTS.sched_slot, depends_on: ['sched_booking'], reset_on: ['sched_when', 'sched_booking'] }]
283
+ : [INPUTS.sched_booking];
284
+ form.inputs = [...clone(fixed), ...own];
285
+ form.before = [{ id: OWN_STEP, type: 'FLOW', value: 'sched-start', callType: 'call', parameters: { form: '{{form_instance}}', service, op } }, ...(form.before || []).filter(step => step && step.id !== OWN_STEP)];
286
+ form.confirm = { question: '{{cargo.schedulingConfirm.question}}', question_es: '{{cargo.schedulingConfirm.question_es}}' };
287
+ const a = ACTIONS[op];
288
+ flow.performs = [{ action: a.action, effect: a.effect, flow: 'sched-execute', confirm: { exact: true }, outcomes: { [a.ok]: 'resolved', taken: 'unresolved', failed: 'unresolved', unknown: 'unresolved' } }];
289
+ flow.prepare = 'sched-prepare';
290
+ flow.present = 'sched-present';
291
+ return flow;
292
+ }
293
+ /** The tenant's reschedule and cancel forms: no fields of their own, so nothing for the tenant to author. */
294
+ export function schedulingChangeForms() {
295
+ const base = (id, name, description) => ({ declarationVersion: 2, id, name, version: '1.0.0', primary: true, description, form: { inputs: [] } });
296
+ return [
297
+ attachScheduling(base('reschedule-appointment', 'RescheduleAppointment', 'The customer wants to move an appointment they already have to another day or time.'), { op: 'move' }),
298
+ attachScheduling(base('cancel-appointment', 'CancelAppointment', 'The customer wants to cancel an appointment they already have.'), { op: 'cancel' }),
299
+ ];
300
+ }
301
+ export const FLOWS = [stop, start, zip, calendarPrompt, when, offer, slot, find, booking, prepare, execute, present];
@@ -75,6 +75,14 @@ export namespace STANDARD_FUNCTIONS {
75
75
  export { yesNoKeys };
76
76
  export { channelVerb };
77
77
  export { dateToWords };
78
+ export { hoursPhrase };
79
+ export { scheduleOpenNow };
80
+ export { zipCovered };
81
+ export { readWhen };
82
+ export { openSlots };
83
+ export { slotToWords };
84
+ export { todayIn };
85
+ export { minutesUntil };
78
86
  export { amountToSpeech };
79
87
  export { phoneToSpeech };
80
88
  export { validateCardNumber };
@@ -232,6 +240,15 @@ import { sorryNotCaught } from './phrases.js';
232
240
  import { yesNoKeys } from './phrases.js';
233
241
  import { channelVerb } from './phrases.js';
234
242
  import { dateToWords } from './date-words.js';
243
+ import { agentHoursText } from './schedule.js';
244
+ import { hoursPhrase } from './schedule.js';
245
+ import { scheduleOpenNow } from './schedule.js';
246
+ import { zipCovered } from './schedule.js';
247
+ import { readWhen } from './schedule.js';
248
+ import { openSlots } from './schedule.js';
249
+ import { slotToWords } from './schedule.js';
250
+ import { todayIn } from './schedule.js';
251
+ import { minutesUntil } from './schedule.js';
235
252
  import { amountToSpeech } from './amount-to-speech.js';
236
253
  import { phoneToSpeech } from './phone-to-speech.js';
237
254
  import { validateCardNumber } from './card-checks.js';
@@ -317,5 +334,5 @@ import { chatTranscript } from './sendables.js';
317
334
  import { conversationCopy } from './sendables.js';
318
335
  import { CONVERSATION_KEY } from './sendables.js';
319
336
  import { WEB_LINK_KEY } from './sendables.js';
320
- export { continuationSafetyProtocol, cancelFormTask, contextualResponseProtocol, validateFormResponse, hasFormResponse, formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, retireStaleFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation, formProposalProtocol, validateFormProposalPolicy, validateFormProposalDescriptor, formProposalDescriptor, clearFormMisses, formNoOwner, missFormInput, formMustComplete, formInputPrompt, formUserDescriptionSource, formConcernLine, formAcknowledges, consumeFormFeedback, keepFormLine, deferFormClarification, takeFormClarification, formClarificationKept, clearFormLines, formConversationOutcome, readMoneyAmount, isMoneyAmount, moneyIntentAllows, isPastPaymentStatement, isPartialMoneyAnswer, validateMoneyOptions, takeChoiceOffer, saysConfirmWord, saysNoValue, confirmOutOfOrderLine, matchesChoice, ANSWER_WORDS, CONFIRM_WORDS, isAnswer, isAgentRequest, isExitRequest, isGlobalExit, isOtherRequest, isSpelledFragment, isAmountAnswer, amountInAnswer, pickChoice, pickWholeChoice, withoutPromptEcho, isReaderFiller, readEmail, emailWithoutEnding, emailEnding, emailSaid, readPhone, readInternationalPhone, readIdentifier, last4, maskEmail, callerTextNumber, textDestination, callerIsInternational, normalizeAndFindCapture, anythingElse, goodbye, sayName, sorryNotCaught, yesNoKeys, channelVerb, dateToWords, amountToSpeech, phoneToSpeech, validateCardNumber, validateExpiration, consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFormAction, confirmFormRevision, prepareFormAction, actionConfirmationValid, beginFormAction, finishFormAction, actionGateVerified, sourceNeedsLoad, beginSourceRefresh, completeSourceRefresh, pickProviderQuestion, matchInputs, readFormAnswer, readArgument, groundAmount, joinSpokenNumbers, findNumbers, assignNumbers, addressDraft, readInputProfile, formAcceptanceTrace, resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, formInputChain, openFormInstance, validateFormIncompleteOutcome, formIncompleteOutcome, validateFormExhaustion, exhaustFormInput, formInitialReadings, orderFormReadings, proposedFormValues, applyFormValidation, formReadingDependencies, exclusiveFormReadings, enrichFormMatches, expandFormActivations, settleFormActivations, rememberFormArguments, resetFormInputs, hasFormValue, formPath, formValuesEqual, formReadingReady, formReadingRelevant, formPreparation, queueFormReadings, pendingFormReadings, formWorkLimit, answerResetsFormReplays, rejectFormReadings, invalidateFormInputs, acceptFormReadings, formInstanceApplies, formParentResume, closeFormInstance, checkOtp, clearOtp, maskDestination, validateOTP, OTP_EXPIRY_MS, validateDigits, validatePhone, validateEmail, urlToSpeech, textWithUrlToSpeech, joinSpokenDigits, spokenDigitsText, wholeSpokenNumber, numberAlone, registerSendable, sendables, chatTranscript, conversationCopy, CONVERSATION_KEY, WEB_LINK_KEY };
337
+ export { continuationSafetyProtocol, cancelFormTask, contextualResponseProtocol, validateFormResponse, hasFormResponse, formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, retireStaleFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation, formProposalProtocol, validateFormProposalPolicy, validateFormProposalDescriptor, formProposalDescriptor, clearFormMisses, formNoOwner, missFormInput, formMustComplete, formInputPrompt, formUserDescriptionSource, formConcernLine, formAcknowledges, consumeFormFeedback, keepFormLine, deferFormClarification, takeFormClarification, formClarificationKept, clearFormLines, formConversationOutcome, readMoneyAmount, isMoneyAmount, moneyIntentAllows, isPastPaymentStatement, isPartialMoneyAnswer, validateMoneyOptions, takeChoiceOffer, saysConfirmWord, saysNoValue, confirmOutOfOrderLine, matchesChoice, ANSWER_WORDS, CONFIRM_WORDS, isAnswer, isAgentRequest, isExitRequest, isGlobalExit, isOtherRequest, isSpelledFragment, isAmountAnswer, amountInAnswer, pickChoice, pickWholeChoice, withoutPromptEcho, isReaderFiller, readEmail, emailWithoutEnding, emailEnding, emailSaid, readPhone, readInternationalPhone, readIdentifier, last4, maskEmail, callerTextNumber, textDestination, callerIsInternational, normalizeAndFindCapture, anythingElse, goodbye, sayName, sorryNotCaught, yesNoKeys, channelVerb, dateToWords, agentHoursText, hoursPhrase, scheduleOpenNow, zipCovered, readWhen, openSlots, slotToWords, todayIn, minutesUntil, amountToSpeech, phoneToSpeech, validateCardNumber, validateExpiration, consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFormAction, confirmFormRevision, prepareFormAction, actionConfirmationValid, beginFormAction, finishFormAction, actionGateVerified, sourceNeedsLoad, beginSourceRefresh, completeSourceRefresh, pickProviderQuestion, matchInputs, readFormAnswer, readArgument, groundAmount, joinSpokenNumbers, findNumbers, assignNumbers, addressDraft, readInputProfile, formAcceptanceTrace, resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, formInputChain, openFormInstance, validateFormIncompleteOutcome, formIncompleteOutcome, validateFormExhaustion, exhaustFormInput, formInitialReadings, orderFormReadings, proposedFormValues, applyFormValidation, formReadingDependencies, exclusiveFormReadings, enrichFormMatches, expandFormActivations, settleFormActivations, rememberFormArguments, resetFormInputs, hasFormValue, formPath, formValuesEqual, formReadingReady, formReadingRelevant, formPreparation, queueFormReadings, pendingFormReadings, formWorkLimit, answerResetsFormReplays, rejectFormReadings, invalidateFormInputs, acceptFormReadings, formInstanceApplies, formParentResume, closeFormInstance, checkOtp, clearOtp, maskDestination, validateOTP, OTP_EXPIRY_MS, validateDigits, validatePhone, validateEmail, urlToSpeech, textWithUrlToSpeech, joinSpokenDigits, spokenDigitsText, wholeSpokenNumber, numberAlone, registerSendable, sendables, chatTranscript, conversationCopy, CONVERSATION_KEY, WEB_LINK_KEY };
321
338
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/helpers/index.js"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/helpers/index.js"],"names":[],"mappings":"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"}
@@ -10,7 +10,7 @@ import { consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFo
10
10
  /**
11
11
  * jsfe/helpers — the functions JSFE's system flows call from expressions, in ONE place for every host: reading an
12
12
  * answer (matchesChoice, pickChoice, isAnswer, readEmail, readIdentifier, amountInAnswer, matchInputs …), saying
13
- * values (amountToSpeech, phoneToSpeech, dateToWords, last4, urlToSpeech …), checking shapes and one-time codes. Pure: no credentials,
13
+ * values (amountToSpeech, phoneToSpeech, dateToWords, last4, urlToSpeech …), schedules and appointment times, checking shapes and one-time codes. Pure: no credentials,
14
14
  * no network, no host state beyond the container a caller passes in.
15
15
  *
16
16
  * The engine does not register them by itself. A host lists them among its approved functions, usually all at once:
@@ -29,6 +29,7 @@ import { readEmail, emailWithoutEnding, emailEnding, emailSaid, readPhone, readI
29
29
  import { normalizeAndFindCapture } from './capture.js';
30
30
  import { anythingElse, goodbye, sayName, sorryNotCaught, yesNoKeys, channelVerb } from './phrases.js';
31
31
  import { dateToWords } from './date-words.js';
32
+ import { agentHoursText, hoursPhrase, scheduleOpenNow, zipCovered, readWhen, openSlots, slotToWords, todayIn, minutesUntil } from './schedule.js';
32
33
  import { amountToSpeech } from './amount-to-speech.js';
33
34
  import { validateCardNumber, validateExpiration } from './card-checks.js';
34
35
  import { matchInputs, readFormAnswer, readArgument, groundAmount, saysConfirmWord, saysNoValue, confirmOutOfOrderLine, readInputProfile, formAcceptanceTrace } from './match-inputs.js';
@@ -40,7 +41,7 @@ import { findNumbers, assignNumbers, joinSpokenNumbers } from './numbers.js';
40
41
  import { addressDraft } from './address.js';
41
42
  import { urlToSpeech, textWithUrlToSpeech } from './url-speech.js';
42
43
  import { phoneToSpeech } from './phone-to-speech.js';
43
- export { continuationSafetyProtocol, cancelFormTask, contextualResponseProtocol, validateFormResponse, hasFormResponse, formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, retireStaleFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation, formProposalProtocol, validateFormProposalPolicy, validateFormProposalDescriptor, formProposalDescriptor, clearFormMisses, formNoOwner, missFormInput, formMustComplete, formInputPrompt, formUserDescriptionSource, formConcernLine, formAcknowledges, consumeFormFeedback, keepFormLine, deferFormClarification, takeFormClarification, formClarificationKept, clearFormLines, formConversationOutcome, readMoneyAmount, isMoneyAmount, moneyIntentAllows, isPastPaymentStatement, isPartialMoneyAnswer, validateMoneyOptions, takeChoiceOffer, saysConfirmWord, saysNoValue, confirmOutOfOrderLine, matchesChoice, ANSWER_WORDS, CONFIRM_WORDS, isAnswer, isAgentRequest, isExitRequest, isGlobalExit, isOtherRequest, isSpelledFragment, isAmountAnswer, amountInAnswer, pickChoice, pickWholeChoice, withoutPromptEcho, isReaderFiller, readEmail, emailWithoutEnding, emailEnding, emailSaid, readPhone, readInternationalPhone, readIdentifier, last4, maskEmail, callerTextNumber, textDestination, callerIsInternational, normalizeAndFindCapture, anythingElse, goodbye, sayName, sorryNotCaught, yesNoKeys, channelVerb, dateToWords, amountToSpeech, phoneToSpeech, validateCardNumber, validateExpiration, consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFormAction, confirmFormRevision, prepareFormAction, actionConfirmationValid, beginFormAction, finishFormAction, actionGateVerified, sourceNeedsLoad, beginSourceRefresh, completeSourceRefresh, pickProviderQuestion, matchInputs, readFormAnswer, readArgument, groundAmount, joinSpokenNumbers, findNumbers, assignNumbers, addressDraft, readInputProfile, formAcceptanceTrace, resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, formInputChain, openFormInstance, validateFormIncompleteOutcome, formIncompleteOutcome, validateFormExhaustion, exhaustFormInput, formInitialReadings, orderFormReadings, proposedFormValues, applyFormValidation, formReadingDependencies, exclusiveFormReadings, enrichFormMatches, expandFormActivations, settleFormActivations, rememberFormArguments, resetFormInputs, hasFormValue, formPath, formValuesEqual, formReadingReady, formReadingRelevant, formPreparation, queueFormReadings, pendingFormReadings, formWorkLimit, answerResetsFormReplays, rejectFormReadings, invalidateFormInputs, acceptFormReadings, formInstanceApplies, formParentResume, closeFormInstance, checkOtp, clearOtp, maskDestination, validateOTP, OTP_EXPIRY_MS, validateDigits, validatePhone, validateEmail, urlToSpeech, textWithUrlToSpeech, joinSpokenDigits, spokenDigitsText, wholeSpokenNumber, numberAlone, registerSendable, sendables, chatTranscript, conversationCopy, CONVERSATION_KEY, WEB_LINK_KEY, };
44
+ export { continuationSafetyProtocol, cancelFormTask, contextualResponseProtocol, validateFormResponse, hasFormResponse, formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, retireStaleFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation, formProposalProtocol, validateFormProposalPolicy, validateFormProposalDescriptor, formProposalDescriptor, clearFormMisses, formNoOwner, missFormInput, formMustComplete, formInputPrompt, formUserDescriptionSource, formConcernLine, formAcknowledges, consumeFormFeedback, keepFormLine, deferFormClarification, takeFormClarification, formClarificationKept, clearFormLines, formConversationOutcome, readMoneyAmount, isMoneyAmount, moneyIntentAllows, isPastPaymentStatement, isPartialMoneyAnswer, validateMoneyOptions, takeChoiceOffer, saysConfirmWord, saysNoValue, confirmOutOfOrderLine, matchesChoice, ANSWER_WORDS, CONFIRM_WORDS, isAnswer, isAgentRequest, isExitRequest, isGlobalExit, isOtherRequest, isSpelledFragment, isAmountAnswer, amountInAnswer, pickChoice, pickWholeChoice, withoutPromptEcho, isReaderFiller, readEmail, emailWithoutEnding, emailEnding, emailSaid, readPhone, readInternationalPhone, readIdentifier, last4, maskEmail, callerTextNumber, textDestination, callerIsInternational, normalizeAndFindCapture, anythingElse, goodbye, sayName, sorryNotCaught, yesNoKeys, channelVerb, dateToWords, agentHoursText, hoursPhrase, scheduleOpenNow, zipCovered, readWhen, openSlots, slotToWords, todayIn, minutesUntil, amountToSpeech, phoneToSpeech, validateCardNumber, validateExpiration, consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFormAction, confirmFormRevision, prepareFormAction, actionConfirmationValid, beginFormAction, finishFormAction, actionGateVerified, sourceNeedsLoad, beginSourceRefresh, completeSourceRefresh, pickProviderQuestion, matchInputs, readFormAnswer, readArgument, groundAmount, joinSpokenNumbers, findNumbers, assignNumbers, addressDraft, readInputProfile, formAcceptanceTrace, resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, formInputChain, openFormInstance, validateFormIncompleteOutcome, formIncompleteOutcome, validateFormExhaustion, exhaustFormInput, formInitialReadings, orderFormReadings, proposedFormValues, applyFormValidation, formReadingDependencies, exclusiveFormReadings, enrichFormMatches, expandFormActivations, settleFormActivations, rememberFormArguments, resetFormInputs, hasFormValue, formPath, formValuesEqual, formReadingReady, formReadingRelevant, formPreparation, queueFormReadings, pendingFormReadings, formWorkLimit, answerResetsFormReplays, rejectFormReadings, invalidateFormInputs, acceptFormReadings, formInstanceApplies, formParentResume, closeFormInstance, checkOtp, clearOtp, maskDestination, validateOTP, OTP_EXPIRY_MS, validateDigits, validatePhone, validateEmail, urlToSpeech, textWithUrlToSpeech, joinSpokenDigits, spokenDigitsText, wholeSpokenNumber, numberAlone, registerSendable, sendables, chatTranscript, conversationCopy, CONVERSATION_KEY, WEB_LINK_KEY, };
44
45
  /** The functions flows call by name, ready to spread into a host's approved functions. */
45
46
  export const STANDARD_FUNCTIONS = {
46
47
  continuationSafetyProtocol, cancelFormTask, contextualResponseProtocol, validateFormResponse, hasFormResponse,
@@ -48,7 +49,7 @@ export const STANDARD_FUNCTIONS = {
48
49
  clearFormMisses, formNoOwner, missFormInput, formMustComplete, formInputPrompt, formUserDescriptionSource, formConcernLine, formAcknowledges, consumeFormFeedback, keepFormLine, deferFormClarification, takeFormClarification, formClarificationKept, clearFormLines, formConversationOutcome,
49
50
  readMoneyAmount, isMoneyAmount, moneyIntentAllows, isPastPaymentStatement, isPartialMoneyAnswer, validateMoneyOptions, takeChoiceOffer, saysConfirmWord, confirmOutOfOrderLine, matchesChoice, isAnswer, isAgentRequest, isExitRequest, isGlobalExit, isOtherRequest, isSpelledFragment, isAmountAnswer, amountInAnswer, pickChoice, pickWholeChoice, withoutPromptEcho, isReaderFiller,
50
51
  readEmail, emailWithoutEnding, emailEnding, emailSaid, readPhone, readInternationalPhone, readIdentifier, last4, maskEmail, callerTextNumber, textDestination, callerIsInternational,
51
- normalizeAndFindCapture, anythingElse, goodbye, sayName, sorryNotCaught, yesNoKeys, channelVerb, dateToWords, amountToSpeech, phoneToSpeech, validateCardNumber, validateExpiration, consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFormAction, confirmFormRevision, prepareFormAction, actionConfirmationValid, beginFormAction, finishFormAction, actionGateVerified, sourceNeedsLoad, beginSourceRefresh, completeSourceRefresh, pickProviderQuestion, matchInputs, readFormAnswer, readArgument, groundAmount, joinSpokenNumbers, findNumbers, assignNumbers, addressDraft, readInputProfile, formAcceptanceTrace, resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, formInputChain, openFormInstance, validateFormIncompleteOutcome, formIncompleteOutcome, validateFormExhaustion, exhaustFormInput, formInitialReadings, orderFormReadings, proposedFormValues, applyFormValidation, formReadingDependencies, exclusiveFormReadings, enrichFormMatches, expandFormActivations, settleFormActivations, rememberFormArguments, resetFormInputs, hasFormValue, formPath, formValuesEqual, formReadingReady, formReadingRelevant, formPreparation, queueFormReadings, pendingFormReadings, formWorkLimit, answerResetsFormReplays, rejectFormReadings, invalidateFormInputs, acceptFormReadings, formInstanceApplies, formParentResume, closeFormInstance,
52
+ normalizeAndFindCapture, anythingElse, goodbye, sayName, sorryNotCaught, yesNoKeys, channelVerb, dateToWords, hoursPhrase, scheduleOpenNow, zipCovered, readWhen, openSlots, slotToWords, todayIn, minutesUntil, amountToSpeech, phoneToSpeech, validateCardNumber, validateExpiration, consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFormAction, confirmFormRevision, prepareFormAction, actionConfirmationValid, beginFormAction, finishFormAction, actionGateVerified, sourceNeedsLoad, beginSourceRefresh, completeSourceRefresh, pickProviderQuestion, matchInputs, readFormAnswer, readArgument, groundAmount, joinSpokenNumbers, findNumbers, assignNumbers, addressDraft, readInputProfile, formAcceptanceTrace, resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, formInputChain, openFormInstance, validateFormIncompleteOutcome, formIncompleteOutcome, validateFormExhaustion, exhaustFormInput, formInitialReadings, orderFormReadings, proposedFormValues, applyFormValidation, formReadingDependencies, exclusiveFormReadings, enrichFormMatches, expandFormActivations, settleFormActivations, rememberFormArguments, resetFormInputs, hasFormValue, formPath, formValuesEqual, formReadingReady, formReadingRelevant, formPreparation, queueFormReadings, pendingFormReadings, formWorkLimit, answerResetsFormReplays, rejectFormReadings, invalidateFormInputs, acceptFormReadings, formInstanceApplies, formParentResume, closeFormInstance,
52
53
  validateOTP, validateDigits, validatePhone, validateEmail, urlToSpeech, textWithUrlToSpeech, joinSpokenDigits, wholeSpokenNumber, numberAlone,
53
54
  registerSendable, sendables, chatTranscript, conversationCopy,
54
55
  };
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The live agent's hours as one spoken sentence, or '' when there are no hours.
3
+ * → "Our agents are available Monday through Friday 9 AM to 7 PM, and Saturday 9 AM to 3 PM, Pacific time."
4
+ */
5
+ export function agentHoursText(schedule: any, lang?: string): string;
6
+ /**
7
+ * Hours as a phrase that follows a number ("…at 1-800-440-0544, every day from 9 AM to 5 PM, Pacific time."), or ''
8
+ * when there are none (always open). Seven days alike read "every day".
9
+ */
10
+ export function hoursPhrase(schedule: any, lang?: string): string;
11
+ /**
12
+ * Is a schedule open at `now`? The rule for the live agent's agentSchedule and every transfer department's schedule:
13
+ * - no schedule (or no range on any day) → always open
14
+ * - otherwise open only when `now`, in schedule.timezone (UTC when unset), falls inside one of that day's [open, close)
15
+ * A schedule that cannot be evaluated (an unknown zone) counts as open; `onError(tz, error)` is told.
16
+ */
17
+ export function scheduleOpenNow(schedule: any, now?: Date, onError?: () => void): boolean;
18
+ /**
19
+ * Does a calendar's zip list cover `zip`? Entries are a zip ('91325'), a prefix with x's ('913xx') or a range
20
+ * ('91301-91311'). No list covers everywhere; no zip given is covered (nothing to filter by).
21
+ */
22
+ export function zipCovered(zips: any, zip: any): boolean;
23
+ /**
24
+ * What a customer said about when, as a constraint for openSlots, or null when nothing in it is a time.
25
+ * readWhen('Saturday morning', { now, timezone }) → { dates: ['2026-12-12'], from: '00:00', to: '12:00' }
26
+ * English and Spanish: today, tomorrow, weekday names (plural = every one), this/next week, weekend, weekdays, a date
27
+ * ("the 12th", "Dec 12", "12 de diciembre", "12/12"), morning/afternoon/evening, at/after/before/between a time,
28
+ * later ({ later: true }: after the times already offered) and any time ({ any: true }). Dates run `days` ahead (60).
29
+ */
30
+ export function readWhen(text: any, { now, timezone, days }?: {
31
+ now?: number | undefined;
32
+ timezone?: string | undefined;
33
+ days?: number | undefined;
34
+ }): {
35
+ from: any;
36
+ to: any;
37
+ at: string | null;
38
+ later: boolean;
39
+ any: boolean;
40
+ } | null;
41
+ /**
42
+ * Up to `count` open times, earliest first, as [{ key, calendar, date, start, end, from, to, label, label_es }]
43
+ * (start/end ISO; from/to wall time in the zone; label for a button or a list).
44
+ *
45
+ * hours the business schedule; a calendar with its own `schedule` uses that instead
46
+ * calendars [{ key, name?, schedule?, zips?, skills? }]; none = one unnamed calendar
47
+ * service { length, buffer?, time: 'exact' | 'window', step? (exact, default 30), windows? [{open, close}] (window),
48
+ * per? (jobs per window per calendar, default 1), avail: 'check' | 'accept', notice? (minutes),
49
+ * ahead? (days, default 30), skill? }
50
+ * busy [{ calendar, start, end }] existing bookings (ignored when avail is 'accept')
51
+ * preference readWhen's result, plus notBefore (epoch or ISO) for "later"
52
+ * zip, calendar the customer's zip; the calendar they picked
53
+ * A slot fits a preference when it starts inside its dates and from/to (a window when it overlaps from/to). The first
54
+ * calendar (in the order given) with room takes the slot; a time two calendars share is offered once.
55
+ */
56
+ export function openSlots({ hours, calendars, service, busy, preference, now, zip, calendar, count }?: {
57
+ busy?: never[] | undefined;
58
+ preference?: null | undefined;
59
+ now?: number | undefined;
60
+ zip?: string | undefined;
61
+ calendar?: string | undefined;
62
+ count?: number | undefined;
63
+ }): {
64
+ key: string;
65
+ calendar: any;
66
+ date: string;
67
+ start: string;
68
+ end: string;
69
+ from: string;
70
+ to: string;
71
+ window: boolean;
72
+ }[];
73
+ /**
74
+ * A slot in words: "tomorrow at 9:15 AM", "Tuesday, December 8, between 8 AM and 12 PM" / "mañana a las 9:15", "el
75
+ * martes 8 de diciembre entre las 8:00 y las 12:00". `today` ('YYYY-MM-DD') turns today and tomorrow into words.
76
+ */
77
+ export function slotToWords(slot: any, lang?: string, today?: string): string;
78
+ /** Today's date in `timezone` ('YYYY-MM-DD'), the `today` slotToWords takes; '' for an unknown zone. */
79
+ export function todayIn(timezone?: string, now?: number): string;
80
+ /** Whole minutes from `now` until `time` (ISO or epoch), negative once it has passed: a change cutoff. */
81
+ export function minutesUntil(time: any, now?: number): number;
82
+ //# sourceMappingURL=schedule.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schedule.d.ts","sourceRoot":"","sources":["../../src/helpers/schedule.js"],"names":[],"mappings":"AAkGA;;;GAGG;AACH,qEAaC;AAED;;;GAGG;AACH,kEAaC;AAuCD;;;;;GAKG;AACH,0FAeC;AAID;;;GAGG;AACH,yDAiBC;AAyCD;;;;;;GAMG;AACH;;;;;;;;;;SA4JC;AAID;;;;;;;;;;;;;;GAcG;AACH;;;;;;;;;;;;;;;;IAgFC;AAED;;;GAGG;AACH,8EAgBC;AAED,wGAAwG;AACxG,iEAMC;AAED,0GAA0G;AAC1G,8DAEC"}
@@ -0,0 +1,606 @@
1
+ /**
2
+ * Schedules and appointment times (APPROVED_FUNCTIONS scheduleOpenNow, hoursPhrase, agentHoursText, readWhen, todayIn, minutesUntil,
3
+ * openSlots, slotToWords, zipCovered). ONE place for what "open" means, so the live agent, a transfer department and a
4
+ * booking can never disagree.
5
+ *
6
+ * A schedule is the shape the User Admin hours editor saves: { timezone, hours: { mon: [{ open: 'HH:MM', close:
7
+ * 'HH:MM' }], … } }. No schedule, or no range on any day, means always open.
8
+ *
9
+ * Pure: no credentials, no network. Times cross the sandbox as ISO strings or epoch milliseconds, never Date objects.
10
+ * Part of jsfe/helpers; zero imports.
11
+ */
12
+ const DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
13
+ const DAY_NAMES = {
14
+ en: { mon: 'Monday', tue: 'Tuesday', wed: 'Wednesday', thu: 'Thursday', fri: 'Friday', sat: 'Saturday', sun: 'Sunday' },
15
+ es: { mon: 'lunes', tue: 'martes', wed: 'miércoles', thu: 'jueves', fri: 'viernes', sat: 'sábado', sun: 'domingo' },
16
+ };
17
+ const MONTH_NAMES = {
18
+ en: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
19
+ es: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'],
20
+ };
21
+ // Spoken zone names for the zones a schedule is set in; any other zone is not named.
22
+ const ZONES = {
23
+ 'America/Los_Angeles': { en: 'Pacific time', es: 'hora del Pacífico' },
24
+ 'America/Denver': { en: 'Mountain time', es: 'hora de la Montaña' },
25
+ 'America/Phoenix': { en: 'Arizona time', es: 'hora de Arizona' },
26
+ 'America/Chicago': { en: 'Central time', es: 'hora del Centro' },
27
+ 'America/New_York': { en: 'Eastern time', es: 'hora del Este' },
28
+ };
29
+ const HHMM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
30
+ const MINUTE = 60000;
31
+ const DAY_MS = 86400000;
32
+ function validRanges(ranges) {
33
+ return (Array.isArray(ranges) ? ranges : []).filter((r) => r && HHMM.test(r.open || '') && HHMM.test(r.close || ''));
34
+ }
35
+ const minutesOf = (hhmm) => { const [h, m] = hhmm.split(':').map(Number); return h * 60 + m; };
36
+ const hhmmOf = (minutes) => `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
37
+ // "9 AM", "9:30 AM", "12 PM" in English; "9:00", "19:00" in Spanish (read naturally by every TTS voice).
38
+ function clock(hhmm, lang) {
39
+ const [h, m] = hhmm.split(':').map(Number);
40
+ if (lang === 'es') {
41
+ return `${h}:${String(m).padStart(2, '0')}`;
42
+ }
43
+ else {
44
+ const h12 = h % 12 === 0 ? 12 : h % 12;
45
+ return `${h12}${m ? `:${String(m).padStart(2, '0')}` : ''} ${h < 12 ? 'AM' : 'PM'}`;
46
+ }
47
+ }
48
+ function rangesText(ranges, lang) {
49
+ const parts = ranges.map((r) => (lang === 'es' ? `de ${clock(r.open, lang)} a ${clock(r.close, lang)}` : `${clock(r.open, lang)} to ${clock(r.close, lang)}`));
50
+ return joinList(parts, lang);
51
+ }
52
+ function joinList(items, lang) {
53
+ const and = lang === 'es' ? 'y' : 'and';
54
+ if (items.length <= 1) {
55
+ return items.join('');
56
+ }
57
+ else if (items.length === 2) {
58
+ return `${items[0]} ${and} ${items[1]}`;
59
+ }
60
+ else {
61
+ return `${items.slice(0, -1).join(', ')}, ${and} ${items[items.length - 1]}`;
62
+ }
63
+ }
64
+ function daysText(days, lang) {
65
+ const names = DAY_NAMES[lang];
66
+ if (days.length === 1) {
67
+ return names[days[0]];
68
+ }
69
+ else if (days.length === 2) {
70
+ return `${names[days[0]]} ${lang === 'es' ? 'y' : 'and'} ${names[days[1]]}`;
71
+ }
72
+ else {
73
+ return lang === 'es' ? `de ${names[days[0]]} a ${names[days.at(-1)]}` : `${names[days[0]]} through ${names[days.at(-1)]}`;
74
+ }
75
+ }
76
+ // Runs of consecutive open days with identical ranges; a closed day is null and breaks a run.
77
+ function dayGroups(schedule) {
78
+ const hours = schedule && typeof schedule.hours === 'object' && schedule.hours ? schedule.hours : {};
79
+ const groups = [];
80
+ for (const day of DAYS) {
81
+ const ranges = validRanges(hours[day]);
82
+ const key = JSON.stringify(ranges.map((r) => [r.open, r.close]));
83
+ const last = groups.at(-1);
84
+ if (!ranges.length) {
85
+ groups.push(null);
86
+ }
87
+ else if (last && last.key === key && last.days.at(-1) === DAYS[DAYS.indexOf(day) - 1]) {
88
+ last.days.push(day);
89
+ }
90
+ else {
91
+ groups.push({ key, days: [day], ranges });
92
+ }
93
+ }
94
+ return groups.filter(Boolean);
95
+ }
96
+ /**
97
+ * The live agent's hours as one spoken sentence, or '' when there are no hours.
98
+ * → "Our agents are available Monday through Friday 9 AM to 7 PM, and Saturday 9 AM to 3 PM, Pacific time."
99
+ */
100
+ export function agentHoursText(schedule, lang = 'en') {
101
+ const L = lang === 'es' ? 'es' : 'en';
102
+ const open = dayGroups(schedule);
103
+ if (!open.length) {
104
+ return '';
105
+ }
106
+ else {
107
+ const spans = open.map((g) => `${daysText(g.days, L)} ${rangesText(g.ranges, L)}`);
108
+ const zone = ZONES[schedule.timezone]?.[L];
109
+ const list = joinList(spans, L);
110
+ return L === 'es'
111
+ ? `Nuestros agentes están disponibles ${list}${zone ? `, ${zone}` : ''}.`
112
+ : `Our agents are available ${list}${zone ? `, ${zone}` : ''}.`;
113
+ }
114
+ }
115
+ /**
116
+ * Hours as a phrase that follows a number ("…at 1-800-440-0544, every day from 9 AM to 5 PM, Pacific time."), or ''
117
+ * when there are none (always open). Seven days alike read "every day".
118
+ */
119
+ export function hoursPhrase(schedule, lang = 'en') {
120
+ const L = lang === 'es' ? 'es' : 'en';
121
+ const open = dayGroups(schedule);
122
+ if (!open.length) {
123
+ return '';
124
+ }
125
+ else {
126
+ const spans = open.map((g) => {
127
+ const days = g.days.length === 7 ? (L === 'es' ? 'todos los días' : 'every day') : daysText(g.days, L);
128
+ return L === 'es' ? `${days} ${rangesText(g.ranges, L)}` : `${days} from ${rangesText(g.ranges, L)}`;
129
+ });
130
+ const zone = ZONES[schedule.timezone]?.[L];
131
+ return `${joinList(spans, L)}${zone ? `, ${zone}` : ''}`;
132
+ }
133
+ }
134
+ // ---- time zones: wall time <-> epoch, through Intl only ----
135
+ const formatters = new Map();
136
+ function zoneFormatter(tz) {
137
+ if (!formatters.has(tz)) {
138
+ formatters.set(tz, new Intl.DateTimeFormat('en-US', { timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short' }));
139
+ }
140
+ else {
141
+ // cached
142
+ }
143
+ return formatters.get(tz);
144
+ }
145
+ /** The wall clock in `tz` at `epoch`: { date: 'YYYY-MM-DD', minutes, day: 'mon'… }. Throws on an unknown zone. */
146
+ function wallClock(epoch, tz) {
147
+ const parts = Object.fromEntries(zoneFormatter(tz).formatToParts(new Date(epoch)).map((p) => [p.type, p.value]));
148
+ const hour = parseInt(parts.hour, 10) % 24;
149
+ return { date: `${parts.year}-${parts.month}-${parts.day}`, minutes: hour * 60 + parseInt(parts.minute, 10), day: String(parts.weekday).toLowerCase() };
150
+ }
151
+ /** The epoch of wall time `date` + `minutes` in `tz`. A time a daylight-saving change skips lands an hour later. */
152
+ function epochOf(date, minutes, tz) {
153
+ const [y, m, d] = date.split('-').map(Number);
154
+ const guess = Date.UTC(y, m - 1, d) + minutes * MINUTE;
155
+ const offsetAt = (epoch) => {
156
+ const w = wallClock(epoch, tz);
157
+ const [wy, wm, wd] = w.date.split('-').map(Number);
158
+ return Date.UTC(wy, wm - 1, wd) + w.minutes * MINUTE - epoch;
159
+ };
160
+ const first = guess - offsetAt(guess);
161
+ const second = guess - offsetAt(first);
162
+ return second;
163
+ }
164
+ const addDays = (date, n) => new Date(Date.parse(`${date}T00:00:00Z`) + n * DAY_MS).toISOString().slice(0, 10);
165
+ const dayOf = (date) => DAYS[(new Date(`${date}T00:00:00Z`).getUTCDay() + 6) % 7];
166
+ const toEpoch = (t) => (typeof t === 'number' ? t : Date.parse(String(t ?? '')));
167
+ /**
168
+ * Is a schedule open at `now`? The rule for the live agent's agentSchedule and every transfer department's schedule:
169
+ * - no schedule (or no range on any day) → always open
170
+ * - otherwise open only when `now`, in schedule.timezone (UTC when unset), falls inside one of that day's [open, close)
171
+ * A schedule that cannot be evaluated (an unknown zone) counts as open; `onError(tz, error)` is told.
172
+ */
173
+ export function scheduleOpenNow(schedule, now = new Date(), onError = () => { }) {
174
+ if (!schedule || !schedule.hours || typeof schedule.hours !== 'object') {
175
+ return true;
176
+ }
177
+ else if (!DAYS.some((d) => Array.isArray(schedule.hours[d]) && schedule.hours[d].some((r) => r && r.open && r.close))) {
178
+ return true;
179
+ }
180
+ else {
181
+ const tz = schedule.timezone || 'UTC';
182
+ try {
183
+ const w = wallClock(now instanceof Date ? now.getTime() : toEpoch(now), tz);
184
+ return validRanges(schedule.hours[w.day]).some((r) => w.minutes >= minutesOf(r.open) && w.minutes < minutesOf(r.close));
185
+ }
186
+ catch (error) {
187
+ onError(tz, error);
188
+ return true;
189
+ }
190
+ }
191
+ }
192
+ // ---- service areas ----
193
+ /**
194
+ * Does a calendar's zip list cover `zip`? Entries are a zip ('91325'), a prefix with x's ('913xx') or a range
195
+ * ('91301-91311'). No list covers everywhere; no zip given is covered (nothing to filter by).
196
+ */
197
+ export function zipCovered(zips, zip) {
198
+ const z = String(zip ?? '').trim().slice(0, 5);
199
+ const list = (Array.isArray(zips) ? zips : []).map((e) => String(e ?? '').trim().toLowerCase()).filter(Boolean);
200
+ if (!list.length || !/^\d{5}$/.test(z)) {
201
+ return true;
202
+ }
203
+ else {
204
+ return list.some((entry) => {
205
+ const range = /^(\d{5})\s*-\s*(\d{5})$/.exec(entry);
206
+ if (range) {
207
+ return z >= range[1] && z <= range[2];
208
+ }
209
+ else if (/^[\dx]{5}$/.test(entry)) {
210
+ return [...entry].every((c, i) => c === 'x' || c === z[i]);
211
+ }
212
+ else {
213
+ return false;
214
+ }
215
+ });
216
+ }
217
+ }
218
+ // ---- reading what a customer says about time ----
219
+ const fold = (s) => String(s ?? '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[.,;!?¡¿]/g, ' ').replace(/\s+/g, ' ').trim();
220
+ const WEEKDAY_WORDS = [
221
+ ['mon', ['monday', 'lunes']], ['tue', ['tuesday', 'tues', 'martes']], ['wed', ['wednesday', 'miercoles']],
222
+ ['thu', ['thursday', 'thurs', 'jueves']], ['fri', ['friday', 'viernes']], ['sat', ['saturday', 'sabado']], ['sun', ['sunday', 'domingo']],
223
+ ];
224
+ const MONTH_WORDS = [
225
+ ['january', 'jan', 'enero'], ['february', 'feb', 'febrero'], ['march', 'mar', 'marzo'], ['april', 'apr', 'abril'],
226
+ ['may', 'mayo'], ['june', 'jun', 'junio'], ['july', 'jul', 'julio'], ['august', 'aug', 'agosto'],
227
+ ['september', 'sept', 'sep', 'septiembre', 'setiembre'], ['october', 'oct', 'octubre'], ['november', 'nov', 'noviembre'], ['december', 'dec', 'diciembre'],
228
+ ];
229
+ const PARTS_OF_DAY = [
230
+ [/\b(?:mornings?|(?:por|en|de) la manana|por las mananas)\b/, ['00:00', '12:00']],
231
+ [/\b(?:afternoons?|(?:por|en|de) la tarde|por las tardes)\b/, ['12:00', '17:00']],
232
+ [/\b(?:evenings?|tonight|(?:por|en|de) la noche|por las noches|esta noche)\b/, ['17:00', '24:00']],
233
+ ];
234
+ // hour, minutes, am/pm, and a Spanish part of day said as the am/pm ("a las 5 de la tarde"), consumed with the time
235
+ const HOUR = '(\\d{1,2})(?::(\\d{2}))?(?:\\s*(am|pm|a m|p m))?(?:\\s+(de la (?:tarde|noche|manana)))?';
236
+ // A time said with a marker: "5", "5pm", "5:30 p.m.", "17:00", "noon". A bare 1-6 is afternoon, 7-11 morning.
237
+ function hourOf(h, m, ampm, part) {
238
+ let hour = parseInt(h, 10);
239
+ const minute = m ? parseInt(m, 10) : 0;
240
+ const mark = ampm ? ampm.replace(' ', '') : (/(tarde|noche)$/.test(part || '') ? 'pm' : (/manana$/.test(part || '') ? 'am' : ''));
241
+ if (hour > 23 || minute > 59) {
242
+ return null;
243
+ }
244
+ else if (mark === 'pm' && hour < 12) {
245
+ hour += 12;
246
+ }
247
+ else if (mark === 'am' && hour === 12) {
248
+ hour = 0;
249
+ }
250
+ else if (!mark && hour >= 1 && hour <= 6) {
251
+ hour += 12;
252
+ }
253
+ else {
254
+ // as said
255
+ }
256
+ return hhmmOf(hour * 60 + minute);
257
+ }
258
+ /**
259
+ * What a customer said about when, as a constraint for openSlots, or null when nothing in it is a time.
260
+ * readWhen('Saturday morning', { now, timezone }) → { dates: ['2026-12-12'], from: '00:00', to: '12:00' }
261
+ * English and Spanish: today, tomorrow, weekday names (plural = every one), this/next week, weekend, weekdays, a date
262
+ * ("the 12th", "Dec 12", "12 de diciembre", "12/12"), morning/afternoon/evening, at/after/before/between a time,
263
+ * later ({ later: true }: after the times already offered) and any time ({ any: true }). Dates run `days` ahead (60).
264
+ */
265
+ export function readWhen(text, { now = Date.now(), timezone = 'UTC', days = 60 } = {}) {
266
+ let t = ` ${fold(text)} `;
267
+ let today;
268
+ try {
269
+ today = wallClock(toEpoch(now), timezone).date;
270
+ }
271
+ catch {
272
+ today = new Date(toEpoch(now)).toISOString().slice(0, 10);
273
+ }
274
+ const span = Math.max(1, Math.min(366, Number(days) || 60));
275
+ const horizon = Array.from({ length: span }, (_, i) => addDays(today, i));
276
+ const out = {};
277
+ const take = (re) => { const m = re.exec(t); if (m) {
278
+ t = t.replace(m[0], ' ');
279
+ }
280
+ else { /* not said */ } return m; };
281
+ const addDates = (list) => { out.dates = [...new Set([...(out.dates || []), ...list])].sort(); };
282
+ // times first, so their words ("de la tarde", "a las 5") are not read as days
283
+ const between = take(new RegExp(`\\b(?:between|entre(?: las?)?|from|de(?: las?)?)\\s+${HOUR}\\s*(?:and|to|until|till|-|y(?: las?)?|a(?: las?)?|hasta(?: las?)?)\\s+${HOUR}`));
284
+ if (between) {
285
+ out.from = hourOf(between[1], between[2], between[3], between[4]);
286
+ out.to = hourOf(between[5], between[6], between[7], between[8]);
287
+ if (out.from && out.to && out.from > out.to && !between[3] && !between[4] && parseInt(between[1], 10) <= 12) {
288
+ out.from = hourOf(between[1], between[2], 'am', ''); // "between 9 and 1": 9 AM to 1 PM
289
+ }
290
+ else {
291
+ // as read
292
+ }
293
+ }
294
+ else {
295
+ // no range said
296
+ }
297
+ const after = take(new RegExp(`\\b(?:after|despues de(?: las?)?|from|starting at|a partir de(?: las?)?)\\s+${HOUR}`));
298
+ if (after) {
299
+ out.from = hourOf(after[1], after[2], after[3], after[4]);
300
+ }
301
+ else {
302
+ // no start said
303
+ }
304
+ const before = take(new RegExp(`\\b(?:before|by|until|antes de(?: las?)?|hasta(?: las?)?)\\s+${HOUR}`));
305
+ if (before) {
306
+ out.to = hourOf(before[1], before[2], before[3], before[4]);
307
+ }
308
+ else {
309
+ // no end said
310
+ }
311
+ if (take(/\b(?:before noon|antes del mediodia)\b/)) {
312
+ out.to = '12:00';
313
+ }
314
+ else if (take(/\b(?:after noon|despues del mediodia)\b/)) {
315
+ out.from = '12:00';
316
+ }
317
+ else {
318
+ // no noon bound
319
+ }
320
+ const at = take(new RegExp(`\\b(?:at|around|a las?|tipo|como a las?)\\s+${HOUR}`)) || take(new RegExp(`\\b(\\d{1,2})(?::(\\d{2}))?\\s*(am|pm|a m|p m)\\b`)) || take(/\b(\d{1,2}):(\d{2})()\b/);
321
+ if (at) {
322
+ out.at = hourOf(at[1], at[2], at[3], at[4]);
323
+ }
324
+ else if (take(/\b(?:at noon|noon|midday|(?:al|a) mediodia|mediodia)\b/)) {
325
+ out.at = '12:00';
326
+ }
327
+ else {
328
+ // no exact time
329
+ }
330
+ for (const [re, [from, to]] of PARTS_OF_DAY) {
331
+ if (take(re)) {
332
+ out.from = out.from && out.from > from ? out.from : from;
333
+ out.to = out.to && out.to < to ? out.to : to;
334
+ }
335
+ else {
336
+ // not this part of the day
337
+ }
338
+ }
339
+ // days
340
+ if (take(/\bpasado manana\b/)) {
341
+ addDates([addDays(today, 2)]);
342
+ }
343
+ else if (take(/\b(?:tomorrow|manana)\b/)) {
344
+ addDates([addDays(today, 1)]);
345
+ }
346
+ else {
347
+ // not tomorrow
348
+ }
349
+ if (take(/\b(?:today|hoy|later today|mas tarde hoy)\b/)) {
350
+ addDates([today]);
351
+ }
352
+ else {
353
+ // not today
354
+ }
355
+ if (take(/\b(?:next week|la semana que viene|la proxima semana|la semana proxima)\b/)) {
356
+ const toMonday = (7 - DAYS.indexOf(dayOf(today))) % 7 || 7;
357
+ addDates(Array.from({ length: 7 }, (_, i) => addDays(today, toMonday + i)));
358
+ }
359
+ else if (take(/\b(?:this week|esta semana)\b/)) {
360
+ addDates(horizon.slice(0, 7 - DAYS.indexOf(dayOf(today))));
361
+ }
362
+ else {
363
+ // no week named
364
+ }
365
+ if (take(/\b(?:weekends|los fines de semana)\b/)) {
366
+ addDates(horizon.filter((d) => ['sat', 'sun'].includes(dayOf(d))));
367
+ }
368
+ else if (take(/\b(?:this weekend|the weekend|weekend|este fin de semana|el fin de semana|fin de semana)\b/)) {
369
+ addDates(horizon.filter((d) => ['sat', 'sun'].includes(dayOf(d))).slice(0, 2));
370
+ }
371
+ else if (take(/\b(?:weekdays|during the week|entre semana)\b/)) {
372
+ addDates(horizon.filter((d) => !['sat', 'sun'].includes(dayOf(d))));
373
+ }
374
+ else {
375
+ // no weekend or weekdays
376
+ }
377
+ for (const [day, words] of WEEKDAY_WORDS) {
378
+ for (const word of words) {
379
+ const plural = take(new RegExp(`\\b(?:${word}s|(?:los|todos los) ${word}s?)\\b`));
380
+ const next = plural ? null : take(new RegExp(`\\b(?:next|el proximo|este proximo) ${word}\\b`));
381
+ const single = plural || next ? null : take(new RegExp(`\\b${word}\\b`));
382
+ const matching = horizon.filter((d) => dayOf(d) === day && !(next && d === today));
383
+ if (plural) {
384
+ addDates(matching);
385
+ }
386
+ else if (next || single) {
387
+ addDates(matching.slice(0, 1));
388
+ }
389
+ else {
390
+ // not this weekday
391
+ }
392
+ }
393
+ }
394
+ // a date: "december 12", "12 de diciembre", "12/12", "the 12th", "el 12"
395
+ const monthIndex = (word) => MONTH_WORDS.findIndex((names) => names.includes(word));
396
+ const resolve = (month, day) => {
397
+ const year = Number(today.slice(0, 4));
398
+ for (const y of [year, year + 1]) {
399
+ const date = `${y}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
400
+ if (date >= today && new Date(`${date}T00:00:00Z`).getUTCDate() === day) {
401
+ return date;
402
+ }
403
+ else {
404
+ // past, or no such day this year
405
+ }
406
+ }
407
+ return null;
408
+ };
409
+ const monthWord = MONTH_WORDS.flat().join('|');
410
+ const md = take(new RegExp(`\\b(${monthWord})\\s+(\\d{1,2})(?:st|nd|rd|th)?\\b`)) || take(new RegExp(`\\b(\\d{1,2})\\s+de\\s+(${monthWord})\\b`));
411
+ const slash = md ? null : take(/\b(\d{1,2})\/(\d{1,2})\b/);
412
+ const nth = md || slash ? null : take(/\b(?:the\s+)?(\d{1,2})(?:st|nd|rd|th)\b|\bel (\d{1,2})\b/);
413
+ if (md) {
414
+ const [month, day] = /^\d/.test(md[1]) ? [monthIndex(md[2]), Number(md[1])] : [monthIndex(md[1]), Number(md[2])];
415
+ const date = resolve(month, day);
416
+ if (date) {
417
+ addDates([date]);
418
+ }
419
+ else { /* no such date */ }
420
+ }
421
+ else if (slash) {
422
+ const date = resolve(Number(slash[1]) - 1, Number(slash[2]));
423
+ if (date) {
424
+ addDates([date]);
425
+ }
426
+ else { /* no such date */ }
427
+ }
428
+ else if (nth) {
429
+ const day = Number(nth[1] || nth[2]);
430
+ const date = horizon.find((d) => Number(d.slice(8)) === day);
431
+ if (date) {
432
+ addDates([date]);
433
+ }
434
+ else { /* not within the horizon */ }
435
+ }
436
+ else {
437
+ // no date
438
+ }
439
+ if (take(/\b(?:later|something later|mas tarde|otro dia|another day|other times?|otra hora|otras horas)\b/)) {
440
+ out.later = true;
441
+ }
442
+ else {
443
+ // not later
444
+ }
445
+ if (take(/\b(?:any ?time|whenever|anything|asap|as soon as possible|earliest|first available|cuando sea|cualquier (?:dia|hora|momento)|lo antes posible|lo mas pronto posible)\b/)) {
446
+ out.any = true;
447
+ }
448
+ else {
449
+ // no "any time"
450
+ }
451
+ for (const key of ['from', 'to', 'at']) {
452
+ if (out[key] === null) {
453
+ delete out[key];
454
+ }
455
+ else { /* read */ }
456
+ }
457
+ return Object.keys(out).length ? out : null;
458
+ }
459
+ // ---- open times ----
460
+ /**
461
+ * Up to `count` open times, earliest first, as [{ key, calendar, date, start, end, from, to, label, label_es }]
462
+ * (start/end ISO; from/to wall time in the zone; label for a button or a list).
463
+ *
464
+ * hours the business schedule; a calendar with its own `schedule` uses that instead
465
+ * calendars [{ key, name?, schedule?, zips?, skills? }]; none = one unnamed calendar
466
+ * service { length, buffer?, time: 'exact' | 'window', step? (exact, default 30), windows? [{open, close}] (window),
467
+ * per? (jobs per window per calendar, default 1), avail: 'check' | 'accept', notice? (minutes),
468
+ * ahead? (days, default 30), skill? }
469
+ * busy [{ calendar, start, end }] existing bookings (ignored when avail is 'accept')
470
+ * preference readWhen's result, plus notBefore (epoch or ISO) for "later"
471
+ * zip, calendar the customer's zip; the calendar they picked
472
+ * A slot fits a preference when it starts inside its dates and from/to (a window when it overlaps from/to). The first
473
+ * calendar (in the order given) with room takes the slot; a time two calendars share is offered once.
474
+ */
475
+ export function openSlots({ hours, calendars, service, busy = [], preference = null, now = Date.now(), zip = '', calendar = '', count = 3 } = {}) {
476
+ const svc = service || {};
477
+ const tz = hours?.timezone || 'UTC';
478
+ const nowMs = toEpoch(now);
479
+ const length = Math.max(5, Number(svc.length) || 60);
480
+ const buffer = Math.max(0, Number(svc.buffer) || 0);
481
+ const step = Math.max(5, Number(svc.step) || 30);
482
+ const per = Math.max(1, Number(svc.per) || 1);
483
+ const earliest = nowMs + Math.max(0, Number(svc.notice) || 0) * MINUTE;
484
+ const ahead = Math.max(1, Math.min(366, Number(svc.ahead) || 30));
485
+ const pref = preference && typeof preference === 'object' ? preference : {};
486
+ const notBefore = pref.notBefore !== undefined ? toEpoch(pref.notBefore) : NaN;
487
+ const wantFrom = pref.at ? minutesOf(pref.at) : (pref.from && HHMM.test(pref.from) ? minutesOf(pref.from) : 0);
488
+ const wantTo = pref.at ? minutesOf(pref.at) + 1 : (pref.to === '24:00' ? 1440 : (pref.to && HHMM.test(pref.to) ? minutesOf(pref.to) : 1440));
489
+ const wantDates = Array.isArray(pref.dates) && pref.dates.length ? new Set(pref.dates) : null;
490
+ const skill = String(svc.skill || '').toLowerCase();
491
+ const cals = (Array.isArray(calendars) && calendars.length ? calendars : [{ key: '' }]).filter((c) => c && (!calendar || c.key === calendar) && zipCovered(c.zips, zip) &&
492
+ (!skill || (Array.isArray(c.skills) && c.skills.some((s) => String(s).toLowerCase() === skill))));
493
+ const bookings = (svc.avail === 'accept' ? [] : (Array.isArray(busy) ? busy : []))
494
+ .map((b) => ({ calendar: b?.calendar ?? '', start: toEpoch(b?.start), end: toEpoch(b?.end) }))
495
+ .filter((b) => Number.isFinite(b.start) && Number.isFinite(b.end));
496
+ const today = wallClock(nowMs, tz).date;
497
+ const slots = [];
498
+ const seen = new Set();
499
+ for (let i = 0; i <= ahead && slots.length < count; i++) {
500
+ const date = addDays(today, i);
501
+ if (wantDates && !wantDates.has(date)) {
502
+ continue;
503
+ }
504
+ else {
505
+ // a day to look at
506
+ }
507
+ // candidate [from, to) wall-minute spans this day, before any calendar's own hours
508
+ const spans = [];
509
+ if (svc.time === 'window') {
510
+ for (const w of validRanges(svc.windows)) {
511
+ const from = minutesOf(w.open), to = minutesOf(w.close);
512
+ if (from < wantTo && to > wantFrom) {
513
+ spans.push([from, to]);
514
+ }
515
+ else { /* outside the preference */ }
516
+ }
517
+ }
518
+ else {
519
+ for (let from = 0; from + length <= 1440; from += step) {
520
+ if (from >= wantFrom && from < wantTo) {
521
+ spans.push([from, from + length]);
522
+ }
523
+ else { /* outside the preference */ }
524
+ }
525
+ }
526
+ for (const [from, to] of spans) {
527
+ const start = epochOf(date, from, tz);
528
+ const end = epochOf(date, to, tz);
529
+ if (start < earliest || (Number.isFinite(notBefore) && start < notBefore) || seen.has(start)) {
530
+ continue;
531
+ }
532
+ else {
533
+ // in the future, after the notice
534
+ }
535
+ const taker = cals.find((c) => {
536
+ const ranges = validRanges((c.schedule?.hours ? c.schedule : hours)?.hours?.[dayOf(date)]);
537
+ const inHours = ranges.some((r) => from >= minutesOf(r.open) && to <= minutesOf(r.close));
538
+ const mine = bookings.filter((b) => b.calendar === (c.key ?? ''));
539
+ if (!inHours) {
540
+ return false;
541
+ }
542
+ else if (svc.avail === 'accept') {
543
+ return true;
544
+ }
545
+ else if (svc.time === 'window') {
546
+ return mine.filter((b) => b.start >= start && b.start < end).length < per;
547
+ }
548
+ else {
549
+ return !mine.some((b) => b.start < end + buffer * MINUTE && start < b.end + buffer * MINUTE);
550
+ }
551
+ });
552
+ if (taker) {
553
+ seen.add(start);
554
+ const slot = { key: '', calendar: taker.key ?? '', date, start: new Date(start).toISOString(), end: new Date(end).toISOString(), from: hhmmOf(from), to: hhmmOf(to), window: svc.time === 'window' };
555
+ slot.key = `${date}T${slot.from}${slot.calendar ? `@${slot.calendar}` : ''}`;
556
+ slot.label = slotToWords(slot, 'en', today);
557
+ slot.label_es = slotToWords(slot, 'es', today);
558
+ slots.push(slot);
559
+ if (slots.length >= count) {
560
+ break;
561
+ }
562
+ else { /* room for more */ }
563
+ }
564
+ else {
565
+ // no calendar has room
566
+ }
567
+ }
568
+ }
569
+ return slots;
570
+ }
571
+ /**
572
+ * A slot in words: "tomorrow at 9:15 AM", "Tuesday, December 8, between 8 AM and 12 PM" / "mañana a las 9:15", "el
573
+ * martes 8 de diciembre entre las 8:00 y las 12:00". `today` ('YYYY-MM-DD') turns today and tomorrow into words.
574
+ */
575
+ export function slotToWords(slot, lang = 'en', today = '') {
576
+ const L = lang === 'es' ? 'es' : 'en';
577
+ if (!slot || !/^\d{4}-\d{2}-\d{2}$/.test(String(slot.date || '')) || !HHMM.test(String(slot.from || ''))) {
578
+ return '';
579
+ }
580
+ else {
581
+ const [, m, d] = slot.date.split('-').map(Number);
582
+ const name = DAY_NAMES[L][dayOf(slot.date)];
583
+ const relative = today && slot.date === today ? (L === 'es' ? 'hoy' : 'today') : (today && slot.date === addDays(today, 1) ? (L === 'es' ? 'mañana' : 'tomorrow') : '');
584
+ const day = relative || (L === 'es' ? `el ${name} ${d} de ${MONTH_NAMES.es[m - 1]}` : `${name}, ${MONTH_NAMES.en[m - 1]} ${d}`);
585
+ const art = (hhmm) => (L === 'es' ? `${minutesOf(hhmm) >= 60 && minutesOf(hhmm) < 120 ? 'la' : 'las'} ${clock(hhmm, L)}` : clock(hhmm, L));
586
+ if (slot.window && HHMM.test(String(slot.to || ''))) {
587
+ return L === 'es' ? `${day} entre ${art(slot.from)} y ${art(slot.to)}` : `${day}${relative ? '' : ','} between ${art(slot.from)} and ${art(slot.to)}`;
588
+ }
589
+ else {
590
+ return L === 'es' ? `${day} a ${art(slot.from)}` : `${day} at ${art(slot.from)}`;
591
+ }
592
+ }
593
+ }
594
+ /** Today's date in `timezone` ('YYYY-MM-DD'), the `today` slotToWords takes; '' for an unknown zone. */
595
+ export function todayIn(timezone = 'UTC', now = Date.now()) {
596
+ try {
597
+ return wallClock(toEpoch(now), timezone || 'UTC').date;
598
+ }
599
+ catch (error) {
600
+ return '';
601
+ }
602
+ }
603
+ /** Whole minutes from `now` until `time` (ISO or epoch), negative once it has passed: a change cutoff. */
604
+ export function minutesUntil(time, now = Date.now()) {
605
+ return Math.floor((toEpoch(time) - toEpoch(now)) / MINUTE);
606
+ }
@@ -1 +1 @@
1
- export const JSFE_RUNTIME_FINGERPRINT = "sha256:a3ad9d949b8c7921e96bcf374089ff2203b16432b7ac42d0e6735883fbea1fde";
1
+ export const JSFE_RUNTIME_FINGERPRINT = "sha256:e8c80684923747d7a70dfe7de0f02a322e0ac1b9b65b749ad416a675628fc180";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsfe",
3
- "version": "1.104.1",
3
+ "version": "1.105.0",
4
4
  "description": "TypeScript workflow engine for conversational/automation apps: multi-flow orchestration, interrupt/resume, stack-based control, robust errors, and flexible tool/REST integration.",
5
5
  "license": "MIT",
6
6
  "author": "Ron Pinkas",