fontdue-js 3.15.1 → 3.16.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.
@@ -0,0 +1,131 @@
1
+ // @vitest-environment happy-dom
2
+ // @vitest-environment-options { "url": "https://store.example.com/contests?ref=app" }
3
+
4
+ // A foundry's own events (`fontdue.track()` / `useTrack()`): they carry the
5
+ // same identity as the page's page views – the cookieless anonymous ID while
6
+ // consent is pending, the signed-in customer's token – and never break the
7
+ // page when the server refuses one.
8
+
9
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
10
+ import { sendTrackEvent } from '../components/Tracking/sendTrackEvent.js';
11
+ import { setClientAnonymousId, setConsent } from '../components/ConsentBanner/consent.js';
12
+ import { resetTokenStore, setTokens } from '../auth/tokenStore.js';
13
+ const URL = 'https://fontdue.example.com';
14
+ function stubFetch() {
15
+ let response = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
16
+ ok: true
17
+ };
18
+ const fetchMock = vi.fn().mockResolvedValue(response);
19
+ vi.stubGlobal('fetch', fetchMock);
20
+ return fetchMock;
21
+ }
22
+ function sent(fetchMock) {
23
+ expect(fetchMock).toHaveBeenCalledTimes(1);
24
+ const [url, init] = fetchMock.mock.calls[0];
25
+ return {
26
+ url,
27
+ init,
28
+ body: JSON.parse(init.body)
29
+ };
30
+ }
31
+ beforeEach(() => {
32
+ document.cookie = '_fontdue_cc=;path=/;max-age=0';
33
+ document.title = 'Contests';
34
+ localStorage.clear();
35
+ resetTokenStore();
36
+ });
37
+ afterEach(() => {
38
+ vi.unstubAllGlobals();
39
+ vi.restoreAllMocks();
40
+ });
41
+ describe('sendTrackEvent', () => {
42
+ it('posts the event with the page it happened on', async () => {
43
+ const fetchMock = stubFetch();
44
+ await sendTrackEvent(URL, 'Contest Entered', {
45
+ contest: 'summer'
46
+ });
47
+ const {
48
+ url,
49
+ init,
50
+ body
51
+ } = sent(fetchMock);
52
+ expect(url).toBe(`${URL}/api/track`);
53
+ expect(init.method).toBe('POST');
54
+ expect(init.credentials).toBe('include');
55
+ // A click that navigates away must still deliver its event.
56
+ expect(init.keepalive).toBe(true);
57
+ expect(body.event).toBe('Contest Entered');
58
+ expect(body.properties).toEqual({
59
+ contest: 'summer'
60
+ });
61
+ expect(body.context.page).toEqual({
62
+ url: 'https://store.example.com/contests?ref=app',
63
+ path: '/contests',
64
+ title: 'Contests',
65
+ referrer: '',
66
+ search: '?ref=app'
67
+ });
68
+ expect(body.user_id).toBeUndefined();
69
+ expect(init.headers.Authorization).toBeUndefined();
70
+ });
71
+ it('names the customer a page passes in userId', async () => {
72
+ const fetchMock = stubFetch();
73
+ await sendTrackEvent(URL, 'Contest Entered', {}, {
74
+ userId: 'Q3VzdG9tZXI6MQ=='
75
+ });
76
+ expect(sent(fetchMock).body.user_id).toBe('Q3VzdG9tZXI6MQ==');
77
+ });
78
+ it('sends a signed-in customer’s token', async () => {
79
+ setTokens({
80
+ accessToken: 'access-1',
81
+ refreshToken: 'refresh-1'
82
+ }, URL);
83
+ const fetchMock = stubFetch();
84
+ await sendTrackEvent(URL, 'Contest Entered');
85
+ expect(sent(fetchMock).init.headers.Authorization).toBe('Bearer access-1');
86
+ });
87
+ it('never sends another Fontdue site’s token', async () => {
88
+ setTokens({
89
+ accessToken: 'access-1',
90
+ refreshToken: 'refresh-1'
91
+ }, 'https://other.example.com');
92
+ const fetchMock = stubFetch();
93
+ await sendTrackEvent(URL, 'Contest Entered');
94
+ expect(sent(fetchMock).init.headers.Authorization).toBeUndefined();
95
+ });
96
+ it('sends the cookieless anonymous ID only while consent is pending', async () => {
97
+ setClientAnonymousId('client-anon-1');
98
+ let fetchMock = stubFetch();
99
+ await sendTrackEvent(URL, 'Contest Entered');
100
+ expect(sent(fetchMock).body.anonymous_id).toBe('client-anon-1');
101
+ setConsent(['necessary', 'analytics']);
102
+ fetchMock = stubFetch();
103
+ await sendTrackEvent(URL, 'Contest Entered');
104
+ expect(sent(fetchMock).body.anonymous_id).toBeUndefined();
105
+ });
106
+ it('warns with the server’s reason when it refuses the event', async () => {
107
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
108
+ stubFetch({
109
+ ok: false,
110
+ status: 422,
111
+ json: () => Promise.resolve({
112
+ success: false,
113
+ error: '“Purchase” is recorded by Fontdue itself'
114
+ })
115
+ });
116
+ await expect(sendTrackEvent(URL, 'Purchase')).resolves.toBeUndefined();
117
+ expect(warn).toHaveBeenCalledWith('fontdue track: “Purchase” was not recorded – “Purchase” is recorded by Fontdue itself');
118
+ });
119
+ it('never throws when the request fails', async () => {
120
+ vi.spyOn(console, 'debug').mockImplementation(() => {});
121
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')));
122
+ await expect(sendTrackEvent(URL, 'Contest Entered')).resolves.toBeUndefined();
123
+ });
124
+ it('sends nothing before Fontdue knows its URL', async () => {
125
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
126
+ const fetchMock = stubFetch();
127
+ await sendTrackEvent('', 'Contest Entered');
128
+ expect(fetchMock).not.toHaveBeenCalled();
129
+ expect(warn).toHaveBeenCalled();
130
+ });
131
+ });
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+ interface FreeDownloadFormElement_props {
3
+ collectionId?: string;
4
+ collectionSlug?: string;
5
+ agreementLabel?: string;
6
+ downloadLabel?: string;
7
+ newsletterCheckboxChecked?: string;
8
+ }
9
+ declare const FreeDownloadFormElement: ({ newsletterCheckboxChecked, ...props }: FreeDownloadFormElement_props) => React.JSX.Element;
10
+ export default FreeDownloadFormElement;
@@ -0,0 +1,17 @@
1
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
2
+ import React from 'react';
3
+ import FreeDownloadForm from './index.js';
4
+
5
+ // `<fontdue-free-download-form collection-slug="…">`: attributes arrive as
6
+ // camelCased strings.
7
+
8
+ const FreeDownloadFormElement = _ref => {
9
+ let {
10
+ newsletterCheckboxChecked,
11
+ ...props
12
+ } = _ref;
13
+ return /*#__PURE__*/React.createElement(FreeDownloadForm, _extends({}, props, {
14
+ newsletterCheckboxChecked: newsletterCheckboxChecked === 'true'
15
+ }));
16
+ };
17
+ export default FreeDownloadFormElement;
@@ -0,0 +1,21 @@
1
+ import React from 'react';
2
+ import { FreeDownloadForm_Query } from '../../__generated__/FreeDownloadForm_Query.graphql.js';
3
+ import { SerializablePreloadedQuery, type LoadQueryOptions } from '../../relay/loadSerializableQuery.js';
4
+ import { Config } from '../ConfigContext.js';
5
+ import { FreeDownloadFormCollectionProps } from './variables.js';
6
+ export interface FreeDownloadForm_props extends FreeDownloadFormCollectionProps {
7
+ agreementLabel?: string;
8
+ downloadLabel?: string;
9
+ newsletterCheckboxChecked?: boolean;
10
+ }
11
+ export type FreeDownloadFormPreloadedQuery = SerializablePreloadedQuery<FreeDownloadForm_Query>;
12
+ export declare function loadFreeDownloadFormQuery(variables: FreeDownloadFormCollectionProps, options?: LoadQueryOptions): Promise<FreeDownloadFormPreloadedQuery>;
13
+ export declare function FreeDownloadFormPreloadedQueryRenderer({ preloadedQuery, ...rest }: FreeDownloadForm_props & {
14
+ preloadedQuery: FreeDownloadFormPreloadedQuery;
15
+ }): React.JSX.Element;
16
+ export type FreeDownloadForm_unifiedProps = FreeDownloadForm_props & {
17
+ preloadedQuery?: FreeDownloadFormPreloadedQuery;
18
+ config?: Config;
19
+ locale?: string;
20
+ };
21
+ export default function FreeDownloadForm({ config, locale, ...props }: FreeDownloadForm_unifiedProps): React.JSX.Element;
@@ -0,0 +1,283 @@
1
+ 'use client';
2
+
3
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
4
+ import _FreeDownloadForm_Query from "../../__generated__/FreeDownloadForm_Query.graphql.js";
5
+ import _FreeDownloadFormMutation from "../../__generated__/FreeDownloadFormMutation.graphql.js";
6
+ import React, { useState, useRef, useCallback, useId } from 'react';
7
+ import { commitMutation, graphql, useRelayEnvironment, useLazyLoadQuery, usePreloadedQuery } from 'react-relay';
8
+ // The script-injecting reCAPTCHA wrapper – see ../Recaptcha.
9
+ import { ReCAPTCHA } from '../Recaptcha.js';
10
+ import { useLocale } from '../LocaleContext.js';
11
+ import TextField from '../TextField/index.js';
12
+ import Checkbox from '../Checkbox/index.js';
13
+ import FreeDownloadFormQueryNode from '../../__generated__/FreeDownloadForm_Query.graphql.js';
14
+ import loadSerializableQuery from '../../relay/loadSerializableQuery.js';
15
+ import useSerializablePreloadedQuery from '../../relay/useSerializablePreloadedQuery.js';
16
+ import { EnsureFontdueContext, LazyQueryBoundary } from '../FontdueContextProvider/index.js';
17
+ import { orderTrackingInput } from '../Cart/orderTracking.js';
18
+ import { freeDownloadFormQueryVariables } from './variables.js';
19
+ import { useRecaptchaTimeout, isRecaptchaScriptLoaded } from '../../hooks/useRecaptchaTimeout.js';
20
+ import { useT } from '../../i18n/useT.js';
21
+
22
+ // The free download form: a collection's free fonts (a font is free when
23
+ // its price is zero) for a name, an email and the licence agreement. The
24
+ // server completes an order of its own – separate from the cart – and emails
25
+ // the receipt with the download link, so the form ends on "check your
26
+ // email" rather than starting a download.
27
+ const createFreeOrderMutation = (_FreeDownloadFormMutation.hash && _FreeDownloadFormMutation.hash !== "ec63092778be13d53040086da58031ff" && console.error("The definition of 'FreeDownloadFormMutation' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."), _FreeDownloadFormMutation);
28
+ const firstErrors = errors => Object.values(errors ?? {}).flatMap(messages => messages ?? []).filter(message => !!message);
29
+ const FreeDownloadFormComponent = _ref => {
30
+ var _data$viewer, _data$viewer2;
31
+ let {
32
+ data,
33
+ agreementLabel,
34
+ downloadLabel: downloadLabelProp,
35
+ newsletterCheckboxChecked = false
36
+ } = _ref;
37
+ const [email, setEmail] = useState('');
38
+ const [name, setName] = useState('');
39
+ const [newsletterOptIn, setNewsletterOptIn] = useState(newsletterCheckboxChecked);
40
+ const [agreed, setAgreed] = useState(false);
41
+ const [highlightMissing, setHighlightMissing] = useState(false);
42
+ const [errors, setErrors] = useState([]);
43
+ const [submitting, setSubmitting] = useState(false);
44
+ const [sentTo, setSentTo] = useState(null);
45
+ const [recaptchaToken, setRecaptchaToken] = useState(null);
46
+ const [pendingSubmit, setPendingSubmit] = useState(false);
47
+ const recaptchaRef = useRef(null);
48
+ const newsletterLabelRef = useRef(null);
49
+ const environment = useRelayEnvironment();
50
+ const recaptchaTimeout = useRecaptchaTimeout();
51
+ const locale = useLocale();
52
+ const t = useT();
53
+ const idPrefix = useId();
54
+ const download = (_data$viewer = data.viewer) === null || _data$viewer === void 0 ? void 0 : _data$viewer.freeDownload;
55
+ const settings = (_data$viewer2 = data.viewer) === null || _data$viewer2 === void 0 ? void 0 : _data$viewer2.settings;
56
+ const newsletterRequired = (download === null || download === void 0 ? void 0 : download.newsletter) === 'REQUIRED';
57
+ const recaptchaEnabled = (settings === null || settings === void 0 ? void 0 : settings.recaptchaEnabled) ?? false;
58
+ const recaptchaSiteKey = settings === null || settings === void 0 ? void 0 : settings.recaptchaSiteKey;
59
+ const downloadLabel = downloadLabelProp ?? t('freeDownload.download');
60
+ const submitForm = useCallback(token => {
61
+ var _newsletterLabelRef$c, _newsletterLabelRef$c2;
62
+ if (!download) return;
63
+ recaptchaTimeout.clear();
64
+ setSubmitting(true);
65
+ setPendingSubmit(false);
66
+ setErrors([]);
67
+ const failed = messages => {
68
+ var _recaptchaRef$current;
69
+ setErrors(messages);
70
+ setSubmitting(false);
71
+ (_recaptchaRef$current = recaptchaRef.current) === null || _recaptchaRef$current === void 0 ? void 0 : _recaptchaRef$current.reset();
72
+ setRecaptchaToken(null);
73
+ };
74
+ commitMutation(environment, {
75
+ mutation: createFreeOrderMutation,
76
+ variables: {
77
+ input: {
78
+ collectionId: download.fontCollection.id,
79
+ name,
80
+ email,
81
+ licenseAgreed: agreed,
82
+ newsletterOptIn,
83
+ // The checkbox's wording, kept with the subscriber's consent.
84
+ newsletterOptInLabel: newsletterOptIn ? ((_newsletterLabelRef$c = newsletterLabelRef.current) === null || _newsletterLabelRef$c === void 0 ? void 0 : (_newsletterLabelRef$c2 = _newsletterLabelRef$c.textContent) === null || _newsletterLabelRef$c2 === void 0 ? void 0 : _newsletterLabelRef$c2.trim()) || undefined : undefined,
85
+ recaptchaToken: token ?? undefined,
86
+ tracking: orderTrackingInput()
87
+ }
88
+ },
89
+ onCompleted: (res, graphqlErrors) => {
90
+ var _res$createFreeOrder;
91
+ if (graphqlErrors && graphqlErrors.length > 0) {
92
+ failed([graphqlErrors[0].message]);
93
+ } else if (!((_res$createFreeOrder = res.createFreeOrder) !== null && _res$createFreeOrder !== void 0 && _res$createFreeOrder.success)) {
94
+ var _res$createFreeOrder2;
95
+ failed(firstErrors((_res$createFreeOrder2 = res.createFreeOrder) === null || _res$createFreeOrder2 === void 0 ? void 0 : _res$createFreeOrder2.errors));
96
+ } else {
97
+ setSubmitting(false);
98
+ setSentTo(email);
99
+ }
100
+ },
101
+ onError: _ref2 => {
102
+ let {
103
+ message
104
+ } = _ref2;
105
+ return failed([message]);
106
+ }
107
+ });
108
+ }, [environment, download, name, email, agreed, newsletterOptIn, recaptchaTimeout]);
109
+ const abortRecaptcha = useCallback(() => {
110
+ var _recaptchaRef$current2;
111
+ recaptchaTimeout.clear();
112
+ setPendingSubmit(false);
113
+ setRecaptchaToken(null);
114
+ (_recaptchaRef$current2 = recaptchaRef.current) === null || _recaptchaRef$current2 === void 0 ? void 0 : _recaptchaRef$current2.reset();
115
+ setErrors([t('recaptcha.unavailable')]);
116
+ }, [recaptchaTimeout, t]);
117
+ const handleRecaptchaChange = useCallback(token => {
118
+ setRecaptchaToken(token);
119
+ if (token && pendingSubmit) submitForm(token);
120
+ }, [pendingSubmit, submitForm]);
121
+ if (!download) {
122
+ return /*#__PURE__*/React.createElement("div", {
123
+ className: "free-download free-download--unavailable"
124
+ }, /*#__PURE__*/React.createElement("p", null, t('freeDownload.unavailable')));
125
+ }
126
+ const handleSubmit = event => {
127
+ event.preventDefault();
128
+ if (!agreed || newsletterRequired && !newsletterOptIn) {
129
+ setHighlightMissing(true);
130
+ return;
131
+ }
132
+ if (recaptchaEnabled && recaptchaSiteKey && !recaptchaToken) {
133
+ var _recaptchaRef$current3;
134
+ setPendingSubmit(true);
135
+ setErrors([]);
136
+ recaptchaTimeout.start(() => {
137
+ if (isRecaptchaScriptLoaded()) return;
138
+ abortRecaptcha();
139
+ });
140
+ (_recaptchaRef$current3 = recaptchaRef.current) === null || _recaptchaRef$current3 === void 0 ? void 0 : _recaptchaRef$current3.execute();
141
+ return;
142
+ }
143
+ submitForm(recaptchaToken);
144
+ };
145
+ if (sentTo) {
146
+ return /*#__PURE__*/React.createElement("div", {
147
+ className: "free-download free-download--sent"
148
+ }, /*#__PURE__*/React.createElement("p", null, t('freeDownload.sent', {
149
+ email: sentTo
150
+ })));
151
+ }
152
+ const freeStyles = download.wholeCollection ? null : download.items.flatMap(item => item.fontStyles.map(style => style.name));
153
+
154
+ // "Desktop, Web and App", each name linking its license.
155
+ const lastIndex = download.licenses.length - 1;
156
+ const licenseLinks = download.licenses.map((license, index) => /*#__PURE__*/React.createElement(React.Fragment, {
157
+ key: license.id
158
+ }, index > 0 && (index === lastIndex ? ` ${t('freeDownload.and')} ` : ', '), license.url ? /*#__PURE__*/React.createElement("a", {
159
+ href: license.url,
160
+ target: "_blank",
161
+ rel: "noreferrer"
162
+ }, license.name) : license.name));
163
+ const newsletterLabel = settings === null || settings === void 0 ? void 0 : settings.newsletterOptInLabel;
164
+ const agreementId = `${idPrefix}-agreement`;
165
+ const newsletterId = `${idPrefix}-newsletter`;
166
+ const disabled = !name || !email || !agreed || newsletterRequired && !newsletterOptIn;
167
+ return /*#__PURE__*/React.createElement("div", {
168
+ className: "free-download"
169
+ }, errors.length > 0 && /*#__PURE__*/React.createElement("div", {
170
+ className: "free-download__errors"
171
+ }, errors.map(message => /*#__PURE__*/React.createElement("p", {
172
+ key: message
173
+ }, message))), /*#__PURE__*/React.createElement("form", {
174
+ className: "free-download__form",
175
+ onSubmit: handleSubmit
176
+ }, freeStyles && freeStyles.length > 0 && /*#__PURE__*/React.createElement("p", {
177
+ className: "free-download__styles"
178
+ }, t('freeDownload.freeStyles', {
179
+ styles: freeStyles.join(', ')
180
+ })), /*#__PURE__*/React.createElement("div", {
181
+ className: "free-download__section"
182
+ }, /*#__PURE__*/React.createElement(TextField, {
183
+ label: t('customerFields.nameRequired'),
184
+ value: name,
185
+ onChange: value => setName(value),
186
+ autocomplete: "name",
187
+ placeholder: t('customerFields.namePlaceholder')
188
+ })), /*#__PURE__*/React.createElement("div", {
189
+ className: "free-download__section"
190
+ }, /*#__PURE__*/React.createElement(TextField, {
191
+ label: t('customerFields.emailRequired'),
192
+ type: "email",
193
+ value: email,
194
+ onChange: value => setEmail(value),
195
+ autocomplete: "email",
196
+ placeholder: t('customerFields.emailPlaceholder')
197
+ })), /*#__PURE__*/React.createElement("div", {
198
+ className: "free-download__agreement free-download__checkbox-field",
199
+ "data-highlighted": highlightMissing && !agreed
200
+ }, /*#__PURE__*/React.createElement(Checkbox, {
201
+ id: agreementId,
202
+ checked: agreed,
203
+ onChange: event => setAgreed(event.target.checked)
204
+ }), agreementLabel ? /*#__PURE__*/React.createElement("label", {
205
+ htmlFor: agreementId,
206
+ dangerouslySetInnerHTML: {
207
+ __html: agreementLabel
208
+ }
209
+ }) : /*#__PURE__*/React.createElement("label", {
210
+ htmlFor: agreementId
211
+ }, t.rich('freeDownload.agreement', {
212
+ licenses: /*#__PURE__*/React.createElement(React.Fragment, null, licenseLinks),
213
+ count: download.licenses.length
214
+ }))), (newsletterRequired || newsletterLabel) && /*#__PURE__*/React.createElement("div", {
215
+ className: "free-download__newsletter-opt-in free-download__checkbox-field",
216
+ "data-highlighted": highlightMissing && newsletterRequired && !newsletterOptIn
217
+ }, /*#__PURE__*/React.createElement(Checkbox, {
218
+ id: newsletterId,
219
+ checked: newsletterOptIn,
220
+ onChange: event => setNewsletterOptIn(event.target.checked)
221
+ }), /*#__PURE__*/React.createElement("label", {
222
+ htmlFor: newsletterId,
223
+ ref: newsletterLabelRef
224
+ }, newsletterLabel ? /*#__PURE__*/React.createElement("span", {
225
+ dangerouslySetInnerHTML: {
226
+ __html: newsletterLabel
227
+ }
228
+ }) : t('freeDownload.newsletter'), newsletterRequired && /*#__PURE__*/React.createElement("span", {
229
+ className: "free-download__required"
230
+ }, ' ', t('freeDownload.newsletterRequired')))), recaptchaEnabled && recaptchaSiteKey && /*#__PURE__*/React.createElement(ReCAPTCHA, {
231
+ ref: recaptchaRef,
232
+ sitekey: recaptchaSiteKey,
233
+ hl: locale,
234
+ size: "invisible",
235
+ onChange: handleRecaptchaChange,
236
+ onExpired: () => setRecaptchaToken(null),
237
+ onErrored: () => pendingSubmit && abortRecaptcha()
238
+ }), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("button", {
239
+ className: "submit-button",
240
+ type: "submit",
241
+ disabled: submitting || pendingSubmit || disabled
242
+ }, submitting || pendingSubmit ? t('common.submittingDots') : downloadLabel, /*#__PURE__*/React.createElement("span", {
243
+ className: "submit-button__arrow"
244
+ }, " \u2192")))));
245
+ };
246
+ const query = (_FreeDownloadForm_Query.hash && _FreeDownloadForm_Query.hash !== "db8a8700fc4dd6730be1e38ac3289d20" && console.error("The definition of 'FreeDownloadForm_Query' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."), _FreeDownloadForm_Query);
247
+ // Pass the same `collectionId` / `collectionSlug` as the form's props.
248
+ export async function loadFreeDownloadFormQuery(variables, options) {
249
+ return loadSerializableQuery(FreeDownloadFormQueryNode, freeDownloadFormQueryVariables(variables), options);
250
+ }
251
+ export function FreeDownloadFormPreloadedQueryRenderer(_ref3) {
252
+ let {
253
+ preloadedQuery,
254
+ ...rest
255
+ } = _ref3;
256
+ const queryRef = useSerializablePreloadedQuery(preloadedQuery, 'store-or-network', query);
257
+ const data = usePreloadedQuery(query, queryRef);
258
+ return /*#__PURE__*/React.createElement(FreeDownloadFormComponent, _extends({
259
+ data: data
260
+ }, rest));
261
+ }
262
+ function FreeDownloadFormLazyQueryRenderer(props) {
263
+ const data = useLazyLoadQuery(query, freeDownloadFormQueryVariables(props));
264
+ return /*#__PURE__*/React.createElement(FreeDownloadFormComponent, _extends({
265
+ data: data
266
+ }, props));
267
+ }
268
+ // Accepts an optional preloaded query (server-side preload path) or fetches
269
+ // lazily on mount, like TestFontsForm.
270
+ export default function FreeDownloadForm(_ref4) {
271
+ var _props$preloadedQuery;
272
+ let {
273
+ config,
274
+ locale,
275
+ ...props
276
+ } = _ref4;
277
+ return /*#__PURE__*/React.createElement(EnsureFontdueContext, {
278
+ config: config,
279
+ locale: locale ?? ((_props$preloadedQuery = props.preloadedQuery) === null || _props$preloadedQuery === void 0 ? void 0 : _props$preloadedQuery.locale)
280
+ }, props.preloadedQuery ? /*#__PURE__*/React.createElement(FreeDownloadFormPreloadedQueryRenderer, _extends({}, props, {
281
+ preloadedQuery: props.preloadedQuery
282
+ })) : /*#__PURE__*/React.createElement(LazyQueryBoundary, null, /*#__PURE__*/React.createElement(FreeDownloadFormLazyQueryRenderer, props)));
283
+ }
@@ -0,0 +1,9 @@
1
+ import React from 'react';
2
+ import { FreeDownloadForm_props } from './index.js';
3
+ import { Config } from '../ConfigContext.js';
4
+ export type { FreeDownloadFormPreloadedQuery } from './index.js';
5
+ export declare function loadFreeDownloadFormQuery(): never;
6
+ export default function FreeDownloadForm(props: FreeDownloadForm_props & {
7
+ config?: Config;
8
+ locale?: string;
9
+ }): Promise<React.JSX.Element>;
@@ -0,0 +1,22 @@
1
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
2
+ import React from 'react';
3
+ import loadSerializableQuery from '../../relay/loadSerializableQuery.js';
4
+ import { FreeDownloadFormPreloadedQueryRenderer } from './index.js';
5
+ import { freeDownloadFormQueryVariables } from './variables.js';
6
+ import FreeDownloadFormQueryNode from '../../__generated__/FreeDownloadForm_Query.graphql.js';
7
+ // Stub for the RSC export condition. See FontdueProvider/index.server.tsx
8
+ // for the rationale.
9
+ export function loadFreeDownloadFormQuery() {
10
+ throw new Error("loadFreeDownloadFormQuery isn't needed in React Server Components — " + 'the <FreeDownloadForm> server entrypoint awaits its query automatically. ' + 'Drop the manual call.');
11
+ }
12
+
13
+ // Next RSC variant: awaits the query on the server and hands the response to
14
+ // the client renderer, like TestFontsForm's.
15
+ export default async function FreeDownloadForm(props) {
16
+ const preloadedQuery = await loadSerializableQuery(FreeDownloadFormQueryNode, freeDownloadFormQueryVariables(props), {
17
+ locale: props.locale
18
+ });
19
+ return /*#__PURE__*/React.createElement(FreeDownloadFormPreloadedQueryRenderer, _extends({
20
+ preloadedQuery: preloadedQuery
21
+ }, props));
22
+ }
@@ -0,0 +1,8 @@
1
+ export interface FreeDownloadFormCollectionProps {
2
+ collectionId?: string;
3
+ collectionSlug?: string;
4
+ }
5
+ export declare const freeDownloadFormQueryVariables: ({ collectionId, collectionSlug, }: FreeDownloadFormCollectionProps) => {
6
+ collectionId: string | null;
7
+ collectionSlug: string | null;
8
+ };
@@ -0,0 +1,18 @@
1
+ // Shared by the client component and the RSC entry (index.server.tsx), so it
2
+ // lives outside the 'use client' module: a server component can't call a
3
+ // function imported from one.
4
+
5
+ const present = value => {
6
+ const trimmed = value === null || value === void 0 ? void 0 : value.trim();
7
+ return trimmed ? trimmed : null;
8
+ };
9
+ export const freeDownloadFormQueryVariables = _ref => {
10
+ let {
11
+ collectionId,
12
+ collectionSlug
13
+ } = _ref;
14
+ return {
15
+ collectionId: present(collectionId),
16
+ collectionSlug: present(collectionSlug)
17
+ };
18
+ };
@@ -24,6 +24,7 @@ const customElementMap = {
24
24
  // @ts-ignore
25
25
  'fontdue-cookie-notification': /*#__PURE__*/lazy(() => retryImport(() => import('../CookieNotification/index.js'))),
26
26
  'fontdue-font-families': /*#__PURE__*/lazy(() => retryImport(() => import('../FontFamilies/index.js'))),
27
+ 'fontdue-free-download-form': /*#__PURE__*/lazy(() => retryImport(() => import('../FreeDownloadForm/FreeDownloadFormElement.js'))),
27
28
  'fontdue-customer-login-form': /*#__PURE__*/lazy(() => retryImport(() => import('../CustomerLoginForm/index.js'))),
28
29
  // Script tag only: CustomerSignIn isn't in the npm package's `exports` yet.
29
30
  'fontdue-customer-sign-in': /*#__PURE__*/lazy(() => retryImport(() => import('../CustomerSignIn/CustomerSignInElement.js'))),
@@ -0,0 +1,28 @@
1
+ export type TrackProperties = Record<string, unknown>;
2
+ export interface TrackOptions {
3
+ /**
4
+ * The customer the event is about, as their Fontdue customer ID (the `id`
5
+ * of `viewer.currentCustomer`). For a page that knows who the customer is
6
+ * from its own server – a page shown in the desktop app, which receives the
7
+ * customer's access token – without them having signed in on the site.
8
+ * A visitor signed in through fontdue.js is identified without it.
9
+ */
10
+ userId?: string;
11
+ }
12
+ /**
13
+ * Records one of the foundry's own analytics events through the tracking API.
14
+ *
15
+ * Everything the page's own page views carry rides along: the visitor's
16
+ * anonymous ID (the cookieless one while consent is pending), the signed-in
17
+ * customer's access token, and the page the event happened on. The server
18
+ * stores the event and forwards it to the foundry's destinations when the
19
+ * visitor's consent allows, exactly like a page view.
20
+ *
21
+ * Never throws: tracking must not break the page. A request the server
22
+ * refuses – a name Fontdue records itself, properties that aren't an object –
23
+ * is reported with `console.warn`, so the developer sees why.
24
+ *
25
+ * Sent with `keepalive`, so an event fired from a click that navigates away
26
+ * still arrives.
27
+ */
28
+ export declare function sendTrackEvent(url: string, event: string, properties?: TrackProperties, options?: TrackOptions): Promise<void>;
@@ -0,0 +1,68 @@
1
+ import { applyCustomerAuthHeader } from '../../auth/session.js';
2
+ import { getClientAnonymousId, hasConsent } from '../ConsentBanner/consent.js';
3
+ /**
4
+ * Records one of the foundry's own analytics events through the tracking API.
5
+ *
6
+ * Everything the page's own page views carry rides along: the visitor's
7
+ * anonymous ID (the cookieless one while consent is pending), the signed-in
8
+ * customer's access token, and the page the event happened on. The server
9
+ * stores the event and forwards it to the foundry's destinations when the
10
+ * visitor's consent allows, exactly like a page view.
11
+ *
12
+ * Never throws: tracking must not break the page. A request the server
13
+ * refuses – a name Fontdue records itself, properties that aren't an object –
14
+ * is reported with `console.warn`, so the developer sees why.
15
+ *
16
+ * Sent with `keepalive`, so an event fired from a click that navigates away
17
+ * still arrives.
18
+ */
19
+ export async function sendTrackEvent(url, event) {
20
+ let properties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
21
+ let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
22
+ if (typeof window === 'undefined') return;
23
+ if (!url) {
24
+ console.warn('fontdue track: no Fontdue URL – call it after Fontdue is initialized.');
25
+ return;
26
+ }
27
+ const body = {
28
+ event,
29
+ properties,
30
+ context: {
31
+ userAgent: navigator.userAgent,
32
+ page: {
33
+ url: window.location.href,
34
+ path: window.location.pathname,
35
+ title: document.title,
36
+ referrer: document.referrer,
37
+ search: window.location.search
38
+ }
39
+ }
40
+ };
41
+
42
+ // Only the cookieless ID needs sending: once consent is granted (or never
43
+ // required) the server's cookie is the visitor's ID. Same rule as page views.
44
+ const anonymousId = hasConsent('analytics') ? undefined : getClientAnonymousId();
45
+ if (anonymousId) body.anonymous_id = anonymousId;
46
+ if (options.userId) body.user_id = options.userId;
47
+ const headers = {
48
+ 'Content-Type': 'application/json'
49
+ };
50
+ // A signed-in visitor's token vouches for who they are. An expired one is
51
+ // harmless here: the server records the event without a customer.
52
+ applyCustomerAuthHeader(headers, url);
53
+ try {
54
+ const response = await fetch(`${url}/api/track`, {
55
+ method: 'POST',
56
+ headers,
57
+ credentials: 'include',
58
+ keepalive: true,
59
+ body: JSON.stringify(body)
60
+ });
61
+ if (!response.ok) {
62
+ const error = await response.json().then(json => json === null || json === void 0 ? void 0 : json.error).catch(() => undefined);
63
+ console.warn(`fontdue track: “${event}” was not recorded` + (typeof error === 'string' ? ` – ${error}` : ` (HTTP ${response.status})`));
64
+ }
65
+ } catch (error) {
66
+ console.debug('fontdue track: request failed', error);
67
+ }
68
+ }
@@ -0,0 +1,21 @@
1
+ import { type TrackOptions, type TrackProperties } from './Tracking/sendTrackEvent.js';
2
+ export type { TrackOptions, TrackProperties };
3
+ /**
4
+ * Returns a function that records one of your own analytics events, sent to
5
+ * the Fontdue site `<FontdueProvider>` is configured for.
6
+ *
7
+ * @example
8
+ * const track = useTrack();
9
+ * <button onClick={() => track('Contest Entered', { contest: 'summer' })}>Enter</button>
10
+ */
11
+ export declare function useTrack(): (event: string, properties?: TrackProperties, options?: TrackOptions) => Promise<void>;
12
+ /**
13
+ * Records one of your own analytics events from outside a React component,
14
+ * sent to the Fontdue site configured in the environment (`FONTDUE_URL`,
15
+ * `NEXT_PUBLIC_FONTDUE_URL`…). Inside a component, prefer `useTrack()`, which
16
+ * follows `<FontdueProvider url>`.
17
+ *
18
+ * @example
19
+ * track('Newsletter Link Clicked', { placement: 'footer' });
20
+ */
21
+ export declare function track(event: string, properties?: TrackProperties, options?: TrackOptions): Promise<void>;