@veroxm/react-sdk 1.11.1 → 1.12.1
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/CHANGELOG.md +33 -0
- package/dist/editor/handler.js +5 -1
- package/dist/editor/i18n.d.ts +3 -0
- package/dist/editor/i18n.js +6 -0
- package/dist/editor/overlay.d.ts +1 -1
- package/dist/editor/overlay.js +25 -0
- package/dist/form-native/checks.d.ts +53 -0
- package/dist/form-native/checks.js +168 -0
- package/dist/form-native/model.d.ts +184 -0
- package/dist/form-native/model.js +261 -0
- package/dist/form-native/relay.d.ts +11 -0
- package/dist/form-native/relay.js +156 -0
- package/dist/form-native/view.d.ts +28 -0
- package/dist/form-native/view.js +286 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/next/form.d.ts +34 -0
- package/dist/next/form.js +47 -0
- package/dist/next/index.d.ts +2 -0
- package/dist/next/index.js +1 -0
- package/dist/slots-core.d.ts +16 -1
- package/dist/slots-core.js +6 -0
- package/package.json +1 -1
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { FORM_MOBILE_COUNTRIES, ageOn, calendarDateToGregorian, isValidEmail, isValidPhone, latinDigits, normalizeMobile, normalizeSaudiId, } from './checks.js';
|
|
2
|
+
/** The element types the native renderer draws; a form with any other is shown in its embed instead. */
|
|
3
|
+
export const NATIVE_ELEMENT_TYPES = [
|
|
4
|
+
'short_text', 'long_text', 'email', 'phone', 'url', 'number', 'single_choice', 'multiple_choice', 'dropdown', 'yes_no', 'legal',
|
|
5
|
+
'saudi_id', 'birth_date', 'mobile', 'statement', 'heading',
|
|
6
|
+
];
|
|
7
|
+
export const FORM_LAYOUT_SUBMIT = '$submit';
|
|
8
|
+
/** Why a form can't be drawn natively (and is shown in its embed instead), or null when it can. */
|
|
9
|
+
export function nativeProblem(def) {
|
|
10
|
+
if (def.mode !== 'classic')
|
|
11
|
+
return 'conversational forms show one question at a time';
|
|
12
|
+
const other = def.elements.find((e) => !NATIVE_ELEMENT_TYPES.includes(e.type));
|
|
13
|
+
if (other)
|
|
14
|
+
return `${other.type} questions`;
|
|
15
|
+
// Branching between pages needs the hosted renderer; a page form has none (show/hide comes with FB-14).
|
|
16
|
+
if (def.logic?.length)
|
|
17
|
+
return 'logic';
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
/** The form in `locale`: its text replaced by the translation wherever there is one (as localizeFormDefinition). */
|
|
21
|
+
export function localizeForm(def, locale) {
|
|
22
|
+
const t = def.translations?.[locale] ?? def.translations?.[locale.split('-')[0]];
|
|
23
|
+
if (!t || locale === def.locale)
|
|
24
|
+
return def;
|
|
25
|
+
const tr = (key, fallback) => (t[key]?.trim() ? t[key] : fallback);
|
|
26
|
+
return {
|
|
27
|
+
...def,
|
|
28
|
+
locale,
|
|
29
|
+
elements: def.elements.map((el) => {
|
|
30
|
+
const k = `el.${el.id}`;
|
|
31
|
+
const src = el;
|
|
32
|
+
const next = { ...el, title: tr(`${k}.title`, el.title), description: tr(`${k}.description`, el.description) };
|
|
33
|
+
if (typeof src.placeholder === 'string')
|
|
34
|
+
next.placeholder = tr(`${k}.placeholder`, src.placeholder);
|
|
35
|
+
if (Array.isArray(src.choices))
|
|
36
|
+
next.choices = src.choices.map((c) => ({ ...c, label: tr(`${k}.choice.${c.id}`, c.label) }));
|
|
37
|
+
return next;
|
|
38
|
+
}),
|
|
39
|
+
endings: def.endings?.map((e) => ({ ...e, title: tr(`end.${e.id}.title`, e.title), description: tr(`end.${e.id}.description`, e.description) })),
|
|
40
|
+
...(def.submitLabel ? { submitLabel: tr('form.submit', def.submitLabel) } : {}),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The rows to draw, as formLayoutRows in shared-types: the layout's rows, then every element not placed in one, each on
|
|
45
|
+
* its own row, in form order; the submit button last unless a row has it.
|
|
46
|
+
*/
|
|
47
|
+
export function layoutRows(def) {
|
|
48
|
+
const rows = def.layout?.rows ?? [];
|
|
49
|
+
const placed = new Set(rows.flatMap((r) => r.cells.map((c) => c.element)));
|
|
50
|
+
const loose = def.elements.filter((el) => el.type !== 'page_break' && !placed.has(el.id));
|
|
51
|
+
const one = (element) => ({ id: `r_${element}`, gap: 12, cells: [{ element, width: null }], medium: null, small: null, submitFullWidth: true });
|
|
52
|
+
return [...rows, ...loose.map((el) => one(el.id)), ...(placed.has(FORM_LAYOUT_SUBMIT) ? [] : [one(FORM_LAYOUT_SUBMIT)])];
|
|
53
|
+
}
|
|
54
|
+
/** CSS grid columns for a row: fixed cells in px, flexible ones share what's left (FB-10). */
|
|
55
|
+
export function gridColumns(row) {
|
|
56
|
+
return row.cells.map((c) => (c.width ? `minmax(0, ${c.width}px)` : 'minmax(0, 1fr)')).join(' ');
|
|
57
|
+
}
|
|
58
|
+
const EN = {
|
|
59
|
+
submit: 'Submit',
|
|
60
|
+
sending: 'Sending…',
|
|
61
|
+
sendError: "Your answers couldn't be sent. Check your connection and try again.",
|
|
62
|
+
chooseOption: 'Choose an option',
|
|
63
|
+
yes: 'Yes',
|
|
64
|
+
no: 'No',
|
|
65
|
+
day: 'Day',
|
|
66
|
+
month: 'Month',
|
|
67
|
+
year: 'Year',
|
|
68
|
+
calendar: 'Calendar',
|
|
69
|
+
gregorian: 'Gregorian',
|
|
70
|
+
hijri: 'Hijri',
|
|
71
|
+
countryCode: 'Country code',
|
|
72
|
+
required: 'required',
|
|
73
|
+
errorsTitle: 'Please check the highlighted fields',
|
|
74
|
+
messages: {
|
|
75
|
+
required: 'Please fill this in',
|
|
76
|
+
requiredChoice: 'Please choose an answer',
|
|
77
|
+
mustAccept: 'Please accept to continue',
|
|
78
|
+
email: 'Please enter a valid email address',
|
|
79
|
+
phone: 'Please enter a valid phone number',
|
|
80
|
+
url: 'Please enter a web address like https://example.com',
|
|
81
|
+
number: 'Please enter a number',
|
|
82
|
+
integer: 'Please enter a whole number',
|
|
83
|
+
min: (n) => `Please enter ${n} or more`,
|
|
84
|
+
max: (n) => `Please enter ${n} or less`,
|
|
85
|
+
minLength: (n) => `Please write at least ${n} characters`,
|
|
86
|
+
maxLength: (n) => `Please keep it under ${n + 1} characters`,
|
|
87
|
+
minSelections: (n) => `Please choose at least ${n}`,
|
|
88
|
+
maxSelections: (n) => `Please choose at most ${n}`,
|
|
89
|
+
choice: 'Please choose one of the options',
|
|
90
|
+
saudiId: 'Please enter a valid 10-digit ID number',
|
|
91
|
+
mobile: 'Please enter a valid mobile number',
|
|
92
|
+
birthDate: 'Please choose a valid date of birth',
|
|
93
|
+
minAge: (n) => `You must be at least ${n} years old`,
|
|
94
|
+
maxAge: (n) => `You must be ${n} years old or younger`,
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
const AR = {
|
|
98
|
+
submit: 'إرسال',
|
|
99
|
+
sending: 'جارٍ الإرسال…',
|
|
100
|
+
sendError: 'تعذّر إرسال إجاباتك. تحقّق من اتصالك وحاول مرة أخرى.',
|
|
101
|
+
chooseOption: 'اختر خيارًا',
|
|
102
|
+
yes: 'نعم',
|
|
103
|
+
no: 'لا',
|
|
104
|
+
day: 'اليوم',
|
|
105
|
+
month: 'الشهر',
|
|
106
|
+
year: 'السنة',
|
|
107
|
+
calendar: 'التقويم',
|
|
108
|
+
gregorian: 'ميلادي',
|
|
109
|
+
hijri: 'هجري',
|
|
110
|
+
countryCode: 'رمز الدولة',
|
|
111
|
+
required: 'مطلوب',
|
|
112
|
+
errorsTitle: 'يرجى مراجعة الحقول المحددة',
|
|
113
|
+
messages: {
|
|
114
|
+
required: 'يرجى تعبئة هذا الحقل',
|
|
115
|
+
requiredChoice: 'يرجى اختيار إجابة',
|
|
116
|
+
mustAccept: 'يرجى الموافقة للمتابعة',
|
|
117
|
+
email: 'يرجى إدخال بريد إلكتروني صحيح',
|
|
118
|
+
phone: 'يرجى إدخال رقم هاتف صحيح',
|
|
119
|
+
url: 'يرجى إدخال عنوان ويب مثل https://example.com',
|
|
120
|
+
number: 'يرجى إدخال رقم',
|
|
121
|
+
integer: 'يرجى إدخال عدد صحيح',
|
|
122
|
+
min: (n) => `يرجى إدخال ${n} أو أكثر`,
|
|
123
|
+
max: (n) => `يرجى إدخال ${n} أو أقل`,
|
|
124
|
+
minLength: (n) => `يرجى كتابة ${n} أحرف على الأقل`,
|
|
125
|
+
maxLength: (n) => `يرجى ألا يتجاوز النص ${n} حرفًا`,
|
|
126
|
+
minSelections: (n) => `يرجى اختيار ${n} على الأقل`,
|
|
127
|
+
maxSelections: (n) => `يرجى اختيار ${n} على الأكثر`,
|
|
128
|
+
choice: 'يرجى اختيار أحد الخيارات',
|
|
129
|
+
saudiId: 'يرجى إدخال رقم هوية صحيح من 10 أرقام',
|
|
130
|
+
mobile: 'يرجى إدخال رقم جوال صحيح',
|
|
131
|
+
birthDate: 'يرجى اختيار تاريخ ميلاد صحيح',
|
|
132
|
+
minAge: (n) => `يجب ألا يقل عمرك عن ${n} سنة`,
|
|
133
|
+
maxAge: (n) => `يجب ألا يزيد عمرك عن ${n} سنة`,
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
/** The renderer's words in English or Arabic; other languages use English in the browser (the server's messages still come in the form's language). */
|
|
137
|
+
export function formWords(locale) {
|
|
138
|
+
return locale.toLowerCase().split('-')[0] === 'ar' ? AR : EN;
|
|
139
|
+
}
|
|
140
|
+
/** Right-to-left languages (FB-12). */
|
|
141
|
+
export function isRtl(locale) {
|
|
142
|
+
return ['ar', 'he', 'fa', 'ur'].includes(locale.toLowerCase().split('-')[0]);
|
|
143
|
+
}
|
|
144
|
+
/** One answer, checked as the server will (FB-15): the value to send, or the message to show under the field. */
|
|
145
|
+
export function checkAnswer(el, raw, m, now = new Date()) {
|
|
146
|
+
const ok = (value) => ({ value, error: null });
|
|
147
|
+
const fail = (error) => ({ error });
|
|
148
|
+
const text = typeof raw === 'string' ? raw.trim() : '';
|
|
149
|
+
switch (el.type) {
|
|
150
|
+
case 'statement':
|
|
151
|
+
case 'heading':
|
|
152
|
+
return fail(null);
|
|
153
|
+
case 'legal':
|
|
154
|
+
if (el.required && raw !== true)
|
|
155
|
+
return fail(m.mustAccept);
|
|
156
|
+
return raw === true ? ok(true) : fail(null);
|
|
157
|
+
case 'yes_no':
|
|
158
|
+
if (raw === 'yes' || raw === 'no')
|
|
159
|
+
return ok(raw === 'yes');
|
|
160
|
+
return fail(el.required ? m.requiredChoice : null);
|
|
161
|
+
case 'single_choice':
|
|
162
|
+
case 'dropdown':
|
|
163
|
+
case 'multiple_choice': {
|
|
164
|
+
const ids = (Array.isArray(raw) ? raw : typeof raw === 'string' && raw ? [raw] : []).filter((id) => el.choices.some((c) => c.id === id));
|
|
165
|
+
if (!ids.length)
|
|
166
|
+
return fail(el.required ? m.requiredChoice : null);
|
|
167
|
+
if (el.type === 'multiple_choice') {
|
|
168
|
+
if (el.minSelections !== null && ids.length < el.minSelections)
|
|
169
|
+
return fail(m.minSelections(el.minSelections));
|
|
170
|
+
if (el.maxSelections !== null && ids.length > el.maxSelections)
|
|
171
|
+
return fail(m.maxSelections(el.maxSelections));
|
|
172
|
+
}
|
|
173
|
+
return ok({ choices: ids });
|
|
174
|
+
}
|
|
175
|
+
case 'mobile': {
|
|
176
|
+
const v = raw && typeof raw === 'object' && 'number' in raw ? raw : { country: el.defaultCountry, number: '' };
|
|
177
|
+
if (!v.number.trim())
|
|
178
|
+
return fail(el.required ? m.required : null);
|
|
179
|
+
const e164 = el.countries.includes(v.country) ? normalizeMobile(v.country, v.number) : null;
|
|
180
|
+
return e164 ? ok({ country: v.country, number: v.number }) : fail(m.mobile);
|
|
181
|
+
}
|
|
182
|
+
case 'birth_date': {
|
|
183
|
+
const v = raw && typeof raw === 'object' && 'calendar' in raw ? raw : null;
|
|
184
|
+
if (!v || (!v.year && !v.month && !v.day))
|
|
185
|
+
return fail(el.required ? m.required : null);
|
|
186
|
+
const date = { calendar: v.calendar, year: Number(latinDigits(v.year)), month: Number(v.month), day: Number(v.day) };
|
|
187
|
+
const g = el.calendars.includes(date.calendar) && Number.isInteger(date.year) && Number.isInteger(date.month) && Number.isInteger(date.day) ? calendarDateToGregorian(date) : null;
|
|
188
|
+
if (!g || g.getTime() > now.getTime())
|
|
189
|
+
return fail(m.birthDate);
|
|
190
|
+
const age = ageOn(g, now);
|
|
191
|
+
if (el.minAge !== null && age < el.minAge)
|
|
192
|
+
return fail(m.minAge(el.minAge));
|
|
193
|
+
if (el.maxAge !== null && age > el.maxAge)
|
|
194
|
+
return fail(m.maxAge(el.maxAge));
|
|
195
|
+
return ok(date);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (!text)
|
|
199
|
+
return fail(el.required ? m.required : null);
|
|
200
|
+
switch (el.type) {
|
|
201
|
+
case 'short_text':
|
|
202
|
+
case 'long_text':
|
|
203
|
+
if (text.length > el.maxLength)
|
|
204
|
+
return fail(m.maxLength(el.maxLength));
|
|
205
|
+
if (el.minLength !== null && text.length < el.minLength)
|
|
206
|
+
return fail(m.minLength(el.minLength));
|
|
207
|
+
return ok(text);
|
|
208
|
+
case 'email':
|
|
209
|
+
return isValidEmail(text) ? ok(text) : fail(m.email);
|
|
210
|
+
case 'phone':
|
|
211
|
+
return text.length <= 40 && isValidPhone(text) ? ok(text) : fail(m.phone);
|
|
212
|
+
case 'url': {
|
|
213
|
+
const v = /^[a-z][a-z0-9+.-]*:/i.test(text) ? text : `https://${text}`;
|
|
214
|
+
try {
|
|
215
|
+
const u = new URL(v);
|
|
216
|
+
return (u.protocol === 'https:' || u.protocol === 'http:') && u.hostname && !/\s/.test(v) ? ok(v) : fail(m.url);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
return fail(m.url);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
case 'number': {
|
|
223
|
+
const n = Number(latinDigits(text).replace(',', '.'));
|
|
224
|
+
if (!Number.isFinite(n))
|
|
225
|
+
return fail(m.number);
|
|
226
|
+
if (el.integer && !Number.isInteger(n))
|
|
227
|
+
return fail(m.integer);
|
|
228
|
+
if (el.min !== null && n < el.min)
|
|
229
|
+
return fail(m.min(el.min));
|
|
230
|
+
if (el.max !== null && n > el.max)
|
|
231
|
+
return fail(m.max(el.max));
|
|
232
|
+
return ok(n);
|
|
233
|
+
}
|
|
234
|
+
case 'saudi_id': {
|
|
235
|
+
const v = normalizeSaudiId(text, el);
|
|
236
|
+
return v ? ok(v) : fail(m.saudiId);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return fail(null);
|
|
240
|
+
}
|
|
241
|
+
/** Every answer, checked: the answers to send (by question ref, as the API takes them) and the errors to show (by element id, as it returns them). */
|
|
242
|
+
export function checkAnswers(def, raw, words, now = new Date()) {
|
|
243
|
+
const answers = {};
|
|
244
|
+
const errors = {};
|
|
245
|
+
for (const el of def.elements) {
|
|
246
|
+
const r = checkAnswer(el, raw[el.id], words.messages, now);
|
|
247
|
+
if (r.error)
|
|
248
|
+
errors[el.id] = r.error;
|
|
249
|
+
else if (r.value !== undefined)
|
|
250
|
+
answers[el.ref] = r.value;
|
|
251
|
+
}
|
|
252
|
+
return { answers, errors };
|
|
253
|
+
}
|
|
254
|
+
/** The country menu's entries: the element's countries, in its order, with their dial codes. */
|
|
255
|
+
export function mobileCountries(el, locale) {
|
|
256
|
+
const ar = locale.toLowerCase().startsWith('ar');
|
|
257
|
+
return el.countries.flatMap((code) => {
|
|
258
|
+
const c = FORM_MOBILE_COUNTRIES[code];
|
|
259
|
+
return c ? [{ code, dial: `+${c.dial}`, name: ar ? c.ar : c.en }] : [];
|
|
260
|
+
});
|
|
261
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The header the native form sends with its JSON. */
|
|
2
|
+
export declare const FORM_HEADER = "x-veroxm-form";
|
|
3
|
+
/** The visitor's address: the first X-Forwarded-For entry (set by the site's own proxy or host), else X-Real-IP. */
|
|
4
|
+
export declare function visitorIp(request: Request): string | null;
|
|
5
|
+
/**
|
|
6
|
+
* A plain form post as the API's body. Names: `a.<ref>` text, `c.<ref>` choices (repeatable), `b.<ref>` yes / no or a
|
|
7
|
+
* ticked box, `m.<ref>.country|number` a mobile, `d.<ref>.calendar|year|month|day` a date of birth, `h.<name>` hidden
|
|
8
|
+
* values; and `version`, `locale`.
|
|
9
|
+
*/
|
|
10
|
+
export declare function bodyFromFormData(fd: FormData): Record<string, unknown>;
|
|
11
|
+
export declare function relayFormSubmit(request: Request, publicId: string): Promise<Response>;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { resolveSlotsConfig } from '../slots-core.js';
|
|
2
|
+
// POST /api/veroxm/forms/:publicId/submit -- a native form's send (FB-19, HO-16), relayed to VeroXM with the site's
|
|
3
|
+
// server key. The browser talks only to the site it is on; VeroXM limits sends per visitor from the address passed
|
|
4
|
+
// on (X-VeroXM-Visitor-Ip), which it trusts only from a server key.
|
|
5
|
+
//
|
|
6
|
+
// Two ways in:
|
|
7
|
+
// - JSON from <VeroxmForm> with script: the API's answer comes back as it is (the redirect URL, or the errors).
|
|
8
|
+
// - A plain form post when the script hasn't run (form-encoded, the field names below): a hand-off redirects (303)
|
|
9
|
+
// straight to the journey, anything else back to the page, and a problem shows a short page with a way back.
|
|
10
|
+
//
|
|
11
|
+
// Changes only from this site (SEC-06): JSON needs the X-VeroXM-Form header (which a cross-site page can't send without
|
|
12
|
+
// CORS), and a browser's Origin / Sec-Fetch-Site must be this site's.
|
|
13
|
+
/** The header the native form sends with its JSON. */
|
|
14
|
+
export const FORM_HEADER = 'x-veroxm-form';
|
|
15
|
+
const FORM_ID = /^f_[A-Za-z0-9]{20}$/;
|
|
16
|
+
const MAX_BODY = 64 * 1024;
|
|
17
|
+
function json(body, status) {
|
|
18
|
+
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } });
|
|
19
|
+
}
|
|
20
|
+
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
21
|
+
function problemPage(message, back, lang, status) {
|
|
22
|
+
const ar = lang.startsWith('ar');
|
|
23
|
+
return new Response(`<!doctype html><html lang="${esc(lang)}" dir="${ar ? 'rtl' : 'ltr'}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${ar ? 'تعذّر الإرسال' : "Couldn't send"}</title>` +
|
|
24
|
+
`<body style="font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 16px"><p role="alert">${esc(message)}</p>` +
|
|
25
|
+
`<p><a href="${esc(back)}">${ar ? 'رجوع' : 'Go back'}</a></p></body></html>`, { status, headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' } });
|
|
26
|
+
}
|
|
27
|
+
/** The visitor's address: the first X-Forwarded-For entry (set by the site's own proxy or host), else X-Real-IP. */
|
|
28
|
+
export function visitorIp(request) {
|
|
29
|
+
const fwd = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
|
|
30
|
+
const ip = fwd || request.headers.get('x-real-ip')?.trim() || '';
|
|
31
|
+
return /^[0-9A-Fa-f:.]{2,45}$/.test(ip) ? ip : null;
|
|
32
|
+
}
|
|
33
|
+
function randomKey() {
|
|
34
|
+
const bytes = new Uint8Array(16);
|
|
35
|
+
crypto.getRandomValues(bytes);
|
|
36
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A plain form post as the API's body. Names: `a.<ref>` text, `c.<ref>` choices (repeatable), `b.<ref>` yes / no or a
|
|
40
|
+
* ticked box, `m.<ref>.country|number` a mobile, `d.<ref>.calendar|year|month|day` a date of birth, `h.<name>` hidden
|
|
41
|
+
* values; and `version`, `locale`.
|
|
42
|
+
*/
|
|
43
|
+
export function bodyFromFormData(fd) {
|
|
44
|
+
const answers = {};
|
|
45
|
+
const hidden = {};
|
|
46
|
+
const parts = {};
|
|
47
|
+
for (const [name, raw] of fd.entries()) {
|
|
48
|
+
if (typeof raw !== 'string')
|
|
49
|
+
continue;
|
|
50
|
+
const dot = name.indexOf('.');
|
|
51
|
+
const kind = name.slice(0, dot);
|
|
52
|
+
const rest = name.slice(dot + 1);
|
|
53
|
+
if (dot < 1 || !rest)
|
|
54
|
+
continue;
|
|
55
|
+
if (kind === 'a')
|
|
56
|
+
answers[rest] = raw;
|
|
57
|
+
else if (kind === 'c') {
|
|
58
|
+
const prev = answers[rest];
|
|
59
|
+
if (raw)
|
|
60
|
+
answers[rest] = { choices: [...(prev?.choices ?? []), raw] };
|
|
61
|
+
}
|
|
62
|
+
else if (kind === 'b')
|
|
63
|
+
answers[rest] = raw === 'no' ? false : raw === 'yes' || raw === 'on' || raw === 'true';
|
|
64
|
+
else if (kind === 'h')
|
|
65
|
+
hidden[rest] = raw;
|
|
66
|
+
else if (kind === 'm' || kind === 'd') {
|
|
67
|
+
const at = rest.lastIndexOf('.');
|
|
68
|
+
if (at < 1)
|
|
69
|
+
continue;
|
|
70
|
+
const ref = `${kind}.${rest.slice(0, at)}`;
|
|
71
|
+
(parts[ref] ?? (parts[ref] = {}))[rest.slice(at + 1)] = raw;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
for (const [key, v] of Object.entries(parts)) {
|
|
75
|
+
const ref = key.slice(2);
|
|
76
|
+
if (key[0] === 'm')
|
|
77
|
+
answers[ref] = { country: v.country ?? '', number: v.number ?? '' };
|
|
78
|
+
else
|
|
79
|
+
answers[ref] = { calendar: v.calendar ?? 'gregorian', year: v.year ?? '', month: v.month ?? '', day: v.day ?? '' };
|
|
80
|
+
}
|
|
81
|
+
// Empty text and menus are no answer.
|
|
82
|
+
for (const [k, v] of Object.entries(answers))
|
|
83
|
+
if (v === '')
|
|
84
|
+
delete answers[k];
|
|
85
|
+
return { key: randomKey(), version: Number(fd.get('version')) || 0, answers, hidden, locale: String(fd.get('locale') ?? '') || undefined };
|
|
86
|
+
}
|
|
87
|
+
export async function relayFormSubmit(request, publicId) {
|
|
88
|
+
const url = new URL(request.url);
|
|
89
|
+
const type = (request.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
|
|
90
|
+
const plain = type === 'application/x-www-form-urlencoded' || type === 'multipart/form-data';
|
|
91
|
+
if (!FORM_ID.test(publicId))
|
|
92
|
+
return json({ error: 'Not found' }, 404);
|
|
93
|
+
const origin = request.headers.get('origin');
|
|
94
|
+
const site = request.headers.get('sec-fetch-site');
|
|
95
|
+
const crossSite = (origin && origin !== url.origin && origin !== 'null') || (site && site !== 'same-origin' && site !== 'none');
|
|
96
|
+
if (crossSite || (!plain && request.headers.get(FORM_HEADER) !== '1'))
|
|
97
|
+
return json({ error: 'Forbidden' }, 403);
|
|
98
|
+
const len = Number(request.headers.get('content-length') ?? 0);
|
|
99
|
+
if (len > MAX_BODY)
|
|
100
|
+
return json({ error: 'Too large' }, 413);
|
|
101
|
+
let body;
|
|
102
|
+
try {
|
|
103
|
+
body = plain ? bodyFromFormData(await request.formData()) : (await request.json());
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return json({ error: 'Bad request' }, 400);
|
|
107
|
+
}
|
|
108
|
+
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
109
|
+
return json({ error: 'Bad request' }, 400);
|
|
110
|
+
const lang = typeof body.locale === 'string' ? body.locale : 'en';
|
|
111
|
+
const referer = request.headers.get('referer');
|
|
112
|
+
const back = referer && new URL(referer, url.origin).origin === url.origin ? new URL(referer, url.origin).pathname + new URL(referer, url.origin).search : '/';
|
|
113
|
+
if (plain)
|
|
114
|
+
body.page = { url: referer ? new URL(back, url.origin).toString() : undefined };
|
|
115
|
+
const cfg = resolveSlotsConfig();
|
|
116
|
+
if (!cfg.ready || !cfg.fetch) {
|
|
117
|
+
const msg = 'VEROXM_API_BASE, VEROXM_PROJECT_ID and VEROXM_API_KEY must be set on the site.';
|
|
118
|
+
return plain ? problemPage(msg, back, lang, 500) : json({ error: msg }, 500);
|
|
119
|
+
}
|
|
120
|
+
const ip = visitorIp(request);
|
|
121
|
+
const res = await cfg
|
|
122
|
+
.fetch(`${cfg.baseUrl}/public/v2/projects/${cfg.projectId}/forms/${publicId}/submit`, {
|
|
123
|
+
method: 'POST',
|
|
124
|
+
cache: 'no-store',
|
|
125
|
+
headers: {
|
|
126
|
+
Authorization: `Bearer ${cfg.apiKey}`,
|
|
127
|
+
Accept: 'application/json',
|
|
128
|
+
'Content-Type': 'application/json',
|
|
129
|
+
...(typeof body.key === 'string' ? { 'Idempotency-Key': body.key } : {}),
|
|
130
|
+
...(ip ? { 'X-VeroXM-Visitor-Ip': ip } : {}),
|
|
131
|
+
...(request.headers.get('user-agent') ? { 'X-VeroXM-Visitor-Agent': request.headers.get('user-agent').slice(0, 500) } : {}),
|
|
132
|
+
},
|
|
133
|
+
body: JSON.stringify(body),
|
|
134
|
+
})
|
|
135
|
+
.catch(() => null);
|
|
136
|
+
const offline = lang.startsWith('ar') ? 'تعذّر إرسال إجاباتك. حاول مرة أخرى.' : "Your answers couldn't be sent. Please try again.";
|
|
137
|
+
if (!res)
|
|
138
|
+
return plain ? problemPage(offline, back, lang, 502) : json({ error: offline }, 502);
|
|
139
|
+
const text = await res.text();
|
|
140
|
+
if (!plain)
|
|
141
|
+
return new Response(text, { status: res.status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } });
|
|
142
|
+
let parsed = {};
|
|
143
|
+
try {
|
|
144
|
+
parsed = JSON.parse(text);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// not JSON: shown as offline
|
|
148
|
+
}
|
|
149
|
+
if (res.ok) {
|
|
150
|
+
const to = typeof parsed.redirectUrl === 'string' && /^https:\/\//.test(parsed.redirectUrl) ? parsed.redirectUrl : `${back}#vx-form-sent`;
|
|
151
|
+
return new Response(null, { status: 303, headers: { Location: to, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' } });
|
|
152
|
+
}
|
|
153
|
+
const details = parsed.fieldErrors ? Object.values(parsed.fieldErrors).filter((v) => typeof v === 'string') : [];
|
|
154
|
+
const message = [typeof parsed.error === 'string' ? parsed.error : offline, ...details].join(' · ');
|
|
155
|
+
return problemPage(message, back, lang, res.status >= 500 ? 502 : res.status);
|
|
156
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type CSSProperties } from 'react';
|
|
2
|
+
import { type PublicForm } from './model.js';
|
|
3
|
+
export interface VeroxmFormViewProps {
|
|
4
|
+
/** The form as GET /public/v2/forms/:publicId gives it, in the language to show (see localizeForm). */
|
|
5
|
+
form: PublicForm;
|
|
6
|
+
/** The language shown: the form's own, or one of its translations ("ar"). */
|
|
7
|
+
locale: string;
|
|
8
|
+
/**
|
|
9
|
+
* Values from the page, sent with the answers (FB-21): the chosen product (its key, slug or id), its line, and any
|
|
10
|
+
* hidden fields the form declares. Campaign (utm_*) values are read from the address on send.
|
|
11
|
+
*/
|
|
12
|
+
hidden?: Record<string, string | number | null | undefined>;
|
|
13
|
+
/** Where the form is sent: default `/api/veroxm/forms/<id>/submit` (the site's VeroXM route relays it). */
|
|
14
|
+
submitPath?: string;
|
|
15
|
+
/** The button's text, when the form's layout doesn't give one (default "Submit" / "إرسال"). */
|
|
16
|
+
submitLabel?: string;
|
|
17
|
+
/**
|
|
18
|
+
* After a successful send: `redirectUrl` is the journey's address for a hand-off form (the browser goes there unless
|
|
19
|
+
* this returns false), or the form's own redirect.
|
|
20
|
+
*/
|
|
21
|
+
onSubmitted?: (result: {
|
|
22
|
+
redirectUrl: string | null;
|
|
23
|
+
endingId: string | null;
|
|
24
|
+
}) => boolean | void;
|
|
25
|
+
className?: string;
|
|
26
|
+
style?: CSSProperties;
|
|
27
|
+
}
|
|
28
|
+
export declare function VeroxmFormView({ form, locale, hidden, submitPath, submitLabel, onSubmitted, className, style }: VeroxmFormViewProps): import("react").JSX.Element;
|