// email-validation.org relay for jotform 1.0.0: npx wrangler deploy relay.mjs. MIT licence: see LICENSE. // Generated from the tested sources; do not edit. // integrations/jotform/src/constants.ts var VERSION = "1.0.0"; var USER_AGENT = `email-validation-jotform/${VERSION}`; var JOTFORM_ORIGINS = Object.freeze({ us: "https://api.jotform.com", eu: "https://eu-api.jotform.com", hipaa: "https://hipaa-api.jotform.com" }); var JOTFORM_KEY_HEADER = "APIKEY"; var DEFAULT_STATUS_LABEL = "Email validation status"; var STATUS_FIELD_TYPES = Object.freeze(["control_textbox", "control_textarea"]); var EMAIL_TYPE = "control_email"; var MIN_RELAY_TOKEN_LENGTH = 32; var MAX_WEBHOOK_BYTES = 10 * 1024 * 1024; // integrations/jotform/src/core/http.ts var CallError = class extends Error { service; /** HTTP status, or 0 when no answer arrived. */ status; code; /** True when trying again later can succeed (rate limits, outages, network). */ retryable; /** Whole seconds from `Retry-After`, or null. */ retryAfter; requestId; constructor(service, fields, requestId = null) { super(`${service}: ${fields.message} (${fields.code}${requestId ? `, request ${requestId}` : ""})`); this.name = "CallError"; this.service = service; this.status = fields.status; this.code = fields.code; this.retryable = fields.retryable; this.retryAfter = fields.retryAfter ?? null; this.requestId = requestId; } }; function retryAfterSeconds(response, nowMs = Date.now()) { const value = response.headers.get("retry-after")?.trim(); if (!value) return null; if (/^\d+$/.test(value)) return Number(value); const at = Date.parse(value); return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - nowMs) / 1e3)); } async function send(opts, url, init) { if (new URL(url).origin !== opts.origin) { throw new CallError(opts.service, { status: 0, code: "invalid_request", message: `Refused a request to a host other than ${opts.origin}.`, retryable: false }); } const headers = new Headers(init.headers); headers.set("User-Agent", opts.userAgent); const fetchFn = opts.fetch; let timer; let signal; if (opts.headersOnly) { const controller = new AbortController(); timer = setTimeout( () => controller.abort(new DOMException("The request timed out.", "TimeoutError")), opts.timeoutMs ); signal = controller.signal; } else { signal = AbortSignal.timeout(opts.timeoutMs); } let response; try { response = await fetchFn(url, { ...init, headers, redirect: "manual", signal }); } catch (err) { throw failure(opts.service, err); } finally { if (timer !== void 0) clearTimeout(timer); } if (response.status >= 300 && response.status < 400) { throw new CallError(opts.service, { status: response.status, code: "unexpected_response", message: `Answered with a redirect (HTTP ${response.status}), which is never followed.`, retryable: false }); } return response; } function failure(service, err) { const timedOut = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"); return new CallError(service, { status: 0, code: timedOut ? "timeout" : "connection_error", message: timedOut ? "The request timed out." : "The service could not be reached.", retryable: true }); } async function jsonOrNull(response) { try { return await response.json(); } catch { return null; } } async function readJson(response, service) { let text2; try { text2 = await response.text(); } catch (err) { throw failure(service, err); } try { return JSON.parse(text2); } catch { return null; } } function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } var realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function withRetries(fn, opts) { for (let attempt = 1; ; attempt++) { try { return await fn(); } catch (err) { const again = err instanceof CallError && err.retryable && (opts.retryIf?.(err) ?? true); if (!again || attempt >= opts.attempts) throw err; await opts.sleep(Math.min(opts.maxWaitS, err.retryAfter ?? 2 ** attempt) * 1e3); } } } // integrations/jotform/src/core/vocabulary.ts var BASE_URLS = Object.freeze({ us: "https://api.email-validation.org", eu: "https://api-eu.email-validation.org" }); var STATUSES = Object.freeze(["valid", "invalid", "catch_all", "unknown", "disposable"]); var ACTIONS = Object.freeze(["send", "send_with_caution", "remove", "retry_later"]); var BULK_JOB_STATUSES = Object.freeze([ "analyzing", "ready", "queued", "running", "cancelling", "finalizing", "completed", "failed", "cancelled", "expired" ]); var TERMINAL_BULK_JOB_STATUSES = Object.freeze(["completed", "failed", "cancelled", "expired"]); var BULK_RESULT_COLUMNS = Object.freeze([ "ev_status", "ev_reason", "ev_action", "ev_free_email", "ev_role_account", "ev_disposable", "ev_catch_all_domain", "ev_did_you_mean", "ev_mx_found", "ev_mx_record", "ev_smtp_provider", "ev_domain_age_days" ]); var ACCOUNT_CODES = Object.freeze(["unauthorized", "insufficient_credits", "forbidden", "key_daily_cap"]); // integrations/jotform/src/core/email-validation.ts var SERVICE = "email-validation"; var DEFAULT_TIMEOUT_MS = 3e4; var RESULTS_PART_BYTES = 8 * 1024 * 1024; function regionOf(value) { if (value === void 0 || value === "" || value === "us") return "us"; if (value === "eu") return "eu"; throw new Error('EV_REGION must be "us" or "eu".'); } function checkKey(name, value) { if (typeof value !== "string" || !/^\S+$/.test(value)) throw new Error(`${name} is missing or holds whitespace.`); return value; } function sharesKey(text2, key) { const run = 12; if (key.length < run) return key !== "" && text2.includes(key); for (let i = 0; i + run <= key.length; i++) if (text2.includes(key.slice(i, i + run))) return true; return false; } function codeOf(value, key) { return typeof value === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(value) && !sharesKey(value, key) ? value : ""; } var PROCESSED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/; function requestIdOf(value, key) { return typeof value === "string" && /^req_[A-Za-z0-9]{1,60}$/.test(value) && !sharesKey(value, key) ? value : null; } async function errorFor(response, key) { const body = await jsonOrNull(response); const envelope = isRecord(body) && isRecord(body.error) ? body.error : null; const code = codeOf(envelope?.code, key) || "unexpected_response"; const message = `The API answered HTTP ${response.status}.`; const requestId = requestIdOf(envelope?.request_id, key) ?? requestIdOf(response.headers.get("x-request-id"), key); return new CallError( SERVICE, { status: response.status, code, message, // By status, as SDK_SPEC ยง7.1: an edge error page without our envelope is retried too (never charged). retryable: (response.status === 429 || response.status === 503) && code !== "key_daily_cap", retryAfter: retryAfterSeconds(response) }, requestId ); } function unexpected(status, what) { return new CallError(SERVICE, { status, code: "unexpected_response", message: `The API answered with something other than ${what}.`, retryable: false }); } async function call(config, path, init, query = "", timing = {}) { const origin = BASE_URLS[config.region ?? "us"]; const response = await send( { service: SERVICE, fetch: config.fetch ?? globalThis.fetch, origin, timeoutMs: timing.timeoutMs ?? config.timeoutMs ?? DEFAULT_TIMEOUT_MS, userAgent: config.userAgent, headersOnly: timing.headersOnly }, `${origin}${path}${query}`, { ...init, headers: { Authorization: `Bearer ${config.apiKey}`, ...init.headers } } ); if (!response.ok) throw await errorFor(response, config.apiKey); return response; } async function validateEmail(config, email, options = {}) { const payload = { email }; if (options.timeout !== void 0) payload.timeout = options.timeout; const response = await call(config, "/v1/validate", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(payload) }); const body = await readJson(response, SERVICE); if (!isRecord(body) || !STATUSES.includes(body.status)) throw unexpected(response.status, "a validation result"); const text2 = (name) => { const value = body[name]; return typeof value === "string" && !sharesKey(value, config.apiKey) ? value : ""; }; const reason = text2("reason"); const action = text2("action"); const processedAt = text2("processed_at"); return { status: body.status, reason: /^[a-z_]{1,64}$/.test(reason) ? reason : "", action: ACTIONS.includes(action) ? action : "", processed_at: PROCESSED_AT.test(processedAt) ? processedAt : "", request_id: requestIdOf(body.request_id, config.apiKey) ?? "" }; } // integrations/jotform/src/jotform.ts var SERVICE2 = "jotform"; var TIMEOUT_MS = 3e4; var ID_PATTERN = /^\d{1,32}$/; function jotformRegionOf(value) { const v = value?.trim() || "us"; if (v === "us" || v === "eu" || v === "hipaa") return v; throw new Error('The Jotform region must be "us", "eu" or "hipaa".'); } function checkId(name, value) { const v = value?.trim() ?? ""; if (!ID_PATTERN.test(v)) throw new Error(`${name} must be a Jotform id (digits only).`); return v; } function messageOf(body, apiKey) { const raw = isRecord(body) && typeof body.message === "string" ? body.message : ""; return (apiKey ? raw.split(apiKey).join("[key]") : raw).replace(/\s+/g, " ").trim().slice(0, 160); } function errorOf(status, body, apiKey) { const said = messageOf(body, apiKey); const tail = said ? ` Jotform said: ${said}` : ""; if (status === 401 || status === 403) { return new CallError(SERVICE2, { status, code: status === 401 ? "unauthorized" : "forbidden", message: `Jotform refused the API key (${status}). Check JOTFORM_API_KEY and the Jotform region; writing the status needs a key with Full Access.${tail}`, retryable: false }); } if (status === 404) { return new CallError(SERVICE2, { status, code: "not_found", message: `Jotform has no such form or submission for this key (404).${tail}`, retryable: false }); } if (status === 429) { return new CallError(SERVICE2, { status, code: "daily_limit", message: `Jotform refused the call: the account\u2019s daily API limit is reached (Jotform resets the count at midnight US Eastern time). Run again after that.${tail}`, retryable: false }); } return new CallError(SERVICE2, { status, code: status >= 500 ? "unavailable" : "unexpected_response", message: `Jotform answered ${status}.${tail}`, retryable: status >= 500 }); } function codeOf2(httpStatus, body) { if (isRecord(body)) { const rc = Number(body.responseCode); if (Number.isInteger(rc) && rc > 0) return rc; } return httpStatus; } async function jotformCall(config, method, path, options = {}) { const origin = JOTFORM_ORIGINS[config.region ?? "us"]; const query = options.query ? `?${new URLSearchParams(options.query).toString()}` : ""; const headers = { [JOTFORM_KEY_HEADER]: config.apiKey, Accept: "application/json" }; let body; if (method === "POST") { headers["Content-Type"] = "application/x-www-form-urlencoded"; body = new URLSearchParams(options.form ?? {}).toString(); } const response = await send( { service: SERVICE2, fetch: config.fetch ?? globalThis.fetch, origin, timeoutMs: config.timeoutMs ?? TIMEOUT_MS, userAgent: config.userAgent }, `${origin}${path}${query}`, { method, headers, body } ); const json = await readJson(response, SERVICE2); if (config.budget && isRecord(json)) { const left = Number(json["limit-left"]); if (Number.isFinite(left)) config.budget.left = left; } const code = codeOf2(response.status, json); if (!response.ok || code < 200 || code >= 300) throw errorOf(response.ok ? code : response.status, json, config.apiKey); if (!isRecord(json) || !("content" in json)) { throw new CallError(SERVICE2, { status: response.status, code: "unexpected_response", message: "Jotform answered without its usual envelope.", retryable: false }); } return { content: json.content, resultSet: isRecord(json.resultSet) ? json.resultSet : null }; } var direct = (fn) => fn(); var text = (record, key) => { const v = record[key]; return typeof v === "string" ? v : typeof v === "number" ? String(v) : ""; }; async function getQuestions(config, formId, wrap = direct) { const { content } = await wrap(() => jotformCall(config, "GET", `/form/${checkId("The form id", formId)}/questions`)); const questions = []; if (!isRecord(content)) return questions; for (const [key, value] of Object.entries(content)) { if (!isRecord(value)) continue; const qid = text(value, "qid") || key; if (!ID_PATTERN.test(qid)) continue; questions.push({ qid, type: text(value, "type"), name: text(value, "name"), text: text(value, "text"), order: Number(text(value, "order")) || 0 }); } return questions.sort((a, b) => a.order - b.order || Number(a.qid) - Number(b.qid)); } var norm = (s) => s.replace(/\s+/g, " ").trim().toLowerCase(); function fieldsOf(questions, choice) { const pick = (want, byLabel) => questions.find((q) => q.qid === want || q.name === want || byLabel && norm(q.text) === norm(want)); const emails = questions.filter((q) => q.type === EMAIL_TYPE); let email; if (choice.emailField) { email = pick(choice.emailField.trim(), false); if (!email) throw new Error(`The form has no field "${choice.emailField}" (give the Email field's qid or unique name).`); if (email.type !== EMAIL_TYPE) throw new Error(`Field ${email.qid} is not an Email field (it is ${email.type}).`); } else { email = emails[0]; if (!email) throw new Error("The form has no Email field."); } const wanted = choice.statusField?.trim() || choice.defaultStatusLabel; const status = pick(wanted, true) ?? null; if (!status && choice.statusField) throw new Error(`The form has no field "${choice.statusField}" for the status.`); if (status && !STATUS_FIELD_TYPES.includes(status.type)) { throw new Error( `Field ${status.qid} ("${status.text}") is ${status.type}: the status is written only to a Short Text or Long Text field.` ); } if (status && status.qid === email.qid) throw new Error("The status field cannot be the Email field."); return { email, status }; } function editedOf(created, updated) { const u = typeof updated === "string" ? updated.trim() : ""; if (u === "" || /^0{4}-0{2}-0{2}/.test(u)) return false; return u !== (typeof created === "string" ? created.trim() : ""); } function heldStatus(s) { return s.edited ? s.statusValue : ""; } function prefilledStatus(s) { return s.statusValue !== "" && !s.edited; } function answerText(answers, qid) { const a = answers[qid]; if (!isRecord(a)) return ""; const v = a.answer; return typeof v === "string" ? v.trim() : ""; } function submissionOf(value, fields) { if (!isRecord(value)) return null; const id = text(value, "id"); if (!ID_PATTERN.test(id)) return null; const answers = isRecord(value.answers) ? value.answers : {}; return { id, formId: text(value, "form_id"), email: answerText(answers, fields.email), statusValue: fields.status ? answerText(answers, fields.status) : "", edited: editedOf(value.created_at, value.updated_at) }; } async function getSubmission(config, submissionId, fields, wrap = direct) { const { content } = await wrap( () => jotformCall(config, "GET", `/submission/${checkId("The submission id", submissionId)}`) ); return submissionOf(content, fields); } async function writeStatus(config, submissionId, statusQid, value, wrap = direct) { const qid = checkId("The status field", statusQid); await wrap( () => jotformCall(config, "POST", `/submission/${checkId("The submission id", submissionId)}`, { form: { [`submission[${qid}]`]: value } }) ); } function statusText(status, reason, checkedAt) { const at = Number.isNaN(Date.parse(checkedAt)) ? "" : new Date(checkedAt).toISOString().replace(/\.\d{3}Z$/, "Z"); return `${status} (${reason || "none"})${at ? `, checked ${at}` : ""}`; } var OURS = new RegExp(`^(${STATUSES.join("|")}) \\(`); function isOurValue(value) { return OURS.test(value); } function plausibleAddress(value) { return /^[^\s@:/]+@[^\s@:/?#]+$/.test(value) && value.length <= 320; } // integrations/jotform/src/handler.ts var SEEN_MS = 24 * 36e5; var MAX_SEEN = 5e3; var FIELDS_MS = 5 * 6e4; var CHECK_TIMEOUT_S = 10; var CHECK_CALL_TIMEOUT_MS = 13e3; var JOTFORM_TIMEOUT_MS = 5e3; var WRITE_AFTER_MS = 1500; var SEEN = /* @__PURE__ */ new Map(); var FORMS = /* @__PURE__ */ new Map(); function answer(status, body) { return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } }); } function configOf(env, fetch) { try { const token = checkKey("RELAY_TOKEN", env.RELAY_TOKEN); if (token.length < MIN_RELAY_TOKEN_LENGTH || !/^[A-Za-z0-9_-]+$/.test(token)) return null; const formIds = (env.FORM_IDS ?? "").split(",").map((s) => s.trim()).filter((s) => s !== ""); if (formIds.some((id) => !ID_PATTERN.test(id))) return null; return { evKey: checkKey("EV_API_KEY", env.EV_API_KEY), jotform: { apiKey: checkKey("JOTFORM_API_KEY", env.JOTFORM_API_KEY), region: jotformRegionOf(env.JOTFORM_REGION), userAgent: USER_AGENT, fetch, timeoutMs: JOTFORM_TIMEOUT_MS }, token, region: regionOf(env.EV_REGION), formIds, emailField: env.EMAIL_FIELD?.trim() || void 0, statusField: env.STATUS_FIELD?.trim() || void 0 }; } catch { return null; } } function sameSecret(a, b) { const x = new TextEncoder().encode(a); const y = new TextEncoder().encode(b); let diff = x.length ^ y.length; for (let i = 0; i < Math.max(x.length, y.length); i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0); return diff === 0; } function forget(seen, now) { for (const [id, at] of seen) { if (now - at < SEEN_MS && seen.size <= MAX_SEEN) break; seen.delete(id); } } async function readCapped(request, max) { if (!request.body) return new Uint8Array(0); const reader = request.body.getReader(); const chunks = []; let size = 0; for (; ; ) { const { done, value } = await reader.read(); if (done) break; size += value.byteLength; if (size > max) { await reader.cancel().catch(() => { }); return null; } chunks.push(value); } const out = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength; } return out; } async function handle(request, env, ctx, deps = {}) { const config = configOf(env, deps.fetch); if (!config) return answer(500, { error: "relay_not_configured" }); const url = new URL(request.url); if (!sameSecret(url.pathname, `/${config.token}`)) return answer(401, { error: "unauthorized" }); if (request.method !== "POST") return answer(405, { error: "method_not_allowed" }); const declared = Number(request.headers.get("content-length") ?? "0"); if (!(declared <= MAX_WEBHOOK_BYTES)) return answer(413, { error: "too_large" }); let form; try { const bytes = await readCapped(request, MAX_WEBHOOK_BYTES); if (bytes === null) return answer(413, { error: "too_large" }); form = await new Request("https://relay.invalid/", { method: "POST", headers: { "Content-Type": request.headers.get("content-type") ?? "" }, body: bytes }).formData(); } catch { return answer(400, { error: "not_form_data" }); } const field = (name) => { const v = form.get(name); return typeof v === "string" ? v.trim() : ""; }; const submissionId = field("submissionID"); const formId = field("formID"); if (!ID_PATTERN.test(submissionId) || !ID_PATTERN.test(formId)) return answer(400, { error: "no_submission_id" }); if (config.formIds.length && !config.formIds.includes(formId)) return answer(200, { result: "ignored", reason: "form" }); const now = deps.now ?? Date.now; const seen = deps.seen ?? SEEN; forget(seen, now()); if (seen.has(submissionId)) return answer(200, { result: "ignored", reason: "duplicate" }); seen.set(submissionId, now()); const work = processSubmission(config, formId, submissionId, { arrivedAt: now(), ...deps, now, seen }); if (ctx) { ctx.waitUntil(work); return answer(200, { result: "accepted" }); } await work; return answer(200, { result: "accepted" }); } async function processSubmission(config, formId, submissionId, deps) { const log = deps.log ?? ((line2) => console.log(line2)); const forms = deps.forms ?? FORMS; const line = (fields) => log(JSON.stringify({ form_id: formId, submission_id: submissionId, ...fields })); let checked = false; try { let cached = forms.get(formId); if (!cached || deps.now() - cached.at > FIELDS_MS) { const fields = fieldsOf(await getQuestions(config.jotform, formId), { emailField: config.emailField, statusField: config.statusField, defaultStatusLabel: DEFAULT_STATUS_LABEL }); cached = { at: deps.now(), fields }; forms.set(formId, cached); } const { email, status } = cached.fields; if (!status) { line({ result: "skipped", reason: "no_status_field" }); return; } const s = await getSubmission(config.jotform, submissionId, { email: email.qid, status: status.qid }); if (!s || s.formId !== formId) { line({ result: "ignored", reason: "not_this_form" }); return; } const held = heldStatus(s); if (held !== "") { line({ result: "skipped", reason: isOurValue(held) ? "already_checked" : "status_field_in_use" }); return; } const prefilled = prefilledStatus(s) ? { prefilled: true } : {}; if (!plausibleAddress(s.email)) { line({ result: "skipped", reason: "no_address" }); return; } const v = await validateEmail( { apiKey: config.evKey, region: config.region, fetch: config.jotform.fetch, userAgent: USER_AGENT, timeoutMs: CHECK_CALL_TIMEOUT_MS }, s.email, { timeout: CHECK_TIMEOUT_S } ); checked = true; const at = v.processed_at || new Date(deps.now()).toISOString(); const sleep = deps.sleep ?? realSleep; const wait = (deps.arrivedAt ?? deps.now()) + WRITE_AFTER_MS - deps.now(); if (wait > 0) await sleep(wait); try { await writeStatus( config.jotform, submissionId, status.qid, statusText(v.status, v.reason, at), (fn) => withRetries(fn, { attempts: 2, maxWaitS: 1, sleep }) ); line({ result: "checked", status: v.status, reason: v.reason, action: v.action, written: true, ...prefilled }); } catch (err) { line({ result: "checked", status: v.status, reason: v.reason, action: v.action, written: false, error: err instanceof CallError ? err.code : "unexpected_error", ...prefilled }); } } catch (err) { const unanswered = err instanceof CallError && err.service === "email-validation" && err.status === 0; if (!checked && !unanswered) deps.seen.delete(submissionId); line({ result: "failed", error: err instanceof CallError ? err.code : "invalid_fields", service: err instanceof CallError ? err.service : "relay", request_id: err instanceof CallError ? err.requestId : null }); } } // integrations/jotform/src/relay.ts var relay_default = { fetch(request, env, ctx) { return handle(request, env, ctx); } }; export { relay_default as default };