@dealsystem/site 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/README.md +145 -2
  2. package/agent-files/claude/skills/angebote-einbauen/SKILL.md +30 -0
  3. package/agent-files/claude/skills/bild-einbauen/SKILL.md +43 -0
  4. package/agent-files/claude/skills/domain-verbinden/SKILL.md +23 -0
  5. package/agent-files/claude/skills/erster-entwurf/SKILL.md +54 -0
  6. package/agent-files/claude/skills/extern-einbinden/SKILL.md +37 -0
  7. package/agent-files/claude/skills/formular-anbinden/SKILL.md +34 -0
  8. package/agent-files/claude/skills/funnel-mehrstufig/BewertungFunnel.svelte +220 -0
  9. package/agent-files/claude/skills/funnel-mehrstufig/SKILL.md +101 -0
  10. package/agent-files/claude/skills/neue-seite/SKILL.md +47 -0
  11. package/agent-files/claude/skills/prueffehler-beheben/SKILL.md +31 -0
  12. package/agent-files/claude/skills/termin-buchung/SKILL.md +51 -0
  13. package/agent-files/claude/skills/veroeffentlichen/SKILL.md +38 -0
  14. package/agent-files/cursor/rules/dealsystem.mdc +7 -0
  15. package/agent-files/manifest.json +101 -0
  16. package/contract/README.md +41 -0
  17. package/contract/ds-content.v1.json +2355 -0
  18. package/contract/external-presets.v1.json +65 -0
  19. package/contract/funnel-code-config.md +87 -0
  20. package/contract/site-api.v1.json +3916 -0
  21. package/dist/client/altcha-workers.d.ts +10 -0
  22. package/dist/client/attribution.d.ts +119 -0
  23. package/dist/client/attribution.js +341 -0
  24. package/dist/client/bookingClient.svelte.d.ts +166 -0
  25. package/dist/client/bookingClient.svelte.js +369 -0
  26. package/dist/client/bookingTime.d.ts +46 -0
  27. package/dist/client/bookingTime.js +109 -0
  28. package/dist/client/captcha.d.ts +26 -0
  29. package/dist/client/captcha.js +71 -0
  30. package/dist/client/captchaSession.d.ts +21 -0
  31. package/dist/client/captchaSession.js +105 -0
  32. package/dist/client/collections.d.ts +34 -0
  33. package/dist/client/collections.js +40 -0
  34. package/dist/client/externalScript.d.ts +20 -0
  35. package/dist/client/externalScript.js +36 -0
  36. package/dist/client/funnelState.svelte.d.ts +47 -0
  37. package/dist/client/funnelState.svelte.js +81 -0
  38. package/dist/client/leadClient.svelte.d.ts +131 -0
  39. package/dist/client/leadClient.svelte.js +250 -0
  40. package/dist/client/pageview.d.ts +7 -0
  41. package/dist/client/pageview.js +44 -0
  42. package/dist/client/siteApi.d.ts +211 -0
  43. package/dist/client/siteApi.js +320 -0
  44. package/dist/client/tracking.d.ts +18 -0
  45. package/dist/client/tracking.js +93 -0
  46. package/dist/client/validation.d.ts +10 -0
  47. package/dist/client/validation.js +66 -0
  48. package/dist/components/Booker.svelte +729 -0
  49. package/dist/components/Booker.svelte.d.ts +42 -0
  50. package/dist/components/CollectionList.svelte +122 -0
  51. package/dist/components/CollectionList.svelte.d.ts +65 -0
  52. package/dist/components/ConsentGate.svelte +68 -0
  53. package/dist/components/ConsentGate.svelte.d.ts +44 -0
  54. package/dist/components/CookieBanner.svelte +303 -0
  55. package/dist/components/CookieBanner.svelte.d.ts +29 -0
  56. package/dist/components/Datenschutz.svelte +84 -0
  57. package/dist/components/Datenschutz.svelte.d.ts +26 -0
  58. package/dist/components/Embed.svelte +263 -0
  59. package/dist/components/Embed.svelte.d.ts +41 -0
  60. package/dist/components/ExternalScript.svelte +94 -0
  61. package/dist/components/ExternalScript.svelte.d.ts +41 -0
  62. package/dist/components/Impressum.svelte +59 -0
  63. package/dist/components/Impressum.svelte.d.ts +25 -0
  64. package/dist/components/LeadForm.svelte +475 -0
  65. package/dist/components/LeadForm.svelte.d.ts +35 -0
  66. package/dist/components/LeadHoneypot.svelte +43 -0
  67. package/dist/components/LeadHoneypot.svelte.d.ts +18 -0
  68. package/dist/components/Link.svelte +48 -0
  69. package/dist/components/Link.svelte.d.ts +30 -0
  70. package/dist/components/MapEmbed.svelte +154 -0
  71. package/dist/components/MapEmbed.svelte.d.ts +28 -0
  72. package/dist/components/MediaImage.svelte +218 -0
  73. package/dist/components/MediaImage.svelte.d.ts +128 -0
  74. package/dist/components/MediaVideo.svelte +103 -0
  75. package/dist/components/MediaVideo.svelte.d.ts +20 -0
  76. package/dist/components/RichText.svelte +105 -0
  77. package/dist/components/RichText.svelte.d.ts +55 -0
  78. package/dist/components/Seo.svelte +89 -0
  79. package/dist/components/Seo.svelte.d.ts +45 -0
  80. package/dist/components/SiteFooterLegal.svelte +75 -0
  81. package/dist/components/SiteFooterLegal.svelte.d.ts +22 -0
  82. package/dist/components/SiteHead.svelte +79 -0
  83. package/dist/components/SiteHead.svelte.d.ts +32 -0
  84. package/dist/components/Text.svelte +100 -0
  85. package/dist/components/Text.svelte.d.ts +55 -0
  86. package/dist/components/Tracking.svelte +30 -0
  87. package/dist/components/Tracking.svelte.d.ts +14 -0
  88. package/dist/components/Zeitfenster.svelte +92 -0
  89. package/dist/components/Zeitfenster.svelte.d.ts +34 -0
  90. package/dist/components/legal.d.ts +12 -0
  91. package/dist/components/legal.js +27 -0
  92. package/dist/config/index.d.ts +121 -0
  93. package/dist/config/index.js +602 -0
  94. package/dist/config/static/index.d.ts +3 -0
  95. package/dist/config/static/index.js +5 -0
  96. package/dist/config/static/lines.d.ts +9 -0
  97. package/dist/config/static/lines.js +22 -0
  98. package/dist/config/static/literal.d.ts +45 -0
  99. package/dist/config/static/literal.js +175 -0
  100. package/dist/config/static/siteConfig.d.ts +39 -0
  101. package/dist/config/static/siteConfig.js +150 -0
  102. package/dist/consent/consent.svelte.d.ts +91 -0
  103. package/dist/consent/consent.svelte.js +221 -0
  104. package/dist/content/index.d.ts +123 -0
  105. package/dist/content/index.js +247 -0
  106. package/dist/contentBlock.d.ts +45 -0
  107. package/dist/contentBlock.js +78 -0
  108. package/dist/csp/index.d.ts +27 -0
  109. package/dist/csp/index.js +74 -0
  110. package/dist/external/csp.d.ts +25 -0
  111. package/dist/external/csp.js +104 -0
  112. package/dist/external/hosts.d.ts +30 -0
  113. package/dist/external/hosts.js +128 -0
  114. package/dist/external/presets.d.ts +54 -0
  115. package/dist/external/presets.js +212 -0
  116. package/dist/external/resolve.d.ts +39 -0
  117. package/dist/external/resolve.js +254 -0
  118. package/dist/index.d.ts +32 -0
  119. package/dist/index.js +32 -0
  120. package/dist/internal/consentNeed.d.ts +21 -0
  121. package/dist/internal/consentNeed.js +50 -0
  122. package/dist/internal/dealsystem-legal-imprint.d.ts +2 -0
  123. package/dist/internal/dealsystem-legal-imprint.js +5 -0
  124. package/dist/internal/dealsystem-legal-privacy.d.ts +2 -0
  125. package/dist/internal/dealsystem-legal-privacy.js +5 -0
  126. package/dist/internal/dealsystem-site-data.d.ts +3 -0
  127. package/dist/internal/dealsystem-site-data.js +2 -0
  128. package/dist/internal/imprint.d.ts +4 -0
  129. package/dist/internal/imprint.js +10 -0
  130. package/dist/internal/mediaImage.d.ts +15 -0
  131. package/dist/internal/mediaImage.js +22 -0
  132. package/dist/internal/privacy.d.ts +4 -0
  133. package/dist/internal/privacy.js +10 -0
  134. package/dist/internal/providers.d.ts +9 -0
  135. package/dist/internal/providers.js +44 -0
  136. package/dist/internal/reload.d.ts +2 -0
  137. package/dist/internal/reload.js +5 -0
  138. package/dist/internal/seo.d.ts +41 -0
  139. package/dist/internal/seo.js +79 -0
  140. package/dist/internal/siteData.d.ts +7 -0
  141. package/dist/internal/siteData.js +39 -0
  142. package/dist/internal/usage.d.ts +7 -0
  143. package/dist/internal/usage.js +13 -0
  144. package/dist/keys.d.ts +20 -0
  145. package/dist/keys.js +58 -0
  146. package/dist/leadmagnet.d.ts +16 -0
  147. package/dist/leadmagnet.js +28 -0
  148. package/dist/paths.d.ts +8 -0
  149. package/dist/paths.js +9 -0
  150. package/dist/richtext/escape.d.ts +4 -0
  151. package/dist/richtext/escape.js +18 -0
  152. package/dist/richtext/server.d.ts +16 -0
  153. package/dist/richtext/server.js +123 -0
  154. package/dist/schedule.d.ts +23 -0
  155. package/dist/schedule.js +67 -0
  156. package/dist/slots.d.ts +9 -0
  157. package/dist/slots.js +38 -0
  158. package/dist/snapshot.d.ts +14 -0
  159. package/dist/snapshot.js +214 -0
  160. package/dist/types.d.ts +550 -0
  161. package/dist/types.js +4 -0
  162. package/dist/version.d.ts +2 -0
  163. package/dist/version.js +2 -0
  164. package/dist/vite/index.d.ts +85 -0
  165. package/dist/vite/index.js +641 -0
  166. package/dist/vite/scan.d.ts +47 -0
  167. package/dist/vite/scan.js +355 -0
  168. package/dist/vite/zeitfenster.d.ts +18 -0
  169. package/dist/vite/zeitfenster.js +76 -0
  170. package/docs/ablauf.md +191 -0
  171. package/docs/agents-block.md +101 -0
  172. package/docs/befehle.md +103 -0
  173. package/docs/extern.md +143 -0
  174. package/docs/gestaltung.md +139 -0
  175. package/docs/inhalte.md +224 -0
  176. package/docs/komponenten.md +1273 -0
  177. package/docs/konfiguration.md +310 -0
  178. package/docs/llms.txt +19 -0
  179. package/docs/rechtstexte.md +84 -0
  180. package/docs/regeln.md +108 -0
  181. package/docs/seo.md +55 -0
  182. package/docs/termine.md +73 -0
  183. package/package.json +115 -5
@@ -0,0 +1,369 @@
1
+ // Terminbuchung ohne eigenes `fetch`: für eigene Oberflächen und intern für `<Booker>`. Eine Implementierung für
2
+ // beides: Terminart laden, freie Zeiten, Prüfung, Captcha (derselbe Weg wie bei Formularen), Bot-Falle,
3
+ // Herkunft und Einwilligung, `submissionId` gegen doppeltes Buchen. Fehler kommen als Werte mit deutschem Text
4
+ // für Besucher zurück, nie als Ausnahme.
5
+ import { buildLeadAttribution } from './attribution.js';
6
+ import { BOOKING_RANGE_MAX_DAYS, visitorTimeZone } from './bookingTime.js';
7
+ import { createCaptchaSession } from './captchaSession.js';
8
+ import { siteApi, } from './siteApi.js';
9
+ import { consent } from '../consent/consent.svelte.js';
10
+ import { getSiteData } from '../internal/siteData.js';
11
+ import { usageError } from '../internal/usage.js';
12
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
13
+ const PHONE = /^[+0-9][0-9 ()/.-]{4,29}$/;
14
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
15
+ const ATTENDEE_FIELDS = ['firstName', 'lastName', 'email', 'phone'];
16
+ const MESSAGES = {
17
+ validation: 'Bitte prüfen Sie Ihre Angaben.',
18
+ captcha: 'Die Sicherheitsprüfung konnte nicht durchgeführt werden. Bitte versuchen Sie es später erneut.',
19
+ unavailable: 'Die Terminbuchung ist zurzeit nicht verfügbar.',
20
+ slot_taken: 'Diese Zeit ist leider nicht mehr frei. Bitte wählen Sie eine andere.',
21
+ not_qualified: 'Für diesen Termin passt Ihre Anfrage leider nicht. Bitte nehmen Sie direkt Kontakt auf, wir helfen gern weiter.',
22
+ };
23
+ const LABELS = {
24
+ firstName: 'Vorname',
25
+ lastName: 'Nachname',
26
+ email: 'E-Mail',
27
+ phone: 'Telefon',
28
+ };
29
+ function apiError(kind, message) {
30
+ return {
31
+ kind,
32
+ status: null,
33
+ code: null,
34
+ message,
35
+ retryAfterSeconds: null,
36
+ invalidFields: [],
37
+ invalidPaths: [],
38
+ formInvalid: false,
39
+ };
40
+ }
41
+ /** Zeitpunkt in ms seit 1970 (`NaN`, wenn ungültig). Zahlen statt `Date`: hier ist nichts reaktiv. */
42
+ function msOf(value) {
43
+ return value instanceof Date ? value.getTime() : Date.parse(value);
44
+ }
45
+ function isoOf(ms) {
46
+ return new Date(ms).toISOString();
47
+ }
48
+ function isEmpty(value) {
49
+ return (value === undefined ||
50
+ value === null ||
51
+ (typeof value === 'string' && value.trim() === '') ||
52
+ (Array.isArray(value) && value.length === 0));
53
+ }
54
+ /** Meldung zu einer Buchungsfrage oder `null`. Regeln wie `validateBookingFieldAnswers` im Core. */
55
+ function checkAnswer(question, value) {
56
+ const label = question.label;
57
+ if (isEmpty(value) || (question.type === 'boolean' && value === false && question.required)) {
58
+ if (!question.required)
59
+ return null;
60
+ if (question.type === 'boolean')
61
+ return `Bitte bestätigen Sie „${label}“.`;
62
+ if (question.type === 'select' || question.type === 'multiselect')
63
+ return `Bitte wählen Sie bei „${label}“ etwas aus.`;
64
+ return `Bitte füllen Sie das Feld „${label}“ aus.`;
65
+ }
66
+ if (question.type === 'multiselect') {
67
+ if (!Array.isArray(value) || value.some((v) => question.options && !question.options.includes(v)))
68
+ return `Bitte wählen Sie bei „${label}“ etwas aus.`;
69
+ return null;
70
+ }
71
+ if (question.type === 'boolean')
72
+ return typeof value === 'boolean' ? null : `Bitte bestätigen Sie „${label}“.`;
73
+ const text = String(value).trim();
74
+ if (text.length > 5000)
75
+ return `„${label}“ ist zu lang. Erlaubt sind höchstens 5000 Zeichen.`;
76
+ if (question.type === 'email' && !EMAIL.test(text))
77
+ return 'Bitte geben Sie eine gültige E-Mail-Adresse ein, z. B. name@beispiel.de.';
78
+ if (question.type === 'phone' && !PHONE.test(text))
79
+ return 'Bitte geben Sie eine gültige Telefonnummer ein, z. B. 0341 1234567.';
80
+ if (question.type === 'number' && !Number.isFinite(Number(text.replace(',', '.'))))
81
+ return `Bitte geben Sie bei „${label}“ eine Zahl an.`;
82
+ if (question.type === 'date' && !DATE.test(text))
83
+ return `Bitte geben Sie bei „${label}“ ein Datum an.`;
84
+ if (question.type === 'select' && question.options?.length && !question.options.includes(text))
85
+ return `Bitte wählen Sie bei „${label}“ etwas aus.`;
86
+ return null;
87
+ }
88
+ /**
89
+ * Terminbuchung ohne `<Booker>`: für eine eigene Oberfläche. Nimmt den Schlüssel aus `booking` in
90
+ * `dealsystem.config.ts`. Die Terminart (Dauer, Arbeitszeiten, Fragen) richtet der Kunde im CRM ein; erfinde
91
+ * keine. Kein eigenes `fetch` an DealSystem (`SEC-004`).
92
+ *
93
+ * Zeiten kommen und gehen in UTC. Zeig sie in der Zeitzone des Besuchers (`groupSlotsByDay`, `visitorTimeZone`)
94
+ * und nenne die des Kalenders (`timezone`) als Hinweis. Zeig bei jedem Fehler außer `validation` den
95
+ * Ausweichkontakt `fallback`; bei `slot_taken` die Zeiten neu laden. Setz `<LeadHoneypot client={termin} />` in
96
+ * die Oberfläche.
97
+ *
98
+ * @example
99
+ * <script lang="ts">
100
+ * import { createBookingClient, groupSlotsByDay, visitorTimeZone, LeadHoneypot } from '@dealsystem/site';
101
+ * import { onMount } from 'svelte';
102
+ *
103
+ * const termin = createBookingClient('erstgespraech');
104
+ * const zone = visitorTimeZone();
105
+ * let tage = $state<ReturnType<typeof groupSlotsByDay>>([]);
106
+ * let start = $state('');
107
+ * let vorname = $state('');
108
+ * let email = $state('');
109
+ * let ergebnis = $state<Awaited<ReturnType<typeof termin.book>> | null>(null);
110
+ *
111
+ * onMount(() => {
112
+ * termin.slots().then((r) => (tage = r.ok ? groupSlotsByDay(r.slots, zone) : []));
113
+ * return () => termin.destroy();
114
+ * });
115
+ *
116
+ * async function buchen(event: SubmitEvent) {
117
+ * event.preventDefault();
118
+ * ergebnis = await termin.book({ start, firstName: vorname, email });
119
+ * }
120
+ * </script>
121
+ *
122
+ * {#each tage as tag (tag.date)}
123
+ * <h3>{tag.long}</h3>
124
+ * {#each tag.slots as zeit (zeit.start)}
125
+ * <button type="button" aria-pressed={start === zeit.start} onclick={() => ((start = zeit.start), termin.prepare())}>
126
+ * {zeit.time}
127
+ * </button>
128
+ * {/each}
129
+ * {/each}
130
+ * <form onsubmit={buchen}>
131
+ * <label for="vorname">Vorname</label>
132
+ * <input id="vorname" required bind:value={vorname} />
133
+ * <label for="email">E-Mail</label>
134
+ * <input id="email" type="email" required bind:value={email} />
135
+ * <LeadHoneypot client={termin} />
136
+ * <button type="submit" disabled={!start}>Termin buchen</button>
137
+ * </form>
138
+ * {#if ergebnis && !ergebnis.ok}<p role="alert">{ergebnis.message}</p>{/if}
139
+ */
140
+ export function createBookingClient(booking, options = {}) {
141
+ const site = getSiteData();
142
+ const definition = site.bookings?.[booking];
143
+ if (!definition) {
144
+ const known = Object.keys(site.bookings ?? {});
145
+ usageError(`${options.caller ?? `createBookingClient("${booking}")`}: Diese Terminbuchung steht nicht unter booking in dealsystem.config.ts. ` +
146
+ (known.length > 0 ? `Vorhanden: ${known.join(', ')}.` : 'Dort ist noch keine eingetragen.'));
147
+ }
148
+ const fallback = { phone: site.legal.phone || null, email: site.legal.email || null };
149
+ const captcha = createCaptchaSession({ name: `booking-${booking}`, element: options.captchaElement });
150
+ let status = $state('idle');
151
+ let honeypot = '';
152
+ let loadedInfo = null;
153
+ /** Je Beginn eine ID: ein neuer Versuch derselben Zeit bucht nicht doppelt, eine andere Zeit ist ein neuer Vorgang. */
154
+ let submission = null;
155
+ let inFlight = null;
156
+ function failure(error, reason) {
157
+ const own = reason ??
158
+ (error.code === 'slot_taken' || error.kind === 'conflict'
159
+ ? 'slot_taken'
160
+ : error.code === 'not_qualified'
161
+ ? 'not_qualified'
162
+ : error.kind === 'captcha_failed'
163
+ ? 'captcha'
164
+ : error.kind === 'rate_limited'
165
+ ? 'rate_limited'
166
+ : error.kind === 'network'
167
+ ? 'network'
168
+ : 'unavailable');
169
+ const message = own === 'slot_taken'
170
+ ? MESSAGES.slot_taken
171
+ : own === 'not_qualified'
172
+ ? MESSAGES.not_qualified
173
+ : own === 'unavailable' && error.kind === 'not_found'
174
+ ? MESSAGES.unavailable
175
+ : error.message;
176
+ return {
177
+ ok: false,
178
+ reason: own,
179
+ message,
180
+ fields: {},
181
+ fallback,
182
+ retryAfterSeconds: error.retryAfterSeconds,
183
+ error: { ...error, message },
184
+ };
185
+ }
186
+ function unavailable() {
187
+ return failure(apiError('not_found', MESSAGES.unavailable), 'unavailable');
188
+ }
189
+ function validate(input, questions = []) {
190
+ const found = {};
191
+ const first = input.firstName?.trim() ?? '';
192
+ if (!first)
193
+ found.firstName = 'Bitte geben Sie Ihren Vornamen an.';
194
+ else if (first.length > 100)
195
+ found.firstName = '„Vorname“ ist zu lang. Erlaubt sind höchstens 100 Zeichen.';
196
+ if ((input.lastName?.trim().length ?? 0) > 100)
197
+ found.lastName = '„Nachname“ ist zu lang. Erlaubt sind höchstens 100 Zeichen.';
198
+ const email = input.email?.trim() ?? '';
199
+ if (!email)
200
+ found.email = 'Bitte geben Sie Ihre E-Mail-Adresse an.';
201
+ else if (!EMAIL.test(email) || email.length > 254)
202
+ found.email = 'Bitte geben Sie eine gültige E-Mail-Adresse ein, z. B. name@beispiel.de.';
203
+ const phone = input.phone?.trim() ?? '';
204
+ if (phone && !PHONE.test(phone))
205
+ found.phone = 'Bitte geben Sie eine gültige Telefonnummer ein, z. B. 0341 1234567.';
206
+ for (const question of questions) {
207
+ const message = checkAnswer(question, input.answers?.[question.key]);
208
+ if (message)
209
+ found[`answers.${question.key}`] = message;
210
+ }
211
+ return found;
212
+ }
213
+ function answersOf(input) {
214
+ const out = {};
215
+ for (const [key, value] of Object.entries(input.answers ?? {})) {
216
+ if (value === undefined || isEmpty(value))
217
+ continue;
218
+ if (Array.isArray(value))
219
+ out[key] = [...value];
220
+ else if (typeof value === 'string')
221
+ out[key] = value.trim();
222
+ else
223
+ out[key] = value;
224
+ }
225
+ return Object.keys(out).length > 0 ? out : undefined;
226
+ }
227
+ async function send(input) {
228
+ if (!definition)
229
+ return unavailable();
230
+ const loaded = await info();
231
+ const questions = loaded.ok ? loaded.info.questions : [];
232
+ const found = validate(input, questions);
233
+ if (!input.start || Number.isNaN(Date.parse(input.start)))
234
+ found.start = 'Bitte wählen Sie eine Zeit.';
235
+ if (Object.keys(found).length > 0) {
236
+ return {
237
+ ok: false,
238
+ reason: 'validation',
239
+ message: MESSAGES.validation,
240
+ fields: found,
241
+ fallback: null,
242
+ error: null,
243
+ };
244
+ }
245
+ if (!loaded.ok)
246
+ return loaded;
247
+ status = 'captcha';
248
+ const payload = await captcha.solution();
249
+ if (!payload)
250
+ return failure(apiError('captcha_failed', MESSAGES.captcha), 'captcha');
251
+ status = 'sending';
252
+ if (!submission || submission.start !== input.start)
253
+ submission = { start: input.start, id: crypto.randomUUID() };
254
+ const id = submission.id;
255
+ const result = await siteApi().createBooking(String(booking), {
256
+ submissionId: id,
257
+ start: input.start,
258
+ tz: visitorTimeZone(),
259
+ attendee: {
260
+ firstName: input.firstName.trim(),
261
+ ...(input.lastName?.trim() ? { lastName: input.lastName.trim() } : {}),
262
+ email: input.email.trim(),
263
+ ...(input.phone?.trim() ? { phone: input.phone.trim() } : {}),
264
+ },
265
+ answers: answersOf(input),
266
+ ...(input.locationType ? { locationType: input.locationType } : {}),
267
+ attribution: buildLeadAttribution(consent.granted(), consent.decidedAt),
268
+ captcha: payload,
269
+ website: honeypot.slice(0, 500),
270
+ });
271
+ if (result.ok) {
272
+ submission = null;
273
+ captcha.clear();
274
+ return {
275
+ ok: true,
276
+ dryRun: result.data.dryRun,
277
+ duplicate: result.data.duplicate,
278
+ start: result.data.start ?? input.start,
279
+ end: result.data.end,
280
+ submissionId: id,
281
+ };
282
+ }
283
+ captcha.consume();
284
+ const error = result.error;
285
+ if (error.kind === 'validation' && error.code !== 'not_qualified') {
286
+ const fields = {};
287
+ for (const path of error.invalidPaths) {
288
+ // Text vom Server wird nie angezeigt: eigene Meldung je Feld.
289
+ const [head, name] = path.split('.');
290
+ if (head === 'attendee' && name && ATTENDEE_FIELDS.includes(name)) {
291
+ fields[name] = `Bitte prüfen Sie Ihre Angabe bei „${LABELS[name]}“.`;
292
+ }
293
+ else if (head === 'answers' && name) {
294
+ const question = questions.find((q) => q.key === name);
295
+ fields[`answers.${name}`] = `Bitte prüfen Sie Ihre Angabe bei „${question?.label ?? name}“.`;
296
+ }
297
+ else if (head === 'start') {
298
+ fields.start = 'Bitte wählen Sie eine Zeit.';
299
+ }
300
+ }
301
+ return { ok: false, reason: 'validation', message: MESSAGES.validation, fields, fallback: null, error };
302
+ }
303
+ return failure(error);
304
+ }
305
+ function info() {
306
+ if (!definition)
307
+ return Promise.resolve(unavailable());
308
+ loadedInfo ??= siteApi()
309
+ .getBooking(String(booking))
310
+ .then((r) => (r.ok ? { ok: true, info: r.data } : failure(r.error)))
311
+ .then((r) => {
312
+ // Fehler nicht merken: Ein späterer Aufruf versucht es neu.
313
+ if (!r.ok)
314
+ loadedInfo = null;
315
+ return r;
316
+ });
317
+ return loadedInfo;
318
+ }
319
+ return {
320
+ booking,
321
+ label: definition?.label ?? String(booking),
322
+ fallback,
323
+ get status() {
324
+ return status;
325
+ },
326
+ info,
327
+ async slots(from, to) {
328
+ if (!definition)
329
+ return unavailable();
330
+ const start = from === undefined ? Date.now() : msOf(from);
331
+ const end = to === undefined ? start + 7 * 86_400_000 : msOf(to);
332
+ if (Number.isNaN(start) || Number.isNaN(end) || end <= start) {
333
+ return failure(apiError('rejected', 'Der Zeitraum ist ungültig.'), 'unavailable');
334
+ }
335
+ status = 'loading';
336
+ try {
337
+ const result = await siteApi().getBookingSlots(String(booking), {
338
+ from: isoOf(start),
339
+ to: isoOf(Math.min(end, start + BOOKING_RANGE_MAX_DAYS * 86_400_000)),
340
+ });
341
+ return result.ok
342
+ ? { ok: true, timezone: result.data.timezone, slots: result.data.slots }
343
+ : failure(result.error);
344
+ }
345
+ finally {
346
+ status = 'idle';
347
+ }
348
+ },
349
+ validate,
350
+ prepare() {
351
+ captcha.start();
352
+ },
353
+ setHoneypot(value) {
354
+ honeypot = value;
355
+ },
356
+ book(input) {
357
+ if (inFlight)
358
+ return inFlight;
359
+ inFlight = send(input).finally(() => {
360
+ inFlight = null;
361
+ status = 'idle';
362
+ });
363
+ return inFlight;
364
+ },
365
+ destroy() {
366
+ captcha.destroy();
367
+ },
368
+ };
369
+ }
@@ -0,0 +1,46 @@
1
+ import type { BookingSlot } from './siteApi.js';
2
+ /** Zeitzone, wenn der Browser keine nennt. */
3
+ export declare const BOOKING_FALLBACK_TIME_ZONE = "Europe/Berlin";
4
+ /** Höchstens so viele Tage fragt die Site-API je Abruf ab. */
5
+ export declare const BOOKING_RANGE_MAX_DAYS = 31;
6
+ /** `true`, wenn `Intl` die Zeitzone kennt. */
7
+ export declare function isTimeZone(timeZone: string): boolean;
8
+ /** IANA-Zeitzone des Besuchers, z. B. `Europe/Berlin`. Ohne Angabe des Browsers `Europe/Berlin`. */
9
+ export declare function visitorTimeZone(): string;
10
+ /** Kalendertag eines Zeitpunkts in einer Zeitzone als `YYYY-MM-DD`. */
11
+ export declare function dayOf(instant: Date | string, timeZone: string): string;
12
+ /** Uhrzeit eines Zeitpunkts in einer Zeitzone, z. B. `09:30`. */
13
+ export declare function formatBookingTime(instant: Date | string, timeZone: string): string;
14
+ /** Datum eines Zeitpunkts in einer Zeitzone, z. B. `Dienstag, 1. Dezember 2026`. */
15
+ export declare function formatBookingDate(instant: Date | string, timeZone: string, locale?: string): string;
16
+ /**
17
+ * Name einer Zeitzone für Besucher, z. B. `Mitteleuropäische Zeit (Berlin)`. Ohne Namen in `Intl` nur die Stadt.
18
+ */
19
+ export declare function timeZoneLabel(timeZone: string, locale?: string, at?: Date): string;
20
+ /** Ein freier Termin für die Anzeige. */
21
+ export interface BookingSlotView extends BookingSlot {
22
+ /** Uhrzeit des Beginns in der Anzeige-Zeitzone, z. B. `09:30`. */
23
+ time: string;
24
+ /** Vollständig für Screenreader, z. B. `Dienstag, 1. Dezember 2026, 09:30 Uhr`. */
25
+ label: string;
26
+ }
27
+ /** Ein Tag mit freien Terminen. */
28
+ export interface BookingDay {
29
+ /** `YYYY-MM-DD` in der Anzeige-Zeitzone. */
30
+ date: string;
31
+ /** Kurz, z. B. `Di., 1. Dez.`. */
32
+ short: string;
33
+ /** Lang, z. B. `Dienstag, 1. Dezember 2026`. */
34
+ long: string;
35
+ slots: BookingSlotView[];
36
+ }
37
+ /**
38
+ * Freie Termine nach Kalendertag in der Anzeige-Zeitzone, aufsteigend. Ein Termin um 23:30 UTC gehört in Berlin
39
+ * zum nächsten Tag; ein Tag der Zeitumstellung hat einfach eine Stunde mehr oder weniger.
40
+ */
41
+ export declare function groupSlotsByDay(slots: readonly BookingSlot[], timeZone: string, locale?: string): BookingDay[];
42
+ /** Zeitraum für `slots()`: ab `from` (Standard: jetzt) für `days` Tage, höchstens 31. */
43
+ export declare function bookingRange(days: number, from?: Date): {
44
+ from: Date;
45
+ to: Date;
46
+ };
@@ -0,0 +1,109 @@
1
+ /** Zeitzone, wenn der Browser keine nennt. */
2
+ export const BOOKING_FALLBACK_TIME_ZONE = 'Europe/Berlin';
3
+ /** Höchstens so viele Tage fragt die Site-API je Abruf ab. */
4
+ export const BOOKING_RANGE_MAX_DAYS = 31;
5
+ /** `true`, wenn `Intl` die Zeitzone kennt. */
6
+ export function isTimeZone(timeZone) {
7
+ try {
8
+ new Intl.DateTimeFormat('en-US', { timeZone });
9
+ return true;
10
+ }
11
+ catch {
12
+ return false;
13
+ }
14
+ }
15
+ /** IANA-Zeitzone des Besuchers, z. B. `Europe/Berlin`. Ohne Angabe des Browsers `Europe/Berlin`. */
16
+ export function visitorTimeZone() {
17
+ try {
18
+ const zone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
19
+ return zone && isTimeZone(zone) ? zone : BOOKING_FALLBACK_TIME_ZONE;
20
+ }
21
+ catch {
22
+ return BOOKING_FALLBACK_TIME_ZONE;
23
+ }
24
+ }
25
+ function parts(instant, timeZone) {
26
+ const out = {};
27
+ const format = new Intl.DateTimeFormat('en-CA', {
28
+ timeZone,
29
+ year: 'numeric',
30
+ month: '2-digit',
31
+ day: '2-digit',
32
+ hour: '2-digit',
33
+ minute: '2-digit',
34
+ hourCycle: 'h23',
35
+ });
36
+ for (const p of format.formatToParts(instant))
37
+ out[p.type] = p.value;
38
+ return out;
39
+ }
40
+ /** Kalendertag eines Zeitpunkts in einer Zeitzone als `YYYY-MM-DD`. */
41
+ export function dayOf(instant, timeZone) {
42
+ const p = parts(new Date(instant), timeZone);
43
+ return `${p.year}-${p.month}-${p.day}`;
44
+ }
45
+ /** Uhrzeit eines Zeitpunkts in einer Zeitzone, z. B. `09:30`. */
46
+ export function formatBookingTime(instant, timeZone) {
47
+ const p = parts(new Date(instant), timeZone);
48
+ return `${p.hour}:${p.minute}`;
49
+ }
50
+ /** Datum eines Zeitpunkts in einer Zeitzone, z. B. `Dienstag, 1. Dezember 2026`. */
51
+ export function formatBookingDate(instant, timeZone, locale = 'de-DE') {
52
+ return new Intl.DateTimeFormat(locale, {
53
+ timeZone,
54
+ weekday: 'long',
55
+ day: 'numeric',
56
+ month: 'long',
57
+ year: 'numeric',
58
+ }).format(new Date(instant));
59
+ }
60
+ /**
61
+ * Name einer Zeitzone für Besucher, z. B. `Mitteleuropäische Zeit (Berlin)`. Ohne Namen in `Intl` nur die Stadt.
62
+ */
63
+ export function timeZoneLabel(timeZone, locale = 'de-DE', at = new Date()) {
64
+ const city = (timeZone.split('/').pop() ?? timeZone).replaceAll('_', ' ');
65
+ try {
66
+ const name = new Intl.DateTimeFormat(locale, { timeZone, timeZoneName: 'longGeneric' })
67
+ .formatToParts(at)
68
+ .find((p) => p.type === 'timeZoneName')?.value;
69
+ return name && name !== timeZone ? `${name} (${city})` : city;
70
+ }
71
+ catch {
72
+ return city;
73
+ }
74
+ }
75
+ /**
76
+ * Freie Termine nach Kalendertag in der Anzeige-Zeitzone, aufsteigend. Ein Termin um 23:30 UTC gehört in Berlin
77
+ * zum nächsten Tag; ein Tag der Zeitumstellung hat einfach eine Stunde mehr oder weniger.
78
+ */
79
+ export function groupSlotsByDay(slots, timeZone, locale = 'de-DE') {
80
+ const short = new Intl.DateTimeFormat(locale, {
81
+ timeZone,
82
+ weekday: 'short',
83
+ day: 'numeric',
84
+ month: 'short',
85
+ });
86
+ const days = new Map();
87
+ const sorted = [...slots].sort((a, b) => Date.parse(a.start) - Date.parse(b.start));
88
+ for (const slot of sorted) {
89
+ const date = dayOf(slot.start, timeZone);
90
+ let day = days.get(date);
91
+ if (!day) {
92
+ day = {
93
+ date,
94
+ short: short.format(new Date(slot.start)),
95
+ long: formatBookingDate(slot.start, timeZone, locale),
96
+ slots: [],
97
+ };
98
+ days.set(date, day);
99
+ }
100
+ const time = formatBookingTime(slot.start, timeZone);
101
+ day.slots.push({ ...slot, time, label: `${day.long}, ${time} Uhr` });
102
+ }
103
+ return [...days.values()];
104
+ }
105
+ /** Zeitraum für `slots()`: ab `from` (Standard: jetzt) für `days` Tage, höchstens 31. */
106
+ export function bookingRange(days, from = new Date()) {
107
+ const span = Math.min(Math.max(1, Math.floor(days)), BOOKING_RANGE_MAX_DAYS);
108
+ return { from, to: new Date(from.getTime() + span * 86_400_000) };
109
+ }
@@ -0,0 +1,26 @@
1
+ /** Ein laufendes Captcha. */
2
+ export interface CaptchaHandle {
3
+ /** Neue Aufgabe holen und lösen, z. B. nach einem abgelehnten Versuch. */
4
+ reset(): void;
5
+ destroy(): void;
6
+ }
7
+ /** Rückmeldungen an das Formular. */
8
+ export interface CaptchaCallbacks {
9
+ /** Aufgabe gelöst. `payload` geht als `captcha` an die Site-API. */
10
+ onSolved(payload: string): void;
11
+ /** Lösung abgelaufen oder zurückgesetzt. */
12
+ onCleared(): void;
13
+ /** Aufgabe nicht ladbar oder nicht lösbar. */
14
+ onError(): void;
15
+ }
16
+ /** Startet das Captcha im angegebenen Element. */
17
+ export type CaptchaAdapter = (element: HTMLElement, challengeUrl: string, callbacks: CaptchaCallbacks) => Promise<CaptchaHandle>;
18
+ /** Algorithmen, deren Worker das Paket mitbringt. Der Server muss einen davon verwenden. */
19
+ export declare const CAPTCHA_ALGORITHMS: {
20
+ readonly pbkdf2: readonly ["PBKDF2/SHA-256", "PBKDF2/SHA-384", "PBKDF2/SHA-512"];
21
+ readonly sha: readonly ["SHA-256", "SHA-384", "SHA-512"];
22
+ };
23
+ /** @internal Nur für Tests. */
24
+ export declare function setCaptchaAdapterForTests(adapter: CaptchaAdapter | null): void;
25
+ /** @internal */
26
+ export declare function captchaAdapter(): CaptchaAdapter;
@@ -0,0 +1,71 @@
1
+ /** Algorithmen, deren Worker das Paket mitbringt. Der Server muss einen davon verwenden. */
2
+ export const CAPTCHA_ALGORITHMS = {
3
+ pbkdf2: ['PBKDF2/SHA-256', 'PBKDF2/SHA-384', 'PBKDF2/SHA-512'],
4
+ sha: ['SHA-256', 'SHA-384', 'SHA-512'],
5
+ };
6
+ const altcha = async (element, challengeUrl, callbacks) => {
7
+ const [, pbkdf2, sha] = await Promise.all([
8
+ import('altcha/external'),
9
+ import('altcha/workers/pbkdf2?worker'),
10
+ import('altcha/workers/sha?worker'),
11
+ ]);
12
+ const registry = globalThis.$altcha;
13
+ for (const name of CAPTCHA_ALGORITHMS.pbkdf2)
14
+ registry.algorithms.set(name, () => new pbkdf2.default());
15
+ for (const name of CAPTCHA_ALGORITHMS.sha)
16
+ registry.algorithms.set(name, () => new sha.default());
17
+ const widget = document.createElement('altcha-widget');
18
+ widget.addEventListener('verified', (event) => {
19
+ const payload = event.detail?.payload;
20
+ if (payload)
21
+ callbacks.onSolved(payload);
22
+ else
23
+ callbacks.onError();
24
+ });
25
+ widget.addEventListener('expired', () => callbacks.onCleared());
26
+ widget.addEventListener('statechange', (event) => {
27
+ if (event.detail?.state === 'error')
28
+ callbacks.onError();
29
+ });
30
+ // Die Methoden des Widgets gibt es erst nach seinem `load`-Ereignis.
31
+ const loaded = new Promise((resolve, reject) => {
32
+ widget.addEventListener('load', () => resolve(), { once: true });
33
+ setTimeout(() => reject(new Error('ALTCHA lädt nicht')), 10_000);
34
+ });
35
+ // Unsichtbar ohne die Styles des Widgets: das Element selbst ist versteckt.
36
+ element.hidden = true;
37
+ element.append(widget);
38
+ if (typeof widget.configure !== 'function')
39
+ await loaded;
40
+ await widget.configure({
41
+ challenge: challengeUrl,
42
+ auto: 'off',
43
+ display: 'invisible',
44
+ // Die Site-API antwortet ohne `Access-Control-Allow-Credentials`.
45
+ credentials: 'omit',
46
+ hideLogo: true,
47
+ hideFooter: true,
48
+ });
49
+ const verify = () => {
50
+ widget.verify().catch(() => callbacks.onError());
51
+ };
52
+ verify();
53
+ return {
54
+ reset() {
55
+ widget.reset();
56
+ verify();
57
+ },
58
+ destroy() {
59
+ widget.remove();
60
+ },
61
+ };
62
+ };
63
+ let testAdapter = null;
64
+ /** @internal Nur für Tests. */
65
+ export function setCaptchaAdapterForTests(adapter) {
66
+ testAdapter = adapter;
67
+ }
68
+ /** @internal */
69
+ export function captchaAdapter() {
70
+ return testAdapter ?? altcha;
71
+ }
@@ -0,0 +1,21 @@
1
+ /** @internal */
2
+ export interface CaptchaSession {
3
+ /** Startet die Prüfung im Hintergrund. Mehrfach aufrufbar. */
4
+ start(): void;
5
+ /** Wartet auf eine frische Lösung. `null`: Die Prüfung ließ sich nicht durchführen. */
6
+ solution(): Promise<string | null>;
7
+ /** Nach einer Antwort des Servers: Lösung verbrauchen und gleich die nächste Aufgabe lösen. */
8
+ consume(): void;
9
+ /** Nach Erfolg: Lösung verwerfen, ohne neu zu rechnen (der nächste Versuch startet neu). */
10
+ clear(): void;
11
+ destroy(): void;
12
+ }
13
+ /** @internal */
14
+ export interface CaptchaSessionOptions {
15
+ /** Kennung am versteckten Element (`data-ds-captcha`), z. B. der Schlüssel des Formulars. */
16
+ name: string;
17
+ /** Eigenes Element für das unsichtbare Widget. Standard: ein verstecktes Element am Ende von `<body>`. */
18
+ element?: () => HTMLElement | null;
19
+ }
20
+ /** @internal */
21
+ export declare function createCaptchaSession(options: CaptchaSessionOptions): CaptchaSession;