@sharadox/form-web-library 0.1.0 → 0.2.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/LICENSE.md CHANGED
@@ -1,40 +1,40 @@
1
- # Sharadox Open Source Licence
1
+ # Sharadox Open Source License
2
2
 
3
3
  Version 0.1.0
4
4
 
5
- This is an informative English translation. The Portuguese text (`LICENCA.md`) is the only original and binding text of this licence; if the two differ, the Portuguese text prevails.
5
+ This is an informative English translation. The Portuguese text (`LICENCA.md`) is the only original and binding text of this license; if the two differ, the Portuguese text prevails.
6
6
 
7
7
  ## 1. Definitions
8
8
 
9
- For the purposes of this licence:
9
+ For the purposes of this license:
10
10
 
11
- 1. **"Work"** — the computer program, its documentation and any other content made available by the Licensor under this licence, in source code or in any other form.
11
+ 1. **"Work"** — the computer program, its documentation and any other content made available by the Licensor under this license, in source code or in any other form.
12
12
  2. **"Licensor"** — the copyright holder identified in the copyright notice that accompanies the Work.
13
- 3. **"Licensee"** — any natural or legal person exercising the rights granted by this licence.
13
+ 3. **"Licensee"** — any natural or legal person exercising the rights granted by this license.
14
14
  4. **"Derivative Work"** — any work based on or incorporating the Work, in whole or in part, with or without modifications, including translations, adaptations and programs that integrate it.
15
- 5. **"Notice"** — the Licensor's copyright notice and the statement that the Work is licensed under this licence, including its version.
15
+ 5. **"Notice"** — the Licensor's copyright notice and the statement that the Work is licensed under this license, including its version.
16
16
 
17
17
  ## 2. Grant of rights
18
18
 
19
- 1. Under this licence, the Licensor grants the Licensee a worldwide, royalty-free, non-exclusive licence, for the whole term of copyright protection, to:
19
+ 1. Under this license, the Licensor grants the Licensee a worldwide, royalty-free, non-exclusive license, for the whole term of copyright protection, to:
20
20
  1. use the Work for any purpose, including commercial purposes;
21
21
  2. reproduce the Work, in whole or in part, by any means and in any form;
22
22
  3. modify, translate, adapt and transform the Work and create Derivative Works;
23
23
  4. distribute, publish, communicate to the public, make available, sell and sublicense the Work and Derivative Works.
24
- 2. To the extent the Licensor holds patents necessarily infringed by the Work as made available by it, the Licensor also grants the Licensee, on the same terms, a licence to use those patents in exercising the rights in the previous paragraph.
25
- 3. This licence does not transfer ownership of any rights, which remain with the Licensor.
24
+ 2. To the extent the Licensor holds patents necessarily infringed by the Work as made available by it, the Licensor also grants the Licensee, on the same terms, a license to use those patents in exercising the rights in the previous paragraph.
25
+ 3. This license does not transfer ownership of any rights, which remain with the Licensor.
26
26
 
27
27
  ## 3. Conditions
28
28
 
29
29
  The exercise of the rights granted is subject to the following conditions:
30
30
 
31
- 1. Every copy of the Work, or of substantial parts of it, and every distributed Derivative Work must include the Notice and a copy of this licence or a stable link to its text.
31
+ 1. Every copy of the Work, or of substantial parts of it, and every distributed Derivative Work must include the Notice and a copy of this license or a stable link to its text.
32
32
  2. Anyone distributing a modified version of the Work must state visibly that it has been modified and may not present it as the Licensor's original version.
33
- 3. The Licensee may license their own modifications under other terms, provided the part of the Work included in them remains subject to the conditions of this licence.
33
+ 3. The Licensee may license their own modifications under other terms, provided the part of the Work included in them remains subject to the conditions of this license.
34
34
 
35
35
  ## 4. Names and trademarks
36
36
 
37
- This licence grants no rights to the Licensor's name, trademarks, logos or other distinctive signs, including the name "Sharadox", except as strictly necessary to comply with the duty to include the Notice. Using them to promote or suggest the Licensor's endorsement of Derivative Works or of any products or services without prior written permission is prohibited.
37
+ This license grants no rights to the Licensor's name, trademarks, logos or other distinctive signs, including the name "Sharadox", except as strictly necessary to comply with the duty to include the Notice. Using them to promote or suggest the Licensor's endorsement of Derivative Works or of any products or services without prior written permission is prohibited.
38
38
 
39
39
  ## 5. Disclaimer of warranties
40
40
 
@@ -43,29 +43,29 @@ The Work is provided "as is" and "as available", without any warranty, express o
43
43
  ## 6. Limitation of liability
44
44
 
45
45
  1. To the maximum extent permitted by applicable law, the Licensor is not liable for any damages, direct or indirect, including loss of profits, loss of data or business interruption, arising from the use of or inability to use the Work, even if advised of the possibility of such damages.
46
- 2. Nothing in this licence excludes or limits the Licensor's liability where such exclusion or limitation is not permitted by law, in particular for acts committed with intent or gross negligence, under article 809 and article 800(2) of the Portuguese Civil Code, nor does it affect rights that the law mandatorily grants to consumers.
46
+ 2. Nothing in this license excludes or limits the Licensor's liability where such exclusion or limitation is not permitted by law, in particular for acts committed with intent or gross negligence, under article 809 and article 800(2) of the Portuguese Civil Code, nor does it affect rights that the law mandatorily grants to consumers.
47
47
 
48
48
  ## 7. Termination
49
49
 
50
- 1. The rights granted by this licence terminate automatically if the Licensee breaches any of its conditions.
50
+ 1. The rights granted by this license terminate automatically if the Licensee breaches any of its conditions.
51
51
  2. The rights are reinstated if the breach is remedied within 30 days of the Licensee becoming aware of it, unless the Licensor has meanwhile objected in writing.
52
- 3. Termination does not affect licences validly granted by the Licensee to third parties who comply with this licence.
52
+ 3. Termination does not affect licenses validly granted by the Licensee to third parties who comply with this license.
53
53
 
54
54
  ## 8. Governing law and jurisdiction
55
55
 
56
- 1. This licence is governed by Portuguese law, in particular the Code of Copyright and Related Rights, approved by Decree-Law no. 63/85 of 14 March, and Decree-Law no. 252/94 of 20 October on the legal protection of computer programs.
57
- 2. The Judicial Court of the District of Faro has jurisdiction over any dispute arising from this licence, without prejudice to applicable mandatory rules of jurisdiction, in particular those protecting consumers.
56
+ 1. This license is governed by Portuguese law, in particular the Code of Copyright and Related Rights, approved by Decree-Law no. 63/85 of 14 March, and Decree-Law no. 252/94 of 20 October on the legal protection of computer programs.
57
+ 2. The Judicial Court of the District of Faro has jurisdiction over any dispute arising from this license, without prejudice to applicable mandatory rules of jurisdiction, in particular those protecting consumers.
58
58
 
59
- ## 9. Licence versions
59
+ ## 9. License versions
60
60
 
61
- The Licensor may publish new versions of this licence, identified by a version number. The Work is subject to the version stated in the Notice. If the Notice allows it, the Licensee may choose any later version.
61
+ The Licensor may publish new versions of this license, identified by a version number. The Work is subject to the version stated in the Notice. If the Notice allows it, the Licensee may choose any later version.
62
62
 
63
63
  ## 10. Final provisions
64
64
 
65
- 1. If any provision of this licence is held invalid or unenforceable, the remaining provisions stay in force, and the affected provision shall be interpreted as closely as possible to its original intent.
66
- 2. Failure to enforce any provision of this licence at any time does not waive the right to enforce it later.
65
+ 1. If any provision of this license is held invalid or unenforceable, the remaining provisions stay in force, and the affected provision shall be interpreted as closely as possible to its original intent.
66
+ 2. Failure to enforce any provision of this license at any time does not waive the right to enforce it later.
67
67
 
68
- ## How to apply this licence
68
+ ## How to apply this license
69
69
 
70
70
  Include in the Work a `LICENCA.md` file with the Portuguese text, this translation as `LICENSE.md`, and the following notice, filling in the year and holder:
71
71
 
package/README.md CHANGED
@@ -6,6 +6,11 @@ Forms on the server, written once for every site:
6
6
  - **Bot checks:** a hidden honeypot field, and a minimum time to fill the form.
7
7
  - **Rate limiting:** a sliding window per key.
8
8
  - **A contact form action:** it validates, fakes success for bots, limits each address, and emails the message in text and HTML with the visitor as reply-to, through `@sharadox/email-web-library`.
9
+ - **Options per site:**
10
+ - accept a phone instead of an email (`reach: "email-or-phone"`)
11
+ - make the message optional (`requireMessage: false`)
12
+ - add single-line fields (`fields: { place: "Home" }`)
13
+ - write the email in the inbox's language (`labels`)
9
14
 
10
15
  ## Install
11
16
 
@@ -38,7 +43,7 @@ export async function sendContactAction(_: ContactState, form: FormData) {
38
43
 
39
44
  The form sends these fields:
40
45
 
41
- - **text:** `name`, `email`, `company`, `message`
46
+ - **text:** `name`, `email`, `phone`, `company`, `message`, plus any `fields` the site adds
42
47
  - **hidden:** `locale`, and `started-at` (`Date.now()` when the visitor started)
43
48
  - **checkboxes:** `need`
44
49
  - **honeypot:** `website`, kept off screen
@@ -47,18 +52,18 @@ The email server comes from `EMAIL_SERVER_*` and `EMAIL_SENDER_ADDRESS`.
47
52
 
48
53
  ## API
49
54
 
50
- | Import | Export |
51
- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
52
- | `…/contact-action` | `createContactAction(options)` → `(form, ip) => Promise<ContactState>`; `ContactState` and `ContactActionOptions` in `…/contact-action/type` |
53
- | `…/parse-contact` | `parseContact(form, { choices?, choiceField?, now? })` → `bot`, `invalid` or `valid` |
54
- | `…/bot-check` | `isLikelyBot(form, { honeypotField?, startedAtField?, minimumFillTime?, now? })` |
55
- | `…/rate-limit` | `createRateLimiter({ window, maximum })` → `(key, now?) => boolean` (kept in memory, per server instance) |
56
- | `…/field` | `readField(form, name, maximumLength)` |
55
+ | Import | Export |
56
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
57
+ | `…/contact-action` | `createContactAction(options)` → `(form, ip) => Promise<ContactState>`; `ENGLISH_LABELS`; `ContactState`, `ContactActionOptions` and `ContactLabels` in `…/contact-action/type` |
58
+ | `…/parse-contact` | `parseContact(form, { choices?, choiceField?, reach?, requireMessage?, fields?, now? })` → `bot`, `invalid` or `valid` |
59
+ | `…/bot-check` | `isLikelyBot(form, { honeypotField?, startedAtField?, minimumFillTime?, now? })` |
60
+ | `…/rate-limit` | `createRateLimiter({ window, maximum })` → `(key, now?) => boolean` (kept in memory, per server instance) |
61
+ | `…/field` | `readField(form, name, maximumLength)` |
57
62
 
58
63
  ## Develop
59
64
 
60
65
  `pnpm verify` runs formatting, lint, type-check, tests with 100% coverage and the build. Branches follow `<feature>.development` → `development` → `index`, and releases are `v<version>` tags on `index`.
61
66
 
62
- ## Licence
67
+ ## License
63
68
 
64
69
  Licença Sharadox de Código Aberto, versão 0.1.0. See [português](LICENCA.md) (the binding text) and the [English translation](LICENSE.md).
@@ -1,8 +1,11 @@
1
- import type { ContactActionOptions, ContactState } from "@sharadox/form-web-library/contact-action/type";
1
+ import type { ContactActionOptions, ContactLabels, ContactState } from "@sharadox/form-web-library/contact-action/type";
2
+ /** The email's words when the site gives none. */
3
+ export declare const ENGLISH_LABELS: ContactLabels;
2
4
  /**
3
5
  * Builds the work of a contact form's server action: checks for bots (they get a fake success), validates, limits
4
- * each address, then emails the message with the visitor as reply-to, in plain text and HTML (user input escaped).
5
- * The application's server action reads the visitor's IP address and calls the result.
6
+ * each address, then emails the message in plain text and HTML (user input escaped), with the visitor as reply-to
7
+ * when they left an email. Sites can accept a phone instead of an email (`reach`), make the message optional, add
8
+ * fields and write the email in their own language (`labels`).
6
9
  *
7
10
  * @example
8
11
  * const sendContact = createContactAction({ to: "contact@sharadox.com", senderName: "Sharadox Web Application",
@@ -10,5 +13,5 @@ import type { ContactActionOptions, ContactState } from "@sharadox/form-web-libr
10
13
  * // in a "use server" file:
11
14
  * export async function sendContactAction(_: ContactState, form: FormData) { return sendContact(form, ip); }
12
15
  */
13
- export declare function createContactAction({ to, senderName, senderAddress, subject, choices, site, rateLimit, readConfiguration, createSender, reportError, }: ContactActionOptions): (form: FormData, ip: string) => Promise<ContactState>;
16
+ export declare function createContactAction({ to, senderName, senderAddress, subject, choices, site, reach, requireMessage, fields, labels: givenLabels, rateLimit, readConfiguration, createSender, reportError, }: ContactActionOptions): (form: FormData, ip: string) => Promise<ContactState>;
14
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/contact-action/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,gDAAgD,CAAC;AAIzG;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,EAAE,EACF,UAAU,EACV,aAAa,EACb,OAAO,EACP,OAAY,EACZ,IAAI,EACJ,SAAkD,EAClD,iBAAgD,EAChD,YAAgC,EAChC,WAA+D,GAChE,EAAE,oBAAoB,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,CAqC9E"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/contact-action/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,oBAAoB,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,gDAAgD,CAAC;AAIxH,kDAAkD;AAClD,eAAO,MAAM,cAAc,EAAE,aAQ5B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,EAAE,EACF,UAAU,EACV,aAAa,EACb,OAAO,EACP,OAAY,EACZ,IAAI,EACJ,KAAe,EACf,cAAqB,EACrB,MAAW,EACX,MAAM,EAAE,WAAgB,EACxB,SAAkD,EAClD,iBAAgD,EAChD,YAAgC,EAChC,WAA+D,GAChE,EAAE,oBAAoB,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,CA4D9E"}
@@ -4,10 +4,21 @@ import { separate } from "@sharadox/web-library/text/separate";
4
4
  import { createRateLimiter } from "@sharadox/form-web-library/rate-limit";
5
5
  import { parseContact } from "@sharadox/form-web-library/parse-contact";
6
6
  const oneLine = (text) => text.replace(/[\r\n]+/g, " ");
7
+ /** The email's words when the site gives none. */
8
+ export const ENGLISH_LABELS = {
9
+ name: "Name",
10
+ email: "Email",
11
+ phone: "Phone",
12
+ company: "Company",
13
+ needs: "Needs",
14
+ language: "Language",
15
+ from: "New message from",
16
+ };
7
17
  /**
8
18
  * Builds the work of a contact form's server action: checks for bots (they get a fake success), validates, limits
9
- * each address, then emails the message with the visitor as reply-to, in plain text and HTML (user input escaped).
10
- * The application's server action reads the visitor's IP address and calls the result.
19
+ * each address, then emails the message in plain text and HTML (user input escaped), with the visitor as reply-to
20
+ * when they left an email. Sites can accept a phone instead of an email (`reach`), make the message optional, add
21
+ * fields and write the email in their own language (`labels`).
11
22
  *
12
23
  * @example
13
24
  * const sendContact = createContactAction({ to: "contact@sharadox.com", senderName: "Sharadox Web Application",
@@ -15,10 +26,16 @@ const oneLine = (text) => text.replace(/[\r\n]+/g, " ");
15
26
  * // in a "use server" file:
16
27
  * export async function sendContactAction(_: ContactState, form: FormData) { return sendContact(form, ip); }
17
28
  */
18
- export function createContactAction({ to, senderName, senderAddress, subject, choices = {}, site, rateLimit = { window: 60 * 60 * 1000, maximum: 5 }, readConfiguration = readEmailServerConfiguration, createSender = createEmailSender, reportError = (message, error) => console.error(message, error), }) {
29
+ export function createContactAction({ to, senderName, senderAddress, subject, choices = {}, site, reach = "email", requireMessage = true, fields = {}, labels: givenLabels = {}, rateLimit = { window: 60 * 60 * 1000, maximum: 5 }, readConfiguration = readEmailServerConfiguration, createSender = createEmailSender, reportError = (message, error) => console.error(message, error), }) {
19
30
  const allow = createRateLimiter(rateLimit);
31
+ const labels = { ...ENGLISH_LABELS, ...givenLabels };
20
32
  return async (form, ip) => {
21
- const parsed = parseContact(form, { choices: Object.keys(choices) });
33
+ const parsed = parseContact(form, {
34
+ choices: Object.keys(choices),
35
+ reach,
36
+ requireMessage,
37
+ fields: Object.keys(fields),
38
+ });
22
39
  if (parsed.kind === "bot")
23
40
  return { status: "sent" };
24
41
  if (parsed.kind === "invalid")
@@ -27,13 +44,30 @@ export function createContactAction({ to, senderName, senderAddress, subject, ch
27
44
  return { status: "rate-limited" };
28
45
  const message = parsed.value;
29
46
  const named = message.choices.map((choice) => choices[choice]);
30
- const text = `Name: ${message.name}\nEmail: ${message.email}\nCompany: ${message.company || "—"}\nNeeds: ${named.join(", ") || "—"}\nLanguage: ${message.locale}\nIP: ${ip}\n\n${message.message}`;
47
+ const extra = Object.entries(fields).map(([field, label]) => [label, message.fields[field]]);
48
+ const lines = [
49
+ [labels.name, message.name],
50
+ [labels.email, message.email || "—"],
51
+ ...(message.phone ? [[labels.phone, message.phone]] : []),
52
+ [labels.company, message.company || "—"],
53
+ ...extra.map(([label, value]) => [label, value || "—"]),
54
+ [labels.needs, named.join(", ") || "—"],
55
+ [labels.language, message.locale],
56
+ ["IP", ip],
57
+ ];
58
+ const text = `${lines.map(([label, value]) => `${label}: ${value}`).join("\n")}${message.message ? `\n\n${message.message}` : ""}`;
59
+ const contacts = [
60
+ message.email && `<a href="mailto:${escapeHtml(message.email)}">${escapeHtml(message.email)}</a>`,
61
+ message.phone &&
62
+ `<a href="tel:${escapeHtml(message.phone.replace(/[^\d+]/g, ""))}">${escapeHtml(message.phone)}</a>`,
63
+ ];
64
+ const details = extra.filter(([, value]) => value);
31
65
  const html = `<div style="font-family:-apple-system,Segoe UI,sans-serif;font-size:15px;line-height:1.6;color:#111">
32
- <p style="color:#666;font-size:13px;margin:0 0 16px">New message from ${escapeHtml(site)} (${escapeHtml(message.locale)})</p>
33
- <p style="margin:0">${separate("·", `<b>${escapeHtml(message.name)}</b>`, message.company && escapeHtml(message.company))}<br><a href="mailto:${escapeHtml(message.email)}">${escapeHtml(message.email)}</a></p>
66
+ <p style="color:#666;font-size:13px;margin:0 0 16px">${escapeHtml(labels.from)} ${escapeHtml(site)} (${escapeHtml(message.locale)})</p>
67
+ <p style="margin:0">${separate("·", `<b>${escapeHtml(message.name)}</b>`, message.company && escapeHtml(message.company))}<br>${separate("·", ...contacts)}</p>
68
+ ${details.length ? `<p style="margin:12px 0 0;color:#444">${details.map(([label, value]) => `${escapeHtml(label)}: ${escapeHtml(value)}`).join("<br>")}</p>` : ""}
34
69
  ${named.length ? `<p style="margin:12px 0 0;color:#444">${escapeHtml(named.join(", "))}</p>` : ""}
35
- <hr style="border:0;border-top:1px solid #eee;margin:18px 0">
36
- <p style="white-space:pre-wrap;margin:0">${escapeHtml(message.message)}</p></div>`;
70
+ ${message.message ? `<hr style="border:0;border-top:1px solid #eee;margin:18px 0">\n <p style="white-space:pre-wrap;margin:0">${escapeHtml(message.message)}</p>` : ""}</div>`;
37
71
  try {
38
72
  const configuration = readConfiguration();
39
73
  await createSender(configuration).send({
@@ -43,7 +77,7 @@ export function createContactAction({ to, senderName, senderAddress, subject, ch
43
77
  },
44
78
  to,
45
79
  // Replying to the email answers the visitor at the address they typed.
46
- replyTo: { name: oneLine(message.name), address: message.email },
80
+ ...(message.email ? { replyTo: { name: oneLine(message.name), address: message.email } } : {}),
47
81
  subject: oneLine(subject(message)).slice(0, 300),
48
82
  text,
49
83
  html,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../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YAC9C,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;QAC9B,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -1,9 +1,20 @@
1
1
  import type { EmailSender, EmailServerConfiguration } from "@sharadox/email-web-library";
2
- import type { ContactMessage } from "@sharadox/form-web-library/parse-contact/type";
2
+ import type { ContactMessage, ContactReach } from "@sharadox/form-web-library/parse-contact/type";
3
3
  /** What the form shows after a submission. */
4
4
  export interface ContactState {
5
5
  status: "idle" | "sent" | "invalid" | "rate-limited" | "failed";
6
6
  }
7
+ /** The words the email uses around the visitor's answers, so the inbox can read it in its own language. */
8
+ export interface ContactLabels {
9
+ name: string;
10
+ email: string;
11
+ phone: string;
12
+ company: string;
13
+ needs: string;
14
+ language: string;
15
+ /** Before the site's name: "New message from". */
16
+ from: string;
17
+ }
7
18
  export interface ContactActionOptions {
8
19
  /** Where messages go, for example "contact@sharadox.com". */
9
20
  to: string;
@@ -17,6 +28,14 @@ export interface ContactActionOptions {
17
28
  choices?: Readonly<Record<string, string>>;
18
29
  /** Where the email says the message came from, for example "sharadox.com". */
19
30
  site: string;
31
+ /** "email" (the default) requires an email; "email-or-phone" accepts either way of answering. */
32
+ reach?: ContactReach;
33
+ /** False lets the message be empty; true by default. */
34
+ requireMessage?: boolean;
35
+ /** Extra single-line fields the form sends, and how each is named in the email, for example `{ place: "Home" }`. */
36
+ fields?: Readonly<Record<string, string>>;
37
+ /** The email's words, in English by default. */
38
+ labels?: Partial<ContactLabels>;
20
39
  /** Messages per address per window; 5 per hour by default. */
21
40
  rateLimit?: {
22
41
  window: number;
@@ -1 +1 @@
1
- {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/contact-action/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACzF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAEpF,8CAA8C;AAC9C,MAA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
@@ -1,11 +1,13 @@
1
1
  import type { ParseContactOptions, ParsedContact } from "@sharadox/form-web-library/parse-contact/type";
2
2
  /**
3
- * Reads and validates a contact form (`name`, `email`, `company`, `message`, `locale` and checkbox choices), and
4
- * flags likely bots (honeypot filled or submitted too fast). Fields are trimmed and capped in length.
3
+ * Reads and validates a contact form (`name`, `email`, `phone`, `company`, `message`, `locale`, checkbox choices and
4
+ * any extra `fields`), and flags likely bots (honeypot filled or submitted too fast). Fields are trimmed and capped in
5
+ * length. By default an email and a message are required; `reach: "email-or-phone"` accepts either way of answering,
6
+ * and `requireMessage: false` an empty message.
5
7
  *
6
8
  * @example
7
9
  * const parsed = parseContact(form, { choices: ["website", "logo", "other"] });
8
10
  * if (parsed.kind === "valid") console.log(parsed.value.choices);
9
11
  */
10
- export declare function parseContact(form: FormData, { choices, choiceField, now }?: ParseContactOptions): ParsedContact;
12
+ export declare function parseContact(form: FormData, { choices, choiceField, reach, requireMessage, fields, now, }?: ParseContactOptions): ParsedContact;
11
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/parse-contact/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,+CAA+C,CAAC;AAIxG;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,EACd,EAAE,OAAY,EAAE,WAAoB,EAAE,GAAgB,EAAE,GAAE,mBAAwB,GACjF,aAAa,CAYf"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/parse-contact/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,+CAA+C,CAAC;AAOxG;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,EACd,EACE,OAAY,EACZ,WAAoB,EACpB,KAAe,EACf,cAAqB,EACrB,MAAW,EACX,GAAgB,GACjB,GAAE,mBAAwB,GAC1B,aAAa,CAmBf"}
@@ -1,26 +1,37 @@
1
1
  import { isLikelyBot } from "@sharadox/form-web-library/bot-check";
2
2
  import { readField } from "@sharadox/form-web-library/field";
3
3
  const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
4
+ /** Digits with the usual phone punctuation, and at least seven digits. */
5
+ const PHONE = /^\+?[\d\s().-]+$/;
6
+ const isPhone = (phone) => PHONE.test(phone) && phone.replace(/\D/g, "").length >= 7;
4
7
  /**
5
- * Reads and validates a contact form (`name`, `email`, `company`, `message`, `locale` and checkbox choices), and
6
- * flags likely bots (honeypot filled or submitted too fast). Fields are trimmed and capped in length.
8
+ * Reads and validates a contact form (`name`, `email`, `phone`, `company`, `message`, `locale`, checkbox choices and
9
+ * any extra `fields`), and flags likely bots (honeypot filled or submitted too fast). Fields are trimmed and capped in
10
+ * length. By default an email and a message are required; `reach: "email-or-phone"` accepts either way of answering,
11
+ * and `requireMessage: false` an empty message.
7
12
  *
8
13
  * @example
9
14
  * const parsed = parseContact(form, { choices: ["website", "logo", "other"] });
10
15
  * if (parsed.kind === "valid") console.log(parsed.value.choices);
11
16
  */
12
- export function parseContact(form, { choices = [], choiceField = "need", now = Date.now() } = {}) {
17
+ export function parseContact(form, { choices = [], choiceField = "need", reach = "email", requireMessage = true, fields = [], now = Date.now(), } = {}) {
13
18
  if (isLikelyBot(form, { now }))
14
19
  return { kind: "bot" };
15
20
  const value = {
16
21
  name: readField(form, "name", 120),
17
22
  email: readField(form, "email", 200),
23
+ phone: readField(form, "phone", 40),
18
24
  company: readField(form, "company", 160),
19
25
  message: readField(form, "message", 5000),
20
26
  locale: readField(form, "locale", 10) || "en",
21
27
  choices: [...new Set(form.getAll(choiceField).map(String))].filter((choice) => choices.includes(choice)),
28
+ fields: Object.fromEntries(fields.map((field) => [field, readField(form, field, 200)])),
22
29
  };
23
- if (!value.name || !value.message || !EMAIL.test(value.email))
30
+ const emailValid = EMAIL.test(value.email);
31
+ const reachable = reach === "email"
32
+ ? emailValid
33
+ : (value.email || value.phone) !== "" && (!value.email || emailValid) && (!value.phone || isPhone(value.phone));
34
+ if (!value.name || (requireMessage && !value.message) || !reachable)
24
35
  return { kind: "invalid" };
25
36
  return { kind: "valid", value };
26
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/parse-contact/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AAG7D,MAAM,KAAK,GAAG,+BAA+B,CAAC;AAE9C;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,IAAc,EACd,EAAE,OAAO,GAAG,EAAE,EAAE,WAAW,GAAG,MAAM,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,KAA0B,EAAE;IAElF,IAAI,WAAW,CAAC,IAAI,EAAE,EAAE,GAAG,EAAE,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IACvD,MAAM,KAAK,GAAG;QACZ,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC;QAClC,KAAK,EAAE,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,CAAC;QACpC,OAAO,EAAE,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,CAAC;QACxC,OAAO,EAAE,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC;QACzC,MAAM,EAAE,SAAS,CAAC,IAAI,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,IAAI;QAC7C,OAAO,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE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C;IAChG,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAClC,CAAC"}
@@ -1,14 +1,20 @@
1
1
  /** A validated contact form submission. */
2
2
  export interface ContactMessage {
3
3
  name: string;
4
+ /** "" when not given (allowed when `reach` is "email-or-phone" and a phone is given). */
4
5
  email: string;
6
+ /** "" when not given. */
7
+ phone: string;
5
8
  /** Optional; "" when not given. */
6
9
  company: string;
10
+ /** "" when not given (allowed when `requireMessage` is false). */
7
11
  message: string;
8
12
  /** The page's locale, sent in a hidden field. */
9
13
  locale: string;
10
14
  /** The ticked choices (for example "what do you need?"), only from the allowed list. */
11
15
  choices: string[];
16
+ /** The extra text fields asked for (`fields`), each "" when not given. */
17
+ fields: Record<string, string>;
12
18
  }
13
19
  export type ParsedContact = {
14
20
  kind: "bot";
@@ -18,11 +24,19 @@ export type ParsedContact = {
18
24
  kind: "valid";
19
25
  value: ContactMessage;
20
26
  };
27
+ /** How the visitor must leave a way to answer them: an email, or at least one of email and phone. */
28
+ export type ContactReach = "email" | "email-or-phone";
21
29
  export interface ParseContactOptions {
22
30
  /** Choice values the form may send; anything else is ignored. None by default. */
23
31
  choices?: readonly string[];
24
32
  /** The checkbox field holding the choices; "need" by default. */
25
33
  choiceField?: string;
34
+ /** "email" (the default) requires a valid email; "email-or-phone" requires either, each valid when given. */
35
+ reach?: ContactReach;
36
+ /** False lets the message be empty; true by default. */
37
+ requireMessage?: boolean;
38
+ /** Extra single-line text fields to read, for example `["place"]`. */
39
+ fields?: readonly string[];
26
40
  /** Now, for the fill-time check (tests). */
27
41
  now?: number;
28
42
  }
@@ -1 +1 @@
1
- {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/parse-contact/type.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,mCAAmC;IACnC,OAAO,EAAE,MAAM,CAAC;IA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,GAAG,OAAO,GAAG,gBAAgB,CAAC;AAEtD,MAAM,WAAW,mBAAmB;IAClC,kFAAkF;IAClF,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,iEAAiE;IACjE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6GAA6G;IAC7G,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB,wDAAwD;IACxD,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,sEAAsE;IACtE,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B,4CAA4C;IAC5C,GAAG,CAAC,EAAE,MAAM,CAAC;CACd"}
package/llms.txt CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  > Server-side forms: bot checks, rate limit, contact action emailing via @sharadox/email-web-library.
4
4
 
5
- - /contact-action: createContactAction({ to, senderName, senderAddress?, site, subject(message), choices?: { key: label }, rateLimit? = 5/hour, readConfiguration?, createSender?, reportError? }) → (form, ip) => { status: idle|sent|invalid|rate-limited|failed }. Reply-to = visitor; bots get fake 'sent'.
6
- - Form fields: name, email, company, message, locale, started-at, website (honeypot), need (checkboxes).
7
- - /parse-contact: parseContact(form, { choices, choiceField='need', now })
5
+ - /contact-action: createContactAction({ to, senderName, senderAddress?, site, subject(message), choices?: { key: label }, reach? = 'email' | 'email-or-phone', requireMessage? = true, fields?: { name: label }, labels?: Partial<ContactLabels> (English default, ENGLISH_LABELS), rateLimit? = 5/hour, readConfiguration?, createSender?, reportError? }) → (form, ip) => { status: idle|sent|invalid|rate-limited|failed }. Reply-to = visitor when they gave an email; bots get fake 'sent'.
6
+ - Form fields: name, email, phone (valid: + digits spaces ().- with ≥7 digits), company, message, extra fields, locale, started-at, website (honeypot), need (checkboxes).
7
+ - /parse-contact: parseContact(form, { choices, choiceField='need', reach, requireMessage, fields, now }) → value { name, email, phone, company, message, locale, choices, fields }
8
8
  - /bot-check isLikelyBot; /rate-limit createRateLimiter({ window, maximum }); /field readField(form, name, max)
9
- - Env: EMAIL_SERVER_HOST/PORT/USERNAME/PASSWORD, EMAIL_SENDER_ADDRESS. Licence: Sharadox Open Source Licence 0.1.0
9
+ - Env: EMAIL_SERVER_HOST/PORT/USERNAME/PASSWORD, EMAIL_SENDER_ADDRESS. License: Sharadox Open Source License 0.1.0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sharadox/form-web-library",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Forms on the server: field reading, honeypot and fill-time bot checks, rate limiting and a contact form action that emails messages with the visitor as reply-to.",
5
5
  "private": false,
6
6
  "license": "SEE LICENSE IN LICENCA.md",
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "sideEffects": false,
31
31
  "engines": {
32
- "node": ">=24"
32
+ "node": ">=26"
33
33
  },
34
34
  "publishConfig": {
35
35
  "access": "public"