@ca-tax/mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1874 @@
1
+ // @generated standalone MCP bundle for @ca-tax/mcp
2
+
3
+ // packages/ca-tax-mcp/src/server.ts
4
+ import { createServer } from "node:http";
5
+
6
+ // src/lib/parser/fitid-v1.ts
7
+ var SEQ_CAPACITY = 36 * 36 - 1;
8
+ var K = new Uint32Array([
9
+ 1116352408,
10
+ 1899447441,
11
+ 3049323471,
12
+ 3921009573,
13
+ 961987163,
14
+ 1508970993,
15
+ 2453635748,
16
+ 2870763221,
17
+ 3624381080,
18
+ 310598401,
19
+ 607225278,
20
+ 1426881987,
21
+ 1925078388,
22
+ 2162078206,
23
+ 2614888103,
24
+ 3248222580,
25
+ 3835390401,
26
+ 4022224774,
27
+ 264347078,
28
+ 604807628,
29
+ 770255983,
30
+ 1249150122,
31
+ 1555081692,
32
+ 1996064986,
33
+ 2554220882,
34
+ 2821834349,
35
+ 2952996808,
36
+ 3210313671,
37
+ 3336571891,
38
+ 3584528711,
39
+ 113926993,
40
+ 338241895,
41
+ 666307205,
42
+ 773529912,
43
+ 1294757372,
44
+ 1396182291,
45
+ 1695183700,
46
+ 1986661051,
47
+ 2177026350,
48
+ 2456956037,
49
+ 2730485921,
50
+ 2820302411,
51
+ 3259730800,
52
+ 3345764771,
53
+ 3516065817,
54
+ 3600352804,
55
+ 4094571909,
56
+ 275423344,
57
+ 430227734,
58
+ 506948616,
59
+ 659060556,
60
+ 883997877,
61
+ 958139571,
62
+ 1322822218,
63
+ 1537002063,
64
+ 1747873779,
65
+ 1955562222,
66
+ 2024104815,
67
+ 2227730452,
68
+ 2361852424,
69
+ 2428436474,
70
+ 2756734187,
71
+ 3204031479,
72
+ 3329325298
73
+ ]);
74
+ var W = new Uint32Array(64);
75
+ function sha256Bytes(input) {
76
+ const msg = typeof input === "string" ? new TextEncoder().encode(input) : input;
77
+ const len = msg.length;
78
+ const total = len + 9 + 63 >> 6 << 6;
79
+ const buf = new Uint8Array(total);
80
+ buf.set(msg);
81
+ buf[len] = 128;
82
+ const dv = new DataView(buf.buffer);
83
+ dv.setUint32(total - 8, Math.floor(len * 8 / 4294967296));
84
+ dv.setUint32(total - 4, len * 8 >>> 0);
85
+ let h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762;
86
+ let h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225;
87
+ for (let off = 0; off < total; off += 64) {
88
+ for (let i = 0; i < 16; i++) W[i] = dv.getUint32(off + i * 4);
89
+ for (let i = 16; i < 64; i++) {
90
+ const a2 = W[i - 15], b2 = W[i - 2];
91
+ const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3;
92
+ const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10;
93
+ W[i] = W[i - 16] + s0 + W[i - 7] + s1 | 0;
94
+ }
95
+ let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
96
+ for (let i = 0; i < 64; i++) {
97
+ const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
98
+ const ch = e & f ^ ~e & g;
99
+ const t1 = h + S1 + ch + K[i] + W[i] | 0;
100
+ const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
101
+ const maj = a & b ^ a & c ^ b & c;
102
+ const t2 = S0 + maj | 0;
103
+ h = g;
104
+ g = f;
105
+ f = e;
106
+ e = d + t1 | 0;
107
+ d = c;
108
+ c = b;
109
+ b = a;
110
+ a = t1 + t2 | 0;
111
+ }
112
+ h0 = h0 + a | 0;
113
+ h1 = h1 + b | 0;
114
+ h2 = h2 + c | 0;
115
+ h3 = h3 + d | 0;
116
+ h4 = h4 + e | 0;
117
+ h5 = h5 + f | 0;
118
+ h6 = h6 + g | 0;
119
+ h7 = h7 + h | 0;
120
+ }
121
+ const out = new Uint8Array(32);
122
+ const odv = new DataView(out.buffer);
123
+ [h0, h1, h2, h3, h4, h5, h6, h7].forEach((v, i) => odv.setUint32(i * 4, v >>> 0));
124
+ return out;
125
+ }
126
+ function sha256Hex(input) {
127
+ const d = sha256Bytes(input);
128
+ let s = "";
129
+ for (let i = 0; i < d.length; i++) s += d[i].toString(16).padStart(2, "0");
130
+ return s;
131
+ }
132
+
133
+ // src/api-worker/receipts.ts
134
+ function canonicalJson(value) {
135
+ if (value === null) return "null";
136
+ switch (typeof value) {
137
+ case "string":
138
+ return JSON.stringify(value);
139
+ case "number":
140
+ if (!Number.isFinite(value)) throw new TypeError("Non-finite number in canonical JSON");
141
+ return JSON.stringify(value === 0 ? 0 : value);
142
+ case "boolean":
143
+ return value ? "true" : "false";
144
+ case "object": {
145
+ if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
146
+ const obj2 = value;
147
+ const parts = [];
148
+ for (const k of Object.keys(obj2).sort()) {
149
+ if (obj2[k] === void 0) continue;
150
+ parts.push(`${JSON.stringify(k)}:${canonicalJson(obj2[k])}`);
151
+ }
152
+ return `{${parts.join(",")}}`;
153
+ }
154
+ default:
155
+ throw new TypeError(`Unsupported type in canonical JSON: ${typeof value}`);
156
+ }
157
+ }
158
+ function digestSha256(value) {
159
+ if (typeof value === "string" || value instanceof Uint8Array) return sha256Hex(value);
160
+ return sha256Hex(canonicalJson(value));
161
+ }
162
+ function bytesToB64(bytes) {
163
+ let s = "";
164
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
165
+ return btoa(s);
166
+ }
167
+ function b64ToBytes(b64) {
168
+ const norm = b64.replace(/-/g, "+").replace(/_/g, "/").replace(/\s+/g, "");
169
+ const s = atob(norm + "=".repeat((4 - norm.length % 4) % 4));
170
+ const out = new Uint8Array(s.length);
171
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
172
+ return out;
173
+ }
174
+ function toBase64Url(bytes) {
175
+ return bytesToB64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
176
+ }
177
+ var PKCS8_ED25519_PREFIX = new Uint8Array([48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32]);
178
+ var SPKI_ED25519_PREFIX = new Uint8Array([48, 42, 48, 5, 6, 3, 43, 101, 112, 3, 33, 0]);
179
+ function concat(a, b) {
180
+ const o = new Uint8Array(a.length + b.length);
181
+ o.set(a);
182
+ o.set(b, a.length);
183
+ return o;
184
+ }
185
+ function stripPem(s) {
186
+ return s.replace(/-----(BEGIN|END)[^-]+-----/g, "").replace(/\s+/g, "");
187
+ }
188
+ var ED = { name: "Ed25519" };
189
+ async function importPrivate(raw) {
190
+ const t = raw.trim();
191
+ if (t.startsWith("{")) {
192
+ const jwk = JSON.parse(t);
193
+ return crypto.subtle.importKey("jwk", { ...jwk, key_ops: ["sign"], ext: true }, ED, true, ["sign"]);
194
+ }
195
+ const bytes = b64ToBytes(stripPem(t));
196
+ const pkcs8 = bytes.length === 32 ? concat(PKCS8_ED25519_PREFIX, bytes) : bytes;
197
+ return crypto.subtle.importKey("pkcs8", pkcs8, ED, true, ["sign"]);
198
+ }
199
+ async function importPublic(raw) {
200
+ const t = raw.trim();
201
+ if (t.startsWith("{")) {
202
+ const jwk = JSON.parse(t);
203
+ const { d: _d, ...pub } = jwk;
204
+ return crypto.subtle.importKey("jwk", { ...pub, key_ops: ["verify"], ext: true }, ED, true, ["verify"]);
205
+ }
206
+ const bytes = b64ToBytes(stripPem(t));
207
+ const spki = bytes.length === 32 ? concat(SPKI_ED25519_PREFIX, bytes) : bytes;
208
+ return crypto.subtle.importKey("spki", spki, ED, true, ["verify"]);
209
+ }
210
+ async function publicFromPrivate(priv) {
211
+ const jwk = await crypto.subtle.exportKey("jwk", priv);
212
+ return crypto.subtle.importKey("jwk", { kty: jwk.kty, crv: jwk.crv, x: jwk.x, ext: true }, ED, true, ["verify"]);
213
+ }
214
+ var keyCache = /* @__PURE__ */ new Map();
215
+ var DEV_SEED = sha256Bytes32("exactrows-receipt-v1-dev-ephemeral-key");
216
+ function sha256Bytes32(s) {
217
+ const hex = sha256Hex(s);
218
+ const out = new Uint8Array(32);
219
+ for (let i = 0; i < 32; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
220
+ return out;
221
+ }
222
+ function loadReceiptKeys(env = {}) {
223
+ const priv = env.EXACTROWS_RECEIPT_ED25519_PRIVATE_KEY?.trim() || "";
224
+ const pub = env.EXACTROWS_RECEIPT_ED25519_PUBLIC_KEY?.trim() || "";
225
+ const cacheKey = `${priv}\0${pub}`;
226
+ let p = keyCache.get(cacheKey);
227
+ if (!p) {
228
+ p = (async () => {
229
+ if (!priv) {
230
+ const privateKey2 = await importPrivate(bytesToB64(DEV_SEED));
231
+ return { privateKey: privateKey2, publicKey: await publicFromPrivate(privateKey2), ephemeral: true };
232
+ }
233
+ const privateKey = await importPrivate(priv);
234
+ const publicKey = pub ? await importPublic(pub) : await publicFromPrivate(privateKey);
235
+ return { privateKey, publicKey, ephemeral: false };
236
+ })();
237
+ p.catch(() => keyCache.delete(cacheKey));
238
+ keyCache.set(cacheKey, p);
239
+ }
240
+ return p;
241
+ }
242
+ async function signReceiptPayload(unsigned, env = {}) {
243
+ const { privateKey } = await loadReceiptKeys(env);
244
+ const sig = await crypto.subtle.sign(ED, privateKey, new TextEncoder().encode(canonicalJson(unsigned)));
245
+ return toBase64Url(new Uint8Array(sig));
246
+ }
247
+ function newReceiptId() {
248
+ const bytes = crypto.getRandomValues(new Uint8Array(24));
249
+ const alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
250
+ let s = "rcpt_";
251
+ for (let i = 0; i < bytes.length; i++) s += alpha[bytes[i] % alpha.length];
252
+ return s;
253
+ }
254
+ var DEFAULT_ENGINE_VERSION = "3.1.0";
255
+ var EMPTY_MATH = {
256
+ currency: "CAD",
257
+ openingCents: 0,
258
+ creditsCents: 0,
259
+ debitsCents: 0,
260
+ closingCents: 0,
261
+ deltaCents: 0,
262
+ balanced: true,
263
+ transactionCount: 0
264
+ };
265
+ async function buildReceipt(input, env = {}) {
266
+ const unsigned = {
267
+ receiptVersion: "ExactRows-Receipt-v1",
268
+ receiptId: input.receiptId ?? newReceiptId(),
269
+ timestampUtc: input.timestampUtc ?? (/* @__PURE__ */ new Date()).toISOString(),
270
+ engineVersion: input.engineVersion ?? DEFAULT_ENGINE_VERSION,
271
+ endpoint: input.endpoint,
272
+ clientId: input.clientId ?? null,
273
+ issuerDisplayName: input.issuerDisplayName ?? null,
274
+ retentionMode: input.retentionMode ?? "none",
275
+ inputSha256: input.inputSha256 ?? digestSha256(input.input ?? ""),
276
+ outputSha256: input.outputSha256 ?? digestSha256(input.output ?? ""),
277
+ reconciliationMath: input.reconciliationMath ?? EMPTY_MATH,
278
+ repairsApplied: input.repairsApplied ?? [],
279
+ ...input.rowConfidenceSummary !== void 0 ? { rowConfidenceSummary: input.rowConfidenceSummary } : {}
280
+ };
281
+ const ed25519Signature = await signReceiptPayload(unsigned, env);
282
+ return { ...unsigned, ed25519Signature };
283
+ }
284
+
285
+ // src/lib/parser/reconcile.ts
286
+ var DATE_TOKEN_RE_SRC = "(?:\\b\\d{4}[-/]\\d{2}[-/]\\d{2}\\b|\\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|janv|fev|fevr|mars|avr|mai|juin|juil|juill|aou|aout|sept|oct|nov|dec|ene|abr|ago|set|dic)[a-z.]*\\s*\\d{1,2}\\b|\\b\\d{1,2}(?:er)?(?:\\s+de\\s+|[\\s-]+)(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|janv|fev|fevr|mars|avr|mai|juin|juil|juill|aou|aout|sept|ene|abr|ago|set|dic)[a-z.]*(?:(?:\\s+de\\s+|[\\s-]+)\\d{2,4})?\\b|\\b\\d{1,2}[/-]\\d{1,2}(?:[/-]\\d{2,4})?\\b)";
287
+ var MONEY_TOKEN_RE_SRC = "(?:[-\\u2013\\u2014\\u2212]?\\$?\\s*(?:\\d{1,3}(?:[ \\u00a0\\u202f,.]\\d{3})*|\\d+)?(?:[.,]\\d{2}|[.,]\\d(?=\\s*(?:CR|DR|[CD]\\b)))(?:\\s*\\$|\\s*(?:CR|DR|CAD|USD|MXN|[-\\u2013\\u2014\\u2212])|\\s+[CD](?=\\s|$))?)";
288
+ var DATE_OR_MONEY_LINE_RE = new RegExp(
289
+ `(?:${DATE_TOKEN_RE_SRC}.*?${MONEY_TOKEN_RE_SRC}|${MONEY_TOKEN_RE_SRC}.*?${DATE_TOKEN_RE_SRC})`,
290
+ "i"
291
+ );
292
+
293
+ // src/lib/parser/qbo-validator.ts
294
+ var MAX_QBO_INPUT_BYTES = 15 * 1024 * 1024;
295
+
296
+ // src/api-worker/auth.ts
297
+ var MAX_BODY_BYTES = 10 * 1024 * 1024;
298
+ var encoder = new TextEncoder();
299
+ var POLAR_REVALIDATE_MS = 60 * 60 * 1e3;
300
+ var IDEMPOTENCY_MAX_CACHED_BYTES = 5 * 1024 * 1024;
301
+
302
+ // src/api-worker/billback.ts
303
+ var CLIENT_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
304
+ var USAGE_TTL_SECONDS = 400 * 86400;
305
+
306
+ // src/api-worker/routes/qbo.ts
307
+ var MAX_BODY_BYTES2 = 10 * 1024 * 1024;
308
+ var ENGINE_VERSION = "3.1.0";
309
+ function apiJson(body, status = 200, headers = {}) {
310
+ return new Response(JSON.stringify(body), {
311
+ status,
312
+ headers: { "content-type": "application/json; charset=utf-8", ...headers }
313
+ });
314
+ }
315
+ function apiError(status, code, message, localizedMessage, extra = {}) {
316
+ return apiJson(
317
+ {
318
+ ok: false,
319
+ error: {
320
+ code,
321
+ message,
322
+ localizedMessage: localizedMessage ?? message,
323
+ retryable: status >= 500 || status === 429,
324
+ ...extra
325
+ },
326
+ receipt: null
327
+ },
328
+ status
329
+ );
330
+ }
331
+ function receiptHeaders(receipt, ctx) {
332
+ return {
333
+ ...receipt ? { "x-exactrows-receipt-id": receipt.receiptId } : {},
334
+ "x-exactrows-engine-version": ctx.engineVersion ?? ENGINE_VERSION,
335
+ "x-exactrows-retention": "none",
336
+ "cache-control": "no-store"
337
+ };
338
+ }
339
+ function pickLang(body, ctx, url) {
340
+ const candidates = [body?.lang, url.searchParams.get("lang"), ctx.lang];
341
+ for (const c of candidates) if (c === "fr" || c === "en") return c;
342
+ return "en";
343
+ }
344
+ async function readJsonBody(request) {
345
+ const declared = Number(request.headers.get("content-length") ?? "0");
346
+ const tooLarge = () => ({
347
+ ok: false,
348
+ response: apiError(413, "PAYLOAD_TOO_LARGE", "Request body exceeds the 10 MiB limit.", "Le corps de la requ\xEAte d\xE9passe la limite de 10 Mio.")
349
+ });
350
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES2) return tooLarge();
351
+ let text;
352
+ try {
353
+ text = await request.text();
354
+ } catch {
355
+ return { ok: false, response: apiError(400, "INVALID_JSON", "Request body must be valid JSON.", "Le corps doit \xEAtre du JSON valide.") };
356
+ }
357
+ if (text.length > MAX_BODY_BYTES2 || new TextEncoder().encode(text).byteLength > MAX_BODY_BYTES2) return tooLarge();
358
+ let parsed;
359
+ try {
360
+ parsed = JSON.parse(text);
361
+ } catch {
362
+ return { ok: false, response: apiError(400, "INVALID_JSON", "Request body must be valid JSON.", "Le corps doit \xEAtre du JSON valide.") };
363
+ }
364
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
365
+ return { ok: false, response: apiError(400, "INVALID_JSON", "Request body must be a JSON object.", "Le corps doit \xEAtre un objet JSON.") };
366
+ }
367
+ const body = parsed;
368
+ if (body.clientId !== void 0 && (typeof body.clientId !== "string" || !CLIENT_ID_PATTERN.test(body.clientId))) {
369
+ return { ok: false, response: apiError(400, "INVALID_CLIENT_ID", "clientId must be 1-64 chars of A-Z a-z 0-9 - _.") };
370
+ }
371
+ return { ok: true, body };
372
+ }
373
+ async function issueReceipt(env, ctx, endpoint, input, output, math, repairs = []) {
374
+ return buildReceipt(
375
+ {
376
+ endpoint,
377
+ engineVersion: ctx.engineVersion ?? ENGINE_VERSION,
378
+ clientId: ctx.clientId ?? null,
379
+ issuerDisplayName: ctx.issuerDisplayName ?? null,
380
+ retentionMode: "none",
381
+ inputSha256: digestSha256(input),
382
+ outputSha256: digestSha256(output),
383
+ reconciliationMath: math,
384
+ repairsApplied: repairs
385
+ },
386
+ env ?? {}
387
+ );
388
+ }
389
+
390
+ // src/api-worker/routes/ca-tax.ts
391
+ var CaTaxValidationError = class extends Error {
392
+ code;
393
+ localizedMessage;
394
+ constructor(code, message, localizedMessage) {
395
+ super(message);
396
+ this.code = code;
397
+ this.localizedMessage = localizedMessage;
398
+ }
399
+ };
400
+ var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
401
+ var POSTAL_RE = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z](?:\d[ABCEGHJ-NPRSTV-Z]\d)?$/;
402
+ var PROVINCE_NAMES = {
403
+ AB: { en: "Alberta", fr: "Alberta" },
404
+ BC: { en: "British Columbia", fr: "Colombie-Britannique" },
405
+ MB: { en: "Manitoba", fr: "Manitoba" },
406
+ NB: { en: "New Brunswick", fr: "Nouveau-Brunswick" },
407
+ NL: { en: "Newfoundland and Labrador", fr: "Terre-Neuve-et-Labrador" },
408
+ NS: { en: "Nova Scotia", fr: "Nouvelle-\xC9cosse" },
409
+ NT: { en: "Northwest Territories", fr: "Territoires du Nord-Ouest" },
410
+ NU: { en: "Nunavut", fr: "Nunavut" },
411
+ ON: { en: "Ontario", fr: "Ontario" },
412
+ PE: { en: "Prince Edward Island", fr: "\xCEle-du-Prince-\xC9douard" },
413
+ QC: { en: "Quebec", fr: "Qu\xE9bec" },
414
+ SK: { en: "Saskatchewan", fr: "Saskatchewan" },
415
+ YT: { en: "Yukon", fr: "Yukon" }
416
+ };
417
+ var FSA_FIRST_LETTER_TO_PROVINCE = {
418
+ A: "NL",
419
+ B: "NS",
420
+ C: "PE",
421
+ E: "NB",
422
+ G: "QC",
423
+ H: "QC",
424
+ J: "QC",
425
+ K: "ON",
426
+ L: "ON",
427
+ M: "ON",
428
+ N: "ON",
429
+ P: "ON",
430
+ R: "MB",
431
+ S: "SK",
432
+ T: "AB",
433
+ V: "BC",
434
+ X: "NT",
435
+ Y: "YT"
436
+ };
437
+ var NUNAVUT_FSAS = /* @__PURE__ */ new Set(["X0A", "X0B", "X0C"]);
438
+ var NT_FSAS = /* @__PURE__ */ new Set(["X0E", "X0G", "X1A"]);
439
+ var AMBIGUOUS_BORDER_FSAS = {
440
+ S9V: {
441
+ en: "FSA S9V covers Lloydminster, which straddles the Saskatchewan/Alberta border; verify municipal side for SK PST exemption.",
442
+ fr: "La RTA S9V couvre Lloydminster, \xE0 cheval sur la fronti\xE8re Saskatchewan/Alberta; v\xE9rifiez le c\xF4t\xE9 municipal pour l\u2019exon\xE9ration de TVP."
443
+ },
444
+ T9V: {
445
+ en: "FSA T9V covers Lloydminster (Alberta side), adjacent to the Saskatchewan border.",
446
+ fr: "La RTA T9V couvre Lloydminster (c\xF4t\xE9 Alberta), \xE0 la fronti\xE8re de la Saskatchewan."
447
+ },
448
+ K1A: {
449
+ en: "FSA K1A is assigned to Government of Canada federal offices across both Ottawa (ON) and Gatineau (QC).",
450
+ fr: "La RTA K1A est attribu\xE9e aux bureaux f\xE9d\xE9raux du gouvernement du Canada \xE0 Ottawa (ON) et Gatineau (QC)."
451
+ },
452
+ R8A: {
453
+ en: "FSA R8A covers Flin Flon, which spans the Manitoba/Saskatchewan border.",
454
+ fr: "La RTA R8A couvre Flin Flon, \xE0 cheval sur la fronti\xE8re Manitoba/Saskatchewan."
455
+ },
456
+ S0P: {
457
+ en: "FSA S0P covers northern Saskatchewan communities adjacent to Flin Flon (MB) along the MB/SK border.",
458
+ fr: "La RTA S0P couvre des communaut\xE9s du nord de la Saskatchewan adjacentes \xE0 Flin Flon (MB) sur la fronti\xE8re MB/SK."
459
+ }
460
+ };
461
+ function isValidIsoDate(s) {
462
+ if (!DATE_RE.test(s)) return false;
463
+ const d = /* @__PURE__ */ new Date(`${s}T00:00:00Z`);
464
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;
465
+ }
466
+ function todayIsoUtc() {
467
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
468
+ }
469
+ function normalizeProvince(raw) {
470
+ const p = raw.trim().toUpperCase();
471
+ if (p in PROVINCE_NAMES) return p;
472
+ throw new CaTaxValidationError(
473
+ "INVALID_PROVINCE",
474
+ `Unsupported Canadian province/territory "${raw}".`,
475
+ `Province ou territoire canadien non pris en charge \xAB ${raw} \xBB.`
476
+ );
477
+ }
478
+ function resolveSalesTaxRates(province, effectiveDate) {
479
+ switch (province) {
480
+ case "ON":
481
+ return { gst: 0, pst: 0, hst: 0.13, qst: 0, sourceCitation: "CRA GST/HST \u2014 Ontario (13% HST)" };
482
+ case "QC":
483
+ return {
484
+ gst: 0.05,
485
+ pst: 0,
486
+ hst: 0,
487
+ qst: 0.09975,
488
+ sourceCitation: "CRA GST (5%) + Revenu Qu\xE9bec QST / TVQ (9.975%, Loi sur la taxe de vente du Qu\xE9bec)"
489
+ };
490
+ case "AB":
491
+ case "NT":
492
+ case "NU":
493
+ case "YT":
494
+ return { gst: 0.05, pst: 0, hst: 0, qst: 0, sourceCitation: `CRA GST \u2014 ${PROVINCE_NAMES[province].en} (5% GST)` };
495
+ case "BC":
496
+ return {
497
+ gst: 0.05,
498
+ pst: 0.07,
499
+ hst: 0,
500
+ qst: 0,
501
+ sourceCitation: "CRA GST (5%) + BC Ministry of Finance PST (7%)"
502
+ };
503
+ case "SK":
504
+ return {
505
+ gst: 0.05,
506
+ pst: 0.06,
507
+ hst: 0,
508
+ qst: 0,
509
+ sourceCitation: "CRA GST (5%) + Saskatchewan Ministry of Finance PST (6%)"
510
+ };
511
+ case "MB":
512
+ return {
513
+ gst: 0.05,
514
+ pst: 0.07,
515
+ hst: 0,
516
+ qst: 0,
517
+ sourceCitation: "CRA GST (5%) + Manitoba Finance RST/PST (7%)"
518
+ };
519
+ case "NS":
520
+ if (effectiveDate >= "2025-04-01") {
521
+ return {
522
+ gst: 0,
523
+ pst: 0,
524
+ hst: 0.14,
525
+ qst: 0,
526
+ sourceCitation: "CRA GST/HST Notice \u2014 Nova Scotia 14% HST (effective 2025-04-01)"
527
+ };
528
+ }
529
+ return {
530
+ gst: 0,
531
+ pst: 0,
532
+ hst: 0.15,
533
+ qst: 0,
534
+ sourceCitation: "CRA GST/HST \u2014 Nova Scotia 15% HST (prior to 2025-04-01)"
535
+ };
536
+ case "NB":
537
+ case "NL":
538
+ case "PE":
539
+ return {
540
+ gst: 0,
541
+ pst: 0,
542
+ hst: 0.15,
543
+ qst: 0,
544
+ sourceCitation: `CRA GST/HST \u2014 ${PROVINCE_NAMES[province].en} (15% HST)`
545
+ };
546
+ }
547
+ }
548
+ function lookupCaSalesTax(input) {
549
+ const lang = input.lang === "fr" ? "fr" : "en";
550
+ const effectiveDate = input.effectiveDate?.trim() || todayIsoUtc();
551
+ if (!isValidIsoDate(effectiveDate)) {
552
+ throw new CaTaxValidationError(
553
+ "INVALID_DATE",
554
+ "effectiveDate must be a valid YYYY-MM-DD date.",
555
+ "effectiveDate doit \xEAtre une date valide au format YYYY-MM-DD."
556
+ );
557
+ }
558
+ let normalizedPostal = null;
559
+ let fsa = null;
560
+ let province;
561
+ let fsaBorderConfidence = "exact";
562
+ let borderNotes;
563
+ if (input.postal && input.postal.trim().length > 0) {
564
+ normalizedPostal = input.postal.replace(/\s+/g, "").toUpperCase();
565
+ if (!POSTAL_RE.test(normalizedPostal)) {
566
+ throw new CaTaxValidationError(
567
+ "INVALID_POSTAL_CODE",
568
+ "postal must be a valid Canadian postal code or 3-character FSA (e.g. H2Y1C6).",
569
+ "postal doit \xEAtre un code postal canadien valide ou une RTA de 3 caract\xE8res (ex. H2Y1C6)."
570
+ );
571
+ }
572
+ fsa = normalizedPostal.slice(0, 3);
573
+ const first = fsa[0];
574
+ if (first === "X") {
575
+ if (NUNAVUT_FSAS.has(fsa)) province = "NU";
576
+ else if (NT_FSAS.has(fsa)) province = "NT";
577
+ else {
578
+ province = "NT";
579
+ fsaBorderConfidence = "ambiguous_border";
580
+ borderNotes = lang === "fr" ? "RTA commen\xE7ant par X non r\xE9pertori\xE9e : fronti\xE8re Territoires du Nord-Ouest / Nunavut \xE0 confirmer." : "Unlisted X-prefix FSA: confirm Northwest Territories vs. Nunavut jurisdiction.";
581
+ }
582
+ } else {
583
+ province = FSA_FIRST_LETTER_TO_PROVINCE[first];
584
+ }
585
+ const border = AMBIGUOUS_BORDER_FSAS[fsa];
586
+ if (border) {
587
+ fsaBorderConfidence = "ambiguous_border";
588
+ borderNotes = border[lang];
589
+ if (normalizedPostal.length === 6) {
590
+ if (fsa === "K1A") {
591
+ const GATINEAU_K1A = /* @__PURE__ */ new Set(["K1A0B8", "K1A0B9", "K1A0S5", "K1A0H2", "K1A0H5", "K1A1C5", "K1A0T4"]);
592
+ if (GATINEAU_K1A.has(normalizedPostal)) {
593
+ province = "QC";
594
+ borderNotes = `${border[lang]} ${lang === "fr" ? `Code postal 6 caract\xE8res ${normalizedPostal} localis\xE9 \xE0 Gatineau (QC) : assujetti \xE0 la TPS (5 %) et \xE0 la TVQ (9,975 %).` : `6-character postal code ${normalizedPostal} localized to Gatineau (QC): subject to GST (5%) and QST (9.975%).`}`;
595
+ } else {
596
+ province = "ON";
597
+ borderNotes = `${border[lang]} ${lang === "fr" ? `Code postal 6 caract\xE8res ${normalizedPostal} localis\xE9 \xE0 Ottawa (ON) : assujetti \xE0 la TVH (13 %).` : `6-character postal code ${normalizedPostal} localized to Ottawa (ON): subject to HST (13%).`}`;
598
+ }
599
+ } else if (fsa === "S9V" || fsa === "T9V") {
600
+ const isSkPostal = fsa === "S9V";
601
+ borderNotes = `${border[lang]} ${lang === "fr" ? `Code postal 6 caract\xE8res ${normalizedPostal} (${isSkPostal ? "c\xF4t\xE9 Saskatchewan" : "c\xF4t\xE9 Alberta"}). En vertu de la charte de Lloydminster, les ventes locales sont exon\xE9r\xE9es de la TVP de la Saskatchewan (TPS de 5 % applicable).` : `6-character postal code ${normalizedPostal} (${isSkPostal ? "Saskatchewan side" : "Alberta side"}). Under the Lloydminster Charter, local retail transactions are exempt from SK PST (5% GST applies).`}`;
602
+ }
603
+ }
604
+ }
605
+ } else if (input.province && input.province.trim().length > 0) {
606
+ province = normalizeProvince(input.province);
607
+ } else {
608
+ throw new CaTaxValidationError(
609
+ "MISSING_POSTAL",
610
+ "postal query parameter is required.",
611
+ "Le param\xE8tre postal est requis."
612
+ );
613
+ }
614
+ const rates = resolveSalesTaxRates(province, effectiveDate);
615
+ const totalRate = Math.round((rates.gst + rates.pst + rates.hst + rates.qst) * 1e5) / 1e5;
616
+ const provinceName = PROVINCE_NAMES[province][lang];
617
+ const labels = lang === "fr" ? {
618
+ gst: "TPS",
619
+ pst: "TVP",
620
+ hst: "TVH",
621
+ qst: "TVQ",
622
+ summary: province === "QC" ? `Qu\xE9bec : TPS ${(rates.gst * 100).toFixed(0)} % + TVQ ${(rates.qst * 100).toFixed(3)} %` : rates.hst > 0 ? `${provinceName} : TVH ${(rates.hst * 100).toFixed(0)} %` : rates.pst > 0 ? `${provinceName} : TPS ${(rates.gst * 100).toFixed(0)} % + TVP ${(rates.pst * 100).toFixed(0)} %` : `${provinceName} : TPS ${(rates.gst * 100).toFixed(0)} %`
623
+ } : {
624
+ gst: "GST",
625
+ pst: "PST",
626
+ hst: "HST",
627
+ qst: "QST",
628
+ summary: province === "QC" ? `Quebec: GST ${(rates.gst * 100).toFixed(0)}% + QST ${(rates.qst * 100).toFixed(3)}%` : rates.hst > 0 ? `${provinceName}: HST ${(rates.hst * 100).toFixed(0)}%` : rates.pst > 0 ? `${provinceName}: GST ${(rates.gst * 100).toFixed(0)}% + PST ${(rates.pst * 100).toFixed(0)}%` : `${provinceName}: GST ${(rates.gst * 100).toFixed(0)}%`
629
+ };
630
+ return {
631
+ postal: normalizedPostal,
632
+ fsa,
633
+ province,
634
+ provinceName,
635
+ gst: rates.gst,
636
+ pst: rates.pst,
637
+ hst: rates.hst,
638
+ qst: rates.qst,
639
+ totalRate,
640
+ effectiveDate,
641
+ sourceCitation: rates.sourceCitation,
642
+ fsaBorderConfidence,
643
+ ...borderNotes ? { borderNotes } : {},
644
+ labels
645
+ };
646
+ }
647
+ var PAYROLL_PARAMS = {
648
+ 2025: {
649
+ cpp: {
650
+ exemptionCents: 35e4,
651
+ ympeCents: 713e4,
652
+ yampeCents: 812e4,
653
+ rate: 0.0595,
654
+ rate2: 0.04,
655
+ maxCents: 403410,
656
+ max2Cents: 39600
657
+ },
658
+ qpp: {
659
+ exemptionCents: 35e4,
660
+ ympeCents: 713e4,
661
+ yampeCents: 812e4,
662
+ rate: 0.064,
663
+ rate2: 0.04,
664
+ maxCents: 433920,
665
+ max2Cents: 39600
666
+ },
667
+ ei: {
668
+ maxInsurableCents: 657e4,
669
+ rateNonQc: 0.0164,
670
+ rateQc: 0.0131,
671
+ maxNonQcCents: 107748,
672
+ maxQcCents: 86067
673
+ },
674
+ qpip: {
675
+ maxInsurableCents: 98e5,
676
+ empRate: 494e-5,
677
+ erRate: 692e-5,
678
+ maxEmpCents: 48412,
679
+ maxErCents: 67816
680
+ },
681
+ cnt: { maxInsurableCents: 98e5, rate: 6e-4, maxCents: 5880 },
682
+ cnesst: { maxInsurableCents: 98e5 },
683
+ fed: {
684
+ bpaCents: 1612900,
685
+ ceaCents: 147100,
686
+ brackets: [
687
+ { upToCents: 5737500, rate: 0.15 },
688
+ { upToCents: 11475e3, rate: 0.205 },
689
+ { upToCents: 17788200, rate: 0.26 },
690
+ { upToCents: 25341400, rate: 0.29 },
691
+ { upToCents: Infinity, rate: 0.33 }
692
+ ]
693
+ },
694
+ prov: {
695
+ QC: {
696
+ bpaCents: 1857100,
697
+ brackets: [
698
+ { upToCents: 5325500, rate: 0.14 },
699
+ { upToCents: 10649500, rate: 0.19 },
700
+ { upToCents: 12959e3, rate: 0.24 },
701
+ { upToCents: Infinity, rate: 0.2575 }
702
+ ]
703
+ },
704
+ ON: {
705
+ bpaCents: 1274700,
706
+ brackets: [
707
+ { upToCents: 5288600, rate: 0.0505 },
708
+ { upToCents: 10577500, rate: 0.0915 },
709
+ { upToCents: 15e6, rate: 0.1116 },
710
+ { upToCents: 22e6, rate: 0.1216 },
711
+ { upToCents: Infinity, rate: 0.1316 }
712
+ ]
713
+ },
714
+ AB: {
715
+ bpaCents: 2232300,
716
+ brackets: [
717
+ { upToCents: 15123400, rate: 0.1 },
718
+ { upToCents: 18148100, rate: 0.12 },
719
+ { upToCents: 24197400, rate: 0.13 },
720
+ { upToCents: 36296100, rate: 0.14 },
721
+ { upToCents: Infinity, rate: 0.15 }
722
+ ]
723
+ },
724
+ BC: {
725
+ bpaCents: 1293200,
726
+ brackets: [
727
+ { upToCents: 4927900, rate: 0.0506 },
728
+ { upToCents: 9856e3, rate: 0.077 },
729
+ { upToCents: 11315800, rate: 0.105 },
730
+ { upToCents: 13740700, rate: 0.1229 },
731
+ { upToCents: 18630600, rate: 0.147 },
732
+ { upToCents: 25982900, rate: 0.168 },
733
+ { upToCents: Infinity, rate: 0.205 }
734
+ ]
735
+ },
736
+ MB: {
737
+ bpaCents: 1578e3,
738
+ brackets: [
739
+ { upToCents: 47e5, rate: 0.108 },
740
+ { upToCents: 1e7, rate: 0.1275 },
741
+ { upToCents: Infinity, rate: 0.174 }
742
+ ]
743
+ },
744
+ SK: {
745
+ bpaCents: 1949100,
746
+ brackets: [
747
+ { upToCents: 5346300, rate: 0.105 },
748
+ { upToCents: 15275e3, rate: 0.125 },
749
+ { upToCents: Infinity, rate: 0.145 }
750
+ ]
751
+ },
752
+ NB: {
753
+ bpaCents: 1339600,
754
+ brackets: [
755
+ { upToCents: 5130600, rate: 0.094 },
756
+ { upToCents: 10261400, rate: 0.14 },
757
+ { upToCents: 19006e3, rate: 0.16 },
758
+ { upToCents: Infinity, rate: 0.195 }
759
+ ]
760
+ },
761
+ NS: {
762
+ bpaCents: 1174400,
763
+ brackets: [
764
+ { upToCents: 3050700, rate: 0.0879 },
765
+ { upToCents: 6101500, rate: 0.1495 },
766
+ { upToCents: 9588300, rate: 0.1667 },
767
+ { upToCents: 15465e3, rate: 0.175 },
768
+ { upToCents: Infinity, rate: 0.21 }
769
+ ]
770
+ },
771
+ PE: {
772
+ bpaCents: 1425e3,
773
+ brackets: [
774
+ { upToCents: 3332800, rate: 0.095 },
775
+ { upToCents: 6465600, rate: 0.1347 },
776
+ { upToCents: 105e5, rate: 0.166 },
777
+ { upToCents: 14e6, rate: 0.1762 },
778
+ { upToCents: Infinity, rate: 0.19 }
779
+ ]
780
+ },
781
+ NL: {
782
+ bpaCents: 1106700,
783
+ brackets: [
784
+ { upToCents: 4419200, rate: 0.087 },
785
+ { upToCents: 8838200, rate: 0.145 },
786
+ { upToCents: 15779200, rate: 0.158 },
787
+ { upToCents: 22091e3, rate: 0.178 },
788
+ { upToCents: 28221400, rate: 0.198 },
789
+ { upToCents: Infinity, rate: 0.218 }
790
+ ]
791
+ },
792
+ NT: {
793
+ bpaCents: 1784200,
794
+ brackets: [
795
+ { upToCents: 5196400, rate: 0.059 },
796
+ { upToCents: 10393e3, rate: 0.086 },
797
+ { upToCents: 16896700, rate: 0.122 },
798
+ { upToCents: Infinity, rate: 0.1405 }
799
+ ]
800
+ },
801
+ NU: {
802
+ bpaCents: 1927400,
803
+ brackets: [
804
+ { upToCents: 5470700, rate: 0.04 },
805
+ { upToCents: 10941300, rate: 0.07 },
806
+ { upToCents: 17788100, rate: 0.09 },
807
+ { upToCents: Infinity, rate: 0.115 }
808
+ ]
809
+ },
810
+ YT: {
811
+ bpaCents: 1612900,
812
+ brackets: [
813
+ { upToCents: 5737500, rate: 0.064 },
814
+ { upToCents: 11475e3, rate: 0.09 },
815
+ { upToCents: 17788200, rate: 0.109 },
816
+ { upToCents: 5e7, rate: 0.128 },
817
+ { upToCents: Infinity, rate: 0.15 }
818
+ ]
819
+ }
820
+ }
821
+ },
822
+ 2026: {
823
+ cpp: {
824
+ exemptionCents: 35e4,
825
+ ympeCents: 746e4,
826
+ yampeCents: 85e5,
827
+ rate: 0.0595,
828
+ rate2: 0.04,
829
+ maxCents: 423045,
830
+ max2Cents: 41600
831
+ },
832
+ qpp: {
833
+ exemptionCents: 35e4,
834
+ ympeCents: 746e4,
835
+ yampeCents: 85e5,
836
+ rate: 0.064,
837
+ rate2: 0.04,
838
+ maxCents: 455040,
839
+ max2Cents: 41600
840
+ },
841
+ ei: {
842
+ maxInsurableCents: 689e4,
843
+ rateNonQc: 0.0163,
844
+ rateQc: 0.013,
845
+ maxNonQcCents: 112307,
846
+ maxQcCents: 89570
847
+ },
848
+ qpip: {
849
+ maxInsurableCents: 103e5,
850
+ empRate: 43e-4,
851
+ erRate: 602e-5,
852
+ maxEmpCents: 44290,
853
+ maxErCents: 62006
854
+ },
855
+ cnt: { maxInsurableCents: 103e5, rate: 6e-4, maxCents: 6180 },
856
+ cnesst: { maxInsurableCents: 103e5 },
857
+ fed: {
858
+ bpaCents: 1645200,
859
+ ceaCents: 150100,
860
+ brackets: [
861
+ { upToCents: 5852300, rate: 0.14 },
862
+ { upToCents: 11704500, rate: 0.205 },
863
+ { upToCents: 18144e3, rate: 0.26 },
864
+ { upToCents: 25848200, rate: 0.29 },
865
+ { upToCents: Infinity, rate: 0.33 }
866
+ ]
867
+ },
868
+ prov: {
869
+ QC: {
870
+ bpaCents: 1895200,
871
+ brackets: [
872
+ { upToCents: 5434500, rate: 0.14 },
873
+ { upToCents: 10868e3, rate: 0.19 },
874
+ { upToCents: 13224500, rate: 0.24 },
875
+ { upToCents: Infinity, rate: 0.2575 }
876
+ ]
877
+ },
878
+ ON: {
879
+ bpaCents: 1300200,
880
+ brackets: [
881
+ { upToCents: 5394400, rate: 0.0505 },
882
+ { upToCents: 10789100, rate: 0.0915 },
883
+ { upToCents: 15e6, rate: 0.1116 },
884
+ { upToCents: 22e6, rate: 0.1216 },
885
+ { upToCents: Infinity, rate: 0.1316 }
886
+ ]
887
+ },
888
+ AB: {
889
+ bpaCents: 2276900,
890
+ brackets: [
891
+ { upToCents: 15425900, rate: 0.1 },
892
+ { upToCents: 18511100, rate: 0.12 },
893
+ { upToCents: 24681300, rate: 0.13 },
894
+ { upToCents: 37022e3, rate: 0.14 },
895
+ { upToCents: Infinity, rate: 0.15 }
896
+ ]
897
+ },
898
+ BC: {
899
+ bpaCents: 1319100,
900
+ brackets: [
901
+ { upToCents: 5026500, rate: 0.0506 },
902
+ { upToCents: 10053100, rate: 0.077 },
903
+ { upToCents: 11542100, rate: 0.105 },
904
+ { upToCents: 14015500, rate: 0.1229 },
905
+ { upToCents: 19003200, rate: 0.147 },
906
+ { upToCents: 26502600, rate: 0.168 },
907
+ { upToCents: Infinity, rate: 0.205 }
908
+ ]
909
+ },
910
+ MB: {
911
+ bpaCents: 1609600,
912
+ brackets: [
913
+ { upToCents: 4794e3, rate: 0.108 },
914
+ { upToCents: 102e5, rate: 0.1275 },
915
+ { upToCents: Infinity, rate: 0.174 }
916
+ ]
917
+ },
918
+ SK: {
919
+ bpaCents: 1988100,
920
+ brackets: [
921
+ { upToCents: 5453200, rate: 0.105 },
922
+ { upToCents: 15580500, rate: 0.125 },
923
+ { upToCents: Infinity, rate: 0.145 }
924
+ ]
925
+ },
926
+ NB: {
927
+ bpaCents: 1366400,
928
+ brackets: [
929
+ { upToCents: 5233200, rate: 0.094 },
930
+ { upToCents: 10466600, rate: 0.14 },
931
+ { upToCents: 19386100, rate: 0.16 },
932
+ { upToCents: Infinity, rate: 0.195 }
933
+ ]
934
+ },
935
+ NS: {
936
+ bpaCents: 1197900,
937
+ brackets: [
938
+ { upToCents: 3111700, rate: 0.0879 },
939
+ { upToCents: 6223500, rate: 0.1495 },
940
+ { upToCents: 9780100, rate: 0.1667 },
941
+ { upToCents: 15774300, rate: 0.175 },
942
+ { upToCents: Infinity, rate: 0.21 }
943
+ ]
944
+ },
945
+ PE: {
946
+ bpaCents: 1453500,
947
+ brackets: [
948
+ { upToCents: 3399500, rate: 0.095 },
949
+ { upToCents: 6594900, rate: 0.1347 },
950
+ { upToCents: 1071e4, rate: 0.166 },
951
+ { upToCents: 1428e4, rate: 0.1762 },
952
+ { upToCents: Infinity, rate: 0.19 }
953
+ ]
954
+ },
955
+ NL: {
956
+ bpaCents: 1128800,
957
+ brackets: [
958
+ { upToCents: 4507600, rate: 0.087 },
959
+ { upToCents: 9015e3, rate: 0.145 },
960
+ { upToCents: 16094800, rate: 0.158 },
961
+ { upToCents: 22532800, rate: 0.178 },
962
+ { upToCents: 28785800, rate: 0.198 },
963
+ { upToCents: Infinity, rate: 0.218 }
964
+ ]
965
+ },
966
+ NT: {
967
+ bpaCents: 1819900,
968
+ brackets: [
969
+ { upToCents: 5300300, rate: 0.059 },
970
+ { upToCents: 10600900, rate: 0.086 },
971
+ { upToCents: 17234600, rate: 0.122 },
972
+ { upToCents: Infinity, rate: 0.1405 }
973
+ ]
974
+ },
975
+ NU: {
976
+ bpaCents: 1965900,
977
+ brackets: [
978
+ { upToCents: 5580100, rate: 0.04 },
979
+ { upToCents: 11160100, rate: 0.07 },
980
+ { upToCents: 18143900, rate: 0.09 },
981
+ { upToCents: Infinity, rate: 0.115 }
982
+ ]
983
+ },
984
+ YT: {
985
+ bpaCents: 1645200,
986
+ brackets: [
987
+ { upToCents: 5852300, rate: 0.064 },
988
+ { upToCents: 11704500, rate: 0.09 },
989
+ { upToCents: 18144e3, rate: 0.109 },
990
+ { upToCents: 5e7, rate: 0.128 },
991
+ { upToCents: Infinity, rate: 0.15 }
992
+ ]
993
+ }
994
+ }
995
+ }
996
+ };
997
+ function resolvePayPeriods(freq) {
998
+ if (freq === 52 || freq === "weekly") return 52;
999
+ if (freq === 26 || freq === "biweekly") return 26;
1000
+ if (freq === 24 || freq === "semi_monthly") return 24;
1001
+ if (freq === 12 || freq === "monthly") return 12;
1002
+ throw new CaTaxValidationError(
1003
+ "INVALID_PAY_FREQUENCY",
1004
+ "payFrequency must be one of 52, 26, 24, 12, weekly, biweekly, semi_monthly, or monthly.",
1005
+ "payFrequency doit \xEAtre 52, 26, 24, 12, weekly, biweekly, semi_monthly ou monthly."
1006
+ );
1007
+ }
1008
+ function computeBracketTaxCents(annualTaxableCents, brackets) {
1009
+ if (annualTaxableCents <= 0) return 0;
1010
+ let tax = 0;
1011
+ let prev = 0;
1012
+ for (const b of brackets) {
1013
+ if (annualTaxableCents <= prev) break;
1014
+ const slice = Math.min(annualTaxableCents, b.upToCents) - prev;
1015
+ tax += slice * b.rate;
1016
+ prev = b.upToCents;
1017
+ }
1018
+ return Math.round(tax);
1019
+ }
1020
+ function clampYtdCents(raw) {
1021
+ if (raw === void 0) return 0;
1022
+ if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0) {
1023
+ throw new CaTaxValidationError(
1024
+ "INVALID_YTD",
1025
+ "YTD values must be non-negative integer cents.",
1026
+ "Les valeurs cumulatives (YTD) doivent \xEAtre des entiers positifs en cents."
1027
+ );
1028
+ }
1029
+ return raw;
1030
+ }
1031
+ function calculateCaPayrollDeductions(input) {
1032
+ const lang = input.lang === "fr" ? "fr" : "en";
1033
+ if (typeof input.grossPayCents !== "number" || !Number.isSafeInteger(input.grossPayCents) || input.grossPayCents < 0) {
1034
+ throw new CaTaxValidationError(
1035
+ "INVALID_GROSS_PAY",
1036
+ "grossPayCents must be a non-negative integer.",
1037
+ "grossPayCents doit \xEAtre un entier positif ou nul."
1038
+ );
1039
+ }
1040
+ const province = normalizeProvince(String(input.province ?? ""));
1041
+ const periods = resolvePayPeriods(input.payFrequency);
1042
+ const effectiveDate = input.effectiveDate?.trim() || "2026-01-01";
1043
+ if (!isValidIsoDate(effectiveDate)) {
1044
+ throw new CaTaxValidationError(
1045
+ "INVALID_DATE",
1046
+ "effectiveDate must be a valid YYYY-MM-DD date.",
1047
+ "effectiveDate doit \xEAtre une date valide au format YYYY-MM-DD."
1048
+ );
1049
+ }
1050
+ const yearNum = Number(effectiveDate.slice(0, 4));
1051
+ if (yearNum !== 2025 && yearNum !== 2026) {
1052
+ throw new CaTaxValidationError(
1053
+ "UNSUPPORTED_TAX_YEAR",
1054
+ `Tax year ${yearNum} is not supported; supported years are 2025 and 2026.`,
1055
+ `L'ann\xE9e d'imposition ${yearNum} n'est pas prise en charge; ann\xE9es disponibles : 2025 et 2026.`
1056
+ );
1057
+ }
1058
+ const taxYear = yearNum;
1059
+ const claimCode = input.claimCode ?? 1;
1060
+ if (typeof claimCode !== "number" || !Number.isInteger(claimCode) || claimCode < 1 || claimCode > 10) {
1061
+ throw new CaTaxValidationError(
1062
+ "INVALID_CLAIM_CODE",
1063
+ "claimCode must be an integer between 1 and 10.",
1064
+ "claimCode doit \xEAtre un entier compris entre 1 et 10."
1065
+ );
1066
+ }
1067
+ const params = PAYROLL_PARAMS[taxYear];
1068
+ const gross = input.grossPayCents;
1069
+ const isQc = province === "QC";
1070
+ const ytd = input.ytd ?? {};
1071
+ const pensionSpec = isQc ? params.qpp : params.cpp;
1072
+ const ytdPension1 = clampYtdCents(isQc ? ytd.qppCents : ytd.cppCents);
1073
+ const periodExemption = Math.floor(pensionSpec.exemptionCents / periods);
1074
+ const rawPension1 = Math.round(Math.max(0, gross - periodExemption) * pensionSpec.rate);
1075
+ const remainingPension1 = Math.max(0, pensionSpec.maxCents - ytdPension1);
1076
+ const pension1Cents = Math.min(rawPension1, remainingPension1);
1077
+ const pension1MaxReached = ytdPension1 + pension1Cents >= pensionSpec.maxCents;
1078
+ const ytdPension2 = clampYtdCents(isQc ? ytd.qpp2Cents : ytd.cpp2Cents);
1079
+ let rawPension2 = 0;
1080
+ if (ytd.pensionableEarningsCents !== void 0) {
1081
+ const prevEarn = clampYtdCents(ytd.pensionableEarningsCents);
1082
+ const nextEarn = prevEarn + gross;
1083
+ const tier2Earn = Math.max(0, Math.min(nextEarn, pensionSpec.yampeCents) - Math.max(prevEarn, pensionSpec.ympeCents));
1084
+ rawPension2 = Math.round(tier2Earn * pensionSpec.rate2);
1085
+ } else {
1086
+ const annualGross2 = gross * periods;
1087
+ if (annualGross2 > pensionSpec.ympeCents) {
1088
+ const annualTier2 = Math.min(annualGross2, pensionSpec.yampeCents) - pensionSpec.ympeCents;
1089
+ rawPension2 = Math.round(annualTier2 * pensionSpec.rate2 / periods);
1090
+ }
1091
+ }
1092
+ const remainingPension2 = Math.max(0, pensionSpec.max2Cents - ytdPension2);
1093
+ const pension2Cents = Math.min(rawPension2, remainingPension2);
1094
+ const pension2MaxReached = ytdPension2 + pension2Cents >= pensionSpec.max2Cents;
1095
+ const ytdEi = clampYtdCents(ytd.eiCents);
1096
+ const eiRate = isQc ? params.ei.rateQc : params.ei.rateNonQc;
1097
+ const eiMax = isQc ? params.ei.maxQcCents : params.ei.maxNonQcCents;
1098
+ const rawEi = Math.round(gross * eiRate);
1099
+ const eiCents = Math.min(rawEi, Math.max(0, eiMax - ytdEi));
1100
+ const eiMaxReached = ytdEi + eiCents >= eiMax;
1101
+ const erEiCents = Math.round(eiCents * 1.4);
1102
+ let qpipCents = 0;
1103
+ let erQpipCents = 0;
1104
+ let qpipMaxReached = false;
1105
+ if (isQc) {
1106
+ const ytdQpip = clampYtdCents(ytd.qpipCents);
1107
+ const rawQpip = Math.round(gross * params.qpip.empRate);
1108
+ qpipCents = Math.min(rawQpip, Math.max(0, params.qpip.maxEmpCents - ytdQpip));
1109
+ qpipMaxReached = ytdQpip + qpipCents >= params.qpip.maxEmpCents;
1110
+ const rawErQpip = Math.round(gross * params.qpip.erRate);
1111
+ erQpipCents = qpipMaxReached && qpipCents === 0 ? 0 : Math.min(rawErQpip, params.qpip.maxErCents);
1112
+ }
1113
+ let fssCents = 0;
1114
+ let cnesstCents = 0;
1115
+ let cntCents = 0;
1116
+ if (isQc) {
1117
+ const fssBps = input.fssRateBps ?? 165;
1118
+ const cnesstBps = input.cnesstRateBps ?? 170;
1119
+ const prevInsurable = clampYtdCents(ytd.insurableEarningsCents);
1120
+ const cnesstEarn = Math.max(0, Math.min(prevInsurable + gross, params.cnesst.maxInsurableCents) - prevInsurable);
1121
+ const cntEarn = Math.max(0, Math.min(prevInsurable + gross, params.cnt.maxInsurableCents) - prevInsurable);
1122
+ fssCents = Math.round(gross * fssBps / 1e4);
1123
+ cnesstCents = Math.round(cnesstEarn * cnesstBps / 1e4);
1124
+ cntCents = Math.round(cntEarn * params.cnt.rate);
1125
+ }
1126
+ const annualGross = gross * periods;
1127
+ const fedGrossTax = computeBracketTaxCents(annualGross, params.fed.brackets);
1128
+ const fedLowestRate = params.fed.brackets[0].rate;
1129
+ const claimCodeStepCents = taxYear === 2026 ? 28e4 : 27e4;
1130
+ const fedClaimAdjustmentCents = (claimCode - 1) * claimCodeStepCents;
1131
+ const provClaimAdjustmentCents = (claimCode - 1) * claimCodeStepCents;
1132
+ const fedCreditsBase = params.fed.bpaCents + fedClaimAdjustmentCents + Math.min(annualGross, params.fed.ceaCents) + Math.min(pension1Cents * periods, pensionSpec.maxCents) + Math.min(eiCents * periods, eiMax) + (isQc ? Math.min(qpipCents * periods, params.qpip.maxEmpCents) : 0);
1133
+ const annualFedTaxBeforeAbatement = Math.max(0, fedGrossTax - Math.round(fedCreditsBase * fedLowestRate));
1134
+ const federalTaxBeforeAbatementCents = Math.round(annualFedTaxBeforeAbatement / periods);
1135
+ const federalAbatementCents = isQc ? Math.round(federalTaxBeforeAbatementCents * 0.165) : 0;
1136
+ const federalTaxCents = Math.max(0, federalTaxBeforeAbatementCents - federalAbatementCents);
1137
+ const provSpec = params.prov[province];
1138
+ const provGrossTax = computeBracketTaxCents(annualGross, provSpec.brackets);
1139
+ const provLowestRate = provSpec.brackets[0].rate;
1140
+ const provCreditsBase = provSpec.bpaCents + provClaimAdjustmentCents + Math.min(pension1Cents * periods, pensionSpec.maxCents) + Math.min(eiCents * periods, eiMax) + (isQc ? Math.min(qpipCents * periods, params.qpip.maxEmpCents) : 0);
1141
+ const annualProvTax = Math.max(0, provGrossTax - Math.round(provCreditsBase * provLowestRate));
1142
+ const provincialTaxCents = Math.round(annualProvTax / periods);
1143
+ let annualOhpCents = 0;
1144
+ if (province === "ON") {
1145
+ if (annualGross <= 2e6) {
1146
+ annualOhpCents = 0;
1147
+ } else if (annualGross <= 36e5) {
1148
+ annualOhpCents = Math.min(3e4, Math.round(0.06 * (annualGross - 2e6)));
1149
+ } else if (annualGross <= 48e5) {
1150
+ annualOhpCents = Math.min(45e3, 3e4 + Math.round(0.06 * (annualGross - 36e5)));
1151
+ } else if (annualGross <= 72e5) {
1152
+ annualOhpCents = Math.min(6e4, 45e3 + Math.round(0.25 * (annualGross - 48e5)));
1153
+ } else if (annualGross <= 2e7) {
1154
+ annualOhpCents = Math.min(75e3, 6e4 + Math.round(0.25 * (annualGross - 72e5)));
1155
+ } else {
1156
+ annualOhpCents = Math.min(9e4, 75e3 + Math.round(0.25 * (annualGross - 2e7)));
1157
+ }
1158
+ }
1159
+ const ontarioHealthPremiumCents = province === "ON" ? Math.round(annualOhpCents / periods) : 0;
1160
+ const provincialHealthCents = ontarioHealthPremiumCents;
1161
+ const cppCents = isQc ? 0 : pension1Cents;
1162
+ const cpp2Cents = isQc ? 0 : pension2Cents;
1163
+ const qppCents = isQc ? pension1Cents : 0;
1164
+ const qpp2Cents = isQc ? pension2Cents : 0;
1165
+ const totalEmployeeDeductionsCents = federalTaxCents + provincialTaxCents + ontarioHealthPremiumCents + cppCents + cpp2Cents + qppCents + qpp2Cents + eiCents + qpipCents;
1166
+ const netPayCents = gross - totalEmployeeDeductionsCents;
1167
+ const totalEmployerContributionsCents = cppCents + cpp2Cents + qppCents + qpp2Cents + erEiCents + erQpipCents + fssCents + cnesstCents + cntCents;
1168
+ const tableVersion = isQc ? `T4127-${taxYear}_TP-1015.G-${taxYear}` : `T4127-${taxYear}`;
1169
+ const sourceCitation = isQc ? `CRA T4127 (${taxYear}) + Revenu Qu\xE9bec TP-1015.G (${taxYear})` : `CRA T4127 (${taxYear})`;
1170
+ const labels = lang === "fr" ? {
1171
+ federalTax: "Imp\xF4t f\xE9d\xE9ral",
1172
+ federalAbatement: "Abattement du Qu\xE9bec (16,5 %)",
1173
+ provincialTax: isQc ? "Imp\xF4t du Qu\xE9bec (TP-1015.G)" : "Imp\xF4t provincial",
1174
+ ontarioHealthPremium: "Contribution-sant\xE9 de l\u2019Ontario (CSO)",
1175
+ provincialHealth: "Cotisation sant\xE9 provinciale",
1176
+ cpp: "RPC",
1177
+ cpp2: "RPC2",
1178
+ qpp: "RRQ",
1179
+ qpp2: "RRQ2",
1180
+ ei: "Assurance-emploi (AE)",
1181
+ qpip: "RQAP",
1182
+ fss: "FSS (employeur)",
1183
+ cnesst: "CNESST (employeur)",
1184
+ cnt: "CNT (employeur)"
1185
+ } : {
1186
+ federalTax: "Federal Income Tax",
1187
+ federalAbatement: "Quebec Federal Abatement (16.5%)",
1188
+ provincialTax: isQc ? "Quebec Income Tax (TP-1015.G)" : "Provincial Income Tax",
1189
+ ontarioHealthPremium: "Ontario Health Premium (OHP)",
1190
+ provincialHealth: "Provincial Health Contribution",
1191
+ cpp: "CPP",
1192
+ cpp2: "CPP2",
1193
+ qpp: "QPP",
1194
+ qpp2: "QPP2",
1195
+ ei: "Employment Insurance (EI)",
1196
+ qpip: "QPIP (RQAP)",
1197
+ fss: "Health Services Fund (FSS)",
1198
+ cnesst: "CNESST",
1199
+ cnt: "CNT (Labour Standards)"
1200
+ };
1201
+ let employerHealthTax;
1202
+ if (typeof input.annualPayrollCents === "number" && Number.isSafeInteger(input.annualPayrollCents) && input.annualPayrollCents >= 0) {
1203
+ const ann = input.annualPayrollCents;
1204
+ if (province === "BC") {
1205
+ let cents = 0;
1206
+ let ratePct = 0;
1207
+ if (ann <= 5e7) {
1208
+ cents = 0;
1209
+ ratePct = 0;
1210
+ } else if (ann <= 1e8) {
1211
+ cents = Math.round((ann - 5e7) * 0.039);
1212
+ ratePct = 3.9;
1213
+ } else {
1214
+ cents = Math.round(ann * 0.0195);
1215
+ ratePct = 1.95;
1216
+ }
1217
+ employerHealthTax = {
1218
+ code: "BC_EHT",
1219
+ label: lang === "fr" ? "Taxe sant\xE9 des employeurs de la C.-B." : "BC Employer Health Tax",
1220
+ ratePct,
1221
+ cents
1222
+ };
1223
+ } else if (province === "MB") {
1224
+ let cents = 0;
1225
+ let ratePct = 0;
1226
+ if (ann <= 225e6) {
1227
+ cents = 0;
1228
+ ratePct = 0;
1229
+ } else if (ann <= 45e7) {
1230
+ cents = Math.round((ann - 225e6) * 0.043);
1231
+ ratePct = 4.3;
1232
+ } else {
1233
+ cents = Math.round(ann * 0.0215);
1234
+ ratePct = 2.15;
1235
+ }
1236
+ employerHealthTax = {
1237
+ code: "MB_HEMT",
1238
+ label: lang === "fr" ? "Imp\xF4t sur la masse salariale du Manitoba" : "Manitoba HEMT",
1239
+ ratePct,
1240
+ cents
1241
+ };
1242
+ } else if (province === "ON") {
1243
+ let cents = 0;
1244
+ let ratePct = 0;
1245
+ if (ann <= 1e8) {
1246
+ cents = 0;
1247
+ ratePct = 0;
1248
+ } else if (ann <= 5e8) {
1249
+ cents = Math.round((ann - 1e8) * 0.0195);
1250
+ ratePct = 1.95;
1251
+ } else {
1252
+ cents = Math.round(ann * 0.0195);
1253
+ ratePct = 1.95;
1254
+ }
1255
+ employerHealthTax = {
1256
+ code: "ON_EHT",
1257
+ label: lang === "fr" ? "Imp\xF4t-sant\xE9 des employeurs de l\u2019Ontario" : "Ontario Employer Health Tax",
1258
+ ratePct,
1259
+ cents
1260
+ };
1261
+ } else {
1262
+ employerHealthTax = {
1263
+ code: `${province}_EHT`,
1264
+ label: `${province} Employer Health Tax`,
1265
+ ratePct: 0,
1266
+ cents: 0
1267
+ };
1268
+ }
1269
+ }
1270
+ return {
1271
+ taxYear,
1272
+ province,
1273
+ provinceName: PROVINCE_NAMES[province][lang],
1274
+ effectiveDate,
1275
+ payFrequency: input.payFrequency,
1276
+ periodsPerYear: periods,
1277
+ claimCode,
1278
+ grossPayCents: gross,
1279
+ netPayCents,
1280
+ totalEmployeeDeductionsCents,
1281
+ totalEmployerContributionsCents,
1282
+ ontarioHealthPremiumCents,
1283
+ provincialHealthCents,
1284
+ ...employerHealthTax !== void 0 ? { employerHealthTax } : {},
1285
+ employee: {
1286
+ federalTaxBeforeAbatementCents,
1287
+ federalAbatementCents,
1288
+ federalTaxCents,
1289
+ provincialTaxCents,
1290
+ ontarioHealthPremiumCents,
1291
+ provincialHealthCents,
1292
+ cppCents,
1293
+ cpp2Cents,
1294
+ qppCents,
1295
+ qpp2Cents,
1296
+ eiCents,
1297
+ qpipCents
1298
+ },
1299
+ employer: {
1300
+ cppCents,
1301
+ cpp2Cents,
1302
+ qppCents,
1303
+ qpp2Cents,
1304
+ eiCents: erEiCents,
1305
+ qpipCents: erQpipCents,
1306
+ fssCents,
1307
+ cnesstCents,
1308
+ cntCents
1309
+ },
1310
+ ytdMaxReached: {
1311
+ cpp: !isQc && pension1MaxReached,
1312
+ cpp2: !isQc && pension2MaxReached,
1313
+ qpp: isQc && pension1MaxReached,
1314
+ qpp2: isQc && pension2MaxReached,
1315
+ ei: eiMaxReached,
1316
+ qpip: isQc && qpipMaxReached
1317
+ },
1318
+ tableVersion,
1319
+ bulletinSla: {
1320
+ updateWindowBusinessDays: 5,
1321
+ regime: isQc ? "CRA_T4127_AND_RQ_TP1015G" : "CRA_T4127"
1322
+ },
1323
+ sourceCitation,
1324
+ labels
1325
+ };
1326
+ }
1327
+ async function handleCaTax(request, env, ctx = {}) {
1328
+ const url = ctx.url ?? new URL(request.url);
1329
+ const path = (ctx.path ?? url.pathname).replace(/\/+$/, "");
1330
+ const method = request.method.toUpperCase();
1331
+ if (path === "/v1/ca/sales-tax") {
1332
+ if (method !== "GET" && method !== "HEAD") {
1333
+ return apiError(405, "METHOD_NOT_ALLOWED", "Use GET /v1/ca/sales-tax.");
1334
+ }
1335
+ const lang = pickLang(null, ctx, url);
1336
+ const postal = url.searchParams.get("postal") ?? void 0;
1337
+ const province = url.searchParams.get("province") ?? void 0;
1338
+ const effectiveDate = url.searchParams.get("effectiveDate") ?? void 0;
1339
+ let result;
1340
+ try {
1341
+ result = lookupCaSalesTax({ postal, province, effectiveDate, lang });
1342
+ } catch (e) {
1343
+ if (e instanceof CaTaxValidationError) {
1344
+ return apiError(400, e.code, e.message, lang === "fr" ? e.localizedMessage : e.message);
1345
+ }
1346
+ throw e;
1347
+ }
1348
+ const inputPayload = { postal: result.postal, province: result.province, effectiveDate: result.effectiveDate, lang };
1349
+ const receipt = await issueReceipt(env, ctx, "/v1/ca/sales-tax", inputPayload, result, {
1350
+ currency: "CAD",
1351
+ openingCents: 0,
1352
+ creditsCents: 0,
1353
+ debitsCents: 0,
1354
+ closingCents: 0,
1355
+ deltaCents: 0,
1356
+ balanced: true
1357
+ });
1358
+ return apiJson({ ok: true, ...result, receipt }, 200, receiptHeaders(receipt, ctx));
1359
+ }
1360
+ if (path === "/v1/ca/sales-tax/batch-postal") {
1361
+ if (method !== "POST") {
1362
+ return apiError(405, "METHOD_NOT_ALLOWED", "Use POST /v1/ca/sales-tax/batch-postal.");
1363
+ }
1364
+ const parsed = await readJsonBody(request);
1365
+ if (!parsed.ok) return parsed.response;
1366
+ const body = parsed.body;
1367
+ const lang = pickLang(body, ctx, url);
1368
+ const items = body.items;
1369
+ if (!Array.isArray(items) || items.length === 0) {
1370
+ return apiError(400, "BATCH_EMPTY", "items must be a non-empty array (1..100).", lang === "fr" ? "items doit \xEAtre un tableau non vide (1..100)." : void 0);
1371
+ }
1372
+ if (items.length > 100) {
1373
+ return apiError(400, "BATCH_TOO_LARGE", `A batch holds at most 100 items (received ${items.length}).`, lang === "fr" ? `Un lot contient au plus 100 \xE9l\xE9ments (re\xE7u ${items.length}).` : void 0, { maxItems: 100 });
1374
+ }
1375
+ const results = [];
1376
+ for (let i = 0; i < items.length; i++) {
1377
+ const item = items[i];
1378
+ if (!item || typeof item !== "object" || typeof item.postal !== "string") {
1379
+ return apiError(400, "INVALID_ITEM", `Item at index ${i} must have a postal string.`);
1380
+ }
1381
+ try {
1382
+ const res = lookupCaSalesTax({ postal: item.postal, effectiveDate: item.effectiveDate, lang });
1383
+ results.push(res);
1384
+ } catch (e) {
1385
+ if (e instanceof CaTaxValidationError) {
1386
+ return apiError(400, e.code, `Item at index ${i}: ${e.message}`, lang === "fr" ? e.localizedMessage : e.message);
1387
+ }
1388
+ throw e;
1389
+ }
1390
+ }
1391
+ const receipt = await issueReceipt(env, ctx, "/v1/ca/sales-tax/batch-postal", body, results, {
1392
+ currency: "CAD",
1393
+ openingCents: 0,
1394
+ creditsCents: 0,
1395
+ debitsCents: 0,
1396
+ closingCents: 0,
1397
+ deltaCents: 0,
1398
+ balanced: true,
1399
+ transactionCount: results.length
1400
+ });
1401
+ return apiJson({ ok: true, count: results.length, items: results, receipt }, 200, receiptHeaders(receipt, ctx));
1402
+ }
1403
+ if (path === "/v1/ca/payroll/deductions") {
1404
+ if (method !== "POST") {
1405
+ return apiError(405, "METHOD_NOT_ALLOWED", "Use POST /v1/ca/payroll/deductions.");
1406
+ }
1407
+ const parsed = await readJsonBody(request);
1408
+ if (!parsed.ok) return parsed.response;
1409
+ const body = parsed.body;
1410
+ const lang = pickLang(body, ctx, url);
1411
+ const effectiveDate = typeof body.effectiveDate === "string" ? body.effectiveDate : url.searchParams.get("effectiveDate") ?? void 0;
1412
+ let result;
1413
+ try {
1414
+ result = calculateCaPayrollDeductions({
1415
+ grossPayCents: body.grossPayCents,
1416
+ province: String(body.province ?? ""),
1417
+ payFrequency: body.payFrequency,
1418
+ effectiveDate,
1419
+ lang,
1420
+ claimCode: typeof body.claimCode === "number" ? body.claimCode : void 0,
1421
+ ytd: body.ytd && typeof body.ytd === "object" ? body.ytd : void 0,
1422
+ cnesstRateBps: typeof body.cnesstRateBps === "number" ? body.cnesstRateBps : void 0,
1423
+ fssRateBps: typeof body.fssRateBps === "number" ? body.fssRateBps : void 0,
1424
+ annualPayrollCents: typeof body.annualPayrollCents === "number" ? body.annualPayrollCents : void 0
1425
+ });
1426
+ } catch (e) {
1427
+ if (e instanceof CaTaxValidationError) {
1428
+ return apiError(400, e.code, e.message, lang === "fr" ? e.localizedMessage : e.message);
1429
+ }
1430
+ throw e;
1431
+ }
1432
+ const receipt = await issueReceipt(env, ctx, "/v1/ca/payroll/deductions", body, result, {
1433
+ currency: "CAD",
1434
+ openingCents: result.grossPayCents,
1435
+ creditsCents: 0,
1436
+ debitsCents: result.totalEmployeeDeductionsCents,
1437
+ closingCents: result.netPayCents,
1438
+ deltaCents: 0,
1439
+ balanced: true
1440
+ });
1441
+ return apiJson({ ok: true, ...result, receipt }, 200, receiptHeaders(receipt, ctx));
1442
+ }
1443
+ return null;
1444
+ }
1445
+
1446
+ // packages/ca-tax-mcp/src/server.ts
1447
+ var PROTOCOL_VERSION = "2025-03-26";
1448
+ var SERVER_INFO = { name: "@ca-tax/mcp", version: "0.1.0" };
1449
+ var obj = (properties = {}, required = []) => ({
1450
+ type: "object",
1451
+ properties,
1452
+ ...required.length > 0 ? { required } : {},
1453
+ additionalProperties: true
1454
+ });
1455
+ var TOOLS = [
1456
+ {
1457
+ name: "ca_sales_tax_lookup",
1458
+ description: "Look up Canadian sales tax rates (GST, PST, HST, QST) by postal code / FSA or province with effective date versioning (e.g. Nova Scotia 2025-04-01), bilingual EN/FR labels, and 6-character border FSA resolution (K1A federal offices in Gatineau QC vs Ottawa ON, S9V/T9V Lloydminster SK/AB border).",
1459
+ inputSchema: obj(
1460
+ {
1461
+ postal: {
1462
+ type: "string",
1463
+ description: "Canadian postal code (6 characters, e.g. K1A 0B8 for Gatineau QC vs K1A 0A6 for Ottawa ON, or S9V 0X8 for Lloydminster) or 3-character FSA (e.g. H2Y 1C6 or M5V)."
1464
+ },
1465
+ province: { type: "string", description: "Two-letter Canadian province/territory code (e.g. ON, QC, AB)." },
1466
+ effectiveDate: { type: "string", description: "Effective date for rate determination in YYYY-MM-DD format." },
1467
+ lang: { type: "string", enum: ["en", "fr"], description: "Language preference for tax labels (en or fr)." }
1468
+ },
1469
+ ["postal"]
1470
+ )
1471
+ },
1472
+ {
1473
+ name: "ca_payroll_deductions",
1474
+ description: "Calculate Canadian payroll deductions under CRA T4127 and Revenu Qu\xE9bec TP-1015.G rules (CPP/CPP2, QPP/QPP2, EI, QPIP, federal abatement, provincial tax, FSS, CNESST, CNT) with full TD1 Claim Codes (1..10) support.",
1475
+ inputSchema: obj(
1476
+ {
1477
+ province: { type: "string", description: "Two-letter Canadian province/territory code (e.g. ON, QC, AB)." },
1478
+ grossPayCents: { type: "integer", minimum: 0, description: "Gross pay for period in integer cents." },
1479
+ payFrequency: {
1480
+ type: "string",
1481
+ enum: ["weekly", "biweekly", "semi_monthly", "monthly"],
1482
+ description: "Pay frequency."
1483
+ },
1484
+ periodsPerYear: {
1485
+ type: "integer",
1486
+ enum: [52, 26, 24, 12],
1487
+ description: "Number of pay periods per year (alternative to payFrequency)."
1488
+ },
1489
+ claimCode: {
1490
+ type: "integer",
1491
+ minimum: 1,
1492
+ maximum: 10,
1493
+ description: "Federal and provincial TD1 claim code (1-10) for basic personal exemption amounts."
1494
+ },
1495
+ ytdPensionableCents: { type: "integer", minimum: 0, description: "YTD pensionable earnings in cents." },
1496
+ ytdInsurableCents: { type: "integer", minimum: 0, description: "YTD insurable earnings in cents." },
1497
+ ytdCppCents: { type: "integer", minimum: 0, description: "YTD CPP deductions in cents." },
1498
+ ytdCpp2Cents: { type: "integer", minimum: 0, description: "YTD CPP2 deductions in cents." },
1499
+ ytdQppCents: { type: "integer", minimum: 0, description: "YTD QPP deductions in cents." },
1500
+ ytdQpp2Cents: { type: "integer", minimum: 0, description: "YTD QPP2 deductions in cents." },
1501
+ ytdEiCents: { type: "integer", minimum: 0, description: "YTD EI deductions in cents." },
1502
+ ytdQpipCents: { type: "integer", minimum: 0, description: "YTD QPIP deductions in cents." },
1503
+ effectiveDate: { type: "string", description: "Effective date in YYYY-MM-DD format (supported years: 2025, 2026)." },
1504
+ lang: { type: "string", enum: ["en", "fr"], description: "Language for labels (en or fr)." },
1505
+ exemptCpp: { type: "boolean", description: "Whether employee is exempt from CPP/QPP." },
1506
+ exemptEi: { type: "boolean", description: "Whether employee is exempt from EI." },
1507
+ exemptQpip: { type: "boolean", description: "Whether employee is exempt from QPIP." },
1508
+ cnesstRateBps: { type: "integer", minimum: 0, description: "Employer CNESST rate in basis points (QC)." },
1509
+ fssRateBps: { type: "integer", minimum: 0, description: "Employer FSS rate in basis points (QC)." }
1510
+ },
1511
+ ["province", "grossPayCents"]
1512
+ )
1513
+ }
1514
+ ];
1515
+ async function runLocalTool(name, args, env = {}) {
1516
+ if (name === "ca_sales_tax_lookup") {
1517
+ const postal = typeof args.postal === "string" ? args.postal : void 0;
1518
+ const province = typeof args.province === "string" ? args.province : void 0;
1519
+ const effectiveDate = typeof args.effectiveDate === "string" ? args.effectiveDate : void 0;
1520
+ const lang = args.lang === "fr" ? "fr" : "en";
1521
+ const params = new URLSearchParams();
1522
+ if (postal) params.set("postal", postal);
1523
+ if (province) params.set("province", province);
1524
+ if (effectiveDate) params.set("effectiveDate", effectiveDate);
1525
+ if (lang) params.set("lang", lang);
1526
+ const req = new Request(`http://local.exactrows.invalid/v1/ca/sales-tax?${params.toString()}`, {
1527
+ method: "GET"
1528
+ });
1529
+ const ctx = { path: "/v1/ca/sales-tax", url: new URL(req.url) };
1530
+ const res = await handleCaTax(req, env, ctx);
1531
+ if (!res) {
1532
+ const pure = lookupCaSalesTax({ postal, province, effectiveDate, lang });
1533
+ return { ok: true, ...pure };
1534
+ }
1535
+ return res.json();
1536
+ }
1537
+ if (name === "ca_payroll_deductions") {
1538
+ const payFrequency = args.payFrequency ?? args.periodsPerYear;
1539
+ const ytd = {
1540
+ ...args.ytd ?? {},
1541
+ ...args.ytdPensionableCents !== void 0 ? { pensionableEarningsCents: Number(args.ytdPensionableCents) } : {},
1542
+ ...args.ytdInsurableCents !== void 0 ? { insurableEarningsCents: Number(args.ytdInsurableCents) } : {},
1543
+ ...args.ytdCppCents !== void 0 ? { cppCents: Number(args.ytdCppCents) } : {},
1544
+ ...args.ytdCpp2Cents !== void 0 ? { cpp2Cents: Number(args.ytdCpp2Cents) } : {},
1545
+ ...args.ytdQppCents !== void 0 ? { qppCents: Number(args.ytdQppCents) } : {},
1546
+ ...args.ytdQpp2Cents !== void 0 ? { qpp2Cents: Number(args.ytdQpp2Cents) } : {},
1547
+ ...args.ytdEiCents !== void 0 ? { eiCents: Number(args.ytdEiCents) } : {},
1548
+ ...args.ytdQpipCents !== void 0 ? { qpipCents: Number(args.ytdQpipCents) } : {}
1549
+ };
1550
+ const body = {
1551
+ ...args,
1552
+ grossPayCents: args.grossPayCents,
1553
+ province: args.province,
1554
+ payFrequency,
1555
+ effectiveDate: args.effectiveDate,
1556
+ lang: args.lang,
1557
+ ...args.claimCode !== void 0 ? { claimCode: Number(args.claimCode) } : {},
1558
+ ...Object.keys(ytd).length > 0 ? { ytd } : {}
1559
+ };
1560
+ const req = new Request("http://local.exactrows.invalid/v1/ca/payroll/deductions", {
1561
+ method: "POST",
1562
+ headers: { "content-type": "application/json" },
1563
+ body: JSON.stringify(body)
1564
+ });
1565
+ const ctx = { path: "/v1/ca/payroll/deductions", url: new URL(req.url) };
1566
+ const res = await handleCaTax(req, env, ctx);
1567
+ if (!res) {
1568
+ const pure = calculateCaPayrollDeductions({
1569
+ grossPayCents: Number(args.grossPayCents),
1570
+ province: String(args.province ?? ""),
1571
+ payFrequency,
1572
+ effectiveDate: typeof args.effectiveDate === "string" ? args.effectiveDate : void 0,
1573
+ claimCode: args.claimCode !== void 0 ? Number(args.claimCode) : void 0,
1574
+ lang: args.lang === "fr" ? "fr" : "en",
1575
+ ytd: Object.keys(ytd).length > 0 ? ytd : void 0,
1576
+ cnesstRateBps: typeof args.cnesstRateBps === "number" ? args.cnesstRateBps : void 0,
1577
+ fssRateBps: typeof args.fssRateBps === "number" ? args.fssRateBps : void 0
1578
+ });
1579
+ return { ok: true, ...pure };
1580
+ }
1581
+ return res.json();
1582
+ }
1583
+ throw new Error(`Unknown tool: ${name}`);
1584
+ }
1585
+ async function callTool(name, args, opts) {
1586
+ if (opts.localWasm) {
1587
+ return runLocalTool(name, args, opts.env ?? {});
1588
+ }
1589
+ const apiBase = opts.apiBase ?? "https://api.exactrows.com";
1590
+ const headers = {
1591
+ "content-type": "application/json",
1592
+ ...opts.apiKey ? { authorization: `Bearer ${opts.apiKey}` } : {}
1593
+ };
1594
+ if (name === "ca_sales_tax_lookup") {
1595
+ const params = new URLSearchParams();
1596
+ if (args.postal) params.set("postal", String(args.postal));
1597
+ if (args.province) params.set("province", String(args.province));
1598
+ if (args.effectiveDate) params.set("effectiveDate", String(args.effectiveDate));
1599
+ if (args.lang) params.set("lang", String(args.lang));
1600
+ const res = await fetch(`${apiBase}/v1/ca/sales-tax?${params.toString()}`, {
1601
+ method: "GET",
1602
+ headers
1603
+ });
1604
+ return res.json();
1605
+ }
1606
+ if (name === "ca_payroll_deductions") {
1607
+ const payFrequency = args.payFrequency ?? args.periodsPerYear;
1608
+ const ytd = {
1609
+ ...args.ytd ?? {},
1610
+ ...args.ytdPensionableCents !== void 0 ? { pensionableEarningsCents: Number(args.ytdPensionableCents) } : {},
1611
+ ...args.ytdInsurableCents !== void 0 ? { insurableEarningsCents: Number(args.ytdInsurableCents) } : {},
1612
+ ...args.ytdCppCents !== void 0 ? { cppCents: Number(args.ytdCppCents) } : {},
1613
+ ...args.ytdCpp2Cents !== void 0 ? { cpp2Cents: Number(args.ytdCpp2Cents) } : {},
1614
+ ...args.ytdQppCents !== void 0 ? { qppCents: Number(args.ytdQppCents) } : {},
1615
+ ...args.ytdQpp2Cents !== void 0 ? { qpp2Cents: Number(args.ytdQpp2Cents) } : {},
1616
+ ...args.ytdEiCents !== void 0 ? { eiCents: Number(args.ytdEiCents) } : {},
1617
+ ...args.ytdQpipCents !== void 0 ? { qpipCents: Number(args.ytdQpipCents) } : {}
1618
+ };
1619
+ const body = {
1620
+ ...args,
1621
+ ...payFrequency ? { payFrequency } : {},
1622
+ ...args.claimCode !== void 0 ? { claimCode: Number(args.claimCode) } : {},
1623
+ ...Object.keys(ytd).length > 0 ? { ytd } : {}
1624
+ };
1625
+ const res = await fetch(`${apiBase}/v1/ca/payroll/deductions`, {
1626
+ method: "POST",
1627
+ headers,
1628
+ body: JSON.stringify(body)
1629
+ });
1630
+ return res.json();
1631
+ }
1632
+ throw new Error(`Unknown tool: ${name}`);
1633
+ }
1634
+ var rpcErr = (id, code, message) => ({
1635
+ jsonrpc: "2.0",
1636
+ id: id === void 0 ? null : id,
1637
+ error: { code, message }
1638
+ });
1639
+ async function handleRpc(msg, opts = {}) {
1640
+ if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0" || typeof msg.method !== "string") {
1641
+ return rpcErr(msg && typeof msg === "object" ? msg.id : null, -32600, "Invalid Request");
1642
+ }
1643
+ const isNotification = msg.id === void 0;
1644
+ switch (msg.method) {
1645
+ case "initialize":
1646
+ return {
1647
+ jsonrpc: "2.0",
1648
+ id: msg.id === void 0 ? null : msg.id,
1649
+ result: {
1650
+ protocolVersion: PROTOCOL_VERSION,
1651
+ capabilities: { tools: { listChanged: false } },
1652
+ serverInfo: SERVER_INFO
1653
+ }
1654
+ };
1655
+ case "ping":
1656
+ return { jsonrpc: "2.0", id: msg.id === void 0 ? null : msg.id, result: {} };
1657
+ case "tools/list":
1658
+ return { jsonrpc: "2.0", id: msg.id === void 0 ? null : msg.id, result: { tools: TOOLS } };
1659
+ case "tools/call": {
1660
+ if (!msg.params || typeof msg.params !== "object" || Array.isArray(msg.params)) {
1661
+ return rpcErr(msg.id, -32602, "Invalid params: params object required");
1662
+ }
1663
+ const name = msg.params?.name;
1664
+ if (typeof name !== "string" || !name) {
1665
+ return rpcErr(msg.id, -32602, "Invalid params: tool name required");
1666
+ }
1667
+ if (!TOOLS.some((t) => t.name === name)) {
1668
+ return rpcErr(msg.id, -32601, `Unknown tool: ${name}`);
1669
+ }
1670
+ if (msg.params.arguments !== void 0 && (typeof msg.params.arguments !== "object" || msg.params.arguments === null || Array.isArray(msg.params.arguments))) {
1671
+ return rpcErr(msg.id, -32602, "Invalid params: arguments must be an object");
1672
+ }
1673
+ try {
1674
+ const out = await callTool(name, msg.params?.arguments ?? {}, opts);
1675
+ const isError = !out || typeof out !== "object" || out.ok === false;
1676
+ return {
1677
+ jsonrpc: "2.0",
1678
+ id: msg.id === void 0 ? null : msg.id,
1679
+ result: { content: [{ type: "text", text: JSON.stringify(out) }], structuredContent: out, isError }
1680
+ };
1681
+ } catch (e) {
1682
+ return {
1683
+ jsonrpc: "2.0",
1684
+ id: msg.id === void 0 ? null : msg.id,
1685
+ result: { content: [{ type: "text", text: e.message }], isError: true }
1686
+ };
1687
+ }
1688
+ }
1689
+ default:
1690
+ if (isNotification || msg.method.startsWith("notifications/")) return null;
1691
+ return rpcErr(msg.id, -32601, `Method not found: ${msg.method}`);
1692
+ }
1693
+ }
1694
+ async function handleRpcPayload(payload, opts = {}) {
1695
+ if (Array.isArray(payload)) {
1696
+ const out = (await Promise.all(payload.map((m) => handleRpc(m, opts)))).filter((r) => r !== null);
1697
+ return out.length ? out : null;
1698
+ }
1699
+ return handleRpc(payload, opts);
1700
+ }
1701
+ var CORS_HEADERS = {
1702
+ "access-control-allow-origin": "*",
1703
+ "access-control-allow-methods": "POST, GET, OPTIONS",
1704
+ "access-control-allow-headers": "Content-Type, Mcp-Session-Id, Authorization",
1705
+ "access-control-expose-headers": "Mcp-Session-Id"
1706
+ };
1707
+ function createHttpServer(opts = {}) {
1708
+ return createServer((req, res) => {
1709
+ const rawSessionId = req.headers["mcp-session-id"];
1710
+ const sessionId = typeof rawSessionId === "string" && rawSessionId.trim() ? rawSessionId.trim() : typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : void 0;
1711
+ const send = (status, body) => {
1712
+ res.writeHead(status, {
1713
+ ...CORS_HEADERS,
1714
+ ...sessionId ? { "mcp-session-id": sessionId } : {},
1715
+ "content-type": "application/json",
1716
+ "cache-control": "no-store"
1717
+ });
1718
+ res.end(body === void 0 ? "" : JSON.stringify(body));
1719
+ };
1720
+ if (req.method === "OPTIONS") {
1721
+ res.writeHead(204, {
1722
+ ...CORS_HEADERS,
1723
+ ...sessionId ? { "mcp-session-id": sessionId } : {},
1724
+ "cache-control": "no-store"
1725
+ });
1726
+ res.end();
1727
+ return;
1728
+ }
1729
+ const path = (req.url ?? "").split("?")[0];
1730
+ if (path !== "/mcp") return send(404, { error: "not_found" });
1731
+ if (req.method !== "POST") {
1732
+ res.setHeader("allow", "POST, OPTIONS");
1733
+ return send(405, { error: "method_not_allowed" });
1734
+ }
1735
+ const chunks = [];
1736
+ let size = 0;
1737
+ req.on("data", (c) => {
1738
+ size += c.length;
1739
+ if (size > 10 * 1024 * 1024) req.destroy();
1740
+ else chunks.push(c);
1741
+ });
1742
+ req.on("end", async () => {
1743
+ let payload;
1744
+ try {
1745
+ payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1746
+ } catch {
1747
+ return send(400, rpcErr(null, -32700, "Parse error"));
1748
+ }
1749
+ const out = await handleRpcPayload(payload, opts);
1750
+ if (out === null) return send(202);
1751
+ send(200, out);
1752
+ });
1753
+ });
1754
+ }
1755
+ async function runStdio(opts = {}, input = process.stdin, output = process.stdout) {
1756
+ let buffer = "";
1757
+ const pending = [];
1758
+ const processBuffer = () => {
1759
+ while (buffer.length > 0) {
1760
+ const trimmed = buffer.trimStart();
1761
+ if (!trimmed) {
1762
+ buffer = "";
1763
+ break;
1764
+ }
1765
+ buffer = trimmed;
1766
+ if (buffer.startsWith("{") || buffer.startsWith("[")) {
1767
+ let depth = 0;
1768
+ let inString = false;
1769
+ let escape = false;
1770
+ let endIdx = -1;
1771
+ for (let i = 0; i < buffer.length; i++) {
1772
+ const ch = buffer[i];
1773
+ if (inString) {
1774
+ if (escape) {
1775
+ escape = false;
1776
+ } else if (ch === "\\") {
1777
+ escape = true;
1778
+ } else if (ch === '"') {
1779
+ inString = false;
1780
+ }
1781
+ } else {
1782
+ if (ch === '"') {
1783
+ inString = true;
1784
+ } else if (ch === "{" || ch === "[") {
1785
+ depth++;
1786
+ } else if (ch === "}" || ch === "]") {
1787
+ depth--;
1788
+ if (depth === 0) {
1789
+ endIdx = i;
1790
+ break;
1791
+ }
1792
+ }
1793
+ }
1794
+ }
1795
+ if (endIdx === -1) {
1796
+ break;
1797
+ }
1798
+ const candidate = buffer.slice(0, endIdx + 1);
1799
+ buffer = buffer.slice(endIdx + 1);
1800
+ pending.push(
1801
+ (async () => {
1802
+ let out;
1803
+ try {
1804
+ out = await handleRpcPayload(JSON.parse(candidate), opts);
1805
+ } catch {
1806
+ out = rpcErr(null, -32700, "Parse error");
1807
+ }
1808
+ if (out !== null) output.write(JSON.stringify(out) + "\n");
1809
+ })()
1810
+ );
1811
+ } else {
1812
+ const nlIdx = buffer.indexOf("\n");
1813
+ if (nlIdx === -1) {
1814
+ break;
1815
+ }
1816
+ const line = buffer.slice(0, nlIdx).trim();
1817
+ buffer = buffer.slice(nlIdx + 1);
1818
+ if (line) {
1819
+ pending.push(
1820
+ (async () => {
1821
+ let out;
1822
+ try {
1823
+ out = await handleRpcPayload(JSON.parse(line), opts);
1824
+ } catch {
1825
+ out = rpcErr(null, -32700, "Parse error");
1826
+ }
1827
+ if (out !== null) output.write(JSON.stringify(out) + "\n");
1828
+ })()
1829
+ );
1830
+ }
1831
+ }
1832
+ }
1833
+ };
1834
+ await new Promise((resolve) => {
1835
+ let closed = false;
1836
+ const onEnd = () => {
1837
+ if (closed) return;
1838
+ closed = true;
1839
+ if (buffer.trim()) {
1840
+ const candidate = buffer.trim();
1841
+ buffer = "";
1842
+ pending.push(
1843
+ (async () => {
1844
+ let out;
1845
+ try {
1846
+ out = await handleRpcPayload(JSON.parse(candidate), opts);
1847
+ } catch {
1848
+ out = rpcErr(null, -32700, "Parse error");
1849
+ }
1850
+ if (out !== null) output.write(JSON.stringify(out) + "\n");
1851
+ })()
1852
+ );
1853
+ }
1854
+ resolve();
1855
+ };
1856
+ input.on("data", (chunk) => {
1857
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
1858
+ processBuffer();
1859
+ });
1860
+ input.on("end", onEnd);
1861
+ input.on("close", onEnd);
1862
+ });
1863
+ await Promise.all(pending);
1864
+ }
1865
+ export {
1866
+ PROTOCOL_VERSION,
1867
+ SERVER_INFO,
1868
+ TOOLS,
1869
+ createHttpServer,
1870
+ handleRpc,
1871
+ handleRpcPayload,
1872
+ runLocalTool,
1873
+ runStdio
1874
+ };