@fayz-ai/core 0.8.0 → 0.8.2

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 (98) hide show
  1. package/dist/access/denial.d.ts +21 -0
  2. package/dist/access/denial.d.ts.map +1 -0
  3. package/dist/access/engine.d.ts +63 -0
  4. package/dist/access/engine.d.ts.map +1 -0
  5. package/dist/access/index.cjs +60 -0
  6. package/dist/access/index.cjs.map +1 -0
  7. package/dist/access/index.d.ts +6 -0
  8. package/dist/access/index.d.ts.map +1 -0
  9. package/dist/access/index.js +51 -0
  10. package/dist/access/index.js.map +1 -0
  11. package/dist/access/limits.d.ts +10 -0
  12. package/dist/access/limits.d.ts.map +1 -0
  13. package/dist/address/index.d.ts +52 -0
  14. package/dist/address/index.d.ts.map +1 -0
  15. package/dist/{chunk-WKZVSKEU.js → chunk-CU64QI4A.js} +2 -2
  16. package/dist/chunk-CU64QI4A.js.map +1 -0
  17. package/dist/{chunk-54SRL7AJ.cjs → chunk-CYAWDW44.cjs} +141 -84
  18. package/dist/chunk-CYAWDW44.cjs.map +1 -0
  19. package/dist/{chunk-KNIVT6XZ.js → chunk-JHGXROKV.js} +230 -2
  20. package/dist/chunk-JHGXROKV.js.map +1 -0
  21. package/dist/{chunk-QR7U2URY.cjs → chunk-SO3VUKGZ.cjs} +230 -2
  22. package/dist/chunk-SO3VUKGZ.cjs.map +1 -0
  23. package/dist/{chunk-2NTHNWEH.cjs → chunk-UKU4RIWM.cjs} +2 -2
  24. package/dist/chunk-UKU4RIWM.cjs.map +1 -0
  25. package/dist/{chunk-ZBIWYDAR.js → chunk-XJKW2JRW.js} +140 -85
  26. package/dist/chunk-XJKW2JRW.js.map +1 -0
  27. package/dist/{chunk-CHGX6UYR.js → chunk-YH25Y4FW.js} +6 -3
  28. package/dist/chunk-YH25Y4FW.js.map +1 -0
  29. package/dist/{chunk-5X2VX3RQ.cjs → chunk-ZOPJB5FN.cjs} +6 -3
  30. package/dist/chunk-ZOPJB5FN.cjs.map +1 -0
  31. package/dist/data/count.d.ts +34 -0
  32. package/dist/data/count.d.ts.map +1 -0
  33. package/dist/data/index.cjs +18 -10
  34. package/dist/data/index.d.ts +2 -0
  35. package/dist/data/index.d.ts.map +1 -1
  36. package/dist/data/index.js +1 -1
  37. package/dist/data/resolve.d.ts.map +1 -1
  38. package/dist/entity/index.cjs +6 -6
  39. package/dist/entity/index.js +1 -1
  40. package/dist/entity/registry.d.ts +9 -0
  41. package/dist/entity/registry.d.ts.map +1 -1
  42. package/dist/i18n/index.cjs +10 -10
  43. package/dist/i18n/index.js +1 -1
  44. package/dist/i18n/shell-translations.d.ts.map +1 -1
  45. package/dist/index.cjs +852 -124
  46. package/dist/index.cjs.map +1 -1
  47. package/dist/index.d.ts +10 -4
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +765 -56
  50. package/dist/index.js.map +1 -1
  51. package/dist/manifest/index.d.ts +109 -3
  52. package/dist/manifest/index.d.ts.map +1 -1
  53. package/dist/manifest/serialize.d.ts +14 -0
  54. package/dist/manifest/serialize.d.ts.map +1 -0
  55. package/dist/plugin/index.cjs +7 -7
  56. package/dist/plugin/index.js +1 -1
  57. package/dist/plugin/runtime.d.ts.map +1 -1
  58. package/dist/types/billing.d.ts +20 -0
  59. package/dist/types/billing.d.ts.map +1 -1
  60. package/dist/types/crud.d.ts +48 -2
  61. package/dist/types/crud.d.ts.map +1 -1
  62. package/dist/types/entitlements.d.ts +45 -0
  63. package/dist/types/entitlements.d.ts.map +1 -0
  64. package/dist/types/index.d.ts +4 -3
  65. package/dist/types/index.d.ts.map +1 -1
  66. package/dist/types/plugins.d.ts +84 -0
  67. package/dist/types/plugins.d.ts.map +1 -1
  68. package/package.json +14 -4
  69. package/src/access/denial.ts +33 -0
  70. package/src/access/engine.test.ts +48 -0
  71. package/src/access/engine.ts +121 -0
  72. package/src/access/index.ts +13 -0
  73. package/src/access/limits.ts +18 -0
  74. package/src/address/index.ts +188 -0
  75. package/src/data/count.test.ts +152 -0
  76. package/src/data/count.ts +131 -0
  77. package/src/data/index.ts +2 -0
  78. package/src/data/resolve.ts +7 -1
  79. package/src/entity/registry.ts +7 -0
  80. package/src/i18n/shell-translations.ts +230 -0
  81. package/src/index.ts +18 -3
  82. package/src/manifest/app-manifest.schema.json +618 -45
  83. package/src/manifest/index.ts +127 -3
  84. package/src/manifest/serialize.ts +52 -0
  85. package/src/plugin/runtime.ts +5 -1
  86. package/src/types/billing.ts +22 -0
  87. package/src/types/crud.ts +49 -2
  88. package/src/types/entitlements.ts +45 -0
  89. package/src/types/index.ts +4 -3
  90. package/src/types/plugins.ts +79 -0
  91. package/dist/chunk-2NTHNWEH.cjs.map +0 -1
  92. package/dist/chunk-54SRL7AJ.cjs.map +0 -1
  93. package/dist/chunk-5X2VX3RQ.cjs.map +0 -1
  94. package/dist/chunk-CHGX6UYR.js.map +0 -1
  95. package/dist/chunk-KNIVT6XZ.js.map +0 -1
  96. package/dist/chunk-QR7U2URY.cjs.map +0 -1
  97. package/dist/chunk-WKZVSKEU.js.map +0 -1
  98. package/dist/chunk-ZBIWYDAR.js.map +0 -1
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "fayz": {
4
4
  "status": "beta"
5
5
  },
6
- "version": "0.8.0",
6
+ "version": "0.8.2",
7
7
  "description": "Fayz SDK core — data providers, entity system, plugin runtime, i18n, routing",
8
8
  "type": "module",
9
9
  "main": "./dist/index.cjs",
@@ -52,6 +52,12 @@
52
52
  "import": "./dist/runtime/index.js",
53
53
  "require": "./dist/runtime/index.cjs"
54
54
  },
55
+ "./access": {
56
+ "source": "./src/access/index.ts",
57
+ "types": "./dist/access/index.d.ts",
58
+ "import": "./dist/access/index.js",
59
+ "require": "./dist/access/index.cjs"
60
+ },
55
61
  "./types": {
56
62
  "source": "./src/types/index.ts",
57
63
  "types": "./dist/types/index.d.ts",
@@ -82,7 +88,7 @@
82
88
  "dependencies": {
83
89
  "@supabase/supabase-js": "^2.45.0",
84
90
  "zustand": "^4.5.0",
85
- "@fayz-ai/sdk": "^0.8.0"
91
+ "@fayz-ai/sdk": "^0.8.2"
86
92
  },
87
93
  "devDependencies": {
88
94
  "@types/react": "^18.3.0",
@@ -90,7 +96,9 @@
90
96
  "react": "^18.3.0",
91
97
  "react-dom": "^18.3.0",
92
98
  "tsup": "^8.2.0",
93
- "typescript": "^5.5.0"
99
+ "typescript": "^5.5.0",
100
+ "vite": "^5.4.0",
101
+ "vitest": "2.1.9"
94
102
  },
95
103
  "license": "MIT",
96
104
  "keywords": [
@@ -104,10 +112,12 @@
104
112
  "access": "public"
105
113
  },
106
114
  "scripts": {
107
- "build": "tsup && tsc --emitDeclarationOnly --declaration --declarationMap --noEmit false",
115
+ "build": "node ./scripts/check-access-purity.mjs && tsup && tsc --emitDeclarationOnly --declaration --declarationMap --noEmit false",
108
116
  "check:manifest": "node ./scripts/check-manifest-contract.mjs",
117
+ "check:access": "node ./scripts/check-access-purity.mjs",
109
118
  "dev": "tsup --watch",
110
119
  "typecheck": "tsc --noEmit",
120
+ "test": "vitest run",
111
121
  "clean": "rm -rf dist"
112
122
  }
113
123
  }
@@ -0,0 +1,33 @@
1
+ import type { DenyReason } from './engine'
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // The structured denial an AGENT surface returns instead of failing silently
5
+ // (docs/ENTITLEMENTS.md § "Superfície de agentes de IA"). One shape for every
6
+ // executor — FAB client-plane, the Fayz broker, and the pool RPCs (which emit
7
+ // its jsonb mirror in their `denial` field) — so the model can explain the
8
+ // denial and offer the upgrade path conversationally.
9
+ // ---------------------------------------------------------------------------
10
+
11
+ /** Where a denied tenant goes to upgrade — the conversational UpgradeModal. */
12
+ export const UPGRADE_URL = '/settings/subscription'
13
+
14
+ export interface AgentDenialLimit {
15
+ key: string
16
+ max: number
17
+ used: number
18
+ }
19
+
20
+ export interface AgentDenial {
21
+ allowed: false
22
+ reason: DenyReason
23
+ /** Present when `reason === 'limit'`. */
24
+ limit?: AgentDenialLimit
25
+ upgradeUrl: string
26
+ }
27
+
28
+ export type AgentGuardResult = { allowed: true } | AgentDenial
29
+
30
+ /** Build a denial with the canonical upgrade URL attached. */
31
+ export function agentDenial(reason: DenyReason, limit?: AgentDenialLimit): AgentDenial {
32
+ return { allowed: false, reason, ...(limit ? { limit } : {}), upgradeUrl: UPGRADE_URL }
33
+ }
@@ -0,0 +1,48 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import type { PermissionProfile } from '../types/permissions'
3
+ import { profileHasPermission, isOwnerProfile, resolveAccess } from './engine'
4
+ import { agentDenial, UPGRADE_URL } from './denial'
5
+
6
+ // The composition matrix (role × plan × limit math) is covered by
7
+ // packages/saas/src/access/resolver.test.ts, which now runs against this
8
+ // engine through the saas re-export — parity by construction. Here we cover
9
+ // the pieces that are new or only reachable from core.
10
+
11
+ const staff: PermissionProfile = { id: 'staff', name: 'Staff', grants: { clients: ['read'] } }
12
+
13
+ describe('profileHasPermission', () => {
14
+ it('null profile is allow-all (catalog not hydrated yet)', () => {
15
+ expect(profileHasPermission(null, 'anything', 'delete')).toBe(true)
16
+ })
17
+
18
+ it('owner matches by id or (localized) name', () => {
19
+ expect(isOwnerProfile({ id: 'owner', name: 'Proprietário', grants: {} })).toBe(true)
20
+ expect(isOwnerProfile({ id: 'x', name: 'Owner', grants: {} })).toBe(true)
21
+ expect(isOwnerProfile(staff)).toBe(false)
22
+ })
23
+
24
+ it('manage satisfies any action; empty grant list denies actionless check', () => {
25
+ const manager: PermissionProfile = { id: 'm', name: 'M', grants: { clients: ['manage'], reports: [] } }
26
+ expect(profileHasPermission(manager, 'clients', 'delete')).toBe(true)
27
+ expect(profileHasPermission(manager, 'reports')).toBe(false)
28
+ })
29
+ })
30
+
31
+ describe('agentDenial', () => {
32
+ it('carries the canonical upgrade URL', () => {
33
+ expect(agentDenial('plan')).toEqual({ allowed: false, reason: 'plan', upgradeUrl: UPGRADE_URL })
34
+ })
35
+
36
+ it('carries limit details for limit denials', () => {
37
+ const d = agentDenial('limit', { key: 'clients', max: 100, used: 100 })
38
+ expect(d.limit).toEqual({ key: 'clients', max: 100, used: 100 })
39
+ expect(d.reason).toBe('limit')
40
+ })
41
+
42
+ it('shape matches what resolveAccess produces for the same reason', () => {
43
+ const decision = resolveAccess({ profile: staff, plan: null }, 'marketing')
44
+ expect(decision.allowed).toBe(false)
45
+ const d = agentDenial(decision.reason!)
46
+ expect(d.reason).toBe('role')
47
+ })
48
+ })
@@ -0,0 +1,121 @@
1
+ import type { PermissionProfile, PermissionAction } from '../types/permissions'
2
+ import type { Plan } from '../types/billing'
3
+
4
+ // ---------------------------------------------------------------------------
5
+ // The access engine — the ONE implementation of the role × plan × limit
6
+ // decision, shared by every runtime that gates anything:
7
+ //
8
+ // - browser (saas AccessProvider / PermissionsProvider re-export from here)
9
+ // - headless client-plane (saas access/headless.ts)
10
+ // - the Fayz broker (server-side agent authorization imports this package)
11
+ //
12
+ // Hard constraint: this module (and everything under core/src/access) must stay
13
+ // free of React, zustand and supabase — pure functions over plain data — so the
14
+ // exact same code runs in Node/edge. Guarded by scripts/check-access-purity.mjs.
15
+ // ---------------------------------------------------------------------------
16
+
17
+ /** Why an access request was denied. `limit` only occurs on guarded writes. */
18
+ export type DenyReason = 'role' | 'plan' | 'limit'
19
+
20
+ export interface AccessDecision {
21
+ allowed: boolean
22
+ reason?: DenyReason
23
+ }
24
+
25
+ /** The minimal subject a decision needs — a projection of any richer session. */
26
+ export interface AccessSubject {
27
+ /** Effective RBAC profile — the previewed role during impersonation. */
28
+ profile: PermissionProfile | null
29
+ /** The tenant's currently-active plan. */
30
+ plan: Plan | null
31
+ }
32
+
33
+ /**
34
+ * The org owner has every permission implicitly. Owner is represented by the
35
+ * canonical role id `owner` across adapters (see org/adapters/supabase.ts
36
+ * buildPermissionProfiles, which also grants owner all catalog perms, and the
37
+ * mock adapter's `owner` fallback). We match by id first, falling back to the
38
+ * (possibly localized) name for safety.
39
+ */
40
+ export function isOwnerProfile(profile: PermissionProfile): boolean {
41
+ return profile.id === 'owner' || profile.name?.toLowerCase() === 'owner'
42
+ }
43
+
44
+ /**
45
+ * The single role-side permission check. The plan axis composes ON TOP of it in
46
+ * {@link resolveAccess} instead of reimplementing owner-bypass / `manage`
47
+ * semantics.
48
+ */
49
+ export function profileHasPermission(
50
+ profile: PermissionProfile | null,
51
+ feature: string,
52
+ action?: string,
53
+ ): boolean {
54
+ if (!profile) return true
55
+
56
+ // Owner bypass: never lock the owner out, even if the RBAC catalog is empty
57
+ // or still loading. Because permission checks read the *effective* profile,
58
+ // an owner previewing a non-owner role correctly loses this bypass — the
59
+ // preview stays honest.
60
+ if (isOwnerProfile(profile)) return true
61
+
62
+ const actions = profile.grants[feature]
63
+ if (!actions) return false
64
+
65
+ if (!action) return actions.length > 0
66
+
67
+ return actions.includes(action) || actions.includes('manage')
68
+ }
69
+
70
+ /**
71
+ * Does the current plan entitle `feature`? A plan gates a feature ONLY with an
72
+ * explicit `false`; absent means "not gated by this plan" (allowed). This keeps
73
+ * entitlements additive and safe: a feature the plan has never heard of stays
74
+ * open rather than silently locking.
75
+ */
76
+ export function isEntitledByPlan(plan: Plan | null, feature: string): boolean {
77
+ return plan?.entitlements?.features?.[feature] !== false
78
+ }
79
+
80
+ /**
81
+ * The single access decision: role FIRST, then plan.
82
+ *
83
+ * 1. Role — reuses `profileHasPermission` (owner bypass + `manage` semantics
84
+ * live there, and impersonation composes for free because `profile` is the
85
+ * previewed role). Denied → `{ allowed:false, reason:'role' }`.
86
+ * 2. Plan — even the owner does NOT bypass the plan: upgrading is the tenant's
87
+ * decision, not a role power. Denied → `{ allowed:false, reason:'plan' }`.
88
+ */
89
+ export function resolveAccess(
90
+ subject: AccessSubject,
91
+ feature: string,
92
+ action?: PermissionAction,
93
+ ): AccessDecision {
94
+ if (!profileHasPermission(subject.profile, feature, action)) {
95
+ return { allowed: false, reason: 'role' }
96
+ }
97
+ if (!isEntitledByPlan(subject.plan, feature)) {
98
+ return { allowed: false, reason: 'plan' }
99
+ }
100
+ return { allowed: true }
101
+ }
102
+
103
+ /**
104
+ * Pure numeric side of a limit: given the plan cap, whether a countable
105
+ * declaration exists, and the current usage, derive the limit math. Unlimited
106
+ * when there's no declaration to count, no cap on the plan, or the cap is `-1`.
107
+ */
108
+ export function resolveLimit(params: { cap: number | undefined; hasDeclaration: boolean; used: number }): {
109
+ max: number
110
+ used: number
111
+ remaining: number
112
+ atLimit: boolean
113
+ unlimited: boolean
114
+ } {
115
+ const { cap, hasDeclaration, used } = params
116
+ const unlimited = !hasDeclaration || cap === undefined || cap === -1
117
+ const max = unlimited ? Infinity : cap
118
+ const remaining = unlimited ? Infinity : Math.max(0, max - used)
119
+ const atLimit = !unlimited && used >= max
120
+ return { max, used, remaining, atLimit, unlimited }
121
+ }
@@ -0,0 +1,13 @@
1
+ export {
2
+ isOwnerProfile,
3
+ profileHasPermission,
4
+ isEntitledByPlan,
5
+ resolveAccess,
6
+ resolveLimit,
7
+ } from './engine'
8
+ export type { DenyReason, AccessDecision, AccessSubject } from './engine'
9
+
10
+ export { UPGRADE_URL, agentDenial } from './denial'
11
+ export type { AgentDenial, AgentDenialLimit, AgentGuardResult } from './denial'
12
+
13
+ export { mergeLimitDeclarations } from './limits'
@@ -0,0 +1,18 @@
1
+ import type { LimitDeclaration } from '../types/entitlements'
2
+
3
+ /**
4
+ * The 4-layer limit-declaration merge, extracted so the browser AccessProvider
5
+ * and the manifest derivation (`fayz manifest emit`) resolve the EXACT same
6
+ * final set: core built-ins < entity-derived < plugin `declaredLimits` < app
7
+ * overrides. Later layers win by key. Pure: pass the layers in, get the merge
8
+ * out — deriving a declaration FROM an entity stays at the call site.
9
+ */
10
+ export function mergeLimitDeclarations(
11
+ ...layers: Array<LimitDeclaration[] | undefined>
12
+ ): LimitDeclaration[] {
13
+ const byKey = new Map<string, LimitDeclaration>()
14
+ for (const layer of layers) {
15
+ for (const decl of layer ?? []) byKey.set(decl.key, decl)
16
+ }
17
+ return Array.from(byKey.values())
18
+ }
@@ -0,0 +1,188 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Postal code → address lookup (SDK-level — shared by any surface that collects
3
+ // an address: storefront checkout, the SaaS address book, CRM, booking).
4
+ //
5
+ // Sits beside ./phone for the same reason: knowing that a Brazilian CEP is
6
+ // eight digits, and that '01310100' means Avenida Paulista, is not a
7
+ // storefront concern. It belongs wherever an address is typed.
8
+ //
9
+ // The lookup itself is behind an interface. ViaCEP is the default because it is
10
+ // free, keyless and CORS-enabled, but it is a third party the merchant does not
11
+ // control — so swapping it for an edge-function proxy (shared cache, no
12
+ // third-party call from the shopper's browser) must be one line, not a rewrite.
13
+ // ---------------------------------------------------------------------------
14
+
15
+ /**
16
+ * An address as a postal service knows it: everything except the parts only the
17
+ * resident can supply (number, complement).
18
+ *
19
+ * Field names mirror ShippingAddressInput in @fayz-ai/shop so the value crosses
20
+ * from lookup to checkout to the order with no translation step in between.
21
+ */
22
+ export interface PostalAddress {
23
+ postalCode: string
24
+ street: string
25
+ district: string
26
+ city: string
27
+ state: string
28
+ country: string
29
+ /** IBGE municipality code when the source provides one — useful for tax later. */
30
+ cityCode?: string
31
+ }
32
+
33
+ /** Where a postal code is resolved. Implementations must not throw for a
34
+ * well-formed code that simply does not exist — that is `null`, not an error. */
35
+ export interface PostalLookupProvider {
36
+ lookup(postalCode: string): Promise<PostalAddress | null>
37
+ }
38
+
39
+ /** Keep only digits. */
40
+ export function normalizePostalCode(value: string): string {
41
+ return (value || '').replace(/\D/g, '')
42
+ }
43
+
44
+ /** '01310100' | '01310-100' -> '01310-100'. Partial input formats progressively. */
45
+ export function formatPostalCode(value: string): string {
46
+ const digits = normalizePostalCode(value).slice(0, 8)
47
+ return digits.length > 5 ? `${digits.slice(0, 5)}-${digits.slice(5)}` : digits
48
+ }
49
+
50
+ /** A Brazilian CEP is exactly eight digits. */
51
+ export function isValidPostalCode(value: string): boolean {
52
+ return normalizePostalCode(value).length === 8
53
+ }
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Cache
57
+ //
58
+ // A CEP maps to the same street for years, so the second lookup of one should
59
+ // never leave the browser. This also keeps a busy storefront well clear of
60
+ // ViaCEP's per-IP rate limit. localStorage when there is a window, an in-memory
61
+ // Map otherwise (SSR, tests, node) — never a hard failure over a cache miss.
62
+ // ---------------------------------------------------------------------------
63
+
64
+ const CACHE_KEY = 'fayz.postal.cache.v1'
65
+ const memoryCache = new Map<string, PostalAddress>()
66
+
67
+ function readCache(code: string): PostalAddress | undefined {
68
+ const hit = memoryCache.get(code)
69
+ if (hit) return hit
70
+ try {
71
+ const raw = globalThis.localStorage?.getItem(CACHE_KEY)
72
+ if (!raw) return undefined
73
+ const all = JSON.parse(raw) as Record<string, PostalAddress>
74
+ const stored = all[code]
75
+ if (stored) memoryCache.set(code, stored)
76
+ return stored
77
+ } catch {
78
+ return undefined
79
+ }
80
+ }
81
+
82
+ function writeCache(code: string, address: PostalAddress): void {
83
+ memoryCache.set(code, address)
84
+ try {
85
+ const store = globalThis.localStorage
86
+ if (!store) return
87
+ const raw = store.getItem(CACHE_KEY)
88
+ const all = raw ? (JSON.parse(raw) as Record<string, PostalAddress>) : {}
89
+ all[code] = address
90
+ store.setItem(CACHE_KEY, JSON.stringify(all))
91
+ } catch {
92
+ /* quota or private mode — the in-memory copy still stands for this session */
93
+ }
94
+ }
95
+
96
+ /** Drop the cache. Exposed for tests and for a "wrong address?" escape hatch. */
97
+ export function clearPostalCache(): void {
98
+ memoryCache.clear()
99
+ try {
100
+ globalThis.localStorage?.removeItem(CACHE_KEY)
101
+ } catch {
102
+ /* ignore */
103
+ }
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // ViaCEP
108
+ // ---------------------------------------------------------------------------
109
+
110
+ interface ViaCepResponse {
111
+ cep?: string
112
+ logradouro?: string
113
+ bairro?: string
114
+ localidade?: string
115
+ uf?: string
116
+ ibge?: string
117
+ erro?: boolean | string
118
+ }
119
+
120
+ /**
121
+ * ViaCEP (https://viacep.com.br). Free, no key, CORS-enabled.
122
+ *
123
+ * The trap: an unknown CEP does NOT come back as 404. ViaCEP answers HTTP 200
124
+ * with `{"erro": true}` (and, on some deploys, the string "true"), so checking
125
+ * response.ok alone yields an address of empty strings that silently overwrites
126
+ * whatever the shopper had typed. Both shapes are treated as "not found".
127
+ */
128
+ export function createViaCepProvider(options?: { fetcher?: typeof fetch }): PostalLookupProvider {
129
+ const fetcher = options?.fetcher ?? globalThis.fetch
130
+ return {
131
+ async lookup(postalCode: string): Promise<PostalAddress | null> {
132
+ const code = normalizePostalCode(postalCode)
133
+ if (code.length !== 8) return null
134
+
135
+ const response = await fetcher(`https://viacep.com.br/ws/${code}/json/`)
136
+ if (!response.ok) throw new Error(`Consulta de CEP falhou (${response.status})`)
137
+
138
+ const data = (await response.json()) as ViaCepResponse
139
+ if (data.erro === true || data.erro === 'true' || !data.localidade) return null
140
+
141
+ return {
142
+ postalCode: code,
143
+ street: data.logradouro ?? '',
144
+ district: data.bairro ?? '',
145
+ city: data.localidade,
146
+ state: (data.uf ?? '').toUpperCase(),
147
+ country: 'BR',
148
+ cityCode: data.ibge || undefined,
149
+ }
150
+ },
151
+ }
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // Module-level resolver — same shape as setShopTenantResolver /
156
+ // setShopAccessTokenResolver, so an app overrides the source once at boot
157
+ // instead of threading a provider through every component that needs a CEP.
158
+ // ---------------------------------------------------------------------------
159
+
160
+ let _provider: PostalLookupProvider | null = null
161
+
162
+ export function setPostalLookupProvider(provider: PostalLookupProvider | null): void {
163
+ _provider = provider
164
+ }
165
+
166
+ export function getPostalLookupProvider(): PostalLookupProvider {
167
+ if (!_provider) _provider = createViaCepProvider()
168
+ return _provider
169
+ }
170
+
171
+ /**
172
+ * Resolve a postal code to an address, through the cache.
173
+ *
174
+ * Returns null for a code that is malformed or does not exist; throws only when
175
+ * the lookup itself failed (offline, provider down), so a caller can tell
176
+ * "no such CEP" from "we could not check right now" and say the right thing.
177
+ */
178
+ export async function lookupPostalCode(postalCode: string): Promise<PostalAddress | null> {
179
+ const code = normalizePostalCode(postalCode)
180
+ if (code.length !== 8) return null
181
+
182
+ const cached = readCache(code)
183
+ if (cached) return cached
184
+
185
+ const address = await getPostalLookupProvider().lookup(code)
186
+ if (address) writeCache(code, address)
187
+ return address
188
+ }
@@ -0,0 +1,152 @@
1
+ import { describe, it, expect, beforeEach, vi } from 'vitest'
2
+ import { countByTenant, invalidateCount } from './count'
3
+ import { setGlobalSupabaseClient } from './supabase'
4
+ import { setActiveTenantId } from '../tenant'
5
+
6
+ // ---------------------------------------------------------------------------
7
+ // Mock Supabase client — a thenable query builder that records .eq/.gte calls.
8
+ // ---------------------------------------------------------------------------
9
+
10
+ interface MockClient {
11
+ client: unknown
12
+ selectCalls: number
13
+ lastEq: Array<[string, unknown]>
14
+ lastGte: Array<[string, unknown]>
15
+ setCount: (n: number, error?: unknown) => void
16
+ }
17
+
18
+ function makeClient(initialCount = 0): MockClient {
19
+ const state = { count: initialCount as number, error: null as unknown }
20
+ const record: MockClient = {
21
+ client: null,
22
+ selectCalls: 0,
23
+ lastEq: [],
24
+ lastGte: [],
25
+ setCount: (n, error = null) => {
26
+ state.count = n
27
+ state.error = error
28
+ },
29
+ }
30
+
31
+ const query: Record<string, unknown> = {
32
+ eq: (col: string, val: unknown) => {
33
+ record.lastEq.push([col, val])
34
+ return query
35
+ },
36
+ gte: (col: string, val: unknown) => {
37
+ record.lastGte.push([col, val])
38
+ return query
39
+ },
40
+ then: (resolve: (r: { count: number; error: unknown }) => void) =>
41
+ resolve({ count: state.count, error: state.error }),
42
+ }
43
+
44
+ record.client = {
45
+ from: () => ({
46
+ select: (_cols: string, _opts: unknown) => {
47
+ record.selectCalls++
48
+ return query
49
+ },
50
+ }),
51
+ }
52
+ return record
53
+ }
54
+
55
+ describe('countByTenant', () => {
56
+ beforeEach(() => {
57
+ invalidateCount() // clear all cached counts
58
+ setGlobalSupabaseClient(null as unknown as object)
59
+ setActiveTenantId('tenant-1')
60
+ })
61
+
62
+ it('returns 0 in mock mode (no supabase client) — never blocks', async () => {
63
+ setGlobalSupabaseClient(null as unknown as object)
64
+ expect(await countByTenant('clients')).toBe(0)
65
+ })
66
+
67
+ it('returns 0 when no tenant is resolvable', async () => {
68
+ setActiveTenantId(undefined)
69
+ const m = makeClient(5)
70
+ setGlobalSupabaseClient(m.client as object)
71
+ expect(await countByTenant('clients')).toBe(0)
72
+ })
73
+
74
+ it('counts tenant-scoped rows via head:true', async () => {
75
+ const m = makeClient(42)
76
+ setGlobalSupabaseClient(m.client as object)
77
+ expect(await countByTenant('clients')).toBe(42)
78
+ expect(m.lastEq).toContainEqual(['tenant_id', 'tenant-1'])
79
+ })
80
+
81
+ it('caches within the TTL (second read does not hit the DB)', async () => {
82
+ const m = makeClient(10)
83
+ setGlobalSupabaseClient(m.client as object)
84
+ await countByTenant('clients')
85
+ await countByTenant('clients')
86
+ expect(m.selectCalls).toBe(1)
87
+ })
88
+
89
+ it('fresh:true bypasses the cache', async () => {
90
+ const m = makeClient(10)
91
+ setGlobalSupabaseClient(m.client as object)
92
+ await countByTenant('clients')
93
+ await countByTenant('clients', { fresh: true })
94
+ expect(m.selectCalls).toBe(2)
95
+ })
96
+
97
+ it('invalidateCount(table) drops the cached value', async () => {
98
+ const m = makeClient(10)
99
+ setGlobalSupabaseClient(m.client as object)
100
+ await countByTenant('clients')
101
+ invalidateCount('clients')
102
+ await countByTenant('clients')
103
+ expect(m.selectCalls).toBe(2)
104
+ })
105
+
106
+ it('separate keys (kind/period) are cached independently', async () => {
107
+ const m = makeClient(3)
108
+ setGlobalSupabaseClient(m.client as object)
109
+ await countByTenant('bookings', { period: 'month' })
110
+ await countByTenant('bookings', { period: 'total' })
111
+ expect(m.selectCalls).toBe(2)
112
+ })
113
+
114
+ it('applies kind filter and month window', async () => {
115
+ const m = makeClient(7)
116
+ setGlobalSupabaseClient(m.client as object)
117
+ await countByTenant('items', { kind: 'product', period: 'month' })
118
+ expect(m.lastEq).toContainEqual(['kind', 'product'])
119
+ expect(m.lastGte.some(([col]) => col === 'created_at')).toBe(true)
120
+ })
121
+
122
+ it('fails open (returns 0) when the query errors', async () => {
123
+ const m = makeClient(0)
124
+ m.setCount(0, new Error('boom'))
125
+ setGlobalSupabaseClient(m.client as object)
126
+ expect(await countByTenant('clients')).toBe(0)
127
+ })
128
+
129
+ it('fails open (returns 0) instead of hanging when the query never settles', async () => {
130
+ // A cold-boot query can be issued before the auth session is ready and then
131
+ // never resolve. The guard awaiting this must not hang the UI forever.
132
+ const client = {
133
+ from: () => ({
134
+ select: () => ({
135
+ eq: () => ({
136
+ eq: () => neverSettles,
137
+ gte: () => neverSettles,
138
+ then: neverSettles.then.bind(neverSettles),
139
+ }),
140
+ }),
141
+ }),
142
+ }
143
+ const neverSettles = { then: () => {} } as unknown as Promise<never>
144
+ setGlobalSupabaseClient(client as object)
145
+
146
+ vi.useFakeTimers()
147
+ const pending = countByTenant('clients', { fresh: true })
148
+ await vi.advanceTimersByTimeAsync(6_000)
149
+ await expect(pending).resolves.toBe(0)
150
+ vi.useRealTimers()
151
+ })
152
+ })