@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,263 @@
1
+ import { FieldKind, FileFormat, FormStage, ImportMode, JsonType, RelationKind, ServiceErrorKind, } from "../core/constants.js";
2
+ import { toServiceError } from "../core/errors.js";
3
+ import { isNumber, isObject, isRecord, isString } from "../core/guards.js";
4
+ import { refuse } from "../core/refusal.js";
5
+ import { toCsv } from "../export/csv.js";
6
+ import { formSchemaOf } from "../resource/form-schema.js";
7
+ import { issuePath, validate } from "../resource/schema.js";
8
+ import { resolveRelations } from "../resource/relations.js";
9
+ import { valueAt } from "../services/memory-query.js";
10
+ import { parseCsv } from "./csv-parse.js";
11
+ const Saved = { created: "created", updated: "updated" };
12
+ const plain = (text) => text
13
+ .normalize("NFD")
14
+ .replace(/\p{M}/gu, "")
15
+ .toLowerCase()
16
+ .replace(/[^\p{L}\p{N}]/gu, "");
17
+ const truthy = new Set(["true", "1", "yes", "y", "si", "x", "on"]);
18
+ const falsy = new Set(["false", "0", "no", "n", "off"]);
19
+ function convert(field, text) {
20
+ const value = text.trim();
21
+ if (value === "")
22
+ return undefined;
23
+ const list = field.multiple || field.kind === FieldKind.tags || field.valueType === JsonType.array;
24
+ if (list)
25
+ return value
26
+ .split(/[;|,]/u)
27
+ .map((entry) => entry.trim())
28
+ .filter((entry) => entry !== "");
29
+ const numeric = field.valueType === JsonType.number ||
30
+ (field.kind === FieldKind.resource && /^-?\d+$/u.test(value)) ||
31
+ field.valueType === JsonType.integer ||
32
+ field.kind === FieldKind.number ||
33
+ field.kind === FieldKind.currency;
34
+ if (numeric) {
35
+ const number = Number(value.replace(/\s/gu, ""));
36
+ return Number.isNaN(number) ? value : number;
37
+ }
38
+ if (field.valueType === JsonType.boolean || field.kind === FieldKind.switch || field.kind === FieldKind.checkbox) {
39
+ const word = plain(value);
40
+ return truthy.has(word) ? true : falsy.has(word) ? false : value;
41
+ }
42
+ return value;
43
+ }
44
+ async function settleChunk(rows, save) {
45
+ return Promise.all(rows.map(async (row) => {
46
+ try {
47
+ return { line: row.line, outcome: { ok: true, value: await save(row) } };
48
+ }
49
+ catch (error) {
50
+ return { line: row.line, outcome: { ok: false, error } };
51
+ }
52
+ }));
53
+ }
54
+ /** Rows that don't pass, in a sentence: how many, and the first three with their fields. */
55
+ export function invalidRowsText(invalid) {
56
+ const first = invalid
57
+ .slice(0, 3)
58
+ .map((row) => `row ${String(row.line)} (${row.issues.map((issue) => (issue.field === "" ? issue.message : `${issue.field}: ${issue.message}`)).join(", ")})`);
59
+ const count = invalid.length === 1 ? "1 row isn't valid" : `${String(invalid.length)} rows aren't valid`;
60
+ return `${count}: ${first.join("; ")}`;
61
+ }
62
+ /**
63
+ * Declares how a resource imports rows: read a CSV file, pair its columns with fields, check every row with the
64
+ * resource's create schema, and save the valid ones in batches, with progress and cancellation (the `signal`).
65
+ */
66
+ export function defineImport(resource, options = {}) {
67
+ const formats = options.formats ?? [FileFormat.csv];
68
+ const mode = options.mode ?? ImportMode.create;
69
+ const chunk = Math.max(1, options.chunk ?? 100);
70
+ const fields = () => {
71
+ const all = resource.fields(FormStage.create).filter((field) => !field.readOnly(undefined));
72
+ return options.fields ? all.filter((field) => options.fields?.includes(field.key) === true) : all;
73
+ };
74
+ async function saveRow(row, context) {
75
+ if (mode === ImportMode.upsert && options.key !== undefined) {
76
+ const keyValue = valueAt(row.values, options.key);
77
+ if (keyValue !== undefined) {
78
+ const found = await resource.service.list({
79
+ filter: resource.filterOf({ [options.key]: keyValue }),
80
+ sort: [],
81
+ size: 1,
82
+ position: { page: 1 },
83
+ }, context);
84
+ const existing = found.items[0];
85
+ if (existing !== undefined) {
86
+ await resource.service.update(resource.idOf(existing), row.values, {
87
+ ...context,
88
+ version: resource.service.versionOf?.(existing),
89
+ });
90
+ return Saved.updated;
91
+ }
92
+ }
93
+ }
94
+ await resource.service.create(row.values, context);
95
+ return Saved.created;
96
+ }
97
+ return {
98
+ resource,
99
+ options,
100
+ formats,
101
+ mode,
102
+ checkFormat(format) {
103
+ if (format !== FileFormat.csv)
104
+ return refuse(`${format} files can't be read in the browser yet`);
105
+ return formats.includes(format) ? true : refuse(`this import takes ${formats.join(", ")} files`);
106
+ },
107
+ fields,
108
+ read: (text) => parseCsv(text),
109
+ match(header) {
110
+ const aliases = new Map(Object.entries(options.match ?? {}).map(([name, key]) => [plain(name), key]));
111
+ const known = fields();
112
+ const taken = new Set();
113
+ return Object.fromEntries(header.map((name) => {
114
+ const wanted = plain(name);
115
+ const key = aliases.get(wanted) ??
116
+ known.find((field) => plain(field.key) === wanted || plain(field.label) === wanted)?.key;
117
+ if (key === undefined || taken.has(key))
118
+ return [name, undefined];
119
+ taken.add(key);
120
+ return [name, key];
121
+ }));
122
+ },
123
+ recordsOf(table, mapping) {
124
+ const byKey = new Map(fields().map((field) => [field.key, field]));
125
+ return table.rows.map((cells) => {
126
+ const record = {};
127
+ for (const [index, name] of table.header.entries()) {
128
+ const key = mapping[name];
129
+ const field = key === undefined ? undefined : byKey.get(key);
130
+ if (key === undefined || field === undefined)
131
+ continue;
132
+ const value = convert(field, cells[index] ?? "");
133
+ if (value !== undefined)
134
+ record[key] = value;
135
+ }
136
+ return record;
137
+ });
138
+ },
139
+ async check(records, firstLine = 2, checking = {}) {
140
+ const describe = checking.describe ?? ((issue) => issue.message);
141
+ const schema = formSchemaOf(resource, FormStage.create, fields().map((field) => field.key));
142
+ const checked = await Promise.all(records.map(async (record, index) => {
143
+ const line = index + firstLine;
144
+ if (!isRecord(record))
145
+ return { line, values: {}, issues: [{ field: "", message: "not a record" }] };
146
+ if (!schema)
147
+ return { line, values: resource.inputOf(record), issues: [] };
148
+ const result = await validate(schema, record);
149
+ if (result.issues === undefined)
150
+ return { line, values: resource.inputOf(result.value), issues: [] };
151
+ const issues = result.issues.map((issue) => ({ field: issuePath(issue), message: describe(issue, record) }));
152
+ return { line, values: resource.inputOf(record), issues };
153
+ }));
154
+ const rows = checking.context
155
+ ? await withRelated(fields(), checked, checking.context, checking.missing ?? ((id) => `no record ${id}`))
156
+ : checked;
157
+ return {
158
+ rows,
159
+ valid: rows.filter((row) => row.issues.length === 0),
160
+ invalid: rows.filter((row) => row.issues.length > 0),
161
+ };
162
+ },
163
+ async run(rows, { onProgress, ...context }) {
164
+ const failed = [];
165
+ const summary = { total: rows.length, created: 0, updated: 0, failed };
166
+ let done = 0;
167
+ onProgress?.(0, rows.length);
168
+ for (let start = 0; start < rows.length; start += chunk) {
169
+ if (context.signal.aborted)
170
+ return { ...summary, cancelled: true };
171
+ const batch = rows.slice(start, start + chunk);
172
+ if (options.run) {
173
+ try {
174
+ // Perf: one batch at a time, so a large file doesn't flood the server.
175
+ // oxlint-disable-next-line no-await-in-loop -- each batch waits for the one before, by design
176
+ const result = await options.run(batch.map((row) => row.values), context);
177
+ summary.created += result.ok;
178
+ for (const failure of result.failed)
179
+ summary.failed.push({ line: batch[failure.index]?.line ?? 0, error: failure.error });
180
+ }
181
+ catch (error) {
182
+ const failure = toServiceError(error);
183
+ if (failure.kind === ServiceErrorKind.aborted)
184
+ return { ...summary, cancelled: true };
185
+ for (const row of batch)
186
+ summary.failed.push({ line: row.line, error: failure });
187
+ }
188
+ }
189
+ else {
190
+ // oxlint-disable-next-line no-await-in-loop -- each batch waits for the one before, by design
191
+ const outcomes = await settleChunk(batch, (row) => saveRow(row, context));
192
+ for (const { outcome, line } of outcomes) {
193
+ if (outcome.ok)
194
+ summary[outcome.value] += 1;
195
+ else
196
+ summary.failed.push({ line, error: toServiceError(outcome.error) });
197
+ }
198
+ }
199
+ done += batch.length;
200
+ onProgress?.(done, rows.length);
201
+ }
202
+ return { ...summary, cancelled: context.signal.aborted && done < rows.length };
203
+ },
204
+ errorsCsv(invalid, errorColumn, lineColumn) {
205
+ const keys = [...new Set(invalid.flatMap((row) => Object.keys(isRecord(row.values) ? row.values : {})))];
206
+ return toCsv(invalid, [
207
+ { key: "line", label: lineColumn, format: (row) => String(row.line) },
208
+ ...keys.map((key) => ({ key, label: key, format: (row) => cellOf(valueAt(row.values, key)) })),
209
+ {
210
+ key: "issues",
211
+ label: errorColumn,
212
+ format: (row) => row.issues
213
+ .map((issue) => (issue.field === "" ? issue.message : `${issue.field}: ${issue.message}`))
214
+ .join("; "),
215
+ },
216
+ ]);
217
+ },
218
+ };
219
+ }
220
+ async function withRelated(fields, rows, context, missing) {
221
+ const related = fields.flatMap((field) => {
222
+ const pointer = field.kind === FieldKind.resource ? (field.relation?.target ?? field.resource) : undefined;
223
+ const target = pointer?.();
224
+ return target ? [{ key: field.key, target }] : [];
225
+ });
226
+ const found = await Promise.all(related.map(async ({ key, target }) => {
227
+ const ids = [...new Set(rows.flatMap((row) => idsAt(row.values, key)))];
228
+ if (ids.length === 0)
229
+ return { key, target, records: new Map() };
230
+ const records = await resolveRelations({ relations: { related: { kind: RelationKind.manyToMany, target: () => target, key } } }, [{ [key]: ids }], ["related"], context);
231
+ const list = isRecord(records[0]) ? records[0].related : undefined;
232
+ const byId = new Map();
233
+ for (const record of Array.isArray(list) ? list : [])
234
+ byId.set(target.idKey(target.idOf(record)), record);
235
+ return { key, target, records: byId };
236
+ }));
237
+ return rows.map((row) => {
238
+ const issues = [...row.issues];
239
+ const titles = {};
240
+ for (const { key, target, records } of found) {
241
+ for (const id of idsAt(row.values, key)) {
242
+ const record = records.get(id);
243
+ if (record === undefined)
244
+ issues.push({ field: key, message: missing(id) });
245
+ else
246
+ titles[key] = titles[key] === undefined ? target.title(record) : `${titles[key]}, ${target.title(record)}`;
247
+ }
248
+ }
249
+ return { ...row, issues, ...(Object.keys(titles).length > 0 ? { titles } : {}) };
250
+ });
251
+ }
252
+ function idsAt(values, key) {
253
+ const raw = valueAt(values, key);
254
+ const list = Array.isArray(raw) ? raw : [raw];
255
+ return list.flatMap((entry) => (isString(entry) || isNumber(entry) ? [String(entry)] : []));
256
+ }
257
+ function cellOf(value) {
258
+ if (value === undefined || value === null)
259
+ return "";
260
+ if (Array.isArray(value))
261
+ return value.map(cellOf).join(", ");
262
+ return isObject(value) ? JSON.stringify(value) : String(value);
263
+ }
@@ -0,0 +1,31 @@
1
+ export * from "./core/constants.js";
2
+ export type { CallContext, ExportResult, Page, PagePosition, PageSourceLike, Query, ResourceCapabilities, ResourceService, SortSpec, SourceCapabilities, Target, Version, } from "./core/contracts.js";
3
+ export { isPagePosition } from "./core/contracts.js";
4
+ export { fieldErrorsOf, httpServiceError, isServiceError, kindOfStatus, problemDetailError, ServiceFailure, serviceError, toServiceError, type ServiceError, type ServiceFieldError, } from "./core/errors.js";
5
+ export { AppActionRefusedError, firstRefusal, isRefusal, refuse, refusedError, toAllowed, unavailableError, clause, failedError, type Allowed, type Refusal, } from "./core/refusal.js";
6
+ export { createSession, fromCasl, type CaslAbilityLike, type CaslSessionOptions, type PermissionSubject, type Session, type SessionOptions, } from "./session/session.js";
7
+ export { betterAuthPermissions, betterAuthServerSession, betterAuthSession, betterAuthStoreSession, type BetterAuthPermissions, type BetterAuthRoleLike, type BetterAuthServerLike, type BetterAuthSessionData, type BetterAuthSessionOptions, type BetterAuthStoreLike, type BetterAuthUser, } from "./session/better-auth.js";
8
+ export { hashRouter, historyRouter, joinPath, memoryRouter, splitPath, tanstackRouter, type HashRouterOptions, type HistoryRouterOptions, type MemoryRouter, type NavigateOptions, type RouterAdapter, type RouterLocation, type TanstackRouterLike, } from "./navigation/router.js";
9
+ export { localPreferences, localViews, memoryPreferences, remotePreferences, type PreferencesStore, type SavedView, type ViewStore, } from "./view/preferences.js";
10
+ export { createRng, type Rng } from "./services/rng.js";
11
+ export { isStandardSchema, issuePath, jsonSchemaProperties, validate, zodIntrospect, type InferOutput, type Introspect, type SchemaProperty, type StandardIssue, type StandardResult, type StandardSchema, } from "./resource/schema.js";
12
+ export { applyQuery, matchesFilter, matchesSearch, sortRows, valueAt } from "./services/memory-query.js";
13
+ export { memoryService, type MemoryService, type MemoryServiceOptions } from "./services/memory-service.js";
14
+ export { HttpMethod, restService, type RestServiceOptions } from "./services/rest-service.js";
15
+ export { fromPageSource, type PageSourceCrud } from "./services/from-page-source.js";
16
+ export { defineResource, dependentsOf, searchKey, type AnyResource, type ColumnDef, type FieldDef, type FieldGroup, type FilterDef, type Option, type Path, type ResolvedColumn, type ResolvedField, type ResolvedFilter, type Resource, type ResourceAudit, type ResourceLabel, type ResourceMatch, type ResourceOptions, type ResourceRoutes, type ResourceShortcuts, type DefineResourceOptions, type ResolvedRelation, type ToneName, } from "./resource/resource.js";
17
+ export { actionsOf, defineAction, isAction, messageOf, type Action, type ActionConfirm, type ActionOptions, type ActionRunOptions, type ActionTarget, type AnyAction, } from "./action/action.js";
18
+ export { defineView, type Selection, type View, type ViewOptions, type ViewPreset, type ViewScope, type ViewSnapshot, type ViewState, } from "./view/view.js";
19
+ export { count, defineNav, isNavCount, navItem, type Nav, type NavBadge, type NavCount, type NavGroup, type NavItem, type NavOptions, type NavRouteBuilder, type NavSnapshot, type TrailEntry, } from "./navigation/nav.js";
20
+ export { defineDraft, isStoredDraft, type Draft, type DraftOptions, type DraftSnapshot, type StoredDraft, } from "./draft/draft.js";
21
+ export { fieldsSchema, formSchemaOf, issueText } from "./resource/form-schema.js";
22
+ export { schemaFields } from "./resource/resource-schema.js";
23
+ export { exportCsv, toCsv, type CsvColumn, type CsvExportOptions } from "./export/csv.js";
24
+ export { dataLabelsEn, dataLabelsEs, type ControlLabels, type DataLabels, type ImportCounts, type IssueText, type RowRange, } from "./core/data-labels.js";
25
+ export { isOneOf, isRecord, valuesOf } from "./core/guards.js";
26
+ export { springFilter, springParams, springService, type SpringPage, type SpringServiceOptions, } from "./services/spring-service.js";
27
+ export { appShortcuts, createShortcutRegistry, normalizeShortcut, shortcutConflicts, warnInDevelopment, warnShortcutConflict, type ShortcutConflict, type ShortcutEntry, type ShortcutRegistry, } from "./navigation/shortcuts.js";
28
+ export { parseCsv, type CsvTable } from "./import/csv-parse.js";
29
+ export { defineImport, invalidRowsText, type Import, type ImportCheckOptions, type ImportChunkResult, type ImportIssue, type ImportMapping, type ImportOptions, type ImportPreview, type ImportRow, type ImportRunOptions, type ImportSummary, } from "./import/import.js";
30
+ export { belongsTo, childChanges, chunkIds, embeds, hasMany, includeOf, keyRelation, manyToMany, registerResource, resolveRelations, type BelongsTo, type ChildChanges, type Embeds, type HasMany, type ManyToMany, type Relation, type RelationContext, type RelationRows, type Relations, } from "./resource/relations.js";
31
+ export { isListSchema } from "./resource/schema.js";
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ export * from "./core/constants.js";
2
+ export { isPagePosition } from "./core/contracts.js";
3
+ export { fieldErrorsOf, httpServiceError, isServiceError, kindOfStatus, problemDetailError, ServiceFailure, serviceError, toServiceError, } from "./core/errors.js";
4
+ export { AppActionRefusedError, firstRefusal, isRefusal, refuse, refusedError, toAllowed, unavailableError, clause, failedError, } from "./core/refusal.js";
5
+ export { createSession, fromCasl, } from "./session/session.js";
6
+ export { betterAuthPermissions, betterAuthServerSession, betterAuthSession, betterAuthStoreSession, } from "./session/better-auth.js";
7
+ export { hashRouter, historyRouter, joinPath, memoryRouter, splitPath, tanstackRouter, } from "./navigation/router.js";
8
+ export { localPreferences, localViews, memoryPreferences, remotePreferences, } from "./view/preferences.js";
9
+ export { createRng } from "./services/rng.js";
10
+ export { isStandardSchema, issuePath, jsonSchemaProperties, validate, zodIntrospect, } from "./resource/schema.js";
11
+ export { applyQuery, matchesFilter, matchesSearch, sortRows, valueAt } from "./services/memory-query.js";
12
+ export { memoryService } from "./services/memory-service.js";
13
+ export { HttpMethod, restService } from "./services/rest-service.js";
14
+ export { fromPageSource } from "./services/from-page-source.js";
15
+ export { defineResource, dependentsOf, searchKey, } from "./resource/resource.js";
16
+ export { actionsOf, defineAction, isAction, messageOf, } from "./action/action.js";
17
+ export { defineView, } from "./view/view.js";
18
+ export { count, defineNav, isNavCount, navItem, } from "./navigation/nav.js";
19
+ export { defineDraft, isStoredDraft, } from "./draft/draft.js";
20
+ export { fieldsSchema, formSchemaOf, issueText } from "./resource/form-schema.js";
21
+ export { schemaFields } from "./resource/resource-schema.js";
22
+ export { exportCsv, toCsv } from "./export/csv.js";
23
+ export { dataLabelsEn, dataLabelsEs, } from "./core/data-labels.js";
24
+ export { isOneOf, isRecord, valuesOf } from "./core/guards.js";
25
+ export { springFilter, springParams, springService, } from "./services/spring-service.js";
26
+ export { appShortcuts, createShortcutRegistry, normalizeShortcut, shortcutConflicts, warnInDevelopment, warnShortcutConflict, } from "./navigation/shortcuts.js";
27
+ export { parseCsv } from "./import/csv-parse.js";
28
+ export { defineImport, invalidRowsText, } from "./import/import.js";
29
+ export { belongsTo, childChanges, chunkIds, embeds, hasMany, includeOf, keyRelation, manyToMany, registerResource, resolveRelations, } from "./resource/relations.js";
30
+ export { isListSchema } from "./resource/schema.js";
@@ -0,0 +1,119 @@
1
+ import { NavMatch, ResourceAction, ResourceScreen } from "../core/constants.js";
2
+ import type { PreferencesStore } from "../view/preferences.js";
3
+ import { type Allowed, type Refusal } from "../core/refusal.js";
4
+ import type { AnyResource, ToneName } from "../resource/resource.js";
5
+ import { type RouterAdapter } from "./router.js";
6
+ import type { Session } from "../session/session.js";
7
+ export type NavCount = {
8
+ readonly resource: AnyResource;
9
+ readonly filter: Record<string, unknown>;
10
+ readonly tone?: ToneName;
11
+ /** Polls every so many ms besides; off by default. */
12
+ readonly refresh?: number;
13
+ };
14
+ export type NavBadge = NavCount | {
15
+ count: () => Promise<number>;
16
+ refresh?: number;
17
+ tone?: ToneName;
18
+ } | string | number;
19
+ export type NavItem = {
20
+ id: string;
21
+ label: string;
22
+ to: string;
23
+ icon?: unknown;
24
+ /** `NavMatch.prefix` by default: `/customers/7` keeps Customers current. */
25
+ match?: NavMatch | ((pathname: string) => boolean);
26
+ children?: readonly NavItem[];
27
+ badge?: NavBadge;
28
+ /** Without permission the item doesn't show. A string asks the session's `can`. */
29
+ can?: ResourceAction | string | (() => boolean | Refusal);
30
+ shortcut?: string;
31
+ keywords?: readonly string[];
32
+ mobile?: boolean | {
33
+ order: number;
34
+ };
35
+ placements?: readonly string[];
36
+ crumb?: (params: Record<string, string>) => string | Promise<string>;
37
+ resource?: AnyResource;
38
+ };
39
+ /**
40
+ * A section of the sidebar. A `collapsible` one folds under its label; whether it's folded is kept in `preferences`,
41
+ * and it opens by itself when the current page is in it.
42
+ */
43
+ export type NavGroup = {
44
+ group: string;
45
+ label?: string;
46
+ collapsible?: boolean;
47
+ items: readonly NavItem[];
48
+ };
49
+ export type TrailEntry = {
50
+ id: string;
51
+ label: string;
52
+ to: string;
53
+ item?: NavItem;
54
+ record?: {
55
+ resource: AnyResource;
56
+ id: string;
57
+ };
58
+ screen?: typeof ResourceScreen.create | typeof ResourceScreen.edit;
59
+ };
60
+ export type NavRouteBuilder<Route> = (nav: Nav<Route>) => Route[];
61
+ export type NavOptions<Route = unknown> = {
62
+ /**
63
+ * Where the app's paths live. Leave it out in a definition shared with server code (Next.js), where the router only
64
+ * exists in a client component, and bind one there with `nav.withRouter(router)` or `useRoutedNav(nav)`.
65
+ */
66
+ router?: RouterAdapter;
67
+ items: readonly (NavGroup | NavItem)[];
68
+ session?: Session;
69
+ preferences?: PreferencesStore;
70
+ title?: (trail: readonly TrailEntry[]) => string;
71
+ /** Builds `nav.routes()`: `tanstackRoutes({ parent: () => rootRoute })` from the `resource-routes` item. */
72
+ routes?: NavRouteBuilder<Route>;
73
+ /** How many recent pages to keep. Default 5. */
74
+ recents?: number;
75
+ };
76
+ export type NavSnapshot = {
77
+ favorites: readonly string[];
78
+ recents: readonly string[];
79
+ collapsed: readonly string[];
80
+ };
81
+ export type Nav<Route = unknown> = {
82
+ readonly router: RouterAdapter;
83
+ readonly session: Session | undefined;
84
+ readonly options: NavOptions<Route>;
85
+ groups(): readonly NavGroup[];
86
+ visibleGroups(): readonly NavGroup[];
87
+ items(): readonly NavItem[];
88
+ visibleItems(): readonly NavItem[];
89
+ find(id: string): NavItem | undefined;
90
+ check(item: NavItem): Allowed;
91
+ checkNavigate(id: string): Allowed;
92
+ navigate(id: string, options?: {
93
+ replace?: boolean;
94
+ }): void;
95
+ current(pathname?: string): NavItem | undefined;
96
+ trail(pathname?: string): readonly TrailEntry[];
97
+ documentTitle(pathname?: string): string | undefined;
98
+ resources(): readonly AnyResource[];
99
+ routes(): Route[];
100
+ getSnapshot(): NavSnapshot;
101
+ subscribe(listener: () => void): () => void;
102
+ isFavorite(id: string): boolean;
103
+ pin(id: string): Allowed;
104
+ unpin(id: string): Allowed;
105
+ isCollapsed(group: string): boolean;
106
+ setCollapsed(group: string, collapsed: boolean): void;
107
+ /** The group an item is in, nested items included. */
108
+ groupOf(id: string): NavGroup | undefined;
109
+ attach(): () => void;
110
+ /** The same manifest over another router, with its own favorites and recents. */
111
+ withRouter(router: RouterAdapter): Nav<Route>;
112
+ };
113
+ export declare function navItem(resource: AnyResource, overrides?: Partial<NavItem>): NavItem;
114
+ export declare function count(resource: AnyResource, filter?: Record<string, unknown>, options?: {
115
+ tone?: ToneName;
116
+ refresh?: number;
117
+ }): NavCount;
118
+ export declare function isNavCount(badge: unknown): badge is NavCount;
119
+ export declare function defineNav<Route = unknown>(options: NavOptions<Route>): Nav<Route>;