jsfe 1.104.0 → 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 +9 -0
- package/dist/forms/address-flows.d.ts.map +1 -1
- package/dist/forms/address-flows.js +8 -7
- package/dist/forms/index.d.ts +1 -0
- package/dist/forms/index.d.ts.map +1 -1
- package/dist/forms/index.js +3 -1
- package/dist/forms/scheduling-flows.d.ts +13 -0
- package/dist/forms/scheduling-flows.d.ts.map +1 -0
- package/dist/forms/scheduling-flows.js +301 -0
- package/dist/helpers/address.d.ts +34 -1
- package/dist/helpers/address.d.ts.map +1 -1
- package/dist/helpers/address.js +33 -2
- package/dist/helpers/index.d.ts +18 -1
- package/dist/helpers/index.d.ts.map +1 -1
- package/dist/helpers/index.js +4 -3
- package/dist/helpers/schedule.d.ts +82 -0
- package/dist/helpers/schedule.d.ts.map +1 -0
- package/dist/helpers/schedule.js +606 -0
- package/dist/runtime-identity.js +1 -1
- package/package.json +1 -1
|
@@ -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
|
+
}
|
package/dist/runtime-identity.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const JSFE_RUNTIME_FINGERPRINT = "sha256:
|
|
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.
|
|
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",
|