@thomasfosterau/effect-forms-svelte 0.2.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -19
- package/dist/ClientValidate.d.ts +1 -2
- package/dist/ClientValidate.js +1 -2
- package/dist/EnhanceCore.d.ts +34 -4
- package/dist/EnhanceCore.js +106 -39
- package/dist/EnhanceCore.js.map +1 -1
- package/dist/EntityForm.d.ts +0 -2
- package/dist/EntityForm.js +29 -30
- package/dist/EntityForm.js.map +1 -1
- package/dist/FormStore.svelte.d.ts +11 -5
- package/dist/FormStore.svelte.js +94 -61
- package/dist/FormStore.svelte.js.map +1 -1
- package/dist/Listeners.d.ts +1 -2
- package/dist/Listeners.js +4 -4
- package/dist/Listeners.js.map +1 -1
- package/dist/SvelteKit.d.ts +1 -2
- package/dist/SvelteKit.js +3 -3
- package/dist/SvelteKit.js.map +1 -1
- package/dist/Tainted.d.ts +1 -2
- package/dist/Tainted.js +28 -41
- package/dist/Tainted.js.map +1 -1
- package/dist/_virtual/_rolldown/runtime.js +1 -2
- package/dist/kit/ActionRedirect.d.ts +0 -2
- package/dist/kit/ActionRedirect.js +12 -15
- package/dist/kit/ActionRedirect.js.map +1 -1
- package/dist/kit/CommandFailure.d.ts +1 -2
- package/dist/kit/CommandFailure.js +18 -20
- package/dist/kit/CommandFailure.js.map +1 -1
- package/dist/kit/Enhance.d.ts +0 -2
- package/dist/kit/Enhance.js +1 -2
- package/dist/kit/FormAction.d.ts +0 -2
- package/dist/kit/FormAction.js +39 -33
- package/dist/kit/FormAction.js.map +1 -1
- package/dist/kit/FormStateReaders.d.ts +0 -2
- package/dist/kit/FormStateReaders.js +4 -4
- package/dist/kit/FormStateReaders.js.map +1 -1
- package/dist/kit/Pointer.d.ts +0 -2
- package/dist/kit/Pointer.js +1 -2
- package/package.json +6 -6
package/dist/Tainted.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import * as Arr from "effect/Array";
|
|
2
|
+
import * as Predicate from "effect/Predicate";
|
|
3
|
+
import * as Record from "effect/Record";
|
|
4
|
+
// src/Tainted.ts
|
|
5
|
+
/** A non-null object or array, indexable by its own string keys. */
|
|
6
|
+
const isObject = (value) => Predicate.isObjectOrArray(value);
|
|
7
|
+
/** The union of both containers' own enumerable keys, `a`'s first. */
|
|
8
|
+
const unionKeys = (a, b) => Arr.union(Record.keys(a), Record.keys(b));
|
|
3
9
|
/** Structural deep equality for plain JSON-ish values. */
|
|
4
10
|
function deepEqual(a, b) {
|
|
5
11
|
if (a === b) return true;
|
|
6
12
|
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
7
|
-
if (isObject(a) && isObject(b))
|
|
8
|
-
const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
9
|
-
for (const key of keys) if (!deepEqual(a[key], b[key])) return false;
|
|
10
|
-
return true;
|
|
11
|
-
}
|
|
13
|
+
if (isObject(a) && isObject(b)) return Arr.every(unionKeys(a, b), (key) => deepEqual(a[key], b[key]));
|
|
12
14
|
return false;
|
|
13
15
|
}
|
|
14
16
|
/** Whether two containers are the same kind (both arrays, or both plain objects). */
|
|
@@ -22,37 +24,27 @@ const sameKind = (a, b) => Array.isArray(a) === Array.isArray(b);
|
|
|
22
24
|
*/
|
|
23
25
|
function computeTainted(original, current) {
|
|
24
26
|
if (!isObject(original) || !isObject(current) || !sameKind(original, current)) return {};
|
|
25
|
-
|
|
26
|
-
const keys = /* @__PURE__ */ new Set([...Object.keys(original), ...Object.keys(current)]);
|
|
27
|
-
for (const key of keys) {
|
|
27
|
+
return Record.fromEntries(Arr.flatMap(unionKeys(original, current), (key) => {
|
|
28
28
|
const before = original[key];
|
|
29
29
|
const after = current[key];
|
|
30
30
|
if (isObject(before) && isObject(after) && sameKind(before, after)) {
|
|
31
31
|
const nested = computeTainted(before, after);
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
|
|
32
|
+
return Record.isEmptyReadonlyRecord(nested) ? [] : [[key, nested]];
|
|
33
|
+
}
|
|
34
|
+
return deepEqual(before, after) ? [] : [[key, true]];
|
|
35
|
+
}));
|
|
36
36
|
}
|
|
37
37
|
/** Whether anything in the tree is tainted. */
|
|
38
38
|
function isAnyTainted(tainted) {
|
|
39
|
-
|
|
40
|
-
const value = tainted[key];
|
|
41
|
-
if (value === true) return true;
|
|
42
|
-
if (isObject(value) && isAnyTainted(value)) return true;
|
|
43
|
-
}
|
|
44
|
-
return false;
|
|
39
|
+
return Arr.some(Record.values(tainted), (value) => value === true || isObject(value) && isAnyTainted(value));
|
|
45
40
|
}
|
|
46
41
|
/** Whether the field at `path` (or anything beneath it) is tainted. */
|
|
47
42
|
function isTaintedAt(tainted, path) {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
if (node === void 0) return false;
|
|
54
|
-
if (typeof node === "boolean") return node;
|
|
55
|
-
return isAnyTainted(node);
|
|
43
|
+
const go = (node, rest) => Arr.match(rest, {
|
|
44
|
+
onEmpty: () => Predicate.isUndefined(node) ? false : Predicate.isBoolean(node) ? node : isAnyTainted(node),
|
|
45
|
+
onNonEmpty: (segments) => Predicate.isUndefined(node) || Predicate.isBoolean(node) ? node === true : go(node[String(Arr.headNonEmpty(segments))], Arr.tailNonEmpty(segments))
|
|
46
|
+
});
|
|
47
|
+
return go(tainted, path);
|
|
56
48
|
}
|
|
57
49
|
/**
|
|
58
50
|
* Flatten a {@link TaintedFields} tree into the list of leaf {@link FormPath}s
|
|
@@ -62,20 +54,15 @@ function isTaintedAt(tainted, path) {
|
|
|
62
54
|
* which only says *something* changed).
|
|
63
55
|
*/
|
|
64
56
|
function taintedLeafPaths(tainted) {
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
walk(tainted, []);
|
|
76
|
-
return out;
|
|
57
|
+
const walk = (node, path) => Arr.flatMap(Record.toEntries(node), ([key, value]) => {
|
|
58
|
+
if (Predicate.isUndefined(value)) return [];
|
|
59
|
+
const segment = /^\d+$/.test(key) ? Number(key) : key;
|
|
60
|
+
if (value === true) return [[...path, segment]];
|
|
61
|
+
if (isObject(value)) return walk(value, [...path, segment]);
|
|
62
|
+
return [];
|
|
63
|
+
});
|
|
64
|
+
return walk(tainted, []);
|
|
77
65
|
}
|
|
78
|
-
//#endregion
|
|
79
66
|
export { computeTainted, deepEqual, isAnyTainted, isTaintedAt, taintedLeafPaths };
|
|
80
67
|
|
|
81
68
|
//# sourceMappingURL=Tainted.js.map
|
package/dist/Tainted.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Tainted.js","names":[],"sources":["../src/Tainted.ts"],"sourcesContent":["/**\n * Tainted-field tracking — which fields the user has changed since the form\n * was seeded.\n *\n * A `tainted` store lets a UI show \"unsaved changes\",\n * guard navigation, or submit only what changed. This is the pure half: a deep\n * diff of the current data against the original snapshot producing a nested\n * boolean tree mirroring the data's shape. The reactive store\n * (`superForm.svelte.ts`) re-derives it as the data changes.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/Tainted\n */\n\nimport type { Issues } from \"@thomasfosterau/effect-forms\";\n\ntype FormPath = Issues.FormPath;\n\n/** A nested tree mirroring the form data, `true` where a leaf has changed. */\nexport interface TaintedFields {\n readonly [key: string]: boolean | TaintedFields | undefined;\n}\n\nconst isObject = (value: unknown): value is
|
|
1
|
+
{"version":3,"file":"Tainted.js","names":[],"sources":["../src/Tainted.ts"],"sourcesContent":["/**\n * Tainted-field tracking — which fields the user has changed since the form\n * was seeded.\n *\n * A `tainted` store lets a UI show \"unsaved changes\",\n * guard navigation, or submit only what changed. This is the pure half: a deep\n * diff of the current data against the original snapshot producing a nested\n * boolean tree mirroring the data's shape. The reactive store\n * (`superForm.svelte.ts`) re-derives it as the data changes.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/Tainted\n */\n\nimport type { Issues } from \"@thomasfosterau/effect-forms\";\nimport * as Arr from \"effect/Array\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\n\ntype FormPath = Issues.FormPath;\n\n/** A nested tree mirroring the form data, `true` where a leaf has changed. */\nexport interface TaintedFields {\n readonly [key: string]: boolean | TaintedFields | undefined;\n}\n\n/** An object or array read through its string keys. */\ntype Indexable = { readonly [key: string]: unknown };\n\n/** A non-null object or array, indexable by its own string keys. */\nconst isObject = (value: unknown): value is Indexable => Predicate.isObjectOrArray(value);\n\n/** The union of both containers' own enumerable keys, `a`'s first. */\nconst unionKeys = (a: Indexable, b: Indexable): Array<string> =>\n Arr.union(Record.keys(a), Record.keys(b));\n\n/** Structural deep equality for plain JSON-ish values. */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));\n }\n if (isObject(a) && isObject(b)) {\n return Arr.every(unionKeys(a, b), (key) => deepEqual(a[key], b[key]));\n }\n return false;\n}\n\n/** Whether two containers are the same kind (both arrays, or both plain objects). */\nconst sameKind = (a: unknown, b: unknown): boolean => Array.isArray(a) === Array.isArray(b);\n\n/**\n * Compare `current` against `original`, returning the nested tainted tree.\n * A changed scalar leaf is `true`; an unchanged leaf is omitted; nested objects\n * **and arrays** recurse (array elements keyed by index), so a single changed\n * row taints only that index — `taintedAt([\"items\", 2, \"name\"])` stays precise.\n * Keys present in either side are considered.\n */\nexport function computeTainted(original: unknown, current: unknown): TaintedFields {\n if (!isObject(original) || !isObject(current) || !sameKind(original, current)) return {};\n\n return Record.fromEntries(\n Arr.flatMap(\n unionKeys(original, current),\n (key): Array<readonly [string, boolean | TaintedFields]> => {\n const before = original[key];\n const after = current[key];\n if (isObject(before) && isObject(after) && sameKind(before, after)) {\n const nested = computeTainted(before, after);\n return Record.isEmptyReadonlyRecord(nested) ? [] : [[key, nested]];\n }\n return deepEqual(before, after) ? [] : [[key, true]];\n },\n ),\n );\n}\n\n/** Whether anything in the tree is tainted. */\nexport function isAnyTainted(tainted: TaintedFields): boolean {\n return Arr.some(\n Record.values(tainted),\n (value) => value === true || (isObject(value) && isAnyTainted(value)),\n );\n}\n\n/** Whether the field at `path` (or anything beneath it) is tainted. */\nexport function isTaintedAt(tainted: TaintedFields, path: FormPath): boolean {\n const go = (node: boolean | TaintedFields | undefined, rest: FormPath): boolean =>\n Arr.match(rest, {\n onEmpty: () =>\n Predicate.isUndefined(node) ? false : Predicate.isBoolean(node) ? node : isAnyTainted(node),\n onNonEmpty: (segments) =>\n Predicate.isUndefined(node) || Predicate.isBoolean(node)\n ? node === true\n : go(node[String(Arr.headNonEmpty(segments))], Arr.tailNonEmpty(segments)),\n });\n return go(tainted, path);\n}\n\n/**\n * Flatten a {@link TaintedFields} tree into the list of leaf {@link FormPath}s\n * that actually changed, in depth-first order — the per-field-changed events\n * a reactive store needs to run per-field validators / clear a superseded\n * server error at exactly the field that moved (as opposed to `isAnyTainted`,\n * which only says *something* changed).\n */\nexport function taintedLeafPaths(tainted: TaintedFields): FormPath[] {\n const walk = (node: TaintedFields, path: Array<string | number>): FormPath[] =>\n Arr.flatMap(Record.toEntries(node), ([key, value]): FormPath[] => {\n if (Predicate.isUndefined(value)) return [];\n const segment: string | number = /^\\d+$/.test(key) ? Number(key) : key;\n if (value === true) return [[...path, segment]];\n if (isObject(value)) return walk(value, [...path, segment]);\n return [];\n });\n\n return walk(tainted, []);\n}\n"],"mappings":";;;;;AA8BA,MAAM,YAAY,UAAuC,UAAU,gBAAgB,KAAK;;AAGxF,MAAM,aAAa,GAAc,MAC/B,IAAI,MAAM,OAAO,KAAK,CAAC,GAAG,OAAO,KAAK,CAAC,CAAC;;AAG1C,SAAgB,UAAU,GAAY,GAAqB;CACzD,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,MAAM,QAAQ,CAAC,KAAK,MAAM,QAAQ,CAAC,GACrC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,MAAM,MAAM,UAAU,MAAM,EAAE,EAAE,CAAC;CAE5E,IAAI,SAAS,CAAC,KAAK,SAAS,CAAC,GAC3B,OAAO,IAAI,MAAM,UAAU,GAAG,CAAC,IAAI,QAAQ,UAAU,EAAE,MAAM,EAAE,IAAI,CAAC;CAEtE,OAAO;AACT;;AAGA,MAAM,YAAY,GAAY,MAAwB,MAAM,QAAQ,CAAC,MAAM,MAAM,QAAQ,CAAC;;;;;;;;AAS1F,SAAgB,eAAe,UAAmB,SAAiC;CACjF,IAAI,CAAC,SAAS,QAAQ,KAAK,CAAC,SAAS,OAAO,KAAK,CAAC,SAAS,UAAU,OAAO,GAAG,OAAO,CAAC;CAEvF,OAAO,OAAO,YACZ,IAAI,QACF,UAAU,UAAU,OAAO,IAC1B,QAA2D;EAC1D,MAAM,SAAS,SAAS;EACxB,MAAM,QAAQ,QAAQ;EACtB,IAAI,SAAS,MAAM,KAAK,SAAS,KAAK,KAAK,SAAS,QAAQ,KAAK,GAAG;GAClE,MAAM,SAAS,eAAe,QAAQ,KAAK;GAC3C,OAAO,OAAO,sBAAsB,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,MAAM,CAAC;EACnE;EACA,OAAO,UAAU,QAAQ,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,IAAI,CAAC;CACrD,CACF,CACF;AACF;;AAGA,SAAgB,aAAa,SAAiC;CAC5D,OAAO,IAAI,KACT,OAAO,OAAO,OAAO,IACpB,UAAU,UAAU,QAAS,SAAS,KAAK,KAAK,aAAa,KAAK,CACrE;AACF;;AAGA,SAAgB,YAAY,SAAwB,MAAyB;CAC3E,MAAM,MAAM,MAA2C,SACrD,IAAI,MAAM,MAAM;EACd,eACE,UAAU,YAAY,IAAI,IAAI,QAAQ,UAAU,UAAU,IAAI,IAAI,OAAO,aAAa,IAAI;EAC5F,aAAa,aACX,UAAU,YAAY,IAAI,KAAK,UAAU,UAAU,IAAI,IACnD,SAAS,OACT,GAAG,KAAK,OAAO,IAAI,aAAa,QAAQ,CAAC,IAAI,IAAI,aAAa,QAAQ,CAAC;CAC/E,CAAC;CACH,OAAO,GAAG,SAAS,IAAI;AACzB;;;;;;;;AASA,SAAgB,iBAAiB,SAAoC;CACnE,MAAM,QAAQ,MAAqB,SACjC,IAAI,QAAQ,OAAO,UAAU,IAAI,IAAI,CAAC,KAAK,WAAuB;EAChE,IAAI,UAAU,YAAY,KAAK,GAAG,OAAO,CAAC;EAC1C,MAAM,UAA2B,QAAQ,KAAK,GAAG,IAAI,OAAO,GAAG,IAAI;EACnE,IAAI,UAAU,MAAM,OAAO,CAAC,CAAC,GAAG,MAAM,OAAO,CAAC;EAC9C,IAAI,SAAS,KAAK,GAAG,OAAO,KAAK,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC;EAC1D,OAAO,CAAC;CACV,CAAC;CAEH,OAAO,KAAK,SAAS,CAAC,CAAC;AACzB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// \0rolldown/runtime.js
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
3
|
var __exportAll = (all, no_symbols) => {
|
|
4
4
|
let target = {};
|
|
@@ -9,5 +9,4 @@ var __exportAll = (all, no_symbols) => {
|
|
|
9
9
|
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
10
10
|
return target;
|
|
11
11
|
};
|
|
12
|
-
//#endregion
|
|
13
12
|
export { __exportAll };
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import * as Option from "effect/Option";
|
|
2
|
-
//#region src/kit/ActionRedirect.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* A user-fixable failure's message; `None` takes the hard-error path.
|
|
5
4
|
*
|
|
@@ -18,5 +17,4 @@ export declare const userFixableMessage: (cause: unknown, fallback: string) => O
|
|
|
18
17
|
* answering the path and query only (never an origin).
|
|
19
18
|
*/
|
|
20
19
|
export declare const withFailureParams: (target: string, params: Readonly<Record<string, string>>) => string;
|
|
21
|
-
//#endregion
|
|
22
20
|
//# sourceMappingURL=ActionRedirect.d.ts.map
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { detailOf, jsonapiFailure } from "./CommandFailure.js";
|
|
2
|
-
import * as
|
|
2
|
+
import * as Arr from "effect/Array";
|
|
3
3
|
import * as Predicate from "effect/Predicate";
|
|
4
|
-
|
|
4
|
+
import * as Record from "effect/Record";
|
|
5
|
+
import * as HashSet from "effect/HashSet";
|
|
6
|
+
import * as Option from "effect/Option";
|
|
7
|
+
// src/kit/ActionRedirect.ts
|
|
5
8
|
/**
|
|
6
9
|
* Failure routing for **action-only** routes: a route with no page of its
|
|
7
10
|
* own (a restore, a confirm) always answers a submission with a redirect, so
|
|
@@ -14,11 +17,7 @@ import * as Predicate from "effect/Predicate";
|
|
|
14
17
|
* @module effect-forms-svelte/kit/ActionRedirect
|
|
15
18
|
*/
|
|
16
19
|
/** The statuses whose failure the submitter can act on (the form layer's set). */
|
|
17
|
-
const USER_FIXABLE_STATUSES =
|
|
18
|
-
400,
|
|
19
|
-
409,
|
|
20
|
-
422
|
|
21
|
-
]);
|
|
20
|
+
const USER_FIXABLE_STATUSES = HashSet.make(400, 409, 422);
|
|
22
21
|
/**
|
|
23
22
|
* A user-fixable failure's message; `None` takes the hard-error path.
|
|
24
23
|
*
|
|
@@ -33,13 +32,12 @@ const USER_FIXABLE_STATUSES = /* @__PURE__ */ new Set([
|
|
|
33
32
|
*/
|
|
34
33
|
const userFixableMessage = (cause, fallback) => {
|
|
35
34
|
if (!Predicate.isObjectOrArray(cause)) return Option.none();
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
return Option.some(Predicate.isString(tagged.message) ? tagged.message : fallback);
|
|
35
|
+
if (Predicate.isTagged(cause, "HttpError")) {
|
|
36
|
+
if (!Predicate.hasProperty(cause, "status") || cause.status !== 400) return Option.none();
|
|
37
|
+
return Option.some(Predicate.hasProperty(cause, "message") && Predicate.isString(cause.message) ? cause.message : fallback);
|
|
40
38
|
}
|
|
41
|
-
if (
|
|
42
|
-
return jsonapiFailure(cause).pipe(Option.filter((failure) =>
|
|
39
|
+
if (!Predicate.isTagged(cause, "JsonapiError") && !Predicate.isTagged(cause, "ErrorResponse")) return Option.none();
|
|
40
|
+
return jsonapiFailure(cause).pipe(Option.filter((failure) => HashSet.has(USER_FIXABLE_STATUSES, failure.status)), Option.map((failure) => Predicate.isTagged(failure, "Routed") ? detailOf(failure.errors[0], fallback) : failure.message));
|
|
43
41
|
};
|
|
44
42
|
/**
|
|
45
43
|
* Append the failure's query parameters to a same-origin return target,
|
|
@@ -47,10 +45,9 @@ const userFixableMessage = (cause, fallback) => {
|
|
|
47
45
|
*/
|
|
48
46
|
const withFailureParams = (target, params) => {
|
|
49
47
|
const url = new URL(target, "http://localhost");
|
|
50
|
-
|
|
48
|
+
Arr.forEach(Record.toEntries(params), ([key, value]) => url.searchParams.set(key, value));
|
|
51
49
|
return url.pathname + url.search;
|
|
52
50
|
};
|
|
53
|
-
//#endregion
|
|
54
51
|
export { userFixableMessage, withFailureParams };
|
|
55
52
|
|
|
56
53
|
//# sourceMappingURL=ActionRedirect.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ActionRedirect.js","names":[],"sources":["../../src/kit/ActionRedirect.ts"],"sourcesContent":["/**\n * Failure routing for **action-only** routes: a route with no page of its\n * own (a restore, a confirm) always answers a submission with a redirect, so\n * a *user-fixable* command failure rides back to the submitting page as\n * query parameters instead of a `fail()` (which would try to render the\n * action route's nonexistent page for a no-JS submitter). Everything else —\n * auth denials, infrastructure faults — stays a hard error at the caller.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/kit/ActionRedirect\n */\n\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport { detailOf, jsonapiFailure } from \"./CommandFailure.ts\";\n\n/** The statuses whose failure the submitter can act on (the form layer's set). */\nconst USER_FIXABLE_STATUSES:
|
|
1
|
+
{"version":3,"file":"ActionRedirect.js","names":[],"sources":["../../src/kit/ActionRedirect.ts"],"sourcesContent":["/**\n * Failure routing for **action-only** routes: a route with no page of its\n * own (a restore, a confirm) always answers a submission with a redirect, so\n * a *user-fixable* command failure rides back to the submitting page as\n * query parameters instead of a `fail()` (which would try to render the\n * action route's nonexistent page for a no-JS submitter). Everything else —\n * auth denials, infrastructure faults — stays a hard error at the caller.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/kit/ActionRedirect\n */\n\nimport * as Arr from \"effect/Array\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport { detailOf, jsonapiFailure } from \"./CommandFailure.ts\";\n\n/** The statuses whose failure the submitter can act on (the form layer's set). */\nconst USER_FIXABLE_STATUSES: HashSet.HashSet<number> = HashSet.make(400, 409, 422);\n\n/**\n * A user-fixable failure's message; `None` takes the hard-error path.\n *\n * - a `JsonapiError` / `ErrorResponse`-tagged cause at 400 / 409 / 422 → its\n * first error object's `detail`, else `title`, else `fallback` (an\n * `ErrorResponse` with no document → its own message);\n * - an `HttpError`-tagged 400 → its message (or `fallback`);\n * - anything else → `None`.\n *\n * `Some(\"\")` is a deliberate *present* answer: an error object carrying a\n * blank `detail` redirects with an empty parameter rather than escalating.\n */\nexport const userFixableMessage = (cause: unknown, fallback: string): Option.Option<string> => {\n if (!Predicate.isObjectOrArray(cause)) return Option.none();\n if (Predicate.isTagged(cause, \"HttpError\")) {\n if (!Predicate.hasProperty(cause, \"status\") || cause.status !== 400) return Option.none();\n return Option.some(\n Predicate.hasProperty(cause, \"message\") && Predicate.isString(cause.message)\n ? cause.message\n : fallback,\n );\n }\n if (!Predicate.isTagged(cause, \"JsonapiError\") && !Predicate.isTagged(cause, \"ErrorResponse\")) {\n return Option.none();\n }\n return jsonapiFailure(cause).pipe(\n Option.filter((failure) => HashSet.has(USER_FIXABLE_STATUSES, failure.status)),\n Option.map((failure) =>\n Predicate.isTagged(failure, \"Routed\")\n ? detailOf(failure.errors[0], fallback)\n : failure.message,\n ),\n );\n};\n\n/**\n * Append the failure's query parameters to a same-origin return target,\n * answering the path and query only (never an origin).\n */\nexport const withFailureParams = (\n target: string,\n params: Readonly<Record<string, string>>,\n): string => {\n const url = new URL(target, \"http://localhost\");\n Arr.forEach(Record.toEntries(params), ([key, value]) => url.searchParams.set(key, value));\n return url.pathname + url.search;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,MAAM,wBAAiD,QAAQ,KAAK,KAAK,KAAK,GAAG;;;;;;;;;;;;;AAcjF,MAAa,sBAAsB,OAAgB,aAA4C;CAC7F,IAAI,CAAC,UAAU,gBAAgB,KAAK,GAAG,OAAO,OAAO,KAAK;CAC1D,IAAI,UAAU,SAAS,OAAO,WAAW,GAAG;EAC1C,IAAI,CAAC,UAAU,YAAY,OAAO,QAAQ,KAAK,MAAM,WAAW,KAAK,OAAO,OAAO,KAAK;EACxF,OAAO,OAAO,KACZ,UAAU,YAAY,OAAO,SAAS,KAAK,UAAU,SAAS,MAAM,OAAO,IACvE,MAAM,UACN,QACN;CACF;CACA,IAAI,CAAC,UAAU,SAAS,OAAO,cAAc,KAAK,CAAC,UAAU,SAAS,OAAO,eAAe,GAC1F,OAAO,OAAO,KAAK;CAErB,OAAO,eAAe,KAAK,CAAC,CAAC,KAC3B,OAAO,QAAQ,YAAY,QAAQ,IAAI,uBAAuB,QAAQ,MAAM,CAAC,GAC7E,OAAO,KAAK,YACV,UAAU,SAAS,SAAS,QAAQ,IAChC,SAAS,QAAQ,OAAO,IAAI,QAAQ,IACpC,QAAQ,OACd,CACF;AACF;;;;;AAMA,MAAa,qBACX,QACA,WACW;CACX,MAAM,MAAM,IAAI,IAAI,QAAQ,kBAAkB;CAC9C,IAAI,QAAQ,OAAO,UAAU,MAAM,IAAI,CAAC,KAAK,WAAW,IAAI,aAAa,IAAI,KAAK,KAAK,CAAC;CACxF,OAAO,IAAI,WAAW,IAAI;AAC5B"}
|
|
@@ -26,7 +26,7 @@ export type CommandFailure = RoutedFailure | MessageFailure;
|
|
|
26
26
|
/** Construct a {@link RoutedFailure}. */
|
|
27
27
|
export declare const routed: (status: number, errors: ReadonlyArray<ErrorObject>) => CommandFailure;
|
|
28
28
|
/** Construct a {@link MessageFailure}. */
|
|
29
|
-
export declare const message: (status: number,
|
|
29
|
+
export declare const message: (status: number, text: string) => CommandFailure;
|
|
30
30
|
/** A classifier: `Some` for a failure the form can show, `None` for an unexpected one. */
|
|
31
31
|
export type Classify = (cause: unknown) => Option.Option<CommandFailure>;
|
|
32
32
|
/** The fallback message for an error object with neither `detail` nor `title`. */
|
|
@@ -47,6 +47,5 @@ export declare const detailOf: (error: ErrorObject | undefined, fallback?: strin
|
|
|
47
47
|
* - anything else → `None` (unexpected).
|
|
48
48
|
*/
|
|
49
49
|
export declare const jsonapiFailure: Classify;
|
|
50
|
-
//#endregion
|
|
51
50
|
export { CommandFailure_d_exports };
|
|
52
51
|
//# sourceMappingURL=CommandFailure.d.ts.map
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { __exportAll } from "../_virtual/_rolldown/runtime.js";
|
|
2
|
-
import * as
|
|
2
|
+
import * as Arr from "effect/Array";
|
|
3
3
|
import * as Predicate from "effect/Predicate";
|
|
4
|
-
|
|
4
|
+
import * as Option from "effect/Option";
|
|
5
|
+
// src/kit/CommandFailure.ts
|
|
5
6
|
/**
|
|
6
7
|
* Classifying what a form action's command failed with.
|
|
7
8
|
*
|
|
@@ -35,26 +36,26 @@ const routed = (status, errors) => ({
|
|
|
35
36
|
errors
|
|
36
37
|
});
|
|
37
38
|
/** Construct a {@link MessageFailure}. */
|
|
38
|
-
const message = (status,
|
|
39
|
+
const message = (status, text) => ({
|
|
39
40
|
_tag: "Message",
|
|
40
41
|
status,
|
|
41
|
-
message
|
|
42
|
+
message: text
|
|
42
43
|
});
|
|
43
44
|
/** The fallback message for an error object with neither `detail` nor `title`. */
|
|
44
45
|
const DEFAULT_MESSAGE = "Request could not be completed";
|
|
45
46
|
/** An error object's human message: its `detail`, else its `title`, else `fallback`. */
|
|
46
47
|
const detailOf = (error, fallback = DEFAULT_MESSAGE) => error?.detail ?? error?.title ?? fallback;
|
|
47
48
|
const isStatus = (u) => Predicate.isNumber(u) && Number.isInteger(u);
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
return Option.
|
|
54
|
-
onSome: (
|
|
55
|
-
onNone: () => message(status, Predicate.isString(cause.message) ? cause.message : DEFAULT_MESSAGE)
|
|
56
|
-
})
|
|
57
|
-
};
|
|
49
|
+
/** The cause's `status`, when it carries an integer one. */
|
|
50
|
+
const statusOf = (cause) => Predicate.hasProperty(cause, "status") && isStatus(cause.status) ? Option.some(cause.status) : Option.none();
|
|
51
|
+
const fromJsonapiError = (cause) => Option.flatMap(statusOf(cause), (status) => Predicate.hasProperty(cause, "errors") && Array.isArray(cause.errors) ? Option.some(routed(status, cause.errors)) : Option.none());
|
|
52
|
+
const fromErrorResponse = (cause) => Option.map(statusOf(cause), (status) => {
|
|
53
|
+
const errors = Predicate.hasProperty(cause, "document") && Option.isOption(cause.document) ? Option.flatMap(cause.document, (document) => Predicate.hasProperty(document, "errors") && Array.isArray(document.errors) && Arr.isReadonlyArrayNonEmpty(document.errors) ? Option.some(document.errors) : Option.none()) : Option.none();
|
|
54
|
+
return Option.match(errors, {
|
|
55
|
+
onSome: (routedErrors) => routed(status, routedErrors),
|
|
56
|
+
onNone: () => message(status, Predicate.hasProperty(cause, "message") && Predicate.isString(cause.message) ? cause.message : DEFAULT_MESSAGE)
|
|
57
|
+
});
|
|
58
|
+
});
|
|
58
59
|
/**
|
|
59
60
|
* The default classifier:
|
|
60
61
|
*
|
|
@@ -70,13 +71,10 @@ const fromErrorResponse = (cause) => {
|
|
|
70
71
|
*/
|
|
71
72
|
const jsonapiFailure = (cause) => {
|
|
72
73
|
if (!Predicate.isObjectOrArray(cause)) return Option.none();
|
|
73
|
-
|
|
74
|
-
if (
|
|
75
|
-
|
|
76
|
-
if (Predicate.isError(cause) && isStatus(tagged.status)) return Option.some(message(tagged.status, cause.message));
|
|
77
|
-
return Option.none();
|
|
74
|
+
if (Predicate.isTagged(cause, "JsonapiError")) return fromJsonapiError(cause);
|
|
75
|
+
if (Predicate.isTagged(cause, "ErrorResponse")) return fromErrorResponse(cause);
|
|
76
|
+
return Predicate.isError(cause) ? Option.map(statusOf(cause), (status) => message(status, cause.message)) : Option.none();
|
|
78
77
|
};
|
|
79
|
-
//#endregion
|
|
80
78
|
export { CommandFailure_exports, DEFAULT_MESSAGE, detailOf, jsonapiFailure, message, routed };
|
|
81
79
|
|
|
82
80
|
//# sourceMappingURL=CommandFailure.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CommandFailure.js","names":[],"sources":["../../src/kit/CommandFailure.ts"],"sourcesContent":["/**\n * Classifying what a form action's command failed with.\n *\n * A command (an API client call, an Effect program) fails with whatever its\n * transport raises. The form layer only needs to know two things about it:\n * which JSON:API error objects it carried (so each can be routed onto a\n * field by its `source.pointer`), or, failing that, a status and a single\n * message for the whole form. {@link CommandFailure} is that view, and\n * {@link jsonapiFailure} is the default classifier.\n *\n * The error-object shape is `@thomasfosterau/effect-jsonapi`'s\n * `Document.ErrorObject` — an optional peer imported for its type only, so\n * nothing here depends on it at runtime and no application type leaks in.\n * Causes are recognised structurally by their `_tag`, so an application's\n * own `JsonapiError` with the same shape is recognised too.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/kit/CommandFailure\n */\n\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport type { Document } from \"@thomasfosterau/effect-jsonapi\";\n\n/** One JSON:API error object: `@thomasfosterau/effect-jsonapi`'s `Document.ErrorObject`. */\nexport type ErrorObject = typeof Document.ErrorObject.Type;\n\n/** A failure carrying JSON:API error objects, each routed to a field (or the root) by its pointer. */\nexport interface RoutedFailure {\n readonly _tag: \"Routed\";\n readonly status: number;\n readonly errors: ReadonlyArray<ErrorObject>;\n}\n\n/** A failure with no error objects to route: one whole-form message. */\nexport interface MessageFailure {\n readonly _tag: \"Message\";\n readonly status: number;\n readonly message: string;\n}\n\n/**\n * What a form action needs to know about a recognised command failure. An\n * unrecognised failure is not a `CommandFailure` at all: the classifier\n * answers `None` and the action treats it as unexpected.\n */\nexport type CommandFailure = RoutedFailure | MessageFailure;\n\n/** Construct a {@link RoutedFailure}. */\nexport const routed = (status: number, errors: ReadonlyArray<ErrorObject>): CommandFailure => ({\n _tag: \"Routed\",\n status,\n errors,\n});\n\n/** Construct a {@link MessageFailure}. */\nexport const message = (status: number,
|
|
1
|
+
{"version":3,"file":"CommandFailure.js","names":[],"sources":["../../src/kit/CommandFailure.ts"],"sourcesContent":["/**\n * Classifying what a form action's command failed with.\n *\n * A command (an API client call, an Effect program) fails with whatever its\n * transport raises. The form layer only needs to know two things about it:\n * which JSON:API error objects it carried (so each can be routed onto a\n * field by its `source.pointer`), or, failing that, a status and a single\n * message for the whole form. {@link CommandFailure} is that view, and\n * {@link jsonapiFailure} is the default classifier.\n *\n * The error-object shape is `@thomasfosterau/effect-jsonapi`'s\n * `Document.ErrorObject` — an optional peer imported for its type only, so\n * nothing here depends on it at runtime and no application type leaks in.\n * Causes are recognised structurally by their `_tag`, so an application's\n * own `JsonapiError` with the same shape is recognised too.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/kit/CommandFailure\n */\n\nimport * as Arr from \"effect/Array\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport type { Document } from \"@thomasfosterau/effect-jsonapi\";\n\n/** One JSON:API error object: `@thomasfosterau/effect-jsonapi`'s `Document.ErrorObject`. */\nexport type ErrorObject = typeof Document.ErrorObject.Type;\n\n/** A failure carrying JSON:API error objects, each routed to a field (or the root) by its pointer. */\nexport interface RoutedFailure {\n readonly _tag: \"Routed\";\n readonly status: number;\n readonly errors: ReadonlyArray<ErrorObject>;\n}\n\n/** A failure with no error objects to route: one whole-form message. */\nexport interface MessageFailure {\n readonly _tag: \"Message\";\n readonly status: number;\n readonly message: string;\n}\n\n/**\n * What a form action needs to know about a recognised command failure. An\n * unrecognised failure is not a `CommandFailure` at all: the classifier\n * answers `None` and the action treats it as unexpected.\n */\nexport type CommandFailure = RoutedFailure | MessageFailure;\n\n/** Construct a {@link RoutedFailure}. */\nexport const routed = (status: number, errors: ReadonlyArray<ErrorObject>): CommandFailure => ({\n _tag: \"Routed\",\n status,\n errors,\n});\n\n/** Construct a {@link MessageFailure}. */\nexport const message = (status: number, text: string): CommandFailure => ({\n _tag: \"Message\",\n status,\n message: text,\n});\n\n/** A classifier: `Some` for a failure the form can show, `None` for an unexpected one. */\nexport type Classify = (cause: unknown) => Option.Option<CommandFailure>;\n\n/** The fallback message for an error object with neither `detail` nor `title`. */\nexport const DEFAULT_MESSAGE = \"Request could not be completed\";\n\n/** An error object's human message: its `detail`, else its `title`, else `fallback`. */\nexport const detailOf = (error: ErrorObject | undefined, fallback = DEFAULT_MESSAGE): string =>\n error?.detail ?? error?.title ?? fallback;\n\nconst isStatus = (u: unknown): u is number => Predicate.isNumber(u) && Number.isInteger(u);\n\n/** A cause recognised by its `_tag` as effect-jsonapi's (or an application's) `JsonapiError`. */\ninterface JsonapiErrorLike {\n readonly _tag: \"JsonapiError\";\n}\n\n/** A cause recognised by its `_tag` as effect-jsonapi's client-side `ErrorResponse`. */\ninterface ErrorResponseLike {\n readonly _tag: \"ErrorResponse\";\n}\n\n/** The cause's `status`, when it carries an integer one. */\nconst statusOf = (cause: JsonapiErrorLike | ErrorResponseLike | Error): Option.Option<number> =>\n Predicate.hasProperty(cause, \"status\") && isStatus(cause.status)\n ? Option.some(cause.status)\n : Option.none();\n\n// `ServerErrors.JsonapiError` (effect-jsonapi) and the applications' own\n// `JsonapiError`: `{ _tag: \"JsonapiError\", status, errors }`.\nconst fromJsonapiError = (cause: JsonapiErrorLike): Option.Option<CommandFailure> =>\n Option.flatMap(statusOf(cause), (status) =>\n Predicate.hasProperty(cause, \"errors\") && Array.isArray(cause.errors)\n ? // SAFETY: a `JsonapiError`-tagged cause carries JSON:API error objects in\n // `errors` by that tag's contract (effect-jsonapi's `ServerErrors.JsonapiError`\n // and the applications' own); causes are recognised structurally, not decoded.\n Option.some(routed(status, cause.errors as ReadonlyArray<ErrorObject>))\n : Option.none(),\n );\n\n// `Client.ErrorResponse` (effect-jsonapi): `{ _tag: \"ErrorResponse\", status,\n// message, document: Option<ErrorDocument> }`. A decoded document routes its\n// error objects; a response with none is its message alone.\nconst fromErrorResponse = (cause: ErrorResponseLike): Option.Option<CommandFailure> =>\n Option.map(statusOf(cause), (status) => {\n const errors =\n Predicate.hasProperty(cause, \"document\") && Option.isOption(cause.document)\n ? Option.flatMap(cause.document, (document) =>\n Predicate.hasProperty(document, \"errors\") &&\n Array.isArray(document.errors) &&\n Arr.isReadonlyArrayNonEmpty(document.errors)\n ? // SAFETY: an `ErrorResponse`'s `document` is effect-jsonapi's decoded\n // `ErrorDocument`, whose `errors` are JSON:API error objects.\n Option.some(document.errors as ReadonlyArray<ErrorObject>)\n : Option.none(),\n )\n : Option.none<ReadonlyArray<ErrorObject>>();\n return Option.match(errors, {\n onSome: (routedErrors) => routed(status, routedErrors),\n onNone: () =>\n message(\n status,\n Predicate.hasProperty(cause, \"message\") && Predicate.isString(cause.message)\n ? cause.message\n : DEFAULT_MESSAGE,\n ),\n });\n });\n\n/**\n * The default classifier:\n *\n * - a `JsonapiError`-tagged cause (`{ status, errors }`) → its error objects,\n * at its own status;\n * - an `ErrorResponse`-tagged cause (effect-jsonapi's client-side decoded\n * error) → its document's error objects, or its message when the response\n * carried no document;\n * - an `Error` carrying a numeric `status` (a transport's status error, e.g.\n * a 413 oversize upload the transport did not map to a document) → its\n * message, at its own status;\n * - anything else → `None` (unexpected).\n */\nexport const jsonapiFailure: Classify = (cause) => {\n if (!Predicate.isObjectOrArray(cause)) return Option.none();\n if (Predicate.isTagged(cause, \"JsonapiError\")) return fromJsonapiError(cause);\n if (Predicate.isTagged(cause, \"ErrorResponse\")) return fromErrorResponse(cause);\n return Predicate.isError(cause)\n ? Option.map(statusOf(cause), (status) => message(status, cause.message))\n : Option.none();\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAa,UAAU,QAAgB,YAAwD;CAC7F,MAAM;CACN;CACA;AACF;;AAGA,MAAa,WAAW,QAAgB,UAAkC;CACxE,MAAM;CACN;CACA,SAAS;AACX;;AAMA,MAAa,kBAAkB;;AAG/B,MAAa,YAAY,OAAgC,WAAW,oBAClE,OAAO,UAAU,OAAO,SAAS;AAEnC,MAAM,YAAY,MAA4B,UAAU,SAAS,CAAC,KAAK,OAAO,UAAU,CAAC;;AAazF,MAAM,YAAY,UAChB,UAAU,YAAY,OAAO,QAAQ,KAAK,SAAS,MAAM,MAAM,IAC3D,OAAO,KAAK,MAAM,MAAM,IACxB,OAAO,KAAK;AAIlB,MAAM,oBAAoB,UACxB,OAAO,QAAQ,SAAS,KAAK,IAAI,WAC/B,UAAU,YAAY,OAAO,QAAQ,KAAK,MAAM,QAAQ,MAAM,MAAM,IAIhE,OAAO,KAAK,OAAO,QAAQ,MAAM,MAAoC,CAAC,IACtE,OAAO,KAAK,CAClB;AAKF,MAAM,qBAAqB,UACzB,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW;CACtC,MAAM,SACJ,UAAU,YAAY,OAAO,UAAU,KAAK,OAAO,SAAS,MAAM,QAAQ,IACtE,OAAO,QAAQ,MAAM,WAAW,aAC9B,UAAU,YAAY,UAAU,QAAQ,KACxC,MAAM,QAAQ,SAAS,MAAM,KAC7B,IAAI,wBAAwB,SAAS,MAAM,IAGvC,OAAO,KAAK,SAAS,MAAoC,IACzD,OAAO,KAAK,CAClB,IACA,OAAO,KAAiC;CAC9C,OAAO,OAAO,MAAM,QAAQ;EAC1B,SAAS,iBAAiB,OAAO,QAAQ,YAAY;EACrD,cACE,QACE,QACA,UAAU,YAAY,OAAO,SAAS,KAAK,UAAU,SAAS,MAAM,OAAO,IACvE,MAAM,UACN,eACN;CACJ,CAAC;AACH,CAAC;;;;;;;;;;;;;;AAeH,MAAa,kBAA4B,UAAU;CACjD,IAAI,CAAC,UAAU,gBAAgB,KAAK,GAAG,OAAO,OAAO,KAAK;CAC1D,IAAI,UAAU,SAAS,OAAO,cAAc,GAAG,OAAO,iBAAiB,KAAK;CAC5E,IAAI,UAAU,SAAS,OAAO,eAAe,GAAG,OAAO,kBAAkB,KAAK;CAC9E,OAAO,UAAU,QAAQ,KAAK,IAC1B,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW,QAAQ,QAAQ,MAAM,OAAO,CAAC,IACtE,OAAO,KAAK;AAClB"}
|
package/dist/kit/Enhance.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { FormStore } from "../FormStore.svelte.js";
|
|
2
2
|
import { Attachment } from "svelte/attachments";
|
|
3
|
-
//#region src/kit/Enhance.d.ts
|
|
4
3
|
/** The spreadable `<form>` props: the POST method plus the enhance attachment under its symbol key. */
|
|
5
4
|
export interface EnhancedFormProps {
|
|
6
5
|
readonly method: "post";
|
|
@@ -26,5 +25,4 @@ export interface EnhancedFormProps {
|
|
|
26
25
|
* ```
|
|
27
26
|
*/
|
|
28
27
|
export declare function enhanceForm(form: FormStore<any, any, any>): EnhancedFormProps;
|
|
29
|
-
//#endregion
|
|
30
28
|
//# sourceMappingURL=Enhance.d.ts.map
|
package/dist/kit/Enhance.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { applyActionResult } from "../SvelteKit.js";
|
|
2
2
|
import { createAttachmentKey } from "svelte/attachments";
|
|
3
3
|
import { enhance } from "$app/forms";
|
|
4
|
-
|
|
4
|
+
// src/kit/Enhance.ts
|
|
5
5
|
/**
|
|
6
6
|
* SvelteKit `$app/forms` glue for the form store. {@link enhanceForm}
|
|
7
7
|
* returns spreadable `<form>` props — `<form {...enhanceForm(form)}>` — that
|
|
@@ -51,7 +51,6 @@ function enhanceForm(form) {
|
|
|
51
51
|
}
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
|
-
//#endregion
|
|
55
54
|
export { enhanceForm };
|
|
56
55
|
|
|
57
56
|
//# sourceMappingURL=Enhance.js.map
|
package/dist/kit/FormAction.d.ts
CHANGED
|
@@ -3,7 +3,6 @@ import { Form, Result, State } from "@thomasfosterau/effect-forms";
|
|
|
3
3
|
import * as Schema from "effect/Schema";
|
|
4
4
|
import * as Effect from "effect/Effect";
|
|
5
5
|
import { RequestEvent } from "@sveltejs/kit";
|
|
6
|
-
//#region src/kit/FormAction.d.ts
|
|
7
6
|
type FormState<A, Message = unknown> = State.FormState<A, Message>;
|
|
8
7
|
type FormActionResult<A, Message = unknown> = Result.FormActionResult<A, Message>;
|
|
9
8
|
type FormActionData<A = unknown, Message = unknown> = Result.FormActionData<A, Message>;
|
|
@@ -127,6 +126,5 @@ export type ActionCommand<I, O> = (input: I, event: RequestEvent) => Promise<O>
|
|
|
127
126
|
* ```
|
|
128
127
|
*/
|
|
129
128
|
export declare function formAction<S extends Schema.Top, O, Message = unknown>(form: Form.Form<S, Message>, run: ActionCommand<S["Type"], O>, locationFor: (output: O, input: S["Type"]) => string, options?: FormActionOptions<S["Type"], O>): (event: RequestEvent) => Promise<FormActionData<S["Type"], unknown> | import("@sveltejs/kit").ActionFailure<FormActionData<S["Type"], unknown>>>;
|
|
130
|
-
//#endregion
|
|
131
129
|
export { Command$1 as Command };
|
|
132
130
|
//# sourceMappingURL=FormAction.d.ts.map
|
package/dist/kit/FormAction.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { DEFAULT_MESSAGE, detailOf, jsonapiFailure } from "./CommandFailure.js";
|
|
2
2
|
import { fieldFromPointer } from "./Pointer.js";
|
|
3
3
|
import { Result, State } from "@thomasfosterau/effect-forms";
|
|
4
|
-
import * as
|
|
5
|
-
import * as Option from "effect/Option";
|
|
4
|
+
import * as Match from "effect/Match";
|
|
6
5
|
import * as Predicate from "effect/Predicate";
|
|
6
|
+
import * as Option from "effect/Option";
|
|
7
|
+
import * as Effect from "effect/Effect";
|
|
7
8
|
import { fail, redirect } from "@sveltejs/kit";
|
|
8
9
|
import * as Cause from "effect/Cause";
|
|
9
10
|
import * as Exit from "effect/Exit";
|
|
10
|
-
|
|
11
|
+
// src/kit/FormAction.ts
|
|
11
12
|
/**
|
|
12
13
|
* Derive a SvelteKit page form action from an `@thomasfosterau/effect-forms`
|
|
13
14
|
* form plus the command it submits to.
|
|
@@ -34,16 +35,12 @@ const toEffect = (thunk) => Effect.suspend(() => {
|
|
|
34
35
|
catch: (cause) => cause
|
|
35
36
|
});
|
|
36
37
|
});
|
|
37
|
-
const isConflict = (cause) => Predicate.isObjectOrArray(cause) && cause.status === 409 && (cause
|
|
38
|
-
const submittedId = (input) =>
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const id = submittedId(input);
|
|
44
|
-
if (id === void 0 || !isConflict(cause)) return Effect.fail(cause);
|
|
45
|
-
return toEffect(() => fetchExisting(id)).pipe(Effect.mapError(() => cause));
|
|
46
|
-
}));
|
|
38
|
+
const isConflict = (cause) => Predicate.isObjectOrArray(cause) && Predicate.hasProperty(cause, "status") && cause.status === 409 && (Predicate.isTagged(cause, "JsonapiError") || Predicate.isTagged(cause, "ErrorResponse"));
|
|
39
|
+
const submittedId = (input) => Predicate.isObjectOrArray(input) && Predicate.hasProperty(input, "id") && Predicate.isString(input.id) && input.id !== "" ? Option.some(input.id) : Option.none();
|
|
40
|
+
const retryOwnConflict = (create, fetchExisting, input) => toEffect(() => create(input)).pipe(Effect.catch((cause) => Option.match(isConflict(cause) ? submittedId(input) : Option.none(), {
|
|
41
|
+
onNone: () => Effect.fail(cause),
|
|
42
|
+
onSome: (id) => toEffect(() => fetchExisting(id)).pipe(Effect.mapError(() => cause))
|
|
43
|
+
})));
|
|
47
44
|
/**
|
|
48
45
|
* Wrap a client-id create command so a 409 conflict on the caller's OWN
|
|
49
46
|
* submitted `id` resolves as success instead of a form error — the
|
|
@@ -75,7 +72,7 @@ const fieldPath = (error) => Option.toArray(fieldFromPointer(error.source !== vo
|
|
|
75
72
|
* at the empty path, which the nested error tree exposes as `_errors` — the
|
|
76
73
|
* form-level message surface (`form.errors._errors`).
|
|
77
74
|
*/
|
|
78
|
-
const routeFailure = (state, failure) => failure
|
|
75
|
+
const routeFailure = (state, failure) => Predicate.isTagged(failure, "Routed") ? failure.errors.reduce((acc, error) => State.withError(acc, fieldPath(error), detailOf(error)), state) : State.withError(state, [], failure.message);
|
|
79
76
|
/**
|
|
80
77
|
* Validate `request` against `form`, then:
|
|
81
78
|
*
|
|
@@ -97,18 +94,29 @@ const routeFailure = (state, failure) => failure._tag === "Routed" ? failure.err
|
|
|
97
94
|
*/
|
|
98
95
|
async function runFormAction(form, request, run, locationFor, options = {}) {
|
|
99
96
|
const redact = options.redact ?? ((state) => state);
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
97
|
+
const classify = options.classify ?? jsonapiFailure;
|
|
98
|
+
const validate = form.validate(request);
|
|
99
|
+
const program = Effect.flatMap(validate, (state) => {
|
|
100
|
+
if (!state.valid) return Effect.succeed(Result.failure(redact(state), 400));
|
|
101
|
+
const idempotent = options.idempotent;
|
|
102
|
+
const command = idempotent?.clientId === true ? retryOwnConflict(run, idempotent.fetchExisting, state.data) : toEffect(() => run(state.data));
|
|
103
|
+
return Effect.matchCauseEffect(command, {
|
|
104
|
+
onSuccess: (output) => Effect.sync(() => Result.redirect(locationFor(output, state.data), 303)),
|
|
105
|
+
onFailure: (commandCause) => Effect.suspend(() => {
|
|
106
|
+
const cause = Cause.squash(commandCause);
|
|
107
|
+
return Option.match(classify(cause), {
|
|
108
|
+
onSome: (failure) => Effect.sync(() => Result.failure(redact(routeFailure(state, failure)), failure.status)),
|
|
109
|
+
onNone: () => options.unrecognised === "throw" ? Effect.fail(cause) : Effect.succeed(Result.errorResult(Predicate.isError(cause) ? cause.message : DEFAULT_MESSAGE, 500))
|
|
110
|
+
});
|
|
111
|
+
})
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
const exit = await Effect.runPromiseExit(program);
|
|
115
|
+
if (Exit.isSuccess(exit)) return exit.value;
|
|
116
|
+
throw Cause.squash(exit.cause);
|
|
111
117
|
}
|
|
118
|
+
/** Pin an action's return to {@link FormActionData}, so every branch types alike. */
|
|
119
|
+
const actionData = (data) => data;
|
|
112
120
|
/**
|
|
113
121
|
* Derive a SvelteKit page form **action** from `form` plus its command. The
|
|
114
122
|
* handler validates the submission, runs the command on success, and maps
|
|
@@ -149,16 +157,14 @@ async function runFormAction(form, request, run, locationFor, options = {}) {
|
|
|
149
157
|
function formAction(form, run, locationFor, options) {
|
|
150
158
|
return async (event) => {
|
|
151
159
|
const result = await runFormAction(form, event.request, (input) => run(input, event), locationFor, options);
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
}
|
|
160
|
+
return Match.valueTags(result, {
|
|
161
|
+
Redirect: (redirectResult) => redirect(redirectResult.status, redirectResult.location),
|
|
162
|
+
Failure: (failure) => fail(failure.status, actionData({ form: failure.state })),
|
|
163
|
+
Error: (error) => fail(error.status, actionData({ message: error.message })),
|
|
164
|
+
Success: (success) => actionData({ form: success.state })
|
|
165
|
+
});
|
|
159
166
|
};
|
|
160
167
|
}
|
|
161
|
-
//#endregion
|
|
162
168
|
export { formAction, idempotentCreate, runFormAction };
|
|
163
169
|
|
|
164
170
|
//# sourceMappingURL=FormAction.js.map
|