@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.
Files changed (159) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -2
  3. package/dist/action/action.d.ts +133 -0
  4. package/dist/action/action.js +224 -0
  5. package/dist/action/bulk.d.ts +24 -0
  6. package/dist/action/bulk.js +24 -0
  7. package/dist/cli/cli.d.ts +2 -0
  8. package/dist/cli/cli.js +51 -0
  9. package/dist/cli/routes.d.ts +17 -0
  10. package/dist/cli/routes.js +36 -0
  11. package/dist/core/assume.d.ts +1 -0
  12. package/dist/core/assume.js +8 -0
  13. package/dist/core/constants.d.ts +359 -0
  14. package/dist/core/constants.js +187 -0
  15. package/dist/core/contracts.d.ts +107 -0
  16. package/dist/core/contracts.js +3 -0
  17. package/dist/core/data-labels.d.ts +210 -0
  18. package/dist/core/data-labels.js +385 -0
  19. package/dist/core/errors.d.ts +52 -0
  20. package/dist/core/errors.js +209 -0
  21. package/dist/core/guards.d.ts +9 -0
  22. package/dist/core/guards.js +14 -0
  23. package/dist/core/refusal.d.ts +30 -0
  24. package/dist/core/refusal.js +53 -0
  25. package/dist/dialogs/dialogs.d.ts +75 -0
  26. package/dist/dialogs/dialogs.js +66 -0
  27. package/dist/draft/draft.d.ts +36 -0
  28. package/dist/draft/draft.js +87 -0
  29. package/dist/errors/adapters.d.ts +21 -0
  30. package/dist/errors/adapters.js +81 -0
  31. package/dist/errors/define-errors.d.ts +88 -0
  32. package/dist/errors/define-errors.js +168 -0
  33. package/dist/errors/idempotency.d.ts +2 -0
  34. package/dist/errors/idempotency.js +13 -0
  35. package/dist/export/csv.d.ts +25 -0
  36. package/dist/export/csv.js +59 -0
  37. package/dist/i18n/adapters.d.ts +53 -0
  38. package/dist/i18n/adapters.js +56 -0
  39. package/dist/i18n/format.d.ts +10 -0
  40. package/dist/i18n/format.js +273 -0
  41. package/dist/i18n/labels.d.ts +10 -0
  42. package/dist/i18n/labels.js +227 -0
  43. package/dist/i18n/locale.d.ts +73 -0
  44. package/dist/i18n/locale.js +74 -0
  45. package/dist/i18n/messages.d.ts +93 -0
  46. package/dist/i18n/messages.js +16 -0
  47. package/dist/import/csv-parse.d.ts +11 -0
  48. package/dist/import/csv-parse.js +70 -0
  49. package/dist/import/import.d.ts +104 -0
  50. package/dist/import/import.js +266 -0
  51. package/dist/index.d.ts +46 -0
  52. package/dist/index.js +45 -0
  53. package/dist/navigation/nav.d.ts +128 -0
  54. package/dist/navigation/nav.js +301 -0
  55. package/dist/navigation/router.d.ts +81 -0
  56. package/dist/navigation/router.js +249 -0
  57. package/dist/navigation/shortcuts.d.ts +37 -0
  58. package/dist/navigation/shortcuts.js +93 -0
  59. package/dist/next/index.d.ts +3 -0
  60. package/dist/next/index.js +3 -0
  61. package/dist/next/screen-hydration.d.ts +12 -0
  62. package/dist/next/screen-hydration.js +26 -0
  63. package/dist/next/screen.d.ts +25 -0
  64. package/dist/next/screen.js +44 -0
  65. package/dist/next/server/handler.d.ts +39 -0
  66. package/dist/next/server/handler.js +190 -0
  67. package/dist/next/server/index.d.ts +6 -0
  68. package/dist/next/server/index.js +6 -0
  69. package/dist/next/server/page.d.ts +63 -0
  70. package/dist/next/server/page.js +110 -0
  71. package/dist/next/server/prefetch.d.ts +29 -0
  72. package/dist/next/server/prefetch.js +97 -0
  73. package/dist/next/server/session.d.ts +25 -0
  74. package/dist/next/server/session.js +23 -0
  75. package/dist/next/use-next-router.d.ts +21 -0
  76. package/dist/next/use-next-router.js +104 -0
  77. package/dist/permissions/permissions.d.ts +134 -0
  78. package/dist/permissions/permissions.js +121 -0
  79. package/dist/react/data-layer.d.ts +68 -0
  80. package/dist/react/data-layer.js +76 -0
  81. package/dist/react/hooks/use-action-dialog.d.ts +25 -0
  82. package/dist/react/hooks/use-action-dialog.js +31 -0
  83. package/dist/react/hooks/use-action.d.ts +37 -0
  84. package/dist/react/hooks/use-action.js +125 -0
  85. package/dist/react/hooks/use-better-auth.d.ts +12 -0
  86. package/dist/react/hooks/use-better-auth.js +11 -0
  87. package/dist/react/hooks/use-bulk-action.d.ts +20 -0
  88. package/dist/react/hooks/use-bulk-action.js +24 -0
  89. package/dist/react/hooks/use-dialogs.d.ts +14 -0
  90. package/dist/react/hooks/use-dialogs.js +20 -0
  91. package/dist/react/hooks/use-draft.d.ts +5 -0
  92. package/dist/react/hooks/use-draft.js +17 -0
  93. package/dist/react/hooks/use-nav.d.ts +17 -0
  94. package/dist/react/hooks/use-nav.js +35 -0
  95. package/dist/react/hooks/use-new-rows.d.ts +22 -0
  96. package/dist/react/hooks/use-new-rows.js +24 -0
  97. package/dist/react/hooks/use-permissions.d.ts +13 -0
  98. package/dist/react/hooks/use-permissions.js +19 -0
  99. package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
  100. package/dist/react/hooks/use-reauthenticate.js +11 -0
  101. package/dist/react/hooks/use-resource.d.ts +92 -0
  102. package/dist/react/hooks/use-resource.js +255 -0
  103. package/dist/react/hooks/use-view.d.ts +6 -0
  104. package/dist/react/hooks/use-view.js +24 -0
  105. package/dist/react/index.d.ts +15 -0
  106. package/dist/react/index.js +15 -0
  107. package/dist/react/keys.d.ts +60 -0
  108. package/dist/react/keys.js +71 -0
  109. package/dist/react/new-rows.d.ts +22 -0
  110. package/dist/react/new-rows.js +72 -0
  111. package/dist/refresh/new-rows.d.ts +13 -0
  112. package/dist/refresh/new-rows.js +18 -0
  113. package/dist/resource/form-schema.d.ts +11 -0
  114. package/dist/resource/form-schema.js +51 -0
  115. package/dist/resource/relations.d.ts +99 -0
  116. package/dist/resource/relations.js +194 -0
  117. package/dist/resource/resource-relations.d.ts +47 -0
  118. package/dist/resource/resource-relations.js +154 -0
  119. package/dist/resource/resource-schema.d.ts +9 -0
  120. package/dist/resource/resource-schema.js +73 -0
  121. package/dist/resource/resource-texts.d.ts +18 -0
  122. package/dist/resource/resource-texts.js +13 -0
  123. package/dist/resource/resource-types.d.ts +420 -0
  124. package/dist/resource/resource-types.js +1 -0
  125. package/dist/resource/resource-words.d.ts +25 -0
  126. package/dist/resource/resource-words.js +221 -0
  127. package/dist/resource/resource.d.ts +15 -0
  128. package/dist/resource/resource.js +280 -0
  129. package/dist/resource/schema.d.ts +57 -0
  130. package/dist/resource/schema.js +115 -0
  131. package/dist/services/from-page-source.d.ts +15 -0
  132. package/dist/services/from-page-source.js +27 -0
  133. package/dist/services/memory-query.d.ts +8 -0
  134. package/dist/services/memory-query.js +165 -0
  135. package/dist/services/memory-service.d.ts +33 -0
  136. package/dist/services/memory-service.js +291 -0
  137. package/dist/services/read-only-service.d.ts +18 -0
  138. package/dist/services/read-only-service.js +25 -0
  139. package/dist/services/rest-service.d.ts +65 -0
  140. package/dist/services/rest-service.js +222 -0
  141. package/dist/services/rng.d.ts +9 -0
  142. package/dist/services/rng.js +22 -0
  143. package/dist/services/spring-service.d.ts +58 -0
  144. package/dist/services/spring-service.js +132 -0
  145. package/dist/session/better-auth.d.ts +83 -0
  146. package/dist/session/better-auth.js +86 -0
  147. package/dist/session/session.d.ts +45 -0
  148. package/dist/session/session.js +36 -0
  149. package/dist/view/preferences.d.ts +35 -0
  150. package/dist/view/preferences.js +93 -0
  151. package/dist/view/view-types.d.ts +124 -0
  152. package/dist/view/view-types.js +1 -0
  153. package/dist/view/view-url.d.ts +7 -0
  154. package/dist/view/view-url.js +54 -0
  155. package/dist/view/view.d.ts +4 -0
  156. package/dist/view/view.js +392 -0
  157. package/locales/en.json +193 -0
  158. package/locales/es.json +193 -0
  159. package/package.json +88 -4
@@ -0,0 +1,209 @@
1
+ import { ErrorReason, ServiceErrorKind } from "./constants.js";
2
+ import { isBoolean, isNumber, isRecord, isString, isText } from "./guards.js";
3
+ const kinds = new Set(Object.values(ServiceErrorKind));
4
+ export function isServiceError(value) {
5
+ return (isRecord(value) &&
6
+ isString(value.kind) &&
7
+ kinds.has(value.kind) &&
8
+ isString(value.message) &&
9
+ isBoolean(value.retryable));
10
+ }
11
+ /**
12
+ * A `ServiceError` you can throw: services and adapters reject with it, so `toServiceError` gets the same object
13
+ * back, and `status` and `retryable` stay readable by retry rules (`isTransientError` from `server-data`).
14
+ */
15
+ export class ServiceFailure extends Error {
16
+ name = "ServiceFailure";
17
+ error;
18
+ kind;
19
+ retryable;
20
+ status;
21
+ fields;
22
+ constructor(error) {
23
+ super(error.message, { cause: error.cause });
24
+ this.error = error;
25
+ this.kind = error.kind;
26
+ this.retryable = error.retryable;
27
+ this.status = error.status;
28
+ this.fields = error.fields;
29
+ }
30
+ }
31
+ export function serviceError(kind, message, extra = {}) {
32
+ return { kind, message, retryable: retryableKind(kind, extra.status), ...extra };
33
+ }
34
+ function retryableKind(kind, status) {
35
+ if (kind === ServiceErrorKind.network)
36
+ return true;
37
+ if (kind !== ServiceErrorKind.server)
38
+ return false;
39
+ return status === undefined || status >= 500 || status === 408 || status === 425 || status === 429;
40
+ }
41
+ export function kindOfStatus(status) {
42
+ if (status === 400 || status === 422)
43
+ return ServiceErrorKind.validation;
44
+ if (status === 401 || status === 403)
45
+ return ServiceErrorKind.forbidden;
46
+ if (status === 404 || status === 410)
47
+ return ServiceErrorKind.notFound;
48
+ if (status === 409 || status === 412)
49
+ return ServiceErrorKind.conflict;
50
+ return ServiceErrorKind.server;
51
+ }
52
+ function text(value) {
53
+ return isText(value) ? value : undefined;
54
+ }
55
+ const reasons = new Set(Object.values(ErrorReason));
56
+ export function isErrorReason(value) {
57
+ return isString(value) && reasons.has(value);
58
+ }
59
+ function reasonOfStatus(status) {
60
+ if (status === 401)
61
+ return ErrorReason.unauthorized;
62
+ if (status === 408 || status === 504)
63
+ return ErrorReason.timeout;
64
+ if (status === 429)
65
+ return ErrorReason.rateLimited;
66
+ return undefined;
67
+ }
68
+ const reasonOfKind = {
69
+ [ServiceErrorKind.validation]: ErrorReason.validation,
70
+ [ServiceErrorKind.conflict]: ErrorReason.conflict,
71
+ [ServiceErrorKind.forbidden]: ErrorReason.forbidden,
72
+ [ServiceErrorKind.notFound]: ErrorReason.notFound,
73
+ [ServiceErrorKind.network]: ErrorReason.network,
74
+ [ServiceErrorKind.server]: ErrorReason.server,
75
+ [ServiceErrorKind.aborted]: ErrorReason.aborted,
76
+ };
77
+ /** Its `reason`, or the one its status and kind tell: a 401 is `unauthorized`, a 429 `rate-limited`. */
78
+ export function reasonOf(error) {
79
+ if (error.reason !== undefined)
80
+ return error.reason;
81
+ const byStatus = error.status === undefined ? undefined : reasonOfStatus(error.status);
82
+ return byStatus ?? reasonOfKind[error.kind];
83
+ }
84
+ function fieldEntry(entry) {
85
+ if (!isRecord(entry))
86
+ return undefined;
87
+ const path = text(entry.field) ??
88
+ text(entry.path) ??
89
+ text(entry.name) ??
90
+ text(entry.pointer) ??
91
+ text(entry.property) ??
92
+ text(entry.propertyPath);
93
+ const message = text(entry.defaultMessage) ?? text(entry.message) ?? text(entry.reason) ?? text(entry.detail);
94
+ if (path === undefined || message === undefined)
95
+ return undefined;
96
+ const code = text(entry.code);
97
+ return {
98
+ path: path.replace(/^\/(?:data\/attributes\/)?/u, "").replaceAll("/", "."),
99
+ message,
100
+ ...(code === undefined ? {} : { code }),
101
+ };
102
+ }
103
+ /**
104
+ * Field errors from the shapes servers send: Spring's `errors`/`fieldErrors` (`field`, `defaultMessage`) and
105
+ * constraint violations (`propertyPath`), RFC 9457
106
+ * `invalid-params` or `violations`, JSON:API `errors[].source.pointer`, and `{ fieldErrors: { name: message } }`.
107
+ */
108
+ export function fieldErrorsOf(body) {
109
+ if (!isRecord(body))
110
+ return undefined;
111
+ const lists = [body.errors, body.fieldErrors, body["invalid-params"], body.violations];
112
+ const found = [];
113
+ for (const list of lists) {
114
+ if (Array.isArray(list)) {
115
+ const entries = list;
116
+ for (const entry of entries) {
117
+ const source = isRecord(entry) && isRecord(entry.source) ? { ...entry, ...entry.source } : entry;
118
+ const field = fieldEntry(source);
119
+ if (field)
120
+ found.push(field);
121
+ }
122
+ }
123
+ else if (isRecord(list)) {
124
+ for (const [path, message] of Object.entries(list)) {
125
+ const values = Array.isArray(message) ? message : [message];
126
+ const first = values[0];
127
+ if (isString(first))
128
+ found.push({ path, message: first });
129
+ }
130
+ }
131
+ }
132
+ return found.length > 0 ? found : undefined;
133
+ }
134
+ function messageOfBody(body) {
135
+ if (!isRecord(body))
136
+ return text(body);
137
+ return text(body.detail) ?? text(body.message) ?? text(body.title) ?? text(body.error);
138
+ }
139
+ export function httpServiceError(status, body, statusText) {
140
+ const kind = kindOfStatus(status);
141
+ const fields = fieldErrorsOf(body);
142
+ const message = messageOfBody(body) ?? text(statusText) ?? `Request failed with status ${String(status)}`;
143
+ const said = isRecord(body) ? body.reason : undefined;
144
+ const reason = isErrorReason(said) ? said : reasonOfStatus(status);
145
+ const code = isRecord(body) ? (text(body.code) ?? (isErrorReason(said) ? undefined : text(said))) : undefined;
146
+ return serviceError(kind, message, {
147
+ status,
148
+ ...(reason === undefined ? {} : { reason }),
149
+ ...(code === undefined ? {} : { code }),
150
+ ...(fields ? { fields } : {}),
151
+ ...(kind === ServiceErrorKind.conflict && isRecord(body) && "current" in body ? { current: body.current } : {}),
152
+ cause: body,
153
+ });
154
+ }
155
+ export async function problemDetailError(response) {
156
+ let body;
157
+ try {
158
+ const raw = await response.text();
159
+ body = raw === "" ? undefined : JSON.parse(raw);
160
+ }
161
+ catch {
162
+ body = undefined;
163
+ }
164
+ return new ServiceFailure(httpServiceError(response.status, body, response.statusText));
165
+ }
166
+ function isAbort(error) {
167
+ return ((error instanceof DOMException && error.name === "AbortError") || (isRecord(error) && error.name === "AbortError"));
168
+ }
169
+ function isTimeout(error) {
170
+ return (error instanceof DOMException || isRecord(error)) && error.name === "TimeoutError";
171
+ }
172
+ /**
173
+ * Normalizes anything a service threw: a `ServiceFailure` or `ServiceError` as it is, an abort `aborted`, a timeout
174
+ * and fetch's `TypeError` `network`, an HTTP `status` by status (`kindOfStatus`), anything else `server` with the
175
+ * `unknown` reason.
176
+ */
177
+ export function toServiceError(error) {
178
+ if (error instanceof ServiceFailure)
179
+ return error.error;
180
+ if (isServiceError(error))
181
+ return error;
182
+ if (isTimeout(error))
183
+ return serviceError(ServiceErrorKind.network, "The request timed out.", {
184
+ reason: ErrorReason.timeout,
185
+ cause: error,
186
+ });
187
+ if (isAbort(error))
188
+ return serviceError(ServiceErrorKind.aborted, "The request was cancelled.", { cause: error });
189
+ if (error instanceof TypeError)
190
+ return serviceError(ServiceErrorKind.network, error.message, { cause: error });
191
+ if (isRecord(error) || error instanceof Error) {
192
+ const record = isRecord(error) ? error : {};
193
+ const status = isNumber(record.status) ? record.status : undefined;
194
+ const message = error instanceof Error ? error.message : (messageOfBody(error) ?? "Something went wrong.");
195
+ if (status !== undefined) {
196
+ const fromBody = httpServiceError(status, record.body ?? record.data ?? record, message);
197
+ return { ...fromBody, message: messageOfBody(record.body ?? record.data) ?? message, cause: error };
198
+ }
199
+ const fields = fieldErrorsOf(record);
200
+ return serviceError(fields ? ServiceErrorKind.validation : ServiceErrorKind.server, message, {
201
+ ...(fields ? { fields } : { reason: ErrorReason.unknown }),
202
+ cause: error,
203
+ });
204
+ }
205
+ return serviceError(ServiceErrorKind.server, text(error) ?? "Something went wrong.", {
206
+ reason: ErrorReason.unknown,
207
+ cause: error,
208
+ });
209
+ }
@@ -0,0 +1,9 @@
1
+ export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
2
+ export declare const isObject: (value: unknown) => value is object;
3
+ export declare const isString: (value: unknown) => value is string;
4
+ export declare const isNumber: (value: unknown) => value is number;
5
+ export declare const isBoolean: (value: unknown) => value is boolean;
6
+ export declare const isFunction: (value: unknown) => value is (...args: never[]) => unknown;
7
+ export declare const isText: (value: unknown) => value is string;
8
+ export declare function isOneOf<const Value extends string>(values: readonly Value[], value: unknown): value is Value;
9
+ export declare function valuesOf<const Values extends Record<string, string>>(values: Values): Values[keyof Values][];
@@ -0,0 +1,14 @@
1
+ import { ValueType } from "./constants.js";
2
+ export const isRecord = (value) => typeof value === ValueType.object && value !== null && !Array.isArray(value);
3
+ export const isObject = (value) => typeof value === ValueType.object && value !== null;
4
+ export const isString = (value) => typeof value === ValueType.string;
5
+ export const isNumber = (value) => typeof value === ValueType.number;
6
+ export const isBoolean = (value) => typeof value === ValueType.boolean;
7
+ export const isFunction = (value) => typeof value === ValueType.function;
8
+ export const isText = (value) => isString(value) && value !== "";
9
+ export function isOneOf(values, value) {
10
+ return values.some((member) => member === value);
11
+ }
12
+ export function valuesOf(values) {
13
+ return Object.values(values).filter((value) => isString(value));
14
+ }
@@ -0,0 +1,30 @@
1
+ import { RefusalKind } from "./constants.js";
2
+ export type Refusal = {
3
+ allowed: false;
4
+ reason: string;
5
+ };
6
+ export type Allowed = true | Refusal;
7
+ export declare function isRefusal(value: unknown): value is Refusal;
8
+ export declare function refuse(reason: string): Refusal;
9
+ /**
10
+ * Reads a check's answer: `true` and `undefined` allow, a `Refusal` keeps its reason, and `false` refuses with
11
+ * `fallback` (the dictionary's "not allowed" text), since it carries none of its own.
12
+ */
13
+ export declare function toAllowed(answer: boolean | Refusal | undefined, fallback: string): Allowed;
14
+ export declare function firstRefusal(...answers: Allowed[]): Allowed;
15
+ export declare function clause(reason: string): string;
16
+ /**
17
+ * Thrown by an App SDK controller when an action called from code or by an agent doesn't run. The message ends with
18
+ * the same `[refused:action]` or `[unavailable:action]` tag as Eskais UI's `action-refusal`, so its
19
+ * `parseActionRefusal` reads either, and UI SDK's agent bridge fails the step with the sentence.
20
+ */
21
+ export declare class AppActionRefusedError extends Error {
22
+ name: string;
23
+ readonly action: string;
24
+ readonly kind: RefusalKind;
25
+ readonly text: string;
26
+ constructor(action: string, kind: RefusalKind, text: string);
27
+ }
28
+ export declare function unavailableError(action: string, why: string): AppActionRefusedError;
29
+ export declare function refusedError(action: string, why?: string): AppActionRefusedError;
30
+ export declare function failedError(action: string, why: string, cause?: unknown): Error;
@@ -0,0 +1,53 @@
1
+ import { RefusalKind } from "./constants.js";
2
+ import { isRecord, isString } from "./guards.js";
3
+ export function isRefusal(value) {
4
+ return isRecord(value) && value.allowed === false && isString(value.reason);
5
+ }
6
+ export function refuse(reason) {
7
+ return { allowed: false, reason };
8
+ }
9
+ /**
10
+ * Reads a check's answer: `true` and `undefined` allow, a `Refusal` keeps its reason, and `false` refuses with
11
+ * `fallback` (the dictionary's "not allowed" text), since it carries none of its own.
12
+ */
13
+ export function toAllowed(answer, fallback) {
14
+ if (answer === undefined || answer === true)
15
+ return true;
16
+ if (answer === false)
17
+ return refuse(fallback);
18
+ return answer;
19
+ }
20
+ export function firstRefusal(...answers) {
21
+ return answers.find((answer) => answer !== true) ?? true;
22
+ }
23
+ const sentenceEnd = /[.!?…]\s*$/;
24
+ export function clause(reason) {
25
+ return reason.trim().replace(sentenceEnd, "");
26
+ }
27
+ /**
28
+ * Thrown by an App SDK controller when an action called from code or by an agent doesn't run. The message ends with
29
+ * the same `[refused:action]` or `[unavailable:action]` tag as Eskais UI's `action-refusal`, so its
30
+ * `parseActionRefusal` reads either, and UI SDK's agent bridge fails the step with the sentence.
31
+ */
32
+ export class AppActionRefusedError extends Error {
33
+ name = "ActionRefusedError";
34
+ action;
35
+ kind;
36
+ text;
37
+ constructor(action, kind, text) {
38
+ super(`${text} [${kind}:${action}]`);
39
+ this.action = action;
40
+ this.kind = kind;
41
+ this.text = text;
42
+ }
43
+ }
44
+ export function unavailableError(action, why) {
45
+ return new AppActionRefusedError(action, RefusalKind.unavailable, `${action} isn't available: ${clause(why)}.`);
46
+ }
47
+ export function refusedError(action, why) {
48
+ const text = why === undefined ? `${action} was refused.` : `${action} was refused: ${clause(why)}.`;
49
+ return new AppActionRefusedError(action, RefusalKind.refused, text);
50
+ }
51
+ export function failedError(action, why, cause) {
52
+ return new Error(`${action} failed: ${clause(why)}.`, { cause });
53
+ }
@@ -0,0 +1,75 @@
1
+ import type { Text } from "../i18n/locale.js";
2
+ export declare const DialogKind: {
3
+ readonly confirm: "confirm";
4
+ readonly alert: "alert";
5
+ readonly prompt: "prompt";
6
+ };
7
+ export type DialogKind = (typeof DialogKind)[keyof typeof DialogKind];
8
+ /** A dialog's words. Each may be a message (`msg("orders.approveTitle")`), worded in the `DataLayer`'s locale. */
9
+ export type DialogTexts = {
10
+ title: Text;
11
+ description?: Text;
12
+ /** The button that answers yes; the catalog's `confirm` (or `ok` for an alert) by default. */
13
+ confirmLabel?: Text;
14
+ };
15
+ export type ConfirmRequest = DialogTexts & {
16
+ /** Red, and the confirm button carries `data-agent-confirm`, so an agent shows a person before pressing it. */
17
+ destructive?: boolean;
18
+ /** The sentence an agent shows before confirming a destructive one: its description, or its title, by default. */
19
+ agentConfirm?: Text;
20
+ cancelLabel?: Text;
21
+ };
22
+ export type AlertRequest = DialogTexts;
23
+ export type PromptRequest = DialogTexts & {
24
+ /** The field's name; the title by default. */
25
+ label?: Text;
26
+ defaultValue?: string;
27
+ placeholder?: Text;
28
+ /** Confirming needs some text. Default false. */
29
+ required?: boolean;
30
+ cancelLabel?: Text;
31
+ };
32
+ export type DialogEntry = {
33
+ id: number;
34
+ kind: typeof DialogKind.confirm;
35
+ request: ConfirmRequest;
36
+ } | {
37
+ id: number;
38
+ kind: typeof DialogKind.alert;
39
+ request: AlertRequest;
40
+ } | {
41
+ id: number;
42
+ kind: typeof DialogKind.prompt;
43
+ request: PromptRequest;
44
+ };
45
+ /** What a dialog resolves with: `confirm` true or false, `prompt` the text or `null`, `alert` nothing. */
46
+ export type DialogAnswer = boolean | string | null | undefined;
47
+ export type DialogsSnapshot = {
48
+ /** The dialog on screen: one at a time, the others wait their turn in order. */
49
+ current: DialogEntry | undefined;
50
+ /** How many wait behind it. */
51
+ waiting: number;
52
+ /** The host that draws them: the first one attached. */
53
+ host: object | undefined;
54
+ };
55
+ export type Dialogs = {
56
+ confirm(request: ConfirmRequest): Promise<boolean>;
57
+ alert(request: AlertRequest): Promise<void>;
58
+ prompt(request: PromptRequest): Promise<string | null>;
59
+ };
60
+ export type DialogQueue = Dialogs & {
61
+ getSnapshot(): DialogsSnapshot;
62
+ subscribe(listener: () => void): () => void;
63
+ /** Answers a dialog and shows the next. A dialog answered twice keeps its first answer. */
64
+ settle(id: number, answer: DialogAnswer): void;
65
+ /** A component that draws the dialogs, by a token of its own; only the first one attached does. Returns detach. */
66
+ attach(host: object): () => void;
67
+ /** Answers every dialog as dismissed: `false`, `null` or nothing. */
68
+ clear(): void;
69
+ };
70
+ /**
71
+ * The queue behind `useDialogs`: `confirm`, `alert` and `prompt` return promises, and a host (`NavDialogs` in the
72
+ * blocks) draws the first one waiting. A request made while one is open waits for it; a dialog opened above another
73
+ * modal stacks over it.
74
+ */
75
+ export declare function createDialogQueue(): DialogQueue;
@@ -0,0 +1,66 @@
1
+ import { isString } from "../core/guards.js";
2
+ export const DialogKind = { confirm: "confirm", alert: "alert", prompt: "prompt" };
3
+ const dismissed = { [DialogKind.confirm]: false, [DialogKind.alert]: undefined, [DialogKind.prompt]: null };
4
+ /**
5
+ * The queue behind `useDialogs`: `confirm`, `alert` and `prompt` return promises, and a host (`NavDialogs` in the
6
+ * blocks) draws the first one waiting. A request made while one is open waits for it; a dialog opened above another
7
+ * modal stacks over it.
8
+ */
9
+ export function createDialogQueue() {
10
+ const waiting = [];
11
+ const hosts = [];
12
+ const listeners = new Set();
13
+ let nextId = 1;
14
+ let snapshot = { current: undefined, waiting: 0, host: undefined };
15
+ const publish = () => {
16
+ snapshot = { current: waiting[0]?.entry, waiting: Math.max(0, waiting.length - 1), host: hosts[0] };
17
+ for (const listener of listeners)
18
+ listener();
19
+ };
20
+ function open(entry) {
21
+ if (hosts.length === 0)
22
+ return Promise.reject(new Error("useDialogs needs a dialog host under the <DataLayer>: render <NavDialogs /> from the blocks."));
23
+ return new Promise((resolve) => {
24
+ waiting.push({ entry, resolve });
25
+ publish();
26
+ });
27
+ }
28
+ const id = () => nextId++;
29
+ return {
30
+ confirm: (request) => open({ id: id(), kind: DialogKind.confirm, request }).then((answer) => answer === true),
31
+ alert: (request) => open({ id: id(), kind: DialogKind.alert, request }).then(() => undefined),
32
+ prompt: (request) => open({ id: id(), kind: DialogKind.prompt, request }).then((answer) => (isString(answer) ? answer : null)),
33
+ getSnapshot: () => snapshot,
34
+ subscribe(listener) {
35
+ listeners.add(listener);
36
+ return () => {
37
+ listeners.delete(listener);
38
+ };
39
+ },
40
+ settle(target, answer) {
41
+ const index = waiting.findIndex((item) => item.entry.id === target);
42
+ if (index === -1)
43
+ return;
44
+ const [item] = waiting.splice(index, 1);
45
+ item?.resolve(answer);
46
+ publish();
47
+ },
48
+ attach(host) {
49
+ hosts.push(host);
50
+ publish();
51
+ return () => {
52
+ const index = hosts.indexOf(host);
53
+ if (index === -1)
54
+ return;
55
+ hosts.splice(index, 1);
56
+ publish();
57
+ };
58
+ },
59
+ clear() {
60
+ const all = waiting.splice(0);
61
+ for (const item of all)
62
+ item.resolve(dismissed[item.entry.kind]);
63
+ publish();
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,36 @@
1
+ import { DraftPersist } from "../core/constants.js";
2
+ import { type PreferencesStore } from "../view/preferences.js";
3
+ import { type Allowed } from "../core/refusal.js";
4
+ import type { RouterAdapter } from "../navigation/router.js";
5
+ export type DraftOptions = {
6
+ key: string | (() => string);
7
+ /** `DraftPersist.memory` (default) keeps it for this page's life; `local` in this browser; or a store of yours. */
8
+ persist?: DraftPersist | PreferencesStore;
9
+ /** How long a stored draft stays offered, in ms. Default a week. */
10
+ ttl?: number;
11
+ /** Asks before losing changes; resolves to true to leave them. */
12
+ ask?: () => Promise<boolean>;
13
+ };
14
+ export type StoredDraft<V> = {
15
+ values: V;
16
+ savedAt: Date;
17
+ };
18
+ export type DraftSnapshot = {
19
+ dirty: boolean;
20
+ stored: {
21
+ savedAt: Date;
22
+ } | undefined;
23
+ };
24
+ export type Draft<V> = {
25
+ key(): string;
26
+ getSnapshot(): DraftSnapshot;
27
+ subscribe(listener: () => void): () => void;
28
+ setDirty(dirty: boolean): void;
29
+ save(values: V): void;
30
+ load(): Promise<StoredDraft<V> | undefined>;
31
+ restore(): Allowed | StoredDraft<V>;
32
+ discard(): void;
33
+ guard(router: RouterAdapter | undefined, ask?: () => Promise<boolean>): () => void;
34
+ };
35
+ export declare function defineDraft<V>(options: DraftOptions): Draft<V>;
36
+ export declare function isStoredDraft<V>(value: Allowed | StoredDraft<V>): value is StoredDraft<V>;
@@ -0,0 +1,87 @@
1
+ import { assumeType } from "../core/assume.js";
2
+ import { DraftPersist, ValueType } from "../core/constants.js";
3
+ import { isFunction, isNumber, isRecord } from "../core/guards.js";
4
+ import { localPreferences, memoryPreferences } from "../view/preferences.js";
5
+ import { refuse } from "../core/refusal.js";
6
+ const sessionDrafts = memoryPreferences();
7
+ let localDrafts;
8
+ function storeOf(persist) {
9
+ if (persist === undefined || persist === DraftPersist.memory)
10
+ return sessionDrafts;
11
+ if (persist === DraftPersist.local) {
12
+ localDrafts ??= localPreferences("app-sdk-draft");
13
+ return localDrafts;
14
+ }
15
+ return persist;
16
+ }
17
+ export function defineDraft(options) {
18
+ const store = storeOf(options.persist);
19
+ const ttl = options.ttl ?? 7 * 86_400_000;
20
+ const key = () => (isFunction(options.key) ? options.key() : options.key);
21
+ let snapshot = { dirty: false, stored: undefined };
22
+ let stored;
23
+ const listeners = new Set();
24
+ const write = (next) => {
25
+ const merged = { ...snapshot, ...next };
26
+ if (merged.dirty === snapshot.dirty && merged.stored === snapshot.stored)
27
+ return;
28
+ snapshot = merged;
29
+ for (const listener of listeners)
30
+ listener();
31
+ };
32
+ const onBeforeUnload = (event) => {
33
+ if (snapshot.dirty)
34
+ event.preventDefault();
35
+ };
36
+ return {
37
+ key,
38
+ getSnapshot: () => snapshot,
39
+ subscribe(listener) {
40
+ listeners.add(listener);
41
+ return () => {
42
+ listeners.delete(listener);
43
+ };
44
+ },
45
+ setDirty: (dirty) => write({ dirty }),
46
+ save(values) {
47
+ void store.set(key(), { values, savedAt: Date.now() });
48
+ },
49
+ async load() {
50
+ const raw = await store.get(key());
51
+ if (!isRecord(raw) || !isNumber(raw.savedAt) || Date.now() - raw.savedAt > ttl) {
52
+ stored = undefined;
53
+ write({ stored: undefined });
54
+ return undefined;
55
+ }
56
+ // Workaround: the draft was written by `save` with this form's values, under this form's key.
57
+ stored = { values: assumeType(raw.values), savedAt: new Date(raw.savedAt) };
58
+ write({ stored: { savedAt: stored.savedAt } });
59
+ return stored;
60
+ },
61
+ restore() {
62
+ if (!stored)
63
+ return refuse("there is no draft");
64
+ const found = stored;
65
+ stored = undefined;
66
+ write({ stored: undefined });
67
+ return found;
68
+ },
69
+ discard() {
70
+ stored = undefined;
71
+ void store.set(key(), null);
72
+ write({ stored: undefined, dirty: false });
73
+ },
74
+ guard(router, ask = options.ask) {
75
+ const unblock = router?.block && ask ? router.block(() => snapshot.dirty, ask) : undefined;
76
+ const target = typeof window === ValueType.undefined ? undefined : window;
77
+ target?.addEventListener("beforeunload", onBeforeUnload);
78
+ return () => {
79
+ unblock?.();
80
+ target?.removeEventListener("beforeunload", onBeforeUnload);
81
+ };
82
+ },
83
+ };
84
+ }
85
+ export function isStoredDraft(value) {
86
+ return isRecord(value) && "values" in value && value.savedAt instanceof Date;
87
+ }
@@ -0,0 +1,21 @@
1
+ import { ErrorReason } from "../core/constants.js";
2
+ import { type ServiceError } from "../core/errors.js";
3
+ /**
4
+ * Turns what a transport threw into a `ServiceError`, or `undefined` when it isn't its shape, so the next adapter (and
5
+ * then `toServiceError`) reads it.
6
+ */
7
+ export type ErrorAdapter = (raw: unknown) => ServiceError | undefined;
8
+ /** A `ServiceError` for a reason, with the kind the rest of the App SDK reads: `appError(ErrorReason.sessionExpired)`. */
9
+ export declare function appError(reason: ErrorReason, message?: string, extra?: Partial<Omit<ServiceError, "kind" | "message" | "reason">>): ServiceError;
10
+ /**
11
+ * A fetch `Response` thrown as it is (`if (!response.ok) throw response`): its status classifies it. The body isn't
12
+ * read, since it may be read already; throw `await problemDetailError(response)` for its message and field errors.
13
+ */
14
+ export declare const responseErrors: ErrorAdapter;
15
+ /**
16
+ * Firebase's errors: a callable function's `HttpsError` (`functions/unauthenticated`), Auth's
17
+ * (`auth/requires-recent-login` is `session-expired`, `auth/network-request-failed` is `network`) and Firestore's.
18
+ * A callable's `details.reason` wins when it's an `ErrorReason`, and is kept as the `code` otherwise
19
+ * (`details: { reason: "card_declined" }`); `details` may carry field errors.
20
+ */
21
+ export declare const firebaseErrors: ErrorAdapter;