@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,278 @@
1
+ import { NavMatch, ResourceAction, ResourceScreen } from "../core/constants.js";
2
+ import { isFunction, isRecord, isString } from "../core/guards.js";
3
+ import { firstRefusal, refuse, toAllowed } from "../core/refusal.js";
4
+ import { memoryRouter } from "./router.js";
5
+ export function navItem(resource, overrides = {}) {
6
+ return {
7
+ id: resource.key,
8
+ label: resource.label(2),
9
+ to: resource.paths.list(),
10
+ icon: resource.icon,
11
+ can: ResourceAction.list,
12
+ resource,
13
+ ...(resource.shortcuts.list === undefined ? {} : { shortcut: resource.shortcuts.list }),
14
+ ...overrides,
15
+ };
16
+ }
17
+ export function count(resource, filter = {}, options = {}) {
18
+ return { resource, filter, ...options };
19
+ }
20
+ export function isNavCount(badge) {
21
+ return isRecord(badge) && "resource" in badge && "filter" in badge;
22
+ }
23
+ function isGroup(entry) {
24
+ return "group" in entry;
25
+ }
26
+ function flatten(items) {
27
+ return items.flatMap((item) => [item, ...flatten(item.children ?? [])]);
28
+ }
29
+ function trimSlash(path) {
30
+ return path.length > 1 ? path.replace(/\/+$/u, "") : path;
31
+ }
32
+ function pathOf(to) {
33
+ const at = to.search(/[?#]/u);
34
+ return trimSlash(at === -1 ? to : to.slice(0, at));
35
+ }
36
+ function matches(item, pathname) {
37
+ if (isFunction(item.match))
38
+ return item.match(pathname);
39
+ const target = pathOf(item.to);
40
+ const path = trimSlash(pathname);
41
+ if (item.match === NavMatch.exact)
42
+ return path === target;
43
+ return path === target || (target === "/" ? false : path.startsWith(`${target}/`));
44
+ }
45
+ const unique = (ids) => [...new Set(ids)];
46
+ const readIds = (value) => (Array.isArray(value) ? value.filter(isString) : []);
47
+ export function defineNav(options) {
48
+ const { session, preferences } = options;
49
+ const router = options.router ?? memoryRouter();
50
+ const limit = options.recents ?? 5;
51
+ let snapshot = { favorites: [], recents: [], collapsed: [] };
52
+ const listeners = new Set();
53
+ const write = (next) => {
54
+ snapshot = { ...snapshot, ...next };
55
+ for (const listener of listeners)
56
+ listener();
57
+ };
58
+ const persist = (key) => void preferences?.set(`nav:${key}`, snapshot[key]);
59
+ const groups = () => {
60
+ const result = [];
61
+ let loose = [];
62
+ const flush = () => {
63
+ if (loose.length > 0)
64
+ result.push({ group: `items-${String(result.length)}`, items: loose });
65
+ loose = [];
66
+ };
67
+ for (const entry of options.items) {
68
+ if (isGroup(entry)) {
69
+ flush();
70
+ result.push(entry);
71
+ }
72
+ else
73
+ loose.push(entry);
74
+ }
75
+ flush();
76
+ return result;
77
+ };
78
+ function check(item) {
79
+ const can = item.can;
80
+ if (can === undefined)
81
+ return true;
82
+ if (isFunction(can))
83
+ return toAllowed(can(), "");
84
+ if (item.resource && can === ResourceAction.list)
85
+ return item.resource.check(ResourceAction.list, undefined, session);
86
+ return toAllowed(session?.can(can), "");
87
+ }
88
+ const visible = (items) => items
89
+ .filter((item) => check(item) === true)
90
+ .map((item) => (item.children ? { ...item, children: visible(item.children) } : item));
91
+ const allItems = () => flatten(groups().flatMap((group) => group.items));
92
+ const find = (id) => allItems().find((item) => item.id === id);
93
+ const pathname = (given) => given ?? router.location().pathname;
94
+ function current(given) {
95
+ const path = pathname(given);
96
+ let best;
97
+ for (const item of allItems()) {
98
+ if (!matches(item, path))
99
+ continue;
100
+ if (!best || pathOf(item.to).length > pathOf(best.to).length)
101
+ best = item;
102
+ }
103
+ return best;
104
+ }
105
+ function parents(target) {
106
+ const walk = (items, chain) => {
107
+ for (const item of items) {
108
+ if (item === target)
109
+ return [...chain, item];
110
+ const found = walk(item.children ?? [], [...chain, item]);
111
+ if (found)
112
+ return found;
113
+ }
114
+ return undefined;
115
+ };
116
+ return (walk(groups().flatMap((group) => group.items), []) ?? [target]);
117
+ }
118
+ function trail(given) {
119
+ const path = pathname(given);
120
+ const item = current(path);
121
+ if (!item)
122
+ return [];
123
+ const entries = parents(item).map((entry) => ({
124
+ id: entry.id,
125
+ label: entry.label,
126
+ to: entry.to,
127
+ item: entry,
128
+ }));
129
+ const resource = item.resource;
130
+ const match = resource?.match(path);
131
+ if (!resource || !match || match.screen === ResourceScreen.list)
132
+ return entries;
133
+ if (match.screen === ResourceScreen.create)
134
+ return [
135
+ ...entries,
136
+ { id: `${item.id}:new`, label: "", to: resource.paths.create(), item, screen: ResourceScreen.create },
137
+ ];
138
+ const id = match.id ?? "";
139
+ const parsed = resource.parseId(id);
140
+ const record = {
141
+ id: `${item.id}:${id}`,
142
+ label: id,
143
+ to: resource.paths.detail(parsed),
144
+ record: { resource, id },
145
+ };
146
+ if (match.screen === ResourceScreen.edit)
147
+ return [
148
+ ...entries,
149
+ record,
150
+ { id: `${item.id}:${id}:edit`, label: "", to: resource.paths.edit(parsed), item, screen: ResourceScreen.edit },
151
+ ];
152
+ return [...entries, record];
153
+ }
154
+ function groupOf(id) {
155
+ return groups().find((group) => flatten(group.items).some((item) => item.id === id));
156
+ }
157
+ function setCollapsed(group, collapsed) {
158
+ const next = collapsed
159
+ ? unique([...snapshot.collapsed, group])
160
+ : snapshot.collapsed.filter((entry) => entry !== group);
161
+ if (next.length === snapshot.collapsed.length && next.every((entry, index) => entry === snapshot.collapsed[index]))
162
+ return;
163
+ write({ collapsed: next });
164
+ persist("collapsed");
165
+ }
166
+ function openCurrent() {
167
+ const item = current();
168
+ const group = item ? groupOf(item.id) : undefined;
169
+ if (group?.collapsible === true && snapshot.collapsed.includes(group.group))
170
+ setCollapsed(group.group, false);
171
+ }
172
+ function recordRecent() {
173
+ openCurrent();
174
+ const item = current();
175
+ if (!item || snapshot.recents[0] === item.id)
176
+ return;
177
+ write({ recents: [item.id, ...snapshot.recents.filter((entry) => entry !== item.id)].slice(0, limit) });
178
+ persist("recents");
179
+ }
180
+ function checkNavigate(id) {
181
+ const item = find(id);
182
+ if (!item)
183
+ return refuse(`no page named "${id}"`);
184
+ const allowed = check(item);
185
+ return allowed === true ? true : firstRefusal(allowed);
186
+ }
187
+ const nav = {
188
+ router,
189
+ session,
190
+ options,
191
+ groups,
192
+ visibleGroups: () => groups()
193
+ .map((group) => ({ ...group, items: visible(group.items) }))
194
+ .filter((group) => group.items.length > 0),
195
+ items: allItems,
196
+ visibleItems: () => flatten(visible(groups().flatMap((group) => group.items))),
197
+ find,
198
+ check,
199
+ checkNavigate,
200
+ navigate(id, navigateOptions) {
201
+ const item = find(id);
202
+ if (!item || checkNavigate(id) !== true)
203
+ return;
204
+ router.navigate(item.to, navigateOptions);
205
+ },
206
+ current,
207
+ trail,
208
+ documentTitle(given) {
209
+ const entries = trail(given);
210
+ if (options.title)
211
+ return options.title(entries);
212
+ const last = entries.at(-1)?.label;
213
+ return last === undefined || last === "" ? undefined : last;
214
+ },
215
+ resources() {
216
+ const found = allItems().flatMap((item) => (item.resource ? [item.resource] : []));
217
+ return [...new Set(found)];
218
+ },
219
+ routes() {
220
+ if (!options.routes)
221
+ throw new Error("nav.routes() needs a route builder: defineNav({ routes: tanstackRoutes({ parent: () => rootRoute }) }).");
222
+ return options.routes(nav);
223
+ },
224
+ getSnapshot: () => snapshot,
225
+ subscribe(listener) {
226
+ listeners.add(listener);
227
+ return () => {
228
+ listeners.delete(listener);
229
+ };
230
+ },
231
+ isFavorite: (id) => snapshot.favorites.includes(id),
232
+ pin(id) {
233
+ const allowed = checkNavigate(id);
234
+ if (allowed !== true)
235
+ return allowed;
236
+ if (!snapshot.favorites.includes(id)) {
237
+ write({ favorites: [...snapshot.favorites, id] });
238
+ persist("favorites");
239
+ }
240
+ return true;
241
+ },
242
+ unpin(id) {
243
+ if (!find(id))
244
+ return refuse(`no page named "${id}"`);
245
+ if (snapshot.favorites.includes(id)) {
246
+ write({ favorites: snapshot.favorites.filter((entry) => entry !== id) });
247
+ persist("favorites");
248
+ }
249
+ return true;
250
+ },
251
+ isCollapsed: (group) => snapshot.collapsed.includes(group),
252
+ setCollapsed,
253
+ groupOf,
254
+ attach() {
255
+ let active = true;
256
+ if (preferences) {
257
+ void Promise.all([
258
+ preferences.get("nav:favorites"),
259
+ preferences.get("nav:recents"),
260
+ preferences.get("nav:collapsed"),
261
+ ]).then(([favorites, recents, collapsed]) => {
262
+ if (!active)
263
+ return;
264
+ write({ favorites: readIds(favorites), recents: readIds(recents), collapsed: readIds(collapsed) });
265
+ openCurrent();
266
+ });
267
+ }
268
+ recordRecent();
269
+ const unsubscribe = router.subscribe(recordRecent);
270
+ return () => {
271
+ active = false;
272
+ unsubscribe();
273
+ };
274
+ },
275
+ withRouter: (next) => defineNav({ ...options, router: next }),
276
+ };
277
+ return nav;
278
+ }
@@ -0,0 +1,81 @@
1
+ import { RouterKind } from "../core/constants.js";
2
+ export type RouterLocation = {
3
+ pathname: string;
4
+ search: string;
5
+ hash: string;
6
+ };
7
+ export type NavigateOptions = {
8
+ replace?: boolean | undefined;
9
+ };
10
+ export interface RouterAdapter {
11
+ kind: RouterKind;
12
+ /** The current location; the same object until it changes, so it can feed `useSyncExternalStore`. */
13
+ location(): RouterLocation;
14
+ subscribe(listener: () => void): () => void;
15
+ /** `to` is a path with an optional query: `/customers/7?tab=orders`. */
16
+ navigate(to: string, options?: NavigateOptions): void;
17
+ href(to: string): string;
18
+ /** Asks before leaving while `when()` holds (unsaved changes); `ask` resolves to true to leave. */
19
+ block?(when: () => boolean, ask: () => Promise<boolean>): () => void;
20
+ }
21
+ export declare function splitPath(path: string): RouterLocation;
22
+ export declare function joinPath(location: {
23
+ pathname: string;
24
+ search: string;
25
+ }): string;
26
+ type BrowserWindow = {
27
+ location: Location;
28
+ history: History;
29
+ addEventListener: Window["addEventListener"];
30
+ removeEventListener: Window["removeEventListener"];
31
+ };
32
+ export type HashRouterOptions = {
33
+ /** What comes before the path in the fragment. Default `"#"`, so `#/customers/7`. */
34
+ prefix?: string;
35
+ window?: BrowserWindow;
36
+ };
37
+ /**
38
+ * Routes in the fragment (`/#/customers/7`): no server configuration, reload and links work, but the server never
39
+ * sees the route (no server rendering) and it clashes with OAuth's implicit flow.
40
+ */
41
+ export declare function hashRouter(options?: HashRouterOptions): RouterAdapter;
42
+ export type HistoryRouterOptions = {
43
+ base?: string;
44
+ window?: BrowserWindow;
45
+ };
46
+ /**
47
+ * Clean URLs with `pushState` and no library. The server must answer every path with `index.html` (an SPA rewrite),
48
+ * or a reload of `/customers/7` is a 404.
49
+ */
50
+ export declare function historyRouter(options?: HistoryRouterOptions): RouterAdapter;
51
+ export type MemoryRouter = RouterAdapter & {
52
+ readonly entries: readonly string[];
53
+ };
54
+ export declare function memoryRouter(initial?: string): MemoryRouter;
55
+ export type TanstackRouterLike = {
56
+ history: {
57
+ location: {
58
+ pathname: string;
59
+ search: string;
60
+ hash: string;
61
+ };
62
+ subscribe(listener: () => void): () => void;
63
+ push(path: string): void;
64
+ replace(path: string): void;
65
+ createHref(path: string): string;
66
+ block?(blocker: {
67
+ blockerFn: () => boolean | Promise<boolean>;
68
+ enableBeforeUnload?: boolean | (() => boolean);
69
+ }): () => void;
70
+ };
71
+ navigate?(options: {
72
+ href: string;
73
+ replace?: boolean;
74
+ }): Promise<void> | void;
75
+ };
76
+ /**
77
+ * TanStack Router as a `RouterAdapter`. Pass the router, or a function that returns it when the router is created
78
+ * after the navigation manifest (its route tree comes from `nav.routes()`).
79
+ */
80
+ export declare function tanstackRouter(router: TanstackRouterLike | (() => TanstackRouterLike)): RouterAdapter;
81
+ export {};
@@ -0,0 +1,249 @@
1
+ import { RouterKind, ValueType } from "../core/constants.js";
2
+ import { isFunction } from "../core/guards.js";
3
+ export function splitPath(path) {
4
+ const hashAt = path.indexOf("#");
5
+ const beforeHash = hashAt === -1 ? path : path.slice(0, hashAt);
6
+ const hash = hashAt === -1 ? "" : path.slice(hashAt);
7
+ const queryAt = beforeHash.indexOf("?");
8
+ const pathname = (queryAt === -1 ? beforeHash : beforeHash.slice(0, queryAt)) || "/";
9
+ const search = queryAt === -1 ? "" : beforeHash.slice(queryAt);
10
+ return { pathname: pathname.startsWith("/") ? pathname : `/${pathname}`, search: search === "?" ? "" : search, hash };
11
+ }
12
+ export function joinPath(location) {
13
+ return `${location.pathname}${location.search}`;
14
+ }
15
+ function cachedLocation(read) {
16
+ let last = "";
17
+ let value = splitPath("/");
18
+ return () => {
19
+ const current = read();
20
+ if (current !== last) {
21
+ last = current;
22
+ value = splitPath(current);
23
+ }
24
+ return value;
25
+ };
26
+ }
27
+ function browserWindow() {
28
+ return typeof window === ValueType.undefined ? undefined : window;
29
+ }
30
+ function listeners() {
31
+ const set = new Set();
32
+ return {
33
+ add(listener) {
34
+ set.add(listener);
35
+ return () => {
36
+ set.delete(listener);
37
+ };
38
+ },
39
+ notify() {
40
+ for (const listener of set)
41
+ listener();
42
+ },
43
+ get size() {
44
+ return set.size;
45
+ },
46
+ };
47
+ }
48
+ function beforeUnloadBlock(target, when) {
49
+ if (!target)
50
+ return () => { };
51
+ const onBeforeUnload = (event) => {
52
+ if (!when())
53
+ return;
54
+ event.preventDefault();
55
+ };
56
+ target.addEventListener("beforeunload", onBeforeUnload);
57
+ return () => target.removeEventListener("beforeunload", onBeforeUnload);
58
+ }
59
+ /**
60
+ * Routes in the fragment (`/#/customers/7`): no server configuration, reload and links work, but the server never
61
+ * sees the route (no server rendering) and it clashes with OAuth's implicit flow.
62
+ */
63
+ export function hashRouter(options = {}) {
64
+ const prefix = options.prefix ?? "#";
65
+ const target = options.window ?? browserWindow();
66
+ const read = () => {
67
+ const hash = target?.location.hash ?? "";
68
+ return hash.startsWith(prefix) ? hash.slice(prefix.length) || "/" : "/";
69
+ };
70
+ const location = cachedLocation(read);
71
+ const own = listeners();
72
+ const onChange = () => own.notify();
73
+ let pendingGuard;
74
+ return {
75
+ kind: RouterKind.hash,
76
+ location,
77
+ subscribe(listener) {
78
+ if (own.size === 0)
79
+ target?.addEventListener("hashchange", onChange);
80
+ const remove = own.add(listener);
81
+ return () => {
82
+ remove();
83
+ if (own.size === 0)
84
+ target?.removeEventListener("hashchange", onChange);
85
+ };
86
+ },
87
+ navigate(to, navigateOptions) {
88
+ if (!target)
89
+ return;
90
+ const go = () => {
91
+ const url = `${target.location.pathname}${target.location.search}${prefix}${to}`;
92
+ if (navigateOptions?.replace === true)
93
+ target.history.replaceState(target.history.state, "", url);
94
+ else
95
+ target.history.pushState(null, "", url);
96
+ own.notify();
97
+ };
98
+ if (pendingGuard)
99
+ void pendingGuard().then((leave) => leave && go());
100
+ else
101
+ go();
102
+ },
103
+ href: (to) => `${prefix}${to}`,
104
+ block(when, ask) {
105
+ const guard = async () => (when() ? ask() : true);
106
+ pendingGuard = guard;
107
+ const unload = beforeUnloadBlock(target, when);
108
+ return () => {
109
+ if (pendingGuard === guard)
110
+ pendingGuard = undefined;
111
+ unload();
112
+ };
113
+ },
114
+ };
115
+ }
116
+ /**
117
+ * Clean URLs with `pushState` and no library. The server must answer every path with `index.html` (an SPA rewrite),
118
+ * or a reload of `/customers/7` is a 404.
119
+ */
120
+ export function historyRouter(options = {}) {
121
+ const base = (options.base ?? "").replace(/\/$/u, "");
122
+ const target = options.window ?? browserWindow();
123
+ const read = () => {
124
+ if (!target)
125
+ return "/";
126
+ const path = target.location.pathname;
127
+ const inside = base !== "" && path.startsWith(base) ? path.slice(base.length) || "/" : path;
128
+ return `${inside}${target.location.search}`;
129
+ };
130
+ const location = cachedLocation(read);
131
+ const own = listeners();
132
+ const onChange = () => own.notify();
133
+ let pendingGuard;
134
+ return {
135
+ kind: RouterKind.history,
136
+ location,
137
+ subscribe(listener) {
138
+ if (own.size === 0)
139
+ target?.addEventListener("popstate", onChange);
140
+ const remove = own.add(listener);
141
+ return () => {
142
+ remove();
143
+ if (own.size === 0)
144
+ target?.removeEventListener("popstate", onChange);
145
+ };
146
+ },
147
+ navigate(to, navigateOptions) {
148
+ if (!target)
149
+ return;
150
+ const go = () => {
151
+ if (navigateOptions?.replace === true)
152
+ target.history.replaceState(target.history.state, "", `${base}${to}`);
153
+ else
154
+ target.history.pushState(null, "", `${base}${to}`);
155
+ own.notify();
156
+ };
157
+ if (pendingGuard)
158
+ void pendingGuard().then((leave) => leave && go());
159
+ else
160
+ go();
161
+ },
162
+ href: (to) => `${base}${to}`,
163
+ block(when, ask) {
164
+ const guard = async () => (when() ? ask() : true);
165
+ pendingGuard = guard;
166
+ const unload = beforeUnloadBlock(target, when);
167
+ return () => {
168
+ if (pendingGuard === guard)
169
+ pendingGuard = undefined;
170
+ unload();
171
+ };
172
+ },
173
+ };
174
+ }
175
+ export function memoryRouter(initial = "/") {
176
+ const entries = [initial];
177
+ const location = cachedLocation(() => entries.at(-1) ?? "/");
178
+ const own = listeners();
179
+ let pendingGuard;
180
+ return {
181
+ kind: RouterKind.memory,
182
+ entries,
183
+ location,
184
+ subscribe: (listener) => own.add(listener),
185
+ navigate(to, options) {
186
+ const go = () => {
187
+ if (options?.replace === true)
188
+ entries[entries.length - 1] = to;
189
+ else
190
+ entries.push(to);
191
+ own.notify();
192
+ };
193
+ if (pendingGuard)
194
+ void pendingGuard().then((leave) => leave && go());
195
+ else
196
+ go();
197
+ },
198
+ href: (to) => to,
199
+ block(when, ask) {
200
+ const guard = async () => (when() ? ask() : true);
201
+ pendingGuard = guard;
202
+ return () => {
203
+ if (pendingGuard === guard)
204
+ pendingGuard = undefined;
205
+ };
206
+ },
207
+ };
208
+ }
209
+ // Workaround: TanStack's hash history (1.170) appends the page's real query to the route's, so `#/x?a=1` under
210
+ // `/?demo=y` reads `?a=1?demo=y`; the route's own query is what comes before the page's.
211
+ function ownSearch(search) {
212
+ const page = typeof window === ValueType.undefined ? "" : window.location.search;
213
+ if (page === "" || search === page || !search.endsWith(page))
214
+ return search;
215
+ return search.slice(0, -page.length);
216
+ }
217
+ /**
218
+ * TanStack Router as a `RouterAdapter`. Pass the router, or a function that returns it when the router is created
219
+ * after the navigation manifest (its route tree comes from `nav.routes()`).
220
+ */
221
+ export function tanstackRouter(router) {
222
+ const get = isFunction(router) ? router : () => router;
223
+ const location = cachedLocation(() => {
224
+ const current = get().history.location;
225
+ return `${current.pathname}${ownSearch(current.search)}${current.hash}`;
226
+ });
227
+ return {
228
+ kind: RouterKind.tanstack,
229
+ location,
230
+ subscribe: (listener) => get().history.subscribe(listener),
231
+ navigate(to, options) {
232
+ const instance = get();
233
+ const replace = options?.replace === true;
234
+ if (instance.navigate)
235
+ void instance.navigate({ href: to, replace });
236
+ else if (replace)
237
+ instance.history.replace(to);
238
+ else
239
+ instance.history.push(to);
240
+ },
241
+ href: (to) => get().history.createHref(to),
242
+ block(when, ask) {
243
+ const history = get().history;
244
+ if (!history.block)
245
+ return () => { };
246
+ return history.block({ blockerFn: async () => (when() ? !(await ask()) : false), enableBeforeUnload: when });
247
+ },
248
+ };
249
+ }
@@ -0,0 +1,37 @@
1
+ /** A registered shortcut: who owns it (`customers`, `customers.block`), where it runs and what it's called. */
2
+ export type ShortcutEntry = {
3
+ keys: string;
4
+ id: string;
5
+ label?: string | undefined;
6
+ /** The screen or region it runs in; none runs everywhere. */
7
+ scope?: string | undefined;
8
+ };
9
+ export type ShortcutConflict = {
10
+ keys: string;
11
+ scope: string | undefined;
12
+ /** The owners whose shortcuts collide, in registration order. */
13
+ ids: readonly string[];
14
+ };
15
+ /** The keys in one spelling: lower case, modifiers in a fixed order, `cmd` as `meta`, steps one space apart. */
16
+ export declare function normalizeShortcut(keys: string): string;
17
+ /**
18
+ * Shortcuts that collide where they can both run: the same keys, or a key that starts another's sequence (`g`
19
+ * against `g c`), in the same scope or with one of them global. One owner registering twice is no conflict.
20
+ */
21
+ export declare function shortcutConflicts(entries: readonly ShortcutEntry[]): ShortcutConflict[];
22
+ export type ShortcutRegistry = {
23
+ /** Registers while the owner is mounted; returns the cleanup. */
24
+ add(entry: ShortcutEntry): () => void;
25
+ entries(): readonly ShortcutEntry[];
26
+ conflicts(): ShortcutConflict[];
27
+ };
28
+ /** Tracks the shortcuts registered now and reports a new one that collides with one already there. */
29
+ export declare function createShortcutRegistry(options?: {
30
+ onConflict?: (conflict: ShortcutConflict) => void;
31
+ }): ShortcutRegistry;
32
+ /** A warning for the developer, in the console, outside production builds. */
33
+ export declare function warnInDevelopment(message: string): void;
34
+ /** Says which owners collide, in the console, outside production builds. */
35
+ export declare function warnShortcutConflict(conflict: ShortcutConflict): void;
36
+ /** The app's registered shortcuts: `NavShell`, `NavCommand` and the resource blocks add theirs here. */
37
+ export declare const appShortcuts: ShortcutRegistry;