@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.
Files changed (143) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/dist/consumers/next/compile-tag-template.d.ts +16 -0
  5. package/dist/consumers/next/compile-tag-template.js +83 -0
  6. package/dist/consumers/next/consumer-types.d.ts +98 -0
  7. package/dist/consumers/next/consumer-types.js +3 -0
  8. package/dist/consumers/next/define-cache.d.ts +4 -0
  9. package/dist/consumers/next/define-cache.js +281 -0
  10. package/dist/consumers/next/host-types.d.ts +44 -0
  11. package/dist/consumers/next/host-types.js +3 -0
  12. package/dist/consumers/next/index.d.ts +5 -0
  13. package/dist/consumers/next/index.js +2 -0
  14. package/dist/consumers/next/param-values.d.ts +8 -0
  15. package/dist/consumers/next/param-values.js +23 -0
  16. package/dist/consumers/next/profile.d.ts +2 -0
  17. package/dist/consumers/next/profile.js +18 -0
  18. package/dist/consumers/next/registry-builders.d.ts +3 -0
  19. package/dist/consumers/next/registry-builders.js +155 -0
  20. package/dist/consumers/next/revalidation-handler.d.ts +6 -0
  21. package/dist/consumers/next/revalidation-handler.js +2 -0
  22. package/dist/consumers/next/runtime.d.ts +5 -0
  23. package/dist/consumers/next/runtime.js +560 -0
  24. package/dist/core/cloudevents.d.ts +27 -0
  25. package/dist/core/cloudevents.js +172 -0
  26. package/dist/core/dispatch-outcome.d.ts +4 -0
  27. package/dist/core/dispatch-outcome.js +17 -0
  28. package/dist/core/errors.d.ts +16 -0
  29. package/dist/core/errors.js +28 -0
  30. package/dist/core/event-limits.d.ts +15 -0
  31. package/dist/core/event-limits.js +20 -0
  32. package/dist/core/event-selector.d.ts +9 -0
  33. package/dist/core/event-selector.js +5 -0
  34. package/dist/core/index.d.ts +10 -0
  35. package/dist/core/index.js +6 -0
  36. package/dist/core/resource-changed-schema.d.ts +35 -0
  37. package/dist/core/resource-changed-schema.js +12 -0
  38. package/dist/core/standard-schema.d.ts +2 -0
  39. package/dist/core/standard-schema.js +7 -0
  40. package/dist/core/types.d.ts +35 -0
  41. package/dist/core/types.js +1 -0
  42. package/dist/core/url-segment.d.ts +2 -0
  43. package/dist/core/url-segment.js +17 -0
  44. package/dist/dispatchers/http/index.d.ts +20 -0
  45. package/dist/dispatchers/http/index.js +274 -0
  46. package/dist/dispatchers/http/targets.d.ts +14 -0
  47. package/dist/dispatchers/http/targets.js +26 -0
  48. package/dist/dispatchers/index.d.ts +1 -0
  49. package/dist/dispatchers/index.js +1 -0
  50. package/dist/producers/payload/exclude-fields.d.ts +19 -0
  51. package/dist/producers/payload/exclude-fields.js +75 -0
  52. package/dist/producers/payload/index.d.ts +4 -0
  53. package/dist/producers/payload/index.js +3 -0
  54. package/dist/producers/payload/lifecycle/deferred.d.ts +55 -0
  55. package/dist/producers/payload/lifecycle/deferred.js +111 -0
  56. package/dist/producers/payload/lifecycle/dispatch.d.ts +18 -0
  57. package/dist/producers/payload/lifecycle/dispatch.js +21 -0
  58. package/dist/producers/payload/lifecycle/doc-content.d.ts +8 -0
  59. package/dist/producers/payload/lifecycle/doc-content.js +88 -0
  60. package/dist/producers/payload/lifecycle/draft-status.d.ts +6 -0
  61. package/dist/producers/payload/lifecycle/draft-status.js +15 -0
  62. package/dist/producers/payload/lifecycle/helpers.d.ts +13 -0
  63. package/dist/producers/payload/lifecycle/helpers.js +12 -0
  64. package/dist/producers/payload/lifecycle/identifier-field.d.ts +8 -0
  65. package/dist/producers/payload/lifecycle/identifier-field.js +48 -0
  66. package/dist/producers/payload/lifecycle/identifiers.d.ts +4 -0
  67. package/dist/producers/payload/lifecycle/identifiers.js +5 -0
  68. package/dist/producers/payload/lifecycle/locale-published.d.ts +7 -0
  69. package/dist/producers/payload/lifecycle/locale-published.js +19 -0
  70. package/dist/producers/payload/lifecycle/locale.d.ts +24 -0
  71. package/dist/producers/payload/lifecycle/locale.js +44 -0
  72. package/dist/producers/payload/lifecycle/log.d.ts +31 -0
  73. package/dist/producers/payload/lifecycle/log.js +67 -0
  74. package/dist/producers/payload/lifecycle/media-equality.d.ts +4 -0
  75. package/dist/producers/payload/lifecycle/media-equality.js +36 -0
  76. package/dist/producers/payload/lifecycle/operation.d.ts +2 -0
  77. package/dist/producers/payload/lifecycle/operation.js +7 -0
  78. package/dist/producers/payload/lifecycle/orderable-hooks.d.ts +21 -0
  79. package/dist/producers/payload/lifecycle/orderable-hooks.js +26 -0
  80. package/dist/producers/payload/lifecycle/orderable-neighbors.d.ts +21 -0
  81. package/dist/producers/payload/lifecycle/orderable-neighbors.js +151 -0
  82. package/dist/producers/payload/lifecycle/public-snapshots.d.ts +16 -0
  83. package/dist/producers/payload/lifecycle/public-snapshots.js +173 -0
  84. package/dist/producers/payload/lifecycle/revalidate.d.ts +16 -0
  85. package/dist/producers/payload/lifecycle/revalidate.js +162 -0
  86. package/dist/producers/payload/lifecycle/skip-rules.d.ts +19 -0
  87. package/dist/producers/payload/lifecycle/skip-rules.js +57 -0
  88. package/dist/producers/payload/lifecycle/types.d.ts +32 -0
  89. package/dist/producers/payload/lifecycle/types.js +1 -0
  90. package/dist/producers/payload/media/media-references.d.ts +31 -0
  91. package/dist/producers/payload/media/media-references.js +127 -0
  92. package/dist/producers/payload/media/resolve-media-affected-locales.d.ts +22 -0
  93. package/dist/producers/payload/media/resolve-media-affected-locales.js +70 -0
  94. package/dist/producers/payload/media/resolve-media-dependents.d.ts +39 -0
  95. package/dist/producers/payload/media/resolve-media-dependents.js +157 -0
  96. package/dist/producers/payload/media/resolve-media-slug.d.ts +7 -0
  97. package/dist/producers/payload/media/resolve-media-slug.js +17 -0
  98. package/dist/producers/payload/media/revalidate-media-dependents.d.ts +14 -0
  99. package/dist/producers/payload/media/revalidate-media-dependents.js +222 -0
  100. package/dist/producers/payload/plugin.d.ts +36 -0
  101. package/dist/producers/payload/plugin.js +235 -0
  102. package/dist/producers/payload/publish-all/context.d.ts +2 -0
  103. package/dist/producers/payload/publish-all/context.js +2 -0
  104. package/dist/producers/payload/publish-all/edited-locale.d.ts +5 -0
  105. package/dist/producers/payload/publish-all/edited-locale.js +5 -0
  106. package/dist/producers/payload/publish-all/index.d.ts +3 -0
  107. package/dist/producers/payload/publish-all/index.js +3 -0
  108. package/dist/producers/payload/publish-all/localization.d.ts +7 -0
  109. package/dist/producers/payload/publish-all/localization.js +1 -0
  110. package/dist/producers/payload/publish-all/mirror-publish-all-locales-to-req.d.ts +19 -0
  111. package/dist/producers/payload/publish-all/mirror-publish-all-locales-to-req.js +32 -0
  112. package/dist/producers/payload/publish-all/preserve-locales-on-publish-all.d.ts +2 -0
  113. package/dist/producers/payload/publish-all/preserve-locales-on-publish-all.js +145 -0
  114. package/dist/producers/payload/publish-all/read-localized-scalar.d.ts +2 -0
  115. package/dist/producers/payload/publish-all/read-localized-scalar.js +24 -0
  116. package/dist/producers/payload/publish-all/request-flags.d.ts +13 -0
  117. package/dist/producers/payload/publish-all/request-flags.js +9 -0
  118. package/dist/producers/payload/publish-all/restore-guard.d.ts +2 -0
  119. package/dist/producers/payload/publish-all/restore-guard.js +12 -0
  120. package/dist/producers/payload/publish-all/restore-locales-after-publish-all.d.ts +2 -0
  121. package/dist/producers/payload/publish-all/restore-locales-after-publish-all.js +85 -0
  122. package/dist/producers/payload/revalidation-custom.d.ts +37 -0
  123. package/dist/producers/payload/revalidation-custom.js +54 -0
  124. package/dist/producers/payload/schema.d.ts +3 -0
  125. package/dist/producers/payload/schema.js +23 -0
  126. package/docs/concepts/architecture.md +32 -0
  127. package/docs/concepts/cache-tags.md +97 -0
  128. package/docs/concepts/event-contract.md +38 -0
  129. package/docs/consumers/custom.md +19 -0
  130. package/docs/consumers/next.md +277 -0
  131. package/docs/dispatchers/custom.md +38 -0
  132. package/docs/dispatchers/http.md +66 -0
  133. package/docs/extending.md +26 -0
  134. package/docs/migration/0.3.0-to-0.4.0.md +67 -0
  135. package/docs/migration/0.4.0-to-0.5.0.md +60 -0
  136. package/docs/migration/0.5.x-to-0.0.0.md +143 -0
  137. package/docs/producers/custom.md +63 -0
  138. package/docs/producers/payload-media-dependencies.md +45 -0
  139. package/docs/producers/payload.md +140 -0
  140. package/docs/reliability.md +35 -0
  141. package/docs/security.md +34 -0
  142. package/docs/troubleshooting.md +14 -0
  143. package/package.json +120 -4
@@ -0,0 +1,281 @@
1
+ import { CacheConfigurationError } from '../../core/errors.js';
2
+ import { CACHE_DEFINITION, RULE_DESCRIPTOR, RULE_EVENT_TYPE, } from './consumer-types.js';
3
+ import { PATH_SYMBOL, TAG_SYMBOL, } from './host-types.js';
4
+ import { isCacheProfile } from './profile.js';
5
+ import { buildPathDefs, buildTagDefs } from './registry-builders.js';
6
+ const isPlainRecord = (value) => {
7
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
8
+ return false;
9
+ const prototype = Object.getPrototypeOf(value);
10
+ return prototype === Object.prototype || prototype === null;
11
+ };
12
+ const ownDataEntries = (value, label) => Object.keys(value).map((key) => {
13
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
14
+ if (!descriptor || !('value' in descriptor)) {
15
+ throw new CacheConfigurationError(`${label} must use own data properties`);
16
+ }
17
+ return [key, descriptor.value];
18
+ });
19
+ const copyToSafeRecord = (value, label) => {
20
+ const output = Object.create(null);
21
+ if (!value)
22
+ return output;
23
+ for (const [key, entry] of ownDataEntries(value, label)) {
24
+ Object.defineProperty(output, key, {
25
+ value: entry,
26
+ enumerable: true,
27
+ configurable: false,
28
+ writable: false,
29
+ });
30
+ }
31
+ return Object.freeze(output);
32
+ };
33
+ const collectReferences = (tree, symbol, label) => {
34
+ const found = Object.create(null);
35
+ const ancestors = new WeakSet();
36
+ const visit = (value) => {
37
+ if (typeof value === 'function') {
38
+ const identity = value[symbol];
39
+ if (typeof identity !== 'string') {
40
+ throw new CacheConfigurationError(`Invalid ${label} declaration`);
41
+ }
42
+ Object.defineProperty(found, identity, { value, enumerable: true });
43
+ return;
44
+ }
45
+ if (!isPlainRecord(value))
46
+ throw new CacheConfigurationError(`Invalid ${label} declaration`);
47
+ if (ancestors.has(value))
48
+ throw new CacheConfigurationError(`${label} declarations must not be cyclic`);
49
+ ancestors.add(value);
50
+ for (const [, child] of ownDataEntries(value, `${label} declarations`))
51
+ visit(child);
52
+ ancestors.delete(value);
53
+ };
54
+ visit(tree);
55
+ return found;
56
+ };
57
+ const isProfileGroup = (value) => Array.isArray(value) && value.length === 2 && Array.isArray(value[1]);
58
+ const validateReference = (value, expected, tags, paths, eventType) => {
59
+ if (typeof value === 'string') {
60
+ if (!value || value.length > (expected === 'tag' ? 256 : 1024)) {
61
+ throw new CacheConfigurationError(`Invalid ${expected} operation in rule for "${eventType}"`);
62
+ }
63
+ if (expected === 'path' && (!value.startsWith('/') || /[?#\\]/.test(value))) {
64
+ throw new CacheConfigurationError(`Invalid path operation in rule for "${eventType}"`);
65
+ }
66
+ return;
67
+ }
68
+ const symbol = expected === 'tag' ? TAG_SYMBOL : PATH_SYMBOL;
69
+ const registry = expected === 'tag' ? tags : paths;
70
+ if (typeof value !== 'function' || !(symbol in value)) {
71
+ throw new CacheConfigurationError(`Rule for "${eventType}" contains an invalid ${expected} reference`);
72
+ }
73
+ const identity = value[symbol];
74
+ if (typeof identity !== 'string' || registry[identity] !== value) {
75
+ throw new CacheConfigurationError(`Rule for "${eventType}" contains an invalid ${expected} reference`);
76
+ }
77
+ };
78
+ const validateProfileGroup = (value, tags, paths, eventType) => {
79
+ if (!isProfileGroup(value) || !isCacheProfile(value[0]) || value[1].length === 0) {
80
+ throw new CacheConfigurationError(`Invalid tag profile group in rule for "${eventType}"`);
81
+ }
82
+ for (const reference of value[1]) {
83
+ validateReference(reference, 'tag', tags, paths, eventType);
84
+ }
85
+ };
86
+ const validateAction = (action, tags, paths, eventType) => {
87
+ if (typeof action === 'function') {
88
+ const boundType = action[RULE_EVENT_TYPE];
89
+ if (RULE_EVENT_TYPE in action && boundType !== eventType) {
90
+ throw new CacheConfigurationError(`Rule for CloudEvent type "${eventType}" was bound to "${String(boundType)}"`);
91
+ }
92
+ return action;
93
+ }
94
+ const descriptor = isPlainRecord(action) &&
95
+ Object.hasOwn(action, RULE_DESCRIPTOR) &&
96
+ action[RULE_DESCRIPTOR] === true;
97
+ let tagEntries;
98
+ let pathEntries;
99
+ if (Array.isArray(action)) {
100
+ if (action.length === 0)
101
+ throw new CacheConfigurationError(`Rule for "${eventType}" is empty`);
102
+ const tagsOut = [];
103
+ const pathsOut = [];
104
+ for (const entry of action) {
105
+ if (isProfileGroup(entry)) {
106
+ validateProfileGroup(entry, tags, paths, eventType);
107
+ tagsOut.push(entry);
108
+ }
109
+ else if (typeof entry === 'function' && PATH_SYMBOL in entry) {
110
+ validateReference(entry, 'path', tags, paths, eventType);
111
+ pathsOut.push(entry);
112
+ }
113
+ else {
114
+ validateReference(entry, 'tag', tags, paths, eventType);
115
+ tagsOut.push(entry);
116
+ }
117
+ }
118
+ return { tags: tagsOut, paths: pathsOut };
119
+ }
120
+ if (!descriptor) {
121
+ throw new CacheConfigurationError(`Object rule for "${eventType}" must be created with rule({ tags, paths })`);
122
+ }
123
+ const entries = ownDataEntries(action, `Rule descriptor for "${eventType}"`).filter(([key]) => key !== String(RULE_DESCRIPTOR));
124
+ for (const [key] of entries) {
125
+ if (key !== 'tags' && key !== 'paths') {
126
+ throw new CacheConfigurationError(`Unsupported rule descriptor property "${key}" for "${eventType}"`);
127
+ }
128
+ }
129
+ const data = Object.fromEntries(entries);
130
+ if ((data.tags !== undefined && !Array.isArray(data.tags)) ||
131
+ (data.paths !== undefined && !Array.isArray(data.paths)) ||
132
+ (!data.tags?.length && !data.paths?.length)) {
133
+ throw new CacheConfigurationError(`Rule descriptor for "${eventType}" must contain operations`);
134
+ }
135
+ tagEntries = (data.tags ?? []);
136
+ pathEntries = (data.paths ?? []);
137
+ for (const entry of tagEntries) {
138
+ if (isProfileGroup(entry))
139
+ validateProfileGroup(entry, tags, paths, eventType);
140
+ else
141
+ validateReference(entry, 'tag', tags, paths, eventType);
142
+ }
143
+ for (const entry of pathEntries)
144
+ validateReference(entry, 'path', tags, paths, eventType);
145
+ return {
146
+ ...(data.tags === undefined ? {} : { tags: tagEntries }),
147
+ ...(data.paths === undefined ? {} : { paths: pathEntries }),
148
+ };
149
+ };
150
+ const normalizeRuleTree = (rules, tags, paths) => {
151
+ if (!isPlainRecord(rules))
152
+ throw new CacheConfigurationError('Rules must be a plain object');
153
+ const output = Object.create(null);
154
+ const locations = new Map();
155
+ const ancestors = new WeakSet();
156
+ const visit = (group, segments) => {
157
+ if (ancestors.has(group))
158
+ throw new CacheConfigurationError('Rule groups must not be cyclic');
159
+ ancestors.add(group);
160
+ const entries = ownDataEntries(group, 'Rule groups');
161
+ if (entries.length === 0) {
162
+ throw new CacheConfigurationError(`Rule group "${segments.join('.') || '<root>'}" must not be empty`);
163
+ }
164
+ for (const [key, value] of entries) {
165
+ const location = [...segments, key];
166
+ if (Array.isArray(value) ||
167
+ typeof value === 'function' ||
168
+ (isPlainRecord(value) && Object.hasOwn(value, RULE_DESCRIPTOR))) {
169
+ const previous = locations.get(key);
170
+ if (previous) {
171
+ throw new CacheConfigurationError(`Duplicate event type "${key}" declared at "${previous}" and "${location.join('.')}"`);
172
+ }
173
+ locations.set(key, location.join('.'));
174
+ Object.defineProperty(output, key, {
175
+ value: validateAction(value, tags, paths, key),
176
+ enumerable: true,
177
+ configurable: false,
178
+ writable: false,
179
+ });
180
+ }
181
+ else if (isPlainRecord(value)) {
182
+ visit(value, location);
183
+ }
184
+ else {
185
+ throw new CacheConfigurationError(`Invalid rule node at "${location.join('.')}"`);
186
+ }
187
+ }
188
+ ancestors.delete(group);
189
+ };
190
+ visit(rules, []);
191
+ return Object.freeze(output);
192
+ };
193
+ export const defineCache = (input) => {
194
+ if (!isPlainRecord(input))
195
+ throw new CacheConfigurationError('defineCache() requires a plain object');
196
+ for (const [key] of ownDataEntries(input, 'defineCache() config')) {
197
+ if (!['config', 'tags', 'paths', 'schemas', 'rules', 'execute'].includes(key)) {
198
+ throw new CacheConfigurationError(`Unsupported defineCache() property "${key}"`);
199
+ }
200
+ }
201
+ const tags = buildTagDefs(input.tags ?? {});
202
+ const paths = buildPathDefs(input.paths ?? {});
203
+ const tagReferences = collectReferences(tags, TAG_SYMBOL, 'tag');
204
+ const pathReferences = collectReferences(paths, PATH_SYMBOL, 'path');
205
+ const configuration = input.config;
206
+ if (configuration !== undefined && !isPlainRecord(configuration)) {
207
+ throw new CacheConfigurationError('Cache config must be a plain object');
208
+ }
209
+ const configEntries = ownDataEntries(configuration ?? {}, 'Cache config');
210
+ for (const [key] of configEntries) {
211
+ if (key !== 'tags') {
212
+ throw new CacheConfigurationError(`Unsupported cache config property "${key}"`);
213
+ }
214
+ }
215
+ const configValues = Object.fromEntries(configEntries);
216
+ let profile;
217
+ if (configValues.tags !== undefined) {
218
+ if (!isPlainRecord(configValues.tags)) {
219
+ throw new CacheConfigurationError('config.tags must be a plain object');
220
+ }
221
+ const tagConfig = ownDataEntries(configValues.tags, 'config.tags');
222
+ for (const [key] of tagConfig) {
223
+ if (key !== 'profile')
224
+ throw new CacheConfigurationError(`Unsupported config.tags property "${key}"`);
225
+ }
226
+ profile = configValues.tags.profile;
227
+ if (profile !== undefined && !isCacheProfile(profile)) {
228
+ throw new CacheConfigurationError('Invalid Next.js tag profile');
229
+ }
230
+ }
231
+ const schemas = copyToSafeRecord(input.schemas === undefined
232
+ ? undefined
233
+ : isPlainRecord(input.schemas)
234
+ ? input.schemas
235
+ : (() => {
236
+ throw new CacheConfigurationError('config.schemas must be a plain object');
237
+ })(), 'Event schemas');
238
+ for (const [type, schema] of Object.entries(schemas)) {
239
+ if (!type || !isPlainRecord(schema) || typeof schema['~standard'] !== 'object') {
240
+ throw new CacheConfigurationError(`Invalid event schema for "${type}"`);
241
+ }
242
+ const standard = schema['~standard'];
243
+ const validate = Object.getOwnPropertyDescriptor(standard, 'validate');
244
+ if (!validate || !('value' in validate) || typeof validate.value !== 'function') {
245
+ throw new CacheConfigurationError(`Invalid event schema for "${type}"`);
246
+ }
247
+ }
248
+ const rawRules = input.rules({
249
+ tags,
250
+ paths,
251
+ rule: (descriptor) => {
252
+ if (!isPlainRecord(descriptor)) {
253
+ throw new CacheConfigurationError('rule() requires a plain descriptor object');
254
+ }
255
+ const clone = Object.create(null);
256
+ for (const [key, value] of ownDataEntries(descriptor, 'rule() descriptor')) {
257
+ Object.defineProperty(clone, key, { value, enumerable: true });
258
+ }
259
+ Object.defineProperty(clone, RULE_DESCRIPTOR, { value: true });
260
+ return Object.freeze(clone);
261
+ },
262
+ on: (type, resolve) => {
263
+ const bound = (context) => resolve(context);
264
+ Object.defineProperty(bound, RULE_EVENT_TYPE, { value: type });
265
+ return bound;
266
+ },
267
+ });
268
+ const rules = normalizeRuleTree(rawRules, tagReferences, pathReferences);
269
+ return Object.freeze({
270
+ tags,
271
+ paths,
272
+ [CACHE_DEFINITION]: Object.freeze({
273
+ schemas: Object.freeze(schemas),
274
+ rules,
275
+ ...(profile === undefined ? {} : { profile }),
276
+ ...(input.execute === undefined ? {} : { execute: input.execute }),
277
+ tagReferences: Object.freeze(tagReferences),
278
+ pathReferences: Object.freeze(pathReferences),
279
+ }),
280
+ });
281
+ };
@@ -0,0 +1,44 @@
1
+ export declare const TAG_SYMBOL: unique symbol;
2
+ export declare const PATH_SYMBOL: unique symbol;
3
+ export declare const PATH_SCOPE_SYMBOL: unique symbol;
4
+ export type TagParamsBag = Record<string, string | undefined>;
5
+ export type TagTemplate = string;
6
+ export type PathTemplate = string | readonly [string, 'page' | 'layout'];
7
+ export type TagDeclaration = TagTemplate | TagDeclarations;
8
+ export interface TagDeclarations {
9
+ readonly [key: string]: TagDeclaration;
10
+ }
11
+ export type PathDeclaration = PathTemplate | PathDeclarations;
12
+ export interface PathDeclarations {
13
+ readonly [key: string]: PathDeclaration;
14
+ }
15
+ export type TagBuilder = (params: TagParamsBag) => string;
16
+ type TemplateParamNames<T extends string> = T extends `${string}[${infer Key}]${infer Rest}` ? Key | TemplateParamNames<Rest> : never;
17
+ type TemplateText<T> = T extends readonly [infer TPath extends string, 'page' | 'layout'] ? TPath : T extends string ? T : never;
18
+ type TemplateBuilder<T extends string> = string extends T ? TagBuilder : [TemplateParamNames<T>] extends [never] ? () => string : (params: {
19
+ [K in TemplateParamNames<T>]: string;
20
+ }) => string;
21
+ export type TagDef<TId extends string = string, TTemplate extends string = string> = TemplateBuilder<TTemplate> & {
22
+ readonly [TAG_SYMBOL]: TId;
23
+ };
24
+ export type PathDef<TId extends string = string, TTemplate = string> = (TTemplate extends readonly [
25
+ string,
26
+ 'page' | 'layout'
27
+ ] ? () => string : TemplateBuilder<TemplateText<TTemplate>>) & {
28
+ readonly [PATH_SYMBOL]: TId;
29
+ readonly [PATH_SCOPE_SYMBOL]?: TTemplate extends readonly [string, infer TScope] ? TScope : never;
30
+ };
31
+ export type TagReference<TId extends string = string> = {
32
+ readonly [TAG_SYMBOL]: TId;
33
+ };
34
+ export type PathReference<TId extends string = string> = {
35
+ readonly [PATH_SYMBOL]: TId;
36
+ };
37
+ type JoinId<TPrefix extends string, TKey extends string> = TPrefix extends '' ? TKey : `${TPrefix}.${TKey}`;
38
+ export type BuiltTags<T extends TagDeclarations = TagDeclarations, TPrefix extends string = ''> = {
39
+ [K in keyof T]-?: T[K] extends string ? TagDef<JoinId<TPrefix, K & string>, T[K]> : T[K] extends TagDeclarations ? BuiltTags<T[K], JoinId<TPrefix, K & string>> : never;
40
+ };
41
+ export type BuiltPaths<T extends PathDeclarations = PathDeclarations, TPrefix extends string = ''> = {
42
+ [K in keyof T]-?: T[K] extends PathTemplate ? PathDef<JoinId<TPrefix, K & string>, T[K]> : T[K] extends PathDeclarations ? BuiltPaths<T[K], JoinId<TPrefix, K & string>> : never;
43
+ };
44
+ export {};
@@ -0,0 +1,3 @@
1
+ export const TAG_SYMBOL = Symbol.for('@klnap/cache-invalidation/tag');
2
+ export const PATH_SYMBOL = Symbol.for('@klnap/cache-invalidation/path');
3
+ export const PATH_SCOPE_SYMBOL = Symbol.for('@klnap/cache-invalidation/pathScope');
@@ -0,0 +1,5 @@
1
+ export type { CacheDefinition, CacheInvalidationExecutionContext, CacheInvalidationExecutor, CacheInvalidationHandlerOptions, CacheInvalidationRuleContext, CacheInvalidationRuleResult, CacheProfile, DefineCacheInput, } from './define-cache.js';
2
+ export { defineCache } from './define-cache.js';
3
+ export type { PathTemplate, TagTemplate } from './host-types.js';
4
+ export type { CacheInvalidationHandlerInput } from './revalidation-handler.js';
5
+ export { cacheInvalidationHandler } from './revalidation-handler.js';
@@ -0,0 +1,2 @@
1
+ export { defineCache } from './define-cache.js';
2
+ export { cacheInvalidationHandler } from './revalidation-handler.js';
@@ -0,0 +1,8 @@
1
+ /** Longest value a slug-derived parameter may carry. */
2
+ export declare const MAX_PARAM_LENGTH = 256;
3
+ /** Why a tag value is unusable, or `undefined` when it is fine. */
4
+ export declare const tagValueProblem: (value: string) => string | undefined;
5
+ /** Path values become URL segments: no dot segments, separators or control characters. */
6
+ export declare const pathValueProblem: (value: string) => string | undefined;
7
+ export declare const assertTagValue: (key: string, value: string) => void;
8
+ export declare const assertPathValue: (key: string, value: string) => void;
@@ -0,0 +1,23 @@
1
+ import { CacheSchemaError } from '../../core/errors.js';
2
+ import { urlSegmentProblem } from '../../core/url-segment.js';
3
+ /** Longest value a slug-derived parameter may carry. */
4
+ export const MAX_PARAM_LENGTH = 256;
5
+ /** Why a tag value is unusable, or `undefined` when it is fine. */
6
+ export const tagValueProblem = (value) => value.length > MAX_PARAM_LENGTH ? `longer than ${MAX_PARAM_LENGTH} characters` : undefined;
7
+ /** Path values become URL segments: no dot segments, separators or control characters. */
8
+ export const pathValueProblem = (value) => {
9
+ const tooLong = tagValueProblem(value);
10
+ if (tooLong)
11
+ return tooLong;
12
+ return urlSegmentProblem(value);
13
+ };
14
+ export const assertTagValue = (key, value) => {
15
+ const problem = tagValueProblem(value);
16
+ if (problem)
17
+ throw new CacheSchemaError(`Parameter "${key}" is ${problem}`);
18
+ };
19
+ export const assertPathValue = (key, value) => {
20
+ const problem = pathValueProblem(value);
21
+ if (problem)
22
+ throw new CacheSchemaError(`Parameter "${key}" is ${problem}`);
23
+ };
@@ -0,0 +1,2 @@
1
+ import type { CacheProfile } from './consumer-types.js';
2
+ export declare const isCacheProfile: (value: unknown) => value is CacheProfile;
@@ -0,0 +1,18 @@
1
+ export const isCacheProfile = (value) => {
2
+ if (typeof value === 'string')
3
+ return value.length > 0;
4
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
5
+ return false;
6
+ const prototype = Object.getPrototypeOf(value);
7
+ if (prototype !== Object.prototype && prototype !== null)
8
+ return false;
9
+ const keys = Object.keys(value);
10
+ if (keys.length !== 1 || keys[0] !== 'expire')
11
+ return false;
12
+ const descriptor = Object.getOwnPropertyDescriptor(value, 'expire');
13
+ return Boolean(descriptor &&
14
+ 'value' in descriptor &&
15
+ typeof descriptor.value === 'number' &&
16
+ !Number.isNaN(descriptor.value) &&
17
+ descriptor.value >= 0);
18
+ };
@@ -0,0 +1,3 @@
1
+ import { type BuiltPaths, type BuiltTags, type PathDeclarations, type TagDeclarations } from './host-types.js';
2
+ export declare const buildTagDefs: <const T extends TagDeclarations>(tags: T) => BuiltTags<T>;
3
+ export declare const buildPathDefs: <const T extends PathDeclarations>(paths: T) => BuiltPaths<T>;
@@ -0,0 +1,155 @@
1
+ import { compileTagTemplate, fitTagLength, TAG_TEMPLATE_KEYS, } from './compile-tag-template.js';
2
+ import { PATH_SCOPE_SYMBOL, PATH_SYMBOL, TAG_SYMBOL, } from './host-types.js';
3
+ import { assertPathValue, assertTagValue } from './param-values.js';
4
+ const tagParamError = (tagId, keys, params) => {
5
+ const missing = keys.filter((k) => !params[k]);
6
+ return `Tag "${tagId}" missing param(s): ${missing.join(', ')}`;
7
+ };
8
+ const isPlainRecord = (value) => {
9
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
10
+ return false;
11
+ const prototype = Object.getPrototypeOf(value);
12
+ return prototype === Object.prototype || prototype === null;
13
+ };
14
+ const entriesOf = (value, label) => {
15
+ const entries = [];
16
+ for (const key of Object.keys(value)) {
17
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
18
+ if (!descriptor || !('value' in descriptor)) {
19
+ throw new TypeError(`${label} declarations must use own data properties`);
20
+ }
21
+ entries.push([key, descriptor.value]);
22
+ }
23
+ return entries;
24
+ };
25
+ const defineOwn = (target, key, value) => {
26
+ Object.defineProperty(target, key, {
27
+ value,
28
+ enumerable: true,
29
+ configurable: true,
30
+ writable: true,
31
+ });
32
+ };
33
+ const displayId = (segments) => segments.join('.');
34
+ const identityId = (segments) => JSON.stringify(segments);
35
+ const builderFromTemplate = (identity, template, fitTag = false, validatePath = false, label = identity) => {
36
+ const compiled = compileTagTemplate(template);
37
+ const render = fitTag
38
+ ? (params) => {
39
+ const value = compiled.render(params);
40
+ return value === null ? null : fitTagLength(value);
41
+ }
42
+ : compiled.render;
43
+ const meta = { ...compiled, render };
44
+ const fn = (params = {}) => {
45
+ if (validatePath) {
46
+ for (const key of compiled.keys) {
47
+ const value = params[key];
48
+ if (value !== undefined)
49
+ assertPathValue(key, value);
50
+ }
51
+ }
52
+ else {
53
+ for (const key of compiled.keys) {
54
+ const value = params[key];
55
+ if (value !== undefined)
56
+ assertTagValue(key, value);
57
+ }
58
+ }
59
+ const value = render(params);
60
+ if (value === null) {
61
+ throw new Error(tagParamError(label, compiled.keys, params));
62
+ }
63
+ return value;
64
+ };
65
+ Object.defineProperty(fn, TAG_SYMBOL, { value: identity, enumerable: false });
66
+ Object.defineProperty(fn, TAG_TEMPLATE_KEYS, {
67
+ value: meta,
68
+ enumerable: false,
69
+ });
70
+ return fn;
71
+ };
72
+ export const buildTagDefs = (tags) => {
73
+ const ancestors = new WeakSet();
74
+ const build = (group, segments) => {
75
+ if (!isPlainRecord(group))
76
+ throw new TypeError('Tag declaration groups must be plain objects');
77
+ if (ancestors.has(group))
78
+ throw new TypeError('Tag declaration groups must not be cyclic');
79
+ ancestors.add(group);
80
+ const out = {};
81
+ for (const [key, declaration] of entriesOf(group, 'Tag')) {
82
+ const path = [...segments, key];
83
+ const label = displayId(path);
84
+ const identity = identityId(path);
85
+ if (typeof declaration === 'string') {
86
+ defineOwn(out, key, builderFromTemplate(identity, declaration, true, false, label));
87
+ }
88
+ else if (isPlainRecord(declaration)) {
89
+ defineOwn(out, key, build(declaration, path));
90
+ }
91
+ else {
92
+ throw new TypeError(`Tag declaration "${label}" must be a template or plain object`);
93
+ }
94
+ }
95
+ ancestors.delete(group);
96
+ return out;
97
+ };
98
+ return build(tags, []);
99
+ };
100
+ export const buildPathDefs = (paths) => {
101
+ const ancestors = new WeakSet();
102
+ const buildPath = (label, identity, declaration) => {
103
+ const scoped = Array.isArray(declaration);
104
+ const template = scoped ? declaration[0] : declaration;
105
+ const scope = scoped ? declaration[1] : undefined;
106
+ if (typeof template !== 'string' ||
107
+ !template.startsWith('/') ||
108
+ template.length > 1024 ||
109
+ (scoped && scope !== 'page' && scope !== 'layout')) {
110
+ throw new Error(`Path template "${label}" must start with "/" and fit within 1024 characters`);
111
+ }
112
+ if (scoped && !/^\/(?:[^?#]*)$/.test(template)) {
113
+ throw new Error(`Scoped path pattern "${label}" is invalid`);
114
+ }
115
+ if (scoped) {
116
+ const fn = (() => template);
117
+ Object.defineProperty(fn, PATH_SYMBOL, { value: identity, enumerable: false });
118
+ Object.defineProperty(fn, PATH_SCOPE_SYMBOL, { value: scope, enumerable: false });
119
+ Object.defineProperty(fn, TAG_TEMPLATE_KEYS, {
120
+ // Scoped route patterns are literal, so route parameters are not tag template keys.
121
+ value: compileTagTemplate(''),
122
+ enumerable: false,
123
+ });
124
+ return fn;
125
+ }
126
+ const fn = builderFromTemplate(identity, template, false, true, label);
127
+ Object.defineProperty(fn, PATH_SYMBOL, { value: identity, enumerable: false });
128
+ return fn;
129
+ };
130
+ const build = (group, segments) => {
131
+ if (!isPlainRecord(group))
132
+ throw new TypeError('Path declaration groups must be plain objects');
133
+ if (ancestors.has(group))
134
+ throw new TypeError('Path declaration groups must not be cyclic');
135
+ ancestors.add(group);
136
+ const out = {};
137
+ for (const [key, declaration] of entriesOf(group, 'Path')) {
138
+ const path = [...segments, key];
139
+ const label = displayId(path);
140
+ const identity = identityId(path);
141
+ if (typeof declaration === 'string' || Array.isArray(declaration)) {
142
+ defineOwn(out, key, buildPath(label, identity, declaration));
143
+ }
144
+ else if (isPlainRecord(declaration)) {
145
+ defineOwn(out, key, build(declaration, path));
146
+ }
147
+ else {
148
+ throw new TypeError(`Path declaration "${label}" must be a template, route tuple, or plain object`);
149
+ }
150
+ }
151
+ ancestors.delete(group);
152
+ return out;
153
+ };
154
+ return build(paths, []);
155
+ };
@@ -0,0 +1,6 @@
1
+ import type { CacheDefinition, CacheInvalidationHandlerOptions, ExecutorMap, SchemaMap } from './consumer-types.js';
2
+ export type CacheInvalidationHandlerInput<TTags extends import('./host-types.js').TagDeclarations = Record<never, never>, TPaths extends import('./host-types.js').PathDeclarations = Record<never, never>, TSchemas extends SchemaMap = SchemaMap, TExecutors extends ExecutorMap = ExecutorMap> = {
3
+ config: CacheDefinition<TTags, TPaths, TSchemas, TExecutors>;
4
+ secret: string;
5
+ } & CacheInvalidationHandlerOptions;
6
+ export declare const cacheInvalidationHandler: <TTags extends import('./host-types.js').TagDeclarations, TPaths extends import('./host-types.js').PathDeclarations, TSchemas extends SchemaMap, TExecutors extends ExecutorMap>(input: CacheInvalidationHandlerInput<TTags, TPaths, TSchemas, TExecutors>) => (request: Request) => Promise<Response>;
@@ -0,0 +1,2 @@
1
+ import { createCacheInvalidationPostHandler } from './runtime.js';
2
+ export const cacheInvalidationHandler = (input) => createCacheInvalidationPostHandler(input);
@@ -0,0 +1,5 @@
1
+ import { type CacheDefinition, type CacheInvalidationHandlerOptions, type ExecutorMap, type SchemaMap } from './consumer-types.js';
2
+ export declare const createCacheInvalidationPostHandler: <TTags extends import('./host-types.js').TagDeclarations, TPaths extends import('./host-types.js').PathDeclarations, TSchemas extends SchemaMap, TExecutors extends ExecutorMap>(input: {
3
+ config: CacheDefinition<TTags, TPaths, TSchemas, TExecutors>;
4
+ secret: string;
5
+ } & CacheInvalidationHandlerOptions) => ((request: Request) => Promise<Response>);