@eskais/app-sdk 0.0.0-stage → 0.1.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 (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -2
  3. package/dist/action/action.d.ts +74 -0
  4. package/dist/action/action.js +106 -0
  5. package/dist/cli/cli.d.ts +2 -0
  6. package/dist/cli/cli.js +51 -0
  7. package/dist/cli/routes.d.ts +17 -0
  8. package/dist/cli/routes.js +36 -0
  9. package/dist/core/assume.d.ts +1 -0
  10. package/dist/core/assume.js +8 -0
  11. package/dist/core/constants.d.ts +302 -0
  12. package/dist/core/constants.js +156 -0
  13. package/dist/core/contracts.d.ts +100 -0
  14. package/dist/core/contracts.js +3 -0
  15. package/dist/core/data-labels.d.ts +196 -0
  16. package/dist/core/data-labels.js +345 -0
  17. package/dist/core/errors.d.ts +46 -0
  18. package/dist/core/errors.js +166 -0
  19. package/dist/core/guards.d.ts +9 -0
  20. package/dist/core/guards.js +14 -0
  21. package/dist/core/refusal.d.ts +30 -0
  22. package/dist/core/refusal.js +53 -0
  23. package/dist/draft/draft.d.ts +36 -0
  24. package/dist/draft/draft.js +87 -0
  25. package/dist/export/csv.d.ts +25 -0
  26. package/dist/export/csv.js +59 -0
  27. package/dist/import/csv-parse.d.ts +11 -0
  28. package/dist/import/csv-parse.js +70 -0
  29. package/dist/import/import.d.ts +102 -0
  30. package/dist/import/import.js +263 -0
  31. package/dist/index.d.ts +31 -0
  32. package/dist/index.js +30 -0
  33. package/dist/navigation/nav.d.ts +119 -0
  34. package/dist/navigation/nav.js +278 -0
  35. package/dist/navigation/router.d.ts +81 -0
  36. package/dist/navigation/router.js +249 -0
  37. package/dist/navigation/shortcuts.d.ts +37 -0
  38. package/dist/navigation/shortcuts.js +93 -0
  39. package/dist/next/index.d.ts +3 -0
  40. package/dist/next/index.js +3 -0
  41. package/dist/next/screen-hydration.d.ts +12 -0
  42. package/dist/next/screen-hydration.js +26 -0
  43. package/dist/next/screen.d.ts +25 -0
  44. package/dist/next/screen.js +44 -0
  45. package/dist/next/server/handler.d.ts +39 -0
  46. package/dist/next/server/handler.js +190 -0
  47. package/dist/next/server/index.d.ts +5 -0
  48. package/dist/next/server/index.js +5 -0
  49. package/dist/next/server/page.d.ts +57 -0
  50. package/dist/next/server/page.js +103 -0
  51. package/dist/next/server/prefetch.d.ts +29 -0
  52. package/dist/next/server/prefetch.js +97 -0
  53. package/dist/next/server/session.d.ts +12 -0
  54. package/dist/next/server/session.js +10 -0
  55. package/dist/next/use-next-router.d.ts +21 -0
  56. package/dist/next/use-next-router.js +104 -0
  57. package/dist/react/data-layer.d.ts +31 -0
  58. package/dist/react/data-layer.js +31 -0
  59. package/dist/react/hooks/use-action.d.ts +12 -0
  60. package/dist/react/hooks/use-action.js +67 -0
  61. package/dist/react/hooks/use-better-auth.d.ts +12 -0
  62. package/dist/react/hooks/use-better-auth.js +11 -0
  63. package/dist/react/hooks/use-draft.d.ts +5 -0
  64. package/dist/react/hooks/use-draft.js +17 -0
  65. package/dist/react/hooks/use-nav.d.ts +17 -0
  66. package/dist/react/hooks/use-nav.js +34 -0
  67. package/dist/react/hooks/use-resource.d.ts +69 -0
  68. package/dist/react/hooks/use-resource.js +218 -0
  69. package/dist/react/hooks/use-view.d.ts +6 -0
  70. package/dist/react/hooks/use-view.js +24 -0
  71. package/dist/react/index.d.ts +8 -0
  72. package/dist/react/index.js +8 -0
  73. package/dist/react/keys.d.ts +51 -0
  74. package/dist/react/keys.js +67 -0
  75. package/dist/resource/form-schema.d.ts +11 -0
  76. package/dist/resource/form-schema.js +51 -0
  77. package/dist/resource/relations.d.ts +99 -0
  78. package/dist/resource/relations.js +194 -0
  79. package/dist/resource/resource-relations.d.ts +44 -0
  80. package/dist/resource/resource-relations.js +141 -0
  81. package/dist/resource/resource-schema.d.ts +9 -0
  82. package/dist/resource/resource-schema.js +73 -0
  83. package/dist/resource/resource-types.d.ts +281 -0
  84. package/dist/resource/resource-types.js +1 -0
  85. package/dist/resource/resource.d.ts +11 -0
  86. package/dist/resource/resource.js +354 -0
  87. package/dist/resource/schema.d.ts +57 -0
  88. package/dist/resource/schema.js +115 -0
  89. package/dist/services/from-page-source.d.ts +15 -0
  90. package/dist/services/from-page-source.js +27 -0
  91. package/dist/services/memory-query.d.ts +8 -0
  92. package/dist/services/memory-query.js +165 -0
  93. package/dist/services/memory-service.d.ts +33 -0
  94. package/dist/services/memory-service.js +291 -0
  95. package/dist/services/rest-service.d.ts +62 -0
  96. package/dist/services/rest-service.js +220 -0
  97. package/dist/services/rng.d.ts +9 -0
  98. package/dist/services/rng.js +22 -0
  99. package/dist/services/spring-service.d.ts +58 -0
  100. package/dist/services/spring-service.js +132 -0
  101. package/dist/session/better-auth.d.ts +83 -0
  102. package/dist/session/better-auth.js +86 -0
  103. package/dist/session/session.d.ts +45 -0
  104. package/dist/session/session.js +36 -0
  105. package/dist/view/preferences.d.ts +35 -0
  106. package/dist/view/preferences.js +93 -0
  107. package/dist/view/view-types.d.ts +122 -0
  108. package/dist/view/view-types.js +1 -0
  109. package/dist/view/view-url.d.ts +7 -0
  110. package/dist/view/view-url.js +54 -0
  111. package/dist/view/view.d.ts +4 -0
  112. package/dist/view/view.js +392 -0
  113. package/package.json +85 -4
@@ -0,0 +1,166 @@
1
+ import { 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
+ function fieldEntry(entry) {
56
+ if (!isRecord(entry))
57
+ return undefined;
58
+ const path = text(entry.field) ??
59
+ text(entry.path) ??
60
+ text(entry.name) ??
61
+ text(entry.pointer) ??
62
+ text(entry.property) ??
63
+ text(entry.propertyPath);
64
+ const message = text(entry.defaultMessage) ?? text(entry.message) ?? text(entry.reason) ?? text(entry.detail);
65
+ if (path === undefined || message === undefined)
66
+ return undefined;
67
+ const code = text(entry.code);
68
+ return {
69
+ path: path.replace(/^\/(?:data\/attributes\/)?/u, "").replaceAll("/", "."),
70
+ message,
71
+ ...(code === undefined ? {} : { code }),
72
+ };
73
+ }
74
+ /**
75
+ * Field errors from the shapes servers send: Spring's `errors`/`fieldErrors` (`field`, `defaultMessage`) and
76
+ * constraint violations (`propertyPath`), RFC 9457
77
+ * `invalid-params` or `violations`, JSON:API `errors[].source.pointer`, and `{ fieldErrors: { name: message } }`.
78
+ */
79
+ export function fieldErrorsOf(body) {
80
+ if (!isRecord(body))
81
+ return undefined;
82
+ const lists = [body.errors, body.fieldErrors, body["invalid-params"], body.violations];
83
+ const found = [];
84
+ for (const list of lists) {
85
+ if (Array.isArray(list)) {
86
+ const entries = list;
87
+ for (const entry of entries) {
88
+ const source = isRecord(entry) && isRecord(entry.source) ? { ...entry, ...entry.source } : entry;
89
+ const field = fieldEntry(source);
90
+ if (field)
91
+ found.push(field);
92
+ }
93
+ }
94
+ else if (isRecord(list)) {
95
+ for (const [path, message] of Object.entries(list)) {
96
+ const values = Array.isArray(message) ? message : [message];
97
+ const first = values[0];
98
+ if (isString(first))
99
+ found.push({ path, message: first });
100
+ }
101
+ }
102
+ }
103
+ return found.length > 0 ? found : undefined;
104
+ }
105
+ function messageOfBody(body) {
106
+ if (!isRecord(body))
107
+ return text(body);
108
+ return text(body.detail) ?? text(body.message) ?? text(body.title) ?? text(body.error);
109
+ }
110
+ export function httpServiceError(status, body, statusText) {
111
+ const kind = kindOfStatus(status);
112
+ const fields = fieldErrorsOf(body);
113
+ const message = messageOfBody(body) ?? text(statusText) ?? `Request failed with status ${String(status)}`;
114
+ return serviceError(kind, message, {
115
+ status,
116
+ ...(fields ? { fields } : {}),
117
+ ...(kind === ServiceErrorKind.conflict && isRecord(body) && "current" in body ? { current: body.current } : {}),
118
+ cause: body,
119
+ });
120
+ }
121
+ export async function problemDetailError(response) {
122
+ let body;
123
+ try {
124
+ const raw = await response.text();
125
+ body = raw === "" ? undefined : JSON.parse(raw);
126
+ }
127
+ catch {
128
+ body = undefined;
129
+ }
130
+ return new ServiceFailure(httpServiceError(response.status, body, response.statusText));
131
+ }
132
+ function isAbort(error) {
133
+ return ((error instanceof DOMException && (error.name === "AbortError" || error.name === "TimeoutError")) ||
134
+ (isRecord(error) && error.name === "AbortError"));
135
+ }
136
+ /**
137
+ * Normalizes anything a service threw: a `ServiceFailure` or `ServiceError` comes back as it is, an abort is
138
+ * `aborted`, fetch's `TypeError` is `network`, an object with an HTTP `status` maps by status (`400`/`422`
139
+ * validation, `401`/`403` forbidden, `404` not found, `409`/`412` conflict, the rest server), and anything else is a
140
+ * `server` error with its message.
141
+ */
142
+ export function toServiceError(error) {
143
+ if (error instanceof ServiceFailure)
144
+ return error.error;
145
+ if (isServiceError(error))
146
+ return error;
147
+ if (isAbort(error))
148
+ return serviceError(ServiceErrorKind.aborted, "The request was cancelled.", { cause: error });
149
+ if (error instanceof TypeError)
150
+ return serviceError(ServiceErrorKind.network, error.message, { cause: error });
151
+ if (isRecord(error) || error instanceof Error) {
152
+ const record = isRecord(error) ? error : {};
153
+ const status = isNumber(record.status) ? record.status : undefined;
154
+ const message = error instanceof Error ? error.message : (messageOfBody(error) ?? "Something went wrong.");
155
+ if (status !== undefined) {
156
+ const fromBody = httpServiceError(status, record.body ?? record.data ?? record, message);
157
+ return { ...fromBody, message: messageOfBody(record.body ?? record.data) ?? message, cause: error };
158
+ }
159
+ const fields = fieldErrorsOf(record);
160
+ return serviceError(fields ? ServiceErrorKind.validation : ServiceErrorKind.server, message, {
161
+ ...(fields ? { fields } : {}),
162
+ cause: error,
163
+ });
164
+ }
165
+ return serviceError(ServiceErrorKind.server, text(error) ?? "Something went wrong.", { cause: error });
166
+ }
@@ -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,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,25 @@
1
+ import type { Query } from "../core/contracts.js";
2
+ import type { RelationContext } from "../resource/relations.js";
3
+ import { type Refusal } from "../core/refusal.js";
4
+ import type { Resource } from "../resource/resource.js";
5
+ export type CsvColumn<T> = {
6
+ key: string;
7
+ label: string;
8
+ format?: (row: T) => string;
9
+ };
10
+ /** Rows as CSV, with a header of the columns' labels and CRLF line ends (RFC 4180). */
11
+ export declare function toCsv<T>(rows: readonly T[], columns: readonly CsvColumn<T>[]): string;
12
+ export type CsvExportOptions<T> = {
13
+ columns: readonly CsvColumn<T>[];
14
+ context: RelationContext;
15
+ /** The relations the columns reach (`customer.name`), read in batches with each page. Default: the columns' keys. */
16
+ paths?: readonly string[];
17
+ /** Rows per request. Default 500. */
18
+ pageSize?: number;
19
+ onProgress?: (done: number, total: number | undefined) => void;
20
+ };
21
+ /**
22
+ * Exports what a query matches as CSV in the browser, page after page, up to the resource's `exportLimit`. Over the
23
+ * limit it answers with a refusal before reading the rest: a server export (`service.export`) is needed then.
24
+ */
25
+ export declare function exportCsv<T, Id, F>(resource: Resource<T, Id, F>, query: Omit<Query<F>, "position" | "size">, options: CsvExportOptions<T>, tooLarge: (count: number, limit: number) => string): Promise<string | Refusal>;
@@ -0,0 +1,59 @@
1
+ import { isBoolean, isNumber, isString } from "../core/guards.js";
2
+ import { valueAt } from "../services/memory-query.js";
3
+ import { refuse } from "../core/refusal.js";
4
+ function cellText(value) {
5
+ if (value === undefined || value === null)
6
+ return "";
7
+ if (isString(value))
8
+ return value;
9
+ if (isNumber(value) || isBoolean(value))
10
+ return String(value);
11
+ if (Array.isArray(value))
12
+ return value.map(cellText).join(", ");
13
+ if (value instanceof Date)
14
+ return value.toISOString();
15
+ return JSON.stringify(value);
16
+ }
17
+ const needsQuotes = /[",\r\n]/u;
18
+ // Security: a cell starting with these runs as a formula in spreadsheet apps (CSV injection), so it gets a quote first.
19
+ const formulaStart = /^[=+\-@\t\r]/u;
20
+ function escapeCell(text) {
21
+ const safe = formulaStart.test(text) ? `'${text}` : text;
22
+ return needsQuotes.test(safe) ? `"${safe.replaceAll('"', '""')}"` : safe;
23
+ }
24
+ /** Rows as CSV, with a header of the columns' labels and CRLF line ends (RFC 4180). */
25
+ export function toCsv(rows, columns) {
26
+ const header = columns.map((column) => escapeCell(column.label)).join(",");
27
+ const lines = rows.map((row) => columns
28
+ .map((column) => escapeCell(column.format ? column.format(row) : cellText(valueAt(row, column.key))))
29
+ .join(","));
30
+ return [header, ...lines].join("\r\n");
31
+ }
32
+ /**
33
+ * Exports what a query matches as CSV in the browser, page after page, up to the resource's `exportLimit`. Over the
34
+ * limit it answers with a refusal before reading the rest: a server export (`service.export`) is needed then.
35
+ */
36
+ export async function exportCsv(resource, query, options, tooLarge) {
37
+ const limit = resource.exportLimit;
38
+ const size = Math.min(options.pageSize ?? 500, resource.service.capabilities.maxPageSize ?? Number.POSITIVE_INFINITY);
39
+ const rows = [];
40
+ let page = 1;
41
+ let total;
42
+ for (;;) {
43
+ // Perf: pages are read one after another, so a large export doesn't flood the server.
44
+ // oxlint-disable-next-line no-await-in-loop -- each page waits for the one before, by design
45
+ const result = await resource.listWith({ ...query, size, position: { page } }, options.context, options.paths ?? options.columns.map((column) => column.key));
46
+ total = result.total ?? total;
47
+ if (total !== undefined && total > limit)
48
+ return refuse(tooLarge(total, limit));
49
+ rows.push(...result.items);
50
+ options.onProgress?.(rows.length, total);
51
+ if (rows.length > limit)
52
+ return refuse(tooLarge(rows.length, limit));
53
+ const more = result.hasMore ?? (total === undefined ? result.items.length === size : rows.length < total);
54
+ if (!more || result.items.length === 0)
55
+ break;
56
+ page += 1;
57
+ }
58
+ return toCsv(rows, options.columns);
59
+ }
@@ -0,0 +1,11 @@
1
+ /** A CSV file read: its header row and the rows under it, each as text cells. */
2
+ export type CsvTable = {
3
+ header: string[];
4
+ rows: string[][];
5
+ };
6
+ /**
7
+ * Reads CSV (RFC 4180): quoted cells with `""` for a quote and line breaks inside, CRLF or LF, a byte order mark,
8
+ * and the delimiter the first line uses most (a comma, the semicolon spreadsheets write in many locales, or a tab).
9
+ * Blank lines are skipped.
10
+ */
11
+ export declare function parseCsv(input: string, delimiter?: string): CsvTable;
@@ -0,0 +1,70 @@
1
+ const delimiters = [",", ";", "\t"];
2
+ function delimiterOf(text) {
3
+ const line = text.slice(0, text.search(/\r?\n|$/u));
4
+ let best = delimiters[0];
5
+ let most = -1;
6
+ for (const candidate of delimiters) {
7
+ const found = line.split(candidate).length - 1;
8
+ if (found > most) {
9
+ best = candidate;
10
+ most = found;
11
+ }
12
+ }
13
+ return best;
14
+ }
15
+ /**
16
+ * Reads CSV (RFC 4180): quoted cells with `""` for a quote and line breaks inside, CRLF or LF, a byte order mark,
17
+ * and the delimiter the first line uses most (a comma, the semicolon spreadsheets write in many locales, or a tab).
18
+ * Blank lines are skipped.
19
+ */
20
+ export function parseCsv(input, delimiter = delimiterOf(input)) {
21
+ const text = input.startsWith("") ? input.slice(1) : input;
22
+ const records = [];
23
+ let record = [];
24
+ let cell = "";
25
+ let quoted = false;
26
+ let index = 0;
27
+ const endCell = () => {
28
+ record.push(cell);
29
+ cell = "";
30
+ };
31
+ const endRecord = () => {
32
+ endCell();
33
+ if (record.length > 1 || record[0] !== "")
34
+ records.push(record);
35
+ record = [];
36
+ };
37
+ while (index < text.length) {
38
+ const char = text[index];
39
+ if (quoted) {
40
+ if (char === '"' && text[index + 1] === '"') {
41
+ cell += '"';
42
+ index += 2;
43
+ continue;
44
+ }
45
+ if (char === '"')
46
+ quoted = false;
47
+ else
48
+ cell += char;
49
+ index += 1;
50
+ continue;
51
+ }
52
+ if (char === '"' && cell === "")
53
+ quoted = true;
54
+ else if (char === delimiter)
55
+ endCell();
56
+ else if (char === "\n")
57
+ endRecord();
58
+ else if (char === "\r") {
59
+ if (text[index + 1] !== "\n")
60
+ endRecord();
61
+ }
62
+ else
63
+ cell += char;
64
+ index += 1;
65
+ }
66
+ if (cell !== "" || record.length > 0)
67
+ endRecord();
68
+ const [header = [], ...rows] = records;
69
+ return { header: header.map((name) => name.trim()), rows };
70
+ }
@@ -0,0 +1,102 @@
1
+ import { FileFormat, ImportMode } from "../core/constants.js";
2
+ import type { CallContext } from "../core/contracts.js";
3
+ import { type ServiceError } from "../core/errors.js";
4
+ import { type Allowed } from "../core/refusal.js";
5
+ import type { ResolvedField, Resource } from "../resource/resource.js";
6
+ import { type StandardIssue } from "../resource/schema.js";
7
+ import { type RelationContext } from "../resource/relations.js";
8
+ import { type CsvTable } from "./csv-parse.js";
9
+ export type ImportChunkResult = {
10
+ ok: number;
11
+ failed: {
12
+ index: number;
13
+ error: ServiceError;
14
+ }[];
15
+ };
16
+ export type ImportOptions<T> = {
17
+ /** `FileFormat.csv`, the one read in the browser today. */
18
+ formats?: readonly FileFormat[];
19
+ /** Other names a column may have, to a field: `{ "E-mail": "email" }`. */
20
+ match?: Readonly<Record<string, string>>;
21
+ /** `ImportMode.create` (default) adds every row; `ImportMode.upsert` updates the record whose `key` matches. */
22
+ mode?: ImportMode;
23
+ /** The natural key for `ImportMode.upsert`, like `email`. */
24
+ key?: string;
25
+ /** Rows per batch. Default 100. */
26
+ chunk?: number;
27
+ /** The fields a file may fill; the create form's by default. */
28
+ fields?: readonly string[];
29
+ /** Saves one batch your way (a bulk endpoint); by default each row is created through the service. */
30
+ run?: (rows: Partial<T>[], context: CallContext) => Promise<ImportChunkResult>;
31
+ };
32
+ /** Which field each column goes to, by the column's header; `undefined` leaves the column out. */
33
+ export type ImportMapping = Readonly<Record<string, string | undefined>>;
34
+ export type ImportIssue = {
35
+ field: string;
36
+ message: string;
37
+ };
38
+ /** A row read and checked: its line in the file (the header is line 1), its values and what's wrong with them. */
39
+ /**
40
+ * A row read and checked: its line in the file (the header is line 1), its values, what's wrong with them, and the
41
+ * titles of the records its relation fields point at (`{ countryId: "España" }`).
42
+ */
43
+ export type ImportRow<T> = {
44
+ line: number;
45
+ values: Partial<T>;
46
+ issues: readonly ImportIssue[];
47
+ titles?: Readonly<Record<string, string>>;
48
+ };
49
+ export type ImportCheckOptions = {
50
+ /** The text of a schema issue, in the app's language; the schema's own message by default. */
51
+ describe?: (issue: StandardIssue, values: unknown) => string;
52
+ /** The text for an id no related record has. */
53
+ missing?: (id: string) => string;
54
+ /** Reads the related records, one `getMany` per relation; without it, relation ids aren't checked. */
55
+ context?: RelationContext;
56
+ };
57
+ export type ImportPreview<T> = {
58
+ rows: readonly ImportRow<T>[];
59
+ valid: readonly ImportRow<T>[];
60
+ invalid: readonly ImportRow<T>[];
61
+ };
62
+ export type ImportSummary = {
63
+ total: number;
64
+ created: number;
65
+ updated: number;
66
+ failed: readonly {
67
+ line: number;
68
+ error: ServiceError;
69
+ }[];
70
+ /** Stopped by the signal: the rows after the batch that was running weren't sent. */
71
+ cancelled: boolean;
72
+ };
73
+ export type ImportRunOptions = CallContext & {
74
+ onProgress?: (done: number, total: number) => void;
75
+ };
76
+ export type Import<T, Id = unknown, F = unknown> = {
77
+ readonly resource: Resource<T, Id, F>;
78
+ readonly options: ImportOptions<T>;
79
+ readonly formats: readonly FileFormat[];
80
+ readonly mode: ImportMode;
81
+ /** Whether a file of this format can be read. */
82
+ checkFormat(format: FileFormat): Allowed;
83
+ fields(): ResolvedField<T>[];
84
+ read(text: string): CsvTable;
85
+ /** Pairs columns with fields by key, label and `match`, ignoring case, accents and punctuation. */
86
+ match(header: readonly string[]): ImportMapping;
87
+ /** The rows as records of the fields they go to, each text turned into the field's type. */
88
+ recordsOf(table: CsvTable, mapping: ImportMapping): Record<string, unknown>[];
89
+ /** Checks records against the resource's create schema; `firstLine` numbers them (2 under a header). */
90
+ check(records: readonly unknown[], firstLine?: number, options?: ImportCheckOptions): Promise<ImportPreview<T>>;
91
+ /** Saves the rows in batches, reporting progress, and stops between batches once `signal` aborts. */
92
+ run(rows: readonly ImportRow<T>[], options: ImportRunOptions): Promise<ImportSummary>;
93
+ /** The invalid rows as CSV, with a column that says what's wrong, to fix and import again. */
94
+ errorsCsv(invalid: readonly ImportRow<T>[], errorColumn: string, lineColumn: string): string;
95
+ };
96
+ /** Rows that don't pass, in a sentence: how many, and the first three with their fields. */
97
+ export declare function invalidRowsText(invalid: readonly ImportRow<unknown>[]): string;
98
+ /**
99
+ * Declares how a resource imports rows: read a CSV file, pair its columns with fields, check every row with the
100
+ * resource's create schema, and save the valid ones in batches, with progress and cancellation (the `signal`).
101
+ */
102
+ export declare function defineImport<T, Id, F>(resource: Resource<T, Id, F>, options?: ImportOptions<T>): Import<T, Id, F>;