@rexezuge/runtime 1.6.0 → 1.7.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 (58) hide show
  1. package/README.md +21 -1
  2. package/dist/base/AbstractDurableObjectWorker.d.ts +6 -0
  3. package/dist/base/AbstractDurableObjectWorker.d.ts.map +1 -1
  4. package/dist/base/AbstractDurableObjectWorker.js +1 -1
  5. package/dist/base/AbstractDurableObjectWorker.js.map +3 -3
  6. package/dist/base/AbstractEntrypointWorker.d.ts +10 -0
  7. package/dist/base/AbstractEntrypointWorker.d.ts.map +1 -1
  8. package/dist/base/AbstractEntrypointWorker.js +1 -1
  9. package/dist/base/AbstractEntrypointWorker.js.map +3 -3
  10. package/dist/base/AbstractQueueWorker.d.ts +21 -10
  11. package/dist/base/AbstractQueueWorker.d.ts.map +1 -1
  12. package/dist/base/AbstractQueueWorker.js +1 -1
  13. package/dist/base/AbstractQueueWorker.js.map +3 -3
  14. package/dist/base/AbstractWorkflowWorker.d.ts +23 -16
  15. package/dist/base/AbstractWorkflowWorker.d.ts.map +1 -1
  16. package/dist/base/AbstractWorkflowWorker.js +1 -1
  17. package/dist/base/AbstractWorkflowWorker.js.map +3 -3
  18. package/dist/base/baseWorkerError.d.ts +34 -0
  19. package/dist/base/baseWorkerError.d.ts.map +1 -0
  20. package/dist/base/baseWorkerError.js +1 -0
  21. package/dist/base/baseWorkerError.js.map +7 -0
  22. package/dist/base/index.d.ts +2 -2
  23. package/dist/base/index.d.ts.map +1 -1
  24. package/dist/base/index.js +1 -1
  25. package/dist/base/index.js.map +3 -3
  26. package/dist/config/EnvParser.d.ts +15 -0
  27. package/dist/config/EnvParser.d.ts.map +1 -1
  28. package/dist/config/EnvParser.js +1 -1
  29. package/dist/config/EnvParser.js.map +2 -2
  30. package/dist/di/RequestScope.d.ts +25 -1
  31. package/dist/di/RequestScope.d.ts.map +1 -1
  32. package/dist/di/RequestScope.js +1 -1
  33. package/dist/di/RequestScope.js.map +3 -3
  34. package/dist/index.d.ts +6 -6
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/index.js.map +3 -3
  38. package/dist/kv/KvCache.d.ts +86 -12
  39. package/dist/kv/KvCache.d.ts.map +1 -1
  40. package/dist/kv/KvCache.js +1 -1
  41. package/dist/kv/KvCache.js.map +3 -3
  42. package/dist/kv/KvDomains.d.ts +49 -5
  43. package/dist/kv/KvDomains.d.ts.map +1 -1
  44. package/dist/kv/KvDomains.js +1 -1
  45. package/dist/kv/KvDomains.js.map +3 -3
  46. package/dist/kv/SubrequestMeterLike.d.ts +26 -0
  47. package/dist/kv/SubrequestMeterLike.d.ts.map +1 -0
  48. package/dist/kv/SubrequestMeterLike.js +1 -0
  49. package/dist/kv/SubrequestMeterLike.js.map +7 -0
  50. package/dist/kv/index.d.ts +5 -3
  51. package/dist/kv/index.d.ts.map +1 -1
  52. package/dist/kv/index.js +1 -1
  53. package/dist/kv/index.js.map +3 -3
  54. package/dist/logger.d.ts +34 -5
  55. package/dist/logger.d.ts.map +1 -1
  56. package/dist/logger.js +1 -1
  57. package/dist/logger.js.map +3 -3
  58. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,YAAY,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACzF,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OA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1 @@
1
- import{Container as o}from"./di/Container.js";import{asScopedContext as p,getRequestScope as s,setRequestScope as a}from"./di/RequestScope.js";import{AppConfiguration as c}from"./config/AppConfiguration.js";import{EnvParser as x}from"./config/EnvParser.js";import{DEFAULT_SITE_URL as b}from"./config/ConfigurationDefaults.js";import{AbstractEntrypointWorker as i}from"./base/AbstractEntrypointWorker.js";import{AbstractDurableObjectWorker as u}from"./base/AbstractDurableObjectWorker.js";import{AbstractQueueWorker as k}from"./base/AbstractQueueWorker.js";import{AbstractWorkflowWorker as v}from"./base/AbstractWorkflowWorker.js";import{createLogger as d,isLogLevel as T,resolveLogLevel as W}from"./logger.js";import{KvCache as E,KV_DOMAINS as K,buildKvKey as R,clampTtl as y,digest128 as D}from"./kv/index.js";import{AbstractScheduledTask as h,TaskRegistry as q}from"./scheduled/index.js";export{u as AbstractDurableObjectWorker,i as AbstractEntrypointWorker,k as AbstractQueueWorker,h as AbstractScheduledTask,v as AbstractWorkflowWorker,c as AppConfiguration,o as Container,b as DEFAULT_SITE_URL,x as EnvParser,K as KV_DOMAINS,E as KvCache,q as TaskRegistry,p as asScopedContext,R as buildKvKey,y as clampTtl,d as createLogger,D as digest128,s as getRequestScope,T as isLogLevel,W as resolveLogLevel,a as setRequestScope};
1
+ import{Container as t}from"./di/Container.js";import{asScopedContext as s,getRequestScope as E,tryGetRequestScope as S,setRequestScope as p,SCOPE_MISSING_MESSAGE as _}from"./di/RequestScope.js";import{AppConfiguration as a}from"./config/AppConfiguration.js";import{EnvParser as m}from"./config/EnvParser.js";import{DEFAULT_SITE_URL as c}from"./config/ConfigurationDefaults.js";import{AbstractEntrypointWorker as T}from"./base/AbstractEntrypointWorker.js";import{AbstractDurableObjectWorker as g}from"./base/AbstractDurableObjectWorker.js";import{AbstractQueueWorker as n}from"./base/AbstractQueueWorker.js";import{AbstractWorkflowWorker as u}from"./base/AbstractWorkflowWorker.js";import{BASE_WORKER_MESSAGES as K}from"./base/baseWorkerError.js";import{createLogger as O,isLogLevel as b,resetLogLevelForTests as k,resolveLogLevel as v,setLogLevel as G}from"./logger.js";import{COOLDOWN_MS as C,FAILURE_THRESHOLD as D,KV_DOMAINS as W,KV_KEY_VERSION as U,KV_MAX_KEY_LENGTH as d,KV_MIN_TTL_SECONDS as y,KvCache as P,PURGE_LIST_LIMIT as V,PURGE_MAX_PAGES as F,UNMETERED as h,buildKvKey as q,clampTtl as B,digest128 as H,resetBreakerForTests as X,sanitizeSegment as Y,utf8ByteLength as j}from"./kv/index.js";import{AbstractScheduledTask as z,TaskRegistry as Q}from"./scheduled/index.js";export{g as AbstractDurableObjectWorker,T as AbstractEntrypointWorker,n as AbstractQueueWorker,z as AbstractScheduledTask,u as AbstractWorkflowWorker,a as AppConfiguration,K as BASE_WORKER_MESSAGES,C as COOLDOWN_MS,t as Container,c as DEFAULT_SITE_URL,m as EnvParser,D as FAILURE_THRESHOLD,W as KV_DOMAINS,U as KV_KEY_VERSION,d as KV_MAX_KEY_LENGTH,y as KV_MIN_TTL_SECONDS,P as KvCache,V as PURGE_LIST_LIMIT,F as PURGE_MAX_PAGES,_ as SCOPE_MISSING_MESSAGE,Q as TaskRegistry,h as UNMETERED,s as asScopedContext,q as buildKvKey,B as clampTtl,O as createLogger,H as digest128,E as getRequestScope,b as isLogLevel,X as resetBreakerForTests,k as resetLogLevelForTests,v as resolveLogLevel,Y as sanitizeSegment,G as setLogLevel,p as setRequestScope,S as tryGetRequestScope,j as utf8ByteLength};
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["/**\n * `@rexezuge/runtime` — the platform foundation layer: DI, configuration,\n * worker bases, logger, KV cache. Zero dependencies (the one platform import\n * is type-only, resolved through each consumer's generated wrangler types).\n */\n\nexport { Container } from './di/Container.ts';\nexport type { Factory, Token } from './di/Container.ts';\nexport { asScopedContext, getRequestScope, setRequestScope } from './di/RequestScope.ts';\nexport type { ScopedContext } from './di/RequestScope.ts';\nexport { AppConfiguration } from './config/AppConfiguration.ts';\nexport { EnvParser } from './config/EnvParser.ts';\nexport { DEFAULT_SITE_URL } from './config/ConfigurationDefaults.ts';\nexport { AbstractEntrypointWorker } from './base/AbstractEntrypointWorker.ts';\nexport type { WorkerExecutionContext, WorkerScheduledController } from './base/AbstractEntrypointWorker.ts';\nexport { AbstractDurableObjectWorker } from './base/AbstractDurableObjectWorker.ts';\nexport { AbstractQueueWorker } from './base/AbstractQueueWorker.ts';\nexport type { WorkerMessageBatch } from './base/AbstractQueueWorker.ts';\nexport { AbstractWorkflowWorker } from './base/AbstractWorkflowWorker.ts';\nexport type { WorkflowEventLike, WorkflowStepLike } from './base/AbstractWorkflowWorker.ts';\nexport { createLogger, isLogLevel, resolveLogLevel } from './logger.ts';\nexport type { LogLevel, Logger } from './logger.ts';\nexport { KvCache, KV_DOMAINS, buildKvKey, clampTtl, digest128 } from './kv/index.ts';\nexport type { KvDomainDef, KvDomainName, KvNamespaceLike } from './kv/index.ts';\nexport { AbstractScheduledTask, TaskRegistry } from './scheduled/index.ts';\nexport type { ApplicationRunHandle, ScheduledTaskEnv, TaskLogger, TaskRunRecorder, TaskRunSummary } from './scheduled/index.ts';\n"],
5
- "mappings": "AAMA,OAAS,aAAAA,MAAiB,oBAE1B,OAAS,mBAAAC,EAAiB,mBAAAC,EAAiB,mBAAAC,MAAuB,uBAElE,OAAS,oBAAAC,MAAwB,+BACjC,OAAS,aAAAC,MAAiB,wBAC1B,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,4BAAAC,MAAgC,qCAEzC,OAAS,+BAAAC,MAAmC,wCAC5C,OAAS,uBAAAC,MAA2B,gCAEpC,OAAS,0BAAAC,MAA8B,mCAEvC,OAAS,gBAAAC,EAAc,cAAAC,EAAY,mBAAAC,MAAuB,cAE1D,OAAS,WAAAC,EAAS,cAAAC,EAAY,cAAAC,EAAY,YAAAC,EAAU,aAAAC,MAAiB,gBAErE,OAAS,yBAAAC,EAAuB,gBAAAC,MAAoB",
6
- "names": ["Container", "asScopedContext", "getRequestScope", "setRequestScope", "AppConfiguration", "EnvParser", "DEFAULT_SITE_URL", "AbstractEntrypointWorker", "AbstractDurableObjectWorker", "AbstractQueueWorker", "AbstractWorkflowWorker", "createLogger", "isLogLevel", "resolveLogLevel", "KvCache", "KV_DOMAINS", "buildKvKey", "clampTtl", "digest128", "AbstractScheduledTask", "TaskRegistry"]
4
+ "sourcesContent": ["/**\n * `@rexezuge/runtime` — the platform foundation layer: DI, configuration,\n * worker bases, logger, KV cache. Zero dependencies (the one platform import\n * is type-only, resolved through each consumer's generated wrangler types).\n */\n\nexport { Container } from './di/Container.ts';\nexport type { Factory, Token } from './di/Container.ts';\nexport { asScopedContext, getRequestScope, tryGetRequestScope, setRequestScope, SCOPE_MISSING_MESSAGE } from './di/RequestScope.ts';\nexport type { ScopedContext } from './di/RequestScope.ts';\nexport { AppConfiguration } from './config/AppConfiguration.ts';\nexport { EnvParser } from './config/EnvParser.ts';\nexport { DEFAULT_SITE_URL } from './config/ConfigurationDefaults.ts';\nexport { AbstractEntrypointWorker } from './base/AbstractEntrypointWorker.ts';\nexport type { WorkerExecutionContext, WorkerScheduledController } from './base/AbstractEntrypointWorker.ts';\nexport { AbstractDurableObjectWorker } from './base/AbstractDurableObjectWorker.ts';\nexport { AbstractQueueWorker } from './base/AbstractQueueWorker.ts';\nexport { AbstractWorkflowWorker } from './base/AbstractWorkflowWorker.ts';\nexport { BASE_WORKER_MESSAGES } from './base/baseWorkerError.ts';\nexport type { BaseWorkerOperation } from './base/baseWorkerError.ts';\nexport { createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel } from './logger.ts';\nexport type { LogLevel, Logger } from './logger.ts';\nexport {\n COOLDOWN_MS,\n FAILURE_THRESHOLD,\n KV_DOMAINS,\n KV_KEY_VERSION,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n KvCache,\n PURGE_LIST_LIMIT,\n PURGE_MAX_PAGES,\n UNMETERED,\n buildKvKey,\n clampTtl,\n digest128,\n resetBreakerForTests,\n sanitizeSegment,\n utf8ByteLength,\n} from './kv/index.ts';\nexport type { KvDomainDef, KvDomainName, KvDomains, KvNamespaceLike, KvPutOptions, SubrequestMeterLike } from './kv/index.ts';\nexport { AbstractScheduledTask, TaskRegistry } from './scheduled/index.ts';\nexport type { ApplicationRunHandle, ScheduledTaskEnv, TaskLogger, TaskRunRecorder, TaskRunSummary } from './scheduled/index.ts';\n"],
5
+ "mappings": "AAMA,OAAS,aAAAA,MAAiB,oBAE1B,OAAS,mBAAAC,EAAiB,mBAAAC,EAAiB,sBAAAC,EAAoB,mBAAAC,EAAiB,yBAAAC,MAA6B,uBAE7G,OAAS,oBAAAC,MAAwB,+BACjC,OAAS,aAAAC,MAAiB,wBAC1B,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,4BAAAC,MAAgC,qCAEzC,OAAS,+BAAAC,MAAmC,wCAC5C,OAAS,uBAAAC,MAA2B,gCACpC,OAAS,0BAAAC,MAA8B,mCACvC,OAAS,wBAAAC,MAA4B,4BAErC,OAAS,gBAAAC,EAAc,cAAAC,EAAY,yBAAAC,EAAuB,mBAAAC,EAAiB,eAAAC,MAAmB,cAE9F,OACE,eAAAC,EACA,qBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,qBAAAC,EACA,sBAAAC,EACA,WAAAC,EACA,oBAAAC,EACA,mBAAAC,EACA,aAAAC,EACA,cAAAC,EACA,YAAAC,EACA,aAAAC,EACA,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,MACK,gBAEP,OAAS,yBAAAC,EAAuB,gBAAAC,MAAoB",
6
+ "names": ["Container", "asScopedContext", "getRequestScope", "tryGetRequestScope", "setRequestScope", "SCOPE_MISSING_MESSAGE", "AppConfiguration", "EnvParser", "DEFAULT_SITE_URL", "AbstractEntrypointWorker", "AbstractDurableObjectWorker", "AbstractQueueWorker", "AbstractWorkflowWorker", "BASE_WORKER_MESSAGES", "createLogger", "isLogLevel", "resetLogLevelForTests", "resolveLogLevel", "setLogLevel", "COOLDOWN_MS", "FAILURE_THRESHOLD", "KV_DOMAINS", "KV_KEY_VERSION", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "KvCache", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "UNMETERED", "buildKvKey", "clampTtl", "digest128", "resetBreakerForTests", "sanitizeSegment", "utf8ByteLength", "AbstractScheduledTask", "TaskRegistry"]
7
7
  }
@@ -1,4 +1,13 @@
1
- import type { KvDomainName } from './KvDomains.ts';
1
+ import type { SubrequestMeterLike } from './SubrequestMeterLike.ts';
2
+ import type { KvDomainName, KvDomains } from './KvDomains.ts';
3
+ /**
4
+ Consecutive failures before the breaker opens.
5
+ */
6
+ declare const FAILURE_THRESHOLD = 3;
7
+ /**
8
+ How long the breaker stays open before a half-open probe.
9
+ */
10
+ declare const COOLDOWN_MS = 5000;
2
11
  interface KvListPage {
3
12
  keys: Array<{
4
13
  name: string;
@@ -39,36 +48,101 @@ interface KvBinaryEntry {
39
48
  }
40
49
  declare const PURGE_LIST_LIMIT = 1000;
41
50
  declare const PURGE_MAX_PAGES = 10;
42
- declare class KvCache {
51
+ /**
52
+ Test seam: force the breaker closed and forget the failure count.
53
+ */
54
+ declare function resetBreakerForTests(): void;
55
+ declare class KvCache<D extends string = KvDomainName> {
43
56
  private readonly namespace?;
44
- constructor(namespace?: (KvNamespaceLike | null) | undefined);
57
+ private readonly meter;
58
+ private readonly domains;
59
+ /**
60
+ * @param namespace The binding, or `null` for a deployment without one.
61
+ * @param meter The invocation's subrequest counter, or an unmetered default.
62
+ * @param domains The keyspace's own domain table. Defaults to the kit's; supply
63
+ * one whose names and lifetimes are yours, because the TTL and size policy is
64
+ * per-repo by definition.
65
+ */
66
+ constructor(namespace?: (KvNamespaceLike | null) | undefined, meter?: SubrequestMeterLike, domains?: KvDomains<D>);
67
+ /**
68
+ * The keyspace's policy table, for a caller building a key beside a read.
69
+ */
70
+ get keyspaces(): KvDomains<D>;
71
+ /**
72
+ * Whether the binding is present.
73
+ *
74
+ * Distinct from "healthy": a present binding can still be failing, and that is
75
+ * the case the breaker exists for. Callers must not branch on this to decide
76
+ * whether they may read the source of truth — they read it regardless.
77
+ */
45
78
  get available(): boolean;
46
- getText(domain: KvDomainName, parts: readonly string[]): Promise<string | null>;
47
- putText(domain: KvDomainName, parts: readonly string[], value: string, options?: KvPutOptions): Promise<boolean>;
48
- getJson<T>(domain: KvDomainName, parts: readonly string[]): Promise<T | null>;
49
- putJson(domain: KvDomainName, parts: readonly string[], value: unknown, options?: KvPutOptions): Promise<boolean>;
79
+ /**
80
+ * Run a KV operation under the breaker.
81
+ *
82
+ * Never throws and never returns a rejection: every failure path is a `null`
83
+ * or `false`, which callers read as "miss" or "not stored".
84
+ *
85
+ * `charge: false` is for the one caller that issues a *loop* of operations
86
+ * inside one `guard` ({@link purgePrefix}), where charging once here would
87
+ * report a 10,000-key purge as a single subrequest. It charges per call instead.
88
+ */
89
+ private guard;
90
+ getText(domain: D, parts: readonly string[]): Promise<string | null>;
91
+ putText(domain: D, parts: readonly string[], value: string, options?: KvPutOptions): Promise<boolean>;
92
+ getJson<T>(domain: D, parts: readonly string[]): Promise<T | null>;
93
+ putJson(domain: D, parts: readonly string[], value: unknown, options?: KvPutOptions): Promise<boolean>;
50
94
  /**
51
95
  * Binary read for the `asset` domain: value bytes plus `{etag, contentType}`
52
96
  * KV metadata in a single entry. Legacy base64-JSON entries carry no metadata
53
97
  * and read as a miss here — the caller falls back to `getJson` for one TTL
54
98
  * window rather than this layer knowing the legacy shape.
55
99
  */
56
- getBinary(domain: KvDomainName, parts: readonly string[]): Promise<KvBinaryEntry | null>;
100
+ getBinary(domain: D, parts: readonly string[]): Promise<KvBinaryEntry | null>;
57
101
  /**
58
102
  * Binary write for the `asset` domain. Size is enforced on raw bytes (no
59
103
  * base64 inflation) and failures stay fail-soft like `putText`.
60
104
  */
61
- putBinary(domain: KvDomainName, parts: readonly string[], bytes: Uint8Array, metadata: {
105
+ putBinary(domain: D, parts: readonly string[], bytes: Uint8Array, metadata: {
62
106
  etag: string;
63
107
  contentType: string | null;
64
108
  }, options?: KvPutOptions): Promise<boolean>;
65
- del(domain: KvDomainName, parts: readonly string[]): Promise<void>;
109
+ del(domain: D, parts: readonly string[]): Promise<void>;
110
+ /**
111
+ * A cached binary value, or `null` — the metadata-free binary path.
112
+ *
113
+ * Distinct from {@link getBinary} because a KV entry may or may not carry
114
+ * metadata, and making every binary cache carry an etag to satisfy the reader
115
+ * means inventing one where there is nothing to validate against. A cache of
116
+ * derived bytes — an extracted image, a rendered thumbnail — has no upstream
117
+ * entity whose etag it could quote, so its entries legitimately carry none,
118
+ * and `getBinary` answers `null` for all of them.
119
+ *
120
+ * `'arrayBuffer'` is stated rather than relied upon: `get`'s default type is
121
+ * **`text`**, and a reader that does not say what it wants is handed the
122
+ * platform's default. Getting that wrong is invisible in every layer above —
123
+ * the bytes arrive, they are the wrong bytes, and nothing throws. UTF-8 is not
124
+ * byte-preserving: a JPEG read as text is lossy-decoded and every invalid
125
+ * sequence re-encodes as three `U+FFFD`.
126
+ */
127
+ getBytes(domain: D, parts: readonly string[]): Promise<Uint8Array | null>;
128
+ /**
129
+ * Cache a binary value under no metadata.
130
+ *
131
+ * @returns `false` when it was not stored — no binding, an open circuit, or a
132
+ * value over the domain's `maxValueBytes`. Never throws, and a `false` is a
133
+ * miss the next read re-derives from the source of truth.
134
+ *
135
+ * A **copy**, not a `subarray` view: the caller almost always passes a slice of
136
+ * a much larger read buffer, and handing KV a view pins that whole buffer for
137
+ * as long as the entry lives.
138
+ */
139
+ putBytes(domain: D, parts: readonly string[], value: Uint8Array, options?: KvPutOptions): Promise<boolean>;
66
140
  /**
67
141
  * Delete every key under a prefix, page-capped. Restarts from the start after
68
142
  * each page: deleting while a positional cursor advances would skip keys.
69
143
  */
70
- purgePrefix(domain: KvDomainName, parts?: readonly string[]): Promise<number>;
144
+ purgePrefix(domain: D, parts?: readonly string[]): Promise<number>;
71
145
  }
72
- export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES };
146
+ export { FAILURE_THRESHOLD, COOLDOWN_MS, KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES, resetBreakerForTests };
73
147
  export type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions };
74
148
  //# sourceMappingURL=KvCache.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"KvCache.d.ts","sourceRoot":"","sources":["../../src/kv/KvCache.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAcnD,UAAU,UAAU;IAClB,IAAI,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC9B,aAAa,EAAE,OAAO,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,uBAAuB;IAC/B,KAAK,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI,CAAC;IACnC,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,UAAU,eAAe;IACvB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACzC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACvD,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IACnE,eAAe,CAAC,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC;IACrF,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,WAAW,EAAE,OAAO,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAC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;var y=(g,e)=>$(g,"name",{value:e,configurable:!0});import{createLogger as b}from"../logger.js";import{KV_DOMAINS as p,buildKvKey as c,clampTtl as h,utf8ByteLength as x}from"./KvDomains.js";const u=b("KvCache"),f=1e3,o=10;class K{static{y(this,"KvCache")}namespace;constructor(e){this.namespace=e}get available(){return!!this.namespace}async getText(e,i){const r=this.namespace;if(!r)return null;try{return await r.get(c(e,i))}catch(t){return u.debug(`KV get failed for ${e}: ${t instanceof Error?t.message:String(t)}`),null}}async putText(e,i,r,t){const n=this.namespace;if(!n)return!1;const s=p[e];if(x(r)>s.maxValueBytes)return u.debug(`KV put skipped for ${e}: value exceeds ${s.maxValueBytes} bytes.`),!1;try{const a=h(t?.ttlSeconds,e);return await n.put(c(e,i),r,{expirationTtl:a}),!0}catch(a){return u.debug(`KV put failed for ${e}: ${a instanceof Error?a.message:String(a)}`),!1}}async getJson(e,i){const r=await this.getText(e,i);if(r===null)return null;try{return JSON.parse(r)}catch{return null}}async putJson(e,i,r,t){let n;try{n=JSON.stringify(r)}catch{return!1}return typeof n=="string"&&this.putText(e,i,n,t)}async getBinary(e,i){const r=this.namespace;if(!r||typeof r.getWithMetadata!="function")return null;try{const t=await r.getWithMetadata(c(e,i),"arrayBuffer");if(!t||t.value==null)return null;const n=t.value;let s=null;if(n instanceof ArrayBuffer?s=new Uint8Array(n.slice(0)):n instanceof Uint8Array?s=n.slice():typeof n=="string"&&(s=new TextEncoder().encode(n)),!s)return null;const a=t.metadata;return typeof a!="object"||a===null||typeof a.etag!="string"||a.etag===""?null:{bytes:s,metadata:{etag:a.etag,contentType:typeof a.contentType=="string"?a.contentType:null}}}catch(t){return u.debug(`KV getBinary failed for ${e}: ${t instanceof Error?t.message:String(t)}`),null}}async putBinary(e,i,r,t,n){const s=this.namespace;if(!s)return!1;if(!(r instanceof Uint8Array))return u.debug(`KV putBinary skipped for ${e}: value is not bytes.`),!1;const a=p[e];if(r.byteLength>a.maxValueBytes)return u.debug(`KV putBinary skipped for ${e}: value exceeds ${a.maxValueBytes} bytes.`),!1;if(typeof t?.etag!="string"||t.etag==="")return u.debug(`KV putBinary skipped for ${e}: missing etag metadata.`),!1;try{const l=h(n?.ttlSeconds,e),d=typeof t.contentType=="string"?t.contentType:null;return await s.put(c(e,i),r.slice().buffer,{expirationTtl:l,metadata:{etag:t.etag,contentType:d}}),!0}catch(l){return u.debug(`KV putBinary failed for ${e}: ${l instanceof Error?l.message:String(l)}`),!1}}async del(e,i){const r=this.namespace;if(r)try{await r.delete(c(e,i))}catch(t){u.debug(`KV delete failed for ${e}: ${t instanceof Error?t.message:String(t)}`)}}async purgePrefix(e,i=[]){const r=this.namespace;if(!r)return 0;const t=i.length===0?`${e}:`:c(e,i);let n=0;try{for(let s=0;s<o;s+=1){const a=await r.list({prefix:t,limit:f});if(a.keys.length===0)return n;for(const l of a.keys)await r.delete(l.name),n+=1;if(a.keys.length<f)return n}return u.warn(`KV purge for ${e} hit the ${o*f}-key page cap; at least one key may survive invalidation`),n}catch(s){return u.warn(`KV purge for ${e} failed: ${s instanceof Error?s.message:String(s)}`),n}}}export{K as KvCache,f as PURGE_LIST_LIMIT,o as PURGE_MAX_PAGES};
1
+ var B=Object.defineProperty;var c=(l,e)=>B(l,"name",{value:e,configurable:!0});import{UNMETERED as S}from"./SubrequestMeterLike.js";import{createLogger as $}from"../logger.js";import{KV_DOMAINS as b,buildKvKey as u,clampTtl as m,utf8ByteLength as k}from"./KvDomains.js";const y=$("KvCache");function f(l,e){y.debug(`KV write skipped for ${l}: ${e}.`)}c(f,"skipReason");const h=3,x=5e3,p=1e3,w=10;let g=0,o=0;function E(){g=0,o=0}c(E,"resetBreakerForTests");function T(l){return o===0?!1:l-o<x?!0:(o=0,g=h-1,!1)}c(T,"isCircuitOpen");function V(){g=0,o=0}c(V,"recordSuccess");function v(){g+=1,g>=h&&o===0&&(o=Date.now(),y.warn(`KV circuit opened after ${h} consecutive failures; serving from the source of truth until it recovers.`))}c(v,"recordFailure");class A{static{c(this,"KvCache")}namespace;meter;domains;constructor(e,s=S,t=b){this.namespace=e,this.meter=s,this.domains=t}get keyspaces(){return this.domains}get available(){return!!this.namespace}async guard(e,s,t,n){if(!this.namespace||T(Date.now()))return t;n?.charge!==!1&&this.meter.charge(1,"kv");try{const r=await s();return V(),r}catch(r){return v(),y.debug(`KV ${e} failed, serving from the source of truth: ${r instanceof Error?r.message:String(r)}`),t}}async getText(e,s){return await this.guard("get",async()=>{const t=await this.namespace.get(u(e,s,this.domains),"text");return t==null?null:typeof t=="string"?t:new TextDecoder().decode(t)},null)}async putText(e,s,t,n){const a=this.domains[e];return k(t)>a.maxValueBytes?(f(e,`value exceeds ${a.maxValueBytes} bytes`),!1):await this.guard("put",async()=>{const r=m(n?.ttlSeconds,e,this.domains);return await this.namespace.put(u(e,s,this.domains),t,{expirationTtl:r}),!0},!1)}async getJson(e,s){const t=await this.getText(e,s);if(t===null)return null;try{return JSON.parse(t)}catch{return null}}async putJson(e,s,t,n){let a;try{a=JSON.stringify(t)}catch{return!1}return await this.putText(e,s,a,n)}async getBinary(e,s){const t=this.namespace;return!t||typeof t.getWithMetadata!="function"?null:await this.guard("getBinary",async()=>{const n=await this.namespace.getWithMetadata(u(e,s,this.domains),"arrayBuffer");if(!n||n.value==null)return null;const a=n.value;let r=null;if(a instanceof ArrayBuffer?r=new Uint8Array(a.slice(0)):a instanceof Uint8Array?r=a.slice():typeof a=="string"&&(r=new TextEncoder().encode(a)),!r)return null;const i=n.metadata;return typeof i!="object"||i===null||typeof i.etag!="string"||i.etag===""?null:{bytes:r,metadata:{etag:i.etag,contentType:typeof i.contentType=="string"?i.contentType:null}}},null)}async putBinary(e,s,t,n,a){if(!(t instanceof Uint8Array))return f(e,"value is not bytes"),!1;const r=this.domains[e];return t.byteLength>r.maxValueBytes?(f(e,`value exceeds ${r.maxValueBytes} bytes`),!1):typeof n?.etag!="string"||n.etag===""?(f(e,"missing etag metadata"),!1):await this.guard("putBinary",async()=>{const i=m(a?.ttlSeconds,e,this.domains),d=typeof n.contentType=="string"?n.contentType:null;return await this.namespace.put(u(e,s,this.domains),t.slice().buffer,{expirationTtl:i,metadata:{etag:n.etag,contentType:d}}),!0},!1)}async del(e,s){await this.guard("delete",async()=>{await this.namespace.delete(u(e,s,this.domains))},void 0)}async getBytes(e,s){return this.namespace?await this.guard("get",async()=>{const n=await this.namespace.get(u(e,s,this.domains),"arrayBuffer");return n==null?null:typeof n=="string"?new TextEncoder().encode(n):new Uint8Array(n)},null):null}async putBytes(e,s,t,n){if(!(t instanceof Uint8Array))return f(e,"value is not bytes"),!1;const a=this.domains[e];return t.byteLength>a.maxValueBytes?(f(e,`value exceeds ${a.maxValueBytes} bytes`),!1):await this.guard("put",async()=>{const r=m(n?.ttlSeconds,e,this.domains);return await this.namespace.put(u(e,s,this.domains),t.slice().buffer,{expirationTtl:r}),!0},!1)}async purgePrefix(e,s=[]){const t=this.namespace;if(!t||T(Date.now()))return 0;const n=s.length===0?`${e}:`:u(e,s,this.domains);let a=0;try{for(let r=0;r<w;r+=1){this.meter.charge(1,"kv");const i=await t.list({prefix:n,limit:p});if(i.keys.length===0)return a;for(const d of i.keys)this.meter.charge(1,"kv"),await t.delete(d.name),a+=1;if(i.keys.length<p)return a}return y.warn(`KV purge for ${e} hit the ${w*p}-key page cap; at least one key may survive invalidation`),a}catch(r){return v(),y.warn(`KV purge for ${e} failed: ${r instanceof Error?r.message:String(r)}`),a}}}export{x as COOLDOWN_MS,h as FAILURE_THRESHOLD,A as KvCache,p as PURGE_LIST_LIMIT,w as PURGE_MAX_PAGES,E as resetBreakerForTests};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/kv/KvCache.ts"],
4
- "sourcesContent": ["import { createLogger } from '../logger.ts';\nimport { KV_DOMAINS, buildKvKey, clampTtl, utf8ByteLength } from './KvDomains.ts';\nimport type { KvDomainName } from './KvDomains.ts';\n\n/**\n * `KvCache` — typed facade over the single `CACHE` KV binding.\n *\n * Converged from `backend-runtime/src/kv/KvCache.ts`, identical in the four\n * repos that cache through KV. Semantics are fail-soft by design: reads return\n * `null` on miss, missing binding, or backend error; writes return `false`\n * when skipped (no binding, oversize value, backend error) and `true` when\n * stored. Callers treat KV as a pure optimization — D1/DO stay authoritative.\n */\n\nconst logger = createLogger('KvCache');\n\ninterface KvListPage {\n keys: Array<{ name: string }>;\n list_complete: boolean;\n cursor?: string;\n}\n\ninterface KvGetWithMetadataResult {\n value: string | ArrayBuffer | null;\n metadata: unknown;\n}\n\ninterface KvNamespaceLike {\n get(key: string): Promise<string | null>;\n get(key: string, type: 'text'): Promise<string | null>;\n get(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>;\n getWithMetadata?(key: string, type: 'arrayBuffer'): Promise<KvGetWithMetadataResult>;\n put(key: string, value: string | ArrayBuffer, options?: { expirationTtl?: number; metadata?: unknown }): Promise<void>;\n delete(key: string): Promise<unknown>;\n list(options: { prefix: string; limit?: number; cursor?: string }): Promise<KvListPage>;\n}\n\ninterface KvPutOptions {\n ttlSeconds?: number;\n}\n\ninterface KvFileMetadata {\n etag: string;\n contentType: string | null;\n}\n\ninterface KvBinaryEntry {\n bytes: Uint8Array;\n metadata: KvFileMetadata;\n}\n\nconst PURGE_LIST_LIMIT = 1000;\nconst PURGE_MAX_PAGES = 10;\n\nclass KvCache {\n public constructor(private readonly namespace?: KvNamespaceLike | null) {}\n\n public get available(): boolean {\n return !!this.namespace;\n }\n\n public async getText(domain: KvDomainName, parts: readonly string[]): Promise<string | null> {\n const ns = this.namespace;\n if (!ns) return null;\n try {\n return await ns.get(buildKvKey(domain, parts));\n } catch (error) {\n logger.debug(`KV get failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n }\n\n public async putText(domain: KvDomainName, parts: readonly string[], value: string, options?: KvPutOptions): Promise<boolean> {\n const ns = this.namespace;\n if (!ns) return false;\n // No unknown-domain check: `buildKvKey` below throws for one, and the\n // return type has never been able to express that. A silent `false` here\n // would have made an unknown domain look like a namespace miss.\n const def = KV_DOMAINS[domain];\n if (utf8ByteLength(value) > def.maxValueBytes) {\n logger.debug(`KV put skipped for ${domain}: value exceeds ${def.maxValueBytes} bytes.`);\n return false;\n }\n try {\n const ttl = clampTtl(options?.ttlSeconds, domain);\n await ns.put(buildKvKey(domain, parts), value, { expirationTtl: ttl });\n return true;\n } catch (error) {\n logger.debug(`KV put failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n public async getJson<T>(domain: KvDomainName, parts: readonly string[]): Promise<T | null> {\n const raw = await this.getText(domain, parts);\n if (raw === null) return null;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n }\n\n public async putJson(domain: KvDomainName, parts: readonly string[], value: unknown, options?: KvPutOptions): Promise<boolean> {\n let raw: unknown;\n try {\n raw = JSON.stringify(value);\n } catch {\n return false;\n }\n return typeof raw === 'string' && this.putText(domain, parts, raw, options);\n }\n\n /**\n * Binary read for the `asset` domain: value bytes plus `{etag, contentType}`\n * KV metadata in a single entry. Legacy base64-JSON entries carry no metadata\n * and read as a miss here — the caller falls back to `getJson` for one TTL\n * window rather than this layer knowing the legacy shape.\n */\n public async getBinary(domain: KvDomainName, parts: readonly string[]): Promise<KvBinaryEntry | null> {\n const ns = this.namespace;\n if (!ns || typeof ns.getWithMetadata !== 'function') return null;\n try {\n const res = await ns.getWithMetadata(buildKvKey(domain, parts), 'arrayBuffer');\n if (!res || res.value == null) return null;\n const value: unknown = res.value;\n let bytes: Uint8Array | null = null;\n if (value instanceof ArrayBuffer) {\n bytes = new Uint8Array(value.slice(0));\n } else if (value instanceof Uint8Array) {\n bytes = value.slice();\n } else if (typeof value === 'string') {\n bytes = new TextEncoder().encode(value);\n }\n if (!bytes) return null;\n const meta = res.metadata as { etag?: unknown; contentType?: unknown } | null | undefined;\n if (typeof meta !== 'object' || meta === null || typeof meta.etag !== 'string' || meta.etag === '') return null;\n return { bytes, metadata: { etag: meta.etag, contentType: typeof meta.contentType === 'string' ? meta.contentType : null } };\n } catch (error) {\n logger.debug(`KV getBinary failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n }\n\n /**\n * Binary write for the `asset` domain. Size is enforced on raw bytes (no\n * base64 inflation) and failures stay fail-soft like `putText`.\n */\n public async putBinary(\n domain: KvDomainName,\n parts: readonly string[],\n bytes: Uint8Array,\n metadata: { etag: string; contentType: string | null },\n options?: KvPutOptions,\n ): Promise<boolean> {\n const ns = this.namespace;\n if (!ns) return false;\n if (!(bytes instanceof Uint8Array)) {\n logger.debug(`KV putBinary skipped for ${domain}: value is not bytes.`);\n return false;\n }\n const def = KV_DOMAINS[domain];\n if (bytes.byteLength > def.maxValueBytes) {\n logger.debug(`KV putBinary skipped for ${domain}: value exceeds ${def.maxValueBytes} bytes.`);\n return false;\n }\n if (typeof metadata?.etag !== 'string' || metadata.etag === '') {\n logger.debug(`KV putBinary skipped for ${domain}: missing etag metadata.`);\n return false;\n }\n try {\n const ttl = clampTtl(options?.ttlSeconds, domain);\n const contentType = typeof metadata.contentType === 'string' ? metadata.contentType : null;\n await ns.put(buildKvKey(domain, parts), bytes.slice().buffer, {\n expirationTtl: ttl,\n metadata: { etag: metadata.etag, contentType },\n });\n return true;\n } catch (error) {\n logger.debug(`KV putBinary failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n public async del(domain: KvDomainName, parts: readonly string[]): Promise<void> {\n const ns = this.namespace;\n if (!ns) return;\n try {\n await ns.delete(buildKvKey(domain, parts));\n } catch (error) {\n logger.debug(`KV delete failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Delete every key under a prefix, page-capped. Restarts from the start after\n * each page: deleting while a positional cursor advances would skip keys.\n */\n public async purgePrefix(domain: KvDomainName, parts: readonly string[] = []): Promise<number> {\n const ns = this.namespace;\n if (!ns) return 0;\n const prefix = parts.length === 0 ? `${domain}:` : buildKvKey(domain, parts);\n let deleted = 0;\n try {\n for (let page = 0; page < PURGE_MAX_PAGES; page += 1) {\n const result = await ns.list({ prefix, limit: PURGE_LIST_LIMIT });\n if (result.keys.length === 0) return deleted;\n for (const key of result.keys) {\n await ns.delete(key.name);\n deleted += 1;\n }\n if (result.keys.length < PURGE_LIST_LIMIT) return deleted;\n }\n // The cap was hit with a full page still coming back, so keys remain and\n // the caller sees a count indistinguishable from a complete purge. A\n // write-invalidation that silently under-purges serves pre-write bytes\n // for a whole TTL while reporting success, so this is never silent.\n logger.warn(\n `KV purge for ${domain} hit the ${PURGE_MAX_PAGES * PURGE_LIST_LIMIT}-key page cap; at least one key may survive invalidation`,\n );\n return deleted;\n } catch (error) {\n logger.warn(`KV purge for ${domain} failed: ${error instanceof Error ? error.message : String(error)}`);\n return deleted;\n }\n }\n}\n\nexport { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES };\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions };\n"],
5
- "mappings": "+EAAA,OAAS,gBAAAA,MAAoB,eAC7B,OAAS,cAAAC,EAAY,cAAAC,EAAY,YAAAC,EAAU,kBAAAC,MAAsB,iBAajE,MAAMC,EAASL,EAAa,SAAS,EAqC/BM,EAAmB,IACnBC,EAAkB,GAExB,MAAMC,CAAO,CAtDb,MAsDa,CAAAC,EAAA,gBACyB,UAApC,YAAoCC,EAAkC,CAAlC,KAAA,UAAAA,CAAqC,CAEzE,IAAW,WAAS,CAClB,MAAO,CAAC,CAAC,KAAK,SAChB,CAEO,MAAM,QAAQC,EAAsBC,EAAwB,CACjE,MAAMC,EAAK,KAAK,UAChB,GAAI,CAACA,EAAI,OAAO,KAChB,GAAI,CACF,OAAO,MAAMA,EAAG,IAAIX,EAAWS,EAAQC,CAAK,CAAC,CAC/C,OAASE,EAAO,CACd,OAAAT,EAAO,MAAM,qBAAqBM,CAAM,KAAKG,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,EAC9F,IACT,CACF,CAEO,MAAM,QAAQH,E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", "clampTtl", "utf8ByteLength", "logger", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "KvCache", "__name", "namespace", "domain", "parts", "ns", "error", "value", "options", "def", "ttl", "raw", "res", "bytes", "meta", "metadata", "contentType", "prefix", "deleted", "page", "result", "key"]
4
+ "sourcesContent": ["/**\n * `KvCache` — typed facade over the single `CACHE` KV binding.\n *\n * Converged from `backend-runtime/src/kv/KvCache.ts`, identical in the four\n * repos that cache through KV. Semantics are fail-soft by design: reads return\n * `null` on miss, missing binding, or backend error; writes return `false`\n * when skipped (no binding, oversize value, backend error) and `true` when\n * stored. Callers treat KV as a pure optimization — D1/DO stay authoritative.\n *\n * ### The circuit breaker is not optional\n *\n * A fail-soft wrapper alone is not enough. \"Fail soft\" protects correctness, but\n * if the namespace is *hanging* rather than erroring, every read still pays a\n * timeout — burning the request's subrequest budget and wall clock, and making\n * the server slower precisely when it is already degraded. The breaker opens\n * after {@link FAILURE_THRESHOLD} consecutive failures, fails fast while open,\n * and half-opens after {@link COOLDOWN_MS} so a recovered namespace is picked up\n * without a restart. Both halves came from Edge-Sonic's copy, which measured\n * the degradation before writing the breaker; two of the family repos that\n * lacked it had this file shorter by a third.\n *\n * ### Every issued operation is charged\n *\n * A KV `get`/`put`/`delete` is a subrequest like any other — D1's limits page\n * counts *queries* per invocation and the Workers page counts subrequests to KV —\n * so a cache that is invisible to the ceiling makes every number that budgets\n * work wrong. The counter is a constructor dependency rather than a module\n * singleton so the composition root hands this facade the same one the rest of\n * the invocation holds; a default of {@link UNMETERED} keeps the\n * no-DI case honest rather than silently unmetered.\n */\nimport { UNMETERED } from './SubrequestMeterLike.ts';\nimport type { SubrequestMeterLike } from './SubrequestMeterLike.ts';\nimport { createLogger } from '../logger.ts';\nimport { KV_DOMAINS, buildKvKey, clampTtl, utf8ByteLength } from './KvDomains.ts';\nimport type { KvDomainName, KvDomains } from './KvDomains.ts';\n\nconst logger = createLogger('KvCache');\n\n/**\n * Log that a skipped write was skipped, at the level the caller can act on.\n *\n * A size or metadata refusal is a code or cache-shape problem, not a namespace\n * fault, so it is debug: the write simply did not happen and the caller reads\n * `false` as \"not stored\", which is what a cache means by that.\n */\nfunction skipReason(domain: string, reason: string): void {\n logger.debug(`KV write skipped for ${domain}: ${reason}.`);\n}\n\n/**\nConsecutive failures before the breaker opens.\n*/\nconst FAILURE_THRESHOLD = 3;\n\n/**\nHow long the breaker stays open before a half-open probe.\n*/\nconst COOLDOWN_MS = 5000;\n\ninterface KvListPage {\n keys: Array<{ name: string }>;\n list_complete: boolean;\n cursor?: string;\n}\n\ninterface KvGetWithMetadataResult {\n value: string | ArrayBuffer | null;\n metadata: unknown;\n}\n\ninterface KvNamespaceLike {\n get(key: string): Promise<string | null>;\n get(key: string, type: 'text'): Promise<string | null>;\n get(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>;\n getWithMetadata?(key: string, type: 'arrayBuffer'): Promise<KvGetWithMetadataResult>;\n put(key: string, value: string | ArrayBuffer, options?: { expirationTtl?: number; metadata?: unknown }): Promise<void>;\n delete(key: string): Promise<unknown>;\n list(options: { prefix: string; limit?: number; cursor?: string }): Promise<KvListPage>;\n}\n\ninterface KvPutOptions {\n ttlSeconds?: number;\n}\n\ninterface KvFileMetadata {\n etag: string;\n contentType: string | null;\n}\n\ninterface KvBinaryEntry {\n bytes: Uint8Array;\n metadata: KvFileMetadata;\n}\n\nconst PURGE_LIST_LIMIT = 1000;\nconst PURGE_MAX_PAGES = 10;\n\n/**\nPer-isolate breaker state.\n\nModule-level rather than per-instance on purpose: the binding is process-wide,\nso a namespace that is down for one `KvCache` is down for all of them, and a\nper-instance breaker would give every request scope its own three failures to\nget through before the fast path engaged.\n*/\nlet consecutiveFailures = 0;\nlet breakerOpenedAt = 0;\n\n/**\nTest seam: force the breaker closed and forget the failure count.\n*/\nfunction resetBreakerForTests(): void {\n consecutiveFailures = 0;\n breakerOpenedAt = 0;\n}\n\n/**\nTrue while the breaker is open, i.e. calls should be skipped entirely.\n*/\nfunction isCircuitOpen(now: number): boolean {\n if (breakerOpenedAt === 0) return false;\n if (now - breakerOpenedAt < COOLDOWN_MS) return true;\n // Cooldown elapsed: allow exactly one probe through by reopening the window.\n breakerOpenedAt = 0;\n consecutiveFailures = FAILURE_THRESHOLD - 1;\n return false;\n}\n\nfunction recordSuccess(): void {\n consecutiveFailures = 0;\n breakerOpenedAt = 0;\n}\n\nfunction recordFailure(): void {\n consecutiveFailures += 1;\n if (!(consecutiveFailures >= FAILURE_THRESHOLD && breakerOpenedAt === 0)) {\n return;\n }\n\n breakerOpenedAt = Date.now();\n logger.warn(`KV circuit opened after ${FAILURE_THRESHOLD} consecutive failures; serving from the source of truth until it recovers.`);\n}\n\nclass KvCache<D extends string = KvDomainName> {\n /**\n * @param namespace The binding, or `null` for a deployment without one.\n * @param meter The invocation's subrequest counter, or an unmetered default.\n * @param domains The keyspace's own domain table. Defaults to the kit's; supply\n * one whose names and lifetimes are yours, because the TTL and size policy is\n * per-repo by definition.\n */\n public constructor(\n private readonly namespace?: KvNamespaceLike | null,\n private readonly meter: SubrequestMeterLike = UNMETERED,\n private readonly domains: KvDomains<D> = KV_DOMAINS as unknown as KvDomains<D>,\n ) {}\n\n /**\n * The keyspace's policy table, for a caller building a key beside a read.\n */\n public get keyspaces(): KvDomains<D> {\n return this.domains;\n }\n\n /**\n * Whether the binding is present.\n *\n * Distinct from \"healthy\": a present binding can still be failing, and that is\n * the case the breaker exists for. Callers must not branch on this to decide\n * whether they may read the source of truth — they read it regardless.\n */\n public get available(): boolean {\n return !!this.namespace;\n }\n\n /**\n * Run a KV operation under the breaker.\n *\n * Never throws and never returns a rejection: every failure path is a `null`\n * or `false`, which callers read as \"miss\" or \"not stored\".\n *\n * `charge: false` is for the one caller that issues a *loop* of operations\n * inside one `guard` ({@link purgePrefix}), where charging once here would\n * report a 10,000-key purge as a single subrequest. It charges per call instead.\n */\n private async guard<T>(operation: string, run: () => Promise<T>, fallback: T, options?: { charge?: boolean }): Promise<T> {\n const ns = this.namespace;\n if (!ns) return fallback;\n if (isCircuitOpen(Date.now())) return fallback;\n // Charged here, not at the call site: this is the point at which a request is\n // *about to be issued*, and it is reached only when there is a namespace and\n // the breaker is closed. A miss caused by no binding, or by a namespace that\n // is down, spends no subrequest — which is the whole point of failing soft,\n // and charging before this line would have counted a request that was never\n // made.\n if (options?.charge !== false) this.meter.charge(1, 'kv');\n try {\n const result = await run();\n recordSuccess();\n return result;\n } catch (error) {\n recordFailure();\n logger.debug(`KV ${operation} failed, serving from the source of truth: ${error instanceof Error ? error.message : String(error)}`);\n return fallback;\n }\n }\n\n public async getText(domain: D, parts: readonly string[]): Promise<string | null> {\n return await this.guard(\n 'get',\n async () => {\n // `'text'` stated rather than relied upon: a reader that does not say what it\n // wants is given the platform's default, and the two defaults are not the\n // same. Only reachable-as-bytes is decoded rather than thrown on, because the\n // caller reads this as a cache and a corrupt entry should cost a recompute.\n const raw = await this.namespace!.get(buildKvKey(domain, parts, this.domains), 'text');\n if (raw === null || raw === undefined) return null;\n return typeof raw === 'string' ? raw : new TextDecoder().decode(raw);\n },\n null,\n );\n }\n\n public async putText(domain: D, parts: readonly string[], value: string, options?: KvPutOptions): Promise<boolean> {\n // No unknown-domain check: `buildKvKey` below throws for one, and the\n // return type has never been able to express that. A silent `false` here\n // would have made an unknown domain look like a namespace miss.\n const def = this.domains[domain];\n if (utf8ByteLength(value) > def.maxValueBytes) {\n skipReason(domain, `value exceeds ${def.maxValueBytes} bytes`);\n return false;\n }\n return await this.guard(\n 'put',\n async () => {\n const ttl = clampTtl(options?.ttlSeconds, domain, this.domains);\n await this.namespace!.put(buildKvKey(domain, parts, this.domains), value, { expirationTtl: ttl });\n return true;\n },\n false,\n );\n }\n\n public async getJson<T>(domain: D, parts: readonly string[]): Promise<T | null> {\n const raw = await this.getText(domain, parts);\n if (raw === null) return null;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n }\n\n public async putJson(domain: D, parts: readonly string[], value: unknown, options?: KvPutOptions): Promise<boolean> {\n let raw: string;\n try {\n raw = JSON.stringify(value);\n } catch {\n return false;\n }\n return await this.putText(domain, parts, raw, options);\n }\n\n /**\n * Binary read for the `asset` domain: value bytes plus `{etag, contentType}`\n * KV metadata in a single entry. Legacy base64-JSON entries carry no metadata\n * and read as a miss here — the caller falls back to `getJson` for one TTL\n * window rather than this layer knowing the legacy shape.\n */\n public async getBinary(domain: D, parts: readonly string[]): Promise<KvBinaryEntry | null> {\n const ns = this.namespace;\n if (!ns || typeof ns.getWithMetadata !== 'function') return null;\n return await this.guard(\n 'getBinary',\n async () => {\n const res = await this.namespace!.getWithMetadata!(buildKvKey(domain, parts, this.domains), 'arrayBuffer');\n if (!res || res.value == null) return null;\n const value: unknown = res.value;\n let bytes: Uint8Array | null = null;\n if (value instanceof ArrayBuffer) {\n bytes = new Uint8Array(value.slice(0));\n } else if (value instanceof Uint8Array) {\n bytes = value.slice();\n } else if (typeof value === 'string') {\n bytes = new TextEncoder().encode(value);\n }\n if (!bytes) return null;\n const meta = res.metadata as { etag?: unknown; contentType?: unknown } | null | undefined;\n if (typeof meta !== 'object' || meta === null || typeof meta.etag !== 'string' || meta.etag === '') return null;\n return { bytes, metadata: { etag: meta.etag, contentType: typeof meta.contentType === 'string' ? meta.contentType : null } };\n },\n null,\n );\n }\n\n /**\n * Binary write for the `asset` domain. Size is enforced on raw bytes (no\n * base64 inflation) and failures stay fail-soft like `putText`.\n */\n public async putBinary(\n domain: D,\n parts: readonly string[],\n bytes: Uint8Array,\n metadata: { etag: string; contentType: string | null },\n options?: KvPutOptions,\n ): Promise<boolean> {\n if (!(bytes instanceof Uint8Array)) {\n skipReason(domain, 'value is not bytes');\n return false;\n }\n const def = this.domains[domain];\n if (bytes.byteLength > def.maxValueBytes) {\n skipReason(domain, `value exceeds ${def.maxValueBytes} bytes`);\n return false;\n }\n if (typeof metadata?.etag !== 'string' || metadata.etag === '') {\n skipReason(domain, 'missing etag metadata');\n return false;\n }\n return await this.guard(\n 'putBinary',\n async () => {\n const ttl = clampTtl(options?.ttlSeconds, domain, this.domains);\n const contentType = typeof metadata.contentType === 'string' ? metadata.contentType : null;\n await this.namespace!.put(buildKvKey(domain, parts, this.domains), bytes.slice().buffer, {\n expirationTtl: ttl,\n metadata: { etag: metadata.etag, contentType },\n });\n return true;\n },\n false,\n );\n }\n\n public async del(domain: D, parts: readonly string[]): Promise<void> {\n await this.guard(\n 'delete',\n async () => {\n await this.namespace!.delete(buildKvKey(domain, parts, this.domains));\n },\n undefined,\n );\n }\n\n /**\n * A cached binary value, or `null` — the metadata-free binary path.\n *\n * Distinct from {@link getBinary} because a KV entry may or may not carry\n * metadata, and making every binary cache carry an etag to satisfy the reader\n * means inventing one where there is nothing to validate against. A cache of\n * derived bytes — an extracted image, a rendered thumbnail — has no upstream\n * entity whose etag it could quote, so its entries legitimately carry none,\n * and `getBinary` answers `null` for all of them.\n *\n * `'arrayBuffer'` is stated rather than relied upon: `get`'s default type is\n * **`text`**, and a reader that does not say what it wants is handed the\n * platform's default. Getting that wrong is invisible in every layer above —\n * the bytes arrive, they are the wrong bytes, and nothing throws. UTF-8 is not\n * byte-preserving: a JPEG read as text is lossy-decoded and every invalid\n * sequence re-encodes as three `U+FFFD`.\n */\n public async getBytes(domain: D, parts: readonly string[]): Promise<Uint8Array | null> {\n const ns = this.namespace;\n if (!ns) return null;\n return await this.guard(\n 'get',\n async () => {\n const raw = await this.namespace!.get(buildKvKey(domain, parts, this.domains), 'arrayBuffer');\n if (raw === null || raw === undefined) return null;\n // Kept for a caller or a double that hands back text. Assert the requested\n // type rather than trusting the returned one.\n return typeof raw === 'string' ? new TextEncoder().encode(raw) : new Uint8Array(raw);\n },\n null,\n );\n }\n\n /**\n * Cache a binary value under no metadata.\n *\n * @returns `false` when it was not stored — no binding, an open circuit, or a\n * value over the domain's `maxValueBytes`. Never throws, and a `false` is a\n * miss the next read re-derives from the source of truth.\n *\n * A **copy**, not a `subarray` view: the caller almost always passes a slice of\n * a much larger read buffer, and handing KV a view pins that whole buffer for\n * as long as the entry lives.\n */\n public async putBytes(domain: D, parts: readonly string[], value: Uint8Array, options?: KvPutOptions): Promise<boolean> {\n if (!(value instanceof Uint8Array)) {\n skipReason(domain, 'value is not bytes');\n return false;\n }\n const def = this.domains[domain];\n if (value.byteLength > def.maxValueBytes) {\n skipReason(domain, `value exceeds ${def.maxValueBytes} bytes`);\n return false;\n }\n return await this.guard(\n 'put',\n async () => {\n const ttl = clampTtl(options?.ttlSeconds, domain, this.domains);\n await this.namespace!.put(buildKvKey(domain, parts, this.domains), value.slice().buffer, { expirationTtl: ttl });\n return true;\n },\n false,\n );\n }\n\n /**\n * Delete every key under a prefix, page-capped. Restarts from the start after\n * each page: deleting while a positional cursor advances would skip keys.\n */\n public async purgePrefix(domain: D, parts: readonly string[] = []): Promise<number> {\n const ns = this.namespace;\n if (!ns || isCircuitOpen(Date.now())) return 0;\n const prefix = parts.length === 0 ? `${domain}:` : buildKvKey(domain, parts, this.domains);\n let deleted = 0;\n try {\n for (let page = 0; page < PURGE_MAX_PAGES; page += 1) {\n // Charged per key rather than once for the loop: this issues up to\n // PURGE_MAX_PAGES * PURGE_LIST_LIMIT requests, and a caller budgeting\n // an invalidation needs to see that many, not one.\n this.meter.charge(1, 'kv');\n const result = await ns.list({ prefix, limit: PURGE_LIST_LIMIT });\n if (result.keys.length === 0) return deleted;\n for (const key of result.keys) {\n this.meter.charge(1, 'kv');\n await ns.delete(key.name);\n deleted += 1;\n }\n if (result.keys.length < PURGE_LIST_LIMIT) return deleted;\n }\n // The cap was hit with a full page still coming back, so keys remain and\n // the caller sees a count indistinguishable from a complete purge. A\n // write-invalidation that silently under-purges serves pre-write bytes\n // for a whole TTL while reporting success, so this is never silent.\n logger.warn(\n `KV purge for ${domain} hit the ${PURGE_MAX_PAGES * PURGE_LIST_LIMIT}-key page cap; at least one key may survive invalidation`,\n );\n return deleted;\n } catch (error) {\n recordFailure();\n logger.warn(`KV purge for ${domain} failed: ${error instanceof Error ? error.message : String(error)}`);\n return deleted;\n }\n }\n}\n\nexport { FAILURE_THRESHOLD, COOLDOWN_MS, KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES, resetBreakerForTests };\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions };\n"],
5
+ "mappings": "+EA+BA,OAAS,aAAAA,MAAiB,2BAE1B,OAAS,gBAAAC,MAAoB,eAC7B,OAAS,cAAAC,EAAY,cAAAC,EAAY,YAAAC,EAAU,kBAAAC,MAAsB,iBAGjE,MAAMC,EAASL,EAAa,SAAS,EASrC,SAASM,EAAWC,EAAgBC,EAAc,CAChDH,EAAO,MAAM,wBAAwBE,CAAM,KAAKC,CAAM,GAAG,CAC3D,CAFSC,EAAAH,EAAA,cAOT,MAAMI,EAAoB,EAKpBC,EAAc,IAqCdC,EAAmB,IACnBC,EAAkB,GAUxB,IAAIC,EAAsB,EACtBC,EAAkB,EAKtB,SAASC,GAAoB,CAC3BF,EAAsB,EACtBC,EAAkB,CACpB,CAHSN,EAAAO,EAAA,wBAQT,SAASC,EAAcC,EAAW,CAChC,OAAIH,IAAoB,EAAU,GAC9BG,EAAMH,EAAkBJ,EAAoB,IAEhDI,EAAkB,EAClBD,EAAsBJ,EAAoB,EACnC,GACT,CAPSD,EAAAQ,EAAA,iBAST,SAASE,GAAa,CACpBL,EAAsB,EACtBC,EAAkB,CACpB,CAHSN,EAAAU,EAAA,iBAKT,SAASC,GAAa,CACpBN,GAAuB,EACjBA,GAAuBJ,GAAqBK,IAAoB,IAItEA,EAAkB,KAAK,IAAG,EAC1BV,EAAO,KAAK,2BAA2BK,CAAiB,4EAA4E,EACtI,CARSD,EAAAW,EAAA,iBAUT,MAAMC,CAAO,CAhJb,MAgJa,CAAAZ,EAAA,gBASQ,UACA,MACA,QAHnB,YACmBa,EACAC,EAA6BxB,EAC7ByB,EAAwBvB,EAAqC,CAF7D,KAAA,UAAAqB,EACA,KAAA,MAAAC,EACA,KAAA,QAAAC,CAChB,CAKH,IAAW,WAAS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CACT,CACF",
6
+ "names": ["UNMETERED", "createLogger", "KV_DOMAINS", "buildKvKey", "clampTtl", "utf8ByteLength", "logger", "skipReason", "domain", "reason", "__name", "FAILURE_THRESHOLD", "COOLDOWN_MS", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "consecutiveFailures", "breakerOpenedAt", "resetBreakerForTests", "isCircuitOpen", "now", "recordSuccess", "recordFailure", "KvCache", "namespace", "meter", "domains", "operation", "run", "fallback", "options", "result", "error", "parts", "raw", "value", "def", "ttl", "ns", "res", "bytes", "meta", "metadata", "contentType", "prefix", "deleted", "page", "key"]
7
7
  }
@@ -1,3 +1,28 @@
1
+ /**
2
+ * Single-KV keyspace: one `CACHE` binding, domains separated by key prefix.
3
+ *
4
+ * Converged from `backend-runtime/src/kv/KvDomains.ts` (Durable-DAV,
5
+ * Durable-DAV-Router, Edge-Sonic, Mail-Otter — the same table under four sets
6
+ * of names). The names here are the three the family shares, and they are the
7
+ * **default**, not a requirement: a repo whose cache vocabulary is genuinely
8
+ * different supplies its own table, because the TTL and size policy below is
9
+ * per-repo by definition — a cache holding album artwork keyed by a file's mtime
10
+ * and a cache holding session profiles cannot share a lifetime, and renaming
11
+ * call sites to fit a shared table would silently change when a library is
12
+ * re-read from its origin.
13
+ *
14
+ * What does **not** become open is the *union*: a consumer's registry is still a
15
+ * closed `Record<D, KvDomainDef>` over its own names, so a typo cannot create a
16
+ * new keyspace, and prefix collisions still start the way the family has always
17
+ * assumed they do.
18
+ *
19
+ * Rationale: D1 and the Durable Object stay the source of truth. KV is a
20
+ * loss-tolerant, read-heavy cache only — a miss or eviction must always be
21
+ * recoverable by recompute. Call sites never touch `env.CACHE` directly; they
22
+ * go through `KvCache` with a registry so prefixes cannot collide and TTL/size
23
+ * policy lives in one table.
24
+ */
25
+ declare const KV_KEY_VERSION = "v1";
1
26
  declare const KV_MAX_KEY_LENGTH = 512;
2
27
  declare const KV_MIN_TTL_SECONDS = 60;
3
28
  type KvDomainName = 'session' | 'asset' | 'metadata';
@@ -6,7 +31,16 @@ interface KvDomainDef {
6
31
  maxValueBytes: number;
7
32
  description: string;
8
33
  }
9
- declare const KV_DOMAINS: Record<KvDomainName, KvDomainDef>;
34
+ /**
35
+ * A keyspace's whole policy, closed over its own domain names.
36
+ *
37
+ * `D` is the consumer's union, so `KV_DOMAINS` satisfies `KvDomains<KvDomainName>`
38
+ * and a repo's own table satisfies `KvDomains<'songMeta' | 'albumArt'>` — with
39
+ * both keeping the "this name exists" check that makes a typo a throw rather than
40
+ * a new prefix.
41
+ */
42
+ type KvDomains<D extends string = KvDomainName> = Readonly<Record<D, KvDomainDef>>;
43
+ declare const KV_DOMAINS: KvDomains;
10
44
  /**
11
45
  * 128-bit digest built from four independent FNV-1a lanes.
12
46
  *
@@ -22,13 +56,23 @@ declare const KV_DOMAINS: Record<KvDomainName, KvDomainDef>;
22
56
  */
23
57
  declare function digest128(input: string): string;
24
58
  declare function sanitizeSegment(segment: string): string;
25
- declare function buildKvKey(domain: KvDomainName, parts: readonly string[]): string;
59
+ /**
60
+ * The key for a value.
61
+ *
62
+ * `domains` is an optional trailing argument rather than a required one so the
63
+ * common case — the kit's own vocabulary — reads as two arguments. It is the
64
+ * **same registry** a `KvCache` holds: a key built against one table and a TTL
65
+ * resolved against another is a cache that reads and writes under one policy and
66
+ * reports another, which is the failure this threading exists to make impossible
67
+ * rather than to document.
68
+ */
69
+ declare function buildKvKey<D extends string = KvDomainName>(domain: D, parts: readonly string[], domains?: KvDomains<D>): string;
26
70
  declare function utf8ByteLength(value: string): number;
27
71
  /**
28
72
  * Resolve a TTL, defaulting to the domain's own. Every domain declares a
29
73
  * required `ttlSeconds`, so there is no "no TTL" case to represent.
30
74
  */
31
- declare function clampTtl(ttlSeconds: number | undefined, domain: KvDomainName): number;
32
- export { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength };
33
- export type { KvDomainDef, KvDomainName };
75
+ declare function clampTtl<D extends string = KvDomainName>(ttlSeconds: number | undefined, domain: D, domains?: KvDomains<D>): number;
76
+ export { KV_DOMAINS, KV_KEY_VERSION, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength, };
77
+ export type { KvDomainDef, KvDomainName, KvDomains };
34
78
  //# sourceMappingURL=KvDomains.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"KvDomains.d.ts","sourceRoot":"","sources":["../../src/kv/KvDomains.ts"],"names":[],"mappings":"AAiBA,QAAA,MAAM,iBAAiB,MAAM,CAAC;AAC9B,QAAA,MAAM,kBAAkB,KAAK,CAAC;AAE9B,KAAK,YAAY,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,CAAC;AAErD,UAAU,WAAW;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,QAAA,MAAM,UAAU,EAAE,MAAM,CAAC,YAAY,EAAE,WAAW,CAgBjD,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,iBAAS,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAcxC;AAED,iBAAS,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAIhD;AAED,iBAAS,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAc1E;AAED,iBAAS,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE7C;AAED;;;GAGG;AACH,iBAAS,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,EAAE,YAAY,GAAG,MAAM,CAG9E;AAED,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,cAAc,EAAE,CAAC;AAC/H,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AAED,OAAO,EACL,UAAU,EACV,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,SAAS,EACT,eAAe,EACf,cAAc,GACf,CAAC;AACF,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC"}
@@ -1 +1 @@
1
- var f=Object.defineProperty;var s=(e,t)=>f(e,"name",{value:t,configurable:!0});const p="v1",u=512,h=60,a={session:{ttlSeconds:300,maxValueBytes:65536,description:"Per-user session/profile snapshots; invalidated on any credential change."},asset:{ttlSeconds:300,maxValueBytes:10485760,description:"Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write."},metadata:{ttlSeconds:120,maxValueBytes:1048576,description:"Listing/derived snapshots keyed by owner or collection; invalidated on mutation."}};function l(e){const i=[2166136261,3266489909,668265263,374761393];let r="";for(let n=0;n<4;n+=1){let o=i[n];const c=16777619+n*2654435769;for(let _=0;_<e.length;_+=1)o^=e.codePointAt(_)??0,o=Math.imul(o,c);r+=(o>>>0).toString(16).padStart(8,"0")}return r}s(l,"digest128");function d(e){const t=e.trim();if(!t)throw new Error("KV key segment must not be empty.");return encodeURIComponent(t)}s(d,"sanitizeSegment");function m(e,t){if(!a[e])throw new Error(`Unknown KV domain: ${e}.`);if(t.length===0)throw new Error(`KV domain ${e} requires at least one key part.`);const r=`${e}:v1:`,n=t.map(c=>d(c)).join(":"),o=r+n;return o.length<=512?o:`${r}h:${l(n)}`}s(m,"buildKvKey");function S(e){return new TextEncoder().encode(e).length}s(S,"utf8ByteLength");function E(e,t){const i=e??a[t].ttlSeconds;return Number.isFinite(i)?Math.max(60,Math.floor(i)):a[t].ttlSeconds}s(E,"clampTtl");export{a as KV_DOMAINS,u as KV_MAX_KEY_LENGTH,h as KV_MIN_TTL_SECONDS,m as buildKvKey,E as clampTtl,l as digest128,d as sanitizeSegment,S as utf8ByteLength};
1
+ var f=Object.defineProperty;var i=(e,t)=>f(e,"name",{value:t,configurable:!0});const u="v1",m=512,h=60,a={session:{ttlSeconds:300,maxValueBytes:65536,description:"Per-user session/profile snapshots; invalidated on any credential change."},asset:{ttlSeconds:300,maxValueBytes:10485760,description:"Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write."},metadata:{ttlSeconds:120,maxValueBytes:1048576,description:"Listing/derived snapshots keyed by owner or collection; invalidated on mutation."}};function l(e){const r=[2166136261,3266489909,668265263,374761393];let o="";for(let n=0;n<4;n+=1){let s=r[n];const c=16777619+n*2654435769;for(let _=0;_<e.length;_+=1)s^=e.codePointAt(_)??0,s=Math.imul(s,c);o+=(s>>>0).toString(16).padStart(8,"0")}return o}i(l,"digest128");function d(e){const t=e.trim();if(!t)throw new Error("KV key segment must not be empty.");return encodeURIComponent(t)}i(d,"sanitizeSegment");function S(e,t,r=a){if(!r[e])throw new Error(`Unknown KV domain: ${e}.`);if(t.length===0)throw new Error(`KV domain ${e} requires at least one key part.`);const o=`${e}:v1:`,n=t.map(c=>d(c)).join(":"),s=o+n;return s.length<=512?s:`${o}h:${l(n)}`}i(S,"buildKvKey");function E(e){return new TextEncoder().encode(e).length}i(E,"utf8ByteLength");function K(e,t,r=a){const o=r[t]?.ttlSeconds??a.session.ttlSeconds,n=e??o;return Number.isFinite(n)?Math.max(60,Math.floor(n)):o}i(K,"clampTtl");export{a as KV_DOMAINS,u as KV_KEY_VERSION,m as KV_MAX_KEY_LENGTH,h as KV_MIN_TTL_SECONDS,S as buildKvKey,K as clampTtl,l as digest128,d as sanitizeSegment,E as utf8ByteLength};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/kv/KvDomains.ts"],
4
- "sourcesContent": ["/**\n * Single-KV keyspace: one `CACHE` binding, domains separated by key prefix.\n *\n * Converged from `backend-runtime/src/kv/KvDomains.ts` (Durable-DAV,\n * Durable-DAV-Router, Edge-Sonic, Mail-Otter — the same table under four sets\n * of names). The domains are generalized to the three the whole family shares;\n * a consumer with a different cache vocabulary renames its call sites (clients\n * adapt) rather than extending the registry, because an open registry is how\n * prefix collisions start.\n *\n * Rationale: D1 and the Durable Object stay the source of truth. KV is a\n * loss-tolerant, read-heavy cache only — a miss or eviction must always be\n * recoverable by recompute. Call sites never touch `env.CACHE` directly; they\n * go through `KvCache` with a closed `KvDomainName` registry so prefixes cannot\n * collide and TTL/size policy lives in one table.\n */\nconst KV_KEY_VERSION = 'v1';\nconst KV_MAX_KEY_LENGTH = 512;\nconst KV_MIN_TTL_SECONDS = 60;\n\ntype KvDomainName = 'session' | 'asset' | 'metadata';\n\ninterface KvDomainDef {\n ttlSeconds: number;\n maxValueBytes: number;\n description: string;\n}\n\nconst KV_DOMAINS: Record<KvDomainName, KvDomainDef> = {\n session: {\n ttlSeconds: 300,\n maxValueBytes: 65_536,\n description: 'Per-user session/profile snapshots; invalidated on any credential change.',\n },\n asset: {\n ttlSeconds: 300,\n maxValueBytes: 10_485_760,\n description: 'Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write.',\n },\n metadata: {\n ttlSeconds: 120,\n maxValueBytes: 1_048_576,\n description: 'Listing/derived snapshots keyed by owner or collection; invalidated on mutation.',\n },\n};\n\n/**\n * 128-bit digest built from four independent FNV-1a lanes.\n *\n * Why not a single 32-bit FNV: `buildKvKey` falls back to a digest when a key\n * exceeds the platform's 512-character limit, and the longest keys embed a\n * user-controlled path or name. A 32-bit digest over a shared keyspace is\n * collision-searchable — someone who controls names in their own scope could\n * grind a colliding key and read another tenant's cached bytes. Four lanes over\n * the same bytes with different offsets/primes cost one extra pass and take a\n * birthday collision to ~2^64 work, which is not worth attacking.\n *\n * Synchronous on purpose: `buildKvKey` is called from sync cache-key builders.\n */\nfunction digest128(input: string): string {\n const LANES = 4;\n const offsets = [0x81_1c_9d_c5, 0xc2_b2_ae_35, 0x27_d4_eb_2f, 0x16_56_67_b1];\n let out = '';\n for (let lane = 0; lane < LANES; lane += 1) {\n let hash = offsets[lane];\n const prime = 0x01_00_01_93 + lane * 0x9e_37_79_b9;\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.codePointAt(i) ?? 0;\n hash = Math.imul(hash, prime);\n }\n out += (hash >>> 0).toString(16).padStart(8, '0');\n }\n return out;\n}\n\nfunction sanitizeSegment(segment: string): string {\n const trimmed = segment.trim();\n if (!trimmed) throw new Error('KV key segment must not be empty.');\n return encodeURIComponent(trimmed);\n}\n\nfunction buildKvKey(domain: KvDomainName, parts: readonly string[]): string {\n const def = KV_DOMAINS[domain];\n if (!def) throw new Error(`Unknown KV domain: ${domain}.`);\n if (parts.length === 0) throw new Error(`KV domain ${domain} requires at least one key part.`);\n const prefix = `${domain}:${KV_KEY_VERSION}:`;\n const joined = parts.map((part) => sanitizeSegment(part)).join(':');\n const full = prefix + joined;\n if (full.length <= KV_MAX_KEY_LENGTH) return full;\n // Deterministic overflow form. Note the consequence for invalidation: an\n // overflowing key does not start with the plain prefix, so `purgePrefix` on\n // the parts will not match it. Callers must therefore bound the key material\n // they cache (path length, identifier length) — the digest is a crash guard,\n // not a caching strategy.\n return `${prefix}h:${digest128(joined)}`;\n}\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Resolve a TTL, defaulting to the domain's own. Every domain declares a\n * required `ttlSeconds`, so there is no \"no TTL\" case to represent.\n */\nfunction clampTtl(ttlSeconds: number | undefined, domain: KvDomainName): number {\n const effective = ttlSeconds ?? KV_DOMAINS[domain].ttlSeconds;\n return Number.isFinite(effective) ? Math.max(KV_MIN_TTL_SECONDS, Math.floor(effective)) : KV_DOMAINS[domain].ttlSeconds;\n}\n\nexport { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength };\nexport type { KvDomainDef, KvDomainName };\n"],
5
- "mappings": "+EAgBA,MAAMA,EAAiB,KACjBC,EAAoB,IACpBC,EAAqB,GAUrBC,EAAgD,CACpD,QAAS,CACP,WAAY,IACZ,cAAe,MACf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SZ,EAAAW,EAAA,kBAQT,SAASE,EAASC,EAAgCT,EAAoB,CACpE,MAAMU,EAAYD,GAAcvB,EAAWc,CAAM,EAAE,WACnD,OAAO,OAAO,SAASU,CAAS,EAAI,KAAK,IAAI,GAAoB,KAAK,MAAMA,CAAS,CAAC,EAAIxB,EAAWc,CAAM,EAAE,UAC/G,CAHSL,EAAAa,EAAA",
6
- "names": ["KV_KEY_VERSION", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "KV_DOMAINS", "digest128", "input", "offsets", "out", "lane", "hash", "prime", "i", "__name", "sanitizeSegment", "segment", "trimmed", "buildKvKey", "domain", "parts", "prefix", "joined", "part", "full", "utf8ByteLength", "value", "clampTtl", "ttlSeconds", "effective"]
4
+ "sourcesContent": ["/**\n * Single-KV keyspace: one `CACHE` binding, domains separated by key prefix.\n *\n * Converged from `backend-runtime/src/kv/KvDomains.ts` (Durable-DAV,\n * Durable-DAV-Router, Edge-Sonic, Mail-Otter — the same table under four sets\n * of names). The names here are the three the family shares, and they are the\n * **default**, not a requirement: a repo whose cache vocabulary is genuinely\n * different supplies its own table, because the TTL and size policy below is\n * per-repo by definition — a cache holding album artwork keyed by a file's mtime\n * and a cache holding session profiles cannot share a lifetime, and renaming\n * call sites to fit a shared table would silently change when a library is\n * re-read from its origin.\n *\n * What does **not** become open is the *union*: a consumer's registry is still a\n * closed `Record<D, KvDomainDef>` over its own names, so a typo cannot create a\n * new keyspace, and prefix collisions still start the way the family has always\n * assumed they do.\n *\n * Rationale: D1 and the Durable Object stay the source of truth. KV is a\n * loss-tolerant, read-heavy cache only — a miss or eviction must always be\n * recoverable by recompute. Call sites never touch `env.CACHE` directly; they\n * go through `KvCache` with a registry so prefixes cannot collide and TTL/size\n * policy lives in one table.\n */\nconst KV_KEY_VERSION = 'v1';\nconst KV_MAX_KEY_LENGTH = 512;\nconst KV_MIN_TTL_SECONDS = 60;\n\ntype KvDomainName = 'session' | 'asset' | 'metadata';\n\ninterface KvDomainDef {\n ttlSeconds: number;\n maxValueBytes: number;\n description: string;\n}\n\n/**\n * A keyspace's whole policy, closed over its own domain names.\n *\n * `D` is the consumer's union, so `KV_DOMAINS` satisfies `KvDomains<KvDomainName>`\n * and a repo's own table satisfies `KvDomains<'songMeta' | 'albumArt'>` — with\n * both keeping the \"this name exists\" check that makes a typo a throw rather than\n * a new prefix.\n */\ntype KvDomains<D extends string = KvDomainName> = Readonly<Record<D, KvDomainDef>>;\n\nconst KV_DOMAINS: KvDomains = {\n session: {\n ttlSeconds: 300,\n maxValueBytes: 65_536,\n description: 'Per-user session/profile snapshots; invalidated on any credential change.',\n },\n asset: {\n ttlSeconds: 300,\n maxValueBytes: 10_485_760,\n description: 'Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write.',\n },\n metadata: {\n ttlSeconds: 120,\n maxValueBytes: 1_048_576,\n description: 'Listing/derived snapshots keyed by owner or collection; invalidated on mutation.',\n },\n};\n\n/**\n * 128-bit digest built from four independent FNV-1a lanes.\n *\n * Why not a single 32-bit FNV: `buildKvKey` falls back to a digest when a key\n * exceeds the platform's 512-character limit, and the longest keys embed a\n * user-controlled path or name. A 32-bit digest over a shared keyspace is\n * collision-searchable — someone who controls names in their own scope could\n * grind a colliding key and read another tenant's cached bytes. Four lanes over\n * the same bytes with different offsets/primes cost one extra pass and take a\n * birthday collision to ~2^64 work, which is not worth attacking.\n *\n * Synchronous on purpose: `buildKvKey` is called from sync cache-key builders.\n */\nfunction digest128(input: string): string {\n const LANES = 4;\n const offsets = [0x81_1c_9d_c5, 0xc2_b2_ae_35, 0x27_d4_eb_2f, 0x16_56_67_b1];\n let out = '';\n for (let lane = 0; lane < LANES; lane += 1) {\n let hash = offsets[lane];\n const prime = 0x01_00_01_93 + lane * 0x9e_37_79_b9;\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.codePointAt(i) ?? 0;\n hash = Math.imul(hash, prime);\n }\n out += (hash >>> 0).toString(16).padStart(8, '0');\n }\n return out;\n}\n\nfunction sanitizeSegment(segment: string): string {\n const trimmed = segment.trim();\n if (!trimmed) throw new Error('KV key segment must not be empty.');\n return encodeURIComponent(trimmed);\n}\n\n/**\n * The key for a value.\n *\n * `domains` is an optional trailing argument rather than a required one so the\n * common case — the kit's own vocabulary — reads as two arguments. It is the\n * **same registry** a `KvCache` holds: a key built against one table and a TTL\n * resolved against another is a cache that reads and writes under one policy and\n * reports another, which is the failure this threading exists to make impossible\n * rather than to document.\n */\nfunction buildKvKey<D extends string = KvDomainName>(\n domain: D,\n parts: readonly string[],\n domains: KvDomains<D> = KV_DOMAINS as KvDomains<D>,\n): string {\n if (!domains[domain]) throw new Error(`Unknown KV domain: ${domain}.`);\n if (parts.length === 0) throw new Error(`KV domain ${domain} requires at least one key part.`);\n const prefix = `${domain}:${KV_KEY_VERSION}:`;\n const joined = parts.map((part) => sanitizeSegment(part)).join(':');\n const full = prefix + joined;\n if (full.length <= KV_MAX_KEY_LENGTH) return full;\n // Deterministic overflow form. Note the consequence for invalidation: an\n // overflowing key does not start with the plain prefix, so `purgePrefix` on\n // the parts will not match it. Callers must therefore bound the key material\n // they cache (path length, identifier length) — the digest is a crash guard,\n // not a caching strategy.\n return `${prefix}h:${digest128(joined)}`;\n}\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Resolve a TTL, defaulting to the domain's own. Every domain declares a\n * required `ttlSeconds`, so there is no \"no TTL\" case to represent.\n */\nfunction clampTtl<D extends string = KvDomainName>(\n ttlSeconds: number | undefined,\n domain: D,\n domains: KvDomains<D> = KV_DOMAINS as KvDomains<D>,\n): number {\n const fallback = domains[domain]?.ttlSeconds ?? KV_DOMAINS.session.ttlSeconds;\n const effective = ttlSeconds ?? fallback;\n return Number.isFinite(effective) ? Math.max(KV_MIN_TTL_SECONDS, Math.floor(effective)) : fallback;\n}\n\nexport {\n KV_DOMAINS,\n KV_KEY_VERSION,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n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KAAK,GAAG,EAC5DC,EAAOH,EAASC,EACtB,OAAIE,EAAK,QAAU,IAA0BA,EAMtC,GAAGH,CAAM,KAAKhB,EAAUiB,CAAM,CAAC,EACxC,CAjBST,EAAAI,EAAA,cAmBT,SAASQ,EAAeC,EAAa,CACnC,OAAO,IAAI,YAAW,EAAG,OAAOA,CAAK,EAAE,MACzC,CAFSb,EAAAY,EAAA,kBAQT,SAASE,EACPC,EACAV,EACAE,EAAwBhB,EAA0B,CAElD,MAAMyB,EAAWT,EAAQF,CAAM,GAAG,YAAcd,EAAW,QAAQ,WAC7D0B,EAAYF,GAAcC,EAChC,OAAO,OAAO,SAASC,CAAS,EAAI,KAAK,IAAI,GAAoB,KAAK,MAAMA,CAAS,CAAC,EAAID,CAC5F,CARShB,EAAAc,EAAA",
6
+ "names": ["KV_KEY_VERSION", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "KV_DOMAINS", "digest128", "input", "offsets", "out", "lane", "hash", "prime", "i", "__name", "sanitizeSegment", "segment", "trimmed", "buildKvKey", "domain", "parts", "domains", "prefix", "joined", "part", "full", "utf8ByteLength", "value", "clampTtl", "ttlSeconds", "fallback", "effective"]
7
7
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The slice of an invocation's subrequest counter that the runtime layer needs.
3
+ *
4
+ * Structural rather than imported from `@rexezuge/shared`, because `runtime` is
5
+ * a zero-dependency base layer by rule and `@rexezuge/shared` is above it. A
6
+ * consumer that already holds a `SubrequestMeter` passes it here unchanged —
7
+ * `charge(count?: number, kind?: SubrequestKind)` satisfies this — and one that
8
+ * does not metering anything passes nothing.
9
+ *
10
+ * The kind is a plain `string` for the same reason: the runtime layer does not
11
+ * get to decide the taxonomy, and narrowing it here would make the shared
12
+ * counter's own `SubrequestKind` union an illegal argument at the call site.
13
+ */
14
+ interface SubrequestMeterLike {
15
+ charge(count?: number, kind?: string): void;
16
+ }
17
+ /**
18
+ * A meter that counts nothing, for a deployment that does not meter.
19
+ *
20
+ * A distinct value rather than a shared mutable singleton: there is nothing to
21
+ * share here, and a no-op object cannot be mutated by accident.
22
+ */
23
+ declare const UNMETERED: SubrequestMeterLike;
24
+ export { UNMETERED };
25
+ export type { SubrequestMeterLike };
26
+ //# sourceMappingURL=SubrequestMeterLike.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubrequestMeterLike.d.ts","sourceRoot":"","sources":["../../src/kv/SubrequestMeterLike.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,UAAU,mBAAmB;IAC3B,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7C;AAED;;;;;GAKG;AACH,QAAA,MAAM,SAAS,EAAE,mBAIhB,CAAC;AAEF,OAAO,EAAE,SAAS,EAAE,CAAC;AACrB,YAAY,EAAE,mBAAmB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var o=Object.defineProperty;var E=(c,e)=>o(c,"name",{value:e,configurable:!0});const r={charge:E(()=>{},"charge")};export{r as UNMETERED};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/kv/SubrequestMeterLike.ts"],
4
+ "sourcesContent": ["/**\n * The slice of an invocation's subrequest counter that the runtime layer needs.\n *\n * Structural rather than imported from `@rexezuge/shared`, because `runtime` is\n * a zero-dependency base layer by rule and `@rexezuge/shared` is above it. A\n * consumer that already holds a `SubrequestMeter` passes it here unchanged —\n * `charge(count?: number, kind?: SubrequestKind)` satisfies this — and one that\n * does not metering anything passes nothing.\n *\n * The kind is a plain `string` for the same reason: the runtime layer does not\n * get to decide the taxonomy, and narrowing it here would make the shared\n * counter's own `SubrequestKind` union an illegal argument at the call site.\n */\ninterface SubrequestMeterLike {\n charge(count?: number, kind?: string): void;\n}\n\n/**\n * A meter that counts nothing, for a deployment that does not meter.\n *\n * A distinct value rather than a shared mutable singleton: there is nothing to\n * share here, and a no-op object cannot be mutated by accident.\n */\nconst UNMETERED: SubrequestMeterLike = {\n charge: (): void => {\n // Deliberately empty.\n },\n};\n\nexport { UNMETERED };\nexport type { SubrequestMeterLike };\n"],
5
+ "mappings": "+EAuBA,MAAMA,EAAiC,CACrC,OAAQC,EAAA,IAAW,CAEnB,EAFQ",
6
+ "names": ["UNMETERED", "__name"]
7
+ }
@@ -1,5 +1,7 @@
1
- export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache.ts';
1
+ export { COOLDOWN_MS, FAILURE_THRESHOLD, KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES, resetBreakerForTests } from './KvCache.ts';
2
2
  export type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache.ts';
3
- export { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength, } from './KvDomains.ts';
4
- export type { KvDomainDef, KvDomainName } from './KvDomains.ts';
3
+ export { UNMETERED } from './SubrequestMeterLike.ts';
4
+ export type { SubrequestMeterLike } from './SubrequestMeterLike.ts';
5
+ export { KV_DOMAINS, KV_KEY_VERSION, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength, } from './KvDomains.ts';
6
+ export type { KvDomainDef, KvDomainName, KvDomains } from './KvDomains.ts';
5
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/kv/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC1E,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACjG,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,SAAS,EACT,eAAe,EACf,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/kv/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAChI,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACjG,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,YAAY,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EACL,UAAU,EACV,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,SAAS,EACT,eAAe,EACf,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/kv/index.js CHANGED
@@ -1 +1 @@
1
- import{KvCache as t,PURGE_LIST_LIMIT as K,PURGE_MAX_PAGES as E}from"./KvCache.js";import{KV_DOMAINS as T,KV_MAX_KEY_LENGTH as I,KV_MIN_TTL_SECONDS as L,buildKvKey as M,clampTtl as i,digest128 as m,sanitizeSegment as o,utf8ByteLength as r}from"./KvDomains.js";export{T as KV_DOMAINS,I as KV_MAX_KEY_LENGTH,L as KV_MIN_TTL_SECONDS,t as KvCache,K as PURGE_LIST_LIMIT,E as PURGE_MAX_PAGES,M as buildKvKey,i as clampTtl,m as digest128,o as sanitizeSegment,r as utf8ByteLength};
1
+ import{COOLDOWN_MS as E,FAILURE_THRESHOLD as t,KvCache as r,PURGE_LIST_LIMIT as K,PURGE_MAX_PAGES as S,resetBreakerForTests as T}from"./KvCache.js";import{UNMETERED as o}from"./SubrequestMeterLike.js";import{KV_DOMAINS as M,KV_KEY_VERSION as N,KV_MAX_KEY_LENGTH as O,KV_MIN_TTL_SECONDS as R,buildKvKey as m,clampTtl as s,digest128 as A,sanitizeSegment as D,utf8ByteLength as V}from"./KvDomains.js";export{E as COOLDOWN_MS,t as FAILURE_THRESHOLD,M as KV_DOMAINS,N as KV_KEY_VERSION,O as KV_MAX_KEY_LENGTH,R as KV_MIN_TTL_SECONDS,r as KvCache,K as PURGE_LIST_LIMIT,S as PURGE_MAX_PAGES,o as UNMETERED,m as buildKvKey,s as clampTtl,A as digest128,T as resetBreakerForTests,D as sanitizeSegment,V as utf8ByteLength};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/kv/index.ts"],
4
- "sourcesContent": ["export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache.ts';\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache.ts';\nexport {\n KV_DOMAINS,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n buildKvKey,\n clampTtl,\n digest128,\n sanitizeSegment,\n utf8ByteLength,\n} from './KvDomains.ts';\nexport type { KvDomainDef, KvDomainName } from './KvDomains.ts';\n"],
5
- "mappings": "AAAA,OAAS,WAAAA,EAAS,oBAAAC,EAAkB,mBAAAC,MAAuB,eAE3D,OACE,cAAAC,EACA,qBAAAC,EACA,sBAAAC,EACA,cAAAC,EACA,YAAAC,EACA,aAAAC,EACA,mBAAAC,EACA,kBAAAC,MACK",
6
- "names": ["KvCache", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "KV_DOMAINS", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "buildKvKey", "clampTtl", "digest128", "sanitizeSegment", "utf8ByteLength"]
4
+ "sourcesContent": ["export { COOLDOWN_MS, FAILURE_THRESHOLD, KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES, resetBreakerForTests } from './KvCache.ts';\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache.ts';\nexport { UNMETERED } from './SubrequestMeterLike.ts';\nexport type { SubrequestMeterLike } from './SubrequestMeterLike.ts';\nexport {\n KV_DOMAINS,\n KV_KEY_VERSION,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n buildKvKey,\n clampTtl,\n digest128,\n sanitizeSegment,\n utf8ByteLength,\n} from './KvDomains.ts';\nexport type { KvDomainDef, KvDomainName, KvDomains } from './KvDomains.ts';\n"],
5
+ "mappings": "AAAA,OAAS,eAAAA,EAAa,qBAAAC,EAAmB,WAAAC,EAAS,oBAAAC,EAAkB,mBAAAC,EAAiB,wBAAAC,MAA4B,eAEjH,OAAS,aAAAC,MAAiB,2BAE1B,OACE,cAAAC,EACA,kBAAAC,EACA,qBAAAC,EACA,sBAAAC,EACA,cAAAC,EACA,YAAAC,EACA,aAAAC,EACA,mBAAAC,EACA,kBAAAC,MACK",
6
+ "names": ["COOLDOWN_MS", "FAILURE_THRESHOLD", "KvCache", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "resetBreakerForTests", "UNMETERED", "KV_DOMAINS", "KV_KEY_VERSION", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "buildKvKey", "clampTtl", "digest128", "sanitizeSegment", "utf8ByteLength"]
7
7
  }