@eskais/app-sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +74 -2
- package/dist/action/action.d.ts +133 -0
- package/dist/action/action.js +224 -0
- package/dist/action/bulk.d.ts +24 -0
- package/dist/action/bulk.js +24 -0
- package/dist/cli/cli.d.ts +2 -0
- package/dist/cli/cli.js +51 -0
- package/dist/cli/routes.d.ts +17 -0
- package/dist/cli/routes.js +36 -0
- package/dist/core/assume.d.ts +1 -0
- package/dist/core/assume.js +8 -0
- package/dist/core/constants.d.ts +359 -0
- package/dist/core/constants.js +187 -0
- package/dist/core/contracts.d.ts +107 -0
- package/dist/core/contracts.js +3 -0
- package/dist/core/data-labels.d.ts +210 -0
- package/dist/core/data-labels.js +385 -0
- package/dist/core/errors.d.ts +52 -0
- package/dist/core/errors.js +209 -0
- package/dist/core/guards.d.ts +9 -0
- package/dist/core/guards.js +14 -0
- package/dist/core/refusal.d.ts +30 -0
- package/dist/core/refusal.js +53 -0
- package/dist/dialogs/dialogs.d.ts +75 -0
- package/dist/dialogs/dialogs.js +66 -0
- package/dist/draft/draft.d.ts +36 -0
- package/dist/draft/draft.js +87 -0
- package/dist/errors/adapters.d.ts +21 -0
- package/dist/errors/adapters.js +81 -0
- package/dist/errors/define-errors.d.ts +88 -0
- package/dist/errors/define-errors.js +168 -0
- package/dist/errors/idempotency.d.ts +2 -0
- package/dist/errors/idempotency.js +13 -0
- package/dist/export/csv.d.ts +25 -0
- package/dist/export/csv.js +59 -0
- package/dist/i18n/adapters.d.ts +53 -0
- package/dist/i18n/adapters.js +56 -0
- package/dist/i18n/format.d.ts +10 -0
- package/dist/i18n/format.js +273 -0
- package/dist/i18n/labels.d.ts +10 -0
- package/dist/i18n/labels.js +227 -0
- package/dist/i18n/locale.d.ts +73 -0
- package/dist/i18n/locale.js +74 -0
- package/dist/i18n/messages.d.ts +93 -0
- package/dist/i18n/messages.js +16 -0
- package/dist/import/csv-parse.d.ts +11 -0
- package/dist/import/csv-parse.js +70 -0
- package/dist/import/import.d.ts +104 -0
- package/dist/import/import.js +266 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +45 -0
- package/dist/navigation/nav.d.ts +128 -0
- package/dist/navigation/nav.js +301 -0
- package/dist/navigation/router.d.ts +81 -0
- package/dist/navigation/router.js +249 -0
- package/dist/navigation/shortcuts.d.ts +37 -0
- package/dist/navigation/shortcuts.js +93 -0
- package/dist/next/index.d.ts +3 -0
- package/dist/next/index.js +3 -0
- package/dist/next/screen-hydration.d.ts +12 -0
- package/dist/next/screen-hydration.js +26 -0
- package/dist/next/screen.d.ts +25 -0
- package/dist/next/screen.js +44 -0
- package/dist/next/server/handler.d.ts +39 -0
- package/dist/next/server/handler.js +190 -0
- package/dist/next/server/index.d.ts +6 -0
- package/dist/next/server/index.js +6 -0
- package/dist/next/server/page.d.ts +63 -0
- package/dist/next/server/page.js +110 -0
- package/dist/next/server/prefetch.d.ts +29 -0
- package/dist/next/server/prefetch.js +97 -0
- package/dist/next/server/session.d.ts +25 -0
- package/dist/next/server/session.js +23 -0
- package/dist/next/use-next-router.d.ts +21 -0
- package/dist/next/use-next-router.js +104 -0
- package/dist/permissions/permissions.d.ts +134 -0
- package/dist/permissions/permissions.js +121 -0
- package/dist/react/data-layer.d.ts +68 -0
- package/dist/react/data-layer.js +76 -0
- package/dist/react/hooks/use-action-dialog.d.ts +25 -0
- package/dist/react/hooks/use-action-dialog.js +31 -0
- package/dist/react/hooks/use-action.d.ts +37 -0
- package/dist/react/hooks/use-action.js +125 -0
- package/dist/react/hooks/use-better-auth.d.ts +12 -0
- package/dist/react/hooks/use-better-auth.js +11 -0
- package/dist/react/hooks/use-bulk-action.d.ts +20 -0
- package/dist/react/hooks/use-bulk-action.js +24 -0
- package/dist/react/hooks/use-dialogs.d.ts +14 -0
- package/dist/react/hooks/use-dialogs.js +20 -0
- package/dist/react/hooks/use-draft.d.ts +5 -0
- package/dist/react/hooks/use-draft.js +17 -0
- package/dist/react/hooks/use-nav.d.ts +17 -0
- package/dist/react/hooks/use-nav.js +35 -0
- package/dist/react/hooks/use-new-rows.d.ts +22 -0
- package/dist/react/hooks/use-new-rows.js +24 -0
- package/dist/react/hooks/use-permissions.d.ts +13 -0
- package/dist/react/hooks/use-permissions.js +19 -0
- package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
- package/dist/react/hooks/use-reauthenticate.js +11 -0
- package/dist/react/hooks/use-resource.d.ts +92 -0
- package/dist/react/hooks/use-resource.js +255 -0
- package/dist/react/hooks/use-view.d.ts +6 -0
- package/dist/react/hooks/use-view.js +24 -0
- package/dist/react/index.d.ts +15 -0
- package/dist/react/index.js +15 -0
- package/dist/react/keys.d.ts +60 -0
- package/dist/react/keys.js +71 -0
- package/dist/react/new-rows.d.ts +22 -0
- package/dist/react/new-rows.js +72 -0
- package/dist/refresh/new-rows.d.ts +13 -0
- package/dist/refresh/new-rows.js +18 -0
- package/dist/resource/form-schema.d.ts +11 -0
- package/dist/resource/form-schema.js +51 -0
- package/dist/resource/relations.d.ts +99 -0
- package/dist/resource/relations.js +194 -0
- package/dist/resource/resource-relations.d.ts +47 -0
- package/dist/resource/resource-relations.js +154 -0
- package/dist/resource/resource-schema.d.ts +9 -0
- package/dist/resource/resource-schema.js +73 -0
- package/dist/resource/resource-texts.d.ts +18 -0
- package/dist/resource/resource-texts.js +13 -0
- package/dist/resource/resource-types.d.ts +420 -0
- package/dist/resource/resource-types.js +1 -0
- package/dist/resource/resource-words.d.ts +25 -0
- package/dist/resource/resource-words.js +221 -0
- package/dist/resource/resource.d.ts +15 -0
- package/dist/resource/resource.js +280 -0
- package/dist/resource/schema.d.ts +57 -0
- package/dist/resource/schema.js +115 -0
- package/dist/services/from-page-source.d.ts +15 -0
- package/dist/services/from-page-source.js +27 -0
- package/dist/services/memory-query.d.ts +8 -0
- package/dist/services/memory-query.js +165 -0
- package/dist/services/memory-service.d.ts +33 -0
- package/dist/services/memory-service.js +291 -0
- package/dist/services/read-only-service.d.ts +18 -0
- package/dist/services/read-only-service.js +25 -0
- package/dist/services/rest-service.d.ts +65 -0
- package/dist/services/rest-service.js +222 -0
- package/dist/services/rng.d.ts +9 -0
- package/dist/services/rng.js +22 -0
- package/dist/services/spring-service.d.ts +58 -0
- package/dist/services/spring-service.js +132 -0
- package/dist/session/better-auth.d.ts +83 -0
- package/dist/session/better-auth.js +86 -0
- package/dist/session/session.d.ts +45 -0
- package/dist/session/session.js +36 -0
- package/dist/view/preferences.d.ts +35 -0
- package/dist/view/preferences.js +93 -0
- package/dist/view/view-types.d.ts +124 -0
- package/dist/view/view-types.js +1 -0
- package/dist/view/view-url.d.ts +7 -0
- package/dist/view/view-url.js +54 -0
- package/dist/view/view.d.ts +4 -0
- package/dist/view/view.js +392 -0
- package/locales/en.json +193 -0
- package/locales/es.json +193 -0
- package/package.json +88 -4
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { CursorDirection, SortDirection } from "../core/constants.js";
|
|
2
|
+
import { isPagePosition } from "../core/contracts.js";
|
|
3
|
+
import { isBoolean, isNumber, isRecord, isString } from "../core/guards.js";
|
|
4
|
+
export function valueAt(row, path) {
|
|
5
|
+
let current = row;
|
|
6
|
+
for (const segment of path.split(".")) {
|
|
7
|
+
if (!isRecord(current))
|
|
8
|
+
return undefined;
|
|
9
|
+
current = current[segment];
|
|
10
|
+
}
|
|
11
|
+
return current;
|
|
12
|
+
}
|
|
13
|
+
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
|
14
|
+
function comparable(value) {
|
|
15
|
+
if (isNumber(value))
|
|
16
|
+
return value;
|
|
17
|
+
if (isBoolean(value))
|
|
18
|
+
return value ? 1 : 0;
|
|
19
|
+
if (isString(value))
|
|
20
|
+
return value;
|
|
21
|
+
if (value instanceof Date)
|
|
22
|
+
return value.getTime();
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
function compare(left, right) {
|
|
26
|
+
const a = comparable(left);
|
|
27
|
+
const b = comparable(right);
|
|
28
|
+
if (a === undefined)
|
|
29
|
+
return b === undefined ? 0 : 1;
|
|
30
|
+
if (b === undefined)
|
|
31
|
+
return -1;
|
|
32
|
+
if (isNumber(a) && isNumber(b))
|
|
33
|
+
return a - b;
|
|
34
|
+
return collator.compare(String(a), String(b));
|
|
35
|
+
}
|
|
36
|
+
export function sortRows(rows, sort) {
|
|
37
|
+
if (sort.length === 0)
|
|
38
|
+
return [...rows];
|
|
39
|
+
return rows.toSorted((left, right) => {
|
|
40
|
+
for (const spec of sort) {
|
|
41
|
+
const order = compare(valueAt(left, spec.field), valueAt(right, spec.field));
|
|
42
|
+
if (order !== 0)
|
|
43
|
+
return spec.direction === SortDirection.desc ? -order : order;
|
|
44
|
+
}
|
|
45
|
+
return 0;
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
export function isActive(value) {
|
|
49
|
+
if (value === undefined || value === null)
|
|
50
|
+
return false;
|
|
51
|
+
if (isString(value))
|
|
52
|
+
return value.trim() !== "";
|
|
53
|
+
if (Array.isArray(value))
|
|
54
|
+
return value.length > 0;
|
|
55
|
+
if (isRecord(value) && ("from" in value || "to" in value))
|
|
56
|
+
return isActive(value.from) || isActive(value.to);
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
function timeOf(value) {
|
|
60
|
+
if (value instanceof Date)
|
|
61
|
+
return value.getTime();
|
|
62
|
+
if (isString(value) || isNumber(value)) {
|
|
63
|
+
const time = new Date(value).getTime();
|
|
64
|
+
return Number.isNaN(time) ? undefined : time;
|
|
65
|
+
}
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
function dayEnd(value) {
|
|
69
|
+
const time = timeOf(value);
|
|
70
|
+
if (time === undefined)
|
|
71
|
+
return undefined;
|
|
72
|
+
return isString(value) && /^\d{4}-\d{2}-\d{2}$/u.test(value) ? time + 86_399_999 : time;
|
|
73
|
+
}
|
|
74
|
+
const loose = (value) => (isString(value) || isNumber(value) || isBoolean(value) ? String(value) : value);
|
|
75
|
+
export function matchesValue(actual, expected) {
|
|
76
|
+
if (!isActive(expected))
|
|
77
|
+
return true;
|
|
78
|
+
if (Array.isArray(expected))
|
|
79
|
+
return expected.some((entry) => matchesValue(actual, entry));
|
|
80
|
+
if (Array.isArray(actual))
|
|
81
|
+
return actual.some((entry) => matchesValue(entry, expected));
|
|
82
|
+
if (isRecord(expected) && ("from" in expected || "to" in expected)) {
|
|
83
|
+
const time = timeOf(actual);
|
|
84
|
+
if (time === undefined)
|
|
85
|
+
return false;
|
|
86
|
+
const from = timeOf(expected.from);
|
|
87
|
+
const to = dayEnd(expected.to);
|
|
88
|
+
return (from === undefined || time >= from) && (to === undefined || time <= to);
|
|
89
|
+
}
|
|
90
|
+
if (isRecord(expected) && isString(expected.op)) {
|
|
91
|
+
if (!isNumber(actual))
|
|
92
|
+
return false;
|
|
93
|
+
if (expected.op === "between")
|
|
94
|
+
return isNumber(expected.min) && isNumber(expected.max) ? actual >= expected.min && actual <= expected.max : true;
|
|
95
|
+
return isNumber(expected.value) ? compareNumber(expected.op, actual, expected.value) : true;
|
|
96
|
+
}
|
|
97
|
+
return loose(actual) === loose(expected);
|
|
98
|
+
}
|
|
99
|
+
function compareNumber(op, actual, value) {
|
|
100
|
+
switch (op) {
|
|
101
|
+
case "neq":
|
|
102
|
+
return actual !== value;
|
|
103
|
+
case "lt":
|
|
104
|
+
return actual < value;
|
|
105
|
+
case "lte":
|
|
106
|
+
return actual <= value;
|
|
107
|
+
case "gt":
|
|
108
|
+
return actual > value;
|
|
109
|
+
case "gte":
|
|
110
|
+
return actual >= value;
|
|
111
|
+
default:
|
|
112
|
+
return actual === value;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
export function matchesFilter(row, filter) {
|
|
116
|
+
if (!isRecord(filter))
|
|
117
|
+
return true;
|
|
118
|
+
return Object.entries(filter).every(([key, expected]) => key.startsWith("$") || matchesValue(valueAt(row, key), expected));
|
|
119
|
+
}
|
|
120
|
+
function textOf(value, depth = 0) {
|
|
121
|
+
if (isString(value))
|
|
122
|
+
return value;
|
|
123
|
+
if (isNumber(value))
|
|
124
|
+
return String(value);
|
|
125
|
+
if (depth > 1)
|
|
126
|
+
return "";
|
|
127
|
+
if (Array.isArray(value))
|
|
128
|
+
return value.map((entry) => textOf(entry, depth + 1)).join(" ");
|
|
129
|
+
if (isRecord(value))
|
|
130
|
+
return Object.values(value)
|
|
131
|
+
.map((entry) => textOf(entry, depth + 1))
|
|
132
|
+
.join(" ");
|
|
133
|
+
return "";
|
|
134
|
+
}
|
|
135
|
+
export function matchesSearch(row, search) {
|
|
136
|
+
if (search === undefined || search.trim() === "")
|
|
137
|
+
return true;
|
|
138
|
+
const haystack = textOf(row).toLocaleLowerCase();
|
|
139
|
+
return search
|
|
140
|
+
.toLocaleLowerCase()
|
|
141
|
+
.split(/\s+/u)
|
|
142
|
+
.filter(Boolean)
|
|
143
|
+
.every((word) => haystack.includes(word));
|
|
144
|
+
}
|
|
145
|
+
export function applyQuery(rows, query) {
|
|
146
|
+
const matched = sortRows(rows.filter((row) => matchesFilter(row, query.filter) && matchesSearch(row, query.search)), query.sort);
|
|
147
|
+
const size = Math.max(1, Math.trunc(query.size));
|
|
148
|
+
if (isPagePosition(query.position)) {
|
|
149
|
+
const page = Math.max(1, Math.trunc(query.position.page));
|
|
150
|
+
const start = (page - 1) * size;
|
|
151
|
+
const items = matched.slice(start, start + size);
|
|
152
|
+
return { items, total: matched.length, hasMore: start + size < matched.length, hasPrevious: page > 1 };
|
|
153
|
+
}
|
|
154
|
+
const offset = query.position.cursor === null ? 0 : Number(query.position.cursor) || 0;
|
|
155
|
+
const start = query.position.direction === CursorDirection.backward ? Math.max(0, offset - size) : offset;
|
|
156
|
+
const items = matched.slice(start, start + size);
|
|
157
|
+
return {
|
|
158
|
+
items,
|
|
159
|
+
total: matched.length,
|
|
160
|
+
hasMore: start + size < matched.length,
|
|
161
|
+
hasPrevious: start > 0,
|
|
162
|
+
nextCursor: start + size < matched.length ? String(start + size) : null,
|
|
163
|
+
prevCursor: start > 0 ? String(start) : null,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ResourceService } from "../core/contracts.js";
|
|
2
|
+
import { type Rng } from "./rng.js";
|
|
3
|
+
import { type Introspect, type StandardSchema } from "../resource/schema.js";
|
|
4
|
+
type IdOf<T> = T extends {
|
|
5
|
+
id: infer Id;
|
|
6
|
+
} ? Id : string;
|
|
7
|
+
export type MemoryServiceOptions<T> = {
|
|
8
|
+
/** The same seed gives the same rows. Default 1. */
|
|
9
|
+
seed?: number;
|
|
10
|
+
/** How many rows to generate. Default 50. */
|
|
11
|
+
count?: number;
|
|
12
|
+
rows?: readonly T[];
|
|
13
|
+
generate?: Partial<Record<string, (rng: Rng, index: number) => unknown>>;
|
|
14
|
+
/** A delay per call, in ms, or a range: to see the loading states. */
|
|
15
|
+
latency?: number | readonly [min: number, max: number];
|
|
16
|
+
/** The share of calls that fail with a retryable server error: to see the error states. */
|
|
17
|
+
failRate?: number;
|
|
18
|
+
versioned?: boolean;
|
|
19
|
+
softDelete?: boolean;
|
|
20
|
+
/** Adds what a server would join on read, like `country` from `countryId`. Never stored. */
|
|
21
|
+
expand?: (row: T) => T;
|
|
22
|
+
introspect?: Introspect;
|
|
23
|
+
/** The time generated dates count back from. A fixed date by default, so fixtures don't drift. */
|
|
24
|
+
now?: Date;
|
|
25
|
+
};
|
|
26
|
+
export type MemoryService<T, Id> = ResourceService<T, Id> & {
|
|
27
|
+
rows(): T[];
|
|
28
|
+
reset(): void;
|
|
29
|
+
};
|
|
30
|
+
export declare function memoryService<T, Id = IdOf<T>>(resource: StandardSchema<unknown, T> | {
|
|
31
|
+
schema: StandardSchema<unknown, T>;
|
|
32
|
+
}, options?: MemoryServiceOptions<T>): MemoryService<T, Id>;
|
|
33
|
+
export {};
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { JsonFormat, JsonType, PagePositionKind, ServiceErrorKind, TargetKind, TotalKind } from "../core/constants.js";
|
|
2
|
+
import { ServiceFailure, serviceError } from "../core/errors.js";
|
|
3
|
+
import { isNumber, isRecord } from "../core/guards.js";
|
|
4
|
+
import { applyQuery, matchesFilter, matchesSearch, valueAt } from "./memory-query.js";
|
|
5
|
+
import { assumeType } from "../core/assume.js";
|
|
6
|
+
import { createRng } from "./rng.js";
|
|
7
|
+
import { isStandardSchema, isValidationFailure, issuePath, validate, zodIntrospect, } from "../resource/schema.js";
|
|
8
|
+
const firstNames = [
|
|
9
|
+
"Ana",
|
|
10
|
+
"Luis",
|
|
11
|
+
"Marta",
|
|
12
|
+
"Jorge",
|
|
13
|
+
"Lucía",
|
|
14
|
+
"Pablo",
|
|
15
|
+
"Elena",
|
|
16
|
+
"Diego",
|
|
17
|
+
"Sara",
|
|
18
|
+
"Hugo",
|
|
19
|
+
"Irene",
|
|
20
|
+
"Raúl",
|
|
21
|
+
];
|
|
22
|
+
const lastNames = ["García", "Martín", "López", "Sánchez", "Pérez", "Gómez", "Ruiz", "Díaz", "Moreno", "Álvarez"];
|
|
23
|
+
const companyWords = ["Acme", "Nova", "Atlas", "Cobalto", "Delta", "Faro", "Lince", "Olivo", "Prisma", "Vela", "Zenit"];
|
|
24
|
+
const companySuffixes = ["S.L.", "S.A.", "Group", "Labs", "& Co."];
|
|
25
|
+
const words = ["alpha", "bravo", "cedar", "dune", "ember", "fjord", "grove", "harbor", "iris", "jade", "kelp", "lumen"];
|
|
26
|
+
const fixedNow = new Date("2026-06-01T09:00:00.000Z");
|
|
27
|
+
function ascii(text) {
|
|
28
|
+
return text
|
|
29
|
+
.normalize("NFD")
|
|
30
|
+
.replace(/[̀-ͯ]/gu, "")
|
|
31
|
+
.replace(/[^a-z0-9]/giu, "")
|
|
32
|
+
.toLowerCase();
|
|
33
|
+
}
|
|
34
|
+
function generateString(property, rng, index, now) {
|
|
35
|
+
const key = property.key.toLowerCase();
|
|
36
|
+
if (property.enum)
|
|
37
|
+
return rng.pick(property.enum);
|
|
38
|
+
if (property.format === JsonFormat.email)
|
|
39
|
+
return `${ascii(rng.pick(firstNames))}.${ascii(rng.pick(lastNames))}${String(index + 1)}@example.com`;
|
|
40
|
+
if (property.format === JsonFormat.dateTime) {
|
|
41
|
+
const back = rng.int(0, 730 * 24 * 60) * 60_000;
|
|
42
|
+
return new Date(now.getTime() - back).toISOString();
|
|
43
|
+
}
|
|
44
|
+
if (property.format === JsonFormat.date)
|
|
45
|
+
return new Date(now.getTime() - rng.int(0, 730) * 86_400_000).toISOString().slice(0, 10);
|
|
46
|
+
if (property.format === JsonFormat.time)
|
|
47
|
+
return `${String(rng.int(8, 19)).padStart(2, "0")}:${String(rng.int(0, 3) * 15).padStart(2, "0")}`;
|
|
48
|
+
if (property.format === JsonFormat.uuid)
|
|
49
|
+
return `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`;
|
|
50
|
+
if (property.format === JsonFormat.uri || property.format === JsonFormat.url)
|
|
51
|
+
return `https://example.com/${String(index + 1)}`;
|
|
52
|
+
if (property.minLength !== undefined && property.minLength === property.maxLength)
|
|
53
|
+
return Array.from({ length: property.minLength }, () => String.fromCodePoint(65 + rng.int(0, 25))).join("");
|
|
54
|
+
if (/(?:number|^code|ref)$/u.test(key))
|
|
55
|
+
return `${key.slice(0, 2).toUpperCase()}-${String(10_000 + index + 1)}`;
|
|
56
|
+
let text;
|
|
57
|
+
if (key === "name" || key.endsWith("name"))
|
|
58
|
+
text = rng.bool(0.5)
|
|
59
|
+
? `${rng.pick(firstNames)} ${rng.pick(lastNames)}`
|
|
60
|
+
: `${rng.pick(companyWords)} ${rng.pick(companyWords)} ${rng.pick(companySuffixes)}`;
|
|
61
|
+
else if (/^(?:title|label)$/u.test(key))
|
|
62
|
+
text = `${rng.pick(companyWords)} ${rng.pick(words)}`;
|
|
63
|
+
else
|
|
64
|
+
text = Array.from({ length: rng.int(2, 6) }, () => rng.pick(words)).join(" ");
|
|
65
|
+
const max = property.maxLength ?? 200;
|
|
66
|
+
const fitted = text.slice(0, max);
|
|
67
|
+
return fitted.length >= (property.minLength ?? 0) ? fitted : fitted.padEnd(property.minLength ?? 0, "x");
|
|
68
|
+
}
|
|
69
|
+
function generateNumber(property, rng) {
|
|
70
|
+
const key = property.key.toLowerCase();
|
|
71
|
+
const min = property.minimum ?? 0;
|
|
72
|
+
const money = ["total", "price", "amount", "balance", "cost"].some((word) => key.includes(word));
|
|
73
|
+
const max = property.maximum ?? (money ? 5000 : 1000);
|
|
74
|
+
if (property.type === JsonType.integer || !money)
|
|
75
|
+
return rng.int(Math.ceil(min), Math.floor(max));
|
|
76
|
+
return Math.round((min + rng.next() * (max - min)) * 100) / 100;
|
|
77
|
+
}
|
|
78
|
+
function generateValue(property, rng, index, now) {
|
|
79
|
+
const { type, items, properties } = property;
|
|
80
|
+
if (type === JsonType.string)
|
|
81
|
+
return generateString(property, rng, index, now);
|
|
82
|
+
if (type === JsonType.number || type === JsonType.integer)
|
|
83
|
+
return generateNumber(property, rng);
|
|
84
|
+
if (type === JsonType.boolean)
|
|
85
|
+
return rng.bool();
|
|
86
|
+
if (type === JsonType.array)
|
|
87
|
+
return items ? Array.from({ length: rng.int(0, 3) }, (_, at) => generateValue(items, rng, index + at, now)) : [];
|
|
88
|
+
if (type === JsonType.object)
|
|
89
|
+
return properties ? generateObject(properties, rng, index, now, {}) : {};
|
|
90
|
+
return property.enum ? rng.pick(property.enum) : undefined;
|
|
91
|
+
}
|
|
92
|
+
function generateObject(properties, rng, index, now, generators) {
|
|
93
|
+
const row = {};
|
|
94
|
+
for (const property of properties) {
|
|
95
|
+
const own = generators?.[property.key];
|
|
96
|
+
if (own)
|
|
97
|
+
row[property.key] = own(rng, index);
|
|
98
|
+
else if (property.key === "id")
|
|
99
|
+
row.id = property.type === JsonType.string ? String(index + 1) : index + 1;
|
|
100
|
+
else if (property.required)
|
|
101
|
+
row[property.key] = generateValue(property, rng, index, now);
|
|
102
|
+
}
|
|
103
|
+
return row;
|
|
104
|
+
}
|
|
105
|
+
function wait(ms, signal) {
|
|
106
|
+
if (ms <= 0)
|
|
107
|
+
return signal.aborted ? Promise.reject(abortReason(signal)) : Promise.resolve();
|
|
108
|
+
return new Promise((resolve, reject) => {
|
|
109
|
+
const timer = setTimeout(() => {
|
|
110
|
+
signal.removeEventListener("abort", onAbort);
|
|
111
|
+
resolve();
|
|
112
|
+
}, ms);
|
|
113
|
+
const onAbort = () => {
|
|
114
|
+
clearTimeout(timer);
|
|
115
|
+
reject(abortReason(signal));
|
|
116
|
+
};
|
|
117
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
function abortReason(signal) {
|
|
121
|
+
return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted.", "AbortError");
|
|
122
|
+
}
|
|
123
|
+
function idKey(id) {
|
|
124
|
+
return String(id);
|
|
125
|
+
}
|
|
126
|
+
function schemaOf(resource) {
|
|
127
|
+
return isStandardSchema(resource) ? resource : resource.schema;
|
|
128
|
+
}
|
|
129
|
+
const deletedKey = "deleted";
|
|
130
|
+
export function memoryService(resource, options = {}) {
|
|
131
|
+
const schema = schemaOf(resource);
|
|
132
|
+
const now = options.now ?? fixedNow;
|
|
133
|
+
const properties = (options.introspect ?? zodIntrospect)(schema) ?? [];
|
|
134
|
+
const make = () => {
|
|
135
|
+
if (options.rows)
|
|
136
|
+
return options.rows.map((row) => structuredClone(row));
|
|
137
|
+
const rng = createRng(options.seed ?? 1);
|
|
138
|
+
const generators = options.generate;
|
|
139
|
+
const rows = [];
|
|
140
|
+
for (let index = 0; index < (options.count ?? 50); index++) {
|
|
141
|
+
// Workaround: a row generated from the schema's own JSON Schema is a T by construction; validating it would be async.
|
|
142
|
+
rows.push(assumeType(generateObject(properties, rng, index, now, generators)));
|
|
143
|
+
}
|
|
144
|
+
return rows;
|
|
145
|
+
};
|
|
146
|
+
let rows = make();
|
|
147
|
+
let deleted = new Set();
|
|
148
|
+
let versions = new Map();
|
|
149
|
+
// Spec: an id is taken before the row is validated, so creates that overlap never share one.
|
|
150
|
+
let issued = 0;
|
|
151
|
+
const jitter = createRng((options.seed ?? 1) + 1);
|
|
152
|
+
// Workaround: `Id` is the type of the rows' `id`, which TypeScript can't read back from a generic `T`.
|
|
153
|
+
const idOf = (row) => assumeType(valueAt(row, "id"));
|
|
154
|
+
const expand = (row) => (options.expand ? options.expand(structuredClone(row)) : structuredClone(row));
|
|
155
|
+
async function call(context) {
|
|
156
|
+
const latency = options.latency ?? 0;
|
|
157
|
+
const ms = isNumber(latency) ? latency : jitter.int(latency[0], latency[1]);
|
|
158
|
+
await wait(ms, context.signal);
|
|
159
|
+
if (options.failRate !== undefined && Math.random() < options.failRate)
|
|
160
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.server, "The in-memory service failed on purpose.", { status: 503 }));
|
|
161
|
+
}
|
|
162
|
+
const live = () => rows.filter((row) => !deleted.has(idKey(idOf(row))));
|
|
163
|
+
const find = (id) => rows.find((row) => idKey(idOf(row)) === idKey(id));
|
|
164
|
+
const notFound = (id) => new ServiceFailure(serviceError(ServiceErrorKind.notFound, `There is no record ${idKey(id)}.`, { status: 404 }));
|
|
165
|
+
async function checked(value) {
|
|
166
|
+
const result = await validate(schema, value);
|
|
167
|
+
if (!isValidationFailure(result))
|
|
168
|
+
return result.value;
|
|
169
|
+
const fields = result.issues.map((issue) => ({ path: issuePath(issue), message: issue.message }));
|
|
170
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.validation, fields[0]?.message ?? "The record isn't valid.", {
|
|
171
|
+
status: 422,
|
|
172
|
+
fields,
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
function stamp(row, created) {
|
|
176
|
+
const at = new Date().toISOString();
|
|
177
|
+
for (const property of properties) {
|
|
178
|
+
if (property.format !== JsonFormat.dateTime)
|
|
179
|
+
continue;
|
|
180
|
+
if (property.key === "updatedAt" || (created && property.key === "createdAt"))
|
|
181
|
+
row[property.key] = at;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function targetRows(target) {
|
|
185
|
+
if (target.kind === TargetKind.ids) {
|
|
186
|
+
const wanted = new Set(target.ids.map(idKey));
|
|
187
|
+
return rows.filter((row) => wanted.has(idKey(idOf(row))));
|
|
188
|
+
}
|
|
189
|
+
const except = new Set(target.except.map(idKey));
|
|
190
|
+
return live().filter((row) => matchesFilter(row, target.filter) && matchesSearch(row, target.search) && !except.has(idKey(idOf(row))));
|
|
191
|
+
}
|
|
192
|
+
const service = {
|
|
193
|
+
capabilities: {
|
|
194
|
+
position: PagePositionKind.page,
|
|
195
|
+
total: TotalKind.exact,
|
|
196
|
+
bulkByQuery: true,
|
|
197
|
+
...(options.versioned === true ? { versioned: true } : {}),
|
|
198
|
+
...(options.softDelete === true ? { restore: true } : {}),
|
|
199
|
+
},
|
|
200
|
+
rows: () => live().map((row) => structuredClone(row)),
|
|
201
|
+
reset() {
|
|
202
|
+
rows = make();
|
|
203
|
+
deleted = new Set();
|
|
204
|
+
issued = 0;
|
|
205
|
+
versions = new Map();
|
|
206
|
+
},
|
|
207
|
+
async list(query, context) {
|
|
208
|
+
await call(context);
|
|
209
|
+
const showDeleted = isRecord(query.filter) && query.filter[deletedKey] === true;
|
|
210
|
+
const pool = showDeleted ? rows.filter((row) => deleted.has(idKey(idOf(row)))) : live();
|
|
211
|
+
const { [deletedKey]: _deleted, ...filter } = query.filter;
|
|
212
|
+
const page = applyQuery(pool.map(expand), { ...query, filter });
|
|
213
|
+
return page;
|
|
214
|
+
},
|
|
215
|
+
async count(filter, context) {
|
|
216
|
+
await call(context);
|
|
217
|
+
return live().filter((row) => matchesFilter(expand(row), filter)).length;
|
|
218
|
+
},
|
|
219
|
+
async get(id, context) {
|
|
220
|
+
await call(context);
|
|
221
|
+
const row = find(id);
|
|
222
|
+
if (row === undefined || deleted.has(idKey(id)))
|
|
223
|
+
throw notFound(id);
|
|
224
|
+
return expand(row);
|
|
225
|
+
},
|
|
226
|
+
async getMany(ids, context) {
|
|
227
|
+
await call(context);
|
|
228
|
+
const wanted = new Set(ids.map(idKey));
|
|
229
|
+
return live()
|
|
230
|
+
.filter((row) => wanted.has(idKey(idOf(row))))
|
|
231
|
+
.map(expand);
|
|
232
|
+
},
|
|
233
|
+
async create(input, context) {
|
|
234
|
+
await call(context);
|
|
235
|
+
const numeric = rows.every((row) => isNumber(idOf(row)));
|
|
236
|
+
const next = Math.max(issued, rows.reduce((max, row) => Math.max(max, Number(idOf(row)) || 0), 0)) + 1;
|
|
237
|
+
issued = next;
|
|
238
|
+
const draft = { ...(isRecord(input) ? input : {}) };
|
|
239
|
+
if (draft.id === undefined)
|
|
240
|
+
draft.id = numeric ? next : String(next);
|
|
241
|
+
stamp(draft, true);
|
|
242
|
+
const row = await checked(draft);
|
|
243
|
+
rows = [...rows, row];
|
|
244
|
+
versions.set(idKey(idOf(row)), 1);
|
|
245
|
+
return expand(row);
|
|
246
|
+
},
|
|
247
|
+
async update(id, patch, context) {
|
|
248
|
+
await call(context);
|
|
249
|
+
const current = find(id);
|
|
250
|
+
if (current === undefined || deleted.has(idKey(id)))
|
|
251
|
+
throw notFound(id);
|
|
252
|
+
const version = versions.get(idKey(id)) ?? 1;
|
|
253
|
+
if (options.versioned === true && context.version !== undefined && context.version !== version)
|
|
254
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.conflict, "The record changed since it was read.", {
|
|
255
|
+
status: 409,
|
|
256
|
+
current: expand(current),
|
|
257
|
+
}));
|
|
258
|
+
const draft = {
|
|
259
|
+
...(isRecord(current) ? current : {}),
|
|
260
|
+
...(isRecord(patch) ? patch : {}),
|
|
261
|
+
};
|
|
262
|
+
draft.id = idOf(current);
|
|
263
|
+
stamp(draft, false);
|
|
264
|
+
const row = await checked(draft);
|
|
265
|
+
rows = rows.map((entry) => (idKey(idOf(entry)) === idKey(id) ? row : entry));
|
|
266
|
+
versions.set(idKey(id), version + 1);
|
|
267
|
+
return expand(row);
|
|
268
|
+
},
|
|
269
|
+
async remove(target, context) {
|
|
270
|
+
await call(context);
|
|
271
|
+
const gone = new Set(targetRows(target).map((row) => idKey(idOf(row))));
|
|
272
|
+
if (options.softDelete === true)
|
|
273
|
+
for (const id of gone)
|
|
274
|
+
deleted.add(id);
|
|
275
|
+
else
|
|
276
|
+
rows = rows.filter((row) => !gone.has(idKey(idOf(row))));
|
|
277
|
+
},
|
|
278
|
+
async restore(target, context) {
|
|
279
|
+
await call(context);
|
|
280
|
+
const back = target.kind === TargetKind.ids
|
|
281
|
+
? target.ids.map(idKey)
|
|
282
|
+
: rows
|
|
283
|
+
.filter((row) => deleted.has(idKey(idOf(row))) && matchesFilter(row, target.filter))
|
|
284
|
+
.map((row) => idKey(idOf(row)));
|
|
285
|
+
for (const id of back)
|
|
286
|
+
deleted.delete(id);
|
|
287
|
+
},
|
|
288
|
+
versionOf: (row) => options.versioned === true ? (versions.get(idKey(idOf(row))) ?? 1) : undefined,
|
|
289
|
+
};
|
|
290
|
+
return service;
|
|
291
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type FileFormat } from "../core/constants.js";
|
|
2
|
+
import type { CallContext, ExportResult, Page, Query, ResourceCapabilities, ResourceService, Version } from "../core/contracts.js";
|
|
3
|
+
/** The reading half of a service: what a third-party API, a report or a log usually offers. */
|
|
4
|
+
export type ReadService<T, Id = string, F = Record<string, unknown>> = {
|
|
5
|
+
capabilities: ResourceCapabilities;
|
|
6
|
+
list(query: Query<F>, context: CallContext): Promise<Page<T>>;
|
|
7
|
+
get(id: Id, context: CallContext): Promise<T>;
|
|
8
|
+
count?(filter: F, context: CallContext): Promise<number>;
|
|
9
|
+
getMany?(ids: readonly Id[], context: CallContext): Promise<T[]>;
|
|
10
|
+
export?(query: Query<F>, format: FileFormat, context: CallContext): Promise<ExportResult>;
|
|
11
|
+
versionOf?(row: T): Version | undefined;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* A service that only reads. Its resource refuses `create`, `update`, `remove`, `restore` and `import` with the reason
|
|
15
|
+
* (`capabilities.readOnly`): their buttons don't show and an agent's step fails saying so. A write that reaches the
|
|
16
|
+
* service anyway (app code) throws a `forbidden` `ServiceError`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function readOnlyService<T, Id = string, F = Record<string, unknown>>(service: ReadService<T, Id, F>): ResourceService<T, Id, F>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ServiceErrorKind } from "../core/constants.js";
|
|
2
|
+
import { ServiceFailure, serviceError } from "../core/errors.js";
|
|
3
|
+
function refused(operation) {
|
|
4
|
+
return Promise.reject(new ServiceFailure(serviceError(ServiceErrorKind.forbidden, `This service is read-only: it has no ${operation}.`)));
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* A service that only reads. Its resource refuses `create`, `update`, `remove`, `restore` and `import` with the reason
|
|
8
|
+
* (`capabilities.readOnly`): their buttons don't show and an agent's step fails saying so. A write that reaches the
|
|
9
|
+
* service anyway (app code) throws a `forbidden` `ServiceError`.
|
|
10
|
+
*/
|
|
11
|
+
export function readOnlyService(service) {
|
|
12
|
+
const { count, getMany, export: exportRows, versionOf } = service;
|
|
13
|
+
return {
|
|
14
|
+
capabilities: { ...service.capabilities, readOnly: true, restore: false },
|
|
15
|
+
list: (query, context) => service.list(query, context),
|
|
16
|
+
get: (id, context) => service.get(id, context),
|
|
17
|
+
...(count ? { count: count.bind(service) } : {}),
|
|
18
|
+
...(getMany ? { getMany: getMany.bind(service) } : {}),
|
|
19
|
+
...(exportRows ? { export: exportRows.bind(service) } : {}),
|
|
20
|
+
...(versionOf ? { versionOf: versionOf.bind(service) } : {}),
|
|
21
|
+
create: () => refused("create"),
|
|
22
|
+
update: () => refused("update"),
|
|
23
|
+
remove: () => refused("remove"),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { PagePositionKind, TotalKind, VersionRead, VersionSend, type SortDirection } from "../core/constants.js";
|
|
2
|
+
import { type CallContext, type Page, type ResourceService } from "../core/contracts.js";
|
|
3
|
+
import { type ServiceError } from "../core/errors.js";
|
|
4
|
+
export declare const HttpMethod: {
|
|
5
|
+
readonly get: "GET";
|
|
6
|
+
readonly post: "POST";
|
|
7
|
+
readonly put: "PUT";
|
|
8
|
+
readonly patch: "PATCH";
|
|
9
|
+
readonly delete: "DELETE";
|
|
10
|
+
};
|
|
11
|
+
export type HttpMethod = (typeof HttpMethod)[keyof typeof HttpMethod];
|
|
12
|
+
export type RestServiceOptions<T, F> = {
|
|
13
|
+
fetch?: typeof fetch;
|
|
14
|
+
/**
|
|
15
|
+
* Headers for every call; `session.token()` becomes `Authorization: Bearer …` unless you set it, and a write's
|
|
16
|
+
* `idempotencyKey` `Idempotency-Key`.
|
|
17
|
+
*/
|
|
18
|
+
headers?: (context: CallContext) => Record<string, string> | Promise<Record<string, string>>;
|
|
19
|
+
position?: PagePositionKind;
|
|
20
|
+
/** The first page's number: 1 (default) or 0. */
|
|
21
|
+
pageBase?: 0 | 1;
|
|
22
|
+
/** Query parameter names; `include` carries the relations to embed (`?include=customer,tags`). */
|
|
23
|
+
params?: {
|
|
24
|
+
page?: string;
|
|
25
|
+
size?: string;
|
|
26
|
+
sort?: string;
|
|
27
|
+
search?: string;
|
|
28
|
+
cursor?: string;
|
|
29
|
+
before?: string;
|
|
30
|
+
include?: string;
|
|
31
|
+
};
|
|
32
|
+
/** Writes `Query.include` as parameters; `?include=a,b` by default, `false` sends nothing. */
|
|
33
|
+
includeParams?: false | ((include: readonly string[]) => Record<string, string>);
|
|
34
|
+
filterParams?: (filter: F) => Record<string, unknown>;
|
|
35
|
+
sortStyle?: (field: string, direction: SortDirection) => string;
|
|
36
|
+
read?: (raw: unknown, response: Response) => Page<T>;
|
|
37
|
+
/** `PATCH` (default) or `PUT` for updates. */
|
|
38
|
+
updateMethod?: typeof HttpMethod.patch | typeof HttpMethod.put;
|
|
39
|
+
version?: {
|
|
40
|
+
read: VersionRead;
|
|
41
|
+
send: VersionSend;
|
|
42
|
+
field?: string;
|
|
43
|
+
};
|
|
44
|
+
total?: TotalKind;
|
|
45
|
+
maxPageSize?: number;
|
|
46
|
+
/** Sends bulk removes and restores as `DELETE /x?…` with the filter, not one call per id. */
|
|
47
|
+
bulkByQuery?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Reads many records in one request, `GET /x?ids=1&ids=2` (`param` renames it), so relations and comboboxes never
|
|
50
|
+
* read one id at a time; `size` is the most ids per request. `resourceHandler` serves it.
|
|
51
|
+
*/
|
|
52
|
+
batch?: boolean | {
|
|
53
|
+
param?: string;
|
|
54
|
+
size?: number;
|
|
55
|
+
};
|
|
56
|
+
/** Has `POST /x/restore` with `{ ids }`. */
|
|
57
|
+
restore?: boolean;
|
|
58
|
+
/** Adjusts every error before it's thrown, like a backend's own field paths. */
|
|
59
|
+
mapError?: (error: ServiceError) => ServiceError;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* A REST backend: `GET /x?page=&size=&sort=`, `GET /x/:id`, `POST /x`, `PATCH /x/:id` and `DELETE /x/:id`. Errors
|
|
63
|
+
* (RFC 9457 `ProblemDetail`, Spring validation, JSON:API) become `ServiceError`s with their fields.
|
|
64
|
+
*/
|
|
65
|
+
export declare function restService<T, Id = string, F = Record<string, unknown>>(base: string, options?: RestServiceOptions<T, F>): ResourceService<T, Id, F>;
|