@vite-hub/kv 0.0.3 → 0.1.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 (39) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +40 -7
  3. package/dist/cli-Cniq99iX.d.ts +85 -0
  4. package/dist/cli.d.ts +15 -0
  5. package/dist/cli.js +448 -0
  6. package/dist/cloudflare-env-C5rM7kUY.js +74 -0
  7. package/dist/{config-C1ofyzSt.js → config-DR6_5ZwI.js} +37 -17
  8. package/dist/continuations-DPyH_vr1.js +63 -0
  9. package/dist/create-storage-29gMzf41.js +442 -0
  10. package/dist/cursor-history-dqYDlsaD.js +148 -0
  11. package/dist/deno-kv-CSYGvRx4.js +120 -0
  12. package/dist/driver-D9fI27jl.d.ts +94 -0
  13. package/dist/error-diagnostics-D_cQeZTi.js +82 -0
  14. package/dist/errors-Dc2oiW-Y.js +38 -0
  15. package/dist/errors.d.ts +12 -7
  16. package/dist/errors.js +2 -20
  17. package/dist/fs-lite-CbLKxLut.js +90 -0
  18. package/dist/index.d.ts +5 -4
  19. package/dist/index.js +119 -49
  20. package/dist/object-B1NW521B.js +7 -0
  21. package/dist/operations-ByuDE12r.js +1442 -0
  22. package/dist/operations-pn8_eGob.js +432 -0
  23. package/dist/operations-tNUdj3G4.d.ts +212 -0
  24. package/dist/operations.d.ts +68 -0
  25. package/dist/operations.js +455 -0
  26. package/dist/results-p7nPCnaJ.js +6 -0
  27. package/dist/runtime/cloudflare-kv.d.ts +6 -0
  28. package/dist/runtime/cloudflare-kv.js +100 -0
  29. package/dist/runtime/upstash-driver.d.ts +5 -2
  30. package/dist/runtime/upstash-driver.js +111 -2
  31. package/dist/types-CMDvN0Wr.d.ts +81 -0
  32. package/dist/utils2-Dsb9P4_2.js +28 -0
  33. package/dist/virtual-module.d.ts +6 -0
  34. package/dist/virtual.d.ts +2 -6
  35. package/dist/vite.d.ts +30 -10
  36. package/dist/vite.js +4910 -213
  37. package/package.json +57 -15
  38. package/dist/deno-kv-JnitV_jG.js +0 -54
  39. package/dist/types-Dg4l318i.d.ts +0 -60
@@ -1,2 +1,111 @@
1
- import upstash_default from "unstorage/drivers/upstash";
2
- export { upstash_default as default };
1
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-D_cQeZTi.js";
2
+ import { t as createKVContinuations } from "../continuations-DPyH_vr1.js";
3
+ import createDriver from "unstorage/drivers/upstash";
4
+ //#region src/runtime/upstash-driver.ts
5
+ const incrementScript = `
6
+ local existed = redis.call('EXISTS', KEYS[1])
7
+ local current = redis.call('GET', KEYS[1])
8
+ if current then
9
+ local negative = string.sub(current, 1, 1) == '-'
10
+ local digits = negative and string.sub(current, 2) or current
11
+ local boundary = negative and '9007199254740992' or '9007199254740991'
12
+ local beyond = #digits > #boundary or (#digits == #boundary and digits > boundary)
13
+ local at_positive_boundary = not negative and digits == boundary
14
+ if beyond or at_positive_boundary then
15
+ return redis.error_reply('Atomic KV increment exceeds the JavaScript safe integer range.')
16
+ end
17
+ end
18
+ local value = redis.call('INCR', KEYS[1])
19
+ if existed == 0 then
20
+ redis.call('EXPIRE', KEYS[1], ARGV[1])
21
+ end
22
+ return value
23
+ `;
24
+ function normalizeTTL(ttl) {
25
+ if (!Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
26
+ const seconds = Math.ceil(ttl);
27
+ if (!Number.isSafeInteger(seconds)) throw kvErrorDiagnostics.KV_INVALID_TTL();
28
+ return seconds;
29
+ }
30
+ function decodeCursor(cursor) {
31
+ if (!cursor) return { cursor: "0" };
32
+ try {
33
+ const value = JSON.parse(decodeURIComponent(cursor));
34
+ if (typeof value.cursor !== "string" || value.cursor.length === 0) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
35
+ return value;
36
+ } catch {
37
+ throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
38
+ }
39
+ }
40
+ function encodeCursor(cursor) {
41
+ return encodeURIComponent(JSON.stringify(cursor));
42
+ }
43
+ function escapeRedisGlob(value) {
44
+ return value.replaceAll(/([*?[\\\]])/g, "\\$1");
45
+ }
46
+ function createUpstashKVDriver(options) {
47
+ const driver = createDriver(options);
48
+ const maximumContinuationBytes = 1048576;
49
+ const expired = () => kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
50
+ const continuations = createKVContinuations({
51
+ expired,
52
+ maximumBytes: maximumContinuationBytes
53
+ });
54
+ const dispose = driver.dispose;
55
+ driver.dispose = async () => {
56
+ try {
57
+ await continuations.dispose();
58
+ } finally {
59
+ await dispose?.call(driver);
60
+ }
61
+ };
62
+ driver.getAndDeleteItem = async (key) => (await driver.getInstance()).getdel(key);
63
+ driver.incrementItem = async (key, ttl) => {
64
+ const value = Number(await (await driver.getInstance()).eval(incrementScript, [key], [String(normalizeTTL(ttl))]));
65
+ if (!Number.isSafeInteger(value)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "The counter exceeds the JavaScript safe integer range." });
66
+ return value;
67
+ };
68
+ function retainContinuation(keys, providerCursor) {
69
+ const encoder = new TextEncoder();
70
+ const bytes = keys.reduce((total, key) => total + encoder.encode(key).byteLength, 0);
71
+ if (bytes > maximumContinuationBytes) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Upstash KV scan overflow exceeds the continuation size limit." });
72
+ return continuations.retain({
73
+ cursor: providerCursor,
74
+ keys
75
+ }, bytes);
76
+ }
77
+ driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
78
+ const retained = cursor ? continuations.take(cursor) : void 0;
79
+ if (cursor && !retained && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(cursor)) throw expired();
80
+ let providerCursor;
81
+ let keys;
82
+ if (retained) {
83
+ providerCursor = retained.cursor;
84
+ keys = retained.keys;
85
+ } else {
86
+ const state = decodeCursor(cursor);
87
+ providerCursor = state.cursor;
88
+ const scanned = await (await driver.getInstance()).scan(providerCursor, {
89
+ count: limit,
90
+ match: `${escapeRedisGlob(prefix)}*`
91
+ });
92
+ providerCursor = String(scanned[0]);
93
+ if (providerCursor === state.cursor && providerCursor !== "0") throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Upstash KV scan returned a repeated pagination cursor." });
94
+ keys = [...new Set(scanned[1])];
95
+ }
96
+ const pageKeys = keys.slice(0, limit);
97
+ const overflow = keys.slice(limit);
98
+ if (overflow.length > 0) return {
99
+ keys: pageKeys,
100
+ cursor: await retainContinuation(overflow, providerCursor)
101
+ };
102
+ if (providerCursor === "0") return { keys: pageKeys };
103
+ return {
104
+ keys: pageKeys,
105
+ cursor: encodeCursor({ cursor: providerCursor })
106
+ };
107
+ };
108
+ return driver;
109
+ }
110
+ //#endregion
111
+ export { createUpstashKVDriver as default };
@@ -0,0 +1,81 @@
1
+ import { Result } from "@vite-hub/runtime";
2
+ //#region src/types.d.ts
3
+ type KVDriver = "cloudflare-kv-binding" | "deno-kv" | "upstash" | "fs-lite";
4
+ interface CloudflareKVStoreConfig {
5
+ driver: "cloudflare-kv-binding";
6
+ binding?: string;
7
+ /** Cloudflare KV namespace id. When omitted, the build reads the id recorded by `vitehub provision run`. */
8
+ namespaceId?: string;
9
+ /** Cloudflare KV namespace title that `vitehub provision run` finds or creates when `namespaceId` is not set. */
10
+ namespaceName?: string;
11
+ }
12
+ interface UpstashKVStoreConfig {
13
+ driver: "upstash";
14
+ token?: string;
15
+ url?: string;
16
+ }
17
+ interface DenoKVStoreConfig {
18
+ driver: "deno-kv";
19
+ path?: string;
20
+ }
21
+ interface FsLiteKVStoreConfig {
22
+ driver: "fs-lite";
23
+ base?: string;
24
+ }
25
+ type KVStoreConfig = CloudflareKVStoreConfig | DenoKVStoreConfig | UpstashKVStoreConfig | FsLiteKVStoreConfig;
26
+ interface ResolvedCloudflareKVStoreConfig extends CloudflareKVStoreConfig {
27
+ binding: string;
28
+ }
29
+ type ResolvedUpstashKVStoreConfig = Required<UpstashKVStoreConfig>;
30
+ interface ResolvedDenoKVStoreConfig extends DenoKVStoreConfig {
31
+ path?: string;
32
+ }
33
+ interface ResolvedFsLiteKVStoreConfig extends FsLiteKVStoreConfig {
34
+ base: string;
35
+ }
36
+ type ResolvedKVStoreConfig = ResolvedCloudflareKVStoreConfig | ResolvedDenoKVStoreConfig | ResolvedUpstashKVStoreConfig | ResolvedFsLiteKVStoreConfig;
37
+ type KVStoreName = "default" | (string & {});
38
+ interface KVStoresConfig {
39
+ stores: Record<string, KVStoreConfig>;
40
+ }
41
+ type KVModuleOptions = KVStoreConfig | KVStoresConfig | false;
42
+ interface ResolvedKVModuleOptions {
43
+ store: ResolvedKVStoreConfig;
44
+ stores?: Record<string, ResolvedKVStoreConfig>;
45
+ }
46
+ type KVOperation = "clear" | "del" | "get" | "getAndDelete" | "has" | "increment" | "keys" | "list" | "set";
47
+ /** Codes that KV operations return in the `[error, data]` tuple. Config errors throw instead. */
48
+ type KVErrorCode = "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_INVALID_TTL" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION";
49
+ interface KVListOptions {
50
+ /** Opaque continuation cursor returned by a previous page. */
51
+ cursor?: string;
52
+ /** Maximum number of keys to read. Must be a positive integer. */
53
+ limit: number;
54
+ prefix?: string;
55
+ }
56
+ interface KVListPage {
57
+ /** Provider-ordered keys. */
58
+ keys: string[];
59
+ /** Omitted when enumeration is complete. */
60
+ cursor?: string;
61
+ }
62
+ /**
63
+ * Each method returns `[error, data]`. `error.code` is one of the codes in the method type.
64
+ * Config errors, for example an unknown store name, throw.
65
+ */
66
+ interface KVStorage {
67
+ clear(base?: string, options?: unknown): Promise<Result<void, "KV_OPERATION_FAILED">>;
68
+ del(key: string, options?: unknown): Promise<Result<void, "KV_OPERATION_FAILED">>;
69
+ get<T = unknown>(key: string, options?: unknown): Promise<Result<T | null, "KV_OPERATION_FAILED">>;
70
+ /** Atomically returns and deletes a value when the configured store supports it. */
71
+ getAndDelete<T = unknown>(key: string): Promise<Result<T | null, "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
72
+ has(key: string, options?: unknown): Promise<Result<boolean, "KV_OPERATION_FAILED">>;
73
+ /** Atomically increments a counter. The TTL is applied only when the counter is created. */
74
+ increment(key: string, ttl: number): Promise<Result<number, "KV_INVALID_TTL" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
75
+ keys(base?: string, options?: unknown): Promise<Result<string[], "KV_OPERATION_FAILED">>;
76
+ list(options: KVListOptions): Promise<Result<KVListPage, "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_OPERATION_FAILED">>;
77
+ set<T = unknown>(key: string, value: T, options?: unknown): Promise<Result<void, "KV_OPERATION_FAILED">>;
78
+ store(name: KVStoreName): KVStorage;
79
+ }
80
+ //#endregion
81
+ export { ResolvedUpstashKVStoreConfig as _, KVErrorCode as a, KVModuleOptions as c, KVStoreConfig as d, ResolvedCloudflareKVStoreConfig as f, ResolvedKVStoreConfig as g, ResolvedKVModuleOptions as h, KVDriver as i, KVOperation as l, ResolvedFsLiteKVStoreConfig as m, DenoKVStoreConfig as n, KVListOptions as o, ResolvedDenoKVStoreConfig as p, FsLiteKVStoreConfig as r, KVListPage as s, CloudflareKVStoreConfig as t, KVStorage as u, UpstashKVStoreConfig as v };
@@ -0,0 +1,28 @@
1
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/_chunks/utils2.mjs
2
+ function normalizeKey(key) {
3
+ if (!key) return "";
4
+ return key.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || "";
5
+ }
6
+ function joinKeys(...keys) {
7
+ return normalizeKey(keys.join(":"));
8
+ }
9
+ function normalizeBaseKey(base) {
10
+ base = normalizeKey(base);
11
+ return base ? base + ":" : "";
12
+ }
13
+ function filterKeyByDepth(key, depth) {
14
+ if (depth === void 0) return true;
15
+ let substrCount = 0;
16
+ let index = key.indexOf(":");
17
+ while (index > -1) {
18
+ substrCount++;
19
+ index = key.indexOf(":", index + 1);
20
+ }
21
+ return substrCount <= depth;
22
+ }
23
+ function filterKeyByBase(key, base) {
24
+ if (base) return key.startsWith(base) && key[key.length - 1] !== "$";
25
+ return key[key.length - 1] !== "$";
26
+ }
27
+ //#endregion
28
+ export { normalizeKey as a, normalizeBaseKey as i, filterKeyByDepth as n, joinKeys as r, filterKeyByBase as t };
@@ -0,0 +1,6 @@
1
+ declare module "#vitehub/kv/config" {
2
+ export const hosting: string | undefined
3
+ export const kv: false | import("./index.js").ResolvedKVModuleOptions
4
+ const config: { hosting?: string, kv: typeof kv }
5
+ export default config
6
+ }
package/dist/virtual.d.ts CHANGED
@@ -1,6 +1,2 @@
1
- declare module "#vitehub/kv/config" {
2
- export const hosting: string | undefined
3
- export const kv: false | import("./index.js").ResolvedKVModuleOptions
4
- const config: { hosting?: string, kv: typeof kv }
5
- export default config
6
- }
1
+ /// <reference path="./virtual-module.d.ts" />
2
+ export {}
package/dist/vite.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { m as ResolvedKVModuleOptions, o as KVModuleOptions } from "./types-Dg4l318i.js";
1
+ import { c as KVModuleOptions, h as ResolvedKVModuleOptions } from "./types-CMDvN0Wr.js";
2
+ import { r as ViteHubCliPluginMetadata } from "./cli-Cniq99iX.js";
3
+ import { n as OperationContributionEntry } from "./operations-tNUdj3G4.js";
2
4
  import { Plugin } from "vite";
3
-
4
5
  //#region src/config.d.ts
5
6
  interface KVResolutionInput {
6
7
  env?: Record<string, string | undefined>;
@@ -8,27 +9,46 @@ interface KVResolutionInput {
8
9
  }
9
10
  //#endregion
10
11
  //#region src/vite-config.d.ts
11
- declare const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
12
- declare const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
12
+ export declare const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
13
+ export declare const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
13
14
  interface KVViteRuntimeConfig {
14
15
  hosting?: string;
15
16
  kv: false | ResolvedKVModuleOptions;
16
17
  }
17
- declare function resolveKVViteConfig(kv: KVModuleOptions | undefined, input?: KVResolutionInput): KVViteRuntimeConfig;
18
+ export declare function resolveKVViteConfig(kv: KVModuleOptions | undefined, input?: KVResolutionInput): KVViteRuntimeConfig;
18
19
  //#endregion
19
20
  //#region src/vite.d.ts
20
- interface KVVitePluginAPI {
21
+ export interface KVVitePluginAPI {
21
22
  getConfig: () => KVViteRuntimeConfig;
22
23
  }
23
- type KVVitePlugin = Plugin & {
24
+ export type KVVitePlugin = Plugin & {
24
25
  api: KVVitePluginAPI;
26
+ nitro: {
27
+ name: string;
28
+ setup: (nitro: {
29
+ options: NitroCloudflareKVTarget;
30
+ }) => void;
31
+ };
32
+ vitehub: ViteHubCliPluginMetadata & {
33
+ operations: readonly OperationContributionEntry[];
34
+ };
25
35
  };
26
- declare function hubKvOptionalPeerResolver(): Plugin;
27
- declare function hubKv(options?: KVModuleOptions): KVVitePlugin;
36
+ export declare function hubKvOptionalPeerResolver(): Plugin;
37
+ interface NitroCloudflareKVTarget {
38
+ cloudflare?: {
39
+ wrangler?: {
40
+ kv_namespaces?: Array<{
41
+ binding: string;
42
+ id?: string;
43
+ }>;
44
+ };
45
+ };
46
+ }
47
+ export declare function hubKv(options?: KVModuleOptions): KVVitePlugin;
28
48
  declare module "vite" {
29
49
  interface UserConfig {
30
50
  kv?: KVModuleOptions;
31
51
  }
32
52
  }
33
53
  //#endregion
34
- export { KVVitePlugin, KVVitePluginAPI, type KVViteRuntimeConfig, KV_VIRTUAL_CONFIG_ID, KV_VITE_PLUGIN_NAME, hubKv, hubKvOptionalPeerResolver, resolveKVViteConfig };
54
+ export type { KVViteRuntimeConfig };