Skip to content

Commit

Permalink
feature(macro): hash based id for js macro
Browse files Browse the repository at this point in the history
  • Loading branch information
timofei-iatsenko committed Feb 15, 2023
1 parent 44f8360 commit 9faba10
Show file tree
Hide file tree
Showing 15 changed files with 498 additions and 274 deletions.
3 changes: 1 addition & 2 deletions packages/macro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@
"dependencies": {
"@babel/runtime": "^7.20.13",
"@babel/types": "^7.20.7",
"@lingui/conf": "3.17.1",
"ramda": "^0.27.1"
"@lingui/conf": "3.17.1"
},
"peerDependencies": {
"@lingui/core": "^3.13.0",
Expand Down
24 changes: 24 additions & 0 deletions packages/macro/src/generateMessageId.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { generateMessageId } from "./generateMessageId"

describe("generateMessageId", () => {
it("Should generate an id for a message", () => {
expect(generateMessageId("my message")).toMatchInlineSnapshot(`vQhkQx`)
})

it("Should generate different id when context is provided", () => {
const withContext = generateMessageId("my message", "custom context")
expect(withContext).toMatchInlineSnapshot(`gGUeZH`)

expect(withContext != generateMessageId("my message")).toBeTruthy()
})

it("Message + context should not clash with message with suffix or prefix", () => {
const context = "custom context"
const withContext = generateMessageId("my message", context)
const withSuffix = generateMessageId("my message" + context)
const withPrefix = generateMessageId(context, "my message")

expect(withContext != withSuffix).toBeTruthy()
expect(withContext != withPrefix).toBeTruthy()
})
})
11 changes: 11 additions & 0 deletions packages/macro/src/generateMessageId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import crypto from "crypto"

const UNIT_SEPARATOR = "\u001F"

export function generateMessageId(msg: string, context = "") {
return crypto
.createHash("sha256")
.update(msg + UNIT_SEPARATOR + context)
.digest("base64")
.slice(0, 6)
}
Loading

0 comments on commit 9faba10

Please sign in to comment.