diff --git a/lib/sdk.test.js b/lib/sdk.test.js index fc56063..df33db7 100644 --- a/lib/sdk.test.js +++ b/lib/sdk.test.js @@ -21,17 +21,29 @@ test("eid ignores case", () => { expect(eid).toEqual(OptableSDK.eid(var4)); }); -test("cid is correct", () => { - const expected = "c:FooBarBAZ-01234#98765.!!!"; +test("cid rejects non-string id", () => { + expect(() => OptableSDK.cid(1)).toThrow(); +}); - expect(expected).toEqual(OptableSDK.cid("FooBarBAZ-01234#98765.!!!")); - expect(expected).toEqual(OptableSDK.cid(" FooBarBAZ-01234#98765.!!!")); - expect(expected).toEqual(OptableSDK.cid("FooBarBAZ-01234#98765.!!! ")); - expect(expected).toEqual(OptableSDK.cid(" FooBarBAZ-01234#98765.!!! ")); +test("cid prefixes with c: by default", () => { + expect(OptableSDK.cid("abc")).toEqual("c:abc"); }); -test("cid is case sensitive", () => { - const unexpected = "c:FooBarBAZ-01234#98765.!!!"; +test("cid accepts a custom variant", () => { + expect(OptableSDK.cid("abc", 0)).toEqual("c:abc"); + for (let i = 1; i < 10; i++) { + expect(OptableSDK.cid("abc", i)).toEqual(`c${i}:abc`); + } + + expect(() => OptableSDK.cid("abc", -1)).toThrow(); + expect(() => OptableSDK.cid("abc", 10)).toThrow(); + expect(() => OptableSDK.cid("abc", "1")).toThrow(); +}); + +test("cid trim spaces", () => { + expect(OptableSDK.cid(" \n abc\t")).toEqual("c:abc"); +}); - expect(OptableSDK.cid("foobarBAZ-01234#98765.!!!")).not.toEqual(unexpected); +test("cid preserve case", () => { + expect(OptableSDK.cid("ABCD")).toEqual("c:ABCD"); }); diff --git a/lib/sdk.ts b/lib/sdk.ts index c1f20c1..927c379 100644 --- a/lib/sdk.ts +++ b/lib/sdk.ts @@ -99,8 +99,22 @@ class OptableSDK { return email ? "e:" + sha256.hex(email.toLowerCase().trim()) : ""; } - static cid(ppid: string): string { - return ppid ? "c:" + ppid.trim() : ""; + static cid(ppid: string, variant: number = 0): string { + let prefix = "c:"; + + if (typeof ppid !== "string") { + throw new Error("Invalid ppid"); + } + + if (typeof variant !== "number" || isNaN(variant) || variant < 0 || variant > 9) { + throw new Error("Invalid variant"); + } + + if (variant > 0) { + prefix = `c${variant}:`; + } + + return ppid ? prefix + ppid.trim() : ""; } static TargetingKeyValues(tdata: TargetingResponse): TargetingKeyValues {