cookie-prefs 0.1.3 → 0.2.1

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
@@ -87,6 +87,15 @@ export function SidebarToggle() {
87
87
  }
88
88
  ```
89
89
 
90
+ Several at once with `usePrefs`, which takes a partial patch:
91
+
92
+ ```tsx
93
+ import { usePrefs } from 'cookie-prefs/react'
94
+
95
+ const [{ theme, sidebar }, set] = usePrefs(prefs)
96
+ set({ sidebar: false, theme: 'dark' })
97
+ ```
98
+
90
99
  Read it in a Server Component (this makes the route dynamic):
91
100
 
92
101
  ```tsx
@@ -114,12 +123,24 @@ export async function setLocale(locale: string) {
114
123
 
115
124
  ## The entries
116
125
 
117
- | Import | What it is | Guide |
118
- | -------------------- | ------------------------------------------------------------------------------------------- | ----- |
119
- | `cookie-prefs` | Core, no DOM required: `definePrefs`, `pref.*`, `readPrefs`, `snapshotPrefs`, `prefsScript` | [Core](docs/core.md) |
120
- | `cookie-prefs/react` | `usePref`, and `PrefsProvider` for SSR outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
121
- | `cookie-prefs/next` | Server-only: `PrefsProvider`, `getPrefs` (App Router) | [Next.js](docs/nextjs.md) |
122
- | `cookie-prefs/theme` | next-themes compatible `ThemeProvider` and `useTheme` | [Theme](docs/theme.md) |
126
+ | Import | What it is | Guide |
127
+ | --------------------- | ------------------------------------------------------------------------------ | ----- |
128
+ | `cookie-prefs` | Core, no DOM required: `definePrefs`, `pref.*`, `readPrefs`, `snapshotPrefs` | [Core](docs/core.md) |
129
+ | `cookie-prefs/react` | `usePref`, `usePrefs`, and `PrefsProvider` for SSR outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
130
+ | `cookie-prefs/script` | `prefsScript`, the pre-paint script for `PrefsProvider` outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
131
+ | `cookie-prefs/next` | Server-only: `PrefsProvider`, `getPrefs` (App Router) | [Next.js](docs/nextjs.md) |
132
+ | `cookie-prefs/theme` | next-themes compatible `ThemeProvider` and `useTheme` | [Theme](docs/theme.md) |
133
+ | `cookie-prefs/theme/next` | Server-only: `getTheme`, the stored theme in the App Router (opt-in) | [Theme](docs/theme.md#reading-the-theme-on-the-server) |
134
+ | `cookie-prefs/theme/server` | `readTheme`, the stored theme from request cookies on any server | [Theme](docs/theme.md#reading-the-theme-on-the-server) |
135
+ | `cookie-prefs/theme/color` | `ThemeColor`, keeps `<meta name="theme-color">` in sync with the theme (opt-in) | [Theme](docs/theme.md#browser-ui-colour-theme-color) |
136
+
137
+ ## Renaming an enum value
138
+
139
+ Users keep their choice when an enum value is renamed: a cookie holding an old name reads as its new value on the server, on the client and in the pre-paint script, and the next `set()` writes the new name.
140
+
141
+ ```ts
142
+ density: pref.enum(['compact', 'comfortable']).default('comfortable').migrate({ cozy: 'comfortable' }),
143
+ ```
123
144
 
124
145
  ## Next.js modes
125
146
 
@@ -138,6 +159,10 @@ export async function setLocale(locale: string) {
138
159
 
139
160
  Props and hook fields keep their next-themes names and defaults; the choice lives in a cookie, and existing `localStorage` themes are moved once. Setup and the full list of differences are in the [Theme guide](docs/theme.md).
140
161
 
162
+ To render from the stored theme on the server (`<html className>`), opt in with `await getTheme({ themes })` from `cookie-prefs/theme/next`, or `readTheme(cookieHeader, { themes })` from `cookie-prefs/theme/server` outside Next.js. It makes the route dynamic, returns `'system'` unresolved, and the inline script stays in charge before hydration; see [Reading the theme on the server](docs/theme.md#reading-the-theme-on-the-server).
163
+
164
+ To colour the browser UI per theme (`<meta name="theme-color">`, next-themes #78), render `<ThemeColor colors={{ light: '#ffffff', dark: '#0a0a0a' }} />` from `cookie-prefs/theme/color` inside `ThemeProvider`. It is right before hydration, follows `setTheme`, the OS scheme, `forcedTheme` and other tabs, and takes precedence over `viewport.themeColor`; see [Browser UI colour](docs/theme.md#browser-ui-colour-theme-color).
165
+
141
166
  ## Security and platform notes
142
167
 
143
168
  Prefs are readable by every script on the page: never store secrets. The pre-paint script needs a CSP nonce under strict policies, and Safari caps script-written cookies at 7 days (cookie-prefs refreshes the long-lived ones once per page load). Details, Trusted Types, iframes and non-goals are in [Security and platform notes](docs/security.md).
@@ -152,3 +177,5 @@ Prefs are readable by every script on the page: never store secrets. The pre-pai
152
177
  ## More
153
178
 
154
179
  Guides: [Core and React](docs/core.md), [Next.js](docs/nextjs.md), [Reflection](docs/reflection.md), [Theme](docs/theme.md), [Security and non-goals](docs/security.md). Design decisions, verified facts and limitations: [docs/design.md](docs/design.md). Contributing: [CONTRIBUTING.md](CONTRIBUTING.md). License: [MIT](LICENSE).
180
+
181
+ Roadmap to 1.0: [docs/roadmap.md](docs/roadmap.md).
package/dist/index.cjs CHANGED
@@ -20,6 +20,7 @@ var builder = (def) => ({
20
20
  ...def,
21
21
  default: (d) => builder({ ...def, d }),
22
22
  options: (o) => builder({ ...def, o: merge(def.o, o) }),
23
+ migrate: (a) => builder({ ...def, a: merge(def.a, a) }),
23
24
  reflect: (r, m) => builder({ ...def, r: [].concat(r), m })
24
25
  });
25
26
 
@@ -40,11 +41,6 @@ var apply = (targets, kind, s) => {
40
41
  } catch {
41
42
  }
42
43
  };
43
- var SOURCE = '(function(P){var r=document.documentElement,C="; "+document.cookie,k=0,j,p,t,n,i,e;for(P=JSON.parse(P);p=P[k++];)try{t=p[2];n=C.split("; "+p[0]+"=")[1];if(n!=null)try{n=decodeURIComponent(n.split(";")[0].replace(/^"(.*)"$/,"$1"));if(t===1){t=parseFloat(n);n=t===+n&&isFinite(t)?""+t:null}else if(t)n={}.hasOwnProperty.call(t,n)?t[n]:null}catch(e){n=null}if(n==null)n=p[3];for(j=0;i=p[1][j++];)if(i=="class"){for(e in t)r.classList.remove(t[e]);n!=null&&r.classList.add(n)}else i[0]=="-"?n==null?r.style.removeProperty(i):r.style.setProperty(i,n):n==null?r.removeAttribute(i):r.setAttribute(i,n)}catch(e){}})(';
44
- var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
45
- /[<>&\u2028\u2029]/g,
46
- (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
47
- ) + ")" : "";
48
44
 
49
45
  // src/core/sync.ts
50
46
  var open = () => {
@@ -55,16 +51,23 @@ var open = () => {
55
51
  };
56
52
  var subs = /* @__PURE__ */ new Set();
57
53
  var channel;
54
+ var timer;
58
55
  var changed = () => subs.forEach((check) => check());
59
56
  var shown = () => document.visibilityState == "visible" && changed();
57
+ var retry = (delay) => {
58
+ clearTimeout(timer);
59
+ if (delay < 4096 && document.visibilityState == "visible") timer = setTimeout(retry, delay, delay * 2);
60
+ changed();
61
+ };
60
62
  var hub = (check, on) => {
61
63
  if (on ? subs.add(check).size == 1 : subs.delete(check) && !subs.size) {
62
64
  const method = on ? "addEventListener" : "removeEventListener";
63
65
  globalThis.cookieStore?.[method]("change", changed);
64
66
  document[method]("visibilitychange", shown);
67
+ clearTimeout(timer);
65
68
  channel?.close();
66
69
  channel = on ? open() : void 0;
67
- if (channel) channel.onmessage = changed;
70
+ if (channel) channel.onmessage = () => retry(16);
68
71
  }
69
72
  };
70
73
  var post = () => {
@@ -80,7 +83,14 @@ var bind = (key, def, prefix, options) => {
80
83
  const attrs = merge(defaults, options, def.o, { name });
81
84
  const fallback = def.d;
82
85
  const targets = def.r;
83
- const kind = def.values ? Object.fromEntries(def.values.map((v) => [v, merge({ [v]: v }, def.m)[v]])) : def.k;
86
+ const values = def.values;
87
+ const enums = values && new Map(
88
+ Object.entries({ ...def.a }).filter((e) => values.includes(e[1])).concat(values.map((v) => [v, v]))
89
+ );
90
+ const kind = enums ? Object.fromEntries(
91
+ [...enums].map(([raw, v]) => [raw, merge({ [v]: v }, def.m)[v]])
92
+ ) : def.k;
93
+ const parse = enums ? (raw) => enums.get(raw) : def.p;
84
94
  if (typeof process == "object" && process.env.NODE_ENV != "production") {
85
95
  if (!name) throw TypeError(`cookie-prefs: ${key} needs a non-empty cookie name`);
86
96
  if (targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
@@ -95,7 +105,7 @@ var bind = (key, def, prefix, options) => {
95
105
  if (typeof raw == "string" && raw.length <= 4096) {
96
106
  if (!cache.has(raw) || typeof document == "undefined") {
97
107
  if (cache.size > 9) cache.clear();
98
- cache.set(raw, def.p(raw));
108
+ cache.set(raw, parse(raw));
99
109
  }
100
110
  const value = cache.get(raw);
101
111
  if (value !== void 0) return value;
@@ -135,10 +145,20 @@ var bind = (key, def, prefix, options) => {
135
145
  });
136
146
  }
137
147
  };
148
+ let rejected = false;
138
149
  const write = (value) => {
139
150
  try {
140
151
  document.cookie = serialize(attrs, value);
141
152
  post();
153
+ if (typeof process == "object" && process.env.NODE_ENV != "production" && !rejected && value != null) {
154
+ const text = value.toWellFormed?.() ?? value;
155
+ if (rawOf(document.cookie, name) !== text) {
156
+ rejected = true;
157
+ console.warn(
158
+ `cookie-prefs: ${key}.set() wrote a cookie that does not read back: the browser dropped it, or another cookie named ${name} hides it. Browsers drop a cookie whose name and value exceed 4096 bytes (here ${name.length + encodeURIComponent(text).length}), one with a __Host- prefix, SameSite=None or Partitioned but no Secure, and one for a domain or path this page is not on.`
159
+ );
160
+ }
161
+ }
142
162
  } catch {
143
163
  }
144
164
  check();
@@ -179,7 +199,7 @@ var bind = (key, def, prefix, options) => {
179
199
 
180
200
  // src/index.ts
181
201
  var pref = {
182
- enum: (values) => builder({ values, p: (raw) => values.includes(raw) ? raw : void 0, s: String }),
202
+ enum: (values) => builder({ values, s: String }),
183
203
  boolean: () => builder({
184
204
  k: { true: "true", false: "false" },
185
205
  p: (raw) => raw == "true" || (raw == "false" ? false : void 0),
@@ -223,14 +243,8 @@ function snapshotPrefs(prefs, source) {
223
243
  })
224
244
  );
225
245
  }
226
- function prefsScript(prefs) {
227
- return script(
228
- Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r)
229
- );
230
- }
231
246
 
232
247
  exports.definePrefs = definePrefs;
233
248
  exports.pref = pref;
234
- exports.prefsScript = prefsScript;
235
249
  exports.readPrefs = readPrefs;
236
250
  exports.snapshotPrefs = snapshotPrefs;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-CQ_6o7nc.cjs';
2
- export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-CQ_6o7nc.cjs';
1
+ import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-C5uwWL7s.cjs';
2
+ export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-C5uwWL7s.cjs';
3
3
 
4
4
  /**
5
5
  * Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
@@ -113,14 +113,6 @@ declare function readPrefs<P extends PrefsRecord>(prefs: P, source: CookieSource
113
113
  * <PrefsProvider snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}>
114
114
  */
115
115
  declare function snapshotPrefs(prefs: PrefsRecord, source: CookieSource): PrefsSnapshot;
116
- /**
117
- * Source of a blocking inline script that applies every `.reflect()` declaration to
118
- * `<html>` from `document.cookie` before first paint. Returns `''` when no pref
119
- * reflects. The output is fixed code plus escaped JSON config, safe to inline.
120
- * @example
121
- * <script nonce={nonce} dangerouslySetInnerHTML={{ __html: prefsScript(prefs) }} />
122
- */
123
- declare function prefsScript(prefs: PrefsRecord): string;
124
116
 
125
- export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
117
+ export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, readPrefs, snapshotPrefs };
126
118
  export type { PrefFactory, StandardSchemaV1 };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-CQ_6o7nc.js';
2
- export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-CQ_6o7nc.js';
1
+ import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-C5uwWL7s.js';
2
+ export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-C5uwWL7s.js';
3
3
 
4
4
  /**
5
5
  * Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
@@ -113,14 +113,6 @@ declare function readPrefs<P extends PrefsRecord>(prefs: P, source: CookieSource
113
113
  * <PrefsProvider snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}>
114
114
  */
115
115
  declare function snapshotPrefs(prefs: PrefsRecord, source: CookieSource): PrefsSnapshot;
116
- /**
117
- * Source of a blocking inline script that applies every `.reflect()` declaration to
118
- * `<html>` from `document.cookie` before first paint. Returns `''` when no pref
119
- * reflects. The output is fixed code plus escaped JSON config, safe to inline.
120
- * @example
121
- * <script nonce={nonce} dangerouslySetInnerHTML={{ __html: prefsScript(prefs) }} />
122
- */
123
- declare function prefsScript(prefs: PrefsRecord): string;
124
116
 
125
- export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
117
+ export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, readPrefs, snapshotPrefs };
126
118
  export type { PrefFactory, StandardSchemaV1 };
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ var builder = (def) => ({
18
18
  ...def,
19
19
  default: (d) => builder({ ...def, d }),
20
20
  options: (o) => builder({ ...def, o: merge(def.o, o) }),
21
+ migrate: (a) => builder({ ...def, a: merge(def.a, a) }),
21
22
  reflect: (r, m) => builder({ ...def, r: [].concat(r), m })
22
23
  });
23
24
 
@@ -38,11 +39,6 @@ var apply = (targets, kind, s) => {
38
39
  } catch {
39
40
  }
40
41
  };
41
- var SOURCE = '(function(P){var r=document.documentElement,C="; "+document.cookie,k=0,j,p,t,n,i,e;for(P=JSON.parse(P);p=P[k++];)try{t=p[2];n=C.split("; "+p[0]+"=")[1];if(n!=null)try{n=decodeURIComponent(n.split(";")[0].replace(/^"(.*)"$/,"$1"));if(t===1){t=parseFloat(n);n=t===+n&&isFinite(t)?""+t:null}else if(t)n={}.hasOwnProperty.call(t,n)?t[n]:null}catch(e){n=null}if(n==null)n=p[3];for(j=0;i=p[1][j++];)if(i=="class"){for(e in t)r.classList.remove(t[e]);n!=null&&r.classList.add(n)}else i[0]=="-"?n==null?r.style.removeProperty(i):r.style.setProperty(i,n):n==null?r.removeAttribute(i):r.setAttribute(i,n)}catch(e){}})(';
42
- var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
43
- /[<>&\u2028\u2029]/g,
44
- (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
45
- ) + ")" : "";
46
42
 
47
43
  // src/core/sync.ts
48
44
  var open = () => {
@@ -53,16 +49,23 @@ var open = () => {
53
49
  };
54
50
  var subs = /* @__PURE__ */ new Set();
55
51
  var channel;
52
+ var timer;
56
53
  var changed = () => subs.forEach((check) => check());
57
54
  var shown = () => document.visibilityState == "visible" && changed();
55
+ var retry = (delay) => {
56
+ clearTimeout(timer);
57
+ if (delay < 4096 && document.visibilityState == "visible") timer = setTimeout(retry, delay, delay * 2);
58
+ changed();
59
+ };
58
60
  var hub = (check, on) => {
59
61
  if (on ? subs.add(check).size == 1 : subs.delete(check) && !subs.size) {
60
62
  const method = on ? "addEventListener" : "removeEventListener";
61
63
  globalThis.cookieStore?.[method]("change", changed);
62
64
  document[method]("visibilitychange", shown);
65
+ clearTimeout(timer);
63
66
  channel?.close();
64
67
  channel = on ? open() : void 0;
65
- if (channel) channel.onmessage = changed;
68
+ if (channel) channel.onmessage = () => retry(16);
66
69
  }
67
70
  };
68
71
  var post = () => {
@@ -78,7 +81,14 @@ var bind = (key, def, prefix, options) => {
78
81
  const attrs = merge(defaults, options, def.o, { name });
79
82
  const fallback = def.d;
80
83
  const targets = def.r;
81
- const kind = def.values ? Object.fromEntries(def.values.map((v) => [v, merge({ [v]: v }, def.m)[v]])) : def.k;
84
+ const values = def.values;
85
+ const enums = values && new Map(
86
+ Object.entries({ ...def.a }).filter((e) => values.includes(e[1])).concat(values.map((v) => [v, v]))
87
+ );
88
+ const kind = enums ? Object.fromEntries(
89
+ [...enums].map(([raw, v]) => [raw, merge({ [v]: v }, def.m)[v]])
90
+ ) : def.k;
91
+ const parse = enums ? (raw) => enums.get(raw) : def.p;
82
92
  if (typeof process == "object" && process.env.NODE_ENV != "production") {
83
93
  if (!name) throw TypeError(`cookie-prefs: ${key} needs a non-empty cookie name`);
84
94
  if (targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
@@ -93,7 +103,7 @@ var bind = (key, def, prefix, options) => {
93
103
  if (typeof raw == "string" && raw.length <= 4096) {
94
104
  if (!cache.has(raw) || typeof document == "undefined") {
95
105
  if (cache.size > 9) cache.clear();
96
- cache.set(raw, def.p(raw));
106
+ cache.set(raw, parse(raw));
97
107
  }
98
108
  const value = cache.get(raw);
99
109
  if (value !== void 0) return value;
@@ -133,10 +143,20 @@ var bind = (key, def, prefix, options) => {
133
143
  });
134
144
  }
135
145
  };
146
+ let rejected = false;
136
147
  const write = (value) => {
137
148
  try {
138
149
  document.cookie = serialize(attrs, value);
139
150
  post();
151
+ if (typeof process == "object" && process.env.NODE_ENV != "production" && !rejected && value != null) {
152
+ const text = value.toWellFormed?.() ?? value;
153
+ if (rawOf(document.cookie, name) !== text) {
154
+ rejected = true;
155
+ console.warn(
156
+ `cookie-prefs: ${key}.set() wrote a cookie that does not read back: the browser dropped it, or another cookie named ${name} hides it. Browsers drop a cookie whose name and value exceed 4096 bytes (here ${name.length + encodeURIComponent(text).length}), one with a __Host- prefix, SameSite=None or Partitioned but no Secure, and one for a domain or path this page is not on.`
157
+ );
158
+ }
159
+ }
140
160
  } catch {
141
161
  }
142
162
  check();
@@ -177,7 +197,7 @@ var bind = (key, def, prefix, options) => {
177
197
 
178
198
  // src/index.ts
179
199
  var pref = {
180
- enum: (values) => builder({ values, p: (raw) => values.includes(raw) ? raw : void 0, s: String }),
200
+ enum: (values) => builder({ values, s: String }),
181
201
  boolean: () => builder({
182
202
  k: { true: "true", false: "false" },
183
203
  p: (raw) => raw == "true" || (raw == "false" ? false : void 0),
@@ -221,10 +241,5 @@ function snapshotPrefs(prefs, source) {
221
241
  })
222
242
  );
223
243
  }
224
- function prefsScript(prefs) {
225
- return script(
226
- Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r)
227
- );
228
- }
229
244
 
230
- export { definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
245
+ export { definePrefs, pref, readPrefs, snapshotPrefs };
@@ -2,6 +2,7 @@
2
2
 
3
3
  var headers_js = require('next/headers.js');
4
4
  var cookiePrefs = require('cookie-prefs');
5
+ var script = require('cookie-prefs/script');
5
6
  var react = require('cookie-prefs/react');
6
7
  var jsxRuntime = require('react/jsx-runtime');
7
8
 
@@ -32,16 +33,14 @@ async function getPrefs(prefs) {
32
33
  async function PrefsProvider({
33
34
  prefs,
34
35
  mode,
35
- nonce,
36
- children
36
+ ...props
37
37
  }) {
38
38
  return /* @__PURE__ */ jsxRuntime.jsx(
39
39
  react.PrefsProvider,
40
40
  {
41
+ ...props,
41
42
  snapshot: mode == "server" ? await requestSnapshot(prefs) : void 0,
42
- script: cookiePrefs.prefsScript(prefs),
43
- nonce,
44
- children
43
+ script: script.prefsScript(prefs)
45
44
  }
46
45
  );
47
46
  }
@@ -42,7 +42,7 @@ interface NextPrefsProviderProps<P extends PrefsRecord> {
42
42
  * </body>
43
43
  * </html>
44
44
  */
45
- declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, nonce, children, }: NextPrefsProviderProps<P>): Promise<ReactElement>;
45
+ declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, ...props }: NextPrefsProviderProps<P>): Promise<ReactElement>;
46
46
 
47
47
  export { PrefsProvider, getPrefs };
48
48
  export type { NextPrefsProviderProps };
@@ -42,7 +42,7 @@ interface NextPrefsProviderProps<P extends PrefsRecord> {
42
42
  * </body>
43
43
  * </html>
44
44
  */
45
- declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, nonce, children, }: NextPrefsProviderProps<P>): Promise<ReactElement>;
45
+ declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, ...props }: NextPrefsProviderProps<P>): Promise<ReactElement>;
46
46
 
47
47
  export { PrefsProvider, getPrefs };
48
48
  export type { NextPrefsProviderProps };
@@ -1,5 +1,6 @@
1
1
  import { headers, cookies } from 'next/headers.js';
2
- import { readPrefs, prefsScript, snapshotPrefs } from 'cookie-prefs';
2
+ import { readPrefs, snapshotPrefs } from 'cookie-prefs';
3
+ import { prefsScript } from 'cookie-prefs/script';
3
4
  import { PrefsProvider as PrefsProvider$1 } from 'cookie-prefs/react';
4
5
  import { jsx } from 'react/jsx-runtime';
5
6
 
@@ -30,16 +31,14 @@ async function getPrefs(prefs) {
30
31
  async function PrefsProvider({
31
32
  prefs,
32
33
  mode,
33
- nonce,
34
- children
34
+ ...props
35
35
  }) {
36
36
  return /* @__PURE__ */ jsx(
37
37
  PrefsProvider$1,
38
38
  {
39
+ ...props,
39
40
  snapshot: mode == "server" ? await requestSnapshot(prefs) : void 0,
40
- script: prefsScript(prefs),
41
- nonce,
42
- children
41
+ script: prefsScript(prefs)
43
42
  }
44
43
  );
45
44
  }
@@ -46,11 +46,7 @@ var useLayout = typeof document == "undefined" ? react.useEffect : react.useLayo
46
46
  var seen = /* @__PURE__ */ new WeakSet();
47
47
  function usePref(pref) {
48
48
  const snapshot = react.useContext(Snapshot);
49
- const value = react.useSyncExternalStore(
50
- pref.subscribe,
51
- pref.get,
52
- () => snapshot ? pref.read(snapshot) : pref.defaultValue
53
- );
49
+ const value = react.useSyncExternalStore(pref.subscribe, pref.get, () => pref.read(snapshot));
54
50
  react.useEffect(() => {
55
51
  if (seen.has(pref)) return;
56
52
  seen.add(pref);
@@ -63,12 +59,24 @@ function usePref(pref) {
63
59
  }, [pref]);
64
60
  return [value, pref.set];
65
61
  }
62
+ function usePrefs(prefs) {
63
+ const entries = Object.entries(prefs);
64
+ const values = entries.map(([key, handle]) => [key, usePref(handle)[0]]);
65
+ return [
66
+ // Keys and values as dependencies: a new object only when a value (or the record's
67
+ // shape) changes. Built with `fromEntries`, so a key named `__proto__` stays a key.
68
+ react.useMemo(() => Object.fromEntries(values), values.flat()),
69
+ react.useMemo(
70
+ () => (patch) => {
71
+ for (const [key, value] of Object.entries(patch)) if (value !== void 0) prefs[key].set(value);
72
+ },
73
+ entries.flat()
74
+ )
75
+ ];
76
+ }
66
77
  function PrefsProvider({ children, snapshot, script, nonce }) {
67
78
  const outer = react.useContext(Snapshot);
68
- const merged = react.useMemo(
69
- () => outer && snapshot ? { ...outer, ...snapshot } : snapshot ?? outer,
70
- [outer, snapshot]
71
- );
79
+ const merged = react.useMemo(() => snapshot ? { ...outer, ...snapshot } : outer, [outer, snapshot]);
72
80
  useLayout(() => {
73
81
  if (!script) return;
74
82
  const onVisible = () => {
@@ -96,3 +104,4 @@ function PrefsProvider({ children, snapshot, script, nonce }) {
96
104
 
97
105
  exports.PrefsProvider = PrefsProvider;
98
106
  exports.usePref = usePref;
107
+ exports.usePrefs = usePrefs;
@@ -1,6 +1,6 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { p as PrefSetter } from '../types-CQ_6o7nc.cjs';
3
- import { PrefsSnapshot, Pref } from '../index.cjs';
2
+ import { p as PrefSetter } from '../types-C5uwWL7s.cjs';
3
+ import { PrefsSnapshot, PrefsRecord, PrefTypes, Pref, PrefValues } from '../index.cjs';
4
4
 
5
5
  /**
6
6
  * Read and write one pref, like `useState`. Built on `useSyncExternalStore`, so every
@@ -23,6 +23,31 @@ import { PrefsSnapshot, Pref } from '../index.cjs';
23
23
  * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
24
24
  */
25
25
  declare function usePref<T, V>(pref: Pref<T, V>): [value: V, setValue: PrefSetter<T, V>];
26
+ /**
27
+ * Writes several prefs of a record at once: each key takes what that pref's `set()`
28
+ * takes, a value or an updater of the previous value. Keys left out (or `undefined`)
29
+ * are not touched.
30
+ */
31
+ type PrefsSetter<P extends PrefsRecord> = (patch: {
32
+ [K in keyof P]?: P[K] extends {
33
+ readonly '~types'?: PrefTypes<infer T, infer V>;
34
+ } ? T | ((prev: V) => T) : never;
35
+ }) => void;
36
+ /**
37
+ * Read and write several prefs at once: `usePref` for every handle in `prefs` (the
38
+ * record from `definePrefs()`, or any record of its handles), with the same server
39
+ * snapshot, hydration, cross-tab sync and Safari refresh. `values` is typed like
40
+ * `readPrefs()` and stays the same object until one of the prefs changes, so it is safe
41
+ * in dependency arrays. The setter takes a partial patch and passes each entry to that
42
+ * pref's `set()`, in order: a value or an updater of the previous value. An entry set
43
+ * to `undefined` is skipped like a missing key; clear a pref with `reset()`. The setter
44
+ * stays the same function while the record holds the same handles. Like any hook, it
45
+ * needs the same keys on every render.
46
+ * @example
47
+ * const [{ theme, sidebar }, set] = usePrefs(prefs)
48
+ * <button onClick={() => set({ sidebar: (open) => !open, theme: 'dark' })}>Focus</button>
49
+ */
50
+ declare function usePrefs<P extends PrefsRecord>(prefs: P): [values: PrefValues<P>, setValues: PrefsSetter<P>];
26
51
  interface PrefsProviderProps {
27
52
  children?: ReactNode;
28
53
  /**
@@ -33,14 +58,14 @@ interface PrefsProviderProps {
33
58
  */
34
59
  snapshot?: PrefsSnapshot | undefined;
35
60
  /**
36
- * Inline script from `prefsScript()`. Rendered once as the provider's first child, so
37
- * place the provider at the top of `<body>`. Only the first value is rendered; a
38
- * later one is still applied on `<html>`. It runs before paint on the initial
39
- * document and is inert on the client, so React does not warn about it. The
40
- * provider applies its reflections again with plain DOM calls, without running it,
41
- * on mount (React can reset `<html>` attributes on remount) and whenever the tab
42
- * becomes visible, so reflections also follow changes made in other tabs to prefs
43
- * that nothing in this tab subscribes to.
61
+ * Inline script from `prefsScript()` (`cookie-prefs/script`). Rendered once as the
62
+ * provider's first child, so place the provider at the top of `<body>`. Only the
63
+ * first value is rendered; a later one is still applied on `<html>`. It runs before
64
+ * paint on the initial document and is inert on the client, so React does not warn
65
+ * about it. The provider applies its reflections again with plain DOM calls, without
66
+ * running it, on mount (React can reset `<html>` attributes on remount) and whenever
67
+ * the tab becomes visible, so reflections also follow changes made in other tabs to
68
+ * prefs that nothing in this tab subscribes to.
44
69
  */
45
70
  script?: string | undefined;
46
71
  /**
@@ -63,5 +88,5 @@ interface PrefsProviderProps {
63
88
  */
64
89
  declare function PrefsProvider({ children, snapshot, script, nonce }: PrefsProviderProps): ReactElement;
65
90
 
66
- export { PrefSetter, PrefsProvider, usePref };
67
- export type { PrefsProviderProps };
91
+ export { PrefSetter, PrefsProvider, usePref, usePrefs };
92
+ export type { PrefsProviderProps, PrefsSetter };
@@ -1,6 +1,6 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { p as PrefSetter } from '../types-CQ_6o7nc.js';
3
- import { PrefsSnapshot, Pref } from '../index.js';
2
+ import { p as PrefSetter } from '../types-C5uwWL7s.js';
3
+ import { PrefsSnapshot, PrefsRecord, PrefTypes, Pref, PrefValues } from '../index.js';
4
4
 
5
5
  /**
6
6
  * Read and write one pref, like `useState`. Built on `useSyncExternalStore`, so every
@@ -23,6 +23,31 @@ import { PrefsSnapshot, Pref } from '../index.js';
23
23
  * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
24
24
  */
25
25
  declare function usePref<T, V>(pref: Pref<T, V>): [value: V, setValue: PrefSetter<T, V>];
26
+ /**
27
+ * Writes several prefs of a record at once: each key takes what that pref's `set()`
28
+ * takes, a value or an updater of the previous value. Keys left out (or `undefined`)
29
+ * are not touched.
30
+ */
31
+ type PrefsSetter<P extends PrefsRecord> = (patch: {
32
+ [K in keyof P]?: P[K] extends {
33
+ readonly '~types'?: PrefTypes<infer T, infer V>;
34
+ } ? T | ((prev: V) => T) : never;
35
+ }) => void;
36
+ /**
37
+ * Read and write several prefs at once: `usePref` for every handle in `prefs` (the
38
+ * record from `definePrefs()`, or any record of its handles), with the same server
39
+ * snapshot, hydration, cross-tab sync and Safari refresh. `values` is typed like
40
+ * `readPrefs()` and stays the same object until one of the prefs changes, so it is safe
41
+ * in dependency arrays. The setter takes a partial patch and passes each entry to that
42
+ * pref's `set()`, in order: a value or an updater of the previous value. An entry set
43
+ * to `undefined` is skipped like a missing key; clear a pref with `reset()`. The setter
44
+ * stays the same function while the record holds the same handles. Like any hook, it
45
+ * needs the same keys on every render.
46
+ * @example
47
+ * const [{ theme, sidebar }, set] = usePrefs(prefs)
48
+ * <button onClick={() => set({ sidebar: (open) => !open, theme: 'dark' })}>Focus</button>
49
+ */
50
+ declare function usePrefs<P extends PrefsRecord>(prefs: P): [values: PrefValues<P>, setValues: PrefsSetter<P>];
26
51
  interface PrefsProviderProps {
27
52
  children?: ReactNode;
28
53
  /**
@@ -33,14 +58,14 @@ interface PrefsProviderProps {
33
58
  */
34
59
  snapshot?: PrefsSnapshot | undefined;
35
60
  /**
36
- * Inline script from `prefsScript()`. Rendered once as the provider's first child, so
37
- * place the provider at the top of `<body>`. Only the first value is rendered; a
38
- * later one is still applied on `<html>`. It runs before paint on the initial
39
- * document and is inert on the client, so React does not warn about it. The
40
- * provider applies its reflections again with plain DOM calls, without running it,
41
- * on mount (React can reset `<html>` attributes on remount) and whenever the tab
42
- * becomes visible, so reflections also follow changes made in other tabs to prefs
43
- * that nothing in this tab subscribes to.
61
+ * Inline script from `prefsScript()` (`cookie-prefs/script`). Rendered once as the
62
+ * provider's first child, so place the provider at the top of `<body>`. Only the
63
+ * first value is rendered; a later one is still applied on `<html>`. It runs before
64
+ * paint on the initial document and is inert on the client, so React does not warn
65
+ * about it. The provider applies its reflections again with plain DOM calls, without
66
+ * running it, on mount (React can reset `<html>` attributes on remount) and whenever
67
+ * the tab becomes visible, so reflections also follow changes made in other tabs to
68
+ * prefs that nothing in this tab subscribes to.
44
69
  */
45
70
  script?: string | undefined;
46
71
  /**
@@ -63,5 +88,5 @@ interface PrefsProviderProps {
63
88
  */
64
89
  declare function PrefsProvider({ children, snapshot, script, nonce }: PrefsProviderProps): ReactElement;
65
90
 
66
- export { PrefSetter, PrefsProvider, usePref };
67
- export type { PrefsProviderProps };
91
+ export { PrefSetter, PrefsProvider, usePref, usePrefs };
92
+ export type { PrefsProviderProps, PrefsSetter };
@@ -44,11 +44,7 @@ var useLayout = typeof document == "undefined" ? useEffect : useLayoutEffect;
44
44
  var seen = /* @__PURE__ */ new WeakSet();
45
45
  function usePref(pref) {
46
46
  const snapshot = useContext(Snapshot);
47
- const value = useSyncExternalStore(
48
- pref.subscribe,
49
- pref.get,
50
- () => snapshot ? pref.read(snapshot) : pref.defaultValue
51
- );
47
+ const value = useSyncExternalStore(pref.subscribe, pref.get, () => pref.read(snapshot));
52
48
  useEffect(() => {
53
49
  if (seen.has(pref)) return;
54
50
  seen.add(pref);
@@ -61,12 +57,24 @@ function usePref(pref) {
61
57
  }, [pref]);
62
58
  return [value, pref.set];
63
59
  }
60
+ function usePrefs(prefs) {
61
+ const entries = Object.entries(prefs);
62
+ const values = entries.map(([key, handle]) => [key, usePref(handle)[0]]);
63
+ return [
64
+ // Keys and values as dependencies: a new object only when a value (or the record's
65
+ // shape) changes. Built with `fromEntries`, so a key named `__proto__` stays a key.
66
+ useMemo(() => Object.fromEntries(values), values.flat()),
67
+ useMemo(
68
+ () => (patch) => {
69
+ for (const [key, value] of Object.entries(patch)) if (value !== void 0) prefs[key].set(value);
70
+ },
71
+ entries.flat()
72
+ )
73
+ ];
74
+ }
64
75
  function PrefsProvider({ children, snapshot, script, nonce }) {
65
76
  const outer = useContext(Snapshot);
66
- const merged = useMemo(
67
- () => outer && snapshot ? { ...outer, ...snapshot } : snapshot ?? outer,
68
- [outer, snapshot]
69
- );
77
+ const merged = useMemo(() => snapshot ? { ...outer, ...snapshot } : outer, [outer, snapshot]);
70
78
  useLayout(() => {
71
79
  if (!script) return;
72
80
  const onVisible = () => {
@@ -92,4 +100,4 @@ function PrefsProvider({ children, snapshot, script, nonce }) {
92
100
  ] });
93
101
  }
94
102
 
95
- export { PrefsProvider, usePref };
103
+ export { PrefsProvider, usePref, usePrefs };