@vllnt/convex-quota 0.1.0-canary.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 (68) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +158 -0
  4. package/dist/client/index.d.ts +59 -0
  5. package/dist/client/index.d.ts.map +1 -0
  6. package/dist/client/index.js +58 -0
  7. package/dist/client/index.js.map +1 -0
  8. package/dist/client/types.d.ts +32 -0
  9. package/dist/client/types.d.ts.map +1 -0
  10. package/dist/client/types.js +3 -0
  11. package/dist/client/types.js.map +1 -0
  12. package/dist/component/_generated/api.d.ts +38 -0
  13. package/dist/component/_generated/api.d.ts.map +1 -0
  14. package/dist/component/_generated/api.js +31 -0
  15. package/dist/component/_generated/api.js.map +1 -0
  16. package/dist/component/_generated/component.d.ts +100 -0
  17. package/dist/component/_generated/component.d.ts.map +1 -0
  18. package/dist/component/_generated/component.js +11 -0
  19. package/dist/component/_generated/component.js.map +1 -0
  20. package/dist/component/_generated/dataModel.d.ts +46 -0
  21. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  22. package/dist/component/_generated/dataModel.js +11 -0
  23. package/dist/component/_generated/dataModel.js.map +1 -0
  24. package/dist/component/_generated/server.d.ts +133 -0
  25. package/dist/component/_generated/server.d.ts.map +1 -0
  26. package/dist/component/_generated/server.js +80 -0
  27. package/dist/component/_generated/server.js.map +1 -0
  28. package/dist/component/convex.config.d.ts +3 -0
  29. package/dist/component/convex.config.d.ts.map +1 -0
  30. package/dist/component/convex.config.js +4 -0
  31. package/dist/component/convex.config.js.map +1 -0
  32. package/dist/component/mutations.d.ts +43 -0
  33. package/dist/component/mutations.d.ts.map +1 -0
  34. package/dist/component/mutations.js +164 -0
  35. package/dist/component/mutations.js.map +1 -0
  36. package/dist/component/queries.d.ts +25 -0
  37. package/dist/component/queries.d.ts.map +1 -0
  38. package/dist/component/queries.js +52 -0
  39. package/dist/component/queries.js.map +1 -0
  40. package/dist/component/schema.d.ts +34 -0
  41. package/dist/component/schema.d.ts.map +1 -0
  42. package/dist/component/schema.js +22 -0
  43. package/dist/component/schema.js.map +1 -0
  44. package/dist/component/validators.d.ts +101 -0
  45. package/dist/component/validators.d.ts.map +1 -0
  46. package/dist/component/validators.js +61 -0
  47. package/dist/component/validators.js.map +1 -0
  48. package/dist/shared.d.ts +66 -0
  49. package/dist/shared.d.ts.map +1 -0
  50. package/dist/shared.js +208 -0
  51. package/dist/shared.js.map +1 -0
  52. package/docs/API.md +94 -0
  53. package/llms-full.txt +1324 -0
  54. package/llms.txt +43 -0
  55. package/package.json +90 -0
  56. package/src/client/index.ts +179 -0
  57. package/src/client/types.ts +37 -0
  58. package/src/component/_generated/api.ts +54 -0
  59. package/src/component/_generated/component.ts +114 -0
  60. package/src/component/_generated/dataModel.ts +60 -0
  61. package/src/component/_generated/server.ts +169 -0
  62. package/src/component/convex.config.ts +5 -0
  63. package/src/component/mutations.ts +219 -0
  64. package/src/component/queries.ts +72 -0
  65. package/src/component/schema.ts +22 -0
  66. package/src/component/validators.ts +89 -0
  67. package/src/shared.ts +324 -0
  68. package/src/test.ts +16 -0
@@ -0,0 +1,101 @@
1
+ export declare function requireRef(value: string, name: string): void;
2
+ export declare function requirePositiveInt(value: number, name: string, code: string): void;
3
+ export declare function requireAllowanceInput(input: {
4
+ key: string;
5
+ limit: number;
6
+ scope: string;
7
+ subjectRef: string;
8
+ }): void;
9
+ export declare const calendarPeriod: import("convex/values").VUnion<"day" | "month" | "week", [import("convex/values").VLiteral<"day", "required">, import("convex/values").VLiteral<"week", "required">, import("convex/values").VLiteral<"month", "required">], "required", never>;
10
+ export declare const weekStartsOn: import("convex/values").VUnion<"monday" | "sunday", [import("convex/values").VLiteral<"monday", "required">, import("convex/values").VLiteral<"sunday", "required">], "required", never>;
11
+ export declare const windowSpec: import("convex/values").VUnion<{
12
+ kind: "calendar";
13
+ period: "day" | "month" | "week";
14
+ timeZone: string;
15
+ weekStartsOn?: "monday" | "sunday" | undefined;
16
+ } | {
17
+ durationMs: number;
18
+ kind: "rolling";
19
+ } | {
20
+ durationMs: number;
21
+ kind: "epoch";
22
+ }, [import("convex/values").VObject<{
23
+ kind: "calendar";
24
+ period: "day" | "month" | "week";
25
+ timeZone: string;
26
+ weekStartsOn?: "monday" | "sunday" | undefined;
27
+ }, {
28
+ kind: import("convex/values").VLiteral<"calendar", "required">;
29
+ period: import("convex/values").VUnion<"day" | "month" | "week", [import("convex/values").VLiteral<"day", "required">, import("convex/values").VLiteral<"week", "required">, import("convex/values").VLiteral<"month", "required">], "required", never>;
30
+ timeZone: import("convex/values").VString<string, "required">;
31
+ weekStartsOn: import("convex/values").VUnion<"monday" | "sunday" | undefined, [import("convex/values").VLiteral<"monday", "required">, import("convex/values").VLiteral<"sunday", "required">], "optional", never>;
32
+ }, "required", "kind" | "period" | "timeZone" | "weekStartsOn">, import("convex/values").VObject<{
33
+ durationMs: number;
34
+ kind: "rolling";
35
+ }, {
36
+ durationMs: import("convex/values").VFloat64<number, "required">;
37
+ kind: import("convex/values").VLiteral<"rolling", "required">;
38
+ }, "required", "durationMs" | "kind">, import("convex/values").VObject<{
39
+ durationMs: number;
40
+ kind: "epoch";
41
+ }, {
42
+ durationMs: import("convex/values").VFloat64<number, "required">;
43
+ kind: import("convex/values").VLiteral<"epoch", "required">;
44
+ }, "required", "durationMs" | "kind">], "required", "durationMs" | "kind" | "period" | "timeZone" | "weekStartsOn">;
45
+ export declare const consumeResult: import("convex/values").VUnion<{
46
+ allowed: true;
47
+ limit: number;
48
+ periodKey: string;
49
+ remaining: number;
50
+ resetsAt: number;
51
+ used: number;
52
+ } | {
53
+ allowed: false;
54
+ limit: number;
55
+ periodKey: string;
56
+ remaining: number;
57
+ resetsAt: number;
58
+ used: number;
59
+ }, [import("convex/values").VObject<{
60
+ allowed: true;
61
+ limit: number;
62
+ periodKey: string;
63
+ remaining: number;
64
+ resetsAt: number;
65
+ used: number;
66
+ }, {
67
+ allowed: import("convex/values").VLiteral<true, "required">;
68
+ limit: import("convex/values").VFloat64<number, "required">;
69
+ periodKey: import("convex/values").VString<string, "required">;
70
+ remaining: import("convex/values").VFloat64<number, "required">;
71
+ resetsAt: import("convex/values").VFloat64<number, "required">;
72
+ used: import("convex/values").VFloat64<number, "required">;
73
+ }, "required", "allowed" | "limit" | "periodKey" | "remaining" | "resetsAt" | "used">, import("convex/values").VObject<{
74
+ allowed: false;
75
+ limit: number;
76
+ periodKey: string;
77
+ remaining: number;
78
+ resetsAt: number;
79
+ used: number;
80
+ }, {
81
+ allowed: import("convex/values").VLiteral<false, "required">;
82
+ limit: import("convex/values").VFloat64<number, "required">;
83
+ periodKey: import("convex/values").VString<string, "required">;
84
+ remaining: import("convex/values").VFloat64<number, "required">;
85
+ resetsAt: import("convex/values").VFloat64<number, "required">;
86
+ used: import("convex/values").VFloat64<number, "required">;
87
+ }, "required", "allowed" | "limit" | "periodKey" | "remaining" | "resetsAt" | "used">], "required", "allowed" | "limit" | "periodKey" | "remaining" | "resetsAt" | "used">;
88
+ export declare const remainingState: import("convex/values").VObject<{
89
+ limit: number;
90
+ periodKey: string;
91
+ remaining: number;
92
+ resetsAt: number;
93
+ used: number;
94
+ }, {
95
+ limit: import("convex/values").VFloat64<number, "required">;
96
+ periodKey: import("convex/values").VString<string, "required">;
97
+ remaining: import("convex/values").VFloat64<number, "required">;
98
+ resetsAt: import("convex/values").VFloat64<number, "required">;
99
+ used: import("convex/values").VFloat64<number, "required">;
100
+ }, "required", "limit" | "periodKey" | "remaining" | "resetsAt" | "used">;
101
+ //# sourceMappingURL=validators.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validators.d.ts","sourceRoot":"","sources":["../../src/component/validators.ts"],"names":[],"mappings":"AAIA,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAO5D;AAED,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,GACX,IAAI,CAON;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;CACpB,GAAG,IAAI,CAKP;AAED,eAAO,MAAM,cAAc,iPAI1B,CAAC;AAEF,eAAO,MAAM,YAAY,0LAAoD,CAAC;AAE9E,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mHAetB,CAAC;AAEF,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0KAiBzB,CAAC;AAEF,eAAO,MAAM,cAAc;;;;;;;;;;;;yEAMzB,CAAC"}
@@ -0,0 +1,61 @@
1
+ import { ConvexError, v } from "convex/values";
2
+ import { MAX_REF_LENGTH } from "../shared";
3
+ export function requireRef(value, name) {
4
+ if (value.length === 0 || value.length > MAX_REF_LENGTH) {
5
+ throw new ConvexError({
6
+ code: "INVALID_REF",
7
+ message: `${name} must be 1..${MAX_REF_LENGTH.toString()} UTF-16 code units`,
8
+ });
9
+ }
10
+ }
11
+ export function requirePositiveInt(value, name, code) {
12
+ if (!Number.isSafeInteger(value) || value < 1) {
13
+ throw new ConvexError({
14
+ code,
15
+ message: `${name} must be a positive safe integer`,
16
+ });
17
+ }
18
+ }
19
+ export function requireAllowanceInput(input) {
20
+ requireRef(input.subjectRef, "subjectRef");
21
+ requireRef(input.key, "key");
22
+ requireRef(input.scope, "scope");
23
+ requirePositiveInt(input.limit, "limit", "INVALID_LIMIT");
24
+ }
25
+ export const calendarPeriod = v.union(v.literal("day"), v.literal("week"), v.literal("month"));
26
+ export const weekStartsOn = v.union(v.literal("monday"), v.literal("sunday"));
27
+ export const windowSpec = v.union(v.object({
28
+ kind: v.literal("calendar"),
29
+ period: calendarPeriod,
30
+ timeZone: v.string(),
31
+ weekStartsOn: v.optional(weekStartsOn),
32
+ }), v.object({
33
+ durationMs: v.number(),
34
+ kind: v.literal("rolling"),
35
+ }), v.object({
36
+ durationMs: v.number(),
37
+ kind: v.literal("epoch"),
38
+ }));
39
+ export const consumeResult = v.union(v.object({
40
+ allowed: v.literal(true),
41
+ limit: v.number(),
42
+ periodKey: v.string(),
43
+ remaining: v.number(),
44
+ resetsAt: v.number(),
45
+ used: v.number(),
46
+ }), v.object({
47
+ allowed: v.literal(false),
48
+ limit: v.number(),
49
+ periodKey: v.string(),
50
+ remaining: v.number(),
51
+ resetsAt: v.number(),
52
+ used: v.number(),
53
+ }));
54
+ export const remainingState = v.object({
55
+ limit: v.number(),
56
+ periodKey: v.string(),
57
+ remaining: v.number(),
58
+ resetsAt: v.number(),
59
+ used: v.number(),
60
+ });
61
+ //# sourceMappingURL=validators.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validators.js","sourceRoot":"","sources":["../../src/component/validators.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,IAAY;IACpD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,cAAc,EAAE,CAAC;QACxD,MAAM,IAAI,WAAW,CAAC;YACpB,IAAI,EAAE,aAAa;YACnB,OAAO,EAAE,GAAG,IAAI,eAAe,cAAc,CAAC,QAAQ,EAAE,oBAAoB;SAC7E,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,KAAa,EACb,IAAY,EACZ,IAAY;IAEZ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC9C,MAAM,IAAI,WAAW,CAAC;YACpB,IA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E,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;CACzB,CAAC,CACH,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAClC,CAAC,CAAC,MAAM,CAAC;IACP,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;IACxB,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;IACpB,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;CACjB,CAAC,EACF,CAAC,CAAC,MAAM,CAAC;IACP,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;IACzB,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;IACpB,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;CACjB,CAAC,CACH,CAAC;AAEF,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC;IACrC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;IACpB,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;CACjB,CAAC,CAAC"}
@@ -0,0 +1,66 @@
1
+ /** Shared constants and window math used by both `client/` and `component/`. */
2
+ export declare const COMPONENT_NAME = "quota";
3
+ /** Default namespace when the host does not scope an allowance. */
4
+ export declare const DEFAULT_SCOPE = "global";
5
+ /** Length limit for opaque refs. */
6
+ export declare const MAX_REF_LENGTH = 256;
7
+ /** Default / max rows deleted per erase pass before the sweep reschedules. */
8
+ export declare const DEFAULT_ERASE_BATCH = 200;
9
+ export declare const MAX_ERASE_BATCH = 500;
10
+ export type CalendarPeriod = "day" | "month" | "week";
11
+ export type WeekStartsOn = "monday" | "sunday";
12
+ export type WindowSpec = {
13
+ durationMs: number;
14
+ kind: "epoch";
15
+ } | {
16
+ durationMs: number;
17
+ kind: "rolling";
18
+ } | {
19
+ kind: "calendar";
20
+ period: CalendarPeriod;
21
+ timeZone: string;
22
+ weekStartsOn?: WeekStartsOn;
23
+ };
24
+ export type ResolvedWindow = {
25
+ endAt: number;
26
+ periodKey: string;
27
+ startAt: number;
28
+ };
29
+ /** Stable policy identity; hosts must use a new key to change window policy. */
30
+ export declare function windowPolicyKey(spec: WindowSpec): string;
31
+ /**
32
+ * Read calendar parts of `now` in `timeZone`. Throws if `timeZone` is not a
33
+ * valid IANA name.
34
+ */
35
+ export declare function zonedParts(now: number, timeZone: string): {
36
+ day: number;
37
+ hour: number;
38
+ minute: number;
39
+ month: number;
40
+ second: number;
41
+ weekday: number;
42
+ year: number;
43
+ };
44
+ type CivilDate = {
45
+ day: number;
46
+ month: number;
47
+ year: number;
48
+ };
49
+ /**
50
+ * UTC ms for the start of a civil date. Repeated midnight chooses the earlier
51
+ * occurrence; a skipped midnight/date advances through the timezone gap.
52
+ */
53
+ export declare function utcMsForLocalMidnight({ day, month, year }: CivilDate, timeZone: string): number;
54
+ /** ISO week (Monday start) for a civil date. */
55
+ export declare function isoWeek(year: number, month: number, day: number): {
56
+ week: number;
57
+ year: number;
58
+ };
59
+ export declare function resolveWindow(now: number, spec: WindowSpec, rollingStartAt?: number): ResolvedWindow;
60
+ export declare function interpretWindowError(error: unknown): {
61
+ code: "INVALID_DURATION" | "INVALID_TIME_ZONE";
62
+ message: string;
63
+ };
64
+ export declare function clampEraseBatch(batch: number): number;
65
+ export {};
66
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.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CAcA;AAED,KAAK,SAAS,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAwB9D;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,SAAS,EAC/B,QAAQ,EAAE,MAAM,GACf,MAAM,CAoBR;AAcD,gDAAgD;AAChD,wBAAgB,OAAO,CACrB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,MAAM,GACV;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAShC;AA8DD,wBAAgB,aAAa,CAC3B,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,UAAU,EAChB,cAAc,CAAC,EAAE,MAAM,GACtB,cAAc,CAuBhB;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG;IACpD,IAAI,EAAE,kBAAkB,GAAG,mBAAmB,CAAC;IAC/C,OAAO,EAAE,MAAM,CAAC;CACjB,CAYA;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAKrD"}
package/dist/shared.js ADDED
@@ -0,0 +1,208 @@
1
+ /** Shared constants and window math used by both `client/` and `component/`. */
2
+ export const COMPONENT_NAME = "quota";
3
+ /** Default namespace when the host does not scope an allowance. */
4
+ export const DEFAULT_SCOPE = "global";
5
+ /** Length limit for opaque refs. */
6
+ export const MAX_REF_LENGTH = 256;
7
+ /** Default / max rows deleted per erase pass before the sweep reschedules. */
8
+ export const DEFAULT_ERASE_BATCH = 200;
9
+ export const MAX_ERASE_BATCH = 500;
10
+ /** Stable policy identity; hosts must use a new key to change window policy. */
11
+ export function windowPolicyKey(spec) {
12
+ return spec.kind === "calendar"
13
+ ? JSON.stringify([
14
+ spec.kind,
15
+ spec.period,
16
+ spec.timeZone,
17
+ spec.period === "week" ? (spec.weekStartsOn ?? "monday") : undefined,
18
+ ])
19
+ : JSON.stringify([spec.kind, spec.durationMs]);
20
+ }
21
+ const formatterCache = new Map();
22
+ function pad2(value) {
23
+ return value.toString().padStart(2, "0");
24
+ }
25
+ function assertFinitePositive(value, code, message) {
26
+ if (!(value > 0 && Number.isSafeInteger(value))) {
27
+ throw new Error(`${code}:${message}`);
28
+ }
29
+ }
30
+ function formatterFor(timeZone) {
31
+ const cached = formatterCache.get(timeZone);
32
+ if (cached !== undefined) {
33
+ return cached;
34
+ }
35
+ try {
36
+ const created = new Intl.DateTimeFormat("en-US", {
37
+ day: "2-digit",
38
+ hour: "2-digit",
39
+ hourCycle: "h23",
40
+ minute: "2-digit",
41
+ month: "2-digit",
42
+ second: "2-digit",
43
+ timeZone,
44
+ weekday: "short",
45
+ year: "numeric",
46
+ });
47
+ formatterCache.set(timeZone, created);
48
+ return created;
49
+ }
50
+ catch {
51
+ throw new Error(`INVALID_TIME_ZONE: ${timeZone}`);
52
+ }
53
+ }
54
+ function partMap(parts) {
55
+ return parts.reduce((accumulator, part) => {
56
+ accumulator[part.type] = part.value;
57
+ return accumulator;
58
+ }, {});
59
+ }
60
+ /**
61
+ * Read calendar parts of `now` in `timeZone`. Throws if `timeZone` is not a
62
+ * valid IANA name.
63
+ */
64
+ export function zonedParts(now, timeZone) {
65
+ const byType = partMap(formatterFor(timeZone).formatToParts(new Date(now)));
66
+ const weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(String(byType.weekday));
67
+ return {
68
+ day: Number(byType.day),
69
+ hour: Number(byType.hour),
70
+ minute: Number(byType.minute),
71
+ month: Number(byType.month),
72
+ second: Number(byType.second),
73
+ weekday,
74
+ year: Number(byType.year),
75
+ };
76
+ }
77
+ function stepMidnight(guess, { day, month, year }, timeZone) {
78
+ const parts = zonedParts(guess, timeZone);
79
+ const asUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
80
+ const target = Date.UTC(year, month - 1, day);
81
+ const diff = asUtc - target;
82
+ if (diff === 0) {
83
+ return guess;
84
+ }
85
+ return guess - diff;
86
+ }
87
+ /**
88
+ * UTC ms for the start of a civil date. Repeated midnight chooses the earlier
89
+ * occurrence; a skipped midnight/date advances through the timezone gap.
90
+ */
91
+ export function utcMsForLocalMidnight({ day, month, year }, timeZone) {
92
+ const first = Date.UTC(year, month - 1, day);
93
+ const corrected = stepMidnight(first, { day, month, year }, timeZone);
94
+ const candidates = [-86_400_000, 0, 86_400_000].map((delta) => stepMidnight(corrected + delta, { day, month, year }, timeZone));
95
+ const exact = candidates.filter((candidate) => {
96
+ const parts = zonedParts(candidate, timeZone);
97
+ return (parts.year === year &&
98
+ parts.month === month &&
99
+ parts.day === day &&
100
+ parts.hour === 0 &&
101
+ parts.minute === 0 &&
102
+ parts.second === 0);
103
+ });
104
+ return exact.length > 0
105
+ ? Math.min(...exact)
106
+ : Math.max(corrected, ...candidates);
107
+ }
108
+ function addDays({ day, month, year }, delta) {
109
+ const date = new Date(Date.UTC(year, month - 1, day + delta));
110
+ return {
111
+ day: date.getUTCDate(),
112
+ month: date.getUTCMonth() + 1,
113
+ year: date.getUTCFullYear(),
114
+ };
115
+ }
116
+ /** ISO week (Monday start) for a civil date. */
117
+ export function isoWeek(year, month, day) {
118
+ const date = new Date(Date.UTC(year, month - 1, day));
119
+ const thursday = new Date(date);
120
+ thursday.setUTCDate(date.getUTCDate() + 4 - (date.getUTCDay() || 7));
121
+ const yearStart = new Date(Date.UTC(thursday.getUTCFullYear(), 0, 1));
122
+ const week = Math.ceil(((thursday.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7);
123
+ return { week, year: thursday.getUTCFullYear() };
124
+ }
125
+ function resolveWeek(parts, timeZone, weekStartsOn) {
126
+ const sunday = weekStartsOn === "sunday";
127
+ const mondayDelta = parts.weekday === 0 ? -6 : 1 - parts.weekday;
128
+ const delta = sunday ? -parts.weekday : mondayDelta;
129
+ const start = addDays(parts, delta);
130
+ const end = addDays(start, 7);
131
+ const labelDate = sunday ? start : parts;
132
+ const label = isoWeek(labelDate.year, labelDate.month, labelDate.day);
133
+ return {
134
+ endAt: utcMsForLocalMidnight(end, timeZone),
135
+ periodKey: `${label.year.toString()}-W${pad2(label.week)}${sunday ? "-sun" : ""}`,
136
+ startAt: utcMsForLocalMidnight(start, timeZone),
137
+ };
138
+ }
139
+ function resolveCalendar(now, spec) {
140
+ const { period, timeZone, weekStartsOn } = spec;
141
+ const parts = zonedParts(now, timeZone);
142
+ if (period === "week")
143
+ return resolveWeek(parts, timeZone, weekStartsOn ?? "monday");
144
+ const start = period === "day" ? parts : { ...parts, day: 1 };
145
+ const next = period === "day"
146
+ ? addDays(parts, 1)
147
+ : {
148
+ day: 1,
149
+ month: parts.month === 12 ? 1 : parts.month + 1,
150
+ year: parts.month === 12 ? parts.year + 1 : parts.year,
151
+ };
152
+ return {
153
+ endAt: utcMsForLocalMidnight(next, timeZone),
154
+ periodKey: `${parts.year.toString()}-${pad2(parts.month)}${period === "day" ? `-${pad2(parts.day)}` : ""}`,
155
+ startAt: utcMsForLocalMidnight(start, timeZone),
156
+ };
157
+ }
158
+ /**
159
+ * Resolve the current window for `spec` at `now`. For `rolling`, pass the
160
+ * stored `windowStartAt` to reuse an in-progress window until it elapses.
161
+ */
162
+ function validateDuration(now, durationMs) {
163
+ assertFinitePositive(durationMs, "INVALID_DURATION", "durationMs must be a positive safe integer");
164
+ assertFinitePositive(now + durationMs, "INVALID_DURATION", "window end must be a positive safe integer");
165
+ }
166
+ export function resolveWindow(now, spec, rollingStartAt) {
167
+ if (spec.kind === "calendar") {
168
+ return resolveCalendar(now, spec);
169
+ }
170
+ validateDuration(now, spec.durationMs);
171
+ if (spec.kind === "epoch") {
172
+ const index = Math.floor(now / spec.durationMs);
173
+ const startAt = index * spec.durationMs;
174
+ return {
175
+ endAt: startAt + spec.durationMs,
176
+ periodKey: `e${index.toString()}`,
177
+ startAt,
178
+ };
179
+ }
180
+ const startAt = rollingStartAt !== undefined && now < rollingStartAt + spec.durationMs
181
+ ? rollingStartAt
182
+ : now;
183
+ return {
184
+ endAt: startAt + spec.durationMs,
185
+ periodKey: `r${startAt.toString()}`,
186
+ startAt,
187
+ };
188
+ }
189
+ export function interpretWindowError(error) {
190
+ const message = error instanceof Error ? error.message : String(error);
191
+ if (message.startsWith("INVALID_DURATION:")) {
192
+ return {
193
+ code: "INVALID_DURATION",
194
+ message: message.slice("INVALID_DURATION:".length),
195
+ };
196
+ }
197
+ return {
198
+ code: "INVALID_TIME_ZONE",
199
+ message: message.replace(/^INVALID_TIME_ZONE:\s*/, ""),
200
+ };
201
+ }
202
+ export function clampEraseBatch(batch) {
203
+ if (!Number.isInteger(batch) || batch < 1) {
204
+ throw new Error("INVALID_BATCH: batch must be a positive integer");
205
+ }
206
+ return Math.min(batch, MAX_ERASE_BATCH);
207
+ }
208
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAEhF,MAAM,CAAC,MAAM,cAAc,GAAG,OAAO,CAAC;AAEtC,mEAAmE;AACnE,MAAM,CAAC,MAAM,aAAa,GAAG,QAAQ,CAAC;AAEtC,oCAAoC;AACpC,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,CAAC;AAElC,8EAA8E;AAC9E,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AACvC,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,CAAC;AA2BnC,gFAAgF;AAChF,MAAM,UAAU,eAAe,CAAC,IAAgB;IAC9C,OAAO,IAAI,CAAC,IAAI,KAAK,UAAU;QAC7B,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC;YACb,IAAI,CAAC,IAAI;YACT,IAAI,CAAC,MAAM;YACX,IAAI,CAAC,QAAQ;YACb,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CA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,KAAc;IAIjD,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,IAAI,OAAO,CAAC,UAAU,CAAC,mBAAmB,CAAC,EAAE,CAAC;QAC5C,OAAO;YACL,IAAI,EAAE,kBAAkB;YACxB,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,mBAAmB,CAAC,MAAM,CAAC;SACnD,CAAC;IACJ,CAAC;IACD,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC;KACvD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAa;IAC3C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;AAC1C,CAAC"}
package/docs/API.md ADDED
@@ -0,0 +1,94 @@
1
+ # API Reference — @vllnt/convex-quota
2
+
3
+ **Compatibility:** `convex@^1.45.0`
4
+
5
+ ```ts
6
+ import { Quota } from "@vllnt/convex-quota";
7
+ const quota = new Quota(components.quota, { defaultScope: "global" });
8
+ ```
9
+
10
+ The host owns authentication, authorization and policy. Never accept identity,
11
+ limit, amount, scope or window policy directly from an untrusted caller.
12
+ `subjectRef`, `key`, `scope`, and refund `periodKey` must be nonempty strings of
13
+ at most 256 UTF-16 code units (`INVALID_REF`). Amounts and limits must be positive
14
+ safe integers (`INVALID_AMOUNT`, `INVALID_LIMIT`). Scope defaults to `"global"`.
15
+ All component errors use `ConvexError({ code, message })`.
16
+
17
+ ## Windows
18
+
19
+ - `{ kind: "calendar", period: "day" | "week" | "month", timeZone: string, weekStartsOn?: "monday" | "sunday" }`
20
+ - `{ kind: "rolling", durationMs: number }` — starts at first **allowed** consume.
21
+ - `{ kind: "epoch", durationMs: number }` — Unix epoch-aligned duration buckets.
22
+
23
+ Calendar weeks default to Monday. Timezones are validated by `Intl`; invalid
24
+ names throw `INVALID_TIME_ZONE`. Repeated midnight uses the earlier occurrence;
25
+ skipped midnight/date advances through the gap. Days can have 23 or 25 hours.
26
+ Durations must be positive safe integer milliseconds with a safely representable
27
+ end timestamp (`INVALID_DURATION`).
28
+
29
+ A `(scope, subjectRef, key)` has a fixed window policy. Changing kind, duration,
30
+ calendar period, timezone spelling, or effective week start throws
31
+ `POLICY_MISMATCH`, even after expiry. Use a new key for a new policy. Changing the
32
+ limit does not reset usage. `periodKey` is an opaque window label, not an
33
+ idempotency token; do not parse it or reuse it across keys, scopes, or erased rows.
34
+
35
+ ## Mutations
36
+
37
+ ### `consume(ctx, subjectRef, key, limit, window, opts?)`
38
+
39
+ `opts: { scope?: string; amount?: number }`; amount defaults to 1.
40
+ Returns `{ allowed: boolean, remaining: number, used: number, limit: number,
41
+ periodKey: string, resetsAt: number }`. Denied calls do not write. A lower limit
42
+ can return `used > limit` with zero remaining. Successful calls store the latest
43
+ limit for refund calculations. Not idempotent: deduplicate host event retries
44
+ in the same transaction (e.g. with `@vllnt/convex-idempotency`).
45
+
46
+ ### `refund(ctx, subjectRef, key, amount, periodKey, scope?)`
47
+
48
+ Returns `{ refunded: boolean, used: number, remaining: number }` in all cases.
49
+ Subtracts amount, clamped at zero, only if the stored period matches and has not
50
+ expired. Otherwise returns `refunded: false` and the stored row's usage/remaining
51
+ (or zeros if absent); these are not a recomputed current-window allowance.
52
+ Remaining uses the limit from the last successful consume, not a later query or
53
+ denied call. A matching zero-usage row still returns `refunded: true`.
54
+
55
+ Privileged, **not idempotent**: repeated refunds subtract repeatedly. The host
56
+ must authorize and deduplicate compensation events transactionally. Erasing and
57
+ recreating the same calendar period can reuse a label: old refunds must not be
58
+ replayed against it.
59
+
60
+ ### `eraseSubject(ctx, subjectRef, scope?, batch?)`
61
+
62
+ Returns the number deleted **this pass**, not the total. Deletes up to batch
63
+ rows (positive integer, default 200, capped at 500; `INVALID_BATCH` otherwise).
64
+ Schedules another pass if full, including a possible final empty pass. Scope is
65
+ always enforced. The host must quiesce writes until scheduled cleanup completes;
66
+ there is no tombstone and a racing consume can survive or be swept. Monitor the
67
+ Convex scheduler for failures. Component mutations are atomic within each pass,
68
+ not across the whole sweep.
69
+
70
+ ## Queries
71
+
72
+ ### `remaining(ctx, subjectRef, key, limit, window, scope?)`
73
+
74
+ Returns `{ remaining: number, used: number, limit: number, periodKey: string,
75
+ resetsAt: number }`. Computes the current window when the query runs; an expired
76
+ row reads as zero usage without writing. A query does not start a rolling window.
77
+ Time is server-sourced, but **time passing alone does not invalidate a cached
78
+ query/subscription**. Treat resetsAt as an expiry hint and use consume for the
79
+ authoritative decision. No timer or reset scheduler is installed.
80
+
81
+ ## Isolation and operations
82
+
83
+ Mount multiple instances with `app.use(quota, { name: "webQuota" })` and
84
+ `app.use(quota, { name: "mobileQuota" })`; each client receives its own generated
85
+ component reference. Runtime scopes isolate indexed reads and erasures inside a
86
+ mount. One row per allowance means hot-key writes contend; different keys are
87
+ independent. No historical usage, receipts, logs or audit trail are stored.
88
+ Host audit instrumentation should avoid exposing opaque refs or sensitive data.
89
+
90
+ ## Testing limits
91
+
92
+ `pnpm test:coverage` runs convex-test's mock backend, including adversarial
93
+ validation, civil-time transitions and scheduled-batch tests. It is not evidence
94
+ of real Convex OCC retries or real scheduler delivery.