@2different/sanity 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,11 @@
1
+ Copyright (c) 2026 2different. All rights reserved.
2
+
3
+ This software is proprietary. It is published on the npm registry only so that
4
+ 2different's own projects can install it. No license or other right is granted
5
+ to anyone else to use, copy, modify, merge, publish, distribute, sublicense or
6
+ sell it, in whole or in part, in source or compiled form.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9
+ IMPLIED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM,
10
+ DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11
+ SOFTWARE OR ITS USE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @2different/sanity
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
@@ -0,0 +1,36 @@
1
+ import { ClientReturn, QueryParams, SanityClient } from "@sanity/client";
2
+ /** Every tag used by any query: pass it to createRevalidationHandler as knownTags. */
3
+ export declare function allQueryTags(queryTags: ReadonlyMap<string, readonly string[]>): string[];
4
+ /**
5
+ * Returns a `sanityFetch` that caches every query in the Data Cache until a
6
+ * publish revalidates one of its tags. Tags come from `queryTags`, never from
7
+ * the caller: each query maps to every document `_type` it filters on AND every
8
+ * type it dereferences (`author->`), because the webhook only revalidates the
9
+ * tag of the document that changed. A query missing from the map throws, so an
10
+ * untagged query can't silently go stale.
11
+ *
12
+ * export const sanityFetch = createSanityFetch({ client, queryTags: QUERY_TAGS });
13
+ * const page = await sanityFetch({ query: pageQuery, params: { slug } });
14
+ */
15
+ export declare function createSanityFetch({ client, queryTags, app }: {
16
+ client: SanityClient;
17
+ queryTags: ReadonlyMap<string, readonly string[]>;
18
+ /** The `app` field of every log line. */
19
+ app?: string;
20
+ }): <const QueryString extends string>({ query, params, operation }: {
21
+ query: QueryString;
22
+ params?: QueryParams;
23
+ /** Names the call site in slow-query and failure logs. */
24
+ operation?: string;
25
+ }) => Promise<ClientReturn<QueryString, unknown>>;
26
+ /**
27
+ * Maps a Sanity image hotspot to a CSS `object-position` value, or `undefined`
28
+ * without a hotspot so callers keep their default framing.
29
+ */
30
+ export declare function hotspotPosition(img?: {
31
+ hotspot?: {
32
+ x?: number;
33
+ y?: number;
34
+ } | null;
35
+ } | null): string | undefined;
36
+ //# sourceMappingURL=fetch.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;wBAiBgB,aAAa,WAAW;;;;;;;;;;;;wBAexB,oBACd,QACA,WACA;EAEA,QAAQ;EACR,WAAW;;EAEX;WAEwC,8BAA4B,OAAA,QAAA;EAKlE,OAAO;EACP,SAAS;;EAET;MACE,QAAQ,aAAa;;;;;wBAqCX,gBACd;EAAQ;IAAY;IAAY"}
package/dist/fetch.mjs ADDED
@@ -0,0 +1,77 @@
1
+ import { createServerLogger, errorName } from "@2different/core/logging";
2
+ // src/fetch.ts
3
+ const SLOW_SANITY_QUERY_MS = 1500;
4
+ function queryFingerprint(query) {
5
+ let hash = 0x811c9dc5;
6
+ for (let i = 0; i < query.length; i += 1) {
7
+ hash ^= query.charCodeAt(i);
8
+ hash = Math.imul(hash, 16777619);
9
+ }
10
+ return (hash >>> 0).toString(16).padStart(8, "0");
11
+ }
12
+ /** Every tag used by any query: pass it to createRevalidationHandler as knownTags. */
13
+ function allQueryTags(queryTags) {
14
+ return [...new Set([...queryTags.values()].flat())];
15
+ }
16
+ /**
17
+ * Returns a `sanityFetch` that caches every query in the Data Cache until a
18
+ * publish revalidates one of its tags. Tags come from `queryTags`, never from
19
+ * the caller: each query maps to every document `_type` it filters on AND every
20
+ * type it dereferences (`author->`), because the webhook only revalidates the
21
+ * tag of the document that changed. A query missing from the map throws, so an
22
+ * untagged query can't silently go stale.
23
+ *
24
+ * export const sanityFetch = createSanityFetch({ client, queryTags: QUERY_TAGS });
25
+ * const page = await sanityFetch({ query: pageQuery, params: { slug } });
26
+ */
27
+ function createSanityFetch({ client, queryTags, app = "web" }) {
28
+ return async function sanityFetch({ query, params = {}, operation }) {
29
+ const startedAt = performance.now();
30
+ const queryId = queryFingerprint(query);
31
+ const tags = queryTags.get(query);
32
+ if (!tags) throw new Error(`Query ${queryId} has no entry in the query tags map`);
33
+ const logger = () => createServerLogger({
34
+ app,
35
+ feature: "sanity-query",
36
+ correlationId: crypto.randomUUID()
37
+ });
38
+ try {
39
+ const result = await client.fetch(query, params, {
40
+ cache: "force-cache",
41
+ next: {
42
+ revalidate: false,
43
+ tags: [...tags]
44
+ }
45
+ });
46
+ const durationMs = Math.round(performance.now() - startedAt);
47
+ if (durationMs >= SLOW_SANITY_QUERY_MS) logger().warn("sanity_query_slow", {
48
+ operation,
49
+ queryId,
50
+ tags,
51
+ durationMs
52
+ });
53
+ return result;
54
+ } catch (error) {
55
+ logger().error("sanity_query_failed", {
56
+ operation,
57
+ queryId,
58
+ tags,
59
+ errorName: errorName(error),
60
+ durationMs: Math.round(performance.now() - startedAt)
61
+ });
62
+ throw error;
63
+ }
64
+ };
65
+ }
66
+ /**
67
+ * Maps a Sanity image hotspot to a CSS `object-position` value, or `undefined`
68
+ * without a hotspot so callers keep their default framing.
69
+ */
70
+ function hotspotPosition(img) {
71
+ const hotspot = img?.hotspot;
72
+ if (hotspot?.x == null || hotspot?.y == null) return void 0;
73
+ return `${hotspot.x * 100}% ${hotspot.y * 100}%`;
74
+ }
75
+ export { allQueryTags, createSanityFetch, hotspotPosition };
76
+
77
+ //# sourceMappingURL=fetch.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.mjs","names":[],"sources":["../src/fetch.ts"],"sourcesContent":["/// <reference types=\"next\" />\n// Pulls in Next's `RequestInit` augmentation so the `next` fetch option below type-checks.\nimport type { ClientReturn, QueryParams, SanityClient } from '@sanity/client';\nimport { createServerLogger, errorName } from '@2different/core/logging';\n\nconst SLOW_SANITY_QUERY_MS = 1_500;\n\nfunction queryFingerprint(query: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < query.length; i += 1) {\n hash ^= query.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, '0');\n}\n\n/** Every tag used by any query: pass it to createRevalidationHandler as knownTags. */\nexport function allQueryTags(queryTags: ReadonlyMap<string, readonly string[]>): string[] {\n return [...new Set([...queryTags.values()].flat())];\n}\n\n/**\n * Returns a `sanityFetch` that caches every query in the Data Cache until a\n * publish revalidates one of its tags. Tags come from `queryTags`, never from\n * the caller: each query maps to every document `_type` it filters on AND every\n * type it dereferences (`author->`), because the webhook only revalidates the\n * tag of the document that changed. A query missing from the map throws, so an\n * untagged query can't silently go stale.\n *\n * export const sanityFetch = createSanityFetch({ client, queryTags: QUERY_TAGS });\n * const page = await sanityFetch({ query: pageQuery, params: { slug } });\n */\nexport function createSanityFetch({\n client,\n queryTags,\n app = 'web',\n}: {\n client: SanityClient;\n queryTags: ReadonlyMap<string, readonly string[]>;\n /** The `app` field of every log line. */\n app?: string;\n}) {\n return async function sanityFetch<const QueryString extends string>({\n query,\n params = {},\n operation,\n }: {\n query: QueryString;\n params?: QueryParams;\n /** Names the call site in slow-query and failure logs. */\n operation?: string;\n }): Promise<ClientReturn<QueryString, unknown>> {\n const startedAt = performance.now();\n const queryId = queryFingerprint(query);\n const tags = queryTags.get(query);\n if (!tags) throw new Error(`Query ${queryId} has no entry in the query tags map`);\n const logger = () =>\n createServerLogger({ app, feature: 'sanity-query', correlationId: crypto.randomUUID() });\n\n try {\n const result = await client.fetch(query, params, {\n cache: 'force-cache',\n next: { revalidate: false, tags: [...tags] },\n });\n const durationMs = Math.round(performance.now() - startedAt);\n if (durationMs >= SLOW_SANITY_QUERY_MS) {\n logger().warn('sanity_query_slow', { operation, queryId, tags, durationMs });\n }\n return result;\n } catch (error) {\n logger().error('sanity_query_failed', {\n operation,\n queryId,\n tags,\n errorName: errorName(error),\n durationMs: Math.round(performance.now() - startedAt),\n });\n // Request-level Sentry instrumentation captures the original exception in\n // the consuming app; rethrowing preserves that stack and trace context.\n throw error;\n }\n };\n}\n\n/**\n * Maps a Sanity image hotspot to a CSS `object-position` value, or `undefined`\n * without a hotspot so callers keep their default framing.\n */\nexport function hotspotPosition(\n img?: { hotspot?: { x?: number; y?: number } | null } | null\n): string | undefined {\n const hotspot = img?.hotspot;\n if (hotspot?.x == null || hotspot?.y == null) return undefined;\n return `${hotspot.x * 100}% ${hotspot.y * 100}%`;\n}\n"],"mappings":";;AAKA,MAAM,uBAAuB;AAE7B,SAAS,iBAAiB,OAAuB;CAC/C,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxC,QAAQ,MAAM,WAAW,CAAC;EAC1B,OAAO,KAAK,KAAK,MAAM,QAAU;CACnC;CACA,QAAQ,SAAS,EAAA,CAAG,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;AAClD;;AAGA,SAAgB,aAAa,WAA6D;CACxF,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,UAAU,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACpD;;;;;;;;;;;;AAaA,SAAgB,kBAAkB,EAChC,QACA,WACA,MAAM,SAML;CACD,OAAO,eAAe,YAA8C,EAClE,OACA,SAAS,CAAC,GACV,aAM8C;EAC9C,MAAM,YAAY,YAAY,IAAI;EAClC,MAAM,UAAU,iBAAiB,KAAK;EACtC,MAAM,OAAO,UAAU,IAAI,KAAK;EAChC,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,SAAS,QAAQ,oCAAoC;EAChF,MAAM,eACJ,mBAAmB;GAAE;GAAK,SAAS;GAAgB,eAAe,OAAO,WAAW;EAAE,CAAC;EAEzF,IAAI;GACF,MAAM,SAAS,MAAM,OAAO,MAAM,OAAO,QAAQ;IAC/C,OAAO;IACP,MAAM;KAAE,YAAY;KAAO,MAAM,CAAC,GAAG,IAAI;IAAE;GAC7C,CAAC;GACD,MAAM,aAAa,KAAK,MAAM,YAAY,IAAI,IAAI,SAAS;GAC3D,IAAI,cAAc,sBAChB,OAAO,CAAC,CAAC,KAAK,qBAAqB;IAAE;IAAW;IAAS;IAAM;GAAW,CAAC;GAE7E,OAAO;EACT,SAAS,OAAO;GACd,OAAO,CAAC,CAAC,MAAM,uBAAuB;IACpC;IACA;IACA;IACA,WAAW,UAAU,KAAK;IAC1B,YAAY,KAAK,MAAM,YAAY,IAAI,IAAI,SAAS;GACtD,CAAC;GAGD,MAAM;EACR;CACF;AACF;;;;;AAMA,SAAgB,gBACd,KACoB;CACpB,MAAM,UAAU,KAAK;CACrB,IAAI,SAAS,KAAK,QAAQ,SAAS,KAAK,MAAM,OAAO,KAAA;CACrD,OAAO,GAAG,QAAQ,IAAI,IAAI,IAAI,QAAQ,IAAI,IAAI;AAChD"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * GROQ for a field of sanity-plugin-internationalized-array: the value in
3
+ * `$lang`, else in `fallback`. The return type spells the string out, so query
4
+ * literals keep their exact type and typegen maps each query to its result.
5
+ *
6
+ * defineQuery(`*[_type == "page"][0]{ "title": ${localized('title', 'en')} }`)
7
+ */
8
+ export declare const localized: <F extends string, L extends string>(field: F, fallback: L) => `coalesce(${F}[language == $lang][0].value, ${F}[language == "${L}"][0].value)`;
9
+ //# sourceMappingURL=groq.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"groq.d.mts","names":[],"sources":["../src/groq.ts"],"mappings":";;;;;;;qBAOa,YAAa,kBAAkB,kBAC1C,OAAO,GACP,UAAU,kBACG,kCAAkC,kBAAkB"}
package/dist/groq.mjs ADDED
@@ -0,0 +1,12 @@
1
+ // src/groq.ts
2
+ /**
3
+ * GROQ for a field of sanity-plugin-internationalized-array: the value in
4
+ * `$lang`, else in `fallback`. The return type spells the string out, so query
5
+ * literals keep their exact type and typegen maps each query to its result.
6
+ *
7
+ * defineQuery(`*[_type == "page"][0]{ "title": ${localized('title', 'en')} }`)
8
+ */
9
+ const localized = (field, fallback) => `coalesce(${field}[language == $lang][0].value, ${field}[language == "${fallback}"][0].value)`;
10
+ export { localized };
11
+
12
+ //# sourceMappingURL=groq.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"groq.mjs","names":[],"sources":["../src/groq.ts"],"sourcesContent":["/**\n * GROQ for a field of sanity-plugin-internationalized-array: the value in\n * `$lang`, else in `fallback`. The return type spells the string out, so query\n * literals keep their exact type and typegen maps each query to its result.\n *\n * defineQuery(`*[_type == \"page\"][0]{ \"title\": ${localized('title', 'en')} }`)\n */\nexport const localized = <F extends string, L extends string>(\n field: F,\n fallback: L\n): `coalesce(${F}[language == $lang][0].value, ${F}[language == \"${L}\"][0].value)` =>\n `coalesce(${field}[language == $lang][0].value, ${field}[language == \"${fallback}\"][0].value)`;\n"],"mappings":";;;;;;;;AAOA,MAAa,aACX,OACA,aAEA,YAAY,MAAM,gCAAgC,MAAM,gBAAgB,SAAS"}
@@ -0,0 +1,14 @@
1
+ import { ImageLoaderProps } from "next/image";
2
+ /**
3
+ * `next/image` loader that delegates resizing/format to Sanity's CDN instead of
4
+ * Next's optimizer, which would download the multi-MB original to re-encode it
5
+ * (latency, cost). Sanity's edge does it: `auto=format` (AVIF/WebP per Accept),
6
+ * `fit=max` (resize to `w`, never upscale). Non-Sanity srcs pass through untouched.
7
+ */
8
+ export default function sanityImageLoader({ src, width, quality }: ImageLoaderProps): string;
9
+ /**
10
+ * Next's default deviceSizes minus 3840: a 2048px hero looks the same, and 4K
11
+ * viewports no longer fetch an oversized candidate. Use as images.deviceSizes.
12
+ */
13
+ export declare const sanityDeviceSizes: number[];
14
+ //# sourceMappingURL=image-loader.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-loader.d.mts","names":[],"sources":["../src/image-loader.ts"],"mappings":";;;;;;;wBAQwB,oBAAoB,KAAK,OAAO,WAAW;;;;;qBAetD"}
@@ -0,0 +1,32 @@
1
+ // src/image-loader.ts
2
+ /**
3
+ * `next/image` loader that delegates resizing/format to Sanity's CDN instead of
4
+ * Next's optimizer, which would download the multi-MB original to re-encode it
5
+ * (latency, cost). Sanity's edge does it: `auto=format` (AVIF/WebP per Accept),
6
+ * `fit=max` (resize to `w`, never upscale). Non-Sanity srcs pass through untouched.
7
+ */
8
+ function sanityImageLoader({ src, width, quality }) {
9
+ if (!src.startsWith("https://cdn.sanity.io/")) return src;
10
+ const url = new URL(src);
11
+ url.searchParams.set("w", String(width));
12
+ url.searchParams.set("q", String(quality ?? 75));
13
+ url.searchParams.set("auto", "format");
14
+ url.searchParams.set("fit", "max");
15
+ return url.toString();
16
+ }
17
+ /**
18
+ * Next's default deviceSizes minus 3840: a 2048px hero looks the same, and 4K
19
+ * viewports no longer fetch an oversized candidate. Use as images.deviceSizes.
20
+ */
21
+ const sanityDeviceSizes = [
22
+ 640,
23
+ 750,
24
+ 828,
25
+ 1080,
26
+ 1200,
27
+ 1920,
28
+ 2048
29
+ ];
30
+ export { sanityImageLoader as default, sanityDeviceSizes };
31
+
32
+ //# sourceMappingURL=image-loader.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-loader.mjs","names":[],"sources":["../src/image-loader.ts"],"sourcesContent":["import type { ImageLoaderProps } from 'next/image';\n\n/**\n * `next/image` loader that delegates resizing/format to Sanity's CDN instead of\n * Next's optimizer, which would download the multi-MB original to re-encode it\n * (latency, cost). Sanity's edge does it: `auto=format` (AVIF/WebP per Accept),\n * `fit=max` (resize to `w`, never upscale). Non-Sanity srcs pass through untouched.\n */\nexport default function sanityImageLoader({ src, width, quality }: ImageLoaderProps): string {\n if (!src.startsWith('https://cdn.sanity.io/')) return src;\n\n const url = new URL(src);\n url.searchParams.set('w', String(width));\n url.searchParams.set('q', String(quality ?? 75));\n url.searchParams.set('auto', 'format');\n url.searchParams.set('fit', 'max');\n return url.toString();\n}\n\n/**\n * Next's default deviceSizes minus 3840: a 2048px hero looks the same, and 4K\n * viewports no longer fetch an oversized candidate. Use as images.deviceSizes.\n */\nexport const sanityDeviceSizes = [640, 750, 828, 1080, 1200, 1920, 2048];\n"],"mappings":";;;;;;;AAQA,SAAwB,kBAAkB,EAAE,KAAK,OAAO,WAAqC;CAC3F,IAAI,CAAC,IAAI,WAAW,wBAAwB,GAAG,OAAO;CAEtD,MAAM,MAAM,IAAI,IAAI,GAAG;CACvB,IAAI,aAAa,IAAI,KAAK,OAAO,KAAK,CAAC;CACvC,IAAI,aAAa,IAAI,KAAK,OAAO,WAAW,EAAE,CAAC;CAC/C,IAAI,aAAa,IAAI,QAAQ,QAAQ;CACrC,IAAI,aAAa,IAAI,OAAO,KAAK;CACjC,OAAO,IAAI,SAAS;AACtB;;;;;AAMA,MAAa,oBAAoB;CAAC;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;AAAI"}
@@ -0,0 +1,58 @@
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ export type ErrorReporter = (error: Error, context: Record<string, unknown>) => void;
3
+ type RevalidationOptions = {
4
+ /** The `app` field of every log line. */
5
+ app: string;
6
+ reportError?: ErrorReporter;
7
+ };
8
+ /** A content app the Studio fans out to; its handler lives at `${baseUrl}/api/sanity/changes`. */
9
+ export type RevalidationTarget = {
10
+ app: string;
11
+ baseUrl: string;
12
+ };
13
+ type RevalidatePathSpec = {
14
+ path: string;
15
+ type?: 'page' | 'layout';
16
+ };
17
+ export declare function createRevalidationHandler({ knownTags, pathsByType, ...options }: RevalidationOptions & {
18
+ /** Every tag a query uses; an unknown type is still revalidated, but logged. */
19
+ knownTags: readonly string[];
20
+ pathsByType?: Record<string, RevalidatePathSpec[]>;
21
+ }): (request: NextRequest) => Promise<NextResponse<{
22
+ error: string;
23
+ }> | NextResponse<{
24
+ revalidated: string;
25
+ paths: string[];
26
+ now: number;
27
+ }>>;
28
+ export declare function createRevalidationDispatcher({ targets, app, ...options }: Partial<RevalidationOptions> & {
29
+ targets: readonly RevalidationTarget[];
30
+ }): (request: NextRequest) => Promise<NextResponse<{
31
+ error: string;
32
+ }> | NextResponse<{
33
+ revalidated: string;
34
+ targets: ({
35
+ target: string;
36
+ status: "failed";
37
+ httpStatus: number;
38
+ providerRequestId: string | undefined;
39
+ durationMs: number;
40
+ errorCode?: undefined;
41
+ } | {
42
+ target: string;
43
+ status: "ok";
44
+ httpStatus: number;
45
+ providerRequestId: string | undefined;
46
+ durationMs: number;
47
+ errorCode?: undefined;
48
+ } | {
49
+ target: string;
50
+ status: "failed";
51
+ errorCode: string;
52
+ durationMs: number;
53
+ httpStatus?: undefined;
54
+ providerRequestId?: undefined;
55
+ })[];
56
+ }>>;
57
+ export {};
58
+ //# sourceMappingURL=revalidation.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"revalidation.d.mts","names":[],"sources":["../src/revalidation.ts"],"mappings":";YAsBY,iBAAiB,OAAO,OAAO,SAAS;KAE/C;;EAEH;EACA,cAAc;;;YAIJ;EAAuB;EAAa;;KAgB3C;EAAuB;EAAc;;wBAU1B,4BACd,WACA,gBACG,WACF;;EAED;EACA,cAAc,eAAe;KAIF,SAAS,gBAAW,QAAA;;;;;;;wBAiHjC,+BACd,SACA,QACG,WACF,QAAQ;EAAyB,kBAAkB;KACzB,SAAS,gBAAW,QAAA"}
@@ -0,0 +1,254 @@
1
+ import { NextResponse } from "next/server";
2
+ import { revalidatePath, revalidateTag } from "next/cache";
3
+ import { parseBody } from "next-sanity/webhook";
4
+ import { createServerLogger, errorName, getCorrelationId, isTimeoutError } from "@2different/core/logging";
5
+ // src/revalidation.ts
6
+ const REVALIDATION_TARGET_TIMEOUT_MS = 1e4;
7
+ function reportError(reporter, error, context) {
8
+ try {
9
+ reporter?.(error, context);
10
+ } catch {}
11
+ }
12
+ function createRevalidationHandler({ knownTags, pathsByType = {}, ...options }) {
13
+ const known = new Set(knownTags);
14
+ return async function POST(request) {
15
+ const correlationId = getCorrelationId(request.headers);
16
+ const startedAt = performance.now();
17
+ const logger = createServerLogger({
18
+ app: options.app,
19
+ feature: "sanity-revalidation",
20
+ correlationId
21
+ });
22
+ logger.info("revalidation_received");
23
+ const secret = process.env.SANITY_REVALIDATE_SECRET;
24
+ if (!secret) {
25
+ const error = /* @__PURE__ */ new Error("Missing SANITY_REVALIDATE_SECRET");
26
+ logger.error("revalidation_configuration_missing", {
27
+ missing: ["SANITY_REVALIDATE_SECRET"],
28
+ durationMs: Math.round(performance.now() - startedAt)
29
+ });
30
+ reportError(options.reportError, error, { correlationId });
31
+ return NextResponse.json({ error: "Server misconfigured" }, {
32
+ status: 500,
33
+ headers: { "x-correlation-id": correlationId }
34
+ });
35
+ }
36
+ const authHeader = request.headers.get("authorization");
37
+ const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : null;
38
+ if (!token || token !== secret) {
39
+ logger.warn("revalidation_authorization_failed", { durationMs: Math.round(performance.now() - startedAt) });
40
+ return NextResponse.json({ error: "Unauthorized" }, {
41
+ status: 401,
42
+ headers: { "x-correlation-id": correlationId }
43
+ });
44
+ }
45
+ let body;
46
+ try {
47
+ body = await request.json();
48
+ } catch (error) {
49
+ logger.warn("revalidation_invalid_json", {
50
+ errorName: errorName(error),
51
+ durationMs: Math.round(performance.now() - startedAt)
52
+ });
53
+ return NextResponse.json({ error: "Invalid JSON body" }, {
54
+ status: 400,
55
+ headers: { "x-correlation-id": correlationId }
56
+ });
57
+ }
58
+ const type = body && typeof body === "object" && "type" in body && typeof body.type === "string" ? body.type : void 0;
59
+ if (!type) {
60
+ logger.warn("revalidation_type_missing", { durationMs: Math.round(performance.now() - startedAt) });
61
+ return NextResponse.json({ error: "Missing type in body" }, {
62
+ status: 400,
63
+ headers: { "x-correlation-id": correlationId }
64
+ });
65
+ }
66
+ if (!known.has(type)) logger.warn("revalidation_unknown_type", { documentType: type });
67
+ const paths = pathsByType[type] ?? [];
68
+ try {
69
+ revalidateTag(type, "max");
70
+ for (const { path, type: pathType } of paths) revalidatePath(path, pathType);
71
+ } catch (error) {
72
+ logger.error("revalidation_failed", {
73
+ documentType: type,
74
+ pathCount: paths.length,
75
+ errorName: errorName(error),
76
+ durationMs: Math.round(performance.now() - startedAt)
77
+ });
78
+ reportError(options.reportError, error instanceof Error ? error : /* @__PURE__ */ new Error("Unknown revalidation error"), {
79
+ correlationId,
80
+ documentType: type,
81
+ pathCount: paths.length
82
+ });
83
+ throw error;
84
+ }
85
+ logger.info("revalidation_completed", {
86
+ documentType: type,
87
+ paths: paths.map((path) => path.path),
88
+ durationMs: Math.round(performance.now() - startedAt)
89
+ });
90
+ return NextResponse.json({
91
+ revalidated: type,
92
+ paths: paths.map((path) => path.path),
93
+ now: Date.now()
94
+ }, { headers: { "x-correlation-id": correlationId } });
95
+ };
96
+ }
97
+ function createRevalidationDispatcher({ targets, app = "studio", ...options }) {
98
+ return async function POST(request) {
99
+ const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;
100
+ const correlationId = getCorrelationId(request.headers);
101
+ const startedAt = performance.now();
102
+ const logger = createServerLogger({
103
+ app,
104
+ feature: "sanity-webhook",
105
+ correlationId
106
+ });
107
+ logger.info("webhook_received");
108
+ const secret = process.env.SANITY_REVALIDATE_SECRET;
109
+ if (!secret) {
110
+ const error = /* @__PURE__ */ new Error("Missing SANITY_REVALIDATE_SECRET");
111
+ logger.error("webhook_configuration_missing", {
112
+ missing: ["SANITY_REVALIDATE_SECRET"],
113
+ durationMs: Math.round(performance.now() - startedAt)
114
+ });
115
+ reportError(options.reportError, error, { correlationId });
116
+ return NextResponse.json({ error: "Server misconfigured" }, {
117
+ status: 500,
118
+ headers: { "x-correlation-id": correlationId }
119
+ });
120
+ }
121
+ let parsed;
122
+ try {
123
+ parsed = await parseBody(request, secret);
124
+ } catch (error) {
125
+ logger.error("webhook_parse_failed", {
126
+ errorName: errorName(error),
127
+ durationMs: Math.round(performance.now() - startedAt)
128
+ });
129
+ reportError(options.reportError, error instanceof Error ? error : /* @__PURE__ */ new Error("Unknown webhook parse error"), { correlationId });
130
+ return NextResponse.json({ error: "Invalid webhook payload" }, {
131
+ status: 400,
132
+ headers: { "x-correlation-id": correlationId }
133
+ });
134
+ }
135
+ const { isValidSignature, body } = parsed;
136
+ if (!isValidSignature) {
137
+ logger.warn("webhook_signature_rejected", { durationMs: Math.round(performance.now() - startedAt) });
138
+ return NextResponse.json({ error: "Invalid signature" }, {
139
+ status: 401,
140
+ headers: { "x-correlation-id": correlationId }
141
+ });
142
+ }
143
+ const documentType = body?._type;
144
+ if (!documentType) {
145
+ logger.warn("webhook_type_missing", {
146
+ hasDocumentId: Boolean(body?._id),
147
+ durationMs: Math.round(performance.now() - startedAt)
148
+ });
149
+ return NextResponse.json({ error: "Missing _type in payload" }, {
150
+ status: 400,
151
+ headers: { "x-correlation-id": correlationId }
152
+ });
153
+ }
154
+ const results = await Promise.all(targets.map(async (target) => {
155
+ const targetStartedAt = performance.now();
156
+ try {
157
+ const response = await fetch(`${target.baseUrl}/api/sanity/changes`, {
158
+ method: "POST",
159
+ headers: {
160
+ "Content-Type": "application/json",
161
+ Authorization: `Bearer ${secret}`,
162
+ ...bypassSecret && { "x-vercel-protection-bypass": bypassSecret },
163
+ "x-correlation-id": correlationId
164
+ },
165
+ body: JSON.stringify({ type: documentType }),
166
+ signal: AbortSignal.timeout(REVALIDATION_TARGET_TIMEOUT_MS)
167
+ });
168
+ const durationMs = Math.round(performance.now() - targetStartedAt);
169
+ const providerRequestId = response.headers.get("x-vercel-id") ?? void 0;
170
+ if (!response.ok) {
171
+ logger.error("fanout_target_failed", {
172
+ documentType,
173
+ target: target.app,
174
+ status: response.status,
175
+ providerRequestId,
176
+ durationMs
177
+ });
178
+ return {
179
+ target: target.app,
180
+ status: "failed",
181
+ httpStatus: response.status,
182
+ providerRequestId,
183
+ durationMs
184
+ };
185
+ }
186
+ logger.info("fanout_target_completed", {
187
+ documentType,
188
+ target: target.app,
189
+ status: response.status,
190
+ providerRequestId,
191
+ durationMs
192
+ });
193
+ return {
194
+ target: target.app,
195
+ status: "ok",
196
+ httpStatus: response.status,
197
+ providerRequestId,
198
+ durationMs
199
+ };
200
+ } catch (error) {
201
+ const durationMs = Math.round(performance.now() - targetStartedAt);
202
+ const errorCode = isTimeoutError(error) ? "target_timeout" : "target_request_failed";
203
+ logger.error("fanout_target_failed", {
204
+ documentType,
205
+ target: target.app,
206
+ errorCode,
207
+ errorName: errorName(error),
208
+ durationMs
209
+ });
210
+ return {
211
+ target: target.app,
212
+ status: "failed",
213
+ errorCode,
214
+ durationMs
215
+ };
216
+ }
217
+ }));
218
+ const failedTargets = results.filter((result) => result.status === "failed");
219
+ const durationMs = Math.round(performance.now() - startedAt);
220
+ if (failedTargets.length > 0) {
221
+ const error = /* @__PURE__ */ new Error(`Revalidation fan-out failed for ${failedTargets.map((result) => result.target).join(", ")}`);
222
+ logger.error("fanout_completed_with_failures", {
223
+ documentType,
224
+ failedTargets: failedTargets.map((result) => result.target),
225
+ targetCount: results.length,
226
+ durationMs
227
+ });
228
+ reportError(options.reportError, error, {
229
+ correlationId,
230
+ documentType,
231
+ failedTargets
232
+ });
233
+ return NextResponse.json({
234
+ revalidated: documentType,
235
+ targets: results
236
+ }, {
237
+ status: 502,
238
+ headers: { "x-correlation-id": correlationId }
239
+ });
240
+ }
241
+ logger.info("fanout_completed", {
242
+ documentType,
243
+ targetCount: results.length,
244
+ durationMs
245
+ });
246
+ return NextResponse.json({
247
+ revalidated: documentType,
248
+ targets: results
249
+ }, { headers: { "x-correlation-id": correlationId } });
250
+ };
251
+ }
252
+ export { createRevalidationDispatcher, createRevalidationHandler };
253
+
254
+ //# sourceMappingURL=revalidation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"revalidation.mjs","names":[],"sources":["../src/revalidation.ts"],"sourcesContent":["// Sanity publish → Next.js cache revalidation. createRevalidationDispatcher is\n// the Studio's webhook receiver: it verifies the signature and fans the\n// document type out to every content app. createRevalidationHandler is each\n// content app's POST endpoint: it checks the bearer secret and revalidates the\n// tag named after that type (see createSanityFetch for how queries get tags).\n//\n// Env: SANITY_REVALIDATE_SECRET (webhook secret and fan-out bearer, same value\n// in the Studio and every app); VERCEL_AUTOMATION_BYPASS_SECRET in the Studio\n// when the apps sit behind Vercel deployment protection (staging).\n\nimport { type NextRequest, NextResponse } from 'next/server';\nimport { revalidateTag, revalidatePath } from 'next/cache';\nimport { parseBody } from 'next-sanity/webhook';\nimport {\n createServerLogger,\n errorName,\n getCorrelationId,\n isTimeoutError,\n} from '@2different/core/logging';\n\nconst REVALIDATION_TARGET_TIMEOUT_MS = 10_000;\n\nexport type ErrorReporter = (error: Error, context: Record<string, unknown>) => void;\n\ntype RevalidationOptions = {\n /** The `app` field of every log line. */\n app: string;\n reportError?: ErrorReporter;\n};\n\n/** A content app the Studio fans out to; its handler lives at `${baseUrl}/api/sanity/changes`. */\nexport type RevalidationTarget = { app: string; baseUrl: string };\n\nfunction reportError(\n reporter: ErrorReporter | undefined,\n error: Error,\n context: Record<string, unknown>\n) {\n try {\n reporter?.(error, context);\n } catch {\n // Monitoring must never change the endpoint response.\n }\n}\n\n// A route path to revalidate alongside a tag. For dynamic routes pass the\n// bracketed pattern (e.g. `/[locale]/[slug]`) with `type: 'page'`.\ntype RevalidatePathSpec = { path: string; type?: 'page' | 'layout' };\n\n// Consumer handler: validate the Bearer secret, revalidate the tag in the body.\n//\n// `pathsByType` maps a document `_type` to route paths to ALSO revalidate.\n// `revalidateTag` alone can't surface a brand-new slug: a page rendered as\n// `notFound()` before publish leaves a cached 404 that isn't associated with\n// the tag, so it survives tag revalidation and only clears on a redeploy.\n// Revalidating the route path busts those stale 404s so new (and deleted)\n// documents appear without a rebuild.\nexport function createRevalidationHandler({\n knownTags,\n pathsByType = {},\n ...options\n}: RevalidationOptions & {\n /** Every tag a query uses; an unknown type is still revalidated, but logged. */\n knownTags: readonly string[];\n pathsByType?: Record<string, RevalidatePathSpec[]>;\n}) {\n const known = new Set(knownTags);\n\n return async function POST(request: NextRequest) {\n const correlationId = getCorrelationId(request.headers);\n const startedAt = performance.now();\n const logger = createServerLogger({\n app: options.app,\n feature: 'sanity-revalidation',\n correlationId,\n });\n logger.info('revalidation_received');\n\n const secret = process.env.SANITY_REVALIDATE_SECRET;\n\n if (!secret) {\n const error = new Error('Missing SANITY_REVALIDATE_SECRET');\n logger.error('revalidation_configuration_missing', {\n missing: ['SANITY_REVALIDATE_SECRET'],\n durationMs: Math.round(performance.now() - startedAt),\n });\n reportError(options.reportError, error, { correlationId });\n return NextResponse.json(\n { error: 'Server misconfigured' },\n { status: 500, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n const authHeader = request.headers.get('authorization');\n const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null;\n\n if (!token || token !== secret) {\n logger.warn('revalidation_authorization_failed', {\n durationMs: Math.round(performance.now() - startedAt),\n });\n return NextResponse.json(\n { error: 'Unauthorized' },\n { status: 401, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n let body: unknown;\n try {\n body = await request.json();\n } catch (error) {\n logger.warn('revalidation_invalid_json', {\n errorName: errorName(error),\n durationMs: Math.round(performance.now() - startedAt),\n });\n return NextResponse.json(\n { error: 'Invalid JSON body' },\n { status: 400, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n const type =\n body && typeof body === 'object' && 'type' in body && typeof body.type === 'string'\n ? body.type\n : undefined;\n\n if (!type) {\n logger.warn('revalidation_type_missing', {\n durationMs: Math.round(performance.now() - startedAt),\n });\n return NextResponse.json(\n { error: 'Missing type in body' },\n { status: 400, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n if (!known.has(type)) {\n logger.warn('revalidation_unknown_type', { documentType: type });\n }\n\n const paths = pathsByType[type] ?? [];\n try {\n revalidateTag(type, 'max');\n for (const { path, type: pathType } of paths) {\n revalidatePath(path, pathType);\n }\n } catch (error) {\n logger.error('revalidation_failed', {\n documentType: type,\n pathCount: paths.length,\n errorName: errorName(error),\n durationMs: Math.round(performance.now() - startedAt),\n });\n reportError(\n options.reportError,\n error instanceof Error ? error : new Error('Unknown revalidation error'),\n { correlationId, documentType: type, pathCount: paths.length }\n );\n throw error;\n }\n\n logger.info('revalidation_completed', {\n documentType: type,\n paths: paths.map((path) => path.path),\n durationMs: Math.round(performance.now() - startedAt),\n });\n\n return NextResponse.json(\n {\n revalidated: type,\n paths: paths.map((path) => path.path),\n now: Date.now(),\n },\n { headers: { 'x-correlation-id': correlationId } }\n );\n };\n}\n\ntype WebhookPayload = { _type?: string; _id?: string };\n\n// Dispatcher (studio): verify the webhook signature, forward the document type\n// to each content app's revalidation endpoint.\nexport function createRevalidationDispatcher({\n targets,\n app = 'studio',\n ...options\n}: Partial<RevalidationOptions> & { targets: readonly RevalidationTarget[] }) {\n return async function POST(request: NextRequest) {\n const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;\n const correlationId = getCorrelationId(request.headers);\n const startedAt = performance.now();\n const logger = createServerLogger({\n app,\n feature: 'sanity-webhook',\n correlationId,\n });\n logger.info('webhook_received');\n\n const secret = process.env.SANITY_REVALIDATE_SECRET;\n\n if (!secret) {\n const error = new Error('Missing SANITY_REVALIDATE_SECRET');\n logger.error('webhook_configuration_missing', {\n missing: ['SANITY_REVALIDATE_SECRET'],\n durationMs: Math.round(performance.now() - startedAt),\n });\n reportError(options.reportError, error, { correlationId });\n return NextResponse.json(\n { error: 'Server misconfigured' },\n { status: 500, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n let parsed: Awaited<ReturnType<typeof parseBody<WebhookPayload>>>;\n try {\n parsed = await parseBody<WebhookPayload>(request, secret);\n } catch (error) {\n logger.error('webhook_parse_failed', {\n errorName: errorName(error),\n durationMs: Math.round(performance.now() - startedAt),\n });\n reportError(\n options.reportError,\n error instanceof Error ? error : new Error('Unknown webhook parse error'),\n { correlationId }\n );\n return NextResponse.json(\n { error: 'Invalid webhook payload' },\n { status: 400, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n const { isValidSignature, body } = parsed;\n\n if (!isValidSignature) {\n logger.warn('webhook_signature_rejected', {\n durationMs: Math.round(performance.now() - startedAt),\n });\n return NextResponse.json(\n { error: 'Invalid signature' },\n { status: 401, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n const documentType = body?._type;\n\n if (!documentType) {\n logger.warn('webhook_type_missing', {\n hasDocumentId: Boolean(body?._id),\n durationMs: Math.round(performance.now() - startedAt),\n });\n return NextResponse.json(\n { error: 'Missing _type in payload' },\n { status: 400, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n const results = await Promise.all(\n targets.map(async (target) => {\n const targetStartedAt = performance.now();\n try {\n const response = await fetch(`${target.baseUrl}/api/sanity/changes`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${secret}`,\n ...(bypassSecret && { 'x-vercel-protection-bypass': bypassSecret }),\n 'x-correlation-id': correlationId,\n },\n body: JSON.stringify({ type: documentType }),\n signal: AbortSignal.timeout(REVALIDATION_TARGET_TIMEOUT_MS),\n });\n const durationMs = Math.round(performance.now() - targetStartedAt);\n const providerRequestId = response.headers.get('x-vercel-id') ?? undefined;\n\n if (!response.ok) {\n logger.error('fanout_target_failed', {\n documentType,\n target: target.app,\n status: response.status,\n providerRequestId,\n durationMs,\n });\n return {\n target: target.app,\n status: 'failed' as const,\n httpStatus: response.status,\n providerRequestId,\n durationMs,\n };\n }\n\n logger.info('fanout_target_completed', {\n documentType,\n target: target.app,\n status: response.status,\n providerRequestId,\n durationMs,\n });\n return {\n target: target.app,\n status: 'ok' as const,\n httpStatus: response.status,\n providerRequestId,\n durationMs,\n };\n } catch (error) {\n const durationMs = Math.round(performance.now() - targetStartedAt);\n const errorCode = isTimeoutError(error) ? 'target_timeout' : 'target_request_failed';\n logger.error('fanout_target_failed', {\n documentType,\n target: target.app,\n errorCode,\n errorName: errorName(error),\n durationMs,\n });\n return {\n target: target.app,\n status: 'failed' as const,\n errorCode,\n durationMs,\n };\n }\n })\n );\n\n const failedTargets = results.filter((result) => result.status === 'failed');\n const durationMs = Math.round(performance.now() - startedAt);\n\n if (failedTargets.length > 0) {\n const error = new Error(\n `Revalidation fan-out failed for ${failedTargets.map((result) => result.target).join(', ')}`\n );\n logger.error('fanout_completed_with_failures', {\n documentType,\n failedTargets: failedTargets.map((result) => result.target),\n targetCount: results.length,\n durationMs,\n });\n reportError(options.reportError, error, {\n correlationId,\n documentType,\n failedTargets,\n });\n // Revalidation is idempotent. A non-2xx response lets Sanity retry the\n // complete fan-out when one deployment was temporarily unavailable.\n return NextResponse.json(\n { revalidated: documentType, targets: results },\n { status: 502, headers: { 'x-correlation-id': correlationId } }\n );\n }\n\n logger.info('fanout_completed', {\n documentType,\n targetCount: results.length,\n durationMs,\n });\n return NextResponse.json(\n { revalidated: documentType, targets: results },\n { headers: { 'x-correlation-id': correlationId } }\n );\n };\n}\n"],"mappings":";;;;;AAoBA,MAAM,iCAAiC;AAavC,SAAS,YACP,UACA,OACA,SACA;CACA,IAAI;EACF,WAAW,OAAO,OAAO;CAC3B,QAAQ,CAER;AACF;AAcA,SAAgB,0BAA0B,EACxC,WACA,cAAc,CAAC,GACf,GAAG,WAKF;CACD,MAAM,QAAQ,IAAI,IAAI,SAAS;CAE/B,OAAO,eAAe,KAAK,SAAsB;EAC/C,MAAM,gBAAgB,iBAAiB,QAAQ,OAAO;EACtD,MAAM,YAAY,YAAY,IAAI;EAClC,MAAM,SAAS,mBAAmB;GAChC,KAAK,QAAQ;GACb,SAAS;GACT;EACF,CAAC;EACD,OAAO,KAAK,uBAAuB;EAEnC,MAAM,SAAS,QAAQ,IAAI;EAE3B,IAAI,CAAC,QAAQ;GACX,MAAM,wBAAQ,IAAI,MAAM,kCAAkC;GAC1D,OAAO,MAAM,sCAAsC;IACjD,SAAS,CAAC,0BAA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,cAAc,KAAK,WAAW,OAAO,MAAM,CAAC,CAAC,KAAK,IAAI,GAC3F;GACA,OAAO,MAAM,kCAAkC;IAC7C;IACA,eAAe,cAAc,KAAK,WAAW,OAAO,MAAM;IAC1D,aAAa,QAAQ;IACrB;GACF,CAAC;GACD,YAAY,QAAQ,aAAa,OAAO;IACtC;IACA;IACA;GACF,CAAC;GAGD,OAAO,aAAa,KAClB;IAAE,aAAa;IAAc,SAAS;GAAQ,GAC9C;IAAE,QAAQ;IAAK,SAAS,EAAE,oBAAoB,cAAc;GAAE,CAChE;EACF;EAEA,OAAO,KAAK,oBAAoB;GAC9B;GACA,aAAa,QAAQ;GACrB;EACF,CAAC;EACD,OAAO,aAAa,KAClB;GAAE,aAAa;GAAc,SAAS;EAAQ,GAC9C,EAAE,SAAS,EAAE,oBAAoB,cAAc,EAAE,CACnD;CACF;AACF"}
@@ -0,0 +1,18 @@
1
+ export declare const SLUG_MAX_LENGTH = 96;
2
+ export declare const SLUG_PATTERN: RegExp;
3
+ /**
4
+ * Turns free text into a slug. Same transliteration as Sanity's default Generate
5
+ * button (speakingurl with `symbols`: ä→ae, ß→ss, ø→o, &→and), then forced into
6
+ * SLUG_PATTERN. Returns '' when nothing usable is left.
7
+ */
8
+ export declare function toSlug(text: string): string;
9
+ export type SlugProblem = 'format' | 'length' | 'reserved';
10
+ /**
11
+ * Why `slug` can't be used, or `null` when it can. Map the code to an editor
12
+ * message in your own language. `reserved` lists paths the slug would shadow
13
+ * (e.g. 'api', 'robots').
14
+ */
15
+ export declare function slugProblem(slug: string, { reserved }?: {
16
+ reserved?: readonly string[];
17
+ }): SlugProblem | null;
18
+ //# sourceMappingURL=slugs.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slugs.d.mts","names":[],"sources":["../src/slugs.ts"],"mappings":"A,qBAMa;qBAIA,cAAY;;;;;;wBAOT,OAAO;YAMX;;;;;;wBAOI,YACd,gBACE;EAAmB;IACpB"}
package/dist/slugs.mjs ADDED
@@ -0,0 +1,29 @@
1
+ import speakingurl from "speakingurl";
2
+ // src/slugs.ts
3
+ const SLUG_MAX_LENGTH = 96;
4
+ const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5
+ /**
6
+ * Turns free text into a slug. Same transliteration as Sanity's default Generate
7
+ * button (speakingurl with `symbols`: ä→ae, ß→ss, ø→o, &→and), then forced into
8
+ * SLUG_PATTERN. Returns '' when nothing usable is left.
9
+ */
10
+ function toSlug(text) {
11
+ return speakingurl(text, {
12
+ truncate: 96,
13
+ symbols: true
14
+ }).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
15
+ }
16
+ /**
17
+ * Why `slug` can't be used, or `null` when it can. Map the code to an editor
18
+ * message in your own language. `reserved` lists paths the slug would shadow
19
+ * (e.g. 'api', 'robots').
20
+ */
21
+ function slugProblem(slug, { reserved = [] } = {}) {
22
+ if (!SLUG_PATTERN.test(slug)) return "format";
23
+ if (slug.length > 96) return "length";
24
+ if (reserved.includes(slug)) return "reserved";
25
+ return null;
26
+ }
27
+ export { SLUG_MAX_LENGTH, SLUG_PATTERN, slugProblem, toSlug };
28
+
29
+ //# sourceMappingURL=slugs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slugs.mjs","names":[],"sources":["../src/slugs.ts"],"sourcesContent":["// One slug format everywhere: how text becomes a slug, and why a slug can't be\n// used. Import it in the Studio (validation + Generate button) and in every app\n// that resolves slugs, so they agree by construction.\n\nimport speakingurl from 'speakingurl';\n\nexport const SLUG_MAX_LENGTH = 96;\n\n// No dots: a next-intl proxy matcher skips any path containing `.` (it looks\n// like a file), so a dotted slug would 404.\nexport const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * Turns free text into a slug. Same transliteration as Sanity's default Generate\n * button (speakingurl with `symbols`: ä→ae, ß→ss, ø→o, &→and), then forced into\n * SLUG_PATTERN. Returns '' when nothing usable is left.\n */\nexport function toSlug(text: string): string {\n return speakingurl(text, { truncate: SLUG_MAX_LENGTH, symbols: true })\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nexport type SlugProblem = 'format' | 'length' | 'reserved';\n\n/**\n * Why `slug` can't be used, or `null` when it can. Map the code to an editor\n * message in your own language. `reserved` lists paths the slug would shadow\n * (e.g. 'api', 'robots').\n */\nexport function slugProblem(\n slug: string,\n { reserved = [] }: { reserved?: readonly string[] } = {}\n): SlugProblem | null {\n if (!SLUG_PATTERN.test(slug)) return 'format';\n if (slug.length > SLUG_MAX_LENGTH) return 'length';\n if (reserved.includes(slug)) return 'reserved';\n return null;\n}\n"],"mappings":";;AAMA,MAAa,kBAAkB;AAI/B,MAAa,eAAe;;;;;;AAO5B,SAAgB,OAAO,MAAsB;CAC3C,OAAO,YAAY,MAAM;EAAE,UAAA;EAA2B,SAAS;CAAK,CAAC,CAAC,CACnE,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,YAAY,EAAE;AAC3B;;;;;;AASA,SAAgB,YACd,MACA,EAAE,WAAW,CAAC,MAAwC,CAAC,GACnC;CACpB,IAAI,CAAC,aAAa,KAAK,IAAI,GAAG,OAAO;CACrC,IAAI,KAAK,SAAA,IAA0B,OAAO;CAC1C,IAAI,SAAS,SAAS,IAAI,GAAG,OAAO;CACpC,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@2different/sanity",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Generic Sanity layer for Next.js: tag-cached fetch, webhook revalidation, CDN image loader, slugs, localized GROQ.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/2different-org/web-kit.git",
10
+ "directory": "packages/sanity"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "LICENSE",
18
+ "README.md"
19
+ ],
20
+ "exports": {
21
+ "./fetch": {
22
+ "@2different/source": "./src/fetch.ts",
23
+ "types": "./dist/fetch.d.mts",
24
+ "default": "./dist/fetch.mjs"
25
+ },
26
+ "./groq": {
27
+ "@2different/source": "./src/groq.ts",
28
+ "types": "./dist/groq.d.mts",
29
+ "default": "./dist/groq.mjs"
30
+ },
31
+ "./revalidation": {
32
+ "@2different/source": "./src/revalidation.ts",
33
+ "types": "./dist/revalidation.d.mts",
34
+ "default": "./dist/revalidation.mjs"
35
+ },
36
+ "./image-loader": {
37
+ "@2different/source": "./src/image-loader.ts",
38
+ "types": "./dist/image-loader.d.mts",
39
+ "default": "./dist/image-loader.mjs"
40
+ },
41
+ "./slugs": {
42
+ "@2different/source": "./src/slugs.ts",
43
+ "types": "./dist/slugs.d.mts",
44
+ "default": "./dist/slugs.mjs"
45
+ }
46
+ },
47
+ "dependencies": {
48
+ "@2different/core": "^0.2.0",
49
+ "speakingurl": "^14.0.1"
50
+ },
51
+ "peerDependencies": {
52
+ "next": ">=16.0.0",
53
+ "next-sanity": "^13.0.0",
54
+ "@sanity/client": "^7.28.0 || ^8.11.0"
55
+ },
56
+ "devDependencies": {
57
+ "@2different/typescript-config": "0.2.0",
58
+ "@types/speakingurl": "^13.0.6",
59
+ "next": "16.4.6",
60
+ "next-sanity": "^13.5.1",
61
+ "@sanity/client": "^7.28.0",
62
+ "react": "^19.2.9",
63
+ "react-dom": "^19.2.9"
64
+ },
65
+ "scripts": {
66
+ "build": "tsdown",
67
+ "check-types": "tsc --noEmit"
68
+ }
6
69
  }