@2different/sanity 0.2.0 → 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.
Files changed (2) hide show
  1. package/README.md +111 -3
  2. package/package.json +4 -4
package/README.md CHANGED
@@ -1,5 +1,113 @@
1
1
  # @2different/sanity
2
2
 
3
- Internal package of 2different, published only so our own projects can
4
- install it. Not for use by others: no license is granted (see LICENSE), no
5
- support is given, and anything may change without notice.
3
+ > Internal package of 2different, published only so our own projects can install it. Not for use by others: no license is granted (see LICENSE), no support is given, and anything may change without notice.
4
+
5
+ The generic Sanity layer for Next.js: content cached until a publish
6
+ invalidates it, webhook revalidation, CDN images, slugs and localized GROQ.
7
+ Peer dependencies: `next`, `next-sanity`, `@sanity/client`.
8
+
9
+ ```bash
10
+ pnpm add @2different/sanity next-sanity @sanity/client
11
+ ```
12
+
13
+ ## How the caching works
14
+
15
+ 1. Every query is fetched with `revalidate: false` and the cache tags you
16
+ declare for it: each document `_type` it filters on **plus every type it
17
+ dereferences** (`author->`).
18
+ 2. On publish, Sanity's webhook calls the Studio's dispatcher, which verifies
19
+ the signature and forwards the document type to every app.
20
+ 3. Each app's handler revalidates the tag named after that type.
21
+
22
+ ## `@2different/sanity/fetch`
23
+
24
+ | Export | What it does |
25
+ | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
26
+ | `createSanityFetch({ client, queryTags, app? })` | Returns `sanityFetch({ query, params?, operation? })`, typed by typegen's client overloads. Throws for a query missing from `queryTags`, so no query can go stale untagged. Logs failures and queries slower than 1.5 s. |
27
+ | `allQueryTags(queryTags)` | Every tag in use, once: the handler's `knownTags`. |
28
+ | `hotspotPosition(image)` | A Sanity hotspot as CSS `object-position` (`"25% 50%"`), or `undefined`. |
29
+
30
+ ```ts
31
+ // queries.ts / tags.ts / client.ts
32
+ export const postQuery = defineQuery(
33
+ `*[_type == "post" && slug.current == $slug][0]{ title, author->{ name } }`
34
+ );
35
+ export const QUERY_TAGS = new Map([[postQuery, ['post', 'author']]]);
36
+ export const sanityFetch = createSanityFetch({ client, queryTags: QUERY_TAGS });
37
+
38
+ const post = await sanityFetch({ query: postQuery, params: { slug } });
39
+ ```
40
+
41
+ Create the client with `useCdn: false`: the Data Cache is the cache.
42
+
43
+ ## `@2different/sanity/groq`
44
+
45
+ | Export | What it does |
46
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
47
+ | `localized(field, fallback)` | GROQ for an internationalized-array field in `$lang`, else in `fallback`. Keeps its exact string type, so typegen still maps the query to its result type. |
48
+
49
+ ```ts
50
+ defineQuery(`*[_type == "page"][0]{ "title": ${localized('title', 'en')} }`);
51
+ ```
52
+
53
+ ## `@2different/sanity/revalidation`
54
+
55
+ | Export | What it does |
56
+ | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
57
+ | `createRevalidationDispatcher({ targets, app?, reportError? })` | The Studio's webhook `POST` handler: verifies the signature, forwards `{ type }` to `${baseUrl}/api/sanity/changes` of every target (10 s timeout each). Any failed target answers 502, so Sanity retries. |
58
+ | `createRevalidationHandler({ app, knownTags, pathsByType?, reportError? })` | Each app's `POST` handler: checks the bearer secret, revalidates the tag, and the paths in `pathsByType[type]`. |
59
+ | `RevalidationTarget`, `ErrorReporter` (types) | `{ app, baseUrl }`; `(error, context) => void` (wire Sentry here). |
60
+
61
+ ```ts
62
+ // studio: app/api/sanity/changes/route.ts
63
+ export const POST = createRevalidationDispatcher({
64
+ targets: [{ app: 'web', baseUrl: appUrls.site }],
65
+ });
66
+
67
+ // app: app/api/sanity/changes/route.ts
68
+ export const POST = createRevalidationHandler({
69
+ app: 'web',
70
+ knownTags: allQueryTags(QUERY_TAGS),
71
+ // A page that rendered notFound() before its document existed is cached
72
+ // without tags: revalidate its route by path so new slugs appear.
73
+ pathsByType: { post: [{ path: '/[locale]/blog/[slug]', type: 'page' }] },
74
+ });
75
+ ```
76
+
77
+ Env: `SANITY_REVALIDATE_SECRET` (the webhook secret and the bearer; same value
78
+ in the Studio and every app). In the Studio also
79
+ `VERCEL_AUTOMATION_BYPASS_SECRET` when the apps sit behind deployment
80
+ protection. Webhook: `POST <studio>/api/sanity/changes`, projection `{_type, _id}`.
81
+
82
+ ## `@2different/sanity/image-loader`
83
+
84
+ | Export | What it does |
85
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
86
+ | default export | A `next/image` loader that lets Sanity's CDN resize (`w`, `q` default 75, `auto=format`, `fit=max`) instead of Next's optimizer; other sources pass through. |
87
+ | `sanityDeviceSizes` | Next's `deviceSizes` capped at 2048. |
88
+
89
+ ```ts
90
+ // src/lib/sanity-image-loader.ts
91
+ export { default } from '@2different/sanity/image-loader';
92
+ // next.config.ts
93
+ images: { loader: 'custom', loaderFile: './src/lib/sanity-image-loader.ts', deviceSizes: sanityDeviceSizes }
94
+ ```
95
+
96
+ ## `@2different/sanity/slugs`
97
+
98
+ | Export | What it does |
99
+ | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
100
+ | `toSlug(text)` | Transliterates like Sanity's Generate button (ä→ae, ß→ss, &→and), then forces `SLUG_PATTERN`; `''` if nothing usable is left. |
101
+ | `slugProblem(slug, { reserved? })` | `'format' \| 'length' \| 'reserved' \| null`; map the code to an editor message in your language. |
102
+ | `SLUG_PATTERN`, `SLUG_MAX_LENGTH` | Lowercase letters, digits and single dashes, no dots (an i18n proxy treats dotted paths as files); at most 96. |
103
+ | `SlugProblem` (type) | The codes above. |
104
+
105
+ ```ts
106
+ defineField({
107
+ name: 'slug',
108
+ type: 'slug',
109
+ options: { slugify: toSlug },
110
+ validation: (rule) =>
111
+ rule.custom((v) => (v?.current && slugProblem(v.current) ? 'Invalid slug' : true)),
112
+ });
113
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@2different/sanity",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Generic Sanity layer for Next.js: tag-cached fetch, webhook revalidation, CDN image loader, slugs, localized GROQ.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -45,7 +45,7 @@
45
45
  }
46
46
  },
47
47
  "dependencies": {
48
- "@2different/core": "^0.2.0",
48
+ "@2different/core": "^0.2.1",
49
49
  "speakingurl": "^14.0.1"
50
50
  },
51
51
  "peerDependencies": {
@@ -54,13 +54,13 @@
54
54
  "@sanity/client": "^7.28.0 || ^8.11.0"
55
55
  },
56
56
  "devDependencies": {
57
- "@2different/typescript-config": "0.2.0",
58
57
  "@types/speakingurl": "^13.0.6",
59
58
  "next": "16.4.6",
60
59
  "next-sanity": "^13.5.1",
61
60
  "@sanity/client": "^7.28.0",
62
61
  "react": "^19.2.9",
63
- "react-dom": "^19.2.9"
62
+ "react-dom": "^19.2.9",
63
+ "@2different/tooling": "0.1.1"
64
64
  },
65
65
  "scripts": {
66
66
  "build": "tsdown",