@urbicon-ui/sveltekit-utils 6.21.2 → 6.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,6 +5,7 @@ Small, focused SvelteKit helpers that Urbicon apps share. Zero runtime dependenc
5
5
  Currently shipping:
6
6
 
7
7
  - **URL-state runes** — reactive `useUrlParam` / `useUrlArrayParam` that keep component state in sync with `?query=` parameters
8
+ - **Table-query URL sync** — opt-in `?q=…&sort=…&page=…` mirroring for `@urbicon-ui/table` server mode, plus the pure serializers behind it
8
9
  - **Cron runner** — interval-based background fetcher for scheduled server endpoints
9
10
 
10
11
  ## Installation
@@ -55,6 +56,56 @@ updateUrlSearchParams({ page: '1', tag: ['a', 'b'] }, { replaceState: true });
55
56
  - URL updates use `goto()` with `replaceState: true`, `noScroll: true`, `keepFocus: true` — suited for filter/pagination UIs, not full page transitions.
56
57
  - `useUrlParam` returns getters (not Svelte stores) so consumers can read the value lazily inside `$derived`/`$effect`.
57
58
 
59
+ ## Table Query ↔ URL (`table-query` + `url.svelte`)
60
+
61
+ Opt-in URL sync for `@urbicon-ui/table` in `mode="server"`: the `TableQuery` the table emits (search, sort, page, page size, filters, grouping) is mirrored onto query parameters (`?q=…&sort=…&page=…`), so the view state survives reloads and can be shared as a link.
62
+
63
+ ```svelte
64
+ <script lang="ts">
65
+ import { Table } from '@urbicon-ui/table';
66
+ import { tableQueryToSearchParams } from '@urbicon-ui/sveltekit-utils/table-query';
67
+ import { createTableQueryUrlSync } from '@urbicon-ui/sveltekit-utils/url.svelte';
68
+
69
+ const sync = createTableQueryUrlSync({ defaults: { itemsPerPage: 25 } });
70
+ </script>
71
+
72
+ <Table
73
+ mode="server"
74
+ {columns}
75
+ itemsPerPage={25}
76
+ initialPage={sync.initialQuery.page}
77
+ initialGroupBy={sync.initialQuery.groupByKey}
78
+ queryFn={async (query, { signal }) => {
79
+ sync.syncQuery(query); // mirror the query onto the URL (replaceState)
80
+ const res = await fetch(`/api/users?${tableQueryToSearchParams(query)}`, { signal });
81
+ const data = await res.json();
82
+ return { items: data.results, totalItems: data.total };
83
+ }}
84
+ />
85
+ ```
86
+
87
+ With manual control (`onQueryChange` instead of `queryFn`), pass `sync.syncQuery` directly — note that `onQueryChange` does not fire when `queryFn` is set, which is why the managed variant calls it inside `queryFn`.
88
+
89
+ The pure serializers live under `@urbicon-ui/sveltekit-utils/table-query` and work without SvelteKit — e.g. to parse the initial query in a server `load` and fetch the first page during SSR:
90
+
91
+ ```typescript
92
+ // +page.server.ts
93
+ import { searchParamsToTableQuery } from '@urbicon-ui/sveltekit-utils/table-query';
94
+
95
+ export const load = async ({ url }) => {
96
+ const query = searchParamsToTableQuery(url.searchParams, { defaults: { itemsPerPage: 25 } });
97
+ return { initialResult: await fetchUsers(query) };
98
+ };
99
+ ```
100
+
101
+ **Design notes**
102
+
103
+ - **Default elision** — values equal to `defaults` are not written; a table in its default state leaves the URL clean. Set `defaults` to the table's initial props (`itemsPerPage`, `initialPage`, `initialGroupBy`) so the elision baseline matches the state the table starts in.
104
+ - **Read tolerant, write strict** — unparsable params fall back to the defaults and malformed `filter` entries are skipped; serializing a structurally invalid query (non-positive page, unknown operator) throws instead of writing corrupt state.
105
+ - **Namespacing** — `prefix: 't_'` scopes all keys (`?t_q=…`) for multiple synced tables on one page; unrelated params are always preserved.
106
+ - **Types** — `TableQueryParams` is a structural mirror of the table's `TableQuery` (no dependency on `@urbicon-ui/table`; a parity test in the table package guards against drift).
107
+ - **Seeding limits** — the table currently has no `initialSort` / initial-filter props, so sort/filter state parsed from the URL can seed your fetch but not the table's header indicators. Once those props exist, `initialQuery` covers them too.
108
+
58
109
  ## Cron Runner (`cron`)
59
110
 
60
111
  Fire HTTP requests against SvelteKit server endpoints on an interval. Pair with a shared-secret header so endpoints can authenticate scheduled calls.
@@ -99,11 +150,12 @@ export const POST = async ({ request }) => {
99
150
 
100
151
  ## Exports
101
152
 
102
- | Subpath | Contents |
103
- | -------------- | ----------------------------------------------------------------------------------- |
104
- | `.` | Barrel of both modules |
105
- | `./url.svelte` | `useUrlParam`, `useUrlArrayParam`, `createUrlParam`, `updateUrlSearchParams`, types |
106
- | `./cron` | `createCronRunner`, `CronJob`, `CronRunnerConfig`, `CronRunner` |
153
+ | Subpath | Contents |
154
+ | --------------- | ------------------------------------------------------------------------------------------------------------------ |
155
+ | `.` | Barrel of all modules |
156
+ | `./url.svelte` | `useUrlParam`, `useUrlArrayParam`, `createUrlParam`, `updateUrlSearchParams`, `createTableQueryUrlSync`, types |
157
+ | `./table-query` | `tableQueryToSearchParams`, `searchParamsToTableQuery`, `applyTableQueryToSearchParams`, `TableQueryParams`, types |
158
+ | `./cron` | `createCronRunner`, `CronJob`, `CronRunnerConfig`, `CronRunner` |
107
159
 
108
160
  ## Development
109
161
 
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './cron';
2
+ export * from './table-query';
2
3
  export * from './url.svelte';
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './cron';
2
+ export * from './table-query';
2
3
  export * from './url.svelte';
@@ -0,0 +1,152 @@
1
+ /**
2
+ * URL (de)serialization for the query state a data table emits in server mode
3
+ * (`TableQuery` from `@urbicon-ui/table`: page, page size, sort, search term,
4
+ * column filters, grouping).
5
+ *
6
+ * The types in this module are a **structural mirror** of `TableQuery` — they
7
+ * are deliberately not imported from `@urbicon-ui/table`, so this package
8
+ * carries no dependency on the table package. Any object shaped like
9
+ * `TableQuery` is accepted; a type-parity test in `@urbicon-ui/table` guards
10
+ * the two shapes against drift.
11
+ *
12
+ * Serialization contract:
13
+ * - **Deterministic** — fixed key order (`q`, `page`, `size`, `sort`, `dir`,
14
+ * `group`, `filter`), stable filter order.
15
+ * - **Default elision** — values equal to the resolved defaults are not
16
+ * written; a table in its default state produces an empty query string.
17
+ * - **Read tolerant** — unparsable params fall back to the defaults, and
18
+ * malformed filter entries are skipped.
19
+ * - **Write strict** — a structurally invalid query (non-positive page,
20
+ * unknown filter operator, …) throws instead of writing corrupt state.
21
+ */
22
+ /** Sort direction of a table query. Mirrors `@urbicon-ui/table`. */
23
+ export type TableQuerySortDirection = 'asc' | 'desc';
24
+ /**
25
+ * Filter operators supported by the table. Mirrors `FilterOperator` from
26
+ * `@urbicon-ui/table`. Used as the runtime whitelist when parsing `filter`
27
+ * params from the URL.
28
+ */
29
+ export declare const TABLE_QUERY_FILTER_OPERATORS: readonly ["contains", "equals", "startsWith", "endsWith", "greaterThan", "lessThan"];
30
+ /** Filter operator of a table query filter. Mirrors `@urbicon-ui/table`. */
31
+ export type TableQueryFilterOperator = (typeof TABLE_QUERY_FILTER_OPERATORS)[number];
32
+ /** Single column filter of a table query. Mirrors `Filter` from `@urbicon-ui/table`. */
33
+ export interface TableQueryFilter {
34
+ /** Column ID the filter applies to. */
35
+ column: string;
36
+ /** Filter operator. */
37
+ operator: TableQueryFilterOperator;
38
+ /** Filter value (always a string, numeric operators convert internally). */
39
+ value: string;
40
+ }
41
+ /**
42
+ * Query state of a table in server mode. Structural mirror of `TableQuery`
43
+ * from `@urbicon-ui/table` — the object passed to `queryFn` / `onQueryChange`
44
+ * is directly assignable.
45
+ */
46
+ export interface TableQueryParams {
47
+ /** Current page (1-based). */
48
+ page: number;
49
+ /** Number of items per page. */
50
+ itemsPerPage: number;
51
+ /** Column ID to sort by, or empty string if no sort is active. */
52
+ sortColumn: string;
53
+ /** Sort direction. */
54
+ sortDirection: TableQuerySortDirection;
55
+ /** Full-text search term. */
56
+ searchTerm: string;
57
+ /** Active column filters. */
58
+ activeFilters: TableQueryFilter[];
59
+ /** Column ID for grouping, or null if ungrouped. */
60
+ groupByKey: string | null;
61
+ }
62
+ /**
63
+ * Baseline used for default elision: query values equal to these defaults are
64
+ * omitted from the URL, and missing params parse back to them.
65
+ *
66
+ * Set the defaults to the table's **initial, uncontrolled state** — i.e. the
67
+ * values you pass as props (`itemsPerPage`, `initialPage`, `initialGroupBy`).
68
+ * Unset fields fall back to the table's own defaults (page 1, 10 items per
69
+ * page, no sort, empty search, ungrouped).
70
+ */
71
+ export interface TableQueryDefaults {
72
+ /** Default page. @default 1 */
73
+ page?: number;
74
+ /** Default page size. @default 10 */
75
+ itemsPerPage?: number;
76
+ /** Default sort column ('' = unsorted). @default '' */
77
+ sortColumn?: string;
78
+ /** Default sort direction. @default 'asc' */
79
+ sortDirection?: TableQuerySortDirection;
80
+ /** Default search term. @default '' */
81
+ searchTerm?: string;
82
+ /** Default group key (null = ungrouped). @default null */
83
+ groupByKey?: string | null;
84
+ }
85
+ /** Options shared by the table-query (de)serializers. */
86
+ export interface TableQueryUrlOptions {
87
+ /** Elision baseline — see {@link TableQueryDefaults}. */
88
+ defaults?: TableQueryDefaults;
89
+ /**
90
+ * Prefix for every param key (`prefix: 't_'` → `?t_q=…&t_page=…`). Use it
91
+ * to namespace multiple synced tables on the same page.
92
+ * @default ''
93
+ */
94
+ prefix?: string;
95
+ }
96
+ /**
97
+ * Serialize a table query into `URLSearchParams`, eliding every value that
98
+ * equals the resolved defaults (see {@link TableQueryDefaults}).
99
+ *
100
+ * Key scheme (each key optionally prefixed via `options.prefix`):
101
+ * - `q` — search term
102
+ * - `page` — 1-based page
103
+ * - `size` — items per page
104
+ * - `sort` — sort column; an **empty** `sort=` marks "explicitly unsorted"
105
+ * and is only written when the defaults specify a sort column
106
+ * - `dir` — `desc` (ascending is implied when absent)
107
+ * - `group` — group key; an empty `group=` marks "explicitly ungrouped"
108
+ * - `filter` — repeated, `<column>:<operator>:<value>` with column and value
109
+ * URI-component-encoded so the `:` separators stay unambiguous
110
+ *
111
+ * When `sortColumn` is empty the sort direction is meaningless and is
112
+ * normalized away (it parses back as `'asc'`).
113
+ *
114
+ * Also handy for building the backend request inside `queryFn` — the same
115
+ * scheme works as an API query string.
116
+ *
117
+ * @param query - Query emitted by the table (`TableQuery` is assignable).
118
+ * @param options - Elision defaults + key prefix.
119
+ * @returns Fresh `URLSearchParams` containing only non-default values.
120
+ * @throws TypeError when the query is structurally invalid (write strict).
121
+ */
122
+ export declare function tableQueryToSearchParams(query: TableQueryParams, options?: TableQueryUrlOptions): URLSearchParams;
123
+ /**
124
+ * Parse `URLSearchParams` back into a full table query, filling every missing
125
+ * param from the resolved defaults (see {@link TableQueryDefaults}).
126
+ *
127
+ * Read tolerant: non-numeric `page`/`size` fall back to the defaults, an
128
+ * unknown `dir` becomes `'asc'`, and malformed `filter` entries (wrong shape,
129
+ * unknown operator, broken percent-encoding) are skipped individually.
130
+ *
131
+ * Works anywhere a `URLSearchParams` exists — including `url.searchParams`
132
+ * in a server `load`, to run the initial server-mode fetch during SSR.
133
+ *
134
+ * @param params - Search params to read (not mutated).
135
+ * @param options - Fallback defaults + key prefix.
136
+ * @returns Complete query object (assignable to `TableQuery`).
137
+ */
138
+ export declare function searchParamsToTableQuery(params: URLSearchParams, options?: TableQueryUrlOptions): TableQueryParams;
139
+ /**
140
+ * Merge a table query into existing search params: all managed keys (`q`,
141
+ * `page`, `size`, `sort`, `dir`, `group`, `filter` — with the configured
142
+ * prefix) are replaced by the serialized query, every other param is
143
+ * preserved untouched. Managed keys whose value returned to the default are
144
+ * removed (default elision).
145
+ *
146
+ * @param existing - Current search params (not mutated — a copy is returned).
147
+ * @param query - Query emitted by the table.
148
+ * @param options - Elision defaults + key prefix.
149
+ * @returns New `URLSearchParams` with the query applied.
150
+ * @throws TypeError when the query is structurally invalid (write strict).
151
+ */
152
+ export declare function applyTableQueryToSearchParams(existing: URLSearchParams, query: TableQueryParams, options?: TableQueryUrlOptions): URLSearchParams;
@@ -0,0 +1,232 @@
1
+ /**
2
+ * URL (de)serialization for the query state a data table emits in server mode
3
+ * (`TableQuery` from `@urbicon-ui/table`: page, page size, sort, search term,
4
+ * column filters, grouping).
5
+ *
6
+ * The types in this module are a **structural mirror** of `TableQuery` — they
7
+ * are deliberately not imported from `@urbicon-ui/table`, so this package
8
+ * carries no dependency on the table package. Any object shaped like
9
+ * `TableQuery` is accepted; a type-parity test in `@urbicon-ui/table` guards
10
+ * the two shapes against drift.
11
+ *
12
+ * Serialization contract:
13
+ * - **Deterministic** — fixed key order (`q`, `page`, `size`, `sort`, `dir`,
14
+ * `group`, `filter`), stable filter order.
15
+ * - **Default elision** — values equal to the resolved defaults are not
16
+ * written; a table in its default state produces an empty query string.
17
+ * - **Read tolerant** — unparsable params fall back to the defaults, and
18
+ * malformed filter entries are skipped.
19
+ * - **Write strict** — a structurally invalid query (non-positive page,
20
+ * unknown filter operator, …) throws instead of writing corrupt state.
21
+ */
22
+ /**
23
+ * Filter operators supported by the table. Mirrors `FilterOperator` from
24
+ * `@urbicon-ui/table`. Used as the runtime whitelist when parsing `filter`
25
+ * params from the URL.
26
+ */
27
+ export const TABLE_QUERY_FILTER_OPERATORS = [
28
+ 'contains',
29
+ 'equals',
30
+ 'startsWith',
31
+ 'endsWith',
32
+ 'greaterThan',
33
+ 'lessThan'
34
+ ];
35
+ /** Resolved param key names for one prefix. */
36
+ function paramKeys(prefix) {
37
+ return {
38
+ q: `${prefix}q`,
39
+ page: `${prefix}page`,
40
+ size: `${prefix}size`,
41
+ sort: `${prefix}sort`,
42
+ dir: `${prefix}dir`,
43
+ group: `${prefix}group`,
44
+ filter: `${prefix}filter`
45
+ };
46
+ }
47
+ function resolveDefaults(defaults) {
48
+ return {
49
+ page: defaults?.page ?? 1,
50
+ itemsPerPage: defaults?.itemsPerPage ?? 10,
51
+ sortColumn: defaults?.sortColumn ?? '',
52
+ sortDirection: defaults?.sortDirection ?? 'asc',
53
+ searchTerm: defaults?.searchTerm ?? '',
54
+ groupByKey: defaults?.groupByKey ?? null
55
+ };
56
+ }
57
+ function isFilterOperator(value) {
58
+ return TABLE_QUERY_FILTER_OPERATORS.includes(value);
59
+ }
60
+ /** Write-side validation: never serialize structurally invalid state. */
61
+ function assertValidQuery(query) {
62
+ if (!Number.isSafeInteger(query.page) || query.page < 1) {
63
+ throw new TypeError(`[table-query] page must be a positive integer, got ${query.page}`);
64
+ }
65
+ if (!Number.isSafeInteger(query.itemsPerPage) || query.itemsPerPage < 1) {
66
+ throw new TypeError(`[table-query] itemsPerPage must be a positive integer, got ${query.itemsPerPage}`);
67
+ }
68
+ if (query.sortDirection !== 'asc' && query.sortDirection !== 'desc') {
69
+ throw new TypeError(`[table-query] sortDirection must be 'asc' or 'desc', got ${String(query.sortDirection)}`);
70
+ }
71
+ if (query.groupByKey === '') {
72
+ throw new TypeError("[table-query] groupByKey must be a non-empty string or null, got ''");
73
+ }
74
+ for (const filter of query.activeFilters) {
75
+ if (!filter.column) {
76
+ throw new TypeError('[table-query] filter.column must be a non-empty string');
77
+ }
78
+ if (!isFilterOperator(filter.operator)) {
79
+ throw new TypeError(`[table-query] unknown filter operator '${String(filter.operator)}' on column '${filter.column}'`);
80
+ }
81
+ }
82
+ }
83
+ /** Read-side tolerant integer parsing: anything non-numeric → null. */
84
+ function parsePositiveInt(raw) {
85
+ if (raw === null || !/^\d+$/.test(raw))
86
+ return null;
87
+ const value = Number(raw);
88
+ return Number.isSafeInteger(value) && value >= 1 ? value : null;
89
+ }
90
+ /**
91
+ * Parse one `filter` param value (`<column>:<operator>:<value>`, column and
92
+ * value URI-component-encoded). Returns null for malformed entries — the
93
+ * caller skips them (read tolerant).
94
+ */
95
+ function parseFilterParam(raw) {
96
+ const parts = raw.split(':');
97
+ if (parts.length !== 3)
98
+ return null;
99
+ const [encodedColumn, operator, encodedValue] = parts;
100
+ if (!isFilterOperator(operator))
101
+ return null;
102
+ try {
103
+ const column = decodeURIComponent(encodedColumn);
104
+ if (!column)
105
+ return null;
106
+ return { column, operator, value: decodeURIComponent(encodedValue) };
107
+ }
108
+ catch {
109
+ // Malformed percent-encoding (URIError) — skip the entry.
110
+ return null;
111
+ }
112
+ }
113
+ /**
114
+ * Serialize a table query into `URLSearchParams`, eliding every value that
115
+ * equals the resolved defaults (see {@link TableQueryDefaults}).
116
+ *
117
+ * Key scheme (each key optionally prefixed via `options.prefix`):
118
+ * - `q` — search term
119
+ * - `page` — 1-based page
120
+ * - `size` — items per page
121
+ * - `sort` — sort column; an **empty** `sort=` marks "explicitly unsorted"
122
+ * and is only written when the defaults specify a sort column
123
+ * - `dir` — `desc` (ascending is implied when absent)
124
+ * - `group` — group key; an empty `group=` marks "explicitly ungrouped"
125
+ * - `filter` — repeated, `<column>:<operator>:<value>` with column and value
126
+ * URI-component-encoded so the `:` separators stay unambiguous
127
+ *
128
+ * When `sortColumn` is empty the sort direction is meaningless and is
129
+ * normalized away (it parses back as `'asc'`).
130
+ *
131
+ * Also handy for building the backend request inside `queryFn` — the same
132
+ * scheme works as an API query string.
133
+ *
134
+ * @param query - Query emitted by the table (`TableQuery` is assignable).
135
+ * @param options - Elision defaults + key prefix.
136
+ * @returns Fresh `URLSearchParams` containing only non-default values.
137
+ * @throws TypeError when the query is structurally invalid (write strict).
138
+ */
139
+ export function tableQueryToSearchParams(query, options = {}) {
140
+ assertValidQuery(query);
141
+ const d = resolveDefaults(options.defaults);
142
+ const k = paramKeys(options.prefix ?? '');
143
+ const sp = new URLSearchParams();
144
+ if (query.searchTerm !== d.searchTerm)
145
+ sp.set(k.q, query.searchTerm);
146
+ if (query.page !== d.page)
147
+ sp.set(k.page, String(query.page));
148
+ if (query.itemsPerPage !== d.itemsPerPage)
149
+ sp.set(k.size, String(query.itemsPerPage));
150
+ if (query.sortColumn === '') {
151
+ // Unsorted: only mark explicitly when the defaults would re-introduce a sort.
152
+ if (d.sortColumn !== '')
153
+ sp.set(k.sort, '');
154
+ }
155
+ else if (query.sortColumn !== d.sortColumn || query.sortDirection !== d.sortDirection) {
156
+ sp.set(k.sort, query.sortColumn);
157
+ if (query.sortDirection === 'desc')
158
+ sp.set(k.dir, 'desc');
159
+ }
160
+ if (query.groupByKey !== d.groupByKey)
161
+ sp.set(k.group, query.groupByKey ?? '');
162
+ for (const filter of query.activeFilters) {
163
+ sp.append(k.filter, `${encodeURIComponent(filter.column)}:${filter.operator}:${encodeURIComponent(filter.value)}`);
164
+ }
165
+ return sp;
166
+ }
167
+ /**
168
+ * Parse `URLSearchParams` back into a full table query, filling every missing
169
+ * param from the resolved defaults (see {@link TableQueryDefaults}).
170
+ *
171
+ * Read tolerant: non-numeric `page`/`size` fall back to the defaults, an
172
+ * unknown `dir` becomes `'asc'`, and malformed `filter` entries (wrong shape,
173
+ * unknown operator, broken percent-encoding) are skipped individually.
174
+ *
175
+ * Works anywhere a `URLSearchParams` exists — including `url.searchParams`
176
+ * in a server `load`, to run the initial server-mode fetch during SSR.
177
+ *
178
+ * @param params - Search params to read (not mutated).
179
+ * @param options - Fallback defaults + key prefix.
180
+ * @returns Complete query object (assignable to `TableQuery`).
181
+ */
182
+ export function searchParamsToTableQuery(params, options = {}) {
183
+ const d = resolveDefaults(options.defaults);
184
+ const k = paramKeys(options.prefix ?? '');
185
+ let sortColumn = d.sortColumn;
186
+ let sortDirection = d.sortDirection;
187
+ const rawSort = params.get(k.sort);
188
+ if (rawSort !== null) {
189
+ sortColumn = rawSort;
190
+ sortDirection = rawSort !== '' && params.get(k.dir) === 'desc' ? 'desc' : 'asc';
191
+ }
192
+ const rawGroup = params.get(k.group);
193
+ const activeFilters = [];
194
+ for (const raw of params.getAll(k.filter)) {
195
+ const filter = parseFilterParam(raw);
196
+ if (filter)
197
+ activeFilters.push(filter);
198
+ }
199
+ return {
200
+ page: parsePositiveInt(params.get(k.page)) ?? d.page,
201
+ itemsPerPage: parsePositiveInt(params.get(k.size)) ?? d.itemsPerPage,
202
+ sortColumn,
203
+ sortDirection,
204
+ searchTerm: params.get(k.q) ?? d.searchTerm,
205
+ activeFilters,
206
+ groupByKey: rawGroup !== null ? (rawGroup === '' ? null : rawGroup) : d.groupByKey
207
+ };
208
+ }
209
+ /**
210
+ * Merge a table query into existing search params: all managed keys (`q`,
211
+ * `page`, `size`, `sort`, `dir`, `group`, `filter` — with the configured
212
+ * prefix) are replaced by the serialized query, every other param is
213
+ * preserved untouched. Managed keys whose value returned to the default are
214
+ * removed (default elision).
215
+ *
216
+ * @param existing - Current search params (not mutated — a copy is returned).
217
+ * @param query - Query emitted by the table.
218
+ * @param options - Elision defaults + key prefix.
219
+ * @returns New `URLSearchParams` with the query applied.
220
+ * @throws TypeError when the query is structurally invalid (write strict).
221
+ */
222
+ export function applyTableQueryToSearchParams(existing, query, options = {}) {
223
+ const serialized = tableQueryToSearchParams(query, options);
224
+ const next = new URLSearchParams(existing);
225
+ for (const key of Object.values(paramKeys(options.prefix ?? ''))) {
226
+ next.delete(key);
227
+ }
228
+ for (const [key, value] of serialized) {
229
+ next.append(key, value);
230
+ }
231
+ return next;
232
+ }
@@ -1,3 +1,4 @@
1
+ import { type TableQueryParams, type TableQueryUrlOptions } from './table-query';
1
2
  export type UrlArrayStrategy = 'repeat' | 'csv';
2
3
  export type UrlParamOptions<T> = {
3
4
  parse: (sp: URLSearchParams) => T | null | undefined;
@@ -7,7 +8,6 @@ export type UrlParamOptions<T> = {
7
8
  };
8
9
  export declare function updateUrlSearchParams(next: URLSearchParams | Record<string, string | string[]>, opts?: {
9
10
  replaceState?: boolean;
10
- keepPath?: boolean;
11
11
  }): void;
12
12
  export declare function createUrlParam<T>(_key: string, options: UrlParamOptions<T>): {
13
13
  readonly get: (sp: URLSearchParams) => T;
@@ -19,3 +19,64 @@ export declare function useUrlArrayParam(key: string, opts: {
19
19
  strategy?: UrlArrayStrategy;
20
20
  delimiter?: string;
21
21
  }): readonly [() => string[], (next: string[]) => void];
22
+ /** Options for {@link createTableQueryUrlSync}. */
23
+ export interface TableQueryUrlSyncOptions extends TableQueryUrlOptions {
24
+ /**
25
+ * Replace the current history entry instead of pushing a new one. The
26
+ * default (`true`) keeps every sort/filter/page interaction from polluting
27
+ * the back button.
28
+ * @default true
29
+ */
30
+ replaceState?: boolean;
31
+ }
32
+ /**
33
+ * Opt-in URL sync for a table in server mode: mirrors the `TableQuery` the
34
+ * table emits onto `?q=…&sort=…&page=…` query params, so the view state
35
+ * survives reloads and can be shared as a link.
36
+ *
37
+ * Two directions, both explicit:
38
+ * - **URL → query**: `initialQuery` is parsed once at creation (SSR-safe) —
39
+ * seed the table (`initialPage`, `initialGroupBy`, controlled `searchTerm`)
40
+ * and run the first fetch from it.
41
+ * - **query → URL**: pass `syncQuery` the query from `onQueryChange`, or call
42
+ * it inside `queryFn` (when `queryFn` is set, `onQueryChange` does not
43
+ * fire). It rewrites only its own — optionally prefixed — params via
44
+ * `goto` (`replaceState`, `noScroll`, `keepFocus`); unrelated params are
45
+ * preserved. Values equal to `options.defaults` are elided, so a table in
46
+ * its default state leaves the URL clean.
47
+ *
48
+ * Set `options.defaults` to the table's initial props (`itemsPerPage`,
49
+ * `initialPage`, `initialGroupBy`) so the elision baseline matches the state
50
+ * the table actually starts in.
51
+ *
52
+ * @example
53
+ * ```svelte
54
+ * <script lang="ts">
55
+ * import { Table } from '@urbicon-ui/table';
56
+ * import { createTableQueryUrlSync } from '@urbicon-ui/sveltekit-utils/url.svelte';
57
+ *
58
+ * const sync = createTableQueryUrlSync({ defaults: { itemsPerPage: 25 } });
59
+ * </script>
60
+ *
61
+ * <Table
62
+ * mode="server"
63
+ * columns={columns}
64
+ * itemsPerPage={25}
65
+ * initialPage={sync.initialQuery.page}
66
+ * queryFn={async (query, { signal }) => {
67
+ * sync.syncQuery(query);
68
+ * const res = await fetch(`/api/users?${new URLSearchParams(...)}`, { signal });
69
+ * const data = await res.json();
70
+ * return { items: data.results, totalItems: data.total };
71
+ * }}
72
+ * />
73
+ * ```
74
+ *
75
+ * @param options - Elision defaults, key prefix, history behaviour.
76
+ * @returns `initialQuery` (the URL parsed at creation time) + `syncQuery`
77
+ * (write a query back to the URL).
78
+ */
79
+ export declare function createTableQueryUrlSync(options?: TableQueryUrlSyncOptions): {
80
+ readonly initialQuery: TableQueryParams;
81
+ readonly syncQuery: (query: TableQueryParams) => void;
82
+ };
@@ -1,5 +1,6 @@
1
1
  import { goto } from '$app/navigation';
2
2
  import { page } from '$app/state';
3
+ import { applyTableQueryToSearchParams, searchParamsToTableQuery } from './table-query';
3
4
  // Local imperative use of URLSearchParams — not reactive state — so the
4
5
  // SvelteURLSearchParams wrapper is unnecessary here. Likewise for `goto`:
5
6
  // we pass constructed relative paths, not resolved route ids; callers of
@@ -25,7 +26,7 @@ export function updateUrlSearchParams(next, opts) {
25
26
  }
26
27
  }
27
28
  const q = base.toString();
28
- const path = opts?.keepPath ? page.url.pathname : '/';
29
+ const path = page.url.pathname;
29
30
  goto(q ? `${path}?${q}` : path, {
30
31
  replaceState: opts?.replaceState ?? true,
31
32
  noScroll: true,
@@ -44,7 +45,7 @@ export function createUrlParam(_key, options) {
44
45
  for (const [k, v] of nextSp)
45
46
  current.append(k, v);
46
47
  const q = current.toString();
47
- goto(q ? `?${q}` : '/', {
48
+ goto(q ? `?${q}` : page.url.pathname, {
48
49
  replaceState: options.replaceState ?? true,
49
50
  noScroll: true,
50
51
  keepFocus: true
@@ -80,3 +81,63 @@ export function useUrlArrayParam(key, opts) {
80
81
  };
81
82
  return useUrlParam(key, { parse, serialize, initial: opts.initial });
82
83
  }
84
+ /**
85
+ * Opt-in URL sync for a table in server mode: mirrors the `TableQuery` the
86
+ * table emits onto `?q=…&sort=…&page=…` query params, so the view state
87
+ * survives reloads and can be shared as a link.
88
+ *
89
+ * Two directions, both explicit:
90
+ * - **URL → query**: `initialQuery` is parsed once at creation (SSR-safe) —
91
+ * seed the table (`initialPage`, `initialGroupBy`, controlled `searchTerm`)
92
+ * and run the first fetch from it.
93
+ * - **query → URL**: pass `syncQuery` the query from `onQueryChange`, or call
94
+ * it inside `queryFn` (when `queryFn` is set, `onQueryChange` does not
95
+ * fire). It rewrites only its own — optionally prefixed — params via
96
+ * `goto` (`replaceState`, `noScroll`, `keepFocus`); unrelated params are
97
+ * preserved. Values equal to `options.defaults` are elided, so a table in
98
+ * its default state leaves the URL clean.
99
+ *
100
+ * Set `options.defaults` to the table's initial props (`itemsPerPage`,
101
+ * `initialPage`, `initialGroupBy`) so the elision baseline matches the state
102
+ * the table actually starts in.
103
+ *
104
+ * @example
105
+ * ```svelte
106
+ * <script lang="ts">
107
+ * import { Table } from '@urbicon-ui/table';
108
+ * import { createTableQueryUrlSync } from '@urbicon-ui/sveltekit-utils/url.svelte';
109
+ *
110
+ * const sync = createTableQueryUrlSync({ defaults: { itemsPerPage: 25 } });
111
+ * </script>
112
+ *
113
+ * <Table
114
+ * mode="server"
115
+ * columns={columns}
116
+ * itemsPerPage={25}
117
+ * initialPage={sync.initialQuery.page}
118
+ * queryFn={async (query, { signal }) => {
119
+ * sync.syncQuery(query);
120
+ * const res = await fetch(`/api/users?${new URLSearchParams(...)}`, { signal });
121
+ * const data = await res.json();
122
+ * return { items: data.results, totalItems: data.total };
123
+ * }}
124
+ * />
125
+ * ```
126
+ *
127
+ * @param options - Elision defaults, key prefix, history behaviour.
128
+ * @returns `initialQuery` (the URL parsed at creation time) + `syncQuery`
129
+ * (write a query back to the URL).
130
+ */
131
+ export function createTableQueryUrlSync(options = {}) {
132
+ const initialQuery = searchParamsToTableQuery(page.url.searchParams, options);
133
+ function syncQuery(query) {
134
+ const next = applyTableQueryToSearchParams(page.url.searchParams, query, options);
135
+ const qs = next.toString();
136
+ goto(`${page.url.pathname}${qs ? `?${qs}` : ''}${page.url.hash}`, {
137
+ replaceState: options.replaceState ?? true,
138
+ noScroll: true,
139
+ keepFocus: true
140
+ });
141
+ }
142
+ return { initialQuery, syncQuery };
143
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urbicon-ui/sveltekit-utils",
3
- "version": "6.21.2",
3
+ "version": "6.22.0",
4
4
  "description": "SvelteKit helper utilities — createCronRunner and URL-state runes",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -40,10 +40,17 @@
40
40
  "./cron": {
41
41
  "types": "./dist/cron.d.ts",
42
42
  "import": "./dist/cron.js"
43
+ },
44
+ "./table-query": {
45
+ "types": "./dist/table-query.d.ts",
46
+ "import": "./dist/table-query.js",
47
+ "default": "./dist/table-query.js"
43
48
  }
44
49
  },
45
50
  "files": [
46
- "dist"
51
+ "dist",
52
+ "!dist/**/*.test.*",
53
+ "!dist/**/*.spec.*"
47
54
  ],
48
55
  "scripts": {
49
56
  "dev": "svelte-package --watch",
@@ -1 +0,0 @@
1
- export {};
package/dist/cron.test.js DELETED
@@ -1,137 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
- import { createCronRunner } from './cron';
3
- describe('createCronRunner', () => {
4
- beforeEach(() => {
5
- vi.useFakeTimers();
6
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 200 })));
7
- });
8
- afterEach(() => {
9
- vi.useRealTimers();
10
- vi.restoreAllMocks();
11
- });
12
- it('should not be running initially', () => {
13
- const runner = createCronRunner({
14
- secret: 'test-secret',
15
- jobs: [{ path: '/api/test', intervalSeconds: 60 }]
16
- });
17
- expect(runner.isRunning()).toBe(false);
18
- });
19
- it('should be running after start()', () => {
20
- const runner = createCronRunner({
21
- secret: 'test-secret',
22
- jobs: [{ path: '/api/test', intervalSeconds: 60 }]
23
- });
24
- runner.start();
25
- expect(runner.isRunning()).toBe(true);
26
- runner.stop();
27
- });
28
- it('should not be running after stop()', () => {
29
- const runner = createCronRunner({
30
- secret: 'test-secret',
31
- jobs: [{ path: '/api/test', intervalSeconds: 60 }]
32
- });
33
- runner.start();
34
- runner.stop();
35
- expect(runner.isRunning()).toBe(false);
36
- });
37
- it('should not start twice', () => {
38
- const runner = createCronRunner({
39
- secret: 'test-secret',
40
- jobs: [{ path: '/api/test', intervalSeconds: 10 }]
41
- });
42
- runner.start();
43
- runner.start();
44
- vi.advanceTimersByTime(10_000);
45
- expect(fetch).toHaveBeenCalledTimes(1);
46
- runner.stop();
47
- });
48
- it('should call fetch for each job at the correct interval', async () => {
49
- const runner = createCronRunner({
50
- secret: 'my-secret',
51
- baseUrl: 'http://localhost:5000',
52
- jobs: [
53
- { path: '/api/job-a', intervalSeconds: 10 },
54
- { path: '/api/job-b', intervalSeconds: 20, method: 'GET' }
55
- ]
56
- });
57
- runner.start();
58
- // At 10s: job-a fires
59
- await vi.advanceTimersByTimeAsync(10_000);
60
- expect(fetch).toHaveBeenCalledTimes(1);
61
- expect(fetch).toHaveBeenCalledWith('http://localhost:5000/api/job-a', {
62
- method: 'POST',
63
- headers: { 'x-cron-secret': 'my-secret' }
64
- });
65
- // At 20s: job-a fires again + job-b fires for the first time
66
- await vi.advanceTimersByTimeAsync(10_000);
67
- expect(fetch).toHaveBeenCalledTimes(3);
68
- expect(fetch).toHaveBeenCalledWith('http://localhost:5000/api/job-b', {
69
- method: 'GET',
70
- headers: { 'x-cron-secret': 'my-secret' }
71
- });
72
- runner.stop();
73
- });
74
- it('should use default baseUrl when not provided', async () => {
75
- const runner = createCronRunner({
76
- secret: 's',
77
- jobs: [{ path: '/api/ping', intervalSeconds: 5 }]
78
- });
79
- runner.start();
80
- await vi.advanceTimersByTimeAsync(5_000);
81
- expect(fetch).toHaveBeenCalledWith('http://localhost:3000/api/ping', expect.any(Object));
82
- runner.stop();
83
- });
84
- it('should use custom secretHeader', async () => {
85
- const runner = createCronRunner({
86
- secret: 'abc',
87
- secretHeader: 'x-internal-key',
88
- jobs: [{ path: '/api/test', intervalSeconds: 5 }]
89
- });
90
- runner.start();
91
- await vi.advanceTimersByTimeAsync(5_000);
92
- expect(fetch).toHaveBeenCalledWith(expect.any(String), {
93
- method: 'POST',
94
- headers: { 'x-internal-key': 'abc' }
95
- });
96
- runner.stop();
97
- });
98
- it('should call onError when fetch throws', async () => {
99
- const error = new Error('Network error');
100
- vi.mocked(fetch).mockRejectedValueOnce(error);
101
- const onError = vi.fn();
102
- const job = { path: '/api/fail', intervalSeconds: 5 };
103
- const runner = createCronRunner({
104
- secret: 's',
105
- jobs: [job],
106
- onError
107
- });
108
- runner.start();
109
- await vi.advanceTimersByTimeAsync(5_000);
110
- expect(onError).toHaveBeenCalledWith(job, error);
111
- runner.stop();
112
- });
113
- it('should not call onError when fetch succeeds', async () => {
114
- const onError = vi.fn();
115
- const runner = createCronRunner({
116
- secret: 's',
117
- jobs: [{ path: '/api/ok', intervalSeconds: 5 }],
118
- onError
119
- });
120
- runner.start();
121
- await vi.advanceTimersByTimeAsync(5_000);
122
- expect(onError).not.toHaveBeenCalled();
123
- runner.stop();
124
- });
125
- it('should stop all timers and not fire after stop()', async () => {
126
- const runner = createCronRunner({
127
- secret: 's',
128
- jobs: [{ path: '/api/test', intervalSeconds: 5 }]
129
- });
130
- runner.start();
131
- await vi.advanceTimersByTimeAsync(5_000);
132
- expect(fetch).toHaveBeenCalledTimes(1);
133
- runner.stop();
134
- await vi.advanceTimersByTimeAsync(15_000);
135
- expect(fetch).toHaveBeenCalledTimes(1);
136
- });
137
- });