@klnap/cache-invalidation 0.0.0-stage → 0.0.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/CHANGELOG.md +139 -0
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/dist/consumers/next/compile-tag-template.d.ts +16 -0
- package/dist/consumers/next/compile-tag-template.js +83 -0
- package/dist/consumers/next/consumer-types.d.ts +98 -0
- package/dist/consumers/next/consumer-types.js +3 -0
- package/dist/consumers/next/define-cache.d.ts +4 -0
- package/dist/consumers/next/define-cache.js +281 -0
- package/dist/consumers/next/host-types.d.ts +44 -0
- package/dist/consumers/next/host-types.js +3 -0
- package/dist/consumers/next/index.d.ts +5 -0
- package/dist/consumers/next/index.js +2 -0
- package/dist/consumers/next/param-values.d.ts +8 -0
- package/dist/consumers/next/param-values.js +23 -0
- package/dist/consumers/next/profile.d.ts +2 -0
- package/dist/consumers/next/profile.js +18 -0
- package/dist/consumers/next/registry-builders.d.ts +3 -0
- package/dist/consumers/next/registry-builders.js +155 -0
- package/dist/consumers/next/revalidation-handler.d.ts +6 -0
- package/dist/consumers/next/revalidation-handler.js +2 -0
- package/dist/consumers/next/runtime.d.ts +5 -0
- package/dist/consumers/next/runtime.js +560 -0
- package/dist/core/cloudevents.d.ts +27 -0
- package/dist/core/cloudevents.js +172 -0
- package/dist/core/dispatch-outcome.d.ts +4 -0
- package/dist/core/dispatch-outcome.js +17 -0
- package/dist/core/errors.d.ts +16 -0
- package/dist/core/errors.js +28 -0
- package/dist/core/event-limits.d.ts +15 -0
- package/dist/core/event-limits.js +20 -0
- package/dist/core/event-selector.d.ts +9 -0
- package/dist/core/event-selector.js +5 -0
- package/dist/core/index.d.ts +10 -0
- package/dist/core/index.js +6 -0
- package/dist/core/resource-changed-schema.d.ts +35 -0
- package/dist/core/resource-changed-schema.js +12 -0
- package/dist/core/standard-schema.d.ts +2 -0
- package/dist/core/standard-schema.js +7 -0
- package/dist/core/types.d.ts +35 -0
- package/dist/core/types.js +1 -0
- package/dist/core/url-segment.d.ts +2 -0
- package/dist/core/url-segment.js +17 -0
- package/dist/dispatchers/http/index.d.ts +20 -0
- package/dist/dispatchers/http/index.js +274 -0
- package/dist/dispatchers/http/targets.d.ts +14 -0
- package/dist/dispatchers/http/targets.js +26 -0
- package/dist/dispatchers/index.d.ts +1 -0
- package/dist/dispatchers/index.js +1 -0
- package/dist/producers/payload/exclude-fields.d.ts +19 -0
- package/dist/producers/payload/exclude-fields.js +75 -0
- package/dist/producers/payload/index.d.ts +4 -0
- package/dist/producers/payload/index.js +3 -0
- package/dist/producers/payload/lifecycle/deferred.d.ts +55 -0
- package/dist/producers/payload/lifecycle/deferred.js +111 -0
- package/dist/producers/payload/lifecycle/dispatch.d.ts +18 -0
- package/dist/producers/payload/lifecycle/dispatch.js +21 -0
- package/dist/producers/payload/lifecycle/doc-content.d.ts +8 -0
- package/dist/producers/payload/lifecycle/doc-content.js +88 -0
- package/dist/producers/payload/lifecycle/draft-status.d.ts +6 -0
- package/dist/producers/payload/lifecycle/draft-status.js +15 -0
- package/dist/producers/payload/lifecycle/helpers.d.ts +13 -0
- package/dist/producers/payload/lifecycle/helpers.js +12 -0
- package/dist/producers/payload/lifecycle/identifier-field.d.ts +8 -0
- package/dist/producers/payload/lifecycle/identifier-field.js +48 -0
- package/dist/producers/payload/lifecycle/identifiers.d.ts +4 -0
- package/dist/producers/payload/lifecycle/identifiers.js +5 -0
- package/dist/producers/payload/lifecycle/locale-published.d.ts +7 -0
- package/dist/producers/payload/lifecycle/locale-published.js +19 -0
- package/dist/producers/payload/lifecycle/locale.d.ts +24 -0
- package/dist/producers/payload/lifecycle/locale.js +44 -0
- package/dist/producers/payload/lifecycle/log.d.ts +31 -0
- package/dist/producers/payload/lifecycle/log.js +67 -0
- package/dist/producers/payload/lifecycle/media-equality.d.ts +4 -0
- package/dist/producers/payload/lifecycle/media-equality.js +36 -0
- package/dist/producers/payload/lifecycle/operation.d.ts +2 -0
- package/dist/producers/payload/lifecycle/operation.js +7 -0
- package/dist/producers/payload/lifecycle/orderable-hooks.d.ts +21 -0
- package/dist/producers/payload/lifecycle/orderable-hooks.js +26 -0
- package/dist/producers/payload/lifecycle/orderable-neighbors.d.ts +21 -0
- package/dist/producers/payload/lifecycle/orderable-neighbors.js +151 -0
- package/dist/producers/payload/lifecycle/public-snapshots.d.ts +16 -0
- package/dist/producers/payload/lifecycle/public-snapshots.js +173 -0
- package/dist/producers/payload/lifecycle/revalidate.d.ts +16 -0
- package/dist/producers/payload/lifecycle/revalidate.js +162 -0
- package/dist/producers/payload/lifecycle/skip-rules.d.ts +19 -0
- package/dist/producers/payload/lifecycle/skip-rules.js +57 -0
- package/dist/producers/payload/lifecycle/types.d.ts +32 -0
- package/dist/producers/payload/lifecycle/types.js +1 -0
- package/dist/producers/payload/media/media-references.d.ts +31 -0
- package/dist/producers/payload/media/media-references.js +127 -0
- package/dist/producers/payload/media/resolve-media-affected-locales.d.ts +22 -0
- package/dist/producers/payload/media/resolve-media-affected-locales.js +70 -0
- package/dist/producers/payload/media/resolve-media-dependents.d.ts +39 -0
- package/dist/producers/payload/media/resolve-media-dependents.js +157 -0
- package/dist/producers/payload/media/resolve-media-slug.d.ts +7 -0
- package/dist/producers/payload/media/resolve-media-slug.js +17 -0
- package/dist/producers/payload/media/revalidate-media-dependents.d.ts +14 -0
- package/dist/producers/payload/media/revalidate-media-dependents.js +222 -0
- package/dist/producers/payload/plugin.d.ts +36 -0
- package/dist/producers/payload/plugin.js +235 -0
- package/dist/producers/payload/publish-all/context.d.ts +2 -0
- package/dist/producers/payload/publish-all/context.js +2 -0
- package/dist/producers/payload/publish-all/edited-locale.d.ts +5 -0
- package/dist/producers/payload/publish-all/edited-locale.js +5 -0
- package/dist/producers/payload/publish-all/index.d.ts +3 -0
- package/dist/producers/payload/publish-all/index.js +3 -0
- package/dist/producers/payload/publish-all/localization.d.ts +7 -0
- package/dist/producers/payload/publish-all/localization.js +1 -0
- package/dist/producers/payload/publish-all/mirror-publish-all-locales-to-req.d.ts +19 -0
- package/dist/producers/payload/publish-all/mirror-publish-all-locales-to-req.js +32 -0
- package/dist/producers/payload/publish-all/preserve-locales-on-publish-all.d.ts +2 -0
- package/dist/producers/payload/publish-all/preserve-locales-on-publish-all.js +145 -0
- package/dist/producers/payload/publish-all/read-localized-scalar.d.ts +2 -0
- package/dist/producers/payload/publish-all/read-localized-scalar.js +24 -0
- package/dist/producers/payload/publish-all/request-flags.d.ts +13 -0
- package/dist/producers/payload/publish-all/request-flags.js +9 -0
- package/dist/producers/payload/publish-all/restore-guard.d.ts +2 -0
- package/dist/producers/payload/publish-all/restore-guard.js +12 -0
- package/dist/producers/payload/publish-all/restore-locales-after-publish-all.d.ts +2 -0
- package/dist/producers/payload/publish-all/restore-locales-after-publish-all.js +85 -0
- package/dist/producers/payload/revalidation-custom.d.ts +37 -0
- package/dist/producers/payload/revalidation-custom.js +54 -0
- package/dist/producers/payload/schema.d.ts +3 -0
- package/dist/producers/payload/schema.js +23 -0
- package/docs/concepts/architecture.md +32 -0
- package/docs/concepts/cache-tags.md +97 -0
- package/docs/concepts/event-contract.md +38 -0
- package/docs/consumers/custom.md +19 -0
- package/docs/consumers/next.md +277 -0
- package/docs/dispatchers/custom.md +38 -0
- package/docs/dispatchers/http.md +66 -0
- package/docs/extending.md +26 -0
- package/docs/migration/0.3.0-to-0.4.0.md +67 -0
- package/docs/migration/0.4.0-to-0.5.0.md +60 -0
- package/docs/migration/0.5.x-to-0.0.0.md +143 -0
- package/docs/producers/custom.md +63 -0
- package/docs/producers/payload-media-dependencies.md +45 -0
- package/docs/producers/payload.md +140 -0
- package/docs/reliability.md +35 -0
- package/docs/security.md +34 -0
- package/docs/troubleshooting.md +14 -0
- package/package.json +120 -4
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { PRESERVE_LOCALES_EDITED_PATCH_CONTEXT_KEY, PRESERVE_LOCALES_SNAPSHOTS_CONTEXT_KEY, } from './context.js';
|
|
2
|
+
import { getAdminEditedLocale } from './edited-locale.js';
|
|
3
|
+
import { isPublishAllLocales } from './request-flags.js';
|
|
4
|
+
import { markLocaleRestoreReq } from './restore-guard.js';
|
|
5
|
+
const restoreChildReq = (req, locale) => {
|
|
6
|
+
const query = { ...(req.query ?? {}) };
|
|
7
|
+
delete query.publishAllLocales;
|
|
8
|
+
delete query.unpublishAllLocales;
|
|
9
|
+
query.locale = locale;
|
|
10
|
+
const childReq = {
|
|
11
|
+
...req,
|
|
12
|
+
locale: locale,
|
|
13
|
+
query,
|
|
14
|
+
// Fresh context: the child must not inherit the parent's snapshot/patch keys.
|
|
15
|
+
context: {},
|
|
16
|
+
};
|
|
17
|
+
markLocaleRestoreReq(childReq);
|
|
18
|
+
return childReq;
|
|
19
|
+
};
|
|
20
|
+
const writeLocalePatch = async ({ args, req, docId, locale, data, }) => {
|
|
21
|
+
if ('collection' in args) {
|
|
22
|
+
await req.payload.update({
|
|
23
|
+
collection: args.collection.slug,
|
|
24
|
+
id: docId,
|
|
25
|
+
locale: locale,
|
|
26
|
+
data,
|
|
27
|
+
draft: false,
|
|
28
|
+
overrideAccess: true,
|
|
29
|
+
req: restoreChildReq(req, locale),
|
|
30
|
+
});
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
await req.payload.updateGlobal({
|
|
34
|
+
slug: args.global.slug,
|
|
35
|
+
locale: locale,
|
|
36
|
+
data,
|
|
37
|
+
draft: false,
|
|
38
|
+
overrideAccess: true,
|
|
39
|
+
req: restoreChildReq(req, locale),
|
|
40
|
+
});
|
|
41
|
+
};
|
|
42
|
+
export const restoreLocalesAfterPublishAll = () => {
|
|
43
|
+
const hook = async (args) => {
|
|
44
|
+
const { doc, req } = args;
|
|
45
|
+
if (!isPublishAllLocales(req))
|
|
46
|
+
return doc;
|
|
47
|
+
const snapshots = req.context?.[PRESERVE_LOCALES_SNAPSHOTS_CONTEXT_KEY];
|
|
48
|
+
const editedPatch = req.context?.[PRESERVE_LOCALES_EDITED_PATCH_CONTEXT_KEY];
|
|
49
|
+
if (!snapshots && !editedPatch)
|
|
50
|
+
return doc;
|
|
51
|
+
const editedLocale = getAdminEditedLocale(req);
|
|
52
|
+
if (!editedLocale)
|
|
53
|
+
return doc;
|
|
54
|
+
if (snapshots) {
|
|
55
|
+
for (const [locale, snapshot] of Object.entries(snapshots)) {
|
|
56
|
+
if (locale === editedLocale)
|
|
57
|
+
continue;
|
|
58
|
+
if (!snapshot || typeof snapshot !== 'object')
|
|
59
|
+
continue;
|
|
60
|
+
await writeLocalePatch({
|
|
61
|
+
args,
|
|
62
|
+
req,
|
|
63
|
+
docId: doc.id,
|
|
64
|
+
locale,
|
|
65
|
+
data: snapshot,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (editedPatch && typeof editedPatch === 'object') {
|
|
70
|
+
await writeLocalePatch({
|
|
71
|
+
args,
|
|
72
|
+
req,
|
|
73
|
+
docId: doc.id,
|
|
74
|
+
locale: editedLocale,
|
|
75
|
+
data: editedPatch,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const nextContext = { ...req.context };
|
|
79
|
+
delete nextContext[PRESERVE_LOCALES_SNAPSHOTS_CONTEXT_KEY];
|
|
80
|
+
delete nextContext[PRESERVE_LOCALES_EDITED_PATCH_CONTEXT_KEY];
|
|
81
|
+
req.context = nextContext;
|
|
82
|
+
return doc;
|
|
83
|
+
};
|
|
84
|
+
return hook;
|
|
85
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type RevalidationSnapshot = Record<string, unknown>;
|
|
2
|
+
export type RevalidationProjectionContext = {
|
|
3
|
+
data: RevalidationSnapshot;
|
|
4
|
+
locale: string;
|
|
5
|
+
operation: 'create' | 'update' | 'delete';
|
|
6
|
+
resource: string;
|
|
7
|
+
};
|
|
8
|
+
export type RevalidationFilterContext = {
|
|
9
|
+
before: RevalidationSnapshot | null;
|
|
10
|
+
after: RevalidationSnapshot | null;
|
|
11
|
+
locale: string;
|
|
12
|
+
operation: 'create' | 'update' | 'delete';
|
|
13
|
+
resource: string;
|
|
14
|
+
};
|
|
15
|
+
export type PayloadCacheInvalidationOptions = {
|
|
16
|
+
enabled?: boolean;
|
|
17
|
+
hooks?: Array<'afterChange' | 'afterDelete'>;
|
|
18
|
+
/** Fields ignored only when deciding whether public content changed. */
|
|
19
|
+
excludeFields?: string[];
|
|
20
|
+
filter?: (change: RevalidationFilterContext) => boolean;
|
|
21
|
+
projection?: (context: RevalidationProjectionContext) => RevalidationSnapshot;
|
|
22
|
+
/** Field used to sort adjacent documents. Defaults to Payload's `_order`. */
|
|
23
|
+
orderField?: string;
|
|
24
|
+
};
|
|
25
|
+
/** Shape for collection/global `custom.cacheInvalidation`. */
|
|
26
|
+
export type PayloadCacheInvalidationCustom = false | true | PayloadCacheInvalidationOptions;
|
|
27
|
+
export declare const readCacheInvalidationCustom: (custom: unknown) => PayloadCacheInvalidationCustom | undefined;
|
|
28
|
+
export type NormalizedPayloadRevalidation = Required<Pick<PayloadCacheInvalidationOptions, 'hooks'>> & Omit<PayloadCacheInvalidationOptions, 'hooks' | 'enabled'> & {
|
|
29
|
+
enabled: boolean;
|
|
30
|
+
};
|
|
31
|
+
export declare const normalizeCollectionRevalidation: (value: true | PayloadCacheInvalidationOptions) => NormalizedPayloadRevalidation;
|
|
32
|
+
export declare const normalizeGlobalRevalidation: (value: true | PayloadCacheInvalidationOptions) => NormalizedPayloadRevalidation;
|
|
33
|
+
export type NormalizedResourceMap = Record<string, true | PayloadCacheInvalidationOptions>;
|
|
34
|
+
export declare const normalizeResourceMap: (central: Record<string, boolean | PayloadCacheInvalidationOptions> | undefined, localResources: readonly {
|
|
35
|
+
slug: string;
|
|
36
|
+
custom?: unknown;
|
|
37
|
+
}[]) => NormalizedResourceMap;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
const readEntry = (custom) => custom && typeof custom === 'object'
|
|
2
|
+
? custom.cacheInvalidation
|
|
3
|
+
: undefined;
|
|
4
|
+
export const readCacheInvalidationCustom = (custom) => {
|
|
5
|
+
const entry = readEntry(custom);
|
|
6
|
+
if (entry === false || entry === true)
|
|
7
|
+
return entry;
|
|
8
|
+
if (!entry || typeof entry !== 'object')
|
|
9
|
+
return undefined;
|
|
10
|
+
return entry;
|
|
11
|
+
};
|
|
12
|
+
export const normalizeCollectionRevalidation = (value) => {
|
|
13
|
+
if (value === true)
|
|
14
|
+
return { enabled: true, hooks: ['afterChange', 'afterDelete'] };
|
|
15
|
+
return {
|
|
16
|
+
...value,
|
|
17
|
+
enabled: value.enabled ?? true,
|
|
18
|
+
hooks: value.hooks ?? ['afterChange', 'afterDelete'],
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
export const normalizeGlobalRevalidation = (value) => {
|
|
22
|
+
const normalized = normalizeCollectionRevalidation(value);
|
|
23
|
+
return { ...normalized, hooks: normalized.hooks.filter((hook) => hook === 'afterChange') };
|
|
24
|
+
};
|
|
25
|
+
export const normalizeResourceMap = (central, localResources) => {
|
|
26
|
+
const result = Object.create(null);
|
|
27
|
+
for (const [slug, value] of Object.entries(central ?? {})) {
|
|
28
|
+
if (value === true)
|
|
29
|
+
result[slug] = true;
|
|
30
|
+
else if (value && typeof value === 'object')
|
|
31
|
+
result[slug] = { ...value };
|
|
32
|
+
}
|
|
33
|
+
for (const resource of localResources) {
|
|
34
|
+
const local = readCacheInvalidationCustom(resource.custom);
|
|
35
|
+
if (local === undefined)
|
|
36
|
+
continue;
|
|
37
|
+
if (local === false) {
|
|
38
|
+
delete result[resource.slug];
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const inherited = result[resource.slug];
|
|
42
|
+
if (local === true) {
|
|
43
|
+
result[resource.slug] =
|
|
44
|
+
inherited && inherited !== true ? { ...inherited, enabled: true } : (inherited ?? true);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
result[resource.slug] = {
|
|
48
|
+
...(inherited === true ? {} : (inherited ?? {})),
|
|
49
|
+
...local,
|
|
50
|
+
enabled: local.enabled ?? (inherited !== true ? inherited?.enabled : undefined) ?? true,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
return result;
|
|
54
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { resourceChangeV1DataSchemaUri } from '../../core/resource-changed-schema.js';
|
|
2
|
+
const eventTypeFor = (change) => `payload.${change.type}.${change.slug}`;
|
|
3
|
+
export const changesToRevalidationEvents = (changes, source) => changes.map((change) => {
|
|
4
|
+
const { before, after } = change;
|
|
5
|
+
if (before === undefined || after === undefined) {
|
|
6
|
+
throw new Error('Payload revalidation requires known public before and after snapshots');
|
|
7
|
+
}
|
|
8
|
+
return {
|
|
9
|
+
specversion: '1.0',
|
|
10
|
+
id: `rev_${crypto.randomUUID()}`,
|
|
11
|
+
source,
|
|
12
|
+
type: eventTypeFor(change),
|
|
13
|
+
time: new Date().toISOString(),
|
|
14
|
+
datacontenttype: 'application/json',
|
|
15
|
+
dataschema: resourceChangeV1DataSchemaUri,
|
|
16
|
+
data: {
|
|
17
|
+
operation: change.operation,
|
|
18
|
+
before,
|
|
19
|
+
after,
|
|
20
|
+
...(change.affected?.length ? { affected: change.affected } : {}),
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
The package separates event production, delivery, and cache consumption:
|
|
4
|
+
|
|
5
|
+
```text
|
|
6
|
+
Producer → Dispatcher → Consumer → Cache API
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
- **Producer:** detects a change and describes producer-owned event data. Payload CMS is built in.
|
|
10
|
+
- **Dispatcher:** delivers CloudEvents, optionally to named destinations. HTTP is built in.
|
|
11
|
+
- **Consumer:** authenticates, validates, matches local rules, and performs cache operations. Next.js is built in.
|
|
12
|
+
- **Core:** defines framework-independent CloudEvents, Standard Schema validation, and dispatcher contracts.
|
|
13
|
+
|
|
14
|
+
The producer does not know cache tags, routes, or cache profiles. The dispatcher does not interpret domain data. The consumer does not require the originating framework.
|
|
15
|
+
|
|
16
|
+
## Event flow
|
|
17
|
+
|
|
18
|
+
1. The producer creates an event with a stable `(source, id)` identity.
|
|
19
|
+
2. The dispatcher filters and batches events for each destination, then signs the exact HTTP body with Standard Webhooks.
|
|
20
|
+
3. The consumer enforces limits, verifies the signature, parses CloudEvents, and authorizes sources.
|
|
21
|
+
4. Local schemas validate relevant event data. Exact event type rules plan cache operations before execution.
|
|
22
|
+
5. The consumer calls native `revalidateTag()` and `revalidatePath()` APIs.
|
|
23
|
+
|
|
24
|
+
CloudEvents provide the shared envelope. Resource Change V1 is optional. Custom producers can define unrelated event data without a mandatory CMS model.
|
|
25
|
+
|
|
26
|
+
## Composable commerce
|
|
27
|
+
|
|
28
|
+
Applications can combine Payload, commerce APIs, and indexing services around their own projection layer. If the frontend reads indexed product data, that layer should emit the event after the public projection is ready. The package delivers events and performs invalidation; the application owns composition, index updates, completion, revisions, and ordering.
|
|
29
|
+
|
|
30
|
+
## Boundaries
|
|
31
|
+
|
|
32
|
+
The package does not provide a cache store, event broker, workflow engine, persistent queue, universal dependency graph, or framework adapter beyond Payload, HTTP, and Next.js. See [reliability](../reliability.md) for delivery and transaction limits.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Cache tags and paths
|
|
2
|
+
|
|
3
|
+
`defineCache()` creates typed helpers for cache instrumentation and event rules. Nested declaration keys organize those helpers; they never change rendered values.
|
|
4
|
+
|
|
5
|
+
## Recursive tags
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
tags: {
|
|
9
|
+
articles: {
|
|
10
|
+
list: 'articles:[locale]',
|
|
11
|
+
detail: 'article:[id]',
|
|
12
|
+
route: 'article-route:[locale]:[slug]',
|
|
13
|
+
},
|
|
14
|
+
categories: {
|
|
15
|
+
list: 'categories:[locale]',
|
|
16
|
+
},
|
|
17
|
+
commerce: {
|
|
18
|
+
products: {
|
|
19
|
+
list: 'products:[locale]',
|
|
20
|
+
detail: 'product:[id]',
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Use the generated helpers directly:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
cache.tags.articles.detail({ id: '42' })
|
|
30
|
+
cache.tags.commerce.products.detail({ id: '123' })
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
They render `article:42` and `product:123`. Group names do not add prefixes. Every placeholder is required by the helper's inferred TypeScript signature. Static tags need no parameters.
|
|
34
|
+
|
|
35
|
+
Prefer stable entity tags such as `article:[id]`. Translated views can share this tag for content and related metadata when the application attaches it to those cache entries. Use route-specific tags for locale and slug dependencies.
|
|
36
|
+
|
|
37
|
+
## Recursive paths
|
|
38
|
+
|
|
39
|
+
Declare a string for a concrete URL template. Declare a tuple for a literal Next.js route pattern and scope:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
paths: {
|
|
43
|
+
articles: {
|
|
44
|
+
home: '/',
|
|
45
|
+
detail: '/[locale]/articles/[slug]',
|
|
46
|
+
all: ['/[locale]/articles/[slug]', 'page'],
|
|
47
|
+
layout: ['/[locale]/articles', 'layout'],
|
|
48
|
+
},
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`cache.paths.articles.detail({ locale: 'pl', slug: 'hello' })` renders `/pl/articles/hello` and calls `revalidatePath()` without a scope. The tuple pattern stays literal and calls `revalidatePath(pattern, 'page' | 'layout')`. Path values are case-sensitive. Concrete paths do not receive an inferred scope. Paths do not accept tag profiles.
|
|
53
|
+
|
|
54
|
+
## Recursive event rules
|
|
55
|
+
|
|
56
|
+
Rules use exact CloudEvents type strings. Plain objects group rules; only leaf event keys match:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
rules: ({ tags, paths }) => ({
|
|
60
|
+
payload: {
|
|
61
|
+
content: {
|
|
62
|
+
'payload.collection.articles': [
|
|
63
|
+
tags.articles.detail,
|
|
64
|
+
paths.articles.detail,
|
|
65
|
+
],
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
})
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The `payload.content` keys do not become part of the match. Duplicate event types declared in different groups fail configuration. Use `rule({ tags, paths })` when an object descriptor must be distinct from a group.
|
|
72
|
+
|
|
73
|
+
## Native tag profiles
|
|
74
|
+
|
|
75
|
+
Set one global default at `config.tags.profile`. The library defaults to `{ expire: 0 }`. For a local override, group only tag helpers under `[profile, tagReferences]`:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
rules: ({ tags }) => ({
|
|
79
|
+
'payload.collection.articles': [
|
|
80
|
+
tags.articles.detail,
|
|
81
|
+
['max', [tags.articles.list, tags.categories.list]],
|
|
82
|
+
[{ expire: 0 }, [tags.articles.route]],
|
|
83
|
+
],
|
|
84
|
+
})
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Each grouped reference becomes one `revalidateTag(tag, profile)` call. Paths are invalidated separately. The native named profile passes through unchanged. If a tag resolves more than once with conflicting profiles, planning fails instead of choosing by rule order.
|
|
88
|
+
|
|
89
|
+
`cacheLife()` controls how long Next.js caches data. `revalidateTag()` controls on-demand invalidation. These settings are separate.
|
|
90
|
+
|
|
91
|
+
## Before, after, and affected resources
|
|
92
|
+
|
|
93
|
+
For Resource Change V1 events, declarations expand independently against `before`, `after`, and each matching affected resource. A slug change invalidates both old and new route values. Values from different snapshots are never combined. Missing required placeholders fail planning.
|
|
94
|
+
|
|
95
|
+
Use a programmable rule for arrays, category ancestry, previous/current relationships, or application-specific projections. Affected resources activate declarative rules only.
|
|
96
|
+
|
|
97
|
+
See the [Next.js consumer](../consumers/next.md) for schemas, programmable rules, and operation planning.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Event contract
|
|
2
|
+
|
|
3
|
+
The package root exposes framework-independent CloudEvents 1.0 and dispatcher contracts. Producers own event data. Consumers validate it with local Standard Schema V1 validators.
|
|
4
|
+
|
|
5
|
+
## CloudEvents
|
|
6
|
+
|
|
7
|
+
Use structured JSON for one event (`application/cloudevents+json`) or an ordered batch (`application/cloudevents-batch+json`). Required CloudEvents attributes are `specversion`, `id`, `source`, and `type`. `subject` and `data` are optional. A CloudEvent may contain JSON `data` or `data_base64`, not both.
|
|
8
|
+
|
|
9
|
+
Producer configuration requires an absolute `source` URI. The event identity is `(source, id)`. Generate the ID once for an event and preserve it when retrying delivery. The built-in Payload producer uses event types such as `payload.collection.articles` and puts the operation in event data.
|
|
10
|
+
|
|
11
|
+
CloudEvents `type` identifies the event contract and selects consumer rules. A consumer can restrict accepted source URIs with `allowedSources`; that check is authorization policy, not sender authentication. HTTP authentication uses Standard Webhooks signatures.
|
|
12
|
+
|
|
13
|
+
## Optional Resource Change V1
|
|
14
|
+
|
|
15
|
+
The root exports `ResourceChangeV1<T>`, `resourceChangeV1DataSchema`, and `resourceChangeV1DataSchemaUri`. This contract is optional for custom producers. Its `dataschema` is `urn:klnap:revalidation:resource-change:v1`.
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
type ResourceChangeV1<T> = {
|
|
19
|
+
operation: string
|
|
20
|
+
before: T | null
|
|
21
|
+
after: T | null
|
|
22
|
+
affected?: Array<{ type: string; data: Record<string, unknown> }>
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`before` and `after` are independent snapshots of the primary resource. `null` means that representation genuinely did not exist. Both snapshots cannot be `null`. An unavailable or unknown state is an acquisition failure; it must not be encoded as `null`.
|
|
27
|
+
|
|
28
|
+
Snapshots keep domain fields directly in their objects. For localized content, `locale` belongs in each snapshot. The core does not define a locale scope, resource registry, or CMS model.
|
|
29
|
+
|
|
30
|
+
`affected` lists dependent resources whose invalidation rules should run. Each item has its own event `type` and `data`, but no before/after snapshots. A resource that changed its own state can also have its own event in the same batch.
|
|
31
|
+
|
|
32
|
+
The Next.js consumer validates this contract locally when it sees the trusted `dataschema` URI. It does not fetch schemas from incoming event URIs. Affected resources activate matching declarative cache rules; they do not run programmable event rules or custom execution.
|
|
33
|
+
|
|
34
|
+
## Custom event contracts
|
|
35
|
+
|
|
36
|
+
Custom producers can use any CloudEvents event type and data shape. Consumers add a Standard Schema V1 validator in `defineCache({ schemas })` and write a rule for the exact event type. Unknown data stays `unknown` until validated.
|
|
37
|
+
|
|
38
|
+
See [custom producers](../producers/custom.md), [custom consumers](../consumers/custom.md), and the [architecture](./architecture.md).
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Custom consumers
|
|
2
|
+
|
|
3
|
+
A custom consumer authenticates deliveries, validates its local event contracts, resolves rules, plans operations, and invokes its cache platform's APIs. The package does not provide a generic consumer factory.
|
|
4
|
+
|
|
5
|
+
The package root exports `parseCloudEvents`, CloudEvents content types, `validateStandardSchema`, Resource Change V1 types/schema, and the framework-independent dispatcher and error contracts.
|
|
6
|
+
|
|
7
|
+
## Receive HTTP events
|
|
8
|
+
|
|
9
|
+
Verify Standard Webhooks against the exact received body before parsing. Enforce body and event limits. Then parse CloudEvents, authorize sources, validate schemas from a local registry, and plan all effects before executing any. Never fetch schemas using an incoming `dataschema` URI.
|
|
10
|
+
|
|
11
|
+
Treat `(source, id)` as event identity. Reject conflicting event content under one identity in a delivery. Make duplicate invalidation idempotent; the protocol does not provide durable replay storage.
|
|
12
|
+
|
|
13
|
+
## Handle Resource Change V1
|
|
14
|
+
|
|
15
|
+
Resource Change V1 is optional. Validate its data with the exported `resourceChangeV1DataSchema` when `dataschema` matches `resourceChangeV1DataSchemaUri`. `before` and `after` are full independent snapshots, and both cannot be `null`. Expand each separately. Affected records contain `{ type, data }` and should activate declarative invalidation only.
|
|
16
|
+
|
|
17
|
+
Custom event producers can use any CloudEvents `type` and data contract. Keep unknown data unknown until a local Standard Schema V1 validator has validated it.
|
|
18
|
+
|
|
19
|
+
See the [event contract](../concepts/event-contract.md), [custom producers](../producers/custom.md), and the [Next.js consumer](./next.md) for the built-in pipeline.
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
# Next.js consumer
|
|
2
|
+
|
|
3
|
+
The Next.js integration maps exact CloudEvents types to native cache operations. It requires Next.js `>=16.4.5 <17`.
|
|
4
|
+
|
|
5
|
+
## Define cache rules
|
|
6
|
+
|
|
7
|
+
Keep the definition in a server-only module:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// src/cache.ts
|
|
11
|
+
import 'server-only'
|
|
12
|
+
import { defineCache } from '@klnap/cache-invalidation/consumers/next'
|
|
13
|
+
|
|
14
|
+
export const cache = defineCache({
|
|
15
|
+
config: {
|
|
16
|
+
tags: {
|
|
17
|
+
profile: { expire: 0 },
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
tags: {
|
|
21
|
+
articles: {
|
|
22
|
+
list: 'articles:[locale]',
|
|
23
|
+
detail: 'article:[id]',
|
|
24
|
+
route: 'article-route:[locale]:[slug]',
|
|
25
|
+
},
|
|
26
|
+
categories: {
|
|
27
|
+
list: 'categories:[locale]',
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
paths: {
|
|
31
|
+
articles: {
|
|
32
|
+
detail: '/[locale]/articles/[slug]',
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
rules: ({ tags, paths }) => ({
|
|
36
|
+
payload: {
|
|
37
|
+
content: {
|
|
38
|
+
'payload.collection.articles': [
|
|
39
|
+
tags.articles.detail,
|
|
40
|
+
tags.articles.route,
|
|
41
|
+
tags.articles.list,
|
|
42
|
+
paths.articles.detail,
|
|
43
|
+
],
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
}),
|
|
47
|
+
})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The simple form needs no `config`, `paths`, schemas, or helper:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
const cache = defineCache({
|
|
54
|
+
tags: { article: 'article:[id]' },
|
|
55
|
+
rules: ({ tags }) => ({
|
|
56
|
+
'payload.collection.articles': [tags.article],
|
|
57
|
+
}),
|
|
58
|
+
})
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`defineCache()` returns nested `cache.tags.*` and `cache.paths.*` helpers. Group names organize the application API; they do not prefix rendered values.
|
|
62
|
+
|
|
63
|
+
## Add the Route Handler
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
// app/api/invalidate/route.ts
|
|
67
|
+
import { cacheInvalidationHandler } from '@klnap/cache-invalidation/consumers/next'
|
|
68
|
+
import { cache } from '@/cache'
|
|
69
|
+
|
|
70
|
+
export const POST = cacheInvalidationHandler({
|
|
71
|
+
config: cache,
|
|
72
|
+
secret: process.env.CACHE_INVALIDATION_SECRET!,
|
|
73
|
+
})
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The handler verifies Standard Webhooks authentication against the received body. A missing or empty secret fails during handler construction. Keep the secret on the server.
|
|
77
|
+
|
|
78
|
+
## Tag cached data
|
|
79
|
+
|
|
80
|
+
Use Next.js native `cacheTag()` where cached data is produced:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { cacheTag } from 'next/cache'
|
|
84
|
+
import { cache } from '@/cache'
|
|
85
|
+
|
|
86
|
+
export async function getArticle(id: string, locale: string) {
|
|
87
|
+
'use cache'
|
|
88
|
+
cacheTag(cache.tags.articles.detail({ id }))
|
|
89
|
+
return loadArticle(id, locale)
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Next.js 16 requires `cacheComponents: true` in `next.config.ts` to use `cacheTag()` and the `use cache` directive.
|
|
94
|
+
|
|
95
|
+
The library does not add tags to application caches. Every cache dependency that should respond to a tag must use it.
|
|
96
|
+
|
|
97
|
+
## Recursive tags
|
|
98
|
+
|
|
99
|
+
Tags can be nested as deeply as needed. Every leaf string creates a helper with inferred template parameters:
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
tags: {
|
|
103
|
+
pages: {
|
|
104
|
+
list: 'pages:[locale]',
|
|
105
|
+
detail: 'page:[id]',
|
|
106
|
+
},
|
|
107
|
+
commerce: {
|
|
108
|
+
products: {
|
|
109
|
+
list: 'products:[locale]',
|
|
110
|
+
detail: 'product:[id]',
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
cache.tags.pages.detail({ id: '42' })
|
|
118
|
+
cache.tags.commerce.products.detail({ id: '123' })
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The second helper renders `product:123`; the nesting does not change its value. Static declarations need no arguments. Dynamic helpers require every declared placeholder.
|
|
122
|
+
|
|
123
|
+
## Recursive paths
|
|
124
|
+
|
|
125
|
+
Use a string for a concrete URL template and a native tuple for a literal route pattern with scope:
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
paths: {
|
|
129
|
+
articles: {
|
|
130
|
+
detail: '/[locale]/articles/[slug]',
|
|
131
|
+
all: ['/[locale]/articles/[slug]', 'page'],
|
|
132
|
+
layout: ['/[locale]/articles', 'layout'],
|
|
133
|
+
},
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`cache.paths.articles.detail({ locale: 'pl', slug: 'hello' })` produces `/pl/articles/hello`. Tuple route patterns stay literal and call native `revalidatePath(pattern, 'page' | 'layout')`. Concrete paths do not receive an inferred scope. Paths do not accept profiles.
|
|
138
|
+
|
|
139
|
+
## Recursive rules
|
|
140
|
+
|
|
141
|
+
Plain objects group declarations. Exact event-type leaf keys match CloudEvents `type` values; group names do not participate in matching:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
rules: ({ tags }) => ({
|
|
145
|
+
// These groups use declarations under tags.commerce and tags.museum.
|
|
146
|
+
payload: {
|
|
147
|
+
commerce: {
|
|
148
|
+
'payload.collection.products': [tags.commerce.products.detail],
|
|
149
|
+
},
|
|
150
|
+
museum: {
|
|
151
|
+
'payload.collection.exhibitions': [tags.museum.exhibitions.detail],
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
custom: {
|
|
155
|
+
indexing: {
|
|
156
|
+
'catalog.product.indexed': [tags.commerce.products.detail],
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
})
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Flat and nested rules can coexist. Duplicate event types across groups are configuration errors. A plain object is always a group, not a rule descriptor.
|
|
163
|
+
|
|
164
|
+
Use the optional `rule()` helper to mark an advanced descriptor explicitly:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
rules: ({ tags, paths, rule }) => ({
|
|
168
|
+
payload: {
|
|
169
|
+
content: {
|
|
170
|
+
'payload.collection.articles': rule({
|
|
171
|
+
tags: [tags.articles.detail, tags.articles.route],
|
|
172
|
+
paths: [paths.articles.detail],
|
|
173
|
+
}),
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
})
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
The helper accepts `tags` and `paths`; it does not execute operations or change matching.
|
|
180
|
+
|
|
181
|
+
## Profiles
|
|
182
|
+
|
|
183
|
+
Profiles use the native second argument to Next.js `revalidateTag(tag, profile)`. Configure a global default in `config.tags.profile`; the library default is `{ expire: 0 }`:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
config: {
|
|
187
|
+
tags: {
|
|
188
|
+
profile: 'max',
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Use the only profile tuple form, `[profile, tagReferences]`, to override one or more tags:
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
defineCache({
|
|
197
|
+
tags: {
|
|
198
|
+
articles: {
|
|
199
|
+
detail: 'article:[id]',
|
|
200
|
+
list: 'articles:[locale]',
|
|
201
|
+
route: 'article-route:[locale]:[slug]',
|
|
202
|
+
},
|
|
203
|
+
categories: { list: 'categories:[locale]' },
|
|
204
|
+
},
|
|
205
|
+
rules: ({ tags }) => ({
|
|
206
|
+
'payload.collection.articles': [
|
|
207
|
+
tags.articles.detail,
|
|
208
|
+
['max', [tags.articles.list, tags.categories.list]],
|
|
209
|
+
[{ expire: 0 }, [tags.articles.route]],
|
|
210
|
+
],
|
|
211
|
+
}),
|
|
212
|
+
})
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Every profile group expands to individual tag operations. Groups accept tag helpers only, not paths. Per-operation profiles override `config.tags.profile`, then `{ expire: 0 }` applies. Conflicting profiles for the same rendered tag fail before execution. Named values pass through unchanged; the package does not rank or translate them.
|
|
216
|
+
|
|
217
|
+
`cacheLife()` configures cache lifetime. `revalidateTag()` requests on-demand invalidation. These are separate Next.js settings.
|
|
218
|
+
|
|
219
|
+
## Custom schemas and programmable rules
|
|
220
|
+
|
|
221
|
+
Register schemas locally by event type. Rule callback data is inferred from the schema output:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
import * as v from 'valibot'
|
|
225
|
+
|
|
226
|
+
const inventorySchema = v.object({ productId: v.string() })
|
|
227
|
+
|
|
228
|
+
const cache = defineCache({
|
|
229
|
+
schemas: {
|
|
230
|
+
'com.example.inventory.updated': inventorySchema,
|
|
231
|
+
},
|
|
232
|
+
tags: {
|
|
233
|
+
product: 'product:[id]',
|
|
234
|
+
},
|
|
235
|
+
rules: ({ tags }) => ({
|
|
236
|
+
'com.example.inventory.updated': ({ data }) => ({
|
|
237
|
+
tags: [tags.product({ id: data.productId })],
|
|
238
|
+
}),
|
|
239
|
+
}),
|
|
240
|
+
})
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Without a local schema, custom event data remains `unknown`. Resource Change V1 is an optional built-in trusted contract identified by its `dataschema` URI. The consumer never fetches remote schemas.
|
|
244
|
+
|
|
245
|
+
When several schemas are configured, use `on(type, resolver)` where a programmable rule needs the exact output for one event type:
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
rules: ({ tags, on }) => ({
|
|
249
|
+
'catalog.product.indexed': on('catalog.product.indexed', ({ data }) => ({
|
|
250
|
+
tags: [tags.product({ id: data.productId })],
|
|
251
|
+
})),
|
|
252
|
+
})
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
Use programmable rules for arrays, previous/current relationships, materialized paths, and application-specific projections. Declarative expansion does not infer Cartesian products from arbitrary data.
|
|
256
|
+
|
|
257
|
+
For Resource Change V1, the consumer resolves `before` and `after` independently. A changed slug invalidates both old and new route values. Matching `affected` records use their own type and data, but activate declarative rules only.
|
|
258
|
+
|
|
259
|
+
## Custom execution
|
|
260
|
+
|
|
261
|
+
A programmable rule can return application-owned operations for configured executor names. These run before that rule's dependent tag and path operations. Failure skips those dependent operations and returns a failed delivery response. Execution is bounded and receives a cooperative `AbortSignal`; it cannot forcibly stop arbitrary JavaScript or reverse external side effects. This is an operation hook, not a workflow engine.
|
|
262
|
+
|
|
263
|
+
Affected resources never invoke custom execution. See [reliability](../reliability.md) for execution outcomes and limits.
|
|
264
|
+
|
|
265
|
+
## Localization and stable IDs
|
|
266
|
+
|
|
267
|
+
Prefer a stable entity tag such as `article:[id]` across translations. Use locale and route data for route-specific tags or paths. Translations can share the entity tag, but application caches must actually attach it to content and dependent metadata.
|
|
268
|
+
|
|
269
|
+
## Native behavior and security
|
|
270
|
+
|
|
271
|
+
The handler calls `revalidateTag(tag, profile)` and `revalidatePath(path, type?)`. It does not use `updateTag()`, which is for Server Functions. Route Handler invalidation marks data or paths for revalidation on a later visit; it does not immediately regenerate every page or refresh every open browser. Next.js owns distributed cache coordination; external CDN invalidation is separate.
|
|
272
|
+
|
|
273
|
+
Configure `allowedSources` when the endpoint should accept only known source URIs. A shared signing secret authenticates every holder of that secret; a source allowlist does not identify which holder sent a request.
|
|
274
|
+
|
|
275
|
+
## Request limits and outcomes
|
|
276
|
+
|
|
277
|
+
The handler checks request size and event count, authenticates before parsing, validates and plans the full request before cache operations, deduplicates `(source, id)` identities, and rejects conflicting content under one identity. Valid unhandled types are reported as ignored. Invalid recognized contracts fail the request. HTTP responses do not expose internal error details.
|