@orechio/platform-angular 0.7.3 → 0.8.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.
package/README.md CHANGED
@@ -28,6 +28,11 @@ provideOrechioAccount({
28
28
  { path: 'conta', children: ORECHIO_ACCOUNT_ROUTES }
29
29
  ```
30
30
 
31
+ **Provisioning (since 0.8.0).** When the BFF (`Orechio.Platform.Bff.Account` 0.5.0 or newer) returns
32
+ `provisioningRequired: true` — at login or when the session is loaded — `provideOrechioAccount` sends
33
+ the user to the first-branch route above, wherever `ORECHIO_ACCOUNT_ROUTES` is mounted. The product
34
+ writes no code for it. `SessionUser.provisioningRequired` is also available to read.
35
+
31
36
  `onCompleted` is required and validated at bootstrap — the package deliberately has no
32
37
  default destination, because a wrong one is only discovered by the first real customer
33
38
  finishing the flow, once, with no way to retry the step.
@@ -1,4 +1,88 @@
1
- import { InjectionToken } from '@angular/core';
1
+ import * as i0 from '@angular/core';
2
+ import { inject, Injector, effect, untracked, Injectable, InjectionToken, ENVIRONMENT_INITIALIZER } from '@angular/core';
3
+ import { Router } from '@angular/router';
4
+ import { SessionStore } from '@orechio/platform-angular';
5
+
6
+ /** O caminho da tela de primeira filial DENTRO de `ORECHIO_ACCOUNT_ROUTES`. */
7
+ const CAMINHO_RELATIVO = 'onboarding/branch';
8
+ /**
9
+ * PROV-1 (inventário A15) — leva a sessão de provisionamento à tela de primeira filial.
10
+ *
11
+ * <p>
12
+ * O BFF passa a aceitar, no login e na leitura da sessão, o token de quem ainda não tem filial
13
+ * e devolve <c>provisioningRequired: true</c>. Sem ninguém reagindo à flag, o dono entraria no
14
+ * painel com uma sessão que não abre nada. Quem reage é este serviço, ligado por
15
+ * <c>provideOrechioAccount</c> — o produto não escreve código novo, só atualiza a versão.
16
+ * </p>
17
+ *
18
+ * <p>
19
+ * <b>Por que observar a sessão e não esperar o login chamar.</b> O login e o <c>GET /session</c>
20
+ * (reload) terminam do mesmo jeito: <c>SessionStore.set</c>. Observar o store cobre os dois
21
+ * sem tocar no <c>AuthClient</c> e sem pedir um callback à tela de login do produto, que o
22
+ * pacote não possui. A navegação vem DEPOIS da que a tela de login faz ao sucesso e a
23
+ * substitui — é a última que vale.
24
+ * </p>
25
+ *
26
+ * <p>
27
+ * A flag decide navegação, nunca autorização: a Platform só aceita o token de provisionamento
28
+ * na rota de primeira filial.
29
+ * </p>
30
+ */
31
+ class ProvisioningRedirect {
32
+ session = inject(SessionStore);
33
+ router = inject(Router);
34
+ injector = inject(Injector);
35
+ iniciado = false;
36
+ start() {
37
+ if (this.iniciado)
38
+ return;
39
+ this.iniciado = true;
40
+ effect(() => {
41
+ if (this.session.user()?.provisioningRequired !== true)
42
+ return;
43
+ untracked(() => void this.irParaAPrimeiraFilial());
44
+ }, { injector: this.injector });
45
+ }
46
+ async irParaAPrimeiraFilial() {
47
+ const destino = caminhoDaPrimeiraFilial(this.router.config);
48
+ if (destino === null) {
49
+ // Sem a rota montada o desvio é impossível, e calar deixaria o dono num painel que não
50
+ // abre nada. Aviso, não exceção: lançar aqui derrubaria o login de todo mundo.
51
+ console.warn('[orechio-account] provisioningRequired recebido, mas ORECHIO_ACCOUNT_ROUTES não está ' +
52
+ `montado de forma estática (rota "${CAMINHO_RELATIVO}" não encontrada em router.config).`);
53
+ return;
54
+ }
55
+ if (this.router.url.split(/[?#]/)[0] === destino)
56
+ return;
57
+ await this.router.navigateByUrl(destino, { replaceUrl: true });
58
+ }
59
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: ProvisioningRedirect, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
60
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: ProvisioningRedirect, providedIn: 'root' });
61
+ }
62
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: ProvisioningRedirect, decorators: [{
63
+ type: Injectable,
64
+ args: [{ providedIn: 'root' }]
65
+ }] });
66
+ /**
67
+ * Procura, em <c>router.config</c>, a rota de primeira filial e devolve o caminho ABSOLUTO dela.
68
+ * O host monta <c>ORECHIO_ACCOUNT_ROUTES</c> onde quiser (<c>conta</c>, <c>auth</c>, a raiz); o
69
+ * pacote só conhece o caminho relativo entre as telas, então o prefixo se descobre pela
70
+ * árvore. Rotas carregadas sob demanda (<c>loadChildren</c>) não estão na árvore até serem
71
+ * visitadas e não são procuradas.
72
+ */
73
+ function caminhoDaPrimeiraFilial(rotas, prefixo = '') {
74
+ for (const rota of rotas) {
75
+ const caminho = [prefixo, rota.path ?? ''].filter((parte) => parte !== '').join('/');
76
+ if (rota.path === CAMINHO_RELATIVO)
77
+ return `/${caminho}`;
78
+ if (rota.children) {
79
+ const achada = caminhoDaPrimeiraFilial(rota.children, caminho);
80
+ if (achada !== null)
81
+ return achada;
82
+ }
83
+ }
84
+ return null;
85
+ }
2
86
 
3
87
  const ORECHIO_ACCOUNT_CONFIG = new InjectionToken('ORECHIO_ACCOUNT_CONFIG');
4
88
  function provideOrechioAccount(options) {
@@ -23,7 +107,19 @@ function provideOrechioAccount(options) {
23
107
  branchLabel: options.branchLabel ?? 'unidade',
24
108
  loginPath: options.loginPath ?? '/login',
25
109
  };
26
- return [{ provide: ORECHIO_ACCOUNT_CONFIG, useValue: config }];
110
+ return [
111
+ { provide: ORECHIO_ACCOUNT_CONFIG, useValue: config },
112
+ // PROV-1: liga o desvio da sessão de provisionamento para a tela de primeira filial. Fica
113
+ // aqui, e não num guard ou callback do host, para o produto só precisar atualizar a versão.
114
+ // `ENVIRONMENT_INITIALIZER` (e não `provideEnvironmentInitializer`) para o retorno continuar
115
+ // `Provider[]`: um `EnvironmentProviders` aqui quebraria quem usa o resultado em
116
+ // `providers` de componente ou o tipa como `Provider[]`.
117
+ {
118
+ provide: ENVIRONMENT_INITIALIZER,
119
+ multi: true,
120
+ useValue: () => inject(ProvisioningRedirect).start(),
121
+ },
122
+ ];
27
123
  }
28
124
 
29
125
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"orechio-platform-angular-account.mjs","sources":["../../../projects/platform-angular/account/src/account-config.ts","../../../projects/platform-angular/account/src/account.routes.ts","../../../projects/platform-angular/account/src/public-api.ts","../../../projects/platform-angular/account/src/orechio-platform-angular-account.ts"],"sourcesContent":["import { InjectionToken, Provider } from '@angular/core';\r\nimport { UrlTree } from '@angular/router';\r\n\r\n/**\r\n * A fronteira do core compartilhado, como o browser a recebe (ADR-019 §3).\r\n *\r\n * <p>\r\n * Sem token nenhum, e isso é o contrato — não uma omissão. O BFF recebe os tokens da\r\n * Platform e os entrega ao mecanismo de sessão do host; o que chega aqui é o estado da\r\n * conta, nunca o material dela.\r\n * </p>\r\n */\r\nexport interface AccountCompletionResult {\r\n tenantId: string;\r\n branchId: string;\r\n applicationId: string;\r\n userId: string;\r\n /**\r\n * `OperationalReady` ou `ProductContinuation` — enum fechado do lado da Platform.\r\n * Trafega como string e é repassado **sem interpretação**: quem traduz isso em rota é o\r\n * host, nunca este pacote.\r\n */\r\n nextStep: string;\r\n}\r\n\r\n/** Rotas do BFF que o host montou. Defaults batem com `MapOrechioAccountEndpoints`. */\r\nexport interface OrechioAccountPaths {\r\n verifyEmail?: string;\r\n initialBranch?: string;\r\n forgotPassword?: string;\r\n resetPassword?: string;\r\n acceptInvite?: string;\r\n resendVerification?: string;\r\n}\r\n\r\nexport interface OrechioAccountConfig {\r\n /**\r\n * Prefixo do BFF de conta, same-origin. Nunca uma URL absoluta cross-origin: o modelo é\r\n * BFF no domínio do produto, e é isso que faz o cookie ser first-party.\r\n */\r\n basePath: string;\r\n\r\n paths: Required<OrechioAccountPaths>;\r\n\r\n /**\r\n * **O único ponto de extensão do pacote.**\r\n *\r\n * Chamado quando a conta fica operacional. O host decide para onde ir: um produto com\r\n * cadastro próprio manda para o passo dele, um produto sem passo próprio manda direto para\r\n * o painel. O pacote não conhece nenhuma dessas rotas, e é essa ignorância que o mantém\r\n * compartilhável (ADR-019 §3).\r\n *\r\n * Nem os nomes desses destinos aparecem aqui — nem em comentário. Um exemplo concreto de\r\n * um produto irmão é a primeira forma do acoplamento: vira referência, depois default,\r\n * depois `if`. A guarda de fronteira varre estes fontes e falha em termo vertical.\r\n */\r\n onCompleted: (result: AccountCompletionResult) => UrlTree | string;\r\n\r\n /**\r\n * Como o produto chama a primeira unidade operacional, no vocabulário dele. \"Unidade\" é o\r\n * default por ser o termo mais neutro que existe — cada produto tem o seu, e nenhum deles\r\n * é assunto do pacote. É por isso que isto é configuração e não literal na tela.\r\n */\r\n branchLabel: string;\r\n\r\n /** Para onde mandar quem termina um fluxo que não abre sessão (reset, convite aceito). */\r\n loginPath: string;\r\n}\r\n\r\nexport const ORECHIO_ACCOUNT_CONFIG = new InjectionToken<OrechioAccountConfig>(\r\n 'ORECHIO_ACCOUNT_CONFIG',\r\n);\r\n\r\nexport interface OrechioAccountOptions {\r\n basePath?: string;\r\n paths?: OrechioAccountPaths;\r\n onCompleted: OrechioAccountConfig['onCompleted'];\r\n branchLabel?: string;\r\n loginPath?: string;\r\n}\r\n\r\nexport function provideOrechioAccount(options: OrechioAccountOptions): Provider[] {\r\n if (typeof options?.onCompleted !== 'function') {\r\n // Falha na composição, não no primeiro cliente que termina o cadastro. Sem\r\n // `onCompleted` o pacote não teria para onde mandar ninguém, e o sintoma apareceria\r\n // exatamente no pior momento: com o usuário já cadastrado, olhando uma tela parada.\r\n throw new Error(\r\n 'provideOrechioAccount: `onCompleted` é obrigatório — é o host que decide a navegação.',\r\n );\r\n }\r\n\r\n const basePath = (options.basePath ?? '/api/account').replace(/\\/+$/, '');\r\n\r\n const config: OrechioAccountConfig = {\r\n basePath,\r\n paths: {\r\n verifyEmail: options.paths?.verifyEmail ?? '/verify-email',\r\n initialBranch: options.paths?.initialBranch ?? '/onboarding/branch',\r\n forgotPassword: options.paths?.forgotPassword ?? '/forgot-password',\r\n resetPassword: options.paths?.resetPassword ?? '/reset-password',\r\n acceptInvite: options.paths?.acceptInvite ?? '/accept-invite',\r\n resendVerification: options.paths?.resendVerification ?? '/resend-verification',\r\n },\r\n onCompleted: options.onCompleted,\r\n branchLabel: options.branchLabel ?? 'unidade',\r\n loginPath: options.loginPath ?? '/login',\r\n };\r\n\r\n return [{ provide: ORECHIO_ACCOUNT_CONFIG, useValue: config }];\r\n}\r\n","import { Routes } from '@angular/router';\r\n\r\n/**\r\n * As rotas de conta, para o host registrar ONDE ELE QUISER.\r\n *\r\n * <p>\r\n * São `Routes[]` e não um módulo com prefixo fixo de propósito: o produto monta em\r\n * `/conta`, em `/auth`, na raiz, ou espalhadas — o pacote não reivindica caminho. O que ele\r\n * fixa são os caminhos RELATIVOS entre elas, porque o `verify-email` navega para\r\n * `../onboarding/branch` quando há provisioning pendente.\r\n * </p>\r\n *\r\n * <pre>\r\n * // no host:\r\n * { path: 'conta', children: ORECHIO_ACCOUNT_ROUTES }\r\n * </pre>\r\n *\r\n * <p>\r\n * Todas com `loadComponent`: quem só usa recuperação de senha não carrega a tela de\r\n * primeira filial, e o bundle inicial do produto não paga por telas que a maioria dos\r\n * usuários vê uma vez na vida.\r\n * </p>\r\n */\r\nexport const ORECHIO_ACCOUNT_ROUTES: Routes = [\r\n {\r\n path: 'verify-email',\r\n title: 'Confirmando e-mail',\r\n loadComponent: () => import('./pages/verify-email.page').then((m) => m.VerifyEmailPage),\r\n },\r\n {\r\n path: 'onboarding/branch',\r\n title: 'Primeira unidade',\r\n loadComponent: () => import('./pages/initial-branch.page').then((m) => m.InitialBranchPage),\r\n },\r\n {\r\n path: 'forgot-password',\r\n title: 'Recuperar acesso',\r\n loadComponent: () => import('./pages/forgot-password.page').then((m) => m.ForgotPasswordPage),\r\n },\r\n {\r\n path: 'reset-password',\r\n title: 'Nova senha',\r\n loadComponent: () => import('./pages/token-password.page').then((m) => m.TokenPasswordPage),\r\n // `reset` também é o default do componente; declarado aqui para a rota dizer o que faz\r\n // sem exigir que se leia a implementação.\r\n data: { modo: 'reset' },\r\n },\r\n {\r\n path: 'accept-invite',\r\n title: 'Primeiro acesso',\r\n loadComponent: () => import('./pages/token-password.page').then((m) => m.TokenPasswordPage),\r\n data: { modo: 'invite' },\r\n },\r\n {\r\n path: 'resend-verification',\r\n title: 'Reenviar confirmação',\r\n loadComponent: () =>\r\n import('./pages/resend-verification.page').then((m) => m.ResendVerificationPage),\r\n },\r\n];\r\n","/*\r\n * Public API Surface of @orechio/platform-angular/account\r\n *\r\n * ACCOUNT-1C — o entry de conta. Ele traz as TELAS do onboarding compartilhado; a sessão,\r\n * o login e os interceptors continuam no entry primário, onde já estavam (ADR-019 §5.1:\r\n * login/refresh/logout são KEEP-SEPARATE — Store e Portal resolvem sessão de formas\r\n * materialmente diferentes).\r\n *\r\n * O que NÃO é exportado é parte do contrato: `AccountClient` é detalhe de implementação, e\r\n * as páginas são alcançadas por `ORECHIO_ACCOUNT_ROUTES`, nunca importadas diretamente —\r\n * exportá-las convidaria o host a montar a própria árvore de rotas por cima delas, e os\r\n * caminhos relativos entre as telas deixariam de valer.\r\n */\r\n\r\nexport type {\r\n AccountCompletionResult,\r\n OrechioAccountConfig,\r\n OrechioAccountOptions,\r\n OrechioAccountPaths,\r\n} from './account-config';\r\nexport { ORECHIO_ACCOUNT_CONFIG, provideOrechioAccount } from './account-config';\r\n\r\nexport { ORECHIO_ACCOUNT_ROUTES } from './account.routes';\r\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;MAqEa,sBAAsB,GAAG,IAAI,cAAc,CACtD,wBAAwB;AAWpB,SAAU,qBAAqB,CAAC,OAA8B,EAAA;AAClE,IAAA,IAAI,OAAO,OAAO,EAAE,WAAW,KAAK,UAAU,EAAE;;;;AAI9C,QAAA,MAAM,IAAI,KAAK,CACb,uFAAuF,CACxF;IACH;AAEA,IAAA,MAAM,QAAQ,GAAG,CAAC,OAAO,CAAC,QAAQ,IAAI,cAAc,EAAE,OAAO,CAAC,MAAM,EAAE,EAAE,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AAE,iBAAiB;AACvB,QAAA,KAAK,EAAE,kBAAkB;AACzB,QAAA,aAAa,EAAE,MAAM,OAAO,sEAA8B,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,kBAAkB,CAAC;AAC9F,KAAA;AACD,IAAA;AACE,QAAA,IAAI,EAAE,gBAAgB;AACtB,QAAA,KAAK,EAAE,YAAY;AACnB,QAAA,aAAa,EAAE,MAAM,OAAO,qEAA6B,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,iBAAiB,CAAC;;;AAG3F,QAAA,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;AACxB,KAAA;AACD,IAAA;AACE,QAAA,IAAI,EAAE,eAAe;AACrB,QAAA,KAAK,EAAE,iBAAiB;AACxB,QAAA,aAAa,EAAE,MAAM,OAAO,qEAA6B,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,iBAAiB,CAAC;AAC3F,QAAA,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,KAAA;AACD,IAAA;AACE,QAAA,IAAI,EAAE,qBAAqB;AAC3B,QAAA,KAAK,EAAE,sBAAsB;AAC7B,QAAA,aAAa,EAAE,MACb,OAAO,0EAAkC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,sBAAsB,CAAC;AACnF,KAAA;;;AC1DH;;;;;;;;;;;;AAYG;;ACZH;;AAEG;;;;"}
1
+ {"version":3,"file":"orechio-platform-angular-account.mjs","sources":["../../../projects/platform-angular/account/src/provisioning-redirect.ts","../../../projects/platform-angular/account/src/account-config.ts","../../../projects/platform-angular/account/src/account.routes.ts","../../../projects/platform-angular/account/src/public-api.ts","../../../projects/platform-angular/account/src/orechio-platform-angular-account.ts"],"sourcesContent":["import { Injectable, Injector, effect, inject, untracked } from '@angular/core';\r\nimport { Route, Router } from '@angular/router';\r\nimport { SessionStore } from '@orechio/platform-angular';\r\n\r\n/** O caminho da tela de primeira filial DENTRO de `ORECHIO_ACCOUNT_ROUTES`. */\r\nconst CAMINHO_RELATIVO = 'onboarding/branch';\r\n\r\n/**\r\n * PROV-1 (inventário A15) — leva a sessão de provisionamento à tela de primeira filial.\r\n *\r\n * <p>\r\n * O BFF passa a aceitar, no login e na leitura da sessão, o token de quem ainda não tem filial\r\n * e devolve <c>provisioningRequired: true</c>. Sem ninguém reagindo à flag, o dono entraria no\r\n * painel com uma sessão que não abre nada. Quem reage é este serviço, ligado por\r\n * <c>provideOrechioAccount</c> — o produto não escreve código novo, só atualiza a versão.\r\n * </p>\r\n *\r\n * <p>\r\n * <b>Por que observar a sessão e não esperar o login chamar.</b> O login e o <c>GET /session</c>\r\n * (reload) terminam do mesmo jeito: <c>SessionStore.set</c>. Observar o store cobre os dois\r\n * sem tocar no <c>AuthClient</c> e sem pedir um callback à tela de login do produto, que o\r\n * pacote não possui. A navegação vem DEPOIS da que a tela de login faz ao sucesso e a\r\n * substitui — é a última que vale.\r\n * </p>\r\n *\r\n * <p>\r\n * A flag decide navegação, nunca autorização: a Platform só aceita o token de provisionamento\r\n * na rota de primeira filial.\r\n * </p>\r\n */\r\n@Injectable({ providedIn: 'root' })\r\nexport class ProvisioningRedirect {\r\n private readonly session = inject(SessionStore);\r\n private readonly router = inject(Router);\r\n private readonly injector = inject(Injector);\r\n\r\n private iniciado = false;\r\n\r\n start(): void {\r\n if (this.iniciado) return;\r\n this.iniciado = true;\r\n\r\n effect(\r\n () => {\r\n if (this.session.user()?.provisioningRequired !== true) return;\r\n untracked(() => void this.irParaAPrimeiraFilial());\r\n },\r\n { injector: this.injector },\r\n );\r\n }\r\n\r\n private async irParaAPrimeiraFilial(): Promise<void> {\r\n const destino = caminhoDaPrimeiraFilial(this.router.config);\r\n if (destino === null) {\r\n // Sem a rota montada o desvio é impossível, e calar deixaria o dono num painel que não\r\n // abre nada. Aviso, não exceção: lançar aqui derrubaria o login de todo mundo.\r\n console.warn(\r\n '[orechio-account] provisioningRequired recebido, mas ORECHIO_ACCOUNT_ROUTES não está ' +\r\n `montado de forma estática (rota \"${CAMINHO_RELATIVO}\" não encontrada em router.config).`,\r\n );\r\n return;\r\n }\r\n\r\n if (this.router.url.split(/[?#]/)[0] === destino) return;\r\n await this.router.navigateByUrl(destino, { replaceUrl: true });\r\n }\r\n}\r\n\r\n/**\r\n * Procura, em <c>router.config</c>, a rota de primeira filial e devolve o caminho ABSOLUTO dela.\r\n * O host monta <c>ORECHIO_ACCOUNT_ROUTES</c> onde quiser (<c>conta</c>, <c>auth</c>, a raiz); o\r\n * pacote só conhece o caminho relativo entre as telas, então o prefixo se descobre pela\r\n * árvore. Rotas carregadas sob demanda (<c>loadChildren</c>) não estão na árvore até serem\r\n * visitadas e não são procuradas.\r\n */\r\nexport function caminhoDaPrimeiraFilial(rotas: readonly Route[], prefixo = ''): string | null {\r\n for (const rota of rotas) {\r\n const caminho = [prefixo, rota.path ?? ''].filter((parte) => parte !== '').join('/');\r\n if (rota.path === CAMINHO_RELATIVO) return `/${caminho}`;\r\n if (rota.children) {\r\n const achada = caminhoDaPrimeiraFilial(rota.children, caminho);\r\n if (achada !== null) return achada;\r\n }\r\n }\r\n return null;\r\n}\r\n","import { ENVIRONMENT_INITIALIZER, InjectionToken, Provider, inject } from '@angular/core';\r\nimport { UrlTree } from '@angular/router';\r\nimport { ProvisioningRedirect } from './provisioning-redirect';\r\n\r\n/**\r\n * A fronteira do core compartilhado, como o browser a recebe (ADR-019 §3).\r\n *\r\n * <p>\r\n * Sem token nenhum, e isso é o contrato — não uma omissão. O BFF recebe os tokens da\r\n * Platform e os entrega ao mecanismo de sessão do host; o que chega aqui é o estado da\r\n * conta, nunca o material dela.\r\n * </p>\r\n */\r\nexport interface AccountCompletionResult {\r\n tenantId: string;\r\n branchId: string;\r\n applicationId: string;\r\n userId: string;\r\n /**\r\n * `OperationalReady` ou `ProductContinuation` — enum fechado do lado da Platform.\r\n * Trafega como string e é repassado **sem interpretação**: quem traduz isso em rota é o\r\n * host, nunca este pacote.\r\n */\r\n nextStep: string;\r\n}\r\n\r\n/** Rotas do BFF que o host montou. Defaults batem com `MapOrechioAccountEndpoints`. */\r\nexport interface OrechioAccountPaths {\r\n verifyEmail?: string;\r\n initialBranch?: string;\r\n forgotPassword?: string;\r\n resetPassword?: string;\r\n acceptInvite?: string;\r\n resendVerification?: string;\r\n}\r\n\r\nexport interface OrechioAccountConfig {\r\n /**\r\n * Prefixo do BFF de conta, same-origin. Nunca uma URL absoluta cross-origin: o modelo é\r\n * BFF no domínio do produto, e é isso que faz o cookie ser first-party.\r\n */\r\n basePath: string;\r\n\r\n paths: Required<OrechioAccountPaths>;\r\n\r\n /**\r\n * **O único ponto de extensão do pacote.**\r\n *\r\n * Chamado quando a conta fica operacional. O host decide para onde ir: um produto com\r\n * cadastro próprio manda para o passo dele, um produto sem passo próprio manda direto para\r\n * o painel. O pacote não conhece nenhuma dessas rotas, e é essa ignorância que o mantém\r\n * compartilhável (ADR-019 §3).\r\n *\r\n * Nem os nomes desses destinos aparecem aqui — nem em comentário. Um exemplo concreto de\r\n * um produto irmão é a primeira forma do acoplamento: vira referência, depois default,\r\n * depois `if`. A guarda de fronteira varre estes fontes e falha em termo vertical.\r\n */\r\n onCompleted: (result: AccountCompletionResult) => UrlTree | string;\r\n\r\n /**\r\n * Como o produto chama a primeira unidade operacional, no vocabulário dele. \"Unidade\" é o\r\n * default por ser o termo mais neutro que existe — cada produto tem o seu, e nenhum deles\r\n * é assunto do pacote. É por isso que isto é configuração e não literal na tela.\r\n */\r\n branchLabel: string;\r\n\r\n /** Para onde mandar quem termina um fluxo que não abre sessão (reset, convite aceito). */\r\n loginPath: string;\r\n}\r\n\r\nexport const ORECHIO_ACCOUNT_CONFIG = new InjectionToken<OrechioAccountConfig>(\r\n 'ORECHIO_ACCOUNT_CONFIG',\r\n);\r\n\r\nexport interface OrechioAccountOptions {\r\n basePath?: string;\r\n paths?: OrechioAccountPaths;\r\n onCompleted: OrechioAccountConfig['onCompleted'];\r\n branchLabel?: string;\r\n loginPath?: string;\r\n}\r\n\r\nexport function provideOrechioAccount(options: OrechioAccountOptions): Provider[] {\r\n if (typeof options?.onCompleted !== 'function') {\r\n // Falha na composição, não no primeiro cliente que termina o cadastro. Sem\r\n // `onCompleted` o pacote não teria para onde mandar ninguém, e o sintoma apareceria\r\n // exatamente no pior momento: com o usuário já cadastrado, olhando uma tela parada.\r\n throw new Error(\r\n 'provideOrechioAccount: `onCompleted` é obrigatório — é o host que decide a navegação.',\r\n );\r\n }\r\n\r\n const basePath = (options.basePath ?? '/api/account').replace(/\\/+$/, '');\r\n\r\n const config: OrechioAccountConfig = {\r\n basePath,\r\n paths: {\r\n verifyEmail: options.paths?.verifyEmail ?? '/verify-email',\r\n initialBranch: options.paths?.initialBranch ?? '/onboarding/branch',\r\n forgotPassword: options.paths?.forgotPassword ?? '/forgot-password',\r\n resetPassword: options.paths?.resetPassword ?? '/reset-password',\r\n acceptInvite: options.paths?.acceptInvite ?? '/accept-invite',\r\n resendVerification: options.paths?.resendVerification ?? '/resend-verification',\r\n },\r\n onCompleted: options.onCompleted,\r\n branchLabel: options.branchLabel ?? 'unidade',\r\n loginPath: options.loginPath ?? '/login',\r\n };\r\n\r\n return [\r\n { provide: ORECHIO_ACCOUNT_CONFIG, useValue: config },\r\n // PROV-1: liga o desvio da sessão de provisionamento para a tela de primeira filial. Fica\r\n // aqui, e não num guard ou callback do host, para o produto só precisar atualizar a versão.\r\n // `ENVIRONMENT_INITIALIZER` (e não `provideEnvironmentInitializer`) para o retorno continuar\r\n // `Provider[]`: um `EnvironmentProviders` aqui quebraria quem usa o resultado em\r\n // `providers` de componente ou o tipa como `Provider[]`.\r\n {\r\n provide: ENVIRONMENT_INITIALIZER,\r\n multi: true,\r\n useValue: () => inject(ProvisioningRedirect).start(),\r\n },\r\n ];\r\n}\r\n","import { Routes } from '@angular/router';\r\n\r\n/**\r\n * As rotas de conta, para o host registrar ONDE ELE QUISER.\r\n *\r\n * <p>\r\n * São `Routes[]` e não um módulo com prefixo fixo de propósito: o produto monta em\r\n * `/conta`, em `/auth`, na raiz, ou espalhadas — o pacote não reivindica caminho. O que ele\r\n * fixa são os caminhos RELATIVOS entre elas, porque o `verify-email` navega para\r\n * `../onboarding/branch` quando há provisioning pendente.\r\n * </p>\r\n *\r\n * <pre>\r\n * // no host:\r\n * { path: 'conta', children: ORECHIO_ACCOUNT_ROUTES }\r\n * </pre>\r\n *\r\n * <p>\r\n * Todas com `loadComponent`: quem só usa recuperação de senha não carrega a tela de\r\n * primeira filial, e o bundle inicial do produto não paga por telas que a maioria dos\r\n * usuários vê uma vez na vida.\r\n * </p>\r\n */\r\nexport const ORECHIO_ACCOUNT_ROUTES: Routes = [\r\n {\r\n path: 'verify-email',\r\n title: 'Confirmando e-mail',\r\n loadComponent: () => import('./pages/verify-email.page').then((m) => m.VerifyEmailPage),\r\n },\r\n {\r\n path: 'onboarding/branch',\r\n title: 'Primeira unidade',\r\n loadComponent: () => import('./pages/initial-branch.page').then((m) => m.InitialBranchPage),\r\n },\r\n {\r\n path: 'forgot-password',\r\n title: 'Recuperar acesso',\r\n loadComponent: () => import('./pages/forgot-password.page').then((m) => m.ForgotPasswordPage),\r\n },\r\n {\r\n path: 'reset-password',\r\n title: 'Nova senha',\r\n loadComponent: () => import('./pages/token-password.page').then((m) => m.TokenPasswordPage),\r\n // `reset` também é o default do componente; declarado aqui para a rota dizer o que faz\r\n // sem exigir que se leia a implementação.\r\n data: { modo: 'reset' },\r\n },\r\n {\r\n path: 'accept-invite',\r\n title: 'Primeiro acesso',\r\n loadComponent: () => import('./pages/token-password.page').then((m) => m.TokenPasswordPage),\r\n data: { modo: 'invite' },\r\n },\r\n {\r\n path: 'resend-verification',\r\n title: 'Reenviar confirmação',\r\n loadComponent: () =>\r\n import('./pages/resend-verification.page').then((m) => m.ResendVerificationPage),\r\n },\r\n];\r\n","/*\r\n * Public API Surface of @orechio/platform-angular/account\r\n *\r\n * ACCOUNT-1C — o entry de conta. Ele traz as TELAS do onboarding compartilhado; a sessão,\r\n * o login e os interceptors continuam no entry primário, onde já estavam (ADR-019 §5.1:\r\n * login/refresh/logout são KEEP-SEPARATE — Store e Portal resolvem sessão de formas\r\n * materialmente diferentes).\r\n *\r\n * O que NÃO é exportado é parte do contrato: `AccountClient` é detalhe de implementação, e\r\n * as páginas são alcançadas por `ORECHIO_ACCOUNT_ROUTES`, nunca importadas diretamente —\r\n * exportá-las convidaria o host a montar a própria árvore de rotas por cima delas, e os\r\n * caminhos relativos entre as telas deixariam de valer.\r\n */\r\n\r\nexport type {\r\n AccountCompletionResult,\r\n OrechioAccountConfig,\r\n OrechioAccountOptions,\r\n OrechioAccountPaths,\r\n} from './account-config';\r\nexport { ORECHIO_ACCOUNT_CONFIG, provideOrechioAccount } from './account-config';\r\n\r\nexport { ORECHIO_ACCOUNT_ROUTES } from './account.routes';\r\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;AAIA;AACA,MAAM,gBAAgB,GAAG,mBAAmB;AAE5C;;;;;;;;;;;;;;;;;;;;;;AAsBG;MAEU,oBAAoB,CAAA;AACd,IAAA,OAAO,GAAG,MAAM,CAAC,YAAY,CAAC;AAC9B,IAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;AACvB,IAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;IAEpC,QAAQ,GAAG,KAAK;IAExB,KAAK,GAAA;QACH,IAAI,IAAI,CAAC,QAAQ;YAAE;AACnB,QAAA,IAAI,CAAC,QAAQ,GAAG,IAAI;QAEpB,MAAM,CACJ,MAAK;YACH,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,oBAAoB,KAAK,IAAI;gBAAE;YACxD,SAAS,CAAC,MAAM,KAAK,IAAI,CAAC,qBAAqB,EAAE,CAAC;QACpD,CAAC,EACD,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAC5B;IACH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a,EAAE,MAAM,OAAO,qEAA6B,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,iBAAiB,CAAC;AAC3F,QAAA,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,KAAA;AACD,IAAA;AACE,QAAA,IAAI,EAAE,qBAAqB;AAC3B,QAAA,KAAK,EAAE,sBAAsB;AAC7B,QAAA,aAAa,EAAE,MACb,OAAO,0EAAkC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,sBAAsB,CAAC;AACnF,KAAA;;;AC1DH;;;;;;;;;;;;AAYG;;ACZH;;AAEG;;;;"}
@@ -193,6 +193,9 @@ function normalizeEntries(raw) {
193
193
  .filter((branch) => branch !== null);
194
194
  }
195
195
 
196
+ function normalizeName(name) {
197
+ return (name ?? '').trim().toLowerCase();
198
+ }
196
199
  /**
197
200
  * Explicit branch picker for the multi-branch login step.
198
201
  *
@@ -249,7 +252,19 @@ class BranchSelector {
249
252
  * why the name is preferred whenever it exists.
250
253
  */
251
254
  label(branch, index) {
252
- return branch.name ? branch.name : `Filial ${index + 1}`;
255
+ return branch.name?.trim() ? branch.name : `Filial ${index + 1}`;
256
+ }
257
+ /**
258
+ * The fragment exists only to tell apart branches that would otherwise read the
259
+ * same, so it is rendered when another option carries the same name (trimmed,
260
+ * case-insensitive) — or when there is no name at all, where the positional
261
+ * "Filial N" fallback gives the user nothing else to go on.
262
+ */
263
+ showFragment(branch) {
264
+ const key = normalizeName(branch.name);
265
+ if (!key)
266
+ return true;
267
+ return this.branches().some((other) => other !== branch && normalizeName(other.name) === key);
253
268
  }
254
269
  /** Fragment of the id, shown beside the label to disambiguate repeated names. */
255
270
  fragment(branch) {
@@ -273,7 +288,9 @@ class BranchSelector {
273
288
  (change)="choose(branch.id)"
274
289
  />
275
290
  <span class="orechio-branch-selector__label">{{ label(branch, index) }}</span>
276
- <span class="orechio-branch-selector__hint">{{ fragment(branch) }}</span>
291
+ @if (showFragment(branch)) {
292
+ <span class="orechio-branch-selector__hint">{{ ' · ' + fragment(branch) }}</span>
293
+ }
277
294
  </label>
278
295
  }
279
296
 
@@ -287,14 +304,11 @@ class BranchSelector {
287
304
  </button>
288
305
  </fieldset>
289
306
  }
290
- `, isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush });
307
+ `, isInline: true, styles: [".orechio-branch-selector__option{display:flex;align-items:center;margin:.25rem 0}.orechio-branch-selector__option input[type=radio]{width:auto;height:auto;margin:0 .5rem 0 0}.orechio-branch-selector__hint{font-size:.85em;opacity:.7;white-space:pre}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush });
291
308
  }
292
309
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImport: i0, type: BranchSelector, decorators: [{
293
310
  type: Component,
294
- args: [{
295
- selector: 'orechio-branch-selector',
296
- changeDetection: ChangeDetectionStrategy.OnPush,
297
- template: `
311
+ args: [{ selector: 'orechio-branch-selector', changeDetection: ChangeDetectionStrategy.OnPush, template: `
298
312
  @if (branches().length === 0) {
299
313
  <p class="orechio-branch-selector__empty" role="status">{{ emptyLabel() }}</p>
300
314
  } @else {
@@ -311,7 +325,9 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImpor
311
325
  (change)="choose(branch.id)"
312
326
  />
313
327
  <span class="orechio-branch-selector__label">{{ label(branch, index) }}</span>
314
- <span class="orechio-branch-selector__hint">{{ fragment(branch) }}</span>
328
+ @if (showFragment(branch)) {
329
+ <span class="orechio-branch-selector__hint">{{ ' · ' + fragment(branch) }}</span>
330
+ }
315
331
  </label>
316
332
  }
317
333
 
@@ -325,8 +341,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.2", ngImpor
325
341
  </button>
326
342
  </fieldset>
327
343
  }
328
- `,
329
- }]
344
+ `, styles: [".orechio-branch-selector__option{display:flex;align-items:center;margin:.25rem 0}.orechio-branch-selector__option input[type=radio]{width:auto;height:auto;margin:0 .5rem 0 0}.orechio-branch-selector__hint{font-size:.85em;opacity:.7;white-space:pre}\n"] }]
330
345
  }], propDecorators: { branches: [{ type: i0.Input, args: [{ isSignal: true, alias: "branches", required: true }] }], busy: [{ type: i0.Input, args: [{ isSignal: true, alias: "busy", required: false }] }], legend: [{ type: i0.Input, args: [{ isSignal: true, alias: "legend", required: false }] }], confirmLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "confirmLabel", required: false }] }], emptyLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "emptyLabel", required: false }] }], selected: [{ type: i0.Output, args: ["selected"] }] } });
331
346
 
332
347
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"orechio-platform-angular.mjs","sources":["../../../projects/platform-angular/src/lib/config/platform-angular-config.ts","../../../projects/platform-angular/src/lib/session/session-store.ts","../../../projects/platform-angular/src/lib/auth/auth-client.ts","../../../projects/platform-angular/src/lib/auth/branch-selection.model.ts","../../../projects/platform-angular/src/lib/auth/branch-selector.ts","../../../projects/platform-angular/src/lib/auth/refresh-coordinator.ts","../../../projects/platform-angular/src/lib/http/provide-platform-angular-http.ts","../../../projects/platform-angular/src/lib/capabilities/capability.model.ts","../../../projects/platform-angular/src/lib/capabilities/capability.directive.ts","../../../projects/platform-angular/src/lib/problem-details/problem-details.model.ts","../../../projects/platform-angular/src/public-api.ts","../../../projects/platform-angular/src/orechio-platform-angular.ts"],"sourcesContent":["import { InjectionToken, Provider } from '@angular/core';\r\n\r\n/**\r\n * BFF endpoint paths for the auth contract. All paths are relative to `apiBaseUrl`.\r\n * `me` is optional: some BFFs bootstrap the session via `refresh` alone (no dedicated\r\n * session-read endpoint) instead of a separate `me` call.\r\n */\r\nexport interface PlatformAngularAuthPaths {\r\n login: string;\r\n refresh: string;\r\n logout: string;\r\n me?: string;\r\n /**\r\n * Branch switch for an already-authenticated session. Optional: only BFFs that\r\n * expose an authenticated switch endpoint set it, and `AuthClient.selectBranch`\r\n * fails fast when it is absent rather than guessing a URL.\r\n */\r\n selectBranch?: string;\r\n /**\r\n * Unwraps the raw auth-endpoint response body into TUser. Defaults to the\r\n * identity function (response body IS the user object), matching Store's\r\n * proven wire format. Portal's BFF wraps the user in an envelope\r\n * (`{ user: UserInfo }`) — Portal supplies `(body) => body.user` here\r\n * rather than the package assuming either shape.\r\n */\r\n unwrapUser?: (body: unknown) => unknown;\r\n}\r\n\r\nexport interface PlatformAngularConfig {\r\n /** Same-origin API base path, e.g. '/api'. Never an absolute cross-origin URL — the\r\n * BFF/cookie-session pattern this library assumes requires same-origin requests. */\r\n apiBaseUrl: string;\r\n auth: PlatformAngularAuthPaths;\r\n /** XSRF cookie/header names. Defaults match Angular's own defaults and both proven\r\n * consumers (Portal, Store): cookie 'XSRF-TOKEN', header 'X-XSRF-TOKEN'. */\r\n xsrf?: {\r\n cookieName?: string;\r\n headerName?: string;\r\n };\r\n /** 401 handling strategy. 'redirect' clears the session and redirects immediately\r\n * (Store's proven behavior). 'refresh-then-redirect' attempts one silent refresh\r\n * before giving up (Portal's proven behavior). Defaults to 'redirect' — the simpler,\r\n * more conservative behavior — when omitted. */\r\n unauthorizedStrategy?: 'redirect' | 'refresh-then-redirect';\r\n /** Route to navigate to after a session is cleared. Defaults to '/login'. */\r\n loginRoute?: string;\r\n}\r\n\r\nexport const PLATFORM_ANGULAR_CONFIG = new InjectionToken<PlatformAngularConfig>(\r\n 'PLATFORM_ANGULAR_CONFIG',\r\n);\r\n\r\nexport function providePlatformAngularConfig(config: PlatformAngularConfig): Provider {\r\n return { provide: PLATFORM_ANGULAR_CONFIG, useValue: config };\r\n}\r\n","import { Injectable, Signal, computed, signal } from '@angular/core';\nimport { SessionUser } from './session-user.model';\n\n/**\n * Generic signal-based session store. Mirrors the pattern already proven\n * independently by both consumers (Portal's AuthService.user, Store's\n * EstadoDaSessao) — deliberately NOT a richer state machine (unknown /\n * loading / error states): neither consumer needed one, and ADR-010 §2.2\n * (\"projete para extração, não extraia por antecipação\") argues against\n * building one speculatively.\n *\n * Parameterized over TUser so each product can extend SessionUser with its\n * own fields without needing a package release.\n */\n@Injectable({ providedIn: 'root' })\nexport class SessionStore<TUser extends SessionUser = SessionUser> {\n private readonly state = signal<TUser | null>(null);\n\n readonly user: Signal<TUser | null> = this.state.asReadonly();\n readonly isAuthenticated: Signal<boolean> = computed(() => this.state() !== null);\n\n set(user: TUser): void {\n this.state.set(user);\n }\n\n clear(): void {\n this.state.set(null);\n }\n}\n","import { HttpClient } from '@angular/common/http';\r\nimport { Injectable, inject } from '@angular/core';\r\nimport { Observable, finalize, map, tap, throwError } from 'rxjs';\r\nimport { PLATFORM_ANGULAR_CONFIG } from '../config/platform-angular-config';\r\nimport { SessionStore } from '../session/session-store';\r\nimport { SessionUser } from '../session/session-user.model';\r\n\r\n/**\r\n * Thin BFF client for the auth contract: login / refresh / logout, and an\r\n * optional session-read (\"me\") endpoint. Deliberately does NOT decode JWTs,\r\n * store bearer tokens, or treat itself as a security authority — per\r\n * ADR-010 §12 and this package's explicit non-goal (no JWT client SDK): the\r\n * BFF/backend is the only place tokens live, this class only reflects\r\n * whatever session-shaped JSON the BFF hands back.\r\n *\r\n * Endpoint paths are entirely config-driven (PLATFORM_ANGULAR_CONFIG) — this\r\n * class contains zero hardcoded URLs, so it works unmodified against\r\n * Portal's /api/auth/{login,me,refresh,logout} (envelope-wrapped\r\n * `{ user: UserInfo }` responses, unwrapped via config.auth.unwrapUser) and\r\n * the cookie-session hosts' /api/auth/{login,session,refresh,logout,select-branch}\r\n * (unwrapped responses; `session` is configured as `me`) alike. Those hosts are\r\n * Store, Moveis and any host mounting Orechio.Platform.Bff.Account 0.3.0\r\n * (ADR-022), which serves exactly this contract.\r\n */\r\n@Injectable({ providedIn: 'root' })\r\nexport class AuthClient<TUser extends SessionUser = SessionUser> {\r\n private readonly http = inject(HttpClient);\r\n private readonly config = inject(PLATFORM_ANGULAR_CONFIG);\r\n private readonly session = inject(SessionStore) as SessionStore<TUser>;\r\n\r\n private url(path: string): string {\r\n return `${this.config.apiBaseUrl}${path}`;\r\n }\r\n\r\n private unwrap(body: unknown): TUser {\r\n const unwrapUser = this.config.auth.unwrapUser;\r\n return (unwrapUser ? unwrapUser(body) : body) as TUser;\r\n }\r\n\r\n login(credentials: unknown): Observable<TUser> {\r\n return this.http.post<unknown>(this.url(this.config.auth.login), credentials).pipe(\r\n map((body) => this.unwrap(body)),\r\n tap((user) => this.session.set(user)),\r\n );\r\n }\r\n\r\n /**\r\n * Reads the current session. Uses the configured `me` endpoint (GET) when\r\n * present (Portal; Store and Moveis via `/api/auth/session`; and the\r\n * Orechio.Platform.Bff.Account 0.3.0 session routes, ADR-022) — a read that\r\n * neither rotates the session nor its cookies. Falls back to `refresh` (POST)\r\n * only for a host that configures no `me`, which then bootstraps via refresh.\r\n */\r\n initSession(): Observable<TUser> {\r\n if (this.config.auth.me) {\r\n return this.http.get<unknown>(this.url(this.config.auth.me)).pipe(\r\n map((body) => this.unwrap(body)),\r\n tap((user) => this.session.set(user)),\r\n );\r\n }\r\n return this.refresh();\r\n }\r\n\r\n /**\r\n * Asks the BFF to make `branchId` the current branch of the session that is\r\n * already authenticated. No credentials are involved and none are re-sent: the\r\n * browser proves nothing here beyond the session it already holds.\r\n *\r\n * `branchId` is a **requested target, never an authorization**. The BFF forwards\r\n * it to the Platform, which re-reads the user's grants and refuses what is not\r\n * granted — a rejection arrives as a failed request, and the session store is\r\n * left exactly as it was, still on the previous branch.\r\n *\r\n * The store is updated only from the session the server returns, never\r\n * optimistically from the requested id: the whole point of an explicit switch is\r\n * that the server, not the client, decides which branch the user ends up in.\r\n */\r\n selectBranch(branchId: string): Observable<TUser> {\r\n const path = this.config.auth.selectBranch;\r\n if (!path) {\r\n return throwError(\r\n () =>\r\n new Error(\r\n 'AuthClient.selectBranch requires config.auth.selectBranch. Configure the ' +\r\n 'BFF path that performs an authenticated branch switch.',\r\n ),\r\n );\r\n }\r\n\r\n return this.http.post<unknown>(this.url(path), { branchId }).pipe(\r\n map((body) => this.unwrap(body)),\r\n tap((user) => this.session.set(user)),\r\n );\r\n }\r\n\r\n refresh(): Observable<TUser> {\r\n return this.http.post<unknown>(this.url(this.config.auth.refresh), {}).pipe(\r\n map((body) => this.unwrap(body)),\r\n tap((user) => this.session.set(user)),\r\n );\r\n }\r\n\r\n /**\r\n * Clears the local session unconditionally — on success, on error, and on\r\n * unsubscribe (`finalize`, not `tap`) — matching the behavior both\r\n * consumers already converged on independently (Portal swallows the\r\n * error before clearing; Store clears via `finalize` while still letting\r\n * the error propagate). This does NOT swallow errors: callers that want\r\n * Portal's \"always succeed\" UX compose their own `catchError` on top.\r\n */\r\n logout(): Observable<void> {\r\n return this.http\r\n .post<void>(this.url(this.config.auth.logout), {})\r\n .pipe(finalize(() => this.session.clear()));\r\n }\r\n}\r\n","import { HttpErrorResponse } from '@angular/common/http';\r\n\r\n/**\r\n * Control-flow code the Platform's auth contract returns (HTTP 409) when the\r\n * authenticated user has access to more than one branch and none was chosen.\r\n *\r\n * It is deliberately NOT a failure: no session is created, no cookie is set,\r\n * and the caller is expected to ask the user which branch to enter. Treating\r\n * it as a generic error is the bug this constant exists to prevent.\r\n */\r\nexport const BRANCH_SELECTION_REQUIRED_CODE = 'auth.branch_selection_required';\r\n\r\n/**\r\n * One selectable branch.\r\n *\r\n * `name` is optional because the current backend contract carries branch ids\r\n * only — see `readBranchSelectionRequired`. Modelling it as optional now means\r\n * the day the backend starts sending names, consumers get them without a\r\n * breaking change to this type.\r\n */\r\nexport interface BranchOption {\r\n readonly id: string;\r\n readonly name?: string | null;\r\n}\r\n\r\n/** Payload of a branch-selection-required response, normalized. */\r\nexport interface BranchSelectionRequired {\r\n readonly branches: readonly BranchOption[];\r\n}\r\n\r\n/**\r\n * Recognizes a branch-selection-required response and normalizes its payload,\r\n * or returns `null` for anything else — so callers branch on a value instead of\r\n * re-deriving the contract from status codes and body shapes.\r\n *\r\n * Reads three wire shapes, in this order of preference:\r\n *\r\n * 1. `branchOptions: [{ id, name }]` — the display metadata the Platform sends\r\n * alongside the ids. Preferred when present, because it is the only shape\r\n * that lets an operator tell the branches apart.\r\n * 2. `branches: [\"<guid>\"]` — the original contract. Still authoritative for\r\n * selection, and still enough on its own.\r\n * 3. `branches: [{ id, name }]` — tolerated since 0.3.0.\r\n *\r\n * Reading all three is what makes the rollout order irrelevant: a frontend on\r\n * this version works against a backend that has the metadata and against one\r\n * that does not, and neither side has to ship first.\r\n *\r\n * Entries without a usable id are dropped rather than rendered as blanks: an\r\n * unselectable option in a selection list is worse than a shorter list.\r\n */\r\nexport function readBranchSelectionRequired(error: unknown): BranchSelectionRequired | null {\r\n if (!(error instanceof HttpErrorResponse) || error.status !== 409) return null;\r\n\r\n const body = error.error as\r\n | { code?: unknown; branches?: unknown; branchOptions?: unknown }\r\n | null;\r\n if (!body || body.code !== BRANCH_SELECTION_REQUIRED_CODE) return null;\r\n\r\n // `branchOptions` só substitui os ids quando traz alguma opção utilizável —\r\n // uma lista vazia ou ilegível não pode apagar a lista de ids que funciona.\r\n const comMetadata = normalizeEntries(body.branchOptions);\r\n if (comMetadata.length > 0) return { branches: comMetadata };\r\n\r\n if (!Array.isArray(body.branches)) return null;\r\n return { branches: normalizeEntries(body.branches) };\r\n}\r\n\r\nfunction normalizeEntries(raw: unknown): BranchOption[] {\r\n if (!Array.isArray(raw)) return [];\r\n\r\n return raw\r\n .map((entry): BranchOption | null => {\r\n if (typeof entry === 'string') return entry ? { id: entry } : null;\r\n if (entry && typeof entry === 'object') {\r\n const { id, name } = entry as { id?: unknown; name?: unknown };\r\n if (typeof id === 'string' && id) {\r\n return { id, name: typeof name === 'string' ? name : null };\r\n }\r\n }\r\n return null;\r\n })\r\n .filter((branch): branch is BranchOption => branch !== null);\r\n}\r\n","import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';\r\nimport { BranchOption } from './branch-selection.model';\r\n\r\n/**\r\n * Explicit branch picker for the multi-branch login step.\r\n *\r\n * Deliberately narrow: it receives options, renders them, and emits the id the\r\n * user actually chose. It does not call any backend, hold credentials, read\r\n * tokens, touch storage, or know which product it is rendering inside — the\r\n * flow around it belongs to the consumer, and the copy around it belongs to the\r\n * consumer's login page.\r\n *\r\n * **It never picks for the user.** When the backend answers\r\n * `auth.branch_selection_required` it has already refused to choose (no session\r\n * is created); a selector that quietly defaulted to the first option would put\r\n * the arbitrary choice back one layer up, in the place hardest to notice.\r\n *\r\n * Rendered as a radio group so the browser gives keyboard navigation, focus\r\n * management, and screen-reader semantics for free — a list of buttons would\r\n * need all three re-implemented, worse.\r\n */\r\n@Component({\r\n selector: 'orechio-branch-selector',\r\n changeDetection: ChangeDetectionStrategy.OnPush,\r\n template: `\r\n @if (branches().length === 0) {\r\n <p class=\"orechio-branch-selector__empty\" role=\"status\">{{ emptyLabel() }}</p>\r\n } @else {\r\n <fieldset class=\"orechio-branch-selector\" [disabled]=\"busy()\">\r\n <legend>{{ legend() }}</legend>\r\n\r\n @for (branch of branches(); track branch.id; let index = $index) {\r\n <label class=\"orechio-branch-selector__option\">\r\n <input\r\n type=\"radio\"\r\n name=\"orechio-branch\"\r\n [value]=\"branch.id\"\r\n [checked]=\"chosen === branch.id\"\r\n (change)=\"choose(branch.id)\"\r\n />\r\n <span class=\"orechio-branch-selector__label\">{{ label(branch, index) }}</span>\r\n <span class=\"orechio-branch-selector__hint\">{{ fragment(branch) }}</span>\r\n </label>\r\n }\r\n\r\n <button\r\n type=\"button\"\r\n class=\"orechio-branch-selector__confirm\"\r\n [disabled]=\"!chosen || busy()\"\r\n (click)=\"confirm()\"\r\n >\r\n {{ confirmLabel() }}\r\n </button>\r\n </fieldset>\r\n }\r\n `,\r\n})\r\nexport class BranchSelector {\r\n /** Options to choose from. An empty list renders the empty state, never a silent no-op. */\r\n readonly branches = input.required<readonly BranchOption[]>();\r\n\r\n /** Blocks input while the consumer is completing the sign-in round-trip. */\r\n readonly busy = input(false);\r\n\r\n // Copy is injectable because wording belongs to the product, not to the\r\n // platform package — the defaults exist so a consumer can drop the component\r\n // in and iterate on the words later.\r\n readonly legend = input('Selecione a filial');\r\n readonly confirmLabel = input('Continuar');\r\n readonly emptyLabel = input('Nenhuma filial disponível para este usuário.');\r\n\r\n /** Emits only in response to a user action. */\r\n readonly selected = output<string>();\r\n\r\n protected chosen: string | null = null;\r\n\r\n protected choose(id: string): void {\r\n this.chosen = id;\r\n }\r\n\r\n protected confirm(): void {\r\n if (this.chosen) this.selected.emit(this.chosen);\r\n }\r\n\r\n /**\r\n * The name is the label whenever the contract carries one. The id fragment stays\r\n * as secondary text rather than disappearing: the domain allows two branches to\r\n * share a name, and when that happens the fragment is the only thing telling\r\n * them apart.\r\n *\r\n * Without a name — an older backend, or metadata the server could not compose —\r\n * the positional fallback keeps the list selectable. Two raw identifiers side by\r\n * side are technically a choice and practically a coin flip, which is exactly\r\n * why the name is preferred whenever it exists.\r\n */\r\n protected label(branch: BranchOption, index: number): string {\r\n return branch.name ? branch.name : `Filial ${index + 1}`;\r\n }\r\n\r\n /** Fragment of the id, shown beside the label to disambiguate repeated names. */\r\n protected fragment(branch: BranchOption): string {\r\n return branch.id.slice(0, 8);\r\n }\r\n}\r\n","import { inject, Injectable } from '@angular/core';\r\nimport { Router } from '@angular/router';\r\nimport { Observable, ReplaySubject, catchError, finalize, share, throwError } from 'rxjs';\r\nimport { PLATFORM_ANGULAR_CONFIG } from '../config/platform-angular-config';\r\nimport { SessionStore } from '../session/session-store';\r\nimport { SessionUser } from '../session/session-user.model';\r\nimport { AuthClient } from './auth-client';\r\n\r\n/**\r\n * INTERNAL. Not exported from public-api.ts — consumers never construct or configure this\r\n * directly; it exists purely to back `sessionExpiryInterceptor`'s `'refresh-then-redirect'`\r\n * strategy (WEB-0.2, ADR-016 §\"WEB-0.2 note\").\r\n *\r\n * Deduplicates concurrent `AuthClient.refresh()` calls that originate from the SAME Angular\r\n * application context (one injector, i.e. one running app/tab). Before this existed, every\r\n * 401'd request independently called `authClient.refresh()`, and since that method returns a\r\n * cold Observable (`http.post(...)`, no multicasting), N simultaneous 401s produced N\r\n * independent `POST /refresh` calls — proven by the characterization test in\r\n * `provide-platform-angular-http.spec.ts`.\r\n *\r\n * This is defense-in-depth ONLY. The Platform already tolerates concurrent legitimate refresh\r\n * rotations correctly and safely (PLATFORM-REFRESH-1/1A/1B, ADR-016's retry leeway) — this class\r\n * exists to cut needless network traffic, cryptographic work, and rate-limit pressure on the\r\n * Platform, not to be the thing that makes concurrent refreshes safe. It does not, and does not\r\n * need to, coordinate across browser tabs/windows or other Angular application instances — see\r\n * the \"Multi-tab\" note on `sessionExpiryInterceptor` for why that's explicitly out of scope here\r\n * and handled server-side instead.\r\n */\r\n@Injectable({ providedIn: 'root' })\r\nexport class RefreshCoordinator {\r\n private readonly authClient = inject(AuthClient);\r\n private readonly session = inject(SessionStore);\r\n private readonly router = inject(Router);\r\n private readonly config = inject(PLATFORM_ANGULAR_CONFIG);\r\n\r\n private inFlight$: Observable<SessionUser> | null = null;\r\n\r\n /**\r\n * Returns the single in-flight refresh operation if one is already running, or starts a new\r\n * one. Every caller — first or piggybacking — gets the SAME underlying HTTP call's outcome.\r\n *\r\n * Semantics (WEB-0.2):\r\n * - Single-flight, not a permanent cache: once the shared operation settles (success or\r\n * error), the reference is cleared (`finalize`, placed BEFORE `share()` so it fires exactly\r\n * once per underlying HTTP call, not once per subscriber — see the `share()` config note\r\n * below). The next call to `refresh()` after that always starts a genuinely new request.\r\n * - On failure, the session is cleared and the browser is navigated to the login route\r\n * exactly once, regardless of how many callers are waiting — not once per waiting caller.\r\n * Each caller still receives its own error notification (multicast by `share()`) and is\r\n * responsible for propagating whatever error IT needs to its own subscriber (see\r\n * `sessionExpiryInterceptor`, which re-throws the ORIGINAL 401 to the request that\r\n * triggered it, not this refresh failure).\r\n * - `resetOnRefCountZero: false` is load-bearing: if one waiting caller unsubscribes (e.g. a\r\n * cancelled navigation), the still-in-flight HTTP request for the OTHER callers must not be\r\n * aborted. Angular's `HttpClient` cancels the underlying network request when its Observable\r\n * loses its last subscriber — without this flag, one caller going away could silently\r\n * cancel the refresh everyone else is still waiting on.\r\n * - `resetOnError`/`resetOnComplete` are left `false` too: this class never reuses a settled\r\n * `inFlight$` reference across cycles (the field is always nulled and rebuilt from scratch\r\n * by `finalize`), so `share()` itself never needs to reset its own internal connector.\r\n */\r\n refresh(): Observable<SessionUser> {\r\n if (this.inFlight$) {\r\n return this.inFlight$;\r\n }\r\n\r\n this.inFlight$ = this.authClient.refresh().pipe(\r\n catchError((error: unknown) => {\r\n this.session.clear();\r\n void this.router.navigateByUrl(this.config.loginRoute ?? '/login');\r\n return throwError(() => error);\r\n }),\r\n finalize(() => {\r\n this.inFlight$ = null;\r\n }),\r\n share({\r\n connector: () => new ReplaySubject<SessionUser>(1),\r\n resetOnError: false,\r\n resetOnComplete: false,\r\n resetOnRefCountZero: false,\r\n }),\r\n );\r\n\r\n return this.inFlight$;\r\n }\r\n}\r\n","import {\r\n HttpErrorResponse,\r\n HttpInterceptorFn,\r\n provideHttpClient,\r\n withInterceptors,\r\n withXsrfConfiguration,\r\n HttpFeature,\r\n HttpFeatureKind,\r\n} from '@angular/common/http';\r\nimport { inject } from '@angular/core';\r\nimport { Router } from '@angular/router';\r\nimport { catchError, switchMap, throwError } from 'rxjs';\r\nimport { PLATFORM_ANGULAR_CONFIG, PlatformAngularAuthPaths } from '../config/platform-angular-config';\r\nimport { RefreshCoordinator } from '../auth/refresh-coordinator';\r\nimport { SessionStore } from '../session/session-store';\r\n\r\nfunction isApiRequest(url: string, apiBaseUrl: string): boolean {\r\n return url === apiBaseUrl || url.startsWith(`${apiBaseUrl}/`);\r\n}\r\n\r\nfunction isAuthEndpoint(url: string, apiBaseUrl: string, auth: PlatformAngularAuthPaths): boolean {\r\n const authPaths = [auth.login, auth.refresh, auth.logout, auth.me].filter(\r\n (p): p is string => !!p,\r\n );\r\n return authPaths.some((p) => url === `${apiBaseUrl}${p}`);\r\n}\r\n\r\n/**\r\n * Forces `withCredentials: true` on same-origin API requests, so the BFF's\r\n * HttpOnly session cookie is sent. Proven identically in both consumers.\r\n * XSRF header injection is intentionally NOT duplicated here — Angular's\r\n * own `withXsrfConfiguration` (registered by `providePlatformAngularHttp`)\r\n * already does that. Portal's local interceptor previously re-implemented\r\n * XSRF header injection manually alongside `withXsrfConfiguration`; that\r\n * was redundant, not a pattern to preserve.\r\n */\r\nexport const credentialsInterceptor: HttpInterceptorFn = (req, next) => {\r\n const { apiBaseUrl } = inject(PLATFORM_ANGULAR_CONFIG);\r\n if (!isApiRequest(req.url, apiBaseUrl)) {\r\n return next(req);\r\n }\r\n return next(req.clone({ withCredentials: true }));\r\n};\r\n\r\n/**\r\n * On 401 from a non-auth API request: 'redirect' (default) clears the\r\n * session and navigates to the login route immediately (Store's proven\r\n * behavior). 'refresh-then-redirect' attempts one silent refresh first and\r\n * retries the original request on success, falling back to redirect\r\n * (Portal's proven behavior). Configured via\r\n * PlatformAngularConfig.unauthorizedStrategy.\r\n *\r\n * WEB-0.2: the 'refresh-then-redirect' path routes through `RefreshCoordinator`\r\n * instead of calling `AuthClient.refresh()` directly — every 401 handled by\r\n * the SAME running app shares one in-flight refresh instead of each request\r\n * triggering its own. The 'redirect' strategy is untouched: it never calls\r\n * refresh at all, so there is nothing to coordinate (see the config note on\r\n * `PlatformAngularConfig.unauthorizedStrategy`). On refresh failure, the\r\n * session-clear/navigate side effect now happens once inside the coordinator\r\n * (shared across every waiting caller) rather than once per waiting caller;\r\n * each caller still receives the ORIGINAL 401 error, not a refresh-specific\r\n * one, exactly as before. Multi-tab/multi-window coordination is explicitly\r\n * NOT handled here — see `RefreshCoordinator`'s doc comment — the Platform's\r\n * own server-side retry leeway (ADR-016) is what makes concurrent refreshes\r\n * from independent contexts safe.\r\n */\r\nexport const sessionExpiryInterceptor: HttpInterceptorFn = (req, next) => {\r\n const config = inject(PLATFORM_ANGULAR_CONFIG);\r\n const session = inject(SessionStore);\r\n const router = inject(Router);\r\n const refreshCoordinator = inject(RefreshCoordinator);\r\n\r\n if (\r\n !isApiRequest(req.url, config.apiBaseUrl) ||\r\n isAuthEndpoint(req.url, config.apiBaseUrl, config.auth)\r\n ) {\r\n return next(req);\r\n }\r\n\r\n return next(req).pipe(\r\n catchError((error: unknown) => {\r\n if (!(error instanceof HttpErrorResponse) || error.status !== 401) {\r\n return throwError(() => error);\r\n }\r\n\r\n if (config.unauthorizedStrategy !== 'refresh-then-redirect') {\r\n session.clear();\r\n void router.navigateByUrl(config.loginRoute ?? '/login');\r\n return throwError(() => error);\r\n }\r\n\r\n return refreshCoordinator.refresh().pipe(\r\n switchMap(() => next(req)),\r\n // The coordinator already cleared the session and navigated once for\r\n // this shared failure (see RefreshCoordinator.refresh()) — this\r\n // request still needs to fail with its OWN original 401, not the\r\n // refresh's error, exactly as before WEB-0.2.\r\n catchError(() => throwError(() => error)),\r\n );\r\n }),\r\n );\r\n};\r\n\r\n/**\r\n * Bundles provideHttpClient with the XSRF configuration and interceptors\r\n * proven necessary by both consumers. Cookie/header names default to\r\n * 'XSRF-TOKEN'/'X-XSRF-TOKEN' (identical in both consumers today) but\r\n * remain overridable via config. Consumers add their own extra\r\n * provideHttpClient features (e.g. Portal's withXhr()) by calling\r\n * provideHttpClient(...) separately — this function only owns the concerns\r\n * proven common to both.\r\n */\r\nexport function providePlatformAngularHttp(...extraFeatures: HttpFeature<HttpFeatureKind>[]) {\r\n return provideHttpClient(\r\n withXsrfConfiguration({\r\n cookieName: 'XSRF-TOKEN',\r\n headerName: 'X-XSRF-TOKEN',\r\n }),\r\n withInterceptors([credentialsInterceptor, sessionExpiryInterceptor]),\r\n ...extraFeatures,\r\n );\r\n}\r\n","/**\n * Generic capability map: a flat set of boolean feature flags fetched once\n * from the BFF (Portal's proven pattern — GET .../capabilities returning a\n * flat boolean-keyed object). Deliberately a generic `Record<string,\n * boolean>` rather than a typed interface enumerating every field: Portal's\n * capability set already has 17 product-specific fields and Store will\n * grow its own, unrelated set. A typed interface would require a package\n * release for every new product capability (see ADR-010 §18 — evolution\n * cadence mismatch is a real argument against sharing). Each product\n * defines its own capability keys locally and reads them through this map.\n *\n * UX ONLY. This does not replace server-side authorization. Every consumer\n * MUST continue to handle 403 from the actual mutating/reading endpoint —\n * capability checks here are a consultive pre-check, exactly as already\n * documented in Portal's application.service.ts before this extraction.\n */\nexport type CapabilityMap = Readonly<Record<string, boolean>>;\n\nexport function hasCapability(capabilities: CapabilityMap | null | undefined, key: string): boolean {\n return capabilities?.[key] === true;\n}\n","import { Directive, Input, TemplateRef, ViewContainerRef, inject } from '@angular/core';\nimport { CapabilityMap, hasCapability } from './capability.model';\n\n/**\n * Structural directive gating template content on a capability key from a\n * consumer-supplied CapabilityMap. Net-new (neither consumer had factored\n * their proven inline `@if (capabilities()?.x)` pattern into a directive),\n * but grounded in Portal's validated usage — see capability.model.ts.\n *\n * UX ONLY — see capability.model.ts. Hiding an element here does not\n * authorize anything; the backend re-validates on every mutating call.\n *\n * Usage: `<button *orxCapability=\"capabilities(); has: 'manageTenants'\">`\n */\n@Directive({\n selector: '[orxCapability]',\n standalone: true,\n})\nexport class CapabilityDirective {\n private readonly templateRef = inject(TemplateRef<unknown>);\n private readonly viewContainer = inject(ViewContainerRef);\n\n private map: CapabilityMap | null | undefined;\n private key: string | undefined;\n private hasView = false;\n\n @Input()\n set orxCapability(map: CapabilityMap | null | undefined) {\n this.map = map;\n this.render();\n }\n\n @Input('orxCapabilityHas')\n set has(key: string) {\n this.key = key;\n this.render();\n }\n\n private render(): void {\n const shouldShow = !!this.key && hasCapability(this.map, this.key);\n if (shouldShow && !this.hasView) {\n this.viewContainer.createEmbeddedView(this.templateRef);\n this.hasView = true;\n } else if (!shouldShow && this.hasView) {\n this.viewContainer.clear();\n this.hasView = false;\n }\n }\n}\n","import { HttpErrorResponse } from '@angular/common/http';\r\n\r\n/**\r\n * Canonical error shape, generalized from Store's already-proven\r\n * ErroApresentavel/normalizarErroApi (the more mature of the two consumers'\r\n * error handling — Portal had no typed contract at all, just five\r\n * duplicated `error.error.code` reads). `message` is optional: Portal never\r\n * received a server-supplied message field, only `code`, and resolves\r\n * user-facing text locally — so this contract cannot require it.\r\n *\r\n * `correlation_id` (API-1, ADR-017 §3.3): added after confirming directly\r\n * from Orechio.Platform's `ProblemResponses.cs` that it IS present in the\r\n * JSON body of every error response the Platform host produces (not just\r\n * the `X-Correlation-ID` response header), and that Portal's BFF relays\r\n * that body byte-for-byte, unreshaped, for every typed endpoint. The\r\n * earlier NG-1-era absence was accurate for what it tested at the time but\r\n * incomplete relative to Platform's actual wire contract. Optional: not\r\n * every error path in every consumer emits this field today (Store's own\r\n * narrower auth/CSRF error shapes don't) — its absence must not be treated\r\n * as a parse failure.\r\n *\r\n * Domain-specific error codes (e.g. 'access.platform_only',\r\n * 'tenant.not_found', 'csrf.invalid') are NOT enumerated here — `code`\r\n * stays a plain string so any code survives normalization unmodified and\r\n * remains identifiable by callers, per Passo 28.\r\n */\r\nexport interface ProblemDetails {\r\n code: string;\r\n message?: string;\r\n status: number;\r\n required?: string;\r\n correlationId?: string;\r\n}\r\n\r\n/**\r\n * Normalizes an HttpErrorResponse into ProblemDetails. Mirrors Store's\r\n * normalizarErroApi exactly, generalized to make `message` optional and to\r\n * accept an HttpErrorResponse without any consumer-specific fallback\r\n * message map (each product keeps its own code→message copy locally —\r\n * that's product-specific text, not shared infrastructure).\r\n */\r\nexport function normalizeProblemDetails(error: HttpErrorResponse): ProblemDetails {\r\n const body = error.error as Record<string, unknown> | null | undefined;\r\n const code = typeof body?.['code'] === 'string' ? (body['code'] as string) : `http.${error.status || 0}`;\r\n const message = typeof body?.['message'] === 'string' ? (body['message'] as string) : undefined;\r\n const required = typeof body?.['required'] === 'string' ? (body['required'] as string) : undefined;\r\n // Wire field is `correlation_id` (snake_case, ADR-017 §3) — kept as-is on the wire,\r\n // exposed as `correlationId` here per TS/Angular convention (same server-side pattern:\r\n // OrechioProblemDetails.CorrelationId is [JsonPropertyName(\"correlation_id\")]).\r\n const correlationId =\r\n typeof body?.['correlation_id'] === 'string' ? (body['correlation_id'] as string) : undefined;\r\n\r\n return {\r\n code,\r\n message,\r\n status: error.status,\r\n ...(required ? { required } : {}),\r\n ...(correlationId ? { correlationId } : {}),\r\n };\r\n}\r\n","/*\r\n * Public API Surface of @orechio/platform-angular\r\n */\r\n\r\nexport type { PlatformAngularConfig, PlatformAngularAuthPaths } from './lib/config/platform-angular-config';\r\nexport { PLATFORM_ANGULAR_CONFIG, providePlatformAngularConfig } from './lib/config/platform-angular-config';\r\n\r\nexport type { SessionUser } from './lib/session/session-user.model';\r\nexport { SessionStore } from './lib/session/session-store';\r\n\r\nexport { AuthClient } from './lib/auth/auth-client';\r\n\r\nexport type { BranchOption, BranchSelectionRequired } from './lib/auth/branch-selection.model';\r\nexport {\r\n BRANCH_SELECTION_REQUIRED_CODE,\r\n readBranchSelectionRequired,\r\n} from './lib/auth/branch-selection.model';\r\nexport { BranchSelector } from './lib/auth/branch-selector';\r\n\r\nexport { credentialsInterceptor, sessionExpiryInterceptor, providePlatformAngularHttp } from './lib/http/provide-platform-angular-http';\r\n\r\nexport type { CapabilityMap } from './lib/capabilities/capability.model';\r\nexport { hasCapability } from './lib/capabilities/capability.model';\r\nexport { CapabilityDirective } from './lib/capabilities/capability.directive';\r\n\r\nexport type { ProblemDetails } from './lib/problem-details/problem-details.model';\r\nexport { normalizeProblemDetails } from './lib/problem-details/problem-details.model';\r\n\r\nexport type { PagedResult } from './lib/pagination/paged-result.model';\r\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;MAgDa,uBAAuB,GAAG,IAAI,cAAc,CACvD,yBAAyB;AAGrB,SAAU,4BAA4B,CAAC,MAA6B,EAAA;IACxE,OAAO,EAAE,OAAO,EAAE,uBAAuB,EAAE,QAAQ,EAAE,MAAM,EAAE;AAC/D;;ACnDA;;;;;;;;;;AAUG;MAEU,YAAY,CAAA;IACN,KAAK,GAAG,MAAM,CAAe,IAAI;8EAAC;AAE1C,IAAA,IAAI,GAAyB,IAAI,CAAC,KAAK,CAA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":"orechio-platform-angular.mjs","sources":["../../../projects/platform-angular/src/lib/config/platform-angular-config.ts","../../../projects/platform-angular/src/lib/session/session-store.ts","../../../projects/platform-angular/src/lib/auth/auth-client.ts","../../../projects/platform-angular/src/lib/auth/branch-selection.model.ts","../../../projects/platform-angular/src/lib/auth/branch-selector.ts","../../../projects/platform-angular/src/lib/auth/refresh-coordinator.ts","../../../projects/platform-angular/src/lib/http/provide-platform-angular-http.ts","../../../projects/platform-angular/src/lib/capabilities/capability.model.ts","../../../projects/platform-angular/src/lib/capabilities/capability.directive.ts","../../../projects/platform-angular/src/lib/problem-details/problem-details.model.ts","../../../projects/platform-angular/src/public-api.ts","../../../projects/platform-angular/src/orechio-platform-angular.ts"],"sourcesContent":["import { InjectionToken, Provider } from '@angular/core';\r\n\r\n/**\r\n * BFF endpoint paths for the auth contract. All paths are relative to `apiBaseUrl`.\r\n * `me` is optional: some BFFs bootstrap the session via `refresh` alone (no dedicated\r\n * session-read endpoint) instead of a separate `me` call.\r\n */\r\nexport interface PlatformAngularAuthPaths {\r\n login: string;\r\n refresh: string;\r\n logout: string;\r\n me?: string;\r\n /**\r\n * Branch switch for an already-authenticated session. Optional: only BFFs that\r\n * expose an authenticated switch endpoint set it, and `AuthClient.selectBranch`\r\n * fails fast when it is absent rather than guessing a URL.\r\n */\r\n selectBranch?: string;\r\n /**\r\n * Unwraps the raw auth-endpoint response body into TUser. Defaults to the\r\n * identity function (response body IS the user object), matching Store's\r\n * proven wire format. Portal's BFF wraps the user in an envelope\r\n * (`{ user: UserInfo }`) — Portal supplies `(body) => body.user` here\r\n * rather than the package assuming either shape.\r\n */\r\n unwrapUser?: (body: unknown) => unknown;\r\n}\r\n\r\nexport interface PlatformAngularConfig {\r\n /** Same-origin API base path, e.g. '/api'. Never an absolute cross-origin URL — the\r\n * BFF/cookie-session pattern this library assumes requires same-origin requests. */\r\n apiBaseUrl: string;\r\n auth: PlatformAngularAuthPaths;\r\n /** XSRF cookie/header names. Defaults match Angular's own defaults and both proven\r\n * consumers (Portal, Store): cookie 'XSRF-TOKEN', header 'X-XSRF-TOKEN'. */\r\n xsrf?: {\r\n cookieName?: string;\r\n headerName?: string;\r\n };\r\n /** 401 handling strategy. 'redirect' clears the session and redirects immediately\r\n * (Store's proven behavior). 'refresh-then-redirect' attempts one silent refresh\r\n * before giving up (Portal's proven behavior). Defaults to 'redirect' — the simpler,\r\n * more conservative behavior — when omitted. */\r\n unauthorizedStrategy?: 'redirect' | 'refresh-then-redirect';\r\n /** Route to navigate to after a session is cleared. Defaults to '/login'. */\r\n loginRoute?: string;\r\n}\r\n\r\nexport const PLATFORM_ANGULAR_CONFIG = new InjectionToken<PlatformAngularConfig>(\r\n 'PLATFORM_ANGULAR_CONFIG',\r\n);\r\n\r\nexport function providePlatformAngularConfig(config: PlatformAngularConfig): Provider {\r\n return { provide: PLATFORM_ANGULAR_CONFIG, useValue: config };\r\n}\r\n","import { Injectable, Signal, computed, signal } from '@angular/core';\nimport { SessionUser } from './session-user.model';\n\n/**\n * Generic signal-based session store. Mirrors the pattern already proven\n * independently by both consumers (Portal's AuthService.user, Store's\n * EstadoDaSessao) — deliberately NOT a richer state machine (unknown /\n * loading / error states): neither consumer needed one, and ADR-010 §2.2\n * (\"projete para extração, não extraia por antecipação\") argues against\n * building one speculatively.\n *\n * Parameterized over TUser so each product can extend SessionUser with its\n * own fields without needing a package release.\n */\n@Injectable({ providedIn: 'root' })\nexport class SessionStore<TUser extends SessionUser = SessionUser> {\n private readonly state = signal<TUser | null>(null);\n\n readonly user: Signal<TUser | null> = this.state.asReadonly();\n readonly isAuthenticated: Signal<boolean> = computed(() => this.state() !== null);\n\n set(user: TUser): void {\n this.state.set(user);\n }\n\n clear(): void {\n this.state.set(null);\n }\n}\n","import { HttpClient } from '@angular/common/http';\r\nimport { Injectable, inject } from '@angular/core';\r\nimport { Observable, finalize, map, tap, throwError } from 'rxjs';\r\nimport { PLATFORM_ANGULAR_CONFIG } from '../config/platform-angular-config';\r\nimport { SessionStore } from '../session/session-store';\r\nimport { SessionUser } from '../session/session-user.model';\r\n\r\n/**\r\n * Thin BFF client for the auth contract: login / refresh / logout, and an\r\n * optional session-read (\"me\") endpoint. Deliberately does NOT decode JWTs,\r\n * store bearer tokens, or treat itself as a security authority — per\r\n * ADR-010 §12 and this package's explicit non-goal (no JWT client SDK): the\r\n * BFF/backend is the only place tokens live, this class only reflects\r\n * whatever session-shaped JSON the BFF hands back.\r\n *\r\n * Endpoint paths are entirely config-driven (PLATFORM_ANGULAR_CONFIG) — this\r\n * class contains zero hardcoded URLs, so it works unmodified against\r\n * Portal's /api/auth/{login,me,refresh,logout} (envelope-wrapped\r\n * `{ user: UserInfo }` responses, unwrapped via config.auth.unwrapUser) and\r\n * the cookie-session hosts' /api/auth/{login,session,refresh,logout,select-branch}\r\n * (unwrapped responses; `session` is configured as `me`) alike. Those hosts are\r\n * Store, Moveis and any host mounting Orechio.Platform.Bff.Account 0.3.0\r\n * (ADR-022), which serves exactly this contract.\r\n */\r\n@Injectable({ providedIn: 'root' })\r\nexport class AuthClient<TUser extends SessionUser = SessionUser> {\r\n private readonly http = inject(HttpClient);\r\n private readonly config = inject(PLATFORM_ANGULAR_CONFIG);\r\n private readonly session = inject(SessionStore) as SessionStore<TUser>;\r\n\r\n private url(path: string): string {\r\n return `${this.config.apiBaseUrl}${path}`;\r\n }\r\n\r\n private unwrap(body: unknown): TUser {\r\n const unwrapUser = this.config.auth.unwrapUser;\r\n return (unwrapUser ? unwrapUser(body) : body) as TUser;\r\n }\r\n\r\n login(credentials: unknown): Observable<TUser> {\r\n return this.http.post<unknown>(this.url(this.config.auth.login), credentials).pipe(\r\n map((body) => this.unwrap(body)),\r\n tap((user) => this.session.set(user)),\r\n );\r\n }\r\n\r\n /**\r\n * Reads the current session. Uses the configured `me` endpoint (GET) when\r\n * present (Portal; Store and Moveis via `/api/auth/session`; and the\r\n * Orechio.Platform.Bff.Account 0.3.0 session routes, ADR-022) — a read that\r\n * neither rotates the session nor its cookies. Falls back to `refresh` (POST)\r\n * only for a host that configures no `me`, which then bootstraps via refresh.\r\n */\r\n initSession(): Observable<TUser> {\r\n if (this.config.auth.me) {\r\n return this.http.get<unknown>(this.url(this.config.auth.me)).pipe(\r\n map((body) => this.unwrap(body)),\r\n tap((user) => this.session.set(user)),\r\n );\r\n }\r\n return this.refresh();\r\n }\r\n\r\n /**\r\n * Asks the BFF to make `branchId` the current branch of the session that is\r\n * already authenticated. No credentials are involved and none are re-sent: the\r\n * browser proves nothing here beyond the session it already holds.\r\n *\r\n * `branchId` is a **requested target, never an authorization**. The BFF forwards\r\n * it to the Platform, which re-reads the user's grants and refuses what is not\r\n * granted — a rejection arrives as a failed request, and the session store is\r\n * left exactly as it was, still on the previous branch.\r\n *\r\n * The store is updated only from the session the server returns, never\r\n * optimistically from the requested id: the whole point of an explicit switch is\r\n * that the server, not the client, decides which branch the user ends up in.\r\n */\r\n selectBranch(branchId: string): Observable<TUser> {\r\n const path = this.config.auth.selectBranch;\r\n if (!path) {\r\n return throwError(\r\n () =>\r\n new Error(\r\n 'AuthClient.selectBranch requires config.auth.selectBranch. Configure the ' +\r\n 'BFF path that performs an authenticated branch switch.',\r\n ),\r\n );\r\n }\r\n\r\n return this.http.post<unknown>(this.url(path), { branchId }).pipe(\r\n map((body) => this.unwrap(body)),\r\n tap((user) => this.session.set(user)),\r\n );\r\n }\r\n\r\n refresh(): Observable<TUser> {\r\n return this.http.post<unknown>(this.url(this.config.auth.refresh), {}).pipe(\r\n map((body) => this.unwrap(body)),\r\n tap((user) => this.session.set(user)),\r\n );\r\n }\r\n\r\n /**\r\n * Clears the local session unconditionally — on success, on error, and on\r\n * unsubscribe (`finalize`, not `tap`) — matching the behavior both\r\n * consumers already converged on independently (Portal swallows the\r\n * error before clearing; Store clears via `finalize` while still letting\r\n * the error propagate). This does NOT swallow errors: callers that want\r\n * Portal's \"always succeed\" UX compose their own `catchError` on top.\r\n */\r\n logout(): Observable<void> {\r\n return this.http\r\n .post<void>(this.url(this.config.auth.logout), {})\r\n .pipe(finalize(() => this.session.clear()));\r\n }\r\n}\r\n","import { HttpErrorResponse } from '@angular/common/http';\r\n\r\n/**\r\n * Control-flow code the Platform's auth contract returns (HTTP 409) when the\r\n * authenticated user has access to more than one branch and none was chosen.\r\n *\r\n * It is deliberately NOT a failure: no session is created, no cookie is set,\r\n * and the caller is expected to ask the user which branch to enter. Treating\r\n * it as a generic error is the bug this constant exists to prevent.\r\n */\r\nexport const BRANCH_SELECTION_REQUIRED_CODE = 'auth.branch_selection_required';\r\n\r\n/**\r\n * One selectable branch.\r\n *\r\n * `name` is optional because the current backend contract carries branch ids\r\n * only — see `readBranchSelectionRequired`. Modelling it as optional now means\r\n * the day the backend starts sending names, consumers get them without a\r\n * breaking change to this type.\r\n */\r\nexport interface BranchOption {\r\n readonly id: string;\r\n readonly name?: string | null;\r\n}\r\n\r\n/** Payload of a branch-selection-required response, normalized. */\r\nexport interface BranchSelectionRequired {\r\n readonly branches: readonly BranchOption[];\r\n}\r\n\r\n/**\r\n * Recognizes a branch-selection-required response and normalizes its payload,\r\n * or returns `null` for anything else — so callers branch on a value instead of\r\n * re-deriving the contract from status codes and body shapes.\r\n *\r\n * Reads three wire shapes, in this order of preference:\r\n *\r\n * 1. `branchOptions: [{ id, name }]` — the display metadata the Platform sends\r\n * alongside the ids. Preferred when present, because it is the only shape\r\n * that lets an operator tell the branches apart.\r\n * 2. `branches: [\"<guid>\"]` — the original contract. Still authoritative for\r\n * selection, and still enough on its own.\r\n * 3. `branches: [{ id, name }]` — tolerated since 0.3.0.\r\n *\r\n * Reading all three is what makes the rollout order irrelevant: a frontend on\r\n * this version works against a backend that has the metadata and against one\r\n * that does not, and neither side has to ship first.\r\n *\r\n * Entries without a usable id are dropped rather than rendered as blanks: an\r\n * unselectable option in a selection list is worse than a shorter list.\r\n */\r\nexport function readBranchSelectionRequired(error: unknown): BranchSelectionRequired | null {\r\n if (!(error instanceof HttpErrorResponse) || error.status !== 409) return null;\r\n\r\n const body = error.error as\r\n | { code?: unknown; branches?: unknown; branchOptions?: unknown }\r\n | null;\r\n if (!body || body.code !== BRANCH_SELECTION_REQUIRED_CODE) return null;\r\n\r\n // `branchOptions` só substitui os ids quando traz alguma opção utilizável —\r\n // uma lista vazia ou ilegível não pode apagar a lista de ids que funciona.\r\n const comMetadata = normalizeEntries(body.branchOptions);\r\n if (comMetadata.length > 0) return { branches: comMetadata };\r\n\r\n if (!Array.isArray(body.branches)) return null;\r\n return { branches: normalizeEntries(body.branches) };\r\n}\r\n\r\nfunction normalizeEntries(raw: unknown): BranchOption[] {\r\n if (!Array.isArray(raw)) return [];\r\n\r\n return raw\r\n .map((entry): BranchOption | null => {\r\n if (typeof entry === 'string') return entry ? { id: entry } : null;\r\n if (entry && typeof entry === 'object') {\r\n const { id, name } = entry as { id?: unknown; name?: unknown };\r\n if (typeof id === 'string' && id) {\r\n return { id, name: typeof name === 'string' ? name : null };\r\n }\r\n }\r\n return null;\r\n })\r\n .filter((branch): branch is BranchOption => branch !== null);\r\n}\r\n","import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';\r\nimport { BranchOption } from './branch-selection.model';\r\n\r\nfunction normalizeName(name: string | null | undefined): string {\r\n return (name ?? '').trim().toLowerCase();\r\n}\r\n\r\n/**\r\n * Explicit branch picker for the multi-branch login step.\r\n *\r\n * Deliberately narrow: it receives options, renders them, and emits the id the\r\n * user actually chose. It does not call any backend, hold credentials, read\r\n * tokens, touch storage, or know which product it is rendering inside — the\r\n * flow around it belongs to the consumer, and the copy around it belongs to the\r\n * consumer's login page.\r\n *\r\n * **It never picks for the user.** When the backend answers\r\n * `auth.branch_selection_required` it has already refused to choose (no session\r\n * is created); a selector that quietly defaulted to the first option would put\r\n * the arbitrary choice back one layer up, in the place hardest to notice.\r\n *\r\n * Rendered as a radio group so the browser gives keyboard navigation, focus\r\n * management, and screen-reader semantics for free — a list of buttons would\r\n * need all three re-implemented, worse.\r\n */\r\n@Component({\r\n selector: 'orechio-branch-selector',\r\n changeDetection: ChangeDetectionStrategy.OnPush,\r\n template: `\r\n @if (branches().length === 0) {\r\n <p class=\"orechio-branch-selector__empty\" role=\"status\">{{ emptyLabel() }}</p>\r\n } @else {\r\n <fieldset class=\"orechio-branch-selector\" [disabled]=\"busy()\">\r\n <legend>{{ legend() }}</legend>\r\n\r\n @for (branch of branches(); track branch.id; let index = $index) {\r\n <label class=\"orechio-branch-selector__option\">\r\n <input\r\n type=\"radio\"\r\n name=\"orechio-branch\"\r\n [value]=\"branch.id\"\r\n [checked]=\"chosen === branch.id\"\r\n (change)=\"choose(branch.id)\"\r\n />\r\n <span class=\"orechio-branch-selector__label\">{{ label(branch, index) }}</span>\r\n @if (showFragment(branch)) {\r\n <span class=\"orechio-branch-selector__hint\">{{ ' · ' + fragment(branch) }}</span>\r\n }\r\n </label>\r\n }\r\n\r\n <button\r\n type=\"button\"\r\n class=\"orechio-branch-selector__confirm\"\r\n [disabled]=\"!chosen || busy()\"\r\n (click)=\"confirm()\"\r\n >\r\n {{ confirmLabel() }}\r\n </button>\r\n </fieldset>\r\n }\r\n `,\r\n // Minimal layout only, no brand colour: the host's global CSS (e.g.\r\n // `input { width: 100% }`) must not be able to stretch the radios, and the host\r\n // can still override any of this.\r\n styles: `\r\n .orechio-branch-selector__option {\r\n display: flex;\r\n align-items: center;\r\n margin: 0.25rem 0;\r\n }\r\n\r\n .orechio-branch-selector__option input[type='radio'] {\r\n width: auto;\r\n height: auto;\r\n margin: 0 0.5rem 0 0;\r\n }\r\n\r\n .orechio-branch-selector__hint {\r\n font-size: 0.85em;\r\n opacity: 0.7;\r\n white-space: pre;\r\n }\r\n `,\r\n})\r\nexport class BranchSelector {\r\n /** Options to choose from. An empty list renders the empty state, never a silent no-op. */\r\n readonly branches = input.required<readonly BranchOption[]>();\r\n\r\n /** Blocks input while the consumer is completing the sign-in round-trip. */\r\n readonly busy = input(false);\r\n\r\n // Copy is injectable because wording belongs to the product, not to the\r\n // platform package — the defaults exist so a consumer can drop the component\r\n // in and iterate on the words later.\r\n readonly legend = input('Selecione a filial');\r\n readonly confirmLabel = input('Continuar');\r\n readonly emptyLabel = input('Nenhuma filial disponível para este usuário.');\r\n\r\n /** Emits only in response to a user action. */\r\n readonly selected = output<string>();\r\n\r\n protected chosen: string | null = null;\r\n\r\n protected choose(id: string): void {\r\n this.chosen = id;\r\n }\r\n\r\n protected confirm(): void {\r\n if (this.chosen) this.selected.emit(this.chosen);\r\n }\r\n\r\n /**\r\n * The name is the label whenever the contract carries one. The id fragment stays\r\n * as secondary text rather than disappearing: the domain allows two branches to\r\n * share a name, and when that happens the fragment is the only thing telling\r\n * them apart.\r\n *\r\n * Without a name — an older backend, or metadata the server could not compose —\r\n * the positional fallback keeps the list selectable. Two raw identifiers side by\r\n * side are technically a choice and practically a coin flip, which is exactly\r\n * why the name is preferred whenever it exists.\r\n */\r\n protected label(branch: BranchOption, index: number): string {\r\n return branch.name?.trim() ? branch.name : `Filial ${index + 1}`;\r\n }\r\n\r\n /**\r\n * The fragment exists only to tell apart branches that would otherwise read the\r\n * same, so it is rendered when another option carries the same name (trimmed,\r\n * case-insensitive) — or when there is no name at all, where the positional\r\n * \"Filial N\" fallback gives the user nothing else to go on.\r\n */\r\n protected showFragment(branch: BranchOption): boolean {\r\n const key = normalizeName(branch.name);\r\n if (!key) return true;\r\n return this.branches().some((other) => other !== branch && normalizeName(other.name) === key);\r\n }\r\n\r\n /** Fragment of the id, shown beside the label to disambiguate repeated names. */\r\n protected fragment(branch: BranchOption): string {\r\n return branch.id.slice(0, 8);\r\n }\r\n}\r\n","import { inject, Injectable } from '@angular/core';\r\nimport { Router } from '@angular/router';\r\nimport { Observable, ReplaySubject, catchError, finalize, share, throwError } from 'rxjs';\r\nimport { PLATFORM_ANGULAR_CONFIG } from '../config/platform-angular-config';\r\nimport { SessionStore } from '../session/session-store';\r\nimport { SessionUser } from '../session/session-user.model';\r\nimport { AuthClient } from './auth-client';\r\n\r\n/**\r\n * INTERNAL. Not exported from public-api.ts — consumers never construct or configure this\r\n * directly; it exists purely to back `sessionExpiryInterceptor`'s `'refresh-then-redirect'`\r\n * strategy (WEB-0.2, ADR-016 §\"WEB-0.2 note\").\r\n *\r\n * Deduplicates concurrent `AuthClient.refresh()` calls that originate from the SAME Angular\r\n * application context (one injector, i.e. one running app/tab). Before this existed, every\r\n * 401'd request independently called `authClient.refresh()`, and since that method returns a\r\n * cold Observable (`http.post(...)`, no multicasting), N simultaneous 401s produced N\r\n * independent `POST /refresh` calls — proven by the characterization test in\r\n * `provide-platform-angular-http.spec.ts`.\r\n *\r\n * This is defense-in-depth ONLY. The Platform already tolerates concurrent legitimate refresh\r\n * rotations correctly and safely (PLATFORM-REFRESH-1/1A/1B, ADR-016's retry leeway) — this class\r\n * exists to cut needless network traffic, cryptographic work, and rate-limit pressure on the\r\n * Platform, not to be the thing that makes concurrent refreshes safe. It does not, and does not\r\n * need to, coordinate across browser tabs/windows or other Angular application instances — see\r\n * the \"Multi-tab\" note on `sessionExpiryInterceptor` for why that's explicitly out of scope here\r\n * and handled server-side instead.\r\n */\r\n@Injectable({ providedIn: 'root' })\r\nexport class RefreshCoordinator {\r\n private readonly authClient = inject(AuthClient);\r\n private readonly session = inject(SessionStore);\r\n private readonly router = inject(Router);\r\n private readonly config = inject(PLATFORM_ANGULAR_CONFIG);\r\n\r\n private inFlight$: Observable<SessionUser> | null = null;\r\n\r\n /**\r\n * Returns the single in-flight refresh operation if one is already running, or starts a new\r\n * one. Every caller — first or piggybacking — gets the SAME underlying HTTP call's outcome.\r\n *\r\n * Semantics (WEB-0.2):\r\n * - Single-flight, not a permanent cache: once the shared operation settles (success or\r\n * error), the reference is cleared (`finalize`, placed BEFORE `share()` so it fires exactly\r\n * once per underlying HTTP call, not once per subscriber — see the `share()` config note\r\n * below). The next call to `refresh()` after that always starts a genuinely new request.\r\n * - On failure, the session is cleared and the browser is navigated to the login route\r\n * exactly once, regardless of how many callers are waiting — not once per waiting caller.\r\n * Each caller still receives its own error notification (multicast by `share()`) and is\r\n * responsible for propagating whatever error IT needs to its own subscriber (see\r\n * `sessionExpiryInterceptor`, which re-throws the ORIGINAL 401 to the request that\r\n * triggered it, not this refresh failure).\r\n * - `resetOnRefCountZero: false` is load-bearing: if one waiting caller unsubscribes (e.g. a\r\n * cancelled navigation), the still-in-flight HTTP request for the OTHER callers must not be\r\n * aborted. Angular's `HttpClient` cancels the underlying network request when its Observable\r\n * loses its last subscriber — without this flag, one caller going away could silently\r\n * cancel the refresh everyone else is still waiting on.\r\n * - `resetOnError`/`resetOnComplete` are left `false` too: this class never reuses a settled\r\n * `inFlight$` reference across cycles (the field is always nulled and rebuilt from scratch\r\n * by `finalize`), so `share()` itself never needs to reset its own internal connector.\r\n */\r\n refresh(): Observable<SessionUser> {\r\n if (this.inFlight$) {\r\n return this.inFlight$;\r\n }\r\n\r\n this.inFlight$ = this.authClient.refresh().pipe(\r\n catchError((error: unknown) => {\r\n this.session.clear();\r\n void this.router.navigateByUrl(this.config.loginRoute ?? '/login');\r\n return throwError(() => error);\r\n }),\r\n finalize(() => {\r\n this.inFlight$ = null;\r\n }),\r\n share({\r\n connector: () => new ReplaySubject<SessionUser>(1),\r\n resetOnError: false,\r\n resetOnComplete: false,\r\n resetOnRefCountZero: false,\r\n }),\r\n );\r\n\r\n return this.inFlight$;\r\n }\r\n}\r\n","import {\r\n HttpErrorResponse,\r\n HttpInterceptorFn,\r\n provideHttpClient,\r\n withInterceptors,\r\n withXsrfConfiguration,\r\n HttpFeature,\r\n HttpFeatureKind,\r\n} from '@angular/common/http';\r\nimport { inject } from '@angular/core';\r\nimport { Router } from '@angular/router';\r\nimport { catchError, switchMap, throwError } from 'rxjs';\r\nimport { PLATFORM_ANGULAR_CONFIG, PlatformAngularAuthPaths } from '../config/platform-angular-config';\r\nimport { RefreshCoordinator } from '../auth/refresh-coordinator';\r\nimport { SessionStore } from '../session/session-store';\r\n\r\nfunction isApiRequest(url: string, apiBaseUrl: string): boolean {\r\n return url === apiBaseUrl || url.startsWith(`${apiBaseUrl}/`);\r\n}\r\n\r\nfunction isAuthEndpoint(url: string, apiBaseUrl: string, auth: PlatformAngularAuthPaths): boolean {\r\n const authPaths = [auth.login, auth.refresh, auth.logout, auth.me].filter(\r\n (p): p is string => !!p,\r\n );\r\n return authPaths.some((p) => url === `${apiBaseUrl}${p}`);\r\n}\r\n\r\n/**\r\n * Forces `withCredentials: true` on same-origin API requests, so the BFF's\r\n * HttpOnly session cookie is sent. Proven identically in both consumers.\r\n * XSRF header injection is intentionally NOT duplicated here — Angular's\r\n * own `withXsrfConfiguration` (registered by `providePlatformAngularHttp`)\r\n * already does that. Portal's local interceptor previously re-implemented\r\n * XSRF header injection manually alongside `withXsrfConfiguration`; that\r\n * was redundant, not a pattern to preserve.\r\n */\r\nexport const credentialsInterceptor: HttpInterceptorFn = (req, next) => {\r\n const { apiBaseUrl } = inject(PLATFORM_ANGULAR_CONFIG);\r\n if (!isApiRequest(req.url, apiBaseUrl)) {\r\n return next(req);\r\n }\r\n return next(req.clone({ withCredentials: true }));\r\n};\r\n\r\n/**\r\n * On 401 from a non-auth API request: 'redirect' (default) clears the\r\n * session and navigates to the login route immediately (Store's proven\r\n * behavior). 'refresh-then-redirect' attempts one silent refresh first and\r\n * retries the original request on success, falling back to redirect\r\n * (Portal's proven behavior). Configured via\r\n * PlatformAngularConfig.unauthorizedStrategy.\r\n *\r\n * WEB-0.2: the 'refresh-then-redirect' path routes through `RefreshCoordinator`\r\n * instead of calling `AuthClient.refresh()` directly — every 401 handled by\r\n * the SAME running app shares one in-flight refresh instead of each request\r\n * triggering its own. The 'redirect' strategy is untouched: it never calls\r\n * refresh at all, so there is nothing to coordinate (see the config note on\r\n * `PlatformAngularConfig.unauthorizedStrategy`). On refresh failure, the\r\n * session-clear/navigate side effect now happens once inside the coordinator\r\n * (shared across every waiting caller) rather than once per waiting caller;\r\n * each caller still receives the ORIGINAL 401 error, not a refresh-specific\r\n * one, exactly as before. Multi-tab/multi-window coordination is explicitly\r\n * NOT handled here — see `RefreshCoordinator`'s doc comment — the Platform's\r\n * own server-side retry leeway (ADR-016) is what makes concurrent refreshes\r\n * from independent contexts safe.\r\n */\r\nexport const sessionExpiryInterceptor: HttpInterceptorFn = (req, next) => {\r\n const config = inject(PLATFORM_ANGULAR_CONFIG);\r\n const session = inject(SessionStore);\r\n const router = inject(Router);\r\n const refreshCoordinator = inject(RefreshCoordinator);\r\n\r\n if (\r\n !isApiRequest(req.url, config.apiBaseUrl) ||\r\n isAuthEndpoint(req.url, config.apiBaseUrl, config.auth)\r\n ) {\r\n return next(req);\r\n }\r\n\r\n return next(req).pipe(\r\n catchError((error: unknown) => {\r\n if (!(error instanceof HttpErrorResponse) || error.status !== 401) {\r\n return throwError(() => error);\r\n }\r\n\r\n if (config.unauthorizedStrategy !== 'refresh-then-redirect') {\r\n session.clear();\r\n void router.navigateByUrl(config.loginRoute ?? '/login');\r\n return throwError(() => error);\r\n }\r\n\r\n return refreshCoordinator.refresh().pipe(\r\n switchMap(() => next(req)),\r\n // The coordinator already cleared the session and navigated once for\r\n // this shared failure (see RefreshCoordinator.refresh()) — this\r\n // request still needs to fail with its OWN original 401, not the\r\n // refresh's error, exactly as before WEB-0.2.\r\n catchError(() => throwError(() => error)),\r\n );\r\n }),\r\n );\r\n};\r\n\r\n/**\r\n * Bundles provideHttpClient with the XSRF configuration and interceptors\r\n * proven necessary by both consumers. Cookie/header names default to\r\n * 'XSRF-TOKEN'/'X-XSRF-TOKEN' (identical in both consumers today) but\r\n * remain overridable via config. Consumers add their own extra\r\n * provideHttpClient features (e.g. Portal's withXhr()) by calling\r\n * provideHttpClient(...) separately — this function only owns the concerns\r\n * proven common to both.\r\n */\r\nexport function providePlatformAngularHttp(...extraFeatures: HttpFeature<HttpFeatureKind>[]) {\r\n return provideHttpClient(\r\n withXsrfConfiguration({\r\n cookieName: 'XSRF-TOKEN',\r\n headerName: 'X-XSRF-TOKEN',\r\n }),\r\n withInterceptors([credentialsInterceptor, sessionExpiryInterceptor]),\r\n ...extraFeatures,\r\n );\r\n}\r\n","/**\n * Generic capability map: a flat set of boolean feature flags fetched once\n * from the BFF (Portal's proven pattern — GET .../capabilities returning a\n * flat boolean-keyed object). Deliberately a generic `Record<string,\n * boolean>` rather than a typed interface enumerating every field: Portal's\n * capability set already has 17 product-specific fields and Store will\n * grow its own, unrelated set. A typed interface would require a package\n * release for every new product capability (see ADR-010 §18 — evolution\n * cadence mismatch is a real argument against sharing). Each product\n * defines its own capability keys locally and reads them through this map.\n *\n * UX ONLY. This does not replace server-side authorization. Every consumer\n * MUST continue to handle 403 from the actual mutating/reading endpoint —\n * capability checks here are a consultive pre-check, exactly as already\n * documented in Portal's application.service.ts before this extraction.\n */\nexport type CapabilityMap = Readonly<Record<string, boolean>>;\n\nexport function hasCapability(capabilities: CapabilityMap | null | undefined, key: string): boolean {\n return capabilities?.[key] === true;\n}\n","import { Directive, Input, TemplateRef, ViewContainerRef, inject } from '@angular/core';\nimport { CapabilityMap, hasCapability } from './capability.model';\n\n/**\n * Structural directive gating template content on a capability key from a\n * consumer-supplied CapabilityMap. Net-new (neither consumer had factored\n * their proven inline `@if (capabilities()?.x)` pattern into a directive),\n * but grounded in Portal's validated usage — see capability.model.ts.\n *\n * UX ONLY — see capability.model.ts. Hiding an element here does not\n * authorize anything; the backend re-validates on every mutating call.\n *\n * Usage: `<button *orxCapability=\"capabilities(); has: 'manageTenants'\">`\n */\n@Directive({\n selector: '[orxCapability]',\n standalone: true,\n})\nexport class CapabilityDirective {\n private readonly templateRef = inject(TemplateRef<unknown>);\n private readonly viewContainer = inject(ViewContainerRef);\n\n private map: CapabilityMap | null | undefined;\n private key: string | undefined;\n private hasView = false;\n\n @Input()\n set orxCapability(map: CapabilityMap | null | undefined) {\n this.map = map;\n this.render();\n }\n\n @Input('orxCapabilityHas')\n set has(key: string) {\n this.key = key;\n this.render();\n }\n\n private render(): void {\n const shouldShow = !!this.key && hasCapability(this.map, this.key);\n if (shouldShow && !this.hasView) {\n this.viewContainer.createEmbeddedView(this.templateRef);\n this.hasView = true;\n } else if (!shouldShow && this.hasView) {\n this.viewContainer.clear();\n this.hasView = false;\n }\n }\n}\n","import { HttpErrorResponse } from '@angular/common/http';\r\n\r\n/**\r\n * Canonical error shape, generalized from Store's already-proven\r\n * ErroApresentavel/normalizarErroApi (the more mature of the two consumers'\r\n * error handling — Portal had no typed contract at all, just five\r\n * duplicated `error.error.code` reads). `message` is optional: Portal never\r\n * received a server-supplied message field, only `code`, and resolves\r\n * user-facing text locally — so this contract cannot require it.\r\n *\r\n * `correlation_id` (API-1, ADR-017 §3.3): added after confirming directly\r\n * from Orechio.Platform's `ProblemResponses.cs` that it IS present in the\r\n * JSON body of every error response the Platform host produces (not just\r\n * the `X-Correlation-ID` response header), and that Portal's BFF relays\r\n * that body byte-for-byte, unreshaped, for every typed endpoint. The\r\n * earlier NG-1-era absence was accurate for what it tested at the time but\r\n * incomplete relative to Platform's actual wire contract. Optional: not\r\n * every error path in every consumer emits this field today (Store's own\r\n * narrower auth/CSRF error shapes don't) — its absence must not be treated\r\n * as a parse failure.\r\n *\r\n * Domain-specific error codes (e.g. 'access.platform_only',\r\n * 'tenant.not_found', 'csrf.invalid') are NOT enumerated here — `code`\r\n * stays a plain string so any code survives normalization unmodified and\r\n * remains identifiable by callers, per Passo 28.\r\n */\r\nexport interface ProblemDetails {\r\n code: string;\r\n message?: string;\r\n status: number;\r\n required?: string;\r\n correlationId?: string;\r\n}\r\n\r\n/**\r\n * Normalizes an HttpErrorResponse into ProblemDetails. Mirrors Store's\r\n * normalizarErroApi exactly, generalized to make `message` optional and to\r\n * accept an HttpErrorResponse without any consumer-specific fallback\r\n * message map (each product keeps its own code→message copy locally —\r\n * that's product-specific text, not shared infrastructure).\r\n */\r\nexport function normalizeProblemDetails(error: HttpErrorResponse): ProblemDetails {\r\n const body = error.error as Record<string, unknown> | null | undefined;\r\n const code = typeof body?.['code'] === 'string' ? (body['code'] as string) : `http.${error.status || 0}`;\r\n const message = typeof body?.['message'] === 'string' ? (body['message'] as string) : undefined;\r\n const required = typeof body?.['required'] === 'string' ? (body['required'] as string) : undefined;\r\n // Wire field is `correlation_id` (snake_case, ADR-017 §3) — kept as-is on the wire,\r\n // exposed as `correlationId` here per TS/Angular convention (same server-side pattern:\r\n // OrechioProblemDetails.CorrelationId is [JsonPropertyName(\"correlation_id\")]).\r\n const correlationId =\r\n typeof body?.['correlation_id'] === 'string' ? (body['correlation_id'] as string) : undefined;\r\n\r\n return {\r\n code,\r\n message,\r\n status: error.status,\r\n ...(required ? { required } : {}),\r\n ...(correlationId ? { correlationId } : {}),\r\n };\r\n}\r\n","/*\r\n * Public API Surface of @orechio/platform-angular\r\n */\r\n\r\nexport type { PlatformAngularConfig, PlatformAngularAuthPaths } from './lib/config/platform-angular-config';\r\nexport { PLATFORM_ANGULAR_CONFIG, providePlatformAngularConfig } from './lib/config/platform-angular-config';\r\n\r\nexport type { SessionUser } from './lib/session/session-user.model';\r\nexport { SessionStore } from './lib/session/session-store';\r\n\r\nexport { AuthClient } from './lib/auth/auth-client';\r\n\r\nexport type { BranchOption, BranchSelectionRequired } from './lib/auth/branch-selection.model';\r\nexport {\r\n BRANCH_SELECTION_REQUIRED_CODE,\r\n readBranchSelectionRequired,\r\n} from './lib/auth/branch-selection.model';\r\nexport { BranchSelector } from './lib/auth/branch-selector';\r\n\r\nexport { credentialsInterceptor, sessionExpiryInterceptor, providePlatformAngularHttp } from './lib/http/provide-platform-angular-http';\r\n\r\nexport type { CapabilityMap } from './lib/capabilities/capability.model';\r\nexport { hasCapability } from './lib/capabilities/capability.model';\r\nexport { CapabilityDirective } from './lib/capabilities/capability.directive';\r\n\r\nexport type { ProblemDetails } from './lib/problem-details/problem-details.model';\r\nexport { normalizeProblemDetails } from './lib/problem-details/problem-details.model';\r\n\r\nexport type { PagedResult } from './lib/pagination/paged-result.model';\r\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;MAgDa,uBAAuB,GAAG,IAAI,cAAc,CAC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IACtE,MAAM,IAAI,GAAG,OAAO,IAAI,GAAG,MAAM,CAAC,KAAK,QAAQ,GAAI,IAAI,CAAC,MAAM,CAAY,GAAG,CAAA,KAAA,EAAQ,KAAK,CAAC,MAAM,IAAI,CAAC,CAAA,CAAE;IACxG,MAAM,OAAO,GAAG,OAAO,IAAI,GAAG,SAAS,CAAC,KAAK,QAAQ,GAAI,IAAI,CAAC,SAAS,CAAY,GAAG,SAAS;IAC/F,MAAM,QAAQ,GAAG,OAAO,IAAI,GAAG,UAAU,CAAC,KAAK,QAAQ,GAAI,IAAI,CAAC,UAAU,CAAY,GAAG,SAAS;;;;IAIlG,MAAM,aAAa,GACjB,OAAO,IAAI,GAAG,gBAAgB,CAAC,KAAK,QAAQ,GAAI,IAAI,CAAC,gBAAgB,CAAY,GAAG,SAAS;IAE/F,OAAO;QACL,IAAI;QACJ,OAAO;QACP,MAAM,EAAE,KAAK,CAAC,MAAM;AACpB,QAAA,IAAI,QAAQ,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC;AACjC,QAAA,IAAI,aAAa,GAAG,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC;KAC5C;AACH;;AC3DA;;AAEG;;ACFH;;AAEG;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orechio/platform-angular",
3
- "version": "0.7.3",
3
+ "version": "0.8.0",
4
4
  "peerDependencies": {
5
5
  "@angular/common": "^22.1.0",
6
6
  "@angular/core": "^22.1.0",
@@ -64,6 +64,13 @@ interface SessionUser {
64
64
  roles: string[];
65
65
  name: string | null;
66
66
  email: string | null;
67
+ /**
68
+ * The session is the PROVISIONING one: the account has no branch yet and the only thing it can
69
+ * do is create the first (PROV-1). Optional and absent from hosts that do not send it. It
70
+ * steers navigation (`@orechio/platform-angular/account` redirects to the first-branch screen);
71
+ * it authorizes nothing.
72
+ */
73
+ provisioningRequired?: boolean;
67
74
  }
68
75
 
69
76
  /**
@@ -239,6 +246,13 @@ declare class BranchSelector {
239
246
  * why the name is preferred whenever it exists.
240
247
  */
241
248
  protected label(branch: BranchOption, index: number): string;
249
+ /**
250
+ * The fragment exists only to tell apart branches that would otherwise read the
251
+ * same, so it is rendered when another option carries the same name (trimmed,
252
+ * case-insensitive) — or when there is no name at all, where the positional
253
+ * "Filial N" fallback gives the user nothing else to go on.
254
+ */
255
+ protected showFragment(branch: BranchOption): boolean;
242
256
  /** Fragment of the id, shown beside the label to disambiguate repeated names. */
243
257
  protected fragment(branch: BranchOption): string;
244
258
  static ɵfac: i0.ɵɵFactoryDeclaration<BranchSelector, never>;