@formular-now/js 0.0.0-stage → 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 +21 -0
- package/README.md +116 -2
- package/dist/index.d.ts +58 -0
- package/dist/index.js +167 -0
- package/package.json +24 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Richard Neuhaus (Netomic)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,117 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @formular-now/js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Send forms to [formular.now](https://formular.now) from JavaScript. The invisible bot check is built in: visitors never see a captcha.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @formular-now/js
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
11
|
+
Create a handle with the form's public key from the dashboard ("fn_…") and pass it the form:
|
|
12
|
+
|
|
13
|
+
```js
|
|
14
|
+
import { formularNow } from "@formular-now/js";
|
|
15
|
+
|
|
16
|
+
const contact = formularNow("fn_…");
|
|
17
|
+
const form = document.querySelector("#contact");
|
|
18
|
+
|
|
19
|
+
// Optional: solve the bot check while the visitor is still typing.
|
|
20
|
+
form.addEventListener("focusin", () => contact.prepare());
|
|
21
|
+
|
|
22
|
+
form.addEventListener("submit", async (event) => {
|
|
23
|
+
event.preventDefault();
|
|
24
|
+
try {
|
|
25
|
+
await contact.submit(form);
|
|
26
|
+
form.reset();
|
|
27
|
+
} catch (error) {
|
|
28
|
+
alert(error.message);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`submit()` takes a form element, a `FormData` or a plain object:
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
await contact.submit({ name: "Ada", email: "ada@example.com", topics: ["a", "b"] });
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### React
|
|
40
|
+
|
|
41
|
+
```jsx
|
|
42
|
+
import { useState } from "react";
|
|
43
|
+
import { formularNow } from "@formular-now/js";
|
|
44
|
+
|
|
45
|
+
const contact = formularNow("fn_…");
|
|
46
|
+
|
|
47
|
+
export function ContactForm() {
|
|
48
|
+
const [state, setState] = useState("idle");
|
|
49
|
+
const [error, setError] = useState("");
|
|
50
|
+
|
|
51
|
+
async function handleSubmit(event) {
|
|
52
|
+
event.preventDefault();
|
|
53
|
+
setState("sending");
|
|
54
|
+
setError("");
|
|
55
|
+
try {
|
|
56
|
+
await contact.submit(event.currentTarget);
|
|
57
|
+
setState("sent");
|
|
58
|
+
} catch (caught) {
|
|
59
|
+
setError(caught.message);
|
|
60
|
+
setState("idle");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (state === "sent") return <p>Thank you! Your message has arrived.</p>;
|
|
65
|
+
|
|
66
|
+
return (
|
|
67
|
+
<form onSubmit={handleSubmit} onFocus={() => contact.prepare()}>
|
|
68
|
+
<label>Name <input name="name" autoComplete="name" required /></label>
|
|
69
|
+
<label>Email <input name="email" type="email" autoComplete="email" required /></label>
|
|
70
|
+
<label>Message <textarea name="message" rows={5} required /></label>
|
|
71
|
+
{error && <p role="alert">{error}</p>}
|
|
72
|
+
<button type="submit" disabled={state === "sending"}>Send</button>
|
|
73
|
+
</form>
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Options
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
formularNow("fn_…", { botCheck: true, language: "en", baseUrl: "https://formular.now" });
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
| Option | Default | Meaning |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `botCheck` | `true` | Solve the invisible bot check in the browser before sending. |
|
|
87
|
+
| `language` | visitor's browser language | Language of error messages, `"de"` or `"en"`. Set it when they should match your page. |
|
|
88
|
+
| `baseUrl` | `https://formular.now` | Origin of the formular.now instance. |
|
|
89
|
+
|
|
90
|
+
`botCheck` only controls what the browser does. Whether a submission without a solved check is accepted, filed as spam or rejected is the form's "Invisible bot check" setting in the dashboard. Set `botCheck: false` for forms where that setting is off, so visitors' browsers skip the work. The bot check is part of the Standard and Premium plans.
|
|
91
|
+
|
|
92
|
+
## Errors
|
|
93
|
+
|
|
94
|
+
`submit()` rejects with a `FormularNowError`:
|
|
95
|
+
|
|
96
|
+
| Property | Meaning |
|
|
97
|
+
| --- | --- |
|
|
98
|
+
| `message` | The server's text, suitable for showing to the visitor. It is in English or German: the `language` option decides, otherwise the visitor's browser language. |
|
|
99
|
+
| `code` | Machine-readable reason, for example `origin_not_allowed`, `cap_required` or `network_error`. |
|
|
100
|
+
| `status` | HTTP status, or `0` if no response arrived. |
|
|
101
|
+
| `requestId` | Quote this ID when contacting support. |
|
|
102
|
+
|
|
103
|
+
## How the bot check works
|
|
104
|
+
|
|
105
|
+
The package itself is a small loader. On the first `prepare()` or `submit()` it adds `<script src="https://formular.now/embed.js">` to the page, which solves a proof of work in the background and returns a single-use token for this form. Because the solver comes from formular.now, it always matches the server and needs no update of this package.
|
|
106
|
+
|
|
107
|
+
If the script cannot load (blocked, offline), the submission is sent without a token and the form's dashboard setting decides.
|
|
108
|
+
|
|
109
|
+
Websites with a Content-Security-Policy must allow `https://formular.now` in `script-src` and `connect-src`, and `worker-src blob:`.
|
|
110
|
+
|
|
111
|
+
## Server-side rendering
|
|
112
|
+
|
|
113
|
+
Importing the package and calling `formularNow()` is safe on the server. Submissions belong in the browser: the bot check needs one, and forms with an allowlist of websites only accept requests with a matching `Origin`.
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
export interface FormularNowOptions {
|
|
2
|
+
/**
|
|
3
|
+
* Runs the invisible bot check before sending. Defaults to `true`.
|
|
4
|
+
*
|
|
5
|
+
* This only controls whether the browser solves the check. What happens to submissions that
|
|
6
|
+
* arrive without one (accept, spam folder or reject) is the form's setting in the dashboard.
|
|
7
|
+
*/
|
|
8
|
+
botCheck?: boolean;
|
|
9
|
+
/** Origin of the formular.now instance. Defaults to `https://formular.now`. */
|
|
10
|
+
baseUrl?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Language of error messages: `"de"` or `"en"`. Without it the server answers in the
|
|
13
|
+
* visitor's browser language; set it when the messages should match your page instead.
|
|
14
|
+
*/
|
|
15
|
+
language?: Language;
|
|
16
|
+
}
|
|
17
|
+
export type Language = "de" | "en";
|
|
18
|
+
export type FieldValue = string | number | boolean | Blob | null | undefined;
|
|
19
|
+
/** A form element, a `FormData`, or a plain object of field names and values. */
|
|
20
|
+
export type SubmitData = HTMLFormElement | FormData | Record<string, FieldValue | FieldValue[]>;
|
|
21
|
+
export interface SubmitResult {
|
|
22
|
+
submissionId: string;
|
|
23
|
+
}
|
|
24
|
+
export interface FormularNowForm {
|
|
25
|
+
/** The form's public submission endpoint. */
|
|
26
|
+
readonly endpoint: string;
|
|
27
|
+
/**
|
|
28
|
+
* Starts the bot check in the background, so `submit()` does not have to wait for it. Call it
|
|
29
|
+
* when the visitor first touches the form. Does nothing with `botCheck: false` or on a server.
|
|
30
|
+
*/
|
|
31
|
+
prepare(): void;
|
|
32
|
+
/** Sends one submission. Rejects with a {@link FormularNowError} if it was not accepted. */
|
|
33
|
+
submit(data: SubmitData): Promise<SubmitResult>;
|
|
34
|
+
}
|
|
35
|
+
/** A submission that was not accepted. `message` is the server's text for the visitor. */
|
|
36
|
+
export declare class FormularNowError extends Error {
|
|
37
|
+
/** Machine-readable reason such as `origin_not_allowed`, `cap_required` or `network_error`. */
|
|
38
|
+
readonly code: string;
|
|
39
|
+
/** HTTP status, or 0 if no response arrived. */
|
|
40
|
+
readonly status: number;
|
|
41
|
+
/** Quote this ID when contacting support. */
|
|
42
|
+
readonly requestId: string | undefined;
|
|
43
|
+
readonly details: unknown;
|
|
44
|
+
constructor(code: string, status: number, message: string, extra?: {
|
|
45
|
+
requestId?: string;
|
|
46
|
+
details?: unknown;
|
|
47
|
+
cause?: unknown;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Creates a handle for one form. `formId` is the form's public key from the dashboard ("fn_…").
|
|
52
|
+
*
|
|
53
|
+
* ```ts
|
|
54
|
+
* const contact = formularNow("fn_…");
|
|
55
|
+
* await contact.submit(formElement);
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
export declare function formularNow(formId: string, options?: FormularNowOptions): FormularNowForm;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
const DEFAULT_BASE_URL = "https://formular.now";
|
|
2
|
+
const TOKEN_FIELD = "cap-token";
|
|
3
|
+
const SCRIPT_TIMEOUT_MS = 10_000;
|
|
4
|
+
/** A submission that was not accepted. `message` is the server's text for the visitor. */
|
|
5
|
+
export class FormularNowError extends Error {
|
|
6
|
+
/** Machine-readable reason such as `origin_not_allowed`, `cap_required` or `network_error`. */
|
|
7
|
+
code;
|
|
8
|
+
/** HTTP status, or 0 if no response arrived. */
|
|
9
|
+
status;
|
|
10
|
+
/** Quote this ID when contacting support. */
|
|
11
|
+
requestId;
|
|
12
|
+
details;
|
|
13
|
+
constructor(code, status, message, extra = {}) {
|
|
14
|
+
super(message, extra.cause === undefined ? undefined : { cause: extra.cause });
|
|
15
|
+
this.name = "FormularNowError";
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.requestId = extra.requestId;
|
|
19
|
+
this.details = extra.details;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Creates a handle for one form. `formId` is the form's public key from the dashboard ("fn_…").
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* const contact = formularNow("fn_…");
|
|
27
|
+
* await contact.submit(formElement);
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export function formularNow(formId, options = {}) {
|
|
31
|
+
if (typeof formId !== "string" || !formId.trim()) {
|
|
32
|
+
throw new TypeError("formularNow() needs the form's public key, for example \"fn_…\".");
|
|
33
|
+
}
|
|
34
|
+
const key = formId.trim();
|
|
35
|
+
const base = new URL(options.baseUrl ?? DEFAULT_BASE_URL).origin;
|
|
36
|
+
const botCheck = options.botCheck ?? true;
|
|
37
|
+
const language = options.language;
|
|
38
|
+
if (language !== undefined && language !== "de" && language !== "en") {
|
|
39
|
+
throw new TypeError('formularNow(): "language" must be "de" or "en".');
|
|
40
|
+
}
|
|
41
|
+
const endpoint = `${base}/f/${encodeURIComponent(key)}`;
|
|
42
|
+
return {
|
|
43
|
+
endpoint,
|
|
44
|
+
prepare() {
|
|
45
|
+
if (!botCheck)
|
|
46
|
+
return;
|
|
47
|
+
void loadEmbed(base).then((embed) => embed?.prepare?.(key));
|
|
48
|
+
},
|
|
49
|
+
async submit(data) {
|
|
50
|
+
const body = toFormData(data);
|
|
51
|
+
// A token left over from an earlier attempt is spent; the server would reject it.
|
|
52
|
+
body.delete(TOKEN_FIELD);
|
|
53
|
+
if (botCheck) {
|
|
54
|
+
const embed = await loadEmbed(base);
|
|
55
|
+
// Without a token the submission still goes out and the form's setting decides.
|
|
56
|
+
const token = embed ? await embed.token(key) : null;
|
|
57
|
+
if (token)
|
|
58
|
+
body.set(TOKEN_FIELD, token);
|
|
59
|
+
}
|
|
60
|
+
return send(endpoint, body, language);
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** The two messages this package words itself; all others come from the server. */
|
|
65
|
+
const OWN_MESSAGES = {
|
|
66
|
+
en: { network: "The submission could not be sent.", rejected: (status) => `The submission was not accepted (HTTP ${status}).` },
|
|
67
|
+
de: { network: "Die Einsendung konnte nicht gesendet werden.", rejected: (status) => `Die Einsendung wurde nicht angenommen (HTTP ${status}).` },
|
|
68
|
+
};
|
|
69
|
+
async function send(endpoint, body, language) {
|
|
70
|
+
const own = OWN_MESSAGES[language ?? "en"];
|
|
71
|
+
// The server words its messages after this header; browsers fill it in when it is left out.
|
|
72
|
+
const headers = language ? { Accept: "application/json", "Accept-Language": language } : { Accept: "application/json" };
|
|
73
|
+
let response;
|
|
74
|
+
try {
|
|
75
|
+
response = await fetch(endpoint, { method: "POST", headers, body });
|
|
76
|
+
}
|
|
77
|
+
catch (cause) {
|
|
78
|
+
throw new FormularNowError("network_error", 0, own.network, { cause });
|
|
79
|
+
}
|
|
80
|
+
const payload = await response.json().catch(() => null);
|
|
81
|
+
if (!response.ok || !payload?.submissionId) {
|
|
82
|
+
const error = payload?.error;
|
|
83
|
+
throw new FormularNowError(error?.code ?? "unexpected_response", response.status, error?.message ?? own.rejected(response.status), { requestId: error?.requestId, details: error?.details });
|
|
84
|
+
}
|
|
85
|
+
return { submissionId: payload.submissionId };
|
|
86
|
+
}
|
|
87
|
+
/** Always a copy, so the caller's FormData never receives the token. */
|
|
88
|
+
function toFormData(data) {
|
|
89
|
+
if (typeof HTMLFormElement !== "undefined" && data instanceof HTMLFormElement)
|
|
90
|
+
return new FormData(data);
|
|
91
|
+
const body = new FormData();
|
|
92
|
+
if (data instanceof FormData) {
|
|
93
|
+
for (const [name, value] of data)
|
|
94
|
+
body.append(name, value);
|
|
95
|
+
return body;
|
|
96
|
+
}
|
|
97
|
+
if (!data || typeof data !== "object") {
|
|
98
|
+
throw new TypeError("submit() needs a form element, a FormData or an object of fields.");
|
|
99
|
+
}
|
|
100
|
+
for (const [name, value] of Object.entries(data)) {
|
|
101
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
102
|
+
if (item === null || item === undefined)
|
|
103
|
+
continue;
|
|
104
|
+
body.append(name, item instanceof Blob ? item : String(item));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return body;
|
|
108
|
+
}
|
|
109
|
+
function embedApi() {
|
|
110
|
+
const api = window.formularNow;
|
|
111
|
+
return api && typeof api.token === "function" ? api : null;
|
|
112
|
+
}
|
|
113
|
+
const loading = new Map();
|
|
114
|
+
/**
|
|
115
|
+
* Loads embed.js from formular.now once per page. Widget and WASM solver stay on the version
|
|
116
|
+
* the server expects, without a release of this package. Resolves to null if the script cannot
|
|
117
|
+
* load (blocked, offline, server-side rendering); the next call tries again.
|
|
118
|
+
*/
|
|
119
|
+
function loadEmbed(base) {
|
|
120
|
+
if (typeof document === "undefined")
|
|
121
|
+
return Promise.resolve(null);
|
|
122
|
+
const ready = embedApi();
|
|
123
|
+
if (ready)
|
|
124
|
+
return Promise.resolve(ready);
|
|
125
|
+
let pending = loading.get(base);
|
|
126
|
+
if (!pending) {
|
|
127
|
+
pending = loadScript(`${base}/embed.js`)
|
|
128
|
+
.then(embedApi, (error) => {
|
|
129
|
+
console.warn("[formular.now] The bot check could not be loaded:", error);
|
|
130
|
+
return null;
|
|
131
|
+
})
|
|
132
|
+
.then((api) => {
|
|
133
|
+
if (!api)
|
|
134
|
+
loading.delete(base);
|
|
135
|
+
return api;
|
|
136
|
+
});
|
|
137
|
+
loading.set(base, pending);
|
|
138
|
+
}
|
|
139
|
+
return pending;
|
|
140
|
+
}
|
|
141
|
+
function loadScript(src) {
|
|
142
|
+
return new Promise((resolve, reject) => {
|
|
143
|
+
// The page may already include the script tag itself; wait for that one instead.
|
|
144
|
+
const existing = Array.from(document.scripts).find((candidate) => candidate.src === src);
|
|
145
|
+
const script = existing ?? document.createElement("script");
|
|
146
|
+
const finish = (error) => {
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
script.removeEventListener("load", onLoad);
|
|
149
|
+
script.removeEventListener("error", onError);
|
|
150
|
+
if (!error)
|
|
151
|
+
return resolve();
|
|
152
|
+
if (!existing)
|
|
153
|
+
script.remove(); // so that the next attempt can add a fresh one
|
|
154
|
+
reject(error);
|
|
155
|
+
};
|
|
156
|
+
const onLoad = () => finish();
|
|
157
|
+
const onError = () => finish(new Error(`${src} failed to load`));
|
|
158
|
+
const timer = setTimeout(() => finish(new Error(`${src} did not load within ${SCRIPT_TIMEOUT_MS / 1000} s`)), SCRIPT_TIMEOUT_MS);
|
|
159
|
+
script.addEventListener("load", onLoad);
|
|
160
|
+
script.addEventListener("error", onError);
|
|
161
|
+
if (!existing) {
|
|
162
|
+
script.src = src;
|
|
163
|
+
script.async = true;
|
|
164
|
+
document.head.append(script);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@formular-now/js",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Send forms to formular.now from JavaScript, with the invisible bot check built in.",
|
|
5
|
+
"keywords": ["formular.now", "forms", "form-backend", "contact-form", "captcha", "spam"],
|
|
6
|
+
"homepage": "https://formular.now",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"sideEffects": false,
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"files": ["dist"],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "tsc -p tsconfig.json",
|
|
21
|
+
"prepack": "npm run build"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
}
|
|
26
|
+
}
|