vitral 0.1.0 → 0.2.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.
Files changed (56) hide show
  1. package/README.md +250 -217
  2. package/dist/angular.d.ts +15 -4
  3. package/dist/angular.js +25 -5
  4. package/dist/auto.d.ts +2 -0
  5. package/dist/auto.js +12 -0
  6. package/dist/chunk-2XF5BKV3.js +190 -0
  7. package/dist/chunk-6Y3VMWHH.js +181 -0
  8. package/dist/chunk-DXORSF4X.js +42 -0
  9. package/dist/chunk-GNPFWISJ.js +80 -0
  10. package/dist/chunk-HP6QWU6K.js +51 -0
  11. package/dist/chunk-NCONW6WS.js +606 -0
  12. package/dist/chunk-PX7PBCCT.js +89 -0
  13. package/dist/chunk-S5MZT5IT.js +20 -0
  14. package/dist/chunk-SFL6LTP3.js +56 -0
  15. package/dist/chunk-UTYAX6MU.js +152 -0
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +88 -0
  18. package/dist/dedupe-IWFIXRWG.js +81 -0
  19. package/dist/devtools.d.ts +12 -0
  20. package/dist/devtools.js +86 -0
  21. package/dist/element.d.ts +60 -2
  22. package/dist/element.js +9 -2
  23. package/dist/errors-KKB8FGCz.d.ts +11 -0
  24. package/dist/events-DUdjhfps.d.ts +6 -0
  25. package/dist/expose-53BEJB34.js +14 -0
  26. package/dist/host-slot-Cz6EiGsB.d.ts +6 -0
  27. package/dist/iframe.d.ts +28 -0
  28. package/dist/iframe.js +236 -0
  29. package/dist/index.d.ts +142 -147
  30. package/dist/index.js +39 -10
  31. package/dist/navigate-BRG1WJUM.d.ts +9 -0
  32. package/dist/overrides-NZAIUGK5.js +15 -0
  33. package/dist/preact.d.ts +30 -7
  34. package/dist/preact.js +37 -9
  35. package/dist/react.d.ts +38 -7
  36. package/dist/react.js +92 -42
  37. package/dist/routes.d.ts +56 -0
  38. package/dist/routes.js +143 -0
  39. package/dist/shadow-MYRJQLLY.js +72 -0
  40. package/dist/slot-pB276oPt.d.ts +36 -0
  41. package/dist/solid.d.ts +29 -6
  42. package/dist/solid.js +31 -8
  43. package/dist/sri-BVKZNX5Q.js +114 -0
  44. package/dist/state-BDdCwc21.d.ts +4 -0
  45. package/dist/svelte.d.ts +19 -3
  46. package/dist/svelte.js +10 -4
  47. package/dist/testing.d.ts +2 -2
  48. package/dist/testing.js +8 -3
  49. package/dist/types-BV-hUrms.d.ts +265 -0
  50. package/dist/vite.d.ts +58 -4
  51. package/dist/vite.js +714 -24
  52. package/dist/vue.d.ts +79 -7
  53. package/dist/vue.js +69 -46
  54. package/package.json +144 -8
  55. package/dist/chunk-IZK6ITIJ.js +0 -96
  56. package/dist/chunk-TTL52BF2.js +0 -547
package/dist/iframe.js ADDED
@@ -0,0 +1,236 @@
1
+ import {
2
+ splitName
3
+ } from "./chunk-HP6QWU6K.js";
4
+ import {
5
+ verifyIntegrity
6
+ } from "./chunk-S5MZT5IT.js";
7
+ import {
8
+ events,
9
+ navigate,
10
+ setFrameMounter,
11
+ track
12
+ } from "./chunk-NCONW6WS.js";
13
+ import {
14
+ resolveEntry
15
+ } from "./chunk-2XF5BKV3.js";
16
+ import "./chunk-SFL6LTP3.js";
17
+ import {
18
+ RemoteError,
19
+ fetchBytes,
20
+ withRetry,
21
+ withTimeout
22
+ } from "./chunk-PX7PBCCT.js";
23
+ import {
24
+ protocol
25
+ } from "./chunk-GNPFWISJ.js";
26
+
27
+ // src/iframe-frame.ts
28
+ var FRAME_RUNTIME = `function (w, load) {
29
+ var parent = w.parent, doc = w.document, handlers = {}, last = {}, channel = {}, mounted = null, stage = 'LOAD_FAILED'
30
+ function post(type, data) { parent.postMessage({ vitral: 1, type: type, data: data }, '*') }
31
+ function call(fn, arg) { try { fn(arg) } catch (e) { w.console.error(e) } }
32
+ var events = {
33
+ emit: function (type, payload) { post('emit', { type: type, payload: payload }) },
34
+ on: function (type, fn) {
35
+ if (!handlers[type]) { handlers[type] = []; post('on', { type: type }) }
36
+ handlers[type].push(fn)
37
+ return function () { handlers[type] = handlers[type].filter(function (h) { return h !== fn }) }
38
+ },
39
+ last: function (type) { return last[type] }
40
+ }
41
+ function start(d) {
42
+ var root = doc.createElement('div')
43
+ root.setAttribute('data-vitral-root', d.name)
44
+ if (d.scope) root.setAttribute('data-vitral-scope', d.scope)
45
+ doc.body.appendChild(root)
46
+ // Ponto de extens\xE3o: uma ponte nova registra handlers em channel[tipo] e
47
+ // acrescenta campos aqui (a Fase 2 acrescenta ctx.shared).
48
+ var ctx = {
49
+ name: d.name, baseUrl: d.baseUrl, events: events, shadowRoot: null, protocol: 1,
50
+ reportError: function (e) { post('report', { message: String((e && e.message) || e) }) },
51
+ navigate: function (url, o) { post('navigate', { url: String(url), replace: !!(o && o.replace) }) }
52
+ }
53
+ Promise.all(d.css.map(function (href) {
54
+ return new Promise(function (done) {
55
+ var link = doc.createElement('link')
56
+ link.rel = 'stylesheet'; link.href = href; link.crossOrigin = 'anonymous'
57
+ link.onload = link.onerror = done
58
+ doc.head.appendChild(link)
59
+ })
60
+ })).then(function () {
61
+ return load(d.code ? w.URL.createObjectURL(new w.Blob([d.code], { type: 'text/javascript' })) : d.url)
62
+ }).then(function (ns) {
63
+ if (!d.key) return ns
64
+ var table = ns.exposes, part = table && table[d.key]
65
+ if (!part) { stage = 'NOT_EXPOSED'; throw new Error(d.name + ' n\xE3o exp\xF5e ' + d.key) }
66
+ return typeof part === 'function' ? part() : part
67
+ }).then(function (ns) {
68
+ var mod = (ns && ns.default) || ns
69
+ if (!mod || typeof mod.mount !== 'function') { stage = 'INVALID_MODULE'; throw new Error('o m\xF3dulo n\xE3o exporta mount()') }
70
+ stage = 'MOUNT_FAILED'
71
+ return mod.mount(root, d.props, ctx)
72
+ }).then(function (handle) {
73
+ mounted = handle
74
+ post('mounted')
75
+ var size = function () { post('size', { height: Math.ceil(doc.body.getBoundingClientRect().height) }) }
76
+ size()
77
+ if (w.ResizeObserver) new w.ResizeObserver(size).observe(doc.body)
78
+ }, function (e) {
79
+ post('error', { code: stage, message: String((e && e.message) || e) })
80
+ })
81
+ }
82
+ w.addEventListener('message', function (e) {
83
+ var m = e.data
84
+ if (e.source !== parent || !m || m.vitral !== 1) return
85
+ var d = m.data
86
+ if (m.type === 'mount') start(d)
87
+ else if (m.type === 'update') { if (mounted && mounted.update) mounted.update(d) }
88
+ else if (m.type === 'unmount') { if (mounted) mounted.unmount(); mounted = null }
89
+ else if (m.type === 'last') last[d.type] = d.payload
90
+ else if (m.type === 'event') {
91
+ last[d.type] = d.payload
92
+ ;(handlers[d.type] || []).slice().forEach(function (h) { call(h, d.payload) })
93
+ } else (channel[m.type] || []).forEach(function (h) { call(h, d) })
94
+ })
95
+ post('ready')
96
+ }`;
97
+ var FRAME_SCRIPT = `(${FRAME_RUNTIME})(window, function (u) { return import(u) })`;
98
+ var FRAME_HTML = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0}body{display:flow-root}</style></head><body><script>${FRAME_SCRIPT}</script></body></html>`;
99
+
100
+ // src/iframe.ts
101
+ var CODES = ["LOAD_FAILED", "NOT_EXPOSED", "INVALID_MODULE", "MOUNT_FAILED"];
102
+ function enableIframe(options = {}) {
103
+ const sandbox = options.sandbox ?? "allow-scripts";
104
+ if (/\ballow-same-origin\b/.test(sandbox) && /\ballow-scripts\b/.test(sandbox)) {
105
+ console.warn("[vitral] sandbox com allow-scripts e allow-same-origin n\xE3o isola o remote da p\xE1gina.");
106
+ }
107
+ setFrameMounter((target, name, props, mountOptions) => mountFrame(target, name, props, mountOptions, sandbox, options.bridges ?? []));
108
+ }
109
+ async function mountFrame(target, name, props, options, sandbox, bridges) {
110
+ const p = protocol();
111
+ const { timeout, retries } = p.settings();
112
+ const [remote, key] = splitName(name);
113
+ const entry = p.entry(remote);
114
+ if (!entry) throw new RemoteError("NOT_REGISTERED", name, "remote n\xE3o registrado. Use configure({ remotes }).");
115
+ if (!entry.url) throw new RemoteError("MOUNT_FAILED", name, "remote local (module) n\xE3o roda em iframe: registre a URL dele");
116
+ const { integrity, ...resolved } = await resolveEntry(remote, entry);
117
+ const code = integrity ? await withRetry(retries, async () => {
118
+ const bytes = await fetchBytes(resolved.entry, timeout, name);
119
+ await verifyIntegrity(name, bytes, integrity);
120
+ return bytes;
121
+ }) : void 0;
122
+ track(name, resolved.entry);
123
+ const baseUrl = /^https?:/.test(resolved.entry) ? new URL(".", resolved.entry).href : resolved.entry;
124
+ const frame = document.createElement("iframe");
125
+ frame.setAttribute("sandbox", sandbox);
126
+ frame.setAttribute("data-vitral-root", name);
127
+ frame.title = name;
128
+ frame.style.cssText = "display:block;width:100%;height:0;border:0";
129
+ frame.srcdoc = FRAME_HTML;
130
+ let warned = false;
131
+ const post = (type, data) => {
132
+ const win = frame.contentWindow;
133
+ if (!win) return;
134
+ try {
135
+ win.postMessage({ vitral: 1, type, data }, "*");
136
+ } catch {
137
+ if (!warned) console.warn(`[vitral] ${name}: props e eventos no modo iframe precisam ser serializ\xE1veis; o que n\xE3o \xE9 foi descartado.`);
138
+ warned = true;
139
+ win.postMessage({ vitral: 1, type, data: JSON.parse(JSON.stringify(data ?? null)) }, "*");
140
+ }
141
+ };
142
+ const subs = /* @__PURE__ */ new Map();
143
+ const channel = /* @__PURE__ */ new Map();
144
+ const port = {
145
+ post,
146
+ on(type, handler) {
147
+ if (!channel.has(type)) channel.set(type, /* @__PURE__ */ new Set());
148
+ channel.get(type).add(handler);
149
+ return () => channel.get(type)?.delete(handler);
150
+ }
151
+ };
152
+ let settle = null;
153
+ const ready = new Promise((ok, fail) => settle = { ok, fail });
154
+ const onMessage = (e) => {
155
+ const m = e.data;
156
+ if (e.source !== frame.contentWindow || !m || m.vitral !== 1) return;
157
+ const d = m.data;
158
+ switch (m.type) {
159
+ case "ready":
160
+ if (settle) post("mount", { name, key, code, url: resolved.entry, css: resolved.css, scope: resolved.scope, baseUrl, props });
161
+ break;
162
+ case "mounted":
163
+ settle?.ok();
164
+ settle = null;
165
+ break;
166
+ case "error":
167
+ settle?.fail(new RemoteError(CODES.includes(d?.code) ? d.code : "MOUNT_FAILED", name, String(d?.message)));
168
+ settle = null;
169
+ break;
170
+ case "size":
171
+ frame.style.height = `${Math.max(0, Number(d?.height) || 0)}px`;
172
+ break;
173
+ case "emit":
174
+ events.emit(String(d?.type), d?.payload);
175
+ break;
176
+ case "on": {
177
+ const type = String(d?.type);
178
+ if (subs.has(type)) break;
179
+ subs.set(type, events.on(type, (payload) => post("event", { type, payload })));
180
+ const value = events.last(type);
181
+ if (value !== void 0) post("last", { type, payload: value });
182
+ break;
183
+ }
184
+ case "navigate": {
185
+ const url = new URL(String(d?.url), location.href);
186
+ if (url.origin === location.origin) navigate(url.href, { replace: !!d?.replace });
187
+ else console.warn(`[vitral] ${name}: navega\xE7\xE3o para outra origem bloqueada (${url.origin})`);
188
+ break;
189
+ }
190
+ case "report": {
191
+ const err = new RemoteError("RENDER_FAILED", name, String(d?.message));
192
+ if (options.onError) options.onError(err);
193
+ else console.error(err);
194
+ break;
195
+ }
196
+ default:
197
+ for (const h of [...channel.get(m.type) ?? []]) h(d);
198
+ }
199
+ };
200
+ const disposers = [];
201
+ const cleanup = () => {
202
+ removeEventListener("message", onMessage);
203
+ for (const off of subs.values()) off();
204
+ for (const off of disposers) off();
205
+ subs.clear();
206
+ frame.remove();
207
+ };
208
+ addEventListener("message", onMessage);
209
+ for (const bridge of bridges) {
210
+ const off = bridge(port, { name });
211
+ if (off) disposers.push(off);
212
+ }
213
+ target.appendChild(frame);
214
+ try {
215
+ await withTimeout(timeout, name, ready);
216
+ } catch (e) {
217
+ cleanup();
218
+ throw e;
219
+ }
220
+ let alive = true;
221
+ return {
222
+ update(next) {
223
+ if (alive) post("update", next);
224
+ },
225
+ unmount() {
226
+ if (!alive) return;
227
+ alive = false;
228
+ post("unmount");
229
+ cleanup();
230
+ }
231
+ };
232
+ }
233
+ export {
234
+ FRAME_SCRIPT,
235
+ enableIframe
236
+ };
package/dist/index.d.ts CHANGED
@@ -1,17 +1,117 @@
1
+ import { V as VitralConfig, c as RemoteEntry, P as Props, a as RemoteModule, I as Isolation, b as StyleOptions, M as MountedRemote, E as EventBus, R as RemoteContext, d as SharedValue } from './types-BV-hUrms.js';
2
+ export { C as CheckedProps, H as Handler, e as PropsOf, f as ProvideOptions, g as ProvidedValue, h as RemoteManifest, i as RemoteMetric, j as Remotes, S as Shared, k as SharedApi, l as SharedModules, m as SharedType, n as batch, p as provide, s as shared } from './types-BV-hUrms.js';
3
+ import { R as RemoteError } from './errors-KKB8FGCz.js';
4
+ export { a as RemoteErrorCode } from './errors-KKB8FGCz.js';
5
+ export { R as RemoteSlot, a as SlotOptions, S as SlotStatus, c as createSlot } from './slot-pB276oPt.js';
6
+ export { e as events } from './events-DUdjhfps.js';
7
+ export { n as navigate } from './navigate-BRG1WJUM.js';
8
+ export { r as __reset } from './state-BDdCwc21.js';
9
+
10
+ /** Configura a lib. Pode ser chamada mais de uma vez; as opções são mescladas. */
11
+ declare function configure(config: VitralConfig): void;
12
+ /** Registra (ou substitui) um remote. */
13
+ declare function register(name: string, entry: string | RemoteEntry): void;
14
+ /**
15
+ * Registra a URL de um `src` e devolve o nome para montar. Sem `name`, o nome
16
+ * é a própria URL (e o nome do manifesto vira um apelido). Com `trusted`, a
17
+ * origem entra na allowlist mesmo com `allowedOrigins`: vale para URL escrita
18
+ * no código do host, nunca para URL vinda de dados.
19
+ */
20
+ declare function registerSrc(src: string, name?: string, trusted?: boolean): string;
21
+
22
+ /** Uma chave do store vista de fora (devtools, SSR, ponte do iframe). */
23
+ interface SharedEntry {
24
+ key: string;
25
+ value: unknown;
26
+ /** `false` quando só o dono altera. */
27
+ writable: boolean;
28
+ /** Quem é o dono (nome do remote; vazio para o host ou sem nome). */
29
+ owner?: string;
30
+ /** Quem fez a última mudança. */
31
+ by?: string;
32
+ /** Quantas assinaturas ativas a chave tem. */
33
+ subscribers: number;
34
+ }
35
+ /**
36
+ * Store guardado no protocolo global (`globalThis[Symbol.for('vitral')].shared()`).
37
+ * Faz parte do protocolo v1: só cresce com métodos novos.
38
+ */
39
+ interface SharedStore {
40
+ /** Valor atual; `undefined` se a chave ainda não tem valor. */
41
+ get(key: string): unknown;
42
+ /**
43
+ * Troca o valor. Passa se `token` é o do dono ou se a chave aceita escrita.
44
+ * Devolve `false` quando a escrita foi bloqueada (`writable: false`).
45
+ */
46
+ set(key: string, value: unknown, token?: object, by?: string): boolean;
47
+ /** Chama `fn(valor)` a cada mudança (não na hora). Devolve a função que cancela. */
48
+ subscribe(key: string, fn: (value: unknown) => void): () => void;
49
+ /**
50
+ * Torna-se dono de uma chave sem dono e grava `value` (um valor vindo do
51
+ * SSR ainda não reivindicado é mantido). Devolve o token do dono, ou
52
+ * `undefined` se a chave já tem dono.
53
+ */
54
+ own(key: string, value: unknown, writable: boolean, by?: string): object | undefined;
55
+ /** O dono larga a chave. O valor fica e a chave volta a aceitar escrita. */
56
+ release(key: string, token: object): void;
57
+ /** Roda `fn` e notifica cada chave alterada uma vez só, no fim. */
58
+ batch<R>(fn: () => R): R;
59
+ /** Chaves com valor e seus metadados. */
60
+ list(): SharedEntry[];
61
+ }
62
+
63
+ /** Baixa (uma vez só) e devolve o módulo de um remote. */
64
+ declare function loadRemote<P extends Props = Props>(name: string): Promise<RemoteModule<P>>;
1
65
  /**
2
- * Remote em JS/TS puro sem escrever mount/update/unmount na mão.
66
+ * Carrega um módulo sem UI que um remote expõe (funções, stores, constantes),
67
+ * com a mesma verificação de SRI e de origem dos componentes.
3
68
  *
4
- * export default component<{ mensagem?: string }>({
5
- * state: { cliques: 0 },
6
- * render: ({ mensagem }, state, ctx) => html`
7
- * <p>${mensagem}</p>
8
- * <button onclick=${() => state.cliques++}>ping ${state.cliques}</button>
9
- * `,
10
- * })
69
+ * const api = await loadModule<typeof import('./tipos/carrinho-api')>('carrinho/api')
11
70
  *
12
- * Valores interpolados são escapados (sem XSS). Mudar `state` ou receber
13
- * props novas renderiza de novo. Funções em `on<evento>=${fn}` viram listeners.
71
+ * Sem `/`, devolve os exports do arquivo principal do remote.
72
+ */
73
+ declare function loadModule<T = Record<string, unknown>>(name: string): Promise<T>;
74
+ /** Começa a baixar um remote (JS e CSS) sem montar (ex.: no hover de um link). */
75
+ declare function preload(name: string): void;
76
+
77
+ interface MountOptions {
78
+ isolate?: Isolation;
79
+ /** `'high'` para o remote que aparece logo ao abrir a página: vira `fetchpriority` nos downloads. */
80
+ priority?: RequestPriority;
81
+ /** Estilos do host no Shadow DOM (somados aos do `configure`). */
82
+ styles?: StyleOptions;
83
+ /** Chamado quando o remote quebra depois de montado (erro de render, handler etc.). */
84
+ onError?: (error: RemoteError) => void;
85
+ }
86
+ /**
87
+ * Monta um remote dentro de `target`. Devolve um handle com `update` e
88
+ * `unmount` que funciona igual para qualquer framework. Com `refresh(nome)`,
89
+ * o mesmo handle passa a apontar para a versão nova.
90
+ */
91
+ declare function mountRemote<P extends Props = Props>(target: HTMLElement, name: string, props: P, options?: MountOptions): Promise<MountedRemote<P>>;
92
+
93
+ /** Declara um remote. É só uma função identidade com tipos. */
94
+ declare function defineRemote<P extends Props = Props>(remote: RemoteModule<P>): RemoteModule<P>;
95
+
96
+ declare function createEventBus(): EventBus;
97
+
98
+ /**
99
+ * Troca as montagens de `name` (e das partes, `name/…`) pela versão que o
100
+ * manifesto aponta agora, sem recarregar a página. Rejeita se a versão nova
101
+ * não carregar; nesse caso nada muda na tela.
102
+ */
103
+ declare function refresh(name: string): Promise<void>;
104
+ /**
105
+ * Revalida os manifestos dos remotes montados e emite
106
+ * `vitral:update-available` com `{ name, entry }` para cada deploy novo.
107
+ * Devolve os nomes com versão nova. Falhas de rede são ignoradas.
14
108
  */
109
+ declare function checkUpdates(): Promise<string[]>;
110
+ /**
111
+ * Revalida os manifestos a cada navegação (`popstate`, que `navigate()` também
112
+ * dispara, e a Navigation API onde existe). Devolve a função que desliga.
113
+ */
114
+ declare function watchUpdates(): () => void;
15
115
 
16
116
  declare const TEMPLATE: unique symbol;
17
117
  interface Template {
@@ -41,151 +141,46 @@ interface ComponentOptions<P extends Props, S extends object> {
41
141
  declare function component<P extends Props = Props, S extends object = Record<string, never>>(options: RenderFn<P, S> | ComponentOptions<P, S>): RemoteModule<P>;
42
142
 
43
143
  /**
44
- * vitral: micro-frontends com um único contrato.
45
- *
46
- * Um remote é um módulo ES que exporta `mount(el, props, ctx)` e devolve
47
- * `{ update?, unmount }`. O host só precisa saber a URL. Nada de config
48
- * compartilhada em tempo de build, nada de container global de dependências.
144
+ * Extras opcionais do contexto compartilhado: guardar no storage, espelhar
145
+ * entre abas e levar os valores do SSR para o cliente. Ficam fora do store
146
+ * para só entrar no bundle de quem usa.
49
147
  */
50
- type Props = Record<string, unknown>;
51
- interface RemoteContext {
52
- /** Nome com que o host registrou este remote. */
53
- name: string;
54
- /** URL base de onde o remote foi carregado (útil para assets). */
55
- baseUrl: string;
56
- /**
57
- * Barramento de eventos compartilhado entre host e todos os remotes. As
58
- * assinaturas feitas por aqui são canceladas sozinhas no unmount.
59
- */
60
- events: EventBus;
61
- /** Shadow root quando o host pediu isolamento, senão `null`. */
62
- shadowRoot: ShadowRoot | null;
63
- /** Avisa o host de um erro em tempo de execução (os adaptadores já chamam). */
64
- reportError(error: unknown): void;
65
- /** Navega a página inteira (host e todos os roteadores) para `url`. */
66
- navigate(url: string, options?: {
67
- replace?: boolean;
68
- }): void;
69
- }
70
- interface MountedRemote<P extends Props = Props> {
71
- update?(props: P): void;
72
- unmount(): void;
73
- }
74
- interface RemoteModule<P extends Props = Props> {
75
- mount(el: HTMLElement, props: P, ctx: RemoteContext): MountedRemote<P> | Promise<MountedRemote<P>>;
76
- }
77
- interface RemoteEntry {
78
- /** URL do módulo JS do remote, ou do `vitral.json` gerado pelo plugin. */
79
- url?: string;
80
- /**
81
- * Remote local, sem rede: o próprio módulo ou uma função que o importa
82
- * (ex.: `() => import('./carrinho')`). Útil em monorepos e testes.
83
- */
84
- module?: RemoteModule<any> | (() => Promise<RemoteModule<any> | {
85
- default: RemoteModule<any>;
86
- }>);
87
- /** Hash SRI (`sha256-…`, `sha384-…`, `sha512-…`) do JS. Verificado antes de executar. */
88
- integrity?: string;
89
- /** CSS extra para carregar junto. */
90
- css?: string[];
91
- /** Isolamento padrão para este remote. */
92
- isolate?: Isolation;
93
- }
94
- type Isolation = 'shadow' | 'none';
95
- interface VitralConfig {
96
- /** Mapa nome → URL (ou entrada completa), ou a URL de um JSON com esse mapa. */
97
- remotes?: Record<string, string | RemoteEntry> | string;
148
+
149
+ interface PersistOptions {
150
+ /** `'local'` (padrão) ou `'session'`. */
151
+ storage?: 'local' | 'session';
98
152
  /**
99
- * Origens de onde é permitido carregar código. Padrão: a própria origem da
100
- * página mais as origens das URLs registradas. Use `['*']` para liberar tudo.
153
+ * Versão do formato do valor. Faz parte da chave do storage
154
+ * (`vitral:<chave>:<versão>`): ao mudar o formato, suba a versão e o valor
155
+ * antigo é ignorado. Padrão `1`.
101
156
  */
102
- allowedOrigins?: string[];
103
- /** Tempo máximo para baixar um remote, em ms. Padrão 15000. */
104
- timeout?: number;
105
- /** Tentativas extras se o download falhar. Padrão 1. */
106
- retries?: number;
107
- /** Isolamento padrão para todos os remotes. Padrão `'none'`. */
108
- isolate?: Isolation;
109
- }
110
- type RemoteErrorCode = 'NOT_REGISTERED' | 'ORIGIN_BLOCKED' | 'TIMEOUT' | 'INTEGRITY' | 'INVALID_MODULE' | 'LOAD_FAILED' | 'MOUNT_FAILED' | 'RENDER_FAILED';
111
- declare class RemoteError extends Error {
112
- code: RemoteErrorCode;
113
- remote: string;
114
- cause?: unknown | undefined;
115
- constructor(code: RemoteErrorCode, remote: string, message: string, cause?: unknown | undefined);
116
- }
117
- /** Formato do `vitral.json` emitido pelo plugin de build. */
118
- interface RemoteManifest {
119
- name: string;
120
- version?: string;
121
- entry: string;
122
- css?: string[];
123
- integrity?: string;
124
- /** Escopo usado pelo plugin para prefixar o CSS (`[data-vitral-scope]`). */
125
- scope?: string;
126
- }
127
- /** Configura a lib. Pode ser chamada mais de uma vez; as opções são mescladas. */
128
- declare function configure(config: VitralConfig): void;
129
- /** Registra (ou substitui) um remote. */
130
- declare function register(name: string, entry: string | RemoteEntry): void;
131
- /** Baixa (uma vez só) e devolve o módulo de um remote. */
132
- declare function loadRemote<P extends Props = Props>(name: string): Promise<RemoteModule<P>>;
133
- /** Começa a baixar um remote sem montar (ex.: no hover de um link). */
134
- declare function preload(name: string): void;
135
- interface MountOptions {
136
- isolate?: Isolation;
137
- /** Chamado quando o remote quebra depois de montado (erro de render, handler etc.). */
138
- onError?: (error: RemoteError) => void;
157
+ version?: string | number;
139
158
  }
140
159
  /**
141
- * Monta um remote dentro de `target`. Devolve um handle com `update` e
142
- * `unmount` que funciona igual para qualquer framework.
160
+ * Restaura o valor guardado (se houver) e guarda cada mudança. Valores que
161
+ * não viram JSON (funções, por exemplo) não são guardados. Sem storage
162
+ * (servidor, modo privado bloqueado), não faz nada.
163
+ *
164
+ * const carrinho = persist(provide('carrinho', []), { version: 2 })
143
165
  */
144
- declare function mountRemote<P extends Props = Props>(target: HTMLElement, name: string, props: P, options?: MountOptions): Promise<MountedRemote<P>>;
145
- type SlotStatus = 'loading' | 'ready' | 'error';
146
- interface SlotOptions<P extends Props = Props> {
147
- name: string;
148
- props?: P;
149
- isolate?: Isolation;
150
- /** Chamado a cada mudança de estado (para mostrar fallback / erro). */
151
- onStatus?: (status: SlotStatus, error: RemoteError | null) => void;
152
- }
153
- interface RemoteSlot<P extends Props = Props> {
154
- /** Atualiza as props sem remontar. */
155
- update(props: P): void;
156
- /** Troca de remote ou de isolamento (remonta). */
157
- set(options: Partial<Pick<SlotOptions<P>, 'name' | 'isolate'>>): void;
158
- /** Remonta do zero (botão "tentar de novo"). */
159
- retry(): void;
160
- destroy(): void;
161
- readonly status: SlotStatus;
162
- }
166
+ declare function persist<V extends SharedValue<any>>(value: V, options?: PersistOptions): V;
163
167
  /**
164
- * Cuida do ciclo de vida de um remote dentro de `target`: monta, atualiza,
165
- * remonta ao trocar de nome, ignora respostas atrasadas e limpa tudo no fim.
166
- * Os adaptadores de host (Web Component, Svelte, Solid, Preact…) usam isto.
168
+ * Espelha as mudanças entre abas da mesma origem (`BroadcastChannel`). Chame
169
+ * nas duas abas, de preferência no dono da chave: assim a mudança que chega
170
+ * passa mesmo com `writable: false`. Só dados que o `structuredClone` aceita
171
+ * atravessam. Junto com `persist`, uma aba nova começa com o último valor.
172
+ *
173
+ * const carrinho = syncTabs(persist(provide('carrinho', [])))
167
174
  */
168
- declare function createSlot<P extends Props = Props>(target: HTMLElement, options: SlotOptions<P>): RemoteSlot<P>;
169
- /** Declara um remote. É só uma função identidade com tipos. */
170
- declare function defineRemote<P extends Props = Props>(remote: RemoteModule<P>): RemoteModule<P>;
171
- type Handler<T = unknown> = (payload: T) => void;
172
- interface EventBus {
173
- emit<T = unknown>(type: string, payload?: T): void;
174
- on<T = unknown>(type: string, handler: Handler<T>): () => void;
175
- /** Último valor emitido em `type` (útil para estado como "usuário logado"). */
176
- last<T = unknown>(type: string): T | undefined;
177
- }
178
- declare function createEventBus(): EventBus;
179
- /** Barramento global. É o mesmo objeto que os remotes recebem em `ctx.events`. */
180
- declare const events: EventBus;
175
+ declare function syncTabs<V extends SharedValue<any>>(value: V): V;
181
176
  /**
182
- * Navega mantendo todos os roteadores em sincronia (React Router, Vue Router,
183
- * Next, Nuxt…): atualiza o histórico e dispara `popstate`, que todos escutam.
177
+ * SSR: transforma os valores de uma requisição no conteúdo do
178
+ * `<script type="application/json" data-vitral-shared>`, que o store do
179
+ * cliente lê antes dos remotes montarem. Funções e `undefined` ficam de fora;
180
+ * `<` é escapado para o JSON não fechar o `<script>`.
181
+ *
182
+ * `<script type="application/json" data-vitral-shared>${serializeShared({ usuario })}</script>`
184
183
  */
185
- declare function navigate(url: string, options?: {
186
- replace?: boolean;
187
- }): void;
188
- /** Só para testes: limpa todo o estado global. */
189
- declare function __reset(): void;
184
+ declare function serializeShared(values: Record<string, unknown>): string;
190
185
 
191
- export { type ComponentOptions, type EventBus, type Handler, type Isolation, type MountOptions, type MountedRemote, type Props, type RemoteContext, type RemoteEntry, RemoteError, type RemoteErrorCode, type RemoteManifest, type RemoteModule, type RemoteSlot, type RenderFn, type SlotOptions, type SlotStatus, type Template, type View, type VitralConfig, __reset, component, configure, createEventBus, createSlot, defineRemote, events, html, loadRemote, mountRemote, navigate, preload, register, render, unsafeHTML };
186
+ export { type ComponentOptions, EventBus, Isolation, type MountOptions, MountedRemote, type PersistOptions, Props, RemoteContext, RemoteEntry, RemoteError, RemoteModule, type RenderFn, type SharedEntry, type SharedStore, SharedValue, StyleOptions, type Template, type View, VitralConfig, checkUpdates, component, configure, createEventBus, defineRemote, html, loadModule, loadRemote, mountRemote, persist, preload, refresh, register, registerSrc, render, serializeShared, syncTabs, unsafeHTML, watchUpdates };
package/dist/index.js CHANGED
@@ -1,24 +1,44 @@
1
1
  import {
2
- RemoteError,
3
- __reset,
2
+ batch,
3
+ checkUpdates,
4
4
  component,
5
- configure,
6
- createEventBus,
7
5
  createSlot,
8
6
  defineRemote,
9
7
  events,
10
8
  html,
11
- loadRemote,
12
9
  mountRemote,
13
10
  navigate,
11
+ persist,
12
+ provide,
13
+ refresh,
14
+ render,
15
+ serializeShared,
16
+ shared,
17
+ syncTabs,
18
+ unsafeHTML,
19
+ watchUpdates
20
+ } from "./chunk-NCONW6WS.js";
21
+ import {
22
+ configure,
23
+ loadModule,
24
+ loadRemote,
14
25
  preload,
15
26
  register,
16
- render,
17
- unsafeHTML
18
- } from "./chunk-TTL52BF2.js";
27
+ registerSrc
28
+ } from "./chunk-2XF5BKV3.js";
29
+ import "./chunk-SFL6LTP3.js";
30
+ import {
31
+ RemoteError
32
+ } from "./chunk-PX7PBCCT.js";
33
+ import {
34
+ createEventBus,
35
+ resetProtocol
36
+ } from "./chunk-GNPFWISJ.js";
19
37
  export {
20
38
  RemoteError,
21
- __reset,
39
+ resetProtocol as __reset,
40
+ batch,
41
+ checkUpdates,
22
42
  component,
23
43
  configure,
24
44
  createEventBus,
@@ -26,11 +46,20 @@ export {
26
46
  defineRemote,
27
47
  events,
28
48
  html,
49
+ loadModule,
29
50
  loadRemote,
30
51
  mountRemote,
31
52
  navigate,
53
+ persist,
32
54
  preload,
55
+ provide,
56
+ refresh,
33
57
  register,
58
+ registerSrc,
34
59
  render,
35
- unsafeHTML
60
+ serializeShared,
61
+ shared,
62
+ syncTabs,
63
+ unsafeHTML,
64
+ watchUpdates
36
65
  };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Navega mantendo todos os roteadores em sincronia (React Router, Vue Router,
3
+ * Next, Nuxt…): atualiza o histórico e dispara `popstate`, que todos escutam.
4
+ */
5
+ declare function navigate(url: string, options?: {
6
+ replace?: boolean;
7
+ }): void;
8
+
9
+ export { navigate as n };
@@ -0,0 +1,15 @@
1
+ import {
2
+ OVERRIDES_KEY,
3
+ manifestUrl,
4
+ overrideFor,
5
+ overridesEnabled,
6
+ storedOverrides
7
+ } from "./chunk-DXORSF4X.js";
8
+ import "./chunk-GNPFWISJ.js";
9
+ export {
10
+ OVERRIDES_KEY,
11
+ manifestUrl,
12
+ overrideFor,
13
+ overridesEnabled,
14
+ storedOverrides
15
+ };