@unkey/api 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +13 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.d.mts
CHANGED
|
@@ -216,7 +216,16 @@ declare class Unkey {
|
|
|
216
216
|
keyId: string;
|
|
217
217
|
}>>;
|
|
218
218
|
verify: (req: {
|
|
219
|
+
/**
|
|
220
|
+
* The key to verify
|
|
221
|
+
*/
|
|
219
222
|
key: string;
|
|
223
|
+
/**
|
|
224
|
+
* The api id to verify against
|
|
225
|
+
*
|
|
226
|
+
* This will be required soon.
|
|
227
|
+
*/
|
|
228
|
+
apiId?: string;
|
|
220
229
|
}) => Promise<Result<{
|
|
221
230
|
/**
|
|
222
231
|
* Whether or not this key is valid and has passed the ratelimit. If false you should not grant access to whatever the user is requesting
|
|
@@ -405,7 +414,10 @@ declare class Unkey {
|
|
|
405
414
|
* console.log(result)
|
|
406
415
|
* ```
|
|
407
416
|
*/
|
|
408
|
-
declare function verifyKey(
|
|
417
|
+
declare function verifyKey(req: string | {
|
|
418
|
+
key: string;
|
|
419
|
+
apiId: string;
|
|
420
|
+
}): Promise<{
|
|
409
421
|
result?: undefined;
|
|
410
422
|
error: UnkeyError;
|
|
411
423
|
} | {
|
package/dist/index.d.ts
CHANGED
|
@@ -216,7 +216,16 @@ declare class Unkey {
|
|
|
216
216
|
keyId: string;
|
|
217
217
|
}>>;
|
|
218
218
|
verify: (req: {
|
|
219
|
+
/**
|
|
220
|
+
* The key to verify
|
|
221
|
+
*/
|
|
219
222
|
key: string;
|
|
223
|
+
/**
|
|
224
|
+
* The api id to verify against
|
|
225
|
+
*
|
|
226
|
+
* This will be required soon.
|
|
227
|
+
*/
|
|
228
|
+
apiId?: string;
|
|
220
229
|
}) => Promise<Result<{
|
|
221
230
|
/**
|
|
222
231
|
* Whether or not this key is valid and has passed the ratelimit. If false you should not grant access to whatever the user is requesting
|
|
@@ -405,7 +414,10 @@ declare class Unkey {
|
|
|
405
414
|
* console.log(result)
|
|
406
415
|
* ```
|
|
407
416
|
*/
|
|
408
|
-
declare function verifyKey(
|
|
417
|
+
declare function verifyKey(req: string | {
|
|
418
|
+
key: string;
|
|
419
|
+
apiId: string;
|
|
420
|
+
}): Promise<{
|
|
409
421
|
result?: undefined;
|
|
410
422
|
error: UnkeyError;
|
|
411
423
|
} | {
|
package/dist/index.js
CHANGED
|
@@ -191,9 +191,9 @@ var Unkey = class {
|
|
|
191
191
|
};
|
|
192
192
|
|
|
193
193
|
// src/verify.ts
|
|
194
|
-
function verifyKey(
|
|
194
|
+
function verifyKey(req) {
|
|
195
195
|
const unkey = new Unkey({ token: "public" });
|
|
196
|
-
return unkey.keys.verify({ key });
|
|
196
|
+
return unkey.keys.verify(typeof req === "string" ? { key: req } : req);
|
|
197
197
|
}
|
|
198
198
|
// Annotate the CommonJS export names for ESM import in node:
|
|
199
199
|
0 && (module.exports = {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/verify.ts"],"sourcesContent":["export * from \"./client\";\nexport * from \"./verify\";\nexport * from \"./errors\";\n","import { UnkeyError } from \"./errors\";\n\nexport type UnkeyOptions = (\n | {\n token?: never;\n\n /**\n * The root key from unkey.dev.\n *\n * You can create/manage your root keys here:\n * https://unkey.dev/app/settings/root-keys\n */\n rootKey: string;\n }\n | {\n /**\n * The workspace key from unkey.dev\n *\n * @deprecated Use `rootKey`\n */\n token: string;\n rootKey?: never;\n }\n) & {\n /**\n * @default https://api.unkey.dev\n */\n baseUrl?: string;\n\n /**\n * Retry on network errors\n */\n retry?: {\n /**\n * How many attempts should be made\n * The maximum number of requests will be `attempts + 1`\n * `0` means no retries\n *\n * @default 5\n */\n attempts?: number;\n /**\n * Return how many milliseconds to wait until the next attempt is made\n *\n * @default `(retryCount) => Math.round(Math.exp(retryCount) * 10)),`\n */\n backoff?: (retryCount: number) => number;\n };\n /**\n * Customize the `fetch` cache behaviour\n */\n cache?: RequestCache;\n // some change\n};\n\ntype ApiRequest = {\n path: string[];\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n body?: unknown;\n query?: Record<string, string>;\n};\n\ntype Result<R> =\n | {\n result: R;\n error?: never;\n }\n | {\n result?: never;\n error: UnkeyError;\n };\n\nexport class Unkey {\n public readonly baseUrl: string;\n private readonly rootKey: string;\n private readonly cache?: RequestCache;\n\n public readonly retry: {\n attempts: number;\n backoff: (retryCount: number) => number;\n };\n\n constructor(opts: UnkeyOptions) {\n this.baseUrl = opts.baseUrl ?? \"https://api.unkey.dev\";\n this.rootKey = opts.rootKey ?? opts.token;\n\n this.cache = opts.cache;\n /**\n * Even though typescript should prevent this, some people still pass undefined or empty strings\n */\n if (!this.rootKey) {\n throw new Error(\n \"Unkey root key must be set, maybe you passed in `undefined` or an empty string?\",\n );\n }\n\n this.retry = {\n attempts: opts.retry?.attempts ?? 5,\n backoff: opts.retry?.backoff ?? ((n) => Math.round(Math.exp(n) * 10)),\n };\n }\n\n private async fetch<TResult>(req: ApiRequest): Promise<Result<TResult>> {\n let res: Response | null = null;\n let err: Error | null = null;\n for (let i = 0; i <= this.retry.attempts; i++) {\n const url = new URL(`${this.baseUrl}/${req.path.join(\"/\")}`);\n if (req.query) {\n for (const [k, v] of Object.entries(req.query)) {\n url.searchParams.set(k, v);\n }\n }\n res = await fetch(url, {\n method: req.method,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.rootKey}`,\n },\n cache: this.cache,\n body: JSON.stringify(req.body),\n }).catch((e: Error) => {\n err = e;\n return null; // set `res` to `null`\n });\n if (res?.ok) {\n return { result: await res.json() };\n }\n const backoff = this.retry.backoff(i);\n console.debug(\n \"attempt %d of %d to reach %s failed, retrying in %d ms: %s\",\n i + 1,\n this.retry.attempts + 1,\n url,\n backoff,\n // @ts-ignore I don't understand why `err` is `never`\n err?.message,\n );\n await new Promise((r) => setTimeout(r, backoff));\n }\n\n if (res) {\n return { error: await res.json() };\n }\n\n return {\n error: {\n code: \"FETCH_ERROR\",\n // @ts-ignore I don't understand why `err` is `never`\n message: err?.message ?? \"No response\",\n docs: \"https://developer.mozilla.org/en-US/docs/Web/API/fetch\",\n requestId: \"N/A\",\n },\n };\n }\n\n public get keys() {\n return {\n create: async (req: {\n /**\n * Provide a name to this key if you want for later reference\n */\n name?: string;\n /**\n * Choose an API where this key should be created.\n */\n apiId: string;\n /**\n * To make it easier for your users to understand which product an api key belongs to, you can add prefix them.\n *\n * For example Stripe famously prefixes their customer ids with cus_ or their api keys with sk_live_.\n *\n * The underscore is automtically added if you are defining a prefix, for example: \"prefix\": \"abc\" will result in a key like abc_xxxxxxxxx\n */\n prefix?: string;\n\n /**\n * The bytelength used to generate your key determines its entropy as well as its length. Higher is better, but keys become longer and more annoying to handle.\n *\n * The default is 16 bytes, or 2128 possible combinations\n */\n byteLength?: number;\n /**\n * Your user’s Id. This will provide a link between Unkey and your customer record.\n *\n * When validating a key, we will return this back to you, so you can clearly identify your user from their api key.\n */\n ownerId?: string;\n /**\n * This is a place for dynamic meta data, anything that feels useful for you should go here\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown;\n /**\n * You can auto expire keys by providing a unix timestamp in milliseconds.\n *\n * Once keys expire they will automatically be deleted and are no longer valid.\n */\n expires?: number;\n\n /**\n * Unkey comes with per-key ratelimiting out of the box.\n *\n * @see https://unkey.dev/docs/features/ratelimiting\n */\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n /**\n * The total amount of burstable requests.\n */\n limit: number;\n\n /**\n * How many tokens to refill during each refillInterval\n */\n refillRate: number;\n\n /**\n * Determines the speed at which tokens are refilled.\n * In milliseconds.\n */\n refillInterval: number;\n };\n\n /**\n * Unkey allows you to set/update usage limits on individual keys\n *\n * @see https://unkey.dev/docs/features/remaining\n */\n remaining?: number;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"keys\"],\n method: \"POST\",\n body: req,\n });\n },\n update: async (req: {\n /**\n * The id of the key to update.\n */\n keyId: string;\n /**\n * Update the name\n */\n name?: string | null;\n\n /**\n * Update the owner id\n */\n ownerId?: string | null;\n /**\n * This is a place for dynamic meta data, anything that feels useful for you should go here\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown | null;\n /**\n * Update the expiration time, Unix timstamp in milliseconds\n *\n *\n */\n expires?: number | null;\n\n /**\n * Update the ratelimit\n *\n * @see https://unkey.dev/docs/features/ratelimiting\n */\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n /**\n * The total amount of burstable requests.\n */\n limit: number;\n\n /**\n * How many tokens to refill during each refillInterval\n */\n refillRate: number;\n\n /**\n * Determines the speed at which tokens are refilled.\n * In milliseconds.\n */\n refillInterval: number;\n } | null;\n\n /**\n * Update the remaining verifications.\n *\n * @see https://unkey.dev/docs/features/remaining\n */\n remaining?: number | null;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"keys\", req.keyId],\n method: \"PUT\",\n body: req,\n });\n },\n verify: async (req: { key: string }): Promise<\n Result<{\n /**\n * Whether or not this key is valid and has passed the ratelimit. If false you should not grant access to whatever the user is requesting\n */\n valid: boolean;\n\n /**\n * If you have set an ownerId on this key it is returned here. You can use this to clearly authenticate a user in your system.\n */\n ownerId?: string;\n\n /**\n * This is the meta data you have set when creating the key.\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown;\n\n /**\n * Unix timestamp in milliseconds when this key expires\n * Only available when the key automatically expires\n */\n expires?: number;\n\n /**\n * How many verifications are remaining after the current request.\n */\n remaining?: number;\n\n /**\n * Ratelimit data if the key is ratelimited.\n */\n ratelimit?: {\n /**\n * The maximum number of requests for bursting.\n */\n limit: number;\n\n /**\n * How many requests are remaining until `reset`\n */\n remaining: number;\n\n /**\n * Unix timestamp in millisecond when the ratelimit is refilled.\n */\n reset: number;\n };\n\n /**\n * Machine readable code that explains why a key is invalid or could not be verified\n */\n code?: \"NOT_FOUND\" | \"FORBIDDEN\" | \"RATELIMITED\" | \"KEY_USAGE_EXCEEDED\";\n }>\n > => {\n return await this.fetch<{\n valid: boolean;\n ownerId?: string;\n meta?: unknown;\n }>({\n path: [\"v1\", \"keys\", \"verify\"],\n method: \"POST\",\n body: req,\n });\n },\n revoke: async (req: { keyId: string }): Promise<Result<void>> => {\n return await this.fetch<void>({\n path: [\"v1\", \"keys\", req.keyId],\n method: \"DELETE\",\n });\n },\n };\n }\n\n public get apis() {\n return {\n create: async (req: {\n /**\n * A name for you to identify your API.\n */\n name: string;\n }): Promise<\n Result<{\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }>\n > => {\n return await this.fetch({\n path: [\"v1\", \"apis.createApi\"],\n method: \"POST\",\n body: req,\n });\n },\n remove: async (req: {\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }): Promise<\n Result<{\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }>\n > => {\n return await this.fetch({\n path: [\"v1\", \"apis.removeApi\"],\n method: \"POST\",\n body: req,\n });\n },\n get: async (req: {\n /**\n * The api id\n */\n apiId: string;\n }): Promise<Result<{ id: string; name: string; workspaceId: string }>> => {\n return await this.fetch({\n path: [\"v1\", \"apis\", req.apiId],\n method: \"GET\",\n });\n },\n\n listKeys: async (req: {\n /**\n * The api id\n */\n apiId: string;\n\n /**\n * Limit the number of returned keys, the maximum is 100.\n *\n * @default 100\n */\n limit?: number;\n\n /**\n * Specify an offset for pagination.\n * @example:\n * An offset of 4 will skip the first 4 keys and return keys starting at the 5th position.\n *\n * @default 0\n */\n offset?: number;\n\n /**\n * If provided, this will only return keys where the ownerId matches.\n */\n ownerId?: string;\n }): Promise<\n Result<{\n keys: {\n id: string;\n apiId: string;\n ownerId?: string;\n workspaceId: string;\n start: string;\n createdAt: number;\n name?: string;\n expires?: number;\n remaining?: number;\n meta?: unknown;\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n limit: number;\n refillRate: number;\n refillInterval: number;\n };\n }[];\n total: number;\n }>\n > => {\n const query: Record<string, string> = {};\n if (typeof req.limit !== \"undefined\") {\n query.limit = req.limit.toString();\n }\n if (typeof req.offset !== \"undefined\") {\n query.offset = req.offset.toString();\n }\n if (typeof req.ownerId !== \"undefined\") {\n query.ownerId = req.ownerId;\n }\n\n return await this.fetch({\n path: [\"v1\", \"apis\", req.apiId, \"keys\"],\n method: \"GET\",\n query,\n });\n },\n };\n }\n /**\n * Must be authenticated via app token\n */\n public get _internal() {\n return {\n createRootKey: async (req: {\n /**\n * Provide a name to this key if you want for later reference\n */\n name?: string;\n\n /**\n * You can auto expire keys by providing a unix timestamp in milliseconds.\n *\n * Once keys expire they will automatically be deleted and are no longer valid.\n */\n expires?: number;\n\n // Used to create root keys from the frontend, please ignore\n forWorkspaceId: string;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"internal\", \"rootkeys\"],\n method: \"POST\",\n body: req,\n });\n },\n deleteRootKey: async (req: {\n /**\n * Used to create root keys from the frontend, please ignore\n */\n keyId: string;\n }): Promise<Result<void>> => {\n return await this.fetch<void>({\n path: [\"v1\", \"internal.removeRootKey\"],\n method: \"POST\",\n body: req,\n });\n },\n };\n }\n}\n","import { Unkey } from \"./client\";\n\n/**\n * Verify a key\n *\n * @example\n * ```ts\n * const { result, error } = await verifyKey(\"key_123\")\n * if (error){\n * // handle potential network or bad request error\n * // a link to our docs will be in the `error.docs` field\n * console.error(error.message)\n * return\n * }\n * if (!result.valid) {\n * // do not grant access\n * return\n * }\n *\n * // process request\n * console.log(result)\n * ```\n */\nexport function verifyKey(key: string) {\n // yes this is empty to make typescript happy but we don't need a token for verifying keys\n // it's not the cleanest but it works for now :)\n const unkey = new Unkey({ token: \"public\" });\n return unkey.keys.verify({ key });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwEO,IAAM,QAAN,MAAY;AAAA,EACD;AAAA,EACC;AAAA,EACA;AAAA,EAED;AAAA,EAKhB,YAAY,MAAoB;AAC9B,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,UAAU,KAAK,WAAW,KAAK;AAEpC,SAAK,QAAQ,KAAK;AAIlB,QAAI,CAAC,KAAK,SAAS;AACjB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,QAAQ;AAAA,MACX,UAAU,KAAK,OAAO,YAAY;AAAA,MAClC,SAAS,KAAK,OAAO,YAAY,CAAC,MAAM,KAAK,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE;AAAA,IACrE;AAAA,EACF;AAAA,EAEA,MAAc,MAAe,KAA2C;AACtE,QAAI,MAAuB;AAC3B,QAAI,MAAoB;AACxB,aAAS,IAAI,GAAG,KAAK,KAAK,MAAM,UAAU,KAAK;AAC7C,YAAM,MAAM,IAAI,IAAI,GAAG,KAAK,OAAO,IAAI,IAAI,KAAK,KAAK,GAAG,CAAC,EAAE;AAC3D,UAAI,IAAI,OAAO;AACb,mBAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,IAAI,KAAK,GAAG;AAC9C,cAAI,aAAa,IAAI,GAAG,CAAC;AAAA,QAC3B;AAAA,MACF;AACA,YAAM,MAAM,MAAM,KAAK;A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AA,UACR;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAIA,IAAW,YAAY;AACrB,WAAO;AAAA,MACL,eAAe,OAAO,QAeiC;AACrD,eAAO,MAAM,KAAK,MAAsC;AAAA,UACtD,MAAM,CAAC,MAAM,YAAY,UAAU;AAAA,UACnC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,MACA,eAAe,OAAO,QAKO;AAC3B,eAAO,MAAM,KAAK,MAAY;AAAA,UAC5B,MAAM,CAAC,MAAM,wBAAwB;AAAA,UACrC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;AC1hBO,SAAS,UAAU,KAAa;AAGrC,QAAM,QAAQ,IAAI,MAAM,EAAE,OAAO,SAAS,CAAC;AAC3C,SAAO,MAAM,KAAK,OAAO,EAAE,IAAI,CAAC;AAClC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/verify.ts"],"sourcesContent":["export * from \"./client\";\nexport * from \"./verify\";\nexport * from \"./errors\";\n","import { UnkeyError } from \"./errors\";\n\nexport type UnkeyOptions = (\n | {\n token?: never;\n\n /**\n * The root key from unkey.dev.\n *\n * You can create/manage your root keys here:\n * https://unkey.dev/app/settings/root-keys\n */\n rootKey: string;\n }\n | {\n /**\n * The workspace key from unkey.dev\n *\n * @deprecated Use `rootKey`\n */\n token: string;\n rootKey?: never;\n }\n) & {\n /**\n * @default https://api.unkey.dev\n */\n baseUrl?: string;\n\n /**\n * Retry on network errors\n */\n retry?: {\n /**\n * How many attempts should be made\n * The maximum number of requests will be `attempts + 1`\n * `0` means no retries\n *\n * @default 5\n */\n attempts?: number;\n /**\n * Return how many milliseconds to wait until the next attempt is made\n *\n * @default `(retryCount) => Math.round(Math.exp(retryCount) * 10)),`\n */\n backoff?: (retryCount: number) => number;\n };\n /**\n * Customize the `fetch` cache behaviour\n */\n cache?: RequestCache;\n // some change\n};\n\ntype ApiRequest = {\n path: string[];\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n body?: unknown;\n query?: Record<string, string>;\n};\n\ntype Result<R> =\n | {\n result: R;\n error?: never;\n }\n | {\n result?: never;\n error: UnkeyError;\n };\n\nexport class Unkey {\n public readonly baseUrl: string;\n private readonly rootKey: string;\n private readonly cache?: RequestCache;\n\n public readonly retry: {\n attempts: number;\n backoff: (retryCount: number) => number;\n };\n\n constructor(opts: UnkeyOptions) {\n this.baseUrl = opts.baseUrl ?? \"https://api.unkey.dev\";\n this.rootKey = opts.rootKey ?? opts.token;\n\n this.cache = opts.cache;\n /**\n * Even though typescript should prevent this, some people still pass undefined or empty strings\n */\n if (!this.rootKey) {\n throw new Error(\n \"Unkey root key must be set, maybe you passed in `undefined` or an empty string?\",\n );\n }\n\n this.retry = {\n attempts: opts.retry?.attempts ?? 5,\n backoff: opts.retry?.backoff ?? ((n) => Math.round(Math.exp(n) * 10)),\n };\n }\n\n private async fetch<TResult>(req: ApiRequest): Promise<Result<TResult>> {\n let res: Response | null = null;\n let err: Error | null = null;\n for (let i = 0; i <= this.retry.attempts; i++) {\n const url = new URL(`${this.baseUrl}/${req.path.join(\"/\")}`);\n if (req.query) {\n for (const [k, v] of Object.entries(req.query)) {\n url.searchParams.set(k, v);\n }\n }\n res = await fetch(url, {\n method: req.method,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.rootKey}`,\n },\n cache: this.cache,\n body: JSON.stringify(req.body),\n }).catch((e: Error) => {\n err = e;\n return null; // set `res` to `null`\n });\n if (res?.ok) {\n return { result: (await res.json()) as TResult };\n }\n const backoff = this.retry.backoff(i);\n console.debug(\n \"attempt %d of %d to reach %s failed, retrying in %d ms: %s\",\n i + 1,\n this.retry.attempts + 1,\n url,\n backoff,\n // @ts-ignore I don't understand why `err` is `never`\n err?.message,\n );\n await new Promise((r) => setTimeout(r, backoff));\n }\n\n if (res) {\n return { error: (await res.json()) as UnkeyError };\n }\n\n return {\n error: {\n code: \"FETCH_ERROR\",\n // @ts-ignore I don't understand why `err` is `never`\n message: err?.message ?? \"No response\",\n docs: \"https://developer.mozilla.org/en-US/docs/Web/API/fetch\",\n requestId: \"N/A\",\n },\n };\n }\n\n public get keys() {\n return {\n create: async (req: {\n /**\n * Provide a name to this key if you want for later reference\n */\n name?: string;\n /**\n * Choose an API where this key should be created.\n */\n apiId: string;\n /**\n * To make it easier for your users to understand which product an api key belongs to, you can add prefix them.\n *\n * For example Stripe famously prefixes their customer ids with cus_ or their api keys with sk_live_.\n *\n * The underscore is automtically added if you are defining a prefix, for example: \"prefix\": \"abc\" will result in a key like abc_xxxxxxxxx\n */\n prefix?: string;\n\n /**\n * The bytelength used to generate your key determines its entropy as well as its length. Higher is better, but keys become longer and more annoying to handle.\n *\n * The default is 16 bytes, or 2128 possible combinations\n */\n byteLength?: number;\n /**\n * Your user’s Id. This will provide a link between Unkey and your customer record.\n *\n * When validating a key, we will return this back to you, so you can clearly identify your user from their api key.\n */\n ownerId?: string;\n /**\n * This is a place for dynamic meta data, anything that feels useful for you should go here\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown;\n /**\n * You can auto expire keys by providing a unix timestamp in milliseconds.\n *\n * Once keys expire they will automatically be deleted and are no longer valid.\n */\n expires?: number;\n\n /**\n * Unkey comes with per-key ratelimiting out of the box.\n *\n * @see https://unkey.dev/docs/features/ratelimiting\n */\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n /**\n * The total amount of burstable requests.\n */\n limit: number;\n\n /**\n * How many tokens to refill during each refillInterval\n */\n refillRate: number;\n\n /**\n * Determines the speed at which tokens are refilled.\n * In milliseconds.\n */\n refillInterval: number;\n };\n\n /**\n * Unkey allows you to set/update usage limits on individual keys\n *\n * @see https://unkey.dev/docs/features/remaining\n */\n remaining?: number;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"keys\"],\n method: \"POST\",\n body: req,\n });\n },\n update: async (req: {\n /**\n * The id of the key to update.\n */\n keyId: string;\n /**\n * Update the name\n */\n name?: string | null;\n\n /**\n * Update the owner id\n */\n ownerId?: string | null;\n /**\n * This is a place for dynamic meta data, anything that feels useful for you should go here\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown | null;\n /**\n * Update the expiration time, Unix timstamp in milliseconds\n *\n *\n */\n expires?: number | null;\n\n /**\n * Update the ratelimit\n *\n * @see https://unkey.dev/docs/features/ratelimiting\n */\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n /**\n * The total amount of burstable requests.\n */\n limit: number;\n\n /**\n * How many tokens to refill during each refillInterval\n */\n refillRate: number;\n\n /**\n * Determines the speed at which tokens are refilled.\n * In milliseconds.\n */\n refillInterval: number;\n } | null;\n\n /**\n * Update the remaining verifications.\n *\n * @see https://unkey.dev/docs/features/remaining\n */\n remaining?: number | null;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"keys\", req.keyId],\n method: \"PUT\",\n body: req,\n });\n },\n verify: async (req: {\n /**\n * The key to verify\n */\n key: string;\n\n /**\n * The api id to verify against\n *\n * This will be required soon.\n */\n apiId?: string;\n }): Promise<\n Result<{\n /**\n * Whether or not this key is valid and has passed the ratelimit. If false you should not grant access to whatever the user is requesting\n */\n valid: boolean;\n\n /**\n * If you have set an ownerId on this key it is returned here. You can use this to clearly authenticate a user in your system.\n */\n ownerId?: string;\n\n /**\n * This is the meta data you have set when creating the key.\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown;\n\n /**\n * Unix timestamp in milliseconds when this key expires\n * Only available when the key automatically expires\n */\n expires?: number;\n\n /**\n * How many verifications are remaining after the current request.\n */\n remaining?: number;\n\n /**\n * Ratelimit data if the key is ratelimited.\n */\n ratelimit?: {\n /**\n * The maximum number of requests for bursting.\n */\n limit: number;\n\n /**\n * How many requests are remaining until `reset`\n */\n remaining: number;\n\n /**\n * Unix timestamp in millisecond when the ratelimit is refilled.\n */\n reset: number;\n };\n\n /**\n * Machine readable code that explains why a key is invalid or could not be verified\n */\n code?: \"NOT_FOUND\" | \"FORBIDDEN\" | \"RATELIMITED\" | \"KEY_USAGE_EXCEEDED\";\n }>\n > => {\n return await this.fetch<{\n valid: boolean;\n ownerId?: string;\n meta?: unknown;\n }>({\n path: [\"v1\", \"keys\", \"verify\"],\n method: \"POST\",\n body: req,\n });\n },\n revoke: async (req: { keyId: string }): Promise<Result<void>> => {\n return await this.fetch<void>({\n path: [\"v1\", \"keys\", req.keyId],\n method: \"DELETE\",\n });\n },\n };\n }\n\n public get apis() {\n return {\n create: async (req: {\n /**\n * A name for you to identify your API.\n */\n name: string;\n }): Promise<\n Result<{\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }>\n > => {\n return await this.fetch({\n path: [\"v1\", \"apis.createApi\"],\n method: \"POST\",\n body: req,\n });\n },\n remove: async (req: {\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }): Promise<\n Result<{\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }>\n > => {\n return await this.fetch({\n path: [\"v1\", \"apis.removeApi\"],\n method: \"POST\",\n body: req,\n });\n },\n get: async (req: {\n /**\n * The api id\n */\n apiId: string;\n }): Promise<Result<{ id: string; name: string; workspaceId: string }>> => {\n return await this.fetch({\n path: [\"v1\", \"apis\", req.apiId],\n method: \"GET\",\n });\n },\n\n listKeys: async (req: {\n /**\n * The api id\n */\n apiId: string;\n\n /**\n * Limit the number of returned keys, the maximum is 100.\n *\n * @default 100\n */\n limit?: number;\n\n /**\n * Specify an offset for pagination.\n * @example:\n * An offset of 4 will skip the first 4 keys and return keys starting at the 5th position.\n *\n * @default 0\n */\n offset?: number;\n\n /**\n * If provided, this will only return keys where the ownerId matches.\n */\n ownerId?: string;\n }): Promise<\n Result<{\n keys: {\n id: string;\n apiId: string;\n ownerId?: string;\n workspaceId: string;\n start: string;\n createdAt: number;\n name?: string;\n expires?: number;\n remaining?: number;\n meta?: unknown;\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n limit: number;\n refillRate: number;\n refillInterval: number;\n };\n }[];\n total: number;\n }>\n > => {\n const query: Record<string, string> = {};\n if (typeof req.limit !== \"undefined\") {\n query.limit = req.limit.toString();\n }\n if (typeof req.offset !== \"undefined\") {\n query.offset = req.offset.toString();\n }\n if (typeof req.ownerId !== \"undefined\") {\n query.ownerId = req.ownerId;\n }\n\n return await this.fetch({\n path: [\"v1\", \"apis\", req.apiId, \"keys\"],\n method: \"GET\",\n query,\n });\n },\n };\n }\n /**\n * Must be authenticated via app token\n */\n public get _internal() {\n return {\n createRootKey: async (req: {\n /**\n * Provide a name to this key if you want for later reference\n */\n name?: string;\n\n /**\n * You can auto expire keys by providing a unix timestamp in milliseconds.\n *\n * Once keys expire they will automatically be deleted and are no longer valid.\n */\n expires?: number;\n\n // Used to create root keys from the frontend, please ignore\n forWorkspaceId: string;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"internal\", \"rootkeys\"],\n method: \"POST\",\n body: req,\n });\n },\n deleteRootKey: async (req: {\n /**\n * Used to create root keys from the frontend, please ignore\n */\n keyId: string;\n }): Promise<Result<void>> => {\n return await this.fetch<void>({\n path: [\"v1\", \"internal.removeRootKey\"],\n method: \"POST\",\n body: req,\n });\n },\n };\n }\n}\n","import { Unkey } from \"./client\";\n\n/**\n * Verify a key\n *\n * @example\n * ```ts\n * const { result, error } = await verifyKey(\"key_123\")\n * if (error){\n * // handle potential network or bad request error\n * // a link to our docs will be in the `error.docs` field\n * console.error(error.message)\n * return\n * }\n * if (!result.valid) {\n * // do not grant access\n * return\n * }\n *\n * // process request\n * console.log(result)\n * ```\n */\nexport function verifyKey(req: string | { key: string; apiId: string }) {\n // yes this is empty to make typescript happy but we don't need a token for verifying keys\n // it's not the cleanest but it works for now :)\n const unkey = new Unkey({ token: \"public\" });\n return unkey.keys.verify(typeof req === \"string\" ? { key: req } : req);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwEO,IAAM,QAAN,MAAY;AAAA,EACD;AAAA,EACC;AAAA,EACA;AAAA,EAED;AAAA,EAKhB,YAAY,MAAoB;AAC9B,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,UAAU,KAAK,WAAW,KAAK;AAEpC,SAAK,QAAQ,KAAK;AAIlB,QAAI,CAAC,KAAK,SAAS;AACjB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,QAAQ;AAAA,MACX,UAAU,KAAK,OAAO,YAAY;AAAA,MAClC,SAAS,KAAK,OAAO,YAAY,CAAC,MAAM,KAAK,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE;AAAA,IACrE;AAAA,EACF;AAAA,EAEA,MAAc,MAAe,KAA2C;AACtE,QAAI,MAAuB;AAC3B,QAAI,MAAoB;AACxB,aAAS,IAAI,GAAG,KAAK,KAAK,MAAM,UAAU,KAAK;AAC7C,YAAM,MAAM,IAAI,IAAI,GAAG,KAAK,OAAO,IAAI,IAAI,KAAK,KAAK,GAAG,CAAC,EAAE;AAC3D,UAAI,IAAI,OAAO;AACb,mBAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,IAAI,KAAK,GAAG;AAC9C,cAAI,aAAa,IAAI,GAAG,CAAC;AAAA,QAC3B;AAAA,MACF;AACA,YAAM,MAAM,MAAM,KAAK;AA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AA,UACR;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAIA,IAAW,YAAY;AACrB,WAAO;AAAA,MACL,eAAe,OAAO,QAeiC;AACrD,eAAO,MAAM,KAAK,MAAsC;AAAA,UACtD,MAAM,CAAC,MAAM,YAAY,UAAU;AAAA,UACnC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,MACA,eAAe,OAAO,QAKO;AAC3B,eAAO,MAAM,KAAK,MAAY;AAAA,UAC5B,MAAM,CAAC,MAAM,wBAAwB;AAAA,UACrC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;ACtiBO,SAAS,UAAU,KAA8C;AAGtE,QAAM,QAAQ,IAAI,MAAM,EAAE,OAAO,SAAS,CAAC;AAC3C,SAAO,MAAM,KAAK,OAAO,OAAO,QAAQ,WAAW,EAAE,KAAK,IAAI,IAAI,GAAG;AACvE;","names":[]}
|
package/dist/index.mjs
CHANGED
|
@@ -164,9 +164,9 @@ var Unkey = class {
|
|
|
164
164
|
};
|
|
165
165
|
|
|
166
166
|
// src/verify.ts
|
|
167
|
-
function verifyKey(
|
|
167
|
+
function verifyKey(req) {
|
|
168
168
|
const unkey = new Unkey({ token: "public" });
|
|
169
|
-
return unkey.keys.verify({ key });
|
|
169
|
+
return unkey.keys.verify(typeof req === "string" ? { key: req } : req);
|
|
170
170
|
}
|
|
171
171
|
export {
|
|
172
172
|
Unkey,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/verify.ts"],"sourcesContent":["import { UnkeyError } from \"./errors\";\n\nexport type UnkeyOptions = (\n | {\n token?: never;\n\n /**\n * The root key from unkey.dev.\n *\n * You can create/manage your root keys here:\n * https://unkey.dev/app/settings/root-keys\n */\n rootKey: string;\n }\n | {\n /**\n * The workspace key from unkey.dev\n *\n * @deprecated Use `rootKey`\n */\n token: string;\n rootKey?: never;\n }\n) & {\n /**\n * @default https://api.unkey.dev\n */\n baseUrl?: string;\n\n /**\n * Retry on network errors\n */\n retry?: {\n /**\n * How many attempts should be made\n * The maximum number of requests will be `attempts + 1`\n * `0` means no retries\n *\n * @default 5\n */\n attempts?: number;\n /**\n * Return how many milliseconds to wait until the next attempt is made\n *\n * @default `(retryCount) => Math.round(Math.exp(retryCount) * 10)),`\n */\n backoff?: (retryCount: number) => number;\n };\n /**\n * Customize the `fetch` cache behaviour\n */\n cache?: RequestCache;\n // some change\n};\n\ntype ApiRequest = {\n path: string[];\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n body?: unknown;\n query?: Record<string, string>;\n};\n\ntype Result<R> =\n | {\n result: R;\n error?: never;\n }\n | {\n result?: never;\n error: UnkeyError;\n };\n\nexport class Unkey {\n public readonly baseUrl: string;\n private readonly rootKey: string;\n private readonly cache?: RequestCache;\n\n public readonly retry: {\n attempts: number;\n backoff: (retryCount: number) => number;\n };\n\n constructor(opts: UnkeyOptions) {\n this.baseUrl = opts.baseUrl ?? \"https://api.unkey.dev\";\n this.rootKey = opts.rootKey ?? opts.token;\n\n this.cache = opts.cache;\n /**\n * Even though typescript should prevent this, some people still pass undefined or empty strings\n */\n if (!this.rootKey) {\n throw new Error(\n \"Unkey root key must be set, maybe you passed in `undefined` or an empty string?\",\n );\n }\n\n this.retry = {\n attempts: opts.retry?.attempts ?? 5,\n backoff: opts.retry?.backoff ?? ((n) => Math.round(Math.exp(n) * 10)),\n };\n }\n\n private async fetch<TResult>(req: ApiRequest): Promise<Result<TResult>> {\n let res: Response | null = null;\n let err: Error | null = null;\n for (let i = 0; i <= this.retry.attempts; i++) {\n const url = new URL(`${this.baseUrl}/${req.path.join(\"/\")}`);\n if (req.query) {\n for (const [k, v] of Object.entries(req.query)) {\n url.searchParams.set(k, v);\n }\n }\n res = await fetch(url, {\n method: req.method,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.rootKey}`,\n },\n cache: this.cache,\n body: JSON.stringify(req.body),\n }).catch((e: Error) => {\n err = e;\n return null; // set `res` to `null`\n });\n if (res?.ok) {\n return { result: await res.json() };\n }\n const backoff = this.retry.backoff(i);\n console.debug(\n \"attempt %d of %d to reach %s failed, retrying in %d ms: %s\",\n i + 1,\n this.retry.attempts + 1,\n url,\n backoff,\n // @ts-ignore I don't understand why `err` is `never`\n err?.message,\n );\n await new Promise((r) => setTimeout(r, backoff));\n }\n\n if (res) {\n return { error: await res.json() };\n }\n\n return {\n error: {\n code: \"FETCH_ERROR\",\n // @ts-ignore I don't understand why `err` is `never`\n message: err?.message ?? \"No response\",\n docs: \"https://developer.mozilla.org/en-US/docs/Web/API/fetch\",\n requestId: \"N/A\",\n },\n };\n }\n\n public get keys() {\n return {\n create: async (req: {\n /**\n * Provide a name to this key if you want for later reference\n */\n name?: string;\n /**\n * Choose an API where this key should be created.\n */\n apiId: string;\n /**\n * To make it easier for your users to understand which product an api key belongs to, you can add prefix them.\n *\n * For example Stripe famously prefixes their customer ids with cus_ or their api keys with sk_live_.\n *\n * The underscore is automtically added if you are defining a prefix, for example: \"prefix\": \"abc\" will result in a key like abc_xxxxxxxxx\n */\n prefix?: string;\n\n /**\n * The bytelength used to generate your key determines its entropy as well as its length. Higher is better, but keys become longer and more annoying to handle.\n *\n * The default is 16 bytes, or 2128 possible combinations\n */\n byteLength?: number;\n /**\n * Your user’s Id. This will provide a link between Unkey and your customer record.\n *\n * When validating a key, we will return this back to you, so you can clearly identify your user from their api key.\n */\n ownerId?: string;\n /**\n * This is a place for dynamic meta data, anything that feels useful for you should go here\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown;\n /**\n * You can auto expire keys by providing a unix timestamp in milliseconds.\n *\n * Once keys expire they will automatically be deleted and are no longer valid.\n */\n expires?: number;\n\n /**\n * Unkey comes with per-key ratelimiting out of the box.\n *\n * @see https://unkey.dev/docs/features/ratelimiting\n */\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n /**\n * The total amount of burstable requests.\n */\n limit: number;\n\n /**\n * How many tokens to refill during each refillInterval\n */\n refillRate: number;\n\n /**\n * Determines the speed at which tokens are refilled.\n * In milliseconds.\n */\n refillInterval: number;\n };\n\n /**\n * Unkey allows you to set/update usage limits on individual keys\n *\n * @see https://unkey.dev/docs/features/remaining\n */\n remaining?: number;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"keys\"],\n method: \"POST\",\n body: req,\n });\n },\n update: async (req: {\n /**\n * The id of the key to update.\n */\n keyId: string;\n /**\n * Update the name\n */\n name?: string | null;\n\n /**\n * Update the owner id\n */\n ownerId?: string | null;\n /**\n * This is a place for dynamic meta data, anything that feels useful for you should go here\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown | null;\n /**\n * Update the expiration time, Unix timstamp in milliseconds\n *\n *\n */\n expires?: number | null;\n\n /**\n * Update the ratelimit\n *\n * @see https://unkey.dev/docs/features/ratelimiting\n */\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n /**\n * The total amount of burstable requests.\n */\n limit: number;\n\n /**\n * How many tokens to refill during each refillInterval\n */\n refillRate: number;\n\n /**\n * Determines the speed at which tokens are refilled.\n * In milliseconds.\n */\n refillInterval: number;\n } | null;\n\n /**\n * Update the remaining verifications.\n *\n * @see https://unkey.dev/docs/features/remaining\n */\n remaining?: number | null;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"keys\", req.keyId],\n method: \"PUT\",\n body: req,\n });\n },\n verify: async (req: { key: string }): Promise<\n Result<{\n /**\n * Whether or not this key is valid and has passed the ratelimit. If false you should not grant access to whatever the user is requesting\n */\n valid: boolean;\n\n /**\n * If you have set an ownerId on this key it is returned here. You can use this to clearly authenticate a user in your system.\n */\n ownerId?: string;\n\n /**\n * This is the meta data you have set when creating the key.\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown;\n\n /**\n * Unix timestamp in milliseconds when this key expires\n * Only available when the key automatically expires\n */\n expires?: number;\n\n /**\n * How many verifications are remaining after the current request.\n */\n remaining?: number;\n\n /**\n * Ratelimit data if the key is ratelimited.\n */\n ratelimit?: {\n /**\n * The maximum number of requests for bursting.\n */\n limit: number;\n\n /**\n * How many requests are remaining until `reset`\n */\n remaining: number;\n\n /**\n * Unix timestamp in millisecond when the ratelimit is refilled.\n */\n reset: number;\n };\n\n /**\n * Machine readable code that explains why a key is invalid or could not be verified\n */\n code?: \"NOT_FOUND\" | \"FORBIDDEN\" | \"RATELIMITED\" | \"KEY_USAGE_EXCEEDED\";\n }>\n > => {\n return await this.fetch<{\n valid: boolean;\n ownerId?: string;\n meta?: unknown;\n }>({\n path: [\"v1\", \"keys\", \"verify\"],\n method: \"POST\",\n body: req,\n });\n },\n revoke: async (req: { keyId: string }): Promise<Result<void>> => {\n return await this.fetch<void>({\n path: [\"v1\", \"keys\", req.keyId],\n method: \"DELETE\",\n });\n },\n };\n }\n\n public get apis() {\n return {\n create: async (req: {\n /**\n * A name for you to identify your API.\n */\n name: string;\n }): Promise<\n Result<{\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }>\n > => {\n return await this.fetch({\n path: [\"v1\", \"apis.createApi\"],\n method: \"POST\",\n body: req,\n });\n },\n remove: async (req: {\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }): Promise<\n Result<{\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }>\n > => {\n return await this.fetch({\n path: [\"v1\", \"apis.removeApi\"],\n method: \"POST\",\n body: req,\n });\n },\n get: async (req: {\n /**\n * The api id\n */\n apiId: string;\n }): Promise<Result<{ id: string; name: string; workspaceId: string }>> => {\n return await this.fetch({\n path: [\"v1\", \"apis\", req.apiId],\n method: \"GET\",\n });\n },\n\n listKeys: async (req: {\n /**\n * The api id\n */\n apiId: string;\n\n /**\n * Limit the number of returned keys, the maximum is 100.\n *\n * @default 100\n */\n limit?: number;\n\n /**\n * Specify an offset for pagination.\n * @example:\n * An offset of 4 will skip the first 4 keys and return keys starting at the 5th position.\n *\n * @default 0\n */\n offset?: number;\n\n /**\n * If provided, this will only return keys where the ownerId matches.\n */\n ownerId?: string;\n }): Promise<\n Result<{\n keys: {\n id: string;\n apiId: string;\n ownerId?: string;\n workspaceId: string;\n start: string;\n createdAt: number;\n name?: string;\n expires?: number;\n remaining?: number;\n meta?: unknown;\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n limit: number;\n refillRate: number;\n refillInterval: number;\n };\n }[];\n total: number;\n }>\n > => {\n const query: Record<string, string> = {};\n if (typeof req.limit !== \"undefined\") {\n query.limit = req.limit.toString();\n }\n if (typeof req.offset !== \"undefined\") {\n query.offset = req.offset.toString();\n }\n if (typeof req.ownerId !== \"undefined\") {\n query.ownerId = req.ownerId;\n }\n\n return await this.fetch({\n path: [\"v1\", \"apis\", req.apiId, \"keys\"],\n method: \"GET\",\n query,\n });\n },\n };\n }\n /**\n * Must be authenticated via app token\n */\n public get _internal() {\n return {\n createRootKey: async (req: {\n /**\n * Provide a name to this key if you want for later reference\n */\n name?: string;\n\n /**\n * You can auto expire keys by providing a unix timestamp in milliseconds.\n *\n * Once keys expire they will automatically be deleted and are no longer valid.\n */\n expires?: number;\n\n // Used to create root keys from the frontend, please ignore\n forWorkspaceId: string;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"internal\", \"rootkeys\"],\n method: \"POST\",\n body: req,\n });\n },\n deleteRootKey: async (req: {\n /**\n * Used to create root keys from the frontend, please ignore\n */\n keyId: string;\n }): Promise<Result<void>> => {\n return await this.fetch<void>({\n path: [\"v1\", \"internal.removeRootKey\"],\n method: \"POST\",\n body: req,\n });\n },\n };\n }\n}\n","import { Unkey } from \"./client\";\n\n/**\n * Verify a key\n *\n * @example\n * ```ts\n * const { result, error } = await verifyKey(\"key_123\")\n * if (error){\n * // handle potential network or bad request error\n * // a link to our docs will be in the `error.docs` field\n * console.error(error.message)\n * return\n * }\n * if (!result.valid) {\n * // do not grant access\n * return\n * }\n *\n * // process request\n * console.log(result)\n * ```\n */\nexport function verifyKey(key: string) {\n // yes this is empty to make typescript happy but we don't need a token for verifying keys\n // it's not the cleanest but it works for now :)\n const unkey = new Unkey({ token: \"public\" });\n return unkey.keys.verify({ key });\n}\n"],"mappings":";AAwEO,IAAM,QAAN,MAAY;AAAA,EACD;AAAA,EACC;AAAA,EACA;AAAA,EAED;AAAA,EAKhB,YAAY,MAAoB;AAC9B,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,UAAU,KAAK,WAAW,KAAK;AAEpC,SAAK,QAAQ,KAAK;AAIlB,QAAI,CAAC,KAAK,SAAS;AACjB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,QAAQ;AAAA,MACX,UAAU,KAAK,OAAO,YAAY;AAAA,MAClC,SAAS,KAAK,OAAO,YAAY,CAAC,MAAM,KAAK,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE;AAAA,IACrE;AAAA,EACF;AAAA,EAEA,MAAc,MAAe,KAA2C;AACtE,QAAI,MAAuB;AAC3B,QAAI,MAAoB;AACxB,aAAS,IAAI,GAAG,KAAK,KAAK,MAAM,UAAU,KAAK;AAC7C,YAAM,MAAM,IAAI,IAAI,GAAG,KAAK,OAAO,IAAI,IAAI,KAAK,KAAK,GAAG,CAAC,EAAE;AAC3D,UAAI,IAAI,OAAO;AACb,mBAA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AAa;AACtC,gBAAM,UAAU,IAAI;AAAA,QACtB;AAEA,eAAO,MAAM,KAAK,MAAM;AAAA,UACtB,MAAM,CAAC,MAAM,QAAQ,IAAI,OAAO,MAAM;AAAA,UACtC,QAAQ;AAAA,UACR;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAIA,IAAW,YAAY;AACrB,WAAO;AAAA,MACL,eAAe,OAAO,QAeiC;AACrD,eAAO,MAAM,KAAK,MAAsC;AAAA,UACtD,MAAM,CAAC,MAAM,YAAY,UAAU;AAAA,UACnC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,MACA,eAAe,OAAO,QAKO;AAC3B,eAAO,MAAM,KAAK,MAAY;AAAA,UAC5B,MAAM,CAAC,MAAM,wBAAwB;AAAA,UACrC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;AC1hBO,SAAS,UAAU,KAAa;AAGrC,QAAM,QAAQ,IAAI,MAAM,EAAE,OAAO,SAAS,CAAC;AAC3C,SAAO,MAAM,KAAK,OAAO,EAAE,IAAI,CAAC;AAClC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/verify.ts"],"sourcesContent":["import { UnkeyError } from \"./errors\";\n\nexport type UnkeyOptions = (\n | {\n token?: never;\n\n /**\n * The root key from unkey.dev.\n *\n * You can create/manage your root keys here:\n * https://unkey.dev/app/settings/root-keys\n */\n rootKey: string;\n }\n | {\n /**\n * The workspace key from unkey.dev\n *\n * @deprecated Use `rootKey`\n */\n token: string;\n rootKey?: never;\n }\n) & {\n /**\n * @default https://api.unkey.dev\n */\n baseUrl?: string;\n\n /**\n * Retry on network errors\n */\n retry?: {\n /**\n * How many attempts should be made\n * The maximum number of requests will be `attempts + 1`\n * `0` means no retries\n *\n * @default 5\n */\n attempts?: number;\n /**\n * Return how many milliseconds to wait until the next attempt is made\n *\n * @default `(retryCount) => Math.round(Math.exp(retryCount) * 10)),`\n */\n backoff?: (retryCount: number) => number;\n };\n /**\n * Customize the `fetch` cache behaviour\n */\n cache?: RequestCache;\n // some change\n};\n\ntype ApiRequest = {\n path: string[];\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n body?: unknown;\n query?: Record<string, string>;\n};\n\ntype Result<R> =\n | {\n result: R;\n error?: never;\n }\n | {\n result?: never;\n error: UnkeyError;\n };\n\nexport class Unkey {\n public readonly baseUrl: string;\n private readonly rootKey: string;\n private readonly cache?: RequestCache;\n\n public readonly retry: {\n attempts: number;\n backoff: (retryCount: number) => number;\n };\n\n constructor(opts: UnkeyOptions) {\n this.baseUrl = opts.baseUrl ?? \"https://api.unkey.dev\";\n this.rootKey = opts.rootKey ?? opts.token;\n\n this.cache = opts.cache;\n /**\n * Even though typescript should prevent this, some people still pass undefined or empty strings\n */\n if (!this.rootKey) {\n throw new Error(\n \"Unkey root key must be set, maybe you passed in `undefined` or an empty string?\",\n );\n }\n\n this.retry = {\n attempts: opts.retry?.attempts ?? 5,\n backoff: opts.retry?.backoff ?? ((n) => Math.round(Math.exp(n) * 10)),\n };\n }\n\n private async fetch<TResult>(req: ApiRequest): Promise<Result<TResult>> {\n let res: Response | null = null;\n let err: Error | null = null;\n for (let i = 0; i <= this.retry.attempts; i++) {\n const url = new URL(`${this.baseUrl}/${req.path.join(\"/\")}`);\n if (req.query) {\n for (const [k, v] of Object.entries(req.query)) {\n url.searchParams.set(k, v);\n }\n }\n res = await fetch(url, {\n method: req.method,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.rootKey}`,\n },\n cache: this.cache,\n body: JSON.stringify(req.body),\n }).catch((e: Error) => {\n err = e;\n return null; // set `res` to `null`\n });\n if (res?.ok) {\n return { result: (await res.json()) as TResult };\n }\n const backoff = this.retry.backoff(i);\n console.debug(\n \"attempt %d of %d to reach %s failed, retrying in %d ms: %s\",\n i + 1,\n this.retry.attempts + 1,\n url,\n backoff,\n // @ts-ignore I don't understand why `err` is `never`\n err?.message,\n );\n await new Promise((r) => setTimeout(r, backoff));\n }\n\n if (res) {\n return { error: (await res.json()) as UnkeyError };\n }\n\n return {\n error: {\n code: \"FETCH_ERROR\",\n // @ts-ignore I don't understand why `err` is `never`\n message: err?.message ?? \"No response\",\n docs: \"https://developer.mozilla.org/en-US/docs/Web/API/fetch\",\n requestId: \"N/A\",\n },\n };\n }\n\n public get keys() {\n return {\n create: async (req: {\n /**\n * Provide a name to this key if you want for later reference\n */\n name?: string;\n /**\n * Choose an API where this key should be created.\n */\n apiId: string;\n /**\n * To make it easier for your users to understand which product an api key belongs to, you can add prefix them.\n *\n * For example Stripe famously prefixes their customer ids with cus_ or their api keys with sk_live_.\n *\n * The underscore is automtically added if you are defining a prefix, for example: \"prefix\": \"abc\" will result in a key like abc_xxxxxxxxx\n */\n prefix?: string;\n\n /**\n * The bytelength used to generate your key determines its entropy as well as its length. Higher is better, but keys become longer and more annoying to handle.\n *\n * The default is 16 bytes, or 2128 possible combinations\n */\n byteLength?: number;\n /**\n * Your user’s Id. This will provide a link between Unkey and your customer record.\n *\n * When validating a key, we will return this back to you, so you can clearly identify your user from their api key.\n */\n ownerId?: string;\n /**\n * This is a place for dynamic meta data, anything that feels useful for you should go here\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown;\n /**\n * You can auto expire keys by providing a unix timestamp in milliseconds.\n *\n * Once keys expire they will automatically be deleted and are no longer valid.\n */\n expires?: number;\n\n /**\n * Unkey comes with per-key ratelimiting out of the box.\n *\n * @see https://unkey.dev/docs/features/ratelimiting\n */\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n /**\n * The total amount of burstable requests.\n */\n limit: number;\n\n /**\n * How many tokens to refill during each refillInterval\n */\n refillRate: number;\n\n /**\n * Determines the speed at which tokens are refilled.\n * In milliseconds.\n */\n refillInterval: number;\n };\n\n /**\n * Unkey allows you to set/update usage limits on individual keys\n *\n * @see https://unkey.dev/docs/features/remaining\n */\n remaining?: number;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"keys\"],\n method: \"POST\",\n body: req,\n });\n },\n update: async (req: {\n /**\n * The id of the key to update.\n */\n keyId: string;\n /**\n * Update the name\n */\n name?: string | null;\n\n /**\n * Update the owner id\n */\n ownerId?: string | null;\n /**\n * This is a place for dynamic meta data, anything that feels useful for you should go here\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown | null;\n /**\n * Update the expiration time, Unix timstamp in milliseconds\n *\n *\n */\n expires?: number | null;\n\n /**\n * Update the ratelimit\n *\n * @see https://unkey.dev/docs/features/ratelimiting\n */\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n /**\n * The total amount of burstable requests.\n */\n limit: number;\n\n /**\n * How many tokens to refill during each refillInterval\n */\n refillRate: number;\n\n /**\n * Determines the speed at which tokens are refilled.\n * In milliseconds.\n */\n refillInterval: number;\n } | null;\n\n /**\n * Update the remaining verifications.\n *\n * @see https://unkey.dev/docs/features/remaining\n */\n remaining?: number | null;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"keys\", req.keyId],\n method: \"PUT\",\n body: req,\n });\n },\n verify: async (req: {\n /**\n * The key to verify\n */\n key: string;\n\n /**\n * The api id to verify against\n *\n * This will be required soon.\n */\n apiId?: string;\n }): Promise<\n Result<{\n /**\n * Whether or not this key is valid and has passed the ratelimit. If false you should not grant access to whatever the user is requesting\n */\n valid: boolean;\n\n /**\n * If you have set an ownerId on this key it is returned here. You can use this to clearly authenticate a user in your system.\n */\n ownerId?: string;\n\n /**\n * This is the meta data you have set when creating the key.\n *\n * Example:\n *\n * ```json\n * {\n * \"billingTier\":\"PRO\",\n * \"trialEnds\": \"2023-06-16T17:16:37.161Z\"\n * }\n * ```\n */\n meta?: unknown;\n\n /**\n * Unix timestamp in milliseconds when this key expires\n * Only available when the key automatically expires\n */\n expires?: number;\n\n /**\n * How many verifications are remaining after the current request.\n */\n remaining?: number;\n\n /**\n * Ratelimit data if the key is ratelimited.\n */\n ratelimit?: {\n /**\n * The maximum number of requests for bursting.\n */\n limit: number;\n\n /**\n * How many requests are remaining until `reset`\n */\n remaining: number;\n\n /**\n * Unix timestamp in millisecond when the ratelimit is refilled.\n */\n reset: number;\n };\n\n /**\n * Machine readable code that explains why a key is invalid or could not be verified\n */\n code?: \"NOT_FOUND\" | \"FORBIDDEN\" | \"RATELIMITED\" | \"KEY_USAGE_EXCEEDED\";\n }>\n > => {\n return await this.fetch<{\n valid: boolean;\n ownerId?: string;\n meta?: unknown;\n }>({\n path: [\"v1\", \"keys\", \"verify\"],\n method: \"POST\",\n body: req,\n });\n },\n revoke: async (req: { keyId: string }): Promise<Result<void>> => {\n return await this.fetch<void>({\n path: [\"v1\", \"keys\", req.keyId],\n method: \"DELETE\",\n });\n },\n };\n }\n\n public get apis() {\n return {\n create: async (req: {\n /**\n * A name for you to identify your API.\n */\n name: string;\n }): Promise<\n Result<{\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }>\n > => {\n return await this.fetch({\n path: [\"v1\", \"apis.createApi\"],\n method: \"POST\",\n body: req,\n });\n },\n remove: async (req: {\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }): Promise<\n Result<{\n /**\n * The global unique identifier of your api.\n * You'll need this for other api requests.\n */\n apiId: string;\n }>\n > => {\n return await this.fetch({\n path: [\"v1\", \"apis.removeApi\"],\n method: \"POST\",\n body: req,\n });\n },\n get: async (req: {\n /**\n * The api id\n */\n apiId: string;\n }): Promise<Result<{ id: string; name: string; workspaceId: string }>> => {\n return await this.fetch({\n path: [\"v1\", \"apis\", req.apiId],\n method: \"GET\",\n });\n },\n\n listKeys: async (req: {\n /**\n * The api id\n */\n apiId: string;\n\n /**\n * Limit the number of returned keys, the maximum is 100.\n *\n * @default 100\n */\n limit?: number;\n\n /**\n * Specify an offset for pagination.\n * @example:\n * An offset of 4 will skip the first 4 keys and return keys starting at the 5th position.\n *\n * @default 0\n */\n offset?: number;\n\n /**\n * If provided, this will only return keys where the ownerId matches.\n */\n ownerId?: string;\n }): Promise<\n Result<{\n keys: {\n id: string;\n apiId: string;\n ownerId?: string;\n workspaceId: string;\n start: string;\n createdAt: number;\n name?: string;\n expires?: number;\n remaining?: number;\n meta?: unknown;\n ratelimit?: {\n type: \"fast\" | \"consistent\";\n limit: number;\n refillRate: number;\n refillInterval: number;\n };\n }[];\n total: number;\n }>\n > => {\n const query: Record<string, string> = {};\n if (typeof req.limit !== \"undefined\") {\n query.limit = req.limit.toString();\n }\n if (typeof req.offset !== \"undefined\") {\n query.offset = req.offset.toString();\n }\n if (typeof req.ownerId !== \"undefined\") {\n query.ownerId = req.ownerId;\n }\n\n return await this.fetch({\n path: [\"v1\", \"apis\", req.apiId, \"keys\"],\n method: \"GET\",\n query,\n });\n },\n };\n }\n /**\n * Must be authenticated via app token\n */\n public get _internal() {\n return {\n createRootKey: async (req: {\n /**\n * Provide a name to this key if you want for later reference\n */\n name?: string;\n\n /**\n * You can auto expire keys by providing a unix timestamp in milliseconds.\n *\n * Once keys expire they will automatically be deleted and are no longer valid.\n */\n expires?: number;\n\n // Used to create root keys from the frontend, please ignore\n forWorkspaceId: string;\n }): Promise<Result<{ key: string; keyId: string }>> => {\n return await this.fetch<{ key: string; keyId: string }>({\n path: [\"v1\", \"internal\", \"rootkeys\"],\n method: \"POST\",\n body: req,\n });\n },\n deleteRootKey: async (req: {\n /**\n * Used to create root keys from the frontend, please ignore\n */\n keyId: string;\n }): Promise<Result<void>> => {\n return await this.fetch<void>({\n path: [\"v1\", \"internal.removeRootKey\"],\n method: \"POST\",\n body: req,\n });\n },\n };\n }\n}\n","import { Unkey } from \"./client\";\n\n/**\n * Verify a key\n *\n * @example\n * ```ts\n * const { result, error } = await verifyKey(\"key_123\")\n * if (error){\n * // handle potential network or bad request error\n * // a link to our docs will be in the `error.docs` field\n * console.error(error.message)\n * return\n * }\n * if (!result.valid) {\n * // do not grant access\n * return\n * }\n *\n * // process request\n * console.log(result)\n * ```\n */\nexport function verifyKey(req: string | { key: string; apiId: string }) {\n // yes this is empty to make typescript happy but we don't need a token for verifying keys\n // it's not the cleanest but it works for now :)\n const unkey = new Unkey({ token: \"public\" });\n return unkey.keys.verify(typeof req === \"string\" ? { key: req } : req);\n}\n"],"mappings":";AAwEO,IAAM,QAAN,MAAY;AAAA,EACD;AAAA,EACC;AAAA,EACA;AAAA,EAED;AAAA,EAKhB,YAAY,MAAoB;AAC9B,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,UAAU,KAAK,WAAW,KAAK;AAEpC,SAAK,QAAQ,KAAK;AAIlB,QAAI,CAAC,KAAK,SAAS;AACjB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,QAAQ;AAAA,MACX,UAAU,KAAK,OAAO,YAAY;AAAA,MAClC,SAAS,KAAK,OAAO,YAAY,CAAC,MAAM,KAAK,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE;AAAA,IACrE;AAAA,EACF;AAAA,EAEA,MAAc,MAAe,KAA2C;AACtE,QAAI,MAAuB;AAC3B,QAAI,MAAoB;AACxB,aAAS,IAAI,GAAG,KAAK,KAAK,MAAM,UAAU,KAAK;AAC7C,YAAM,MAAM,IAAI,IAAI,GAAG,KAAK,OAAO,IAAI,IAAI,KAAK,KAAK,GAAG,CAAC,EAAE;AAC3D,UAAI,IAAI,OAAO;AACb,mBAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,IAAI,KAAK,GAAG;AAC9C,cAAI,aAAa,IAAI,GAAG,CAAC;AAAA,QAC3B;AAAA,MACF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AAO,MAAM;AAAA,UACtC,QAAQ;AAAA,UACR;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAIA,IAAW,YAAY;AACrB,WAAO;AAAA,MACL,eAAe,OAAO,QAeiC;AACrD,eAAO,MAAM,KAAK,MAAsC;AAAA,UACtD,MAAM,CAAC,MAAM,YAAY,UAAU;AAAA,UACnC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,MACA,eAAe,OAAO,QAKO;AAC3B,eAAO,MAAM,KAAK,MAAY;AAAA,UAC5B,MAAM,CAAC,MAAM,wBAAwB;AAAA,UACrC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;ACtiBO,SAAS,UAAU,KAA8C;AAGtE,QAAM,QAAQ,IAAI,MAAM,EAAE,OAAO,SAAS,CAAC;AAC3C,SAAO,MAAM,KAAK,OAAO,OAAO,QAAQ,WAAW,EAAE,KAAK,IAAI,IAAI,GAAG;AACvE;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unkey/api",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.1",
|
|
4
4
|
"main": "./dist/index.js",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"license": "MIT",
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
],
|
|
23
23
|
"author": "Andreas Thomas <andreas@chronark.com>",
|
|
24
24
|
"devDependencies": {
|
|
25
|
-
"@types/node": "^20.
|
|
25
|
+
"@types/node": "^20.8.7",
|
|
26
26
|
"tsup": "^7.2.0",
|
|
27
|
-
"tsx": "^3.
|
|
27
|
+
"tsx": "^3.14.0",
|
|
28
28
|
"typescript": "^5.2.2"
|
|
29
29
|
},
|
|
30
30
|
"scripts": {
|