@weatherboard/cms 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.
Files changed (100) hide show
  1. package/README.md +70 -2
  2. package/dist/adapters/next/reader.d.cts +2 -0
  3. package/dist/adapters/next/reader.d.mts +2 -0
  4. package/dist/adapters/next/reader.d.ts +2 -0
  5. package/dist/adapters/sanity/adapter.d.cts +15 -0
  6. package/dist/adapters/sanity/adapter.d.mts +15 -0
  7. package/dist/adapters/sanity/adapter.d.ts +15 -0
  8. package/dist/contracts/query.d.cts +20 -0
  9. package/dist/contracts/query.d.mts +20 -0
  10. package/dist/contracts/query.d.ts +20 -0
  11. package/dist/contracts/text.d.cts +65 -0
  12. package/dist/contracts/text.d.mts +65 -0
  13. package/dist/contracts/text.d.ts +65 -0
  14. package/dist/guard.cjs +3 -0
  15. package/dist/guard.cjs.map +7 -0
  16. package/dist/guard.d.cts +2 -0
  17. package/dist/guard.d.mts +2 -0
  18. package/dist/guard.d.ts +2 -0
  19. package/dist/guard.mjs +3 -0
  20. package/dist/guard.mjs.map +7 -0
  21. package/dist/index.cjs +2 -0
  22. package/dist/index.cjs.map +7 -0
  23. package/dist/index.d.cts +4 -0
  24. package/dist/index.d.mts +4 -0
  25. package/dist/index.d.ts +4 -0
  26. package/dist/index.mjs +2 -0
  27. package/dist/index.mjs.map +7 -0
  28. package/dist/invalidation/route.d.cts +12 -0
  29. package/dist/invalidation/route.d.mts +12 -0
  30. package/dist/invalidation/route.d.ts +12 -0
  31. package/dist/next.cjs +2 -0
  32. package/dist/next.cjs.map +7 -0
  33. package/dist/next.d.cts +4 -0
  34. package/dist/next.d.mts +4 -0
  35. package/dist/next.d.ts +4 -0
  36. package/dist/next.mjs +2 -0
  37. package/dist/next.mjs.map +7 -0
  38. package/dist/portable/array.d.cts +2 -0
  39. package/dist/portable/array.d.mts +2 -0
  40. package/dist/portable/array.d.ts +2 -0
  41. package/dist/portable/fallback.d.cts +4 -0
  42. package/dist/portable/fallback.d.mts +4 -0
  43. package/dist/portable/fallback.d.ts +4 -0
  44. package/dist/portable/site-content.d.cts +220 -0
  45. package/dist/portable/site-content.d.mts +220 -0
  46. package/dist/portable/site-content.d.ts +220 -0
  47. package/dist/portable/webhook.d.cts +133 -0
  48. package/dist/portable/webhook.d.mts +133 -0
  49. package/dist/portable/webhook.d.ts +133 -0
  50. package/dist/runtime/reader.d.cts +51 -0
  51. package/dist/runtime/reader.d.mts +51 -0
  52. package/dist/runtime/reader.d.ts +51 -0
  53. package/dist/sanity.cjs +2 -0
  54. package/dist/sanity.cjs.map +7 -0
  55. package/dist/sanity.d.cts +3 -0
  56. package/dist/sanity.d.mts +3 -0
  57. package/dist/sanity.d.ts +3 -0
  58. package/dist/sanity.mjs +2 -0
  59. package/dist/sanity.mjs.map +7 -0
  60. package/dist/server.cjs +2 -0
  61. package/dist/server.cjs.map +7 -0
  62. package/dist/server.d.cts +3 -0
  63. package/dist/server.d.mts +3 -0
  64. package/dist/server.d.ts +3 -0
  65. package/dist/server.mjs +2 -0
  66. package/dist/server.mjs.map +7 -0
  67. package/dist/site-content.cjs +7 -0
  68. package/dist/site-content.cjs.map +7 -0
  69. package/dist/site-content.d.cts +4 -0
  70. package/dist/site-content.d.mts +4 -0
  71. package/dist/site-content.d.ts +4 -0
  72. package/dist/site-content.mjs +7 -0
  73. package/dist/site-content.mjs.map +7 -0
  74. package/dist/testing.cjs +2 -0
  75. package/dist/testing.cjs.map +7 -0
  76. package/dist/testing.d.cts +2 -0
  77. package/dist/testing.d.mts +2 -0
  78. package/dist/testing.d.ts +2 -0
  79. package/dist/testing.mjs +2 -0
  80. package/dist/testing.mjs.map +7 -0
  81. package/dist/tooling/guard.d.cts +13 -0
  82. package/dist/tooling/guard.d.mts +13 -0
  83. package/dist/tooling/guard.d.ts +13 -0
  84. package/dist/tooling/test-fixtures/break-proof.d.cts +1 -0
  85. package/dist/tooling/test-fixtures/break-proof.d.mts +1 -0
  86. package/dist/tooling/test-fixtures/break-proof.d.ts +1 -0
  87. package/dist/tooling/test-fixtures/consumer.d.cts +9 -0
  88. package/dist/tooling/test-fixtures/consumer.d.mts +9 -0
  89. package/dist/tooling/test-fixtures/consumer.d.ts +9 -0
  90. package/dist/tooling/testing.d.cts +10 -0
  91. package/dist/tooling/testing.d.mts +10 -0
  92. package/dist/tooling/testing.d.ts +10 -0
  93. package/dist/webhook.cjs +2 -0
  94. package/dist/webhook.cjs.map +7 -0
  95. package/dist/webhook.d.cts +2 -0
  96. package/dist/webhook.d.mts +2 -0
  97. package/dist/webhook.d.ts +2 -0
  98. package/dist/webhook.mjs +2 -0
  99. package/dist/webhook.mjs.map +7 -0
  100. package/package.json +142 -3
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Verifying a Sanity webhook (A-590 step 1, A-592's `SANITY_WEBHOOK_SECRET`).
3
+ *
4
+ * -------------------------------------------------------------------------
5
+ * WHY THIS ENDPOINT NEEDS A SIGNATURE AT ALL
6
+ * -------------------------------------------------------------------------
7
+ *
8
+ * `/revalidate` throws away cache entries. A-590: "An unauthenticated
9
+ * revalidation endpoint is a free cache-purge and rebuild trigger for anyone
10
+ * who finds the URL." On a plan whose API request allowance is a HARD cap that
11
+ * returns 402 rather than a bill, an attacker who can empty the cache at will
12
+ * can take a client's site content-offline for the rest of the month. So the
13
+ * signature is not hygiene here; it is the availability control.
14
+ *
15
+ * -------------------------------------------------------------------------
16
+ * THE WIRE FORMAT IS MEASURED, NOT REMEMBERED
17
+ * -------------------------------------------------------------------------
18
+ *
19
+ * Read on 2026-09-16 from Sanity's own toolkit,
20
+ * `https://raw.githubusercontent.com/sanity-io/webhook-toolkit/main/src/signature.ts`:
21
+ *
22
+ * header `sanity-webhook-signature`
23
+ * value `t=<millis>,v1=<signature>` (regex `/^t=(\d+)[, ]+v1=([^, ]+)$/`)
24
+ * signed payload `` `${timestamp}.${body}` ``
25
+ * algorithm HMAC-SHA256
26
+ * digest encoding base64url — standard base64 with `+`→`-`, `/`→`_`, padding stripped
27
+ * MINIMUM_TIMESTAMP 1609459200000 (2021-01-01Z), below which a value is nonsense
28
+ *
29
+ * `signature.test.ts` does not take that paragraph's word for it either: it
30
+ * signs a payload with `@sanity/webhook`'s own `encodeSignatureHeader` and
31
+ * asserts this verifier accepts it. If Sanity changes the format, that test
32
+ * goes red rather than production quietly rejecting every webhook.
33
+ *
34
+ * -------------------------------------------------------------------------
35
+ * WHAT THIS ADDS TO THE TOOLKIT, AND WHY IT IS NOT JUST IMPORTED
36
+ * -------------------------------------------------------------------------
37
+ *
38
+ * Two things, both of which are `CLAUDE.md`'s "take the safer construction".
39
+ *
40
+ * First, a REPLAY WINDOW. The toolkit enforces only that the timestamp is after
41
+ * 2021; a captured webhook is otherwise replayable forever. A replayed purge is
42
+ * the attack in the first paragraph, executed with a request somebody was
43
+ * legitimately sent. `verifySanityWebhook` takes a symmetric tolerance — the
44
+ * window is symmetric for A-44's reason, since a far-future timestamp is
45
+ * precisely how you mint a request that stays replayable for a year.
46
+ *
47
+ * Second, a MISSING SECRET IS A REJECTION, never a bypass. A-590 says it in as
48
+ * many words: "reject on absence rather than skipping the check when the secret
49
+ * is unset." The degraded mode of "no secret configured, so allow it" is
50
+ * produced by a deploy that forgot `wrangler secret put`, announces itself
51
+ * nowhere, and grants strangers the purge endpoint.
52
+ *
53
+ * The comparison is `crypto.subtle.verify`, which compares raw digests in
54
+ * constant time. A `===` on the base64 strings short-circuits at the first
55
+ * differing character, which turns one 2^256 search into a few dozen sequential
56
+ * 64-way ones against an endpoint that answers in milliseconds.
57
+ *
58
+ * -------------------------------------------------------------------------
59
+ * `encodeSignatureHeader` IS ASYNC. AWAIT IT. (A-651)
60
+ * -------------------------------------------------------------------------
61
+ *
62
+ * `@sanity/webhook@4.0.4` declares
63
+ *
64
+ * encodeSignatureHeader(payload: string, timestamp: number, secret: string):
65
+ * Promise<string>
66
+ *
67
+ * and nothing forces you to await it. Drop the `await` and the Promise is
68
+ * stringified into the header as the literal `[object Promise]`, which arrives
69
+ * here, fails `SIGNATURE_VALUE`, and is rejected as `malformed-signature`. The
70
+ * rejection is correct and the message is about the wire format, so it sends
71
+ * you to read Sanity's header spec — the one place the bug is not. TypeScript
72
+ * does not save you either: the value usually lands in a `Record<string,
73
+ * string>` built by a helper, or inside a template literal, both of which take
74
+ * a Promise without complaint.
75
+ *
76
+ * The rule: every call to `encodeSignatureHeader` is awaited, and the helper
77
+ * that wraps it is `async` rather than returning the Promise for someone else
78
+ * to forget. The content-client compatibility tests and CMS signer tests await every
79
+ * encoder call; this note exists so the next one
80
+ * is too, because the symptom will not tell you.
81
+ */
82
+ /** Sanity's header. Lower-cased; `Headers.get` is case-insensitive either way. */
83
+ export declare const SANITY_SIGNATURE_HEADER = "sanity-webhook-signature";
84
+ /** 2021-01-01T00:00:00.000Z. Sanity's `MINIMUM_TIMESTAMP`; anything earlier is not a timestamp. */
85
+ export declare const MINIMUM_TIMESTAMP = 1609459200000;
86
+ /**
87
+ * How far from `now` a webhook timestamp may be, in milliseconds.
88
+ *
89
+ * Five minutes rather than A-44's sixty seconds: this one crosses Sanity's
90
+ * delivery queue rather than two NTP-synced clouds, and a retried delivery is a
91
+ * normal event. It is still a window rather than "forever", which is the whole
92
+ * difference from the toolkit.
93
+ */
94
+ export declare const DEFAULT_TOLERANCE_MS = 300000;
95
+ export type WebhookRejection =
96
+ /** `SANITY_WEBHOOK_SECRET` is unset or empty. Fail closed. */
97
+ "no-secret"
98
+ /** No `sanity-webhook-signature` header. */
99
+ | "no-signature"
100
+ /** Header present but not `t=…,v1=…`, or `v1` is not decodable base64url. */
101
+ | "malformed-signature"
102
+ /** Before 2021, or outside the tolerance in either direction. */
103
+ | "stale-timestamp"
104
+ /** Well-formed, in window, wrong. */
105
+ | "bad-signature";
106
+ export type WebhookVerification = {
107
+ ok: true;
108
+ } | {
109
+ ok: false;
110
+ reason: WebhookRejection;
111
+ };
112
+ /**
113
+ * Verify a Sanity webhook delivery.
114
+ *
115
+ * `rawBody` must be the bytes as received — `await request.text()`, never
116
+ * `JSON.stringify(await request.json())`. A parse-and-restringify is not a
117
+ * byte-for-byte round trip (key order, number formatting, whitespace) and one
118
+ * byte changes the whole digest, so the symptom is every webhook failing after
119
+ * a refactor that looked like tidying.
120
+ *
121
+ * The `reason` is for our logs and our tests. It is never returned to the
122
+ * caller: "your signature was fine but your clock is stale" is the next step in
123
+ * an attack, handed over free.
124
+ */
125
+ export declare function verifySanityWebhook(options: {
126
+ secret: string | undefined;
127
+ rawBody: string;
128
+ headers: {
129
+ get(name: string): string | null;
130
+ };
131
+ now?: number;
132
+ toleranceMs?: number;
133
+ }): Promise<WebhookVerification>;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Verifying a Sanity webhook (A-590 step 1, A-592's `SANITY_WEBHOOK_SECRET`).
3
+ *
4
+ * -------------------------------------------------------------------------
5
+ * WHY THIS ENDPOINT NEEDS A SIGNATURE AT ALL
6
+ * -------------------------------------------------------------------------
7
+ *
8
+ * `/revalidate` throws away cache entries. A-590: "An unauthenticated
9
+ * revalidation endpoint is a free cache-purge and rebuild trigger for anyone
10
+ * who finds the URL." On a plan whose API request allowance is a HARD cap that
11
+ * returns 402 rather than a bill, an attacker who can empty the cache at will
12
+ * can take a client's site content-offline for the rest of the month. So the
13
+ * signature is not hygiene here; it is the availability control.
14
+ *
15
+ * -------------------------------------------------------------------------
16
+ * THE WIRE FORMAT IS MEASURED, NOT REMEMBERED
17
+ * -------------------------------------------------------------------------
18
+ *
19
+ * Read on 2026-09-16 from Sanity's own toolkit,
20
+ * `https://raw.githubusercontent.com/sanity-io/webhook-toolkit/main/src/signature.ts`:
21
+ *
22
+ * header `sanity-webhook-signature`
23
+ * value `t=<millis>,v1=<signature>` (regex `/^t=(\d+)[, ]+v1=([^, ]+)$/`)
24
+ * signed payload `` `${timestamp}.${body}` ``
25
+ * algorithm HMAC-SHA256
26
+ * digest encoding base64url — standard base64 with `+`→`-`, `/`→`_`, padding stripped
27
+ * MINIMUM_TIMESTAMP 1609459200000 (2021-01-01Z), below which a value is nonsense
28
+ *
29
+ * `signature.test.ts` does not take that paragraph's word for it either: it
30
+ * signs a payload with `@sanity/webhook`'s own `encodeSignatureHeader` and
31
+ * asserts this verifier accepts it. If Sanity changes the format, that test
32
+ * goes red rather than production quietly rejecting every webhook.
33
+ *
34
+ * -------------------------------------------------------------------------
35
+ * WHAT THIS ADDS TO THE TOOLKIT, AND WHY IT IS NOT JUST IMPORTED
36
+ * -------------------------------------------------------------------------
37
+ *
38
+ * Two things, both of which are `CLAUDE.md`'s "take the safer construction".
39
+ *
40
+ * First, a REPLAY WINDOW. The toolkit enforces only that the timestamp is after
41
+ * 2021; a captured webhook is otherwise replayable forever. A replayed purge is
42
+ * the attack in the first paragraph, executed with a request somebody was
43
+ * legitimately sent. `verifySanityWebhook` takes a symmetric tolerance — the
44
+ * window is symmetric for A-44's reason, since a far-future timestamp is
45
+ * precisely how you mint a request that stays replayable for a year.
46
+ *
47
+ * Second, a MISSING SECRET IS A REJECTION, never a bypass. A-590 says it in as
48
+ * many words: "reject on absence rather than skipping the check when the secret
49
+ * is unset." The degraded mode of "no secret configured, so allow it" is
50
+ * produced by a deploy that forgot `wrangler secret put`, announces itself
51
+ * nowhere, and grants strangers the purge endpoint.
52
+ *
53
+ * The comparison is `crypto.subtle.verify`, which compares raw digests in
54
+ * constant time. A `===` on the base64 strings short-circuits at the first
55
+ * differing character, which turns one 2^256 search into a few dozen sequential
56
+ * 64-way ones against an endpoint that answers in milliseconds.
57
+ *
58
+ * -------------------------------------------------------------------------
59
+ * `encodeSignatureHeader` IS ASYNC. AWAIT IT. (A-651)
60
+ * -------------------------------------------------------------------------
61
+ *
62
+ * `@sanity/webhook@4.0.4` declares
63
+ *
64
+ * encodeSignatureHeader(payload: string, timestamp: number, secret: string):
65
+ * Promise<string>
66
+ *
67
+ * and nothing forces you to await it. Drop the `await` and the Promise is
68
+ * stringified into the header as the literal `[object Promise]`, which arrives
69
+ * here, fails `SIGNATURE_VALUE`, and is rejected as `malformed-signature`. The
70
+ * rejection is correct and the message is about the wire format, so it sends
71
+ * you to read Sanity's header spec — the one place the bug is not. TypeScript
72
+ * does not save you either: the value usually lands in a `Record<string,
73
+ * string>` built by a helper, or inside a template literal, both of which take
74
+ * a Promise without complaint.
75
+ *
76
+ * The rule: every call to `encodeSignatureHeader` is awaited, and the helper
77
+ * that wraps it is `async` rather than returning the Promise for someone else
78
+ * to forget. The content-client compatibility tests and CMS signer tests await every
79
+ * encoder call; this note exists so the next one
80
+ * is too, because the symptom will not tell you.
81
+ */
82
+ /** Sanity's header. Lower-cased; `Headers.get` is case-insensitive either way. */
83
+ export declare const SANITY_SIGNATURE_HEADER = "sanity-webhook-signature";
84
+ /** 2021-01-01T00:00:00.000Z. Sanity's `MINIMUM_TIMESTAMP`; anything earlier is not a timestamp. */
85
+ export declare const MINIMUM_TIMESTAMP = 1609459200000;
86
+ /**
87
+ * How far from `now` a webhook timestamp may be, in milliseconds.
88
+ *
89
+ * Five minutes rather than A-44's sixty seconds: this one crosses Sanity's
90
+ * delivery queue rather than two NTP-synced clouds, and a retried delivery is a
91
+ * normal event. It is still a window rather than "forever", which is the whole
92
+ * difference from the toolkit.
93
+ */
94
+ export declare const DEFAULT_TOLERANCE_MS = 300000;
95
+ export type WebhookRejection =
96
+ /** `SANITY_WEBHOOK_SECRET` is unset or empty. Fail closed. */
97
+ "no-secret"
98
+ /** No `sanity-webhook-signature` header. */
99
+ | "no-signature"
100
+ /** Header present but not `t=…,v1=…`, or `v1` is not decodable base64url. */
101
+ | "malformed-signature"
102
+ /** Before 2021, or outside the tolerance in either direction. */
103
+ | "stale-timestamp"
104
+ /** Well-formed, in window, wrong. */
105
+ | "bad-signature";
106
+ export type WebhookVerification = {
107
+ ok: true;
108
+ } | {
109
+ ok: false;
110
+ reason: WebhookRejection;
111
+ };
112
+ /**
113
+ * Verify a Sanity webhook delivery.
114
+ *
115
+ * `rawBody` must be the bytes as received — `await request.text()`, never
116
+ * `JSON.stringify(await request.json())`. A parse-and-restringify is not a
117
+ * byte-for-byte round trip (key order, number formatting, whitespace) and one
118
+ * byte changes the whole digest, so the symptom is every webhook failing after
119
+ * a refactor that looked like tidying.
120
+ *
121
+ * The `reason` is for our logs and our tests. It is never returned to the
122
+ * caller: "your signature was fine but your clock is stale" is the next step in
123
+ * an attack, handed over free.
124
+ */
125
+ export declare function verifySanityWebhook(options: {
126
+ secret: string | undefined;
127
+ rawBody: string;
128
+ headers: {
129
+ get(name: string): string | null;
130
+ };
131
+ now?: number;
132
+ toleranceMs?: number;
133
+ }): Promise<WebhookVerification>;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Verifying a Sanity webhook (A-590 step 1, A-592's `SANITY_WEBHOOK_SECRET`).
3
+ *
4
+ * -------------------------------------------------------------------------
5
+ * WHY THIS ENDPOINT NEEDS A SIGNATURE AT ALL
6
+ * -------------------------------------------------------------------------
7
+ *
8
+ * `/revalidate` throws away cache entries. A-590: "An unauthenticated
9
+ * revalidation endpoint is a free cache-purge and rebuild trigger for anyone
10
+ * who finds the URL." On a plan whose API request allowance is a HARD cap that
11
+ * returns 402 rather than a bill, an attacker who can empty the cache at will
12
+ * can take a client's site content-offline for the rest of the month. So the
13
+ * signature is not hygiene here; it is the availability control.
14
+ *
15
+ * -------------------------------------------------------------------------
16
+ * THE WIRE FORMAT IS MEASURED, NOT REMEMBERED
17
+ * -------------------------------------------------------------------------
18
+ *
19
+ * Read on 2026-09-16 from Sanity's own toolkit,
20
+ * `https://raw.githubusercontent.com/sanity-io/webhook-toolkit/main/src/signature.ts`:
21
+ *
22
+ * header `sanity-webhook-signature`
23
+ * value `t=<millis>,v1=<signature>` (regex `/^t=(\d+)[, ]+v1=([^, ]+)$/`)
24
+ * signed payload `` `${timestamp}.${body}` ``
25
+ * algorithm HMAC-SHA256
26
+ * digest encoding base64url — standard base64 with `+`→`-`, `/`→`_`, padding stripped
27
+ * MINIMUM_TIMESTAMP 1609459200000 (2021-01-01Z), below which a value is nonsense
28
+ *
29
+ * `signature.test.ts` does not take that paragraph's word for it either: it
30
+ * signs a payload with `@sanity/webhook`'s own `encodeSignatureHeader` and
31
+ * asserts this verifier accepts it. If Sanity changes the format, that test
32
+ * goes red rather than production quietly rejecting every webhook.
33
+ *
34
+ * -------------------------------------------------------------------------
35
+ * WHAT THIS ADDS TO THE TOOLKIT, AND WHY IT IS NOT JUST IMPORTED
36
+ * -------------------------------------------------------------------------
37
+ *
38
+ * Two things, both of which are `CLAUDE.md`'s "take the safer construction".
39
+ *
40
+ * First, a REPLAY WINDOW. The toolkit enforces only that the timestamp is after
41
+ * 2021; a captured webhook is otherwise replayable forever. A replayed purge is
42
+ * the attack in the first paragraph, executed with a request somebody was
43
+ * legitimately sent. `verifySanityWebhook` takes a symmetric tolerance — the
44
+ * window is symmetric for A-44's reason, since a far-future timestamp is
45
+ * precisely how you mint a request that stays replayable for a year.
46
+ *
47
+ * Second, a MISSING SECRET IS A REJECTION, never a bypass. A-590 says it in as
48
+ * many words: "reject on absence rather than skipping the check when the secret
49
+ * is unset." The degraded mode of "no secret configured, so allow it" is
50
+ * produced by a deploy that forgot `wrangler secret put`, announces itself
51
+ * nowhere, and grants strangers the purge endpoint.
52
+ *
53
+ * The comparison is `crypto.subtle.verify`, which compares raw digests in
54
+ * constant time. A `===` on the base64 strings short-circuits at the first
55
+ * differing character, which turns one 2^256 search into a few dozen sequential
56
+ * 64-way ones against an endpoint that answers in milliseconds.
57
+ *
58
+ * -------------------------------------------------------------------------
59
+ * `encodeSignatureHeader` IS ASYNC. AWAIT IT. (A-651)
60
+ * -------------------------------------------------------------------------
61
+ *
62
+ * `@sanity/webhook@4.0.4` declares
63
+ *
64
+ * encodeSignatureHeader(payload: string, timestamp: number, secret: string):
65
+ * Promise<string>
66
+ *
67
+ * and nothing forces you to await it. Drop the `await` and the Promise is
68
+ * stringified into the header as the literal `[object Promise]`, which arrives
69
+ * here, fails `SIGNATURE_VALUE`, and is rejected as `malformed-signature`. The
70
+ * rejection is correct and the message is about the wire format, so it sends
71
+ * you to read Sanity's header spec — the one place the bug is not. TypeScript
72
+ * does not save you either: the value usually lands in a `Record<string,
73
+ * string>` built by a helper, or inside a template literal, both of which take
74
+ * a Promise without complaint.
75
+ *
76
+ * The rule: every call to `encodeSignatureHeader` is awaited, and the helper
77
+ * that wraps it is `async` rather than returning the Promise for someone else
78
+ * to forget. The content-client compatibility tests and CMS signer tests await every
79
+ * encoder call; this note exists so the next one
80
+ * is too, because the symptom will not tell you.
81
+ */
82
+ /** Sanity's header. Lower-cased; `Headers.get` is case-insensitive either way. */
83
+ export declare const SANITY_SIGNATURE_HEADER = "sanity-webhook-signature";
84
+ /** 2021-01-01T00:00:00.000Z. Sanity's `MINIMUM_TIMESTAMP`; anything earlier is not a timestamp. */
85
+ export declare const MINIMUM_TIMESTAMP = 1609459200000;
86
+ /**
87
+ * How far from `now` a webhook timestamp may be, in milliseconds.
88
+ *
89
+ * Five minutes rather than A-44's sixty seconds: this one crosses Sanity's
90
+ * delivery queue rather than two NTP-synced clouds, and a retried delivery is a
91
+ * normal event. It is still a window rather than "forever", which is the whole
92
+ * difference from the toolkit.
93
+ */
94
+ export declare const DEFAULT_TOLERANCE_MS = 300000;
95
+ export type WebhookRejection =
96
+ /** `SANITY_WEBHOOK_SECRET` is unset or empty. Fail closed. */
97
+ "no-secret"
98
+ /** No `sanity-webhook-signature` header. */
99
+ | "no-signature"
100
+ /** Header present but not `t=…,v1=…`, or `v1` is not decodable base64url. */
101
+ | "malformed-signature"
102
+ /** Before 2021, or outside the tolerance in either direction. */
103
+ | "stale-timestamp"
104
+ /** Well-formed, in window, wrong. */
105
+ | "bad-signature";
106
+ export type WebhookVerification = {
107
+ ok: true;
108
+ } | {
109
+ ok: false;
110
+ reason: WebhookRejection;
111
+ };
112
+ /**
113
+ * Verify a Sanity webhook delivery.
114
+ *
115
+ * `rawBody` must be the bytes as received — `await request.text()`, never
116
+ * `JSON.stringify(await request.json())`. A parse-and-restringify is not a
117
+ * byte-for-byte round trip (key order, number formatting, whitespace) and one
118
+ * byte changes the whole digest, so the symptom is every webhook failing after
119
+ * a refactor that looked like tidying.
120
+ *
121
+ * The `reason` is for our logs and our tests. It is never returned to the
122
+ * caller: "your signature was fine but your clock is stale" is the next step in
123
+ * an attack, handed over free.
124
+ */
125
+ export declare function verifySanityWebhook(options: {
126
+ secret: string | undefined;
127
+ rawBody: string;
128
+ headers: {
129
+ get(name: string): string | null;
130
+ };
131
+ now?: number;
132
+ toleranceMs?: number;
133
+ }): Promise<WebhookVerification>;
@@ -0,0 +1,51 @@
1
+ import { type CmsQuery, type CmsResolution } from "../contracts/query.cjs";
2
+ export type CmsFailure = "configuration" | "network" | "timeout" | "rate-limit" | "upstream" | "plan-limit" | "permission" | "malformed";
3
+ export type CmsDiagnostic = {
4
+ readonly event: "cms.fallback" | "cms.partial-fallback" | "cms.refused";
5
+ readonly query: string;
6
+ readonly reason: CmsFailure | "missing" | "invalid-field";
7
+ readonly status?: number;
8
+ readonly fields: readonly string[];
9
+ readonly warnings?: CmsResolution<unknown>["warnings"];
10
+ };
11
+ export type CmsFetch = (url: string, init: RequestInit & {
12
+ next?: {
13
+ revalidate: number;
14
+ tags: string[];
15
+ };
16
+ }) => Promise<Response>;
17
+ export type CmsReadPolicy = {
18
+ readonly tags: readonly string[];
19
+ readonly revalidateSeconds: number;
20
+ };
21
+ export type CmsAdapterResult = {
22
+ readonly ok: true;
23
+ readonly value: unknown;
24
+ } | {
25
+ readonly ok: false;
26
+ readonly reason: CmsFailure;
27
+ readonly status?: number;
28
+ };
29
+ export type CmsAdapter = {
30
+ readonly scope: string;
31
+ read(query: Pick<CmsQuery<unknown>, "name" | "query" | "params">, policy: CmsReadPolicy): Promise<CmsAdapterResult>;
32
+ };
33
+ export type CmsReadResult<T> = {
34
+ readonly data: T;
35
+ readonly source: "cms" | "mixed" | "fallback";
36
+ readonly fallbackFields: readonly string[];
37
+ readonly reason?: CmsFailure | "missing" | "invalid-field";
38
+ readonly warnings?: CmsResolution<unknown>["warnings"];
39
+ };
40
+ export type CmsReaderOptions = {
41
+ readonly adapter: CmsAdapter;
42
+ readonly revalidateSeconds?: number;
43
+ readonly onDiagnostic?: (event: CmsDiagnostic) => void;
44
+ };
45
+ export type CmsReader = {
46
+ read<T>(query: CmsQuery<T>, options: {
47
+ readonly fallback: T;
48
+ }): Promise<CmsReadResult<T>>;
49
+ };
50
+ /** Forwards cache policy; persistence and rendered-output invalidation belong to the host. */
51
+ export declare function createCmsReader(options: CmsReaderOptions): CmsReader;
@@ -0,0 +1,51 @@
1
+ import { type CmsQuery, type CmsResolution } from "../contracts/query.mjs";
2
+ export type CmsFailure = "configuration" | "network" | "timeout" | "rate-limit" | "upstream" | "plan-limit" | "permission" | "malformed";
3
+ export type CmsDiagnostic = {
4
+ readonly event: "cms.fallback" | "cms.partial-fallback" | "cms.refused";
5
+ readonly query: string;
6
+ readonly reason: CmsFailure | "missing" | "invalid-field";
7
+ readonly status?: number;
8
+ readonly fields: readonly string[];
9
+ readonly warnings?: CmsResolution<unknown>["warnings"];
10
+ };
11
+ export type CmsFetch = (url: string, init: RequestInit & {
12
+ next?: {
13
+ revalidate: number;
14
+ tags: string[];
15
+ };
16
+ }) => Promise<Response>;
17
+ export type CmsReadPolicy = {
18
+ readonly tags: readonly string[];
19
+ readonly revalidateSeconds: number;
20
+ };
21
+ export type CmsAdapterResult = {
22
+ readonly ok: true;
23
+ readonly value: unknown;
24
+ } | {
25
+ readonly ok: false;
26
+ readonly reason: CmsFailure;
27
+ readonly status?: number;
28
+ };
29
+ export type CmsAdapter = {
30
+ readonly scope: string;
31
+ read(query: Pick<CmsQuery<unknown>, "name" | "query" | "params">, policy: CmsReadPolicy): Promise<CmsAdapterResult>;
32
+ };
33
+ export type CmsReadResult<T> = {
34
+ readonly data: T;
35
+ readonly source: "cms" | "mixed" | "fallback";
36
+ readonly fallbackFields: readonly string[];
37
+ readonly reason?: CmsFailure | "missing" | "invalid-field";
38
+ readonly warnings?: CmsResolution<unknown>["warnings"];
39
+ };
40
+ export type CmsReaderOptions = {
41
+ readonly adapter: CmsAdapter;
42
+ readonly revalidateSeconds?: number;
43
+ readonly onDiagnostic?: (event: CmsDiagnostic) => void;
44
+ };
45
+ export type CmsReader = {
46
+ read<T>(query: CmsQuery<T>, options: {
47
+ readonly fallback: T;
48
+ }): Promise<CmsReadResult<T>>;
49
+ };
50
+ /** Forwards cache policy; persistence and rendered-output invalidation belong to the host. */
51
+ export declare function createCmsReader(options: CmsReaderOptions): CmsReader;
@@ -0,0 +1,51 @@
1
+ import { type CmsQuery, type CmsResolution } from "../contracts/query.js";
2
+ export type CmsFailure = "configuration" | "network" | "timeout" | "rate-limit" | "upstream" | "plan-limit" | "permission" | "malformed";
3
+ export type CmsDiagnostic = {
4
+ readonly event: "cms.fallback" | "cms.partial-fallback" | "cms.refused";
5
+ readonly query: string;
6
+ readonly reason: CmsFailure | "missing" | "invalid-field";
7
+ readonly status?: number;
8
+ readonly fields: readonly string[];
9
+ readonly warnings?: CmsResolution<unknown>["warnings"];
10
+ };
11
+ export type CmsFetch = (url: string, init: RequestInit & {
12
+ next?: {
13
+ revalidate: number;
14
+ tags: string[];
15
+ };
16
+ }) => Promise<Response>;
17
+ export type CmsReadPolicy = {
18
+ readonly tags: readonly string[];
19
+ readonly revalidateSeconds: number;
20
+ };
21
+ export type CmsAdapterResult = {
22
+ readonly ok: true;
23
+ readonly value: unknown;
24
+ } | {
25
+ readonly ok: false;
26
+ readonly reason: CmsFailure;
27
+ readonly status?: number;
28
+ };
29
+ export type CmsAdapter = {
30
+ readonly scope: string;
31
+ read(query: Pick<CmsQuery<unknown>, "name" | "query" | "params">, policy: CmsReadPolicy): Promise<CmsAdapterResult>;
32
+ };
33
+ export type CmsReadResult<T> = {
34
+ readonly data: T;
35
+ readonly source: "cms" | "mixed" | "fallback";
36
+ readonly fallbackFields: readonly string[];
37
+ readonly reason?: CmsFailure | "missing" | "invalid-field";
38
+ readonly warnings?: CmsResolution<unknown>["warnings"];
39
+ };
40
+ export type CmsReaderOptions = {
41
+ readonly adapter: CmsAdapter;
42
+ readonly revalidateSeconds?: number;
43
+ readonly onDiagnostic?: (event: CmsDiagnostic) => void;
44
+ };
45
+ export type CmsReader = {
46
+ read<T>(query: CmsQuery<T>, options: {
47
+ readonly fallback: T;
48
+ }): Promise<CmsReadResult<T>>;
49
+ };
50
+ /** Forwards cache policy; persistence and rendered-output invalidation belong to the host. */
51
+ export declare function createCmsReader(options: CmsReaderOptions): CmsReader;
@@ -0,0 +1,2 @@
1
+ "use strict";var w=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var R=(e,t)=>{for(var n in t)w(e,n,{get:t[n],enumerable:!0})},x=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of z(t))!$.call(e,s)&&s!==n&&w(e,s,{get:()=>t[s],enumerable:!(r=E(t,s))||r.enumerable});return e};var P=e=>x(w({},"__esModule",{value:!0}),e);var B={};R(B,{createSanityAdapter:()=>v,sanityBindingFromEnv:()=>I});module.exports=P(B);var Y=require("server-only");var M=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,D=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,N=/^[a-z0-9]{6,12}\.[a-z][a-z0-9_-]{0,63}$/;function T(e){if(!e||!Array.isArray(e.types)||e.types.length===0)throw new TypeError("CMS dependencies require document types");let t=[...e.types];for(let r of t)if(typeof r!="string"||!M.test(r))throw new TypeError("Invalid CMS document type");if(e.ids!==void 0&&!Array.isArray(e.ids))throw new TypeError("Invalid CMS document IDs");let n=e.ids===void 0?void 0:[...e.ids];for(let r of n??[])if(typeof r!="string"||!D.test(r)||/^(drafts|versions)\./.test(r))throw new TypeError("Invalid CMS document ID");if(new Set(t).size+new Set(n).size>128)throw new TypeError("Too many CMS tags");return Object.freeze({types:Object.freeze(t),...n===void 0?{}:{ids:Object.freeze(n)}})}function b(e){if(!e||typeof e.name!="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(e.name)||typeof e.query!="string"||e.query.trim()===""||typeof e.resolve!="function")throw new TypeError("Invalid CMS query configuration");let t=e.params;if(!t||typeof t!="object"||Object.getPrototypeOf(t)!==Object.prototype&&Object.getPrototypeOf(t)!==null)throw new TypeError("CMS params must be plain JSON scalars");let n={};for(let r of Reflect.ownKeys(t)){let s=Object.getOwnPropertyDescriptor(t,r);if(typeof r!="string"||!s||!Object.hasOwn(s,"value")||!s.enumerable)throw new TypeError("CMS params must be plain JSON scalars");let i=s.value;if(!(i===null||typeof i=="string"||typeof i=="boolean"||typeof i=="number"&&Number.isFinite(i)))throw new TypeError("CMS params must be plain JSON scalars");Object.defineProperty(n,r,{value:i,enumerable:!0})}return Object.freeze({name:e.name,query:e.query,params:Object.freeze(n),dependencies:T(e.dependencies),resolve:e.resolve})}function C(e,t){if(typeof e!="string"||e.length>77||!N.test(e))throw new TypeError("Invalid CMS scope");let n=T(t),r=[...[...new Set(n.types)].sort().map(s=>`cms:${e}:type:${s}`),...[...new Set(n.ids??[])].sort().map(s=>`cms:${e}:id:${s}`)];return Object.freeze(r)}var _=2*1024*1024;function A(e){if(!e||typeof e.projectId!="string"||!/^[a-z0-9]{6,12}$/.test(e.projectId)||typeof e.dataset!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(e.dataset)||typeof e.apiVersion!="string"||!/^v?\d{4}-\d{2}-\d{2}$/.test(e.apiVersion))throw new TypeError("Invalid Sanity binding configuration");return Object.freeze({projectId:e.projectId,dataset:e.dataset,apiVersion:e.apiVersion.replace(/^v/,"")})}function v(e){let t=A(e?.binding),n=e.timeoutMs??1500,r=e.readToken;if(!Number.isSafeInteger(n)||n<=0||n>2147483647||e.fetchImpl!==void 0&&typeof e.fetchImpl!="function"||r!==void 0&&(typeof r!="string"||r.trim()===""||/[\r\n]/.test(r)))throw new TypeError("Invalid Sanity adapter configuration");let s=e.fetchImpl,i=`${t.projectId}.${t.dataset}`;return Object.freeze({scope:i,async read(O,c){let y;try{if(!c||!Number.isSafeInteger(c.revalidateSeconds)||c.revalidateSeconds<3600||!Array.isArray(c.tags))throw new TypeError;let o=[],p=[];for(let d of c.tags){if(typeof d!="string")throw new TypeError;if(d.startsWith(`cms:${i}:type:`))o.push(d.slice(`cms:${i}:type:`.length));else if(d.startsWith(`cms:${i}:id:`))p.push(d.slice(`cms:${i}:id:`.length));else throw new TypeError}let l=C(i,{types:o,ids:p});if(l.length!==c.tags.length||l.some((d,a)=>d!==c.tags[a]))throw new TypeError;y=b({...O,dependencies:{types:o,ids:p},resolve:d=>({data:d,fallbackFields:[]})})}catch{throw new TypeError("Invalid Sanity read configuration")}let f=new URL(`https://${t.projectId}.api.sanity.io/v${t.apiVersion}/data/query/${t.dataset}`);f.searchParams.set("query",y.query),f.searchParams.set("perspective","published");for(let o of Object.keys(y.params).sort())f.searchParams.set(`$${o}`,JSON.stringify(y.params[o]));let h=new AbortController,m,u=!1,g=()=>{h.abort(),m&&m.cancel().catch(()=>{})},S,k=new Promise(o=>{S=setTimeout(()=>{u=!0,g(),o({ok:!1,reason:"timeout"})},n)}),j=async()=>{try{let o=await(s??globalThis.fetch)(f.href,{method:"GET",redirect:"error",signal:h.signal,headers:r===void 0?{}:{Authorization:`Bearer ${r}`},next:{revalidate:c.revalidateSeconds,tags:[...c.tags]}});if(u)return o.body?.cancel().catch(()=>{}),{ok:!1,reason:"timeout"};if(!o.ok){o.body?.cancel().catch(()=>{});let a=o.status;return{ok:!1,reason:a===402?"plan-limit":a===401||a===403?"permission":a===429?"rate-limit":"upstream",status:a}}if(!o.body)return{ok:!1,reason:"malformed"};m=o.body.getReader();let p=0,l="",d=new TextDecoder("utf-8",{fatal:!0});for(;;){let a=await m.read();if(u)return{ok:!1,reason:"timeout"};if(a.done)break;if(p+=a.value.byteLength,p>_)return g(),{ok:!1,reason:"malformed"};try{l+=d.decode(a.value,{stream:!0})}catch{return g(),{ok:!1,reason:"malformed"}}}try{l+=d.decode();let a=JSON.parse(l);return!a||typeof a!="object"||Array.isArray(a)||!Object.hasOwn(a,"result")?{ok:!1,reason:"malformed"}:{ok:!0,value:a.result}}catch{return{ok:!1,reason:"malformed"}}}catch{return{ok:!1,reason:u?"timeout":"network"}}};try{return await Promise.race([j(),k])}finally{clearTimeout(S)}}})}function I(e){return A({projectId:e.SANITY_PROJECT_ID,dataset:e.SANITY_DATASET,apiVersion:e.SANITY_API_VERSION})}0&&(module.exports={createSanityAdapter,sanityBindingFromEnv});
2
+ //# sourceMappingURL=sanity.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/sanity.ts", "../src/contracts/query.ts", "../src/adapters/sanity/adapter.ts"],
4
+ "sourcesContent": ["import \"server-only\";\nexport { createSanityAdapter, sanityBindingFromEnv } from \"./adapters/sanity/adapter.js\";\nexport type { SanityBinding, SanityAdapterOptions } from \"./adapters/sanity/adapter.js\";\n", "/** A-1822 S1 owns this implementation. S0 registers the public signatures. */\nexport type CmsParams = Readonly<Record<string, string | number | boolean | null>>;\nexport type CmsDependencies = {\n readonly types: readonly string[];\n readonly ids?: readonly string[];\n};\nexport type CmsResolution<T> = {\n readonly data: T;\n readonly fallbackFields: readonly string[];\n readonly warnings?: readonly \"siteHero.layout.defaulted\"[];\n};\nexport type CmsQuery<T> = {\n readonly name: string;\n readonly query: string;\n readonly params: CmsParams;\n readonly dependencies: CmsDependencies;\n readonly resolve: (raw: unknown, fallback: T) => CmsResolution<T>;\n};\n\nconst TYPE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;\nconst ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\nconst SCOPE = /^[a-z0-9]{6,12}\\.[a-z][a-z0-9_-]{0,63}$/;\n\nfunction dependenciesCopy(dependencies: CmsDependencies): CmsDependencies {\n if (!dependencies || !Array.isArray(dependencies.types) || dependencies.types.length === 0) {\n throw new TypeError(\"CMS dependencies require document types\");\n }\n const types = [...dependencies.types];\n for (const type of types) {\n if (typeof type !== \"string\" || !TYPE.test(type)) throw new TypeError(\"Invalid CMS document type\");\n }\n if (dependencies.ids !== undefined && !Array.isArray(dependencies.ids)) throw new TypeError(\"Invalid CMS document IDs\");\n const ids = dependencies.ids === undefined ? undefined : [...dependencies.ids];\n for (const id of ids ?? []) {\n if (typeof id !== \"string\" || !ID.test(id) || /^(drafts|versions)\\./.test(id)) {\n throw new TypeError(\"Invalid CMS document ID\");\n }\n }\n if (new Set(types).size + new Set(ids).size > 128) throw new TypeError(\"Too many CMS tags\");\n return Object.freeze({ types: Object.freeze(types), ...(ids === undefined ? {} : { ids: Object.freeze(ids) }) });\n}\n\nexport function defineCmsQuery<T>(query: CmsQuery<T>): CmsQuery<T> {\n if (!query || typeof query.name !== \"string\" || !/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(query.name)\n || typeof query.query !== \"string\" || query.query.trim() === \"\" || typeof query.resolve !== \"function\") {\n throw new TypeError(\"Invalid CMS query configuration\");\n }\n const params = query.params;\n if (!params || typeof params !== \"object\" || (Object.getPrototypeOf(params) !== Object.prototype && Object.getPrototypeOf(params) !== null)) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n const copied: Record<string, string | number | boolean | null> = {};\n for (const key of Reflect.ownKeys(params)) {\n const descriptor = Object.getOwnPropertyDescriptor(params, key);\n if (typeof key !== \"string\" || !descriptor || !Object.hasOwn(descriptor, \"value\") || !descriptor.enumerable) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n const value: unknown = descriptor.value;\n if (!(value === null || typeof value === \"string\" || typeof value === \"boolean\" || (typeof value === \"number\" && Number.isFinite(value)))) {\n throw new TypeError(\"CMS params must be plain JSON scalars\");\n }\n Object.defineProperty(copied, key, { value, enumerable: true });\n }\n return Object.freeze({ name: query.name, query: query.query, params: Object.freeze(copied), dependencies: dependenciesCopy(query.dependencies), resolve: query.resolve });\n}\n\nexport function cmsTags(scope: string, dependencies: CmsDependencies): readonly string[] {\n if (typeof scope !== \"string\" || scope.length > 77 || !SCOPE.test(scope)) throw new TypeError(\"Invalid CMS scope\");\n const copied = dependenciesCopy(dependencies);\n const tags = [\n ...[...new Set(copied.types)].sort().map((type) => `cms:${scope}:type:${type}`),\n ...[...new Set(copied.ids ?? [])].sort().map((id) => `cms:${scope}:id:${id}`),\n ];\n return Object.freeze(tags);\n}\n", "import type { CmsAdapter, CmsFetch } from \"../../runtime/reader.js\";\nimport { cmsTags, defineCmsQuery } from \"../../contracts/query.js\";\n\nexport type SanityBinding = {\n readonly projectId: string;\n readonly dataset: string;\n readonly apiVersion: string;\n};\nexport type SanityAdapterOptions = {\n readonly binding: SanityBinding;\n readonly readToken?: string;\n readonly fetchImpl?: CmsFetch;\n readonly timeoutMs?: number;\n};\n\nconst RESPONSE_LIMIT = 2 * 1024 * 1024;\n\nfunction bindingCopy(binding: SanityBinding): SanityBinding {\n if (!binding || typeof binding.projectId !== \"string\" || !/^[a-z0-9]{6,12}$/.test(binding.projectId)\n || typeof binding.dataset !== \"string\" || !/^[a-z][a-z0-9_-]{0,63}$/.test(binding.dataset)\n || typeof binding.apiVersion !== \"string\" || !/^v?\\d{4}-\\d{2}-\\d{2}$/.test(binding.apiVersion)) {\n throw new TypeError(\"Invalid Sanity binding configuration\");\n }\n return Object.freeze({ projectId: binding.projectId, dataset: binding.dataset, apiVersion: binding.apiVersion.replace(/^v/, \"\") });\n}\n\n/** Applies policy via fetch's Next metadata. Standard fetch has no persistent cache or HTML invalidation. */\nexport function createSanityAdapter(options: SanityAdapterOptions): CmsAdapter {\n const binding = bindingCopy(options?.binding);\n const timeoutMs = options.timeoutMs ?? 1500;\n const token = options.readToken;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647\n || (options.fetchImpl !== undefined && typeof options.fetchImpl !== \"function\")\n || (token !== undefined && (typeof token !== \"string\" || token.trim() === \"\" || /[\\r\\n]/.test(token)))) {\n throw new TypeError(\"Invalid Sanity adapter configuration\");\n }\n const fetchImpl = options.fetchImpl;\n const scope = `${binding.projectId}.${binding.dataset}`;\n return Object.freeze({\n scope,\n async read(query, policy) {\n // Direct structural callers receive the same configuration refusals.\n let validated;\n try {\n if (!policy || !Number.isSafeInteger(policy.revalidateSeconds) || policy.revalidateSeconds < 3600 || !Array.isArray(policy.tags)) throw new TypeError();\n const types: string[] = [];\n const ids: string[] = [];\n for (const tag of policy.tags) {\n if (typeof tag !== \"string\") throw new TypeError();\n if (tag.startsWith(`cms:${scope}:type:`)) types.push(tag.slice(`cms:${scope}:type:`.length));\n else if (tag.startsWith(`cms:${scope}:id:`)) ids.push(tag.slice(`cms:${scope}:id:`.length));\n else throw new TypeError();\n }\n const expected = cmsTags(scope, { types, ids });\n if (expected.length !== policy.tags.length || expected.some((tag, i) => tag !== policy.tags[i])) throw new TypeError();\n validated = defineCmsQuery({ ...query, dependencies: { types, ids }, resolve: (raw: unknown) => ({ data: raw, fallbackFields: [] }) });\n } catch { throw new TypeError(\"Invalid Sanity read configuration\"); }\n const url = new URL(`https://${binding.projectId}.api.sanity.io/v${binding.apiVersion}/data/query/${binding.dataset}`);\n url.searchParams.set(\"query\", validated.query);\n url.searchParams.set(\"perspective\", \"published\");\n for (const key of Object.keys(validated.params).sort()) url.searchParams.set(`$${key}`, JSON.stringify(validated.params[key]));\n const controller = new AbortController();\n let bodyReader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let expired = false;\n const cancel = (): void => {\n controller.abort();\n if (bodyReader) void bodyReader.cancel().catch(() => {});\n };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<Awaited<ReturnType<CmsAdapter[\"read\"]>>>((resolve) => {\n timer = setTimeout(() => {\n expired = true;\n cancel();\n resolve({ ok: false, reason: \"timeout\" });\n }, timeoutMs);\n });\n const work = async (): Promise<Awaited<ReturnType<CmsAdapter[\"read\"]>>> => {\n try {\n // Look up global fetch at read time so Next's patched fetch is retained.\n const response = await (fetchImpl ?? globalThis.fetch)(url.href, {\n method: \"GET\", redirect: \"error\", signal: controller.signal,\n headers: token === undefined ? {} : { Authorization: `Bearer ${token}` },\n next: { revalidate: policy.revalidateSeconds, tags: [...policy.tags] },\n });\n if (expired) { void response.body?.cancel().catch(() => {}); return { ok: false, reason: \"timeout\" }; }\n if (!response.ok) {\n void response.body?.cancel().catch(() => {});\n const status = response.status;\n const reason = status === 402 ? \"plan-limit\" : status === 401 || status === 403 ? \"permission\"\n : status === 429 ? \"rate-limit\" : \"upstream\";\n return { ok: false, reason, status };\n }\n if (!response.body) return { ok: false, reason: \"malformed\" };\n bodyReader = response.body.getReader();\n let bytes = 0;\n let text = \"\";\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n while (true) {\n const chunk = await bodyReader.read();\n if (expired) return { ok: false, reason: \"timeout\" };\n if (chunk.done) break;\n bytes += chunk.value.byteLength;\n if (bytes > RESPONSE_LIMIT) { cancel(); return { ok: false, reason: \"malformed\" }; }\n try { text += decoder.decode(chunk.value, { stream: true }); }\n catch { cancel(); return { ok: false, reason: \"malformed\" }; }\n }\n try {\n text += decoder.decode();\n const envelope: unknown = JSON.parse(text);\n if (!envelope || typeof envelope !== \"object\" || Array.isArray(envelope) || !Object.hasOwn(envelope, \"result\")) return { ok: false, reason: \"malformed\" };\n return { ok: true, value: (envelope as Record<string, unknown>).result };\n } catch { return { ok: false, reason: \"malformed\" }; }\n } catch { return { ok: false, reason: expired ? \"timeout\" : \"network\" }; }\n };\n try { return await Promise.race([work(), deadline]); }\n finally { clearTimeout(timer); }\n },\n } satisfies CmsAdapter);\n}\n\nexport function sanityBindingFromEnv(env: Readonly<Record<string, string | undefined>>): SanityBinding {\n return bindingCopy({ projectId: env.SANITY_PROJECT_ID, dataset: env.SANITY_DATASET, apiVersion: env.SANITY_API_VERSION } as SanityBinding);\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,yBAAAE,EAAA,yBAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAO,uBCmBP,IAAMC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AE,GAAI,GAAO,OAAQ,WAAY,CAAG,CAC/D,CACA,GAAI,CACFQ,GAAQC,EAAQ,OAAO,EACvB,IAAME,EAAoB,KAAK,MAAMH,CAAI,EACzC,MAAI,CAACG,GAAY,OAAOA,GAAa,UAAY,MAAM,QAAQA,CAAQ,GAAK,CAAC,OAAO,OAAOA,EAAU,QAAQ,EAAU,CAAE,GAAI,GAAO,OAAQ,WAAY,EACjJ,CAAE,GAAI,GAAM,MAAQA,EAAqC,MAAO,CACzE,MAAQ,CAAE,MAAO,CAAE,GAAI,GAAO,OAAQ,WAAY,CAAG,CACvD,MAAQ,CAAE,MAAO,CAAE,GAAI,GAAO,OAAQZ,EAAU,UAAY,SAAU,CAAG,CAC3E,EACA,GAAI,CAAE,OAAO,MAAM,QAAQ,KAAK,CAACK,EAAK,EAAGF,CAAQ,CAAC,CAAG,QACrD,CAAU,aAAaD,CAAK,CAAG,CACjC,CACF,CAAsB,CACxB,CAEO,SAASW,EAAqBC,EAAkE,CACrG,OAAOrC,EAAY,CAAE,UAAWqC,EAAI,kBAAmB,QAASA,EAAI,eAAgB,WAAYA,EAAI,kBAAmB,CAAkB,CAC3I",
6
+ "names": ["sanity_exports", "__export", "createSanityAdapter", "sanityBindingFromEnv", "__toCommonJS", "import_server_only", "TYPE", "ID", "SCOPE", "dependenciesCopy", "dependencies", "types", "type", "ids", "id", "defineCmsQuery", "query", "params", "copied", "key", "descriptor", "value", "cmsTags", "scope", "tags", "RESPONSE_LIMIT", "bindingCopy", "binding", "createSanityAdapter", "options", "timeoutMs", "token", "fetchImpl", "scope", "query", "policy", "validated", "types", "ids", "tag", "expected", "cmsTags", "i", "defineCmsQuery", "raw", "url", "key", "controller", "bodyReader", "expired", "cancel", "timer", "deadline", "resolve", "work", "response", "status", "bytes", "text", "decoder", "chunk", "envelope", "sanityBindingFromEnv", "env"]
7
+ }
@@ -0,0 +1,3 @@
1
+ import "server-only";
2
+ export { createSanityAdapter, sanityBindingFromEnv } from "./adapters/sanity/adapter.cjs";
3
+ export type { SanityBinding, SanityAdapterOptions } from "./adapters/sanity/adapter.cjs";
@@ -0,0 +1,3 @@
1
+ import "server-only";
2
+ export { createSanityAdapter, sanityBindingFromEnv } from "./adapters/sanity/adapter.mjs";
3
+ export type { SanityBinding, SanityAdapterOptions } from "./adapters/sanity/adapter.mjs";
@@ -0,0 +1,3 @@
1
+ import "server-only";
2
+ export { createSanityAdapter, sanityBindingFromEnv } from "./adapters/sanity/adapter.js";
3
+ export type { SanityBinding, SanityAdapterOptions } from "./adapters/sanity/adapter.js";
@@ -0,0 +1,2 @@
1
+ import"server-only";var O=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,k=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,j=/^[a-z0-9]{6,12}\.[a-z][a-z0-9_-]{0,63}$/;function S(e){if(!e||!Array.isArray(e.types)||e.types.length===0)throw new TypeError("CMS dependencies require document types");let r=[...e.types];for(let t of r)if(typeof t!="string"||!O.test(t))throw new TypeError("Invalid CMS document type");if(e.ids!==void 0&&!Array.isArray(e.ids))throw new TypeError("Invalid CMS document IDs");let a=e.ids===void 0?void 0:[...e.ids];for(let t of a??[])if(typeof t!="string"||!k.test(t)||/^(drafts|versions)\./.test(t))throw new TypeError("Invalid CMS document ID");if(new Set(r).size+new Set(a).size>128)throw new TypeError("Too many CMS tags");return Object.freeze({types:Object.freeze(r),...a===void 0?{}:{ids:Object.freeze(a)}})}function T(e){if(!e||typeof e.name!="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(e.name)||typeof e.query!="string"||e.query.trim()===""||typeof e.resolve!="function")throw new TypeError("Invalid CMS query configuration");let r=e.params;if(!r||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null)throw new TypeError("CMS params must be plain JSON scalars");let a={};for(let t of Reflect.ownKeys(r)){let d=Object.getOwnPropertyDescriptor(r,t);if(typeof t!="string"||!d||!Object.hasOwn(d,"value")||!d.enumerable)throw new TypeError("CMS params must be plain JSON scalars");let o=d.value;if(!(o===null||typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)))throw new TypeError("CMS params must be plain JSON scalars");Object.defineProperty(a,t,{value:o,enumerable:!0})}return Object.freeze({name:e.name,query:e.query,params:Object.freeze(a),dependencies:S(e.dependencies),resolve:e.resolve})}function b(e,r){if(typeof e!="string"||e.length>77||!j.test(e))throw new TypeError("Invalid CMS scope");let a=S(r),t=[...[...new Set(a.types)].sort().map(d=>`cms:${e}:type:${d}`),...[...new Set(a.ids??[])].sort().map(d=>`cms:${e}:id:${d}`)];return Object.freeze(t)}var E=2*1024*1024;function C(e){if(!e||typeof e.projectId!="string"||!/^[a-z0-9]{6,12}$/.test(e.projectId)||typeof e.dataset!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(e.dataset)||typeof e.apiVersion!="string"||!/^v?\d{4}-\d{2}-\d{2}$/.test(e.apiVersion))throw new TypeError("Invalid Sanity binding configuration");return Object.freeze({projectId:e.projectId,dataset:e.dataset,apiVersion:e.apiVersion.replace(/^v/,"")})}function z(e){let r=C(e?.binding),a=e.timeoutMs??1500,t=e.readToken;if(!Number.isSafeInteger(a)||a<=0||a>2147483647||e.fetchImpl!==void 0&&typeof e.fetchImpl!="function"||t!==void 0&&(typeof t!="string"||t.trim()===""||/[\r\n]/.test(t)))throw new TypeError("Invalid Sanity adapter configuration");let d=e.fetchImpl,o=`${r.projectId}.${r.dataset}`;return Object.freeze({scope:o,async read(A,c){let y;try{if(!c||!Number.isSafeInteger(c.revalidateSeconds)||c.revalidateSeconds<3600||!Array.isArray(c.tags))throw new TypeError;let s=[],p=[];for(let i of c.tags){if(typeof i!="string")throw new TypeError;if(i.startsWith(`cms:${o}:type:`))s.push(i.slice(`cms:${o}:type:`.length));else if(i.startsWith(`cms:${o}:id:`))p.push(i.slice(`cms:${o}:id:`.length));else throw new TypeError}let l=b(o,{types:s,ids:p});if(l.length!==c.tags.length||l.some((i,n)=>i!==c.tags[n]))throw new TypeError;y=T({...A,dependencies:{types:s,ids:p},resolve:i=>({data:i,fallbackFields:[]})})}catch{throw new TypeError("Invalid Sanity read configuration")}let f=new URL(`https://${r.projectId}.api.sanity.io/v${r.apiVersion}/data/query/${r.dataset}`);f.searchParams.set("query",y.query),f.searchParams.set("perspective","published");for(let s of Object.keys(y.params).sort())f.searchParams.set(`$${s}`,JSON.stringify(y.params[s]));let w=new AbortController,m,u=!1,g=()=>{w.abort(),m&&m.cancel().catch(()=>{})},h,v=new Promise(s=>{h=setTimeout(()=>{u=!0,g(),s({ok:!1,reason:"timeout"})},a)}),I=async()=>{try{let s=await(d??globalThis.fetch)(f.href,{method:"GET",redirect:"error",signal:w.signal,headers:t===void 0?{}:{Authorization:`Bearer ${t}`},next:{revalidate:c.revalidateSeconds,tags:[...c.tags]}});if(u)return s.body?.cancel().catch(()=>{}),{ok:!1,reason:"timeout"};if(!s.ok){s.body?.cancel().catch(()=>{});let n=s.status;return{ok:!1,reason:n===402?"plan-limit":n===401||n===403?"permission":n===429?"rate-limit":"upstream",status:n}}if(!s.body)return{ok:!1,reason:"malformed"};m=s.body.getReader();let p=0,l="",i=new TextDecoder("utf-8",{fatal:!0});for(;;){let n=await m.read();if(u)return{ok:!1,reason:"timeout"};if(n.done)break;if(p+=n.value.byteLength,p>E)return g(),{ok:!1,reason:"malformed"};try{l+=i.decode(n.value,{stream:!0})}catch{return g(),{ok:!1,reason:"malformed"}}}try{l+=i.decode();let n=JSON.parse(l);return!n||typeof n!="object"||Array.isArray(n)||!Object.hasOwn(n,"result")?{ok:!1,reason:"malformed"}:{ok:!0,value:n.result}}catch{return{ok:!1,reason:"malformed"}}}catch{return{ok:!1,reason:u?"timeout":"network"}}};try{return await Promise.race([I(),v])}finally{clearTimeout(h)}}})}function $(e){return C({projectId:e.SANITY_PROJECT_ID,dataset:e.SANITY_DATASET,apiVersion:e.SANITY_API_VERSION})}export{z as createSanityAdapter,$ as sanityBindingFromEnv};
2
+ //# sourceMappingURL=sanity.mjs.map