lutra 0.1.0 → 0.1.5

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 (154) hide show
  1. package/dist/components/Avatar.svelte +105 -0
  2. package/dist/components/Avatar.svelte.d.ts +14 -0
  3. package/dist/components/Close.svelte +76 -0
  4. package/dist/components/Close.svelte.d.ts +7 -0
  5. package/dist/components/ContextTip.svelte +41 -0
  6. package/dist/components/ContextTip.svelte.d.ts +7 -0
  7. package/dist/components/Icon.svelte +62 -0
  8. package/dist/components/Icon.svelte.d.ts +8 -0
  9. package/dist/components/IconButton.svelte +120 -0
  10. package/dist/components/IconButton.svelte.d.ts +16 -0
  11. package/dist/components/Image.svelte +172 -0
  12. package/dist/components/Image.svelte.d.ts +56 -0
  13. package/dist/components/Indicator.svelte +387 -0
  14. package/dist/components/Indicator.svelte.d.ts +12 -0
  15. package/dist/components/Inset.svelte +23 -0
  16. package/dist/components/Inset.svelte.d.ts +7 -0
  17. package/dist/components/Layout.svelte +2 -1
  18. package/dist/components/MenuDropdown.svelte +195 -0
  19. package/dist/components/MenuDropdown.svelte.d.ts +16 -0
  20. package/dist/components/MenuItem.svelte +159 -0
  21. package/dist/components/MenuItem.svelte.d.ts +11 -0
  22. package/dist/components/MenuItemContent.svelte +25 -0
  23. package/dist/components/MenuItemContent.svelte.d.ts +10 -0
  24. package/dist/components/MenuTypes.d.ts +79 -0
  25. package/dist/components/MenuTypes.js +1 -0
  26. package/dist/components/Modal.svelte +149 -0
  27. package/dist/components/Modal.svelte.d.ts +16 -0
  28. package/dist/components/Notification.svelte +115 -0
  29. package/dist/components/Notification.svelte.d.ts +12 -0
  30. package/dist/components/Overlay.svelte +31 -0
  31. package/dist/components/Overlay.svelte.d.ts +14 -0
  32. package/dist/components/OverlayContainer.svelte +31 -0
  33. package/dist/components/OverlayContainer.svelte.d.ts +18 -0
  34. package/dist/components/OverlayLayer.svelte +168 -0
  35. package/dist/components/OverlayLayer.svelte.d.ts +8 -0
  36. package/dist/components/PageContent.svelte +4 -82
  37. package/dist/components/PageContent.svelte.d.ts +0 -31
  38. package/dist/components/TabbedContent.svelte +74 -0
  39. package/dist/components/TabbedContent.svelte.d.ts +11 -0
  40. package/dist/components/TabbedContentItem.svelte +33 -0
  41. package/dist/components/TabbedContentItem.svelte.d.ts +10 -0
  42. package/dist/components/Table.svelte +41 -0
  43. package/dist/components/Table.svelte.d.ts +13 -0
  44. package/dist/components/Tabs.svelte +216 -0
  45. package/dist/components/Tabs.svelte.d.ts +20 -0
  46. package/dist/components/Tag.svelte +120 -0
  47. package/dist/components/Tag.svelte.d.ts +21 -0
  48. package/dist/components/Theme.svelte +32 -14
  49. package/dist/components/Tooltip.svelte +8 -8
  50. package/dist/components/UIContent.svelte +19 -0
  51. package/dist/components/UIContent.svelte.d.ts +7 -0
  52. package/dist/components/index.d.ts +28 -0
  53. package/dist/components/index.js +29 -0
  54. package/dist/components/notifications.svelte.d.ts +21 -0
  55. package/dist/components/notifications.svelte.js +30 -0
  56. package/dist/components/overlays.svelte.d.ts +36 -0
  57. package/dist/components/overlays.svelte.js +44 -0
  58. package/dist/css/1-props.css +389 -724
  59. package/dist/css/2-base.css +257 -123
  60. package/dist/css/3-typo.css +74 -34
  61. package/dist/css/4-layout.css +364 -1
  62. package/dist/css/5-media.css +106 -11
  63. package/dist/css/lutra.css +2 -1
  64. package/dist/css/themes/DefaultTheme.css +209 -0
  65. package/dist/form/Button.svelte +58 -0
  66. package/dist/form/Button.svelte.d.ts +15 -0
  67. package/dist/form/Datepicker.svelte +311 -0
  68. package/dist/form/Datepicker.svelte.d.ts +9 -0
  69. package/dist/form/FieldContent.svelte +178 -0
  70. package/dist/form/FieldContent.svelte.d.ts +21 -0
  71. package/dist/form/FieldError.svelte +24 -0
  72. package/dist/form/FieldError.svelte.d.ts +7 -0
  73. package/dist/form/Fieldset.svelte +103 -0
  74. package/dist/form/Fieldset.svelte.d.ts +20 -0
  75. package/dist/form/Form.svelte +220 -0
  76. package/dist/form/Form.svelte.d.ts +38 -0
  77. package/dist/form/FormActions.svelte +80 -0
  78. package/dist/form/FormActions.svelte.d.ts +9 -0
  79. package/dist/form/FormSection.svelte +96 -0
  80. package/dist/form/FormSection.svelte.d.ts +9 -0
  81. package/dist/form/ImageUpload.svelte +299 -0
  82. package/dist/form/ImageUpload.svelte.d.ts +20 -0
  83. package/dist/form/Input.svelte +444 -0
  84. package/dist/form/Input.svelte.d.ts +108 -0
  85. package/dist/form/InputLength.svelte +42 -0
  86. package/dist/form/InputLength.svelte.d.ts +9 -0
  87. package/dist/form/Label.svelte +88 -0
  88. package/dist/form/Label.svelte.d.ts +16 -0
  89. package/dist/form/LogoUpload.svelte +115 -0
  90. package/dist/form/LogoUpload.svelte.d.ts +18 -0
  91. package/dist/form/Select.svelte +186 -0
  92. package/dist/form/Select.svelte.d.ts +59 -0
  93. package/dist/form/Textarea.svelte +265 -0
  94. package/dist/form/Textarea.svelte.d.ts +95 -0
  95. package/dist/form/Toggle.svelte +4 -0
  96. package/dist/form/Toggle.svelte.d.ts +18 -0
  97. package/dist/form/client.svelte.d.ts +45 -0
  98. package/dist/form/client.svelte.js +102 -0
  99. package/dist/form/form.d.ts +55 -0
  100. package/dist/form/form.js +345 -0
  101. package/dist/form/index.d.ts +17 -0
  102. package/dist/form/index.js +17 -0
  103. package/dist/form/types.d.ts +55 -0
  104. package/dist/form/types.js +1 -0
  105. package/dist/icons/IconAlert.svelte +3 -0
  106. package/dist/icons/IconAlert.svelte.d.ts +26 -0
  107. package/dist/icons/IconCopy.svelte +3 -0
  108. package/dist/icons/IconCopy.svelte.d.ts +26 -0
  109. package/dist/icons/IconDone.svelte +3 -0
  110. package/dist/icons/IconDone.svelte.d.ts +26 -0
  111. package/dist/icons/IconError.svelte +3 -0
  112. package/dist/icons/IconError.svelte.d.ts +26 -0
  113. package/dist/icons/IconHelp.svelte +3 -0
  114. package/dist/icons/IconHelp.svelte.d.ts +26 -0
  115. package/dist/icons/IconHide.svelte +3 -0
  116. package/dist/icons/IconHide.svelte.d.ts +26 -0
  117. package/dist/icons/IconInfo.svelte +3 -0
  118. package/dist/icons/IconInfo.svelte.d.ts +26 -0
  119. package/dist/icons/IconLink.svelte +3 -0
  120. package/dist/icons/IconLink.svelte.d.ts +26 -0
  121. package/dist/icons/IconMenuBurger.svelte +3 -0
  122. package/dist/icons/IconMenuBurger.svelte.d.ts +26 -0
  123. package/dist/icons/IconMenuDots.svelte +3 -0
  124. package/dist/icons/IconMenuDots.svelte.d.ts +26 -0
  125. package/dist/icons/IconSearch.svelte +3 -0
  126. package/dist/icons/IconSearch.svelte.d.ts +26 -0
  127. package/dist/icons/IconShow.svelte +3 -0
  128. package/dist/icons/IconShow.svelte.d.ts +26 -0
  129. package/dist/icons/IconSuccess.svelte +3 -0
  130. package/dist/icons/IconSuccess.svelte.d.ts +26 -0
  131. package/dist/icons/IconWarning.svelte +3 -0
  132. package/dist/icons/IconWarning.svelte.d.ts +26 -0
  133. package/dist/icons/index.d.ts +14 -0
  134. package/dist/icons/index.js +14 -0
  135. package/dist/index.d.ts +3 -5
  136. package/dist/index.js +3 -5
  137. package/dist/util/StringOrComponent.svelte +20 -0
  138. package/dist/util/StringOrComponent.svelte.d.ts +8 -0
  139. package/dist/util/StringOrSnippet.svelte +16 -0
  140. package/dist/util/StringOrSnippet.svelte.d.ts +8 -0
  141. package/dist/util/attr.d.ts +5 -0
  142. package/dist/util/attr.js +21 -0
  143. package/dist/util/color.d.ts +51 -0
  144. package/dist/util/color.js +97 -0
  145. package/dist/util/dom.d.ts +15 -0
  146. package/dist/util/dom.js +73 -0
  147. package/dist/util/keyboard.svelte.d.ts +22 -0
  148. package/dist/util/keyboard.svelte.js +161 -0
  149. package/dist/util/locale.d.ts +1 -0
  150. package/dist/util/locale.js +47 -0
  151. package/dist/util/settings.d.ts +4 -0
  152. package/dist/util/settings.js +1 -0
  153. package/package.json +20 -11
  154. package/dist/css/0-layers.css +0 -1
@@ -0,0 +1,95 @@
1
+ import { type Snippet } from "svelte";
2
+ import type { Autocomplete } from "./types.js";
3
+ type $$ComponentProps = {
4
+ /** Whether the input should be autofocused. */
5
+ autofocus?: boolean;
6
+ /** Whether the input should be autocapitalized. */
7
+ autocapitalize?: boolean | 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters';
8
+ /** Specifies whether autocomplete is enabled for the input. */
9
+ autocomplete?: Autocomplete;
10
+ /** Whether the input should resize automatically. */
11
+ autoresize?: boolean;
12
+ /** A hint to the browser for which capture method to use. */
13
+ capture?: 'user' | 'environment';
14
+ /** Whether the input should be checked. */
15
+ checked?: boolean;
16
+ /** Whether the input should be contained. */
17
+ contained?: boolean;
18
+ /** Whether the input should be copyable. */
19
+ copyable?: boolean;
20
+ /** The default value of the input element. */
21
+ defaultValue?: string;
22
+ /** Form field name for the directionality of the element's text content during form submission */
23
+ dirname?: string;
24
+ /** Whether the input should be disabled. */
25
+ disabled?: boolean;
26
+ /** A hint to the browser for which enter key to display for the input. */
27
+ enterkeyhint?: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send';
28
+ /** The height of the input element. Valid for image inputs. */
29
+ height?: number;
30
+ /** Help text to display below the input. */
31
+ help?: string | Snippet;
32
+ /** A random id is generated if not provided. */
33
+ id?: string;
34
+ /** Whether the input should be indeterminate. */
35
+ indeterminate?: boolean;
36
+ /** A hint to the browser for which keyboard to display. This is only used for type="text" inputs. Strongly consider using type="email" or type="url" etc. instead */
37
+ inputmode?: 'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';
38
+ /** The label for the input */
39
+ label?: string | Snippet;
40
+ /** Context tooltip for a label. Renders with a questionmark using ContextTip. */
41
+ labelTip?: string | Snippet;
42
+ /** The id of a datalist element that contains pre-defined options for the input element. */
43
+ list?: string;
44
+ /** The maximum number of characters (as UTF-16 code units) the user can enter into the input. Valid for text, search, url, tel, email, and password. */
45
+ maxlength?: number;
46
+ /** The minimum number of characters (as UTF-16 code units) the user can enter into the input. Valid for text, search, url, tel, email, and password. */
47
+ minlength?: number;
48
+ /** The name of the input element. */
49
+ name: string;
50
+ /** The onblur event handler */
51
+ onblur?: (e: FocusEvent) => void;
52
+ /** Onchange event handler */
53
+ onchange?: (e: Event) => void;
54
+ /** Onclick event handler */
55
+ onclick?: (e: MouseEvent) => void;
56
+ /** Onfocus event handler */
57
+ onfocus?: (e: FocusEvent) => void;
58
+ /** Keyup event handler */
59
+ onkeyup?: (e: KeyboardEvent) => void;
60
+ /** Keydown event handler */
61
+ onkeydown?: (e: KeyboardEvent) => void;
62
+ /** Keypress event handler */
63
+ onkeypress?: (e: KeyboardEvent) => void;
64
+ /** A regular expression that the input's value is checked against. Valid for text, search, url, tel, email, and password. */
65
+ pattern?: string;
66
+ /** Placeholder text to display when the input is empty. */
67
+ placeholder?: string;
68
+ /** Suffix content, to display after the input. */
69
+ suffix?: string | Snippet;
70
+ /** Prefix content, to display before the input. */
71
+ prefix?: string | Snippet;
72
+ /** Whether the input should be read-only. */
73
+ readonly?: boolean;
74
+ /** Whether the input should be required. */
75
+ required?: boolean;
76
+ /** Whether the textarea is resizable. */
77
+ resize?: boolean | 'both' | 'horizontal' | 'vertical' | 'none';
78
+ /** The shape of the input element. */
79
+ shape?: 'default' | 'rounded' | 'pill' | 'circle';
80
+ /** Spellcheck the input. */
81
+ spellcheck?: boolean;
82
+ /** A number that specifies the granularity that the value must adhere to. Valid for date, month, week, time, datetime-local, number, and range. */
83
+ step?: number;
84
+ /** Inline styles to apply to the input element. */
85
+ style?: string;
86
+ /** An integer attribute indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation. */
87
+ tabindex?: number;
88
+ /** A string that defines the title of the input element. */
89
+ title?: string;
90
+ /** The value of the input element. */
91
+ value?: string | null;
92
+ };
93
+ declare const Textarea: import("svelte").Component<$$ComponentProps, {}, "id" | "value">;
94
+ type Textarea = ReturnType<typeof Textarea>;
95
+ export default Textarea;
@@ -0,0 +1,4 @@
1
+ <script lang="ts">
2
+
3
+ </script>
4
+
@@ -0,0 +1,18 @@
1
+ interface $$__sveltets_2_IsomorphicComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any, Exports = {}, Bindings = string> {
2
+ new (options: import('svelte').ComponentConstructorOptions<Props>): import('svelte').SvelteComponent<Props, Events, Slots> & {
3
+ $$bindings?: Bindings;
4
+ } & Exports;
5
+ (internal: unknown, props: {
6
+ $$events?: Events;
7
+ $$slots?: Slots;
8
+ }): Exports & {
9
+ $set?: any;
10
+ $on?: any;
11
+ };
12
+ z_$$bindings?: Bindings;
13
+ }
14
+ declare const Toggle: $$__sveltets_2_IsomorphicComponent<Record<string, never>, {
15
+ [evt: string]: CustomEvent<any>;
16
+ }, {}, {}, string>;
17
+ type Toggle = InstanceType<typeof Toggle>;
18
+ export default Toggle;
@@ -0,0 +1,45 @@
1
+ import type { ZodType } from "zod";
2
+ import type { LutraForm } from "./types.js";
3
+ /**
4
+ * Use a form in a Svelte component.
5
+ * @param {Form} form - The form to use.
6
+ * @returns
7
+ */
8
+ export declare function useForm(form: LutraForm<any>): LutraForm<any> & {
9
+ originalData: any;
10
+ domForm: null;
11
+ data: any;
12
+ state: string;
13
+ };
14
+ /**
15
+ * Validate a single field.
16
+ * @param {Form} form - The form to validate.
17
+ * @param {string} name - The name of the field to validate.
18
+ * @param {HTMLInputElement | HTMLSelectElement} el - The element to validate.
19
+ * @param {ZodType} validator - The validator to use.
20
+ */
21
+ export declare function fieldValidate(form: LutraForm<any>, name: string, el?: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement, validator?: ZodType<any, any>): void;
22
+ /**
23
+ * Keydown event handler for a field.
24
+ * @param {KeyboardEvent} e - The event.
25
+ * @param {Form} form - The form to use.
26
+ * @param {string} name - The name of the field.
27
+ * @param {HTMLInputElement | HTMLSelectElement} el - The element to validate.
28
+ * @param {ZodType} validator - The validator to use.
29
+ * @param {(e: KeyboardEvent) => void} onkeydown - The onkeydown event handler.
30
+ */
31
+ export declare function fieldKeydown(form: LutraForm<any>, name: string, el: () => HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | undefined, validator?: ZodType<any, any>, onkeydown?: (e: KeyboardEvent) => void): (e: KeyboardEvent) => Promise<void>;
32
+ /**
33
+ * Change event handler for a field.
34
+ * @param {Event} e - The event.
35
+ * @param {Form} form - The form to use.
36
+ * @param {string} name - The name of the field.
37
+ * @param {HTMLInputElement | HTMLSelectElement} el - The element to validate.
38
+ * @param {ZodType} validator - The validator to use.
39
+ * @param {(e: Event) => void} onchange - The onchange event handler.
40
+ */
41
+ export declare function fieldChange(form: LutraForm<any>, name: string, el: () => HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | undefined, validator?: ZodType<any, any>, onchange?: (e: Event) => void): (e: Event) => Promise<void>;
42
+ /**
43
+ * Keys that should be ignored when marking a field as tainted.
44
+ */
45
+ export declare const ignoreKeys: string[];
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Use a form in a Svelte component.
3
+ * @param {Form} form - The form to use.
4
+ * @returns
5
+ */
6
+ export function useForm(form) {
7
+ let _form = Object.assign(form, {
8
+ originalData: JSON.parse(JSON.stringify(form.data ?? {})),
9
+ domForm: null,
10
+ data: form.data ?? {},
11
+ state: 'idle',
12
+ });
13
+ // Have to declare a variable separately to use in the return object
14
+ // as the compiler is looking for a declaration.
15
+ let __form = $state(_form);
16
+ return __form;
17
+ }
18
+ /**
19
+ * Validate a single field.
20
+ * @param {Form} form - The form to validate.
21
+ * @param {string} name - The name of the field to validate.
22
+ * @param {HTMLInputElement | HTMLSelectElement} el - The element to validate.
23
+ * @param {ZodType} validator - The validator to use.
24
+ */
25
+ export function fieldValidate(form, name, el, validator) {
26
+ if (!validator)
27
+ return;
28
+ const result = validator.safeParse(getTypedValue(el));
29
+ if (result.success) {
30
+ form.issues = (form.issues || []).filter((issue) => issue.name !== name);
31
+ form.valid = form.issues.length === 0;
32
+ }
33
+ else {
34
+ form.valid = false;
35
+ form.issues = (form.issues || []).filter((issue) => issue.name !== name);
36
+ form.issues?.push({
37
+ name, // Include the path of the field.
38
+ ...((result.error?.issues?.length ? result.error.issues : [])?.[0]), // Include the first issue as we only care about one at a time.
39
+ });
40
+ }
41
+ }
42
+ /**
43
+ * Keydown event handler for a field.
44
+ * @param {KeyboardEvent} e - The event.
45
+ * @param {Form} form - The form to use.
46
+ * @param {string} name - The name of the field.
47
+ * @param {HTMLInputElement | HTMLSelectElement} el - The element to validate.
48
+ * @param {ZodType} validator - The validator to use.
49
+ * @param {(e: KeyboardEvent) => void} onkeydown - The onkeydown event handler.
50
+ */
51
+ export function fieldKeydown(form, name, el, validator, onkeydown) {
52
+ return async function (e) {
53
+ setTimeout(() => {
54
+ if (form) {
55
+ const possibleKey = e?.key;
56
+ if (ignoreKeys.includes(possibleKey))
57
+ return;
58
+ form.data[name] = el()?.value || '';
59
+ fieldValidate(form, name, el(), validator);
60
+ }
61
+ }, 0); // Wait for the key to be updated in the input.
62
+ if (onkeydown)
63
+ return onkeydown(e);
64
+ };
65
+ }
66
+ function getTypedValue(el) {
67
+ if (el?.type === 'number') {
68
+ const parsed = parseFloat(el.value);
69
+ // Zod v4 no longer accepts infinite values
70
+ return isFinite(parsed) ? parsed : el.value;
71
+ }
72
+ if (el?.type === 'checkbox')
73
+ return el.checked;
74
+ return el?.value;
75
+ }
76
+ /**
77
+ * Change event handler for a field.
78
+ * @param {Event} e - The event.
79
+ * @param {Form} form - The form to use.
80
+ * @param {string} name - The name of the field.
81
+ * @param {HTMLInputElement | HTMLSelectElement} el - The element to validate.
82
+ * @param {ZodType} validator - The validator to use.
83
+ * @param {(e: Event) => void} onchange - The onchange event handler.
84
+ */
85
+ export function fieldChange(form, name, el, validator, onchange) {
86
+ return async function (e) {
87
+ if (form && form.fields[name]) {
88
+ console.log('fieldChange', name, el()?.value, form.data[name]);
89
+ // Update the form data with the new value.
90
+ form.data[name] = getTypedValue(el());
91
+ // if the value is the same as the original value, then the field is not tainted
92
+ form.fields[name].tainted = form.data[name] !== form.originalData[name];
93
+ fieldValidate(form, name, el(), validator);
94
+ }
95
+ if (onchange)
96
+ return onchange(e);
97
+ };
98
+ }
99
+ /**
100
+ * Keys that should be ignored when marking a field as tainted.
101
+ */
102
+ export const ignoreKeys = ['Tab', 'Shift', 'Control', 'Alt', 'Meta', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Escape', 'CapsLock', 'NumLock', 'ScrollLock', 'Pause', 'ContextMenu', 'PrintScreen', 'Help', 'Clear', 'OS', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F12'];
@@ -0,0 +1,55 @@
1
+ import { Bodyguard, type BodyguardFormConfig, type BodyguardResult, type GenericIssue, type JSONLike } from "@auth70/bodyguard";
2
+ import type { RequestEvent } from "@sveltejs/kit";
3
+ import type { infer as Infer } from "zod";
4
+ import { type ZodTypes } from "zodex";
5
+ import type { LutraForm, FormField, FormIssue } from "./types.js";
6
+ export declare const bodyguard: Bodyguard;
7
+ /**
8
+ * Get fields from a Zod schema.
9
+ * @param {ZodTypes} schema - The schema to get fields from.
10
+ * @returns {Record<string, any>} - The fields from the schema.
11
+ */
12
+ export declare function getFieldsFromSchema<Z extends ZodTypes>(schema: Z, data?: BodyguardResult<any>, parents?: string[]): Record<string, FormField>;
13
+ /**
14
+ * Server page load call. Optionally with a default object to populate the form with from locals.
15
+ * @param {ZodTypes} schema - The schema to parse the form with.
16
+ * @param {RequestEvent} event - The event to load the (possible) form from.
17
+ * @param {JSONLike | string} objOrName - The default object to populate the form with, or the name of the object in locals.
18
+ * @param {JSONLike} obj - The default object to populate the form with.
19
+ * @returns {Promise<Form<Z>>} - The form to use.
20
+ */
21
+ export declare function loadForm<Z extends ZodTypes>(schema: Z, event: RequestEvent, objOrName?: JSONLike | string, obj?: JSONLike): Promise<LutraForm<Z>>;
22
+ /**
23
+ * Parse zod issues into form issues (with a path string).
24
+ * @param {ZodIssue[]} issues - The issues to parse.
25
+ * @returns {FormIssue[]} - The parsed issues.
26
+ */
27
+ export declare function parseFormIssues(issues: GenericIssue[]): FormIssue[];
28
+ /**
29
+ * Parse a form using a schema.
30
+ * @param {ZodTypes} schema - The schema to parse the form with.
31
+ * @param {Request} request - The request to parse.
32
+ * @param {BodyguardFormConfig | string} optsOrName - The options for the form validation, or the name of the form in locals.
33
+ * @param {BodyguardFormConfig} opts - The options for the form validation.
34
+ * @returns {Promise<{ valid: false } | { valid: true, data: Infer<Z> }>} - The result of the form validation.
35
+ */
36
+ export declare function parseForm<Z extends ZodTypes>(schema: Z, event: RequestEvent, optsOrName?: BodyguardFormConfig | string, opts?: BodyguardFormConfig): Promise<LutraForm<Z>>;
37
+ /**
38
+ * Convert an array path from a Zod issue to a string path for a form field.
39
+ * @param {PropertyKey[]} path - The path to convert.
40
+ * @returns {string} - The string path.
41
+ */
42
+ export declare function arrayPathToStringPath(path: PropertyKey[]): string;
43
+ /**
44
+ * Get a value from an object using a string path.
45
+ * @param {any} obj - The object to get the value from.
46
+ * @param {string} path - The path to get the value from.
47
+ * @returns {string | number | Date | boolean | object | undefined} - The value from the object.
48
+ */
49
+ export declare function getFromObjWithStringPath(obj: any, path: string): string | number | Date | boolean | object | undefined;
50
+ /**
51
+ * Get individual validators for each field in a form.
52
+ * @param {Form} form - The form to get the validators from.
53
+ * @returns {Record<keyof Infer<T>, (value: any) => boolean>} - The validators for each field.
54
+ */
55
+ export declare function getIndividualValidators<T extends ZodTypes>(form?: LutraForm<T>): Record<keyof Infer<T>, (value: any) => boolean>;
@@ -0,0 +1,345 @@
1
+ import { Bodyguard } from "@auth70/bodyguard";
2
+ import { ZodArray, ZodNullable, ZodOptional, ZodObject, ZodDefault, ZodString, ZodNumber, ZodBoolean, ZodDate } from "zod";
3
+ import { zerialize, dezerialize } from "zodex";
4
+ export const bodyguard = new Bodyguard();
5
+ /**
6
+ * Map a Zod type to a field type as a string.
7
+ * @param {Zod.ZodType} schema - The Zod schema to map to a field type.
8
+ * @returns {string} - The field type as a string.
9
+ */
10
+ function mapZodTypeToFieldType(schema) {
11
+ if (schema instanceof ZodNullable) {
12
+ return mapZodTypeToFieldType(schema.unwrap());
13
+ }
14
+ if (schema instanceof ZodOptional) {
15
+ return mapZodTypeToFieldType(schema.unwrap());
16
+ }
17
+ if (schema instanceof ZodArray) {
18
+ return `Array<${mapZodTypeToFieldType(schema.element)}>`;
19
+ }
20
+ if (schema instanceof ZodObject) {
21
+ return 'object';
22
+ }
23
+ if (schema instanceof ZodDefault) {
24
+ return mapZodTypeToFieldType(schema._zod.def.innerType);
25
+ }
26
+ if (schema instanceof ZodDate) {
27
+ return 'date';
28
+ }
29
+ if (schema instanceof ZodString) {
30
+ return 'string';
31
+ }
32
+ if (schema instanceof ZodNumber) {
33
+ return 'number';
34
+ }
35
+ if (schema instanceof ZodBoolean) {
36
+ return 'boolean';
37
+ }
38
+ return schema.constructor.name;
39
+ }
40
+ /**
41
+ * Get fields from a Zod schema.
42
+ * @param {ZodTypes} schema - The schema to get fields from.
43
+ * @returns {Record<string, any>} - The fields from the schema.
44
+ */
45
+ export function getFieldsFromSchema(schema, data, parents) {
46
+ if (!parents)
47
+ parents = [];
48
+ else
49
+ parents = [...parents];
50
+ const fields = {};
51
+ if (!(schema instanceof ZodObject)) {
52
+ console.error('[lutra] getFieldsFromSchema: Schema is not an object:', schema.constructor.name);
53
+ return fields;
54
+ }
55
+ for (const key in schema.shape) {
56
+ const field = schema.shape[key];
57
+ // Fields can be wrapped like ZodDefault.def.innerType.def.InnerType, etc. We want the last inner type's definition.
58
+ // On the way, let's check if any of the def include a defaultValue.
59
+ let required = true;
60
+ let defaultValue = undefined;
61
+ let min = undefined;
62
+ let max = undefined;
63
+ let pattern = undefined;
64
+ let minlength = undefined;
65
+ let maxlength = undefined;
66
+ let type = field;
67
+ while (type instanceof ZodOptional || type instanceof ZodDefault || type instanceof ZodNullable) {
68
+ if (type instanceof ZodOptional || type instanceof ZodNullable) {
69
+ required = false;
70
+ type = type._zod.def.innerType;
71
+ }
72
+ if (type instanceof ZodDefault) {
73
+ defaultValue = typeof type._zod.def.defaultValue === 'function'
74
+ ? type._zod.def.defaultValue()
75
+ : type._zod.def.defaultValue;
76
+ type = type._zod.def.innerType;
77
+ }
78
+ else {
79
+ type = type._zod.def.innerType ? type._zod.def.innerType : type;
80
+ }
81
+ }
82
+ // Check for min/max/regex checks
83
+ if ((type._zod.def).checks) {
84
+ for (const check of type._zod.def.checks) {
85
+ if (check.kind === 'min') {
86
+ if (field instanceof ZodString || field._zod?.def?.innerType instanceof ZodString) {
87
+ minlength = check.value;
88
+ }
89
+ else {
90
+ min = check.value;
91
+ }
92
+ }
93
+ if (check.kind === 'max') {
94
+ if (field instanceof ZodString || field._zod?.def?.innerType instanceof ZodString) {
95
+ maxlength = check.value;
96
+ }
97
+ else {
98
+ max = check.value;
99
+ }
100
+ }
101
+ if (check.kind === 'regex') {
102
+ pattern = check.regex.source;
103
+ }
104
+ if (check.kind === 'email') {
105
+ pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
106
+ }
107
+ if (check.kind === 'url') {
108
+ pattern = /^(https?:\/\/)?[^\s/$.?#].[^\s]*$/;
109
+ }
110
+ if (check.kind === 'uuid') {
111
+ pattern = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
112
+ }
113
+ }
114
+ }
115
+ if (type instanceof ZodObject) {
116
+ const children = getFieldsFromSchema(type, data, [...parents, key]);
117
+ Object.entries(children).forEach(([childKey, childField]) => {
118
+ const name = [...parents, key, childKey].join('.');
119
+ fields[name] = {
120
+ name,
121
+ tainted: childField.tainted,
122
+ coerce: childField.coerce,
123
+ min: childField.min,
124
+ max: childField.max,
125
+ minlength: childField.minlength,
126
+ maxlength: childField.maxlength,
127
+ pattern: childField.pattern,
128
+ required: childField.required,
129
+ defaultValue: childField.defaultValue,
130
+ isArray: childField.isArray,
131
+ type: childField.type,
132
+ };
133
+ });
134
+ }
135
+ else {
136
+ fields[key] = {
137
+ name: [...parents, key].join('.'),
138
+ tainted: false,
139
+ min,
140
+ max,
141
+ minlength,
142
+ maxlength,
143
+ pattern,
144
+ required,
145
+ defaultValue,
146
+ isArray: field instanceof ZodArray,
147
+ type: mapZodTypeToFieldType(field instanceof ZodArray ? field.element : field),
148
+ };
149
+ }
150
+ }
151
+ return fields;
152
+ }
153
+ /**
154
+ * Server page load call. Optionally with a default object to populate the form with from locals.
155
+ * @param {ZodTypes} schema - The schema to parse the form with.
156
+ * @param {RequestEvent} event - The event to load the (possible) form from.
157
+ * @param {JSONLike | string} objOrName - The default object to populate the form with, or the name of the object in locals.
158
+ * @param {JSONLike} obj - The default object to populate the form with.
159
+ * @returns {Promise<Form<Z>>} - The form to use.
160
+ */
161
+ export async function loadForm(schema, event, objOrName = 'form', obj) {
162
+ let name = typeof objOrName === 'string' ? objOrName : 'form';
163
+ let _obj = typeof objOrName === 'string' ? obj : objOrName;
164
+ // If there is a form in locals, it's been passed down from a form action using parseForm. Return it.
165
+ if (event.locals[name]) {
166
+ return Promise.resolve(event.locals[name]);
167
+ }
168
+ // Serialize the schema to send over the wire.
169
+ const serializedSchema = zerialize(schema);
170
+ // Get the fields from the schema.
171
+ const fields = getFieldsFromSchema(schema);
172
+ // Create the form object.
173
+ const form = event.locals.form;
174
+ return {
175
+ name,
176
+ valid: form ? form.valid : (obj ? true : false),
177
+ tainted: form ? form.tainted : false,
178
+ schema: serializedSchema,
179
+ posted: form ? form.posted : false,
180
+ state: form ? form.state : 'idle',
181
+ fields,
182
+ data: Object.assign(Object.fromEntries(Object.entries(fields).map(([key, value]) => {
183
+ // If the key is in the passed object, use that value. Otherwise, try to use the default value.
184
+ return [key, value.defaultValue];
185
+ })), _obj ? _obj : {}),
186
+ };
187
+ }
188
+ /**
189
+ * Parse zod issues into form issues (with a path string).
190
+ * @param {ZodIssue[]} issues - The issues to parse.
191
+ * @returns {FormIssue[]} - The parsed issues.
192
+ */
193
+ export function parseFormIssues(issues) {
194
+ return JSON.parse(JSON.stringify((issues || []).map((issue) => {
195
+ return {
196
+ ...issue,
197
+ name: arrayPathToStringPath(issue.path),
198
+ };
199
+ })));
200
+ }
201
+ /**
202
+ * Parse a form using a schema.
203
+ * @param {ZodTypes} schema - The schema to parse the form with.
204
+ * @param {Request} request - The request to parse.
205
+ * @param {BodyguardFormConfig | string} optsOrName - The options for the form validation, or the name of the form in locals.
206
+ * @param {BodyguardFormConfig} opts - The options for the form validation.
207
+ * @returns {Promise<{ valid: false } | { valid: true, data: Infer<Z> }>} - The result of the form validation.
208
+ */
209
+ export async function parseForm(schema, event, optsOrName = 'form', opts) {
210
+ let name = typeof optsOrName === 'string' ? optsOrName : 'form';
211
+ opts = typeof optsOrName === 'string' ? opts : optsOrName;
212
+ // Use bodyguard to parse the form.
213
+ const data = await bodyguard.softForm(event.request, (input) => schema.parse(input), opts);
214
+ // Get the fields from the schema.
215
+ const fields = getFieldsFromSchema(schema, data);
216
+ // Serialize the schema to send over the wire.
217
+ const serializedSchema = zerialize(schema);
218
+ // Create the form object.
219
+ const form = {
220
+ name: name,
221
+ valid: data.success,
222
+ tainted: !data.success,
223
+ state: data.success ? 'success' : 'error',
224
+ schema: serializedSchema,
225
+ posted: true,
226
+ fields: Object.fromEntries(Object.entries(fields).map(([key, field]) => {
227
+ // Mark fields as tainted if they were in the request.
228
+ return [key, {
229
+ ...field,
230
+ tainted: data.success ? false : (data.value && typeof data.value === 'object' && 'hasOwnProperty' in data.value ? data.value.hasOwnProperty(key) : false),
231
+ }];
232
+ })),
233
+ // ensure all fields are present by populating `data` from `fields` instead of trusting `data` to have all fields
234
+ data: Object.assign(Object.fromEntries(Object.entries(fields).map(([key, value]) => {
235
+ const dataValue = data.value && typeof data.value === 'object' ? data.value[key] : undefined;
236
+ return [key, value.isArray ? (dataValue || []) : (dataValue !== undefined ? dataValue : (value.defaultValue ?? null))];
237
+ })), data.value || {}),
238
+ issues: data.success ? undefined : parseFormIssues(data.error.issues),
239
+ };
240
+ // Attach the form to the locals to pass it to the client via loadForm.
241
+ event.locals[name] = form;
242
+ return form;
243
+ }
244
+ /**
245
+ * Convert an array path from a Zod issue to a string path for a form field.
246
+ * @param {PropertyKey[]} path - The path to convert.
247
+ * @returns {string} - The string path.
248
+ */
249
+ export function arrayPathToStringPath(path) {
250
+ // Joins the path with dots. For arrays, it adds brackets.
251
+ // Symbols are converted to strings using String()
252
+ return path.map((p) => {
253
+ const pStr = typeof p === 'symbol' ? String(p) : p.toString();
254
+ if (pStr.match(/^\d+$/)) {
255
+ return `${pStr}[]`;
256
+ }
257
+ return pStr;
258
+ }).join('.');
259
+ }
260
+ /**
261
+ * Get a value from an object using a string path.
262
+ * @param {any} obj - The object to get the value from.
263
+ * @param {string} path - The path to get the value from.
264
+ * @returns {string | number | Date | boolean | object | undefined} - The value from the object.
265
+ */
266
+ export function getFromObjWithStringPath(obj, path) {
267
+ if (!obj)
268
+ return undefined;
269
+ const parts = path.split('.');
270
+ let current = obj;
271
+ for (let i = 0; i < parts.length; i++) {
272
+ const part = parts[i];
273
+ // Support for array access patterns: foo[] or foo[0]
274
+ const arrayMatch = part.match(/^(.+?)(\[\d*\])?$/);
275
+ if (arrayMatch) {
276
+ const [, key, indexPart] = arrayMatch;
277
+ // Navigate into 'properties' if it exists
278
+ if (current.properties && current.properties[key]) {
279
+ current = current.properties[key];
280
+ }
281
+ else if (current[key]) {
282
+ current = current[key];
283
+ }
284
+ else {
285
+ // The path is invalid for the given structure or the index is not a number
286
+ return undefined;
287
+ }
288
+ // If indexPart is defined, it means we're dealing with an array index
289
+ if (indexPart) {
290
+ // Dealing with an array index, e.g., [0]
291
+ const index = parseInt(indexPart.slice(1, -1), 10);
292
+ if (!Array.isArray(current) || isNaN(index)) {
293
+ return undefined;
294
+ }
295
+ current = current[index];
296
+ }
297
+ }
298
+ else {
299
+ // Direct property access
300
+ if (current.properties && current.properties[part]) {
301
+ current = current.properties[part];
302
+ }
303
+ else if (current[part]) {
304
+ current = current[part];
305
+ }
306
+ else {
307
+ return undefined;
308
+ }
309
+ }
310
+ if (current === undefined) {
311
+ return undefined;
312
+ }
313
+ }
314
+ // The value must be directly returnable without checking type,
315
+ // as we might be looking for an object structure.
316
+ return current;
317
+ }
318
+ /**
319
+ * Get individual validators for each field in a form.
320
+ * @param {Form} form - The form to get the validators from.
321
+ * @returns {Record<keyof Infer<T>, (value: any) => boolean>} - The validators for each field.
322
+ */
323
+ export function getIndividualValidators(form) {
324
+ if (!form)
325
+ return {};
326
+ const schema = form.schema;
327
+ const fields = form.fields;
328
+ //console.log('[lutra] getIndividualValidators:', schema, fields, form)
329
+ if (!schema || !fields) {
330
+ console.error('[lutra] getIndividualValidators: Schema or fields not found:', schema, fields);
331
+ return {};
332
+ }
333
+ // Match the dot-notation form fields with the object schema fields.
334
+ // For each field, create a validator function by dezerilizing the schema for that field from the schema.
335
+ // Return the validators, not the parsed data.
336
+ const validators = Object.fromEntries(Object.entries(fields).map(([key, field]) => {
337
+ const schemaField = getFromObjWithStringPath(schema, key);
338
+ if (!schemaField) {
339
+ console.error('[lutra] getIndividualValidators: Schema field not found:', key);
340
+ return [key, (value) => true];
341
+ }
342
+ return [key, dezerialize(schemaField)];
343
+ }));
344
+ return validators;
345
+ }