{"version":3,"sources":["../../src/stores/cloudflare-kv.ts","../../src/types.ts"],"sourcesContent":["import { type IdempotencyRecord, RECORD_STATUS_COMPLETED } from \"../types.js\";\nimport type { IdempotencyStore } from \"./types.js\";\n\nconst DEFAULT_TTL = 86400; // 24 hours in seconds\n\n/** Minimal KVNamespace subset used by kvStore (avoids @cloudflare/workers-types dependency). */\nexport interface KVNamespaceLike {\n\tget(key: string, options: { type: \"json\" }): Promise<unknown>;\n\tput(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;\n\tdelete(key: string): Promise<void>;\n}\n\nexport interface KVStoreOptions {\n\t/** Cloudflare Workers KV namespace binding. */\n\tnamespace: KVNamespaceLike;\n\t/** TTL in seconds (default: 86400 = 24h). KV minimum is 60 seconds. */\n\tttl?: number;\n}\n\n/**\n * KV is eventually consistent — lock() uses write-first with read-back\n * verification for best-effort race detection but cannot guarantee atomicity.\n * For strict concurrency guarantees, use d1Store or durableObjectStore.\n */\nexport function kvStore(options: KVStoreOptions): IdempotencyStore {\n\tconst { namespace: kv, ttl = DEFAULT_TTL } = options;\n\n\t// KV parses `type: \"json\"` internally and throws on corrupt data — treat as absent\n\tconst safeGetJson = async (key: string): Promise<unknown> => {\n\t\ttry {\n\t\t\treturn await kv.get(key, { type: \"json\" });\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\treturn {\n\t\tasync get(key) {\n\t\t\tconst raw = (await safeGetJson(key)) as (IdempotencyRecord & { lockId?: string }) | null;\n\t\t\tif (!raw) return undefined;\n\t\t\t// Strip internal lockId before returning to consumers\n\t\t\tconst { lockId: _, ...record } = raw;\n\t\t\treturn record;\n\t\t},\n\n\t\tasync lock(key, record) {\n\t\t\tconst existing = (await safeGetJson(key)) as IdempotencyRecord | null;\n\t\t\tif (existing) return false;\n\n\t\t\t// Embed a unique lockId to distinguish concurrent writers with the same fingerprint\n\t\t\tconst lockId = crypto.randomUUID();\n\t\t\tconst withLock = { ...record, lockId };\n\t\t\tlet serialized: string;\n\t\t\ttry {\n\t\t\t\tserialized = JSON.stringify(withLock);\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tawait kv.put(key, serialized, { expirationTtl: ttl });\n\n\t\t\t// Read-back verification using lockId (not fingerprint) for reliable race detection\n\t\t\tconst stored = (await safeGetJson(key)) as (IdempotencyRecord & { lockId?: string }) | null;\n\t\t\treturn stored?.lockId === lockId;\n\t\t},\n\n\t\tasync complete(key, response) {\n\t\t\tconst raw = (await safeGetJson(key)) as (IdempotencyRecord & { lockId?: string }) | null;\n\t\t\tif (!raw) return;\n\t\t\tconst { lockId: _, ...record } = raw;\n\t\t\trecord.status = RECORD_STATUS_COMPLETED;\n\t\t\trecord.response = response;\n\t\t\tconst elapsed = Math.floor((Date.now() - record.createdAt) / 1000);\n\t\t\tconst remaining = Math.max(1, ttl - elapsed);\n\t\t\tlet serialized: string;\n\t\t\ttry {\n\t\t\t\tserialized = JSON.stringify(record);\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait kv.put(key, serialized, { expirationTtl: remaining });\n\t\t},\n\n\t\tasync delete(key) {\n\t\t\tawait kv.delete(key);\n\t\t},\n\n\t\tasync purge() {\n\t\t\t// KV handles expiration automatically via expirationTtl — no manual purge needed\n\t\t\treturn 0;\n\t\t},\n\t};\n}\n","import type { Context, Env } from \"hono\";\nimport type { ProblemDetail } from \"./errors.js\";\nimport type { IdempotencyStore } from \"./stores/types.js\";\n\nexport const RECORD_STATUS_PROCESSING = \"processing\" as const;\nexport const RECORD_STATUS_COMPLETED = \"completed\" as const;\n\nexport interface IdempotencyEnv extends Env {\n\tVariables: {\n\t\tidempotencyKey: string | undefined;\n\t};\n}\n\nexport interface StoredResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n\tbody: string;\n}\n\nexport interface IdempotencyRecord {\n\tkey: string;\n\tfingerprint: string;\n\tstatus: \"processing\" | \"completed\";\n\tresponse?: StoredResponse;\n\tcreatedAt: number;\n}\n\nexport interface IdempotencyOptions {\n\tstore: IdempotencyStore;\n\theaderName?: string;\n\tfingerprint?: (c: Context) => string | Promise<string>;\n\trequired?: boolean;\n\tmethods?: string[];\n\tmaxKeyLength?: number;\n\t/**\n\t * Maximum request body size in bytes. Pre-checked via Content-Length header,\n\t * then enforced against actual body byte length.\n\t * Only applies when an Idempotency-Key header is present.\n\t * Requests without the key bypass this check regardless of this setting.\n\t */\n\tmaxBodySize?: number;\n\t/** Should be a lightweight, side-effect-free predicate. Avoid reading the request body. */\n\tskipRequest?: (c: Context) => boolean | Promise<boolean>;\n\t/** Return a Response with an error status (4xx/5xx). Returning 2xx bypasses idempotency guarantees. */\n\tonError?: (error: ProblemDetail, c: Context) => Response | Promise<Response>;\n\tcacheKeyPrefix?: string | ((c: Context) => string | Promise<string>);\n\t/**\n\t * Called when a cached response is about to be replayed.\n\t * Errors are swallowed — hooks must not affect request processing.\n\t * `key` is the raw header value; sanitize before logging to prevent log injection.\n\t */\n\tonCacheHit?: (key: string, c: Context) => void | Promise<void>;\n\t/**\n\t * Called when a new request acquires the lock (before the handler runs).\n\t * Fires on each lock acquisition, including retries after prior failures.\n\t * Errors are swallowed — hooks must not affect request processing.\n\t */\n\tonCacheMiss?: (key: string, c: Context) => void | Promise<void>;\n\t/**\n\t * Opt out of the multi-tenant safety warning.\n\t *\n\t * When `cacheKeyPrefix` is not set and `methods` includes any state-mutating\n\t * method (POST/PATCH/PUT/DELETE), the middleware emits a one-time\n\t * `console.warn` at factory construction time. Set this to `true` to\n\t * acknowledge that the deployment is single-tenant and silence the warning.\n\t *\n\t * @default false\n\t */\n\tdangerouslyAllowGlobalKeys?: boolean;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,0BAA0B;;;ADFvC,IAAM,cAAc;AAqBb,SAAS,QAAQ,SAA2C;AAClE,QAAM,EAAE,WAAW,IAAI,MAAM,YAAY,IAAI;AAG7C,QAAM,cAAc,OAA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